@sanity/workbench 0.1.0-alpha.19 → 0.1.0-alpha.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"system.js","sources":["../src/system/auth.machine.ts","../src/system/inspect.ts","../src/system/remote.machine.ts","../src/system/remotes.machine.ts","../src/system/system-preferences.machine.ts","../src/system/telemetry.machine.ts","../src/system/root.machine.ts"],"sourcesContent":["import {\n type AuthState,\n AuthStateType,\n type CurrentUser,\n getAuthState,\n type LoggedInAuthState,\n logout,\n type SanityInstance,\n} from \"@sanity/sdk\";\nimport { assign, fromObservable, fromPromise, setup } from \"xstate\";\n\nimport type { OSBaseInput } from \"./root.machine\";\n\n/**\n * @internal\n */\nexport interface AuthInput extends OSBaseInput {}\n\nconst authStateLogic = fromObservable<AuthState, AuthInput>(\n ({ input }) => getAuthState(input.instance).observable,\n);\n\n/**\n * @internal\n */\nexport interface LogoutInput extends OSBaseInput {}\n\nconst logoutActorLogic = fromPromise<void, LogoutInput>(async ({ input }) => {\n await logout(input.instance);\n});\n\ntype AuthContext = {\n instance: SanityInstance;\n token: string | null;\n currentUser: CurrentUser | null;\n error: unknown;\n};\n\ntype AuthEvent = { type: \"auth.logout\" };\n\nexport const authLogic = setup({\n types: {\n input: {} as AuthInput,\n context: {} as AuthContext,\n events: {} as AuthEvent,\n tags: {} as \"authenticating\" | \"authenticated\" | \"error\",\n },\n actors: {\n authState: authStateLogic,\n logoutActor: logoutActorLogic,\n },\n delays: {\n authTimeout: 30_000,\n },\n guards: {\n isLoggedInComplete: (_, params: { state: AuthState | undefined }) =>\n params.state?.type === AuthStateType.LOGGED_IN &&\n Boolean((params.state as LoggedInAuthState).token) &&\n (params.state as LoggedInAuthState).currentUser !== null,\n isAuthState: (\n _,\n params: { state: AuthState | undefined; type: AuthStateType },\n ) => params.state?.type === params.type,\n },\n actions: {\n setLoggedIn: assign({\n token: (_, params: { token: string; currentUser: CurrentUser }) =>\n params.token,\n currentUser: (_, params: { token: string; currentUser: CurrentUser }) =>\n params.currentUser,\n error: () => null,\n }),\n clearAuth: assign({\n token: () => null,\n currentUser: () => null,\n error: () => null,\n }),\n setError: assign({\n token: () => null,\n currentUser: () => null,\n error: (_, params: { error: unknown }) => params.error,\n }),\n },\n}).createMachine({\n id: \"auth\",\n initial: \"init\",\n context: ({ input }) => ({\n instance: input.instance,\n token: null,\n currentUser: null,\n error: null,\n }),\n invoke: {\n src: \"authState\",\n input: ({ context }) => ({ instance: context.instance }),\n onSnapshot: [\n {\n guard: {\n type: \"isLoggedInComplete\",\n params: ({ event }) => ({\n state: event.snapshot.context,\n }),\n },\n actions: [\n {\n type: \"setLoggedIn\",\n params: ({ event }) => {\n const state = event.snapshot.context as LoggedInAuthState;\n return {\n token: state.token,\n currentUser: state.currentUser!,\n };\n },\n },\n ],\n target: `.${AuthStateType.LOGGED_IN}`,\n },\n {\n guard: {\n type: \"isAuthState\",\n params: ({ event }) => ({\n state: event.snapshot.context,\n type: AuthStateType.LOGGING_IN,\n }),\n },\n actions: [{ type: \"clearAuth\" }],\n target: `.${AuthStateType.LOGGING_IN}`,\n },\n {\n guard: {\n type: \"isAuthState\",\n params: ({ event }) => ({\n state: event.snapshot.context,\n type: AuthStateType.ERROR,\n }),\n },\n actions: [\n {\n type: \"setError\",\n params: ({ event }) => ({\n error:\n event.snapshot.context?.type === AuthStateType.ERROR\n ? event.snapshot.context.error\n : null,\n }),\n },\n ],\n target: `.${AuthStateType.ERROR}`,\n },\n {\n guard: {\n type: \"isAuthState\",\n params: ({ event }) => ({\n state: event.snapshot.context,\n type: AuthStateType.LOGGED_OUT,\n }),\n },\n actions: [{ type: \"clearAuth\" }],\n target: `.${AuthStateType.LOGGED_OUT}`,\n },\n ],\n },\n states: {\n init: {\n tags: [\"authenticating\"],\n after: {\n authTimeout: {\n actions: [\n {\n type: \"setError\",\n params: () => ({\n error: new Error(\"Authentication timed out\"),\n }),\n },\n ],\n target: AuthStateType.ERROR,\n },\n },\n },\n [AuthStateType.LOGGING_IN]: {\n tags: [\"authenticating\"],\n after: {\n authTimeout: {\n actions: [\n {\n type: \"setError\",\n params: () => ({\n error: new Error(\"Authentication timed out\"),\n }),\n },\n ],\n target: AuthStateType.ERROR,\n },\n },\n },\n [AuthStateType.LOGGED_IN]: {\n tags: [\"authenticated\"],\n on: {\n \"auth.logout\": { target: \"logging-out\" },\n },\n },\n [\"logging-out\"]: {\n invoke: {\n src: \"logoutActor\",\n input: ({ context }) => ({ instance: context.instance }),\n onDone: {\n target: AuthStateType.LOGGED_OUT,\n },\n onError: {\n actions: [\n {\n type: \"setError\",\n params: ({ event }) => ({ error: event.error }),\n },\n ],\n target: AuthStateType.ERROR,\n },\n },\n },\n [AuthStateType.LOGGED_OUT]: {},\n [AuthStateType.ERROR]: { tags: [\"error\"] },\n },\n});\n","import { type ActorRefLike, type InspectionEvent } from \"xstate\";\n\nimport { logger } from \"../core\";\n\n// Mirrors @statelyai/inspect's ActorRefLikeWithData — the inspect\n// callback receives full Actor instances at runtime, but the type is\n// narrowed for @xstate/store compat.\ntype ActorRefWithAncestry = ActorRefLike & {\n id?: string;\n _parent?: ActorRefWithAncestry;\n};\n\nconst actorPath = (ref: ActorRefWithAncestry): string => {\n const segments: string[] = [];\n let current: ActorRefWithAncestry | undefined = ref;\n while (current) {\n segments.unshift(current.id ?? current.sessionId);\n current = current._parent;\n }\n return segments.join(\":\");\n};\n\n/** @internal exported for testing */\nexport const inspect = (event: InspectionEvent): void => {\n const ref = event.actorRef as ActorRefWithAncestry;\n const log = logger.child(actorPath(ref));\n\n switch (event.type) {\n case \"@xstate.snapshot\": {\n log.debug(\"snapshot\", event.snapshot);\n break;\n }\n case \"@xstate.event\":\n log.debug(\"event\", event.event);\n break;\n case \"@xstate.action\":\n log.debug(\"action\", event.action);\n break;\n }\n};\n","import type { FederationInstance } from \"@sanity/federation/runtime\";\nimport { assign, fromPromise, sendParent, setup } from \"xstate\";\n\n/**\n * @public\n */\nexport interface RemoteRenderOptions {\n basePath?: string;\n scheme?: \"light\" | \"dark\";\n /**\n * This is a temporary measure designed to authenticate federated\n * studios & SDK apps before we write a working protocol.\n */\n unstable_temporaryToken?: string | null;\n}\n\n/**\n * @public\n */\nexport interface LoadedRemoteModule {\n render: (\n rootElement: HTMLElement,\n options?: RemoteRenderOptions,\n ) => () => void;\n}\n\n/**\n * @public\n */\nexport interface RemoteError {\n message: string;\n cause: unknown;\n}\n\n/**\n * Thrown by the load actor when a remote responds successfully but does\n * not expose a `render` function. Surfaced via `RemoteError.cause` for\n * consumers that need to discriminate.\n * @internal\n */\nexport class ModuleShapeError extends Error {\n constructor(remoteId: string) {\n super(`Remote \"${remoteId}\" did not expose a render function`);\n }\n}\n\n/**\n * @internal\n */\nexport interface RemoteInput {\n id: string;\n entry: string;\n instance: FederationInstance;\n}\n\ntype RemoteContext = RemoteInput & {\n module: LoadedRemoteModule | null;\n error: RemoteError | null;\n};\n\nconst REMOTE_MODULE = \"App\";\n\nconst loadLogic = fromPromise<LoadedRemoteModule, RemoteInput>(\n async ({ input }) => {\n input.instance.registerRemotes([{ name: input.id, entry: input.entry }]);\n const remoteModule = await input.instance.loadRemote<unknown>(\n `${input.id}/${REMOTE_MODULE}`,\n );\n if (\n !remoteModule ||\n typeof (remoteModule as { render?: unknown }).render !== \"function\"\n ) {\n throw new ModuleShapeError(input.id);\n }\n return remoteModule as LoadedRemoteModule;\n },\n);\n\n/**\n * Lifecycle machine for a single federated application remote.\n *\n * Spawned by the {@link remotesLogic} supervisor on demand. Each instance\n * owns one remote's load lifecycle: `loading` → `loaded | error`. Tags\n * (`loading` / `ready` / `failed`) drive the UI contract — state names\n * are internal.\n *\n * The machine sends a `remote.settled` event to its parent on entry to\n * either terminal state, reserved for future supervision/retry.\n *\n * @internal\n */\nexport const remoteLogic = setup({\n types: {\n input: {} as RemoteInput,\n context: {} as RemoteContext,\n tags: {} as \"loading\" | \"ready\" | \"failed\",\n },\n actors: {\n load: loadLogic,\n },\n actions: {\n setModule: assign({\n module: (_, params: { module: LoadedRemoteModule }) => params.module,\n error: () => null,\n }),\n setError: assign({\n module: () => null,\n error: (_, params: { error: unknown }) => normaliseError(params.error),\n }),\n },\n}).createMachine({\n id: \"remote\",\n initial: \"loading\",\n context: ({ input }) => ({\n ...input,\n module: null,\n error: null,\n }),\n states: {\n loading: {\n tags: [\"loading\"],\n invoke: {\n src: \"load\",\n input: ({ context }) => ({\n id: context.id,\n entry: context.entry,\n instance: context.instance,\n }),\n onDone: {\n target: \"loaded\",\n actions: [\n {\n type: \"setModule\",\n params: ({ event }) => ({ module: event.output }),\n },\n ],\n },\n onError: {\n target: \"error\",\n actions: [\n {\n type: \"setError\",\n params: ({ event }) => ({ error: event.error }),\n },\n ],\n },\n },\n },\n loaded: {\n tags: [\"ready\"],\n entry: sendParent(({ context }) => ({\n type: \"remote.settled\" as const,\n id: context.id,\n status: \"loaded\" as const,\n })),\n },\n error: {\n tags: [\"failed\"],\n entry: sendParent(({ context }) => ({\n type: \"remote.settled\" as const,\n id: context.id,\n status: \"error\" as const,\n })),\n },\n },\n});\n\nfunction normaliseError(error: unknown): RemoteError {\n if (error instanceof Error) {\n return { message: error.message, cause: error };\n }\n return { message: String(error), cause: error };\n}\n","import {\n createInstance,\n type FederationInstance,\n} from \"@sanity/federation/runtime\";\nimport { log } from \"@sanity/federation/runtime/plugins/log\";\nimport { type ActorRefFrom, assign, setup } from \"xstate\";\n\nimport { logger } from \"../core/log\";\nimport { remoteLogic } from \"./remote.machine\";\n\ntype RemotesContext = {\n instance: FederationInstance;\n children: Map<string, ActorRefFrom<typeof remoteLogic>>;\n};\n\ntype RemotesEvent =\n | { type: \"remote.load.request\"; id: string; entry: string }\n | { type: \"remote.settled\"; id: string; status: \"loaded\" | \"error\" };\n\n/**\n * Supervisor machine for federated application remotes.\n *\n * Owns a single {@link FederationInstance} (the `workbench-applications`\n * instance) and spawns one {@link remoteLogic} child per requested\n * remote. The supervisor is invoked at the root of the OS machine for\n * inspector visibility (`[sanity-workbench:os:remotes]`) — boot does\n * not gate on it.\n *\n * @internal\n */\nexport const remotesLogic = setup({\n types: {\n context: {} as RemotesContext,\n events: {} as RemotesEvent,\n },\n actors: {\n remote: remoteLogic,\n },\n guards: {\n remoteNotKnown: ({ context }, params: { id: string }) =>\n !context.children.has(params.id),\n },\n actions: {\n spawnRemote: assign({\n children: ({ context, spawn }, params: { id: string; entry: string }) => {\n const ref = spawn(\"remote\", {\n id: params.id,\n systemId: `remotes.${params.id}`,\n input: {\n id: params.id,\n entry: params.entry,\n instance: context.instance,\n },\n });\n return new Map(context.children).set(params.id, ref);\n },\n }),\n },\n}).createMachine({\n id: \"remotes\",\n context: () => ({\n instance: createInstance({\n name: \"workbench-applications\",\n plugins: [log(logger.debug)],\n }),\n children: new Map(),\n }),\n on: {\n \"remote.load.request\": {\n guard: {\n type: \"remoteNotKnown\",\n params: ({ event }) => ({ id: event.id }),\n },\n actions: [\n {\n type: \"spawnRemote\",\n params: ({ event }) => ({ id: event.id, entry: event.entry }),\n },\n ],\n },\n // Reserved for future supervision/retry. Forwarded by per-remote\n // children on entry to `loaded` or `error`; currently a no-op so the\n // event is part of the typed surface rather than a silent unknown.\n \"remote.settled\": {},\n },\n});\n","import { assign, fromCallback, sendTo, setup } from \"xstate\";\n\ntype ColorScheme = \"light\" | \"dark\";\n\ntype ColorSchemePreference = \"system\" | ColorScheme;\n\n/**\n * The system-preferences machine's context. Consumers read fields directly\n * (e.g. via `useSelector`) rather than going through a resolver utility —\n * the action handlers keep `colorScheme` in sync with `preferredColorScheme`\n * and `osColorScheme`.\n *\n * Note: `colorScheme` is intentionally stored as derived state in context so\n * consumers can read the resolved value directly without a utility. The\n * action handlers below are the single source of truth for the resolution.\n * @public\n */\nexport type SystemPreferencesContext = {\n /** User's color scheme choice; `system` defers to the OS preference. */\n preferredColorScheme: ColorSchemePreference;\n /** Last reported OS color scheme. Used to resolve `colorScheme` when the\n * preference is `system`. */\n osColorScheme: ColorScheme;\n /** Resolved color scheme — what the UI should render. Recomputed by the\n * action handlers whenever an input changes. */\n colorScheme: ColorScheme;\n};\n\nconst DEFAULT_PREFERRED_COLOR_SCHEME: ColorSchemePreference = \"system\";\nconst DEFAULT_OS_COLOR_SCHEME: ColorScheme = \"light\";\n\n/**\n * Events the system-preferences machine accepts. Both originate from the\n * host's adapter — `preferredColorScheme.set` is also forwarded back to it\n * so it can persist the user's choice.\n * @public\n */\nexport type SystemPreferencesEvent =\n | {\n type: \"preferredColorScheme.set\";\n preferredColorScheme: ColorSchemePreference;\n }\n | {\n type: \"osColorScheme.set\";\n osColorScheme: ColorScheme;\n };\n\n/**\n * Adapter interface the host implements to give the system-preferences\n * machine access to the user's environment (OS color scheme, persistent\n * storage, cross-context change notifications).\n *\n * The package owns all orchestration — synchronous seeding, idempotent\n * persistence, mapping cleared storage to `\"system\"`. The host's\n * implementation is pure DOM/storage glue: read, write, subscribe.\n * @public\n */\nexport type SystemPreferencesAdapter = {\n /** Read the user's stored preference. `null` means \"no preference set\"\n * (the machine treats this as `\"system\"`). */\n getPreferredColorScheme: () => ColorSchemePreference | null;\n /** Write the user's preference to persistent storage. */\n persistPreferredColorScheme: (value: ColorSchemePreference) => void;\n /** Subscribe to cross-context preference changes (e.g. another tab\n * writing to the shared storage). The callback receives the new stored\n * value (or `null` if it was cleared). Returns an unsubscribe function. */\n subscribePreferredColorScheme: (\n callback: (next: ColorSchemePreference | null) => void,\n ) => () => void;\n /** Read the current OS-detected color scheme. */\n getOsColorScheme: () => ColorScheme;\n /** Subscribe to OS color-scheme changes (e.g. user flipping dark mode).\n * Returns an unsubscribe function. */\n subscribeOsColorScheme: (callback: (next: ColorScheme) => void) => () => void;\n};\n\nconst resolveColorScheme = (\n preferred: ColorSchemePreference,\n osColorScheme: ColorScheme,\n): ColorScheme => (preferred === \"system\" ? osColorScheme : preferred);\n\n// Internal bridge actor — subscribes to the host's adapter for runtime\n// changes and persists user-driven preference changes when the parent\n// forwards them. No-op if the host didn't pass an adapter (SSR, tests).\ntype AdapterBridgeReceiveEvent = Extract<\n SystemPreferencesEvent,\n { type: \"preferredColorScheme.set\" }\n>;\n\nconst adapterBridgeLogic = fromCallback<\n AdapterBridgeReceiveEvent,\n SystemPreferencesAdapter | undefined,\n SystemPreferencesEvent\n>(({ input: adapter, sendBack, receive }) => {\n if (!adapter) return;\n\n const unsubscribePreferredColorScheme = adapter.subscribePreferredColorScheme(\n (next) => {\n // Falls back to `\"system\"` so an external clear (another tab deleting\n // the key) resets the preference rather than silently keeping the\n // previous value.\n sendBack({\n type: \"preferredColorScheme.set\",\n preferredColorScheme: next ?? \"system\",\n });\n },\n );\n\n const unsubscribeOs = adapter.subscribeOsColorScheme((next) => {\n sendBack({ type: \"osColorScheme.set\", osColorScheme: next });\n });\n\n receive((event) => {\n // Idempotent: skip writes that match the current stored value so a\n // `preferredColorScheme.set` originating from cross-context change\n // doesn't loop back into another write.\n if (adapter.getPreferredColorScheme() === event.preferredColorScheme)\n return;\n\n adapter.persistPreferredColorScheme(event.preferredColorScheme);\n });\n\n return () => {\n unsubscribePreferredColorScheme();\n unsubscribeOs();\n };\n});\n\n/**\n * @internal\n */\nexport const systemPreferencesLogic = setup({\n types: {\n input: {} as { adapter?: SystemPreferencesAdapter },\n context: {} as SystemPreferencesContext & {\n adapter: SystemPreferencesAdapter | undefined;\n },\n events: {} as SystemPreferencesEvent,\n },\n actors: {\n adapterBridge: adapterBridgeLogic,\n },\n actions: {\n setPreferredColorScheme: assign({\n preferredColorScheme: (\n _,\n params: { preferredColorScheme: ColorSchemePreference },\n ) => params.preferredColorScheme,\n colorScheme: (\n { context },\n params: { preferredColorScheme: ColorSchemePreference },\n ) =>\n resolveColorScheme(params.preferredColorScheme, context.osColorScheme),\n }),\n setOsColorScheme: assign({\n osColorScheme: (_, params: { osColorScheme: ColorScheme }) =>\n params.osColorScheme,\n colorScheme: ({ context }, params: { osColorScheme: ColorScheme }) =>\n resolveColorScheme(context.preferredColorScheme, params.osColorScheme),\n }),\n },\n}).createMachine({\n id: \"system-preferences\",\n initial: \"ready\",\n context: ({ input }) => {\n const adapter = input.adapter;\n const preferredColorScheme =\n adapter?.getPreferredColorScheme() ?? DEFAULT_PREFERRED_COLOR_SCHEME;\n const osColorScheme =\n adapter?.getOsColorScheme() ?? DEFAULT_OS_COLOR_SCHEME;\n\n return {\n adapter,\n preferredColorScheme,\n osColorScheme,\n colorScheme: resolveColorScheme(preferredColorScheme, osColorScheme),\n };\n },\n invoke: {\n id: \"adapter\",\n src: \"adapterBridge\",\n input: ({ context }) => context.adapter,\n },\n states: {\n ready: {\n on: {\n \"preferredColorScheme.set\": {\n actions: [\n {\n type: \"setPreferredColorScheme\",\n params: ({ event }) => ({\n preferredColorScheme: event.preferredColorScheme,\n }),\n },\n // Forward to the adapter bridge so it can persist the user's\n // choice. The bridge guards against redundant writes, so\n // round-tripping a `preferredColorScheme.set` it sourced itself\n // (e.g. from a `storage` event in another tab) is a no-op.\n sendTo(\"adapter\", ({ event }) => event),\n ],\n },\n \"osColorScheme.set\": {\n actions: [\n {\n type: \"setOsColorScheme\",\n params: ({ event }) => ({\n osColorScheme: event.osColorScheme,\n }),\n },\n ],\n },\n },\n },\n },\n});\n","import { getClient, type SanityInstance } from \"@sanity/sdk\";\nimport {\n type ConsentStatus,\n createBatchedStore,\n createSessionId,\n type TelemetryEvent,\n type TelemetryStore,\n} from \"@sanity/telemetry\";\nimport { assign, fromPromise, setup } from \"xstate\";\n\nimport type { OSBaseInput } from \"./root.machine\";\n\n/**\n * @public\n */\nexport type WorkbenchUserProperties = {\n version: string;\n organizationId: string;\n environment: string;\n userAgent: string;\n};\n\n/**\n * @internal\n */\nexport interface TelemetryInput extends OSBaseInput, WorkbenchUserProperties {}\n\n/**\n * TODO: this shouldn't be unique to the telemetry machine,\n * remove this and set it globally with a single client actor.\n */\nconst TELEMETRY_API_VERSION = \"2024-11-12\";\n/**\n * 30 seconds, in milliseconds, is the default flush interval\n * for the telemetry store.\n */\nconst FLUSH_INTERVAL_MS = 30_000;\n\ntype ConsentResult = { status: ConsentStatus };\n\nconst checkConsentLogic = fromPromise<\n ConsentResult,\n { instance: SanityInstance }\n>(async ({ input, signal }) => {\n try {\n const client = getClient(input.instance, {\n apiVersion: TELEMETRY_API_VERSION,\n });\n return await client.request<ConsentResult>({\n uri: \"/intake/telemetry-status\",\n tag: \"telemetry-consent\",\n signal,\n });\n } catch {\n return { status: \"undetermined\" } satisfies ConsentResult;\n }\n});\n\ntype TelemetryContext = {\n instance: SanityInstance;\n store: TelemetryStore<WorkbenchUserProperties> | null;\n userProperties: WorkbenchUserProperties;\n};\n\ntype TelemetryMachineEvent =\n | { type: \"telemetry.start\" }\n | { type: \"telemetry.stop\" };\n\nexport const telemetryLogic = setup({\n types: {\n input: {} as TelemetryInput,\n context: {} as TelemetryContext,\n events: {} as TelemetryMachineEvent,\n },\n actors: {\n checkConsent: checkConsentLogic,\n },\n guards: {\n isConsentGranted: (_, params: { status: ConsentStatus }) =>\n params.status === \"granted\",\n },\n actions: {\n createStore: assign({\n store: ({ context }) => {\n const sessionId = createSessionId();\n const client = getClient(context.instance, {\n apiVersion: TELEMETRY_API_VERSION,\n });\n const store = createBatchedStore<WorkbenchUserProperties>(sessionId, {\n flushInterval: FLUSH_INTERVAL_MS,\n resolveConsent: () =>\n client.request<{ status: ConsentStatus }>({\n uri: \"/intake/telemetry-status\",\n tag: \"telemetry-consent\",\n }),\n sendEvents: (batch: TelemetryEvent[]) =>\n client.request({\n uri: \"/intake/batch\",\n method: \"POST\",\n body: { batch },\n tag: \"telemetry.batch\",\n }),\n sendBeacon: (batch: TelemetryEvent[]) => {\n if (typeof navigator === \"undefined\") {\n return false;\n }\n return navigator.sendBeacon(\n client.getUrl(\"/intake/batch\"),\n JSON.stringify({ batch }),\n );\n },\n });\n store.logger.updateUserProperties(context.userProperties);\n return store;\n },\n }),\n teardownStore: ({ context }) => {\n context.store?.end();\n },\n },\n}).createMachine({\n id: \"telemetry\",\n initial: \"idle\",\n context: ({ input }) => ({\n instance: input.instance,\n store: null,\n userProperties: {\n version: input.version,\n organizationId: input.organizationId,\n environment: input.environment,\n userAgent: input.userAgent,\n },\n }),\n states: {\n idle: {\n on: {\n \"telemetry.start\": {\n target: \"checkingConsent\",\n },\n },\n },\n checkingConsent: {\n invoke: {\n src: \"checkConsent\",\n input: ({ context }) => ({\n instance: context.instance,\n }),\n onDone: [\n {\n guard: {\n type: \"isConsentGranted\",\n params: ({ event }) => ({\n status: event.output.status,\n }),\n },\n actions: [{ type: \"createStore\" }],\n target: \"active\",\n },\n {\n target: \"denied\",\n },\n ],\n },\n },\n active: {\n tags: [\"telemetry-resolved\"],\n exit: [{ type: \"teardownStore\" }],\n on: {\n \"telemetry.stop\": { target: \"stopped\" },\n },\n },\n stopped: {\n type: \"final\",\n },\n denied: {\n tags: [\"telemetry-resolved\"],\n },\n },\n});\n","import { createSanityInstance, type SanityInstance } from \"@sanity/sdk\";\nimport { raise, sendTo, setup, type ActorOptions } from \"xstate\";\n\nimport { authLogic } from \"./auth.machine\";\nimport { inspect } from \"./inspect\";\nimport { remotesLogic } from \"./remotes.machine\";\nimport {\n type SystemPreferencesAdapter,\n systemPreferencesLogic,\n} from \"./system-preferences.machine\";\nimport {\n telemetryLogic,\n type WorkbenchUserProperties,\n} from \"./telemetry.machine\";\n\ntype OSInput = WorkbenchUserProperties & {\n systemPreferencesAdapter?: SystemPreferencesAdapter;\n};\n\ntype OSContext = {\n instance: SanityInstance;\n userProperties: WorkbenchUserProperties;\n systemPreferencesAdapter: SystemPreferencesAdapter | undefined;\n};\n\n/**\n * The base inputs for the OS machine.\n * @internal\n */\nexport interface OSBaseInput extends Pick<OSContext, \"instance\"> {}\n\n/**\n * The sanity OS machine, responsible for managing the global state of the OS.\n * @public\n * @example\n * ```ts\n * import { os, createOSOptions } from \"@sanity/workbench/system\";\n * import { useActor } from \"@xstate/react\";\n *\n * const [state, send] = useActor(os, createOSOptions({\n * version: \"1.0.0\",\n * organizationId: \"...\",\n * environment: \"production\",\n * userAgent: navigator.userAgent,\n * }));\n * ```\n */\nexport const os = setup({\n types: {\n input: {} as OSInput,\n context: {} as OSContext,\n events: {} as\n | { type: \"boot.auth.ready\" }\n | { type: \"boot.auth.failed\" }\n | { type: \"boot.telemetry.ready\" },\n // https://github.com/statelyai/xstate/issues/5515\n children: {} as {\n auth: \"auth\";\n telemetry: \"telemetry\";\n \"system-preferences\": \"systemPreferences\";\n remotes: \"remotes\";\n },\n },\n actors: {\n auth: authLogic,\n telemetry: telemetryLogic,\n systemPreferences: systemPreferencesLogic,\n remotes: remotesLogic,\n },\n guards: {\n hasTag: (_, params: { hasTag: boolean }) => params.hasTag,\n },\n actions: {\n raiseAuthReady: raise({ type: \"boot.auth.ready\" }),\n raiseAuthFailed: raise({ type: \"boot.auth.failed\" }),\n raiseTelemetryReady: raise({\n type: \"boot.telemetry.ready\",\n }),\n startTelemetry: sendTo(\"telemetry\", {\n type: \"telemetry.start\",\n }),\n },\n}).createMachine({\n id: \"os\",\n context: ({ input }) => ({\n instance: createSanityInstance(),\n userProperties: {\n version: input.version,\n organizationId: input.organizationId,\n environment: input.environment,\n userAgent: input.userAgent,\n },\n systemPreferencesAdapter: input.systemPreferencesAdapter,\n }),\n initial: \"booting\",\n invoke: [\n {\n id: \"auth\",\n systemId: \"auth\",\n src: \"auth\",\n input: ({ context }) => ({ instance: context.instance }),\n onSnapshot: [\n {\n guard: {\n type: \"hasTag\",\n params: ({ event }) => ({\n hasTag: event.snapshot.hasTag(\"authenticated\"),\n }),\n },\n actions: [{ type: \"raiseAuthReady\" }],\n },\n {\n guard: {\n type: \"hasTag\",\n params: ({ event }) => ({\n hasTag: event.snapshot.hasTag(\"error\"),\n }),\n },\n actions: [{ type: \"raiseAuthFailed\" }],\n },\n ],\n },\n {\n id: \"telemetry\",\n systemId: \"telemetry\",\n src: \"telemetry\",\n input: ({ context }) => ({\n instance: context.instance,\n ...context.userProperties,\n }),\n onSnapshot: [\n {\n guard: {\n type: \"hasTag\",\n params: ({ event }) => ({\n hasTag: event.snapshot.hasTag(\"telemetry-resolved\"),\n }),\n },\n actions: [{ type: \"raiseTelemetryReady\" }],\n },\n ],\n },\n {\n id: \"system-preferences\",\n systemId: \"system-preferences\",\n src: \"systemPreferences\",\n input: ({ context }) => ({ adapter: context.systemPreferencesAdapter }),\n },\n {\n id: \"remotes\",\n systemId: \"remotes\",\n src: \"remotes\",\n },\n ],\n states: {\n booting: {\n initial: \"auth\",\n states: {\n auth: {\n on: {\n \"boot.auth.ready\": {\n target: \"telemetry\",\n actions: [{ type: \"startTelemetry\" }],\n },\n \"boot.auth.failed\": { target: \"error\" },\n },\n },\n telemetry: {\n on: {\n \"boot.telemetry.ready\": { target: \"done\" },\n },\n },\n error: {},\n done: { type: \"final\" },\n },\n onDone: { target: \"running\" },\n },\n running: {\n type: \"parallel\",\n },\n },\n});\n\n/**\n * Creates a set of default options for the OS machine. Forwards the workbench\n * user properties to the machine's input and wires the structured-logging\n * `inspect` callback. Browser-specific concerns (color-scheme seeding,\n * persistence) live in the {@link SystemPreferencesAdapter} the host passes\n * via `systemPreferencesAdapter`.\n * @public\n */\nexport function createOSOptions(input: OSInput) {\n return {\n id: \"os\",\n input,\n inspect,\n } satisfies ActorOptions<typeof os>;\n}\n"],"names":["log"],"mappings":";;;;;;;AAkBA,MAAM,iBAAiB;AAAA,EACrB,CAAC,EAAE,MAAA,MAAY,aAAa,MAAM,QAAQ,EAAE;AAC9C,GAOM,mBAAmB,YAA+B,OAAO,EAAE,YAAY;AAC3E,QAAM,OAAO,MAAM,QAAQ;AAC7B,CAAC,GAWY,YAAY,MAAM;AAAA,EAC7B,OAAO;AAAA,IACL,OAAO,CAAA;AAAA,IACP,SAAS,CAAA;AAAA,IACT,QAAQ,CAAA;AAAA,IACR,MAAM,CAAA;AAAA,EAAC;AAAA,EAET,QAAQ;AAAA,IACN,WAAW;AAAA,IACX,aAAa;AAAA,EAAA;AAAA,EAEf,QAAQ;AAAA,IACN,aAAa;AAAA,E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I;AAAA,IACJ;AAAA,IACA;AAAA,EAAA;AAEJ;"}
1
+ {"version":3,"file":"system.js","sources":["../src/system/load-federated-module.ts","../src/system/remote.machine.ts","../src/system/auth.machine.ts","../src/system/inspect.ts","../src/system/remotes.machine.ts","../src/system/service.machine.ts","../src/system/services.machine.ts","../src/system/system-preferences.machine.ts","../src/system/telemetry.machine.ts","../src/system/root.machine.ts"],"sourcesContent":["import type { FederationInstance } from \"@sanity/federation/runtime\";\n\nimport { logger } from \"../core/log\";\n\n/**\n * A module exposed by an application's federation remote.\n *\n * @public\n */\nexport interface FederatedModuleRef {\n /**\n * Fully-qualified module id — `${appId}/${expose}`, e.g.\n * `studio-1/views/feed/panel` (a view component) or `studio-1/App` (the\n * full-page view). The remote's name is its first segment.\n */\n moduleId: string;\n /** The remote's `mf-manifest.json` URL (served from the app's origin). */\n entry: string;\n}\n\n/**\n * Register an app's federation remote (idempotent) and load one of its exposes\n * by its fully-qualified `moduleId`. Failures propagate, so the caller drives\n * its own error handling (e.g. a machine's error state with the original\n * cause). For the render-empty-on-failure policy, use {@link loadFederatedModule}.\n */\nexport async function loadRemoteModule<T>(\n instance: FederationInstance,\n { moduleId, entry }: FederatedModuleRef,\n): Promise<T | null> {\n // The remote name is the first segment; the expose is the remainder.\n const name = moduleId.slice(0, moduleId.indexOf(\"/\"));\n instance.registerRemotes([{ name, entry }]);\n return (await instance.loadRemote<T | null>(moduleId)) ?? null;\n}\n\n/**\n * {@link loadRemoteModule} with the render-empty-on-failure policy: any failure\n * resolves to `null` (and logs), so every caller handles a missing interface\n * the same way — a panel renders empty, a worker doesn't spawn.\n *\n * @public\n */\nexport async function loadFederatedModule<T>(\n instance: FederationInstance,\n ref: FederatedModuleRef,\n): Promise<T | null> {\n try {\n return await loadRemoteModule<T>(instance, ref);\n } catch (error) {\n logger.error(`Failed to load federated module \"${ref.moduleId}\"`, error);\n return null;\n }\n}\n","import type { FederationInstance } from \"@sanity/federation/runtime\";\nimport { assign, fromPromise, sendParent, setup } from \"xstate\";\n\nimport { loadRemoteModule } from \"./load-federated-module\";\n\n/**\n * @public\n */\nexport interface RemoteRenderOptions {\n basePath?: string;\n scheme?: \"light\" | \"dark\";\n /**\n * This is a temporary measure designed to authenticate federated\n * studios & SDK apps before we write a working protocol.\n */\n unstable_temporaryToken?: string | null;\n}\n\n/**\n * A loaded render-contract module. `TProps` is what its `render` accepts —\n * `RemoteRenderOptions` for an application's full-page view, the view's props\n * for a dock-panel component.\n * @public\n */\nexport interface LoadedRemoteModule<TProps = RemoteRenderOptions> {\n render: (rootElement: HTMLElement, props?: TProps) => () => void;\n}\n\n/**\n * A worker service's loader module — the `worker` interface's expose. Carries\n * the worker bundle URL (root-relative to the app origin) for the host to\n * bootstrap, not a render function; the services counterpart of\n * {@link LoadedRemoteModule}.\n * @public\n */\nexport interface ServiceLoaderModule {\n url: string;\n type: string;\n name: string;\n version: number;\n}\n\n/**\n * The federated-module shape each interface type exposes, keyed by\n * `interface_type`. Every interface — `panel`, `app`, `worker` — loads through\n * the same {@link remoteLogic} lifecycle; this maps what its loaded module looks\n * like so each consumer narrows the machine's shape-agnostic `module` to the\n * right type: a render contract for `panel`/`app` (rendered by an island), a\n * worker loader for `worker` (run as a Web Worker, never rendered).\n * @public\n */\nexport interface RemoteModuleByInterfaceType {\n panel: LoadedRemoteModule;\n app: LoadedRemoteModule;\n worker: ServiceLoaderModule;\n}\n\n/**\n * @public\n */\nexport interface RemoteError {\n message: string;\n cause: unknown;\n}\n\n/**\n * Thrown by a render consumer (e.g. the island) when a loaded module doesn't\n * expose a `render` function. Render-specific — `remoteLogic` itself is\n * shape-agnostic, so this lives with the consumer that needs the contract, not\n * the loader. Surfaced via `RemoteError.cause` for consumers that discriminate.\n * @public\n */\nexport class ModuleShapeError extends Error {\n constructor(remoteId: string) {\n super(`Remote \"${remoteId}\" did not expose a render function`);\n }\n}\n\n/**\n * Thrown by the load actor when a remote's expose resolves empty — the module\n * isn't published, or `loadRemote` returned nothing. Generic across interface\n * types; the shape-specific check (a render function, a worker URL) is the\n * consumer's, since `remoteLogic` loads every interface the same way.\n * @internal\n */\nexport class ModuleLoadError extends Error {\n constructor(remoteId: string) {\n super(`Remote module \"${remoteId}\" failed to load`);\n }\n}\n\n/**\n * @internal\n */\nexport interface RemoteInput {\n /** Fully-qualified module id — `${appId}/${expose}`. One child per moduleId. */\n moduleId: string;\n entry: string;\n instance: FederationInstance;\n}\n\ntype RemoteContext = RemoteInput & {\n /** The loaded module, shape-agnostic — each consumer narrows it. @see {@link RemoteModuleByInterfaceType} */\n module: unknown;\n error: RemoteError | null;\n};\n\nconst loadLogic = fromPromise<unknown, RemoteInput>(async ({ input }) => {\n const remoteModule = await loadRemoteModule<unknown>(input.instance, {\n moduleId: input.moduleId,\n entry: input.entry,\n });\n // The loader is interface-agnostic: it only guarantees a module came back.\n // Render-vs-worker shape validation is the consumer's (a panel/app island\n // checks `render`; a service checks `url`).\n if (remoteModule == null) {\n throw new ModuleLoadError(input.moduleId);\n }\n return remoteModule;\n});\n\n/**\n * Lifecycle machine for a single federated interface module — an application's\n * `App` entry, one view component, or a worker service's loader. Interface-\n * agnostic: it loads and tracks any module, leaving the shape contract\n * (render vs. worker URL) to the consumer.\n *\n * Spawned by the {@link remotesLogic} supervisor on demand, one per remote id\n * (`${appId}/${moduleId}`). Each instance owns one module's load lifecycle:\n * `loading` → `loaded | error`. Tags (`loading` / `ready` / `failed`) drive the\n * UI contract — state names are internal.\n *\n * The machine sends a `remote.settled` event to its parent on entry to\n * either terminal state, reserved for future supervision/retry.\n *\n * @internal\n */\nexport const remoteLogic = setup({\n types: {\n input: {} as RemoteInput,\n context: {} as RemoteContext,\n tags: {} as \"loading\" | \"ready\" | \"failed\",\n },\n actors: {\n load: loadLogic,\n },\n actions: {\n setModule: assign({\n module: (_, params: { module: unknown }) => params.module,\n error: () => null,\n }),\n setError: assign({\n module: () => null,\n error: (_, params: { error: unknown }) => normaliseError(params.error),\n }),\n },\n}).createMachine({\n id: \"remote\",\n initial: \"loading\",\n context: ({ input }) => ({\n ...input,\n module: null,\n error: null,\n }),\n states: {\n loading: {\n tags: [\"loading\"],\n invoke: {\n src: \"load\",\n input: ({ context }) => ({\n moduleId: context.moduleId,\n entry: context.entry,\n instance: context.instance,\n }),\n onDone: {\n target: \"loaded\",\n actions: [\n {\n type: \"setModule\",\n params: ({ event }) => ({ module: event.output }),\n },\n ],\n },\n onError: {\n target: \"error\",\n actions: [\n {\n type: \"setError\",\n params: ({ event }) => ({ error: event.error }),\n },\n ],\n },\n },\n },\n loaded: {\n tags: [\"ready\"],\n entry: sendParent(({ context }) => ({\n type: \"remote.settled\" as const,\n moduleId: context.moduleId,\n status: \"loaded\" as const,\n })),\n },\n error: {\n tags: [\"failed\"],\n entry: sendParent(({ context }) => ({\n type: \"remote.settled\" as const,\n moduleId: context.moduleId,\n status: \"error\" as const,\n })),\n },\n },\n});\n\nfunction normaliseError(error: unknown): RemoteError {\n if (error instanceof Error) {\n return { message: error.message, cause: error };\n }\n return { message: String(error), cause: error };\n}\n","import {\n type AuthState,\n AuthStateType,\n type CurrentUser,\n getAuthState,\n type LoggedInAuthState,\n logout,\n type SanityInstance,\n} from \"@sanity/sdk\";\nimport { assign, fromObservable, fromPromise, setup } from \"xstate\";\n\nimport type { OSBaseInput } from \"./root.machine\";\n\n/**\n * @internal\n */\nexport interface AuthInput extends OSBaseInput {}\n\nconst authStateLogic = fromObservable<AuthState, AuthInput>(\n ({ input }) => getAuthState(input.instance).observable,\n);\n\n/**\n * @internal\n */\nexport interface LogoutInput extends OSBaseInput {}\n\nconst logoutActorLogic = fromPromise<void, LogoutInput>(async ({ input }) => {\n await logout(input.instance);\n});\n\ntype AuthContext = {\n instance: SanityInstance;\n token: string | null;\n currentUser: CurrentUser | null;\n error: unknown;\n};\n\ntype AuthEvent = { type: \"auth.logout\" };\n\nexport const authLogic = setup({\n types: {\n input: {} as AuthInput,\n context: {} as AuthContext,\n events: {} as AuthEvent,\n tags: {} as \"authenticating\" | \"authenticated\" | \"error\",\n },\n actors: {\n authState: authStateLogic,\n logoutActor: logoutActorLogic,\n },\n delays: {\n authTimeout: 30_000,\n },\n guards: {\n isLoggedInComplete: (_, params: { state: AuthState | undefined }) =>\n params.state?.type === AuthStateType.LOGGED_IN &&\n Boolean((params.state as LoggedInAuthState).token) &&\n (params.state as LoggedInAuthState).currentUser !== null,\n isAuthState: (\n _,\n params: { state: AuthState | undefined; type: AuthStateType },\n ) => params.state?.type === params.type,\n },\n actions: {\n setLoggedIn: assign({\n token: (_, params: { token: string; currentUser: CurrentUser }) =>\n params.token,\n currentUser: (_, params: { token: string; currentUser: CurrentUser }) =>\n params.currentUser,\n error: () => null,\n }),\n clearAuth: assign({\n token: () => null,\n currentUser: () => null,\n error: () => null,\n }),\n setError: assign({\n token: () => null,\n currentUser: () => null,\n error: (_, params: { error: unknown }) => params.error,\n }),\n },\n}).createMachine({\n id: \"auth\",\n initial: \"init\",\n context: ({ input }) => ({\n instance: input.instance,\n token: null,\n currentUser: null,\n error: null,\n }),\n invoke: {\n src: \"authState\",\n input: ({ context }) => ({ instance: context.instance }),\n onSnapshot: [\n {\n guard: {\n type: \"isLoggedInComplete\",\n params: ({ event }) => ({\n state: event.snapshot.context,\n }),\n },\n actions: [\n {\n type: \"setLoggedIn\",\n params: ({ event }) => {\n const state = event.snapshot.context as LoggedInAuthState;\n return {\n token: state.token,\n currentUser: state.currentUser!,\n };\n },\n },\n ],\n target: `.${AuthStateType.LOGGED_IN}`,\n },\n {\n guard: {\n type: \"isAuthState\",\n params: ({ event }) => ({\n state: event.snapshot.context,\n type: AuthStateType.LOGGING_IN,\n }),\n },\n actions: [{ type: \"clearAuth\" }],\n target: `.${AuthStateType.LOGGING_IN}`,\n },\n {\n guard: {\n type: \"isAuthState\",\n params: ({ event }) => ({\n state: event.snapshot.context,\n type: AuthStateType.ERROR,\n }),\n },\n actions: [\n {\n type: \"setError\",\n params: ({ event }) => ({\n error:\n event.snapshot.context?.type === AuthStateType.ERROR\n ? event.snapshot.context.error\n : null,\n }),\n },\n ],\n target: `.${AuthStateType.ERROR}`,\n },\n {\n guard: {\n type: \"isAuthState\",\n params: ({ event }) => ({\n state: event.snapshot.context,\n type: AuthStateType.LOGGED_OUT,\n }),\n },\n actions: [{ type: \"clearAuth\" }],\n target: `.${AuthStateType.LOGGED_OUT}`,\n },\n ],\n },\n states: {\n init: {\n tags: [\"authenticating\"],\n after: {\n authTimeout: {\n actions: [\n {\n type: \"setError\",\n params: () => ({\n error: new Error(\"Authentication timed out\"),\n }),\n },\n ],\n target: AuthStateType.ERROR,\n },\n },\n },\n [AuthStateType.LOGGING_IN]: {\n tags: [\"authenticating\"],\n after: {\n authTimeout: {\n actions: [\n {\n type: \"setError\",\n params: () => ({\n error: new Error(\"Authentication timed out\"),\n }),\n },\n ],\n target: AuthStateType.ERROR,\n },\n },\n },\n [AuthStateType.LOGGED_IN]: {\n tags: [\"authenticated\"],\n on: {\n \"auth.logout\": { target: \"logging-out\" },\n },\n },\n [\"logging-out\"]: {\n invoke: {\n src: \"logoutActor\",\n input: ({ context }) => ({ instance: context.instance }),\n onDone: {\n target: AuthStateType.LOGGED_OUT,\n },\n onError: {\n actions: [\n {\n type: \"setError\",\n params: ({ event }) => ({ error: event.error }),\n },\n ],\n target: AuthStateType.ERROR,\n },\n },\n },\n [AuthStateType.LOGGED_OUT]: {},\n [AuthStateType.ERROR]: { tags: [\"error\"] },\n },\n});\n","import { type ActorRefLike, type InspectionEvent } from \"xstate\";\n\nimport { logger } from \"../core\";\n\n// Mirrors @statelyai/inspect's ActorRefLikeWithData — the inspect\n// callback receives full Actor instances at runtime, but the type is\n// narrowed for @xstate/store compat.\ntype ActorRefWithAncestry = ActorRefLike & {\n id?: string;\n _parent?: ActorRefWithAncestry;\n};\n\nconst actorPath = (ref: ActorRefWithAncestry): string => {\n const segments: string[] = [];\n let current: ActorRefWithAncestry | undefined = ref;\n while (current) {\n segments.unshift(current.id ?? current.sessionId);\n current = current._parent;\n }\n return segments.join(\":\");\n};\n\n/** @internal exported for testing */\nexport const inspect = (event: InspectionEvent): void => {\n const ref = event.actorRef as ActorRefWithAncestry;\n const log = logger.child(actorPath(ref));\n\n switch (event.type) {\n case \"@xstate.snapshot\": {\n log.debug(\"snapshot\", event.snapshot);\n break;\n }\n case \"@xstate.event\":\n log.debug(\"event\", event.event);\n break;\n case \"@xstate.action\":\n log.debug(\"action\", event.action);\n break;\n }\n};\n","import { type FederationInstance } from \"@sanity/federation/runtime\";\nimport { type ActorRefFrom, assign, setup } from \"xstate\";\n\nimport { remoteLogic } from \"./remote.machine\";\n\n/** The shared federation instance, supplied by the root machine. */\ntype RemotesInput = {\n instance: FederationInstance;\n};\n\ntype RemotesContext = {\n instance: FederationInstance;\n children: Map<string, ActorRefFrom<typeof remoteLogic>>;\n};\n\ntype RemotesEvent =\n | { type: \"remote.load.request\"; moduleId: string; entry: string }\n | { type: \"remote.settled\"; moduleId: string; status: \"loaded\" | \"error\" };\n\n/**\n * Supervisor machine for federated modules.\n *\n * Uses the shared {@link FederationInstance} (the `workbench-applications`\n * instance, supplied by the root machine and shared with `services`) and spawns\n * one {@link remoteLogic} child per remote id (`${appId}/${moduleId}`) — so an\n * application's `App` entry and each of its dock-panel view components load (and\n * are tracked) independently. The\n * supervisor is invoked at the root of the OS machine for inspector visibility\n * (`[sanity-workbench:os:remotes]`) — boot does not gate on it.\n *\n * @internal\n */\nexport const remotesLogic = setup({\n types: {\n input: {} as RemotesInput,\n context: {} as RemotesContext,\n events: {} as RemotesEvent,\n },\n actors: {\n remote: remoteLogic,\n },\n guards: {\n remoteNotKnown: ({ context }, params: { moduleId: string }) =>\n !context.children.has(params.moduleId),\n },\n actions: {\n spawnRemote: assign({\n children: (\n { context, spawn },\n params: { moduleId: string; entry: string },\n ) => {\n const ref = spawn(\"remote\", {\n id: params.moduleId,\n systemId: `remotes.${params.moduleId}`,\n input: {\n moduleId: params.moduleId,\n entry: params.entry,\n instance: context.instance,\n },\n });\n return new Map(context.children).set(params.moduleId, ref);\n },\n }),\n },\n}).createMachine({\n id: \"remotes\",\n context: ({ input }) => ({\n instance: input.instance,\n children: new Map(),\n }),\n on: {\n \"remote.load.request\": {\n guard: {\n type: \"remoteNotKnown\",\n params: ({ event }) => ({ moduleId: event.moduleId }),\n },\n actions: [\n {\n type: \"spawnRemote\",\n params: ({ event }) => ({\n moduleId: event.moduleId,\n entry: event.entry,\n }),\n },\n ],\n },\n // Reserved for future supervision/retry. Forwarded by per-remote\n // children on entry to `loaded` or `error`; currently a no-op so the\n // event is part of the typed surface rather than a silent unknown.\n \"remote.settled\": {},\n },\n});\n","import { type FederationInstance } from \"@sanity/federation/runtime\";\nimport { assign, fromCallback, setup } from \"xstate\";\n\nimport { logger } from \"../core/log\";\nimport {\n remoteLogic,\n type RemoteError,\n type ServiceLoaderModule,\n} from \"./remote.machine\";\n\n/**\n * @internal\n */\nexport interface ServiceInput {\n /** Stable child key, `${appId}:${serviceName}`. */\n key: string;\n appId: string;\n serviceName: string;\n /** The app's `mf-manifest.json` URL — the federation remote entry. */\n entry: string;\n instance: FederationInstance;\n}\n\ntype ServiceContext = ServiceInput & {\n /** Resolved worker-bundle URL, absolute on the app origin. */\n workerUrl: string | null;\n};\n\n/** Federation expose segment a service's loader lives under: `services/<name>`. */\nconst SERVICES_MODULE = \"services\";\n\n/**\n * Run the worker. `new Worker(appOriginUrl)` is cross-origin-blocked, and the\n * dev worker isn't self-contained (its root-relative imports would resolve\n * against the wrong origin from a blob). So bootstrap a same-origin worker that\n * dynamically `import()`s the app-origin URL: the worker module then resolves\n * its own imports against the app origin, in dev and build alike. Crashes, a\n * failed load, and the worker's `console.*` (bridged by the wrapper) are\n * surfaced through the host logger (the host owns logging; a worker's own\n * console isn't visible in the page DevTools anyway). Cleanup disposes, then\n * terminates.\n */\nconst runWorker = fromCallback<\n { type: string },\n { key: string; serviceName: string; workerUrl: string }\n>(({ input }) => {\n let worker: Worker | undefined;\n let blobUrl: string | undefined;\n\n try {\n // A same-origin module worker whose only job is to load the real worker\n // from the app origin, so that worker's imports resolve there too.\n const bootstrap = `import(${JSON.stringify(input.workerUrl)})`;\n blobUrl = URL.createObjectURL(\n new Blob([bootstrap], { type: \"text/javascript\" }),\n );\n worker = new Worker(blobUrl, { type: \"module\" });\n\n worker.addEventListener(\"message\", (event: MessageEvent) => {\n if (event.data?.kind === \"workbench.worker.error\") {\n logger.error(\n `Service \"${input.key}\" worker error`,\n event.data.payload?.message,\n );\n } else if (event.data?.kind === \"workbench.worker.log\") {\n // Re-emit the worker's `console.*` (bridged by the wrapper) through the\n // host logger, prefixed with the service name so it shows in the page\n // console.\n const { level, message } = event.data.payload ?? {};\n const emit: Record<string, (message: string) => void> = {\n warn: logger.warn,\n error: logger.error,\n debug: logger.debug,\n };\n (emit[level] ?? logger.info)(\n `[service:${input.serviceName}] ${message ?? \"\"}`,\n );\n }\n });\n\n // A module-load failure (or any uncaught worker error) fires here on the\n // host side — surface it instead of failing silently.\n worker.addEventListener(\"error\", (event: ErrorEvent) => {\n logger.error(\n `Service \"${input.key}\" worker error: ${event.message || String(event)}`,\n );\n });\n } catch (error) {\n logger.error(`Service \"${input.key}\" failed to start its worker`, error);\n }\n\n return () => {\n try {\n worker?.postMessage({ kind: \"workbench.worker.terminate\" });\n } finally {\n worker?.terminate();\n if (blobUrl) URL.revokeObjectURL(blobUrl);\n }\n };\n});\n\n/**\n * Lifecycle machine for a single background service worker.\n *\n * Spawned by the {@link servicesLogic} supervisor, one per `(app, service)`.\n * `loading` loads the worker's loader module through the shared\n * {@link remoteLogic} lifecycle — the same machine every interface (panel, app,\n * worker) loads through — and reads the bundle URL off it. A worker isn't a\n * render module, so it's never handed to an island; `running` bootstraps it as\n * a Web Worker from that URL.\n *\n * @internal\n */\nexport const serviceLogic = setup({\n types: {\n input: {} as ServiceInput,\n context: {} as ServiceContext,\n tags: {} as \"loading\" | \"running\" | \"failed\",\n },\n actors: {\n loadInterface: remoteLogic,\n runWorker,\n },\n}).createMachine({\n id: \"service\",\n initial: \"loading\",\n context: ({ input }) => ({ ...input, workerUrl: null }),\n // The invoked loader `sendParent`s a `remote.settled` on settle; this machine\n // reacts via `onSnapshot` instead, so the event is a no-op here.\n on: { \"remote.settled\": {} },\n states: {\n loading: {\n tags: [\"loading\"],\n invoke: {\n id: \"loader\",\n src: \"loadInterface\",\n input: ({ context }) => ({\n moduleId: `${context.appId}/${SERVICES_MODULE}/${context.serviceName}`,\n entry: context.entry,\n instance: context.instance,\n }),\n onSnapshot: [\n {\n // Loaded and exposing a bundle URL → run it.\n guard: ({ event }) => {\n const module = event.snapshot.context\n .module as ServiceLoaderModule | null;\n return (\n event.snapshot.hasTag(\"ready\") &&\n typeof module?.url === \"string\"\n );\n },\n target: \"running\",\n actions: assign({\n workerUrl: ({ context, event }) => {\n const module = event.snapshot.context\n .module as ServiceLoaderModule;\n // The URL is root-relative to the app; resolve it absolute\n // against the app origin since the loader runs in the host page.\n return new URL(module.url, new URL(context.entry).origin).href;\n },\n }),\n },\n {\n // Load failed, or loaded without a usable URL → no worker.\n guard: ({ event }) => {\n const module = event.snapshot.context\n .module as ServiceLoaderModule | null;\n return (\n event.snapshot.hasTag(\"failed\") ||\n (event.snapshot.hasTag(\"ready\") &&\n typeof module?.url !== \"string\")\n );\n },\n target: \"error\",\n // A worker has no UI surface (unlike a view's error boundary), so a\n // failed load would otherwise be silent — log it through the host.\n actions: ({ context, event }) => {\n const cause = (event.snapshot.context.error as RemoteError | null)\n ?.message;\n logger.error(\n `Service \"${context.key}\" failed to load its worker${\n cause ? `: ${cause}` : \"\"\n }`,\n );\n },\n },\n ],\n },\n },\n running: {\n tags: [\"running\"],\n invoke: {\n src: \"runWorker\",\n input: ({ context }) => ({\n key: context.key,\n serviceName: context.serviceName,\n // `workerUrl` is set on entry to `running` from `loading`'s output.\n workerUrl: context.workerUrl!,\n }),\n },\n },\n error: {\n tags: [\"failed\"],\n },\n },\n});\n","import { type FederationInstance } from \"@sanity/federation/runtime\";\nimport { type ActorRefFrom, enqueueActions, setup } from \"xstate\";\n\nimport { serviceLogic } from \"./service.machine\";\n\n/** The shared federation instance, supplied by the root machine. */\ntype ServicesInput = {\n instance: FederationInstance;\n};\n\ntype ServicesContext = {\n instance: FederationInstance;\n children: Map<string, ActorRefFrom<typeof serviceLogic>>;\n};\n\n/**\n * The full set of background services the workbench should currently be\n * running, re-sent whenever the application list — or any app's declared\n * interfaces — changes. The supervisor reconciles its children against it.\n */\ntype ServicesEvent = {\n type: \"services.sync\";\n services: ReadonlyArray<{\n appId: string;\n serviceName: string;\n entry: string;\n }>;\n};\n\n/** Stable child key for a service: `${appId}:${serviceName}`. */\nfunction serviceKey(appId: string, serviceName: string): string {\n return `${appId}:${serviceName}`;\n}\n\n/**\n * Supervisor machine for background service workers.\n *\n * Uses the shared {@link FederationInstance} (supplied by the root machine and\n * shared with `remotes`, so an app's remote is registered once for both its\n * views and its workers) and spawns one {@link serviceLogic} child per\n * `(app, service)`. Invoked at the root of the OS machine for inspector\n * visibility — boot does not gate on it.\n *\n * On every `services.sync` it reconciles its children against the desired set:\n * a newly-declared worker is spawned, and a worker whose declaration was\n * removed (e.g. deleted from `sanity.cli.ts` during dev — FR-024) is stopped,\n * which disposes its `runWorker` callback and terminates the Web Worker. A\n * service `src` edit still triggers a Vite full page reload (workers have no\n * HMR boundary), which reboots the workbench and respawns with the new code.\n *\n * @internal\n */\nexport const servicesLogic = setup({\n types: {\n input: {} as ServicesInput,\n context: {} as ServicesContext,\n events: {} as ServicesEvent,\n },\n actors: {\n service: serviceLogic,\n },\n actions: {\n /**\n * Reconcile the running workers against the desired set: spawn the ones not\n * yet running, stop (and forget) the ones no longer declared.\n */\n syncServices: enqueueActions(({ context, event, enqueue }) => {\n const desired = new Map(\n event.services.map((service) => [\n serviceKey(service.appId, service.serviceName),\n service,\n ]),\n );\n\n // Stop + forget workers whose declaration was removed. Stopping the child\n // disposes its `runWorker` callback, which terminates the Web Worker.\n for (const [key, ref] of context.children) {\n if (!desired.has(key)) enqueue.stopChild(ref);\n }\n\n enqueue.assign({\n children: ({ context: ctx, spawn }) => {\n const next = new Map<string, ActorRefFrom<typeof serviceLogic>>();\n // Keep the children still declared.\n for (const [key, ref] of ctx.children) {\n if (desired.has(key)) next.set(key, ref);\n }\n // Spawn the newly-declared ones.\n for (const [key, service] of desired) {\n if (next.has(key)) continue;\n next.set(\n key,\n spawn(\"service\", {\n id: key,\n systemId: `services.${key}`,\n input: {\n key,\n appId: service.appId,\n serviceName: service.serviceName,\n entry: service.entry,\n instance: ctx.instance,\n },\n }),\n );\n }\n return next;\n },\n });\n }),\n },\n}).createMachine({\n id: \"services\",\n context: ({ input }) => ({\n instance: input.instance,\n children: new Map(),\n }),\n on: {\n \"services.sync\": { actions: \"syncServices\" },\n },\n});\n","import { assign, fromCallback, sendTo, setup } from \"xstate\";\n\ntype ColorScheme = \"light\" | \"dark\";\n\ntype ColorSchemePreference = \"system\" | ColorScheme;\n\n/**\n * The system-preferences machine's context. Consumers read fields directly\n * (e.g. via `useSelector`) rather than going through a resolver utility —\n * the action handlers keep `colorScheme` in sync with `preferredColorScheme`\n * and `osColorScheme`.\n *\n * Note: `colorScheme` is intentionally stored as derived state in context so\n * consumers can read the resolved value directly without a utility. The\n * action handlers below are the single source of truth for the resolution.\n * @public\n */\nexport type SystemPreferencesContext = {\n /** User's color scheme choice; `system` defers to the OS preference. */\n preferredColorScheme: ColorSchemePreference;\n /** Last reported OS color scheme. Used to resolve `colorScheme` when the\n * preference is `system`. */\n osColorScheme: ColorScheme;\n /** Resolved color scheme — what the UI should render. Recomputed by the\n * action handlers whenever an input changes. */\n colorScheme: ColorScheme;\n};\n\nconst DEFAULT_PREFERRED_COLOR_SCHEME: ColorSchemePreference = \"system\";\nconst DEFAULT_OS_COLOR_SCHEME: ColorScheme = \"light\";\n\n/**\n * Events the system-preferences machine accepts. Both originate from the\n * host's adapter — `preferredColorScheme.set` is also forwarded back to it\n * so it can persist the user's choice.\n * @public\n */\nexport type SystemPreferencesEvent =\n | {\n type: \"preferredColorScheme.set\";\n preferredColorScheme: ColorSchemePreference;\n }\n | {\n type: \"osColorScheme.set\";\n osColorScheme: ColorScheme;\n };\n\n/**\n * Adapter interface the host implements to give the system-preferences\n * machine access to the user's environment (OS color scheme, persistent\n * storage, cross-context change notifications).\n *\n * The package owns all orchestration — synchronous seeding, idempotent\n * persistence, mapping cleared storage to `\"system\"`. The host's\n * implementation is pure DOM/storage glue: read, write, subscribe.\n * @public\n */\nexport type SystemPreferencesAdapter = {\n /** Read the user's stored preference. `null` means \"no preference set\"\n * (the machine treats this as `\"system\"`). */\n getPreferredColorScheme: () => ColorSchemePreference | null;\n /** Write the user's preference to persistent storage. */\n persistPreferredColorScheme: (value: ColorSchemePreference) => void;\n /** Subscribe to cross-context preference changes (e.g. another tab\n * writing to the shared storage). The callback receives the new stored\n * value (or `null` if it was cleared). Returns an unsubscribe function. */\n subscribePreferredColorScheme: (\n callback: (next: ColorSchemePreference | null) => void,\n ) => () => void;\n /** Read the current OS-detected color scheme. */\n getOsColorScheme: () => ColorScheme;\n /** Subscribe to OS color-scheme changes (e.g. user flipping dark mode).\n * Returns an unsubscribe function. */\n subscribeOsColorScheme: (callback: (next: ColorScheme) => void) => () => void;\n};\n\nconst resolveColorScheme = (\n preferred: ColorSchemePreference,\n osColorScheme: ColorScheme,\n): ColorScheme => (preferred === \"system\" ? osColorScheme : preferred);\n\n// Internal bridge actor — subscribes to the host's adapter for runtime\n// changes and persists user-driven preference changes when the parent\n// forwards them. No-op if the host didn't pass an adapter (SSR, tests).\ntype AdapterBridgeReceiveEvent = Extract<\n SystemPreferencesEvent,\n { type: \"preferredColorScheme.set\" }\n>;\n\nconst adapterBridgeLogic = fromCallback<\n AdapterBridgeReceiveEvent,\n SystemPreferencesAdapter | undefined,\n SystemPreferencesEvent\n>(({ input: adapter, sendBack, receive }) => {\n if (!adapter) return;\n\n const unsubscribePreferredColorScheme = adapter.subscribePreferredColorScheme(\n (next) => {\n // Falls back to `\"system\"` so an external clear (another tab deleting\n // the key) resets the preference rather than silently keeping the\n // previous value.\n sendBack({\n type: \"preferredColorScheme.set\",\n preferredColorScheme: next ?? \"system\",\n });\n },\n );\n\n const unsubscribeOs = adapter.subscribeOsColorScheme((next) => {\n sendBack({ type: \"osColorScheme.set\", osColorScheme: next });\n });\n\n receive((event) => {\n // Idempotent: skip writes that match the current stored value so a\n // `preferredColorScheme.set` originating from cross-context change\n // doesn't loop back into another write.\n if (adapter.getPreferredColorScheme() === event.preferredColorScheme)\n return;\n\n adapter.persistPreferredColorScheme(event.preferredColorScheme);\n });\n\n return () => {\n unsubscribePreferredColorScheme();\n unsubscribeOs();\n };\n});\n\n/**\n * @internal\n */\nexport const systemPreferencesLogic = setup({\n types: {\n input: {} as { adapter?: SystemPreferencesAdapter },\n context: {} as SystemPreferencesContext & {\n adapter: SystemPreferencesAdapter | undefined;\n },\n events: {} as SystemPreferencesEvent,\n },\n actors: {\n adapterBridge: adapterBridgeLogic,\n },\n actions: {\n setPreferredColorScheme: assign({\n preferredColorScheme: (\n _,\n params: { preferredColorScheme: ColorSchemePreference },\n ) => params.preferredColorScheme,\n colorScheme: (\n { context },\n params: { preferredColorScheme: ColorSchemePreference },\n ) =>\n resolveColorScheme(params.preferredColorScheme, context.osColorScheme),\n }),\n setOsColorScheme: assign({\n osColorScheme: (_, params: { osColorScheme: ColorScheme }) =>\n params.osColorScheme,\n colorScheme: ({ context }, params: { osColorScheme: ColorScheme }) =>\n resolveColorScheme(context.preferredColorScheme, params.osColorScheme),\n }),\n },\n}).createMachine({\n id: \"system-preferences\",\n initial: \"ready\",\n context: ({ input }) => {\n const adapter = input.adapter;\n const preferredColorScheme =\n adapter?.getPreferredColorScheme() ?? DEFAULT_PREFERRED_COLOR_SCHEME;\n const osColorScheme =\n adapter?.getOsColorScheme() ?? DEFAULT_OS_COLOR_SCHEME;\n\n return {\n adapter,\n preferredColorScheme,\n osColorScheme,\n colorScheme: resolveColorScheme(preferredColorScheme, osColorScheme),\n };\n },\n invoke: {\n id: \"adapter\",\n src: \"adapterBridge\",\n input: ({ context }) => context.adapter,\n },\n states: {\n ready: {\n on: {\n \"preferredColorScheme.set\": {\n actions: [\n {\n type: \"setPreferredColorScheme\",\n params: ({ event }) => ({\n preferredColorScheme: event.preferredColorScheme,\n }),\n },\n // Forward to the adapter bridge so it can persist the user's\n // choice. The bridge guards against redundant writes, so\n // round-tripping a `preferredColorScheme.set` it sourced itself\n // (e.g. from a `storage` event in another tab) is a no-op.\n sendTo(\"adapter\", ({ event }) => event),\n ],\n },\n \"osColorScheme.set\": {\n actions: [\n {\n type: \"setOsColorScheme\",\n params: ({ event }) => ({\n osColorScheme: event.osColorScheme,\n }),\n },\n ],\n },\n },\n },\n },\n});\n","import { getClient, type SanityInstance } from \"@sanity/sdk\";\nimport {\n type ConsentStatus,\n createBatchedStore,\n createSessionId,\n type TelemetryEvent,\n type TelemetryStore,\n} from \"@sanity/telemetry\";\nimport { assign, fromPromise, setup } from \"xstate\";\n\nimport type { OSBaseInput } from \"./root.machine\";\n\n/**\n * @public\n */\nexport type WorkbenchUserProperties = {\n version: string;\n organizationId: string;\n environment: string;\n userAgent: string;\n};\n\n/**\n * @internal\n */\nexport interface TelemetryInput extends OSBaseInput, WorkbenchUserProperties {}\n\n/**\n * TODO: this shouldn't be unique to the telemetry machine,\n * remove this and set it globally with a single client actor.\n */\nconst TELEMETRY_API_VERSION = \"2024-11-12\";\n/**\n * 30 seconds, in milliseconds, is the default flush interval\n * for the telemetry store.\n */\nconst FLUSH_INTERVAL_MS = 30_000;\n\ntype ConsentResult = { status: ConsentStatus };\n\nconst checkConsentLogic = fromPromise<\n ConsentResult,\n { instance: SanityInstance }\n>(async ({ input, signal }) => {\n try {\n const client = getClient(input.instance, {\n apiVersion: TELEMETRY_API_VERSION,\n });\n return await client.request<ConsentResult>({\n uri: \"/intake/telemetry-status\",\n tag: \"telemetry-consent\",\n signal,\n });\n } catch {\n return { status: \"undetermined\" } satisfies ConsentResult;\n }\n});\n\ntype TelemetryContext = {\n instance: SanityInstance;\n store: TelemetryStore<WorkbenchUserProperties> | null;\n userProperties: WorkbenchUserProperties;\n};\n\ntype TelemetryMachineEvent =\n | { type: \"telemetry.start\" }\n | { type: \"telemetry.stop\" };\n\nexport const telemetryLogic = setup({\n types: {\n input: {} as TelemetryInput,\n context: {} as TelemetryContext,\n events: {} as TelemetryMachineEvent,\n },\n actors: {\n checkConsent: checkConsentLogic,\n },\n guards: {\n isConsentGranted: (_, params: { status: ConsentStatus }) =>\n params.status === \"granted\",\n },\n actions: {\n createStore: assign({\n store: ({ context }) => {\n const sessionId = createSessionId();\n const client = getClient(context.instance, {\n apiVersion: TELEMETRY_API_VERSION,\n });\n const store = createBatchedStore<WorkbenchUserProperties>(sessionId, {\n flushInterval: FLUSH_INTERVAL_MS,\n resolveConsent: () =>\n client.request<{ status: ConsentStatus }>({\n uri: \"/intake/telemetry-status\",\n tag: \"telemetry-consent\",\n }),\n sendEvents: (batch: TelemetryEvent[]) =>\n client.request({\n uri: \"/intake/batch\",\n method: \"POST\",\n body: { batch },\n tag: \"telemetry.batch\",\n }),\n sendBeacon: (batch: TelemetryEvent[]) => {\n if (typeof navigator === \"undefined\") {\n return false;\n }\n return navigator.sendBeacon(\n client.getUrl(\"/intake/batch\"),\n JSON.stringify({ batch }),\n );\n },\n });\n store.logger.updateUserProperties(context.userProperties);\n return store;\n },\n }),\n teardownStore: ({ context }) => {\n context.store?.end();\n },\n },\n}).createMachine({\n id: \"telemetry\",\n initial: \"idle\",\n context: ({ input }) => ({\n instance: input.instance,\n store: null,\n userProperties: {\n version: input.version,\n organizationId: input.organizationId,\n environment: input.environment,\n userAgent: input.userAgent,\n },\n }),\n states: {\n idle: {\n on: {\n \"telemetry.start\": {\n target: \"checkingConsent\",\n },\n },\n },\n checkingConsent: {\n invoke: {\n src: \"checkConsent\",\n input: ({ context }) => ({\n instance: context.instance,\n }),\n onDone: [\n {\n guard: {\n type: \"isConsentGranted\",\n params: ({ event }) => ({\n status: event.output.status,\n }),\n },\n actions: [{ type: \"createStore\" }],\n target: \"active\",\n },\n {\n target: \"denied\",\n },\n ],\n },\n },\n active: {\n tags: [\"telemetry-resolved\"],\n exit: [{ type: \"teardownStore\" }],\n on: {\n \"telemetry.stop\": { target: \"stopped\" },\n },\n },\n stopped: {\n type: \"final\",\n },\n denied: {\n tags: [\"telemetry-resolved\"],\n },\n },\n});\n","import {\n createInstance,\n type FederationInstance,\n} from \"@sanity/federation/runtime\";\nimport { log } from \"@sanity/federation/runtime/plugins/log\";\nimport { createSanityInstance, type SanityInstance } from \"@sanity/sdk\";\nimport { raise, sendTo, setup, type ActorOptions } from \"xstate\";\n\nimport { logger } from \"../core/log\";\nimport { authLogic } from \"./auth.machine\";\nimport { inspect } from \"./inspect\";\nimport { remotesLogic } from \"./remotes.machine\";\nimport { servicesLogic } from \"./services.machine\";\nimport {\n type SystemPreferencesAdapter,\n systemPreferencesLogic,\n} from \"./system-preferences.machine\";\nimport {\n telemetryLogic,\n type WorkbenchUserProperties,\n} from \"./telemetry.machine\";\n\ntype OSInput = WorkbenchUserProperties & {\n systemPreferencesAdapter?: SystemPreferencesAdapter;\n};\n\ntype OSContext = {\n instance: SanityInstance;\n /**\n * The single module-federation instance every interface loads through —\n * shared by the `remotes` (views) and `services` (workers) supervisors so an\n * app's remote is registered once for all its interfaces.\n */\n federationInstance: FederationInstance;\n userProperties: WorkbenchUserProperties;\n systemPreferencesAdapter: SystemPreferencesAdapter | undefined;\n};\n\n/**\n * The base inputs for the OS machine.\n * @internal\n */\nexport interface OSBaseInput extends Pick<OSContext, \"instance\"> {}\n\n/**\n * The sanity OS machine, responsible for managing the global state of the OS.\n * @public\n * @example\n * ```ts\n * import { os, createOSOptions } from \"@sanity/workbench/system\";\n * import { useActor } from \"@xstate/react\";\n *\n * const [state, send] = useActor(os, createOSOptions({\n * version: \"1.0.0\",\n * organizationId: \"...\",\n * environment: \"production\",\n * userAgent: navigator.userAgent,\n * }));\n * ```\n */\nexport const os = setup({\n types: {\n input: {} as OSInput,\n context: {} as OSContext,\n events: {} as\n | { type: \"boot.auth.ready\" }\n | { type: \"boot.auth.failed\" }\n | { type: \"boot.telemetry.ready\" },\n // https://github.com/statelyai/xstate/issues/5515\n children: {} as {\n auth: \"auth\";\n telemetry: \"telemetry\";\n \"system-preferences\": \"systemPreferences\";\n remotes: \"remotes\";\n services: \"services\";\n },\n },\n actors: {\n auth: authLogic,\n telemetry: telemetryLogic,\n systemPreferences: systemPreferencesLogic,\n remotes: remotesLogic,\n services: servicesLogic,\n },\n guards: {\n hasTag: (_, params: { hasTag: boolean }) => params.hasTag,\n },\n actions: {\n raiseAuthReady: raise({ type: \"boot.auth.ready\" }),\n raiseAuthFailed: raise({ type: \"boot.auth.failed\" }),\n raiseTelemetryReady: raise({\n type: \"boot.telemetry.ready\",\n }),\n startTelemetry: sendTo(\"telemetry\", {\n type: \"telemetry.start\",\n }),\n },\n}).createMachine({\n id: \"os\",\n context: ({ input }) => ({\n instance: createSanityInstance(),\n federationInstance: createInstance({\n name: \"workbench-applications\",\n plugins: [log(logger.debug)],\n }),\n userProperties: {\n version: input.version,\n organizationId: input.organizationId,\n environment: input.environment,\n userAgent: input.userAgent,\n },\n systemPreferencesAdapter: input.systemPreferencesAdapter,\n }),\n initial: \"booting\",\n invoke: [\n {\n id: \"auth\",\n systemId: \"auth\",\n src: \"auth\",\n input: ({ context }) => ({ instance: context.instance }),\n onSnapshot: [\n {\n guard: {\n type: \"hasTag\",\n params: ({ event }) => ({\n hasTag: event.snapshot.hasTag(\"authenticated\"),\n }),\n },\n actions: [{ type: \"raiseAuthReady\" }],\n },\n {\n guard: {\n type: \"hasTag\",\n params: ({ event }) => ({\n hasTag: event.snapshot.hasTag(\"error\"),\n }),\n },\n actions: [{ type: \"raiseAuthFailed\" }],\n },\n ],\n },\n {\n id: \"telemetry\",\n systemId: \"telemetry\",\n src: \"telemetry\",\n input: ({ context }) => ({\n instance: context.instance,\n ...context.userProperties,\n }),\n onSnapshot: [\n {\n guard: {\n type: \"hasTag\",\n params: ({ event }) => ({\n hasTag: event.snapshot.hasTag(\"telemetry-resolved\"),\n }),\n },\n actions: [{ type: \"raiseTelemetryReady\" }],\n },\n ],\n },\n {\n id: \"system-preferences\",\n systemId: \"system-preferences\",\n src: \"systemPreferences\",\n input: ({ context }) => ({ adapter: context.systemPreferencesAdapter }),\n },\n {\n id: \"remotes\",\n systemId: \"remotes\",\n src: \"remotes\",\n input: ({ context }) => ({ instance: context.federationInstance }),\n },\n {\n id: \"services\",\n systemId: \"services\",\n src: \"services\",\n input: ({ context }) => ({ instance: context.federationInstance }),\n },\n ],\n states: {\n booting: {\n initial: \"auth\",\n states: {\n auth: {\n on: {\n \"boot.auth.ready\": {\n target: \"telemetry\",\n actions: [{ type: \"startTelemetry\" }],\n },\n \"boot.auth.failed\": { target: \"error\" },\n },\n },\n telemetry: {\n on: {\n \"boot.telemetry.ready\": { target: \"done\" },\n },\n },\n error: {},\n done: { type: \"final\" },\n },\n onDone: { target: \"running\" },\n },\n running: {\n type: \"parallel\",\n },\n },\n});\n\n/**\n * Creates a set of default options for the OS machine. Forwards the workbench\n * user properties to the machine's input and wires the structured-logging\n * `inspect` callback. Browser-specific concerns (color-scheme seeding,\n * persistence) live in the {@link SystemPreferencesAdapter} the host passes\n * via `systemPreferencesAdapter`.\n * @public\n */\nexport function createOSOptions(input: OSInput) {\n return {\n id: \"os\",\n input,\n inspect,\n } satisfies ActorOptions<typeof os>;\n}\n"],"names":["log"],"mappings":";;;;;;;AA0BA,eAAsB,iBACpB,UACA,EAAE,UAAU,SACO;AAEnB,QAAM,OAAO,SAAS,MAAM,GAAG,SAAS,QAAQ,GAAG,CAAC;AACpD,SAAA,SAAS,gBAAgB,CAAC,EAAE,MAAM,MAAA,CAAO,CAAC,GAClC,MAAM,SAAS,WAAqB,QAAQ,KAAM;AAC5D;AASA,eAAsB,oBACpB,UACA,KACmB;AACnB,MAAI;AACF,WAAO,MAAM,iBAAoB,UAAU,GAAG;AAAA,EAChD,SAAS,OAA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,UAAO;AAAA,QAC3C;AAAA,QAEF,OAAO,CAAA;AAAA,QACP,MAAM,EAAE,MAAM,QAAA;AAAA,MAAQ;AAAA,MAExB,QAAQ,EAAE,QAAQ,UAAA;AAAA,IAAU;AAAA,IAE9B,SAAS;AAAA,MACP,MAAM;AAAA,IAAA;AAAA,EACR;AAEJ,CAAC;AAUM,SAAS,gBAAgB,OAAgB;AAC9C,SAAO;AAAA,IACL,IAAI;AAAA,IACJ;AAAA,IACA;AAAA,EAAA;AAEJ;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sanity/workbench",
3
- "version": "0.1.0-alpha.19",
3
+ "version": "0.1.0-alpha.20",
4
4
  "description": "Workbench component for the Sanity Content Operating System",
5
5
  "keywords": [],
6
6
  "homepage": "https://github.com/sanity-io/workbench/packages/@sanity/workbench#readme",
@@ -48,7 +48,7 @@
48
48
  "semver": "^7.7.4",
49
49
  "xstate": "^5.31.0",
50
50
  "zod": "^4.3.6",
51
- "@sanity/federation": "0.1.0-alpha.9"
51
+ "@sanity/federation": "0.1.0-alpha.10"
52
52
  },
53
53
  "devDependencies": {
54
54
  "@sanity/pkg-utils": "^9.2.3",
@@ -1,5 +1,37 @@
1
+ import {
2
+ type App,
3
+ type Interface,
4
+ InterfaceSchema,
5
+ type LocalApp,
6
+ type LocalInterface,
7
+ LocalInterfaceSchema,
8
+ type LocalPanel,
9
+ type LocalService,
10
+ type Panel,
11
+ type PanelComponent,
12
+ type Service,
13
+ } from "@sanity/federation";
1
14
  import type { Resource as ProtocolResource } from "@sanity/message-protocol";
2
15
 
16
+ // The interface model lives in @sanity/federation, which owns the
17
+ // `unstable_defineView` / `unstable_defineService` contracts. Re-export it so it
18
+ // stays part of the workbench app-model surface. `Panel`/`LocalPanel`,
19
+ // `Service`/`LocalService`, and `App`/`LocalApp` are the panel-, worker-, and
20
+ // app-typed subsets.
21
+ export {
22
+ type App,
23
+ type Interface,
24
+ InterfaceSchema,
25
+ type LocalApp,
26
+ type LocalInterface,
27
+ LocalInterfaceSchema,
28
+ type LocalPanel,
29
+ type LocalService,
30
+ type Panel,
31
+ type PanelComponent,
32
+ type Service,
33
+ };
34
+
3
35
  /**
4
36
  * @public
5
37
  */
@@ -26,7 +58,13 @@ export abstract class AbstractApplication<
26
58
  this.type = type;
27
59
  }
28
60
 
29
- abstract get href(): string;
61
+ /**
62
+ * The in-app route this application navigates to, or `null` when it isn't
63
+ * navigable as a full-page app (US5 — e.g. an SDK app with no `app` view).
64
+ * The dock renders a navigable item only for a non-null `href`; the app
65
+ * routes 404 a `null`-href app on direct visit.
66
+ */
67
+ abstract get href(): string | null;
30
68
 
31
69
  abstract get title(): string;
32
70
 
@@ -49,6 +87,47 @@ export abstract class AbstractApplication<
49
87
 
50
88
  abstract get url(): URL;
51
89
 
90
+ /**
91
+ * Interfaces the application exposes (e.g. dock panels). Defaults to none;
92
+ * user applications surface what they declared via `unstable_defineApp`.
93
+ */
94
+ get interfaces(): readonly LocalInterface[] {
95
+ return [];
96
+ }
97
+
98
+ /**
99
+ * Whether the application has a navigable full-page `app` view (US5). Defaults
100
+ * to `true` — studios, Canvas, and Media Library are always navigable. An SDK
101
+ * app overrides this to derive it from whether it declares an `app` interface.
102
+ */
103
+ get hasAppView(): boolean {
104
+ return true;
105
+ }
106
+
107
+ /**
108
+ * Federation module id of the app's full-page view (`${id}/App`), or `null`
109
+ * when it can't be federation-loaded: the app isn't federated (Canvas, Media
110
+ * Library, deployed apps shown in an iframe) or has no app view. Only a
111
+ * non-null `moduleId` is fetched and rendered by the remotes machine.
112
+ */
113
+ get moduleId(): string | null {
114
+ return this.isFederated && this.hasAppView ? `${this.id}/App` : null;
115
+ }
116
+
117
+ /**
118
+ * Federation module id of one of this app's panel view components, or `null`
119
+ * when the app isn't federated (a non-federated app's panels can't be loaded
120
+ * as remotes).
121
+ */
122
+ resolveViewModuleId(
123
+ view: LocalPanel,
124
+ component: PanelComponent,
125
+ ): string | null {
126
+ return this.isFederated
127
+ ? `${this.id}/views/${view.name}/${component}`
128
+ : null;
129
+ }
130
+
52
131
  get initials(): string {
53
132
  const SYMBOLS = /[^\p{Alpha}\p{N}\p{White_Space}]/gu;
54
133
  const WHITESPACE = /\p{White_Space}+/u;
@@ -16,6 +16,8 @@ export const CoreAppUserApplicationManifest = z.object({
16
16
  version: z.string(),
17
17
  icon: z.string().optional(),
18
18
  title: z.string().optional(),
19
+ group: z.string().optional(),
20
+ priority: z.number().optional(),
19
21
  });
20
22
 
21
23
  /**
@@ -94,7 +96,9 @@ export class CoreAppApplication extends UserApplication<
94
96
  this.activeDeployment = application.activeDeployment;
95
97
  }
96
98
 
97
- get href() {
99
+ // Typed `string | null` so the UI-aware remote subclass can override it to
100
+ // `null` for a non-navigable app (US5); the core route itself is always set.
101
+ get href(): string | null {
98
102
  return this.isLocal
99
103
  ? `/local/${this.id}`
100
104
  : `/application/${this.application.id}`;
@@ -25,6 +25,8 @@ export const ServerManifest = z.object({
25
25
  buildId: z.string().optional(),
26
26
  bundleVersion: z.string().optional(),
27
27
  version: z.string().optional(),
28
+ group: z.string().optional(),
29
+ priority: z.number().optional(),
28
30
  workspaces: z
29
31
  .array(
30
32
  Workspace.extend({
@@ -47,6 +49,8 @@ export const ClientManifest = z.object({
47
49
  version: z.number(),
48
50
  createdAt: z.string(),
49
51
  studioVersion: z.string().optional(),
52
+ group: z.string().optional(),
53
+ priority: z.number().optional(),
50
54
  workspaces: z.array(
51
55
  Workspace.extend({
52
56
  schema: z.string(),
@@ -5,6 +5,8 @@ import { z } from "zod";
5
5
  import {
6
6
  AbstractApplication,
7
7
  type AbstractApplicationType,
8
+ type LocalInterface,
9
+ LocalInterfaceSchema,
8
10
  } from "../applications/application";
9
11
  import { getSanityDomain, getSanityEnv } from "../env";
10
12
  import type { CoreAppUserApplicationManifest } from "./core-app";
@@ -36,6 +38,12 @@ export function brandUserApplicationId(id: string): UserApplicationId {
36
38
  const LocalUserApplicationBase = z.object({
37
39
  host: z.string(),
38
40
  port: z.number(),
41
+ /**
42
+ * Interfaces the app exposes — dock panels (`interface_type: "panel"`) and
43
+ * background workers (`interface_type: "worker"`), forwarded from the dev
44
+ * server in one list.
45
+ */
46
+ interfaces: z.array(LocalInterfaceSchema).optional(),
39
47
  /** The `deployment.appId` from the application's `sanity.cli.ts`, when set. */
40
48
  id: z.string().optional(),
41
49
  /**
@@ -86,6 +94,11 @@ export const UserApplicationBase = z.object({
86
94
  createdAt: z.string(),
87
95
  updatedAt: z.string(),
88
96
  dashboardStatus: z.enum(["default", "disabled"]),
97
+ /**
98
+ * Interfaces the app exposes (dock panels and background workers). Not part
99
+ * of the manifest.
100
+ */
101
+ interfaces: z.array(LocalInterfaceSchema).optional(),
89
102
  });
90
103
 
91
104
  /**
@@ -167,6 +180,10 @@ export abstract class UserApplication<
167
180
  return this.#isLocal;
168
181
  }
169
182
 
183
+ override get interfaces(): readonly LocalInterface[] {
184
+ return this.application.interfaces ?? [];
185
+ }
186
+
170
187
  /**
171
188
  * @returns A fully resolved URL instance for the application.
172
189
  * For internal applications, constructs a URL using the Sanity studio domain
@@ -1,15 +1,20 @@
1
1
  export type { AuthInput, LogoutInput } from "./auth.machine";
2
+ export { ModuleShapeError } from "./remote.machine";
2
3
  export type {
3
4
  LoadedRemoteModule,
4
5
  RemoteError,
5
6
  RemoteInput,
7
+ RemoteModuleByInterfaceType,
6
8
  RemoteRenderOptions,
9
+ ServiceLoaderModule,
7
10
  } from "./remote.machine";
8
11
  export type {
9
12
  SystemPreferencesAdapter,
10
13
  SystemPreferencesContext,
11
14
  SystemPreferencesEvent,
12
15
  } from "./system-preferences.machine";
16
+ export { loadFederatedModule } from "./load-federated-module";
17
+ export type { FederatedModuleRef } from "./load-federated-module";
13
18
  export { os, createOSOptions } from "./root.machine";
14
19
  export type {
15
20
  TelemetryInput,
@@ -0,0 +1,54 @@
1
+ import type { FederationInstance } from "@sanity/federation/runtime";
2
+
3
+ import { logger } from "../core/log";
4
+
5
+ /**
6
+ * A module exposed by an application's federation remote.
7
+ *
8
+ * @public
9
+ */
10
+ export interface FederatedModuleRef {
11
+ /**
12
+ * Fully-qualified module id — `${appId}/${expose}`, e.g.
13
+ * `studio-1/views/feed/panel` (a view component) or `studio-1/App` (the
14
+ * full-page view). The remote's name is its first segment.
15
+ */
16
+ moduleId: string;
17
+ /** The remote's `mf-manifest.json` URL (served from the app's origin). */
18
+ entry: string;
19
+ }
20
+
21
+ /**
22
+ * Register an app's federation remote (idempotent) and load one of its exposes
23
+ * by its fully-qualified `moduleId`. Failures propagate, so the caller drives
24
+ * its own error handling (e.g. a machine's error state with the original
25
+ * cause). For the render-empty-on-failure policy, use {@link loadFederatedModule}.
26
+ */
27
+ export async function loadRemoteModule<T>(
28
+ instance: FederationInstance,
29
+ { moduleId, entry }: FederatedModuleRef,
30
+ ): Promise<T | null> {
31
+ // The remote name is the first segment; the expose is the remainder.
32
+ const name = moduleId.slice(0, moduleId.indexOf("/"));
33
+ instance.registerRemotes([{ name, entry }]);
34
+ return (await instance.loadRemote<T | null>(moduleId)) ?? null;
35
+ }
36
+
37
+ /**
38
+ * {@link loadRemoteModule} with the render-empty-on-failure policy: any failure
39
+ * resolves to `null` (and logs), so every caller handles a missing interface
40
+ * the same way — a panel renders empty, a worker doesn't spawn.
41
+ *
42
+ * @public
43
+ */
44
+ export async function loadFederatedModule<T>(
45
+ instance: FederationInstance,
46
+ ref: FederatedModuleRef,
47
+ ): Promise<T | null> {
48
+ try {
49
+ return await loadRemoteModule<T>(instance, ref);
50
+ } catch (error) {
51
+ logger.error(`Failed to load federated module "${ref.moduleId}"`, error);
52
+ return null;
53
+ }
54
+ }