@morscherlab/mint-sdk
v1.5.24
Published
MINT Platform SDK — Vue 3 components, composables, and types for plugin development. MINT = Mass-spec Infrastructure for Next-generation Toolkits.
Maintainers
Readme
@morscherlab/mint-sdk (Frontend)
Vue 3 SDK for MINT Platform plugin development. Provides reusable components, composables, stores, and types for building consistent, well-integrated plugins.
Full Documentation: See the MINT SDK docs for detailed API reference and guides.
- API Reference
- Component Catalog - All public components with props/events
- Composables Reference - All public composables with examples
- Theming Guide - CSS variables and customization
Installation
bun add @morscherlab/mint-sdkRequirements
- Vue 3.4+
- Pinia 2.1+
- Tailwind CSS 4.0+ (optional - SDK includes pre-built utility classes)
Quick Start
1. Import Styles
Import the SDK styles in your main entry point:
// main.ts
import '@morscherlab/mint-sdk/styles'The SDK includes all necessary CSS utility classes pre-built, so Tailwind CSS is optional. The styles work standalone or alongside Tailwind.
Required.
dist/styles.cssis the SDK's single stylesheet: components no longer@importtheir own CSS from their<style>block, so a plugin that skips this import renders unstyled components.src/styles/index.cssis the sole aggregator — every component stylesheet is imported there exactly once.
2. (Optional) Map SDK tokens into Tailwind
With Tailwind CSS v4, map the SDK tokens you need in your own stylesheet. The values stay theme-aware because they reference the SDK custom properties:
@import "tailwindcss";
@import "@morscherlab/mint-sdk/styles";
@theme inline {
--color-mint-primary: var(--color-primary);
--color-mint-danger: var(--mint-error);
--radius-mint: var(--radius-md);
}3. Use Components
<script setup lang="ts">
import { BaseButton, BaseInput, FormField } from '@morscherlab/mint-sdk'
import { useToast } from '@morscherlab/mint-sdk'
import type { ButtonVariant } from '@morscherlab/mint-sdk'
const { success } = useToast()
function handleSubmit() {
success('Saved!')
}
</script>
<template>
<FormField label="Username" required>
<BaseInput v-model="username" placeholder="Enter username" />
</FormField>
<BaseButton variant="primary" @click="handleSubmit">
Save
</BaseButton>
</template>Package entries
The package root exports the base controls, forms, feedback, the workspace shell, composables, stores and types. Domain components come from subpaths:
| Entry | Components |
|---|---|
| @morscherlab/mint-sdk/lab | plates, samples, dose, chemistry, charts, sequences, instruments, scheduling |
| @morscherlab/mint-sdk/shell | AppTopBar, AppSidebar, AppLayout, LayoutResizeHandle |
| @morscherlab/mint-sdk/data | experiment and artifact pickers, FilePicker, AuditTrail, JobsStatusTray, TagsInput, SecretInput |
| @morscherlab/mint-sdk/runtime | generated-UI views and renderers, RuntimeUpdateNotice |
@morscherlab/mint-sdk/host is for the MINT platform only. Plugins do not import it.
Native Plotly charts
PlotlyChart accepts native Plotly data, layout, and config props and
loads Plotly lazily. It shares MINT's chart header, loading/empty states, and
toolbar/legend slots. Explicit layout colors override the MINT defaults.
<PlotlyChart
title="QC overview"
:data="[{ type: 'scatter', x: [1, 2, 3], y: [3, 4, 2] }]"
:layout="{ xaxis: { title: { text: 'Sample' } } }"
:config="{ toImageButtonOptions: { filename: 'qc-overview', format: 'png' } }"
/>Replace data/layout/config references to redraw; nested in-place mutations do
not schedule a render. The component isolates Plotly's mutations of data and
layout, observes container size and the root theme, and cleans up on unmount.
Use loading, empty, and emptyMessage for explicit states, and the error
slot for a custom failure presentation. Generated Plotly results reuse this
renderer and retain their static-image fallback.
4. Use Generated Plugin Clients
For plugin frontends scaffolded by mint init, run this from the plugin root:
mint sdk generateUse mint sdk generate --check --json when CI or editor tasks need machine-readable contract drift status.
Then call backend routes through the generated client:
import { useClient } from './generated/mint-plugin'
const client = useClient()
const health = await client.health()
// Cancel a generated request without bypassing SDK authentication.
const controller = new AbortController()
const result = await client.analyze(
{ body: { parameters: { threshold: '0.05' } } },
{ signal: controller.signal },
)Generated requests (including uploads and downloads) throw MintApiError from
@morscherlab/mint-sdk for HTTP failures. It exposes code, message, status,
requestId, details, and the original response body; the status comes from
HTTP, and the request ID falls back to X-Request-ID. Legacy FastAPI detail
and SDK plugin error responses are supported. Direct useApi() calls throw
the same MintApiError; cancellations and network failures without a response
keep their Axios error.
Generated files also expose typed plugin settings when the backend declares
@mint_plugin(config=PluginConfig):
import { settingsForm, settingsSchema, useSettings } from './generated/mint-plugin'
const pluginSettings = useSettings()
const threshold = pluginSettings.settings.value?.threshold
const settingsConfig = pluginSettings.settingsConfigPass settingsConfig to PluginWorkspaceView or AppTopBar.
settingsSchema is the Pydantic JSON Schema used for generated
TypeScript values. settingsForm is the SDK
SettingsModalSchema used to render controls; they are deliberately separate.
When .env, process-environment, or startup values override a field, saving
still updates its backing value. The effective override remains active, while
the saved value is returned in stored_settings and marked inactive until
that higher-priority override is removed.
The generated client is built from backend plugin metadata, FastAPI routes, and Pydantic schemas, and uses the frontend SDK to resolve the API prefix automatically.
FastAPI request or response content declared as standard
application/octet-stream is generated as a raw binary transport: request
bodies accept Blob | ArrayBuffer | Uint8Array, responses resolve to Blob,
and the SDK does not JSON-encode the payload. Multipart
type: string, format: binary fields remain typed as File | Blob.
Routes with an experimentId path parameter can omit it inside an experiment page; the client reads the current experiment from the experiment store:
await client.analyze({ body: { parameters: { threshold: '0.05' } } })Use useExperiment() when a plugin view needs the current experiment. It is
read-only: the platform selects the experiment and keeps it in step with the
URL. Watch id to respond to a change; null means no experiment is selected,
and it stays null in standalone mode.
import { watch } from 'vue'
import { useExperiment } from '@morscherlab/mint-sdk'
const experiment = useExperiment()
watch(experiment.id, (id) => {
if (id !== null) void loadResults(id)
}, { immediate: true })5. Build Control Workspaces
For custom plugin tools, pass one control model to PluginWorkspaceView as
spec.sidebar.controls. It generates the top-bar pills, the sidebar sections,
their forms, the component prop bindings and their shared values from the same
source:
<script setup lang="ts">
import { ref } from 'vue'
import { PluginWorkspaceView, defineControlModel, definePluginWorkspaceView } from '@morscherlab/mint-sdk'
const workspaceModel = defineControlModel({
views: {
analysis: {
label: 'Analysis',
sections: {
parameters: {
label: 'Parameters',
controls: {
threshold: { type: 'number', default: 0.05, min: 0, max: 1 },
method: ['linear', 'logistic'],
saveResults: true,
},
},
},
},
},
})
const workspace = definePluginWorkspaceView({
title: 'Analysis',
sidebar: { controls: workspaceModel },
})
const values = ref({})
</script>
<template>
<PluginWorkspaceView v-model:values="values" :spec="workspace" />
</template>Use defineControls() for flat forms, and use useControlWorkspace()
directly only when a plugin needs full manual control over the generated
AppTopBar, AppSidebar, or FormBuilder bindings.
For WellPlate + DoseCalculator pages, start from the dose-design preset instead of writing the sidebar controls and component prop mappings yourself:
<script setup lang="ts">
import { PluginWorkspaceView, defineDoseDesignControlModel, definePluginWorkspaceView } from '@morscherlab/mint-sdk'
import { DoseCalculator, WellPlate } from '@morscherlab/mint-sdk/lab'
const workspaceModel = defineDoseDesignControlModel({
selectedWells: ['A1', 'A2'],
includeMolecularWeight: true,
})
const workspace = definePluginWorkspaceView({
title: 'Dose Design',
sidebar: { controls: workspaceModel },
})
</script>
<template>
<PluginWorkspaceView :spec="workspace" v-slot="{ componentPropsById }">
<WellPlate v-bind="componentPropsById.plate" />
<DoseCalculator v-bind="componentPropsById.dose" />
</PluginWorkspaceView>
</template>Components
Base Components
BaseButton- Button with variants (primary, secondary, cta, danger, success, ghost);icon+labelwithout a default slot gives an icon-only buttonBaseInput- Text input with aninvalidstate;type="textarea"gives a multi-line fieldNumberInput- Numeric input with steppers;units+v-model:unitgives a unit segmentBaseSelect- Native select;searchablegives a search listbox,multiplean array-bound chip list (maxcaps it)BaseCheckbox- Checkbox;type="switch"gives an on/off switch,layout="row"a settings rowDatePicker- Date picker;type="time"andtype="datetime"pick a time or bothBasePill- Label pill withtone,variant(soft,outline),dotandpulsefor live statusBaseTabs- Underline tab bar;optionstakesSelectOptionInput[]BaseModal- Modal dialog with Teleport; open state isv-model:open
Every component that takes a color uses tone: Tone (neutral, primary,
cta, success, warning, error, info); LoadingSpinner also takes
tone="inherit". Input components mark an error with invalid, data views
take loading, error and emptyText, and overlays bind v-model:open.
Form Components
FormField- Form field wrapper with label, error, and hintFormBuilder- Schema-driven forms from fullschemaobjects or compactcontrols
Contributor rule: SDK components compose SDK fields (FormField + BaseInput,
BaseSelect, NumberInput, BaseButton) and
never restyle them. A component stylesheet may size and place a field; it does
not define its own input, select, textarea, unit or button looks.
Feedback Components
AlertBox- Alert messages;tonesets the colorAppToastContainer- Toast notification container for the globaluseToast()queue
Action Components
ThemeToggle- Light/dark mode toggle
Layout Components
CollapsibleCard- Expandable card sections with optional icon badge and toggle switchAppTopBar- Application header with slotsAppSidebar- Context sidebar that accepts panels/forms or a compactcontrolsschema
File & Data Components
FileUploader- Drag-and-drop file upload with file/folder mode support
Sample Management Components
SampleSelector stays public, with its smartGroup event and the
AutoGroupResult type. The auto-group modal and engine are private
SampleSelector code since 1.4: AutoGroupModal, useAutoGroup,
DEFAULT_COLORS and extractSamplesFromDesignData are not exported. For
grouping, use SampleSelector and its smartGroup event. To read sample rows,
use unwrapExperimentDesignData() and its samples. MINT 1.4 removed the other sample
grouping exports (SmartGroupModal, SmartGroupFieldRecipe,
SmartGroupManual, GroupAssigner, useGroupAssignment).
Removed Compatibility APIs
The public SDK no longer exports ToastNotification, GroupingModal,
SettingsButton, FormSection, FormFieldRenderer, usePluginApi(), or
usePluginConfig(). MINT 1.4 removed the identity-only usePluginClient(),
useJobsStatusTray() with its jobs / adapter / eventStream options and
JobsStatusTray props, and usePluginJobs().jobsAdapter.
Use AppToastContainer, AppTopBar settings or
SettingsModal, FormBuilder, the generated useSettings(), useClient()
and useJobs(), and source-driven useJobCenter() instead.
MINT 1.3 also removed ColorSlider (pass colorStops, thresholds,
showLabels, minLabel and maxLabel to BaseSlider), DropdownButton
(BaseSelect for values, ActionMenu for actions),
InstrumentAlertLog, InstrumentStatusCard, LcmsSequenceTable, useAsync(),
useOptimisticMutation() (use useRequest()), useResourceCrud()
(use the generated useClient()), useCommandHistory(),
useWellPlateAdapter(), useWellPlateValidation() (no SDK replacement; keep
them in the plugin), useWellPainting() and useWellPlateEditor() (use
useRackEditor() with PlateEditor). mint doctor still detects old imports
and reports the replacement path.
MINT 1.3 removed AppPluginSwitcher and its PluginSwitcherPlugin /
PluginSwitcherInfo types, with the pluginSwitcher prop and
plugin-switcher-* events on AppTopBar and PluginWorkspaceView: integrated
plugins now show their icon, name and version as a static identity in
AppTopBar. ProgressBar lost its segmented variant (variant, steps,
currentStep); use StepWizard for step progress and the rail for percentages.
Composables
useJobs(definition, options?)
The generated client exports useJobs() with the input, job, and output types
of each job definition:
import { useJobs } from './generated/mint-plugin'
const analyze = useJobs('analyze', { immediate: true })
const job = await analyze.submit({
source: new File(['peak\n1'], 'peaks.csv'),
threshold: 0.1,
})
const done = await analyze.wait(job, {
signal: abortController.signal,
rejectOnFailure: true,
})
const result = await analyze.result(done)
await analyze.cancel(job)
// Releases only finished `analyze` jobs and their retained results.
await analyze.clear()The returned object exposes the jobs and latest getters, status,
error, isLoading, isSubmitting, submit(), wait(), result(),
get(), cancel(), delete(), clear(), refresh(), pause(), resume(),
dispose(), and staging (upload, part, get, seal). The first
submit() or refresh() opens the job session; immediate: true lists the
existing jobs at once. Passing a job from another definition fails instead of
crossing the scope. Capability fields are presentation hints; the server
remains authoritative when cancel/delete are called. Each useJobs() call owns
its own runtime (session, poll timer, event stream).
get() fetches one fresh canonical job without refreshing the list. wait()
settles from the same SSE/poll-backed canonical source and cleans up on abort,
deletion, or disposal, so callers do not need a second event stream or Promise
registry. A call made while the runtime is paused rejects immediately. Waiting
on a known active job tolerates a transient direct lookup failure and continues
through SSE/poll updates; pausing an existing wait suspends those updates until
resume(). cancel() updates active work, while delete() releases one
terminal job and its retained result. dispose() is idempotent and also runs
automatically with the owning Vue effect scope.
Both staging.upload({ ..., signal }) and
staging.part(job, { ..., signal }) forward the supplied AbortSignal to the
authenticated multipart request. Abort stops the client-side transfer, but the
caller should refresh job/staging state before retrying because the server may
already have committed the upload.
Automatic submission binds ordinary Path uploads to its job definition. When
uploading manually, staging.upload(input) binds the upload to the definition
so the server can authorize it before reading its body.
cancel() and delete() accept either a canonical job object or its ID.
Pass the runtime's canonical source directly to standard job UI. The job center derives its groups from the same jobs ref and does not mirror it with a watcher:
<script setup lang="ts">
import { AppTopBar } from '@morscherlab/mint-sdk/shell'
import { JobsStatusTray } from '@morscherlab/mint-sdk/data'
import { useJobCenter } from '@morscherlab/mint-sdk/runtime'
import type { JobState } from '@morscherlab/mint-sdk/types'
import { useJobs } from './generated/mint-plugin'
const jobs = useJobs('analyze')
const center = useJobCenter({ source: jobs })
function openResult(job: JobState) { /* show the job's result */ }
</script>
<template>
<AppTopBar
:job="center.topBarJob.value"
:jobs-done="center.completedCount.value"
@job-click="center.handleTopBarClick(openResult)"
/>
<JobsStatusTray :center="center" @select="openResult" />
</template>The job center reads only the runtime source. Polling, SSE updates, and job
actions therefore have exactly one state owner. PluginWorkspaceView does this
wiring when its spec sets jobs: jobs and emits job-select.
When an incremental migration temporarily has more than one owner, use
combinePluginJobSources([sdkJobs, legacyJobs]). It preserves each source's
live jobs getter, fans out refresh/clear operations, routes per-job actions to
the owning source, and rejects duplicate IDs instead of guessing.
Job state exposes definition_id, result_status, and result_expires_at.
Managed file results carry a short-lived, result-scoped download_url instead
of embedded base64 data or the user's bearer token, so regular browser
downloads work through an integrated plugin proxy.
useApi(options?)
Generic API client with auth interceptor, on @morscherlab/mint-sdk/runtime.
import { useApi } from '@morscherlab/mint-sdk/runtime'
const api = useApi()
// GET request
const data = await api.get<User[]>('/users')
// POST with body
const created = await api.post<User>('/users', { name: 'John' })
// File upload
const result = await api.upload<UploadResponse>('/upload', file)
// Build URLs for external use
const downloadUrl = api.buildUrl('/files/123/download')Authenticated requests that receive HTTP 401 clear the rejected SDK token and
throw the public AuthenticationRequiredError. Requests are never replayed;
callers can present a single sign-in prompt without risking duplicate writes.
Clients created with withAuth: false retain their existing auth state and
receive the original HTTP error.
useTheme()
Theme switching.
const { isDark, toggleTheme, setTheme } = useTheme()
toggleTheme()
setTheme(true) // dark modeuseToast()
Toast notification management.
const { success, error, warning, info, push } = useToast()
success('Operation completed!')
error('Something went wrong', { duration: 8000 })
warning('Please review your input')
info('New update available')usePlatform()
Read the platform context of a plugin page and check access.
const { integrated, plugin, user, isAdmin, can } = usePlatform()
const canConfigure = computed(() => can('configure'))can(access) takes the same levels as the Python access option: use,
configure and admin. A page with no signed-in user (standalone, or sign-in
turned off) passes every check; the platform still checks every request.
useExperimentSamples(options?)
Load experiment design_data and derive SampleSelector-compatible sample values.
const { samples, sampleOptions, fetch } = useExperimentSamples({ experimentId: 42 })
await fetch()Stores
useAuthStore
Pinia store for authentication state.
const authStore = useAuthStore()
// State
authStore.token
authStore.userInfo
authStore.isAuthenticated
authStore.isAdmin
// Actions
authStore.initialize()
authStore.setToken(token, expiresIn)
authStore.logout()useSettingsStore
Pinia store for app settings.
const settingsStore = useSettingsStore()
// State
settingsStore.theme // 'light' | 'dark' | 'system'
settingsStore.colorPalette
// Methods
settingsStore.getApiBaseUrl()
settingsStore.getWsBaseUrl()
settingsStore.isDark()TypeScript Types
All types are exported from @morscherlab/mint-sdk:
import type {
// Components
ButtonVariant,
ButtonSize,
ModalSize,
Tone,
Toast,
SelectOption,
// Sample Management
SampleGroup, // { name, color, samples[] }
FileUploaderMode, // 'file' | 'folder'
// Auth
AuthConfig,
UserInfo,
// Platform
PluginInfo,
PlatformContext,
ThemeMode,
} from '@morscherlab/mint-sdk'Icons
lucide-vue-next is the icon standard for this SDK. New components should import the icon component they need rather than inlining an SVG:
<script setup lang="ts">
import { RefreshCw } from 'lucide-vue-next'
</script>
<template>
<RefreshCw :size="16" />
</template>lucide-vue-next is a declared dependency and is external to the built
bundle (like axios and @floating-ui/dom), so the consumer resolves one
shared copy instead of the SDK shipping its own.
A number of older components still carry hand-written inline <svg> markup —
usually annotated with the Lucide icon name they were traced from. Those are
converted opportunistically, not in bulk; leave one alone unless you are already
editing the component.
Theming
The SDK uses CSS variables for theming. Override them to customize:
:root {
--bg-primary: #F8FAFC;
--bg-secondary: #FFFFFF;
--bg-tertiary: #F1F5F9;
--text-primary: #1E293B;
--text-secondary: #64748B;
--border-color: #E5E7EB;
--color-primary: #3B82F6;
}
html.dark {
--bg-primary: #0F172A;
--bg-secondary: #1E293B;
--bg-tertiary: #334155;
--text-primary: #F8FAFC;
--text-secondary: #94A3B8;
--border-color: #334155;
}License
MIT
