@sanity/workbench-cli 2.15.1 → 2.16.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.
- package/dist/_exports/_internal_worker_bus.d.ts +3 -3
- package/dist/_exports/_internal_worker_bus.js +1 -1
- package/dist/_exports/_internal_worker_bus.js.map +1 -1
- package/dist/_exports/build.d.ts +3 -3
- package/dist/_exports/{contract-C4Y6gi-b.d.ts → contract-WrU3aOYd.d.ts} +9 -6
- package/dist/_exports/deploy.d.ts +3 -3
- package/dist/_exports/dev.d.ts +1 -1
- package/dist/_exports/index.d.ts +5 -4
- package/dist/_exports/index.js +1 -1
- package/dist/_exports/index.js.map +1 -1
- package/dist/_exports/{resolveWorkbenchConfig-CgKD8AJ7.d.ts → resolveWorkbenchConfig-JRi01VJM.d.ts} +2 -2
- package/dist/_exports/{summarizeInterfaces-CeV5Umpj.d.ts → summarizeInterfaces-CpCUSMrz.d.ts} +6 -6
- package/dist/_exports/undeploy.d.ts +2 -2
- package/dist/_exports/{defineService-DPZwNN6_.d.ts → webWorker-TWUbh0uo.d.ts} +63 -39
- package/dist/actions/build/artifact.js +2 -2
- package/dist/actions/build/artifact.js.map +1 -1
- package/dist/actions/build/render-remote.js +8 -4
- package/dist/actions/build/render-remote.js.map +1 -1
- package/dist/actions/build/views/artifact.js +7 -5
- package/dist/actions/build/views/artifact.js.map +1 -1
- package/dist/actions/build/vite/optimize-deps.js +2 -2
- package/dist/actions/build/vite/optimize-deps.js.map +1 -1
- package/dist/actions/build/vite/plugin.js +2 -2
- package/dist/actions/build/vite/plugin.js.map +1 -1
- package/dist/actions/build/vite/plugins/plugin-sanity-environment.js +1 -0
- package/dist/actions/build/vite/plugins/plugin-sanity-environment.js.map +1 -1
- package/dist/actions/build/vite/plugins/plugin-sanity-extension-artifacts.js +2 -2
- package/dist/actions/build/vite/plugins/plugin-sanity-extension-artifacts.js.map +1 -1
- package/dist/actions/build/{services → webWorkers}/artifact.js +28 -27
- package/dist/actions/build/webWorkers/artifact.js.map +1 -0
- package/dist/actions/build/{services → webWorkers}/workerBus.js +1 -1
- package/dist/actions/build/webWorkers/workerBus.js.map +1 -0
- package/dist/actions/deploy/getWorkbench.js.map +1 -1
- package/dist/actions/deploy/summarizeInterfaces.js +3 -3
- package/dist/actions/deploy/summarizeInterfaces.js.map +1 -1
- package/dist/actions/dev/appServerSupervisor.js +2 -2
- package/dist/actions/dev/appServerSupervisor.js.map +1 -1
- package/dist/actions/dev/exposesSetId.js +1 -1
- package/dist/actions/dev/exposesSetId.js.map +1 -1
- package/dist/actions/dev/startWorkbenchDev.js +1 -1
- package/dist/actions/dev/startWorkbenchDev.js.map +1 -1
- package/dist/contract.js +5 -5
- package/dist/contract.js.map +1 -1
- package/dist/defineApp.js +2 -2
- package/dist/defineApp.js.map +1 -1
- package/dist/defineView.js +2 -2
- package/dist/defineView.js.map +1 -1
- package/dist/webWorker.js +20 -0
- package/dist/webWorker.js.map +1 -0
- package/package.json +12 -12
- package/dist/actions/build/services/artifact.js.map +0 -1
- package/dist/actions/build/services/workerBus.js.map +0 -1
- package/dist/defineService.js +0 -52
- package/dist/defineService.js.map +0 -1
|
@@ -39,9 +39,9 @@ import { sanityFederationRuntime } from './plugins/plugin-sanity-federation-runt
|
|
|
39
39
|
// eslint-disable-next-line no-console -- build-time warning for the app developer
|
|
40
40
|
console.warn(`The installed sanity version does not ship ${MEDIA_LIBRARY_ISLAND_RUNTIME_MODULE}; ` + 'custom field inputs will not render in the Media Library until sanity is upgraded.');
|
|
41
41
|
}
|
|
42
|
-
// Each view component (`./views/<view>/<component>`) and each
|
|
42
|
+
// Each view component (`./views/<view>/<component>`) and each web worker loader
|
|
43
43
|
// (`./services/<name>`) is exposed straight to the host, pointing at the file
|
|
44
|
-
// the extension-artifacts plugin generates under RUNTIME_DIR. A
|
|
44
|
+
// the extension-artifacts plugin generates under RUNTIME_DIR. A web worker's
|
|
45
45
|
// worker bundle carries no expose — the host reaches it through its loader.
|
|
46
46
|
const artifacts = workbenchArtifacts(exposes ?? {}, {
|
|
47
47
|
islandRuntime
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/actions/build/vite/plugin.ts"],"sourcesContent":["import path from 'node:path'\n\nimport {type ModuleFederationOptions} from '@module-federation/vite'\nimport {type PackageJson} from '@sanity/cli-core'\nimport {type PluginOption} from 'vite'\n\nimport {type WorkbenchExposes} from '../../../resolveWorkbenchApp.js'\nimport {artifactExposes, workbenchArtifacts} from '../artifact.js'\nimport {isMediaLibraryConfigApp} from '../configs/configApp.js'\nimport {\n hasMediaLibraryIslandRuntime,\n MEDIA_LIBRARY_ISLAND_RUNTIME_MODULE,\n} from '../configs/mediaLibraryIslandRuntime.js'\nimport {FEDERATION_FILE_NAME, RUNTIME_DIR} from './constants.js'\nimport {sanityFederationHost} from './plugins/plugin-federation-host.js'\nimport {type FederationOptions, sanityModuleFederation} from './plugins/plugin-module-federation.js'\nimport {type AutoUpdates, sanityAutoUpdates} from './plugins/plugin-sanity-auto-updates.js'\nimport {sanityEnvironmentPlugin} from './plugins/plugin-sanity-environment.js'\nimport {sanityExtensionArtifacts} from './plugins/plugin-sanity-extension-artifacts.js'\nimport {\n type FederationRuntimeOptions,\n sanityFederationRuntime,\n} from './plugins/plugin-sanity-federation-runtime.js'\n\ninterface FederationPluginOptionsBase extends Omit<Partial<FederationOptions>, 'exposes'> {\n autoUpdates?: AutoUpdates\n exposes?: WorkbenchExposes\n /** Blueprints build (via `@sanity/runtime-cli`) — emit the resource-bindings module. */\n isBlueprints?: boolean\n pkgJson?: PackageJson\n /**\n * Current working directory to read package.json from, defaults to process.cwd()\n */\n workDir?: string\n}\n\ninterface AppFederationPluginOptions extends FederationPluginOptionsBase {\n isApp: true\n\n /**\n * Relative path to the App entry from the runtime directory, e.g.\n * `../../src/App.tsx`. Omit it for a dock-only app that declares no `entry`:\n * no `./App` is exposed and the remote serves only its views.\n */\n appEntry?: string\n studioConfigPath?: never\n}\n\ninterface StudioFederationPluginOptions extends FederationPluginOptionsBase {\n /** relative path to the Studio config file from the runtime directory (e.g. `../../sanity.config.ts`). */\n studioConfigPath: string\n\n appEntry?: never\n /** @defaultValue false */\n isApp?: false\n}\n\n/**\n * Plugin options for the federation vite plugin.\n *\n * Discriminated on `isApp`:\n * - `isApp: true` → requires `appEntry`\n * - `isApp: false` (default) → requires `studioConfigPath`\n *\n * @internal\n */\ntype FederationPluginOptions = AppFederationPluginOptions | StudioFederationPluginOptions\n\n/**\n * @internal\n */\nexport const federation = (options: FederationPluginOptions): PluginOption => {\n const {exposes, isBlueprints, name: defaultName, pkgJson, workDir = process.cwd()} = options\n\n let name = defaultName\n\n if (!name) {\n name = pkgJson?.name\n }\n\n if (!name) {\n throw new Error('\"name\" option is required but could not be inferred from package.json')\n }\n\n const generatedEntry = `./${RUNTIME_DIR}/${FEDERATION_FILE_NAME}.jsx`\n\n function resolveEntryPath(entry: string) {\n const resolvedPath = path.resolve(workDir, entry)\n\n if (!resolvedPath) {\n throw new Error(\n `Could not resolve path for entry \"${entry}\". Please check that the file exists and the path is correct.`,\n )\n }\n\n return resolvedPath\n }\n\n const entryPath = resolveEntryPath(generatedEntry)\n\n // A Media Library config's `./island-runtime` expose re-exports the mount\n // runtime from the app's installed `sanity`; skip it (the host falls back to\n // degraded rendering for custom inputs) when that version predates the entry,\n // since an unresolvable import would fail the whole build.\n const isConfigApp = isMediaLibraryConfigApp(exposes)\n const islandRuntime = isConfigApp && hasMediaLibraryIslandRuntime(workDir)\n if (isConfigApp && !islandRuntime) {\n // eslint-disable-next-line no-console -- build-time warning for the app developer\n console.warn(\n `The installed sanity version does not ship ${MEDIA_LIBRARY_ISLAND_RUNTIME_MODULE}; ` +\n 'custom field inputs will not render in the Media Library until sanity is upgraded.',\n )\n }\n\n // Each view component (`./views/<view>/<component>`) and each
|
|
1
|
+
{"version":3,"sources":["../../../../src/actions/build/vite/plugin.ts"],"sourcesContent":["import path from 'node:path'\n\nimport {type ModuleFederationOptions} from '@module-federation/vite'\nimport {type PackageJson} from '@sanity/cli-core'\nimport {type PluginOption} from 'vite'\n\nimport {type WorkbenchExposes} from '../../../resolveWorkbenchApp.js'\nimport {artifactExposes, workbenchArtifacts} from '../artifact.js'\nimport {isMediaLibraryConfigApp} from '../configs/configApp.js'\nimport {\n hasMediaLibraryIslandRuntime,\n MEDIA_LIBRARY_ISLAND_RUNTIME_MODULE,\n} from '../configs/mediaLibraryIslandRuntime.js'\nimport {FEDERATION_FILE_NAME, RUNTIME_DIR} from './constants.js'\nimport {sanityFederationHost} from './plugins/plugin-federation-host.js'\nimport {type FederationOptions, sanityModuleFederation} from './plugins/plugin-module-federation.js'\nimport {type AutoUpdates, sanityAutoUpdates} from './plugins/plugin-sanity-auto-updates.js'\nimport {sanityEnvironmentPlugin} from './plugins/plugin-sanity-environment.js'\nimport {sanityExtensionArtifacts} from './plugins/plugin-sanity-extension-artifacts.js'\nimport {\n type FederationRuntimeOptions,\n sanityFederationRuntime,\n} from './plugins/plugin-sanity-federation-runtime.js'\n\ninterface FederationPluginOptionsBase extends Omit<Partial<FederationOptions>, 'exposes'> {\n autoUpdates?: AutoUpdates\n exposes?: WorkbenchExposes\n /** Blueprints build (via `@sanity/runtime-cli`) — emit the resource-bindings module. */\n isBlueprints?: boolean\n pkgJson?: PackageJson\n /**\n * Current working directory to read package.json from, defaults to process.cwd()\n */\n workDir?: string\n}\n\ninterface AppFederationPluginOptions extends FederationPluginOptionsBase {\n isApp: true\n\n /**\n * Relative path to the App entry from the runtime directory, e.g.\n * `../../src/App.tsx`. Omit it for a dock-only app that declares no `entry`:\n * no `./App` is exposed and the remote serves only its views.\n */\n appEntry?: string\n studioConfigPath?: never\n}\n\ninterface StudioFederationPluginOptions extends FederationPluginOptionsBase {\n /** relative path to the Studio config file from the runtime directory (e.g. `../../sanity.config.ts`). */\n studioConfigPath: string\n\n appEntry?: never\n /** @defaultValue false */\n isApp?: false\n}\n\n/**\n * Plugin options for the federation vite plugin.\n *\n * Discriminated on `isApp`:\n * - `isApp: true` → requires `appEntry`\n * - `isApp: false` (default) → requires `studioConfigPath`\n *\n * @internal\n */\ntype FederationPluginOptions = AppFederationPluginOptions | StudioFederationPluginOptions\n\n/**\n * @internal\n */\nexport const federation = (options: FederationPluginOptions): PluginOption => {\n const {exposes, isBlueprints, name: defaultName, pkgJson, workDir = process.cwd()} = options\n\n let name = defaultName\n\n if (!name) {\n name = pkgJson?.name\n }\n\n if (!name) {\n throw new Error('\"name\" option is required but could not be inferred from package.json')\n }\n\n const generatedEntry = `./${RUNTIME_DIR}/${FEDERATION_FILE_NAME}.jsx`\n\n function resolveEntryPath(entry: string) {\n const resolvedPath = path.resolve(workDir, entry)\n\n if (!resolvedPath) {\n throw new Error(\n `Could not resolve path for entry \"${entry}\". Please check that the file exists and the path is correct.`,\n )\n }\n\n return resolvedPath\n }\n\n const entryPath = resolveEntryPath(generatedEntry)\n\n // A Media Library config's `./island-runtime` expose re-exports the mount\n // runtime from the app's installed `sanity`; skip it (the host falls back to\n // degraded rendering for custom inputs) when that version predates the entry,\n // since an unresolvable import would fail the whole build.\n const isConfigApp = isMediaLibraryConfigApp(exposes)\n const islandRuntime = isConfigApp && hasMediaLibraryIslandRuntime(workDir)\n if (isConfigApp && !islandRuntime) {\n // eslint-disable-next-line no-console -- build-time warning for the app developer\n console.warn(\n `The installed sanity version does not ship ${MEDIA_LIBRARY_ISLAND_RUNTIME_MODULE}; ` +\n 'custom field inputs will not render in the Media Library until sanity is upgraded.',\n )\n }\n\n // Each view component (`./views/<view>/<component>`) and each web worker loader\n // (`./services/<name>`) is exposed straight to the host, pointing at the file\n // the extension-artifacts plugin generates under RUNTIME_DIR. A web worker's\n // worker bundle carries no expose — the host reaches it through its loader.\n const artifacts = workbenchArtifacts(exposes ?? {}, {islandRuntime})\n const artifactModuleExposes = artifactExposes(artifacts, (artifactPath) =>\n resolveEntryPath(`./${RUNTIME_DIR}/${artifactPath}`),\n )\n\n // A dock-only app (`isApp` with no `appEntry`) has no navigable full-page\n // view, so it exposes no `./App` — only its views. Studios and apps with an\n // entry expose `./App` (the generated render entry).\n const exposesApp = !options.isApp || options.appEntry !== undefined\n\n const federationExposes: NonNullable<ModuleFederationOptions['exposes']> = {\n ...(exposesApp ? {'./App': entryPath} : {}),\n ...artifactModuleExposes,\n }\n\n const runtimeOptions: FederationRuntimeOptions = options.isApp\n ? {appEntry: options.appEntry, isApp: true, isBlueprints}\n : {isApp: false, isBlueprints, studioConfigPath: options.studioConfigPath}\n\n // Every federated app and studio also serves itself standalone. Whenever there's\n // an `./App` to mount (never for a dock-only app), build the SPA client\n // environment from the runtime bootstrap cli-build writes.\n const clientInput = exposesApp ? path.join(workDir, '.sanity', 'runtime', 'app.js') : undefined\n\n return [\n sanityEnvironmentPlugin({clientInput, input: entryPath, isBlueprints}),\n sanityFederationRuntime(runtimeOptions),\n sanityExtensionArtifacts({artifacts}),\n sanityModuleFederation({exposes: federationExposes, name}),\n sanityFederationHost(),\n sanityAutoUpdates(options.autoUpdates),\n ]\n}\n"],"names":["path","artifactExposes","workbenchArtifacts","isMediaLibraryConfigApp","hasMediaLibraryIslandRuntime","MEDIA_LIBRARY_ISLAND_RUNTIME_MODULE","FEDERATION_FILE_NAME","RUNTIME_DIR","sanityFederationHost","sanityModuleFederation","sanityAutoUpdates","sanityEnvironmentPlugin","sanityExtensionArtifacts","sanityFederationRuntime","federation","options","exposes","isBlueprints","name","defaultName","pkgJson","workDir","process","cwd","Error","generatedEntry","resolveEntryPath","entry","resolvedPath","resolve","entryPath","isConfigApp","islandRuntime","console","warn","artifacts","artifactModuleExposes","artifactPath","exposesApp","isApp","appEntry","undefined","federationExposes","runtimeOptions","studioConfigPath","clientInput","join","input","autoUpdates"],"mappings":"AAAA,OAAOA,UAAU,YAAW;AAO5B,SAAQC,eAAe,EAAEC,kBAAkB,QAAO,iBAAgB;AAClE,SAAQC,uBAAuB,QAAO,0BAAyB;AAC/D,SACEC,4BAA4B,EAC5BC,mCAAmC,QAC9B,0CA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,CAAC,GAAG;QAACgB;IAAa;IAClE,MAAMI,wBAAwBnC,gBAAgBkC,WAAW,CAACE,eACxDX,iBAAiB,CAAC,EAAE,EAAEnB,YAAY,CAAC,EAAE8B,cAAc;IAGrD,0EAA0E;IAC1E,4EAA4E;IAC5E,qDAAqD;IACrD,MAAMC,aAAa,CAACvB,QAAQwB,KAAK,IAAIxB,QAAQyB,QAAQ,KAAKC;IAE1D,MAAMC,oBAAqE;QACzE,GAAIJ,aAAa;YAAC,SAASR;QAAS,IAAI,CAAC,CAAC;QAC1C,GAAGM,qBAAqB;IAC1B;IAEA,MAAMO,iBAA2C5B,QAAQwB,KAAK,GAC1D;QAACC,UAAUzB,QAAQyB,QAAQ;QAAED,OAAO;QAAMtB;IAAY,IACtD;QAACsB,OAAO;QAAOtB;QAAc2B,kBAAkB7B,QAAQ6B,gBAAgB;IAAA;IAE3E,iFAAiF;IACjF,wEAAwE;IACxE,2DAA2D;IAC3D,MAAMC,cAAcP,aAAatC,KAAK8C,IAAI,CAACzB,SAAS,WAAW,WAAW,YAAYoB;IAEtF,OAAO;QACL9B,wBAAwB;YAACkC;YAAaE,OAAOjB;YAAWb;QAAY;QACpEJ,wBAAwB8B;QACxB/B,yBAAyB;YAACuB;QAAS;QACnC1B,uBAAuB;YAACO,SAAS0B;YAAmBxB;QAAI;QACxDV;QACAE,kBAAkBK,QAAQiC,WAAW;KACtC;AACH,EAAC"}
|
|
@@ -19,6 +19,7 @@ export function sanityEnvironmentPlugin(options) {
|
|
|
19
19
|
// chunk so Brett can rewrite it at deploy. Off Blueprints, no such chunk.
|
|
20
20
|
const output = isBlueprints ? resourceBindingsOutput : undefined;
|
|
21
21
|
return {
|
|
22
|
+
apply: 'build',
|
|
22
23
|
config () {
|
|
23
24
|
return {
|
|
24
25
|
builder: {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/actions/build/vite/plugins/plugin-sanity-environment.ts"],"sourcesContent":["import {type Plugin} from 'vite'\n\nimport {\n resourceBindingsChunkFileName,\n resourceBindingsCodeSplittingGroup,\n} from '../../resource-bindings.js'\nimport {FEDERATION_DIR_NAME} from '../constants.js'\n\n// Keep the resource-bindings module in its own unhashed chunk at the bundle root\n// so Brett can rewrite it at deploy. `@module-federation/vite` preserves user\n// `codeSplitting` groups (clamped below its own), so this survives the federation\n// build. The chunk sizing lives on the group itself (see\n// `resourceBindingsCodeSplittingGroup`), so it only affects the bindings module.\nconst resourceBindingsOutput = {\n chunkFileNames: (chunk: {name: string}) =>\n resourceBindingsChunkFileName(chunk.name) ?? 'static/[name]-[hash].js',\n codeSplitting: {\n groups: [resourceBindingsCodeSplittingGroup],\n },\n}\n\ninterface EnvironmentOptions {\n input: string\n\n /**\n * When set, also build a standalone `client` SPA environment (its own\n * `index.html` + bootstrap) alongside the federation remote, from this entry.\n * Set for every federated app and studio; omitted only for a dock-only app.\n */\n clientInput?: string\n\n /** Blueprints build (via `@sanity/runtime-cli`) — emit the resource-bindings module. */\n isBlueprints?: boolean\n}\n\nexport function sanityEnvironmentPlugin(options: EnvironmentOptions): Plugin {\n const {clientInput, input, isBlueprints} = options\n\n // Blueprints only: force the resource-bindings module into its own unhashed\n // chunk so Brett can rewrite it at deploy. Off Blueprints, no such chunk.\n const output = isBlueprints ? resourceBindingsOutput : undefined\n\n return {\n config() {\n return {\n builder: {\n async buildApp(builder) {\n // Both environments inherit the top-level `build.outDir` (`dist` by\n // default, or the `outputDir` a caller such as Blueprints passes).\n // `emptyOutDir` is false on both and the CLI clears the output dir\n // once up-front, so the SPA and federation outputs coexist without\n // either build wiping the other's files.\n if (clientInput) {\n await builder.build(builder.environments.client)\n }\n await builder.build(builder.environments[FEDERATION_DIR_NAME])\n },\n },\n environments: {\n ...(clientInput\n ? {\n client: {\n build: {\n assetsDir: 'static',\n copyPublicDir: false,\n emptyOutDir: false,\n rolldownOptions: {\n input: {sanity: clientInput},\n output,\n },\n },\n consumer: 'client',\n },\n }\n : {}),\n [FEDERATION_DIR_NAME]: {\n build: {\n assetsDir: 'static',\n copyPublicDir: false,\n emptyOutDir: false,\n rolldownOptions: {input, output},\n },\n consumer: 'client',\n },\n },\n }\n },\n name: 'sanity/environment',\n }\n}\n"],"names":["resourceBindingsChunkFileName","resourceBindingsCodeSplittingGroup","FEDERATION_DIR_NAME","resourceBindingsOutput","chunkFileNames","chunk","name","codeSplitting","groups","sanityEnvironmentPlugin","options","clientInput","input","isBlueprints","output","undefined","config","builder","buildApp","build","environments","client","assetsDir","copyPublicDir","emptyOutDir","rolldownOptions","sanity","consumer"],"mappings":"AAEA,SACEA,6BAA6B,EAC7BC,kCAAkC,QAC7B,6BAA4B;AACnC,SAAQC,mBAAmB,QAAO,kBAAiB;AAEnD,iFAAiF;AACjF,8EAA8E;AAC9E,kFAAkF;AAClF,yDAAyD;AACzD,iFAAiF;AACjF,MAAMC,yBAAyB;IAC7BC,gBAAgB,CAACC,QACfL,8BAA8BK,MAAMC,IAAI,KAAK;IAC/CC,eAAe;QACbC,QAAQ;YAACP;SAAmC;IAC9C;AACF;AAgBA,OAAO,SAASQ,wBAAwBC,OAA2B;IACjE,MAAM,EAACC,WAAW,EAAEC,KAAK,EAAEC,YAAY,EAAC,GAAGH;IAE3C,4EAA4E;IAC5E,0EAA0E;IAC1E,MAAMI,SAASD,eAAeV,yBAAyBY;IAEvD,OAAO;QACLC;YACE,OAAO;gBACLC,SAAS;oBACP,MAAMC,UAASD,OAAO;wBACpB,oEAAoE;wBACpE,mEAAmE;wBACnE,mEAAmE;wBACnE,mEAAmE;wBACnE,yCAAyC;wBACzC,
|
|
1
|
+
{"version":3,"sources":["../../../../../src/actions/build/vite/plugins/plugin-sanity-environment.ts"],"sourcesContent":["import {type Plugin} from 'vite'\n\nimport {\n resourceBindingsChunkFileName,\n resourceBindingsCodeSplittingGroup,\n} from '../../resource-bindings.js'\nimport {FEDERATION_DIR_NAME} from '../constants.js'\n\n// Keep the resource-bindings module in its own unhashed chunk at the bundle root\n// so Brett can rewrite it at deploy. `@module-federation/vite` preserves user\n// `codeSplitting` groups (clamped below its own), so this survives the federation\n// build. The chunk sizing lives on the group itself (see\n// `resourceBindingsCodeSplittingGroup`), so it only affects the bindings module.\nconst resourceBindingsOutput = {\n chunkFileNames: (chunk: {name: string}) =>\n resourceBindingsChunkFileName(chunk.name) ?? 'static/[name]-[hash].js',\n codeSplitting: {\n groups: [resourceBindingsCodeSplittingGroup],\n },\n}\n\ninterface EnvironmentOptions {\n input: string\n\n /**\n * When set, also build a standalone `client` SPA environment (its own\n * `index.html` + bootstrap) alongside the federation remote, from this entry.\n * Set for every federated app and studio; omitted only for a dock-only app.\n */\n clientInput?: string\n\n /** Blueprints build (via `@sanity/runtime-cli`) — emit the resource-bindings module. */\n isBlueprints?: boolean\n}\n\nexport function sanityEnvironmentPlugin(options: EnvironmentOptions): Plugin {\n const {clientInput, input, isBlueprints} = options\n\n // Blueprints only: force the resource-bindings module into its own unhashed\n // chunk so Brett can rewrite it at deploy. Off Blueprints, no such chunk.\n const output = isBlueprints ? resourceBindingsOutput : undefined\n\n return {\n apply: 'build',\n config() {\n return {\n builder: {\n async buildApp(builder) {\n // Both environments inherit the top-level `build.outDir` (`dist` by\n // default, or the `outputDir` a caller such as Blueprints passes).\n // `emptyOutDir` is false on both and the CLI clears the output dir\n // once up-front, so the SPA and federation outputs coexist without\n // either build wiping the other's files.\n if (clientInput) {\n await builder.build(builder.environments.client)\n }\n await builder.build(builder.environments[FEDERATION_DIR_NAME])\n },\n },\n environments: {\n ...(clientInput\n ? {\n client: {\n build: {\n assetsDir: 'static',\n copyPublicDir: false,\n emptyOutDir: false,\n rolldownOptions: {\n input: {sanity: clientInput},\n output,\n },\n },\n consumer: 'client',\n },\n }\n : {}),\n [FEDERATION_DIR_NAME]: {\n build: {\n assetsDir: 'static',\n copyPublicDir: false,\n emptyOutDir: false,\n rolldownOptions: {input, output},\n },\n consumer: 'client',\n },\n },\n }\n },\n name: 'sanity/environment',\n }\n}\n"],"names":["resourceBindingsChunkFileName","resourceBindingsCodeSplittingGroup","FEDERATION_DIR_NAME","resourceBindingsOutput","chunkFileNames","chunk","name","codeSplitting","groups","sanityEnvironmentPlugin","options","clientInput","input","isBlueprints","output","undefined","apply","config","builder","buildApp","build","environments","client","assetsDir","copyPublicDir","emptyOutDir","rolldownOptions","sanity","consumer"],"mappings":"AAEA,SACEA,6BAA6B,EAC7BC,kCAAkC,QAC7B,6BAA4B;AACnC,SAAQC,mBAAmB,QAAO,kBAAiB;AAEnD,iFAAiF;AACjF,8EAA8E;AAC9E,kFAAkF;AAClF,yDAAyD;AACzD,iFAAiF;AACjF,MAAMC,yBAAyB;IAC7BC,gBAAgB,CAACC,QACfL,8BAA8BK,MAAMC,IAAI,KAAK;IAC/CC,eAAe;QACbC,QAAQ;YAACP;SAAmC;IAC9C;AACF;AAgBA,OAAO,SAASQ,wBAAwBC,OAA2B;IACjE,MAAM,EAACC,WAAW,EAAEC,KAAK,EAAEC,YAAY,EAAC,GAAGH;IAE3C,4EAA4E;IAC5E,0EAA0E;IAC1E,MAAMI,SAASD,eAAeV,yBAAyBY;IAEvD,OAAO;QACLC,OAAO;QACPC;YACE,OAAO;gBACLC,SAAS;oBACP,MAAMC,UAASD,OAAO;wBACpB,oEAAoE;wBACpE,mEAAmE;wBACnE,mEAAmE;wBACnE,mEAAmE;wBACnE,yCAAyC;wBACzC,IAAIP,aAAa;4BACf,MAAMO,QAAQE,KAAK,CAACF,QAAQG,YAAY,CAACC,MAAM;wBACjD;wBACA,MAAMJ,QAAQE,KAAK,CAACF,QAAQG,YAAY,CAACnB,oBAAoB;oBAC/D;gBACF;gBACAmB,cAAc;oBACZ,GAAIV,cACA;wBACEW,QAAQ;4BACNF,OAAO;gCACLG,WAAW;gCACXC,eAAe;gCACfC,aAAa;gCACbC,iBAAiB;oCACfd,OAAO;wCAACe,QAAQhB;oCAAW;oCAC3BG;gCACF;4BACF;4BACAc,UAAU;wBACZ;oBACF,IACA,CAAC,CAAC;oBACN,CAAC1B,oBAAoB,EAAE;wBACrBkB,OAAO;4BACLG,WAAW;4BACXC,eAAe;4BACfC,aAAa;4BACbC,iBAAiB;gCAACd;gCAAOE;4BAAM;wBACjC;wBACAc,UAAU;oBACZ;gBACF;YACF;QACF;QACAtB,MAAM;IACR;AACF"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import fs from 'node:fs';
|
|
2
2
|
import path from 'node:path';
|
|
3
3
|
import { fileURLToPath } from 'node:url';
|
|
4
|
-
import { WORKER_BUS_ENTRY } from '../../
|
|
4
|
+
import { WORKER_BUS_ENTRY } from '../../webWorkers/artifact.js';
|
|
5
5
|
import { RUNTIME_DIR } from '../constants.js';
|
|
6
6
|
import { getFederationApi } from './plugin-module-federation.js';
|
|
7
7
|
const workerBusPath = fileURLToPath(new URL('../../../../_exports/_internal_worker_bus.js', import.meta.url));
|
|
@@ -22,7 +22,7 @@ function writeArtifacts({ artifacts, isolateStyles, root }) {
|
|
|
22
22
|
}
|
|
23
23
|
}
|
|
24
24
|
/**
|
|
25
|
-
* Writes the federation runtime artifacts (view render-contract modules,
|
|
25
|
+
* Writes the federation runtime artifacts (view render-contract modules, web worker
|
|
26
26
|
* worker bundles + loaders) into `RUNTIME_DIR`, resolving each artifact's import
|
|
27
27
|
* paths relative to where it lands on disk. The set is expanded once by
|
|
28
28
|
* `workbenchArtifacts` and handed in — this plugin only writes it.
|
|
@@ -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'\nimport {fileURLToPath} from 'node:url'\n\nimport {type Plugin} from 'vite'\n\nimport {type GeneratedArtifact} from '../../artifact.js'\nimport {WORKER_BUS_ENTRY} from '../../
|
|
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 '../../webWorkers/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, web worker\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,+BAA8B;AAC7D,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,57 +1,57 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { WEB_WORKER_CONTRACT_VERSION } from '../../../contract.js';
|
|
2
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';
|
|
3
|
-
/** Subdirectory under the federation runtime dir
|
|
4
|
-
const
|
|
3
|
+
/** Subdirectory under the federation runtime dir for web worker artifacts; hosts load them as `services/<name>`. */ const WEB_WORKERS_DIR_NAME = 'services';
|
|
4
|
+
const WEB_WORKER_TYPES = [
|
|
5
5
|
'worker'
|
|
6
6
|
];
|
|
7
7
|
/**
|
|
8
|
-
* Expand each
|
|
8
|
+
* Expand each web worker into its two generated artifacts: a self-contained worker
|
|
9
9
|
* bundle (imports the user's `src`, runs the callback) and a loader module the
|
|
10
10
|
* host loads to read the worker's URL. Only the loader is a federation expose —
|
|
11
11
|
* the host reaches the worker bundle through it, never directly.
|
|
12
|
-
*/ export function
|
|
13
|
-
return
|
|
14
|
-
const dir = `${
|
|
12
|
+
*/ export function webWorkerArtifacts(workers) {
|
|
13
|
+
return workers.filter((worker)=>WEB_WORKER_TYPES.includes(worker.type)).flatMap((worker)=>{
|
|
14
|
+
const dir = `${WEB_WORKERS_DIR_NAME}/${worker.name}`;
|
|
15
15
|
return [
|
|
16
16
|
{
|
|
17
17
|
path: `${dir}/worker.js`,
|
|
18
|
-
source: ({ resolveImport })=>
|
|
19
|
-
importPath: resolveImport(
|
|
20
|
-
|
|
18
|
+
source: ({ resolveImport })=>webWorkerArtifactSource({
|
|
19
|
+
importPath: resolveImport(worker.src),
|
|
20
|
+
worker
|
|
21
21
|
})
|
|
22
22
|
},
|
|
23
23
|
{
|
|
24
24
|
expose: `./${dir}`,
|
|
25
25
|
path: `${dir}/index.js`,
|
|
26
|
-
source: ()=>
|
|
27
|
-
|
|
26
|
+
source: ()=>webWorkerLoaderArtifactSource({
|
|
27
|
+
worker
|
|
28
28
|
})
|
|
29
29
|
}
|
|
30
30
|
];
|
|
31
31
|
});
|
|
32
32
|
}
|
|
33
33
|
/**
|
|
34
|
-
* Source for one
|
|
35
|
-
* the user's `unstable_defineService` result and runs
|
|
36
|
-
*
|
|
34
|
+
* Source for one web worker's **worker** bundle — the Web Worker entry. Imports
|
|
35
|
+
* the user's worker function or `unstable_defineService` result and runs it with the
|
|
36
|
+
* web worker's own declaration (mirroring how a view component receives its
|
|
37
37
|
* `view`) and a message bus client (`workerBus.ts`), then wires the returned
|
|
38
38
|
* disposer to the host's terminate message.
|
|
39
39
|
* Crashes — and the worker's `console.*`, which is patched to forward to the
|
|
40
40
|
* host — are surfaced through the host logger (the host owns logging; a worker's
|
|
41
41
|
* own console isn't visible in the page DevTools anyway).
|
|
42
|
-
*/ function
|
|
42
|
+
*/ function webWorkerArtifactSource(input) {
|
|
43
43
|
return `\
|
|
44
44
|
// This file is auto-generated on 'sanity build' / 'sanity dev'
|
|
45
45
|
// Modifications to this file are automatically discarded
|
|
46
|
-
import
|
|
46
|
+
import worker from ${JSON.stringify(input.importPath)}
|
|
47
47
|
import { createWorkerBus } from ${JSON.stringify(WORKER_BUS_ENTRY)}
|
|
48
48
|
|
|
49
|
-
const
|
|
49
|
+
const WORKER = { type: ${JSON.stringify(input.worker.type)}, name: ${JSON.stringify(input.worker.name)} }
|
|
50
50
|
|
|
51
51
|
// Bridge the worker's console to the host. A worker's own console isn't visible
|
|
52
52
|
// in the page DevTools, so patch console.* to forward each call as a message
|
|
53
53
|
// the host re-emits through the workbench logger — any console.log in the
|
|
54
|
-
//
|
|
54
|
+
// worker (or its deps) just shows up in the page console.
|
|
55
55
|
const __format = (arg) => {
|
|
56
56
|
if (typeof arg === 'string') return arg
|
|
57
57
|
try { return JSON.stringify(arg) } catch (_) { return String(arg) }
|
|
@@ -70,7 +70,8 @@ const { bus, close: closeBus, receive: receiveBus } = createWorkerBus()
|
|
|
70
70
|
|
|
71
71
|
let dispose
|
|
72
72
|
try {
|
|
73
|
-
|
|
73
|
+
// Backwards compatibility: an \`unstable_defineService\` result passes the worker as \`service\`. Remove in SDK-3210.
|
|
74
|
+
const result = worker.run ? worker.run({ bus, service: WORKER }) : worker({ bus, worker: WORKER })
|
|
74
75
|
if (typeof result === 'function') dispose = result
|
|
75
76
|
} catch (error) {
|
|
76
77
|
self.postMessage({ kind: 'workbench.worker.error', payload: { message: String(error) } })
|
|
@@ -101,8 +102,8 @@ self.addEventListener('unhandledrejection', (event) => {
|
|
|
101
102
|
`;
|
|
102
103
|
}
|
|
103
104
|
/**
|
|
104
|
-
* Source for one
|
|
105
|
-
* host the worker bundle's URL (via Vite `?worker&url`) plus the
|
|
105
|
+
* Source for one web worker's **loader** — the module-federation expose. Hands the
|
|
106
|
+
* host the worker bundle's URL (via Vite `?worker&url`) plus the web worker's
|
|
106
107
|
* type/version.
|
|
107
108
|
*
|
|
108
109
|
* A URL (not an inlined worker) on purpose: the host can't `new Worker()` it
|
|
@@ -114,7 +115,7 @@ self.addEventListener('unhandledrejection', (event) => {
|
|
|
114
115
|
* No HMR boundary: a worker lives in its own `?worker&url` module graph with no
|
|
115
116
|
* accepting importer, so Vite full-reloads the page on a `src` edit (which
|
|
116
117
|
* re-loads the worker with the new code) — in-place worker HMR isn't possible.
|
|
117
|
-
*/ function
|
|
118
|
+
*/ function webWorkerLoaderArtifactSource(input) {
|
|
118
119
|
return `\
|
|
119
120
|
// This file is auto-generated on 'sanity build' / 'sanity dev'
|
|
120
121
|
// Modifications to this file are automatically discarded
|
|
@@ -122,10 +123,10 @@ import workerUrl from './worker.js?worker&url'
|
|
|
122
123
|
|
|
123
124
|
/** URL of the worker bundle, on the app's origin. */
|
|
124
125
|
export const url = workerUrl
|
|
125
|
-
/**
|
|
126
|
-
export const type = ${JSON.stringify(input.
|
|
127
|
-
export const name = ${JSON.stringify(input.
|
|
128
|
-
export const version = ${
|
|
126
|
+
/** Web worker type and contract version, surfaced for the host to dispatch on. */
|
|
127
|
+
export const type = ${JSON.stringify(input.worker.type)}
|
|
128
|
+
export const name = ${JSON.stringify(input.worker.name)}
|
|
129
|
+
export const version = ${WEB_WORKER_CONTRACT_VERSION}
|
|
129
130
|
`;
|
|
130
131
|
}
|
|
131
132
|
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../src/actions/build/webWorkers/artifact.ts"],"sourcesContent":["import {WEB_WORKER_CONTRACT_VERSION, type WebWorkerType} 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 for web worker artifacts; hosts load them as `services/<name>`. */\nconst WEB_WORKERS_DIR_NAME = 'services'\n\nconst WEB_WORKER_TYPES: readonly WebWorkerType[] = ['worker']\n\n/**\n * A web worker to generate artifacts for. The `src` file default-exports\n * a worker function or an `unstable_defineService(...)` result; the build emits\n * a self-contained Web Worker bundle plus a loader module that hands the host its URL.\n * @internal\n */\nexport interface WebWorkerArtifact {\n /** Web worker name, unique within the app. */\n name: string\n /** Path to the web worker `src` file, relative to the app root (or absolute). */\n src: string\n /** Web worker type, e.g. `\"worker\"`. */\n type: string\n}\n\n/**\n * Expand each web worker 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 webWorkerArtifacts(workers: readonly WebWorkerArtifact[]): GeneratedArtifact[] {\n return workers\n .filter((worker) => (WEB_WORKER_TYPES as readonly string[]).includes(worker.type))\n .flatMap((worker): GeneratedArtifact[] => {\n const dir = `${WEB_WORKERS_DIR_NAME}/${worker.name}`\n return [\n {\n path: `${dir}/worker.js`,\n source: ({resolveImport}) =>\n webWorkerArtifactSource({\n importPath: resolveImport(worker.src),\n worker,\n }),\n },\n {\n expose: `./${dir}`,\n path: `${dir}/index.js`,\n source: () => webWorkerLoaderArtifactSource({worker}),\n },\n ]\n })\n}\n\n/**\n * Source for one web worker's **worker** bundle — the Web Worker entry. Imports\n * the user's worker function or `unstable_defineService` result and runs it with the\n * web worker'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 webWorkerArtifactSource(input: {\n importPath: string\n worker: {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 worker from ${JSON.stringify(input.importPath)}\nimport { createWorkerBus } from ${JSON.stringify(WORKER_BUS_ENTRY)}\n\nconst WORKER = { type: ${JSON.stringify(input.worker.type)}, name: ${JSON.stringify(input.worker.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// worker (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 // Backwards compatibility: an \\`unstable_defineService\\` result passes the worker as \\`service\\`. Remove in SDK-3210.\n const result = worker.run ? worker.run({ bus, service: WORKER }) : worker({ bus, worker: WORKER })\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 web worker's **loader** — the module-federation expose. Hands the\n * host the worker bundle's URL (via Vite `?worker&url`) plus the web worker'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 webWorkerLoaderArtifactSource(input: {worker: {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/** Web worker type and contract version, surfaced for the host to dispatch on. */\nexport const type = ${JSON.stringify(input.worker.type)}\nexport const name = ${JSON.stringify(input.worker.name)}\nexport const version = ${WEB_WORKER_CONTRACT_VERSION}\n`\n}\n"],"names":["WEB_WORKER_CONTRACT_VERSION","WORKER_BUS_ENTRY","WEB_WORKERS_DIR_NAME","WEB_WORKER_TYPES","webWorkerArtifacts","workers","filter","worker","includes","type","flatMap","dir","name","path","source","resolveImport","webWorkerArtifactSource","importPath","src","expose","webWorkerLoaderArtifactSource","input","JSON","stringify"],"mappings":"AAAA,SAAQA,2BAA2B,QAA2B,uBAAsB;AAGpF,yGAAyG,GACzG,OAAO,MAAMC,mBAAmB,6CAA4C;AAE5E,kHAAkH,GAClH,MAAMC,uBAAuB;AAE7B,MAAMC,mBAA6C;IAAC;CAAS;AAiB7D;;;;;CAKC,GACD,OAAO,SAASC,mBAAmBC,OAAqC;IACtE,OAAOA,QACJC,MAAM,CAAC,CAACC,SAAW,AAACJ,iBAAuCK,QAAQ,CAACD,OAAOE,IAAI,GAC/EC,OAAO,CAAC,CAACH;QACR,MAAMI,MAAM,GAAGT,qBAAqB,CAAC,EAAEK,OAAOK,IAAI,EAAE;QACpD,OAAO;YACL;gBACEC,MAAM,GAAGF,IAAI,UAAU,CAAC;gBACxBG,QAAQ,CAAC,EAACC,aAAa,EAAC,GACtBC,wBAAwB;wBACtBC,YAAYF,cAAcR,OAAOW,GAAG;wBACpCX;oBACF;YACJ;YACA;gBACEY,QAAQ,CAAC,EAAE,EAAER,KAAK;gBAClBE,MAAM,GAAGF,IAAI,SAAS,CAAC;gBACvBG,QAAQ,IAAMM,8BAA8B;wBAACb;oBAAM;YACrD;SACD;IACH;AACJ;AAEA;;;;;;;;;CASC,GACD,SAASS,wBAAwBK,KAGhC;IACC,OAAO,CAAC;;;mBAGS,EAAEC,KAAKC,SAAS,CAACF,MAAMJ,UAAU,EAAE;gCACtB,EAAEK,KAAKC,SAAS,CAACtB,kBAAkB;;uBAE5C,EAAEqB,KAAKC,SAAS,CAACF,MAAMd,MAAM,CAACE,IAAI,EAAE,QAAQ,EAAEa,KAAKC,SAAS,CAACF,MAAMd,MAAM,CAACK,IAAI,EAAE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqDvG,CAAC;AACD;AAEA;;;;;;;;;;;;;;CAcC,GACD,SAASQ,8BAA8BC,KAA6C;IAClF,OAAO,CAAC;;;;;;;;oBAQU,EAAEC,KAAKC,SAAS,CAACF,MAAMd,MAAM,CAACE,IAAI,EAAE;oBACpC,EAAEa,KAAKC,SAAS,CAACF,MAAMd,MAAM,CAACK,IAAI,EAAE;uBACjC,EAAEZ,4BAA4B;AACrD,CAAC;AACD"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// Runs inside the
|
|
1
|
+
// Runs inside the web worker's Web Worker, bundled by Vite from the generated
|
|
2
2
|
// `worker.js`. Keep it free of Node and of runtime imports: `@sanity/sdk` is
|
|
3
3
|
// only ever imported for types.
|
|
4
4
|
const DEFAULT_TIMEOUT_MS = 5000;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../src/actions/build/webWorkers/workerBus.ts"],"sourcesContent":["// Runs inside the web worker'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 {\n type MessageBusEmitResult,\n type MessageBusErrorCode,\n type MessageBusMessage,\n type MessageBusMeta,\n} from '@sanity/sdk/dashboard'\n\nimport {type WebWorkerBus} from '../../../webWorker.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 Answer =\n | {error: {code: 'HANDLER_THREW' | 'REFUSED'; message: string}; ok: false}\n | {ok: true; value: unknown}\n\n// What a host refusal can carry besides its code and message, such as the fix\n// and docs link for one of the Dashboard's coded errors.\ninterface RefusalDetails {\n docsUrl?: string\n fix?: string\n}\n\ntype HostMessage =\n | {\n error: RefusalDetails & {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 id: number\n kind: 'workbench.bus.message'\n messageId: number\n meta: MessageBusMeta\n payload: unknown\n type: string\n }\n | {kind: 'workbench.bus.cancel'; messageId: number}\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, details?: RefusalDetails): Error =>\n Object.assign(new Error(message || code), {\n code,\n docsUrl: details?.docsUrl,\n fix: details?.fix,\n name: 'MessageBusError',\n })\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 web worker 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: WebWorkerBus\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 // The worker can't tell a state topic from an event topic, so it stores every\n // handler alike; the host's `value` or `message` decides how it is called.\n const subscriptions = new Map<number, (value: unknown) => unknown>()\n const inFlight = new Map<number, AbortController>()\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 // Matches the SDK's `invokeResponder`, so a responder behaves the same in a\n // worker as on the page.\n function respond(\n handler: (message: MessageBusMessage<unknown, unknown, string>) => unknown,\n {messageId, meta, payload, type}: Extract<HostMessage, {kind: 'workbench.bus.message'}>,\n ) {\n const controller = new AbortController()\n inFlight.set(messageId, controller)\n const answer = (result: Answer) => {\n if (inFlight.get(messageId) !== controller) return false\n inFlight.delete(messageId)\n self.postMessage({...result, kind: 'workbench.bus.answer', messageId})\n return true\n }\n const warnIfIgnored = (answered: boolean, action: string) => {\n if (answered) return\n // eslint-disable-next-line no-console -- the worker's console is bridged to the host logger\n console.warn(\n `Message bus ${action} ignored for \"${type}\": no waiting caller or already replied`,\n )\n }\n const fail = () => answer({error: {code: 'HANDLER_THREW', message: 'HANDLER_THREW'}, ok: false})\n\n try {\n const result = handler({\n meta,\n payload,\n reject: (reason) =>\n warnIfIgnored(\n answer({error: {code: 'REFUSED', message: reason ?? 'REFUSED'}, ok: false}),\n 'reject',\n ),\n reply: (value) => warnIfIgnored(answer({ok: true, value}), 'reply'),\n signal: controller.signal,\n type,\n })\n if (result instanceof Promise) result.catch(fail)\n } catch {\n fail()\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) => unknown, 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 WebWorkerBus,\n close: () => {\n closed = true\n subscriptions.clear()\n const controllers = [...inFlight.values()]\n inFlight.clear()\n for (const controller of controllers) controller.abort()\n for (const settle of pending.values()) settle({error: busError('ABORTED'), ok: false})\n },\n receive: (data) => {\n const message = data as HostMessage\n switch (message.kind) {\n case 'workbench.bus.cancel': {\n const controller = inFlight.get(message.messageId)\n // Forget it first so an abort listener's reply is ignored.\n inFlight.delete(message.messageId)\n controller?.abort()\n return\n }\n case 'workbench.bus.message': {\n const handler = subscriptions.get(message.id)\n if (handler) respond(handler, message)\n return\n }\n case '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. The Dashboard prints the refusal.\n subscriptions.delete(message.id)\n settle?.({\n error: busError(message.error.code, message.error.message, message.error),\n ok: false,\n })\n return\n }\n case 'workbench.bus.value': {\n subscriptions.get(message.id)?.(message.value)\n }\n }\n },\n }\n}\n"],"names":["DEFAULT_TIMEOUT_MS","busError","code","message","details","Object","assign","Error","docsUrl","fix","name","createWorkerBus","pending","Map","subscriptions","inFlight","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","respond","handler","messageId","meta","payload","type","controller","AbortController","answer","get","warnIfIgnored","answered","action","console","warn","fail","reason","reply","catch","bus","emit","topic","awaitReply","onRejected","then","finally","onFinally","onFulfilled","query","subscribe","close","clear","controllers","values","abort","receive","data"],"mappings":"AAAA,8EAA8E;AAC9E,6EAA6E;AAC7E,gCAAgC;AAUhC,MAAMA,qBAAqB;AAuC3B,4EAA4E;AAC5E,kCAAkC;AAClC,MAAMC,WAAW,CAACC,MAA2BC,SAAkBC,UAC7DC,OAAOC,MAAM,CAAC,IAAIC,MAAMJ,WAAWD,OAAO;QACxCA;QACAM,SAASJ,SAASI;QAClBC,KAAKL,SAASK;QACdC,MAAM;IACR;AAEF;;;;;CAKC,GACD,OAAO,SAASC;IAoBd,MAAMC,UAAU,IAAIC;IACpB,8EAA8E;IAC9E,2EAA2E;IAC3E,MAAMC,gBAAgB,IAAID;IAC1B,MAAME,WAAW,IAAIF;IACrB,IAAIG,SAAS;IACb,IAAIC,SAAS;IAEb,2EAA2E;IAC3E,4EAA4E;IAC5E,oFAAoF;IACpF,SAASC,QAAQf,OAAgC,EAAEgB,UAA0B,CAAC,CA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C9B;oBACF;gBACA,KAAK;oBAAuB;wBAC1B,MAAMuB,SAASd,QAAQ6C,GAAG,CAACtD,QAAQmB,EAAE;wBACrC,IAAInB,QAAQiC,EAAE,EAAE;4BACdV,SAAS;gCAACU,IAAI;gCAAMW,OAAO5C,QAAQ4C,KAAK;4BAAA;4BACxC;wBACF;wBACA,qFAAqF;wBACrFjC,cAAce,MAAM,CAAC1B,QAAQmB,EAAE;wBAC/BI,SAAS;4BACPS,OAAOlC,SAASE,QAAQgC,KAAK,CAACjC,IAAI,EAAEC,QAAQgC,KAAK,CAAChC,OAAO,EAAEA,QAAQgC,KAAK;4BACxEC,IAAI;wBACN;wBACA;oBACF;gBACA,KAAK;oBAAuB;wBAC1BtB,cAAc2C,GAAG,CAACtD,QAAQmB,EAAE,IAAInB,QAAQ4C,KAAK;oBAC/C;YACF;QACF;IACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/actions/deploy/getWorkbench.ts"],"sourcesContent":["// The deploy command's view of a workbench app: the resolved interfaces plus\n// the deploy-time guards that need the app's declarations. `sanity deploy` calls\n// `getWorkbench(config)` once and either gets `null` (plain project — normal\n// deploy) or an object it asks to validate the app before shipping.\n\nimport {type CliConfig} from '@sanity/cli-core'\n\nimport {type ResolvedWorkbenchApp, resolveWorkbenchApp} from '../../resolveWorkbenchApp.js'\nimport {buildViewDeploymentPayload, type ViewDeploymentPayload} from './viewDeployment.js'\n\nexport interface DeployableWorkbenchApp extends ResolvedWorkbenchApp {\n /**\n * Throws when the app exposes nothing (no entry, view, or
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/deploy/getWorkbench.ts"],"sourcesContent":["// The deploy command's view of a workbench app: the resolved interfaces plus\n// the deploy-time guards that need the app's declarations. `sanity deploy` calls\n// `getWorkbench(config)` once and either gets `null` (plain project — normal\n// deploy) or an object it asks to validate the app before shipping.\n\nimport {type CliConfig} from '@sanity/cli-core'\n\nimport {type ResolvedWorkbenchApp, resolveWorkbenchApp} from '../../resolveWorkbenchApp.js'\nimport {buildViewDeploymentPayload, type ViewDeploymentPayload} from './viewDeployment.js'\n\nexport interface DeployableWorkbenchApp extends ResolvedWorkbenchApp {\n /**\n * Throws when the app exposes nothing (no entry, view, or web worker) — the\n * remote would have nothing to load. Gated before any prompt or API call.\n */\n assertDeployable(): void\n /**\n * Validates the app's declared views into the application-service payload.\n * Throws when a view declaration is malformed.\n */\n buildViewDeploymentPayload(applicationId: string): ViewDeploymentPayload\n /** Declares something to host as an application — an entry, view, or web worker. */\n hasInterfaces: boolean\n}\n\nexport function getWorkbench(\n cliConfig: CliConfig | null | undefined,\n): DeployableWorkbenchApp | null {\n const app = resolveWorkbenchApp(cliConfig)\n if (!app) return null\n\n const {entry, views, webWorkers} = app\n\n return {\n ...app,\n\n hasInterfaces: !!entry || views.length > 0 || webWorkers.length > 0,\n\n assertDeployable() {\n if (!entry && views.length === 0 && webWorkers.length === 0) {\n throw new Error(\n 'Nothing to deploy: the app declares no entry, views or web workers. ' +\n 'Add at least one to the app config.',\n )\n }\n },\n\n buildViewDeploymentPayload(applicationId) {\n return buildViewDeploymentPayload({applicationId, views})\n },\n }\n}\n"],"names":["resolveWorkbenchApp","buildViewDeploymentPayload","getWorkbench","cliConfig","app","entry","views","webWorkers","hasInterfaces","length","assertDeployable","Error","applicationId"],"mappings":"AAAA,6EAA6E;AAC7E,iFAAiF;AACjF,6EAA6E;AAC7E,oEAAoE;AAIpE,SAAmCA,mBAAmB,QAAO,+BAA8B;AAC3F,SAAQC,0BAA0B,QAAmC,sBAAqB;AAiB1F,OAAO,SAASC,aACdC,SAAuC;IAEvC,MAAMC,MAAMJ,oBAAoBG;IAChC,IAAI,CAACC,KAAK,OAAO;IAEjB,MAAM,EAACC,KAAK,EAAEC,KAAK,EAAEC,UAAU,EAAC,GAAGH;IAEnC,OAAO;QACL,GAAGA,GAAG;QAENI,eAAe,CAAC,CAACH,SAASC,MAAMG,MAAM,GAAG,KAAKF,WAAWE,MAAM,GAAG;QAElEC;YACE,IAAI,CAACL,SAASC,MAAMG,MAAM,KAAK,KAAKF,WAAWE,MAAM,KAAK,GAAG;gBAC3D,MAAM,IAAIE,MACR,yEACE;YAEN;QACF;QAEAV,4BAA2BW,aAAa;YACtC,OAAOX,2BAA2B;gBAACW;gBAAeN;YAAK;QACzD;IACF;AACF"}
|
|
@@ -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
|
|
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 (
|
|
26
|
+
if (deployedWebWorkers.length > 0) lines.push(summarizeGroup('Web workers', deployedWebWorkers));
|
|
27
27
|
return {
|
|
28
28
|
lines,
|
|
29
|
-
services:
|
|
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
|
|
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/
|
|
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/
|
|
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/
|
|
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
|
|
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
|
|
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,C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AIE,QAAQ7B,GAAG,CAAC,CAACoB,SAAW;oBAACD,UAAUC;oBAASI,gBAAgBJ;iBAAQ;YACpF,OAAOU;QACT;IACF;AACF"}
|
|
@@ -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/
|
|
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/
|
|
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,OAAO,EACR,GAAGX;IAEJ,4EAA4E;IAC5E,0CAA0C;IAC1C,IAAIY,QAAQC,GAAG,CAACC,mCAAmC,KAAK,QAAQ;QAC9D,MAAMC,SAAS,MAAML,eAAe;YAACM,aAAa;YAAMb;YAAWG;QAAQ;QAC3E,IAAI,CAACS,OAAOE,OAAO,EAAE,OAAO;YAACC,OAAO,WAAa;QAAC;QAElD,MAAMC,cAAcrB,gCAAgC;YAACsB,QAAQL,OAAOK,MAAM;QAAA;QAE1E,OAAO;YACLF,OAAO;gBACL,MAAMC,YAAYD,K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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,9 @@
|
|
|
1
1
|
import { z } from 'zod/mini';
|
|
2
|
-
// Shared module-federation extension contract: interface (view/
|
|
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 =
|
|
6
|
-
/** @internal */ export const
|
|
5
|
+
/** @internal */ export const VIEW_CONTRACT_VERSION = 2;
|
|
6
|
+
/** @internal */ export const WEB_WORKER_CONTRACT_VERSION = 1;
|
|
7
7
|
/** @internal */ export const MEDIA_LIBRARY_CONFIG_CONTRACT_VERSION = 1;
|
|
8
8
|
/** Component slots per view surface; windows load outside the component artifact path. @internal */ export const VIEW_COMPONENTS = {
|
|
9
9
|
asset_source: [
|
|
@@ -61,7 +61,7 @@ const PanelDockSchema = z.object({
|
|
|
61
61
|
panel: VIEW_CONTRACT_VERSION,
|
|
62
62
|
tile: VIEW_CONTRACT_VERSION,
|
|
63
63
|
window: undefined,
|
|
64
|
-
worker:
|
|
64
|
+
worker: WEB_WORKER_CONTRACT_VERSION
|
|
65
65
|
};
|
|
66
66
|
/** @internal */ export function interfaceContractVersion(kind) {
|
|
67
67
|
const version = INTERFACE_CONTRACT_VERSIONS[kind];
|
|
@@ -169,7 +169,7 @@ const WebWorkerSchema = z.object({
|
|
|
169
169
|
type: 'worker'
|
|
170
170
|
};
|
|
171
171
|
}
|
|
172
|
-
/** @internal */ export const
|
|
172
|
+
/** @internal */ export const WebWorkerDeclarationSchema = z.discriminatedUnion('type', [
|
|
173
173
|
WebWorkerSchema
|
|
174
174
|
]);
|
|
175
175
|
const MediaLibraryFieldSchema = z.object({
|