@sanity/workbench-cli 2.16.0 → 2.17.0

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,4 +1,4 @@
1
- import { t as DevServerManifest } from "./registry-NvtHmoN1.js";
1
+ import { t as DevServerManifest } from "./registry-CbruhmxE.js";
2
2
  import { ViteDevServer } from "vite";
3
3
  import { CliConfig, Output } from "@sanity/cli-core";
4
4
  /**
@@ -1,4 +1,4 @@
1
- import { t as DevServerManifest } from "./registry-NvtHmoN1.js";
1
+ import { t as DevServerManifest } from "./registry-CbruhmxE.js";
2
2
  import { CliConfig, Output } from "@sanity/cli-core";
3
3
  interface StartWorkbenchPreviewOptions {
4
4
  /** Directory for the workbench Vite server's dependency cache. */
@@ -15,6 +15,7 @@ declare const devServerManifestSchema: z.ZodMiniObject<{
15
15
  version: z.ZodMiniString<string>;
16
16
  }, z.core.$strip>>>;
17
17
  host: z.ZodMiniString<string>;
18
+ https: z.ZodMiniOptional<z.ZodMiniBoolean<boolean>>;
18
19
  id: z.ZodMiniOptional<z.ZodMiniString<string>>;
19
20
  interfaces: z.ZodMiniOptional<z.ZodMiniArray<z.ZodMiniUnion<readonly [z.ZodMiniDiscriminatedUnion<[z.ZodMiniObject<{
20
21
  metadata: z.ZodMiniNullable<z.ZodMiniObject<{
@@ -129,4 +130,4 @@ declare const devServerManifestSchema: z.ZodMiniObject<{
129
130
  */
130
131
  type DevServerManifest = z.infer<typeof devServerManifestSchema>;
131
132
  export { DevServerManifest as t };
132
- //# sourceMappingURL=registry-NvtHmoN1.d.ts.map
133
+ //# sourceMappingURL=registry-CbruhmxE.d.ts.map
@@ -20,7 +20,7 @@ const HMR_REMOUNT = `if (import.meta.hot) {
20
20
  }`;
21
21
  /**
22
22
  * - `app`: omit when the preamble imports `App` itself (the SDK-app entry).
23
- * - `version`: lets the host check view/web worker contract compatibility.
23
+ * - `version`: the contract version the host checks before rendering.
24
24
  */ export function renderRemote({ app, hmr = false, isolateStyles = false, preamble, version, viewType }) {
25
25
  // Keep apps without styled-components buildable; the unused branch is removed from their bundle.
26
26
  const stylesheetImport = isolateStyles ? "import { StyleSheetManager } from 'styled-components'" : 'const StyleSheetManager = undefined';
@@ -31,7 +31,9 @@ import * as React from 'react'
31
31
  import { createRoot } from 'react-dom/client'
32
32
  ${stylesheetImport}
33
33
  ${preamble}
34
- ${app ? `\nconst App = ${app}\n` : ''}${version ? `\nexport const version = ${version}\n` : ''}
34
+ ${app ? `\nconst App = ${app}\n` : ''}
35
+ export const version = ${version}
36
+
35
37
  // The SDK reads this slot via getDashboardRootContext(), so its symbol, key and value are a
36
38
  // contract. Keyed by createContext, not the React namespace: Vite dev pre-bundling can give two
37
39
  // importers of one React copy different namespaces.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/actions/build/render-remote.ts"],"sourcesContent":["/**\n * Every generated entry (studio, SDK app, view artifacts) shares one render body\n * so the host can drive them all the same way; only the `App` they bind differs.\n * The workbench host depends on `render`'s signature and return shape, so change\n * them together.\n */\n\n// Re-renders through the new module so edits apply without a page reload. The\n// new module mounts in the foreground, so reapply the host's lifecycle. The host\n// still holds this module's controller, so it forwards to the new one.\nconst HMR_REMOUNT = `if (import.meta.hot) {\n import.meta.hot.accept((next) => {\n if (!next) return\n for (const [rootElement, args] of renderArgs) {\n rootMap.get(rootElement)?.unmount()\n rootMap.delete(rootElement)\n closeRoot(rootElement)\n args.next = next.render(rootElement, args.props, args.renderOptions)\n args.next.setLifecycle(args.lifecycle)\n }\n })\n}`\n\n/**\n * - `app`: omit when the preamble imports `App` itself (the SDK-app entry).\n * - `version`: lets the host check view/web worker contract compatibility.\n */\nexport function renderRemote({\n app,\n hmr = false,\n isolateStyles = false,\n preamble,\n version,\n viewType,\n}: {\n app?: string\n hmr?: boolean\n isolateStyles?: boolean\n preamble: string\n version?: string\n viewType?: string\n}): string {\n // Keep apps without styled-components buildable; the unused branch is removed from their bundle.\n const stylesheetImport = isolateStyles\n ? \"import { StyleSheetManager } from 'styled-components'\"\n : 'const StyleSheetManager = undefined'\n\n return `\\\n// This file is auto-generated on 'sanity build' / 'sanity dev'\n// Modifications to this file are automatically discarded\nimport * as React from 'react'\nimport { createRoot } from 'react-dom/client'\n${stylesheetImport}\n${preamble}\n${app ? `\\nconst App = ${app}\\n` : ''}${version ? `\\nexport const version = ${version}\\n` : ''}\n// The SDK reads this slot via getDashboardRootContext(), so its symbol, key and value are a\n// contract. Keyed by createContext, not the React namespace: Vite dev pre-bundling can give two\n// importers of one React copy different namespaces.\nconst rootSlot = (globalThis[Symbol.for('sanity.os.root')] ??= new WeakMap())\nif (!rootSlot.has(React.createContext)) rootSlot.set(React.createContext, React.createContext(undefined))\nconst RootContext = rootSlot.get(React.createContext)\nconst rootMap = new Map()\nconst rootContexts = new Map()\n// A shared default sheet can overwrite another app's global rules; each root needs its own sheet.\nconst styleTargets = new Map()\nconst stylisPlugins = new Map()\nconst renderArgs = new Map()\n// On globalThis: every module embeds its own copy of this harness, and names must be page-unique.\nconst stylisPluginCount = Symbol.for('sanity.os.stylisPluginCount')\n\n// Identical CSS gets an identical class in every sheet, so a later sheet overrides earlier rules.\n// StyleSheetManager hashes stylis plugin names into class names: a uniquely named no-op isolates a root.\nfunction uniqueStylisPlugin() {\n globalThis[stylisPluginCount] = (globalThis[stylisPluginCount] ?? 0) + 1\n return Object.defineProperty(() => {}, 'name', { value: 'sanity-root-' + globalThis[stylisPluginCount] })\n}\n\n// The SDK disposes the root's instance, closing its bus connection, when the signal aborts. Next tick:\n// a host disposing a child root from its own cleanup code leaves the child still unmounting.\nfunction closeRoot(rootElement) {\n const closing = rootContexts.get(rootElement)\n rootContexts.delete(rootElement)\n if (closing) setTimeout(() => closing.controller.abort(), 0)\n}\n\nfunction mount(rootElement, args) {\n let root = rootMap.get(rootElement)\n if (!root) {\n root = createRoot(rootElement, args?.renderOptions?.rootOptions)\n rootMap.set(rootElement, root)\n const controller = new AbortController()\n // Read once: the SDK pins the root's bus identity when it first connects.\n const { moduleId, parentKey } = args?.renderOptions ?? {}\n rootContexts.set(rootElement, { controller, value: { signal: controller.signal, moduleId, parentKey${viewType ? `, viewType: ${JSON.stringify(viewType)}` : ''} } })\n if (StyleSheetManager) {\n const target = rootElement.ownerDocument.createElement('sanity-styles')\n if (typeof __SANITY_APP_ID__ === 'string') target.setAttribute('data-application-id', __SANITY_APP_ID__)\n // React can replace the mount node's contents; keep its stylesheet outside that node.\n rootElement.ownerDocument.head.appendChild(target)\n styleTargets.set(rootElement, target)\n stylisPlugins.set(rootElement, [uniqueStylisPlugin()])\n }\n }\n const rootContext = rootContexts.get(rootElement)\n\n if (rootContext.value.props !== args.props) rootContext.value = { ...rootContext.value, props: args.props }\n\n let element = React.createElement(RootContext.Provider, { value: rootContext.value }, React.createElement(App, args.props))\n if (StyleSheetManager) element = React.createElement(StyleSheetManager, { target: styleTargets.get(rootElement), stylisPlugins: stylisPlugins.get(rootElement) }, element)\n // The host's React can't pause this root, so the host pauses the app through this Activity.\n // Keep it inside StrictMode: outside, it stops StrictMode double-invoking effects.\n element = React.createElement(React.Activity, { mode: args.lifecycle === 'background' ? 'hidden' : 'visible' }, element)\n if (args?.renderOptions?.reactStrictMode) element = React.createElement(React.StrictMode, null, element)\n root.render(element)\n}\n\nexport function render(rootElement, props, renderOptions) {\n const args = { lifecycle: 'foreground', props, renderOptions }\n renderArgs.set(rootElement, args)\n mount(rootElement, args)\n return {\n dispose() {\n const current = renderArgs.get(rootElement)\n renderArgs.delete(rootElement)\n if (current?.next) return current.next.dispose()\n const root = rootMap.get(rootElement)\n rootMap.delete(rootElement)\n root?.unmount()\n // Unmount first so effect cleanup can still reach this root's stylesheet.\n styleTargets.get(rootElement)?.remove()\n styleTargets.delete(rootElement)\n stylisPlugins.delete(rootElement)\n closeRoot(rootElement)\n },\n setLifecycle(state) {\n const current = renderArgs.get(rootElement)\n if (!current) return\n if (current.next) return current.next.setLifecycle(state)\n current.lifecycle = state\n mount(rootElement, current)\n },\n }\n}${hmr ? `\\n\\n${HMR_REMOUNT}` : ''}\n`\n}\n"],"names":["HMR_REMOUNT","renderRemote","app","hmr","isolateStyles","preamble","version","viewType","stylesheetImport","JSON","stringify"],"mappings":"AAAA;;;;;CAKC,GAED,8EAA8E;AAC9E,iFAAiF;AACjF,uEAAuE;AACvE,MAAMA,cAAc,CAAC;;;;;;;;;;;CAWpB,CAAC;AAEF;;;CAGC,GACD,OAAO,SAASC,aAAa,EAC3BC,GAAG,EACHC,MAAM,KAAK,EACXC,gBAAgB,KAAK,EACrBC,QAAQ,EACRC,OAAO,EACPC,QAAQ,EAQT;IACC,iGAAiG;IACjG,MAAMC,mBAAmBJ,gBACrB,0DACA;IAEJ,OAAO,CAAC;;;;;AAKV,EAAEI,iBAAiB;AACnB,EAAEH,SAAS;AACX,EAAEH,MAAM,CAAC,cAAc,EAAEA,IAAI,EAAE,CAAC,GAAG,KAAKI,UAAU,CAAC,yBAAyB,EAAEA,QAAQ,EAAE,CAAC,GAAG,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;uGAuCQ,EAAEC,WAAW,CAAC,YAAY,EAAEE,KAAKC,SAAS,CAACH,WAAW,GAAG,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAiDlK,EAAEJ,MAAM,CAAC,IAAI,EAAEH,aAAa,GAAG,GAAG;AACnC,CAAC;AACD"}
1
+ {"version":3,"sources":["../../../src/actions/build/render-remote.ts"],"sourcesContent":["/**\n * Every generated entry (studio, SDK app, view artifacts) shares one render body\n * so the host can drive them all the same way; only the `App` they bind differs.\n * The workbench host depends on `render`'s signature and return shape, so change\n * them together.\n */\n\n// Re-renders through the new module so edits apply without a page reload. The\n// new module mounts in the foreground, so reapply the host's lifecycle. The host\n// still holds this module's controller, so it forwards to the new one.\nconst HMR_REMOUNT = `if (import.meta.hot) {\n import.meta.hot.accept((next) => {\n if (!next) return\n for (const [rootElement, args] of renderArgs) {\n rootMap.get(rootElement)?.unmount()\n rootMap.delete(rootElement)\n closeRoot(rootElement)\n args.next = next.render(rootElement, args.props, args.renderOptions)\n args.next.setLifecycle(args.lifecycle)\n }\n })\n}`\n\n/**\n * - `app`: omit when the preamble imports `App` itself (the SDK-app entry).\n * - `version`: the contract version the host checks before rendering.\n */\nexport function renderRemote({\n app,\n hmr = false,\n isolateStyles = false,\n preamble,\n version,\n viewType,\n}: {\n app?: string\n hmr?: boolean\n isolateStyles?: boolean\n preamble: string\n version: string\n viewType?: string\n}): string {\n // Keep apps without styled-components buildable; the unused branch is removed from their bundle.\n const stylesheetImport = isolateStyles\n ? \"import { StyleSheetManager } from 'styled-components'\"\n : 'const StyleSheetManager = undefined'\n\n return `\\\n// This file is auto-generated on 'sanity build' / 'sanity dev'\n// Modifications to this file are automatically discarded\nimport * as React from 'react'\nimport { createRoot } from 'react-dom/client'\n${stylesheetImport}\n${preamble}\n${app ? `\\nconst App = ${app}\\n` : ''}\nexport const version = ${version}\n\n// The SDK reads this slot via getDashboardRootContext(), so its symbol, key and value are a\n// contract. Keyed by createContext, not the React namespace: Vite dev pre-bundling can give two\n// importers of one React copy different namespaces.\nconst rootSlot = (globalThis[Symbol.for('sanity.os.root')] ??= new WeakMap())\nif (!rootSlot.has(React.createContext)) rootSlot.set(React.createContext, React.createContext(undefined))\nconst RootContext = rootSlot.get(React.createContext)\nconst rootMap = new Map()\nconst rootContexts = new Map()\n// A shared default sheet can overwrite another app's global rules; each root needs its own sheet.\nconst styleTargets = new Map()\nconst stylisPlugins = new Map()\nconst renderArgs = new Map()\n// On globalThis: every module embeds its own copy of this harness, and names must be page-unique.\nconst stylisPluginCount = Symbol.for('sanity.os.stylisPluginCount')\n\n// Identical CSS gets an identical class in every sheet, so a later sheet overrides earlier rules.\n// StyleSheetManager hashes stylis plugin names into class names: a uniquely named no-op isolates a root.\nfunction uniqueStylisPlugin() {\n globalThis[stylisPluginCount] = (globalThis[stylisPluginCount] ?? 0) + 1\n return Object.defineProperty(() => {}, 'name', { value: 'sanity-root-' + globalThis[stylisPluginCount] })\n}\n\n// The SDK disposes the root's instance, closing its bus connection, when the signal aborts. Next tick:\n// a host disposing a child root from its own cleanup code leaves the child still unmounting.\nfunction closeRoot(rootElement) {\n const closing = rootContexts.get(rootElement)\n rootContexts.delete(rootElement)\n if (closing) setTimeout(() => closing.controller.abort(), 0)\n}\n\nfunction mount(rootElement, args) {\n let root = rootMap.get(rootElement)\n if (!root) {\n root = createRoot(rootElement, args?.renderOptions?.rootOptions)\n rootMap.set(rootElement, root)\n const controller = new AbortController()\n // Read once: the SDK pins the root's bus identity when it first connects.\n const { moduleId, parentKey } = args?.renderOptions ?? {}\n rootContexts.set(rootElement, { controller, value: { signal: controller.signal, moduleId, parentKey${viewType ? `, viewType: ${JSON.stringify(viewType)}` : ''} } })\n if (StyleSheetManager) {\n const target = rootElement.ownerDocument.createElement('sanity-styles')\n if (typeof __SANITY_APP_ID__ === 'string') target.setAttribute('data-application-id', __SANITY_APP_ID__)\n // React can replace the mount node's contents; keep its stylesheet outside that node.\n rootElement.ownerDocument.head.appendChild(target)\n styleTargets.set(rootElement, target)\n stylisPlugins.set(rootElement, [uniqueStylisPlugin()])\n }\n }\n const rootContext = rootContexts.get(rootElement)\n\n if (rootContext.value.props !== args.props) rootContext.value = { ...rootContext.value, props: args.props }\n\n let element = React.createElement(RootContext.Provider, { value: rootContext.value }, React.createElement(App, args.props))\n if (StyleSheetManager) element = React.createElement(StyleSheetManager, { target: styleTargets.get(rootElement), stylisPlugins: stylisPlugins.get(rootElement) }, element)\n // The host's React can't pause this root, so the host pauses the app through this Activity.\n // Keep it inside StrictMode: outside, it stops StrictMode double-invoking effects.\n element = React.createElement(React.Activity, { mode: args.lifecycle === 'background' ? 'hidden' : 'visible' }, element)\n if (args?.renderOptions?.reactStrictMode) element = React.createElement(React.StrictMode, null, element)\n root.render(element)\n}\n\nexport function render(rootElement, props, renderOptions) {\n const args = { lifecycle: 'foreground', props, renderOptions }\n renderArgs.set(rootElement, args)\n mount(rootElement, args)\n return {\n dispose() {\n const current = renderArgs.get(rootElement)\n renderArgs.delete(rootElement)\n if (current?.next) return current.next.dispose()\n const root = rootMap.get(rootElement)\n rootMap.delete(rootElement)\n root?.unmount()\n // Unmount first so effect cleanup can still reach this root's stylesheet.\n styleTargets.get(rootElement)?.remove()\n styleTargets.delete(rootElement)\n stylisPlugins.delete(rootElement)\n closeRoot(rootElement)\n },\n setLifecycle(state) {\n const current = renderArgs.get(rootElement)\n if (!current) return\n if (current.next) return current.next.setLifecycle(state)\n current.lifecycle = state\n mount(rootElement, current)\n },\n }\n}${hmr ? `\\n\\n${HMR_REMOUNT}` : ''}\n`\n}\n"],"names":["HMR_REMOUNT","renderRemote","app","hmr","isolateStyles","preamble","version","viewType","stylesheetImport","JSON","stringify"],"mappings":"AAAA;;;;;CAKC,GAED,8EAA8E;AAC9E,iFAAiF;AACjF,uEAAuE;AACvE,MAAMA,cAAc,CAAC;;;;;;;;;;;CAWpB,CAAC;AAEF;;;CAGC,GACD,OAAO,SAASC,aAAa,EAC3BC,GAAG,EACHC,MAAM,KAAK,EACXC,gBAAgB,KAAK,EACrBC,QAAQ,EACRC,OAAO,EACPC,QAAQ,EAQT;IACC,iGAAiG;IACjG,MAAMC,mBAAmBJ,gBACrB,0DACA;IAEJ,OAAO,CAAC;;;;;AAKV,EAAEI,iBAAiB;AACnB,EAAEH,SAAS;AACX,EAAEH,MAAM,CAAC,cAAc,EAAEA,IAAI,EAAE,CAAC,GAAG,GAAG;uBACf,EAAEI,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;uGAwCsE,EAAEC,WAAW,CAAC,YAAY,EAAEE,KAAKC,SAAS,CAACH,WAAW,GAAG,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAiDlK,EAAEJ,MAAM,CAAC,IAAI,EAAEH,aAAa,GAAG,GAAG;AACnC,CAAC;AACD"}
@@ -1,5 +1,6 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
+ import { WINDOW_CONTRACT_VERSION } from '../../../../contract.js';
3
4
  import { renderRemote } from '../../render-remote.js';
4
5
  import { RESOURCE_BINDINGS_ENTRY_IMPORT, RESOURCE_BINDINGS_FILENAME, RESOURCE_BINDINGS_MODULE_SOURCE } from '../../resource-bindings.js';
5
6
  import { FEDERATION_FILE_NAME, RUNTIME_DIR } from '../constants.js';
@@ -15,13 +16,15 @@ const studioEntry = (isolateStyles)=>renderRemote({
15
16
  isolateStyles,
16
17
  preamble: `%RESOURCE_BINDINGS_IMPORT%import { Studio } from 'sanity'
17
18
  import { studioProps } from '${AUTO_UPDATES_ID}'
18
- import config from %STUDIO_CONFIG%`
19
+ import config from %STUDIO_CONFIG%`,
20
+ version: String(WINDOW_CONTRACT_VERSION)
19
21
  });
20
22
  // An SDK app's default export is the component; it Fast-Refreshes through its
21
23
  // own dev server, so the wrapper needs no HMR boundary.
22
24
  const appEntry = (isolateStyles)=>renderRemote({
23
25
  isolateStyles,
24
- preamble: `%RESOURCE_BINDINGS_IMPORT%import App from %APP_ENTRY%`
26
+ preamble: `%RESOURCE_BINDINGS_IMPORT%import App from %APP_ENTRY%`,
27
+ version: String(WINDOW_CONTRACT_VERSION)
25
28
  });
26
29
  // A branded app that declares no `entry` (e.g. a dock-only panel/worker app)
27
30
  // has no navigable full-page view, so there's no `App` to import. The runtime
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../src/actions/build/vite/plugins/plugin-sanity-federation-runtime.ts"],"sourcesContent":["import fs from 'node:fs'\nimport path from 'node:path'\n\nimport {type EnvironmentModuleNode, type Plugin} from 'vite'\n\nimport {renderRemote} from '../../render-remote.js'\nimport {\n RESOURCE_BINDINGS_ENTRY_IMPORT,\n RESOURCE_BINDINGS_FILENAME,\n RESOURCE_BINDINGS_MODULE_SOURCE,\n} from '../../resource-bindings.js'\nimport {FEDERATION_FILE_NAME, RUNTIME_DIR} from '../constants.js'\nimport {getFederationApi} from './plugin-module-federation.js'\nimport {AUTO_UPDATES_ID} from './plugin-sanity-auto-updates.js'\n\nconst REMOTE_ENTRY_FILE = `${FEDERATION_FILE_NAME}.jsx`\n\n// The studio wraps `Studio` with the user's config; HMR re-renders through the\n// new module so a config edit takes effect. The `%RESOURCE_BINDINGS_IMPORT%`\n// placeholder is filled in per-build (Blueprints only — see below).\nconst studioEntry = (isolateStyles: boolean) =>\n renderRemote({\n app: `(props) => React.createElement(Studio, { config, ...studioProps(), ...props })`,\n hmr: true,\n isolateStyles,\n preamble: `%RESOURCE_BINDINGS_IMPORT%import { Studio } from 'sanity'\nimport { studioProps } from '${AUTO_UPDATES_ID}'\nimport config from %STUDIO_CONFIG%`,\n })\n\n// An SDK app's default export is the component; it Fast-Refreshes through its\n// own dev server, so the wrapper needs no HMR boundary.\nconst appEntry = (isolateStyles: boolean) =>\n renderRemote({\n isolateStyles,\n preamble: `%RESOURCE_BINDINGS_IMPORT%import App from %APP_ENTRY%`,\n })\n\n// A branded app that declares no `entry` (e.g. a dock-only panel/worker app)\n// has no navigable full-page view, so there's no `App` to import. The runtime\n// still needs a valid module for the federation build input, but it exposes no\n// `./App` (see `plugin.ts`) — its `render` is unreachable and throws if reached.\n// It renders no React tree, so it carries no lifecycle controller: there is\n// nothing to pause.\nconst HEADLESS_APP_ENTRY = `\\\n// This file is auto-generated on 'sanity dev'\n// Modifications to this file are automatically discarded\n// This application declares no app view (no \\`entry\\`): it isn't navigable as a\n// full-page app, only its panels/web workers are exposed.\n%RESOURCE_BINDINGS_IMPORT%export function render() {\n throw new Error('This application has no app view: it declares no \\`entry\\`.')\n}\n`\n\nexport type FederationRuntimeOptions =\n | {appEntry?: string; isApp: true; isBlueprints?: boolean}\n | {isApp: false; isBlueprints?: boolean; studioConfigPath: string}\n\nfunction renderEntry(options: FederationRuntimeOptions, isolateStyles: boolean): string {\n const {isBlueprints} = options\n\n let content: string\n if (options.isApp) {\n content = options.appEntry\n ? appEntry(isolateStyles).replace(/%APP_ENTRY%/, JSON.stringify(options.appEntry))\n : HEADLESS_APP_ENTRY\n } else {\n content = studioEntry(isolateStyles).replace(\n /%STUDIO_CONFIG%/,\n JSON.stringify(options.studioConfigPath),\n )\n }\n\n // Blueprints only: the remote entry statically imports the resource-bindings\n // module first, so bindings evaluate before app code. Off Blueprints the\n // placeholder resolves to nothing and the module is neither imported nor\n // written below.\n return content.replace(\n /%RESOURCE_BINDINGS_IMPORT%/,\n isBlueprints ? `${RESOURCE_BINDINGS_ENTRY_IMPORT}\\n` : '',\n )\n}\n\nexport function sanityFederationRuntime(options: FederationRuntimeOptions): Plugin {\n const {isBlueprints} = options\n let entryFileAbsPath = ''\n\n return {\n configResolved(config) {\n const dir = path.resolve(config.root, RUNTIME_DIR)\n entryFileAbsPath = path.join(dir, REMOTE_ENTRY_FILE)\n\n fs.mkdirSync(dir, {recursive: true})\n const isolateStyles = getFederationApi(config.plugins)?.isolateStyles ?? false\n fs.writeFileSync(entryFileAbsPath, renderEntry(options, isolateStyles))\n\n if (isBlueprints) {\n // Brett bakes the resolved values into this module at deploy.\n fs.writeFileSync(\n path.join(dir, RESOURCE_BINDINGS_FILENAME),\n RESOURCE_BINDINGS_MODULE_SOURCE,\n )\n }\n },\n hotUpdate({file, modules, timestamp}) {\n if (options.isApp) return\n if (this.environment.name !== 'client') return\n\n const {moduleGraph} = this.environment\n const studioMods = moduleGraph.getModulesByFile(entryFileAbsPath)\n if (!studioMods?.size) return\n\n // Is the changed file reachable from the studio entry?\n const visited = new Set<EnvironmentModuleNode>()\n const queue: EnvironmentModuleNode[] = [...studioMods]\n while (queue.length > 0) {\n const mod = queue.pop()!\n if (visited.has(mod)) continue\n visited.add(mod)\n if (mod.file === file) {\n // The walk from `file` up through importers dead-ends at federation\n // gaps, so invalidate changed modules ourselves and route HMR to the\n // self-accepting studio entry.\n const seen = new Set<EnvironmentModuleNode>()\n for (const m of modules) {\n moduleGraph.invalidateModule(m, seen, timestamp, true)\n }\n return [...studioMods]\n }\n for (const dep of mod.importedModules) queue.push(dep)\n }\n },\n name: 'sanity/federation-runtime',\n }\n}\n"],"names":["fs","path","renderRemote","RESOURCE_BINDINGS_ENTRY_IMPORT","RESOURCE_BINDINGS_FILENAME","RESOURCE_BINDINGS_MODULE_SOURCE","FEDERATION_FILE_NAME","RUNTIME_DIR","getFederationApi","AUTO_UPDATES_ID","REMOTE_ENTRY_FILE","studioEntry","isolateStyles","app","hmr","preamble","appEntry","HEADLESS_APP_ENTRY","renderEntry","options","isBlueprints","content","isApp","replace","JSON","stringify","studioConfigPath","sanityFederationRuntime","entryFileAbsPath","configResolved","config","dir","resolve","root","join","mkdirSync","recursive","plugins","writeFileSync","hotUpdate","file","modules","timestamp","environment","name","moduleGraph","studioMods","getModulesByFile","size","visited","Set","queue","length","mod","pop","has","add","seen","m","invalidateModule","dep","importedModules","push"],"mappings":"AAAA,OAAOA,QAAQ,UAAS;AACxB,OAAOC,UAAU,YAAW;AAI5B,SAAQC,YAAY,QAAO,yBAAwB;AACnD,SACEC,8BAA8B,EAC9BC,0BAA0B,EAC1BC,+BAA+B,QAC1B,6BAA4B;AACnC,SAAQC,oBAAoB,EAAEC,WAAW,QAAO,kBAAiB;AACjE,SAAQC,gBAAgB,QAAO,gCAA+B;AAC9D,SAAQC,eAAe,QAAO,kCAAiC;AAE/D,MAAMC,oBAAoB,GAAGJ,qBAAqB,IAAI,CAAC;AAEvD,+EAA+E;AAC/E,6EAA6E;AAC7E,oEAAoE;AACpE,MAAMK,cAAc,CAACC,gBACnBV,aAAa;QACXW,KAAK,CAAC,8EAA8E,CAAC;QACrFC,KAAK;QACLF;QACAG,UAAU,CAAC;6BACc,EAAEN,gBAAgB;kCACb,CAAC;IACjC;AAEF,8EAA8E;AAC9E,wDAAwD;AACxD,MAAMO,WAAW,CAACJ,gBAChBV,aAAa;QACXU;QACAG,UAAU,CAAC,qDAAqD,CAAC;IACnE;AAEF,6EAA6E;AAC7E,8EAA8E;AAC9E,+EAA+E;AAC/E,iFAAiF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KAAK,UAAU;YAExC,MAAM,EAACC,WAAW,EAAC,GAAG,IAAI,CAACF,WAAW;YACtC,MAAMG,aAAaD,YAAYE,gBAAgB,CAACnB;YAChD,IAAI,CAACkB,YAAYE,MAAM;YAEvB,uDAAuD;YACvD,MAAMC,UAAU,IAAIC;YACpB,MAAMC,QAAiC;mBAAIL;aAAW;YACtD,MAAOK,MAAMC,MAAM,GAAG,EAAG;gBACvB,MAAMC,MAAMF,MAAMG,GAAG;gBACrB,IAAIL,QAAQM,GAAG,CAACF,MAAM;gBACtBJ,QAAQO,GAAG,CAACH;gBACZ,IAAIA,IAAIb,IAAI,KAAKA,MAAM;oBACrB,oEAAoE;oBACpE,qEAAqE;oBACrE,+BAA+B;oBAC/B,MAAMiB,OAAO,IAAIP;oBACjB,KAAK,MAAMQ,KAAKjB,QAAS;wBACvBI,YAAYc,gBAAgB,CAACD,GAAGD,MAAMf,WAAW;oBACnD;oBACA,OAAO;2BAAII;qBAAW;gBACxB;gBACA,KAAK,MAAMc,OAAOP,IAAIQ,eAAe,CAAEV,MAAMW,IAAI,CAACF;YACpD;QACF;QACAhB,MAAM;IACR;AACF"}
1
+ {"version":3,"sources":["../../../../../src/actions/build/vite/plugins/plugin-sanity-federation-runtime.ts"],"sourcesContent":["import fs from 'node:fs'\nimport path from 'node:path'\n\nimport {type EnvironmentModuleNode, type Plugin} from 'vite'\n\nimport {WINDOW_CONTRACT_VERSION} from '../../../../contract.js'\nimport {renderRemote} from '../../render-remote.js'\nimport {\n RESOURCE_BINDINGS_ENTRY_IMPORT,\n RESOURCE_BINDINGS_FILENAME,\n RESOURCE_BINDINGS_MODULE_SOURCE,\n} from '../../resource-bindings.js'\nimport {FEDERATION_FILE_NAME, RUNTIME_DIR} from '../constants.js'\nimport {getFederationApi} from './plugin-module-federation.js'\nimport {AUTO_UPDATES_ID} from './plugin-sanity-auto-updates.js'\n\nconst REMOTE_ENTRY_FILE = `${FEDERATION_FILE_NAME}.jsx`\n\n// The studio wraps `Studio` with the user's config; HMR re-renders through the\n// new module so a config edit takes effect. The `%RESOURCE_BINDINGS_IMPORT%`\n// placeholder is filled in per-build (Blueprints only — see below).\nconst studioEntry = (isolateStyles: boolean) =>\n renderRemote({\n app: `(props) => React.createElement(Studio, { config, ...studioProps(), ...props })`,\n hmr: true,\n isolateStyles,\n preamble: `%RESOURCE_BINDINGS_IMPORT%import { Studio } from 'sanity'\nimport { studioProps } from '${AUTO_UPDATES_ID}'\nimport config from %STUDIO_CONFIG%`,\n version: String(WINDOW_CONTRACT_VERSION),\n })\n\n// An SDK app's default export is the component; it Fast-Refreshes through its\n// own dev server, so the wrapper needs no HMR boundary.\nconst appEntry = (isolateStyles: boolean) =>\n renderRemote({\n isolateStyles,\n preamble: `%RESOURCE_BINDINGS_IMPORT%import App from %APP_ENTRY%`,\n version: String(WINDOW_CONTRACT_VERSION),\n })\n\n// A branded app that declares no `entry` (e.g. a dock-only panel/worker app)\n// has no navigable full-page view, so there's no `App` to import. The runtime\n// still needs a valid module for the federation build input, but it exposes no\n// `./App` (see `plugin.ts`) — its `render` is unreachable and throws if reached.\n// It renders no React tree, so it carries no lifecycle controller: there is\n// nothing to pause.\nconst HEADLESS_APP_ENTRY = `\\\n// This file is auto-generated on 'sanity dev'\n// Modifications to this file are automatically discarded\n// This application declares no app view (no \\`entry\\`): it isn't navigable as a\n// full-page app, only its panels/web workers are exposed.\n%RESOURCE_BINDINGS_IMPORT%export function render() {\n throw new Error('This application has no app view: it declares no \\`entry\\`.')\n}\n`\n\nexport type FederationRuntimeOptions =\n | {appEntry?: string; isApp: true; isBlueprints?: boolean}\n | {isApp: false; isBlueprints?: boolean; studioConfigPath: string}\n\nfunction renderEntry(options: FederationRuntimeOptions, isolateStyles: boolean): string {\n const {isBlueprints} = options\n\n let content: string\n if (options.isApp) {\n content = options.appEntry\n ? appEntry(isolateStyles).replace(/%APP_ENTRY%/, JSON.stringify(options.appEntry))\n : HEADLESS_APP_ENTRY\n } else {\n content = studioEntry(isolateStyles).replace(\n /%STUDIO_CONFIG%/,\n JSON.stringify(options.studioConfigPath),\n )\n }\n\n // Blueprints only: the remote entry statically imports the resource-bindings\n // module first, so bindings evaluate before app code. Off Blueprints the\n // placeholder resolves to nothing and the module is neither imported nor\n // written below.\n return content.replace(\n /%RESOURCE_BINDINGS_IMPORT%/,\n isBlueprints ? `${RESOURCE_BINDINGS_ENTRY_IMPORT}\\n` : '',\n )\n}\n\nexport function sanityFederationRuntime(options: FederationRuntimeOptions): Plugin {\n const {isBlueprints} = options\n let entryFileAbsPath = ''\n\n return {\n configResolved(config) {\n const dir = path.resolve(config.root, RUNTIME_DIR)\n entryFileAbsPath = path.join(dir, REMOTE_ENTRY_FILE)\n\n fs.mkdirSync(dir, {recursive: true})\n const isolateStyles = getFederationApi(config.plugins)?.isolateStyles ?? false\n fs.writeFileSync(entryFileAbsPath, renderEntry(options, isolateStyles))\n\n if (isBlueprints) {\n // Brett bakes the resolved values into this module at deploy.\n fs.writeFileSync(\n path.join(dir, RESOURCE_BINDINGS_FILENAME),\n RESOURCE_BINDINGS_MODULE_SOURCE,\n )\n }\n },\n hotUpdate({file, modules, timestamp}) {\n if (options.isApp) return\n if (this.environment.name !== 'client') return\n\n const {moduleGraph} = this.environment\n const studioMods = moduleGraph.getModulesByFile(entryFileAbsPath)\n if (!studioMods?.size) return\n\n // Is the changed file reachable from the studio entry?\n const visited = new Set<EnvironmentModuleNode>()\n const queue: EnvironmentModuleNode[] = [...studioMods]\n while (queue.length > 0) {\n const mod = queue.pop()!\n if (visited.has(mod)) continue\n visited.add(mod)\n if (mod.file === file) {\n // The walk from `file` up through importers dead-ends at federation\n // gaps, so invalidate changed modules ourselves and route HMR to the\n // self-accepting studio entry.\n const seen = new Set<EnvironmentModuleNode>()\n for (const m of modules) {\n moduleGraph.invalidateModule(m, seen, timestamp, true)\n }\n return [...studioMods]\n }\n for (const dep of mod.importedModules) queue.push(dep)\n }\n },\n name: 'sanity/federation-runtime',\n }\n}\n"],"names":["fs","path","WINDOW_CONTRACT_VERSION","renderRemote","RESOURCE_BINDINGS_ENTRY_IMPORT","RESOURCE_BINDINGS_FILENAME","RESOURCE_BINDINGS_MODULE_SOURCE","FEDERATION_FILE_NAME","RUNTIME_DIR","getFederationApi","AUTO_UPDATES_ID","REMOTE_ENTRY_FILE","studioEntry","isolateStyles","app","hmr","preamble","version","String","appEntry","HEADLESS_APP_ENTRY","renderEntry","options","isBlueprints","content","isApp","replace","JSON","stringify","studioConfigPath","sanityFederationRuntime","entryFileAbsPath","configResolved","config","dir","resolve","root","join","mkdirSync","recursive","plugins","writeFileSync","hotUpdate","file","modules","timestamp","environment","name","moduleGraph","studioMods","getModulesByFile","size","visited","Set","queue","length","mod","pop","has","add","seen","m","invalidateModule","dep","importedModules","push"],"mappings":"AAAA,OAAOA,QAAQ,UAAS;AACxB,OAAOC,UAAU,YAAW;AAI5B,SAAQC,uBAAuB,QAAO,0BAAyB;AAC/D,SAAQC,YAAY,QAAO,yBAAwB;AACnD,SACEC,8BAA8B,EAC9BC,0BAA0B,EAC1BC,+BAA+B,QAC1B,6BAA4B;AACnC,SAAQC,oBAAoB,EAAEC,WAAW,QAAO,kBAAiB;AACjE,SAAQC,gBAAgB,QAAO,gCAA+B;AAC9D,SAAQC,eAAe,QAAO,kCAAiC;AAE/D,MAAMC,oBAAoB,GAAGJ,qBAAqB,IAAI,CAAC;AAEvD,+EAA+E;AAC/E,6EAA6E;AAC7E,oEAAoE;AACpE,MAAMK,cAAc,CAACC,gBACnBV,aAAa;QACXW,KAAK,CAAC,8EAA8E,CAAC;QACrFC,KAAK;QACLF;QACAG,UAAU,CAAC;6BACc,EAAEN,gBAAgB;kCACb,CAAC;QAC/BO,SAASC,OAAOhB;IAClB;AAEF,8EAA8E;AAC9E,wDAAwD;AACxD,MAAMiB,WAAW,CAACN,gBAChBV,aAAa;QACXU;QACAG,UAAU,CAAC,qDAAqD,CAAC;QACjEC,SAASC,OAAOhB;IAClB;AAEF,6EAA6E;AAC7E,8EAA8E;A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CAACqB,WAAW,CAACC,IAAI,KAAK,UAAU;YAExC,MAAM,EAACC,WAAW,EAAC,GAAG,IAAI,CAACF,WAAW;YACtC,MAAMG,aAAaD,YAAYE,gBAAgB,CAACnB;YAChD,IAAI,CAACkB,YAAYE,MAAM;YAEvB,uDAAuD;YACvD,MAAMC,UAAU,IAAIC;YACpB,MAAMC,QAAiC;mBAAIL;aAAW;YACtD,MAAOK,MAAMC,MAAM,GAAG,EAAG;gBACvB,MAAMC,MAAMF,MAAMG,GAAG;gBACrB,IAAIL,QAAQM,GAAG,CAACF,MAAM;gBACtBJ,QAAQO,GAAG,CAACH;gBACZ,IAAIA,IAAIb,IAAI,KAAKA,MAAM;oBACrB,oEAAoE;oBACpE,qEAAqE;oBACrE,+BAA+B;oBAC/B,MAAMiB,OAAO,IAAIP;oBACjB,KAAK,MAAMQ,KAAKjB,QAAS;wBACvBI,YAAYc,gBAAgB,CAACD,GAAGD,MAAMf,WAAW;oBACnD;oBACA,OAAO;2BAAII;qBAAW;gBACxB;gBACA,KAAK,MAAMc,OAAOP,IAAIQ,eAAe,CAAEV,MAAMW,IAAI,CAACF;YACpD;QACF;QACAhB,MAAM;IACR;AACF"}
@@ -5,20 +5,16 @@ import { spinner } from '@sanity/cli-core/ux';
5
5
  import { c as createTar } from 'tar';
6
6
  import { deriveInterfaces } from '../../deriveInterfaces.js';
7
7
  import { createApplication, createDeployment, deleteApplication, updateApplication } from '../../services/applications.js';
8
- function toBrettInterface(iface, version) {
8
+ function toBrettInterface(iface) {
9
9
  const { id: _id, src: _src, ...declaration } = iface;
10
- if ('type' in declaration) return {
11
- ...declaration,
12
- version
13
- };
10
+ if ('type' in declaration) return declaration;
14
11
  switch(declaration.surface){
15
12
  case 'asset_source':
16
13
  {
17
14
  const { surface, ...view } = declaration;
18
15
  return {
19
16
  ...view,
20
- type: surface,
21
- version
17
+ type: surface
22
18
  };
23
19
  }
24
20
  case 'panel':
@@ -26,8 +22,7 @@ function toBrettInterface(iface, version) {
26
22
  const { surface, ...view } = declaration;
27
23
  return {
28
24
  ...view,
29
- type: surface,
30
- version
25
+ type: surface
31
26
  };
32
27
  }
33
28
  case 'tile':
@@ -35,8 +30,7 @@ function toBrettInterface(iface, version) {
35
30
  const { surface, ...view } = declaration;
36
31
  return {
37
32
  ...view,
38
- type: surface,
39
- version
33
+ type: surface
40
34
  };
41
35
  }
42
36
  case 'window':
@@ -44,8 +38,7 @@ function toBrettInterface(iface, version) {
44
38
  const { surface, ...view } = declaration;
45
39
  return {
46
40
  ...view,
47
- type: 'app',
48
- version
41
+ type: 'app'
49
42
  };
50
43
  }
51
44
  }
@@ -120,7 +113,7 @@ function toBrettInterface(iface, version) {
120
113
  interfaces: deriveInterfaces(app, {
121
114
  appTitle: title,
122
115
  isApp
123
- }).map((iface)=>toBrettInterface(iface, version)),
116
+ }).map((iface)=>toBrettInterface(iface)),
124
117
  isAutoUpdating,
125
118
  mfManifest,
126
119
  tarball,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/actions/deploy/deployWorkbenchApp.ts"],"sourcesContent":["import {basename, dirname} from 'node:path'\nimport {createGzip} from 'node:zlib'\n\nimport {type AppVisibility, type CliConfig} from '@sanity/cli-core'\nimport {getErrorMessage} from '@sanity/cli-core/errors'\nimport {spinner} from '@sanity/cli-core/ux'\nimport {c as createTar} from 'tar'\n\nimport {type DerivedInterface, deriveInterfaces} from '../../deriveInterfaces.js'\nimport {\n type Application,\n type BrettAccess,\n type BrettInterface,\n type BrettWorkspace,\n createApplication,\n createDeployment,\n deleteApplication,\n updateApplication,\n} from '../../services/applications.js'\n\n/**\n * `rollback` undoes the creation, so a later failure leaves no record stranded at the slug.\n * @internal\n */\nexport interface CreatedApplication {\n application: Application\n rollback: () => Promise<void>\n}\n\nfunction toBrettInterface(iface: DerivedInterface, version: string): BrettInterface {\n const {id: _id, src: _src, ...declaration} = iface\n if ('type' in declaration) return {...declaration, version}\n\n switch (declaration.surface) {\n case 'asset_source': {\n const {surface, ...view} = declaration\n return {...view, type: surface, version}\n }\n case 'panel': {\n const {surface, ...view} = declaration\n return {...view, type: surface, version}\n }\n case 'tile': {\n const {surface, ...view} = declaration\n return {...view, type: surface, version}\n }\n case 'window': {\n const {surface, ...view} = declaration\n return {...view, type: 'app', version}\n }\n }\n}\n\n/**\n * Create a coreApp record (no deployment), so the CLI can build with its id\n * before shipping the first deployment. First deploy only.\n * @internal\n */\nexport async function createCoreApp(options: {\n isSingleton?: boolean\n name?: string\n organizationId: string\n slug: string\n title: string\n visibility?: AppVisibility\n}): Promise<CreatedApplication> {\n const spin = spinner('Creating application...').start()\n try {\n const application = await createApplication({...options, type: 'coreApp'})\n spin.succeed()\n return {application, rollback: () => deleteApplication(application.id)}\n } catch (error) {\n spin.fail()\n throw error\n }\n}\n\n/**\n * Create a studio record (no deployment).\n * @internal\n */\nexport async function createStudio(options: {\n externalUrl?: string\n name?: string\n organizationId: string\n projectId: string | undefined\n slug: string\n title: string\n visibility?: AppVisibility\n}): Promise<CreatedApplication> {\n const spin = spinner('Creating studio...').start()\n try {\n const application = await createApplication({...options, type: 'studio'})\n spin.succeed()\n return {application, rollback: () => deleteApplication(application.id)}\n } catch (error) {\n spin.fail()\n throw error\n }\n}\n\n/**\n * Ship a deployment to an already-created (or `deployment.appId`) application,\n * then sync its mutable metadata (`title`, and `icon`/`slug`/`visibility` when\n * set) from config. The deploy endpoint ignores these, so a redeploy patches\n * them here alongside the new deployment.\n *\n * `onDeployed` fires the instant the deployment is live, before the metadata\n * sync — so a caller can disarm a create-time rollback that must not delete an\n * application once it has an active deployment.\n *\n * `isExternal` skips the tarball: the customer serves the build from the\n * application's registered origin.\n * @internal\n */\nexport async function deployWorkbenchApp(options: {\n access?: readonly BrettAccess[]\n app: CliConfig['app']\n applicationId: string\n icon?: string\n isApp: boolean\n isAutoUpdating: boolean\n isExternal?: boolean\n label?: string\n mfManifest: Record<string, unknown>\n onDeployed?: () => void\n /**\n * The address from config. Only `createApplication` used to send it, so an\n * app with a `deployment.appId` kept whatever slug it was created at.\n */\n slug?: string\n sourceDir: string\n title: string\n version: string\n visibility?: AppVisibility\n workspaces?: readonly BrettWorkspace[]\n}): Promise<void> {\n const {\n access,\n app,\n applicationId,\n icon,\n isApp,\n isAutoUpdating,\n isExternal = false,\n label = 'Deploying...',\n mfManifest,\n onDeployed,\n slug,\n sourceDir,\n title,\n version,\n visibility,\n workspaces,\n } = options\n const tarball = isExternal\n ? undefined\n : createTar({cwd: dirname(sourceDir)}, [basename(sourceDir)]).pipe(createGzip())\n\n const spin = spinner(label).start()\n try {\n await createDeployment({\n access,\n applicationId,\n // Brett assigns the id and resolves modules by `moduleId`, so neither travels.\n interfaces: deriveInterfaces(app, {appTitle: title, isApp}).map((iface) =>\n toBrettInterface(iface, version),\n ),\n isAutoUpdating,\n mfManifest,\n tarball,\n version,\n workspaces,\n })\n onDeployed?.()\n try {\n await updateApplication(applicationId, {\n title,\n ...(icon ? {icon} : {}),\n ...(slug ? {slug} : {}),\n ...(visibility ? {visibility} : {}),\n })\n } catch (error) {\n throw toSlugRejection(error, slug)\n }\n spin.succeed()\n } catch (error) {\n spin.clear()\n throw error\n }\n}\n\n/**\n * The slug is the one synced field the server validates — it must be free\n * within the organization, and a singleton app only accepts its reserved\n * identifiers — so a 4xx on the metadata patch is a rejected rename. Name the\n * slug and the server's reason; anything else propagates untouched.\n */\nfunction toSlugRejection(error: unknown, slug: string | undefined): unknown {\n const statusCode = (error as {statusCode?: number})?.statusCode\n if (!slug || statusCode === undefined || statusCode < 400 || statusCode >= 500) return error\n return new Error(\n `Slug \"${slug}\" was rejected: ${getErrorMessage(error)}. The deployment is live at the application's previous slug — change \\`app.slug\\` in sanity.cli.ts and deploy again.`,\n {cause: error},\n )\n}\n"],"names":["basename","dirname","createGzip","getErrorMessage","spinner","c","createTar","deriveInterfaces","createApplication","createDeployment","deleteApplication","updateApplication","toBrettInterface","iface","version","id","_id","src","_src","declaration","surface","view","type","createCoreApp","options","spin","start","application","succeed","rollback","error","fail","createStudio","deployWorkbenchApp","access","app","applicationId","icon","isApp","isAutoUpdating","isExternal","label","mfManifest","onDeployed","slug","sourceDir","title","visibility","workspaces","tarball","undefined","cwd","pipe","interfaces","appTitle","map","toSlugRejection","clear","statusCode","Error","cause"],"mappings":"AAAA,SAAQA,QAAQ,EAAEC,OAAO,QAAO,YAAW;AAC3C,SAAQC,UAAU,QAAO,YAAW;AAGpC,SAAQC,eAAe,QAAO,0BAAyB;AACvD,SAAQC,OAAO,QAAO,sBAAqB;AAC3C,SAAQC,KAAKC,SAAS,QAAO,MAAK;AAElC,SAA+BC,gBAAgB,QAAO,4BAA2B;AACjF,SAKEC,iBAAiB,EACjBC,gBAAgB,EAChBC,iBAAiB,EACjBC,iBAAiB,QACZ,iCAAgC;AAWvC,SAASC,iBAAiBC,KAAuB,EAAEC,OAAe;IAChE,MAAM,EAACC,IAAIC,GAAG,EAAEC,KAAKC,IAAI,EAAE,GAAGC,aAAY,GAAGN;IAC7C,IAAI,UAAUM,aAAa,OAAO;QAAC,GAAGA,WAAW;QAAEL;IAAO;IAE1D,OAAQK,YAAYC,OAAO;QACzB,KAAK;YAAgB;gBACnB,MAAM,EAACA,OAAO,EAAE,GAAGC,MAAK,GAAGF;gBAC3B,OAAO;oBAAC,GAAGE,IAAI;oBAAEC,MAAMF;oBAASN;gBAAO;YACzC;QACA,KAAK;YAAS;gBACZ,MAAM,EAACM,OAAO,EAAE,GAAGC,MAAK,GAAGF;gBAC3B,OAAO;oBAAC,GAAGE,IAAI;oBAAEC,MAAMF;oBAASN;gBAAO;YACzC;QACA,KAAK;YAAQ;gBACX,MAAM,EAACM,OAAO,EAAE,GAAGC,MAAK,GAAGF;gBAC3B,OAAO;oBAAC,GAAGE,IAAI;oBAAEC,MAAMF;oBAASN;gBAAO;YACzC;QACA,KAAK;YAAU;gBACb,MAAM,EAACM,OAAO,EAAE,GAAGC,MAAK,GAAGF;gBAC3B,OAAO;oBAAC,GAAGE,IAAI;oBAAEC,MAAM;oBAAOR;gBAAO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,iBAAiB4B,KAAK;gBAACmB,UAAUR;gBAAOR;YAAK,GAAGiB,GAAG,CAAC,CAAC1C,QAC/DD,iBAAiBC,OAAOC;YAE1ByB;YACAG;YACAO;YACAnC;YACAkC;QACF;QACAL;QACA,IAAI;YACF,MAAMhC,kBAAkByB,eAAe;gBACrCU;gBACA,GAAIT,OAAO;oBAACA;gBAAI,IAAI,CAAC,CAAC;gBACtB,GAAIO,OAAO;oBAACA;gBAAI,IAAI,CAAC,CAAC;gBACtB,GAAIG,aAAa;oBAACA;gBAAU,IAAI,CAAC,CAAC;YACpC;QACF,EAAE,OAAOjB,OAAO;YACd,MAAM0B,gBAAgB1B,OAAOc;QAC/B;QACAnB,KAAKG,OAAO;IACd,EAAE,OAAOE,OAAO;QACdL,KAAKgC,KAAK;QACV,MAAM3B;IACR;AACF;AAEA;;;;;CAKC,GACD,SAAS0B,gBAAgB1B,KAAc,EAAEc,IAAwB;IAC/D,MAAMc,aAAc5B,OAAiC4B;IACrD,IAAI,CAACd,QAAQc,eAAeR,aAAaQ,aAAa,OAAOA,cAAc,KAAK,OAAO5B;IACvF,OAAO,IAAI6B,MACT,CAAC,MAAM,EAAEf,KAAK,gBAAgB,EAAEzC,gBAAgB2B,OAAO,oHAAoH,CAAC,EAC5K;QAAC8B,OAAO9B;IAAK;AAEjB"}
1
+ {"version":3,"sources":["../../../src/actions/deploy/deployWorkbenchApp.ts"],"sourcesContent":["import {basename, dirname} from 'node:path'\nimport {createGzip} from 'node:zlib'\n\nimport {type AppVisibility, type CliConfig} from '@sanity/cli-core'\nimport {getErrorMessage} from '@sanity/cli-core/errors'\nimport {spinner} from '@sanity/cli-core/ux'\nimport {c as createTar} from 'tar'\n\nimport {type DerivedInterface, deriveInterfaces} from '../../deriveInterfaces.js'\nimport {\n type Application,\n type BrettAccess,\n type BrettInterface,\n type BrettWorkspace,\n createApplication,\n createDeployment,\n deleteApplication,\n updateApplication,\n} from '../../services/applications.js'\n\n/**\n * `rollback` undoes the creation, so a later failure leaves no record stranded at the slug.\n * @internal\n */\nexport interface CreatedApplication {\n application: Application\n rollback: () => Promise<void>\n}\n\nfunction toBrettInterface(iface: DerivedInterface): BrettInterface {\n const {id: _id, src: _src, ...declaration} = iface\n if ('type' in declaration) return declaration\n\n switch (declaration.surface) {\n case 'asset_source': {\n const {surface, ...view} = declaration\n return {...view, type: surface}\n }\n case 'panel': {\n const {surface, ...view} = declaration\n return {...view, type: surface}\n }\n case 'tile': {\n const {surface, ...view} = declaration\n return {...view, type: surface}\n }\n case 'window': {\n const {surface, ...view} = declaration\n return {...view, type: 'app'}\n }\n }\n}\n\n/**\n * Create a coreApp record (no deployment), so the CLI can build with its id\n * before shipping the first deployment. First deploy only.\n * @internal\n */\nexport async function createCoreApp(options: {\n isSingleton?: boolean\n name?: string\n organizationId: string\n slug: string\n title: string\n visibility?: AppVisibility\n}): Promise<CreatedApplication> {\n const spin = spinner('Creating application...').start()\n try {\n const application = await createApplication({...options, type: 'coreApp'})\n spin.succeed()\n return {application, rollback: () => deleteApplication(application.id)}\n } catch (error) {\n spin.fail()\n throw error\n }\n}\n\n/**\n * Create a studio record (no deployment).\n * @internal\n */\nexport async function createStudio(options: {\n externalUrl?: string\n name?: string\n organizationId: string\n projectId: string | undefined\n slug: string\n title: string\n visibility?: AppVisibility\n}): Promise<CreatedApplication> {\n const spin = spinner('Creating studio...').start()\n try {\n const application = await createApplication({...options, type: 'studio'})\n spin.succeed()\n return {application, rollback: () => deleteApplication(application.id)}\n } catch (error) {\n spin.fail()\n throw error\n }\n}\n\n/**\n * Ship a deployment to an already-created (or `deployment.appId`) application,\n * then sync its mutable metadata (`title`, and `icon`/`slug`/`visibility` when\n * set) from config. The deploy endpoint ignores these, so a redeploy patches\n * them here alongside the new deployment.\n *\n * `onDeployed` fires the instant the deployment is live, before the metadata\n * sync — so a caller can disarm a create-time rollback that must not delete an\n * application once it has an active deployment.\n *\n * `isExternal` skips the tarball: the customer serves the build from the\n * application's registered origin.\n * @internal\n */\nexport async function deployWorkbenchApp(options: {\n access?: readonly BrettAccess[]\n app: CliConfig['app']\n applicationId: string\n icon?: string\n isApp: boolean\n isAutoUpdating: boolean\n isExternal?: boolean\n label?: string\n mfManifest: Record<string, unknown>\n onDeployed?: () => void\n /**\n * The address from config. Only `createApplication` used to send it, so an\n * app with a `deployment.appId` kept whatever slug it was created at.\n */\n slug?: string\n sourceDir: string\n title: string\n version: string\n visibility?: AppVisibility\n workspaces?: readonly BrettWorkspace[]\n}): Promise<void> {\n const {\n access,\n app,\n applicationId,\n icon,\n isApp,\n isAutoUpdating,\n isExternal = false,\n label = 'Deploying...',\n mfManifest,\n onDeployed,\n slug,\n sourceDir,\n title,\n version,\n visibility,\n workspaces,\n } = options\n const tarball = isExternal\n ? undefined\n : createTar({cwd: dirname(sourceDir)}, [basename(sourceDir)]).pipe(createGzip())\n\n const spin = spinner(label).start()\n try {\n await createDeployment({\n access,\n applicationId,\n // Brett assigns the id and resolves modules by `moduleId`, so neither travels.\n interfaces: deriveInterfaces(app, {appTitle: title, isApp}).map((iface) =>\n toBrettInterface(iface),\n ),\n isAutoUpdating,\n mfManifest,\n tarball,\n version,\n workspaces,\n })\n onDeployed?.()\n try {\n await updateApplication(applicationId, {\n title,\n ...(icon ? {icon} : {}),\n ...(slug ? {slug} : {}),\n ...(visibility ? {visibility} : {}),\n })\n } catch (error) {\n throw toSlugRejection(error, slug)\n }\n spin.succeed()\n } catch (error) {\n spin.clear()\n throw error\n }\n}\n\n/**\n * The slug is the one synced field the server validates — it must be free\n * within the organization, and a singleton app only accepts its reserved\n * identifiers — so a 4xx on the metadata patch is a rejected rename. Name the\n * slug and the server's reason; anything else propagates untouched.\n */\nfunction toSlugRejection(error: unknown, slug: string | undefined): unknown {\n const statusCode = (error as {statusCode?: number})?.statusCode\n if (!slug || statusCode === undefined || statusCode < 400 || statusCode >= 500) return error\n return new Error(\n `Slug \"${slug}\" was rejected: ${getErrorMessage(error)}. The deployment is live at the application's previous slug — change \\`app.slug\\` in sanity.cli.ts and deploy again.`,\n {cause: error},\n )\n}\n"],"names":["basename","dirname","createGzip","getErrorMessage","spinner","c","createTar","deriveInterfaces","createApplication","createDeployment","deleteApplication","updateApplication","toBrettInterface","iface","id","_id","src","_src","declaration","surface","view","type","createCoreApp","options","spin","start","application","succeed","rollback","error","fail","createStudio","deployWorkbenchApp","access","app","applicationId","icon","isApp","isAutoUpdating","isExternal","label","mfManifest","onDeployed","slug","sourceDir","title","version","visibility","workspaces","tarball","undefined","cwd","pipe","interfaces","appTitle","map","toSlugRejection","clear","statusCode","Error","cause"],"mappings":"AAAA,SAAQA,QAAQ,EAAEC,OAAO,QAAO,YAAW;AAC3C,SAAQC,UAAU,QAAO,YAAW;AAGpC,SAAQC,eAAe,QAAO,0BAAyB;AACvD,SAAQC,OAAO,QAAO,sBAAqB;AAC3C,SAAQC,KAAKC,SAAS,QAAO,MAAK;AAElC,SAA+BC,gBAAgB,QAAO,4BAA2B;AACjF,SAKEC,iBAAiB,EACjBC,gBAAgB,EAChBC,iBAAiB,EACjBC,iBAAiB,QACZ,iCAAgC;AAWvC,SAASC,iBAAiBC,KAAuB;IAC/C,MAAM,EAACC,IAAIC,GAAG,EAAEC,KAAKC,IAAI,EAAE,GAAGC,aAAY,GAAGL;IAC7C,IAAI,UAAUK,aAAa,OAAOA;IAElC,OAAQA,YAAYC,OAAO;QACzB,KAAK;YAAgB;gBACnB,MAAM,EAACA,OAAO,EAAE,GAAGC,MAAK,GAAGF;gBAC3B,OAAO;oBAAC,GAAGE,IAAI;oBAAEC,MAAMF;gBAAO;YAChC;QACA,KAAK;YAAS;gBACZ,MAAM,EAACA,OAAO,EAAE,GAAGC,MAAK,GAAGF;gBAC3B,OAAO;oBAAC,GAAGE,IAAI;oBAAEC,MAAMF;gBAAO;YAChC;QACA,KAAK;YAAQ;gBACX,MAAM,EAACA,OAAO,EAAE,GAAGC,MAAK,GAAGF;gBAC3B,OAAO;oBAAC,GAAGE,IAAI;oBAAEC,MAAMF;gBAAO;YACh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;IAErE,MAAMsB,OAAOpB,QAAQoC,OAAOf,KAAK;IACjC,IAAI;QACF,MAAMhB,iBAAiB;YACrBwB;YACAE;YACA,+EAA+E;YAC/EkB,YAAY9C,iBAAiB2B,KAAK;gBAACoB,UAAUT;gBAAOR;YAAK,GAAGkB,GAAG,CAAC,CAAC1C,QAC/DD,iBAAiBC;YAEnByB;YACAG;YACAQ;YACAH;YACAE;QACF;QACAN;QACA,IAAI;YACF,MAAM/B,kBAAkBwB,eAAe;gBACrCU;gBACA,GAAIT,OAAO;oBAACA;gBAAI,IAAI,CAAC,CAAC;gBACtB,GAAIO,OAAO;oBAACA;gBAAI,IAAI,CAAC,CAAC;gBACtB,GAAII,aAAa;oBAACA;gBAAU,IAAI,CAAC,CAAC;YACpC;QACF,EAAE,OAAOlB,OAAO;YACd,MAAM2B,gBAAgB3B,OAAOc;QAC/B;QACAnB,KAAKG,OAAO;IACd,EAAE,OAAOE,OAAO;QACdL,KAAKiC,KAAK;QACV,MAAM5B;IACR;AACF;AAEA;;;;;CAKC,GACD,SAAS2B,gBAAgB3B,KAAc,EAAEc,IAAwB;IAC/D,MAAMe,aAAc7B,OAAiC6B;IACrD,IAAI,CAACf,QAAQe,eAAeR,aAAaQ,aAAa,OAAOA,cAAc,KAAK,OAAO7B;IACvF,OAAO,IAAI8B,MACT,CAAC,MAAM,EAAEhB,KAAK,gBAAgB,EAAExC,gBAAgB0B,OAAO,oHAAoH,CAAC,EAC5K;QAAC+B,OAAO/B;IAAK;AAEjB"}
@@ -102,6 +102,7 @@ export const devServerManifestSchema = z.object({
102
102
  version: z.string()
103
103
  }))),
104
104
  host: z.string(),
105
+ https: z.optional(z.boolean()),
105
106
  /**
106
107
  * The id the app runs under on the bus. It stays apart from `applicationId`,
107
108
  * because Dashboards that predate `applicationId` key local apps on it.
@@ -226,6 +227,7 @@ function runExitCleanups() {
226
227
  */ export function registerDevServer(manifest) {
227
228
  const registryDir = getRegistryDir();
228
229
  mkdirSync(registryDir, {
230
+ mode: 0o700,
229
231
  recursive: true
230
232
  });
231
233
  let current = {
@@ -235,7 +237,9 @@ function runExitCleanups() {
235
237
  version: REGISTRY_VERSION
236
238
  };
237
239
  const filePath = join(registryDir, `${process.pid}.json`);
238
- writeFileSync(filePath, JSON.stringify(current, null, 2));
240
+ writeFileSync(filePath, JSON.stringify(current, null, 2), {
241
+ mode: 0o600
242
+ });
239
243
  // Guard against late updates from background tasks (e.g. the initial
240
244
  // manifest extraction) landing after `release()` has deleted the file —
241
245
  // without this, the update would re-create the registry entry and leak.
@@ -258,7 +262,9 @@ function runExitCleanups() {
258
262
  ...current,
259
263
  ...patch
260
264
  };
261
- writeFileSync(filePath, JSON.stringify(current, null, 2));
265
+ writeFileSync(filePath, JSON.stringify(current, null, 2), {
266
+ mode: 0o600
267
+ });
262
268
  }
263
269
  };
264
270
  }
@@ -303,6 +309,7 @@ function runExitCleanups() {
303
309
  */ export function watchRegistry(callback) {
304
310
  const registryDir = getRegistryDir();
305
311
  mkdirSync(registryDir, {
312
+ mode: 0o700,
306
313
  recursive: true
307
314
  });
308
315
  // Canonicalize to the real long path so `fs.watch` doesn't abort on Windows
@@ -422,6 +429,7 @@ function pruneWorkbenchLock(lockPath) {
422
429
  */ export function acquireWorkbenchLock(info, retries = 1) {
423
430
  const registryDir = getRegistryDir();
424
431
  mkdirSync(registryDir, {
432
+ mode: 0o700,
425
433
  recursive: true
426
434
  });
427
435
  const lockPath = getLockPath(info.organizationId);
@@ -437,7 +445,8 @@ function pruneWorkbenchLock(lockPath) {
437
445
  devDebug('Acquiring workbench lock at %s', lockPath);
438
446
  try {
439
447
  writeFileSync(lockPath, JSON.stringify(lockData), {
440
- flag: 'wx'
448
+ flag: 'wx',
449
+ mode: 0o600
441
450
  });
442
451
  devDebug('Workbench lock acquired');
443
452
  let released = false;
@@ -463,7 +472,9 @@ function pruneWorkbenchLock(lockPath) {
463
472
  ...lockData,
464
473
  port,
465
474
  ready: true
466
- }));
475
+ }), {
476
+ mode: 0o600
477
+ });
467
478
  }
468
479
  };
469
480
  } catch (err) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/actions/dev/registry.ts"],"sourcesContent":["import {\n existsSync,\n mkdirSync,\n readdirSync,\n readFileSync,\n unlinkSync,\n watch,\n writeFileSync,\n} from 'node:fs'\nimport {join} from 'node:path'\n\nimport {\n coreAppManifestSchema,\n getSanityDataDir,\n studioManifestSchema,\n subdebug,\n} from '@sanity/cli-core'\nimport {z} from 'zod/mini'\n\nimport {applicationReference} from '../../applicationReference.js'\nimport {TileInterfaceMetadataSchema, ViewPlacementMetadataSchema} from '../../contract.js'\nimport {type WorkbenchApp} from '../../defineApp.js'\nimport {canonicalizeWatchDir} from './canonicalizeWatchDir.js'\nimport {getProcessStartTime, isOurProcess} from './processLiveness.js'\n\n/**\n * The dev-server registry: how a running `sanity dev` / `sanity start` process\n * advertises itself so the workbench on this machine can find and load it.\n *\n * Two kinds of file under `~/.sanity/dev-servers/` do the coordinating:\n *\n * - `<pid>.json` — one per running app/studio server, holding where it's served\n * plus its inlined manifest and interfaces. The workbench reads these to\n * discover and render local apps. Written by `registerDevServer`, watched by\n * `watchRegistry`.\n * - `workbench-<organizationId>.lock` — one lock per organization, so only one\n * workbench shell per org runs at a time and later `dev`s register into it\n * instead of starting their own. Managed by `acquireWorkbenchLock` / `readWorkbenchLock`.\n *\n * Both files belong to the process that created them and must not outlive it.\n * Three things keep that true: an explicit `release()` on clean shutdown, an\n * `exit` backstop for abrupt exits (`unlinkOnProcessExit`), and a dead-pid prune\n * on read (`isOurProcess`) that clears whatever a crashed process left behind.\n */\n\nconst devDebug = subdebug('dev')\n\n/** Bump when the manifest/lock shape changes in a breaking way. */\nconst REGISTRY_VERSION = 2\n\n/**\n * The current process's start time as reported by the OS, for the `startedAt`\n * that `isOurProcess` checks on re-read. Falls back to now when the OS time is\n * unavailable — `new Date()` alone records the write time, which drifts from\n * process start by enough to look stale and get pruned right after writing.\n */\nfunction ownStartedAt(): string {\n return (getProcessStartTime(process.pid) ?? new Date()).toISOString()\n}\n\nconst interfaceBaseFields = {\n /** CLI-minted for a local interface; a deployed one gets its id from Brett. */\n id: z.string(),\n moduleId: z.string(),\n name: z.string(),\n /** Raw source vite serves; a deployed interface carries only the `moduleId`. */\n src: z.string(),\n title: z.string(),\n version: z.optional(z.string()),\n}\n\n/**\n * A forwarded interface. Kept outside the manifest so\n * the workbench renders local panels and runs workers without a deploy.\n */\nconst devServerInterfaceSchema = z.union([\n z.discriminatedUnion('surface', [\n z.object({\n ...interfaceBaseFields,\n metadata: z.nullable(ViewPlacementMetadataSchema),\n surface: z.literal('window'),\n }),\n z.object({\n ...interfaceBaseFields,\n metadata: z.nullable(ViewPlacementMetadataSchema),\n surface: z.literal('panel'),\n }),\n z.object({...interfaceBaseFields, metadata: z.null(), surface: z.literal('asset_source')}),\n z.object({\n ...interfaceBaseFields,\n metadata: TileInterfaceMetadataSchema,\n surface: z.literal('tile'),\n }),\n ]),\n z.object({...interfaceBaseFields, metadata: z.null(), type: z.literal('worker')}),\n])\n\n// Exported so test fixtures can validate against the same schema the registry\n// parses with — see `aDevServerManifest`. Used internally by `getRegisteredServers`.\nexport const devServerManifestSchema = z.object({\n applicationId: z.optional(z.string()),\n /**\n * Field schema *values* load from the federation module; each field's `src`\n * rides along so a repoint bumps the exposes-set id and forces a rebuild.\n * Lenient — the workbench is the authority.\n */\n configs: z.optional(\n z.array(\n z.object({\n // Identifies the owning app when it has no app id (singletons).\n appType: z.optional(z.string()),\n fields: z.array(\n z.object({\n name: z.string(),\n public: z.optional(z.boolean()),\n src: z.string(),\n title: z.string(),\n }),\n ),\n // Content hash of the config — the workbench's change-detection key\n // (see deriveConfigs).\n id: z.string(),\n // The app's `defineApplication` slug — the module-federation alias the\n // workbench loads this config's live values from.\n moduleName: z.optional(z.string()),\n // The version the workbench federates this config's module under —\n // a string, like the one Brett returns on a deployed `activeConfig`.\n version: z.string(),\n }),\n ),\n ),\n host: z.string(),\n /**\n * The id the app runs under on the bus. It stays apart from `applicationId`,\n * because Dashboards that predate `applicationId` key local apps on it.\n */\n id: z.optional(z.string()),\n interfaces: z.optional(z.array(devServerInterfaceSchema)),\n /**\n * Inlined manifest — either a {@link StudioManifest} or {@link CoreAppManifest},\n * validated against the shared cli-core schemas. The registry stores and\n * rebroadcasts it; the CLI is what extracts and writes it.\n */\n manifest: z.optional(z.union([studioManifestSchema, coreAppManifestSchema])),\n /**\n * ISO timestamp of the most recent successful manifest extraction. Bumped\n * on every regeneration so re-writing this registry entry triggers the\n * workbench `watchRegistry` watcher and forces a rebroadcast to clients.\n */\n manifestUpdatedAt: z.optional(z.string()),\n // Stable identity + qualified reference, composed by the CLI (the authority for\n // local apps, which never reach brett) and read straight by the workbench.\n name: z.optional(z.string()),\n organizationId: z.optional(z.string()),\n pid: z.number(),\n port: z.number(),\n projectId: z.optional(z.string()),\n reference: z.optional(z.string()),\n slug: z.optional(z.string()),\n startedAt: z.string(),\n type: z.enum(['coreApp', 'studio']),\n version: z.literal(REGISTRY_VERSION),\n visibility: z.optional(z.enum(['default', 'unlisted', 'disabled'])),\n workDir: z.string(),\n})\n/**\n * A manifest describing a running dev server process (studio or app).\n * Stored as `~/.sanity/dev-servers/<pid>.json`.\n *\n * The workbench singleton is tracked separately via the lock file — see\n * `acquireWorkbenchLock` and `readWorkbenchLock` below.\n */\nexport type DevServerManifest = z.infer<typeof devServerManifestSchema>\n\n/**\n * A config-only server carries configs but no interfaces — e.g. a\n * media-library config app under development. The workbench never routes it\n * as an app; only its configs are published. It therefore plays a different\n * role than an app server, and the two may share a slug (a config app\n * developed alongside the locally served singleton it configures).\n */\nexport function isConfigOnlyServer(\n server: Pick<DevServerManifest, 'configs' | 'interfaces'>,\n): boolean {\n return Boolean(server.configs?.length) && !server.interfaces?.length\n}\n\nexport function localAppIdentity(\n app: Pick<WorkbenchApp, 'isSingleton' | 'name' | 'organizationId' | 'slug' | 'visibility'>,\n): Pick<DevServerManifest, 'name' | 'organizationId' | 'reference' | 'slug' | 'visibility'> {\n const name = app.name ?? app.slug\n\n return {\n name,\n organizationId: app.organizationId,\n reference: applicationReference({\n isSingleton: app.isSingleton ?? false,\n name,\n organizationId: app.organizationId,\n }),\n slug: app.slug,\n visibility: app.visibility ?? 'default',\n }\n}\n\n/**\n * Where the Dashboard shell opens a registered server, matching the Workbench's\n * `StudioApplication.href` and `CoreApplication.href`. Only servers with a\n * `surface: 'window'` interface get one (see toWireInterface): studios always do,\n * configs and panel-only apps don't, so they'd 404.\n */\nexport function dashboardPath(\n server: Pick<DevServerManifest, 'id' | 'interfaces' | 'slug' | 'type'>,\n): string | undefined {\n const hasAppView = (server.interfaces ?? []).some(\n (iface) => 'surface' in iface && iface.surface === 'window',\n )\n\n const segment = server.slug ?? server.id\n\n if (!segment || !hasAppView) {\n return undefined\n }\n\n const root = server.type === 'studio' ? 'studios' : 'applications'\n\n return `/${root}/${encodeURIComponent(segment)}`\n}\n\n/**\n * Path to the dev server registry directory. Lives under the shared Sanity\n * config directory to stay consistent with other CLI paths.\n */\nfunction getRegistryDir(): string {\n return join(getSanityDataDir(), 'dev-servers')\n}\n\n// One shared `exit` listener drives every registered cleanup, so N locks/entries\n// don't each add a listener and trip Node's MaxListeners warning.\nconst exitCleanups = new Set<() => void>()\nlet exitListenerInstalled = false\n\nfunction runExitCleanups(): void {\n for (const cleanup of exitCleanups) cleanup()\n}\n\n/** Exercise the exit backstop in tests without terminating the process; not part\n * of the package's public surface. */\nexport const runRegistryExitCleanupForTesting = runExitCleanups\n\n/**\n * Delete a registry file synchronously on process exit, as a backstop for abrupt\n * termination. Vite installs its own SIGTERM handler that calls `process.exit()`,\n * which can outrun the async server teardown and leave the lock or registry entry\n * behind — a stray dev-server that lingers until the dead-pid prune clears it. The\n * `exit` event only runs synchronous work, hence `unlinkSync`. `ownedByUs` guards\n * the shared lock so a successor that reacquired it isn't wiped. Returns a\n * detacher to call after a clean release.\n */\nfunction unlinkOnProcessExit(filePath: string, ownedByUs: () => boolean): () => void {\n const cleanup = () => {\n if (!ownedByUs()) return\n try {\n unlinkSync(filePath)\n } catch {\n // The file may already have been removed during shutdown.\n }\n }\n exitCleanups.add(cleanup)\n\n if (!exitListenerInstalled) {\n exitListenerInstalled = true\n process.once('exit', runExitCleanups)\n }\n\n return () => exitCleanups.delete(cleanup)\n}\n\ninterface DevServerRegistration {\n /** Remove the registry entry. */\n release: () => void\n /**\n * Rewrite the registry entry with partial updates merged in. Also bumps the\n * file's mtime, which fires `watchRegistry` in any workbench process and\n * triggers a rebroadcast to connected clients.\n */\n update: (patch: Partial<Omit<DevServerManifest, 'pid' | 'startedAt' | 'version'>>) => void\n}\n\n/**\n * Write a manifest file for the current process and return a handle with a\n * `release` function that removes it plus an `update` function for patching\n * fields post-registration. Uses synchronous I/O so the file exists before\n * any signal handler could fire.\n */\nexport function registerDevServer(\n manifest: Omit<DevServerManifest, 'pid' | 'startedAt' | 'version'>,\n): DevServerRegistration {\n const registryDir = getRegistryDir()\n mkdirSync(registryDir, {recursive: true})\n\n let current: DevServerManifest = {\n ...manifest,\n pid: process.pid,\n startedAt: ownStartedAt(),\n version: REGISTRY_VERSION,\n }\n\n const filePath = join(registryDir, `${process.pid}.json`)\n writeFileSync(filePath, JSON.stringify(current, null, 2))\n\n // Guard against late updates from background tasks (e.g. the initial\n // manifest extraction) landing after `release()` has deleted the file —\n // without this, the update would re-create the registry entry and leak.\n let released = false\n\n // The file is pid-named, so it's always ours to remove on exit.\n const detachExitCleanup = unlinkOnProcessExit(filePath, () => !released)\n\n return {\n release() {\n released = true\n detachExitCleanup()\n try {\n unlinkSync(filePath)\n } catch {\n // ENOENT is fine — already cleaned up\n }\n },\n update(patch) {\n if (released) return\n current = {...current, ...patch}\n writeFileSync(filePath, JSON.stringify(current, null, 2))\n },\n }\n}\n\n/**\n * Read all manifest files from the registry, prune stale entries (dead PIDs),\n * and return the live ones.\n */\nexport function getRegisteredServers(): DevServerManifest[] {\n const registryDir = getRegistryDir()\n\n if (!existsSync(registryDir)) {\n return []\n }\n\n const files = readdirSync(registryDir).filter((f) => f.endsWith('.json'))\n const servers: DevServerManifest[] = []\n\n for (const file of files) {\n const filePath = join(registryDir, file)\n let raw: unknown\n try {\n raw = JSON.parse(readFileSync(filePath, 'utf8'))\n } catch {\n continue\n }\n\n const {data, success} = devServerManifestSchema.safeParse(raw)\n if (!success) continue\n\n if (isOurProcess(data.pid, data.startedAt)) {\n servers.push(data)\n } else {\n try {\n unlinkSync(filePath)\n } catch {\n // Ignore — another process may have already cleaned it up\n }\n }\n }\n\n return servers\n}\n\ninterface RegistryWatcher {\n close(): void\n}\n\n/**\n * Watch the registry directory for changes and invoke the callback with the\n * current list of live servers whenever a change is detected.\n *\n * Uses `fs.watch` with a debounce to coalesce rapid file changes (e.g. a\n * server starting and writing its manifest triggers multiple FS events).\n */\nexport function watchRegistry(callback: (servers: DevServerManifest[]) => void): RegistryWatcher {\n const registryDir = getRegistryDir()\n mkdirSync(registryDir, {recursive: true})\n\n // Canonicalize to the real long path so `fs.watch` doesn't abort on Windows\n // short-path dirs. See `canonicalizeWatchDir`.\n const watchDir = canonicalizeWatchDir(registryDir)\n\n let debounceTimer: ReturnType<typeof setTimeout> | undefined\n\n const notify = () => {\n clearTimeout(debounceTimer)\n debounceTimer = setTimeout(() => {\n callback(getRegisteredServers())\n }, 50)\n }\n\n const watcher = watch(watchDir, notify)\n\n return {\n close() {\n clearTimeout(debounceTimer)\n watcher.close()\n },\n }\n}\n\n// The workbench singleton lock — \"one workbench per organization\". Lives in the same\n// registry dir and shares the liveness/prune model: a stale lock left by a\n// crashed process is pruned on read so the next acquire isn't blocked forever.\n\nconst workbenchLockSchema = z.object({\n host: z.string(),\n pid: z.number(),\n port: z.number(),\n ready: z.optional(z.boolean()),\n startedAt: z.string(),\n version: z.literal(REGISTRY_VERSION),\n})\n\n/**\n * Read the workbench lock file and return its contents if the holding\n * process is still alive. Prunes stale locks from crashed processes.\n */\nexport function readWorkbenchLock(\n organizationId: string,\n): z.infer<typeof workbenchLockSchema> | undefined {\n const file = readLockFile(organizationId)\n // File doesn't exist — nothing to prune, nothing to return\n if (!file) return undefined\n\n // Past this point the file exists. Anything that isn't a live, valid lock\n // (unparsable JSON, schema mismatch, dead/reused PID) is stale and must be\n // pruned — otherwise the next `acquireWorkbenchLock` call is blocked by\n // EEXIST forever and `sanity dev` silently no-ops the workbench server.\n const {data} = file\n devDebug('Read workbench lock: %o', data)\n if (data && isOurProcess(data.pid, data.startedAt)) {\n devDebug('Workbench process is alive at pid %d on port %d', data.pid, data.port)\n return data\n }\n\n pruneWorkbenchLock(getLockPath(organizationId))\n return undefined\n}\n\nconst LOCK_READY_TIMEOUT_MS = 10_000\nconst LOCK_READY_POLL_MS = 50\n\n/**\n * Read the workbench lock once its holder's shell is listening, so the port is\n * the bound one. Returns the lock as-is after {@link LOCK_READY_TIMEOUT_MS}.\n */\nexport async function waitForWorkbenchLock(\n organizationId: string,\n): Promise<z.infer<typeof workbenchLockSchema> | undefined> {\n const deadline = Date.now() + LOCK_READY_TIMEOUT_MS\n let lock = readWorkbenchLock(organizationId)\n // Read the raw file here: `readWorkbenchLock` spawns `ps`/PowerShell per call\n // and deletes a lock it catches half-written by `updatePort`.\n while (lock?.ready === false && Date.now() < deadline) {\n await new Promise((resolve) => setTimeout(resolve, LOCK_READY_POLL_MS))\n const file = readLockFile(organizationId)\n if (!file) break\n lock = file.data ?? lock\n }\n if (lock?.ready === false && Date.now() >= deadline) {\n devDebug(\n 'Workbench lock not ready after %d ms, using port %d',\n LOCK_READY_TIMEOUT_MS,\n lock.port,\n )\n }\n return readWorkbenchLock(organizationId)\n}\n\nconst getLockPath = (organizationId: string) =>\n join(getRegistryDir(), `workbench-${organizationId}.lock`)\n\n/**\n * Read the lock file with no liveness check and no pruning. `undefined` when\n * there is no file; `data` is `undefined` when its contents don't parse.\n */\nfunction readLockFile(\n organizationId: string,\n): {data: z.infer<typeof workbenchLockSchema> | undefined} | undefined {\n let contents: string\n try {\n contents = readFileSync(getLockPath(organizationId), 'utf8')\n } catch {\n return undefined\n }\n let json: unknown\n try {\n json = JSON.parse(contents)\n } catch {\n return {data: undefined}\n }\n const {data, success} = workbenchLockSchema.safeParse(json)\n return {data: success ? data : undefined}\n}\n\nfunction pruneWorkbenchLock(lockPath: string): void {\n try {\n devDebug('Removing stale workbench lock')\n unlinkSync(lockPath)\n devDebug('Stale workbench lock removed')\n } catch {\n // Another process may have already cleaned it up\n }\n}\n\ninterface WorkbenchLock {\n /** Release the lock file. */\n release: () => void\n /** Update the lock with the actual port after the server starts listening. */\n updatePort: (port: number) => void\n}\n\n/**\n * Attempt to acquire an exclusive lock for the workbench process.\n * Uses `O_EXCL` (the `wx` flag) which is atomic at the OS level — only one\n * process can create the file.\n *\n * The lock stores `{pid, host, port}` so other processes can find the\n * running workbench. Call `updatePort` after the Vite server starts to\n * write the actual port (Vite may pick a different one).\n *\n * @returns A {@link WorkbenchLock} if acquired, or `undefined` if another\n * live process already holds it.\n */\nexport function acquireWorkbenchLock(\n info: {host: string; organizationId: string; port: number},\n retries = 1,\n): WorkbenchLock | undefined {\n const registryDir = getRegistryDir()\n mkdirSync(registryDir, {recursive: true})\n\n const lockPath = getLockPath(info.organizationId)\n const startedAt = ownStartedAt()\n const lockData = {\n host: info.host,\n pid: process.pid,\n port: info.port,\n ready: false,\n startedAt,\n version: REGISTRY_VERSION,\n }\n\n devDebug('Acquiring workbench lock at %s', lockPath)\n\n try {\n writeFileSync(lockPath, JSON.stringify(lockData), {flag: 'wx'})\n devDebug('Workbench lock acquired')\n\n let released = false\n // Only wipe the lock on exit if it's still ours — a successor that reacquired\n // it after our own release must not be clobbered.\n const detachExitCleanup = unlinkOnProcessExit(lockPath, () => {\n if (released) return false\n const disk = readLockFile(info.organizationId)?.data\n return disk?.pid === process.pid && disk.startedAt === startedAt\n })\n\n return {\n release() {\n released = true\n detachExitCleanup()\n try {\n unlinkSync(lockPath)\n } catch {\n // Already cleaned up\n }\n },\n updatePort(port: number) {\n writeFileSync(lockPath, JSON.stringify({...lockData, port, ready: true}))\n },\n }\n } catch (err: unknown) {\n devDebug(\n 'Failed to acquire workbench lock: %s',\n err instanceof Error ? err.message : String(err),\n )\n if (!isNodeError(err) || err.code !== 'EEXIST') return undefined\n\n // Lock exists — check if the holder is still alive\n const existing = readWorkbenchLock(info.organizationId)\n if (existing) return undefined\n\n // Stale lock was pruned by readWorkbenchLock — retry (with guard against infinite recursion)\n if (retries <= 0) return undefined\n return acquireWorkbenchLock(info, retries - 1)\n }\n}\n\nfunction isNodeError(err: unknown): err is NodeJS.ErrnoException {\n return err instanceof Error && 'code' in err\n}\n"],"names":["existsSync","mkdirSync","readdirSync","readFileSync","unlinkSync","watch","writeFileSync","join","coreAppManifestSchema","getSanityDataDir","studioManifestSchema","subdebug","z","applicationReference","TileInterfaceMetadataSchema","ViewPlacementMetadataSchema","canonicalizeWatchDir","getProcessStartTime","isOurProcess","devDebug","REGISTRY_VERSION","ownStartedAt","process","pid","Date","toISOString","interfaceBaseFields","id","string","moduleId","name","src","title","version","optional","devServerInterfaceSchema","union","discriminatedUnion","object","metadata","nullable","surface","literal","null","type","devServerManifestSchema","applicationId","configs","array","appType","fields","public","boolean","moduleName","host","interfaces","manifest","manifestUpdatedAt","organizationId","number","port","projectId","reference","slug","startedAt","enum","visibility","workDir","isConfigOnlyServer","server","Boolean","length","localAppIdentity","app","isSingleton","dashboardPath","hasAppView","some","iface","segment","undefined","root","encodeURIComponent","getRegistryDir","exitCleanups","Set","exitListenerInstalled","runExitCleanups","cleanup","runRegistryExitCleanupForTesting","unlinkOnProcessExit","filePath","ownedByUs","add","once","delete","registerDevServer","registryDir","recursive","current","JSON","stringify","released","detachExitCleanup","release","update","patch","getRegisteredServers","files","filter","f","endsWith","servers","file","raw","parse","data","success","safeParse","push","watchRegistry","callback","watchDir","debounceTimer","notify","clearTimeout","setTimeout","watcher","close","workbenchLockSchema","ready","readWorkbenchLock","readLockFile","pruneWorkbenchLock","getLockPath","LOCK_READY_TIMEOUT_MS","LOCK_READY_POLL_MS","waitForWorkbenchLock","deadline","now","lock","Promise","resolve","contents","json","lockPath","acquireWorkbenchLock","info","retries","lockData","flag","disk","updatePort","err","Error","message","String","isNodeError","code","existing"],"mappings":"AAAA,SACEA,UAAU,EACVC,SAAS,EACTC,WAAW,EACXC,YAAY,EACZC,UAAU,EACVC,KAAK,EACLC,aAAa,QACR,UAAS;AAChB,SAAQC,IAAI,QAAO,YAAW;AAE9B,SACEC,qBAAqB,EACrBC,gBAAgB,EAChBC,oBAAoB,EACpBC,QAAQ,QACH,mBAAkB;AACzB,SAAQC,CAAC,QAAO,WAAU;AAE1B,SAAQC,oBAAoB,QAAO,gCAA+B;AAClE,SAAQC,2BAA2B,EAAEC,2BAA2B,QAAO,oBAAmB;AAE1F,SAAQC,oBAAoB,QAAO,4BAA2B;AAC9D,SAAQC,mBAAmB,EAAEC,YAAY,QAAO,uBAAsB;AAEtE;;;;;;;;;;;;;;;;;;CAkBC,GAED,MAAMC,WAAWR,SAAS;AAE1B,iEAAiE,GACjE,MAAMS,mBAAmB;AAEzB;;;;;CAKC,GACD,SAASC;IACP,OAAO,AAACJ,CAAAA,oBAAoBK,QAAQC,GAAG,KAAK,IAAIC,MAAK,EAAGC,WAAW;AACrE;AAEA,MAAMC,sBAAsB;IAC1B,6EAA6E,GAC7EC,IAAIf,EAAEgB,MAAM;IACZC,UAAUjB,EAAEgB,MAAM;IAClBE,MAAMlB,EAAEgB,MAAM;IACd,8EAA8E,GAC9EG,KAAKnB,EAAEgB,MAAM;IACbI,OAAOpB,EAAEgB,MAAM;IACfK,SAASrB,EAAEsB,QAAQ,CAACtB,EAAEgB,MAAM;AAC9B;AAEA;;;CAGC,GACD,MAAMO,2BAA2BvB,EAAEwB,KAAK,CAAC;IACvCxB,EAAEyB,kBAAkB,CAAC,WAAW;QAC9BzB,EAAE0B,MAAM,CAAC;YACP,GAAGZ,mBAAmB;YACtBa,UAAU3B,EAAE4B,QAAQ,CAACzB;YACrB0B,SAAS7B,EAAE8B,OAAO,CAA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,GAAG,OAAOpE;QACzB,OAAOkE,qBAAqBC,MAAMC,UAAU;IAC9C;AACF;AAEA,SAASS,YAAYJ,GAAY;IAC/B,OAAOA,eAAeC,SAAS,UAAUD;AAC3C"}
1
+ {"version":3,"sources":["../../../src/actions/dev/registry.ts"],"sourcesContent":["import {\n existsSync,\n mkdirSync,\n readdirSync,\n readFileSync,\n unlinkSync,\n watch,\n writeFileSync,\n} from 'node:fs'\nimport {join} from 'node:path'\n\nimport {\n coreAppManifestSchema,\n getSanityDataDir,\n studioManifestSchema,\n subdebug,\n} from '@sanity/cli-core'\nimport {z} from 'zod/mini'\n\nimport {applicationReference} from '../../applicationReference.js'\nimport {TileInterfaceMetadataSchema, ViewPlacementMetadataSchema} from '../../contract.js'\nimport {type WorkbenchApp} from '../../defineApp.js'\nimport {canonicalizeWatchDir} from './canonicalizeWatchDir.js'\nimport {getProcessStartTime, isOurProcess} from './processLiveness.js'\n\n/**\n * The dev-server registry: how a running `sanity dev` / `sanity start` process\n * advertises itself so the workbench on this machine can find and load it.\n *\n * Two kinds of file under `~/.sanity/dev-servers/` do the coordinating:\n *\n * - `<pid>.json` — one per running app/studio server, holding where it's served\n * plus its inlined manifest and interfaces. The workbench reads these to\n * discover and render local apps. Written by `registerDevServer`, watched by\n * `watchRegistry`.\n * - `workbench-<organizationId>.lock` — one lock per organization, so only one\n * workbench shell per org runs at a time and later `dev`s register into it\n * instead of starting their own. Managed by `acquireWorkbenchLock` / `readWorkbenchLock`.\n *\n * Both files belong to the process that created them and must not outlive it.\n * Three things keep that true: an explicit `release()` on clean shutdown, an\n * `exit` backstop for abrupt exits (`unlinkOnProcessExit`), and a dead-pid prune\n * on read (`isOurProcess`) that clears whatever a crashed process left behind.\n */\n\nconst devDebug = subdebug('dev')\n\n/** Bump when the manifest/lock shape changes in a breaking way. */\nconst REGISTRY_VERSION = 2\n\n/**\n * The current process's start time as reported by the OS, for the `startedAt`\n * that `isOurProcess` checks on re-read. Falls back to now when the OS time is\n * unavailable — `new Date()` alone records the write time, which drifts from\n * process start by enough to look stale and get pruned right after writing.\n */\nfunction ownStartedAt(): string {\n return (getProcessStartTime(process.pid) ?? new Date()).toISOString()\n}\n\nconst interfaceBaseFields = {\n /** CLI-minted for a local interface; a deployed one gets its id from Brett. */\n id: z.string(),\n moduleId: z.string(),\n name: z.string(),\n /** Raw source vite serves; a deployed interface carries only the `moduleId`. */\n src: z.string(),\n title: z.string(),\n version: z.optional(z.string()),\n}\n\n/**\n * A forwarded interface. Kept outside the manifest so\n * the workbench renders local panels and runs workers without a deploy.\n */\nconst devServerInterfaceSchema = z.union([\n z.discriminatedUnion('surface', [\n z.object({\n ...interfaceBaseFields,\n metadata: z.nullable(ViewPlacementMetadataSchema),\n surface: z.literal('window'),\n }),\n z.object({\n ...interfaceBaseFields,\n metadata: z.nullable(ViewPlacementMetadataSchema),\n surface: z.literal('panel'),\n }),\n z.object({...interfaceBaseFields, metadata: z.null(), surface: z.literal('asset_source')}),\n z.object({\n ...interfaceBaseFields,\n metadata: TileInterfaceMetadataSchema,\n surface: z.literal('tile'),\n }),\n ]),\n z.object({...interfaceBaseFields, metadata: z.null(), type: z.literal('worker')}),\n])\n\n// Exported so test fixtures can validate against the same schema the registry\n// parses with — see `aDevServerManifest`. Used internally by `getRegisteredServers`.\nexport const devServerManifestSchema = z.object({\n applicationId: z.optional(z.string()),\n /**\n * Field schema *values* load from the federation module; each field's `src`\n * rides along so a repoint bumps the exposes-set id and forces a rebuild.\n * Lenient — the workbench is the authority.\n */\n configs: z.optional(\n z.array(\n z.object({\n // Identifies the owning app when it has no app id (singletons).\n appType: z.optional(z.string()),\n fields: z.array(\n z.object({\n name: z.string(),\n public: z.optional(z.boolean()),\n src: z.string(),\n title: z.string(),\n }),\n ),\n // Content hash of the config — the workbench's change-detection key\n // (see deriveConfigs).\n id: z.string(),\n // The app's `defineApplication` slug — the module-federation alias the\n // workbench loads this config's live values from.\n moduleName: z.optional(z.string()),\n // The version the workbench federates this config's module under —\n // a string, like the one Brett returns on a deployed `activeConfig`.\n version: z.string(),\n }),\n ),\n ),\n host: z.string(),\n https: z.optional(z.boolean()),\n /**\n * The id the app runs under on the bus. It stays apart from `applicationId`,\n * because Dashboards that predate `applicationId` key local apps on it.\n */\n id: z.optional(z.string()),\n interfaces: z.optional(z.array(devServerInterfaceSchema)),\n /**\n * Inlined manifest — either a {@link StudioManifest} or {@link CoreAppManifest},\n * validated against the shared cli-core schemas. The registry stores and\n * rebroadcasts it; the CLI is what extracts and writes it.\n */\n manifest: z.optional(z.union([studioManifestSchema, coreAppManifestSchema])),\n /**\n * ISO timestamp of the most recent successful manifest extraction. Bumped\n * on every regeneration so re-writing this registry entry triggers the\n * workbench `watchRegistry` watcher and forces a rebroadcast to clients.\n */\n manifestUpdatedAt: z.optional(z.string()),\n // Stable identity + qualified reference, composed by the CLI (the authority for\n // local apps, which never reach brett) and read straight by the workbench.\n name: z.optional(z.string()),\n organizationId: z.optional(z.string()),\n pid: z.number(),\n port: z.number(),\n projectId: z.optional(z.string()),\n reference: z.optional(z.string()),\n slug: z.optional(z.string()),\n startedAt: z.string(),\n type: z.enum(['coreApp', 'studio']),\n version: z.literal(REGISTRY_VERSION),\n visibility: z.optional(z.enum(['default', 'unlisted', 'disabled'])),\n workDir: z.string(),\n})\n/**\n * A manifest describing a running dev server process (studio or app).\n * Stored as `~/.sanity/dev-servers/<pid>.json`.\n *\n * The workbench singleton is tracked separately via the lock file — see\n * `acquireWorkbenchLock` and `readWorkbenchLock` below.\n */\nexport type DevServerManifest = z.infer<typeof devServerManifestSchema>\n\n/**\n * A config-only server carries configs but no interfaces — e.g. a\n * media-library config app under development. The workbench never routes it\n * as an app; only its configs are published. It therefore plays a different\n * role than an app server, and the two may share a slug (a config app\n * developed alongside the locally served singleton it configures).\n */\nexport function isConfigOnlyServer(\n server: Pick<DevServerManifest, 'configs' | 'interfaces'>,\n): boolean {\n return Boolean(server.configs?.length) && !server.interfaces?.length\n}\n\nexport function localAppIdentity(\n app: Pick<WorkbenchApp, 'isSingleton' | 'name' | 'organizationId' | 'slug' | 'visibility'>,\n): Pick<DevServerManifest, 'name' | 'organizationId' | 'reference' | 'slug' | 'visibility'> {\n const name = app.name ?? app.slug\n\n return {\n name,\n organizationId: app.organizationId,\n reference: applicationReference({\n isSingleton: app.isSingleton ?? false,\n name,\n organizationId: app.organizationId,\n }),\n slug: app.slug,\n visibility: app.visibility ?? 'default',\n }\n}\n\n/**\n * Where the Dashboard shell opens a registered server, matching the Workbench's\n * `StudioApplication.href` and `CoreApplication.href`. Only servers with a\n * `surface: 'window'` interface get one (see toWireInterface): studios always do,\n * configs and panel-only apps don't, so they'd 404.\n */\nexport function dashboardPath(\n server: Pick<DevServerManifest, 'id' | 'interfaces' | 'slug' | 'type'>,\n): string | undefined {\n const hasAppView = (server.interfaces ?? []).some(\n (iface) => 'surface' in iface && iface.surface === 'window',\n )\n\n const segment = server.slug ?? server.id\n\n if (!segment || !hasAppView) {\n return undefined\n }\n\n const root = server.type === 'studio' ? 'studios' : 'applications'\n\n return `/${root}/${encodeURIComponent(segment)}`\n}\n\n/**\n * Path to the dev server registry directory. Lives under the shared Sanity\n * config directory to stay consistent with other CLI paths.\n */\nfunction getRegistryDir(): string {\n return join(getSanityDataDir(), 'dev-servers')\n}\n\n// One shared `exit` listener drives every registered cleanup, so N locks/entries\n// don't each add a listener and trip Node's MaxListeners warning.\nconst exitCleanups = new Set<() => void>()\nlet exitListenerInstalled = false\n\nfunction runExitCleanups(): void {\n for (const cleanup of exitCleanups) cleanup()\n}\n\n/** Exercise the exit backstop in tests without terminating the process; not part\n * of the package's public surface. */\nexport const runRegistryExitCleanupForTesting = runExitCleanups\n\n/**\n * Delete a registry file synchronously on process exit, as a backstop for abrupt\n * termination. Vite installs its own SIGTERM handler that calls `process.exit()`,\n * which can outrun the async server teardown and leave the lock or registry entry\n * behind — a stray dev-server that lingers until the dead-pid prune clears it. The\n * `exit` event only runs synchronous work, hence `unlinkSync`. `ownedByUs` guards\n * the shared lock so a successor that reacquired it isn't wiped. Returns a\n * detacher to call after a clean release.\n */\nfunction unlinkOnProcessExit(filePath: string, ownedByUs: () => boolean): () => void {\n const cleanup = () => {\n if (!ownedByUs()) return\n try {\n unlinkSync(filePath)\n } catch {\n // The file may already have been removed during shutdown.\n }\n }\n exitCleanups.add(cleanup)\n\n if (!exitListenerInstalled) {\n exitListenerInstalled = true\n process.once('exit', runExitCleanups)\n }\n\n return () => exitCleanups.delete(cleanup)\n}\n\ninterface DevServerRegistration {\n /** Remove the registry entry. */\n release: () => void\n /**\n * Rewrite the registry entry with partial updates merged in. Also bumps the\n * file's mtime, which fires `watchRegistry` in any workbench process and\n * triggers a rebroadcast to connected clients.\n */\n update: (patch: Partial<Omit<DevServerManifest, 'pid' | 'startedAt' | 'version'>>) => void\n}\n\n/**\n * Write a manifest file for the current process and return a handle with a\n * `release` function that removes it plus an `update` function for patching\n * fields post-registration. Uses synchronous I/O so the file exists before\n * any signal handler could fire.\n */\nexport function registerDevServer(\n manifest: Omit<DevServerManifest, 'pid' | 'startedAt' | 'version'>,\n): DevServerRegistration {\n const registryDir = getRegistryDir()\n mkdirSync(registryDir, {mode: 0o700, recursive: true})\n\n let current: DevServerManifest = {\n ...manifest,\n pid: process.pid,\n startedAt: ownStartedAt(),\n version: REGISTRY_VERSION,\n }\n\n const filePath = join(registryDir, `${process.pid}.json`)\n writeFileSync(filePath, JSON.stringify(current, null, 2), {mode: 0o600})\n\n // Guard against late updates from background tasks (e.g. the initial\n // manifest extraction) landing after `release()` has deleted the file —\n // without this, the update would re-create the registry entry and leak.\n let released = false\n\n // The file is pid-named, so it's always ours to remove on exit.\n const detachExitCleanup = unlinkOnProcessExit(filePath, () => !released)\n\n return {\n release() {\n released = true\n detachExitCleanup()\n try {\n unlinkSync(filePath)\n } catch {\n // ENOENT is fine — already cleaned up\n }\n },\n update(patch) {\n if (released) return\n current = {...current, ...patch}\n writeFileSync(filePath, JSON.stringify(current, null, 2), {mode: 0o600})\n },\n }\n}\n\n/**\n * Read all manifest files from the registry, prune stale entries (dead PIDs),\n * and return the live ones.\n */\nexport function getRegisteredServers(): DevServerManifest[] {\n const registryDir = getRegistryDir()\n\n if (!existsSync(registryDir)) {\n return []\n }\n\n const files = readdirSync(registryDir).filter((f) => f.endsWith('.json'))\n const servers: DevServerManifest[] = []\n\n for (const file of files) {\n const filePath = join(registryDir, file)\n let raw: unknown\n try {\n raw = JSON.parse(readFileSync(filePath, 'utf8'))\n } catch {\n continue\n }\n\n const {data, success} = devServerManifestSchema.safeParse(raw)\n if (!success) continue\n\n if (isOurProcess(data.pid, data.startedAt)) {\n servers.push(data)\n } else {\n try {\n unlinkSync(filePath)\n } catch {\n // Ignore — another process may have already cleaned it up\n }\n }\n }\n\n return servers\n}\n\ninterface RegistryWatcher {\n close(): void\n}\n\n/**\n * Watch the registry directory for changes and invoke the callback with the\n * current list of live servers whenever a change is detected.\n *\n * Uses `fs.watch` with a debounce to coalesce rapid file changes (e.g. a\n * server starting and writing its manifest triggers multiple FS events).\n */\nexport function watchRegistry(callback: (servers: DevServerManifest[]) => void): RegistryWatcher {\n const registryDir = getRegistryDir()\n mkdirSync(registryDir, {mode: 0o700, recursive: true})\n\n // Canonicalize to the real long path so `fs.watch` doesn't abort on Windows\n // short-path dirs. See `canonicalizeWatchDir`.\n const watchDir = canonicalizeWatchDir(registryDir)\n\n let debounceTimer: ReturnType<typeof setTimeout> | undefined\n\n const notify = () => {\n clearTimeout(debounceTimer)\n debounceTimer = setTimeout(() => {\n callback(getRegisteredServers())\n }, 50)\n }\n\n const watcher = watch(watchDir, notify)\n\n return {\n close() {\n clearTimeout(debounceTimer)\n watcher.close()\n },\n }\n}\n\n// The workbench singleton lock — \"one workbench per organization\". Lives in the same\n// registry dir and shares the liveness/prune model: a stale lock left by a\n// crashed process is pruned on read so the next acquire isn't blocked forever.\n\nconst workbenchLockSchema = z.object({\n host: z.string(),\n pid: z.number(),\n port: z.number(),\n ready: z.optional(z.boolean()),\n startedAt: z.string(),\n version: z.literal(REGISTRY_VERSION),\n})\n\n/**\n * Read the workbench lock file and return its contents if the holding\n * process is still alive. Prunes stale locks from crashed processes.\n */\nexport function readWorkbenchLock(\n organizationId: string,\n): z.infer<typeof workbenchLockSchema> | undefined {\n const file = readLockFile(organizationId)\n // File doesn't exist — nothing to prune, nothing to return\n if (!file) return undefined\n\n // Past this point the file exists. Anything that isn't a live, valid lock\n // (unparsable JSON, schema mismatch, dead/reused PID) is stale and must be\n // pruned — otherwise the next `acquireWorkbenchLock` call is blocked by\n // EEXIST forever and `sanity dev` silently no-ops the workbench server.\n const {data} = file\n devDebug('Read workbench lock: %o', data)\n if (data && isOurProcess(data.pid, data.startedAt)) {\n devDebug('Workbench process is alive at pid %d on port %d', data.pid, data.port)\n return data\n }\n\n pruneWorkbenchLock(getLockPath(organizationId))\n return undefined\n}\n\nconst LOCK_READY_TIMEOUT_MS = 10_000\nconst LOCK_READY_POLL_MS = 50\n\n/**\n * Read the workbench lock once its holder's shell is listening, so the port is\n * the bound one. Returns the lock as-is after {@link LOCK_READY_TIMEOUT_MS}.\n */\nexport async function waitForWorkbenchLock(\n organizationId: string,\n): Promise<z.infer<typeof workbenchLockSchema> | undefined> {\n const deadline = Date.now() + LOCK_READY_TIMEOUT_MS\n let lock = readWorkbenchLock(organizationId)\n // Read the raw file here: `readWorkbenchLock` spawns `ps`/PowerShell per call\n // and deletes a lock it catches half-written by `updatePort`.\n while (lock?.ready === false && Date.now() < deadline) {\n await new Promise((resolve) => setTimeout(resolve, LOCK_READY_POLL_MS))\n const file = readLockFile(organizationId)\n if (!file) break\n lock = file.data ?? lock\n }\n if (lock?.ready === false && Date.now() >= deadline) {\n devDebug(\n 'Workbench lock not ready after %d ms, using port %d',\n LOCK_READY_TIMEOUT_MS,\n lock.port,\n )\n }\n return readWorkbenchLock(organizationId)\n}\n\nconst getLockPath = (organizationId: string) =>\n join(getRegistryDir(), `workbench-${organizationId}.lock`)\n\n/**\n * Read the lock file with no liveness check and no pruning. `undefined` when\n * there is no file; `data` is `undefined` when its contents don't parse.\n */\nfunction readLockFile(\n organizationId: string,\n): {data: z.infer<typeof workbenchLockSchema> | undefined} | undefined {\n let contents: string\n try {\n contents = readFileSync(getLockPath(organizationId), 'utf8')\n } catch {\n return undefined\n }\n let json: unknown\n try {\n json = JSON.parse(contents)\n } catch {\n return {data: undefined}\n }\n const {data, success} = workbenchLockSchema.safeParse(json)\n return {data: success ? data : undefined}\n}\n\nfunction pruneWorkbenchLock(lockPath: string): void {\n try {\n devDebug('Removing stale workbench lock')\n unlinkSync(lockPath)\n devDebug('Stale workbench lock removed')\n } catch {\n // Another process may have already cleaned it up\n }\n}\n\ninterface WorkbenchLock {\n /** Release the lock file. */\n release: () => void\n /** Update the lock with the actual port after the server starts listening. */\n updatePort: (port: number) => void\n}\n\n/**\n * Attempt to acquire an exclusive lock for the workbench process.\n * Uses `O_EXCL` (the `wx` flag) which is atomic at the OS level — only one\n * process can create the file.\n *\n * The lock stores `{pid, host, port}` so other processes can find the\n * running workbench. Call `updatePort` after the Vite server starts to\n * write the actual port (Vite may pick a different one).\n *\n * @returns A {@link WorkbenchLock} if acquired, or `undefined` if another\n * live process already holds it.\n */\nexport function acquireWorkbenchLock(\n info: {host: string; organizationId: string; port: number},\n retries = 1,\n): WorkbenchLock | undefined {\n const registryDir = getRegistryDir()\n mkdirSync(registryDir, {mode: 0o700, recursive: true})\n\n const lockPath = getLockPath(info.organizationId)\n const startedAt = ownStartedAt()\n const lockData = {\n host: info.host,\n pid: process.pid,\n port: info.port,\n ready: false,\n startedAt,\n version: REGISTRY_VERSION,\n }\n\n devDebug('Acquiring workbench lock at %s', lockPath)\n\n try {\n writeFileSync(lockPath, JSON.stringify(lockData), {flag: 'wx', mode: 0o600})\n devDebug('Workbench lock acquired')\n\n let released = false\n // Only wipe the lock on exit if it's still ours — a successor that reacquired\n // it after our own release must not be clobbered.\n const detachExitCleanup = unlinkOnProcessExit(lockPath, () => {\n if (released) return false\n const disk = readLockFile(info.organizationId)?.data\n return disk?.pid === process.pid && disk.startedAt === startedAt\n })\n\n return {\n release() {\n released = true\n detachExitCleanup()\n try {\n unlinkSync(lockPath)\n } catch {\n // Already cleaned up\n }\n },\n updatePort(port: number) {\n writeFileSync(lockPath, JSON.stringify({...lockData, port, ready: true}), {mode: 0o600})\n },\n }\n } catch (err: unknown) {\n devDebug(\n 'Failed to acquire workbench lock: %s',\n err instanceof Error ? err.message : String(err),\n )\n if (!isNodeError(err) || err.code !== 'EEXIST') return undefined\n\n // Lock exists — check if the holder is still alive\n const existing = readWorkbenchLock(info.organizationId)\n if (existing) return undefined\n\n // Stale lock was pruned by readWorkbenchLock — retry (with guard against infinite recursion)\n if (retries <= 0) return undefined\n return acquireWorkbenchLock(info, retries - 1)\n }\n}\n\nfunction isNodeError(err: unknown): err is NodeJS.ErrnoException {\n return err instanceof Error && 'code' in err\n}\n"],"names":["existsSync","mkdirSync","readdirSync","readFileSync","unlinkSync","watch","writeFileSync","join","coreAppManifestSchema","getSanityDataDir","studioManifestSchema","subdebug","z","applicationReference","TileInterfaceMetadataSchema","ViewPlacementMetadataSchema","canonicalizeWatchDir","getProcessStartTime","isOurProcess","devDebug","REGISTRY_VERSION","ownStartedAt","process","pid","Date","toISOString","interfaceBaseFields","id","string","moduleId","name","src","title","version","optional","devServerInterfaceSchema","union","discriminatedUnion","object","metadata","nullable","surface","literal","null","type","devServerManifestSchema","applicationId","configs","array","appType","fields","public","boolean","moduleName","host","https","interfaces","manifest","manifestUpdatedAt","organizationId","number","port","projectId","reference","slug","startedAt","enum","visibility","workDir","isConfigOnlyServer","server","Boolean","length","localAppIdentity","app","isSingleton","dashboardPath","hasAppView","some","iface","segment","undefined","root","encodeURIComponent","getRegistryDir","exitCleanups","Set","exitListenerInstalled","runExitCleanups","cleanup","runRegistryExitCleanupForTesting","unlinkOnProcessExit","filePath","ownedByUs","add","once","delete","registerDevServer","registryDir","mode","recursive","current","JSON","stringify","released","detachExitCleanup","release","update","patch","getRegisteredServers","files","filter","f","endsWith","servers","file","raw","parse","data","success","safeParse","push","watchRegistry","callback","watchDir","debounceTimer","notify","clearTimeout","setTimeout","watcher","close","workbenchLockSchema","ready","readWorkbenchLock","readLockFile","pruneWorkbenchLock","getLockPath","LOCK_READY_TIMEOUT_MS","LOCK_READY_POLL_MS","waitForWorkbenchLock","deadline","now","lock","Promise","resolve","contents","json","lockPath","acquireWorkbenchLock","info","retries","lockData","flag","disk","updatePort","err","Error","message","String","isNodeError","code","existing"],"mappings":"AAAA,SACEA,UAAU,EACVC,SAAS,EACTC,WAAW,EACXC,YAAY,EACZC,UAAU,EACVC,KAAK,EACLC,aAAa,QACR,UAAS;AAChB,SAAQC,IAAI,QAAO,YAAW;AAE9B,SACEC,qBAAqB,EACrBC,gBAAgB,EAChBC,oBAAoB,EACpBC,QAAQ,QACH,mBAAkB;AACzB,SAAQC,CAAC,QAAO,WAAU;AAE1B,SAAQC,oBAAoB,QAAO,gCAA+B;AAClE,SAAQC,2BAA2B,EAAEC,2BAA2B,QAAO,oBAAmB;AAE1F,SAAQC,oBAAoB,QAAO,4BAA2B;AAC9D,SAAQC,mBAAmB,EAAEC,YAAY,QAAO,uBAAsB;AAEtE;;;;;;;;;;;;;;;;;;CAkBC,GAED,MAAMC,WAAWR,SAAS;AAE1B,iEAAiE,GACjE,MAAMS,mBAAmB;AAEzB;;;;;CAKC,GACD,SAASC;IACP,OAAO,AAACJ,CAAAA,oBAAoBK,QAAQC,GAAG,KAAK,IAAIC,MAAK,EAAGC,WAAW;AACrE;AAEA,MAAMC,sBAAsB;IAC1B,6EAA6E,GAC7EC,IAAIf,EAAEgB,MAAM;IACZC,UAAUjB,EAAEgB,MAAM;IAClBE,MAAMlB,EAAEgB,MAAM;IACd,8EAA8E,GAC9EG,KAAKnB,EAAEgB,MAAM;IACbI,OAAOpB,EAAEgB,MAAM;IACfK,SAASrB,EAAEsB,QAAQ,CAACtB,EAAEgB,MAAM;AAC9B;AAEA;;;CAGC,GACD,MAAMO,2BAA2BvB,EA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oBAAC,GAAGgD,QAAQ;oBAAE1F;oBAAMuE,OAAO;gBAAI,IAAI;oBAACjC,MAAM;gBAAK;YACxF;QACF;IACF,EAAE,OAAOwD,KAAc;QACrBxI,SACE,wCACAwI,eAAeC,QAAQD,IAAIE,OAAO,GAAGC,OAAOH;QAE9C,IAAI,CAACI,YAAYJ,QAAQA,IAAIK,IAAI,KAAK,UAAU,OAAO/E;QAEvD,mDAAmD;QACnD,MAAMgF,WAAW5B,kBAAkBgB,KAAK1F,cAAc;QACtD,IAAIsG,UAAU,OAAOhF;QAErB,6FAA6F;QAC7F,IAAIqE,WAAW,GAAG,OAAOrE;QACzB,OAAOmE,qBAAqBC,MAAMC,UAAU;IAC9C;AACF;AAEA,SAASS,YAAYJ,GAAY;IAC/B,OAAOA,eAAeC,SAAS,UAAUD;AAC3C"}
@@ -23,6 +23,7 @@ import { startDevManifestWatcher } from './startDevManifestWatcher.js';
23
23
  const addr = server.httpServer?.address();
24
24
  return {
25
25
  host: typeof resolvedHost === 'string' ? resolvedHost : 'localhost',
26
+ https: Boolean(server.config.server.https),
26
27
  port: typeof addr === 'object' && addr ? addr.port : server.config.server.port
27
28
  };
28
29
  }
@@ -32,7 +33,7 @@ import { startDevManifestWatcher } from './startDevManifestWatcher.js';
32
33
  * server; the watcher keeps it current as `sanity.cli.ts` is edited.
33
34
  */ export async function startDevServerRegistration(options) {
34
35
  const { cliConfig, extractManifest, isApp, onInterfaceSetChange, output, server, workDir } = options;
35
- const { host: appHost, port: appPort } = serverAddress(server);
36
+ const { host: appHost, https, port: appPort } = serverAddress(server);
36
37
  reportConfigErrors(cliConfig.app, output);
37
38
  // Forwarded alongside (not inside) the manifest so the workbench renders local
38
39
  // panels/workers and reads the configs without a deploy.
@@ -66,6 +67,7 @@ import { startDevManifestWatcher } from './startDevManifestWatcher.js';
66
67
  applicationId,
67
68
  configs,
68
69
  host: appHost,
70
+ https,
69
71
  id,
70
72
  interfaces,
71
73
  organizationId,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/actions/dev/startDevServerRegistration.ts"],"sourcesContent":["import {type CliConfig, getCliConfigUncached, type Output} from '@sanity/cli-core'\nimport {type ViteDevServer} from 'vite'\n\nimport {isWorkbenchApp, isWorkbenchConfig} from '../../defineApp.js'\nimport {deriveInterfaces} from '../../deriveInterfaces.js'\nimport {resolveWorkbenchConfig} from '../../resolveWorkbenchConfig.js'\nimport {formatWorkbenchAppErrors, validateWorkbenchApp} from '../../validateWorkbenchApp.js'\nimport {deriveConfigs} from './deriveConfigs.js'\nimport {trackExposesSet} from './exposesSetId.js'\nimport {\n dashboardPath,\n type DevServerManifest,\n getRegisteredServers,\n localAppIdentity,\n registerDevServer,\n} from './registry.js'\nimport {startDevManifestWatcher} from './startDevManifestWatcher.js'\n\ninterface DevServerRegistrationOptions {\n cliConfig: CliConfig\n /**\n * Extract the project manifest to inline into the registry. The caller owns the\n * studio-vs-app split (manifest formats are CLI-domain); registration re-derives\n * the interface set alongside it.\n */\n extractManifest: (params: {\n applicationId?: string\n configPath: string\n workDir: string\n }) => Promise<DevServerManifest['manifest']>\n isApp: boolean\n output: Output\n server: ViteDevServer\n workDir: string\n\n /**\n * Rebuild the app's federation remote when its interface set changes, awaited\n * *before* the registry patch — the patch reloads the workbench page, which must\n * re-fetch a remote that already exposes the new interface. Resolves with the\n * recreated server so the entry gets its actual address (non-strict ports may\n * shift it); must reject if the restart produces no server, so the set stays\n * uncommitted and the next save retries instead of advertising a dead port.\n */\n onInterfaceSetChange?: () => Promise<ViteDevServer>\n}\n\ninterface DevServerRegistrationHandle {\n close: () => Promise<void>\n\n /** Where the Dashboard opens this server; unset when it can't open it there. */\n path?: string\n}\n\n/**\n * Log any app validation errors without aborting. Unlike build and deploy, dev\n * stays up on an invalid app so the author sees the errors and fixes them live on\n * the next save. A config is not an app — it isn't validated by the app schema\n * (which would spuriously demand a slug/title), so skip it here.\n */\nfunction reportConfigErrors(app: CliConfig['app'], output: Output): void {\n if (isWorkbenchConfig(app)) return\n const errors = validateWorkbenchApp(app)\n if (errors.length === 0) return\n output.warn(formatWorkbenchAppErrors(errors))\n}\n\n/** The address the server actually bound — the live socket, which can differ from the configured port under non-strict ports. */\nfunction serverAddress(server: ViteDevServer) {\n const resolvedHost = server.config.server.host\n const addr = server.httpServer?.address()\n return {\n host: typeof resolvedHost === 'string' ? resolvedHost : 'localhost',\n port: typeof addr === 'object' && addr ? addr.port : server.config.server.port,\n }\n}\n\n/**\n * Register the dev server in the registry and watch its config for manifest +\n * interface changes. The workbench reads the entry to locate and render the\n * server; the watcher keeps it current as `sanity.cli.ts` is edited.\n */\nexport async function startDevServerRegistration(\n options: DevServerRegistrationOptions,\n): Promise<DevServerRegistrationHandle> {\n const {cliConfig, extractManifest, isApp, onInterfaceSetChange, output, server, workDir} = options\n\n const {host: appHost, port: appPort} = serverAddress(server)\n\n reportConfigErrors(cliConfig.app, output)\n\n // Forwarded alongside (not inside) the manifest so the workbench renders local\n // panels/workers and reads the configs without a deploy.\n const interfaces = deriveInterfaces(cliConfig.app, {isApp})\n const configs = await deriveConfigs(cliConfig)\n\n const workbenchApp = isWorkbenchApp(cliConfig.app) ? cliConfig.app : undefined\n const config = resolveWorkbenchConfig(cliConfig)\n // A config runs alongside the app it configures, so give it its own id\n // namespace — sharing the app's slug would make the two indistinguishable here.\n const id = config ? `config:${config.appType}` : workbenchApp?.slug\n const applicationId = workbenchApp ? cliConfig.deployment?.appId : undefined\n // Identity is resolved and the reference composed here, so the workbench reads\n // both off the registry entry instead of recomposing them.\n const identity = workbenchApp ? localAppIdentity(workbenchApp) : undefined\n\n // The Dashboard tells local apps apart by their bus id and by the application\n // they stand in for.\n const organizationId = cliConfig.app?.organizationId\n const devServer = getRegisteredServers().find(\n (server) =>\n server.organizationId === organizationId &&\n (server.id === id || (applicationId && server.applicationId === applicationId)),\n )\n\n if (id && devServer) {\n const served =\n devServer.id === id\n ? `\"${id}\" is already served`\n : `\"${id}\" is the same application as \"${devServer.id}\", served`\n output.error(\n `${served} by another dev server running on port ${devServer.port}, ` +\n \"so the Dashboard can't tell them apart and this one stays out of it. Stop that server first.\",\n {exit: false},\n )\n return {close: async () => {}}\n }\n\n const registration = registerDevServer({\n applicationId,\n configs,\n host: appHost,\n id,\n interfaces,\n organizationId,\n port: appPort,\n projectId: cliConfig?.api?.projectId,\n ...identity,\n type: isApp ? 'coreApp' : 'studio',\n workDir,\n })\n\n const exposesSet = trackExposesSet({configs, interfaces})\n\n const watcher = await startDevManifestWatcher({\n // Re-derive every pass (don't omit): the registry patch is a shallow merge,\n // so omitting would wipe the registered set.\n extract: async (params) => {\n const nextConfig = await getCliConfigUncached(params.workDir)\n reportConfigErrors(nextConfig.app, output)\n return {\n configs: await deriveConfigs(nextConfig),\n interfaces: deriveInterfaces(nextConfig.app, {isApp}),\n manifest: await extractManifest({...params, applicationId: id}),\n }\n },\n // A studio's root resolves to `sanity.config.*` but its interfaces live in\n // `sanity.cli.*` — watch that too. Apps already root at `sanity.cli.*`.\n extraWatchFilenames: isApp ? undefined : ['sanity.cli.js', 'sanity.cli.ts'],\n output,\n update: async (patch) => {\n if (\n !exposesSet.changed({\n configs: patch.configs,\n interfaces: patch.interfaces,\n })\n ) {\n registration.update(patch)\n return\n }\n // Rebuild the remote *before* patching the registry — the patch reloads the\n // page, which must re-fetch a remote that already exposes the new interface.\n const rebuiltServer = await onInterfaceSetChange?.()\n // Commit only after a successful rebuild, so a thrown one retries next pass.\n exposesSet.commit({\n configs: patch.configs,\n interfaces: patch.interfaces,\n })\n // The recreated server can bind a different port (non-strict ports).\n registration.update(rebuiltServer ? {...patch, ...serverAddress(rebuiltServer)} : patch)\n },\n workDir,\n })\n\n return {\n close: async () => {\n registration.release()\n await watcher.close()\n },\n path: dashboardPath({\n id,\n interfaces,\n slug: identity?.slug,\n type: isApp ? 'coreApp' : 'studio',\n }),\n }\n}\n"],"names":["getCliConfigUncached","isWorkbenchApp","isWorkbenchConfig","deriveInterfaces","resolveWorkbenchConfig","formatWorkbenchAppErrors","validateWorkbenchApp","deriveConfigs","trackExposesSet","dashboardPath","getRegisteredServers","localAppIdentity","registerDevServer","startDevManifestWatcher","reportConfigErrors","app","output","errors","length","warn","serverAddress","server","resolvedHost","config","host","addr","httpServer","address","port","startDevServerRegistration","options","cliConfig","extractManifest","isApp","onInterfaceSetChange","workDir","appHost","appPort","interfaces","configs","workbenchApp","undefined","id","appType","slug","applicationId","deployment","appId","identity","organizationId","devServer","find","served","error","exit","close","registration","projectId","api","type","exposesSet","watcher","extract","params","nextConfig","manifest","extraWatchFilenames","update","patch","changed","rebuiltServer","commit","release","path"],"mappings":"AAAA,SAAwBA,oBAAoB,QAAoB,mBAAkB;AAGlF,SAAQC,cAAc,EAAEC,iBAAiB,QAAO,qBAAoB;AACpE,SAAQC,gBAAgB,QAAO,4BAA2B;AAC1D,SAAQC,sBAAsB,QAAO,kCAAiC;AACtE,SAAQC,wBAAwB,EAAEC,oBAAoB,QAAO,gCAA+B;AAC5F,SAAQC,aAAa,QAAO,qBAAoB;AAChD,SAAQC,eAAe,QAAO,oBAAmB;AACjD,SACEC,aAAa,EAEbC,oBAAoB,EACpBC,gBAAgB,EAChBC,iBAAiB,QACZ,gBAAe;AACtB,SAAQC,uBAAuB,QAAO,+BAA8B;AAqCpE;;;;;CAKC,GACD,SAASC,mBAAmBC,GAAqB,EAAEC,MAAc;IAC/D,IAAId,kBAAkBa,MAAM;IAC5B,MAAME,SAASX,qBAAqBS;IACpC,IAAIE,OAAOC,MAAM,KAAK,GAAG;IACzBF,OAAOG,IAAI,CAACd,yBAAyBY;AACvC;AAEA,+HAA+H,GAC/H,SAASG,cAAcC,MAAqB;IAC1C,MAAMC,eAAeD,OAAOE,MAAM,CAACF,MAAM,CAACG,IAAI;IAC9C,MAAMC,OAAOJ,OAAOK,UAAU,EAAEC;IAChC,OAAO;QACLH,MAAM,OAAOF,iBAAiB,WAAWA,eAAe;QACxDM,MAAM,OAAOH,SAAS,YAAYA,OAAOA,KAAKG,IAAI,GAAGP,OAAOE,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U;YAC9B;YACA,qEAAqE;YACrEkB,aAAaW,MAAM,CAACG,gBAAgB;gBAAC,GAAGF,KAAK;gBAAE,GAAGhD,cAAckD,cAAc;YAAA,IAAIF;QACpF;QACAjC;IACF;IAEA,OAAO;QACLoB,OAAO;YACLC,aAAagB,OAAO;YACpB,MAAMX,QAAQN,KAAK;QACrB;QACAkB,MAAMhE,cAAc;YAClBiC;YACAJ;YACAM,MAAMI,UAAUJ;YAChBe,MAAM1B,QAAQ,YAAY;QAC5B;IACF;AACF"}
1
+ {"version":3,"sources":["../../../src/actions/dev/startDevServerRegistration.ts"],"sourcesContent":["import {type CliConfig, getCliConfigUncached, type Output} from '@sanity/cli-core'\nimport {type ViteDevServer} from 'vite'\n\nimport {isWorkbenchApp, isWorkbenchConfig} from '../../defineApp.js'\nimport {deriveInterfaces} from '../../deriveInterfaces.js'\nimport {resolveWorkbenchConfig} from '../../resolveWorkbenchConfig.js'\nimport {formatWorkbenchAppErrors, validateWorkbenchApp} from '../../validateWorkbenchApp.js'\nimport {deriveConfigs} from './deriveConfigs.js'\nimport {trackExposesSet} from './exposesSetId.js'\nimport {\n dashboardPath,\n type DevServerManifest,\n getRegisteredServers,\n localAppIdentity,\n registerDevServer,\n} from './registry.js'\nimport {startDevManifestWatcher} from './startDevManifestWatcher.js'\n\ninterface DevServerRegistrationOptions {\n cliConfig: CliConfig\n /**\n * Extract the project manifest to inline into the registry. The caller owns the\n * studio-vs-app split (manifest formats are CLI-domain); registration re-derives\n * the interface set alongside it.\n */\n extractManifest: (params: {\n applicationId?: string\n configPath: string\n workDir: string\n }) => Promise<DevServerManifest['manifest']>\n isApp: boolean\n output: Output\n server: ViteDevServer\n workDir: string\n\n /**\n * Rebuild the app's federation remote when its interface set changes, awaited\n * *before* the registry patch — the patch reloads the workbench page, which must\n * re-fetch a remote that already exposes the new interface. Resolves with the\n * recreated server so the entry gets its actual address (non-strict ports may\n * shift it); must reject if the restart produces no server, so the set stays\n * uncommitted and the next save retries instead of advertising a dead port.\n */\n onInterfaceSetChange?: () => Promise<ViteDevServer>\n}\n\ninterface DevServerRegistrationHandle {\n close: () => Promise<void>\n\n /** Where the Dashboard opens this server; unset when it can't open it there. */\n path?: string\n}\n\n/**\n * Log any app validation errors without aborting. Unlike build and deploy, dev\n * stays up on an invalid app so the author sees the errors and fixes them live on\n * the next save. A config is not an app — it isn't validated by the app schema\n * (which would spuriously demand a slug/title), so skip it here.\n */\nfunction reportConfigErrors(app: CliConfig['app'], output: Output): void {\n if (isWorkbenchConfig(app)) return\n const errors = validateWorkbenchApp(app)\n if (errors.length === 0) return\n output.warn(formatWorkbenchAppErrors(errors))\n}\n\n/** The address the server actually bound — the live socket, which can differ from the configured port under non-strict ports. */\nfunction serverAddress(server: ViteDevServer) {\n const resolvedHost = server.config.server.host\n const addr = server.httpServer?.address()\n return {\n host: typeof resolvedHost === 'string' ? resolvedHost : 'localhost',\n https: Boolean(server.config.server.https),\n port: typeof addr === 'object' && addr ? addr.port : server.config.server.port,\n }\n}\n\n/**\n * Register the dev server in the registry and watch its config for manifest +\n * interface changes. The workbench reads the entry to locate and render the\n * server; the watcher keeps it current as `sanity.cli.ts` is edited.\n */\nexport async function startDevServerRegistration(\n options: DevServerRegistrationOptions,\n): Promise<DevServerRegistrationHandle> {\n const {cliConfig, extractManifest, isApp, onInterfaceSetChange, output, server, workDir} = options\n\n const {host: appHost, https, port: appPort} = serverAddress(server)\n\n reportConfigErrors(cliConfig.app, output)\n\n // Forwarded alongside (not inside) the manifest so the workbench renders local\n // panels/workers and reads the configs without a deploy.\n const interfaces = deriveInterfaces(cliConfig.app, {isApp})\n const configs = await deriveConfigs(cliConfig)\n\n const workbenchApp = isWorkbenchApp(cliConfig.app) ? cliConfig.app : undefined\n const config = resolveWorkbenchConfig(cliConfig)\n // A config runs alongside the app it configures, so give it its own id\n // namespace — sharing the app's slug would make the two indistinguishable here.\n const id = config ? `config:${config.appType}` : workbenchApp?.slug\n const applicationId = workbenchApp ? cliConfig.deployment?.appId : undefined\n // Identity is resolved and the reference composed here, so the workbench reads\n // both off the registry entry instead of recomposing them.\n const identity = workbenchApp ? localAppIdentity(workbenchApp) : undefined\n\n // The Dashboard tells local apps apart by their bus id and by the application\n // they stand in for.\n const organizationId = cliConfig.app?.organizationId\n const devServer = getRegisteredServers().find(\n (server) =>\n server.organizationId === organizationId &&\n (server.id === id || (applicationId && server.applicationId === applicationId)),\n )\n\n if (id && devServer) {\n const served =\n devServer.id === id\n ? `\"${id}\" is already served`\n : `\"${id}\" is the same application as \"${devServer.id}\", served`\n output.error(\n `${served} by another dev server running on port ${devServer.port}, ` +\n \"so the Dashboard can't tell them apart and this one stays out of it. Stop that server first.\",\n {exit: false},\n )\n return {close: async () => {}}\n }\n\n const registration = registerDevServer({\n applicationId,\n configs,\n host: appHost,\n https,\n id,\n interfaces,\n organizationId,\n port: appPort,\n projectId: cliConfig?.api?.projectId,\n ...identity,\n type: isApp ? 'coreApp' : 'studio',\n workDir,\n })\n\n const exposesSet = trackExposesSet({configs, interfaces})\n\n const watcher = await startDevManifestWatcher({\n // Re-derive every pass (don't omit): the registry patch is a shallow merge,\n // so omitting would wipe the registered set.\n extract: async (params) => {\n const nextConfig = await getCliConfigUncached(params.workDir)\n reportConfigErrors(nextConfig.app, output)\n return {\n configs: await deriveConfigs(nextConfig),\n interfaces: deriveInterfaces(nextConfig.app, {isApp}),\n manifest: await extractManifest({...params, applicationId: id}),\n }\n },\n // A studio's root resolves to `sanity.config.*` but its interfaces live in\n // `sanity.cli.*` — watch that too. Apps already root at `sanity.cli.*`.\n extraWatchFilenames: isApp ? undefined : ['sanity.cli.js', 'sanity.cli.ts'],\n output,\n update: async (patch) => {\n if (\n !exposesSet.changed({\n configs: patch.configs,\n interfaces: patch.interfaces,\n })\n ) {\n registration.update(patch)\n return\n }\n // Rebuild the remote *before* patching the registry — the patch reloads the\n // page, which must re-fetch a remote that already exposes the new interface.\n const rebuiltServer = await onInterfaceSetChange?.()\n // Commit only after a successful rebuild, so a thrown one retries next pass.\n exposesSet.commit({\n configs: patch.configs,\n interfaces: patch.interfaces,\n })\n // The recreated server can bind a different port (non-strict ports).\n registration.update(rebuiltServer ? {...patch, ...serverAddress(rebuiltServer)} : patch)\n },\n workDir,\n })\n\n return {\n close: async () => {\n registration.release()\n await watcher.close()\n },\n path: dashboardPath({\n id,\n interfaces,\n slug: identity?.slug,\n type: isApp ? 'coreApp' : 'studio',\n }),\n }\n}\n"],"names":["getCliConfigUncached","isWorkbenchApp","isWorkbenchConfig","deriveInterfaces","resolveWorkbenchConfig","formatWorkbenchAppErrors","validateWorkbenchApp","deriveConfigs","trackExposesSet","dashboardPath","getRegisteredServers","localAppIdentity","registerDevServer","startDevManifestWatcher","reportConfigErrors","app","output","errors","length","warn","serverAddress","server","resolvedHost","config","host","addr","httpServer","address","https","Boolean","port","startDevServerRegistration","options","cliConfig","extractManifest","isApp","onInterfaceSetChange","workDir","appHost","appPort","interfaces","configs","workbenchApp","undefined","id","appType","slug","applicationId","deployment","appId","identity","organizationId","devServer","find","served","error","exit","close","registration","projectId","api","type","exposesSet","watcher","extract","params","nextConfig","manifest","extraWatchFilenames","update","patch","changed","rebuiltServer","commit","release","path"],"mappings":"AAAA,SAAwBA,oBAAoB,QAAoB,mBAAkB;AAGlF,SAAQC,cAAc,EAAEC,iBAAiB,QAAO,qBAAoB;AACpE,SAAQC,gBAAgB,QAAO,4BAA2B;AAC1D,SAAQC,sBAAsB,QAAO,kCAAiC;AACtE,SAAQC,wBAAwB,EAAEC,oBAAoB,QAAO,gCAA+B;AAC5F,SAAQC,aAAa,QAAO,qBAAoB;AAChD,SAAQC,eAAe,QAAO,oBAAmB;AACjD,SACEC,aAAa,EAEbC,oBAAoB,EACpBC,gBAAgB,EAChBC,iBAAiB,QACZ,gBAAe;AACtB,SAAQC,uBAAuB,QAAO,+BAA8B;AAqCpE;;;;;CAKC,GACD,SAASC,mBAAmBC,GAAqB,EAAEC,MAAc;IAC/D,IAAId,kBAAkBa,MAAM;IAC5B,MA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gBAAE;YAC/D;QACF;QACA,2EAA2E;QAC3E,wEAAwE;QACxEwB,qBAAqBjC,QAAQQ,YAAY;YAAC;YAAiB;SAAgB;QAC3E3B;QACAqD,QAAQ,OAAOC;YACb,IACE,CAACR,WAAWS,OAAO,CAAC;gBAClB9B,SAAS6B,MAAM7B,OAAO;gBACtBD,YAAY8B,MAAM9B,UAAU;YAC9B,IACA;gBACAkB,aAAaW,MAAM,CAACC;gBACpB;YACF;YACA,4EAA4E;YAC5E,6EAA6E;YAC7E,MAAME,gBAAgB,MAAMpC;YAC5B,6EAA6E;YAC7E0B,WAAWW,MAAM,CAAC;gBAChBhC,SAAS6B,MAAM7B,OAAO;gBACtBD,YAAY8B,MAAM9B,UAAU;YAC9B;YACA,qEAAqE;YACrEkB,aAAaW,MAAM,CAACG,gBAAgB;gBAAC,GAAGF,KAAK;gBAAE,GAAGlD,cAAcoD,cAAc;YAAA,IAAIF;QACpF;QACAjC;IACF;IAEA,OAAO;QACLoB,OAAO;YACLC,aAAagB,OAAO;YACpB,MAAMX,QAAQN,KAAK;QACrB;QACAkB,MAAMlE,cAAc;YAClBmC;YACAJ;YACAM,MAAMI,UAAUJ;YAChBe,MAAM1B,QAAQ,YAAY;QAC5B;IACF;AACF"}
@@ -16,9 +16,10 @@ const noop = async ()=>{};
16
16
  // Every server is a local app except a config-only one — a config
17
17
  // with no interfaces (the media library). A server with both lands in both channels.
18
18
  const toApplicationsPayload = (servers)=>({
19
- applications: servers.filter((server)=>!isConfigOnlyServer(server)).map(({ applicationId, host, id, interfaces, manifest, name, organizationId, port, projectId, reference, slug, type, visibility })=>({
19
+ applications: servers.filter((server)=>!isConfigOnlyServer(server)).map(({ applicationId, host, https, id, interfaces, manifest, name, organizationId, port, projectId, reference, slug, type, visibility })=>({
20
20
  applicationId,
21
21
  host,
22
+ https,
22
23
  id,
23
24
  // Views cross to the remote keyed on `type`, never the internal `surface`.
24
25
  interfaces: interfaces?.map((iface)=>toWireInterface(iface)),
@@ -34,7 +35,7 @@ const toApplicationsPayload = (servers)=>({
34
35
  visibility
35
36
  } : {}
36
37
  })),
37
- configs: servers.flatMap(({ configs, host, port })=>// The registry stores the config flat; the workbench wire shape nests the
38
+ configs: servers.flatMap(({ configs, host, https, port })=>// The registry stores the config flat; the workbench wire shape nests the
38
39
  // type-specific payload (`fields` for a media library) under `config`, keyed
39
40
  // by the `appType` discriminator.
40
41
  (configs ?? []).map(({ appType, id, moduleName, version, ...config })=>({
@@ -42,7 +43,7 @@ const toApplicationsPayload = (servers)=>({
42
43
  config,
43
44
  id,
44
45
  moduleName,
45
- remoteURL: `http://${host}:${port}`,
46
+ remoteURL: `${https ? 'https' : 'http'}://${host}:${port}`,
46
47
  version
47
48
  })))
48
49
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/actions/dev/startWorkbenchDevServer.ts"],"sourcesContent":["import {fileURLToPath} from 'node:url'\n\nimport {type CliConfig, type Output, subdebug} from '@sanity/cli-core'\nimport {isStaging} from '@sanity/cli-core/util'\nimport viteReact from '@vitejs/plugin-react'\nimport {createServer, type InlineConfig, type Plugin, type ViteDevServer} from 'vite'\nimport {z} from 'zod/mini'\n\nimport {isWorkbenchApp, isWorkbenchConfig} from '../../defineApp.js'\nimport {createExposesTracker} from './exposesSetId.js'\nimport {\n acquireWorkbenchLock,\n type DevServerManifest,\n getRegisteredServers,\n isConfigOnlyServer,\n waitForWorkbenchLock,\n watchRegistry,\n} from './registry.js'\nimport {toWireInterface} from './toWireInterface.js'\nimport {writeWorkbenchRuntime} from './writeWorkbenchRuntime.js'\n\nconst devDebug = subdebug('dev')\nconst renderDashboardEntry = '@sanity/workbench-cli/_internal_render'\nconst renderDashboardPath = fileURLToPath(\n new URL('../../_exports/_internal_render.js', import.meta.url),\n)\n\nconst noop = async () => {}\n\n// Every server is a local app except a config-only one — a config\n// with no interfaces (the media library). A server with both lands in both channels.\nconst toApplicationsPayload = (servers: DevServerManifest[]) => ({\n applications: servers\n .filter((server) => !isConfigOnlyServer(server))\n .map(\n ({\n applicationId,\n host,\n id,\n interfaces,\n manifest,\n name,\n organizationId,\n port,\n projectId,\n reference,\n slug,\n type,\n visibility,\n }) => ({\n applicationId,\n host,\n id,\n // Views cross to the remote keyed on `type`, never the internal `surface`.\n interfaces: interfaces?.map((iface) => toWireInterface(iface)),\n manifest,\n name,\n port,\n projectId,\n reference,\n type,\n ...(organizationId && slug && visibility ? {organizationId, slug, visibility} : {}),\n }),\n ),\n configs: servers.flatMap(({configs, host, port}) =>\n // The registry stores the config flat; the workbench wire shape nests the\n // type-specific payload (`fields` for a media library) under `config`, keyed\n // by the `appType` discriminator.\n (configs ?? []).map(({appType, id, moduleName, version, ...config}) => ({\n appType,\n config,\n id,\n moduleName,\n remoteURL: `http://${host}:${port}`,\n version,\n })),\n ),\n})\n\n/**\n * Bridge the dev-server registry into a workbench Vite server's HMR channel so\n * the page tracks apps as they come and go. A changed interface set means a\n * rebuilt remote — full-reload to drop the stale remote-entry; otherwise\n * rebroadcast for a soft reconcile. Returns a detach fn.\n */\nfunction attachViteDevServerBridge(server: ViteDevServer, organizationId?: string): () => void {\n const ownServers = (servers: DevServerManifest[]) =>\n organizationId ? servers.filter((entry) => entry.organizationId === organizationId) : servers\n\n server.ws.on('sanity:workbench:get-local-applications', (_, client) => {\n client.send(\n 'sanity:workbench:local-applications',\n toApplicationsPayload(ownServers(getRegisteredServers())),\n )\n })\n\n const setTracker = createExposesTracker()\n const registryWatcher = watchRegistry((allServers) => {\n const servers = ownServers(allServers)\n if (setTracker.hasChanged(servers)) {\n server.ws.send({type: 'full-reload'})\n return\n }\n server.ws.send('sanity:workbench:local-applications', toApplicationsPayload(servers))\n })\n\n return () => registryWatcher.close()\n}\n\n/**\n * Bridge the registry into the workbench remote's HMR channel. The remote never\n * claims the workbench lock: a held lock tells the next `sanity dev` a shell is\n * running, and the remote only renders inside that shell.\n */\nexport function startWorkbenchRemoteCoordinator(options: {server: ViteDevServer}): {\n close: () => Promise<void>\n} {\n const detachBridge = attachViteDevServerBridge(options.server)\n\n return {\n close: async () => detachBridge(),\n }\n}\n\ninterface WorkbenchDevServerResult {\n close: () => Promise<void>\n httpHost: string | undefined\n workbenchAvailable: boolean\n workbenchPort: number\n}\n\nexport interface StartWorkbenchOptions {\n /** Dependency-cache dir for the workbench Vite server, kept apart from the user's own. */\n cacheDir: string\n cliConfig: CliConfig\n httpHost: string | undefined\n httpPort: number\n output: Output\n /** Wrap the workbench in React StrictMode; the CLI resolves it (unset collapses to `false`). */\n reactStrictMode: boolean\n workDir: string\n}\n\nexport async function startWorkbenchDevServer(\n options: StartWorkbenchOptions,\n): Promise<WorkbenchDevServerResult> {\n const {\n cacheDir,\n cliConfig,\n httpHost,\n httpPort: workbenchPort,\n output,\n reactStrictMode,\n workDir,\n } = options\n\n // Workbench is opted into by a `defineApplication` app or a config-only\n // `unstable_defineMediaLibrary` config — the latter still needs the shell to\n // render it.\n if (!isWorkbenchApp(cliConfig?.app) && !isWorkbenchConfig(cliConfig?.app)) {\n devDebug('Not a workbench app or config, skipping workbench dev server')\n return {close: noop, httpHost, workbenchAvailable: false, workbenchPort}\n }\n\n const organizationId = resolveOrganizationId(cliConfig)\n\n // Acquire an exclusive lock — only one workbench per organization.\n // Uses O_EXCL which is atomic at the OS level, preventing races when\n // multiple `sanity dev` processes start simultaneously (e.g. via turbo).\n const workbenchLock = acquireWorkbenchLock({\n host: httpHost || 'localhost',\n organizationId,\n port: workbenchPort,\n })\n if (!workbenchLock) {\n const existing = await waitForWorkbenchLock(organizationId)\n devDebug(\n 'Workbench already running at pid %d on port %d, skipping',\n existing?.pid,\n existing?.port,\n )\n return {\n close: noop,\n httpHost: existing?.host ?? httpHost,\n workbenchAvailable: true,\n workbenchPort: existing?.port ?? workbenchPort,\n }\n }\n\n // The lock is already held; an exception here (runtime-file write failure,\n // invalid remote URL) would otherwise leak it until the next acquire prunes\n // the stale PID.\n let result: Awaited<ReturnType<typeof createWorkbenchViteServer>>\n try {\n result = await createWorkbenchViteServer({\n cacheDir,\n httpHost,\n organizationId,\n output,\n reactStrictMode,\n workbenchPort,\n workDir,\n })\n } catch (err) {\n workbenchLock.release()\n throw err\n }\n\n if (!result) {\n workbenchLock.release()\n return {close: noop, httpHost, workbenchAvailable: false, workbenchPort}\n }\n\n const {actualPort, close} = result\n workbenchLock.updatePort(actualPort)\n\n return {\n close: async () => {\n workbenchLock.release()\n await close()\n },\n httpHost,\n workbenchAvailable: true,\n workbenchPort: actualPort,\n }\n}\n\ninterface CreateWorkbenchViteServerOptions {\n cacheDir: string\n httpHost: string | undefined\n organizationId: string\n output: Output\n reactStrictMode: boolean\n workbenchPort: number\n workDir: string\n}\n\ninterface CreateWorkbenchViteServerResult {\n actualPort: number\n close: () => Promise<void>\n}\n\nasync function createWorkbenchViteServer(\n options: CreateWorkbenchViteServerOptions,\n): Promise<CreateWorkbenchViteServerResult | undefined> {\n const {cacheDir, httpHost, organizationId, output, reactStrictMode, workbenchPort, workDir} =\n options\n\n const remoteUrl = parseRemoteUrl(process.env.SANITY_INTERNAL_WORKBENCH_REMOTE_URL)\n\n devDebug('Writing workbench runtime files')\n const root = await writeWorkbenchRuntime({\n cwd: workDir,\n organizationId,\n reactStrictMode,\n remoteUrl,\n })\n\n const viteConfig: InlineConfig = {\n // Custom cache directory so sanity's vite cache doesn't conflict with local vite projects\n cacheDir,\n configFile: false,\n define: {\n __SANITY_STAGING__: isStaging(),\n 'import.meta.env.SANITY_INTERNAL_WORKBENCH_REMOTE_URL': JSON.stringify(remoteUrl),\n },\n logLevel: 'warn',\n mode: 'development',\n optimizeDeps: {\n // Keep this entry out of pre-bundling so Vite injects its HMR context.\n exclude: [renderDashboardEntry],\n },\n // viteReact looks inert here — it transforms none of the host's own modules —\n // but it's load-bearing for the remotes. It serves the Fast Refresh runtime at\n // /@react-refresh and injects the preamble that defines window.$RefreshReg$. The\n // federated remotes loaded into this page are react-refresh transformed, so\n // without the preamble they throw \"can't detect preamble\", and without the\n // runtime their /@react-refresh import (wired by @module-federation/vite's\n // remoteHmr) fails. Dropping it as dead code broke every panel; see #1262.\n plugins: [viteReact(), ...(remoteUrl ? [remoteManifestPreloadHeaderPlugin(remoteUrl)] : [])],\n resolve: {\n // The generated Vite root cannot reliably resolve this package.\n alias: {[renderDashboardEntry]: renderDashboardPath},\n dedupe: ['react', 'react-dom'],\n },\n root,\n server: {\n host: httpHost,\n port: workbenchPort,\n strictPort: false,\n warmup: {\n clientFiles: ['./workbench.js'],\n },\n },\n }\n\n devDebug('Creating workbench vite server')\n const server = await createServer(viteConfig)\n try {\n await server.listen()\n } catch (err) {\n await server.close()\n output.warn(\n `Dashboard dev server failed to start: ${err instanceof Error ? err.message : String(err)}`,\n )\n return undefined\n }\n\n // Vite may have picked a different port if the desired one was occupied\n const addr = server.httpServer?.address()\n const actualPort = typeof addr === 'object' && addr ? addr.port : workbenchPort\n\n // Fire-and-forget: warm the workbench remote's Vite transform pipeline so\n // the first browser request hits a pre-populated module graph.\n if (remoteUrl) {\n fetch(remoteUrl)\n .then((r) => r.body?.cancel())\n .catch(() => {})\n devDebug('Warming workbench remote at %s', remoteUrl)\n }\n\n const detachBridge = attachViteDevServerBridge(server, organizationId)\n\n return {\n actualPort,\n close: async () => {\n detachBridge()\n await server.close()\n },\n }\n}\n\n// Workbench is opted into via `defineApplication`, which carries the\n// organization ID. Deliberately no fallback (e.g. resolving it from the\n// configured project): the lookup would need an authenticated user and an\n// API round-trip on every startup for something the opt-in already declares.\nconst resolveOrganizationId = (cliConfig: CliConfig): string => {\n if (cliConfig.app?.organizationId) {\n return cliConfig.app.organizationId\n }\n\n throw new Error(\n 'The Dashboard requires an organization ID. Pass \"organizationId\" to defineApplication() in sanity.cli.ts.',\n )\n}\n\n// Restricts protocol to http(s) so the URL is safe to interpolate into HTML\n// attributes and Link headers downstream.\nconst remoteUrlSchema = z.url({normalize: true, protocol: /^https?$/})\n\nfunction parseRemoteUrl(value: string | undefined): string | undefined {\n if (!value) return undefined\n\n const result = remoteUrlSchema.safeParse(value)\n\n if (!result.success) {\n throw new Error(\n `Invalid SANITY_INTERNAL_WORKBENCH_REMOTE_URL: ${value} (must be an http(s) URL)`,\n )\n }\n\n return result.data\n}\n\n/**\n * Sets a `Link: <remoteUrl>; rel=preload; as=fetch; crossorigin` response header\n * on the index document so the browser can start fetching the Module Federation\n * manifest as soon as response headers arrive — before HTML parsing reaches the\n * in-head preconnect hint. `as=fetch` matches how the federation runtime later\n * retrieves the JSON manifest, allowing the preload entry to satisfy that fetch.\n */\nfunction remoteManifestPreloadHeaderPlugin(remoteUrl: string): Plugin {\n return {\n apply: 'serve',\n configureServer(server) {\n server.middlewares.use((req, res, next) => {\n const pathname = (req.url || '/').split('?')[0]\n if (pathname === '/' || pathname === '/index.html') {\n res.setHeader('Link', `<${remoteUrl}>; rel=preload; as=fetch; crossorigin`)\n }\n next()\n })\n },\n name: 'sanity:workbench-remote-preload-header',\n }\n}\n"],"names":["fileURLToPath","subdebug","isStaging","viteReact","createServer","z","isWorkbenchApp","isWorkbenchConfig","createExposesTracker","acquireWorkbenchLock","getRegisteredServers","isConfigOnlyServer","waitForWorkbenchLock","watchRegistry","toWireInterface","writeWorkbenchRuntime","devDebug","renderDashboardEntry","renderDashboardPath","URL","url","noop","toApplicationsPayload","servers","applications","filter","server","map","applicationId","host","id","interfaces","manifest","name","organizationId","port","projectId","reference","slug","type","visibility","iface","configs","flatMap","appType","moduleName","version","config","remoteURL","attachViteDevServerBridge","ownServers","entry","ws","on","_","client","send","setTracker","registryWatcher","allServers","hasChanged","close","startWorkbenchRemoteCoordinator","options","detachBridge","startWorkbenchDevServer","cacheDir","cliConfig","httpHost","httpPort","workbenchPort","output","reactStrictMode","workDir","app","workbenchAvailable","resolveOrganizationId","workbenchLock","existing","pid","result","createWorkbenchViteServer","err","release","actualPort","updatePort","remoteUrl","parseRemoteUrl","process","env","SANITY_INTERNAL_WORKBENCH_REMOTE_URL","root","cwd","viteConfig","configFile","define","__SANITY_STAGING__","JSON","stringify","logLevel","mode","optimizeDeps","exclude","plugins","remoteManifestPreloadHeaderPlugin","resolve","alias","dedupe","strictPort","warmup","clientFiles","listen","warn","Error","message","String","undefined","addr","httpServer","address","fetch","then","r","body","cancel","catch","remoteUrlSchema","normalize","protocol","value","safeParse","success","data","apply","configureServer","middlewares","use","req","res","next","pathname","split","setHeader"],"mappings":"AAAA,SAAQA,aAAa,QAAO,WAAU;AAEtC,SAAqCC,QAAQ,QAAO,mBAAkB;AACtE,SAAQC,SAAS,QAAO,wBAAuB;AAC/C,OAAOC,eAAe,uBAAsB;AAC5C,SAAQC,YAAY,QAA2D,OAAM;AACrF,SAAQC,CAAC,QAAO,WAAU;AAE1B,SAAQC,cAAc,EAAEC,iBAAiB,QAAO,qBAAoB;AACpE,SAAQC,oBAAoB,QAAO,oBAAmB;AACtD,SACEC,oBAAoB,EAEpBC,oBAAoB,EACpBC,kBAAkB,EAClBC,oBAAoB,EACpBC,aAAa,QACR,gBAAe;AACtB,SAAQC,eAAe,QAAO,uBAAsB;AACpD,SAAQC,qBAAqB,QAAO,6BAA4B;AAEhE,MAAMC,WAAWf,SAAS;AAC1B,MAAMgB,uBAAuB;AAC7B,MAAMC,sBAAsBlB,cAC1B,IAAImB,IAAI,sCAAsC,YAAYC,GAAG;AAG/D,MAAMC,OAAO,WAAa;AAE1B,kEAAkE;AAClE,qFAAqF;AACrF,MAAMC,wBAAwB,CAACC,UAAkC,CAAA;QAC/DC,cAAcD,QACXE,MAAM,CAAC,CAACC,SAAW,CAACf,mBAAmBe,SACvCC,GAAG,CACF,CAAC,EACCC,aAAa,EACbC,IAAI,EACJC,EAAE,EACFC,UAAU,EACVC,QAAQ,EACRC,IAAI,EACJC,cAAc,EACdC,IAAI,EACJC,SAAS,EACTC,SAAS,EACTC,IAAI,EACJC,IAAI,EACJC,UAAU,EACX,GAAM,CAAA;gBACLZ;gBACAC;gBACAC;gBACA,2EAA2E;gBAC3EC,YAAYA,YAAYJ,IAAI,CAACc,QAAU3B,gBAAgB2B;gBACvDT;gBACAC;g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,MAAMC,WAAW,AAACH,CAAAA,IAAIrH,GAAG,IAAI,GAAE,EAAGyH,KAAK,CAAC,IAAI,CAAC,EAAE;gBAC/C,IAAID,aAAa,OAAOA,aAAa,eAAe;oBAClDF,IAAII,SAAS,CAAC,QAAQ,CAAC,CAAC,EAAExD,UAAU,qCAAqC,CAAC;gBAC5E;gBACAqD;YACF;QACF;QACA1G,MAAM;IACR;AACF"}
1
+ {"version":3,"sources":["../../../src/actions/dev/startWorkbenchDevServer.ts"],"sourcesContent":["import {fileURLToPath} from 'node:url'\n\nimport {type CliConfig, type Output, subdebug} from '@sanity/cli-core'\nimport {isStaging} from '@sanity/cli-core/util'\nimport viteReact from '@vitejs/plugin-react'\nimport {createServer, type InlineConfig, type Plugin, type ViteDevServer} from 'vite'\nimport {z} from 'zod/mini'\n\nimport {isWorkbenchApp, isWorkbenchConfig} from '../../defineApp.js'\nimport {createExposesTracker} from './exposesSetId.js'\nimport {\n acquireWorkbenchLock,\n type DevServerManifest,\n getRegisteredServers,\n isConfigOnlyServer,\n waitForWorkbenchLock,\n watchRegistry,\n} from './registry.js'\nimport {toWireInterface} from './toWireInterface.js'\nimport {writeWorkbenchRuntime} from './writeWorkbenchRuntime.js'\n\nconst devDebug = subdebug('dev')\nconst renderDashboardEntry = '@sanity/workbench-cli/_internal_render'\nconst renderDashboardPath = fileURLToPath(\n new URL('../../_exports/_internal_render.js', import.meta.url),\n)\n\nconst noop = async () => {}\n\n// Every server is a local app except a config-only one — a config\n// with no interfaces (the media library). A server with both lands in both channels.\nconst toApplicationsPayload = (servers: DevServerManifest[]) => ({\n applications: servers\n .filter((server) => !isConfigOnlyServer(server))\n .map(\n ({\n applicationId,\n host,\n https,\n id,\n interfaces,\n manifest,\n name,\n organizationId,\n port,\n projectId,\n reference,\n slug,\n type,\n visibility,\n }) => ({\n applicationId,\n host,\n https,\n id,\n // Views cross to the remote keyed on `type`, never the internal `surface`.\n interfaces: interfaces?.map((iface) => toWireInterface(iface)),\n manifest,\n name,\n port,\n projectId,\n reference,\n type,\n ...(organizationId && slug && visibility ? {organizationId, slug, visibility} : {}),\n }),\n ),\n configs: servers.flatMap(({configs, host, https, port}) =>\n // The registry stores the config flat; the workbench wire shape nests the\n // type-specific payload (`fields` for a media library) under `config`, keyed\n // by the `appType` discriminator.\n (configs ?? []).map(({appType, id, moduleName, version, ...config}) => ({\n appType,\n config,\n id,\n moduleName,\n remoteURL: `${https ? 'https' : 'http'}://${host}:${port}`,\n version,\n })),\n ),\n})\n\n/**\n * Bridge the dev-server registry into a workbench Vite server's HMR channel so\n * the page tracks apps as they come and go. A changed interface set means a\n * rebuilt remote — full-reload to drop the stale remote-entry; otherwise\n * rebroadcast for a soft reconcile. Returns a detach fn.\n */\nfunction attachViteDevServerBridge(server: ViteDevServer, organizationId?: string): () => void {\n const ownServers = (servers: DevServerManifest[]) =>\n organizationId ? servers.filter((entry) => entry.organizationId === organizationId) : servers\n\n server.ws.on('sanity:workbench:get-local-applications', (_, client) => {\n client.send(\n 'sanity:workbench:local-applications',\n toApplicationsPayload(ownServers(getRegisteredServers())),\n )\n })\n\n const setTracker = createExposesTracker()\n const registryWatcher = watchRegistry((allServers) => {\n const servers = ownServers(allServers)\n if (setTracker.hasChanged(servers)) {\n server.ws.send({type: 'full-reload'})\n return\n }\n server.ws.send('sanity:workbench:local-applications', toApplicationsPayload(servers))\n })\n\n return () => registryWatcher.close()\n}\n\n/**\n * Bridge the registry into the workbench remote's HMR channel. The remote never\n * claims the workbench lock: a held lock tells the next `sanity dev` a shell is\n * running, and the remote only renders inside that shell.\n */\nexport function startWorkbenchRemoteCoordinator(options: {server: ViteDevServer}): {\n close: () => Promise<void>\n} {\n const detachBridge = attachViteDevServerBridge(options.server)\n\n return {\n close: async () => detachBridge(),\n }\n}\n\ninterface WorkbenchDevServerResult {\n close: () => Promise<void>\n httpHost: string | undefined\n workbenchAvailable: boolean\n workbenchPort: number\n}\n\nexport interface StartWorkbenchOptions {\n /** Dependency-cache dir for the workbench Vite server, kept apart from the user's own. */\n cacheDir: string\n cliConfig: CliConfig\n httpHost: string | undefined\n httpPort: number\n output: Output\n /** Wrap the workbench in React StrictMode; the CLI resolves it (unset collapses to `false`). */\n reactStrictMode: boolean\n workDir: string\n}\n\nexport async function startWorkbenchDevServer(\n options: StartWorkbenchOptions,\n): Promise<WorkbenchDevServerResult> {\n const {\n cacheDir,\n cliConfig,\n httpHost,\n httpPort: workbenchPort,\n output,\n reactStrictMode,\n workDir,\n } = options\n\n // Workbench is opted into by a `defineApplication` app or a config-only\n // `unstable_defineMediaLibrary` config — the latter still needs the shell to\n // render it.\n if (!isWorkbenchApp(cliConfig?.app) && !isWorkbenchConfig(cliConfig?.app)) {\n devDebug('Not a workbench app or config, skipping workbench dev server')\n return {close: noop, httpHost, workbenchAvailable: false, workbenchPort}\n }\n\n const organizationId = resolveOrganizationId(cliConfig)\n\n // Acquire an exclusive lock — only one workbench per organization.\n // Uses O_EXCL which is atomic at the OS level, preventing races when\n // multiple `sanity dev` processes start simultaneously (e.g. via turbo).\n const workbenchLock = acquireWorkbenchLock({\n host: httpHost || 'localhost',\n organizationId,\n port: workbenchPort,\n })\n if (!workbenchLock) {\n const existing = await waitForWorkbenchLock(organizationId)\n devDebug(\n 'Workbench already running at pid %d on port %d, skipping',\n existing?.pid,\n existing?.port,\n )\n return {\n close: noop,\n httpHost: existing?.host ?? httpHost,\n workbenchAvailable: true,\n workbenchPort: existing?.port ?? workbenchPort,\n }\n }\n\n // The lock is already held; an exception here (runtime-file write failure,\n // invalid remote URL) would otherwise leak it until the next acquire prunes\n // the stale PID.\n let result: Awaited<ReturnType<typeof createWorkbenchViteServer>>\n try {\n result = await createWorkbenchViteServer({\n cacheDir,\n httpHost,\n organizationId,\n output,\n reactStrictMode,\n workbenchPort,\n workDir,\n })\n } catch (err) {\n workbenchLock.release()\n throw err\n }\n\n if (!result) {\n workbenchLock.release()\n return {close: noop, httpHost, workbenchAvailable: false, workbenchPort}\n }\n\n const {actualPort, close} = result\n workbenchLock.updatePort(actualPort)\n\n return {\n close: async () => {\n workbenchLock.release()\n await close()\n },\n httpHost,\n workbenchAvailable: true,\n workbenchPort: actualPort,\n }\n}\n\ninterface CreateWorkbenchViteServerOptions {\n cacheDir: string\n httpHost: string | undefined\n organizationId: string\n output: Output\n reactStrictMode: boolean\n workbenchPort: number\n workDir: string\n}\n\ninterface CreateWorkbenchViteServerResult {\n actualPort: number\n close: () => Promise<void>\n}\n\nasync function createWorkbenchViteServer(\n options: CreateWorkbenchViteServerOptions,\n): Promise<CreateWorkbenchViteServerResult | undefined> {\n const {cacheDir, httpHost, organizationId, output, reactStrictMode, workbenchPort, workDir} =\n options\n\n const remoteUrl = parseRemoteUrl(process.env.SANITY_INTERNAL_WORKBENCH_REMOTE_URL)\n\n devDebug('Writing workbench runtime files')\n const root = await writeWorkbenchRuntime({\n cwd: workDir,\n organizationId,\n reactStrictMode,\n remoteUrl,\n })\n\n const viteConfig: InlineConfig = {\n // Custom cache directory so sanity's vite cache doesn't conflict with local vite projects\n cacheDir,\n configFile: false,\n define: {\n __SANITY_STAGING__: isStaging(),\n 'import.meta.env.SANITY_INTERNAL_WORKBENCH_REMOTE_URL': JSON.stringify(remoteUrl),\n },\n logLevel: 'warn',\n mode: 'development',\n optimizeDeps: {\n // Keep this entry out of pre-bundling so Vite injects its HMR context.\n exclude: [renderDashboardEntry],\n },\n // viteReact looks inert here — it transforms none of the host's own modules —\n // but it's load-bearing for the remotes. It serves the Fast Refresh runtime at\n // /@react-refresh and injects the preamble that defines window.$RefreshReg$. The\n // federated remotes loaded into this page are react-refresh transformed, so\n // without the preamble they throw \"can't detect preamble\", and without the\n // runtime their /@react-refresh import (wired by @module-federation/vite's\n // remoteHmr) fails. Dropping it as dead code broke every panel; see #1262.\n plugins: [viteReact(), ...(remoteUrl ? [remoteManifestPreloadHeaderPlugin(remoteUrl)] : [])],\n resolve: {\n // The generated Vite root cannot reliably resolve this package.\n alias: {[renderDashboardEntry]: renderDashboardPath},\n dedupe: ['react', 'react-dom'],\n },\n root,\n server: {\n host: httpHost,\n port: workbenchPort,\n strictPort: false,\n warmup: {\n clientFiles: ['./workbench.js'],\n },\n },\n }\n\n devDebug('Creating workbench vite server')\n const server = await createServer(viteConfig)\n try {\n await server.listen()\n } catch (err) {\n await server.close()\n output.warn(\n `Dashboard dev server failed to start: ${err instanceof Error ? err.message : String(err)}`,\n )\n return undefined\n }\n\n // Vite may have picked a different port if the desired one was occupied\n const addr = server.httpServer?.address()\n const actualPort = typeof addr === 'object' && addr ? addr.port : workbenchPort\n\n // Fire-and-forget: warm the workbench remote's Vite transform pipeline so\n // the first browser request hits a pre-populated module graph.\n if (remoteUrl) {\n fetch(remoteUrl)\n .then((r) => r.body?.cancel())\n .catch(() => {})\n devDebug('Warming workbench remote at %s', remoteUrl)\n }\n\n const detachBridge = attachViteDevServerBridge(server, organizationId)\n\n return {\n actualPort,\n close: async () => {\n detachBridge()\n await server.close()\n },\n }\n}\n\n// Workbench is opted into via `defineApplication`, which carries the\n// organization ID. Deliberately no fallback (e.g. resolving it from the\n// configured project): the lookup would need an authenticated user and an\n// API round-trip on every startup for something the opt-in already declares.\nconst resolveOrganizationId = (cliConfig: CliConfig): string => {\n if (cliConfig.app?.organizationId) {\n return cliConfig.app.organizationId\n }\n\n throw new Error(\n 'The Dashboard requires an organization ID. Pass \"organizationId\" to defineApplication() in sanity.cli.ts.',\n )\n}\n\n// Restricts protocol to http(s) so the URL is safe to interpolate into HTML\n// attributes and Link headers downstream.\nconst remoteUrlSchema = z.url({normalize: true, protocol: /^https?$/})\n\nfunction parseRemoteUrl(value: string | undefined): string | undefined {\n if (!value) return undefined\n\n const result = remoteUrlSchema.safeParse(value)\n\n if (!result.success) {\n throw new Error(\n `Invalid SANITY_INTERNAL_WORKBENCH_REMOTE_URL: ${value} (must be an http(s) URL)`,\n )\n }\n\n return result.data\n}\n\n/**\n * Sets a `Link: <remoteUrl>; rel=preload; as=fetch; crossorigin` response header\n * on the index document so the browser can start fetching the Module Federation\n * manifest as soon as response headers arrive — before HTML parsing reaches the\n * in-head preconnect hint. `as=fetch` matches how the federation runtime later\n * retrieves the JSON manifest, allowing the preload entry to satisfy that fetch.\n */\nfunction remoteManifestPreloadHeaderPlugin(remoteUrl: string): Plugin {\n return {\n apply: 'serve',\n configureServer(server) {\n server.middlewares.use((req, res, next) => {\n const pathname = (req.url || '/').split('?')[0]\n if (pathname === '/' || pathname === '/index.html') {\n res.setHeader('Link', `<${remoteUrl}>; rel=preload; as=fetch; crossorigin`)\n }\n next()\n })\n },\n name: 'sanity:workbench-remote-preload-header',\n }\n}\n"],"names":["fileURLToPath","subdebug","isStaging","viteReact","createServer","z","isWorkbenchApp","isWorkbenchConfig","createExposesTracker","acquireWorkbenchLock","getRegisteredServers","isConfigOnlyServer","waitForWorkbenchLock","watchRegistry","toWireInterface","writeWorkbenchRuntime","devDebug","renderDashboardEntry","renderDashboardPath","URL","url","noop","toApplicationsPayload","servers","applications","filter","server","map","applicationId","host","https","id","interfaces","manifest","name","organizationId","port","projectId","reference","slug","type","visibility","iface","configs","flatMap","appType","moduleName","version","config","remoteURL","attachViteDevServerBridge","ownServers","entry","ws","on","_","client","send","setTracker","registryWatcher","allServers","hasChanged","close","startWorkbenchRemoteCoordinator","options","detachBridge","startWorkbenchDevServer","cacheDir","cliConfig","httpHost","httpPort","workbenchPort","output","reactStrictMode","workDir","app","workbenchAvailable","resolveOrganizationId","workbenchLock","existing","pid","result","createWorkbenchViteServer","err","release","actualPort","updatePort","remoteUrl","parseRemoteUrl","process","env","SANITY_INTERNAL_WORKBENCH_REMOTE_URL","root","cwd","viteConfig","configFile","define","__SANITY_STAGING__","JSON","stringify","logLevel","mode","optimizeDeps","exclude","plugins","remoteManifestPreloadHeaderPlugin","resolve","alias","dedupe","strictPort","warmup","clientFiles","listen","warn","Error","message","String","undefined","addr","httpServer","address","fetch","then","r","body","cancel","catch","remoteUrlSchema","normalize","protocol","value","safeParse","success","data","apply","configureServer","middlewares","use","req","res","next","pathname","split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Ae;oBAClDF,IAAII,SAAS,CAAC,QAAQ,CAAC,CAAC,EAAExD,UAAU,qCAAqC,CAAC;gBAC5E;gBACAqD;YACF;QACF;QACA1G,MAAM;IACR;AACF"}
package/dist/contract.js CHANGED
@@ -4,6 +4,7 @@ import { z } from 'zod/mini';
4
4
  // `zod/mini` keeps the bundle small.
5
5
  /** @internal */ export const VIEW_CONTRACT_VERSION = 2;
6
6
  /** @internal */ export const WEB_WORKER_CONTRACT_VERSION = 1;
7
+ /** @internal */ export const WINDOW_CONTRACT_VERSION = 1;
7
8
  /** @internal */ export const MEDIA_LIBRARY_CONFIG_CONTRACT_VERSION = 1;
8
9
  /** Component slots per view surface; windows load outside the component artifact path. @internal */ export const VIEW_COMPONENTS = {
9
10
  asset_source: [
@@ -60,12 +61,11 @@ const PanelDockSchema = z.object({
60
61
  asset_source: VIEW_CONTRACT_VERSION,
61
62
  panel: VIEW_CONTRACT_VERSION,
62
63
  tile: VIEW_CONTRACT_VERSION,
63
- window: undefined,
64
+ window: WINDOW_CONTRACT_VERSION,
64
65
  worker: WEB_WORKER_CONTRACT_VERSION
65
66
  };
66
67
  /** @internal */ export function interfaceContractVersion(kind) {
67
- const version = INTERFACE_CONTRACT_VERSIONS[kind];
68
- return version === undefined ? undefined : String(version);
68
+ return String(INTERFACE_CONTRACT_VERSIONS[kind]);
69
69
  }
70
70
  /**
71
71
  * The module-federation id a build exposes an interface at. Dev stamps the same
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/contract.ts"],"sourcesContent":["import {z} from 'zod/mini'\n\n// Shared module-federation extension contract: interface (view/web worker) and\n// config declaration schemas, plus the versions the build stamps.\n// `zod/mini` keeps the bundle small.\n\n/** @internal */\nexport const VIEW_CONTRACT_VERSION = 2\n\n/** @internal */\nexport const WEB_WORKER_CONTRACT_VERSION = 1\n\n/** @internal */\nexport const MEDIA_LIBRARY_CONFIG_CONTRACT_VERSION = 1\n\n/**\n * A view component. The return is opaque so the runtime helpers carry no React\n * dependency — the generated artifact renders it with the app's own React.\n * @public\n */\nexport type ViewComponent<TProps> = (props: TProps) => unknown\n\n/** @public */\nexport interface ViewComponentBaseProps<TView> {\n view: TView\n}\n\n/** Component slots per view surface; windows load outside the component artifact path. @internal */\nexport const VIEW_COMPONENTS = {\n asset_source: ['asset_source'],\n panel: ['title', 'panel'],\n tile: ['tile'],\n window: [],\n} as const satisfies Record<string, readonly string[]>\n\n/** @public */\nexport type ViewSurface = keyof typeof VIEW_COMPONENTS\n\n/**\n * A tile's footprint family — the shape it occupies on the dashboard. Modelled\n * on iOS WidgetKit families, not a linear scale: `banner` is full-width and\n * shallow, which a `small`→`large` magnitude can't express. The host maps a\n * family to a layout slot; the component reads it to render per footprint.\n * @public\n */\nexport const TileSizeSchema = z.enum(['small', 'large', 'banner'])\n\n/** @public */\nexport type TileSize = z.infer<typeof TileSizeSchema>\n\n/** @public */\nexport type WebWorkerType = 'worker'\n\n/**\n * @deprecated Use `WebWorkerType`.\n * @public\n */\nexport type ServiceType = WebWorkerType\n\nconst DockGroupSchema = z.enum(['system', 'applications'])\n\n/** @public */\nexport type DockGroup = z.output<typeof DockGroupSchema>\n\n/** @internal */\nexport const DockSchema = z.object({\n group: z.optional(DockGroupSchema),\n order: z.optional(z.number()),\n})\n\n/** @internal */\nexport type Dock = z.infer<typeof DockSchema>\n\nconst PanelDockSchema = z.object({order: z.optional(z.number())})\n\n/** @internal */\nexport const ViewPlacementMetadataSchema = z.object({dock: DockSchema})\n\n/** @internal */\nexport type ViewPlacementMetadata = z.infer<typeof ViewPlacementMetadataSchema>\n\n/**\n * A tile's interface metadata: its footprint `size` and an optional `order`\n * the dashboard sorts on, ascending. Both are authored as top-level view fields\n * (see {@link InterfaceDeclarationSchema}) but stored on the record as metadata.\n * @internal\n */\nexport const TileInterfaceMetadataSchema = z.object({\n order: z.optional(z.number()),\n size: TileSizeSchema,\n})\n\n/** @internal */\nexport type TileInterfaceMetadata = z.infer<typeof TileInterfaceMetadataSchema>\n\n/**\n * The contract version each interface type advertises, so the host can check it\n * renders/runs what it expects.\n * @internal\n */\nconst INTERFACE_CONTRACT_VERSIONS = {\n asset_source: VIEW_CONTRACT_VERSION,\n panel: VIEW_CONTRACT_VERSION,\n tile: VIEW_CONTRACT_VERSION,\n window: undefined,\n worker: WEB_WORKER_CONTRACT_VERSION,\n} as const\n\n/** Every interface type an app exposes — a window, a view, or a web worker. */\nexport type InterfaceKind = keyof typeof INTERFACE_CONTRACT_VERSIONS\n\n/** @internal */\nexport function interfaceContractVersion(kind: InterfaceKind): string | undefined {\n const version = INTERFACE_CONTRACT_VERSIONS[kind]\n return version === undefined ? undefined : String(version)\n}\n\n/**\n * The module-federation id a build exposes an interface at. Dev stamps the same\n * id a deploy would, so the workbench loads a local interface like a deployed one.\n * @internal\n */\nexport function interfaceModuleId(kind: string, name: string): string {\n switch (kind) {\n case 'asset_source':\n case 'panel':\n case 'tile': {\n return `views/${name}`\n }\n case 'window': {\n return 'App'\n }\n case 'worker': {\n return `services/${name}`\n }\n default: {\n throw new Error(`Cannot derive a moduleId for unknown interface kind: ${kind}`)\n }\n }\n}\n\n// Shared `name` + `src`; `kind` only tailors the validation message.\nfunction extensionDeclarationFields(kind: 'Field' | 'View' | 'Web worker') {\n const pattern = /^[a-zA-Z0-9_-]+$/\n return {\n name: z.string().check(z.regex(pattern, `${kind} \\`name\\` must match ${pattern}`)),\n src: z.string(),\n }\n}\n\n// Every interface shares `name` + `src` + a display `title`,\n// which Brett requires on the record each becomes.\nfunction interfaceDeclarationFields(kind: 'View' | 'Web worker') {\n return {\n ...extensionDeclarationFields(kind),\n title: z.string(`${kind} \\`title\\` is required`),\n }\n}\n\nconst PanelViewSchema = z.object({\n surface: z.literal('panel'),\n ...interfaceDeclarationFields('View'),\n dock: z.optional(PanelDockSchema),\n})\n\n/** @public */\nexport type PanelView = z.output<typeof PanelViewSchema>\n\n/** @public */\nexport type DefinePanelViewInput = Omit<PanelView, 'surface'>\n\n/** @public */\nexport function definePanelView(view: DefinePanelViewInput): PanelView {\n return {...view, surface: 'panel'}\n}\n\nconst WindowViewSchema = z.object({\n surface: z.literal('window'),\n ...interfaceDeclarationFields('View'),\n dock: z.optional(DockSchema),\n})\n\n/** @public */\nexport type WindowView = z.output<typeof WindowViewSchema>\n\n/** @public */\nexport type DefineWindowViewInput = Omit<WindowView, 'surface'>\n\n/** @public */\nexport function defineWindowView(view: DefineWindowViewInput): WindowView {\n return {...view, surface: 'window'}\n}\n\nconst AssetSourceViewSchema = z.object({\n surface: z.literal('asset_source'),\n ...interfaceDeclarationFields('View'),\n})\n\n/** @public */\nexport type AssetSourceView = z.output<typeof AssetSourceViewSchema>\n\n/** @public */\nexport type DefineAssetSourceViewInput = Omit<AssetSourceView, 'surface'>\n\n/** @public */\nexport function defineAssetSourceView(view: DefineAssetSourceViewInput): AssetSourceView {\n return {...view, surface: 'asset_source'}\n}\n\nconst TileViewSchema = z.object({\n surface: z.literal('tile'),\n ...interfaceDeclarationFields('View'),\n /** Sort position within its layout track, ascending. Optional. */\n order: z.optional(z.number()),\n /** Footprint family the dashboard lays the tile out by. */\n size: TileSizeSchema,\n})\n\n/** @public */\nexport type TileView = z.output<typeof TileViewSchema>\n\n/** @public */\nexport type DefineTileViewInput = Omit<TileView, 'surface'>\n\n/** @public */\nexport function defineTileView(view: DefineTileViewInput): TileView {\n return {...view, surface: 'tile'}\n}\n\n/** @internal */\nexport const InterfaceDeclarationSchema = z.discriminatedUnion('surface', [\n WindowViewSchema,\n PanelViewSchema,\n AssetSourceViewSchema,\n TileViewSchema,\n])\n\n/** @public */\nexport type ViewDeclaration = z.output<typeof InterfaceDeclarationSchema>\n\nconst WebWorkerSchema = z.object({\n type: z.literal('worker'),\n ...interfaceDeclarationFields('Web worker'),\n})\n\n/** @public */\nexport type WebWorker = z.output<typeof WebWorkerSchema>\n\n/** @public */\nexport type DefineWebWorkerInput = Omit<WebWorker, 'type'>\n\n/** @public */\nexport function defineWebWorker(webWorker: DefineWebWorkerInput): WebWorker {\n return {...webWorker, type: 'worker'}\n}\n\n/** @internal */\nexport const WebWorkerDeclarationSchema = z.discriminatedUnion('type', [WebWorkerSchema])\n\nconst MediaLibraryFieldSchema = z.object({\n ...extensionDeclarationFields('Field'),\n public: z.optional(z.boolean()),\n title: z.string(),\n})\n\n/**\n * Stamped where the config crosses a boundary so the authoring model doesn't carry a constant discriminator.\n * @internal\n */\nexport const INSTALLATION_CONFIG_TYPE = 'installation_config'\n\n// `appType` is stamped by `unstable_defineMediaLibrary`, never authored.\nconst MediaLibraryConfigSchema = z.object({\n appType: z.literal('media-library'),\n fields: z\n .array(MediaLibraryFieldSchema)\n .check(\n z.refine(\n (fields) => new Set(fields.map((field) => field.name)).size === fields.length,\n 'Field `name` must be unique within a media library',\n ),\n ),\n})\n\n/**\n * A workbench config's built value, keyed by `appType`; deploys as a versioned\n * snapshot, not an interface.\n * @internal\n */\nexport const ConfigSchema = z.discriminatedUnion('appType', [MediaLibraryConfigSchema])\n\n/**\n * The `{appType, fields}` config value the build expands into a federation\n * remote and the deploy summarizes.\n * @internal\n */\nexport type WorkbenchConfigValue = z.output<typeof ConfigSchema>\n"],"names":["z","VIEW_CONTRACT_VERSION","WEB_WORKER_CONTRACT_VERSION","MEDIA_LIBRARY_CONFIG_CONTRACT_VERSION","VIEW_COMPONENTS","asset_source","panel","tile","window","TileSizeSchema","enum","DockGroupSchema","DockSchema","object","group","optional","order","number","PanelDockSchema","ViewPlacementMetadataSchema","dock","TileInterfaceMetadataSchema","size","INTERFACE_CONTRACT_VERSIONS","undefined","worker","interfaceContractVersion","kind","version","String","interfaceModuleId","name","Error","extensionDeclarationFields","pattern","string","check","regex","src","interfaceDeclarationFields","title","PanelViewSchema","surface","literal","definePanelView","view","WindowViewSchema","defineWindowView","AssetSourceViewSchema","defineAssetSourceView","TileViewSchema","defineTileView","InterfaceDeclarationSchema","discriminatedUnion","WebWorkerSchema","type","defineWebWorker","webWorker","WebWorkerDeclarationSchema","MediaLibraryFieldSchema","public","boolean","INSTALLATION_CON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EmC,MAAM;AACjB;AAEA;;;CAGC,GACD,OAAO,MAAM2B,2BAA2B,sBAAqB;AAE7D,yEAAyE;AACzE,MAAMC,2BAA2B/D,EAAEa,MAAM,CAAC;IACxCmD,SAAShE,EAAE2C,OAAO,CAAC;IACnBsB,QAAQjE,EACLkE,KAAK,CAACP,yBACNvB,KAAK,CACJpC,EAAEmE,MAAM,CACN,CAACF,SAAW,IAAIG,IAAIH,OAAOI,GAAG,CAAC,CAACC,QAAUA,MAAMvC,IAAI,GAAGT,IAAI,KAAK2C,OAAOM,MAAM,EAC7E;AAGR;AAEA;;;;CAIC,GACD,OAAO,MAAMC,eAAexE,EAAEqD,kBAAkB,CAAC,WAAW;IAACU;CAAyB,EAAC"}
1
+ {"version":3,"sources":["../src/contract.ts"],"sourcesContent":["import {z} from 'zod/mini'\n\n// Shared module-federation extension contract: interface (view/web worker) and\n// config declaration schemas, plus the versions the build stamps.\n// `zod/mini` keeps the bundle small.\n\n/** @internal */\nexport const VIEW_CONTRACT_VERSION = 2\n\n/** @internal */\nexport const WEB_WORKER_CONTRACT_VERSION = 1\n\n/** @internal */\nexport const WINDOW_CONTRACT_VERSION = 1\n\n/** @internal */\nexport const MEDIA_LIBRARY_CONFIG_CONTRACT_VERSION = 1\n\n/**\n * A view component. The return is opaque so the runtime helpers carry no React\n * dependency — the generated artifact renders it with the app's own React.\n * @public\n */\nexport type ViewComponent<TProps> = (props: TProps) => unknown\n\n/** @public */\nexport interface ViewComponentBaseProps<TView> {\n view: TView\n}\n\n/** Component slots per view surface; windows load outside the component artifact path. @internal */\nexport const VIEW_COMPONENTS = {\n asset_source: ['asset_source'],\n panel: ['title', 'panel'],\n tile: ['tile'],\n window: [],\n} as const satisfies Record<string, readonly string[]>\n\n/** @public */\nexport type ViewSurface = keyof typeof VIEW_COMPONENTS\n\n/**\n * A tile's footprint family — the shape it occupies on the dashboard. Modelled\n * on iOS WidgetKit families, not a linear scale: `banner` is full-width and\n * shallow, which a `small`→`large` magnitude can't express. The host maps a\n * family to a layout slot; the component reads it to render per footprint.\n * @public\n */\nexport const TileSizeSchema = z.enum(['small', 'large', 'banner'])\n\n/** @public */\nexport type TileSize = z.infer<typeof TileSizeSchema>\n\n/** @public */\nexport type WebWorkerType = 'worker'\n\n/**\n * @deprecated Use `WebWorkerType`.\n * @public\n */\nexport type ServiceType = WebWorkerType\n\nconst DockGroupSchema = z.enum(['system', 'applications'])\n\n/** @public */\nexport type DockGroup = z.output<typeof DockGroupSchema>\n\n/** @internal */\nexport const DockSchema = z.object({\n group: z.optional(DockGroupSchema),\n order: z.optional(z.number()),\n})\n\n/** @internal */\nexport type Dock = z.infer<typeof DockSchema>\n\nconst PanelDockSchema = z.object({order: z.optional(z.number())})\n\n/** @internal */\nexport const ViewPlacementMetadataSchema = z.object({dock: DockSchema})\n\n/** @internal */\nexport type ViewPlacementMetadata = z.infer<typeof ViewPlacementMetadataSchema>\n\n/**\n * A tile's interface metadata: its footprint `size` and an optional `order`\n * the dashboard sorts on, ascending. Both are authored as top-level view fields\n * (see {@link InterfaceDeclarationSchema}) but stored on the record as metadata.\n * @internal\n */\nexport const TileInterfaceMetadataSchema = z.object({\n order: z.optional(z.number()),\n size: TileSizeSchema,\n})\n\n/** @internal */\nexport type TileInterfaceMetadata = z.infer<typeof TileInterfaceMetadataSchema>\n\n/**\n * The contract version each interface type advertises, so the host can check it\n * renders/runs what it expects.\n * @internal\n */\nconst INTERFACE_CONTRACT_VERSIONS = {\n asset_source: VIEW_CONTRACT_VERSION,\n panel: VIEW_CONTRACT_VERSION,\n tile: VIEW_CONTRACT_VERSION,\n window: WINDOW_CONTRACT_VERSION,\n worker: WEB_WORKER_CONTRACT_VERSION,\n} as const satisfies Record<string, number>\n\n/** Every interface type an app exposes — a window, a view, or a web worker. */\nexport type InterfaceKind = keyof typeof INTERFACE_CONTRACT_VERSIONS\n\n/** @internal */\nexport function interfaceContractVersion(kind: InterfaceKind): string {\n return String(INTERFACE_CONTRACT_VERSIONS[kind])\n}\n\n/**\n * The module-federation id a build exposes an interface at. Dev stamps the same\n * id a deploy would, so the workbench loads a local interface like a deployed one.\n * @internal\n */\nexport function interfaceModuleId(kind: string, name: string): string {\n switch (kind) {\n case 'asset_source':\n case 'panel':\n case 'tile': {\n return `views/${name}`\n }\n case 'window': {\n return 'App'\n }\n case 'worker': {\n return `services/${name}`\n }\n default: {\n throw new Error(`Cannot derive a moduleId for unknown interface kind: ${kind}`)\n }\n }\n}\n\n// Shared `name` + `src`; `kind` only tailors the validation message.\nfunction extensionDeclarationFields(kind: 'Field' | 'View' | 'Web worker') {\n const pattern = /^[a-zA-Z0-9_-]+$/\n return {\n name: z.string().check(z.regex(pattern, `${kind} \\`name\\` must match ${pattern}`)),\n src: z.string(),\n }\n}\n\n// Every interface shares `name` + `src` + a display `title`,\n// which Brett requires on the record each becomes.\nfunction interfaceDeclarationFields(kind: 'View' | 'Web worker') {\n return {\n ...extensionDeclarationFields(kind),\n title: z.string(`${kind} \\`title\\` is required`),\n }\n}\n\nconst PanelViewSchema = z.object({\n surface: z.literal('panel'),\n ...interfaceDeclarationFields('View'),\n dock: z.optional(PanelDockSchema),\n})\n\n/** @public */\nexport type PanelView = z.output<typeof PanelViewSchema>\n\n/** @public */\nexport type DefinePanelViewInput = Omit<PanelView, 'surface'>\n\n/** @public */\nexport function definePanelView(view: DefinePanelViewInput): PanelView {\n return {...view, surface: 'panel'}\n}\n\nconst WindowViewSchema = z.object({\n surface: z.literal('window'),\n ...interfaceDeclarationFields('View'),\n dock: z.optional(DockSchema),\n})\n\n/** @public */\nexport type WindowView = z.output<typeof WindowViewSchema>\n\n/** @public */\nexport type DefineWindowViewInput = Omit<WindowView, 'surface'>\n\n/** @public */\nexport function defineWindowView(view: DefineWindowViewInput): WindowView {\n return {...view, surface: 'window'}\n}\n\nconst AssetSourceViewSchema = z.object({\n surface: z.literal('asset_source'),\n ...interfaceDeclarationFields('View'),\n})\n\n/** @public */\nexport type AssetSourceView = z.output<typeof AssetSourceViewSchema>\n\n/** @public */\nexport type DefineAssetSourceViewInput = Omit<AssetSourceView, 'surface'>\n\n/** @public */\nexport function defineAssetSourceView(view: DefineAssetSourceViewInput): AssetSourceView {\n return {...view, surface: 'asset_source'}\n}\n\nconst TileViewSchema = z.object({\n surface: z.literal('tile'),\n ...interfaceDeclarationFields('View'),\n /** Sort position within its layout track, ascending. Optional. */\n order: z.optional(z.number()),\n /** Footprint family the dashboard lays the tile out by. */\n size: TileSizeSchema,\n})\n\n/** @public */\nexport type TileView = z.output<typeof TileViewSchema>\n\n/** @public */\nexport type DefineTileViewInput = Omit<TileView, 'surface'>\n\n/** @public */\nexport function defineTileView(view: DefineTileViewInput): TileView {\n return {...view, surface: 'tile'}\n}\n\n/** @internal */\nexport const InterfaceDeclarationSchema = z.discriminatedUnion('surface', [\n WindowViewSchema,\n PanelViewSchema,\n AssetSourceViewSchema,\n TileViewSchema,\n])\n\n/** @public */\nexport type ViewDeclaration = z.output<typeof InterfaceDeclarationSchema>\n\nconst WebWorkerSchema = z.object({\n type: z.literal('worker'),\n ...interfaceDeclarationFields('Web worker'),\n})\n\n/** @public */\nexport type WebWorker = z.output<typeof WebWorkerSchema>\n\n/** @public */\nexport type DefineWebWorkerInput = Omit<WebWorker, 'type'>\n\n/** @public */\nexport function defineWebWorker(webWorker: DefineWebWorkerInput): WebWorker {\n return {...webWorker, type: 'worker'}\n}\n\n/** @internal */\nexport const WebWorkerDeclarationSchema = z.discriminatedUnion('type', [WebWorkerSchema])\n\nconst MediaLibraryFieldSchema = z.object({\n ...extensionDeclarationFields('Field'),\n public: z.optional(z.boolean()),\n title: z.string(),\n})\n\n/**\n * Stamped where the config crosses a boundary so the authoring model doesn't carry a constant discriminator.\n * @internal\n */\nexport const INSTALLATION_CONFIG_TYPE = 'installation_config'\n\n// `appType` is stamped by `unstable_defineMediaLibrary`, never authored.\nconst MediaLibraryConfigSchema = z.object({\n appType: z.literal('media-library'),\n fields: z\n .array(MediaLibraryFieldSchema)\n .check(\n z.refine(\n (fields) => new Set(fields.map((field) => field.name)).size === fields.length,\n 'Field `name` must be unique within a media library',\n ),\n ),\n})\n\n/**\n * A workbench config's built value, keyed by `appType`; deploys as a versioned\n * snapshot, not an interface.\n * @internal\n */\nexport const ConfigSchema = z.discriminatedUnion('appType', [MediaLibraryConfigSchema])\n\n/**\n * The `{appType, fields}` config value the build expands into a federation\n * remote and the deploy summarizes.\n * @internal\n */\nexport type WorkbenchConfigValue = z.output<typeof ConfigSchema>\n"],"names":["z","VIEW_CONTRACT_VERSION","WEB_WORKER_CONTRACT_VERSION","WINDOW_CONTRACT_VERSION","MEDIA_LIBRARY_CONFIG_CONTRACT_VERSION","VIEW_COMPONENTS","asset_source","panel","tile","window","TileSizeSchema","enum","DockGroupSchema","DockSchema","object","group","optional","order","number","PanelDockSchema","ViewPlacementMetadataSchema","dock","TileInterfaceMetadataSchema","size","INTERFACE_CONTRACT_VERSIONS","worker","interfaceContractVersion","kind","String","interfaceModuleId","name","Error","extensionDeclarationFields","pattern","string","check","regex","src","interfaceDeclarationFields","title","PanelViewSchema","surface","literal","definePanelView","view","WindowViewSchema","defineWindowView","AssetSourceViewSchema","defineAssetSourceView","TileViewSchema","defineTileView","InterfaceDeclarationSchema","discriminatedUnion","WebWorkerSchema","type","defineWebWorker","webWorker","WebWorkerDeclarationSchema","MediaLibraryFieldSchema","public","boolean","INSTALLATION_CONFIG_TYPE","MediaLibraryConfigSchema","appType","fields","array","refine","Set","map","field","length","ConfigSchema"],"mappings":"AAAA,SAAQA,CAAC,QAAO,WAAU;AAE1B,+EAA+E;AAC/E,kEAAkE;AAClE,qCAAqC;AAErC,cAAc,GACd,OAAO,MAAMC,wBAAwB,EAAC;AAEtC,cAAc,GACd,OAAO,MAAMC,8BAA8B,EAAC;AAE5C,cAAc,GACd,OAAO,MAAMC,0BAA0B,EAAC;AAExC,cAAc,GACd,OAAO,MAAMC,wCAAwC,EAAC;AActD,kGAAkG,GAClG,OAAO,MAAMC,kBAAkB;IAC7BC,cAAc;QAA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D,OAAO,MAAMC,eAAevE,EAAEoD,kBAAkB,CAAC,WAAW;IAACU;CAAyB,EAAC"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/deriveInterfaces.ts"],"sourcesContent":["import {type CliConfig} from '@sanity/cli-core'\n\nimport {FEDERATION_FILE_NAME, RUNTIME_DIR} from './actions/build/vite/constants.js'\nimport {\n type Dock,\n interfaceContractVersion,\n type InterfaceKind,\n interfaceModuleId,\n type PanelView,\n type TileInterfaceMetadata,\n type ViewPlacementMetadata,\n type WindowView,\n} from './contract.js'\nimport {isWorkbenchApp} from './defineApp.js'\n\n/** What a studio exposes as `./App` — the generated entry that renders `sanity.config.ts`. */\nconst GENERATED_ENTRY = `./${RUNTIME_DIR}/${FEDERATION_FILE_NAME}.jsx`\n\ninterface DerivedInterfaceBase {\n /** CLI-minted for a local interface; a deployed one gets its id from Brett. */\n id: string\n moduleId: string\n name: string\n src: string\n title: string\n\n version?: string\n}\n\n/** @internal */\nexport type DerivedInterface =\n | (DerivedInterfaceBase & {metadata: null; surface: 'asset_source'})\n | (DerivedInterfaceBase & {metadata: null; type: 'worker'})\n | (DerivedInterfaceBase & {metadata: TileInterfaceMetadata; surface: 'tile'})\n | (DerivedInterfaceBase & {metadata: ViewPlacementMetadata | null; surface: 'panel'})\n | (DerivedInterfaceBase & {metadata: ViewPlacementMetadata | null; surface: 'window'})\n\n/**\n * `appTitle` titles the window where a deploy resolved one through `--title`;\n * dev takes it from the config.\n * @internal\n */\nexport function deriveInterfaces(\n app: CliConfig['app'],\n {appTitle, isApp}: {appTitle?: string; isApp: boolean},\n): DerivedInterface[] {\n if (!isWorkbenchApp(app)) return []\n\n // The schema rejects a *declared* studio with an `entry`; `isApp` is resolved\n // from the project, so a detected one only fails here.\n if (!isApp && app.entry !== undefined) {\n throw new Error('App views for studios are not implemented yet')\n }\n const entry = isApp ? app.entry : GENERATED_ENTRY\n\n // Identity, not address: interface ids and the window name key on `name`\n // (which defaults to `slug`, so existing apps derive byte-identical ids).\n const appName = app.name ?? app.slug\n\n const shared = (\n kind: InterfaceKind,\n declaration: {name: string; src: string; title: string},\n ) => ({\n id: `${appName}-${kind}-${declaration.name}`,\n moduleId: interfaceModuleId(kind, declaration.name),\n name: declaration.name,\n src: declaration.src,\n title: declaration.title,\n version: interfaceContractVersion(kind),\n })\n\n const placementMetadata = (\n dock?: Dock,\n surface: (PanelView | WindowView)['surface'] = 'window',\n ): ViewPlacementMetadata | null => {\n const group = surface === 'panel' ? undefined : (dock?.group ?? app.dock?.group)\n const order = dock?.order ?? app.dock?.order\n if (group === undefined && order === undefined) return null\n return {\n dock: {\n ...(group === undefined ? {} : {group}),\n ...(order === undefined ? {} : {order}),\n },\n }\n }\n\n return [\n ...(app.views ?? []).map((view): DerivedInterface => {\n if (view.surface === 'tile') {\n return {\n ...shared(view.surface, view),\n metadata:\n view.order === undefined ? {size: view.size} : {order: view.order, size: view.size},\n surface: view.surface,\n }\n }\n if (view.surface === 'panel' || view.surface === 'window') {\n return {\n ...shared(view.surface, view),\n metadata: placementMetadata(view.dock, view.surface),\n surface: view.surface,\n }\n }\n return {...shared(view.surface, view), metadata: null, surface: view.surface}\n }),\n ...(app.webWorkers ?? []).map((webWorker): DerivedInterface => ({\n ...shared('worker', webWorker),\n metadata: null,\n type: 'worker',\n })),\n ...(entry === undefined\n ? []\n : [\n {\n ...shared('window', {name: appName, src: entry, title: appTitle ?? app.title}),\n metadata: placementMetadata(),\n surface: 'window' as const,\n },\n ]),\n ]\n}\n"],"names":["FEDERATION_FILE_NAME","RUNTIME_DIR","interfaceContractVersion","interfaceModuleId","isWorkbenchApp","GENERATED_ENTRY","deriveInterfaces","app","appTitle","isApp","entry","undefined","Error","appName","name","slug","shared","kind","declaration","id","moduleId","src","title","version","placementMetadata","dock","surface","group","order","views","map","view","metadata","size","webWorkers","webWorker","type"],"mappings":"AAEA,SAAQA,oBAAoB,EAAEC,WAAW,QAAO,oCAAmC;AACnF,SAEEC,wBAAwB,EAExBC,iBAAiB,QA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ACrB,CAAAA,IAAIsB,KAAK,IAAI,EAAE,AAAD,EAAGC,GAAG,CAAC,CAACC;YACxB,IAAIA,KAAKL,OAAO,KAAK,QAAQ;gBAC3B,OAAO;oBACL,GAAGV,OAAOe,KAAKL,OAAO,EAAEK,KAAK;oBAC7BC,UACED,KAAKH,KAAK,KAAKjB,YAAY;wBAACsB,MAAMF,KAAKE,IAAI;oBAAA,IAAI;wBAACL,OAAOG,KAAKH,KAAK;wBAAEK,MAAMF,KAAKE,IAAI;oBAAA;oBACpFP,SAASK,KAAKL,OAAO;gBACvB;YACF;YACA,IAAIK,KAAKL,OAAO,KAAK,WAAWK,KAAKL,OAAO,KAAK,UAAU;gBACzD,OAAO;oBACL,GAAGV,OAAOe,KAAKL,OAAO,EAAEK,KAAK;oBAC7BC,UAAUR,kBAAkBO,KAAKN,IAAI,EAAEM,KAAKL,OAAO;oBACnDA,SAASK,KAAKL,OAAO;gBACvB;YACF;YACA,OAAO;gBAAC,GAAGV,OAAOe,KAAKL,OAAO,EAAEK,KAAK;gBAAEC,UAAU;gBAAMN,SAASK,KAAKL,OAAO;YAAA;QAC9E;WACG,AAACnB,CAAAA,IAAI2B,UAAU,IAAI,EAAE,AAAD,EAAGJ,GAAG,CAAC,CAACK,YAAiC,CAAA;gBAC9D,GAAGnB,OAAO,UAAUmB,UAAU;gBAC9BH,UAAU;gBACVI,MAAM;YACR,CAAA;WACI1B,UAAUC,YACV,EAAE,GACF;YACE;gBACE,GAAGK,OAAO,UAAU;oBAACF,MAAMD;oBAASQ,KAAKX;oBAAOY,OAAOd,YAAYD,IAAIe,KAAK;gBAAA,EAAE;gBAC9EU,UAAUR;gBACVE,SAAS;YACX;SACD;KACN;AACH"}
1
+ {"version":3,"sources":["../src/deriveInterfaces.ts"],"sourcesContent":["import {type CliConfig} from '@sanity/cli-core'\n\nimport {FEDERATION_FILE_NAME, RUNTIME_DIR} from './actions/build/vite/constants.js'\nimport {\n type Dock,\n interfaceContractVersion,\n type InterfaceKind,\n interfaceModuleId,\n type PanelView,\n type TileInterfaceMetadata,\n type ViewPlacementMetadata,\n type WindowView,\n} from './contract.js'\nimport {isWorkbenchApp} from './defineApp.js'\n\n/** What a studio exposes as `./App` — the generated entry that renders `sanity.config.ts`. */\nconst GENERATED_ENTRY = `./${RUNTIME_DIR}/${FEDERATION_FILE_NAME}.jsx`\n\ninterface DerivedInterfaceBase {\n /** CLI-minted for a local interface; a deployed one gets its id from Brett. */\n id: string\n moduleId: string\n name: string\n src: string\n title: string\n\n version: string\n}\n\n/** @internal */\nexport type DerivedInterface =\n | (DerivedInterfaceBase & {metadata: null; surface: 'asset_source'})\n | (DerivedInterfaceBase & {metadata: null; type: 'worker'})\n | (DerivedInterfaceBase & {metadata: TileInterfaceMetadata; surface: 'tile'})\n | (DerivedInterfaceBase & {metadata: ViewPlacementMetadata | null; surface: 'panel'})\n | (DerivedInterfaceBase & {metadata: ViewPlacementMetadata | null; surface: 'window'})\n\n/**\n * `appTitle` titles the window where a deploy resolved one through `--title`;\n * dev takes it from the config.\n * @internal\n */\nexport function deriveInterfaces(\n app: CliConfig['app'],\n {appTitle, isApp}: {appTitle?: string; isApp: boolean},\n): DerivedInterface[] {\n if (!isWorkbenchApp(app)) return []\n\n // The schema rejects a *declared* studio with an `entry`; `isApp` is resolved\n // from the project, so a detected one only fails here.\n if (!isApp && app.entry !== undefined) {\n throw new Error('App views for studios are not implemented yet')\n }\n const entry = isApp ? app.entry : GENERATED_ENTRY\n\n // Identity, not address: interface ids and the window name key on `name`\n // (which defaults to `slug`, so existing apps derive byte-identical ids).\n const appName = app.name ?? app.slug\n\n const shared = (\n kind: InterfaceKind,\n declaration: {name: string; src: string; title: string},\n ) => ({\n id: `${appName}-${kind}-${declaration.name}`,\n moduleId: interfaceModuleId(kind, declaration.name),\n name: declaration.name,\n src: declaration.src,\n title: declaration.title,\n version: interfaceContractVersion(kind),\n })\n\n const placementMetadata = (\n dock?: Dock,\n surface: (PanelView | WindowView)['surface'] = 'window',\n ): ViewPlacementMetadata | null => {\n const group = surface === 'panel' ? undefined : (dock?.group ?? app.dock?.group)\n const order = dock?.order ?? app.dock?.order\n if (group === undefined && order === undefined) return null\n return {\n dock: {\n ...(group === undefined ? {} : {group}),\n ...(order === undefined ? {} : {order}),\n },\n }\n }\n\n return [\n ...(app.views ?? []).map((view): DerivedInterface => {\n if (view.surface === 'tile') {\n return {\n ...shared(view.surface, view),\n metadata:\n view.order === undefined ? {size: view.size} : {order: view.order, size: view.size},\n surface: view.surface,\n }\n }\n if (view.surface === 'panel' || view.surface === 'window') {\n return {\n ...shared(view.surface, view),\n metadata: placementMetadata(view.dock, view.surface),\n surface: view.surface,\n }\n }\n return {...shared(view.surface, view), metadata: null, surface: view.surface}\n }),\n ...(app.webWorkers ?? []).map((webWorker): DerivedInterface => ({\n ...shared('worker', webWorker),\n metadata: null,\n type: 'worker',\n })),\n ...(entry === undefined\n ? []\n : [\n {\n ...shared('window', {name: appName, src: entry, title: appTitle ?? app.title}),\n metadata: placementMetadata(),\n surface: 'window' as const,\n },\n ]),\n ]\n}\n"],"names":["FEDERATION_FILE_NAME","RUNTIME_DIR","interfaceContractVersion","interfaceModuleId","isWorkbenchApp","GENERATED_ENTRY","deriveInterfaces","app","appTitle","isApp","entry","undefined","Error","appName","name","slug","shared","kind","declaration","id","moduleId","src","title","version","placementMetadata","dock","surface","group","order","views","map","view","metadata","size","webWorkers","webWorker","type"],"mappings":"AAEA,SAAQA,oBAAoB,EAAEC,WAAW,QAAO,oCAAmC;AACnF,SAEEC,wBAAwB,EAExBC,iBAAiB,QAKZ,gBAAe;AACtB,SAAQC,cAAc,QAAO,iBAAgB;AAE7C,4FAA4F,GAC5F,MAAMC,kBAAkB,CAAC,EAAE,EAAEJ,YAAY,CAAC,EAAED,qBAAqB,IAAI,CAAC;AAqBtE;;;;CAIC,GACD,OAAO,SAASM,iBACdC,GAAqB,EACrB,EAACC,QAAQ,EAAEC,KAAK,EAAsC;IAEtD,IAAI,CAACL,eAAeG,MAAM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AAOG,KAAKH,KAAK;wBAAEK,MAAMF,KAAKE,IAAI;oBAAA;oBACpFP,SAASK,KAAKL,OAAO;gBACvB;YACF;YACA,IAAIK,KAAKL,OAAO,KAAK,WAAWK,KAAKL,OAAO,KAAK,UAAU;gBACzD,OAAO;oBACL,GAAGV,OAAOe,KAAKL,OAAO,EAAEK,KAAK;oBAC7BC,UAAUR,kBAAkBO,KAAKN,IAAI,EAAEM,KAAKL,OAAO;oBACnDA,SAASK,KAAKL,OAAO;gBACvB;YACF;YACA,OAAO;gBAAC,GAAGV,OAAOe,KAAKL,OAAO,EAAEK,KAAK;gBAAEC,UAAU;gBAAMN,SAASK,KAAKL,OAAO;YAAA;QAC9E;WACG,AAACnB,CAAAA,IAAI2B,UAAU,IAAI,EAAE,AAAD,EAAGJ,GAAG,CAAC,CAACK,YAAiC,CAAA;gBAC9D,GAAGnB,OAAO,UAAUmB,UAAU;gBAC9BH,UAAU;gBACVI,MAAM;YACR,CAAA;WACI1B,UAAUC,YACV,EAAE,GACF;YACE;gBACE,GAAGK,OAAO,UAAU;oBAACF,MAAMD;oBAASQ,KAAKX;oBAAOY,OAAOd,YAAYD,IAAIe,KAAK;gBAAA,EAAE;gBAC9EU,UAAUR;gBACVE,SAAS;YACX;SACD;KACN;AACH"}
@@ -10,7 +10,7 @@ export async function renderDashboard(rootElement, config, options) {
10
10
  if (!rootElement) {
11
11
  throw new Error('Missing root element to mount application into');
12
12
  }
13
- const deployedDashboardHost = globalThis.__SANITY_STAGING__ === true ? 'workbench-apps-of5p8qpku.run.sanity.work' : 'workbench-apps-osyh1iet5.sanity.run';
13
+ const deployedDashboardHost = globalThis.__SANITY_STAGING__ === true ? 'workbench--apps--of5p8qpku.run.sanity.work' : 'workbench--apps--osyh1iet5.sanity.run';
14
14
  const remoteUrl = import.meta.env.SANITY_INTERNAL_WORKBENCH_REMOTE_URL ?? `https://${deployedDashboardHost}/mf-manifest.json`;
15
15
  const federation = createInstance({
16
16
  name: 'sanity-workbench',
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/renderDashboard.ts"],"sourcesContent":["/// <reference types=\"vite/client\" />\n\n// Keep this module browser-safe: Vite loads it directly in the generated dashboard runtime.\nimport {createInstance} from '@module-federation/runtime'\nimport {BehaviorSubject, type Observable} from 'rxjs'\n\ndeclare global {\n var __SANITY_STAGING__: boolean | undefined\n}\n\ninterface DashboardConfig {\n organizationId: string\n}\n\ninterface RenderDashboardOptions {\n reactStrictMode?: boolean\n}\n\ninterface DashboardRemoteModule {\n render: (\n rootElement: HTMLElement,\n props: {\n appConfigs?: Observable<unknown[]>\n config: DashboardConfig\n localApplications?: Observable<unknown[]>\n },\n options?: RenderDashboardOptions,\n ) => () => void\n}\n\nconst remoteName = 'workbench-remote'\nconst remoteModuleId = `${remoteName}/App`\nconst localApplicationsEvent = 'sanity:workbench:local-applications'\nconst noop = () => {}\n\nexport async function renderDashboard(\n rootElement: HTMLElement | null,\n config: DashboardConfig,\n options?: RenderDashboardOptions,\n): Promise<() => void> {\n if (!rootElement) {\n throw new Error('Missing root element to mount application into')\n }\n\n const deployedDashboardHost =\n globalThis.__SANITY_STAGING__ === true\n ? 'workbench-apps-of5p8qpku.run.sanity.work'\n : 'workbench-apps-osyh1iet5.sanity.run'\n const remoteUrl =\n import.meta.env.SANITY_INTERNAL_WORKBENCH_REMOTE_URL ??\n `https://${deployedDashboardHost}/mf-manifest.json`\n\n const federation = createInstance({\n name: 'sanity-workbench',\n remotes: [{entry: remoteUrl, name: remoteName}],\n })\n\n let remoteModule: DashboardRemoteModule | null\n try {\n remoteModule = await federation.loadRemote<DashboardRemoteModule>(remoteModuleId)\n } catch (error) {\n throw new Error(`Failed to load remote module \"${remoteModuleId}\"`, {cause: error})\n }\n\n if (!remoteModule || typeof remoteModule.render !== 'function') {\n throw new Error(`Remote module \"${remoteModuleId}\" did not expose a render function`)\n }\n\n let appConfigs: BehaviorSubject<unknown[]> | undefined\n let cleanupHmr = noop\n let localApplications: BehaviorSubject<unknown[]> | undefined\n\n if (import.meta.hot) {\n const hot = import.meta.hot\n const hmrLocalApplications = new BehaviorSubject<unknown[]>([])\n const hmrAppConfigs = new BehaviorSubject<unknown[]>([])\n const handler = (payload: {applications: unknown[]; configs?: unknown[]}) => {\n hmrLocalApplications.next(payload.applications)\n hmrAppConfigs.next(payload.configs ?? [])\n }\n\n localApplications = hmrLocalApplications\n appConfigs = hmrAppConfigs\n hot.on(localApplicationsEvent, handler)\n hot.send('sanity:workbench:get-local-applications')\n cleanupHmr = () => hot.off(localApplicationsEvent, handler)\n }\n\n const unmount = remoteModule.render(rootElement, {appConfigs, config, localApplications}, options)\n\n return () => {\n cleanupHmr()\n unmount()\n }\n}\n"],"names":["createInstance","BehaviorSubject","remoteName","remoteModuleId","localApplicationsEvent","noop","renderDashboard","rootElement","config","options","Error","deployedDashboardHost","globalThis","__SANITY_STAGING__","remoteUrl","env","SANITY_INTERNAL_WORKBENCH_REMOTE_URL","federation","name","remotes","entry","remoteModule","loadRemote","error","cause","render","appConfigs","cleanupHmr","localApplications","hot","hmrLocalApplications","hmrAppConfigs","handler","payload","next","applications","configs","on","send","off","unmount"],"mappings":"AAAA,qCAAqC;AAErC,4FAA4F;AAC5F,SAAQA,cAAc,QAAO,6BAA4B;AACzD,SAAQC,eAAe,QAAwB,OAAM;AA0BrD,MAAMC,aAAa;AACnB,MAAMC,iBAAiB,GAAGD,WAAW,IAAI,CAAC;AAC1C,MAAME,yBAAyB;AAC/B,MAAMC,OAAO,KAAO;AAEpB,OAAO,eAAeC,gBACpBC,WAA+B,EAC/BC,MAAuB,EACvBC,OAAgC;IAEhC,IAAI,CAACF,aAAa;QAChB,MAAM,IAAIG,MAAM;IAClB;IAEA,MAAMC,wBACJC,WAAWC,kBAAkB,KAAK,OAC9B,6CACA;IACN,MAAMC,YACJ,YAAYC,GAAG,CAACC,oCAAoC,IACpD,CAAC,QAAQ,EAAEL,sBAAsB,iBAAiB,CAAC;IAErD,MAAMM,aAAajB,eAAe;QAChCkB,MAAM;QACNC,SAAS;YAAC;gBAACC,OAAON;gBAAWI,MAAMhB;YAAU;SAAE;IACjD;IAEA,IAAImB;IACJ,IAAI;QACFA,eAAe,MAAMJ,WAAWK,UAAU,CAAwBnB;IACpE,EAAE,OAAOoB,OAAO;QACd,MAAM,IAAIb,MAAM,CAAC,8BAA8B,EAAEP,eAAe,CAAC,CAAC,EAAE;YAACqB,OAAOD;QAAK;IACnF;IAEA,IAAI,CAACF,gBAAgB,OAAOA,aAAaI,MAAM,KAAK,YAAY;QAC9D,MAAM,IAAIf,MAAM,CAAC,eAAe,EAAEP,eAAe,kCAAkC,CAAC;IACtF;IAEA,IAAIuB;IACJ,IAAIC,aAAatB;IACjB,IAAIuB;IAEJ,IAAI,YAAYC,GAAG,EAAE;QACnB,MAAMA,MAAM,YAAYA,GAAG;QAC3B,MAAMC,uBAAuB,IAAI7B,gBAA2B,EAAE;QAC9D,MAAM8B,gBAAgB,IAAI9B,gBAA2B,EAAE;QACvD,MAAM+B,UAAU,CAACC;YACfH,qBAAqBI,IAAI,CAACD,QAAQE,YAAY;YAC9CJ,cAAcG,IAAI,CAACD,QAAQG,OAAO,IAAI,EAAE;QAC1C;QAEAR,oBAAoBE;QACpBJ,aAAaK;QACbF,IAAIQ,EAAE,CAACjC,wBAAwB4B;QAC/BH,IAAIS,IAAI,CAAC;QACTX,aAAa,IAAME,IAAIU,GAAG,CAACnC,wBAAwB4B;IACrD;IAEA,MAAMQ,UAAUnB,aAAaI,MAAM,CAAClB,aAAa;QAACmB;QAAYlB;QAAQoB;IAAiB,GAAGnB;IAE1F,OAAO;QACLkB;QACAa;IACF;AACF"}
1
+ {"version":3,"sources":["../src/renderDashboard.ts"],"sourcesContent":["/// <reference types=\"vite/client\" />\n\n// Keep this module browser-safe: Vite loads it directly in the generated dashboard runtime.\nimport {createInstance} from '@module-federation/runtime'\nimport {BehaviorSubject, type Observable} from 'rxjs'\n\ndeclare global {\n var __SANITY_STAGING__: boolean | undefined\n}\n\ninterface DashboardConfig {\n organizationId: string\n}\n\ninterface RenderDashboardOptions {\n reactStrictMode?: boolean\n}\n\ninterface DashboardRemoteModule {\n render: (\n rootElement: HTMLElement,\n props: {\n appConfigs?: Observable<unknown[]>\n config: DashboardConfig\n localApplications?: Observable<unknown[]>\n },\n options?: RenderDashboardOptions,\n ) => () => void\n}\n\nconst remoteName = 'workbench-remote'\nconst remoteModuleId = `${remoteName}/App`\nconst localApplicationsEvent = 'sanity:workbench:local-applications'\nconst noop = () => {}\n\nexport async function renderDashboard(\n rootElement: HTMLElement | null,\n config: DashboardConfig,\n options?: RenderDashboardOptions,\n): Promise<() => void> {\n if (!rootElement) {\n throw new Error('Missing root element to mount application into')\n }\n\n const deployedDashboardHost =\n globalThis.__SANITY_STAGING__ === true\n ? 'workbench--apps--of5p8qpku.run.sanity.work'\n : 'workbench--apps--osyh1iet5.sanity.run'\n const remoteUrl =\n import.meta.env.SANITY_INTERNAL_WORKBENCH_REMOTE_URL ??\n `https://${deployedDashboardHost}/mf-manifest.json`\n\n const federation = createInstance({\n name: 'sanity-workbench',\n remotes: [{entry: remoteUrl, name: remoteName}],\n })\n\n let remoteModule: DashboardRemoteModule | null\n try {\n remoteModule = await federation.loadRemote<DashboardRemoteModule>(remoteModuleId)\n } catch (error) {\n throw new Error(`Failed to load remote module \"${remoteModuleId}\"`, {cause: error})\n }\n\n if (!remoteModule || typeof remoteModule.render !== 'function') {\n throw new Error(`Remote module \"${remoteModuleId}\" did not expose a render function`)\n }\n\n let appConfigs: BehaviorSubject<unknown[]> | undefined\n let cleanupHmr = noop\n let localApplications: BehaviorSubject<unknown[]> | undefined\n\n if (import.meta.hot) {\n const hot = import.meta.hot\n const hmrLocalApplications = new BehaviorSubject<unknown[]>([])\n const hmrAppConfigs = new BehaviorSubject<unknown[]>([])\n const handler = (payload: {applications: unknown[]; configs?: unknown[]}) => {\n hmrLocalApplications.next(payload.applications)\n hmrAppConfigs.next(payload.configs ?? [])\n }\n\n localApplications = hmrLocalApplications\n appConfigs = hmrAppConfigs\n hot.on(localApplicationsEvent, handler)\n hot.send('sanity:workbench:get-local-applications')\n cleanupHmr = () => hot.off(localApplicationsEvent, handler)\n }\n\n const unmount = remoteModule.render(rootElement, {appConfigs, config, localApplications}, options)\n\n return () => {\n cleanupHmr()\n unmount()\n }\n}\n"],"names":["createInstance","BehaviorSubject","remoteName","remoteModuleId","localApplicationsEvent","noop","renderDashboard","rootElement","config","options","Error","deployedDashboardHost","globalThis","__SANITY_STAGING__","remoteUrl","env","SANITY_INTERNAL_WORKBENCH_REMOTE_URL","federation","name","remotes","entry","remoteModule","loadRemote","error","cause","render","appConfigs","cleanupHmr","localApplications","hot","hmrLocalApplications","hmrAppConfigs","handler","payload","next","applications","configs","on","send","off","unmount"],"mappings":"AAAA,qCAAqC;AAErC,4FAA4F;AAC5F,SAAQA,cAAc,QAAO,6BAA4B;AACzD,SAAQC,eAAe,QAAwB,OAAM;AA0BrD,MAAMC,aAAa;AACnB,MAAMC,iBAAiB,GAAGD,WAAW,IAAI,CAAC;AAC1C,MAAME,yBAAyB;AAC/B,MAAMC,OAAO,KAAO;AAEpB,OAAO,eAAeC,gBACpBC,WAA+B,EAC/BC,MAAuB,EACvBC,OAAgC;IAEhC,IAAI,CAACF,aAAa;QAChB,MAAM,IAAIG,MAAM;IAClB;IAEA,MAAMC,wBACJC,WAAWC,kBAAkB,KAAK,OAC9B,+CACA;IACN,MAAMC,YACJ,YAAYC,GAAG,CAACC,oCAAoC,IACpD,CAAC,QAAQ,EAAEL,sBAAsB,iBAAiB,CAAC;IAErD,MAAMM,aAAajB,eAAe;QAChCkB,MAAM;QACNC,SAAS;YAAC;gBAACC,OAAON;gBAAWI,MAAMhB;YAAU;SAAE;IACjD;IAEA,IAAImB;IACJ,IAAI;QACFA,eAAe,MAAMJ,WAAWK,UAAU,CAAwBnB;IACpE,EAAE,OAAOoB,OAAO;QACd,MAAM,IAAIb,MAAM,CAAC,8BAA8B,EAAEP,eAAe,CAAC,CAAC,EAAE;YAACqB,OAAOD;QAAK;IACnF;IAEA,IAAI,CAACF,gBAAgB,OAAOA,aAAaI,MAAM,KAAK,YAAY;QAC9D,MAAM,IAAIf,MAAM,CAAC,eAAe,EAAEP,eAAe,kCAAkC,CAAC;IACtF;IAEA,IAAIuB;IACJ,IAAIC,aAAatB;IACjB,IAAIuB;IAEJ,IAAI,YAAYC,GAAG,EAAE;QACnB,MAAMA,MAAM,YAAYA,GAAG;QAC3B,MAAMC,uBAAuB,IAAI7B,gBAA2B,EAAE;QAC9D,MAAM8B,gBAAgB,IAAI9B,gBAA2B,EAAE;QACvD,MAAM+B,UAAU,CAACC;YACfH,qBAAqBI,IAAI,CAACD,QAAQE,YAAY;YAC9CJ,cAAcG,IAAI,CAACD,QAAQG,OAAO,IAAI,EAAE;QAC1C;QAEAR,oBAAoBE;QACpBJ,aAAaK;QACbF,IAAIQ,EAAE,CAACjC,wBAAwB4B;QAC/BH,IAAIS,IAAI,CAAC;QACTX,aAAa,IAAME,IAAIU,GAAG,CAACnC,wBAAwB4B;IACrD;IAEA,MAAMQ,UAAUnB,aAAaI,MAAM,CAAClB,aAAa;QAACmB;QAAYlB;QAAQoB;IAAiB,GAAGnB;IAE1F,OAAO;QACLkB;QACAa;IACF;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sanity/workbench-cli",
3
- "version": "2.16.0",
3
+ "version": "2.17.0",
4
4
  "description": "Internal implementation detail of the Sanity CLI's unstable workbench support. Not intended for direct use.",
5
5
  "homepage": "https://github.com/sanity-io/cli",
6
6
  "bugs": "https://github.com/sanity-io/cli/issues",
@@ -66,15 +66,15 @@
66
66
  },
67
67
  "dependencies": {
68
68
  "@module-federation/runtime": "2.9.3",
69
- "@module-federation/vite": "1.23.11",
70
- "@sanity/cli-core": "^3.15.0",
69
+ "@module-federation/vite": "1.24.0",
70
+ "@sanity/cli-core": "^3.15.1",
71
71
  "@sanity/sdk": "^3.12.0",
72
72
  "@sanity/types": "^6.22.0",
73
73
  "@vitejs/plugin-react": "^6.3.0",
74
- "form-data": "^4.0.5",
74
+ "form-data": "^4.0.6",
75
75
  "rxjs": "^7.8.2",
76
76
  "semver": "^7.8.6",
77
- "tar": "^7.5.22",
77
+ "tar": "^7.5.23",
78
78
  "vite": "^8.3.8",
79
79
  "zod": "^4.6.7"
80
80
  },
@@ -82,7 +82,7 @@
82
82
  "@eslint/compat": "^2.1.0",
83
83
  "@repo/package.config": "0.0.1",
84
84
  "@repo/tsconfig": "3.70.0",
85
- "@sanity/cli-test": "25.0.0",
85
+ "@sanity/cli-test": "25.0.1",
86
86
  "@sanity/eslint-config-cli": "^1.1.3",
87
87
  "@sanity/pkg-utils": "^12.3.4",
88
88
  "@swc/cli": "^0.8.2",
@@ -94,8 +94,8 @@
94
94
  "eslint": "^10.7.0",
95
95
  "jsdom": "^29.1.1",
96
96
  "publint": "^0.3.21",
97
- "react": "^19.3.0",
98
- "react-dom": "^19.3.0",
97
+ "react": "^19.3.1",
98
+ "react-dom": "^19.3.1",
99
99
  "typescript": "^6.0.3",
100
100
  "vitest": "^5.1.0"
101
101
  },