@sanity/workbench-cli 2.15.0 → 2.15.1
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.
- package/dist/actions/build/configs/mediaLibraryIslandRuntime.js +2 -3
- package/dist/actions/build/configs/mediaLibraryIslandRuntime.js.map +1 -1
- package/dist/actions/build/render-remote.js +1 -0
- package/dist/actions/build/render-remote.js.map +1 -1
- package/dist/actions/build/vite/plugins/plugin-sanity-app-styles.js +61 -0
- package/dist/actions/build/vite/plugins/plugin-sanity-app-styles.js.map +1 -0
- package/dist/actions/build/vite/workbench-vite-plugins.js +3 -1
- package/dist/actions/build/vite/workbench-vite-plugins.js.map +1 -1
- package/dist/actions/dev/registry.js +10 -5
- package/dist/actions/dev/registry.js.map +1 -1
- package/dist/actions/dev/startDevServerRegistration.js +3 -1
- package/dist/actions/dev/startDevServerRegistration.js.map +1 -1
- package/dist/actions/preview/startWorkbenchPreview.js +3 -1
- package/dist/actions/preview/startWorkbenchPreview.js.map +1 -1
- package/dist/defineApp.js +4 -1
- package/dist/defineApp.js.map +1 -1
- package/package.json +10 -10
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import path from 'node:path';
|
|
1
|
+
import { resolveLocalPackagePath } from '@sanity/cli-core';
|
|
3
2
|
/**
|
|
4
3
|
* The `sanity` package entry carrying the Media Library island-mount runtime
|
|
5
4
|
* (`mountIsland`). The generated `./media-library-island-runtime` federation
|
|
@@ -15,7 +14,7 @@ import path from 'node:path';
|
|
|
15
14
|
* for custom inputs.
|
|
16
15
|
*/ export function hasMediaLibraryIslandRuntime(appRoot) {
|
|
17
16
|
try {
|
|
18
|
-
|
|
17
|
+
resolveLocalPackagePath(MEDIA_LIBRARY_ISLAND_RUNTIME_MODULE, appRoot);
|
|
19
18
|
return true;
|
|
20
19
|
} catch {
|
|
21
20
|
return false;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/actions/build/configs/mediaLibraryIslandRuntime.ts"],"sourcesContent":["import {
|
|
1
|
+
{"version":3,"sources":["../../../../src/actions/build/configs/mediaLibraryIslandRuntime.ts"],"sourcesContent":["import {resolveLocalPackagePath} from '@sanity/cli-core'\n\n/**\n * The `sanity` package entry carrying the Media Library island-mount runtime\n * (`mountIsland`). The generated `./media-library-island-runtime` federation\n * expose re-exports it, so the runtime is bundled into the config app's\n * remote from the app's own `sanity` install — whichever version the app\n * installs brings a matching runtime.\n */\nexport const MEDIA_LIBRARY_ISLAND_RUNTIME_MODULE = 'sanity/media-library-island-runtime'\n\n/**\n * Whether the config app's installed `sanity` ships the island runtime entry.\n * Older `sanity` versions don't; exposing a module whose import can never\n * resolve would fail the whole build, so the expose is skipped (with a\n * warning) and the Media Library host falls back to its degraded rendering\n * for custom inputs.\n */\nexport function hasMediaLibraryIslandRuntime(appRoot: string): boolean {\n try {\n resolveLocalPackagePath(MEDIA_LIBRARY_ISLAND_RUNTIME_MODULE, appRoot)\n return true\n } catch {\n return false\n }\n}\n"],"names":["resolveLocalPackagePath","MEDIA_LIBRARY_ISLAND_RUNTIME_MODULE","hasMediaLibraryIslandRuntime","appRoot"],"mappings":"AAAA,SAAQA,uBAAuB,QAAO,mBAAkB;AAExD;;;;;;CAMC,GACD,OAAO,MAAMC,sCAAsC,sCAAqC;AAExF;;;;;;CAMC,GACD,OAAO,SAASC,6BAA6BC,OAAe;IAC1D,IAAI;QACFH,wBAAwBC,qCAAqCE;QAC7D,OAAO;IACT,EAAE,OAAM;QACN,OAAO;IACT;AACF"}
|
|
@@ -73,6 +73,7 @@ function mount(rootElement, args) {
|
|
|
73
73
|
rootContexts.set(rootElement, { controller, value: { signal: controller.signal, moduleId, parentKey } })
|
|
74
74
|
if (StyleSheetManager) {
|
|
75
75
|
const target = rootElement.ownerDocument.createElement('sanity-styles')
|
|
76
|
+
if (typeof __SANITY_APP_ID__ === 'string') target.setAttribute('data-application-id', __SANITY_APP_ID__)
|
|
76
77
|
// React can replace the mount node's contents; keep its stylesheet outside that node.
|
|
77
78
|
rootElement.ownerDocument.head.appendChild(target)
|
|
78
79
|
styleTargets.set(rootElement, target)
|
|
@@ -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/service contract compatibility.\n */\nexport function renderRemote({\n app,\n hmr = false,\n isolateStyles = false,\n preamble,\n version,\n}: {\n app?: string\n hmr?: boolean\n isolateStyles?: boolean\n preamble: string\n version?: 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 } })\n if (StyleSheetManager) {\n const target = rootElement.ownerDocument.createElement('sanity-styles')\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 let element = React.createElement(RootContext.Provider, { value: rootContexts.get(rootElement).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","stylesheetImport"],"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,EAOR;IACC,iGAAiG;IACjG,MAAMC,mBAAmBH,gBACrB,0DACA;IAEJ,OAAO,CAAC;;;;;AAKV,EAAEG,iBAAiB;AACnB,EAAEF,SAAS;AACX,EAAEH,MAAM,CAAC,cAAc,EAAEA,IAAI,EAAE,CAAC,GAAG,KAAKI,UAAU,CAAC,yBAAyB,EAAEA,QAAQ,EAAE,CAAC,GAAG,GAAG
|
|
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/service contract compatibility.\n */\nexport function renderRemote({\n app,\n hmr = false,\n isolateStyles = false,\n preamble,\n version,\n}: {\n app?: string\n hmr?: boolean\n isolateStyles?: boolean\n preamble: string\n version?: 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 } })\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 let element = React.createElement(RootContext.Provider, { value: rootContexts.get(rootElement).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","stylesheetImport"],"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,EAOR;IACC,iGAAiG;IACjG,MAAMC,mBAAmBH,gBACrB,0DACA;IAEJ,OAAO,CAAC;;;;;AAKV,EAAEG,iBAAiB;AACnB,EAAEF,SAAS;AACX,EAAEH,MAAM,CAAC,cAAc,EAAEA,IAAI,EAAE,CAAC,GAAG,KAAKI,UAAU,CAAC,yBAAyB,EAAEA,QAAQ,EAAE,CAAC,GAAG,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAoF9F,EAAEH,MAAM,CAAC,IAAI,EAAEH,aAAa,GAAG,GAAG;AACnC,CAAC;AACD"}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
const APP_ID_ATTRIBUTE = JSON.stringify('data-application-id');
|
|
2
|
+
/**
|
|
3
|
+
* Tag every stylesheet element the app's own bundle inserts with the app id,
|
|
4
|
+
* so Workbench can switch an app's CSS off while the app is off stage.
|
|
5
|
+
*/ export function sanityAppStyles(appId) {
|
|
6
|
+
const id = JSON.stringify(appId);
|
|
7
|
+
const tagged = (create)=>`((el) => (el.setAttribute(${APP_ID_ATTRIBUTE}, ${id}), el))(${create})`;
|
|
8
|
+
const owned = (element)=>`${element}.getAttribute(${APP_ID_ATTRIBUTE}) === ${id}`;
|
|
9
|
+
const inserters = [
|
|
10
|
+
{
|
|
11
|
+
edits: [
|
|
12
|
+
[
|
|
13
|
+
'document.createElement("link")',
|
|
14
|
+
tagged('document.createElement("link")')
|
|
15
|
+
],
|
|
16
|
+
[
|
|
17
|
+
'link.rel === "stylesheet"',
|
|
18
|
+
`link.rel === "stylesheet" && ${owned('link')}`
|
|
19
|
+
]
|
|
20
|
+
],
|
|
21
|
+
id: /^\0vite\/preload-helper\.js$/
|
|
22
|
+
},
|
|
23
|
+
{
|
|
24
|
+
edits: [
|
|
25
|
+
[
|
|
26
|
+
'document.createElement("style")',
|
|
27
|
+
tagged('document.createElement("style")')
|
|
28
|
+
],
|
|
29
|
+
[
|
|
30
|
+
'document.querySelectorAll("style[data-vite-dev-id]")',
|
|
31
|
+
`Array.from(document.querySelectorAll("style[data-vite-dev-id]")).filter((el) => ${owned('el')})`
|
|
32
|
+
]
|
|
33
|
+
],
|
|
34
|
+
id: /\/vite\/dist\/client\/client\.mjs$/
|
|
35
|
+
}
|
|
36
|
+
];
|
|
37
|
+
return {
|
|
38
|
+
name: 'sanity/workbench/app-styles',
|
|
39
|
+
transform: {
|
|
40
|
+
filter: {
|
|
41
|
+
id: inserters.map((inserter)=>inserter.id)
|
|
42
|
+
},
|
|
43
|
+
handler (code, moduleId) {
|
|
44
|
+
const { edits } = inserters.find((inserter)=>inserter.id.test(moduleId));
|
|
45
|
+
let result = code;
|
|
46
|
+
for (const [anchor, replacement] of edits){
|
|
47
|
+
if (!result.includes(anchor)) {
|
|
48
|
+
this.error(`Could not find \`${anchor}\` in ${moduleId} to tag the app's stylesheets`);
|
|
49
|
+
}
|
|
50
|
+
result = result.replaceAll(anchor, replacement);
|
|
51
|
+
}
|
|
52
|
+
return {
|
|
53
|
+
code: result,
|
|
54
|
+
map: null
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
//# sourceMappingURL=plugin-sanity-app-styles.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../src/actions/build/vite/plugins/plugin-sanity-app-styles.ts"],"sourcesContent":["import {type Plugin} from 'vite'\n\nconst APP_ID_ATTRIBUTE = JSON.stringify('data-application-id')\n\n/**\n * Tag every stylesheet element the app's own bundle inserts with the app id,\n * so Workbench can switch an app's CSS off while the app is off stage.\n */\nexport function sanityAppStyles(appId: string): Plugin {\n const id = JSON.stringify(appId)\n const tagged = (create: string) =>\n `((el) => (el.setAttribute(${APP_ID_ATTRIBUTE}, ${id}), el))(${create})`\n const owned = (element: string) => `${element}.getAttribute(${APP_ID_ATTRIBUTE}) === ${id}`\n\n const inserters = [\n {\n edits: [\n ['document.createElement(\"link\")', tagged('document.createElement(\"link\")')],\n ['link.rel === \"stylesheet\"', `link.rel === \"stylesheet\" && ${owned('link')}`],\n ],\n id: /^\\0vite\\/preload-helper\\.js$/,\n },\n {\n edits: [\n ['document.createElement(\"style\")', tagged('document.createElement(\"style\")')],\n [\n 'document.querySelectorAll(\"style[data-vite-dev-id]\")',\n `Array.from(document.querySelectorAll(\"style[data-vite-dev-id]\")).filter((el) => ${owned('el')})`,\n ],\n ],\n id: /\\/vite\\/dist\\/client\\/client\\.mjs$/,\n },\n ]\n\n return {\n name: 'sanity/workbench/app-styles',\n transform: {\n filter: {id: inserters.map((inserter) => inserter.id)},\n handler(code, moduleId) {\n const {edits} = inserters.find((inserter) => inserter.id.test(moduleId))!\n let result = code\n for (const [anchor, replacement] of edits) {\n if (!result.includes(anchor)) {\n this.error(`Could not find \\`${anchor}\\` in ${moduleId} to tag the app's stylesheets`)\n }\n result = result.replaceAll(anchor, replacement)\n }\n return {code: result, map: null}\n },\n },\n }\n}\n"],"names":["APP_ID_ATTRIBUTE","JSON","stringify","sanityAppStyles","appId","id","tagged","create","owned","element","inserters","edits","name","transform","filter","map","inserter","handler","code","moduleId","find","test","result","anchor","replacement","includes","error","replaceAll"],"mappings":"AAEA,MAAMA,mBAAmBC,KAAKC,SAAS,CAAC;AAExC;;;CAGC,GACD,OAAO,SAASC,gBAAgBC,KAAa;IAC3C,MAAMC,KAAKJ,KAAKC,SAAS,CAACE;IAC1B,MAAME,SAAS,CAACC,SACd,CAAC,0BAA0B,EAAEP,iBAAiB,EAAE,EAAEK,GAAG,QAAQ,EAAEE,OAAO,CAAC,CAAC;IAC1E,MAAMC,QAAQ,CAACC,UAAoB,GAAGA,QAAQ,cAAc,EAAET,iBAAiB,MAAM,EAAEK,IAAI;IAE3F,MAAMK,YAAY;QAChB;YACEC,OAAO;gBACL;oBAAC;oBAAkCL,OAAO;iBAAkC;gBAC5E;oBAAC;oBAA6B,CAAC,6BAA6B,EAAEE,MAAM,SAAS;iBAAC;aAC/E;YACDH,IAAI;QACN;QACA;YACEM,OAAO;gBACL;oBAAC;oBAAmCL,OAAO;iBAAmC;gBAC9E;oBACE;oBACA,CAAC,gFAAgF,EAAEE,MAAM,MAAM,CAAC,CAAC;iBAClG;aACF;YACDH,IAAI;QACN;KACD;IAED,OAAO;QACLO,MAAM;QACNC,WAAW;YACTC,QAAQ;gBAACT,IAAIK,UAAUK,GAAG,CAAC,CAACC,WAAaA,SAASX,EAAE;YAAC;YACrDY,SAAQC,IAAI,EAAEC,QAAQ;gBACpB,MAAM,EAACR,KAAK,EAAC,GAAGD,UAAUU,IAAI,CAAC,CAACJ,WAAaA,SAASX,EAAE,CAACgB,IAAI,CAACF;gBAC9D,IAAIG,SAASJ;gBACb,KAAK,MAAM,CAACK,QAAQC,YAAY,IAAIb,MAAO;oBACzC,IAAI,CAACW,OAAOG,QAAQ,CAACF,SAAS;wBAC5B,IAAI,CAACG,KAAK,CAAC,CAAC,iBAAiB,EAAEH,OAAO,MAAM,EAAEJ,SAAS,6BAA6B,CAAC;oBACvF;oBACAG,SAASA,OAAOK,UAAU,CAACJ,QAAQC;gBACrC;gBACA,OAAO;oBAACN,MAAMI;oBAAQP,KAAK;gBAAI;YACjC;QACF;IACF;AACF"}
|
|
@@ -9,6 +9,7 @@ import { readPackageJson } from '@sanity/cli-core';
|
|
|
9
9
|
import { isMediaLibraryConfigApp } from '../configs/configApp.js';
|
|
10
10
|
import { federation } from './plugin.js';
|
|
11
11
|
import { sanityAppId } from './plugins/plugin-sanity-app-id.js';
|
|
12
|
+
import { sanityAppStyles } from './plugins/plugin-sanity-app-styles.js';
|
|
12
13
|
import { stripSuiGlobalReset } from './plugins/plugin-strip-sui-global-reset.js';
|
|
13
14
|
/**
|
|
14
15
|
* A workbench studio renders from its `sanity.config.*`, so the build needs one.
|
|
@@ -55,7 +56,8 @@ import { stripSuiGlobalReset } from './plugins/plugin-strip-sui-global-reset.js'
|
|
|
55
56
|
...configAppPlugins,
|
|
56
57
|
federationPlugin,
|
|
57
58
|
...appId === undefined ? [] : [
|
|
58
|
-
sanityAppId(appId)
|
|
59
|
+
sanityAppId(appId),
|
|
60
|
+
sanityAppStyles(appId)
|
|
59
61
|
]
|
|
60
62
|
];
|
|
61
63
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/actions/build/vite/workbench-vite-plugins.ts"],"sourcesContent":["// The build-facing entry of the workbench federation stack: turn a workbench\n// app's build inputs into the Vite plugins that produce its module-federation\n// remote. `@sanity/cli-build`'s `getViteConfig` calls this instead of\n// assembling `federation`'s options itself, so the discriminated app-vs-studio\n// option shape, the no-app-view rule, and the studio-config requirement all\n// live here next to `federation` — the build package just hands over its inputs.\n\nimport path from 'node:path'\n\nimport {readPackageJson} from '@sanity/cli-core'\nimport {type PluginOption} from 'vite'\n\nimport {type WorkbenchExposes} from '../../../resolveWorkbenchApp.js'\nimport {isMediaLibraryConfigApp} from '../configs/configApp.js'\nimport {federation} from './plugin.js'\nimport {sanityAppId} from './plugins/plugin-sanity-app-id.js'\nimport {type AutoUpdates} from './plugins/plugin-sanity-auto-updates.js'\nimport {stripSuiGlobalReset} from './plugins/plugin-strip-sui-global-reset.js'\n\ninterface WorkbenchViteOptions {\n /** Project root — read for the federation remote name, and the plugin workDir. */\n cwd: string\n /**\n * Build entry paths relative to the federation runtime dir. `relativeEntry` is\n * the app's `entry` (null for a dock-only app with no app view);\n * `relativeConfigLocation` is the studio's `sanity.config.*` (null when absent).\n */\n entries: {relativeConfigLocation: string | null; relativeEntry: string | null}\n\n /** The app's bus identity, stamped into its modules for `@sanity/runtime`. */\n appId?: string\n\n autoUpdates?: AutoUpdates\n exposes?: WorkbenchExposes\n /** App (vs studio) build — selects the discriminated federation option shape. */\n isApp?: boolean\n /** Blueprints build (via `@sanity/runtime-cli`) — emit the resource-bindings module. */\n isBlueprints?: boolean\n}\n\n/**\n * A workbench studio renders from its `sanity.config.*`, so the build needs one.\n * An explicit `applicationType: 'studio'` wins over detection, so a studio can\n * reach here with no config file — fail with the fix rather than a cryptic build\n * error downstream.\n */\nfunction requireStudioConfigPath(relativeConfigLocation: string | null): string {\n if (relativeConfigLocation === null) {\n throw new Error(\n 'Dashboard studios need a sanity.config.js or sanity.config.ts file. ' +\n \"Add one, or remove `applicationType: 'studio'` from `defineApplication` \" +\n 'to let the CLI infer the application type.',\n )\n }\n return relativeConfigLocation\n}\n\n/** Build the Vite plugins for a workbench app's module-federation remote. */\nexport async function workbenchVitePlugins(options: WorkbenchViteOptions): Promise<PluginOption> {\n const {appId, autoUpdates, cwd, entries, exposes, isApp, isBlueprints} = options\n if (autoUpdates && appId === undefined) {\n throw new Error('An auto-updating workbench app needs an app ID')\n }\n\n const pkgJson = await readPackageJson(path.join(cwd, 'package.json'))\n\n const federationPlugin = federation({\n ...(isApp\n ? {\n // `null` relativeEntry (a branded app with no `entry`) → omit `appEntry`,\n // so the remote exposes no `./App`, only its views.\n ...(entries.relativeEntry ? {appEntry: entries.relativeEntry} : {}),\n isApp: true as const,\n }\n : {\n isApp: false as const,\n studioConfigPath: requireStudioConfigPath(entries.relativeConfigLocation),\n }),\n autoUpdates,\n exposes,\n isBlueprints,\n pkgJson,\n workDir: cwd,\n })\n\n // Media Library config apps run their modules inside the host's page, so\n // the `sanity` barrel's document-wide CSS reset must not travel with the\n // bundle (see the plugin for the full why).\n const configAppPlugins: PluginOption[] = isMediaLibraryConfigApp(exposes)\n ? [stripSuiGlobalReset()]\n : []\n\n return [\n ...configAppPlugins,\n federationPlugin,\n ...(appId === undefined ? [] : [sanityAppId(appId)]),\n ]\n}\n"],"names":["path","readPackageJson","isMediaLibraryConfigApp","federation","sanityAppId","stripSuiGlobalReset","requireStudioConfigPath","relativeConfigLocation","Error","workbenchVitePlugins","options","appId","autoUpdates","cwd","entries","exposes","isApp","isBlueprints","undefined","pkgJson","join","federationPlugin","relativeEntry","appEntry","studioConfigPath","workDir","configAppPlugins"],"mappings":"AAAA,6EAA6E;AAC7E,8EAA8E;AAC9E,sEAAsE;AACtE,+EAA+E;AAC/E,4EAA4E;AAC5E,iFAAiF;AAEjF,OAAOA,UAAU,YAAW;AAE5B,SAAQC,eAAe,QAAO,mBAAkB;AAIhD,SAAQC,uBAAuB,QAAO,0BAAyB;AAC/D,SAAQC,UAAU,QAAO,cAAa;AACtC,SAAQC,WAAW,QAAO,oCAAmC;
|
|
1
|
+
{"version":3,"sources":["../../../../src/actions/build/vite/workbench-vite-plugins.ts"],"sourcesContent":["// The build-facing entry of the workbench federation stack: turn a workbench\n// app's build inputs into the Vite plugins that produce its module-federation\n// remote. `@sanity/cli-build`'s `getViteConfig` calls this instead of\n// assembling `federation`'s options itself, so the discriminated app-vs-studio\n// option shape, the no-app-view rule, and the studio-config requirement all\n// live here next to `federation` — the build package just hands over its inputs.\n\nimport path from 'node:path'\n\nimport {readPackageJson} from '@sanity/cli-core'\nimport {type PluginOption} from 'vite'\n\nimport {type WorkbenchExposes} from '../../../resolveWorkbenchApp.js'\nimport {isMediaLibraryConfigApp} from '../configs/configApp.js'\nimport {federation} from './plugin.js'\nimport {sanityAppId} from './plugins/plugin-sanity-app-id.js'\nimport {sanityAppStyles} from './plugins/plugin-sanity-app-styles.js'\nimport {type AutoUpdates} from './plugins/plugin-sanity-auto-updates.js'\nimport {stripSuiGlobalReset} from './plugins/plugin-strip-sui-global-reset.js'\n\ninterface WorkbenchViteOptions {\n /** Project root — read for the federation remote name, and the plugin workDir. */\n cwd: string\n /**\n * Build entry paths relative to the federation runtime dir. `relativeEntry` is\n * the app's `entry` (null for a dock-only app with no app view);\n * `relativeConfigLocation` is the studio's `sanity.config.*` (null when absent).\n */\n entries: {relativeConfigLocation: string | null; relativeEntry: string | null}\n\n /** The app's bus identity, stamped into its modules for `@sanity/runtime`. */\n appId?: string\n\n autoUpdates?: AutoUpdates\n exposes?: WorkbenchExposes\n /** App (vs studio) build — selects the discriminated federation option shape. */\n isApp?: boolean\n /** Blueprints build (via `@sanity/runtime-cli`) — emit the resource-bindings module. */\n isBlueprints?: boolean\n}\n\n/**\n * A workbench studio renders from its `sanity.config.*`, so the build needs one.\n * An explicit `applicationType: 'studio'` wins over detection, so a studio can\n * reach here with no config file — fail with the fix rather than a cryptic build\n * error downstream.\n */\nfunction requireStudioConfigPath(relativeConfigLocation: string | null): string {\n if (relativeConfigLocation === null) {\n throw new Error(\n 'Dashboard studios need a sanity.config.js or sanity.config.ts file. ' +\n \"Add one, or remove `applicationType: 'studio'` from `defineApplication` \" +\n 'to let the CLI infer the application type.',\n )\n }\n return relativeConfigLocation\n}\n\n/** Build the Vite plugins for a workbench app's module-federation remote. */\nexport async function workbenchVitePlugins(options: WorkbenchViteOptions): Promise<PluginOption> {\n const {appId, autoUpdates, cwd, entries, exposes, isApp, isBlueprints} = options\n if (autoUpdates && appId === undefined) {\n throw new Error('An auto-updating workbench app needs an app ID')\n }\n\n const pkgJson = await readPackageJson(path.join(cwd, 'package.json'))\n\n const federationPlugin = federation({\n ...(isApp\n ? {\n // `null` relativeEntry (a branded app with no `entry`) → omit `appEntry`,\n // so the remote exposes no `./App`, only its views.\n ...(entries.relativeEntry ? {appEntry: entries.relativeEntry} : {}),\n isApp: true as const,\n }\n : {\n isApp: false as const,\n studioConfigPath: requireStudioConfigPath(entries.relativeConfigLocation),\n }),\n autoUpdates,\n exposes,\n isBlueprints,\n pkgJson,\n workDir: cwd,\n })\n\n // Media Library config apps run their modules inside the host's page, so\n // the `sanity` barrel's document-wide CSS reset must not travel with the\n // bundle (see the plugin for the full why).\n const configAppPlugins: PluginOption[] = isMediaLibraryConfigApp(exposes)\n ? [stripSuiGlobalReset()]\n : []\n\n return [\n ...configAppPlugins,\n federationPlugin,\n ...(appId === undefined ? [] : [sanityAppId(appId), sanityAppStyles(appId)]),\n ]\n}\n"],"names":["path","readPackageJson","isMediaLibraryConfigApp","federation","sanityAppId","sanityAppStyles","stripSuiGlobalReset","requireStudioConfigPath","relativeConfigLocation","Error","workbenchVitePlugins","options","appId","autoUpdates","cwd","entries","exposes","isApp","isBlueprints","undefined","pkgJson","join","federationPlugin","relativeEntry","appEntry","studioConfigPath","workDir","configAppPlugins"],"mappings":"AAAA,6EAA6E;AAC7E,8EAA8E;AAC9E,sEAAsE;AACtE,+EAA+E;AAC/E,4EAA4E;AAC5E,iFAAiF;AAEjF,O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
};
|
|
167
167
|
}
|
|
168
168
|
/**
|
|
169
|
-
* Where the Dashboard shell opens a registered server
|
|
170
|
-
*
|
|
171
|
-
*
|
|
172
|
-
*
|
|
169
|
+
* Where the Dashboard shell opens a registered server, matching the Workbench's
|
|
170
|
+
* `StudioApplication.href` and `CoreApplication.href`. Only servers with a
|
|
171
|
+
* `surface: 'window'` interface get one (see toWireInterface): studios always do,
|
|
172
|
+
* configs and panel-only apps don't, so they'd 404.
|
|
173
173
|
*/ export function dashboardPath(server) {
|
|
174
174
|
const hasAppView = (server.interfaces ?? []).some((iface)=>'surface' in iface && iface.surface === 'window');
|
|
175
|
-
|
|
175
|
+
const segment = server.slug ?? server.id;
|
|
176
|
+
if (!segment || !hasAppView) {
|
|
177
|
+
return undefined;
|
|
178
|
+
}
|
|
179
|
+
const root = server.type === 'studio' ? 'studios' : 'applications';
|
|
180
|
+
return `/${root}/${encodeURIComponent(segment)}`;
|
|
176
181
|
}
|
|
177
182
|
/**
|
|
178
183
|
* Path to the dev server registry directory. Lives under the shared Sanity
|
|
@@ -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: `/local/<id>`, only when\n * it has an id and a `surface: 'window'` interface. That interface is the app\n * view the shell's `/local/:applicationId` route renders (see toWireInterface);\n * studios always get one, configs and panel-only apps don't, so they'd 404.\n */\nexport function dashboardPath(\n server: Pick<DevServerManifest, 'id' | 'interfaces'>,\n): string | undefined {\n const hasAppView = (server.interfaces ?? []).some(\n (iface) => 'surface' in iface && iface.surface === 'window',\n )\n return server.id && hasAppView ? `/local/${encodeURIComponent(server.id)}` : undefined\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","encodeURIComponent","undefined","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,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1F,IAAY;gBACrBtD,cAAcyI,UAAU7C,KAAKC,SAAS,CAAC;oBAAC,GAAGgD,QAAQ;oBAAEvF;oBAAMoE,OAAO;gBAAI;YACxE;QACF;IACF,EAAE,OAAOuB,KAAc;QACrBpI,SACE,wCACAoI,eAAeC,QAAQD,IAAIE,OAAO,GAAGC,OAAOH;QAE9C,IAAI,CAACI,YAAYJ,QAAQA,IAAIK,IAAI,KAAK,UAAU,OAAO5E;QAEvD,mDAAmD;QACnD,MAAM6E,WAAW5B,kBAAkBgB,KAAKvF,cAAc;QACtD,IAAImG,UAAU,OAAO7E;QAErB,6FAA6F;QAC7F,IAAIkE,WAAW,GAAG,OAAOlE;QACzB,OAAOgE,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 /**\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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gBACXC;gBACA,IAAI;oBACFnG,WAAW6I;gBACb,EAAE,OAAM;gBACN,qBAAqB;gBACvB;YACF;YACAO,YAAW5F,IAAY;gBACrBtD,cAAc2I,UAAU7C,KAAKC,SAAS,CAAC;oBAAC,GAAGgD,QAAQ;oBAAEzF;oBAAMsE,OAAO;gBAAI;YACxE;QACF;IACF,EAAE,OAAOuB,KAAc;QACrBtI,SACE,wCACAsI,eAAeC,QAAQD,IAAIE,OAAO,GAAGC,OAAOH;QAE9C,IAAI,CAACI,YAAYJ,QAAQA,IAAIK,IAAI,KAAK,UAAU,OAAO9E;QAEvD,mDAAmD;QACnD,MAAM+E,WAAW5B,kBAAkBgB,KAAKzF,cAAc;QACtD,IAAIqG,UAAU,OAAO/E;QAErB,6FAA6F;QAC7F,IAAIoE,WAAW,GAAG,OAAOpE;QACzB,OAAOkE,qBAAqBC,MAAMC,UAAU;IAC9C;AACF;AAEA,SAASS,YAAYJ,GAAY;IAC/B,OAAOA,eAAeC,SAAS,UAAUD;AAC3C"}
|
|
@@ -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({id, interfaces}),\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,q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AO;gBACLuB,SAAS,MAAMhC,cAAcyD;gBAC7B1B,YAAYnC,iBAAiB6D,WAAWjD,GAAG,EAAE;oBAACkB;gBAAK;gBACnDgC,UAAU,MAAMjC,gBAAgB;oBAAC,GAAG+B,MAAM;oBAAElB,eAAeH;gBAAE;YAC/D;QACF;QACA,2EAA2E;QAC3E,wEAAwE;QACxEwB,qBAAqBjC,QAAQQ,YAAY;YAAC;YAAiB;SAAgB;QAC3EzB;QACAmD,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,GAAGhD,cAAckD,cAAc;YAAA,IAAIF;QACpF;QACAjC;IACF;IAEA,OAAO;QACLoB,OAAO;YACLC,aAAagB,OAAO;YACpB,MAAMX,QAAQN,KAAK;QACrB;QACAkB,MAAMhE,cAAc;YAACiC;YAAIJ;QAAU;IACrC;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 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","extraW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|
@@ -82,7 +82,9 @@ import { serveBuiltApplication } from './serveBuiltApplication.js';
|
|
|
82
82
|
closers.push(async ()=>registration.release());
|
|
83
83
|
dashboardAppPath = dashboardPath({
|
|
84
84
|
id,
|
|
85
|
-
interfaces
|
|
85
|
+
interfaces,
|
|
86
|
+
slug: workbench.slug,
|
|
87
|
+
type: isApp ? 'coreApp' : 'studio'
|
|
86
88
|
});
|
|
87
89
|
} catch (err) {
|
|
88
90
|
await close();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/actions/preview/startWorkbenchPreview.ts"],"sourcesContent":["import {readFile} from 'node:fs/promises'\nimport path from 'node:path'\nimport {styleText} from 'node:util'\n\nimport {type CliConfig, findProjectRoot, type Output} from '@sanity/cli-core'\n\nimport {buildAppId, SANITY_APP_ID_FILE} from '../../appId.js'\nimport {deriveInterfaces} from '../../deriveInterfaces.js'\nimport {resolveWorkbenchApp} from '../../resolveWorkbenchApp.js'\nimport {createServerLifecycle, toDisplayHost} from '../../util/serverOrchestration.js'\nimport {deriveConfigs} from '../dev/deriveConfigs.js'\nimport {\n dashboardPath,\n type DevServerManifest,\n localAppIdentity,\n registerDevServer,\n} from '../dev/registry.js'\nimport {startWorkbenchDevServer} from '../dev/startWorkbenchDevServer.js'\nimport {serveBuiltApplication} from './serveBuiltApplication.js'\n\nexport interface StartWorkbenchPreviewOptions {\n /** Directory for the workbench Vite server's dependency cache. */\n cacheDir: string\n /** CLI-domain `app.id`/`deployment.appId` deprecation check, run before registering. */\n checkForDeprecatedAppId: () => void\n cliConfig: CliConfig\n /** Extract the project manifest to inline into the registry (studio-vs-app handled by the CLI). */\n extractManifest: (params: {\n applicationId?: string\n configPath: string\n workDir: string\n }) => Promise<DevServerManifest['manifest']>\n httpHost: string\n httpPort: number\n isApp: boolean\n /** The built `dist` directory to serve as the federation remote. */\n outDir: string\n output: Output\n reactStrictMode: boolean\n workDir: string\n}\n\n/**\n * `sanity start` for a workbench app: serve a production build the way dev serves\n * a live one. The same singleton workbench shell renders it and the same registry\n * advertises it — only the remote differs, static files from the build output\n * instead of a live Vite dev server. There's no config watcher or rebuild: a\n * build is fixed, so nothing re-syncs.\n *\n * A running workbench claims the configured port, so the built remote binds the\n * next one. Without one the remote takes the configured port and announces its\n * own URL.\n */\nexport async function startWorkbenchPreview(\n options: StartWorkbenchPreviewOptions,\n): Promise<{close: () => Promise<void>}> {\n const {\n cacheDir,\n checkForDeprecatedAppId,\n cliConfig,\n extractManifest,\n httpHost,\n httpPort,\n isApp,\n outDir,\n output,\n reactStrictMode,\n workDir,\n } = options\n\n const {close, closers, installSignalHandlers} = createServerLifecycle()\n\n const workbench = await startWorkbenchDevServer({\n cacheDir,\n cliConfig,\n httpHost,\n httpPort,\n output,\n reactStrictMode,\n workDir,\n })\n closers.push(workbench.close)\n\n const remotePort = workbench.workbenchAvailable ? workbench.workbenchPort + 1 : httpPort\n\n const remote = await serveBuiltApplication({\n cacheDir,\n httpHost,\n httpPort: remotePort,\n outDir,\n workDir,\n }).catch(async (err) => {\n await close()\n throw err\n })\n closers.push(remote.close)\n\n let dashboardAppPath: string | undefined\n try {\n // Callers provide CLI-only validation and manifest extraction to keep them\n // out of workbench-cli.\n checkForDeprecatedAppId()\n const configPath = (await findProjectRoot(workDir)).path\n const workbench = resolveWorkbenchApp(cliConfig)\n\n if (!workbench) {\n throw new Error(\n '`sanity start` was invoked in an application that is not set up for the Dashboard',\n )\n }\n const inlinedId = await readInlinedAppId(outDir)\n const configs = await deriveConfigs(cliConfig)\n const id = inlinedId ?? (await buildAppId(workbench))\n const interfaces = deriveInterfaces(cliConfig.app, {isApp})\n const registration = registerDevServer({\n applicationId: cliConfig.deployment?.appId,\n configs,\n host: remote.host,\n id,\n interfaces,\n manifest: await extractManifest({applicationId: id, configPath, workDir}),\n manifestUpdatedAt: new Date().toISOString(),\n port: remote.port,\n projectId: cliConfig?.api?.projectId,\n ...localAppIdentity(workbench),\n type: isApp ? 'coreApp' : 'studio',\n workDir,\n })\n closers.push(async () => registration.release())\n dashboardAppPath = dashboardPath({id
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/preview/startWorkbenchPreview.ts"],"sourcesContent":["import {readFile} from 'node:fs/promises'\nimport path from 'node:path'\nimport {styleText} from 'node:util'\n\nimport {type CliConfig, findProjectRoot, type Output} from '@sanity/cli-core'\n\nimport {buildAppId, SANITY_APP_ID_FILE} from '../../appId.js'\nimport {deriveInterfaces} from '../../deriveInterfaces.js'\nimport {resolveWorkbenchApp} from '../../resolveWorkbenchApp.js'\nimport {createServerLifecycle, toDisplayHost} from '../../util/serverOrchestration.js'\nimport {deriveConfigs} from '../dev/deriveConfigs.js'\nimport {\n dashboardPath,\n type DevServerManifest,\n localAppIdentity,\n registerDevServer,\n} from '../dev/registry.js'\nimport {startWorkbenchDevServer} from '../dev/startWorkbenchDevServer.js'\nimport {serveBuiltApplication} from './serveBuiltApplication.js'\n\nexport interface StartWorkbenchPreviewOptions {\n /** Directory for the workbench Vite server's dependency cache. */\n cacheDir: string\n /** CLI-domain `app.id`/`deployment.appId` deprecation check, run before registering. */\n checkForDeprecatedAppId: () => void\n cliConfig: CliConfig\n /** Extract the project manifest to inline into the registry (studio-vs-app handled by the CLI). */\n extractManifest: (params: {\n applicationId?: string\n configPath: string\n workDir: string\n }) => Promise<DevServerManifest['manifest']>\n httpHost: string\n httpPort: number\n isApp: boolean\n /** The built `dist` directory to serve as the federation remote. */\n outDir: string\n output: Output\n reactStrictMode: boolean\n workDir: string\n}\n\n/**\n * `sanity start` for a workbench app: serve a production build the way dev serves\n * a live one. The same singleton workbench shell renders it and the same registry\n * advertises it — only the remote differs, static files from the build output\n * instead of a live Vite dev server. There's no config watcher or rebuild: a\n * build is fixed, so nothing re-syncs.\n *\n * A running workbench claims the configured port, so the built remote binds the\n * next one. Without one the remote takes the configured port and announces its\n * own URL.\n */\nexport async function startWorkbenchPreview(\n options: StartWorkbenchPreviewOptions,\n): Promise<{close: () => Promise<void>}> {\n const {\n cacheDir,\n checkForDeprecatedAppId,\n cliConfig,\n extractManifest,\n httpHost,\n httpPort,\n isApp,\n outDir,\n output,\n reactStrictMode,\n workDir,\n } = options\n\n const {close, closers, installSignalHandlers} = createServerLifecycle()\n\n const workbench = await startWorkbenchDevServer({\n cacheDir,\n cliConfig,\n httpHost,\n httpPort,\n output,\n reactStrictMode,\n workDir,\n })\n closers.push(workbench.close)\n\n const remotePort = workbench.workbenchAvailable ? workbench.workbenchPort + 1 : httpPort\n\n const remote = await serveBuiltApplication({\n cacheDir,\n httpHost,\n httpPort: remotePort,\n outDir,\n workDir,\n }).catch(async (err) => {\n await close()\n throw err\n })\n closers.push(remote.close)\n\n let dashboardAppPath: string | undefined\n try {\n // Callers provide CLI-only validation and manifest extraction to keep them\n // out of workbench-cli.\n checkForDeprecatedAppId()\n const configPath = (await findProjectRoot(workDir)).path\n const workbench = resolveWorkbenchApp(cliConfig)\n\n if (!workbench) {\n throw new Error(\n '`sanity start` was invoked in an application that is not set up for the Dashboard',\n )\n }\n const inlinedId = await readInlinedAppId(outDir)\n const configs = await deriveConfigs(cliConfig)\n const id = inlinedId ?? (await buildAppId(workbench))\n const interfaces = deriveInterfaces(cliConfig.app, {isApp})\n const registration = registerDevServer({\n applicationId: cliConfig.deployment?.appId,\n configs,\n host: remote.host,\n id,\n interfaces,\n manifest: await extractManifest({applicationId: id, configPath, workDir}),\n manifestUpdatedAt: new Date().toISOString(),\n port: remote.port,\n projectId: cliConfig?.api?.projectId,\n ...localAppIdentity(workbench),\n type: isApp ? 'coreApp' : 'studio',\n workDir,\n })\n closers.push(async () => registration.release())\n dashboardAppPath = dashboardPath({\n id,\n interfaces,\n slug: workbench.slug,\n type: isApp ? 'coreApp' : 'studio',\n })\n } catch (err) {\n await close()\n throw err\n }\n\n if (workbench.workbenchAvailable) {\n const appUrl = `http://${toDisplayHost(workbench.httpHost)}:${workbench.workbenchPort}${dashboardAppPath ?? ''}`\n output.log(`Dashboard preview server started at ${styleText(['blue', 'underline'], appUrl)}`)\n } else {\n const remoteUrl = `http://${toDisplayHost(remote.host)}:${remote.port}`\n output.log(`Serving build at ${styleText(['blue', 'underline'], remoteUrl)}`)\n }\n\n installSignalHandlers()\n\n return {close}\n}\n\n/** The id the build inlined into its bundle, or undefined when absent. */\nasync function readInlinedAppId(outDir: string): Promise<string | undefined> {\n try {\n return (await readFile(path.join(outDir, SANITY_APP_ID_FILE), 'utf8')).trim() || undefined\n } catch {\n return undefined\n }\n}\n"],"names":["readFile","path","styleText","findProjectRoot","buildAppId","SANITY_APP_ID_FILE","deriveInterfaces","resolveWorkbenchApp","createServerLifecycle","toDisplayHost","deriveConfigs","dashboardPath","localAppIdentity","registerDevServer","startWorkbenchDevServer","serveBuiltApplication","startWorkbenchPreview","options","cacheDir","checkForDeprecatedAppId","cliConfig","extractManifest","httpHost","httpPort","isApp","outDir","output","reactStrictMode","workDir","close","closers","installSignalHandlers","workbench","push","remotePort","workbenchAvailable","workbenchPort","remote","catch","err","dashboardAppPath","configPath","Error","inlinedId","readInlinedAppId","configs","id","interfaces","app","registration","applicationId","deployment","appId","host","manifest","manifestUpdatedAt","Date","toISOString","port","projectId","api","type","release","slug","appUrl","log","remoteUrl","join","trim","undefined"],"mappings":"AAAA,SAAQA,QAAQ,QAAO,mBAAkB;AACzC,OAAOC,UAAU,YAAW;AAC5B,SAAQC,SAAS,QAAO,YAAW;AAEnC,SAAwBC,eAAe,QAAoB,mBAAkB;AAE7E,SAAQC,UAAU,EAAEC,kBAAkB,QAAO,iBAAgB;AAC7D,SAAQC,gBAAgB,QAAO,4BAA2B;AAC1D,SAAQC,mBAAmB,QAAO,+BAA8B;AAChE,SAAQC,qBAAqB,EAAEC,aAAa,QAAO,oCAAmC;AACtF,SAAQC,aAAa,QAAO,0BAAyB;AACrD,SACEC,aAAa,EAEbC,gBAAgB,EAChBC,iBAAiB,QACZ,qBAAoB;AAC3B,SAAQC,uBAAuB,QAAO,oCAAmC;AACzE,SAAQC,qBAAqB,QAAO,6BAA4B;AAwB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IL;gBAAYb;YAAO;YACvE2B,mBAAmB,IAAIC,OAAOC,WAAW;YACzCC,MAAMrB,OAAOqB,IAAI;YACjBC,WAAWvC,WAAWwC,KAAKD;YAC3B,GAAG/C,iBAAiBoB,UAAU;YAC9B6B,MAAMrC,QAAQ,YAAY;YAC1BI;QACF;QACAE,QAAQG,IAAI,CAAC,UAAYgB,aAAaa,OAAO;QAC7CtB,mBAAmB7B,cAAc;YAC/BmC;YACAC;YACAgB,MAAM/B,UAAU+B,IAAI;YACpBF,MAAMrC,QAAQ,YAAY;QAC5B;IACF,EAAE,OAAOe,KAAK;QACZ,MAAMV;QACN,MAAMU;IACR;IAEA,IAAIP,UAAUG,kBAAkB,EAAE;QAChC,MAAM6B,SAAS,CAAC,OAAO,EAAEvD,cAAcuB,UAAUV,QAAQ,EAAE,CAAC,EAAEU,UAAUI,aAAa,GAAGI,oBAAoB,IAAI;QAChHd,OAAOuC,GAAG,CAAC,CAAC,oCAAoC,EAAE/D,UAAU;YAAC;YAAQ;SAAY,EAAE8D,SAAS;IAC9F,OAAO;QACL,MAAME,YAAY,CAAC,OAAO,EAAEzD,cAAc4B,OAAOgB,IAAI,EAAE,CAAC,EAAEhB,OAAOqB,IAAI,EAAE;QACvEhC,OAAOuC,GAAG,CAAC,CAAC,iBAAiB,EAAE/D,UAAU;YAAC;YAAQ;SAAY,EAAEgE,YAAY;IAC9E;IAEAnC;IAEA,OAAO;QAACF;IAAK;AACf;AAEA,wEAAwE,GACxE,eAAee,iBAAiBnB,MAAc;IAC5C,IAAI;QACF,OAAO,AAAC,CAAA,MAAMzB,SAASC,KAAKkE,IAAI,CAAC1C,QAAQpB,qBAAqB,OAAM,EAAG+D,IAAI,MAAMC;IACnF,EAAE,OAAM;QACN,OAAOA;IACT;AACF"}
|
package/dist/defineApp.js
CHANGED
|
@@ -34,7 +34,10 @@ import { DockSchema, InterfaceDeclarationSchema, ServiceDeclarationSchema } from
|
|
|
34
34
|
* derives the app's navigable `app` view from it. SDK apps only — setting it
|
|
35
35
|
* on a studio is rejected (studio app views are not yet implemented).
|
|
36
36
|
*/ entry: z.optional(z.string("must be a path to the app's entry file")),
|
|
37
|
-
/**
|
|
37
|
+
/**
|
|
38
|
+
* Path to an `.svg` file, relative to the project root. Other file types are
|
|
39
|
+
* rejected. Wins over manifest/studio icon.
|
|
40
|
+
*/ icon: z.optional(z.string().check(z.regex(/\.svg$/i, 'App `icon` must be a path to an .svg file'))),
|
|
38
41
|
/** Sanity-owned app deployed once and installed per org. @internal */ isSingleton: z.optional(z.boolean()),
|
|
39
42
|
/**
|
|
40
43
|
* Stable identity, distinct from the `slug` address. Defaults to `slug` when
|
package/dist/defineApp.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/defineApp.ts"],"sourcesContent":["import {z} from 'zod/mini'\n\nimport {APP_SLUG_PATTERN} from './appSlug.js'\nimport {DockSchema, InterfaceDeclarationSchema, ServiceDeclarationSchema} from './contract.js'\n\n/**\n * Dashboard visibility values. Mirrors `APP_VISIBILITIES` in `@sanity/cli-core`\n * (which can't be imported here — pulling the barrel into this lean module bloats\n * the config-load path). Kept in sync by a type test in `defineApp.test.ts`.\n */\nconst APP_VISIBILITIES = ['default', 'unlisted', 'disabled'] as const\n\n/**\n * Internal application discriminator. Sanity-owned singleton apps only;\n * validated by the schema but excluded from the public `DefineAppInput` type.\n */\nconst ApplicationType = z.enum(['coreApp', 'studio', 'canvas', 'dashboard'])\n\n/**\n * Runtime-validation schema for `defineApplication`.\n * @internal\n */\nexport const DefineAppInputSchema = z\n .object({\n /**\n * Internal — Sanity-owned singleton apps only. Validated here but excluded\n * from the public `DefineAppInput` type.\n * @internal\n */\n applicationType: z.optional(ApplicationType),\n /** Default placement inherited by window views. */\n dock: z.optional(DockSchema),\n /**\n * App entrypoint module. Defaults to `./src/App.tsx` when omitted. The build\n * derives the app's navigable `app` view from it. SDK apps only — setting it\n * on a studio is rejected (studio app views are not yet implemented).\n */\n entry: z.optional(z.string(\"must be a path to the app's entry file\")),\n /** Optional icon override (path to an SVG). Wins over manifest/studio icon. */\n icon: z.optional(z.string()),\n /** Sanity-owned app deployed once and installed per org. @internal */\n isSingleton: z.optional(z.boolean()),\n /**\n * Stable identity, distinct from the `slug` address. Defaults to `slug` when\n * omitted. Identity keys — the build id and derived interface ids — are built\n * from this, so renaming the slug no longer changes identity.\n */\n name: z.optional(\n z\n .string()\n .check(\n z.regex(\n APP_SLUG_PATTERN,\n 'App `name` must be lowercase alphanumerics and hyphens, starting with a letter and ending with an alphanumeric',\n ),\n ),\n ),\n /** Organization that owns the app — it runs in and deploys to this organization's Dashboard. */\n organizationId: z.string(\n \"App `organizationId` is required — pass the owning organization's ID to `defineApplication`\",\n ),\n slug: z\n .string('App `slug` is required — the hostname the application is created at on deploy')\n .check(\n z.regex(\n APP_SLUG_PATTERN,\n 'App `slug` must be lowercase alphanumerics and hyphens, starting with a letter and ending with an alphanumeric',\n ),\n ),\n /** User-facing app title. Wins over studio.config.ts title on merge. */\n title: z.string(),\n /** Views the app exposes (e.g. a window, dock panels, and tiles). */\n views: z.optional(z.array(InterfaceDeclarationSchema, 'must be an array of views')),\n /** Dashboard visibility of the app. Defaults to `default` when omitted. */\n visibility: z.optional(z.enum(APP_VISIBILITIES)),\n /** Background web workers the app runs. */\n webWorkers: z.optional(z.array(ServiceDeclarationSchema, 'must be an array of web workers')),\n })\n .check(\n z.refine((input) => {\n const names = [\n ...(input.entry === undefined ? [] : [input.name ?? input.slug]),\n ...(input.views ?? []).map((view) => view.name),\n ...(input.webWorkers ?? []).map((webWorker) => webWorker.name),\n ]\n return new Set(names).size === names.length\n }, '`name` must be unique across views and web workers. Rename one of the duplicates.'),\n // Studio app views are not implemented yet. A studio that declares `entry`\n // (the SDK app-view entrypoint) is rejected here rather than silently\n // generating one; studios keep navigating via their existing render path.\n z.refine((input) => !(input.applicationType === 'studio' && input.entry !== undefined), {\n error: 'App views for studios are not implemented yet',\n path: ['entry'],\n }),\n )\n\n/**\n * User-facing input for `defineApplication`. Excludes the internal\n * `applicationType` and `isSingleton`.\n * @public\n */\nexport type DefineAppInput = Omit<\n z.output<typeof DefineAppInputSchema>,\n 'applicationType' | 'isSingleton'\n>\n\n/**\n * Nominal brand the CLI discriminates on to enable the workbench build/deploy\n * codepath. Registered via `Symbol.for` so the marker survives module-realm\n * boundaries — `@sanity/cli-core` re-derives the same global symbol with\n * `Symbol.for` rather than importing it, so it stays internal to this module.\n */\nconst WORKBENCH_APP: unique symbol = Symbol.for('sanity.workbench.defineApp')\n\n/**\n * The branded result of `defineApplication`. Carries the same fields as the\n * input plus the internal brand — users only ever see `DefineAppInput`.\n * @public\n */\nexport type DefineAppResult = DefineAppInput & {readonly [WORKBENCH_APP]: true}\n\n/**\n * A branded app as the CLI reads it — the full schema shape, including the\n * internal fields `DefineAppInput` omits. Schema-derived so the narrowing\n * can't drift from what the schema validates.\n * @public\n */\nexport type WorkbenchApp = DefineAppResult & z.output<typeof DefineAppInputSchema>\n\n/**\n * Whether `app` is a branded `defineApplication(...)` result — the sole\n * workbench opt-in.\n * @public\n */\nexport function isWorkbenchApp(app: unknown): app is WorkbenchApp {\n return typeof app === 'object' && app !== null && WORKBENCH_APP in app\n}\n\n/**\n * Declare a Sanity Dashboard application. Identity at runtime — returns the same\n * object reference, tagged with the Dashboard brand. Field validation (the\n * `slug` pattern etc.) runs at build time in the CLI via `DefineAppInputSchema`;\n * this helper stays a thin, pure identity wrapper.\n * @public\n */\nexport function defineApplication(input: DefineAppInput): DefineAppResult {\n return Object.defineProperty(input, WORKBENCH_APP, {\n configurable: false,\n enumerable: false,\n value: true,\n writable: false,\n }) as DefineAppResult\n}\n\n/**\n * One custom field a media library exposes. `src` default-exports a `defineField(...)` schema type.\n * @public\n */\nexport interface MediaLibraryField {\n /** Unique within the media library. */\n name: string\n src: string\n title: string\n\n /** Readable outside the owning organization. */\n public?: boolean\n}\n\n/**\n * Sanity-owned singleton, so authors don't name or title the app — only `organizationId` is required.\n * @public\n */\nexport interface DefineMediaLibraryInput {\n /** Organization that owns the media library — the CLI runs and deploys against it. */\n organizationId: string\n\n fields?: MediaLibraryField[]\n}\n\n/**\n * Nominal brand the CLI discriminates a config on. A config is *not* an app: it\n * carries no `slug`/`title`/application identity, only a target `appType`, its\n * owning `organizationId`, and its `fields`. Registered via `Symbol.for` so the\n * marker survives module-realm boundaries — `@sanity/cli-core` re-derives the\n * same global symbol rather than importing it.\n */\nconst WORKBENCH_CONFIG: unique symbol = Symbol.for('sanity.workbench.defineConfig')\n\n/**\n * A branded workbench config as the CLI reads it: bound to its target app by\n * `appType`, not carrying its own app identity. The deploy/undeploy/build paths\n * discriminate it via {@link isWorkbenchConfig}.\n * @public\n */\nexport interface WorkbenchConfig {\n appType: 'media-library'\n fields: MediaLibraryField[]\n organizationId: string\n readonly [WORKBENCH_CONFIG]: true\n}\n\n/**\n * Whether `app` is a branded `unstable_defineMediaLibrary(...)` config — a\n * config-carrier rather than an app. Configs live in `cliConfig.app` alongside\n * apps but resolve through `resolveWorkbenchConfig`, not `resolveWorkbenchApp`.\n * @public\n */\nexport function isWorkbenchConfig(app: unknown): app is WorkbenchConfig {\n return typeof app === 'object' && app !== null && WORKBENCH_CONFIG in app\n}\n\n/**\n * Declare the Sanity Media Library config. The Media Library is a Sanity-owned\n * singleton, so this is not an app — it carries no slug or title, only the\n * target `appType`, its owning organization, and the `fields` it contributes to\n * the installation's config.\n * @public\n */\nexport function unstable_defineMediaLibrary(input: DefineMediaLibraryInput): WorkbenchConfig {\n return Object.defineProperty(\n {appType: 'media-library', fields: input.fields ?? [], organizationId: input.organizationId},\n WORKBENCH_CONFIG,\n {configurable: false, enumerable: false, value: true, writable: false},\n ) as WorkbenchConfig\n}\n"],"names":["z","APP_SLUG_PATTERN","DockSchema","InterfaceDeclarationSchema","ServiceDeclarationSchema","APP_VISIBILITIES","ApplicationType","enum","DefineAppInputSchema","object","applicationType","optional","dock","entry","string","icon","isSingleton","boolean","name","check","regex","organizationId","slug","title","views","array","visibility","webWorkers","refine","input","names","undefined","map","view","webWorker","Set","size","length","error","path","WORKBENCH_APP","Symbol","for","isWorkbenchApp","app","defineApplication","Object","defineProperty","configurable","enumerable","value","writable","WORKBENCH_CONFIG","isWorkbenchConfig","unstable_defineMediaLibrary","appType","fields"],"mappings":"AAAA,SAAQA,CAAC,QAAO,WAAU;AAE1B,SAAQC,gBAAgB,QAAO,eAAc;AAC7C,SAAQC,UAAU,EAAEC,0BAA0B,EAAEC,wBAAwB,QAAO,gBAAe;AAE9F;;;;CAIC,GACD,MAAMC,mBAAmB;IAAC;IAAW;IAAY;CAAW;AAE5D;;;CAGC,GACD,MAAMC,kBAAkBN,EAAEO,IAAI,CAAC;IAAC;IAAW;IAAU;IAAU;CAAY;AAE3E;;;CAGC,GACD,OAAO,MAAMC,uBAAuBR,EACjCS,MAAM,CAAC;IACN;;;;KAIC,GACDC,iBAAiBV,EAAEW,QAAQ,CAACL;IAC5B,iDAAiD,GACjDM,MAAMZ,EAAEW,QAAQ,CAACT;IACjB;;;;KAIC,GACDW,OAAOb,EAAEW,QAAQ,CAACX,EAAEc,MAAM,CAAC;IAC3B,6EAA6E,GAC7EC,MAAMf,EAAEW,QAAQ,CAACX,EAAEc,MAAM;IACzB,oEAAoE,GACpEE,aAAahB,EAAEW,QAAQ,CAACX,EAAEiB,OAAO;IACjC;;;;KAIC,GACDC,MAAMlB,EAAEW,QAAQ,CACdX,EACGc,MAAM,GACNK,KAAK,CACJnB,EAAEoB,KAAK,CACLnB,kBACA;IAIR,8FAA8F,GAC9FoB,gBAAgBrB,EAAEc,MAAM,CACtB;IAEFQ,MAAMtB,EACHc,MAAM,CAAC,iFACPK,KAAK,CACJnB,EAAEoB,KAAK,CACLnB,kBACA;IAGN,sEAAsE,GACtEsB,OAAOvB,EAAEc,MAAM;IACf,mEAAmE,GACnEU,OAAOxB,EAAEW,QAAQ,CAACX,EAAEyB,KAAK,CAACtB,4BAA4B;IACtD,yEAAyE,GACzEuB,YAAY1B,EAAEW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OA,QAAQ,YAAYA,QAAQ,QAAQQ,oBAAoBR;AACxE;AAEA;;;;;;CAMC,GACD,OAAO,SAASU,4BAA4BzB,KAA8B;IACxE,OAAOiB,OAAOC,cAAc,CAC1B;QAACQ,SAAS;QAAiBC,QAAQ3B,MAAM2B,MAAM,IAAI,EAAE;QAAEnC,gBAAgBQ,MAAMR,cAAc;IAAA,GAC3F+B,kBACA;QAACJ,cAAc;QAAOC,YAAY;QAAOC,OAAO;QAAMC,UAAU;IAAK;AAEzE"}
|
|
1
|
+
{"version":3,"sources":["../src/defineApp.ts"],"sourcesContent":["import {z} from 'zod/mini'\n\nimport {APP_SLUG_PATTERN} from './appSlug.js'\nimport {DockSchema, InterfaceDeclarationSchema, ServiceDeclarationSchema} from './contract.js'\n\n/**\n * Dashboard visibility values. Mirrors `APP_VISIBILITIES` in `@sanity/cli-core`\n * (which can't be imported here — pulling the barrel into this lean module bloats\n * the config-load path). Kept in sync by a type test in `defineApp.test.ts`.\n */\nconst APP_VISIBILITIES = ['default', 'unlisted', 'disabled'] as const\n\n/**\n * Internal application discriminator. Sanity-owned singleton apps only;\n * validated by the schema but excluded from the public `DefineAppInput` type.\n */\nconst ApplicationType = z.enum(['coreApp', 'studio', 'canvas', 'dashboard'])\n\n/**\n * Runtime-validation schema for `defineApplication`.\n * @internal\n */\nexport const DefineAppInputSchema = z\n .object({\n /**\n * Internal — Sanity-owned singleton apps only. Validated here but excluded\n * from the public `DefineAppInput` type.\n * @internal\n */\n applicationType: z.optional(ApplicationType),\n /** Default placement inherited by window views. */\n dock: z.optional(DockSchema),\n /**\n * App entrypoint module. Defaults to `./src/App.tsx` when omitted. The build\n * derives the app's navigable `app` view from it. SDK apps only — setting it\n * on a studio is rejected (studio app views are not yet implemented).\n */\n entry: z.optional(z.string(\"must be a path to the app's entry file\")),\n /**\n * Path to an `.svg` file, relative to the project root. Other file types are\n * rejected. Wins over manifest/studio icon.\n */\n icon: z.optional(\n z.string().check(z.regex(/\\.svg$/i, 'App `icon` must be a path to an .svg file')),\n ),\n /** Sanity-owned app deployed once and installed per org. @internal */\n isSingleton: z.optional(z.boolean()),\n /**\n * Stable identity, distinct from the `slug` address. Defaults to `slug` when\n * omitted. Identity keys — the build id and derived interface ids — are built\n * from this, so renaming the slug no longer changes identity.\n */\n name: z.optional(\n z\n .string()\n .check(\n z.regex(\n APP_SLUG_PATTERN,\n 'App `name` must be lowercase alphanumerics and hyphens, starting with a letter and ending with an alphanumeric',\n ),\n ),\n ),\n /** Organization that owns the app — it runs in and deploys to this organization's Dashboard. */\n organizationId: z.string(\n \"App `organizationId` is required — pass the owning organization's ID to `defineApplication`\",\n ),\n slug: z\n .string('App `slug` is required — the hostname the application is created at on deploy')\n .check(\n z.regex(\n APP_SLUG_PATTERN,\n 'App `slug` must be lowercase alphanumerics and hyphens, starting with a letter and ending with an alphanumeric',\n ),\n ),\n /** User-facing app title. Wins over studio.config.ts title on merge. */\n title: z.string(),\n /** Views the app exposes (e.g. a window, dock panels, and tiles). */\n views: z.optional(z.array(InterfaceDeclarationSchema, 'must be an array of views')),\n /** Dashboard visibility of the app. Defaults to `default` when omitted. */\n visibility: z.optional(z.enum(APP_VISIBILITIES)),\n /** Background web workers the app runs. */\n webWorkers: z.optional(z.array(ServiceDeclarationSchema, 'must be an array of web workers')),\n })\n .check(\n z.refine((input) => {\n const names = [\n ...(input.entry === undefined ? [] : [input.name ?? input.slug]),\n ...(input.views ?? []).map((view) => view.name),\n ...(input.webWorkers ?? []).map((webWorker) => webWorker.name),\n ]\n return new Set(names).size === names.length\n }, '`name` must be unique across views and web workers. Rename one of the duplicates.'),\n // Studio app views are not implemented yet. A studio that declares `entry`\n // (the SDK app-view entrypoint) is rejected here rather than silently\n // generating one; studios keep navigating via their existing render path.\n z.refine((input) => !(input.applicationType === 'studio' && input.entry !== undefined), {\n error: 'App views for studios are not implemented yet',\n path: ['entry'],\n }),\n )\n\n/**\n * User-facing input for `defineApplication`. Excludes the internal\n * `applicationType` and `isSingleton`.\n * @public\n */\nexport type DefineAppInput = Omit<\n z.output<typeof DefineAppInputSchema>,\n 'applicationType' | 'isSingleton'\n>\n\n/**\n * Nominal brand the CLI discriminates on to enable the workbench build/deploy\n * codepath. Registered via `Symbol.for` so the marker survives module-realm\n * boundaries — `@sanity/cli-core` re-derives the same global symbol with\n * `Symbol.for` rather than importing it, so it stays internal to this module.\n */\nconst WORKBENCH_APP: unique symbol = Symbol.for('sanity.workbench.defineApp')\n\n/**\n * The branded result of `defineApplication`. Carries the same fields as the\n * input plus the internal brand — users only ever see `DefineAppInput`.\n * @public\n */\nexport type DefineAppResult = DefineAppInput & {readonly [WORKBENCH_APP]: true}\n\n/**\n * A branded app as the CLI reads it — the full schema shape, including the\n * internal fields `DefineAppInput` omits. Schema-derived so the narrowing\n * can't drift from what the schema validates.\n * @public\n */\nexport type WorkbenchApp = DefineAppResult & z.output<typeof DefineAppInputSchema>\n\n/**\n * Whether `app` is a branded `defineApplication(...)` result — the sole\n * workbench opt-in.\n * @public\n */\nexport function isWorkbenchApp(app: unknown): app is WorkbenchApp {\n return typeof app === 'object' && app !== null && WORKBENCH_APP in app\n}\n\n/**\n * Declare a Sanity Dashboard application. Identity at runtime — returns the same\n * object reference, tagged with the Dashboard brand. Field validation (the\n * `slug` pattern etc.) runs at build time in the CLI via `DefineAppInputSchema`;\n * this helper stays a thin, pure identity wrapper.\n * @public\n */\nexport function defineApplication(input: DefineAppInput): DefineAppResult {\n return Object.defineProperty(input, WORKBENCH_APP, {\n configurable: false,\n enumerable: false,\n value: true,\n writable: false,\n }) as DefineAppResult\n}\n\n/**\n * One custom field a media library exposes. `src` default-exports a `defineField(...)` schema type.\n * @public\n */\nexport interface MediaLibraryField {\n /** Unique within the media library. */\n name: string\n src: string\n title: string\n\n /** Readable outside the owning organization. */\n public?: boolean\n}\n\n/**\n * Sanity-owned singleton, so authors don't name or title the app — only `organizationId` is required.\n * @public\n */\nexport interface DefineMediaLibraryInput {\n /** Organization that owns the media library — the CLI runs and deploys against it. */\n organizationId: string\n\n fields?: MediaLibraryField[]\n}\n\n/**\n * Nominal brand the CLI discriminates a config on. A config is *not* an app: it\n * carries no `slug`/`title`/application identity, only a target `appType`, its\n * owning `organizationId`, and its `fields`. Registered via `Symbol.for` so the\n * marker survives module-realm boundaries — `@sanity/cli-core` re-derives the\n * same global symbol rather than importing it.\n */\nconst WORKBENCH_CONFIG: unique symbol = Symbol.for('sanity.workbench.defineConfig')\n\n/**\n * A branded workbench config as the CLI reads it: bound to its target app by\n * `appType`, not carrying its own app identity. The deploy/undeploy/build paths\n * discriminate it via {@link isWorkbenchConfig}.\n * @public\n */\nexport interface WorkbenchConfig {\n appType: 'media-library'\n fields: MediaLibraryField[]\n organizationId: string\n readonly [WORKBENCH_CONFIG]: true\n}\n\n/**\n * Whether `app` is a branded `unstable_defineMediaLibrary(...)` config — a\n * config-carrier rather than an app. Configs live in `cliConfig.app` alongside\n * apps but resolve through `resolveWorkbenchConfig`, not `resolveWorkbenchApp`.\n * @public\n */\nexport function isWorkbenchConfig(app: unknown): app is WorkbenchConfig {\n return typeof app === 'object' && app !== null && WORKBENCH_CONFIG in app\n}\n\n/**\n * Declare the Sanity Media Library config. The Media Library is a Sanity-owned\n * singleton, so this is not an app — it carries no slug or title, only the\n * target `appType`, its owning organization, and the `fields` it contributes to\n * the installation's config.\n * @public\n */\nexport function unstable_defineMediaLibrary(input: DefineMediaLibraryInput): WorkbenchConfig {\n return Object.defineProperty(\n {appType: 'media-library', fields: input.fields ?? [], organizationId: input.organizationId},\n WORKBENCH_CONFIG,\n {configurable: false, enumerable: false, value: true, writable: false},\n ) as WorkbenchConfig\n}\n"],"names":["z","APP_SLUG_PATTERN","DockSchema","InterfaceDeclarationSchema","ServiceDeclarationSchema","APP_VISIBILITIES","ApplicationType","enum","DefineAppInputSchema","object","applicationType","optional","dock","entry","string","icon","check","regex","isSingleton","boolean","name","organizationId","slug","title","views","array","visibility","webWorkers","refine","input","names","undefined","map","view","webWorker","Set","size","length","error","path","WORKBENCH_APP","Symbol","for","isWorkbenchApp","app","defineApplication","Object","defineProperty","configurable","enumerable","value","writable","WORKBENCH_CONFIG","isWorkbenchConfig","unstable_defineMediaLibrary","appType","fields"],"mappings":"AAAA,SAAQA,CAAC,QAAO,WAAU;AAE1B,SAAQC,gBAAgB,QAAO,eAAc;AAC7C,SAAQC,UAAU,EAAEC,0BAA0B,EAAEC,wBAAwB,QAAO,gBAAe;AAE9F;;;;CAIC,GACD,MAAMC,mBAAmB;IAAC;IAAW;IAAY;CAAW;AAE5D;;;CAGC,GACD,MAAMC,kBAAkBN,EAAEO,IAAI,CAAC;IAAC;IAAW;IAAU;IAAU;CAAY;AAE3E;;;CAGC,GACD,OAAO,MAAMC,uBAAuBR,EACjCS,MAAM,CAAC;IACN;;;;KAIC,GACDC,iBAAiBV,EAAEW,QAAQ,CAACL;IAC5B,iDAAiD,GACjDM,MAAMZ,EAAEW,QAAQ,CAACT;IACjB;;;;KAIC,GACDW,OAAOb,EAAEW,QAAQ,CAACX,EAAEc,MAAM,CAAC;IAC3B;;;KAGC,GACDC,MAAMf,EAAEW,QAAQ,CACdX,EAAEc,MAAM,GAAGE,KAAK,CAAChB,EAAEiB,KAAK,CAAC,WAAW;IAEtC,oEAAoE,GACpEC,aAAalB,EAAEW,QAAQ,CAACX,EAAEmB,OAAO;IACjC;;;;KAIC,GACDC,MAAMpB,EAAEW,QAAQ,CACdX,EACGc,MAAM,GACNE,KAAK,CACJhB,EAAEiB,KAAK,CACLhB,kBACA;IAIR,8FAA8F,GAC9FoB,gBAAgBrB,EAAEc,MAAM,CACtB;IAEFQ,MAAMtB,EACHc,MAAM,CAAC,iFACPE,KAAK,CACJhB,EAAEiB,KAAK,CACLhB,kBACA;IAGN,sEAAsE,GACtEsB,OAAOvB,EAAEc,MAAM;IACf,mEAAmE,GACnEU,OAAOxB,EAAEW,QAAQ,CAACX,EAAEyB,KAAK,CAACtB,4BAA4B;IACtD,yEAAyE,GACzEuB,YAAY1B,EAAEW,QAAQ,C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AAYA,QAAQ,QAAQQ,oBAAoBR;AACxE;AAEA;;;;;;CAMC,GACD,OAAO,SAASU,4BAA4BzB,KAA8B;IACxE,OAAOiB,OAAOC,cAAc,CAC1B;QAACQ,SAAS;QAAiBC,QAAQ3B,MAAM2B,MAAM,IAAI,EAAE;QAAEnC,gBAAgBQ,MAAMR,cAAc;IAAA,GAC3F+B,kBACA;QAACJ,cAAc;QAAOC,YAAY;QAAOC,OAAO;QAAMC,UAAU;IAAK;AAEzE"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sanity/workbench-cli",
|
|
3
|
-
"version": "2.15.
|
|
3
|
+
"version": "2.15.1",
|
|
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",
|
|
@@ -65,24 +65,24 @@
|
|
|
65
65
|
"access": "public"
|
|
66
66
|
},
|
|
67
67
|
"dependencies": {
|
|
68
|
-
"@module-federation/runtime": "2.9.
|
|
69
|
-
"@module-federation/vite": "1.23.
|
|
68
|
+
"@module-federation/runtime": "2.9.3",
|
|
69
|
+
"@module-federation/vite": "1.23.8",
|
|
70
70
|
"@sanity/cli-core": "^3.14.1",
|
|
71
|
-
"@sanity/sdk": "^3.
|
|
72
|
-
"@sanity/types": "^6.
|
|
73
|
-
"@vitejs/plugin-react": "^6.1
|
|
71
|
+
"@sanity/sdk": "^3.12.0",
|
|
72
|
+
"@sanity/types": "^6.22.0",
|
|
73
|
+
"@vitejs/plugin-react": "^6.2.1",
|
|
74
74
|
"form-data": "^4.0.5",
|
|
75
75
|
"rxjs": "^7.8.2",
|
|
76
76
|
"semver": "^7.8.1",
|
|
77
77
|
"tar": "^7.5.18",
|
|
78
|
-
"vite": "^8.3.
|
|
78
|
+
"vite": "^8.3.6",
|
|
79
79
|
"zod": "^4.5.2"
|
|
80
80
|
},
|
|
81
81
|
"devDependencies": {
|
|
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": "24.0.
|
|
85
|
+
"@sanity/cli-test": "24.0.2",
|
|
86
86
|
"@sanity/eslint-config-cli": "^1.1.3",
|
|
87
87
|
"@sanity/pkg-utils": "^12.3.4",
|
|
88
88
|
"@swc/cli": "^0.8.1",
|
|
@@ -90,14 +90,14 @@
|
|
|
90
90
|
"@types/node": "^22.20.5",
|
|
91
91
|
"@types/react": "^19.3.0",
|
|
92
92
|
"@types/semver": "^7.7.1",
|
|
93
|
-
"@vitest/coverage-istanbul": "^
|
|
93
|
+
"@vitest/coverage-istanbul": "^5.1.0",
|
|
94
94
|
"eslint": "^10.7.0",
|
|
95
95
|
"jsdom": "^29.1.1",
|
|
96
96
|
"publint": "^0.3.21",
|
|
97
97
|
"react": "^19.3.0",
|
|
98
98
|
"react-dom": "^19.3.0",
|
|
99
99
|
"typescript": "^6.0.3",
|
|
100
|
-
"vitest": "^
|
|
100
|
+
"vitest": "^5.1.0"
|
|
101
101
|
},
|
|
102
102
|
"engines": {
|
|
103
103
|
"node": ">=22.12"
|