@sanity/workbench-cli 2.14.1 → 2.15.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/dist/_exports/_internal_auto_updates.d.ts +14 -0
  2. package/dist/_exports/_internal_auto_updates.js +3 -0
  3. package/dist/_exports/_internal_auto_updates.js.map +1 -0
  4. package/dist/_exports/_internal_worker_bus.d.ts +1 -1
  5. package/dist/_exports/build.d.ts +8 -0
  6. package/dist/_exports/{defineService-D_DFLM8x.d.ts → defineService-DPZwNN6_.d.ts} +5 -2
  7. package/dist/_exports/deploy.d.ts +15 -1
  8. package/dist/_exports/deploy.js +1 -0
  9. package/dist/_exports/deploy.js.map +1 -1
  10. package/dist/_exports/dev.d.ts +1 -1
  11. package/dist/_exports/index.d.ts +1 -1
  12. package/dist/_exports/preview.d.ts +1 -1
  13. package/dist/_exports/{registry-DCjjQ1sS.d.ts → registry-NvtHmoN1.d.ts} +3 -1
  14. package/dist/actions/build/autoUpdatesLoader.js +36 -0
  15. package/dist/actions/build/autoUpdatesLoader.js.map +1 -0
  16. package/dist/actions/build/configs/mediaLibraryIslandRuntime.js +2 -3
  17. package/dist/actions/build/configs/mediaLibraryIslandRuntime.js.map +1 -1
  18. package/dist/actions/build/render-remote.js +23 -7
  19. package/dist/actions/build/render-remote.js.map +1 -1
  20. package/dist/actions/build/services/workerBus.js +6 -7
  21. package/dist/actions/build/services/workerBus.js.map +1 -1
  22. package/dist/actions/build/vite/plugin.js +3 -1
  23. package/dist/actions/build/vite/plugin.js.map +1 -1
  24. package/dist/actions/build/vite/plugins/plugin-sanity-app-styles.js +61 -0
  25. package/dist/actions/build/vite/plugins/plugin-sanity-app-styles.js.map +1 -0
  26. package/dist/actions/build/vite/plugins/plugin-sanity-auto-updates.js +125 -0
  27. package/dist/actions/build/vite/plugins/plugin-sanity-auto-updates.js.map +1 -0
  28. package/dist/actions/build/vite/plugins/plugin-sanity-federation-runtime.js +3 -1
  29. package/dist/actions/build/vite/plugins/plugin-sanity-federation-runtime.js.map +1 -1
  30. package/dist/actions/build/vite/workbench-vite-plugins.js +8 -2
  31. package/dist/actions/build/vite/workbench-vite-plugins.js.map +1 -1
  32. package/dist/actions/deploy/selectWorkbenchAppId.js +31 -0
  33. package/dist/actions/deploy/selectWorkbenchAppId.js.map +1 -0
  34. package/dist/actions/dev/registry.js +30 -6
  35. package/dist/actions/dev/registry.js.map +1 -1
  36. package/dist/actions/dev/startDevServerRegistration.js +14 -20
  37. package/dist/actions/dev/startDevServerRegistration.js.map +1 -1
  38. package/dist/actions/dev/startWorkbenchDevServer.js +2 -1
  39. package/dist/actions/dev/startWorkbenchDevServer.js.map +1 -1
  40. package/dist/actions/preview/startWorkbenchPreview.js +6 -5
  41. package/dist/actions/preview/startWorkbenchPreview.js.map +1 -1
  42. package/dist/defineApp.js +4 -1
  43. package/dist/defineApp.js.map +1 -1
  44. package/dist/defineService.js +4 -1
  45. package/dist/defineService.js.map +1 -1
  46. package/package.json +15 -11
@@ -0,0 +1,14 @@
1
+ type Module = Record<string, unknown>;
2
+ interface AutoUpdatesLoaderOptions {
3
+ appId: string;
4
+ cssUrls: string[];
5
+ imports: Record<string, string>;
6
+ specifiers: string[];
7
+ vendor: Record<string, () => Promise<Module>>;
8
+ }
9
+ declare function createAutoUpdatesLoader({ appId, cssUrls, imports, specifiers, vendor }: AutoUpdatesLoaderOptions): {
10
+ importMapUrl: (specifier: string) => string | undefined;
11
+ load: (specifier: string) => Promise<Module>;
12
+ };
13
+ export { createAutoUpdatesLoader };
14
+ //# sourceMappingURL=_internal_auto_updates.d.ts.map
@@ -0,0 +1,3 @@
1
+ export { createAutoUpdatesLoader } from '../actions/build/autoUpdatesLoader.js';
2
+
3
+ //# sourceMappingURL=_internal_auto_updates.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/_exports/_internal_auto_updates.ts"],"sourcesContent":["export {createAutoUpdatesLoader} from '../actions/build/autoUpdatesLoader.js'\n"],"names":["createAutoUpdatesLoader"],"mappings":"AAAA,SAAQA,uBAAuB,QAAO,wCAAuC"}
@@ -1,4 +1,4 @@
1
- import { n as ServiceBus } from "./defineService-D_DFLM8x.js";
1
+ import { n as ServiceBus } from "./defineService-DPZwNN6_.js";
2
2
  /**
3
3
  * The worker's side of the `workbench.bus.*` wire contract. The host relays
4
4
  * each request to the Dashboard bus and stamps it with the worker's identity,
@@ -91,6 +91,13 @@ declare function workbenchOptimizeDeps(options: {
91
91
  entries: string[];
92
92
  include: string[];
93
93
  };
94
+ interface AutoUpdates {
95
+ imports: Record<string, string>;
96
+ vendor: {
97
+ specifiersByChunkName: Record<string, string>;
98
+ };
99
+ cssUrls?: string[];
100
+ }
94
101
  interface WorkbenchViteOptions {
95
102
  /** Project root — read for the federation remote name, and the plugin workDir. */
96
103
  cwd: string;
@@ -105,6 +112,7 @@ interface WorkbenchViteOptions {
105
112
  };
106
113
  /** The app's bus identity, stamped into its modules for `@sanity/runtime`. */
107
114
  appId?: string;
115
+ autoUpdates?: AutoUpdates;
108
116
  exposes?: WorkbenchExposes;
109
117
  /** App (vs studio) build — selects the discriminated federation option shape. */
110
118
  isApp?: boolean;
@@ -61,7 +61,10 @@ interface DefinedService<TType extends ServiceType = ServiceType> {
61
61
  * new value of a state topic, or on each event of an event topic, until its
62
62
  * `signal` aborts. A refused, unanswered or timed-out `emit` or `query` rejects
63
63
  * with an `Error` named `MessageBusError` whose `code` says why; it is not an
64
- * instance of the SDK's `MessageBusError` class.
64
+ * instance of the SDK's `MessageBusError` class. When the Dashboard's refusal
65
+ * says how to fix it, the error also carries `fix` and `docsUrl`. A refused
66
+ * `subscribe` has no error: its handler never runs, and the Dashboard reports
67
+ * the refusal in the browser console.
65
68
  *
66
69
  * An event handler answers the sender with `message.reply(value)` or refuses
67
70
  * with `message.reject(reason)`; one that throws refuses with code
@@ -93,4 +96,4 @@ interface DefinedService<TType extends ServiceType = ServiceType> {
93
96
  */
94
97
  declare function unstable_defineService<TType extends ServiceType>(type: TType, run: ServiceCallbacksByType[TType]): DefinedService<TType>;
95
98
  export { ServiceInfo as a, ServiceContext as i, ServiceBus as n, unstable_defineService as o, ServiceCallback as r, DefinedService as t };
96
- //# sourceMappingURL=defineService-D_DFLM8x.d.ts.map
99
+ //# sourceMappingURL=defineService-DPZwNN6_.d.ts.map
@@ -167,5 +167,19 @@ declare function deployWorkbenchApp(options: {
167
167
  visibility?: AppVisibility;
168
168
  workspaces?: readonly BrettWorkspace[];
169
169
  }): Promise<void>;
170
- export { type Application, type BrettAccess, type BrettWorkspace, type CreatedApplication, type DeployedInterface, type DeployedView, type DeployedWebWorker, type ResolvedMediaLibraryConfig, type WorkbenchDeployPayload, createCoreApp, createStudio, deployConfig, deployWorkbenchApp, getApplication, getApplicationUrl, getWorkbench, getWorkbenchUrl, listApplications, resolveInstallationId, resolveWorkbenchConfig, summarizeConfig, summarizeInterfaces, toWorkbenchPayload };
170
+ /**
171
+ * Offers an interactive deploy without `deployment.appId` the organization's
172
+ * applications of `type`. Returns the configured or picked id; undefined creates one.
173
+ * @internal
174
+ */
175
+ declare function selectWorkbenchAppId({ appId, flags, organizationId, type }: {
176
+ appId: string | undefined;
177
+ flags: {
178
+ build: boolean;
179
+ yes: boolean;
180
+ };
181
+ organizationId: string | undefined;
182
+ type: ApplicationType;
183
+ }): Promise<string | undefined>;
184
+ export { type Application, type BrettAccess, type BrettWorkspace, type CreatedApplication, type DeployedInterface, type DeployedView, type DeployedWebWorker, type ResolvedMediaLibraryConfig, type WorkbenchDeployPayload, createCoreApp, createStudio, deployConfig, deployWorkbenchApp, getApplication, getApplicationUrl, getWorkbench, getWorkbenchUrl, listApplications, resolveInstallationId, resolveWorkbenchConfig, selectWorkbenchAppId, summarizeConfig, summarizeInterfaces, toWorkbenchPayload };
171
185
  //# sourceMappingURL=deploy.d.ts.map
@@ -2,6 +2,7 @@ export { deployConfig, resolveInstallationId, summarizeConfig } from '../actions
2
2
  export { toWorkbenchPayload } from '../actions/deploy/deployPayload.js';
3
3
  export { createCoreApp, createStudio, deployWorkbenchApp } from '../actions/deploy/deployWorkbenchApp.js';
4
4
  export { getWorkbench } from '../actions/deploy/getWorkbench.js';
5
+ export { selectWorkbenchAppId } from '../actions/deploy/selectWorkbenchAppId.js';
5
6
  export { summarizeInterfaces } from '../actions/deploy/summarizeInterfaces.js';
6
7
  export { resolveWorkbenchConfig } from '../resolveWorkbenchConfig.js';
7
8
  export { getApplication, getApplicationUrl, getWorkbenchUrl, listApplications } from '../services/applications.js';
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/_exports/deploy.ts"],"sourcesContent":["export {\n deployConfig,\n resolveInstallationId,\n summarizeConfig,\n} from '../actions/deploy/deployConfig.js'\nexport {toWorkbenchPayload, type WorkbenchDeployPayload} from '../actions/deploy/deployPayload.js'\nexport {\n createCoreApp,\n type CreatedApplication,\n createStudio,\n deployWorkbenchApp,\n} from '../actions/deploy/deployWorkbenchApp.js'\nexport {getWorkbench} from '../actions/deploy/getWorkbench.js'\nexport {\n type DeployedInterface,\n type DeployedView,\n type DeployedWebWorker,\n summarizeInterfaces,\n} from '../actions/deploy/summarizeInterfaces.js'\nexport {type ResolvedMediaLibraryConfig, resolveWorkbenchConfig} from '../resolveWorkbenchConfig.js'\nexport {\n type Application,\n type BrettAccess,\n type BrettWorkspace,\n getApplication,\n getApplicationUrl,\n getWorkbenchUrl,\n listApplications,\n} from '../services/applications.js'\n"],"names":["deployConfig","resolveInstallationId","summarizeConfig","toWorkbenchPayload","createCoreApp","createStudio","deployWorkbenchApp","getWorkbench","summarizeInterfaces","resolveWorkbenchConfig","getApplication","getApplicationUrl","getWorkbenchUrl","listApplications"],"mappings":"AAAA,SACEA,YAAY,EACZC,qBAAqB,EACrBC,eAAe,QACV,oCAAmC;AAC1C,SAAQC,kBAAkB,QAAoC,qCAAoC;AAClG,SACEC,aAAa,EAEbC,YAAY,EACZC,kBAAkB,QACb,0CAAyC;AAChD,SAAQC,YAAY,QAAO,oCAAmC;AAC9D,SAIEC,mBAAmB,QACd,2CAA0C;AACjD,SAAyCC,sBAAsB,QAAO,+BAA8B;AACpG,SAIEC,cAAc,EACdC,iBAAiB,EACjBC,eAAe,EACfC,gBAAgB,QACX,8BAA6B"}
1
+ {"version":3,"sources":["../../src/_exports/deploy.ts"],"sourcesContent":["export {\n deployConfig,\n resolveInstallationId,\n summarizeConfig,\n} from '../actions/deploy/deployConfig.js'\nexport {toWorkbenchPayload, type WorkbenchDeployPayload} from '../actions/deploy/deployPayload.js'\nexport {\n createCoreApp,\n type CreatedApplication,\n createStudio,\n deployWorkbenchApp,\n} from '../actions/deploy/deployWorkbenchApp.js'\nexport {getWorkbench} from '../actions/deploy/getWorkbench.js'\nexport {selectWorkbenchAppId} from '../actions/deploy/selectWorkbenchAppId.js'\nexport {\n type DeployedInterface,\n type DeployedView,\n type DeployedWebWorker,\n summarizeInterfaces,\n} from '../actions/deploy/summarizeInterfaces.js'\nexport {type ResolvedMediaLibraryConfig, resolveWorkbenchConfig} from '../resolveWorkbenchConfig.js'\nexport {\n type Application,\n type BrettAccess,\n type BrettWorkspace,\n getApplication,\n getApplicationUrl,\n getWorkbenchUrl,\n listApplications,\n} from '../services/applications.js'\n"],"names":["deployConfig","resolveInstallationId","summarizeConfig","toWorkbenchPayload","createCoreApp","createStudio","deployWorkbenchApp","getWorkbench","selectWorkbenchAppId","summarizeInterfaces","resolveWorkbenchConfig","getApplication","getApplicationUrl","getWorkbenchUrl","listApplications"],"mappings":"AAAA,SACEA,YAAY,EACZC,qBAAqB,EACrBC,eAAe,QACV,oCAAmC;AAC1C,SAAQC,kBAAkB,QAAoC,qCAAoC;AAClG,SACEC,aAAa,EAEbC,YAAY,EACZC,kBAAkB,QACb,0CAAyC;AAChD,SAAQC,YAAY,QAAO,oCAAmC;AAC9D,SAAQC,oBAAoB,QAAO,4CAA2C;AAC9E,SAIEC,mBAAmB,QACd,2CAA0C;AACjD,SAAyCC,sBAAsB,QAAO,+BAA8B;AACpG,SAIEC,cAAc,EACdC,iBAAiB,EACjBC,eAAe,EACfC,gBAAgB,QACX,8BAA6B"}
@@ -1,4 +1,4 @@
1
- import { t as DevServerManifest } from "./registry-DCjjQ1sS.js";
1
+ import { t as DevServerManifest } from "./registry-NvtHmoN1.js";
2
2
  import { ViteDevServer } from "vite";
3
3
  import { CliConfig, Output } from "@sanity/cli-core";
4
4
  /**
@@ -1,5 +1,5 @@
1
1
  import { C as defineTileView, S as definePanelView, T as defineWindowView, _ as ViewSurface, a as DefineWebWorkerInput, c as PanelView, d as TileSize, f as TileView, g as ViewDeclaration, h as ViewComponentBaseProps, i as DefineTileViewInput, m as ViewComponent, n as DefineAssetSourceViewInput, o as DefineWindowViewInput, p as VIEW_CONTRACT_VERSION, r as DefinePanelViewInput, s as DockGroup, t as AssetSourceView, u as ServiceType, v as WebWorker, w as defineWebWorker, x as defineAssetSourceView, y as WindowView } from "./contract-C4Y6gi-b.js";
2
- import { a as ServiceInfo, i as ServiceContext, n as ServiceBus, o as unstable_defineService, r as ServiceCallback, t as DefinedService } from "./defineService-D_DFLM8x.js";
2
+ import { a as ServiceInfo, i as ServiceContext, n as ServiceBus, o as unstable_defineService, r as ServiceCallback, t as DefinedService } from "./defineService-DPZwNN6_.js";
3
3
  import { a as WorkbenchApp, c as isWorkbenchApp, i as MediaLibraryField, l as isWorkbenchConfig, n as DefineAppResult, o as WorkbenchConfig, r as DefineMediaLibraryInput, s as defineApplication, t as DefineAppInput, u as unstable_defineMediaLibrary } from "./defineApp-vbUu_rBA.js";
4
4
  import { AssetSourceComponentProps } from "@sanity/types";
5
5
  /** @public */
@@ -1,4 +1,4 @@
1
- import { t as DevServerManifest } from "./registry-DCjjQ1sS.js";
1
+ import { t as DevServerManifest } from "./registry-NvtHmoN1.js";
2
2
  import { CliConfig, Output } from "@sanity/cli-core";
3
3
  interface StartWorkbenchPreviewOptions {
4
4
  /** Directory for the workbench Vite server's dependency cache. */
@@ -1,5 +1,7 @@
1
+ import "./defineApp-vbUu_rBA.js";
1
2
  import { z } from "zod/mini";
2
3
  declare const devServerManifestSchema: z.ZodMiniObject<{
4
+ applicationId: z.ZodMiniOptional<z.ZodMiniString<string>>;
3
5
  configs: z.ZodMiniOptional<z.ZodMiniArray<z.ZodMiniObject<{
4
6
  appType: z.ZodMiniOptional<z.ZodMiniString<string>>;
5
7
  fields: z.ZodMiniArray<z.ZodMiniObject<{
@@ -127,4 +129,4 @@ declare const devServerManifestSchema: z.ZodMiniObject<{
127
129
  */
128
130
  type DevServerManifest = z.infer<typeof devServerManifestSchema>;
129
131
  export { DevServerManifest as t };
130
- //# sourceMappingURL=registry-DCjjQ1sS.d.ts.map
132
+ //# sourceMappingURL=registry-NvtHmoN1.d.ts.map
@@ -0,0 +1,36 @@
1
+ const TIMESTAMP = /(\/(?:by-app|default)\/[^/]+)\/t\d+/;
2
+ // Loads the app's auto-updated packages from the module server as its own copy.
3
+ export function createAutoUpdatesLoader({ appId, cssUrls, imports, specifiers, vendor }) {
4
+ // The build's timestamp would pin the versions the module CDN served on build day.
5
+ const timestamp = `/t${Math.floor(Date.now() / 1000)}`;
6
+ const currentImports = Object.fromEntries(Object.entries(imports).map(([specifier, url])=>[
7
+ specifier,
8
+ url.replace(TIMESTAMP, `$1${timestamp}`)
9
+ ]));
10
+ let modules;
11
+ let ready;
12
+ return {
13
+ importMapUrl: (specifier)=>modules ? currentImports[specifier] : undefined,
14
+ load
15
+ };
16
+ async function load(specifier) {
17
+ ready ??= prepare();
18
+ await ready;
19
+ if (!modules) throw new Error("Couldn't load auto-updated packages: the Dashboard doesn't provide the auto-update loader. Contact Sanity support.");
20
+ const module = modules?.[specifier];
21
+ if (!module) throw new Error(`${specifier} was not loaded from the module server`);
22
+ return module;
23
+ }
24
+ async function prepare() {
25
+ const workbench = globalThis[Symbol.for('sanity.autoUpdates')];
26
+ const result = await workbench?.versions?.[1]?.(appId, {
27
+ imports: currentImports,
28
+ specifiers,
29
+ styles: cssUrls.map((url)=>url.replace(TIMESTAMP, `$1${timestamp}`)),
30
+ vendor
31
+ });
32
+ modules = result?.modules;
33
+ }
34
+ }
35
+
36
+ //# sourceMappingURL=autoUpdatesLoader.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/actions/build/autoUpdatesLoader.ts"],"sourcesContent":["type Module = Record<string, unknown>\n\n// Workbench's `load`, contract version 1: it loads every specifier as the app's own copy, with its\n// app ID and vendor modules, and links the stylesheets.\ntype Load = (\n appId: string,\n request: {\n imports: Record<string, string>\n specifiers: string[]\n styles: string[]\n vendor: Record<string, () => Promise<Module>>\n },\n) => Promise<{modules: Record<string, Module>}>\n\ninterface AutoUpdatesLoaderOptions {\n appId: string\n cssUrls: string[]\n imports: Record<string, string>\n specifiers: string[]\n vendor: Record<string, () => Promise<Module>>\n}\n\nconst TIMESTAMP = /(\\/(?:by-app|default)\\/[^/]+)\\/t\\d+/\n\n// Loads the app's auto-updated packages from the module server as its own copy.\nexport function createAutoUpdatesLoader({\n appId,\n cssUrls,\n imports,\n specifiers,\n vendor,\n}: AutoUpdatesLoaderOptions) {\n // The build's timestamp would pin the versions the module CDN served on build day.\n const timestamp = `/t${Math.floor(Date.now() / 1000)}`\n const currentImports = Object.fromEntries(\n Object.entries(imports).map(([specifier, url]) => [\n specifier,\n url.replace(TIMESTAMP, `$1${timestamp}`),\n ]),\n )\n let modules: Record<string, Module> | undefined\n let ready: Promise<void> | undefined\n\n return {\n importMapUrl: (specifier: string) => (modules ? currentImports[specifier] : undefined),\n load,\n }\n\n async function load(specifier: string): Promise<Module> {\n ready ??= prepare()\n await ready\n if (!modules)\n throw new Error(\n \"Couldn't load auto-updated packages: the Dashboard doesn't provide the auto-update loader. Contact Sanity support.\",\n )\n\n const module = modules?.[specifier]\n if (!module) throw new Error(`${specifier} was not loaded from the module server`)\n\n return module\n }\n\n async function prepare(): Promise<void> {\n const workbench = (\n globalThis as {[key: symbol]: {versions?: Record<number, Load>} | undefined}\n )[Symbol.for('sanity.autoUpdates')]\n const result = await workbench?.versions?.[1]?.(appId, {\n imports: currentImports,\n specifiers,\n styles: cssUrls.map((url) => url.replace(TIMESTAMP, `$1${timestamp}`)),\n vendor,\n })\n modules = result?.modules\n }\n}\n"],"names":["TIMESTAMP","createAutoUpdatesLoader","appId","cssUrls","imports","specifiers","vendor","timestamp","Math","floor","Date","now","currentImports","Object","fromEntries","entries","map","specifier","url","replace","modules","ready","importMapUrl","undefined","load","prepare","Error","module","workbench","globalThis","Symbol","for","result","versions","styles"],"mappings":"AAsBA,MAAMA,YAAY;AAElB,gFAAgF;AAChF,OAAO,SAASC,wBAAwB,EACtCC,KAAK,EACLC,OAAO,EACPC,OAAO,EACPC,UAAU,EACVC,MAAM,EACmB;IACzB,mFAAmF;IACnF,MAAMC,YAAY,CAAC,EAAE,EAAEC,KAAKC,KAAK,CAACC,KAAKC,GAAG,KAAK,OAAO;IACtD,MAAMC,iBAAiBC,OAAOC,WAAW,CACvCD,OAAOE,OAAO,CAACX,SAASY,GAAG,CAAC,CAAC,CAACC,WAAWC,IAAI,GAAK;YAChDD;YACAC,IAAIC,OAAO,CAACnB,WAAW,CAAC,EAAE,EAAEO,WAAW;SACxC;IAEH,IAAIa;IACJ,IAAIC;IAEJ,OAAO;QACLC,cAAc,CAACL,YAAuBG,UAAUR,cAAc,CAACK,UAAU,GAAGM;QAC5EC;IACF;IAEA,eAAeA,KAAKP,SAAiB;QACnCI,UAAUI;QACV,MAAMJ;QACN,IAAI,CAACD,SACH,MAAM,IAAIM,MACR;QAGJ,MAAMC,SAASP,SAAS,CAACH,UAAU;QACnC,IAAI,CAACU,QAAQ,MAAM,IAAID,MAAM,GAAGT,UAAU,sCAAsC,CAAC;QAEjF,OAAOU;IACT;IAEA,eAAeF;QACb,MAAMG,YAAY,AAChBC,UACD,CAACC,OAAOC,GAAG,CAAC,sBAAsB;QACnC,MAAMC,SAAS,MAAMJ,WAAWK,UAAU,CAAC,EAAE,GAAG/B,OAAO;YACrDE,SAASQ;YACTP;YACA6B,QAAQ/B,QAAQa,GAAG,CAAC,CAACE,MAAQA,IAAIC,OAAO,CAACnB,WAAW,CAAC,EAAE,EAAEO,WAAW;YACpED;QACF;QACAc,UAAUY,QAAQZ;IACpB;AACF"}
@@ -1,5 +1,4 @@
1
- import { createRequire } from 'node:module';
2
- import path from 'node:path';
1
+ import { resolveLocalPackagePath } from '@sanity/cli-core';
3
2
  /**
4
3
  * The `sanity` package entry carrying the Media Library island-mount runtime
5
4
  * (`mountIsland`). The generated `./media-library-island-runtime` federation
@@ -15,7 +14,7 @@ import path from 'node:path';
15
14
  * for custom inputs.
16
15
  */ export function hasMediaLibraryIslandRuntime(appRoot) {
17
16
  try {
18
- createRequire(path.join(appRoot, 'package.json')).resolve(MEDIA_LIBRARY_ISLAND_RUNTIME_MODULE);
17
+ resolveLocalPackagePath(MEDIA_LIBRARY_ISLAND_RUNTIME_MODULE, appRoot);
19
18
  return true;
20
19
  } catch {
21
20
  return false;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/actions/build/configs/mediaLibraryIslandRuntime.ts"],"sourcesContent":["import {createRequire} from 'node:module'\nimport path from 'node:path'\n\n/**\n * The `sanity` package entry carrying the Media Library island-mount runtime\n * (`mountIsland`). The generated `./media-library-island-runtime` federation\n * expose re-exports it, so the runtime is bundled into the config app's\n * remote from the app's own `sanity` install — whichever version the app\n * installs brings a matching runtime.\n */\nexport const MEDIA_LIBRARY_ISLAND_RUNTIME_MODULE = 'sanity/media-library-island-runtime'\n\n/**\n * Whether the config app's installed `sanity` ships the island runtime entry.\n * Older `sanity` versions don't; exposing a module whose import can never\n * resolve would fail the whole build, so the expose is skipped (with a\n * warning) and the Media Library host falls back to its degraded rendering\n * for custom inputs.\n */\nexport function hasMediaLibraryIslandRuntime(appRoot: string): boolean {\n try {\n createRequire(path.join(appRoot, 'package.json')).resolve(MEDIA_LIBRARY_ISLAND_RUNTIME_MODULE)\n return true\n } catch {\n return false\n }\n}\n"],"names":["createRequire","path","MEDIA_LIBRARY_ISLAND_RUNTIME_MODULE","hasMediaLibraryIslandRuntime","appRoot","join","resolve"],"mappings":"AAAA,SAAQA,aAAa,QAAO,cAAa;AACzC,OAAOC,UAAU,YAAW;AAE5B;;;;;;CAMC,GACD,OAAO,MAAMC,sCAAsC,sCAAqC;AAExF;;;;;;CAMC,GACD,OAAO,SAASC,6BAA6BC,OAAe;IAC1D,IAAI;QACFJ,cAAcC,KAAKI,IAAI,CAACD,SAAS,iBAAiBE,OAAO,CAACJ;QAC1D,OAAO;IACT,EAAE,OAAM;QACN,OAAO;IACT;AACF"}
1
+ {"version":3,"sources":["../../../../src/actions/build/configs/mediaLibraryIslandRuntime.ts"],"sourcesContent":["import {resolveLocalPackagePath} from '@sanity/cli-core'\n\n/**\n * The `sanity` package entry carrying the Media Library island-mount runtime\n * (`mountIsland`). The generated `./media-library-island-runtime` federation\n * expose re-exports it, so the runtime is bundled into the config app's\n * remote from the app's own `sanity` install — whichever version the app\n * installs brings a matching runtime.\n */\nexport const MEDIA_LIBRARY_ISLAND_RUNTIME_MODULE = 'sanity/media-library-island-runtime'\n\n/**\n * Whether the config app's installed `sanity` ships the island runtime entry.\n * Older `sanity` versions don't; exposing a module whose import can never\n * resolve would fail the whole build, so the expose is skipped (with a\n * warning) and the Media Library host falls back to its degraded rendering\n * for custom inputs.\n */\nexport function hasMediaLibraryIslandRuntime(appRoot: string): boolean {\n try {\n resolveLocalPackagePath(MEDIA_LIBRARY_ISLAND_RUNTIME_MODULE, appRoot)\n return true\n } catch {\n return false\n }\n}\n"],"names":["resolveLocalPackagePath","MEDIA_LIBRARY_ISLAND_RUNTIME_MODULE","hasMediaLibraryIslandRuntime","appRoot"],"mappings":"AAAA,SAAQA,uBAAuB,QAAO,mBAAkB;AAExD;;;;;;CAMC,GACD,OAAO,MAAMC,sCAAsC,sCAAqC;AAExF;;;;;;CAMC,GACD,OAAO,SAASC,6BAA6BC,OAAe;IAC1D,IAAI;QACFH,wBAAwBC,qCAAqCE;QAC7D,OAAO;IACT,EAAE,OAAM;QACN,OAAO;IACT;AACF"}
@@ -12,6 +12,7 @@ const HMR_REMOUNT = `if (import.meta.hot) {
12
12
  for (const [rootElement, args] of renderArgs) {
13
13
  rootMap.get(rootElement)?.unmount()
14
14
  rootMap.delete(rootElement)
15
+ closeRoot(rootElement)
15
16
  args.next = next.render(rootElement, args.props, args.renderOptions)
16
17
  args.next.setLifecycle(args.lifecycle)
17
18
  }
@@ -31,13 +32,14 @@ import { createRoot } from 'react-dom/client'
31
32
  ${stylesheetImport}
32
33
  ${preamble}
33
34
  ${app ? `\nconst App = ${app}\n` : ''}${version ? `\nexport const version = ${version}\n` : ''}
34
- // The SDK reads this slot via getDashboardModuleContext(), so its symbol, key and
35
- // value are a contract. Keyed by createContext, not the React namespace: Vite dev
36
- // pre-bundling can give two importers of one React copy different namespaces.
37
- const moduleSlot = (globalThis[Symbol.for('sanity.os.module')] ??= new WeakMap())
38
- if (!moduleSlot.has(React.createContext)) moduleSlot.set(React.createContext, React.createContext(undefined))
39
- const ModuleContext = moduleSlot.get(React.createContext)
35
+ // The SDK reads this slot via getDashboardRootContext(), so its symbol, key and value are a
36
+ // contract. Keyed by createContext, not the React namespace: Vite dev pre-bundling can give two
37
+ // importers of one React copy different namespaces.
38
+ const rootSlot = (globalThis[Symbol.for('sanity.os.root')] ??= new WeakMap())
39
+ if (!rootSlot.has(React.createContext)) rootSlot.set(React.createContext, React.createContext(undefined))
40
+ const RootContext = rootSlot.get(React.createContext)
40
41
  const rootMap = new Map()
42
+ const rootContexts = new Map()
41
43
  // A shared default sheet can overwrite another app's global rules; each root needs its own sheet.
42
44
  const styleTargets = new Map()
43
45
  const stylisPlugins = new Map()
@@ -52,20 +54,33 @@ function uniqueStylisPlugin() {
52
54
  return Object.defineProperty(() => {}, 'name', { value: 'sanity-root-' + globalThis[stylisPluginCount] })
53
55
  }
54
56
 
57
+ // The SDK disposes the root's instance, closing its bus connection, when the signal aborts. Next tick:
58
+ // a host disposing a child root from its own cleanup code leaves the child still unmounting.
59
+ function closeRoot(rootElement) {
60
+ const closing = rootContexts.get(rootElement)
61
+ rootContexts.delete(rootElement)
62
+ if (closing) setTimeout(() => closing.controller.abort(), 0)
63
+ }
64
+
55
65
  function mount(rootElement, args) {
56
66
  let root = rootMap.get(rootElement)
57
67
  if (!root) {
58
68
  root = createRoot(rootElement, args?.renderOptions?.rootOptions)
59
69
  rootMap.set(rootElement, root)
70
+ const controller = new AbortController()
71
+ // Read once: the SDK pins the root's bus identity when it first connects.
72
+ const { moduleId, parentKey } = args?.renderOptions ?? {}
73
+ rootContexts.set(rootElement, { controller, value: { signal: controller.signal, moduleId, parentKey } })
60
74
  if (StyleSheetManager) {
61
75
  const target = rootElement.ownerDocument.createElement('sanity-styles')
76
+ if (typeof __SANITY_APP_ID__ === 'string') target.setAttribute('data-application-id', __SANITY_APP_ID__)
62
77
  // React can replace the mount node's contents; keep its stylesheet outside that node.
63
78
  rootElement.ownerDocument.head.appendChild(target)
64
79
  styleTargets.set(rootElement, target)
65
80
  stylisPlugins.set(rootElement, [uniqueStylisPlugin()])
66
81
  }
67
82
  }
68
- let element = React.createElement(ModuleContext.Provider, { value: args?.renderOptions?.moduleId }, React.createElement(App, args.props))
83
+ let element = React.createElement(RootContext.Provider, { value: rootContexts.get(rootElement).value }, React.createElement(App, args.props))
69
84
  if (StyleSheetManager) element = React.createElement(StyleSheetManager, { target: styleTargets.get(rootElement), stylisPlugins: stylisPlugins.get(rootElement) }, element)
70
85
  // The host's React can't pause this root, so the host pauses the app through this Activity.
71
86
  // Keep it inside StrictMode: outside, it stops StrictMode double-invoking effects.
@@ -90,6 +105,7 @@ export function render(rootElement, props, renderOptions) {
90
105
  styleTargets.get(rootElement)?.remove()
91
106
  styleTargets.delete(rootElement)
92
107
  stylisPlugins.delete(rootElement)
108
+ closeRoot(rootElement)
93
109
  },
94
110
  setLifecycle(state) {
95
111
  const current = renderArgs.get(rootElement)
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/actions/build/render-remote.ts"],"sourcesContent":["/**\n * Every generated entry (studio, SDK app, view artifacts) shares one render body\n * so the host can drive them all the same way; only the `App` they bind differs.\n * The workbench host depends on `render`'s signature and return shape, so change\n * them together.\n */\n\n// Re-renders through the new module so edits apply without a page reload. The\n// new module mounts in the foreground, so reapply the host's lifecycle. The host\n// still holds this module's controller, so it forwards to the new one.\nconst HMR_REMOUNT = `if (import.meta.hot) {\n import.meta.hot.accept((next) => {\n if (!next) return\n for (const [rootElement, args] of renderArgs) {\n rootMap.get(rootElement)?.unmount()\n rootMap.delete(rootElement)\n args.next = next.render(rootElement, args.props, args.renderOptions)\n args.next.setLifecycle(args.lifecycle)\n }\n })\n}`\n\n/**\n * - `app`: omit when the preamble imports `App` itself (the SDK-app entry).\n * - `version`: lets the host check view/service contract compatibility.\n */\nexport function renderRemote({\n app,\n hmr = false,\n isolateStyles = false,\n preamble,\n version,\n}: {\n app?: string\n hmr?: boolean\n isolateStyles?: boolean\n preamble: string\n version?: string\n}): string {\n // Keep apps without styled-components buildable; the unused branch is removed from their bundle.\n const stylesheetImport = isolateStyles\n ? \"import { StyleSheetManager } from 'styled-components'\"\n : 'const StyleSheetManager = undefined'\n\n return `\\\n// This file is auto-generated on 'sanity build' / 'sanity dev'\n// Modifications to this file are automatically discarded\nimport * as React from 'react'\nimport { createRoot } from 'react-dom/client'\n${stylesheetImport}\n${preamble}\n${app ? `\\nconst App = ${app}\\n` : ''}${version ? `\\nexport const version = ${version}\\n` : ''}\n// The SDK reads this slot via getDashboardModuleContext(), so its symbol, key and\n// value are a contract. Keyed by createContext, not the React namespace: Vite dev\n// pre-bundling can give two importers of one React copy different namespaces.\nconst moduleSlot = (globalThis[Symbol.for('sanity.os.module')] ??= new WeakMap())\nif (!moduleSlot.has(React.createContext)) moduleSlot.set(React.createContext, React.createContext(undefined))\nconst ModuleContext = moduleSlot.get(React.createContext)\nconst rootMap = new Map()\n// A shared default sheet can overwrite another app's global rules; each root needs its own sheet.\nconst styleTargets = new Map()\nconst stylisPlugins = new Map()\nconst renderArgs = new Map()\n// On globalThis: every module embeds its own copy of this harness, and names must be page-unique.\nconst stylisPluginCount = Symbol.for('sanity.os.stylisPluginCount')\n\n// Identical CSS gets an identical class in every sheet, so a later sheet overrides earlier rules.\n// StyleSheetManager hashes stylis plugin names into class names: a uniquely named no-op isolates a root.\nfunction uniqueStylisPlugin() {\n globalThis[stylisPluginCount] = (globalThis[stylisPluginCount] ?? 0) + 1\n return Object.defineProperty(() => {}, 'name', { value: 'sanity-root-' + globalThis[stylisPluginCount] })\n}\n\nfunction mount(rootElement, args) {\n let root = rootMap.get(rootElement)\n if (!root) {\n root = createRoot(rootElement, args?.renderOptions?.rootOptions)\n rootMap.set(rootElement, root)\n if (StyleSheetManager) {\n const target = rootElement.ownerDocument.createElement('sanity-styles')\n // React can replace the mount node's contents; keep its stylesheet outside that node.\n rootElement.ownerDocument.head.appendChild(target)\n styleTargets.set(rootElement, target)\n stylisPlugins.set(rootElement, [uniqueStylisPlugin()])\n }\n }\n let element = React.createElement(ModuleContext.Provider, { value: args?.renderOptions?.moduleId }, React.createElement(App, args.props))\n if (StyleSheetManager) element = React.createElement(StyleSheetManager, { target: styleTargets.get(rootElement), stylisPlugins: stylisPlugins.get(rootElement) }, element)\n // The host's React can't pause this root, so the host pauses the app through this Activity.\n // Keep it inside StrictMode: outside, it stops StrictMode double-invoking effects.\n element = React.createElement(React.Activity, { mode: args.lifecycle === 'background' ? 'hidden' : 'visible' }, element)\n if (args?.renderOptions?.reactStrictMode) element = React.createElement(React.StrictMode, null, element)\n root.render(element)\n}\n\nexport function render(rootElement, props, renderOptions) {\n const args = { lifecycle: 'foreground', props, renderOptions }\n renderArgs.set(rootElement, args)\n mount(rootElement, args)\n return {\n dispose() {\n const current = renderArgs.get(rootElement)\n renderArgs.delete(rootElement)\n if (current?.next) return current.next.dispose()\n const root = rootMap.get(rootElement)\n rootMap.delete(rootElement)\n root?.unmount()\n // Unmount first so effect cleanup can still reach this root's stylesheet.\n styleTargets.get(rootElement)?.remove()\n styleTargets.delete(rootElement)\n stylisPlugins.delete(rootElement)\n },\n setLifecycle(state) {\n const current = renderArgs.get(rootElement)\n if (!current) return\n if (current.next) return current.next.setLifecycle(state)\n current.lifecycle = state\n mount(rootElement, current)\n },\n }\n}${hmr ? `\\n\\n${HMR_REMOUNT}` : ''}\n`\n}\n"],"names":["HMR_REMOUNT","renderRemote","app","hmr","isolateStyles","preamble","version","stylesheetImport"],"mappings":"AAAA;;;;;CAKC,GAED,8EAA8E;AAC9E,iFAAiF;AACjF,uEAAuE;AACvE,MAAMA,cAAc,CAAC;;;;;;;;;;CAUpB,CAAC;AAEF;;;CAGC,GACD,OAAO,SAASC,aAAa,EAC3BC,GAAG,EACHC,MAAM,KAAK,EACXC,gBAAgB,KAAK,EACrBC,QAAQ,EACRC,OAAO,EAOR;IACC,iGAAiG;IACjG,MAAMC,mBAAmBH,gBACrB,0DACA;IAEJ,OAAO,CAAC;;;;;AAKV,EAAEG,iBAAiB;AACnB,EAAEF,SAAS;AACX,EAAEH,MAAM,CAAC,cAAc,EAAEA,IAAI,EAAE,CAAC,GAAG,KAAKI,UAAU,CAAC,yBAAyB,EAAEA,QAAQ,EAAE,CAAC,GAAG,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAqE9F,EAAEH,MAAM,CAAC,IAAI,EAAEH,aAAa,GAAG,GAAG;AACnC,CAAC;AACD"}
1
+ {"version":3,"sources":["../../../src/actions/build/render-remote.ts"],"sourcesContent":["/**\n * Every generated entry (studio, SDK app, view artifacts) shares one render body\n * so the host can drive them all the same way; only the `App` they bind differs.\n * The workbench host depends on `render`'s signature and return shape, so change\n * them together.\n */\n\n// Re-renders through the new module so edits apply without a page reload. The\n// new module mounts in the foreground, so reapply the host's lifecycle. The host\n// still holds this module's controller, so it forwards to the new one.\nconst HMR_REMOUNT = `if (import.meta.hot) {\n import.meta.hot.accept((next) => {\n if (!next) return\n for (const [rootElement, args] of renderArgs) {\n rootMap.get(rootElement)?.unmount()\n rootMap.delete(rootElement)\n closeRoot(rootElement)\n args.next = next.render(rootElement, args.props, args.renderOptions)\n args.next.setLifecycle(args.lifecycle)\n }\n })\n}`\n\n/**\n * - `app`: omit when the preamble imports `App` itself (the SDK-app entry).\n * - `version`: lets the host check view/service contract compatibility.\n */\nexport function renderRemote({\n app,\n hmr = false,\n isolateStyles = false,\n preamble,\n version,\n}: {\n app?: string\n hmr?: boolean\n isolateStyles?: boolean\n preamble: string\n version?: string\n}): string {\n // Keep apps without styled-components buildable; the unused branch is removed from their bundle.\n const stylesheetImport = isolateStyles\n ? \"import { StyleSheetManager } from 'styled-components'\"\n : 'const StyleSheetManager = undefined'\n\n return `\\\n// This file is auto-generated on 'sanity build' / 'sanity dev'\n// Modifications to this file are automatically discarded\nimport * as React from 'react'\nimport { createRoot } from 'react-dom/client'\n${stylesheetImport}\n${preamble}\n${app ? `\\nconst App = ${app}\\n` : ''}${version ? `\\nexport const version = ${version}\\n` : ''}\n// The SDK reads this slot via getDashboardRootContext(), so its symbol, key and value are a\n// contract. Keyed by createContext, not the React namespace: Vite dev pre-bundling can give two\n// importers of one React copy different namespaces.\nconst rootSlot = (globalThis[Symbol.for('sanity.os.root')] ??= new WeakMap())\nif (!rootSlot.has(React.createContext)) rootSlot.set(React.createContext, React.createContext(undefined))\nconst RootContext = rootSlot.get(React.createContext)\nconst rootMap = new Map()\nconst rootContexts = new Map()\n// A shared default sheet can overwrite another app's global rules; each root needs its own sheet.\nconst styleTargets = new Map()\nconst stylisPlugins = new Map()\nconst renderArgs = new Map()\n// On globalThis: every module embeds its own copy of this harness, and names must be page-unique.\nconst stylisPluginCount = Symbol.for('sanity.os.stylisPluginCount')\n\n// Identical CSS gets an identical class in every sheet, so a later sheet overrides earlier rules.\n// StyleSheetManager hashes stylis plugin names into class names: a uniquely named no-op isolates a root.\nfunction uniqueStylisPlugin() {\n globalThis[stylisPluginCount] = (globalThis[stylisPluginCount] ?? 0) + 1\n return Object.defineProperty(() => {}, 'name', { value: 'sanity-root-' + globalThis[stylisPluginCount] })\n}\n\n// The SDK disposes the root's instance, closing its bus connection, when the signal aborts. Next tick:\n// a host disposing a child root from its own cleanup code leaves the child still unmounting.\nfunction closeRoot(rootElement) {\n const closing = rootContexts.get(rootElement)\n rootContexts.delete(rootElement)\n if (closing) setTimeout(() => closing.controller.abort(), 0)\n}\n\nfunction mount(rootElement, args) {\n let root = rootMap.get(rootElement)\n if (!root) {\n root = createRoot(rootElement, args?.renderOptions?.rootOptions)\n rootMap.set(rootElement, root)\n const controller = new AbortController()\n // Read once: the SDK pins the root's bus identity when it first connects.\n const { moduleId, parentKey } = args?.renderOptions ?? {}\n rootContexts.set(rootElement, { controller, value: { signal: controller.signal, moduleId, parentKey } })\n if (StyleSheetManager) {\n const target = rootElement.ownerDocument.createElement('sanity-styles')\n if (typeof __SANITY_APP_ID__ === 'string') target.setAttribute('data-application-id', __SANITY_APP_ID__)\n // React can replace the mount node's contents; keep its stylesheet outside that node.\n rootElement.ownerDocument.head.appendChild(target)\n styleTargets.set(rootElement, target)\n stylisPlugins.set(rootElement, [uniqueStylisPlugin()])\n }\n }\n let element = React.createElement(RootContext.Provider, { value: rootContexts.get(rootElement).value }, React.createElement(App, args.props))\n if (StyleSheetManager) element = React.createElement(StyleSheetManager, { target: styleTargets.get(rootElement), stylisPlugins: stylisPlugins.get(rootElement) }, element)\n // The host's React can't pause this root, so the host pauses the app through this Activity.\n // Keep it inside StrictMode: outside, it stops StrictMode double-invoking effects.\n element = React.createElement(React.Activity, { mode: args.lifecycle === 'background' ? 'hidden' : 'visible' }, element)\n if (args?.renderOptions?.reactStrictMode) element = React.createElement(React.StrictMode, null, element)\n root.render(element)\n}\n\nexport function render(rootElement, props, renderOptions) {\n const args = { lifecycle: 'foreground', props, renderOptions }\n renderArgs.set(rootElement, args)\n mount(rootElement, args)\n return {\n dispose() {\n const current = renderArgs.get(rootElement)\n renderArgs.delete(rootElement)\n if (current?.next) return current.next.dispose()\n const root = rootMap.get(rootElement)\n rootMap.delete(rootElement)\n root?.unmount()\n // Unmount first so effect cleanup can still reach this root's stylesheet.\n styleTargets.get(rootElement)?.remove()\n styleTargets.delete(rootElement)\n stylisPlugins.delete(rootElement)\n closeRoot(rootElement)\n },\n setLifecycle(state) {\n const current = renderArgs.get(rootElement)\n if (!current) return\n if (current.next) return current.next.setLifecycle(state)\n current.lifecycle = state\n mount(rootElement, current)\n },\n }\n}${hmr ? `\\n\\n${HMR_REMOUNT}` : ''}\n`\n}\n"],"names":["HMR_REMOUNT","renderRemote","app","hmr","isolateStyles","preamble","version","stylesheetImport"],"mappings":"AAAA;;;;;CAKC,GAED,8EAA8E;AAC9E,iFAAiF;AACjF,uEAAuE;AACvE,MAAMA,cAAc,CAAC;;;;;;;;;;;CAWpB,CAAC;AAEF;;;CAGC,GACD,OAAO,SAASC,aAAa,EAC3BC,GAAG,EACHC,MAAM,KAAK,EACXC,gBAAgB,KAAK,EACrBC,QAAQ,EACRC,OAAO,EAOR;IACC,iGAAiG;IACjG,MAAMC,mBAAmBH,gBACrB,0DACA;IAEJ,OAAO,CAAC;;;;;AAKV,EAAEG,iBAAiB;AACnB,EAAEF,SAAS;AACX,EAAEH,MAAM,CAAC,cAAc,EAAEA,IAAI,EAAE,CAAC,GAAG,KAAKI,UAAU,CAAC,yBAAyB,EAAEA,QAAQ,EAAE,CAAC,GAAG,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAoF9F,EAAEH,MAAM,CAAC,IAAI,EAAEH,aAAa,GAAG,GAAG;AACnC,CAAC;AACD"}
@@ -4,8 +4,10 @@
4
4
  const DEFAULT_TIMEOUT_MS = 5000;
5
5
  // Mirrors the SDK's MessageBusError: importing the class would pull the SDK
6
6
  // runtime into the worker bundle.
7
- const busError = (code, message)=>Object.assign(new Error(message || code), {
7
+ const busError = (code, message, details)=>Object.assign(new Error(message || code), {
8
8
  code,
9
+ docsUrl: details?.docsUrl,
10
+ fix: details?.fix,
9
11
  name: 'MessageBusError'
10
12
  });
11
13
  /**
@@ -214,13 +216,10 @@ const busError = (code, message)=>Object.assign(new Error(message || code), {
214
216
  });
215
217
  return;
216
218
  }
217
- // A refused subscription has no promise to reject, so tell the author through the host logger.
218
- if (subscriptions.delete(message.id)) {
219
- // eslint-disable-next-line no-console -- the worker's console is bridged to the host logger
220
- console.error(`Message bus subscription refused: ${message.error.code}: ${message.error.message}`);
221
- }
219
+ // A refused subscription has no promise to reject. The Dashboard prints the refusal.
220
+ subscriptions.delete(message.id);
222
221
  settle?.({
223
- error: busError(message.error.code, message.error.message),
222
+ error: busError(message.error.code, message.error.message, message.error),
224
223
  ok: false
225
224
  });
226
225
  return;
@@ -1 +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 {\n type MessageBusEmitResult,\n type MessageBusErrorCode,\n type MessageBusMessage,\n type MessageBusMeta,\n} 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 Answer =\n | {error: {code: 'HANDLER_THREW' | 'REFUSED'; message: string}; ok: false}\n | {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 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): 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 // 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 ServiceBus,\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, 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 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","Object","assign","Error","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,2EAA2E;AAC3E,6EAA6E;AAC7E,gCAAgC;AAUhC,MAAMA,qBAAqB;AAgC3B,4EAA4E;AAC5E,kCAAkC;AAClC,MAAMC,WAAW,CAACC,MAA2BC,UAC3CC,OAAOC,MAAM,CAAC,IAAIC,MAAMH,WAAWD,OAAO;QAACA;QAAMK,MAAM;IAAiB;AAE1E;;;;;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,QAAQZ,OAAgC,EAAEa,UAA0B,CAAC,CAAC;QAC7E,MAAM,EAACC,MAAM,EAAEC,OAAO,EAAC,GAAGF;QAC1B,MAAMG,KAAK,EAAEN;QACb,IAAIO;QACJ,IAAIC;QACJ,IAAIC;QAEJ,MAAMC,SAAS,CAACC;YACd,IAAIJ,SAAS;YACbA,UAAUI;YACVC,aAAaH;YACbb,QAAQiB,MAAM,CAACP;YACfF,QAAQU,oBAAoB,SAASC;YACrCP,YAAYG;QACd;QACA,MAAMI,UAAU;YACdC,KAAKC,WAAW,CAAC;gBAACX;gBAAIY,MAAM;YA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AAkC,EAAE7B,QAAQ6B,KAAK,CAAC9B,IAAI,CAAC,EAAE,EAAEC,QAAQ6B,KAAK,CAAC7B,OAAO,EAAE;wBAEvF;wBACAoB,SAAS;4BAACS,OAAO/B,SAASE,QAAQ6B,KAAK,CAAC9B,IAAI,EAAEC,QAAQ6B,KAAK,CAAC7B,OAAO;4BAAG8B,IAAI;wBAAK;wBAC/E;oBACF;gBACA,KAAK;oBAAuB;wBAC1BtB,cAAc2C,GAAG,CAACnD,QAAQgB,EAAE,IAAIhB,QAAQyC,KAAK;oBAC/C;YACF;QACF;IACF;AACF"}
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 {\n type MessageBusEmitResult,\n type MessageBusErrorCode,\n type MessageBusMessage,\n type MessageBusMeta,\n} 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 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 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 // 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 ServiceBus,\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,2EAA2E;AAC3E,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,CAAC;QAC7E,MAAM,EAACC,MAAM,EAAEC,OAAO,EAAC,GAAGF;QAC1B,MAAMG,KAAK,EAAEN;QACb,IAAIO;QACJ,IAAIC;QACJ,IAAIC;QAEJ,MAAMC,SAAS,CAACC;YACd,IAAIJ,SAAS;YACbA,UAAUI;YACVC,aAAaH;YACbb,QAAQiB,MAAM,CAACP;YACfF,QAAQU,oBAAoB,SAASC;YACrCP,YAAYG;QACd;QACA,MAAMI,UAAU;YACdC,KAAKC,WAAW,CAAC;gBAACX;gBAAIY,MAAM;YAAqB;YAC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gC,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"}
@@ -5,6 +5,7 @@ import { hasMediaLibraryIslandRuntime, MEDIA_LIBRARY_ISLAND_RUNTIME_MODULE } fro
5
5
  import { FEDERATION_FILE_NAME, RUNTIME_DIR } from './constants.js';
6
6
  import { sanityFederationHost } from './plugins/plugin-federation-host.js';
7
7
  import { sanityModuleFederation } from './plugins/plugin-module-federation.js';
8
+ import { sanityAutoUpdates } from './plugins/plugin-sanity-auto-updates.js';
8
9
  import { sanityEnvironmentPlugin } from './plugins/plugin-sanity-environment.js';
9
10
  import { sanityExtensionArtifacts } from './plugins/plugin-sanity-extension-artifacts.js';
10
11
  import { sanityFederationRuntime } from './plugins/plugin-sanity-federation-runtime.js';
@@ -83,7 +84,8 @@ import { sanityFederationRuntime } from './plugins/plugin-sanity-federation-runt
83
84
  exposes: federationExposes,
84
85
  name
85
86
  }),
86
- sanityFederationHost()
87
+ sanityFederationHost(),
88
+ sanityAutoUpdates(options.autoUpdates)
87
89
  ];
88
90
  };
89
91
 
@@ -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 {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 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 service loader\n // (`./services/<name>`) is exposed straight to the host, pointing at the file\n // the extension-artifacts plugin generates under RUNTIME_DIR. A service'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 ]\n}\n"],"names":["path","artifactExposes","workbenchArtifacts","isMediaLibraryConfigApp","hasMediaLibraryIslandRuntime","MEDIA_LIBRARY_ISLAND_RUNTIME_MODULE","FEDERATION_FILE_NAME","RUNTIME_DIR","sanityFederationHost","sanityModuleFederation","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"],"mappings":"AAAA,OAAOA,UAAU,YAAW;AAO5B,SAAQC,eAAe,EAAEC,kBAAkB,QAAO,iBAAgB;AAClE,SAAQC,uBAAuB,QAAO,0BAAyB;AAC/D,SACEC,4BAA4B,EAC5BC,mCAAmC,QAC9B,0CAAyC;AAChD,SAAQC,oBAAoB,EAAEC,WAAW,QAAO,iBAAgB;AAChE,SAAQC,oBAAoB,QAAO,sCAAqC;AACxE,SAAgCC,sBAAsB,QAAO,wCAAuC;AACpG,SAAQC,uBAAuB,QAAO,yCAAwC;AAC9E,SAAQC,wBAAwB,QAAO,iDAAgD;AACvF,SAEEC,uBAAuB,QAClB,gDAA+C;AA6CtD;;CAEC,GACD,OAAO,MAAMC,aAAa,CAACC;IACzB,MAAM,EAACC,OAAO,EAAEC,YAAY,EAAEC,MAAMC,WAAW,EAAEC,OAAO,EAAEC,UAAUC,QAAQC,GAAG,EAAE,EAAC,GAAGR;IAErF,IAAIG,OAAOC;IAEX,IAAI,CAACD,MAAM;QACTA,OAAOE,SA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c2B,kBAAkB7B,QAAQ6B,gBAAgB;IAAA;IAE3E,iFAAiF;IACjF,wEAAwE;IACxE,2DAA2D;IAC3D,MAAMC,cAAcP,aAAarC,KAAK6C,IAAI,CAACzB,SAAS,WAAW,WAAW,YAAYoB;IAEtF,OAAO;QACL9B,wBAAwB;YAACkC;YAAaE,OAAOjB;YAAWb;QAAY;QACpEJ,wBAAwB8B;QACxB/B,yBAAyB;YAACuB;QAAS;QACnCzB,uBAAuB;YAACM,SAAS0B;YAAmBxB;QAAI;QACxDT;KACD;AACH,EAAC"}
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 service loader\n // (`./services/<name>`) is exposed straight to the host, pointing at the file\n // the extension-artifacts plugin generates under RUNTIME_DIR. A service'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,0CAAyC;AAChD,SAAQC,oBAAoB,EAAEC,WAAW,QAAO,iBAAgB;AAChE,SAAQC,oBAAoB,QAAO,sCAAqC;AACxE,SAAgCC,sBAAsB,QAAO,wCAAuC;AACpG,SAA0BC,iBAAiB,QAAO,0CAAyC;AAC3F,SAAQC,uBAAuB,QAAO,yCAAwC;AAC9E,SAAQC,wBAAwB,QAAO,iDAAgD;AACvF,SAEEC,uBAAuB,QAClB,gDAA+C;AA8CtD;;CAEC,GACD,OAAO,MAAMC,aAAa,CAACC;IACzB,MAAM,EAACC,OAAO,EAAEC,YAAY,EAAEC,MAAMC,WAAW,EAAEC,OAAO,EAAEC,UAAUC,QAAQC,GAAG,EAAE,EAAC,GAAGR;IAErF,IAAIG,OAAOC;IAEX,IAAI,CAACD,MAAM;QACTA,OAAOE,SAASF;IAClB;IAEA,IAAI,CAACA,MAAM;QACT,MAAM,IAAIM,MAAM;IAClB;IAEA,MAAMC,iBAAiB,CAAC,EAAE,EAAElB,YAAY,CAAC,EAAED,qBAAqB,IAAI,CAAC;IAErE,SAASoB,iBAAiBC,KAAa;QACrC,MAAMC,eAAe5B,KAAK6B,OAAO,CAACR,SAASM;QAE3C,IAAI,CAACC,cAAc;YACjB,MAAM,IAAIJ,MACR,CAAC,kCAAkC,EAAEG,MAAM,6DA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S0B;YAAmBxB;QAAI;QACxDV;QACAE,kBAAkBK,QAAQiC,WAAW;KACtC;AACH,EAAC"}
@@ -0,0 +1,61 @@
1
+ const APP_ID_ATTRIBUTE = JSON.stringify('data-application-id');
2
+ /**
3
+ * Tag every stylesheet element the app's own bundle inserts with the app id,
4
+ * so Workbench can switch an app's CSS off while the app is off stage.
5
+ */ export function sanityAppStyles(appId) {
6
+ const id = JSON.stringify(appId);
7
+ const tagged = (create)=>`((el) => (el.setAttribute(${APP_ID_ATTRIBUTE}, ${id}), el))(${create})`;
8
+ const owned = (element)=>`${element}.getAttribute(${APP_ID_ATTRIBUTE}) === ${id}`;
9
+ const inserters = [
10
+ {
11
+ edits: [
12
+ [
13
+ 'document.createElement("link")',
14
+ tagged('document.createElement("link")')
15
+ ],
16
+ [
17
+ 'link.rel === "stylesheet"',
18
+ `link.rel === "stylesheet" && ${owned('link')}`
19
+ ]
20
+ ],
21
+ id: /^\0vite\/preload-helper\.js$/
22
+ },
23
+ {
24
+ edits: [
25
+ [
26
+ 'document.createElement("style")',
27
+ tagged('document.createElement("style")')
28
+ ],
29
+ [
30
+ 'document.querySelectorAll("style[data-vite-dev-id]")',
31
+ `Array.from(document.querySelectorAll("style[data-vite-dev-id]")).filter((el) => ${owned('el')})`
32
+ ]
33
+ ],
34
+ id: /\/vite\/dist\/client\/client\.mjs$/
35
+ }
36
+ ];
37
+ return {
38
+ name: 'sanity/workbench/app-styles',
39
+ transform: {
40
+ filter: {
41
+ id: inserters.map((inserter)=>inserter.id)
42
+ },
43
+ handler (code, moduleId) {
44
+ const { edits } = inserters.find((inserter)=>inserter.id.test(moduleId));
45
+ let result = code;
46
+ for (const [anchor, replacement] of edits){
47
+ if (!result.includes(anchor)) {
48
+ this.error(`Could not find \`${anchor}\` in ${moduleId} to tag the app's stylesheets`);
49
+ }
50
+ result = result.replaceAll(anchor, replacement);
51
+ }
52
+ return {
53
+ code: result,
54
+ map: null
55
+ };
56
+ }
57
+ }
58
+ };
59
+ }
60
+
61
+ //# sourceMappingURL=plugin-sanity-app-styles.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../src/actions/build/vite/plugins/plugin-sanity-app-styles.ts"],"sourcesContent":["import {type Plugin} from 'vite'\n\nconst APP_ID_ATTRIBUTE = JSON.stringify('data-application-id')\n\n/**\n * Tag every stylesheet element the app's own bundle inserts with the app id,\n * so Workbench can switch an app's CSS off while the app is off stage.\n */\nexport function sanityAppStyles(appId: string): Plugin {\n const id = JSON.stringify(appId)\n const tagged = (create: string) =>\n `((el) => (el.setAttribute(${APP_ID_ATTRIBUTE}, ${id}), el))(${create})`\n const owned = (element: string) => `${element}.getAttribute(${APP_ID_ATTRIBUTE}) === ${id}`\n\n const inserters = [\n {\n edits: [\n ['document.createElement(\"link\")', tagged('document.createElement(\"link\")')],\n ['link.rel === \"stylesheet\"', `link.rel === \"stylesheet\" && ${owned('link')}`],\n ],\n id: /^\\0vite\\/preload-helper\\.js$/,\n },\n {\n edits: [\n ['document.createElement(\"style\")', tagged('document.createElement(\"style\")')],\n [\n 'document.querySelectorAll(\"style[data-vite-dev-id]\")',\n `Array.from(document.querySelectorAll(\"style[data-vite-dev-id]\")).filter((el) => ${owned('el')})`,\n ],\n ],\n id: /\\/vite\\/dist\\/client\\/client\\.mjs$/,\n },\n ]\n\n return {\n name: 'sanity/workbench/app-styles',\n transform: {\n filter: {id: inserters.map((inserter) => inserter.id)},\n handler(code, moduleId) {\n const {edits} = inserters.find((inserter) => inserter.id.test(moduleId))!\n let result = code\n for (const [anchor, replacement] of edits) {\n if (!result.includes(anchor)) {\n this.error(`Could not find \\`${anchor}\\` in ${moduleId} to tag the app's stylesheets`)\n }\n result = result.replaceAll(anchor, replacement)\n }\n return {code: result, map: null}\n },\n },\n }\n}\n"],"names":["APP_ID_ATTRIBUTE","JSON","stringify","sanityAppStyles","appId","id","tagged","create","owned","element","inserters","edits","name","transform","filter","map","inserter","handler","code","moduleId","find","test","result","anchor","replacement","includes","error","replaceAll"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