@sanity/workbench-cli 2.15.2 → 2.16.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.
Files changed (61) hide show
  1. package/dist/_exports/_internal_worker_bus.d.ts +3 -3
  2. package/dist/_exports/_internal_worker_bus.js +1 -1
  3. package/dist/_exports/_internal_worker_bus.js.map +1 -1
  4. package/dist/_exports/build.d.ts +3 -3
  5. package/dist/_exports/{contract-C4Y6gi-b.d.ts → contract-WrU3aOYd.d.ts} +9 -6
  6. package/dist/_exports/deploy.d.ts +3 -3
  7. package/dist/_exports/dev.d.ts +1 -1
  8. package/dist/_exports/index.d.ts +5 -4
  9. package/dist/_exports/index.js +1 -1
  10. package/dist/_exports/index.js.map +1 -1
  11. package/dist/_exports/{resolveWorkbenchConfig-CgKD8AJ7.d.ts → resolveWorkbenchConfig-JRi01VJM.d.ts} +2 -2
  12. package/dist/_exports/{summarizeInterfaces-CeV5Umpj.d.ts → summarizeInterfaces-CpCUSMrz.d.ts} +6 -6
  13. package/dist/_exports/undeploy.d.ts +2 -2
  14. package/dist/_exports/{defineService-DPZwNN6_.d.ts → webWorker-TWUbh0uo.d.ts} +63 -39
  15. package/dist/actions/build/artifact.js +2 -2
  16. package/dist/actions/build/artifact.js.map +1 -1
  17. package/dist/actions/build/render-remote.js +11 -5
  18. package/dist/actions/build/render-remote.js.map +1 -1
  19. package/dist/actions/build/views/artifact.js +7 -5
  20. package/dist/actions/build/views/artifact.js.map +1 -1
  21. package/dist/actions/build/vite/optimize-deps.js +2 -2
  22. package/dist/actions/build/vite/optimize-deps.js.map +1 -1
  23. package/dist/actions/build/vite/plugin.js +2 -2
  24. package/dist/actions/build/vite/plugin.js.map +1 -1
  25. package/dist/actions/build/vite/plugins/plugin-sanity-environment.js +1 -0
  26. package/dist/actions/build/vite/plugins/plugin-sanity-environment.js.map +1 -1
  27. package/dist/actions/build/vite/plugins/plugin-sanity-extension-artifacts.js +2 -2
  28. package/dist/actions/build/vite/plugins/plugin-sanity-extension-artifacts.js.map +1 -1
  29. package/dist/actions/build/vite/plugins/plugin-sanity-federation-runtime.js +5 -2
  30. package/dist/actions/build/vite/plugins/plugin-sanity-federation-runtime.js.map +1 -1
  31. package/dist/actions/build/{services → webWorkers}/artifact.js +28 -27
  32. package/dist/actions/build/webWorkers/artifact.js.map +1 -0
  33. package/dist/actions/build/{services → webWorkers}/workerBus.js +1 -1
  34. package/dist/actions/build/webWorkers/workerBus.js.map +1 -0
  35. package/dist/actions/deploy/deployWorkbenchApp.js +7 -14
  36. package/dist/actions/deploy/deployWorkbenchApp.js.map +1 -1
  37. package/dist/actions/deploy/getWorkbench.js.map +1 -1
  38. package/dist/actions/deploy/summarizeInterfaces.js +3 -3
  39. package/dist/actions/deploy/summarizeInterfaces.js.map +1 -1
  40. package/dist/actions/dev/appServerSupervisor.js +2 -2
  41. package/dist/actions/dev/appServerSupervisor.js.map +1 -1
  42. package/dist/actions/dev/exposesSetId.js +1 -1
  43. package/dist/actions/dev/exposesSetId.js.map +1 -1
  44. package/dist/actions/dev/registry.js +14 -4
  45. package/dist/actions/dev/registry.js.map +1 -1
  46. package/dist/actions/dev/startWorkbenchDev.js +1 -1
  47. package/dist/actions/dev/startWorkbenchDev.js.map +1 -1
  48. package/dist/contract.js +8 -8
  49. package/dist/contract.js.map +1 -1
  50. package/dist/defineApp.js +2 -2
  51. package/dist/defineApp.js.map +1 -1
  52. package/dist/defineView.js +2 -2
  53. package/dist/defineView.js.map +1 -1
  54. package/dist/deriveInterfaces.js.map +1 -1
  55. package/dist/webWorker.js +20 -0
  56. package/dist/webWorker.js.map +1 -0
  57. package/package.json +11 -11
  58. package/dist/actions/build/services/artifact.js.map +0 -1
  59. package/dist/actions/build/services/workerBus.js.map +0 -1
  60. package/dist/defineService.js +0 -52
  61. package/dist/defineService.js.map +0 -1
@@ -15,7 +15,7 @@ const label = (item)=>item.title === item.name ? item.name : `${item.title} (${i
15
15
  surface: view.surface,
16
16
  title: view.title
17
17
  }));
18
- const deployedServices = (webWorkers ?? []).map((webWorker)=>({
18
+ const deployedWebWorkers = (webWorkers ?? []).map((webWorker)=>({
19
19
  name: webWorker.name,
20
20
  src: webWorker.src,
21
21
  title: webWorker.title,
@@ -23,10 +23,10 @@ const label = (item)=>item.title === item.name ? item.name : `${item.title} (${i
23
23
  }));
24
24
  const lines = [];
25
25
  if (deployedViews.length > 0) lines.push(summarizeGroup('Views', deployedViews));
26
- if (deployedServices.length > 0) lines.push(summarizeGroup('Web workers', deployedServices));
26
+ if (deployedWebWorkers.length > 0) lines.push(summarizeGroup('Web workers', deployedWebWorkers));
27
27
  return {
28
28
  lines,
29
- services: deployedServices,
29
+ services: deployedWebWorkers,
30
30
  views: deployedViews
31
31
  };
32
32
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/actions/deploy/summarizeInterfaces.ts"],"sourcesContent":["import {type ServiceType, type ViewSurface} from '../../contract.js'\nimport {type WorkbenchExposes} from '../../resolveWorkbenchApp.js'\n\ninterface DeployedInterfaceBase {\n name: string\n src: string\n title: string\n}\n\n/** A view as the deploy report and `--json` output surface it. */\nexport interface DeployedView extends DeployedInterfaceBase {\n surface: ViewSurface\n}\n\n/** A web worker as the deploy report and `--json` output surface it. */\nexport interface DeployedWebWorker extends DeployedInterfaceBase {\n type: ServiceType\n}\n\nexport type DeployedInterface = DeployedView | DeployedWebWorker\n\nconst label = (item: {name: string; title: string}) =>\n item.title === item.name ? item.name : `${item.title} (${item.name})`\n\n/**\n * One `Title (name): src` report line per declared entry point.\n * @internal\n */\nexport function summarizeGroup(\n heading: string,\n items: readonly {name: string; src: string; title: string}[],\n): string {\n return `${heading}:\\n${items.map((item) => ` ${label(item)}: ${item.src}`).join('\\n')}`\n}\n\n/**\n * One report line per non-empty group, alongside the records `--json` reports.\n * @internal\n */\nexport function summarizeInterfaces({views, webWorkers}: WorkbenchExposes): {\n lines: string[]\n services: DeployedWebWorker[]\n views: DeployedView[]\n} {\n const deployedViews = (views ?? []).map((view): DeployedView => ({\n name: view.name,\n src: view.src,\n surface: view.surface,\n title: view.title,\n }))\n const deployedServices = (webWorkers ?? []).map((webWorker): DeployedWebWorker => ({\n name: webWorker.name,\n src: webWorker.src,\n title: webWorker.title,\n type: webWorker.type,\n }))\n\n const lines: string[] = []\n if (deployedViews.length > 0) lines.push(summarizeGroup('Views', deployedViews))\n if (deployedServices.length > 0) lines.push(summarizeGroup('Web workers', deployedServices))\n return {lines, services: deployedServices, views: deployedViews}\n}\n"],"names":["label","item","title","name","summarizeGroup","heading","items","map","src","join","summarizeInterfaces","views","webWorkers","deployedViews","view","surface","deployedServices","webWorker","type","lines","length","push","services"],"mappings":"AAqBA,MAAMA,QAAQ,CAACC,OACbA,KAAKC,KAAK,KAAKD,KAAKE,IAAI,GAAGF,KAAKE,IAAI,GAAG,GAAGF,KAAKC,KAAK,CAAC,EAAE,EAAED,KAAKE,IAAI,CAAC,CAAC,CAAC;AAEvE;;;CAGC,GACD,OAAO,SAASC,eACdC,OAAe,EACfC,KAA4D;IAE5D,OAAO,GAAGD,QAAQ,GAAG,EAAEC,MAAMC,GAAG,CAAC,CAACN,OAAS,CAAC,EAAE,EAAED,MAAMC,MAAM,EAAE,EAAEA,KAAKO,GAAG,EAAE,EAAEC,IAAI,CAAC,OAAO;AAC1F;AAEA;;;CAGC,GACD,OAAO,SAASC,oBAAoB,EAACC,KAAK,EAAEC,UAAU,EAAmB;IAKvE,MAAMC,gBAAgB,AAACF,CAAAA,SAAS,EAAE,AAAD,EAAGJ,GAAG,CAAC,CAACO,OAAwB,CAAA;YAC/DX,MAAMW,KAAKX,IAAI;YACfK,KAAKM,KAAKN,GAAG;YACbO,SAASD,KAAKC,OAAO;YACrBb,OAAOY,KAAKZ,KAAK;QACnB,CAAA;IACA,MAAMc,mBAAmB,AAACJ,CAAAA,cAAc,EAAE,AAAD,EAAGL,GAAG,CAAC,CAACU,YAAkC,CAAA;YACjFd,MAAMc,UAAUd,IAAI;YACpBK,KAAKS,UAAUT,GAAG;YAClBN,OAAOe,UAAUf,KAAK;YACtBgB,MAAMD,UAAUC,IAAI;QACtB,CAAA;IAEA,MAAMC,QAAkB,EAAE;IAC1B,IAAIN,cAAcO,MAAM,GAAG,GAAGD,MAAME,IAAI,CAACjB,eAAe,SAASS;IACjE,IAAIG,iBAAiBI,MAAM,GAAG,GAAGD,MAAME,IAAI,CAACjB,eAAe,eAAeY;IAC1E,OAAO;QAACG;QAAOG,UAAUN;QAAkBL,OAAOE;IAAa;AACjE"}
1
+ {"version":3,"sources":["../../../src/actions/deploy/summarizeInterfaces.ts"],"sourcesContent":["import {type ViewSurface, type WebWorkerType} from '../../contract.js'\nimport {type WorkbenchExposes} from '../../resolveWorkbenchApp.js'\n\ninterface DeployedInterfaceBase {\n name: string\n src: string\n title: string\n}\n\n/** A view as the deploy report and `--json` output surface it. */\nexport interface DeployedView extends DeployedInterfaceBase {\n surface: ViewSurface\n}\n\n/** A web worker as the deploy report and `--json` output surface it. */\nexport interface DeployedWebWorker extends DeployedInterfaceBase {\n type: WebWorkerType\n}\n\nexport type DeployedInterface = DeployedView | DeployedWebWorker\n\nconst label = (item: {name: string; title: string}) =>\n item.title === item.name ? item.name : `${item.title} (${item.name})`\n\n/**\n * One `Title (name): src` report line per declared entry point.\n * @internal\n */\nexport function summarizeGroup(\n heading: string,\n items: readonly {name: string; src: string; title: string}[],\n): string {\n return `${heading}:\\n${items.map((item) => ` ${label(item)}: ${item.src}`).join('\\n')}`\n}\n\n/**\n * One report line per non-empty group, alongside the records `--json` reports.\n * @internal\n */\nexport function summarizeInterfaces({views, webWorkers}: WorkbenchExposes): {\n lines: string[]\n services: DeployedWebWorker[]\n views: DeployedView[]\n} {\n const deployedViews = (views ?? []).map((view): DeployedView => ({\n name: view.name,\n src: view.src,\n surface: view.surface,\n title: view.title,\n }))\n const deployedWebWorkers = (webWorkers ?? []).map((webWorker): DeployedWebWorker => ({\n name: webWorker.name,\n src: webWorker.src,\n title: webWorker.title,\n type: webWorker.type,\n }))\n\n const lines: string[] = []\n if (deployedViews.length > 0) lines.push(summarizeGroup('Views', deployedViews))\n if (deployedWebWorkers.length > 0) lines.push(summarizeGroup('Web workers', deployedWebWorkers))\n return {lines, services: deployedWebWorkers, views: deployedViews}\n}\n"],"names":["label","item","title","name","summarizeGroup","heading","items","map","src","join","summarizeInterfaces","views","webWorkers","deployedViews","view","surface","deployedWebWorkers","webWorker","type","lines","length","push","services"],"mappings":"AAqBA,MAAMA,QAAQ,CAACC,OACbA,KAAKC,KAAK,KAAKD,KAAKE,IAAI,GAAGF,KAAKE,IAAI,GAAG,GAAGF,KAAKC,KAAK,CAAC,EAAE,EAAED,KAAKE,IAAI,CAAC,CAAC,CAAC;AAEvE;;;CAGC,GACD,OAAO,SAASC,eACdC,OAAe,EACfC,KAA4D;IAE5D,OAAO,GAAGD,QAAQ,GAAG,EAAEC,MAAMC,GAAG,CAAC,CAACN,OAAS,CAAC,EAAE,EAAED,MAAMC,MAAM,EAAE,EAAEA,KAAKO,GAAG,EAAE,EAAEC,IAAI,CAAC,OAAO;AAC1F;AAEA;;;CAGC,GACD,OAAO,SAASC,oBAAoB,EAACC,KAAK,EAAEC,UAAU,EAAmB;IAKvE,MAAMC,gBAAgB,AAACF,CAAAA,SAAS,EAAE,AAAD,EAAGJ,GAAG,CAAC,CAACO,OAAwB,CAAA;YAC/DX,MAAMW,KAAKX,IAAI;YACfK,KAAKM,KAAKN,GAAG;YACbO,SAASD,KAAKC,OAAO;YACrBb,OAAOY,KAAKZ,KAAK;QACnB,CAAA;IACA,MAAMc,qBAAqB,AAACJ,CAAAA,cAAc,EAAE,AAAD,EAAGL,GAAG,CAAC,CAACU,YAAkC,CAAA;YACnFd,MAAMc,UAAUd,IAAI;YACpBK,KAAKS,UAAUT,GAAG;YAClBN,OAAOe,UAAUf,KAAK;YACtBgB,MAAMD,UAAUC,IAAI;QACtB,CAAA;IAEA,MAAMC,QAAkB,EAAE;IAC1B,IAAIN,cAAcO,MAAM,GAAG,GAAGD,MAAME,IAAI,CAACjB,eAAe,SAASS;IACjE,IAAIG,mBAAmBI,MAAM,GAAG,GAAGD,MAAME,IAAI,CAACjB,eAAe,eAAeY;IAC5E,OAAO;QAACG;QAAOG,UAAUN;QAAoBL,OAAOE;IAAa;AACnE"}
@@ -3,7 +3,7 @@ const noop = async ()=>{};
3
3
  /**
4
4
  * Own the app/studio dev server's lifecycle behind the dev-server registry seam.
5
5
  *
6
- * Adding or removing a view/service rebuilds the federation remote: its
6
+ * Adding or removing a view/web worker rebuilds the federation remote: its
7
7
  * module-federation `exposes` map and codegen artifacts are computed once at
8
8
  * server start, so a newly-declared interface has no expose until the server is
9
9
  * recreated — `server.restart()` can't do it (it reuses the inline config).
@@ -37,7 +37,7 @@ const noop = async ()=>{};
37
37
  const result = await start(freshConfig);
38
38
  if (!result.started) {
39
39
  // The server already reported why (e.g. organizationId was removed).
40
- throw new Error('Dev server did not restart after the view/service change');
40
+ throw new Error('Dev server did not restart after the view/web worker change');
41
41
  }
42
42
  server = result.server;
43
43
  closeCurrent = result.close;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/actions/dev/appServerSupervisor.ts"],"sourcesContent":["import {type CliConfig, getCliConfigUncached} from '@sanity/cli-core'\nimport {type ViteDevServer} from 'vite'\n\n/**\n * Minimal shape the supervisor needs back from a started app/studio dev server.\n * The not-started arm is reserved for expected early exits the server already\n * reported (e.g. a missing organization id) — a failure to *boot* still throws.\n */\nexport type AppServerResult =\n | {close: () => Promise<void>; server: ViteDevServer; started: true}\n | {reason: string; started: false}\n\n/** Start the app/studio dev server for a given config (port + URL intent baked in by the caller). */\nexport type StartAppServer = (cliConfig: CliConfig) => Promise<AppServerResult>\n\nconst noop = async () => {}\n\nexport interface AppServerSupervisor {\n /** Stop the server once, waiting out any rebuild already in flight. */\n close: () => Promise<void>\n /** Tear down the running server and bring it back up with a freshly-loaded config. */\n rebuild: () => Promise<ViteDevServer>\n /** The currently-live dev server; re-points after a rebuild. */\n readonly server: ViteDevServer\n}\n\n/**\n * Own the app/studio dev server's lifecycle behind the dev-server registry seam.\n *\n * Adding or removing a view/service rebuilds the federation remote: its\n * module-federation `exposes` map and codegen artifacts are computed once at\n * server start, so a newly-declared interface has no expose until the server is\n * recreated — `server.restart()` can't do it (it reuses the inline config).\n * `rebuild` therefore tears the server down and starts a fresh one with a\n * reloaded config; the registry watcher calls it when the interface set changes.\n *\n * Returns the not-started result verbatim when the initial boot is an expected\n * early exit, so the caller can skip the rest of the orchestration.\n */\nexport async function startAppServerSupervisor(options: {\n cliConfig: CliConfig\n start: StartAppServer\n workDir: string\n}): Promise<{reason: string; started: false} | {started: true; supervisor: AppServerSupervisor}> {\n const {cliConfig, start, workDir} = options\n\n const initial = await start(cliConfig)\n if (!initial.started) return {reason: initial.reason, started: false}\n\n // `closeCurrent` repoints at the replacement only once a rebuild succeeds, so a\n // failed rebuild (old server already closed) leaves nothing for close() to re-close.\n let server = initial.server\n let closeCurrent = initial.close\n let closed = false\n // close() waits on this so a rebuild racing teardown can't orphan the replacement.\n // Rejections are the watcher's (warn + retry); the tracked copy is swallowed.\n let rebuildInFlight: Promise<unknown> = Promise.resolve()\n\n const runRebuild = async (): Promise<ViteDevServer> => {\n // Refuse once shutting down — a config save in the teardown window must not\n // boot a replacement nobody owns.\n if (closed) throw new Error('Dev server is shutting down')\n const freshConfig = await getCliConfigUncached(workDir)\n await closeCurrent()\n closeCurrent = noop\n const result = await start(freshConfig)\n if (!result.started) {\n // The server already reported why (e.g. organizationId was removed).\n throw new Error('Dev server did not restart after the view/service change')\n }\n server = result.server\n closeCurrent = result.close\n return server\n }\n\n return {\n started: true,\n supervisor: {\n async close() {\n closed = true\n await rebuildInFlight\n await closeCurrent()\n },\n rebuild() {\n const rebuild = runRebuild()\n rebuildInFlight = rebuild.catch(() => {})\n return rebuild\n },\n get server() {\n return server\n },\n },\n }\n}\n"],"names":["getCliConfigUncached","noop","startAppServerSupervisor","options","cliConfig","start","workDir","initial","started","reason","server","closeCurrent","close","closed","rebuildInFlight","Promise","resolve","runRebuild","Error","freshConfig","result","supervisor","rebuild","catch"],"mappings":"AAAA,SAAwBA,oBAAoB,QAAO,mBAAkB;AAerE,MAAMC,OAAO,WAAa;AAW1B;;;;;;;;;;;;CAYC,GACD,OAAO,eAAeC,yBAAyBC,OAI9C;IACC,MAAM,EAACC,SAAS,EAAEC,KAAK,EAAEC,OAAO,EAAC,GAAGH;IAEpC,MAAMI,UAAU,MAAMF,MAAMD;IAC5B,IAAI,CAACG,QAAQC,OAAO,EAAE,OAAO;QAACC,QAAQF,QAAQE,MAAM;QAAED,SAAS;IAAK;IAEpE,gFAAgF;IAChF,qFAAqF;IACrF,IAAIE,SAASH,QAAQG,MAAM;IAC3B,IAAIC,eAAeJ,QAAQK,KAAK;IAChC,IAAIC,SAAS;IACb,mFAAmF;IACnF,8EAA8E;IAC9E,IAAIC,kBAAoCC,QAAQC,OAAO;IAEvD,MAAMC,aAAa;QACjB,4EAA4E;QAC5E,kCAAkC;QAClC,IAAIJ,QAAQ,MAAM,IAAIK,MAAM;QAC5B,MAAMC,cAAc,MAAMnB,qBAAqBM;QAC/C,MAAMK;QACNA,eAAeV;QACf,MAAMmB,SAAS,MAAMf,MAAMc;QAC3B,IAAI,CAACC,OAAOZ,OAAO,EAAE;YACnB,qEAAqE;YACrE,MAAM,IAAIU,MAAM;QAClB;QACAR,SAASU,OAAOV,MAAM;QACtBC,eAAeS,OAAOR,KAAK;QAC3B,OAAOF;IACT;IAEA,OAAO;QACLF,SAAS;QACTa,YAAY;YACV,MAAMT;gBACJC,SAAS;gBACT,MAAMC;gBACN,MAAMH;YACR;YACAW;gBACE,MAAMA,UAAUL;gBAChBH,kBAAkBQ,QAAQC,KAAK,CAAC,KAAO;gBACvC,OAAOD;YACT;YACA,IAAIZ;gBACF,OAAOA;YACT;QACF;IACF;AACF"}
1
+ {"version":3,"sources":["../../../src/actions/dev/appServerSupervisor.ts"],"sourcesContent":["import {type CliConfig, getCliConfigUncached} from '@sanity/cli-core'\nimport {type ViteDevServer} from 'vite'\n\n/**\n * Minimal shape the supervisor needs back from a started app/studio dev server.\n * The not-started arm is reserved for expected early exits the server already\n * reported (e.g. a missing organization id) — a failure to *boot* still throws.\n */\nexport type AppServerResult =\n | {close: () => Promise<void>; server: ViteDevServer; started: true}\n | {reason: string; started: false}\n\n/** Start the app/studio dev server for a given config (port + URL intent baked in by the caller). */\nexport type StartAppServer = (cliConfig: CliConfig) => Promise<AppServerResult>\n\nconst noop = async () => {}\n\nexport interface AppServerSupervisor {\n /** Stop the server once, waiting out any rebuild already in flight. */\n close: () => Promise<void>\n /** Tear down the running server and bring it back up with a freshly-loaded config. */\n rebuild: () => Promise<ViteDevServer>\n /** The currently-live dev server; re-points after a rebuild. */\n readonly server: ViteDevServer\n}\n\n/**\n * Own the app/studio dev server's lifecycle behind the dev-server registry seam.\n *\n * Adding or removing a view/web worker rebuilds the federation remote: its\n * module-federation `exposes` map and codegen artifacts are computed once at\n * server start, so a newly-declared interface has no expose until the server is\n * recreated — `server.restart()` can't do it (it reuses the inline config).\n * `rebuild` therefore tears the server down and starts a fresh one with a\n * reloaded config; the registry watcher calls it when the interface set changes.\n *\n * Returns the not-started result verbatim when the initial boot is an expected\n * early exit, so the caller can skip the rest of the orchestration.\n */\nexport async function startAppServerSupervisor(options: {\n cliConfig: CliConfig\n start: StartAppServer\n workDir: string\n}): Promise<{reason: string; started: false} | {started: true; supervisor: AppServerSupervisor}> {\n const {cliConfig, start, workDir} = options\n\n const initial = await start(cliConfig)\n if (!initial.started) return {reason: initial.reason, started: false}\n\n // `closeCurrent` repoints at the replacement only once a rebuild succeeds, so a\n // failed rebuild (old server already closed) leaves nothing for close() to re-close.\n let server = initial.server\n let closeCurrent = initial.close\n let closed = false\n // close() waits on this so a rebuild racing teardown can't orphan the replacement.\n // Rejections are the watcher's (warn + retry); the tracked copy is swallowed.\n let rebuildInFlight: Promise<unknown> = Promise.resolve()\n\n const runRebuild = async (): Promise<ViteDevServer> => {\n // Refuse once shutting down — a config save in the teardown window must not\n // boot a replacement nobody owns.\n if (closed) throw new Error('Dev server is shutting down')\n const freshConfig = await getCliConfigUncached(workDir)\n await closeCurrent()\n closeCurrent = noop\n const result = await start(freshConfig)\n if (!result.started) {\n // The server already reported why (e.g. organizationId was removed).\n throw new Error('Dev server did not restart after the view/web worker change')\n }\n server = result.server\n closeCurrent = result.close\n return server\n }\n\n return {\n started: true,\n supervisor: {\n async close() {\n closed = true\n await rebuildInFlight\n await closeCurrent()\n },\n rebuild() {\n const rebuild = runRebuild()\n rebuildInFlight = rebuild.catch(() => {})\n return rebuild\n },\n get server() {\n return server\n },\n },\n }\n}\n"],"names":["getCliConfigUncached","noop","startAppServerSupervisor","options","cliConfig","start","workDir","initial","started","reason","server","closeCurrent","close","closed","rebuildInFlight","Promise","resolve","runRebuild","Error","freshConfig","result","supervisor","rebuild","catch"],"mappings":"AAAA,SAAwBA,oBAAoB,QAAO,mBAAkB;AAerE,MAAMC,OAAO,WAAa;AAW1B;;;;;;;;;;;;CAYC,GACD,OAAO,eAAeC,yBAAyBC,OAI9C;IACC,MAAM,EAACC,SAAS,EAAEC,KAAK,EAAEC,OAAO,EAAC,GAAGH;IAEpC,MAAMI,UAAU,MAAMF,MAAMD;IAC5B,IAAI,CAACG,QAAQC,OAAO,EAAE,OAAO;QAACC,QAAQF,QAAQE,MAAM;QAAED,SAAS;IAAK;IAEpE,gFAAgF;IAChF,qFAAqF;IACrF,IAAIE,SAASH,QAAQG,MAAM;IAC3B,IAAIC,eAAeJ,QAAQK,KAAK;IAChC,IAAIC,SAAS;IACb,mFAAmF;IACnF,8EAA8E;IAC9E,IAAIC,kBAAoCC,QAAQC,OAAO;IAEvD,MAAMC,aAAa;QACjB,4EAA4E;QAC5E,kCAAkC;QAClC,IAAIJ,QAAQ,MAAM,IAAIK,MAAM;QAC5B,MAAMC,cAAc,MAAMnB,qBAAqBM;QAC/C,MAAMK;QACNA,eAAeV;QACf,MAAMmB,SAAS,MAAMf,MAAMc;QAC3B,IAAI,CAACC,OAAOZ,OAAO,EAAE;YACnB,qEAAqE;YACrE,MAAM,IAAIU,MAAM;QAClB;QACAR,SAASU,OAAOV,MAAM;QACtBC,eAAeS,OAAOR,KAAK;QAC3B,OAAOF;IACT;IAEA,OAAO;QACLF,SAAS;QACTa,YAAY;YACV,MAAMT;gBACJC,SAAS;gBACT,MAAMC;gBACN,MAAMH;YACR;YACAW;gBACE,MAAMA,UAAUL;gBAChBH,kBAAkBQ,QAAQC,KAAK,CAAC,KAAO;gBACvC,OAAOD;YACT;YACA,IAAIZ;gBACF,OAAOA;YACT;QACF;IACF;AACF"}
@@ -1,7 +1,7 @@
1
1
  import { deriveConfigEntries } from './deriveConfigs.js';
2
2
  /**
3
3
  * Order-independent id of an app's exposed-module set. Keys each interface by
4
- * its surface or service type, name, and source file, and each config by its module
4
+ * its surface or web worker type, name, and source file, and each config by its module
5
5
  * identity plus one key per entry (a named source file), so the id changes on
6
6
  * any rebuild-worthy edit — add, remove, rename, repoint, or gaining/losing the
7
7
  * config module — while reordering and HMR content edits keep it stable.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/actions/dev/exposesSetId.ts"],"sourcesContent":["import {\n deriveConfigEntries,\n type DevServerConfig,\n type DevServerInterface,\n} from './deriveConfigs.js'\nimport {type DevServerManifest} from './registry.js'\n\ninterface ExposeSet {\n configs?: readonly DevServerConfig[] | undefined\n interfaces?: readonly DevServerInterface[] | undefined\n}\n\n/**\n * Order-independent id of an app's exposed-module set. Keys each interface by\n * its surface or service type, name, and source file, and each config by its module\n * identity plus one key per entry (a named source file), so the id changes on\n * any rebuild-worthy edit — add, remove, rename, repoint, or gaining/losing the\n * config module — while reordering and HMR content edits keep it stable.\n */\nexport function exposesSetId({configs, interfaces}: ExposeSet): string {\n const keys = [\n ...(interfaces ?? []).map((iface) =>\n ['surface' in iface ? iface.surface : iface.type, iface.name, iface.src].join('::'),\n ),\n ...(configs ?? []).flatMap((config) => [\n ['config', config.appType].join('::'),\n ...deriveConfigEntries(config).map((entry) =>\n ['config', config.appType, entry.name, entry.src].join('::'),\n ),\n ]),\n ]\n if (keys.length === 0) return ''\n return keys.toSorted().join('|')\n}\n\n/**\n * `changed`/`commit` are split so the caller commits only after the rebuild that\n * depends on the new set succeeds — a thrown rebuild retries on the next save.\n */\nexport function trackExposesSet(initial: ExposeSet): {\n changed: (next: ExposeSet) => boolean\n commit: (next: ExposeSet) => void\n} {\n let lastId = exposesSetId(initial)\n return {\n changed: (next) => exposesSetId(next) !== lastId,\n commit: (next) => {\n lastId = exposesSetId(next)\n },\n }\n}\n\nconst serverKey = (server: DevServerManifest): string =>\n `${server.id ?? ''}@${server.host ?? ''}:${server.port}`\n\nconst serverExposesId = (server: DevServerManifest): string =>\n exposesSetId({configs: server.configs, interfaces: server.interfaces})\n\n/**\n * Multi-app counterpart to {@link trackExposesSet}: true when a *known* app's\n * set changed — its remote was rebuilt, so the workbench must full-reload to\n * drop the stale remote-entry. A new/removed app isn't a rebuild.\n */\nexport function createExposesTracker(): {\n hasChanged: (servers: readonly DevServerManifest[]) => boolean\n} {\n let known = new Map<string, string>()\n return {\n hasChanged(servers) {\n const rebuilt = servers.some((server) => {\n const key = serverKey(server)\n return known.has(key) && known.get(key) !== serverExposesId(server)\n })\n known = new Map(servers.map((server) => [serverKey(server), serverExposesId(server)]))\n return rebuilt\n },\n }\n}\n"],"names":["deriveConfigEntries","exposesSetId","configs","interfaces","keys","map","iface","surface","type","name","src","join","flatMap","config","appType","entry","length","toSorted","trackExposesSet","initial","lastId","changed","next","commit","serverKey","server","id","host","port","serverExposesId","createExposesTracker","known","Map","hasChanged","servers","rebuilt","some","key","has","get"],"mappings":"AAAA,SACEA,mBAAmB,QAGd,qBAAoB;AAQ3B;;;;;;CAMC,GACD,OAAO,SAASC,aAAa,EAACC,OAAO,EAAEC,UAAU,EAAY;IAC3D,MAAMC,OAAO;WACR,AAACD,CAAAA,cAAc,EAAE,AAAD,EAAGE,GAAG,CAAC,CAACC,QACzB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7B,GAAG,CAAC,CAACoB,SAAW;oBAACD,UAAUC;oBAASI,gBAAgBJ;iBAAQ;YACpF,OAAOU;QACT;IACF;AACF"}
1
+ {"version":3,"sources":["../../../src/actions/dev/exposesSetId.ts"],"sourcesContent":["import {\n deriveConfigEntries,\n type DevServerConfig,\n type DevServerInterface,\n} from './deriveConfigs.js'\nimport {type DevServerManifest} from './registry.js'\n\ninterface ExposeSet {\n configs?: readonly DevServerConfig[] | undefined\n interfaces?: readonly DevServerInterface[] | undefined\n}\n\n/**\n * Order-independent id of an app's exposed-module set. Keys each interface by\n * its surface or web worker type, name, and source file, and each config by its module\n * identity plus one key per entry (a named source file), so the id changes on\n * any rebuild-worthy edit — add, remove, rename, repoint, or gaining/losing the\n * config module — while reordering and HMR content edits keep it stable.\n */\nexport function exposesSetId({configs, interfaces}: ExposeSet): string {\n const keys = [\n ...(interfaces ?? []).map((iface) =>\n ['surface' in iface ? iface.surface : iface.type, iface.name, iface.src].join('::'),\n ),\n ...(configs ?? []).flatMap((config) => [\n ['config', config.appType].join('::'),\n ...deriveConfigEntries(config).map((entry) =>\n ['config', config.appType, entry.name, entry.src].join('::'),\n ),\n ]),\n ]\n if (keys.length === 0) return ''\n return keys.toSorted().join('|')\n}\n\n/**\n * `changed`/`commit` are split so the caller commits only after the rebuild that\n * depends on the new set succeeds — a thrown rebuild retries on the next save.\n */\nexport function trackExposesSet(initial: ExposeSet): {\n changed: (next: ExposeSet) => boolean\n commit: (next: ExposeSet) => void\n} {\n let lastId = exposesSetId(initial)\n return {\n changed: (next) => exposesSetId(next) !== lastId,\n commit: (next) => {\n lastId = exposesSetId(next)\n },\n }\n}\n\nconst serverKey = (server: DevServerManifest): string =>\n `${server.id ?? ''}@${server.host ?? ''}:${server.port}`\n\nconst serverExposesId = (server: DevServerManifest): string =>\n exposesSetId({configs: server.configs, interfaces: server.interfaces})\n\n/**\n * Multi-app counterpart to {@link trackExposesSet}: true when a *known* app's\n * set changed — its remote was rebuilt, so the workbench must full-reload to\n * drop the stale remote-entry. A new/removed app isn't a rebuild.\n */\nexport function createExposesTracker(): {\n hasChanged: (servers: readonly DevServerManifest[]) => boolean\n} {\n let known = new Map<string, string>()\n return {\n hasChanged(servers) {\n const rebuilt = servers.some((server) => {\n const key = serverKey(server)\n return known.has(key) && known.get(key) !== serverExposesId(server)\n })\n known = new Map(servers.map((server) => [serverKey(server), serverExposesId(server)]))\n return rebuilt\n },\n }\n}\n"],"names":["deriveConfigEntries","exposesSetId","configs","interfaces","keys","map","iface","surface","type","name","src","join","flatMap","config","appType","entry","length","toSorted","trackExposesSet","initial","lastId","changed","next","commit","serverKey","server","id","host","port","serverExposesId","createExposesTracker","known","Map","hasChanged","servers","rebuilt","some","key","has","get"],"mappings":"AAAA,SACEA,mBAAmB,QAGd,qBAAoB;AAQ3B;;;;;;CAMC,GACD,OAAO,SAASC,aAAa,EAACC,OAAO,EAAEC,UAAU,EAAY;IAC3D,MAAMC,OAAO;WACR,AAACD,CAAAA,cAAc,EAAE,AAAD,EAAGE,GAAG,CAAC,CAACC,QACzB;gBAAC,aAAaA,QAAQA,MAAMC,OAAO,GAAGD,MAAME,IAAI;gBAAEF,MAAMG,IAAI;gBAAEH,MAAMI,GAAG;aAAC,CAACC,IAAI,CAAC;WAE7E,AAACT,CAAAA,WAAW,EAAE,AAAD,EAAGU,OAAO,CAAC,CAACC,SAAW;gBACrC;oBAAC;oBAAUA,OAAOC,OAAO;iBAAC,CAACH,IAAI,CAAC;mBAC7BX,oBAAoBa,QAAQR,GAAG,CAAC,CAACU,QAClC;wBAAC;wBAAUF,OAAOC,OAAO;wBAAEC,MAAMN,IAAI;wBAAEM,MAAML,GAAG;qBAAC,CAACC,IAAI,CAAC;aAE1D;KACF;IACD,IAAIP,KAAKY,MAAM,KAAK,GAAG,OAAO;IAC9B,OAAOZ,KAAKa,QAAQ,GAAGN,IAAI,CAAC;AAC9B;AAEA;;;CAGC,GACD,OAAO,SAASO,gBAAgBC,OAAkB;IAIhD,IAAIC,SAASnB,aAAakB;IAC1B,OAAO;QACLE,SAAS,CAACC,OAASrB,aAAaqB,UAAUF;QAC1CG,QAAQ,CAACD;YACPF,SAASnB,aAAaqB;QACxB;IACF;AACF;AAEA,MAAME,YAAY,CAACC,SACjB,GAAGA,OAAOC,EAAE,IAAI,GAAG,CAAC,EAAED,OAAOE,IAAI,IAAI,GAAG,CAAC,EAAEF,OAAOG,IAAI,EAAE;AAE1D,MAAMC,kBAAkB,CAACJ,SACvBxB,aAAa;QAACC,SAASuB,OAAOvB,OAAO;QAAEC,YAAYsB,OAAOtB,UAAU;IAAA;AAEtE;;;;CAIC,GACD,OAAO,SAAS2B;IAGd,IAAIC,QAAQ,IAAIC;IAChB,OAAO;QACLC,YAAWC,OAAO;YAChB,MAAMC,UAAUD,QAAQE,IAAI,CAAC,CAACX;gBAC5B,MAAMY,MAAMb,UAAUC;gBACtB,OAAOM,MAAMO,GAAG,CAACD,QAAQN,MAAMQ,GAAG,CAACF,SAASR,gBAAgBJ;YAC9D;YACAM,QAAQ,IAAIC,IAAIE,QAAQ7B,GAAG,CAAC,CAACoB,SAAW;oBAACD,UAAUC;oBAASI,gBAAgBJ;iBAAQ;YACpF,OAAOU;QACT;IACF;AACF"}
@@ -226,6 +226,7 @@ function runExitCleanups() {
226
226
  */ export function registerDevServer(manifest) {
227
227
  const registryDir = getRegistryDir();
228
228
  mkdirSync(registryDir, {
229
+ mode: 0o700,
229
230
  recursive: true
230
231
  });
231
232
  let current = {
@@ -235,7 +236,9 @@ function runExitCleanups() {
235
236
  version: REGISTRY_VERSION
236
237
  };
237
238
  const filePath = join(registryDir, `${process.pid}.json`);
238
- writeFileSync(filePath, JSON.stringify(current, null, 2));
239
+ writeFileSync(filePath, JSON.stringify(current, null, 2), {
240
+ mode: 0o600
241
+ });
239
242
  // Guard against late updates from background tasks (e.g. the initial
240
243
  // manifest extraction) landing after `release()` has deleted the file —
241
244
  // without this, the update would re-create the registry entry and leak.
@@ -258,7 +261,9 @@ function runExitCleanups() {
258
261
  ...current,
259
262
  ...patch
260
263
  };
261
- writeFileSync(filePath, JSON.stringify(current, null, 2));
264
+ writeFileSync(filePath, JSON.stringify(current, null, 2), {
265
+ mode: 0o600
266
+ });
262
267
  }
263
268
  };
264
269
  }
@@ -303,6 +308,7 @@ function runExitCleanups() {
303
308
  */ export function watchRegistry(callback) {
304
309
  const registryDir = getRegistryDir();
305
310
  mkdirSync(registryDir, {
311
+ mode: 0o700,
306
312
  recursive: true
307
313
  });
308
314
  // Canonicalize to the real long path so `fs.watch` doesn't abort on Windows
@@ -422,6 +428,7 @@ function pruneWorkbenchLock(lockPath) {
422
428
  */ export function acquireWorkbenchLock(info, retries = 1) {
423
429
  const registryDir = getRegistryDir();
424
430
  mkdirSync(registryDir, {
431
+ mode: 0o700,
425
432
  recursive: true
426
433
  });
427
434
  const lockPath = getLockPath(info.organizationId);
@@ -437,7 +444,8 @@ function pruneWorkbenchLock(lockPath) {
437
444
  devDebug('Acquiring workbench lock at %s', lockPath);
438
445
  try {
439
446
  writeFileSync(lockPath, JSON.stringify(lockData), {
440
- flag: 'wx'
447
+ flag: 'wx',
448
+ mode: 0o600
441
449
  });
442
450
  devDebug('Workbench lock acquired');
443
451
  let released = false;
@@ -463,7 +471,9 @@ function pruneWorkbenchLock(lockPath) {
463
471
  ...lockData,
464
472
  port,
465
473
  ready: true
466
- }));
474
+ }), {
475
+ mode: 0o600
476
+ });
467
477
  }
468
478
  };
469
479
  } catch (err) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/actions/dev/registry.ts"],"sourcesContent":["import {\n existsSync,\n mkdirSync,\n readdirSync,\n readFileSync,\n unlinkSync,\n watch,\n writeFileSync,\n} from 'node:fs'\nimport {join} from 'node:path'\n\nimport {\n coreAppManifestSchema,\n getSanityDataDir,\n studioManifestSchema,\n subdebug,\n} from '@sanity/cli-core'\nimport {z} from 'zod/mini'\n\nimport {applicationReference} from '../../applicationReference.js'\nimport {TileInterfaceMetadataSchema, ViewPlacementMetadataSchema} from '../../contract.js'\nimport {type WorkbenchApp} from '../../defineApp.js'\nimport {canonicalizeWatchDir} from './canonicalizeWatchDir.js'\nimport {getProcessStartTime, isOurProcess} from './processLiveness.js'\n\n/**\n * The dev-server registry: how a running `sanity dev` / `sanity start` process\n * advertises itself so the workbench on this machine can find and load it.\n *\n * Two kinds of file under `~/.sanity/dev-servers/` do the coordinating:\n *\n * - `<pid>.json` — one per running app/studio server, holding where it's served\n * plus its inlined manifest and interfaces. The workbench reads these to\n * discover and render local apps. Written by `registerDevServer`, watched by\n * `watchRegistry`.\n * - `workbench-<organizationId>.lock` — one lock per organization, so only one\n * workbench shell per org runs at a time and later `dev`s register into it\n * instead of starting their own. Managed by `acquireWorkbenchLock` / `readWorkbenchLock`.\n *\n * Both files belong to the process that created them and must not outlive it.\n * Three things keep that true: an explicit `release()` on clean shutdown, an\n * `exit` backstop for abrupt exits (`unlinkOnProcessExit`), and a dead-pid prune\n * on read (`isOurProcess`) that clears whatever a crashed process left behind.\n */\n\nconst devDebug = subdebug('dev')\n\n/** Bump when the manifest/lock shape changes in a breaking way. */\nconst REGISTRY_VERSION = 2\n\n/**\n * The current process's start time as reported by the OS, for the `startedAt`\n * that `isOurProcess` checks on re-read. Falls back to now when the OS time is\n * unavailable — `new Date()` alone records the write time, which drifts from\n * process start by enough to look stale and get pruned right after writing.\n */\nfunction ownStartedAt(): string {\n return (getProcessStartTime(process.pid) ?? new Date()).toISOString()\n}\n\nconst interfaceBaseFields = {\n /** CLI-minted for a local interface; a deployed one gets its id from Brett. */\n id: z.string(),\n moduleId: z.string(),\n name: z.string(),\n /** Raw source vite serves; a deployed interface carries only the `moduleId`. */\n src: z.string(),\n title: z.string(),\n version: z.optional(z.string()),\n}\n\n/**\n * A forwarded interface. Kept outside the manifest so\n * the workbench renders local panels and runs workers without a deploy.\n */\nconst devServerInterfaceSchema = z.union([\n z.discriminatedUnion('surface', [\n z.object({\n ...interfaceBaseFields,\n metadata: z.nullable(ViewPlacementMetadataSchema),\n surface: z.literal('window'),\n }),\n z.object({\n ...interfaceBaseFields,\n metadata: z.nullable(ViewPlacementMetadataSchema),\n surface: z.literal('panel'),\n }),\n z.object({...interfaceBaseFields, metadata: z.null(), surface: z.literal('asset_source')}),\n z.object({\n ...interfaceBaseFields,\n metadata: TileInterfaceMetadataSchema,\n surface: z.literal('tile'),\n }),\n ]),\n z.object({...interfaceBaseFields, metadata: z.null(), type: z.literal('worker')}),\n])\n\n// Exported so test fixtures can validate against the same schema the registry\n// parses with — see `aDevServerManifest`. Used internally by `getRegisteredServers`.\nexport const devServerManifestSchema = z.object({\n applicationId: z.optional(z.string()),\n /**\n * Field schema *values* load from the federation module; each field's `src`\n * rides along so a repoint bumps the exposes-set id and forces a rebuild.\n * Lenient — the workbench is the authority.\n */\n configs: z.optional(\n z.array(\n z.object({\n // Identifies the owning app when it has no app id (singletons).\n appType: z.optional(z.string()),\n fields: z.array(\n z.object({\n name: z.string(),\n public: z.optional(z.boolean()),\n src: z.string(),\n title: z.string(),\n }),\n ),\n // Content hash of the config — the workbench's change-detection key\n // (see deriveConfigs).\n id: z.string(),\n // The app's `defineApplication` slug — the module-federation alias the\n // workbench loads this config's live values from.\n moduleName: z.optional(z.string()),\n // The version the workbench federates this config's module under —\n // a string, like the one Brett returns on a deployed `activeConfig`.\n version: z.string(),\n }),\n ),\n ),\n host: z.string(),\n /**\n * The id the app runs under on the bus. It stays apart from `applicationId`,\n * because Dashboards that predate `applicationId` key local apps on it.\n */\n id: z.optional(z.string()),\n interfaces: z.optional(z.array(devServerInterfaceSchema)),\n /**\n * Inlined manifest — either a {@link StudioManifest} or {@link CoreAppManifest},\n * validated against the shared cli-core schemas. The registry stores and\n * rebroadcasts it; the CLI is what extracts and writes it.\n */\n manifest: z.optional(z.union([studioManifestSchema, coreAppManifestSchema])),\n /**\n * ISO timestamp of the most recent successful manifest extraction. Bumped\n * on every regeneration so re-writing this registry entry triggers the\n * workbench `watchRegistry` watcher and forces a rebroadcast to clients.\n */\n manifestUpdatedAt: z.optional(z.string()),\n // Stable identity + qualified reference, composed by the CLI (the authority for\n // local apps, which never reach brett) and read straight by the workbench.\n name: z.optional(z.string()),\n organizationId: z.optional(z.string()),\n pid: z.number(),\n port: z.number(),\n projectId: z.optional(z.string()),\n reference: z.optional(z.string()),\n slug: z.optional(z.string()),\n startedAt: z.string(),\n type: z.enum(['coreApp', 'studio']),\n version: z.literal(REGISTRY_VERSION),\n visibility: z.optional(z.enum(['default', 'unlisted', 'disabled'])),\n workDir: z.string(),\n})\n/**\n * A manifest describing a running dev server process (studio or app).\n * Stored as `~/.sanity/dev-servers/<pid>.json`.\n *\n * The workbench singleton is tracked separately via the lock file — see\n * `acquireWorkbenchLock` and `readWorkbenchLock` below.\n */\nexport type DevServerManifest = z.infer<typeof devServerManifestSchema>\n\n/**\n * A config-only server carries configs but no interfaces — e.g. a\n * media-library config app under development. The workbench never routes it\n * as an app; only its configs are published. It therefore plays a different\n * role than an app server, and the two may share a slug (a config app\n * developed alongside the locally served singleton it configures).\n */\nexport function isConfigOnlyServer(\n server: Pick<DevServerManifest, 'configs' | 'interfaces'>,\n): boolean {\n return Boolean(server.configs?.length) && !server.interfaces?.length\n}\n\nexport function localAppIdentity(\n app: Pick<WorkbenchApp, 'isSingleton' | 'name' | 'organizationId' | 'slug' | 'visibility'>,\n): Pick<DevServerManifest, 'name' | 'organizationId' | 'reference' | 'slug' | 'visibility'> {\n const name = app.name ?? app.slug\n\n return {\n name,\n organizationId: app.organizationId,\n reference: applicationReference({\n isSingleton: app.isSingleton ?? false,\n name,\n organizationId: app.organizationId,\n }),\n slug: app.slug,\n visibility: app.visibility ?? 'default',\n }\n}\n\n/**\n * Where the Dashboard shell opens a registered server, matching the Workbench's\n * `StudioApplication.href` and `CoreApplication.href`. Only servers with a\n * `surface: 'window'` interface get one (see toWireInterface): studios always do,\n * configs and panel-only apps don't, so they'd 404.\n */\nexport function dashboardPath(\n server: Pick<DevServerManifest, 'id' | 'interfaces' | 'slug' | 'type'>,\n): string | undefined {\n const hasAppView = (server.interfaces ?? []).some(\n (iface) => 'surface' in iface && iface.surface === 'window',\n )\n\n const segment = server.slug ?? server.id\n\n if (!segment || !hasAppView) {\n return undefined\n }\n\n const root = server.type === 'studio' ? 'studios' : 'applications'\n\n return `/${root}/${encodeURIComponent(segment)}`\n}\n\n/**\n * Path to the dev server registry directory. Lives under the shared Sanity\n * config directory to stay consistent with other CLI paths.\n */\nfunction getRegistryDir(): string {\n return join(getSanityDataDir(), 'dev-servers')\n}\n\n// One shared `exit` listener drives every registered cleanup, so N locks/entries\n// don't each add a listener and trip Node's MaxListeners warning.\nconst exitCleanups = new Set<() => void>()\nlet exitListenerInstalled = false\n\nfunction runExitCleanups(): void {\n for (const cleanup of exitCleanups) cleanup()\n}\n\n/** Exercise the exit backstop in tests without terminating the process; not part\n * of the package's public surface. */\nexport const runRegistryExitCleanupForTesting = runExitCleanups\n\n/**\n * Delete a registry file synchronously on process exit, as a backstop for abrupt\n * termination. Vite installs its own SIGTERM handler that calls `process.exit()`,\n * which can outrun the async server teardown and leave the lock or registry entry\n * behind — a stray dev-server that lingers until the dead-pid prune clears it. The\n * `exit` event only runs synchronous work, hence `unlinkSync`. `ownedByUs` guards\n * the shared lock so a successor that reacquired it isn't wiped. Returns a\n * detacher to call after a clean release.\n */\nfunction unlinkOnProcessExit(filePath: string, ownedByUs: () => boolean): () => void {\n const cleanup = () => {\n if (!ownedByUs()) return\n try {\n unlinkSync(filePath)\n } catch {\n // The file may already have been removed during shutdown.\n }\n }\n exitCleanups.add(cleanup)\n\n if (!exitListenerInstalled) {\n exitListenerInstalled = true\n process.once('exit', runExitCleanups)\n }\n\n return () => exitCleanups.delete(cleanup)\n}\n\ninterface DevServerRegistration {\n /** Remove the registry entry. */\n release: () => void\n /**\n * Rewrite the registry entry with partial updates merged in. Also bumps the\n * file's mtime, which fires `watchRegistry` in any workbench process and\n * triggers a rebroadcast to connected clients.\n */\n update: (patch: Partial<Omit<DevServerManifest, 'pid' | 'startedAt' | 'version'>>) => void\n}\n\n/**\n * Write a manifest file for the current process and return a handle with a\n * `release` function that removes it plus an `update` function for patching\n * fields post-registration. Uses synchronous I/O so the file exists before\n * any signal handler could fire.\n */\nexport function registerDevServer(\n manifest: Omit<DevServerManifest, 'pid' | 'startedAt' | 'version'>,\n): DevServerRegistration {\n const registryDir = getRegistryDir()\n mkdirSync(registryDir, {recursive: true})\n\n let current: DevServerManifest = {\n ...manifest,\n pid: process.pid,\n startedAt: ownStartedAt(),\n version: REGISTRY_VERSION,\n }\n\n const filePath = join(registryDir, `${process.pid}.json`)\n writeFileSync(filePath, JSON.stringify(current, null, 2))\n\n // Guard against late updates from background tasks (e.g. the initial\n // manifest extraction) landing after `release()` has deleted the file —\n // without this, the update would re-create the registry entry and leak.\n let released = false\n\n // The file is pid-named, so it's always ours to remove on exit.\n const detachExitCleanup = unlinkOnProcessExit(filePath, () => !released)\n\n return {\n release() {\n released = true\n detachExitCleanup()\n try {\n unlinkSync(filePath)\n } catch {\n // ENOENT is fine — already cleaned up\n }\n },\n update(patch) {\n if (released) return\n current = {...current, ...patch}\n writeFileSync(filePath, JSON.stringify(current, null, 2))\n },\n }\n}\n\n/**\n * Read all manifest files from the registry, prune stale entries (dead PIDs),\n * and return the live ones.\n */\nexport function getRegisteredServers(): DevServerManifest[] {\n const registryDir = getRegistryDir()\n\n if (!existsSync(registryDir)) {\n return []\n }\n\n const files = readdirSync(registryDir).filter((f) => f.endsWith('.json'))\n const servers: DevServerManifest[] = []\n\n for (const file of files) {\n const filePath = join(registryDir, file)\n let raw: unknown\n try {\n raw = JSON.parse(readFileSync(filePath, 'utf8'))\n } catch {\n continue\n }\n\n const {data, success} = devServerManifestSchema.safeParse(raw)\n if (!success) continue\n\n if (isOurProcess(data.pid, data.startedAt)) {\n servers.push(data)\n } else {\n try {\n unlinkSync(filePath)\n } catch {\n // Ignore — another process may have already cleaned it up\n }\n }\n }\n\n return servers\n}\n\ninterface RegistryWatcher {\n close(): void\n}\n\n/**\n * Watch the registry directory for changes and invoke the callback with the\n * current list of live servers whenever a change is detected.\n *\n * Uses `fs.watch` with a debounce to coalesce rapid file changes (e.g. a\n * server starting and writing its manifest triggers multiple FS events).\n */\nexport function watchRegistry(callback: (servers: DevServerManifest[]) => void): RegistryWatcher {\n const registryDir = getRegistryDir()\n mkdirSync(registryDir, {recursive: true})\n\n // Canonicalize to the real long path so `fs.watch` doesn't abort on Windows\n // short-path dirs. See `canonicalizeWatchDir`.\n const watchDir = canonicalizeWatchDir(registryDir)\n\n let debounceTimer: ReturnType<typeof setTimeout> | undefined\n\n const notify = () => {\n clearTimeout(debounceTimer)\n debounceTimer = setTimeout(() => {\n callback(getRegisteredServers())\n }, 50)\n }\n\n const watcher = watch(watchDir, notify)\n\n return {\n close() {\n clearTimeout(debounceTimer)\n watcher.close()\n },\n }\n}\n\n// The workbench singleton lock — \"one workbench per organization\". Lives in the same\n// registry dir and shares the liveness/prune model: a stale lock left by a\n// crashed process is pruned on read so the next acquire isn't blocked forever.\n\nconst workbenchLockSchema = z.object({\n host: z.string(),\n pid: z.number(),\n port: z.number(),\n ready: z.optional(z.boolean()),\n startedAt: z.string(),\n version: z.literal(REGISTRY_VERSION),\n})\n\n/**\n * Read the workbench lock file and return its contents if the holding\n * process is still alive. Prunes stale locks from crashed processes.\n */\nexport function readWorkbenchLock(\n organizationId: string,\n): z.infer<typeof workbenchLockSchema> | undefined {\n const file = readLockFile(organizationId)\n // File doesn't exist — nothing to prune, nothing to return\n if (!file) return undefined\n\n // Past this point the file exists. Anything that isn't a live, valid lock\n // (unparsable JSON, schema mismatch, dead/reused PID) is stale and must be\n // pruned — otherwise the next `acquireWorkbenchLock` call is blocked by\n // EEXIST forever and `sanity dev` silently no-ops the workbench server.\n const {data} = file\n devDebug('Read workbench lock: %o', data)\n if (data && isOurProcess(data.pid, data.startedAt)) {\n devDebug('Workbench process is alive at pid %d on port %d', data.pid, data.port)\n return data\n }\n\n pruneWorkbenchLock(getLockPath(organizationId))\n return undefined\n}\n\nconst LOCK_READY_TIMEOUT_MS = 10_000\nconst LOCK_READY_POLL_MS = 50\n\n/**\n * Read the workbench lock once its holder's shell is listening, so the port is\n * the bound one. Returns the lock as-is after {@link LOCK_READY_TIMEOUT_MS}.\n */\nexport async function waitForWorkbenchLock(\n organizationId: string,\n): Promise<z.infer<typeof workbenchLockSchema> | undefined> {\n const deadline = Date.now() + LOCK_READY_TIMEOUT_MS\n let lock = readWorkbenchLock(organizationId)\n // Read the raw file here: `readWorkbenchLock` spawns `ps`/PowerShell per call\n // and deletes a lock it catches half-written by `updatePort`.\n while (lock?.ready === false && Date.now() < deadline) {\n await new Promise((resolve) => setTimeout(resolve, LOCK_READY_POLL_MS))\n const file = readLockFile(organizationId)\n if (!file) break\n lock = file.data ?? lock\n }\n if (lock?.ready === false && Date.now() >= deadline) {\n devDebug(\n 'Workbench lock not ready after %d ms, using port %d',\n LOCK_READY_TIMEOUT_MS,\n lock.port,\n )\n }\n return readWorkbenchLock(organizationId)\n}\n\nconst getLockPath = (organizationId: string) =>\n join(getRegistryDir(), `workbench-${organizationId}.lock`)\n\n/**\n * Read the lock file with no liveness check and no pruning. `undefined` when\n * there is no file; `data` is `undefined` when its contents don't parse.\n */\nfunction readLockFile(\n organizationId: string,\n): {data: z.infer<typeof workbenchLockSchema> | undefined} | undefined {\n let contents: string\n try {\n contents = readFileSync(getLockPath(organizationId), 'utf8')\n } catch {\n return undefined\n }\n let json: unknown\n try {\n json = JSON.parse(contents)\n } catch {\n return {data: undefined}\n }\n const {data, success} = workbenchLockSchema.safeParse(json)\n return {data: success ? data : undefined}\n}\n\nfunction pruneWorkbenchLock(lockPath: string): void {\n try {\n devDebug('Removing stale workbench lock')\n unlinkSync(lockPath)\n devDebug('Stale workbench lock removed')\n } catch {\n // Another process may have already cleaned it up\n }\n}\n\ninterface WorkbenchLock {\n /** Release the lock file. */\n release: () => void\n /** Update the lock with the actual port after the server starts listening. */\n updatePort: (port: number) => void\n}\n\n/**\n * Attempt to acquire an exclusive lock for the workbench process.\n * Uses `O_EXCL` (the `wx` flag) which is atomic at the OS level — only one\n * process can create the file.\n *\n * The lock stores `{pid, host, port}` so other processes can find the\n * running workbench. Call `updatePort` after the Vite server starts to\n * write the actual port (Vite may pick a different one).\n *\n * @returns A {@link WorkbenchLock} if acquired, or `undefined` if another\n * live process already holds it.\n */\nexport function acquireWorkbenchLock(\n info: {host: string; organizationId: string; port: number},\n retries = 1,\n): WorkbenchLock | undefined {\n const registryDir = getRegistryDir()\n mkdirSync(registryDir, {recursive: true})\n\n const lockPath = getLockPath(info.organizationId)\n const startedAt = ownStartedAt()\n const lockData = {\n host: info.host,\n pid: process.pid,\n port: info.port,\n ready: false,\n startedAt,\n version: REGISTRY_VERSION,\n }\n\n devDebug('Acquiring workbench lock at %s', lockPath)\n\n try {\n writeFileSync(lockPath, JSON.stringify(lockData), {flag: 'wx'})\n devDebug('Workbench lock acquired')\n\n let released = false\n // Only wipe the lock on exit if it's still ours — a successor that reacquired\n // it after our own release must not be clobbered.\n const detachExitCleanup = unlinkOnProcessExit(lockPath, () => {\n if (released) return false\n const disk = readLockFile(info.organizationId)?.data\n return disk?.pid === process.pid && disk.startedAt === startedAt\n })\n\n return {\n release() {\n released = true\n detachExitCleanup()\n try {\n unlinkSync(lockPath)\n } catch {\n // Already cleaned up\n }\n },\n updatePort(port: number) {\n writeFileSync(lockPath, JSON.stringify({...lockData, port, ready: true}))\n },\n }\n } catch (err: unknown) {\n devDebug(\n 'Failed to acquire workbench lock: %s',\n err instanceof Error ? err.message : String(err),\n )\n if (!isNodeError(err) || err.code !== 'EEXIST') return undefined\n\n // Lock exists — check if the holder is still alive\n const existing = readWorkbenchLock(info.organizationId)\n if (existing) return undefined\n\n // Stale lock was pruned by readWorkbenchLock — retry (with guard against infinite recursion)\n if (retries <= 0) return undefined\n return acquireWorkbenchLock(info, retries - 1)\n }\n}\n\nfunction isNodeError(err: unknown): err is NodeJS.ErrnoException {\n return err instanceof Error && 'code' in err\n}\n"],"names":["existsSync","mkdirSync","readdirSync","readFileSync","unlinkSync","watch","writeFileSync","join","coreAppManifestSchema","getSanityDataDir","studioManifestSchema","subdebug","z","applicationReference","TileInterfaceMetadataSchema","ViewPlacementMetadataSchema","canonicalizeWatchDir","getProcessStartTime","isOurProcess","devDebug","REGISTRY_VERSION","ownStartedAt","process","pid","Date","toISOString","interfaceBaseFields","id","string","moduleId","name","src","title","version","optional","devServerInterfaceSchema","union","discriminatedUnion","object","metadata","nullable","surface","literal","null","type","devServerManifestSchema","applicationId","configs","array","appType","fields","public","boolean","moduleName","host","interfaces","manifest","manifestUpdatedAt","organizationId","number","port","projectId","reference","slug","startedAt","enum","visibility","workDir","isConfigOnlyServer","server","Boolean","length","localAppIdentity","app","isSingleton","dashboardPath","hasAppView","some","iface","segment","undefined","root","encodeURIComponent","getRegistryDir","exitCleanups","Set","exitListenerInstalled","runExitCleanups","cleanup","runRegistryExitCleanupForTesting","unlinkOnProcessExit","filePath","ownedByUs","add","once","delete","registerDevServer","registryDir","recursive","current","JSON","stringify","released","detachExitCleanup","release","update","patch","getRegisteredServers","files","filter","f","endsWith","servers","file","raw","parse","data","success","safeParse","push","watchRegistry","callback","watchDir","debounceTimer","notify","clearTimeout","setTimeout","watcher","close","workbenchLockSchema","ready","readWorkbenchLock","readLockFile","pruneWorkbenchLock","getLockPath","LOCK_READY_TIMEOUT_MS","LOCK_READY_POLL_MS","waitForWorkbenchLock","deadline","now","lock","Promise","resolve","contents","json","lockPath","acquireWorkbenchLock","info","retries","lockData","flag","disk","updatePort","err","Error","message","String","isNodeError","code","existing"],"mappings":"AAAA,SACEA,UAAU,EACVC,SAAS,EACTC,WAAW,EACXC,YAAY,EACZC,UAAU,EACVC,KAAK,EACLC,aAAa,QACR,UAAS;AAChB,SAAQC,IAAI,QAAO,YAAW;AAE9B,SACEC,qBAAqB,EACrBC,gBAAgB,EAChBC,oBAAoB,EACpBC,QAAQ,QACH,mBAAkB;AACzB,SAAQC,CAAC,QAAO,WAA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E3C,IAAI;QACF3I,cAAc2I,UAAU7C,KAAKC,SAAS,CAACgD,WAAW;YAACC,MAAM;QAAI;QAC7DnI,SAAS;QAET,IAAImF,WAAW;QACf,8EAA8E;QAC9E,kDAAkD;QAClD,MAAMC,oBAAoBb,oBAAoBuD,UAAU;YACtD,IAAI3C,UAAU,OAAO;YACrB,MAAMiD,OAAOnB,aAAae,KAAKzF,cAAc,GAAG0D;YAChD,OAAOmC,MAAMhI,QAAQD,QAAQC,GAAG,IAAIgI,KAAKvF,SAAS,KAAKA;QACzD;QAEA,OAAO;YACLwC;gBACEF,WAAW;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
+ {"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, {mode: 0o700, recursive: true})\n\n let current: DevServerManifest = {\n ...manifest,\n pid: process.pid,\n startedAt: ownStartedAt(),\n version: REGISTRY_VERSION,\n }\n\n const filePath = join(registryDir, `${process.pid}.json`)\n writeFileSync(filePath, JSON.stringify(current, null, 2), {mode: 0o600})\n\n // Guard against late updates from background tasks (e.g. the initial\n // manifest extraction) landing after `release()` has deleted the file —\n // without this, the update would re-create the registry entry and leak.\n let released = false\n\n // The file is pid-named, so it's always ours to remove on exit.\n const detachExitCleanup = unlinkOnProcessExit(filePath, () => !released)\n\n return {\n release() {\n released = true\n detachExitCleanup()\n try {\n unlinkSync(filePath)\n } catch {\n // ENOENT is fine — already cleaned up\n }\n },\n update(patch) {\n if (released) return\n current = {...current, ...patch}\n writeFileSync(filePath, JSON.stringify(current, null, 2), {mode: 0o600})\n },\n }\n}\n\n/**\n * Read all manifest files from the registry, prune stale entries (dead PIDs),\n * and return the live ones.\n */\nexport function getRegisteredServers(): DevServerManifest[] {\n const registryDir = getRegistryDir()\n\n if (!existsSync(registryDir)) {\n return []\n }\n\n const files = readdirSync(registryDir).filter((f) => f.endsWith('.json'))\n const servers: DevServerManifest[] = []\n\n for (const file of files) {\n const filePath = join(registryDir, file)\n let raw: unknown\n try {\n raw = JSON.parse(readFileSync(filePath, 'utf8'))\n } catch {\n continue\n }\n\n const {data, success} = devServerManifestSchema.safeParse(raw)\n if (!success) continue\n\n if (isOurProcess(data.pid, data.startedAt)) {\n servers.push(data)\n } else {\n try {\n unlinkSync(filePath)\n } catch {\n // Ignore — another process may have already cleaned it up\n }\n }\n }\n\n return servers\n}\n\ninterface RegistryWatcher {\n close(): void\n}\n\n/**\n * Watch the registry directory for changes and invoke the callback with the\n * current list of live servers whenever a change is detected.\n *\n * Uses `fs.watch` with a debounce to coalesce rapid file changes (e.g. a\n * server starting and writing its manifest triggers multiple FS events).\n */\nexport function watchRegistry(callback: (servers: DevServerManifest[]) => void): RegistryWatcher {\n const registryDir = getRegistryDir()\n mkdirSync(registryDir, {mode: 0o700, recursive: true})\n\n // Canonicalize to the real long path so `fs.watch` doesn't abort on Windows\n // short-path dirs. See `canonicalizeWatchDir`.\n const watchDir = canonicalizeWatchDir(registryDir)\n\n let debounceTimer: ReturnType<typeof setTimeout> | undefined\n\n const notify = () => {\n clearTimeout(debounceTimer)\n debounceTimer = setTimeout(() => {\n callback(getRegisteredServers())\n }, 50)\n }\n\n const watcher = watch(watchDir, notify)\n\n return {\n close() {\n clearTimeout(debounceTimer)\n watcher.close()\n },\n }\n}\n\n// The workbench singleton lock — \"one workbench per organization\". Lives in the same\n// registry dir and shares the liveness/prune model: a stale lock left by a\n// crashed process is pruned on read so the next acquire isn't blocked forever.\n\nconst workbenchLockSchema = z.object({\n host: z.string(),\n pid: z.number(),\n port: z.number(),\n ready: z.optional(z.boolean()),\n startedAt: z.string(),\n version: z.literal(REGISTRY_VERSION),\n})\n\n/**\n * Read the workbench lock file and return its contents if the holding\n * process is still alive. Prunes stale locks from crashed processes.\n */\nexport function readWorkbenchLock(\n organizationId: string,\n): z.infer<typeof workbenchLockSchema> | undefined {\n const file = readLockFile(organizationId)\n // File doesn't exist — nothing to prune, nothing to return\n if (!file) return undefined\n\n // Past this point the file exists. Anything that isn't a live, valid lock\n // (unparsable JSON, schema mismatch, dead/reused PID) is stale and must be\n // pruned — otherwise the next `acquireWorkbenchLock` call is blocked by\n // EEXIST forever and `sanity dev` silently no-ops the workbench server.\n const {data} = file\n devDebug('Read workbench lock: %o', data)\n if (data && isOurProcess(data.pid, data.startedAt)) {\n devDebug('Workbench process is alive at pid %d on port %d', data.pid, data.port)\n return data\n }\n\n pruneWorkbenchLock(getLockPath(organizationId))\n return undefined\n}\n\nconst LOCK_READY_TIMEOUT_MS = 10_000\nconst LOCK_READY_POLL_MS = 50\n\n/**\n * Read the workbench lock once its holder's shell is listening, so the port is\n * the bound one. Returns the lock as-is after {@link LOCK_READY_TIMEOUT_MS}.\n */\nexport async function waitForWorkbenchLock(\n organizationId: string,\n): Promise<z.infer<typeof workbenchLockSchema> | undefined> {\n const deadline = Date.now() + LOCK_READY_TIMEOUT_MS\n let lock = readWorkbenchLock(organizationId)\n // Read the raw file here: `readWorkbenchLock` spawns `ps`/PowerShell per call\n // and deletes a lock it catches half-written by `updatePort`.\n while (lock?.ready === false && Date.now() < deadline) {\n await new Promise((resolve) => setTimeout(resolve, LOCK_READY_POLL_MS))\n const file = readLockFile(organizationId)\n if (!file) break\n lock = file.data ?? lock\n }\n if (lock?.ready === false && Date.now() >= deadline) {\n devDebug(\n 'Workbench lock not ready after %d ms, using port %d',\n LOCK_READY_TIMEOUT_MS,\n lock.port,\n )\n }\n return readWorkbenchLock(organizationId)\n}\n\nconst getLockPath = (organizationId: string) =>\n join(getRegistryDir(), `workbench-${organizationId}.lock`)\n\n/**\n * Read the lock file with no liveness check and no pruning. `undefined` when\n * there is no file; `data` is `undefined` when its contents don't parse.\n */\nfunction readLockFile(\n organizationId: string,\n): {data: z.infer<typeof workbenchLockSchema> | undefined} | undefined {\n let contents: string\n try {\n contents = readFileSync(getLockPath(organizationId), 'utf8')\n } catch {\n return undefined\n }\n let json: unknown\n try {\n json = JSON.parse(contents)\n } catch {\n return {data: undefined}\n }\n const {data, success} = workbenchLockSchema.safeParse(json)\n return {data: success ? data : undefined}\n}\n\nfunction pruneWorkbenchLock(lockPath: string): void {\n try {\n devDebug('Removing stale workbench lock')\n unlinkSync(lockPath)\n devDebug('Stale workbench lock removed')\n } catch {\n // Another process may have already cleaned it up\n }\n}\n\ninterface WorkbenchLock {\n /** Release the lock file. */\n release: () => void\n /** Update the lock with the actual port after the server starts listening. */\n updatePort: (port: number) => void\n}\n\n/**\n * Attempt to acquire an exclusive lock for the workbench process.\n * Uses `O_EXCL` (the `wx` flag) which is atomic at the OS level — only one\n * process can create the file.\n *\n * The lock stores `{pid, host, port}` so other processes can find the\n * running workbench. Call `updatePort` after the Vite server starts to\n * write the actual port (Vite may pick a different one).\n *\n * @returns A {@link WorkbenchLock} if acquired, or `undefined` if another\n * live process already holds it.\n */\nexport function acquireWorkbenchLock(\n info: {host: string; organizationId: string; port: number},\n retries = 1,\n): WorkbenchLock | undefined {\n const registryDir = getRegistryDir()\n mkdirSync(registryDir, {mode: 0o700, recursive: true})\n\n const lockPath = getLockPath(info.organizationId)\n const startedAt = ownStartedAt()\n const lockData = {\n host: info.host,\n pid: process.pid,\n port: info.port,\n ready: false,\n startedAt,\n version: REGISTRY_VERSION,\n }\n\n devDebug('Acquiring workbench lock at %s', lockPath)\n\n try {\n writeFileSync(lockPath, JSON.stringify(lockData), {flag: 'wx', mode: 0o600})\n devDebug('Workbench lock acquired')\n\n let released = false\n // Only wipe the lock on exit if it's still ours — a successor that reacquired\n // it after our own release must not be clobbered.\n const detachExitCleanup = unlinkOnProcessExit(lockPath, () => {\n if (released) return false\n const disk = readLockFile(info.organizationId)?.data\n return disk?.pid === process.pid && disk.startedAt === startedAt\n })\n\n return {\n release() {\n released = true\n detachExitCleanup()\n try {\n unlinkSync(lockPath)\n } catch {\n // Already cleaned up\n }\n },\n updatePort(port: number) {\n writeFileSync(lockPath, JSON.stringify({...lockData, port, ready: true}), {mode: 0o600})\n },\n }\n } catch (err: unknown) {\n devDebug(\n 'Failed to acquire workbench lock: %s',\n err instanceof Error ? err.message : String(err),\n )\n if (!isNodeError(err) || err.code !== 'EEXIST') return undefined\n\n // Lock exists — check if the holder is still alive\n const existing = readWorkbenchLock(info.organizationId)\n if (existing) return undefined\n\n // Stale lock was pruned by readWorkbenchLock — retry (with guard against infinite recursion)\n if (retries <= 0) return undefined\n return acquireWorkbenchLock(info, retries - 1)\n }\n}\n\nfunction isNodeError(err: unknown): err is NodeJS.ErrnoException {\n return err instanceof Error && 'code' in err\n}\n"],"names":["existsSync","mkdirSync","readdirSync","readFileSync","unlinkSync","watch","writeFileSync","join","coreAppManifestSchema","getSanityDataDir","studioManifestSchema","subdebug","z","applicationReference","TileInterfaceMetadataSchema","ViewPlacementMetadataSchema","canonicalizeWatchDir","getProcessStartTime","isOurProcess","devDebug","REGISTRY_VERSION","ownStartedAt","process","pid","Date","toISOString","interfaceBaseFields","id","string","moduleId","name","src","title","version","optional","devServerInterfaceSchema","union","discriminatedUnion","object","metadata","nullable","surface","literal","null","type","devServerManifestSchema","applicationId","configs","array","appType","fields","public","boolean","moduleName","host","interfaces","manifest","manifestUpdatedAt","organizationId","number","port","projectId","reference","slug","startedAt","enum","visibility","workDir","isConfigOnlyServer","server","Boolean","length","localAppIdentity","app","isSingleton","dashboardPath","hasAppView","some","iface","segment","undefined","root","encodeURIComponent","getRegistryDir","exitCleanups","Set","exitListenerInstalled","runExitCleanups","cleanup","runRegistryExitCleanupForTesting","unlinkOnProcessExit","filePath","ownedByUs","add","once","delete","registerDevServer","registryDir","mode","recursive","current","JSON","stringify","released","detachExitCleanup","release","update","patch","getRegisteredServers","files","filter","f","endsWith","servers","file","raw","parse","data","success","safeParse","push","watchRegistry","callback","watchDir","debounceTimer","notify","clearTimeout","setTimeout","watcher","close","workbenchLockSchema","ready","readWorkbenchLock","readLockFile","pruneWorkbenchLock","getLockPath","LOCK_READY_TIMEOUT_MS","LOCK_READY_POLL_MS","waitForWorkbenchLock","deadline","now","lock","Promise","resolve","contents","json","lockPath","acquireWorkbenchLock","info","retries","lockData","flag","disk","updatePort","err","Error","message","String","isNodeError","code","existing"],"mappings":"AAAA,SACEA,UAAU,EACVC,SAAS,EACTC,WAAW,EACXC,YAAY,EACZC,UAAU,EACVC,KAAK,EACLC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EA,SAASS,YAAYJ,GAAY;IAC/B,OAAOA,eAAeC,SAAS,UAAUD;AAC3C"}
@@ -6,7 +6,7 @@ import { startWorkbenchDevServer, startWorkbenchRemoteCoordinator } from './star
6
6
  /**
7
7
  * Orchestrate the dev servers a workbench project needs: a singleton workbench
8
8
  * Vite server plus the app/studio dev server it renders, wired to the dev-server
9
- * registry so view/service edits re-sync live.
9
+ * registry so view/web worker edits re-sync live.
10
10
  *
11
11
  * A running workbench claims the configured port, so the app server binds the
12
12
  * next one. If the workbench can't start (package or port unavailable), the app
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/actions/dev/startWorkbenchDev.ts"],"sourcesContent":["import {styleText} from 'node:util'\n\nimport {type CliConfig, type Output} from '@sanity/cli-core'\n\nimport {createServerLifecycle, toDisplayHost} from '../../util/serverOrchestration.js'\nimport {type AppServerResult, startAppServerSupervisor} from './appServerSupervisor.js'\nimport {type DevServerManifest} from './registry.js'\nimport {startDevServerRegistration} from './startDevServerRegistration.js'\nimport {\n startWorkbenchDevServer,\n startWorkbenchRemoteCoordinator,\n} from './startWorkbenchDevServer.js'\n\nexport interface StartWorkbenchDevOptions {\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 | undefined\n httpPort: number\n isApp: boolean\n output: Output\n reactStrictMode: boolean\n /** Start the app/studio dev server — the CLI owns the server, this orchestrates it. */\n startAppServer: (params: {\n announceUrl: boolean\n cliConfig: CliConfig\n httpPort: number\n }) => Promise<AppServerResult>\n workDir: string\n}\n\n/**\n * Orchestrate the dev servers a workbench project needs: a singleton workbench\n * Vite server plus the app/studio dev server it renders, wired to the dev-server\n * registry so view/service edits re-sync live.\n *\n * A running workbench claims the configured port, so the app server binds the\n * next one. If the workbench can't start (package or port unavailable), the app\n * server falls back to the configured port and announces its own URL, exactly as\n * a plain `sanity dev` would.\n */\nexport async function startWorkbenchDev(\n options: StartWorkbenchDevOptions,\n): Promise<{close: () => Promise<void>}> {\n const {\n cacheDir,\n checkForDeprecatedAppId,\n cliConfig,\n extractManifest,\n httpHost,\n httpPort,\n isApp,\n output,\n reactStrictMode,\n startAppServer,\n workDir,\n } = options\n\n // The remote can't render itself, so it runs as a plain app server (not the\n // shell) that still bridges the registry.\n if (process.env.SANITY_INTERNAL_IS_WORKBENCH_REMOTE === 'true') {\n const remote = await startAppServer({announceUrl: true, cliConfig, httpPort})\n if (!remote.started) return {close: async () => {}}\n\n const coordinator = startWorkbenchRemoteCoordinator({server: remote.server})\n\n return {\n close: async () => {\n await coordinator.close()\n await remote.close()\n },\n }\n }\n\n // Unwound in reverse on any failure or on close(): the watcher stops before\n // the app server, and the supervisor waits out an in-flight rebuild.\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 // A running workbench owns the configured port; the app server takes the next.\n // Without one it claims the configured port and announces its own URL.\n const appPort = workbench.workbenchAvailable ? workbench.workbenchPort + 1 : httpPort\n const announceUrl = !workbench.workbenchAvailable\n\n const supervised = await startAppServerSupervisor({\n cliConfig,\n start: (config) => startAppServer({announceUrl, cliConfig: config, httpPort: appPort}),\n workDir,\n }).catch(async (err) => {\n await close()\n throw err\n })\n\n if (!supervised.started) {\n // The app server already reported why (e.g. missing organization id). Hand\n // back a close that releases the workbench lock; nothing else came up.\n return {close}\n }\n const {supervisor} = supervised\n closers.push(supervisor.close)\n\n let dashboardAppPath: string | undefined\n try {\n // The deprecated-id check and manifest extractor are CLI-domain, injected here.\n checkForDeprecatedAppId()\n const registration = await startDevServerRegistration({\n cliConfig,\n extractManifest,\n isApp,\n onInterfaceSetChange: () => supervisor.rebuild(),\n output,\n server: supervisor.server,\n workDir,\n })\n closers.push(registration.close)\n dashboardAppPath = registration.path\n } catch (err) {\n // Registration runs after both servers are up; a failure here would leak the\n // workbench lock and dev servers without this teardown.\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 dev server started at ${styleText(['blue', 'underline'], appUrl)}`)\n }\n\n installSignalHandlers()\n\n return {close}\n}\n"],"names":["styleText","createServerLifecycle","toDisplayHost","startAppServerSupervisor","startDevServerRegistration","startWorkbenchDevServer","startWorkbenchRemoteCoordinator","startWorkbenchDev","options","cacheDir","checkForDeprecatedAppId","cliConfig","extractManifest","httpHost","httpPort","isApp","output","reactStrictMode","startAppServer","workDir","process","env","SANITY_INTERNAL_IS_WORKBENCH_REMOTE","remote","announceUrl","started","close","coordinator","server","closers","installSignalHandlers","workbench","push","appPort","workbenchAvailable","workbenchPort","supervised","start","config","catch","err","supervisor","dashboardAppPath","registration","onInterfaceSetChange","rebuild","path","appUrl","log"],"mappings":"AAAA,SAAQA,SAAS,QAAO,YAAW;AAInC,SAAQC,qBAAqB,EAAEC,aAAa,QAAO,oCAAmC;AACtF,SAA8BC,wBAAwB,QAAO,2BAA0B;AAEvF,SAAQC,0BAA0B,QAAO,kCAAiC;AAC1E,SACEC,uBAAuB,EACvBC,+BAA+B,QAC1B,+BAA8B;AA4BrC;;;;;;;;;CASC,GACD,OAAO,eAAeC,kBACpBC,OAAiC;IAEjC,MAAM,EACJC,QAAQ,EACRC,uBAAuB,EACvBC,SAAS,EACTC,eAAe,EACfC,QAAQ,EACRC,QAAQ,EACRC,KAAK,EACLC,MAAM,EACNC,eAAe,EACfC,cAAc,EACdC,OAAO,EACR,GAAGX;IAEJ,4EAA4E;IAC5E,0CAA0C;IAC1C,IAAIY,QAAQC,GAAG,CAACC,mCAAmC,KA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U,QAAQG,IAAI,CAACW,aAAajB,KAAK;QAC/BgB,mBAAmBC,aAAaG,IAAI;IACtC,EAAE,OAAON,KAAK;QACZ,6EAA6E;QAC7E,wDAAwD;QACxD,MAAMd;QACN,MAAMc;IACR;IAEA,IAAIT,UAAUG,kBAAkB,EAAE;QAChC,MAAMa,SAAS,CAAC,OAAO,EAAE7C,cAAc6B,UAAUlB,QAAQ,EAAE,CAAC,EAAEkB,UAAUI,aAAa,GAAGO,oBAAoB,IAAI;QAChH1B,OAAOgC,GAAG,CAAC,CAAC,gCAAgC,EAAEhD,UAAU;YAAC;YAAQ;SAAY,EAAE+C,SAAS;IAC1F;IAEAjB;IAEA,OAAO;QAACJ;IAAK;AACf"}
1
+ {"version":3,"sources":["../../../src/actions/dev/startWorkbenchDev.ts"],"sourcesContent":["import {styleText} from 'node:util'\n\nimport {type CliConfig, type Output} from '@sanity/cli-core'\n\nimport {createServerLifecycle, toDisplayHost} from '../../util/serverOrchestration.js'\nimport {type AppServerResult, startAppServerSupervisor} from './appServerSupervisor.js'\nimport {type DevServerManifest} from './registry.js'\nimport {startDevServerRegistration} from './startDevServerRegistration.js'\nimport {\n startWorkbenchDevServer,\n startWorkbenchRemoteCoordinator,\n} from './startWorkbenchDevServer.js'\n\nexport interface StartWorkbenchDevOptions {\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 | undefined\n httpPort: number\n isApp: boolean\n output: Output\n reactStrictMode: boolean\n /** Start the app/studio dev server — the CLI owns the server, this orchestrates it. */\n startAppServer: (params: {\n announceUrl: boolean\n cliConfig: CliConfig\n httpPort: number\n }) => Promise<AppServerResult>\n workDir: string\n}\n\n/**\n * Orchestrate the dev servers a workbench project needs: a singleton workbench\n * Vite server plus the app/studio dev server it renders, wired to the dev-server\n * registry so view/web worker edits re-sync live.\n *\n * A running workbench claims the configured port, so the app server binds the\n * next one. If the workbench can't start (package or port unavailable), the app\n * server falls back to the configured port and announces its own URL, exactly as\n * a plain `sanity dev` would.\n */\nexport async function startWorkbenchDev(\n options: StartWorkbenchDevOptions,\n): Promise<{close: () => Promise<void>}> {\n const {\n cacheDir,\n checkForDeprecatedAppId,\n cliConfig,\n extractManifest,\n httpHost,\n httpPort,\n isApp,\n output,\n reactStrictMode,\n startAppServer,\n workDir,\n } = options\n\n // The remote can't render itself, so it runs as a plain app server (not the\n // shell) that still bridges the registry.\n if (process.env.SANITY_INTERNAL_IS_WORKBENCH_REMOTE === 'true') {\n const remote = await startAppServer({announceUrl: true, cliConfig, httpPort})\n if (!remote.started) return {close: async () => {}}\n\n const coordinator = startWorkbenchRemoteCoordinator({server: remote.server})\n\n return {\n close: async () => {\n await coordinator.close()\n await remote.close()\n },\n }\n }\n\n // Unwound in reverse on any failure or on close(): the watcher stops before\n // the app server, and the supervisor waits out an in-flight rebuild.\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 // A running workbench owns the configured port; the app server takes the next.\n // Without one it claims the configured port and announces its own URL.\n const appPort = workbench.workbenchAvailable ? workbench.workbenchPort + 1 : httpPort\n const announceUrl = !workbench.workbenchAvailable\n\n const supervised = await startAppServerSupervisor({\n cliConfig,\n start: (config) => startAppServer({announceUrl, cliConfig: config, httpPort: appPort}),\n workDir,\n }).catch(async (err) => {\n await close()\n throw err\n })\n\n if (!supervised.started) {\n // The app server already reported why (e.g. missing organization id). Hand\n // back a close that releases the workbench lock; nothing else came up.\n return {close}\n }\n const {supervisor} = supervised\n closers.push(supervisor.close)\n\n let dashboardAppPath: string | undefined\n try {\n // The deprecated-id check and manifest extractor are CLI-domain, injected here.\n checkForDeprecatedAppId()\n const registration = await startDevServerRegistration({\n cliConfig,\n extractManifest,\n isApp,\n onInterfaceSetChange: () => supervisor.rebuild(),\n output,\n server: supervisor.server,\n workDir,\n })\n closers.push(registration.close)\n dashboardAppPath = registration.path\n } catch (err) {\n // Registration runs after both servers are up; a failure here would leak the\n // workbench lock and dev servers without this teardown.\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 dev server started at ${styleText(['blue', 'underline'], appUrl)}`)\n }\n\n installSignalHandlers()\n\n return {close}\n}\n"],"names":["styleText","createServerLifecycle","toDisplayHost","startAppServerSupervisor","startDevServerRegistration","startWorkbenchDevServer","startWorkbenchRemoteCoordinator","startWorkbenchDev","options","cacheDir","checkForDeprecatedAppId","cliConfig","extractManifest","httpHost","httpPort","isApp","output","reactStrictMode","startAppServer","workDir","process","env","SANITY_INTERNAL_IS_WORKBENCH_REMOTE","remote","announceUrl","started","close","coordinator","server","closers","installSignalHandlers","workbench","push","appPort","workbenchAvailable","workbenchPort","supervised","start","config","catch","err","supervisor","dashboardAppPath","registration","onInterfaceSetChange","rebuild","path","appUrl","log"],"mappings":"AAAA,SAAQA,SAAS,QAAO,YAAW;AAInC,SAAQC,qBAAqB,EAAEC,aAAa,QAAO,oCAAmC;AACtF,SAA8BC,wBAAwB,QAAO,2BAA0B;AAEvF,SAAQC,0BAA0B,QAAO,kCAAiC;AAC1E,SACEC,uBAAuB,EACvBC,+BAA+B,QAC1B,+BAA8B;AA4BrC;;;;;;;;;CASC,GACD,OAAO,eAAeC,kBACpBC,OAAiC;IAEjC,MAAM,EACJC,QAAQ,EACRC,uBAAuB,EACvBC,SAAS,EACTC,eAAe,EACfC,QAAQ,EACRC,QAAQ,EACRC,KAAK,EACLC,MAAM,EACNC,eAAe,EACfC,cAAc,EACdC,OA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AG;YACA6B,sBAAsB,IAAMH,WAAWI,OAAO;YAC9C7B;YACAY,QAAQa,WAAWb,MAAM;YACzBT;QACF;QACAU,QAAQG,IAAI,CAACW,aAAajB,KAAK;QAC/BgB,mBAAmBC,aAAaG,IAAI;IACtC,EAAE,OAAON,KAAK;QACZ,6EAA6E;QAC7E,wDAAwD;QACxD,MAAMd;QACN,MAAMc;IACR;IAEA,IAAIT,UAAUG,kBAAkB,EAAE;QAChC,MAAMa,SAAS,CAAC,OAAO,EAAE7C,cAAc6B,UAAUlB,QAAQ,EAAE,CAAC,EAAEkB,UAAUI,aAAa,GAAGO,oBAAoB,IAAI;QAChH1B,OAAOgC,GAAG,CAAC,CAAC,gCAAgC,EAAEhD,UAAU;YAAC;YAAQ;SAAY,EAAE+C,SAAS;IAC1F;IAEAjB;IAEA,OAAO;QAACJ;IAAK;AACf"}
package/dist/contract.js CHANGED
@@ -1,9 +1,10 @@
1
1
  import { z } from 'zod/mini';
2
- // Shared module-federation extension contract: interface (view/service) and
2
+ // Shared module-federation extension contract: interface (view/web worker) and
3
3
  // config declaration schemas, plus the versions the build stamps.
4
4
  // `zod/mini` keeps the bundle small.
5
- /** @internal */ export const VIEW_CONTRACT_VERSION = 1;
6
- /** @internal */ export const SERVICE_CONTRACT_VERSION = 1;
5
+ /** @internal */ export const VIEW_CONTRACT_VERSION = 2;
6
+ /** @internal */ export const WEB_WORKER_CONTRACT_VERSION = 1;
7
+ /** @internal */ export const WINDOW_CONTRACT_VERSION = 1;
7
8
  /** @internal */ export const MEDIA_LIBRARY_CONFIG_CONTRACT_VERSION = 1;
8
9
  /** Component slots per view surface; windows load outside the component artifact path. @internal */ export const VIEW_COMPONENTS = {
9
10
  asset_source: [
@@ -60,12 +61,11 @@ const PanelDockSchema = z.object({
60
61
  asset_source: VIEW_CONTRACT_VERSION,
61
62
  panel: VIEW_CONTRACT_VERSION,
62
63
  tile: VIEW_CONTRACT_VERSION,
63
- window: undefined,
64
- worker: SERVICE_CONTRACT_VERSION
64
+ window: WINDOW_CONTRACT_VERSION,
65
+ worker: WEB_WORKER_CONTRACT_VERSION
65
66
  };
66
67
  /** @internal */ export function interfaceContractVersion(kind) {
67
- const version = INTERFACE_CONTRACT_VERSIONS[kind];
68
- return version === undefined ? undefined : String(version);
68
+ return String(INTERFACE_CONTRACT_VERSIONS[kind]);
69
69
  }
70
70
  /**
71
71
  * The module-federation id a build exposes an interface at. Dev stamps the same
@@ -169,7 +169,7 @@ const WebWorkerSchema = z.object({
169
169
  type: 'worker'
170
170
  };
171
171
  }
172
- /** @internal */ export const ServiceDeclarationSchema = z.discriminatedUnion('type', [
172
+ /** @internal */ export const WebWorkerDeclarationSchema = z.discriminatedUnion('type', [
173
173
  WebWorkerSchema
174
174
  ]);
175
175
  const MediaLibraryFieldSchema = z.object({
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/contract.ts"],"sourcesContent":["import {z} from 'zod/mini'\n\n// Shared module-federation extension contract: interface (view/service) and\n// config declaration schemas, plus the versions the build stamps.\n// `zod/mini` keeps the bundle small.\n\n/** @internal */\nexport const VIEW_CONTRACT_VERSION = 1\n\n/** @internal */\nexport const SERVICE_CONTRACT_VERSION = 1\n\n/** @internal */\nexport const MEDIA_LIBRARY_CONFIG_CONTRACT_VERSION = 1\n\n/**\n * A view component. The return is opaque so the runtime helpers carry no React\n * dependency — the generated artifact renders it with the app's own React.\n * @public\n */\nexport type ViewComponent<TProps> = (props: TProps) => unknown\n\n/** @public */\nexport interface ViewComponentBaseProps<TView> {\n view: TView\n}\n\n/** Component slots per view surface; windows load outside the component artifact path. @internal */\nexport const VIEW_COMPONENTS = {\n asset_source: ['asset_source'],\n panel: ['title', 'panel'],\n tile: ['tile'],\n window: [],\n} as const satisfies Record<string, readonly string[]>\n\n/** @public */\nexport type ViewSurface = keyof typeof VIEW_COMPONENTS\n\n/**\n * A tile's footprint family — the shape it occupies on the dashboard. Modelled\n * on iOS WidgetKit families, not a linear scale: `banner` is full-width and\n * shallow, which a `small`→`large` magnitude can't express. The host maps a\n * family to a layout slot; the component reads it to render per footprint.\n * @public\n */\nexport const TileSizeSchema = z.enum(['small', 'large', 'banner'])\n\n/** @public */\nexport type TileSize = z.infer<typeof TileSizeSchema>\n\n/** @public */\nexport type ServiceType = 'worker'\n\nconst DockGroupSchema = z.enum(['system', 'applications'])\n\n/** @public */\nexport type DockGroup = z.output<typeof DockGroupSchema>\n\n/** @internal */\nexport const DockSchema = z.object({\n group: z.optional(DockGroupSchema),\n order: z.optional(z.number()),\n})\n\n/** @internal */\nexport type Dock = z.infer<typeof DockSchema>\n\nconst PanelDockSchema = z.object({order: z.optional(z.number())})\n\n/** @internal */\nexport const ViewPlacementMetadataSchema = z.object({dock: DockSchema})\n\n/** @internal */\nexport type ViewPlacementMetadata = z.infer<typeof ViewPlacementMetadataSchema>\n\n/**\n * A tile's interface metadata: its footprint `size` and an optional `order`\n * the dashboard sorts on, ascending. Both are authored as top-level view fields\n * (see {@link InterfaceDeclarationSchema}) but stored on the record as metadata.\n * @internal\n */\nexport const TileInterfaceMetadataSchema = z.object({\n order: z.optional(z.number()),\n size: TileSizeSchema,\n})\n\n/** @internal */\nexport type TileInterfaceMetadata = z.infer<typeof TileInterfaceMetadataSchema>\n\n/**\n * The contract version each interface type advertises, so the host can check it\n * renders/runs what it expects.\n * @internal\n */\nconst INTERFACE_CONTRACT_VERSIONS = {\n asset_source: VIEW_CONTRACT_VERSION,\n panel: VIEW_CONTRACT_VERSION,\n tile: VIEW_CONTRACT_VERSION,\n window: undefined,\n worker: SERVICE_CONTRACT_VERSION,\n} as const\n\n/** Every interface type an app exposes — a window, a view, or a service. */\nexport type InterfaceKind = keyof typeof INTERFACE_CONTRACT_VERSIONS\n\n/** @internal */\nexport function interfaceContractVersion(kind: InterfaceKind): string | undefined {\n const version = INTERFACE_CONTRACT_VERSIONS[kind]\n return version === undefined ? undefined : String(version)\n}\n\n/**\n * The module-federation id a build exposes an interface at. Dev stamps the same\n * id a deploy would, so the workbench loads a local interface like a deployed one.\n * @internal\n */\nexport function interfaceModuleId(kind: string, name: string): string {\n switch (kind) {\n case 'asset_source':\n case 'panel':\n case 'tile': {\n return `views/${name}`\n }\n case 'window': {\n return 'App'\n }\n case 'worker': {\n return `services/${name}`\n }\n default: {\n throw new Error(`Cannot derive a moduleId for unknown interface kind: ${kind}`)\n }\n }\n}\n\n// Shared `name` + `src`; `kind` only tailors the validation message.\nfunction extensionDeclarationFields(kind: 'Field' | 'View' | 'Web worker') {\n const pattern = /^[a-zA-Z0-9_-]+$/\n return {\n name: z.string().check(z.regex(pattern, `${kind} \\`name\\` must match ${pattern}`)),\n src: z.string(),\n }\n}\n\n// Every interface shares `name` + `src` + a display `title`,\n// which Brett requires on the record each becomes.\nfunction interfaceDeclarationFields(kind: 'View' | 'Web worker') {\n return {\n ...extensionDeclarationFields(kind),\n title: z.string(`${kind} \\`title\\` is required`),\n }\n}\n\nconst PanelViewSchema = z.object({\n surface: z.literal('panel'),\n ...interfaceDeclarationFields('View'),\n dock: z.optional(PanelDockSchema),\n})\n\n/** @public */\nexport type PanelView = z.output<typeof PanelViewSchema>\n\n/** @public */\nexport type DefinePanelViewInput = Omit<PanelView, 'surface'>\n\n/** @public */\nexport function definePanelView(view: DefinePanelViewInput): PanelView {\n return {...view, surface: 'panel'}\n}\n\nconst WindowViewSchema = z.object({\n surface: z.literal('window'),\n ...interfaceDeclarationFields('View'),\n dock: z.optional(DockSchema),\n})\n\n/** @public */\nexport type WindowView = z.output<typeof WindowViewSchema>\n\n/** @public */\nexport type DefineWindowViewInput = Omit<WindowView, 'surface'>\n\n/** @public */\nexport function defineWindowView(view: DefineWindowViewInput): WindowView {\n return {...view, surface: 'window'}\n}\n\nconst AssetSourceViewSchema = z.object({\n surface: z.literal('asset_source'),\n ...interfaceDeclarationFields('View'),\n})\n\n/** @public */\nexport type AssetSourceView = z.output<typeof AssetSourceViewSchema>\n\n/** @public */\nexport type DefineAssetSourceViewInput = Omit<AssetSourceView, 'surface'>\n\n/** @public */\nexport function defineAssetSourceView(view: DefineAssetSourceViewInput): AssetSourceView {\n return {...view, surface: 'asset_source'}\n}\n\nconst TileViewSchema = z.object({\n surface: z.literal('tile'),\n ...interfaceDeclarationFields('View'),\n /** Sort position within its layout track, ascending. Optional. */\n order: z.optional(z.number()),\n /** Footprint family the dashboard lays the tile out by. */\n size: TileSizeSchema,\n})\n\n/** @public */\nexport type TileView = z.output<typeof TileViewSchema>\n\n/** @public */\nexport type DefineTileViewInput = Omit<TileView, 'surface'>\n\n/** @public */\nexport function defineTileView(view: DefineTileViewInput): TileView {\n return {...view, surface: 'tile'}\n}\n\n/** @internal */\nexport const InterfaceDeclarationSchema = z.discriminatedUnion('surface', [\n WindowViewSchema,\n PanelViewSchema,\n AssetSourceViewSchema,\n TileViewSchema,\n])\n\n/** @public */\nexport type ViewDeclaration = z.output<typeof InterfaceDeclarationSchema>\n\nconst WebWorkerSchema = z.object({\n type: z.literal('worker'),\n ...interfaceDeclarationFields('Web worker'),\n})\n\n/** @public */\nexport type WebWorker = z.output<typeof WebWorkerSchema>\n\n/** @public */\nexport type DefineWebWorkerInput = Omit<WebWorker, 'type'>\n\n/** @public */\nexport function defineWebWorker(webWorker: DefineWebWorkerInput): WebWorker {\n return {...webWorker, type: 'worker'}\n}\n\n/** @internal */\nexport const ServiceDeclarationSchema = z.discriminatedUnion('type', [WebWorkerSchema])\n\nconst MediaLibraryFieldSchema = z.object({\n ...extensionDeclarationFields('Field'),\n public: z.optional(z.boolean()),\n title: z.string(),\n})\n\n/**\n * Stamped where the config crosses a boundary so the authoring model doesn't carry a constant discriminator.\n * @internal\n */\nexport const INSTALLATION_CONFIG_TYPE = 'installation_config'\n\n// `appType` is stamped by `unstable_defineMediaLibrary`, never authored.\nconst MediaLibraryConfigSchema = z.object({\n appType: z.literal('media-library'),\n fields: z\n .array(MediaLibraryFieldSchema)\n .check(\n z.refine(\n (fields) => new Set(fields.map((field) => field.name)).size === fields.length,\n 'Field `name` must be unique within a media library',\n ),\n ),\n})\n\n/**\n * A workbench config's built value, keyed by `appType`; deploys as a versioned\n * snapshot, not an interface.\n * @internal\n */\nexport const ConfigSchema = z.discriminatedUnion('appType', [MediaLibraryConfigSchema])\n\n/**\n * The `{appType, fields}` config value the build expands into a federation\n * remote and the deploy summarizes.\n * @internal\n */\nexport type WorkbenchConfigValue = z.output<typeof ConfigSchema>\n"],"names":["z","VIEW_CONTRACT_VERSION","SERVICE_CONTRACT_VERSION","MEDIA_LIBRARY_CONFIG_CONTRACT_VERSION","VIEW_COMPONENTS","asset_source","panel","tile","window","TileSizeSchema","enum","DockGroupSchema","DockSchema","object","group","optional","order","number","PanelDockSchema","ViewPlacementMetadataSchema","dock","TileInterfaceMetadataSchema","size","INTERFACE_CONTRACT_VERSIONS","undefined","worker","interfaceContractVersion","kind","version","String","interfaceModuleId","name","Error","extensionDeclarationFields","pattern","string","check","regex","src","interfaceDeclarationFields","title","PanelViewSchema","surface","literal","definePanelView","view","WindowViewSchema","defineWindowView","AssetSourceViewSchema","defineAssetSourceView","TileViewSchema","defineTileView","InterfaceDeclarationSchema","discriminatedUnion","WebWorkerSchema","type","defineWebWorker","webWorker","ServiceDeclarationSchema","MediaLibraryFieldSchema","public","boolean","INSTALLATION_CONFIG_TYPE","MediaLibraryConfigSchema","appType","fields","array","refine","Set","map","field","length","ConfigSchema"],"mappings":"AAAA,SAAQA,CAAC,QAAO,WAAU;AAE1B,4EAA4E;AAC5E,kEAAkE;AAClE,qCAAqC;AAErC,cAAc,GACd,OAAO,MAAMC,wBAAwB,EAAC;AAEtC,cAAc,GACd,OAAO,MAAMC,2BAA2B,EAAC;AAEzC,cAAc,GACd,OAAO,MAAMC,wCAAwC,EAAC;AActD,kGAAkG,GAClG,OAAO,MAAMC,kBAAkB;IAC7BC,cAAc;QAAC;KAAe;IAC9BC,OAAO;QAAC;QAAS;KAAQ;IACzBC,MAAM;QAAC;KAAO;IACdC,QAAQ,EAAE;AACZ,EAAsD;AAKtD;;;;;;CAMC,GACD,OAAO,M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src/contract.ts"],"sourcesContent":["import {z} from 'zod/mini'\n\n// Shared module-federation extension contract: interface (view/web worker) and\n// config declaration schemas, plus the versions the build stamps.\n// `zod/mini` keeps the bundle small.\n\n/** @internal */\nexport const VIEW_CONTRACT_VERSION = 2\n\n/** @internal */\nexport const WEB_WORKER_CONTRACT_VERSION = 1\n\n/** @internal */\nexport const WINDOW_CONTRACT_VERSION = 1\n\n/** @internal */\nexport const MEDIA_LIBRARY_CONFIG_CONTRACT_VERSION = 1\n\n/**\n * A view component. The return is opaque so the runtime helpers carry no React\n * dependency — the generated artifact renders it with the app's own React.\n * @public\n */\nexport type ViewComponent<TProps> = (props: TProps) => unknown\n\n/** @public */\nexport interface ViewComponentBaseProps<TView> {\n view: TView\n}\n\n/** Component slots per view surface; windows load outside the component artifact path. @internal */\nexport const VIEW_COMPONENTS = {\n asset_source: ['asset_source'],\n panel: ['title', 'panel'],\n tile: ['tile'],\n window: [],\n} as const satisfies Record<string, readonly string[]>\n\n/** @public */\nexport type ViewSurface = keyof typeof VIEW_COMPONENTS\n\n/**\n * A tile's footprint family — the shape it occupies on the dashboard. Modelled\n * on iOS WidgetKit families, not a linear scale: `banner` is full-width and\n * shallow, which a `small`→`large` magnitude can't express. The host maps a\n * family to a layout slot; the component reads it to render per footprint.\n * @public\n */\nexport const TileSizeSchema = z.enum(['small', 'large', 'banner'])\n\n/** @public */\nexport type TileSize = z.infer<typeof TileSizeSchema>\n\n/** @public */\nexport type WebWorkerType = 'worker'\n\n/**\n * @deprecated Use `WebWorkerType`.\n * @public\n */\nexport type ServiceType = WebWorkerType\n\nconst DockGroupSchema = z.enum(['system', 'applications'])\n\n/** @public */\nexport type DockGroup = z.output<typeof DockGroupSchema>\n\n/** @internal */\nexport const DockSchema = z.object({\n group: z.optional(DockGroupSchema),\n order: z.optional(z.number()),\n})\n\n/** @internal */\nexport type Dock = z.infer<typeof DockSchema>\n\nconst PanelDockSchema = z.object({order: z.optional(z.number())})\n\n/** @internal */\nexport const ViewPlacementMetadataSchema = z.object({dock: DockSchema})\n\n/** @internal */\nexport type ViewPlacementMetadata = z.infer<typeof ViewPlacementMetadataSchema>\n\n/**\n * A tile's interface metadata: its footprint `size` and an optional `order`\n * the dashboard sorts on, ascending. Both are authored as top-level view fields\n * (see {@link InterfaceDeclarationSchema}) but stored on the record as metadata.\n * @internal\n */\nexport const TileInterfaceMetadataSchema = z.object({\n order: z.optional(z.number()),\n size: TileSizeSchema,\n})\n\n/** @internal */\nexport type TileInterfaceMetadata = z.infer<typeof TileInterfaceMetadataSchema>\n\n/**\n * The contract version each interface type advertises, so the host can check it\n * renders/runs what it expects.\n * @internal\n */\nconst INTERFACE_CONTRACT_VERSIONS = {\n asset_source: VIEW_CONTRACT_VERSION,\n panel: VIEW_CONTRACT_VERSION,\n tile: VIEW_CONTRACT_VERSION,\n window: WINDOW_CONTRACT_VERSION,\n worker: WEB_WORKER_CONTRACT_VERSION,\n} as const satisfies Record<string, number>\n\n/** Every interface type an app exposes — a window, a view, or a web worker. */\nexport type InterfaceKind = keyof typeof INTERFACE_CONTRACT_VERSIONS\n\n/** @internal */\nexport function interfaceContractVersion(kind: InterfaceKind): string {\n return String(INTERFACE_CONTRACT_VERSIONS[kind])\n}\n\n/**\n * The module-federation id a build exposes an interface at. Dev stamps the same\n * id a deploy would, so the workbench loads a local interface like a deployed one.\n * @internal\n */\nexport function interfaceModuleId(kind: string, name: string): string {\n switch (kind) {\n case 'asset_source':\n case 'panel':\n case 'tile': {\n return `views/${name}`\n }\n case 'window': {\n return 'App'\n }\n case 'worker': {\n return `services/${name}`\n }\n default: {\n throw new Error(`Cannot derive a moduleId for unknown interface kind: ${kind}`)\n }\n }\n}\n\n// Shared `name` + `src`; `kind` only tailors the validation message.\nfunction extensionDeclarationFields(kind: 'Field' | 'View' | 'Web worker') {\n const pattern = /^[a-zA-Z0-9_-]+$/\n return {\n name: z.string().check(z.regex(pattern, `${kind} \\`name\\` must match ${pattern}`)),\n src: z.string(),\n }\n}\n\n// Every interface shares `name` + `src` + a display `title`,\n// which Brett requires on the record each becomes.\nfunction interfaceDeclarationFields(kind: 'View' | 'Web worker') {\n return {\n ...extensionDeclarationFields(kind),\n title: z.string(`${kind} \\`title\\` is required`),\n }\n}\n\nconst PanelViewSchema = z.object({\n surface: z.literal('panel'),\n ...interfaceDeclarationFields('View'),\n dock: z.optional(PanelDockSchema),\n})\n\n/** @public */\nexport type PanelView = z.output<typeof PanelViewSchema>\n\n/** @public */\nexport type DefinePanelViewInput = Omit<PanelView, 'surface'>\n\n/** @public */\nexport function definePanelView(view: DefinePanelViewInput): PanelView {\n return {...view, surface: 'panel'}\n}\n\nconst WindowViewSchema = z.object({\n surface: z.literal('window'),\n ...interfaceDeclarationFields('View'),\n dock: z.optional(DockSchema),\n})\n\n/** @public */\nexport type WindowView = z.output<typeof WindowViewSchema>\n\n/** @public */\nexport type DefineWindowViewInput = Omit<WindowView, 'surface'>\n\n/** @public */\nexport function defineWindowView(view: DefineWindowViewInput): WindowView {\n return {...view, surface: 'window'}\n}\n\nconst AssetSourceViewSchema = z.object({\n surface: z.literal('asset_source'),\n ...interfaceDeclarationFields('View'),\n})\n\n/** @public */\nexport type AssetSourceView = z.output<typeof AssetSourceViewSchema>\n\n/** @public */\nexport type DefineAssetSourceViewInput = Omit<AssetSourceView, 'surface'>\n\n/** @public */\nexport function defineAssetSourceView(view: DefineAssetSourceViewInput): AssetSourceView {\n return {...view, surface: 'asset_source'}\n}\n\nconst TileViewSchema = z.object({\n surface: z.literal('tile'),\n ...interfaceDeclarationFields('View'),\n /** Sort position within its layout track, ascending. Optional. */\n order: z.optional(z.number()),\n /** Footprint family the dashboard lays the tile out by. */\n size: TileSizeSchema,\n})\n\n/** @public */\nexport type TileView = z.output<typeof TileViewSchema>\n\n/** @public */\nexport type DefineTileViewInput = Omit<TileView, 'surface'>\n\n/** @public */\nexport function defineTileView(view: DefineTileViewInput): TileView {\n return {...view, surface: 'tile'}\n}\n\n/** @internal */\nexport const InterfaceDeclarationSchema = z.discriminatedUnion('surface', [\n WindowViewSchema,\n PanelViewSchema,\n AssetSourceViewSchema,\n TileViewSchema,\n])\n\n/** @public */\nexport type ViewDeclaration = z.output<typeof InterfaceDeclarationSchema>\n\nconst WebWorkerSchema = z.object({\n type: z.literal('worker'),\n ...interfaceDeclarationFields('Web worker'),\n})\n\n/** @public */\nexport type WebWorker = z.output<typeof WebWorkerSchema>\n\n/** @public */\nexport type DefineWebWorkerInput = Omit<WebWorker, 'type'>\n\n/** @public */\nexport function defineWebWorker(webWorker: DefineWebWorkerInput): WebWorker {\n return {...webWorker, type: 'worker'}\n}\n\n/** @internal */\nexport const WebWorkerDeclarationSchema = z.discriminatedUnion('type', [WebWorkerSchema])\n\nconst MediaLibraryFieldSchema = z.object({\n ...extensionDeclarationFields('Field'),\n public: z.optional(z.boolean()),\n title: z.string(),\n})\n\n/**\n * Stamped where the config crosses a boundary so the authoring model doesn't carry a constant discriminator.\n * @internal\n */\nexport const INSTALLATION_CONFIG_TYPE = 'installation_config'\n\n// `appType` is stamped by `unstable_defineMediaLibrary`, never authored.\nconst MediaLibraryConfigSchema = z.object({\n appType: z.literal('media-library'),\n fields: z\n .array(MediaLibraryFieldSchema)\n .check(\n z.refine(\n (fields) => new Set(fields.map((field) => field.name)).size === fields.length,\n 'Field `name` must be unique within a media library',\n ),\n ),\n})\n\n/**\n * A workbench config's built value, keyed by `appType`; deploys as a versioned\n * snapshot, not an interface.\n * @internal\n */\nexport const ConfigSchema = z.discriminatedUnion('appType', [MediaLibraryConfigSchema])\n\n/**\n * The `{appType, fields}` config value the build expands into a federation\n * remote and the deploy summarizes.\n * @internal\n */\nexport type WorkbenchConfigValue = z.output<typeof ConfigSchema>\n"],"names":["z","VIEW_CONTRACT_VERSION","WEB_WORKER_CONTRACT_VERSION","WINDOW_CONTRACT_VERSION","MEDIA_LIBRARY_CONFIG_CONTRACT_VERSION","VIEW_COMPONENTS","asset_source","panel","tile","window","TileSizeSchema","enum","DockGroupSchema","DockSchema","object","group","optional","order","number","PanelDockSchema","ViewPlacementMetadataSchema","dock","TileInterfaceMetadataSchema","size","INTERFACE_CONTRACT_VERSIONS","worker","interfaceContractVersion","kind","String","interfaceModuleId","name","Error","extensionDeclarationFields","pattern","string","check","regex","src","interfaceDeclarationFields","title","PanelViewSchema","surface","literal","definePanelView","view","WindowViewSchema","defineWindowView","AssetSourceViewSchema","defineAssetSourceView","TileViewSchema","defineTileView","InterfaceDeclarationSchema","discriminatedUnion","WebWorkerSchema","type","defineWebWorker","webWorker","WebWorkerDeclarationSchema","MediaLibraryFieldSchema","public","boolean","INSTALLATION_CONFIG_TYPE","MediaLibraryConfigSchema","appType","fields","array","refine","Set","map","field","length","ConfigSchema"],"mappings":"AAAA,SAAQA,CAAC,QAAO,WAAU;AAE1B,+EAA+E;AAC/E,kEAAkE;AAClE,qCAAqC;AAErC,cAAc,GACd,OAAO,MAAMC,wBAAwB,EAAC;AAEtC,cAAc,GACd,OAAO,MAAMC,8BAA8B,EAAC;AAE5C,cAAc,GACd,OAAO,MAAMC,0BAA0B,EAAC;AAExC,cAAc,GACd,OAAO,MAAMC,wCAAwC,EAAC;AActD,kGAAkG,GAClG,OAAO,MAAMC,kBAAkB;IAC7BC,cAAc;QAAC;KAAe;IAC9BC,OAAO;QAAC;QAAS;KAAQ;IACzBC,MAAM;QAAC;KAAO;IACdC,QAAQ,EAAE;AACZ,EAAsD;AAKtD;;;;;;CAMC,GACD,OAAO,MAAMC,iBAAiBV,EAAEW,IAAI,CAAC;IAAC;IAAS;IAAS;CAAS,EAAC;AAclE,MAAMC,kBAAkBZ,EAAEW,IAAI,CAAC;IAAC;IAAU;CAAe;AAKzD,cAAc,GACd,OAAO,MAAME,aAAab,EAAEc,MAAM,CAAC;IACjCC,OAAOf,EAAEgB,QAAQ,CAACJ;IAClBK,OAAOjB,EAAEgB,QAAQ,CAAChB,EAAEkB,MAAM;AAC5B,GAAE;AAKF,MAAMC,kBAAkBnB,EAAEc,MAAM,CAAC;IAACG,OAAOj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,GAAGJ,2BAA2B,aAAa;AAC7C;AAQA,YAAY,GACZ,OAAO,SAASiB,gBAAgBC,SAA+B;IAC7D,OAAO;QAAC,GAAGA,SAAS;QAAEF,MAAM;IAAQ;AACtC;AAEA,cAAc,GACd,OAAO,MAAMG,6BAA6BzD,EAAEoD,kBAAkB,CAAC,QAAQ;IAACC;CAAgB,EAAC;AAEzF,MAAMK,0BAA0B1D,EAAEc,MAAM,CAAC;IACvC,GAAGkB,2BAA2B,QAAQ;IACtC2B,QAAQ3D,EAAEgB,QAAQ,CAAChB,EAAE4D,OAAO;IAC5BrB,OAAOvC,EAAEkC,MAAM;AACjB;AAEA;;;CAGC,GACD,OAAO,MAAM2B,2BAA2B,sBAAqB;AAE7D,yEAAyE;AACzE,MAAMC,2BAA2B9D,EAAEc,MAAM,CAAC;IACxCiD,SAAS/D,EAAE0C,OAAO,CAAC;IACnBsB,QAAQhE,EACLiE,KAAK,CAACP,yBACNvB,KAAK,CACJnC,EAAEkE,MAAM,CACN,CAACF,SAAW,IAAIG,IAAIH,OAAOI,GAAG,CAAC,CAACC,QAAUA,MAAMvC,IAAI,GAAGP,IAAI,KAAKyC,OAAOM,MAAM,EAC7E;AAGR;AAEA;;;;CAIC,GACD,OAAO,MAAMC,eAAevE,EAAEoD,kBAAkB,CAAC,WAAW;IAACU;CAAyB,EAAC"}
package/dist/defineApp.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { z } from 'zod/mini';
2
2
  import { APP_SLUG_PATTERN } from './appSlug.js';
3
- import { DockSchema, InterfaceDeclarationSchema, ServiceDeclarationSchema } from './contract.js';
3
+ import { DockSchema, InterfaceDeclarationSchema, WebWorkerDeclarationSchema } from './contract.js';
4
4
  /**
5
5
  * Dashboard visibility values. Mirrors `APP_VISIBILITIES` in `@sanity/cli-core`
6
6
  * (which can't be imported here — pulling the barrel into this lean module bloats
@@ -49,7 +49,7 @@ import { DockSchema, InterfaceDeclarationSchema, ServiceDeclarationSchema } from
49
49
  /** User-facing app title. Wins over studio.config.ts title on merge. */ title: z.string(),
50
50
  /** Views the app exposes (e.g. a window, dock panels, and tiles). */ views: z.optional(z.array(InterfaceDeclarationSchema, 'must be an array of views')),
51
51
  /** Dashboard visibility of the app. Defaults to `default` when omitted. */ visibility: z.optional(z.enum(APP_VISIBILITIES)),
52
- /** Background web workers the app runs. */ webWorkers: z.optional(z.array(ServiceDeclarationSchema, 'must be an array of web workers'))
52
+ /** Background web workers the app runs. */ webWorkers: z.optional(z.array(WebWorkerDeclarationSchema, 'must be an array of web workers'))
53
53
  }).check(z.refine((input)=>{
54
54
  const names = [
55
55
  ...input.entry === undefined ? [] : [