@sanity/workbench-cli 2.8.3 → 2.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/dist/_exports/_internal_worker_bus.d.ts +29 -0
  2. package/dist/_exports/_internal_worker_bus.js +3 -0
  3. package/dist/_exports/_internal_worker_bus.js.map +1 -0
  4. package/dist/_exports/build.d.ts +1 -1
  5. package/dist/_exports/contract-D_HnLQtT.d.ts +197 -0
  6. package/dist/_exports/defineApp-4hImcIIe.d.ts +182 -0
  7. package/dist/_exports/defineService-C1MhDwmh.d.ts +74 -0
  8. package/dist/_exports/deploy.d.ts +11 -3
  9. package/dist/_exports/index.d.ts +4 -50
  10. package/dist/_exports/index.js.map +1 -1
  11. package/dist/_exports/init.d.ts +3 -3
  12. package/dist/_exports/{resolveWorkbenchConfig-KhXnVKZ6.d.ts → resolveWorkbenchConfig-s3msa3Hu.d.ts} +3 -2
  13. package/dist/_exports/{summarizeInterfaces-noqbAtVC.d.ts → summarizeInterfaces-C0TCOa0J.d.ts} +4 -4
  14. package/dist/_exports/undeploy.d.ts +2 -2
  15. package/dist/actions/build/services/artifact.js +13 -3
  16. package/dist/actions/build/services/artifact.js.map +1 -1
  17. package/dist/actions/build/services/workerBus.js +159 -0
  18. package/dist/actions/build/services/workerBus.js.map +1 -0
  19. package/dist/actions/build/vite/plugins/plugin-sanity-extension-artifacts.js +17 -0
  20. package/dist/actions/build/vite/plugins/plugin-sanity-extension-artifacts.js.map +1 -1
  21. package/dist/actions/deploy/checkBuiltOutput.js +10 -2
  22. package/dist/actions/deploy/checkBuiltOutput.js.map +1 -1
  23. package/dist/actions/deploy/deployWorkbenchApp.js +10 -3
  24. package/dist/actions/deploy/deployWorkbenchApp.js.map +1 -1
  25. package/dist/actions/dev/registry.js +9 -0
  26. package/dist/actions/dev/registry.js.map +1 -1
  27. package/dist/actions/dev/startDevServerRegistration.js +6 -2
  28. package/dist/actions/dev/startDevServerRegistration.js.map +1 -1
  29. package/dist/actions/dev/startWorkbenchDev.js +4 -4
  30. package/dist/actions/dev/startWorkbenchDev.js.map +1 -1
  31. package/dist/actions/init/cliConfig.js +3 -1
  32. package/dist/actions/init/cliConfig.js.map +1 -1
  33. package/dist/actions/preview/startWorkbenchPreview.js +12 -6
  34. package/dist/actions/preview/startWorkbenchPreview.js.map +1 -1
  35. package/dist/defineService.js +11 -2
  36. package/dist/defineService.js.map +1 -1
  37. package/dist/services/applications.js +20 -8
  38. package/dist/services/applications.js.map +1 -1
  39. package/package.json +14 -9
  40. package/dist/_exports/defineApp-DOJE2kjo.d.ts +0 -376
@@ -1,7 +1,7 @@
1
- import { D as ViewSurface, b as ServiceType } from "./defineApp-DOJE2kjo.js";
2
- import { i as WorkbenchExposes, r as ResolvedWorkbenchApp } from "./resolveWorkbenchConfig-KhXnVKZ6.js";
3
- import { CliConfig } from "@sanity/cli-core";
1
+ import { _ as ViewSurface, u as ServiceType } from "./contract-D_HnLQtT.js";
2
+ import { i as WorkbenchExposes, r as ResolvedWorkbenchApp } from "./resolveWorkbenchConfig-s3msa3Hu.js";
4
3
  import { z } from "zod/mini";
4
+ import { CliConfig } from "@sanity/cli-core";
5
5
  /**
6
6
  * Payload registering an app's views with the application service on deploy.
7
7
  *
@@ -62,4 +62,4 @@ declare function summarizeInterfaces({ views, webWorkers }: WorkbenchExposes): {
62
62
  views: DeployedView[];
63
63
  };
64
64
  export { DeployableWorkbenchApp as a, summarizeInterfaces as i, DeployedView as n, getWorkbench as o, DeployedWebWorker as r, DeployedInterface as t };
65
- //# sourceMappingURL=summarizeInterfaces-noqbAtVC.d.ts.map
65
+ //# sourceMappingURL=summarizeInterfaces-C0TCOa0J.d.ts.map
@@ -1,5 +1,5 @@
1
- import { t as ResolvedMediaLibraryConfig } from "./resolveWorkbenchConfig-KhXnVKZ6.js";
2
- import { a as DeployableWorkbenchApp, n as DeployedView, r as DeployedWebWorker } from "./summarizeInterfaces-noqbAtVC.js";
1
+ import { t as ResolvedMediaLibraryConfig } from "./resolveWorkbenchConfig-s3msa3Hu.js";
2
+ import { a as DeployableWorkbenchApp, n as DeployedView, r as DeployedWebWorker } from "./summarizeInterfaces-C0TCOa0J.js";
3
3
  import "node:zlib";
4
4
  import { UndeployAdapter, UndeployApplicationTarget, UndeployConfigTarget } from "@sanity/cli-core/undeploy";
5
5
  interface ConfigSnapshot {
@@ -1,4 +1,5 @@
1
1
  import { SERVICE_CONTRACT_VERSION } from '../../../contract.js';
2
+ /** The worker bus client the generated `worker.js` imports; see the extension-artifacts plugin's alias. */ export const WORKER_BUS_ENTRY = '@sanity/workbench-cli/_internal_worker_bus';
2
3
  /** Subdirectory under the federation runtime dir where service artifacts live. */ const SERVICES_DIR_NAME = 'services';
3
4
  const SERVICE_TYPES = [
4
5
  'worker'
@@ -33,7 +34,8 @@ const SERVICE_TYPES = [
33
34
  * Source for one service's **worker** bundle — the Web Worker entry. Imports
34
35
  * the user's `unstable_defineService` result and runs its callback with the
35
36
  * service's own declaration (mirroring how a view component receives its
36
- * `view`), then wires the returned disposer to the host's terminate message.
37
+ * `view`) and a message bus client (`workerBus.ts`), then wires the returned
38
+ * disposer to the host's terminate message.
37
39
  * Crashes — and the worker's `console.*`, which is patched to forward to the
38
40
  * host — are surfaced through the host logger (the host owns logging; a worker's
39
41
  * own console isn't visible in the page DevTools anyway).
@@ -42,6 +44,7 @@ const SERVICE_TYPES = [
42
44
  // This file is auto-generated on 'sanity build' / 'sanity dev'
43
45
  // Modifications to this file are automatically discarded
44
46
  import service from ${JSON.stringify(input.importPath)}
47
+ import { createWorkerBus } from ${JSON.stringify(WORKER_BUS_ENTRY)}
45
48
 
46
49
  const SERVICE = { type: ${JSON.stringify(input.service.type)}, name: ${JSON.stringify(input.service.name)} }
47
50
 
@@ -63,17 +66,24 @@ for (const __level of ['log', 'info', 'warn', 'error', 'debug']) {
63
66
  }
64
67
  }
65
68
 
69
+ const { bus, close: closeBus, receive: receiveBus } = createWorkerBus()
70
+
66
71
  let dispose
67
72
  try {
68
- const result = service.run({ service: SERVICE })
73
+ const result = service.run({ bus, service: SERVICE })
69
74
  if (typeof result === 'function') dispose = result
70
75
  } catch (error) {
71
76
  self.postMessage({ kind: 'workbench.worker.error', payload: { message: String(error) } })
72
77
  }
73
78
 
74
79
  self.addEventListener('message', (event) => {
75
- if (event.data && event.data.kind === 'workbench.worker.terminate') {
80
+ if (!event.data) return
81
+ if (event.data.kind === 'workbench.worker.terminate') {
82
+ // Close the bus first: the host has disconnected, so the disposer's bus calls must fail at once.
83
+ closeBus()
76
84
  try { dispose && dispose() } finally { self.close() }
85
+ } else {
86
+ receiveBus(event.data)
77
87
  }
78
88
  })
79
89
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/actions/build/services/artifact.ts"],"sourcesContent":["import {SERVICE_CONTRACT_VERSION, type ServiceType} from '../../../contract.js'\nimport {type GeneratedArtifact} from '../artifact.js'\n\n/** Subdirectory under the federation runtime dir where service artifacts live. */\nconst SERVICES_DIR_NAME = 'services'\n\nconst SERVICE_TYPES: readonly ServiceType[] = ['worker']\n\n/**\n * A service to generate a worker artifact for. The `src` file default-exports\n * an `unstable_defineService(...)` result; the build emits a self-contained Web\n * Worker bundle plus a loader module that hands the host its URL.\n * @internal\n */\nexport interface ServiceArtifact {\n /** Service name, unique within the app. */\n name: string\n /** Path to the service `src` file, relative to the app root (or absolute). */\n src: string\n /** Service type, e.g. `\"worker\"`. */\n type: string\n}\n\n/**\n * Expand each service into its two generated artifacts: a self-contained worker\n * bundle (imports the user's `src`, runs the callback) and a loader module the\n * host loads to read the worker's URL. Only the loader is a federation expose —\n * the host reaches the worker bundle through it, never directly.\n */\nexport function serviceArtifacts(services: readonly ServiceArtifact[]): GeneratedArtifact[] {\n return services\n .filter((service) => (SERVICE_TYPES as readonly string[]).includes(service.type))\n .flatMap((service): GeneratedArtifact[] => {\n const dir = `${SERVICES_DIR_NAME}/${service.name}`\n return [\n {\n path: `${dir}/worker.js`,\n source: ({resolveImport}) =>\n serviceWorkerArtifactSource({\n importPath: resolveImport(service.src),\n service,\n }),\n },\n {\n expose: `./${dir}`,\n path: `${dir}/index.js`,\n source: () => serviceLoaderArtifactSource({service}),\n },\n ]\n })\n}\n\n/**\n * Source for one service's **worker** bundle — the Web Worker entry. Imports\n * the user's `unstable_defineService` result and runs its callback with the\n * service's own declaration (mirroring how a view component receives its\n * `view`), then wires the returned disposer to the host's terminate message.\n * Crashes — and the worker's `console.*`, which is patched to forward to the\n * host — are surfaced through the host logger (the host owns logging; a worker's\n * own console isn't visible in the page DevTools anyway).\n */\nfunction serviceWorkerArtifactSource(input: {\n importPath: string\n service: {name: string; type: string}\n}): string {\n return `\\\n// This file is auto-generated on 'sanity build' / 'sanity dev'\n// Modifications to this file are automatically discarded\nimport service from ${JSON.stringify(input.importPath)}\n\nconst SERVICE = { type: ${JSON.stringify(input.service.type)}, name: ${JSON.stringify(input.service.name)} }\n\n// Bridge the worker's console to the host. A worker's own console isn't visible\n// in the page DevTools, so patch console.* to forward each call as a message\n// the host re-emits through the workbench logger — any console.log in the\n// service (or its deps) just shows up in the page console.\nconst __format = (arg) => {\n if (typeof arg === 'string') return arg\n try { return JSON.stringify(arg) } catch (_) { return String(arg) }\n}\nfor (const __level of ['log', 'info', 'warn', 'error', 'debug']) {\n const __native = typeof console[__level] === 'function' ? console[__level].bind(console) : () => {}\n console[__level] = (...args) => {\n __native(...args)\n try {\n self.postMessage({ kind: 'workbench.worker.log', payload: { level: __level, message: args.map(__format).join(' ') } })\n } catch (_) {}\n }\n}\n\nlet dispose\ntry {\n const result = service.run({ service: SERVICE })\n if (typeof result === 'function') dispose = result\n} catch (error) {\n self.postMessage({ kind: 'workbench.worker.error', payload: { message: String(error) } })\n}\n\nself.addEventListener('message', (event) => {\n if (event.data && event.data.kind === 'workbench.worker.terminate') {\n try { dispose && dispose() } finally { self.close() }\n }\n})\n\nself.addEventListener('error', (event) => {\n self.postMessage({ kind: 'workbench.worker.error', payload: { message: String(event.message || event) } })\n})\n\n// An async run callback (or async work it kicks off) rejects without hitting\n// the synchronous try/catch above; module workers surface that as\n// 'unhandledrejection' on self, not 'error'. Forward it so the crash reaches\n// the host either way.\nself.addEventListener('unhandledrejection', (event) => {\n self.postMessage({ kind: 'workbench.worker.error', payload: { message: String(event.reason) } })\n})\n`\n}\n\n/**\n * Source for one service's **loader** — the module-federation expose. Hands the\n * host the worker bundle's URL (via Vite `?worker&url`) plus the service's\n * type/version.\n *\n * A URL (not an inlined worker) on purpose: the host can't `new Worker()` it\n * directly — cross-origin in dev/prod, and `?worker&inline` only self-contains\n * the worker in a build, not under `sanity dev`. Instead the host bootstraps a\n * same-origin worker that dynamically `import()`s this URL, so the worker\n * resolves its own imports against the app origin. Works in dev and build alike.\n *\n * No HMR boundary: a worker lives in its own `?worker&url` module graph with no\n * accepting importer, so Vite full-reloads the page on a `src` edit (which\n * re-loads the worker with the new code) — in-place worker HMR isn't possible.\n */\nfunction serviceLoaderArtifactSource(input: {service: {name: string; type: string}}): string {\n return `\\\n// This file is auto-generated on 'sanity build' / 'sanity dev'\n// Modifications to this file are automatically discarded\nimport workerUrl from './worker.js?worker&url'\n\n/** URL of the worker bundle, on the app's origin. */\nexport const url = workerUrl\n/** Service type and contract version, surfaced for the host to dispatch on. */\nexport const type = ${JSON.stringify(input.service.type)}\nexport const name = ${JSON.stringify(input.service.name)}\nexport const version = ${SERVICE_CONTRACT_VERSION}\n`\n}\n"],"names":["SERVICE_CONTRACT_VERSION","SERVICES_DIR_NAME","SERVICE_TYPES","serviceArtifacts","services","filter","service","includes","type","flatMap","dir","name","path","source","resolveImport","serviceWorkerArtifactSource","importPath","src","expose","serviceLoaderArtifactSource","input","JSON","stringify"],"mappings":"AAAA,SAAQA,wBAAwB,QAAyB,uBAAsB;AAG/E,gFAAgF,GAChF,MAAMC,oBAAoB;AAE1B,MAAMC,gBAAwC;IAAC;CAAS;AAiBxD;;;;;CAKC,GACD,OAAO,SAASC,iBAAiBC,QAAoC;IACnE,OAAOA,SACJC,MAAM,CAAC,CAACC,UAAY,AAACJ,cAAoCK,QAAQ,CAACD,QAAQE,IAAI,GAC9EC,OAAO,CAAC,CAACH;QACR,MAAMI,MAAM,GAAGT,kBAAkB,CAAC,EAAEK,QAAQK,IAAI,EAAE;QAClD,OAAO;YACL;gBACEC,MAAM,GAAGF,IAAI,UAAU,CAAC;gBACxBG,QAAQ,CAAC,EAACC,aAAa,EAAC,GACtBC,4BAA4B;wBAC1BC,YAAYF,cAAcR,QAAQW,GAAG;wBACrCX;oBACF;YACJ;YACA;gBACEY,QAAQ,CAAC,EAAE,EAAER,KAAK;gBAClBE,MAAM,GAAGF,IAAI,SAAS,CAAC;gBACvBG,QAAQ,IAAMM,4BAA4B;wBAACb;oBAAO;YACpD;SACD;IACH;AACJ;AAEA;;;;;;;;CAQC,GACD,SAASS,4BAA4BK,KAGpC;IACC,OAAO,CAAC;;;oBAGU,EAAEC,KAAKC,SAAS,CAACF,MAAMJ,UAAU,EAAE;;wBAE/B,EAAEK,KAAKC,SAAS,CAACF,MAAMd,OAAO,CAACE,IAAI,EAAE,QAAQ,EAAEa,KAAKC,SAAS,CAACF,MAAMd,OAAO,CAACK,IAAI,EAAE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6C1G,CAAC;AACD;AAEA;;;;;;;;;;;;;;CAcC,GACD,SAASQ,4BAA4BC,KAA8C;IACjF,OAAO,CAAC;;;;;;;;oBAQU,EAAEC,KAAKC,SAAS,CAACF,MAAMd,OAAO,CAACE,IAAI,EAAE;oBACrC,EAAEa,KAAKC,SAAS,CAACF,MAAMd,OAAO,CAACK,IAAI,EAAE;uBAClC,EAAEX,yBAAyB;AAClD,CAAC;AACD"}
1
+ {"version":3,"sources":["../../../../src/actions/build/services/artifact.ts"],"sourcesContent":["import {SERVICE_CONTRACT_VERSION, type ServiceType} from '../../../contract.js'\nimport {type GeneratedArtifact} from '../artifact.js'\n\n/** The worker bus client the generated `worker.js` imports; see the extension-artifacts plugin's alias. */\nexport const WORKER_BUS_ENTRY = '@sanity/workbench-cli/_internal_worker_bus'\n\n/** Subdirectory under the federation runtime dir where service artifacts live. */\nconst SERVICES_DIR_NAME = 'services'\n\nconst SERVICE_TYPES: readonly ServiceType[] = ['worker']\n\n/**\n * A service to generate a worker artifact for. The `src` file default-exports\n * an `unstable_defineService(...)` result; the build emits a self-contained Web\n * Worker bundle plus a loader module that hands the host its URL.\n * @internal\n */\nexport interface ServiceArtifact {\n /** Service name, unique within the app. */\n name: string\n /** Path to the service `src` file, relative to the app root (or absolute). */\n src: string\n /** Service type, e.g. `\"worker\"`. */\n type: string\n}\n\n/**\n * Expand each service into its two generated artifacts: a self-contained worker\n * bundle (imports the user's `src`, runs the callback) and a loader module the\n * host loads to read the worker's URL. Only the loader is a federation expose —\n * the host reaches the worker bundle through it, never directly.\n */\nexport function serviceArtifacts(services: readonly ServiceArtifact[]): GeneratedArtifact[] {\n return services\n .filter((service) => (SERVICE_TYPES as readonly string[]).includes(service.type))\n .flatMap((service): GeneratedArtifact[] => {\n const dir = `${SERVICES_DIR_NAME}/${service.name}`\n return [\n {\n path: `${dir}/worker.js`,\n source: ({resolveImport}) =>\n serviceWorkerArtifactSource({\n importPath: resolveImport(service.src),\n service,\n }),\n },\n {\n expose: `./${dir}`,\n path: `${dir}/index.js`,\n source: () => serviceLoaderArtifactSource({service}),\n },\n ]\n })\n}\n\n/**\n * Source for one service's **worker** bundle — the Web Worker entry. Imports\n * the user's `unstable_defineService` result and runs its callback with the\n * service's own declaration (mirroring how a view component receives its\n * `view`) and a message bus client (`workerBus.ts`), then wires the returned\n * disposer to the host's terminate message.\n * Crashes — and the worker's `console.*`, which is patched to forward to the\n * host — are surfaced through the host logger (the host owns logging; a worker's\n * own console isn't visible in the page DevTools anyway).\n */\nfunction serviceWorkerArtifactSource(input: {\n importPath: string\n service: {name: string; type: string}\n}): string {\n return `\\\n// This file is auto-generated on 'sanity build' / 'sanity dev'\n// Modifications to this file are automatically discarded\nimport service from ${JSON.stringify(input.importPath)}\nimport { createWorkerBus } from ${JSON.stringify(WORKER_BUS_ENTRY)}\n\nconst SERVICE = { type: ${JSON.stringify(input.service.type)}, name: ${JSON.stringify(input.service.name)} }\n\n// Bridge the worker's console to the host. A worker's own console isn't visible\n// in the page DevTools, so patch console.* to forward each call as a message\n// the host re-emits through the workbench logger — any console.log in the\n// service (or its deps) just shows up in the page console.\nconst __format = (arg) => {\n if (typeof arg === 'string') return arg\n try { return JSON.stringify(arg) } catch (_) { return String(arg) }\n}\nfor (const __level of ['log', 'info', 'warn', 'error', 'debug']) {\n const __native = typeof console[__level] === 'function' ? console[__level].bind(console) : () => {}\n console[__level] = (...args) => {\n __native(...args)\n try {\n self.postMessage({ kind: 'workbench.worker.log', payload: { level: __level, message: args.map(__format).join(' ') } })\n } catch (_) {}\n }\n}\n\nconst { bus, close: closeBus, receive: receiveBus } = createWorkerBus()\n\nlet dispose\ntry {\n const result = service.run({ bus, service: SERVICE })\n if (typeof result === 'function') dispose = result\n} catch (error) {\n self.postMessage({ kind: 'workbench.worker.error', payload: { message: String(error) } })\n}\n\nself.addEventListener('message', (event) => {\n if (!event.data) return\n if (event.data.kind === 'workbench.worker.terminate') {\n // Close the bus first: the host has disconnected, so the disposer's bus calls must fail at once.\n closeBus()\n try { dispose && dispose() } finally { self.close() }\n } else {\n receiveBus(event.data)\n }\n})\n\nself.addEventListener('error', (event) => {\n self.postMessage({ kind: 'workbench.worker.error', payload: { message: String(event.message || event) } })\n})\n\n// An async run callback (or async work it kicks off) rejects without hitting\n// the synchronous try/catch above; module workers surface that as\n// 'unhandledrejection' on self, not 'error'. Forward it so the crash reaches\n// the host either way.\nself.addEventListener('unhandledrejection', (event) => {\n self.postMessage({ kind: 'workbench.worker.error', payload: { message: String(event.reason) } })\n})\n`\n}\n\n/**\n * Source for one service's **loader** — the module-federation expose. Hands the\n * host the worker bundle's URL (via Vite `?worker&url`) plus the service's\n * type/version.\n *\n * A URL (not an inlined worker) on purpose: the host can't `new Worker()` it\n * directly — cross-origin in dev/prod, and `?worker&inline` only self-contains\n * the worker in a build, not under `sanity dev`. Instead the host bootstraps a\n * same-origin worker that dynamically `import()`s this URL, so the worker\n * resolves its own imports against the app origin. Works in dev and build alike.\n *\n * No HMR boundary: a worker lives in its own `?worker&url` module graph with no\n * accepting importer, so Vite full-reloads the page on a `src` edit (which\n * re-loads the worker with the new code) — in-place worker HMR isn't possible.\n */\nfunction serviceLoaderArtifactSource(input: {service: {name: string; type: string}}): string {\n return `\\\n// This file is auto-generated on 'sanity build' / 'sanity dev'\n// Modifications to this file are automatically discarded\nimport workerUrl from './worker.js?worker&url'\n\n/** URL of the worker bundle, on the app's origin. */\nexport const url = workerUrl\n/** Service type and contract version, surfaced for the host to dispatch on. */\nexport const type = ${JSON.stringify(input.service.type)}\nexport const name = ${JSON.stringify(input.service.name)}\nexport const version = ${SERVICE_CONTRACT_VERSION}\n`\n}\n"],"names":["SERVICE_CONTRACT_VERSION","WORKER_BUS_ENTRY","SERVICES_DIR_NAME","SERVICE_TYPES","serviceArtifacts","services","filter","service","includes","type","flatMap","dir","name","path","source","resolveImport","serviceWorkerArtifactSource","importPath","src","expose","serviceLoaderArtifactSource","input","JSON","stringify"],"mappings":"AAAA,SAAQA,wBAAwB,QAAyB,uBAAsB;AAG/E,yGAAyG,GACzG,OAAO,MAAMC,mBAAmB,6CAA4C;AAE5E,gFAAgF,GAChF,MAAMC,oBAAoB;AAE1B,MAAMC,gBAAwC;IAAC;CAAS;AAiBxD;;;;;CAKC,GACD,OAAO,SAASC,iBAAiBC,QAAoC;IACnE,OAAOA,SACJC,MAAM,CAAC,CAACC,UAAY,AAACJ,cAAoCK,QAAQ,CAACD,QAAQE,IAAI,GAC9EC,OAAO,CAAC,CAACH;QACR,MAAMI,MAAM,GAAGT,kBAAkB,CAAC,EAAEK,QAAQK,IAAI,EAAE;QAClD,OAAO;YACL;gBACEC,MAAM,GAAGF,IAAI,UAAU,CAAC;gBACxBG,QAAQ,CAAC,EAACC,aAAa,EAAC,GACtBC,4BAA4B;wBAC1BC,YAAYF,cAAcR,QAAQW,GAAG;wBACrCX;oBACF;YACJ;YACA;gBACEY,QAAQ,CAAC,EAAE,EAAER,KAAK;gBAClBE,MAAM,GAAGF,IAAI,SAAS,CAAC;gBACvBG,QAAQ,IAAMM,4BAA4B;wBAACb;oBAAO;YACpD;SACD;IACH;AACJ;AAEA;;;;;;;;;CASC,GACD,SAASS,4BAA4BK,KAGpC;IACC,OAAO,CAAC;;;oBAGU,EAAEC,KAAKC,SAAS,CAACF,MAAMJ,UAAU,EAAE;gCACvB,EAAEK,KAAKC,SAAS,CAACtB,kBAAkB;;wBAE3C,EAAEqB,KAAKC,SAAS,CAACF,MAAMd,OAAO,CAACE,IAAI,EAAE,QAAQ,EAAEa,KAAKC,SAAS,CAACF,MAAMd,OAAO,CAACK,IAAI,EAAE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoD1G,CAAC;AACD;AAEA;;;;;;;;;;;;;;CAcC,GACD,SAASQ,4BAA4BC,KAA8C;IACjF,OAAO,CAAC;;;;;;;;oBAQU,EAAEC,KAAKC,SAAS,CAACF,MAAMd,OAAO,CAACE,IAAI,EAAE;oBACrC,EAAEa,KAAKC,SAAS,CAACF,MAAMd,OAAO,CAACK,IAAI,EAAE;uBAClC,EAAEZ,yBAAyB;AAClD,CAAC;AACD"}
@@ -0,0 +1,159 @@
1
+ // Runs inside the service's Web Worker, bundled by Vite from the generated
2
+ // `worker.js`. Keep it free of Node and of runtime imports: `@sanity/sdk` is
3
+ // only ever imported for types.
4
+ const DEFAULT_TIMEOUT_MS = 5000;
5
+ // Mirrors the SDK's MessageBusError: importing the class would pull the SDK
6
+ // runtime into the worker bundle.
7
+ const busError = (code, message)=>Object.assign(new Error(message || code), {
8
+ code,
9
+ name: 'MessageBusError'
10
+ });
11
+ /**
12
+ * The worker's side of the `workbench.bus.*` wire contract. The host relays
13
+ * each request to the Dashboard bus and stamps it with the worker's identity,
14
+ * so the client only tracks ids.
15
+ * @internal
16
+ */ export function createWorkerBus() {
17
+ const pending = new Map();
18
+ const subscriptions = new Map();
19
+ let nextId = 0;
20
+ let closed = false;
21
+ // Posts a request and returns a function that creates its promise on first
22
+ // call. Until then a reply, even an error, is only held: a rejected promise
23
+ // nobody awaits would reach the worker's 'unhandledrejection' forwarder as a crash.
24
+ function request(message, options = {}) {
25
+ const { signal, timeout } = options;
26
+ const id = ++nextId;
27
+ let outcome;
28
+ let onOutcome;
29
+ let timer;
30
+ const settle = (result)=>{
31
+ if (outcome) return;
32
+ outcome = result;
33
+ clearTimeout(timer);
34
+ pending.delete(id);
35
+ signal?.removeEventListener('abort', onAbort);
36
+ onOutcome?.(result);
37
+ };
38
+ const onAbort = ()=>{
39
+ self.postMessage({
40
+ id,
41
+ kind: 'workbench.bus.abort'
42
+ });
43
+ settle({
44
+ error: busError('ABORTED'),
45
+ ok: false
46
+ });
47
+ };
48
+ if (closed || signal?.aborted) {
49
+ outcome = {
50
+ error: busError('ABORTED'),
51
+ ok: false
52
+ };
53
+ } else {
54
+ // An omitted timeout must stay absent on the wire, so the host applies its default.
55
+ self.postMessage(timeout === undefined ? {
56
+ ...message,
57
+ id
58
+ } : {
59
+ ...message,
60
+ id,
61
+ timeout
62
+ });
63
+ pending.set(id, settle);
64
+ // A host that predates the bus never replies; time out here too so the call still settles.
65
+ if (timeout !== null) {
66
+ timer = setTimeout(()=>settle({
67
+ error: busError('TIMEOUT'),
68
+ ok: false
69
+ }), timeout ?? DEFAULT_TIMEOUT_MS);
70
+ }
71
+ signal?.addEventListener('abort', onAbort, {
72
+ once: true
73
+ });
74
+ }
75
+ let promise;
76
+ return ()=>promise ??= new Promise((resolve, reject)=>{
77
+ onOutcome = (result)=>result.ok ? resolve(result.value) : reject(result.error);
78
+ if (outcome) onOutcome(outcome);
79
+ });
80
+ }
81
+ const bus = {
82
+ emit: (topic, payload, options)=>{
83
+ const awaitReply = request({
84
+ kind: 'workbench.bus.emit',
85
+ payload,
86
+ topic
87
+ }, options);
88
+ const result = {
89
+ catch: (onRejected)=>awaitReply().then(undefined, onRejected),
90
+ finally: (onFinally)=>awaitReply().finally(onFinally),
91
+ // eslint-disable-next-line unicorn/no-thenable -- awaiting arms reply failure handling; fire-and-forget does not.
92
+ then: (onFulfilled, onRejected)=>awaitReply().then(onFulfilled, onRejected)
93
+ };
94
+ return result;
95
+ },
96
+ query: (topic, options)=>request({
97
+ kind: 'workbench.bus.query',
98
+ topic
99
+ }, options)(),
100
+ subscribe: (topic, handler, options)=>{
101
+ if (closed) throw busError('ABORTED');
102
+ const signal = options?.signal;
103
+ if (signal?.aborted) return;
104
+ const id = ++nextId;
105
+ self.postMessage({
106
+ id,
107
+ kind: 'workbench.bus.subscribe',
108
+ topic
109
+ });
110
+ subscriptions.set(id, handler);
111
+ signal?.addEventListener('abort', ()=>{
112
+ if (subscriptions.delete(id)) self.postMessage({
113
+ id,
114
+ kind: 'workbench.bus.abort'
115
+ });
116
+ }, {
117
+ once: true
118
+ });
119
+ }
120
+ };
121
+ return {
122
+ // The topic generics only exist at the call site; the wire carries plain strings.
123
+ bus: bus,
124
+ close: ()=>{
125
+ closed = true;
126
+ subscriptions.clear();
127
+ for (const settle of pending.values())settle({
128
+ error: busError('ABORTED'),
129
+ ok: false
130
+ });
131
+ },
132
+ receive: (data)=>{
133
+ const message = data;
134
+ if (message.kind === 'workbench.bus.value') {
135
+ subscriptions.get(message.id)?.(message.value);
136
+ } else if (message.kind === 'workbench.bus.reply') {
137
+ const settle = pending.get(message.id);
138
+ if (message.ok) {
139
+ settle?.({
140
+ ok: true,
141
+ value: message.value
142
+ });
143
+ return;
144
+ }
145
+ // A refused subscription has no promise to reject, so tell the author through the host logger.
146
+ if (subscriptions.delete(message.id)) {
147
+ // eslint-disable-next-line no-console -- the worker's console is bridged to the host logger
148
+ console.error(`Message bus subscription refused: ${message.error.code}: ${message.error.message}`);
149
+ }
150
+ settle?.({
151
+ error: busError(message.error.code, message.error.message),
152
+ ok: false
153
+ });
154
+ }
155
+ }
156
+ };
157
+ }
158
+
159
+ //# sourceMappingURL=workerBus.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../src/actions/build/services/workerBus.ts"],"sourcesContent":["// Runs inside the service's Web Worker, bundled by Vite from the generated\n// `worker.js`. Keep it free of Node and of runtime imports: `@sanity/sdk` is\n// only ever imported for types.\nimport {type MessageBusEmitResult, type MessageBusErrorCode} from '@sanity/sdk/dashboard'\n\nimport {type ServiceBus} from '../../../defineService.js'\n\nconst DEFAULT_TIMEOUT_MS = 5000\n\ninterface RequestOptions {\n signal?: AbortSignal\n timeout?: number | null\n}\n\ntype Outcome = {error: Error; ok: false} | {ok: true; value: unknown}\n\ntype HostMessage =\n | {\n error: {code: MessageBusErrorCode; message: string}\n id: number\n kind: 'workbench.bus.reply'\n ok: false\n }\n | {id: number; kind: 'workbench.bus.reply'; ok: true; value: unknown}\n | {id: number; kind: 'workbench.bus.value'; value: unknown}\n\n// Mirrors the SDK's MessageBusError: importing the class would pull the SDK\n// runtime into the worker bundle.\nconst busError = (code: MessageBusErrorCode, message?: string): Error =>\n Object.assign(new Error(message || code), {code, name: 'MessageBusError'})\n\n/**\n * The worker's side of the `workbench.bus.*` wire contract. The host relays\n * each request to the Dashboard bus and stamps it with the worker's identity,\n * so the client only tracks ids.\n * @internal\n */\nexport function createWorkerBus(): {\n /**\n * The service author's API. The host owns the connection, opening it and ending it when\n * it terminates the worker, so the worker cannot end it.\n */\n bus: ServiceBus\n /**\n * The generated entry's terminate hook, not the author's. It sends nothing to\n * the host, which has already disconnected; it only marks the client closed so\n * the disposer's bus calls reject `ABORTED` at once instead of waiting out the\n * local timeout. Hence not `disconnect`.\n */\n close: () => void\n /**\n * The generated `worker.js` is the single `message` listener on `self` and\n * routes every kind (terminate to the disposer, `workbench.bus.*` here), the\n * way the host's `runWorker` routes to its relay.\n */\n receive: (data: unknown) => void\n} {\n const pending = new Map<number, (outcome: Outcome) => void>()\n const subscriptions = new Map<number, (value: unknown) => void>()\n let nextId = 0\n let closed = false\n\n // Posts a request and returns a function that creates its promise on first\n // call. Until then a reply, even an error, is only held: a rejected promise\n // nobody awaits would reach the worker's 'unhandledrejection' forwarder as a crash.\n function request(message: Record<string, unknown>, options: RequestOptions = {}) {\n const {signal, timeout} = options\n const id = ++nextId\n let outcome: Outcome | undefined\n let onOutcome: ((result: Outcome) => void) | undefined\n let timer: ReturnType<typeof setTimeout> | undefined\n\n const settle = (result: Outcome) => {\n if (outcome) return\n outcome = result\n clearTimeout(timer)\n pending.delete(id)\n signal?.removeEventListener('abort', onAbort)\n onOutcome?.(result)\n }\n const onAbort = () => {\n self.postMessage({id, kind: 'workbench.bus.abort'})\n settle({error: busError('ABORTED'), ok: false})\n }\n\n if (closed || signal?.aborted) {\n outcome = {error: busError('ABORTED'), ok: false}\n } else {\n // An omitted timeout must stay absent on the wire, so the host applies its default.\n self.postMessage(timeout === undefined ? {...message, id} : {...message, id, timeout})\n pending.set(id, settle)\n // A host that predates the bus never replies; time out here too so the call still settles.\n if (timeout !== null) {\n timer = setTimeout(\n () => settle({error: busError('TIMEOUT'), ok: false}),\n timeout ?? DEFAULT_TIMEOUT_MS,\n )\n }\n signal?.addEventListener('abort', onAbort, {once: true})\n }\n\n let promise: Promise<unknown> | undefined\n return () =>\n (promise ??= new Promise((resolve, reject) => {\n onOutcome = (result) => (result.ok ? resolve(result.value) : reject(result.error))\n if (outcome) onOutcome(outcome)\n }))\n }\n\n const bus = {\n emit: (topic: string, payload?: unknown, options?: RequestOptions) => {\n const awaitReply = request({kind: 'workbench.bus.emit', payload, topic}, options)\n const result: MessageBusEmitResult<unknown> = {\n catch: (onRejected) => awaitReply().then(undefined, onRejected),\n finally: (onFinally) => awaitReply().finally(onFinally),\n // eslint-disable-next-line unicorn/no-thenable -- awaiting arms reply failure handling; fire-and-forget does not.\n then: (onFulfilled, onRejected) => awaitReply().then(onFulfilled, onRejected),\n }\n return result\n },\n query: (topic: string, options?: RequestOptions) =>\n request({kind: 'workbench.bus.query', topic}, options)(),\n subscribe: (topic: string, handler: (value: unknown) => void, options?: RequestOptions) => {\n if (closed) throw busError('ABORTED')\n const signal = options?.signal\n if (signal?.aborted) return\n const id = ++nextId\n self.postMessage({id, kind: 'workbench.bus.subscribe', topic})\n subscriptions.set(id, handler)\n signal?.addEventListener(\n 'abort',\n () => {\n if (subscriptions.delete(id)) self.postMessage({id, kind: 'workbench.bus.abort'})\n },\n {once: true},\n )\n },\n }\n\n return {\n // The topic generics only exist at the call site; the wire carries plain strings.\n bus: bus as unknown as ServiceBus,\n close: () => {\n closed = true\n subscriptions.clear()\n for (const settle of pending.values()) settle({error: busError('ABORTED'), ok: false})\n },\n receive: (data) => {\n const message = data as HostMessage\n if (message.kind === 'workbench.bus.value') {\n subscriptions.get(message.id)?.(message.value)\n } else if (message.kind === 'workbench.bus.reply') {\n const settle = pending.get(message.id)\n if (message.ok) {\n settle?.({ok: true, value: message.value})\n return\n }\n // A refused subscription has no promise to reject, so tell the author through the host logger.\n if (subscriptions.delete(message.id)) {\n // eslint-disable-next-line no-console -- the worker's console is bridged to the host logger\n console.error(\n `Message bus subscription refused: ${message.error.code}: ${message.error.message}`,\n )\n }\n settle?.({error: busError(message.error.code, message.error.message), ok: false})\n }\n },\n }\n}\n"],"names":["DEFAULT_TIMEOUT_MS","busError","code","message","Object","assign","Error","name","createWorkerBus","pending","Map","subscriptions","nextId","closed","request","options","signal","timeout","id","outcome","onOutcome","timer","settle","result","clearTimeout","delete","removeEventListener","onAbort","self","postMessage","kind","error","ok","aborted","undefined","set","setTimeout","addEventListener","once","promise","Promise","resolve","reject","value","bus","emit","topic","payload","awaitReply","catch","onRejected","then","finally","onFinally","onFulfilled","query","subscribe","handler","close","clear","values","receive","data","get","console"],"mappings":"AAAA,2EAA2E;AAC3E,6EAA6E;AAC7E,gCAAgC;AAKhC,MAAMA,qBAAqB;AAmB3B,4EAA4E;AAC5E,kCAAkC;AAClC,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IAAI;YAAK;QACtF;QACA6B,SAAS,CAACC;YACR,MAAM3D,UAAU2D;YAChB,IAAI3D,QAAQ2B,IAAI,KAAK,uBAAuB;gBAC1CnB,cAAcoD,GAAG,CAAC5D,QAAQe,EAAE,IAAIf,QAAQwC,KAAK;YAC/C,OAAO,IAAIxC,QAAQ2B,IAAI,KAAK,uBAAuB;gBACjD,MAAMR,SAASb,QAAQsD,GAAG,CAAC5D,QAAQe,EAAE;gBACrC,IAAIf,QAAQ6B,EAAE,EAAE;oBACdV,SAAS;wBAACU,IAAI;wBAAMW,OAAOxC,QAAQwC,KAAK;oBAAA;oBACxC;gBACF;gBACA,+FAA+F;gBAC/F,IAAIhC,cAAcc,MAAM,CAACtB,QAAQe,EAAE,GAAG;oBACpC,4FAA4F;oBAC5F8C,QAAQjC,KAAK,CACX,CAAC,kCAAkC,EAAE5B,QAAQ4B,KAAK,CAAC7B,IAAI,CAAC,EAAE,EAAEC,QAAQ4B,KAAK,CAAC5B,OAAO,EAAE;gBAEvF;gBACAmB,SAAS;oBAACS,OAAO9B,SAASE,QAAQ4B,KAAK,CAAC7B,IAAI,EAAEC,QAAQ4B,KAAK,CAAC5B,OAAO;oBAAG6B,IAAI;gBAAK;YACjF;QACF;IACF;AACF"}
@@ -1,7 +1,10 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { WORKER_BUS_ENTRY } from '../../services/artifact.js';
3
5
  import { RUNTIME_DIR } from '../constants.js';
4
6
  import { getFederationApi } from './plugin-module-federation.js';
7
+ const workerBusPath = fileURLToPath(new URL('../../../../_exports/_internal_worker_bus.js', import.meta.url));
5
8
  function relativeImport(fromFile, toFile) {
6
9
  const rel = path.relative(path.dirname(fromFile), toFile).split(path.sep).join('/');
7
10
  return rel.startsWith('.') ? rel : `./${rel}`;
@@ -25,6 +28,20 @@ function writeArtifacts({ artifacts, isolateStyles, root }) {
25
28
  * `workbenchArtifacts` and handed in — this plugin only writes it.
26
29
  */ export function sanityExtensionArtifacts(options) {
27
30
  return {
31
+ // The generated worker.js imports the bus client from this package, which
32
+ // the app has no dependency on and so can't resolve by name.
33
+ config: ()=>({
34
+ optimizeDeps: {
35
+ exclude: [
36
+ WORKER_BUS_ENTRY
37
+ ]
38
+ },
39
+ resolve: {
40
+ alias: {
41
+ [WORKER_BUS_ENTRY]: workerBusPath
42
+ }
43
+ }
44
+ }),
28
45
  configResolved (config) {
29
46
  writeArtifacts({
30
47
  artifacts: options.artifacts,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../src/actions/build/vite/plugins/plugin-sanity-extension-artifacts.ts"],"sourcesContent":["import fs from 'node:fs'\nimport path from 'node:path'\n\nimport {type Plugin} from 'vite'\n\nimport {type GeneratedArtifact} from '../../artifact.js'\nimport {RUNTIME_DIR} from '../constants.js'\nimport {getFederationApi} from './plugin-module-federation.js'\n\nfunction relativeImport(fromFile: string, toFile: string): string {\n const rel = path.relative(path.dirname(fromFile), toFile).split(path.sep).join('/')\n return rel.startsWith('.') ? rel : `./${rel}`\n}\n\nfunction writeArtifacts({\n artifacts,\n isolateStyles,\n root,\n}: {\n artifacts: readonly GeneratedArtifact[]\n isolateStyles: boolean\n root: string\n}): void {\n for (const artifact of artifacts) {\n const artifactPath = path.resolve(root, RUNTIME_DIR, artifact.path)\n fs.mkdirSync(path.dirname(artifactPath), {recursive: true})\n fs.writeFileSync(\n artifactPath,\n artifact.source({\n isolateStyles,\n resolveImport: (src) => relativeImport(artifactPath, path.resolve(root, src)),\n }),\n )\n }\n}\n\n/**\n * Writes the federation runtime artifacts (view render-contract modules, service\n * worker bundles + loaders) into `RUNTIME_DIR`, resolving each artifact's import\n * paths relative to where it lands on disk. The set is expanded once by\n * `workbenchArtifacts` and handed in — this plugin only writes it.\n */\nexport function sanityExtensionArtifacts(options: {\n artifacts: readonly GeneratedArtifact[]\n}): Plugin {\n return {\n configResolved(config) {\n writeArtifacts({\n artifacts: options.artifacts,\n isolateStyles: getFederationApi(config.plugins)?.isolateStyles ?? false,\n root: config.root,\n })\n },\n name: 'sanity/extension-artifacts',\n }\n}\n"],"names":["fs","path","RUNTIME_DIR","getFederationApi","relativeImport","fromFile","toFile","rel","relative","dirname","split","sep","join","startsWith","writeArtifacts","artifacts","isolateStyles","root","artifact","artifactPath","resolve","mkdirSync","recursive","writeFileSync","source","resolveImport","src","sanityExtensionArtifacts","options","configResolved","config","plugins","name"],"mappings":"AAAA,OAAOA,QAAQ,UAAS;AACxB,OAAOC,UAAU,YAAW;AAK5B,SAAQC,WAAW,QAAO,kBAAiB;AAC3C,SAAQC,gBAAgB,QAAO,gCAA+B;AAE9D,SAASC,eAAeC,QAAgB,EAAEC,MAAc;IACtD,MAAMC,MAAMN,KAAKO,QAAQ,CAACP,KAAKQ,OAAO,CAACJ,WAAWC,QAAQI,KAAK,CAACT,KAAKU,GAAG,EAAEC,IAAI,CAAC;IAC/E,OAAOL,IAAIM,UAAU,CAAC,OAAON,MAAM,CAAC,EAAE,EAAEA,KAAK;AAC/C;AAEA,SAASO,eAAe,EACtBC,SAAS,EACTC,aAAa,EACbC,IAAI,EAKL;IACC,KAAK,MAAMC,YAAYH,UAAW;QAChC,MAAMI,eAAelB,KAAKmB,OAAO,CAACH,MAAMf,aAAagB,SAASjB,IAAI;QAClED,GAAGqB,SAAS,CAACpB,KAAKQ,OAAO,CAACU,eAAe;YAACG,WAAW;QAAI;QACzDtB,GAAGuB,aAAa,CACdJ,cACAD,SAASM,MAAM,CAAC;YACdR;YACAS,eAAe,CAACC,MAAQtB,eAAee,cAAclB,KAAKmB,OAAO,CAACH,MAAMS;QAC1E;IAEJ;AACF;AAEA;;;;;CAKC,GACD,OAAO,SAASC,yBAAyBC,OAExC;IACC,OAAO;QACLC,gBAAeC,MAAM;YACnBhB,eAAe;gBACbC,WAAWa,QAAQb,SAAS;gBAC5BC,eAAeb,iBAAiB2B,OAAOC,OAAO,GAAGf,iBAAiB;gBAClEC,MAAMa,OAAOb,IAAI;YACnB;QACF;QACAe,MAAM;IACR;AACF"}
1
+ {"version":3,"sources":["../../../../../src/actions/build/vite/plugins/plugin-sanity-extension-artifacts.ts"],"sourcesContent":["import fs from 'node:fs'\nimport path from 'node:path'\nimport {fileURLToPath} from 'node:url'\n\nimport {type Plugin} from 'vite'\n\nimport {type GeneratedArtifact} from '../../artifact.js'\nimport {WORKER_BUS_ENTRY} from '../../services/artifact.js'\nimport {RUNTIME_DIR} from '../constants.js'\nimport {getFederationApi} from './plugin-module-federation.js'\n\nconst workerBusPath = fileURLToPath(\n new URL('../../../../_exports/_internal_worker_bus.js', import.meta.url),\n)\n\nfunction relativeImport(fromFile: string, toFile: string): string {\n const rel = path.relative(path.dirname(fromFile), toFile).split(path.sep).join('/')\n return rel.startsWith('.') ? rel : `./${rel}`\n}\n\nfunction writeArtifacts({\n artifacts,\n isolateStyles,\n root,\n}: {\n artifacts: readonly GeneratedArtifact[]\n isolateStyles: boolean\n root: string\n}): void {\n for (const artifact of artifacts) {\n const artifactPath = path.resolve(root, RUNTIME_DIR, artifact.path)\n fs.mkdirSync(path.dirname(artifactPath), {recursive: true})\n fs.writeFileSync(\n artifactPath,\n artifact.source({\n isolateStyles,\n resolveImport: (src) => relativeImport(artifactPath, path.resolve(root, src)),\n }),\n )\n }\n}\n\n/**\n * Writes the federation runtime artifacts (view render-contract modules, service\n * worker bundles + loaders) into `RUNTIME_DIR`, resolving each artifact's import\n * paths relative to where it lands on disk. The set is expanded once by\n * `workbenchArtifacts` and handed in — this plugin only writes it.\n */\nexport function sanityExtensionArtifacts(options: {\n artifacts: readonly GeneratedArtifact[]\n}): Plugin {\n return {\n // The generated worker.js imports the bus client from this package, which\n // the app has no dependency on and so can't resolve by name.\n config: () => ({\n optimizeDeps: {exclude: [WORKER_BUS_ENTRY]},\n resolve: {alias: {[WORKER_BUS_ENTRY]: workerBusPath}},\n }),\n configResolved(config) {\n writeArtifacts({\n artifacts: options.artifacts,\n isolateStyles: getFederationApi(config.plugins)?.isolateStyles ?? false,\n root: config.root,\n })\n },\n name: 'sanity/extension-artifacts',\n }\n}\n"],"names":["fs","path","fileURLToPath","WORKER_BUS_ENTRY","RUNTIME_DIR","getFederationApi","workerBusPath","URL","url","relativeImport","fromFile","toFile","rel","relative","dirname","split","sep","join","startsWith","writeArtifacts","artifacts","isolateStyles","root","artifact","artifactPath","resolve","mkdirSync","recursive","writeFileSync","source","resolveImport","src","sanityExtensionArtifacts","options","config","optimizeDeps","exclude","alias","configResolved","plugins","name"],"mappings":"AAAA,OAAOA,QAAQ,UAAS;AACxB,OAAOC,UAAU,YAAW;AAC5B,SAAQC,aAAa,QAAO,WAAU;AAKtC,SAAQC,gBAAgB,QAAO,6BAA4B;AAC3D,SAAQC,WAAW,QAAO,kBAAiB;AAC3C,SAAQC,gBAAgB,QAAO,gCAA+B;AAE9D,MAAMC,gBAAgBJ,cACpB,IAAIK,IAAI,gDAAgD,YAAYC,GAAG;AAGzE,SAASC,eAAeC,QAAgB,EAAEC,MAAc;IACtD,MAAMC,MAAMX,KAAKY,QAAQ,CAACZ,KAAKa,OAAO,CAACJ,WAAWC,QAAQI,KAAK,CAACd,KAAKe,GAAG,EAAEC,IAAI,CAAC;IAC/E,OAAOL,IAAIM,UAAU,CAAC,OAAON,MAAM,CAAC,EAAE,EAAEA,KAAK;AAC/C;AAEA,SAASO,eAAe,EACtBC,SAAS,EACTC,aAAa,EACbC,IAAI,EAKL;IACC,KAAK,MAAMC,YAAYH,UAAW;QAChC,MAAMI,eAAevB,KAAKwB,OAAO,CAACH,MAAMlB,aAAamB,SAAStB,IAAI;QAClED,GAAG0B,SAAS,CAACzB,KAAKa,OAAO,CAACU,eAAe;YAACG,WAAW;QAAI;QACzD3B,GAAG4B,aAAa,CACdJ,cACAD,SAASM,MAAM,CAAC;YACdR;YACAS,eAAe,CAACC,MAAQtB,eAAee,cAAcvB,KAAKwB,OAAO,CAACH,MAAMS;QAC1E;IAEJ;AACF;AAEA;;;;;CAKC,GACD,OAAO,SAASC,yBAAyBC,OAExC;IACC,OAAO;QACL,0EAA0E;QAC1E,6DAA6D;QAC7DC,QAAQ,IAAO,CAAA;gBACbC,cAAc;oBAACC,SAAS;wBAACjC;qBAAiB;gBAAA;gBAC1CsB,SAAS;oBAACY,OAAO;wBAAC,CAAClC,iBAAiB,EAAEG;oBAAa;gBAAC;YACtD,CAAA;QACAgC,gBAAeJ,MAAM;YACnBf,eAAe;gBACbC,WAAWa,QAAQb,SAAS;gBAC5BC,eAAehB,iBAAiB6B,OAAOK,OAAO,GAAGlB,iBAAiB;gBAClEC,MAAMY,OAAOZ,IAAI;YACnB;QACF;QACAkB,MAAM;IACR;AACF"}
@@ -1,4 +1,4 @@
1
- import { stat } from 'node:fs/promises';
1
+ import { readFile, stat } from 'node:fs/promises';
2
2
  import { join } from 'node:path';
3
3
  /**
4
4
  * A genuinely-missing-build error, named so callers can offer the "run sanity
@@ -27,14 +27,22 @@ import { join } from 'node:path';
27
27
  throw err;
28
28
  }
29
29
  const manifestPath = join(sourceDir, 'mf-manifest.json');
30
+ let manifest;
30
31
  try {
31
- await stat(manifestPath);
32
+ manifest = await readFile(manifestPath, 'utf8');
32
33
  } catch (err) {
33
34
  if (err.code === 'ENOENT') {
34
35
  throw buildNotFound(`"${manifestPath}" does not exist. ` + 'The deploy directory must contain a federation build created with "sanity build".');
35
36
  }
36
37
  throw err;
37
38
  }
39
+ // Every deploy sends this file to the API, so a corrupt one must fail here
40
+ // rather than after the application is created.
41
+ try {
42
+ JSON.parse(manifest);
43
+ } catch {
44
+ throw new Error(`"${manifestPath}" is not valid JSON. Run "sanity build" again to regenerate it.`);
45
+ }
38
46
  }
39
47
 
40
48
  //# sourceMappingURL=checkBuiltOutput.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/actions/deploy/checkBuiltOutput.ts"],"sourcesContent":["import {stat} from 'node:fs/promises'\nimport {join} from 'node:path'\n\n/**\n * A genuinely-missing-build error, named so callers can offer the \"run sanity\n * build\" hint (the `preview` command keys off this name, matching how the studio\n * path keys off a missing `index.html`). Only the missing cases get it — real\n * I/O failures keep their own name so they surface as themselves.\n */\nfunction buildNotFound(message: string): Error {\n const error = new Error(message)\n error.name = 'BUILD_NOT_FOUND'\n return error\n}\n\n/**\n * Throws unless `sourceDir` is a directory holding a federation build.\n * A workbench build always emits a module-federation remote, and may\n * additionally emit a standalone `index.html` SPA (workbench remotes). Either\n * way `mf-manifest.json` is the reliable marker that `sanity build` produced a\n * federation build, so that — not `index.html` — is what we check for.\n */\nexport async function checkBuiltOutput(sourceDir: string): Promise<void> {\n try {\n const stats = await stat(sourceDir)\n if (!stats.isDirectory()) {\n throw new Error(`\"${sourceDir}\" is not a directory`)\n }\n } catch (err) {\n if (err.code === 'ENOENT') throw buildNotFound(`Directory \"${sourceDir}\" does not exist`)\n throw err\n }\n\n const manifestPath = join(sourceDir, 'mf-manifest.json')\n try {\n await stat(manifestPath)\n } catch (err) {\n if (err.code === 'ENOENT') {\n throw buildNotFound(\n `\"${manifestPath}\" does not exist. ` +\n 'The deploy directory must contain a federation build created with \"sanity build\".',\n )\n }\n throw err\n }\n}\n"],"names":["stat","join","buildNotFound","message","error","Error","name","checkBuiltOutput","sourceDir","stats","isDirectory","err","code","manifestPath"],"mappings":"AAAA,SAAQA,IAAI,QAAO,mBAAkB;AACrC,SAAQC,IAAI,QAAO,YAAW;AAE9B;;;;;CAKC,GACD,SAASC,cAAcC,OAAe;IACpC,MAAMC,QAAQ,IAAIC,MAAMF;IACxBC,MAAME,IAAI,GAAG;IACb,OAAOF;AACT;AAEA;;;;;;CAMC,GACD,OAAO,eAAeG,iBAAiBC,SAAiB;IACtD,IAAI;QACF,MAAMC,QAAQ,MAAMT,KAAKQ;QACzB,IAAI,CAACC,MAAMC,WAAW,IAAI;YACxB,MAAM,IAAIL,MAAM,CAAC,CAAC,EAAEG,UAAU,oBAAoB,CAAC;QACrD;IACF,EAAE,OAAOG,KAAK;QACZ,IAAIA,IAAIC,IAAI,KAAK,UAAU,MAAMV,cAAc,CAAC,WAAW,EAAEM,UAAU,gBAAgB,CAAC;QACxF,MAAMG;IACR;IAEA,MAAME,eAAeZ,KAAKO,WAAW;IACrC,IAAI;QACF,MAAMR,KAAKa;IACb,EAAE,OAAOF,KAAK;QACZ,IAAIA,IAAIC,IAAI,KAAK,UAAU;YACzB,MAAMV,cACJ,CAAC,CAAC,EAAEW,aAAa,kBAAkB,CAAC,GAClC;QAEN;QACA,MAAMF;IACR;AACF"}
1
+ {"version":3,"sources":["../../../src/actions/deploy/checkBuiltOutput.ts"],"sourcesContent":["import {readFile, stat} from 'node:fs/promises'\nimport {join} from 'node:path'\n\n/**\n * A genuinely-missing-build error, named so callers can offer the \"run sanity\n * build\" hint (the `preview` command keys off this name, matching how the studio\n * path keys off a missing `index.html`). Only the missing cases get it — real\n * I/O failures keep their own name so they surface as themselves.\n */\nfunction buildNotFound(message: string): Error {\n const error = new Error(message)\n error.name = 'BUILD_NOT_FOUND'\n return error\n}\n\n/**\n * Throws unless `sourceDir` is a directory holding a federation build.\n * A workbench build always emits a module-federation remote, and may\n * additionally emit a standalone `index.html` SPA (workbench remotes). Either\n * way `mf-manifest.json` is the reliable marker that `sanity build` produced a\n * federation build, so that — not `index.html` — is what we check for.\n */\nexport async function checkBuiltOutput(sourceDir: string): Promise<void> {\n try {\n const stats = await stat(sourceDir)\n if (!stats.isDirectory()) {\n throw new Error(`\"${sourceDir}\" is not a directory`)\n }\n } catch (err) {\n if (err.code === 'ENOENT') throw buildNotFound(`Directory \"${sourceDir}\" does not exist`)\n throw err\n }\n\n const manifestPath = join(sourceDir, 'mf-manifest.json')\n let manifest: string\n try {\n manifest = await readFile(manifestPath, 'utf8')\n } catch (err) {\n if (err.code === 'ENOENT') {\n throw buildNotFound(\n `\"${manifestPath}\" does not exist. ` +\n 'The deploy directory must contain a federation build created with \"sanity build\".',\n )\n }\n throw err\n }\n\n // Every deploy sends this file to the API, so a corrupt one must fail here\n // rather than after the application is created.\n try {\n JSON.parse(manifest)\n } catch {\n throw new Error(\n `\"${manifestPath}\" is not valid JSON. Run \"sanity build\" again to regenerate it.`,\n )\n }\n}\n"],"names":["readFile","stat","join","buildNotFound","message","error","Error","name","checkBuiltOutput","sourceDir","stats","isDirectory","err","code","manifestPath","manifest","JSON","parse"],"mappings":"AAAA,SAAQA,QAAQ,EAAEC,IAAI,QAAO,mBAAkB;AAC/C,SAAQC,IAAI,QAAO,YAAW;AAE9B;;;;;CAKC,GACD,SAASC,cAAcC,OAAe;IACpC,MAAMC,QAAQ,IAAIC,MAAMF;IACxBC,MAAME,IAAI,GAAG;IACb,OAAOF;AACT;AAEA;;;;;;CAMC,GACD,OAAO,eAAeG,iBAAiBC,SAAiB;IACtD,IAAI;QACF,MAAMC,QAAQ,MAAMT,KAAKQ;QACzB,IAAI,CAACC,MAAMC,WAAW,IAAI;YACxB,MAAM,IAAIL,MAAM,CAAC,CAAC,EAAEG,UAAU,oBAAoB,CAAC;QACrD;IACF,EAAE,OAAOG,KAAK;QACZ,IAAIA,IAAIC,IAAI,KAAK,UAAU,MAAMV,cAAc,CAAC,WAAW,EAAEM,UAAU,gBAAgB,CAAC;QACxF,MAAMG;IACR;IAEA,MAAME,eAAeZ,KAAKO,WAAW;IACrC,IAAIM;IACJ,IAAI;QACFA,WAAW,MAAMf,SAASc,cAAc;IAC1C,EAAE,OAAOF,KAAK;QACZ,IAAIA,IAAIC,IAAI,KAAK,UAAU;YACzB,MAAMV,cACJ,CAAC,CAAC,EAAEW,aAAa,kBAAkB,CAAC,GAClC;QAEN;QACA,MAAMF;IACR;IAEA,2EAA2E;IAC3E,gDAAgD;IAChD,IAAI;QACFI,KAAKC,KAAK,CAACF;IACb,EAAE,OAAM;QACN,MAAM,IAAIT,MACR,CAAC,CAAC,EAAEQ,aAAa,+DAA+D,CAAC;IAErF;AACF"}
@@ -1,4 +1,5 @@
1
- import { basename, dirname } from 'node:path';
1
+ import { readFile } from 'node:fs/promises';
2
+ import { basename, dirname, join } from 'node:path';
2
3
  import { createGzip } from 'node:zlib';
3
4
  import { getErrorMessage } from '@sanity/cli-core/errors';
4
5
  import { spinner } from '@sanity/cli-core/ux';
@@ -100,10 +101,15 @@ function toBrettInterface(iface, version) {
100
101
  * `onDeployed` fires the instant the deployment is live, before the metadata
101
102
  * sync — so a caller can disarm a create-time rollback that must not delete an
102
103
  * application once it has an active deployment.
104
+ *
105
+ * The build's `mf-manifest.json` ships with every deployment. `isExternal`
106
+ * skips the tarball: the customer serves the build from the application's
107
+ * registered origin.
103
108
  * @internal
104
109
  */ export async function deployWorkbenchApp(options) {
105
- const { access, app, applicationId, icon, isApp, isAutoUpdating, label = 'Deploying...', onDeployed, slug, sourceDir, title, version, visibility, workspaces } = options;
106
- const tarball = createTar({
110
+ const { access, app, applicationId, icon, isApp, isAutoUpdating, isExternal = false, label = 'Deploying...', onDeployed, slug, sourceDir, title, version, visibility, workspaces } = options;
111
+ const mfManifest = JSON.parse(await readFile(join(sourceDir, 'mf-manifest.json'), 'utf8'));
112
+ const tarball = isExternal ? undefined : createTar({
107
113
  cwd: dirname(sourceDir)
108
114
  }, [
109
115
  basename(sourceDir)
@@ -119,6 +125,7 @@ function toBrettInterface(iface, version) {
119
125
  isApp
120
126
  }).map((iface)=>toBrettInterface(iface, version)),
121
127
  isAutoUpdating,
128
+ mfManifest,
122
129
  tarball,
123
130
  version,
124
131
  workspaces
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/actions/deploy/deployWorkbenchApp.ts"],"sourcesContent":["import {basename, dirname} from 'node:path'\nimport {createGzip} from 'node:zlib'\n\nimport {type AppVisibility, type CliConfig} from '@sanity/cli-core'\nimport {getErrorMessage} from '@sanity/cli-core/errors'\nimport {spinner} from '@sanity/cli-core/ux'\nimport {c as createTar} from 'tar'\n\nimport {type DerivedInterface, deriveInterfaces} from '../../deriveInterfaces.js'\nimport {\n type Application,\n type BrettAccess,\n type BrettInterface,\n type BrettWorkspace,\n createApplication,\n createDeployment,\n deleteApplication,\n updateApplication,\n} from '../../services/applications.js'\n\n/**\n * `rollback` undoes the creation, so a later failure leaves no record stranded at the slug.\n * @internal\n */\nexport interface CreatedApplication {\n application: Application\n rollback: () => Promise<void>\n}\n\nfunction toBrettInterface(iface: DerivedInterface, version: string): BrettInterface {\n const {id: _id, src: _src, ...declaration} = iface\n if ('type' in declaration) return {...declaration, version}\n\n switch (declaration.surface) {\n case 'asset_source': {\n const {surface, ...view} = declaration\n return {...view, type: surface, version}\n }\n case 'panel': {\n const {surface, ...view} = declaration\n return {...view, type: surface, version}\n }\n case 'tile': {\n const {surface, ...view} = declaration\n return {...view, type: surface, version}\n }\n case 'window': {\n const {surface, ...view} = declaration\n return {...view, type: 'app', version}\n }\n }\n}\n\n/**\n * Create a coreApp record (no deployment), so the CLI can build with its id\n * before shipping the first deployment. First deploy only.\n * @internal\n */\nexport async function createCoreApp(options: {\n isSingleton?: boolean\n name?: string\n organizationId: string\n slug: string\n title: string\n visibility?: AppVisibility\n}): Promise<CreatedApplication> {\n const spin = spinner('Creating application...').start()\n try {\n const application = await createApplication({...options, type: 'coreApp'})\n spin.succeed()\n return {application, rollback: () => deleteApplication(application.id)}\n } catch (error) {\n spin.fail()\n throw error\n }\n}\n\n/**\n * Create a studio record (no deployment).\n * @internal\n */\nexport async function createStudio(options: {\n name?: string\n organizationId: string\n projectId: string | undefined\n slug: string\n title: string\n visibility?: AppVisibility\n}): Promise<CreatedApplication> {\n const spin = spinner('Creating studio...').start()\n try {\n const application = await createApplication({...options, type: 'studio'})\n spin.succeed()\n return {application, rollback: () => deleteApplication(application.id)}\n } catch (error) {\n spin.fail()\n throw error\n }\n}\n\n/**\n * Ship a deployment to an already-created (or `deployment.appId`) application,\n * then sync its mutable metadata (`title`, and `icon`/`slug`/`visibility` when\n * set) from config. The deploy endpoint ignores these, so a redeploy patches\n * them here alongside the new deployment.\n *\n * `onDeployed` fires the instant the deployment is live, before the metadata\n * sync — so a caller can disarm a create-time rollback that must not delete an\n * application once it has an active deployment.\n * @internal\n */\nexport async function deployWorkbenchApp(options: {\n access?: readonly BrettAccess[]\n app: CliConfig['app']\n applicationId: string\n icon?: string\n isApp: boolean\n isAutoUpdating: boolean\n label?: string\n onDeployed?: () => void\n /**\n * The address from config. Only `createApplication` used to send it, so an\n * app with a `deployment.appId` kept whatever slug it was created at.\n */\n slug?: string\n sourceDir: string\n title: string\n version: string\n visibility?: AppVisibility\n workspaces?: readonly BrettWorkspace[]\n}): Promise<void> {\n const {\n access,\n app,\n applicationId,\n icon,\n isApp,\n isAutoUpdating,\n label = 'Deploying...',\n onDeployed,\n slug,\n sourceDir,\n title,\n version,\n visibility,\n workspaces,\n } = options\n const tarball = createTar({cwd: dirname(sourceDir)}, [basename(sourceDir)]).pipe(createGzip())\n\n const spin = spinner(label).start()\n try {\n await createDeployment({\n access,\n applicationId,\n // Brett assigns the id and resolves modules by `moduleId`, so neither travels.\n interfaces: deriveInterfaces(app, {appTitle: title, isApp}).map((iface) =>\n toBrettInterface(iface, version),\n ),\n isAutoUpdating,\n tarball,\n version,\n workspaces,\n })\n onDeployed?.()\n try {\n await updateApplication(applicationId, {\n title,\n ...(icon ? {icon} : {}),\n ...(slug ? {slug} : {}),\n ...(visibility ? {visibility} : {}),\n })\n } catch (error) {\n throw toSlugRejection(error, slug)\n }\n spin.succeed()\n } catch (error) {\n spin.clear()\n throw error\n }\n}\n\n/**\n * The slug is the one synced field the server validates — it must be free\n * within the organization, and a singleton app only accepts its reserved\n * identifiers — so a 4xx on the metadata patch is a rejected rename. Name the\n * slug and the server's reason; anything else propagates untouched.\n */\nfunction toSlugRejection(error: unknown, slug: string | undefined): unknown {\n const statusCode = (error as {statusCode?: number})?.statusCode\n if (!slug || statusCode === undefined || statusCode < 400 || statusCode >= 500) return error\n return new Error(\n `Slug \"${slug}\" was rejected: ${getErrorMessage(error)}. The deployment is live at the application's previous slug — change \\`app.slug\\` in sanity.cli.ts and deploy again.`,\n {cause: error},\n )\n}\n"],"names":["basename","dirname","createGzip","getErrorMessage","spinner","c","createTar","deriveInterfaces","createApplication","createDeployment","deleteApplication","updateApplication","toBrettInterface","iface","version","id","_id","src","_src","declaration","surface","view","type","createCoreApp","options","spin","start","application","succeed","rollback","error","fail","createStudio","deployWorkbenchApp","access","app","applicationId","icon","isApp","isAutoUpdating","label","onDeployed","slug","sourceDir","title","visibility","workspaces","tarball","cwd","pipe","interfaces","appTitle","map","toSlugRejection","clear","statusCode","undefined","Error","cause"],"mappings":"AAAA,SAAQA,QAAQ,EAAEC,OAAO,QAAO,YAAW;AAC3C,SAAQC,UAAU,QAAO,YAAW;AAGpC,SAAQC,eAAe,QAAO,0BAAyB;AACvD,SAAQC,OAAO,QAAO,sBAAqB;AAC3C,SAAQC,KAAKC,SAAS,QAAO,MAAK;AAElC,SAA+BC,gBAAgB,QAAO,4BAA2B;AACjF,SAKEC,iBAAiB,EACjBC,gBAAgB,EAChBC,iBAAiB,EACjBC,iBAAiB,QACZ,iCAAgC;AAWvC,SAASC,iBAAiBC,KAAuB,EAAEC,OAAe;IAChE,MAAM,EAACC,IAAIC,GAAG,EAAEC,KAAKC,IAAI,EAAE,GAAGC,aAAY,GAAGN;IAC7C,IAAI,UAAUM,aAAa,OAAO;QAAC,GAAGA,WAAW;QAAEL;IAAO;IAE1D,OAAQK,YAAYC,OAAO;QACzB,KAAK;YAAgB;gBACnB,MAAM,EAACA,OAAO,EAAE,GAAGC,MAAK,GAAGF;gBAC3B,OAAO;oBAAC,GAAGE,IAAI;oBAAEC,MAAMF;oBAASN;gBAAO;YACzC;QACA,KAAK;YAAS;gBACZ,MAAM,EAACM,OAAO,EAAE,GAAGC,MAAK,GAAGF;gBAC3B,OAAO;oBAAC,GAAGE,IAAI;oBAAEC,MAAMF;oBAASN;gBAAO;YACzC;QACA,KAAK;YAAQ;gBACX,MAAM,EAACM,OAAO,EAAE,GAAGC,MAAK,GAAGF;gBAC3B,OAAO;oBAAC,GAAGE,IAAI;oBAAEC,MAAMF;oBAASN;gBAAO;YACzC;QACA,KAAK;YAAU;gBACb,MAAM,EAACM,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iBAAiB;YACrByB;YACAE;YACA,+EAA+E;YAC/Ec,YAAY3C,iBAAiB4B,KAAK;gBAACgB,UAAUP;gBAAON;YAAK,GAAGc,GAAG,CAAC,CAACvC,QAC/DD,iBAAiBC,OAAOC;YAE1ByB;YACAQ;YACAjC;YACAgC;QACF;QACAL;QACA,IAAI;YACF,MAAM9B,kBAAkByB,eAAe;gBACrCQ;gBACA,GAAIP,OAAO;oBAACA;gBAAI,IAAI,CAAC,CAAC;gBACtB,GAAIK,OAAO;oBAACA;gBAAI,IAAI,CAAC,CAAC;gBACtB,GAAIG,aAAa;oBAACA;gBAAU,IAAI,CAAC,CAAC;YACpC;QACF,EAAE,OAAOf,OAAO;YACd,MAAMuB,gBAAgBvB,OAAOY;QAC/B;QACAjB,KAAKG,OAAO;IACd,EAAE,OAAOE,OAAO;QACdL,KAAK6B,KAAK;QACV,MAAMxB;IACR;AACF;AAEA;;;;;CAKC,GACD,SAASuB,gBAAgBvB,KAAc,EAAEY,IAAwB;IAC/D,MAAMa,aAAczB,OAAiCyB;IACrD,IAAI,CAACb,QAAQa,eAAeC,aAAaD,aAAa,OAAOA,cAAc,KAAK,OAAOzB;IACvF,OAAO,IAAI2B,MACT,CAAC,MAAM,EAAEf,KAAK,gBAAgB,EAAEvC,gBAAgB2B,OAAO,oHAAoH,CAAC,EAC5K;QAAC4B,OAAO5B;IAAK;AAEjB"}
1
+ {"version":3,"sources":["../../../src/actions/deploy/deployWorkbenchApp.ts"],"sourcesContent":["import {readFile} from 'node:fs/promises'\nimport {basename, dirname, join} from 'node:path'\nimport {createGzip} from 'node:zlib'\n\nimport {type AppVisibility, type CliConfig} from '@sanity/cli-core'\nimport {getErrorMessage} from '@sanity/cli-core/errors'\nimport {spinner} from '@sanity/cli-core/ux'\nimport {c as createTar} from 'tar'\n\nimport {type DerivedInterface, deriveInterfaces} from '../../deriveInterfaces.js'\nimport {\n type Application,\n type BrettAccess,\n type BrettInterface,\n type BrettWorkspace,\n createApplication,\n createDeployment,\n deleteApplication,\n updateApplication,\n} from '../../services/applications.js'\n\n/**\n * `rollback` undoes the creation, so a later failure leaves no record stranded at the slug.\n * @internal\n */\nexport interface CreatedApplication {\n application: Application\n rollback: () => Promise<void>\n}\n\nfunction toBrettInterface(iface: DerivedInterface, version: string): BrettInterface {\n const {id: _id, src: _src, ...declaration} = iface\n if ('type' in declaration) return {...declaration, version}\n\n switch (declaration.surface) {\n case 'asset_source': {\n const {surface, ...view} = declaration\n return {...view, type: surface, version}\n }\n case 'panel': {\n const {surface, ...view} = declaration\n return {...view, type: surface, version}\n }\n case 'tile': {\n const {surface, ...view} = declaration\n return {...view, type: surface, version}\n }\n case 'window': {\n const {surface, ...view} = declaration\n return {...view, type: 'app', version}\n }\n }\n}\n\n/**\n * Create a coreApp record (no deployment), so the CLI can build with its id\n * before shipping the first deployment. First deploy only.\n * @internal\n */\nexport async function createCoreApp(options: {\n isSingleton?: boolean\n name?: string\n organizationId: string\n slug: string\n title: string\n visibility?: AppVisibility\n}): Promise<CreatedApplication> {\n const spin = spinner('Creating application...').start()\n try {\n const application = await createApplication({...options, type: 'coreApp'})\n spin.succeed()\n return {application, rollback: () => deleteApplication(application.id)}\n } catch (error) {\n spin.fail()\n throw error\n }\n}\n\n/**\n * Create a studio record (no deployment).\n * @internal\n */\nexport async function createStudio(options: {\n externalUrl?: string\n name?: string\n organizationId: string\n projectId: string | undefined\n slug: string\n title: string\n visibility?: AppVisibility\n}): Promise<CreatedApplication> {\n const spin = spinner('Creating studio...').start()\n try {\n const application = await createApplication({...options, type: 'studio'})\n spin.succeed()\n return {application, rollback: () => deleteApplication(application.id)}\n } catch (error) {\n spin.fail()\n throw error\n }\n}\n\n/**\n * Ship a deployment to an already-created (or `deployment.appId`) application,\n * then sync its mutable metadata (`title`, and `icon`/`slug`/`visibility` when\n * set) from config. The deploy endpoint ignores these, so a redeploy patches\n * them here alongside the new deployment.\n *\n * `onDeployed` fires the instant the deployment is live, before the metadata\n * sync — so a caller can disarm a create-time rollback that must not delete an\n * application once it has an active deployment.\n *\n * The build's `mf-manifest.json` ships with every deployment. `isExternal`\n * skips the tarball: the customer serves the build from the application's\n * registered origin.\n * @internal\n */\nexport async function deployWorkbenchApp(options: {\n access?: readonly BrettAccess[]\n app: CliConfig['app']\n applicationId: string\n icon?: string\n isApp: boolean\n isAutoUpdating: boolean\n isExternal?: boolean\n label?: string\n onDeployed?: () => void\n /**\n * The address from config. Only `createApplication` used to send it, so an\n * app with a `deployment.appId` kept whatever slug it was created at.\n */\n slug?: string\n sourceDir: string\n title: string\n version: string\n visibility?: AppVisibility\n workspaces?: readonly BrettWorkspace[]\n}): Promise<void> {\n const {\n access,\n app,\n applicationId,\n icon,\n isApp,\n isAutoUpdating,\n isExternal = false,\n label = 'Deploying...',\n onDeployed,\n slug,\n sourceDir,\n title,\n version,\n visibility,\n workspaces,\n } = options\n const mfManifest = JSON.parse(await readFile(join(sourceDir, 'mf-manifest.json'), 'utf8'))\n const tarball = isExternal\n ? undefined\n : createTar({cwd: dirname(sourceDir)}, [basename(sourceDir)]).pipe(createGzip())\n\n const spin = spinner(label).start()\n try {\n await createDeployment({\n access,\n applicationId,\n // Brett assigns the id and resolves modules by `moduleId`, so neither travels.\n interfaces: deriveInterfaces(app, {appTitle: title, isApp}).map((iface) =>\n toBrettInterface(iface, version),\n ),\n isAutoUpdating,\n mfManifest,\n tarball,\n version,\n workspaces,\n })\n onDeployed?.()\n try {\n await updateApplication(applicationId, {\n title,\n ...(icon ? {icon} : {}),\n ...(slug ? {slug} : {}),\n ...(visibility ? {visibility} : {}),\n })\n } catch (error) {\n throw toSlugRejection(error, slug)\n }\n spin.succeed()\n } catch (error) {\n spin.clear()\n throw error\n }\n}\n\n/**\n * The slug is the one synced field the server validates — it must be free\n * within the organization, and a singleton app only accepts its reserved\n * identifiers — so a 4xx on the metadata patch is a rejected rename. Name the\n * slug and the server's reason; anything else propagates untouched.\n */\nfunction toSlugRejection(error: unknown, slug: string | undefined): unknown {\n const statusCode = (error as {statusCode?: number})?.statusCode\n if (!slug || statusCode === undefined || statusCode < 400 || statusCode >= 500) return error\n return new Error(\n `Slug \"${slug}\" was rejected: ${getErrorMessage(error)}. The deployment is live at the application's previous slug — change \\`app.slug\\` in sanity.cli.ts and deploy again.`,\n {cause: error},\n )\n}\n"],"names":["readFile","basename","dirname","join","createGzip","getErrorMessage","spinner","c","createTar","deriveInterfaces","createApplication","createDeployment","deleteApplication","updateApplication","toBrettInterface","iface","version","id","_id","src","_src","declaration","surface","view","type","createCoreApp","options","spin","start","application","succeed","rollback","error","fail","createStudio","deployWorkbenchApp","access","app","applicationId","icon","isApp","isAutoUpdating","isExternal","label","onDeployed","slug","sourceDir","title","visibility","workspaces","mfManifest","JSON","parse","tarball","undefined","cwd","pipe","interfaces","appTitle","map","toSlugRejection","clear","statusCode","Error","cause"],"mappings":"AAAA,SAAQA,QAAQ,QAAO,mBAAkB;AACzC,SAAQC,QAAQ,EAAEC,OAAO,EAAEC,IAAI,QAAO,YAAW;AACjD,SAAQC,UAAU,QAAO,YAAW;AAGpC,SAAQC,eAAe,QAAO,0BAAyB;AACvD,SAAQC,OAAO,QAAO,sBAAqB;AAC3C,SAAQC,KAAKC,SAAS,QAAO,MAAK;AAElC,SAA+BC,gBAAgB,QAAO,4BAA2B;AACjF,SAKEC,iBAAiB,EACjBC,gBAAgB,EAChBC,iBAAiB,EACjBC,iBAAiB,QACZ,iCAAgC;AAWvC,SAASC,iBAAiBC,KAAuB,EAAEC,OAAe;IAChE,MAAM,EAACC,IAAIC,GAAG,EAAEC,KAAKC,IAAI,EAAE,GAAGC,aAAY,GAAGN;IAC7C,IAAI,UAAUM,aAAa,OAAO;QAAC,GAAGA,WAAW;QAAEL;IAAO;IAE1D,OAAQK,YAAYC,OAAO;QACzB,KAAK;YAAgB;gBACnB,MAAM,EAACA,OAAO,EAAE,GAAGC,MAAK,GAAGF;gBAC3B,OAAO;oBAAC,GAAGE,IAAI;oBAAEC,MAAMF;oBAASN;gBAAO;YACzC;QACA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,OAAO,oHAAoH,CAAC,EAC5K;QAACgC,OAAOhC;IAAK;AAEjB"}
@@ -146,6 +146,15 @@ export const devServerManifestSchema = z.object({
146
146
  */ export function isConfigOnlyServer(server) {
147
147
  return Boolean(server.configs?.length) && !server.interfaces?.length;
148
148
  }
149
+ /**
150
+ * Where the Dashboard shell opens a registered server: `/local/<id>`, only when
151
+ * it has an id and a `surface: 'window'` interface. That interface is the app
152
+ * view the shell's `/local/:applicationId` route renders (see toWireInterface);
153
+ * studios always get one, configs and panel-only apps don't, so they'd 404.
154
+ */ export function dashboardPath(server) {
155
+ const hasAppView = (server.interfaces ?? []).some((iface)=>'surface' in iface && iface.surface === 'window');
156
+ return server.id && hasAppView ? `/local/${encodeURIComponent(server.id)}` : undefined;
157
+ }
149
158
  /**
150
159
  * Path to the dev server registry directory. Lives under the shared Sanity
151
160
  * config directory to stay consistent with other CLI paths.