@sanity/workbench-cli 2.18.0 → 2.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/dist/_exports/_internal_worker_bus.d.ts +2 -2
  2. package/dist/_exports/deploy.d.ts +22 -6
  3. package/dist/_exports/deploy.js +1 -0
  4. package/dist/_exports/deploy.js.map +1 -1
  5. package/dist/_exports/dev.d.ts +2 -0
  6. package/dist/_exports/index.d.ts +67 -2
  7. package/dist/_exports/preview.d.ts +2 -0
  8. package/dist/_exports/{summarizeInterfaces-CpCUSMrz.d.ts → summarizeInterfaces-DGh6ARce.d.ts} +2 -2
  9. package/dist/_exports/undeploy.d.ts +1 -1
  10. package/dist/actions/build/webWorkers/workerBus.js.map +1 -1
  11. package/dist/actions/deploy/deployWorkbenchApp.js +21 -7
  12. package/dist/actions/deploy/deployWorkbenchApp.js.map +1 -1
  13. package/dist/actions/dev/deriveConfigs.js +1 -1
  14. package/dist/actions/dev/deriveConfigs.js.map +1 -1
  15. package/dist/actions/dev/startDevServerRegistration.js +16 -1
  16. package/dist/actions/dev/startDevServerRegistration.js.map +1 -1
  17. package/dist/actions/dev/startWorkbenchDev.js.map +1 -1
  18. package/dist/actions/preview/serveBuiltApplication.js +12 -1
  19. package/dist/actions/preview/serveBuiltApplication.js.map +1 -1
  20. package/dist/actions/preview/startWorkbenchPreview.js +11 -0
  21. package/dist/actions/preview/startWorkbenchPreview.js.map +1 -1
  22. package/dist/appId.js +1 -1
  23. package/dist/appId.js.map +1 -1
  24. package/dist/defineApp.js +4 -3
  25. package/dist/defineApp.js.map +1 -1
  26. package/dist/readAppIcon.js +31 -0
  27. package/dist/readAppIcon.js.map +1 -0
  28. package/dist/services/applications.js +18 -0
  29. package/dist/services/applications.js.map +1 -1
  30. package/dist/webWorker.js.map +1 -1
  31. package/package.json +12 -13
  32. package/dist/_exports/webWorker-TWUbh0uo.d.ts +0 -123
@@ -1,4 +1,4 @@
1
- import { o as WebWorkerBus } from "./webWorker-TWUbh0uo.js";
1
+ import { WebWorkerProps } from "@sanity/sdk/dashboard";
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,
@@ -10,7 +10,7 @@ declare function createWorkerBus(): {
10
10
  * The web worker author's API. The host owns the connection, opening it and ending it when
11
11
  * it terminates the worker, so the worker cannot end it.
12
12
  */
13
- bus: WebWorkerBus;
13
+ bus: WebWorkerProps['bus'];
14
14
  /**
15
15
  * The generated entry's terminate hook, not the author's. It sends nothing to
16
16
  * the host, which has already disconnected; it only marks the client closed so
@@ -1,7 +1,8 @@
1
1
  import "./contract-WrU3aOYd.js";
2
2
  import { n as resolveWorkbenchConfig, t as ResolvedMediaLibraryConfig } from "./resolveWorkbenchConfig-JRi01VJM.js";
3
- import { a as DeployableWorkbenchApp, i as summarizeInterfaces, n as DeployedView, o as getWorkbench, r as DeployedWebWorker, t as DeployedInterface } from "./summarizeInterfaces-CpCUSMrz.js";
3
+ import { a as DeployableWorkbenchApp, i as summarizeInterfaces, n as DeployedView, o as getWorkbench, r as DeployedWebWorker, t as DeployedInterface } from "./summarizeInterfaces-DGh6ARce.js";
4
4
  import { AppVisibility, CliConfig, Output } from "@sanity/cli-core";
5
+ import { ImageFile } from "@sanity/cli-core/images";
5
6
  import "node:zlib";
6
7
  /**
7
8
  * The org's active installation for an app type, or `undefined` when none is
@@ -149,9 +150,10 @@ declare function createStudio(options: {
149
150
  }): Promise<CreatedApplication>;
150
151
  /**
151
152
  * Ship a deployment to an already-created (or `deployment.appId`) application,
152
- * then sync its mutable metadata (`title`, and `icon`/`slug`/`visibility` when
153
- * set) from config. The deploy endpoint ignores these, so a redeploy patches
154
- * them here alongside the new deployment.
153
+ * then sync its mutable metadata (`title`, and `slug`/`visibility` when set)
154
+ * and its icon from config. The deploy endpoint ignores these, so a redeploy
155
+ * patches them here alongside the new deployment. No `icon` removes the
156
+ * application's icon.
155
157
  *
156
158
  * `onDeployed` fires the instant the deployment is live, before the metadata
157
159
  * sync — so a caller can disarm a create-time rollback that must not delete an
@@ -165,7 +167,7 @@ declare function deployWorkbenchApp(options: {
165
167
  access?: readonly BrettAccess[];
166
168
  app: CliConfig['app'];
167
169
  applicationId: string;
168
- icon?: string;
170
+ icon?: ImageFile;
169
171
  isApp: boolean;
170
172
  isAutoUpdating: boolean;
171
173
  isExternal?: boolean;
@@ -197,5 +199,19 @@ declare function selectWorkbenchAppId({ appId, flags, organizationId, type }: {
197
199
  organizationId: string | undefined;
198
200
  type: ApplicationType;
199
201
  }): Promise<string | undefined>;
200
- export { type Application, type BrettAccess, type BrettWorkspace, type CreatedApplication, type DeployedInterface, type DeployedView, type DeployedWebWorker, type ResolvedMediaLibraryConfig, type WorkbenchDeployPayload, createCoreApp, createStudio, deployConfig, deployWorkbenchApp, fetchDeploySummaryDetails, formatDeploySummary, getApplication, getApplicationUrl, getWorkbench, getWorkbenchUrl, listApplications, resolveInstallationId, resolveWorkbenchConfig, selectWorkbenchAppId, summarizeConfig, summarizeInterfaces, toWorkbenchPayload };
202
+ /**
203
+ * An app's `icon` image, read from its project.
204
+ * @internal
205
+ */
206
+ interface AppIcon extends ImageFile {
207
+ /** Absolute path to the file. */
208
+ file: string;
209
+ }
210
+ /**
211
+ * Read the image `app.icon` points at. The path is relative to the project
212
+ * root and must stay inside it.
213
+ * @internal
214
+ */
215
+ declare function readAppIcon(workDir: string, iconPath: string): Promise<AppIcon>;
216
+ export { type Application, type BrettAccess, type BrettWorkspace, type CreatedApplication, type DeployedInterface, type DeployedView, type DeployedWebWorker, type ResolvedMediaLibraryConfig, type WorkbenchDeployPayload, createCoreApp, createStudio, deployConfig, deployWorkbenchApp, fetchDeploySummaryDetails, formatDeploySummary, getApplication, getApplicationUrl, getWorkbench, getWorkbenchUrl, listApplications, readAppIcon, resolveInstallationId, resolveWorkbenchConfig, selectWorkbenchAppId, summarizeConfig, summarizeInterfaces, toWorkbenchPayload };
201
217
  //# sourceMappingURL=deploy.d.ts.map
@@ -5,6 +5,7 @@ export { createCoreApp, createStudio, deployWorkbenchApp } from '../actions/depl
5
5
  export { getWorkbench } from '../actions/deploy/getWorkbench.js';
6
6
  export { selectWorkbenchAppId } from '../actions/deploy/selectWorkbenchAppId.js';
7
7
  export { summarizeInterfaces } from '../actions/deploy/summarizeInterfaces.js';
8
+ export { readAppIcon } from '../readAppIcon.js';
8
9
  export { resolveWorkbenchConfig } from '../resolveWorkbenchConfig.js';
9
10
  export { getApplication, getApplicationUrl, getWorkbenchUrl, listApplications } from '../services/applications.js';
10
11
 
@@ -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 {fetchDeploySummaryDetails, formatDeploySummary} from '../actions/deploy/deploySummary.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","fetchDeploySummaryDetails","formatDeploySummary","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,SAAQC,yBAAyB,EAAEC,mBAAmB,QAAO,qCAAoC;AACjG,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
+ {"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 {fetchDeploySummaryDetails, formatDeploySummary} from '../actions/deploy/deploySummary.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 {readAppIcon} from '../readAppIcon.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","fetchDeploySummaryDetails","formatDeploySummary","createCoreApp","createStudio","deployWorkbenchApp","getWorkbench","selectWorkbenchAppId","summarizeInterfaces","readAppIcon","resolveWorkbenchConfig","getApplication","getApplicationUrl","getWorkbenchUrl","listApplications"],"mappings":"AAAA,SACEA,YAAY,EACZC,qBAAqB,EACrBC,eAAe,QACV,oCAAmC;AAC1C,SAAQC,kBAAkB,QAAoC,qCAAoC;AAClG,SAAQC,yBAAyB,EAAEC,mBAAmB,QAAO,qCAAoC;AACjG,SACEC,aAAa,EAEbC,YAAY,EACZC,kBAAkB,QACb,0CAAyC;AAChD,SAAQC,YAAY,QAAO,oCAAmC;AAC9D,SAAQC,oBAAoB,QAAO,4CAA2C;AAC9E,SAIEC,mBAAmB,QACd,2CAA0C;AACjD,SAAQC,WAAW,QAAO,oBAAmB;AAC7C,SAAyCC,sBAAsB,QAAO,+BAA8B;AACpG,SAIEC,cAAc,EACdC,iBAAiB,EACjBC,eAAe,EACfC,gBAAgB,QACX,8BAA6B"}
@@ -24,6 +24,8 @@ interface StartWorkbenchDevOptions {
24
24
  extractManifest: (params: {
25
25
  applicationId?: string;
26
26
  configPath: string;
27
+ /** Where the app server serves the app's icon. */
28
+ iconUrl?: string;
27
29
  workDir: string;
28
30
  }) => Promise<DevServerManifest['manifest']>;
29
31
  httpHost: string | undefined;
@@ -1,6 +1,6 @@
1
- import { C as defineTileView, S as definePanelView, T as defineWindowView, _ as WebWorker, a as DefineWebWorkerInput, c as PanelView, d as TileView, f as ViewComponent, h as ViewSurface, i as DefineTileViewInput, l as ServiceType, m as ViewDeclaration, n as DefineAssetSourceViewInput, o as DefineWindowViewInput, p as ViewComponentBaseProps, r as DefinePanelViewInput, s as DockGroup, t as AssetSourceView, u as TileSize, v as WebWorkerType, w as defineWebWorker, x as defineAssetSourceView, y as WindowView } from "./contract-WrU3aOYd.js";
2
- import { a as ServiceInfo, c as WebWorkerProps, i as ServiceContext, l as unstable_defineService, n as ServiceBus, o as WebWorkerBus, r as ServiceCallback, s as WebWorkerInfo, t as DefinedService } from "./webWorker-TWUbh0uo.js";
1
+ import { C as defineTileView, S as definePanelView, T as defineWindowView, _ as WebWorker, a as DefineWebWorkerInput, c as PanelView, d as TileView, f as ViewComponent, g as WEB_WORKER_CONTRACT_VERSION, h as ViewSurface, i as DefineTileViewInput, l as ServiceType, m as ViewDeclaration, n as DefineAssetSourceViewInput, o as DefineWindowViewInput, p as ViewComponentBaseProps, r as DefinePanelViewInput, s as DockGroup, t as AssetSourceView, u as TileSize, v as WebWorkerType, w as defineWebWorker, x as defineAssetSourceView, y as WindowView } from "./contract-WrU3aOYd.js";
3
2
  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";
3
+ import { WebWorkerProps, WebWorkerProps as WebWorkerProps$1 } from "@sanity/sdk/dashboard";
4
4
  import { AssetSourceComponentProps } from "@sanity/types";
5
5
  /** @public */
6
6
  type WindowViewProps = ViewComponentBaseProps<{
@@ -112,5 +112,70 @@ interface DefinedView<TSurface extends ViewSurface = ViewSurface> {
112
112
  * @public
113
113
  */
114
114
  declare function unstable_defineView<TSurface extends ViewSurface>(surface: TSurface, components: ViewComponentsBySurface[TSurface]): DefinedView<TSurface>;
115
+ /**
116
+ * @deprecated Use `WebWorkerProps['worker']`.
117
+ * @public
118
+ */
119
+ type WebWorkerInfo = WebWorkerProps$1['worker'];
120
+ /**
121
+ * @deprecated Use `WebWorkerProps['bus']`.
122
+ * @public
123
+ */
124
+ type WebWorkerBus = WebWorkerProps$1['bus'];
125
+ /**
126
+ * Context every service callback receives when its worker starts. Mirrors how a
127
+ * view component receives its `view` — the service receives its own `service`.
128
+ * @deprecated Use {@link WebWorkerProps}.
129
+ * @public
130
+ */
131
+ interface ServiceContext {
132
+ readonly bus: WebWorkerProps$1['bus'];
133
+ readonly service: WebWorkerProps$1['worker'];
134
+ }
135
+ /**
136
+ * A service callback. Runs once inside the worker on start; returns an optional
137
+ * disposer the host calls before terminating the worker.
138
+ * @deprecated Default-export a plain function that receives {@link WebWorkerProps} instead.
139
+ * @public
140
+ */
141
+ type ServiceCallback = (context: ServiceContext) => (() => void) | void;
142
+ /** The callback shape each service type defines, keyed by type. */
143
+ interface ServiceCallbacksByType {
144
+ worker: ServiceCallback;
145
+ }
146
+ /**
147
+ * The result of `unstable_defineService`: the author's callback, the service
148
+ * type, and the internal contract version the worker artifact targets.
149
+ * @deprecated Default-export a plain function that receives {@link WebWorkerProps} instead.
150
+ * @public
151
+ */
152
+ interface DefinedService<TType extends WebWorkerType = WebWorkerType> {
153
+ readonly run: ServiceCallbacksByType[TType];
154
+ readonly type: TType;
155
+ /** @internal */
156
+ readonly version: typeof WEB_WORKER_CONTRACT_VERSION;
157
+ }
158
+ /**
159
+ * Define a Sanity Dashboard background service. The first argument narrows the
160
+ * callback shape — `"worker"` runs the callback inside a Web Worker with the
161
+ * bus described on {@link WebWorkerProps}.
162
+ *
163
+ * Identity at runtime: returns the callback tagged with its type and the contract
164
+ * version, for the CLI build to generate a worker artifact from. Used as the
165
+ * default export of a service's `src` file.
166
+ * @deprecated Default-export a plain function that receives {@link WebWorkerProps} from the web worker's `src` file instead.
167
+ * @public
168
+ */
169
+ declare function unstable_defineService<TType extends WebWorkerType>(type: TType, run: ServiceCallbacksByType[TType]): DefinedService<TType>;
170
+ /**
171
+ * @deprecated Use `WebWorkerProps['bus']`.
172
+ * @public
173
+ */
174
+ type ServiceBus = WebWorkerProps$1['bus'];
175
+ /**
176
+ * @deprecated Use `WebWorkerProps['worker']`.
177
+ * @public
178
+ */
179
+ type ServiceInfo = WebWorkerProps$1['worker'];
115
180
  export { type AssetSourceComponent, type AssetSourceView, type AssetSourceViewComponents, type DefineAppInput, type DefineAppResult, type DefineAssetSourceViewInput, type DefineMediaLibraryInput, type DefinePanelViewInput, type DefineTileViewInput, type DefineWebWorkerInput, type DefineWindowViewInput, type DefinedService, type DefinedView, type DockGroup, type MediaLibraryField, type PanelComponent, type PanelView, type PanelViewComponents, type PanelViewProps, type ServiceBus, type ServiceCallback, type ServiceContext, type ServiceInfo, type ServiceType, type TileComponent, type TileSize, type TileView, type TileViewComponents, type TileViewProps, type ViewComponentsBySurface, type ViewDeclaration, type ViewSurface, type WebWorker, type WebWorkerBus, type WebWorkerInfo, type WebWorkerProps, type WebWorkerType, type WindowView, type WindowViewProps, type WorkbenchApp, type WorkbenchConfig, defineApplication, defineAssetSourceView, definePanelView, defineTileView, defineWebWorker, defineWindowView, isWorkbenchApp, isWorkbenchConfig, unstable_defineMediaLibrary, unstable_defineService, unstable_defineView };
116
181
  //# sourceMappingURL=index.d.ts.map
@@ -10,6 +10,8 @@ interface StartWorkbenchPreviewOptions {
10
10
  extractManifest: (params: {
11
11
  applicationId?: string;
12
12
  configPath: string;
13
+ /** Where the preview serves the app's icon. */
14
+ iconUrl?: string;
13
15
  workDir: string;
14
16
  }) => Promise<DevServerManifest['manifest']>;
15
17
  httpHost: string;
@@ -1,7 +1,7 @@
1
1
  import { h as ViewSurface, v as WebWorkerType } from "./contract-WrU3aOYd.js";
2
2
  import { i as WorkbenchExposes, r as ResolvedWorkbenchApp } from "./resolveWorkbenchConfig-JRi01VJM.js";
3
- import { z } from "zod/mini";
4
3
  import { CliConfig } from "@sanity/cli-core";
4
+ import { z } from "zod/mini";
5
5
  /**
6
6
  * Payload registering an app's views with the application service on deploy.
7
7
  *
@@ -62,4 +62,4 @@ declare function summarizeInterfaces({ views, webWorkers }: WorkbenchExposes): {
62
62
  views: DeployedView[];
63
63
  };
64
64
  export { DeployableWorkbenchApp as a, summarizeInterfaces as i, DeployedView as n, getWorkbench as o, DeployedWebWorker as r, DeployedInterface as t };
65
- //# sourceMappingURL=summarizeInterfaces-CpCUSMrz.d.ts.map
65
+ //# sourceMappingURL=summarizeInterfaces-DGh6ARce.d.ts.map
@@ -1,5 +1,5 @@
1
1
  import { t as ResolvedMediaLibraryConfig } from "./resolveWorkbenchConfig-JRi01VJM.js";
2
- import { a as DeployableWorkbenchApp, n as DeployedView, r as DeployedWebWorker } from "./summarizeInterfaces-CpCUSMrz.js";
2
+ import { a as DeployableWorkbenchApp, n as DeployedView, r as DeployedWebWorker } from "./summarizeInterfaces-DGh6ARce.js";
3
3
  import "node:zlib";
4
4
  import { UndeployAdapter, UndeployApplicationTarget, UndeployConfigTarget } from "@sanity/cli-core/undeploy";
5
5
  interface ConfigSnapshot {
@@ -1 +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,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;YACjDR,OAAO;gBAACS,OAAOlC,SAAS;gBAAYmC,IAAI;YAAK;QAC/C;QAEA,IA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;oBACF;gBACA,KAAK;oBAAuB;wBAC1BtB,cAAc2C,GAAG,CAACtD,QAAQmB,EAAE,IAAInB,QAAQ4C,KAAK;oBAC/C;YACF;QACF;IACF;AACF"}
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 type WebWorkerProps,\n} from '@sanity/sdk/dashboard'\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: WebWorkerProps['bus']\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 WebWorkerProps['bus'],\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;AAShC,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;YACjDR,OAAO;gBAACS,OAAOlC,SAAS;gBAAYmC,IAAI;YAAK;QAC/C;QAEA,IAAInB,UAAUG,QAAQiB,SAAS;YAC7Bd,UAAU;gBAACY,OAAOlC,SAAS;gBAAYmC,IAAI;YAAK;QAClD,OAAO;YACL,oFAAoF;YACpFJ,KAAKC,WAAW,CAACZ,YAAYiB,YAAY;gBAAC,GAAG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/cli-core/errors';
4
4
  import { spinner } from '@sanity/cli-core/ux';
5
5
  import { c as createTar } from 'tar';
6
6
  import { deriveInterfaces } from '../../deriveInterfaces.js';
7
- import { createApplication, createDeployment, deleteApplication, updateApplication } from '../../services/applications.js';
7
+ import { createApplication, createDeployment, deleteApplication, removeApplicationIcon, setApplicationIcon, updateApplication } from '../../services/applications.js';
8
8
  function toBrettInterface(iface) {
9
9
  const { id: _id, src: _src, ...declaration } = iface;
10
10
  if ('type' in declaration) return declaration;
@@ -86,9 +86,10 @@ function toBrettInterface(iface) {
86
86
  }
87
87
  /**
88
88
  * Ship a deployment to an already-created (or `deployment.appId`) application,
89
- * then sync its mutable metadata (`title`, and `icon`/`slug`/`visibility` when
90
- * set) from config. The deploy endpoint ignores these, so a redeploy patches
91
- * them here alongside the new deployment.
89
+ * then sync its mutable metadata (`title`, and `slug`/`visibility` when set)
90
+ * and its icon from config. The deploy endpoint ignores these, so a redeploy
91
+ * patches them here alongside the new deployment. No `icon` removes the
92
+ * application's icon.
92
93
  *
93
94
  * `onDeployed` fires the instant the deployment is live, before the metadata
94
95
  * sync — so a caller can disarm a create-time rollback that must not delete an
@@ -124,9 +125,6 @@ function toBrettInterface(iface) {
124
125
  try {
125
126
  await updateApplication(applicationId, {
126
127
  title,
127
- ...icon ? {
128
- icon
129
- } : {},
130
128
  ...slug ? {
131
129
  slug
132
130
  } : {},
@@ -137,6 +135,15 @@ function toBrettInterface(iface) {
137
135
  } catch (error) {
138
136
  throw toSlugRejection(error, slug);
139
137
  }
138
+ if (icon) {
139
+ try {
140
+ await setApplicationIcon(applicationId, icon);
141
+ } catch (error) {
142
+ throw toIconRejection(error);
143
+ }
144
+ } else {
145
+ await removeApplicationIcon(applicationId);
146
+ }
140
147
  spin.succeed();
141
148
  } catch (error) {
142
149
  spin.clear();
@@ -155,5 +162,12 @@ function toBrettInterface(iface) {
155
162
  cause: error
156
163
  });
157
164
  }
165
+ /** A 4xx on the icon upload is the image being rejected; name the server's reason. */ function toIconRejection(error) {
166
+ const statusCode = error?.statusCode;
167
+ if (statusCode === undefined || statusCode < 400 || statusCode >= 500) return error;
168
+ return new Error(`The app icon was rejected: ${getErrorMessage(error)}. The deployment is live with the application's previous icon. Change \`app.icon\` in sanity.cli.ts and deploy again.`, {
169
+ cause: error
170
+ });
171
+ }
158
172
 
159
173
  //# sourceMappingURL=deployWorkbenchApp.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/actions/deploy/deployWorkbenchApp.ts"],"sourcesContent":["import {basename, dirname} from 'node:path'\nimport {createGzip} from 'node:zlib'\n\nimport {type AppVisibility, type CliConfig} from '@sanity/cli-core'\nimport {getErrorMessage} from '@sanity/cli-core/errors'\nimport {spinner} from '@sanity/cli-core/ux'\nimport {c as createTar} from 'tar'\n\nimport {type DerivedInterface, deriveInterfaces} from '../../deriveInterfaces.js'\nimport {\n type Application,\n type BrettAccess,\n type BrettInterface,\n type BrettWorkspace,\n createApplication,\n createDeployment,\n deleteApplication,\n updateApplication,\n} from '../../services/applications.js'\n\n/**\n * `rollback` undoes the creation, so a later failure leaves no record stranded at the slug.\n * @internal\n */\nexport interface CreatedApplication {\n application: Application\n rollback: () => Promise<void>\n}\n\nfunction toBrettInterface(iface: DerivedInterface): BrettInterface {\n const {id: _id, src: _src, ...declaration} = iface\n if ('type' in declaration) return declaration\n\n switch (declaration.surface) {\n case 'asset_source': {\n const {surface, ...view} = declaration\n return {...view, type: surface}\n }\n case 'panel': {\n const {surface, ...view} = declaration\n return {...view, type: surface}\n }\n case 'tile': {\n const {surface, ...view} = declaration\n return {...view, type: surface}\n }\n case 'window': {\n const {surface, ...view} = declaration\n return {...view, type: 'app'}\n }\n }\n}\n\n/**\n * Create a coreApp record (no deployment), so the CLI can build with its id\n * before shipping the first deployment. First deploy only.\n * @internal\n */\nexport async function createCoreApp(options: {\n isSingleton?: boolean\n name?: string\n organizationId: string\n slug: string\n title: string\n visibility?: AppVisibility\n}): Promise<CreatedApplication> {\n const spin = spinner('Creating application...').start()\n try {\n const application = await createApplication({...options, type: 'coreApp'})\n spin.succeed()\n return {application, rollback: () => deleteApplication(application.id)}\n } catch (error) {\n spin.fail()\n throw error\n }\n}\n\n/**\n * Create a studio record (no deployment).\n * @internal\n */\nexport async function createStudio(options: {\n externalUrl?: string\n name?: string\n organizationId: string\n projectId: string | undefined\n slug: string\n title: string\n visibility?: AppVisibility\n}): Promise<CreatedApplication> {\n const spin = spinner('Creating studio...').start()\n try {\n const application = await createApplication({...options, type: 'studio'})\n spin.succeed()\n return {application, rollback: () => deleteApplication(application.id)}\n } catch (error) {\n spin.fail()\n throw error\n }\n}\n\n/**\n * Ship a deployment to an already-created (or `deployment.appId`) application,\n * then sync its mutable metadata (`title`, and `icon`/`slug`/`visibility` when\n * set) from config. The deploy endpoint ignores these, so a redeploy patches\n * them here alongside the new deployment.\n *\n * `onDeployed` fires the instant the deployment is live, before the metadata\n * sync — so a caller can disarm a create-time rollback that must not delete an\n * application once it has an active deployment.\n *\n * `isExternal` skips the tarball: the customer serves the build from the\n * application's registered origin.\n * @internal\n */\nexport async function deployWorkbenchApp(options: {\n access?: readonly BrettAccess[]\n app: CliConfig['app']\n applicationId: string\n icon?: string\n isApp: boolean\n isAutoUpdating: boolean\n isExternal?: boolean\n label?: string\n mfManifest: Record<string, unknown>\n onDeployed?: () => void\n /**\n * The address from config. Only `createApplication` used to send it, so an\n * app with a `deployment.appId` kept whatever slug it was created at.\n */\n slug?: string\n sourceDir: string\n title: string\n version: string\n visibility?: AppVisibility\n workspaces?: readonly BrettWorkspace[]\n}): Promise<void> {\n const {\n access,\n app,\n applicationId,\n icon,\n isApp,\n isAutoUpdating,\n isExternal = false,\n label = 'Deploying...',\n mfManifest,\n onDeployed,\n slug,\n sourceDir,\n title,\n version,\n visibility,\n workspaces,\n } = options\n const tarball = isExternal\n ? undefined\n : createTar({cwd: dirname(sourceDir)}, [basename(sourceDir)]).pipe(createGzip())\n\n const spin = spinner(label).start()\n try {\n await createDeployment({\n access,\n applicationId,\n // Brett assigns the id and resolves modules by `moduleId`, so neither travels.\n interfaces: deriveInterfaces(app, {appTitle: title, isApp}).map((iface) =>\n toBrettInterface(iface),\n ),\n isAutoUpdating,\n mfManifest,\n tarball,\n version,\n workspaces,\n })\n onDeployed?.()\n try {\n await updateApplication(applicationId, {\n title,\n ...(icon ? {icon} : {}),\n ...(slug ? {slug} : {}),\n ...(visibility ? {visibility} : {}),\n })\n } catch (error) {\n throw toSlugRejection(error, slug)\n }\n spin.succeed()\n } catch (error) {\n spin.clear()\n throw error\n }\n}\n\n/**\n * The slug is the one synced field the server validates — it must be free\n * within the organization, and a singleton app only accepts its reserved\n * identifiers — so a 4xx on the metadata patch is a rejected rename. Name the\n * slug and the server's reason; anything else propagates untouched.\n */\nfunction toSlugRejection(error: unknown, slug: string | undefined): unknown {\n const statusCode = (error as {statusCode?: number})?.statusCode\n if (!slug || statusCode === undefined || statusCode < 400 || statusCode >= 500) return error\n return new Error(\n `Slug \"${slug}\" was rejected: ${getErrorMessage(error)}. The deployment is live at the application's previous slug — change \\`app.slug\\` in sanity.cli.ts and deploy again.`,\n {cause: error},\n )\n}\n"],"names":["basename","dirname","createGzip","getErrorMessage","spinner","c","createTar","deriveInterfaces","createApplication","createDeployment","deleteApplication","updateApplication","toBrettInterface","iface","id","_id","src","_src","declaration","surface","view","type","createCoreApp","options","spin","start","application","succeed","rollback","error","fail","createStudio","deployWorkbenchApp","access","app","applicationId","icon","isApp","isAutoUpdating","isExternal","label","mfManifest","onDeployed","slug","sourceDir","title","version","visibility","workspaces","tarball","undefined","cwd","pipe","interfaces","appTitle","map","toSlugRejection","clear","statusCode","Error","cause"],"mappings":"AAAA,SAAQA,QAAQ,EAAEC,OAAO,QAAO,YAAW;AAC3C,SAAQC,UAAU,QAAO,YAAW;AAGpC,SAAQC,eAAe,QAAO,0BAAyB;AACvD,SAAQC,OAAO,QAAO,sBAAqB;AAC3C,SAAQC,KAAKC,SAAS,QAAO,MAAK;AAElC,SAA+BC,gBA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,EAAE,OAAOE,OAAO;QACdL,KAAKiC,KAAK;QACV,MAAM5B;IACR;AACF;AAEA;;;;;CAKC,GACD,SAAS2B,gBAAgB3B,KAAc,EAAEc,IAAwB;IAC/D,MAAMe,aAAc7B,OAAiC6B;IACrD,IAAI,CAACf,QAAQe,eAAeR,aAAaQ,aAAa,OAAOA,cAAc,KAAK,OAAO7B;IACvF,OAAO,IAAI8B,MACT,CAAC,MAAM,EAAEhB,KAAK,gBAAgB,EAAExC,gBAAgB0B,OAAO,oHAAoH,CAAC,EAC5K;QAAC+B,OAAO/B;IAAK;AAEjB"}
1
+ {"version":3,"sources":["../../../src/actions/deploy/deployWorkbenchApp.ts"],"sourcesContent":["import {basename, dirname} from 'node:path'\nimport {createGzip} from 'node:zlib'\n\nimport {type AppVisibility, type CliConfig} from '@sanity/cli-core'\nimport {getErrorMessage} from '@sanity/cli-core/errors'\nimport {type ImageFile} from '@sanity/cli-core/images'\nimport {spinner} from '@sanity/cli-core/ux'\nimport {c as createTar} from 'tar'\n\nimport {type DerivedInterface, deriveInterfaces} from '../../deriveInterfaces.js'\nimport {\n type Application,\n type BrettAccess,\n type BrettInterface,\n type BrettWorkspace,\n createApplication,\n createDeployment,\n deleteApplication,\n removeApplicationIcon,\n setApplicationIcon,\n updateApplication,\n} from '../../services/applications.js'\n\n/**\n * `rollback` undoes the creation, so a later failure leaves no record stranded at the slug.\n * @internal\n */\nexport interface CreatedApplication {\n application: Application\n rollback: () => Promise<void>\n}\n\nfunction toBrettInterface(iface: DerivedInterface): BrettInterface {\n const {id: _id, src: _src, ...declaration} = iface\n if ('type' in declaration) return declaration\n\n switch (declaration.surface) {\n case 'asset_source': {\n const {surface, ...view} = declaration\n return {...view, type: surface}\n }\n case 'panel': {\n const {surface, ...view} = declaration\n return {...view, type: surface}\n }\n case 'tile': {\n const {surface, ...view} = declaration\n return {...view, type: surface}\n }\n case 'window': {\n const {surface, ...view} = declaration\n return {...view, type: 'app'}\n }\n }\n}\n\n/**\n * Create a coreApp record (no deployment), so the CLI can build with its id\n * before shipping the first deployment. First deploy only.\n * @internal\n */\nexport async function createCoreApp(options: {\n isSingleton?: boolean\n name?: string\n organizationId: string\n slug: string\n title: string\n visibility?: AppVisibility\n}): Promise<CreatedApplication> {\n const spin = spinner('Creating application...').start()\n try {\n const application = await createApplication({...options, type: 'coreApp'})\n spin.succeed()\n return {application, rollback: () => deleteApplication(application.id)}\n } catch (error) {\n spin.fail()\n throw error\n }\n}\n\n/**\n * Create a studio record (no deployment).\n * @internal\n */\nexport async function createStudio(options: {\n externalUrl?: string\n name?: string\n organizationId: string\n projectId: string | undefined\n slug: string\n title: string\n visibility?: AppVisibility\n}): Promise<CreatedApplication> {\n const spin = spinner('Creating studio...').start()\n try {\n const application = await createApplication({...options, type: 'studio'})\n spin.succeed()\n return {application, rollback: () => deleteApplication(application.id)}\n } catch (error) {\n spin.fail()\n throw error\n }\n}\n\n/**\n * Ship a deployment to an already-created (or `deployment.appId`) application,\n * then sync its mutable metadata (`title`, and `slug`/`visibility` when set)\n * and its icon from config. The deploy endpoint ignores these, so a redeploy\n * patches them here alongside the new deployment. No `icon` removes the\n * application's icon.\n *\n * `onDeployed` fires the instant the deployment is live, before the metadata\n * sync — so a caller can disarm a create-time rollback that must not delete an\n * application once it has an active deployment.\n *\n * `isExternal` skips the tarball: the customer serves the build from the\n * application's registered origin.\n * @internal\n */\nexport async function deployWorkbenchApp(options: {\n access?: readonly BrettAccess[]\n app: CliConfig['app']\n applicationId: string\n icon?: ImageFile\n isApp: boolean\n isAutoUpdating: boolean\n isExternal?: boolean\n label?: string\n mfManifest: Record<string, unknown>\n onDeployed?: () => void\n /**\n * The address from config. Only `createApplication` used to send it, so an\n * app with a `deployment.appId` kept whatever slug it was created at.\n */\n slug?: string\n sourceDir: string\n title: string\n version: string\n visibility?: AppVisibility\n workspaces?: readonly BrettWorkspace[]\n}): Promise<void> {\n const {\n access,\n app,\n applicationId,\n icon,\n isApp,\n isAutoUpdating,\n isExternal = false,\n label = 'Deploying...',\n mfManifest,\n onDeployed,\n slug,\n sourceDir,\n title,\n version,\n visibility,\n workspaces,\n } = options\n const tarball = isExternal\n ? undefined\n : createTar({cwd: dirname(sourceDir)}, [basename(sourceDir)]).pipe(createGzip())\n\n const spin = spinner(label).start()\n try {\n await createDeployment({\n access,\n applicationId,\n // Brett assigns the id and resolves modules by `moduleId`, so neither travels.\n interfaces: deriveInterfaces(app, {appTitle: title, isApp}).map((iface) =>\n toBrettInterface(iface),\n ),\n isAutoUpdating,\n mfManifest,\n tarball,\n version,\n workspaces,\n })\n onDeployed?.()\n try {\n await updateApplication(applicationId, {\n title,\n ...(slug ? {slug} : {}),\n ...(visibility ? {visibility} : {}),\n })\n } catch (error) {\n throw toSlugRejection(error, slug)\n }\n if (icon) {\n try {\n await setApplicationIcon(applicationId, icon)\n } catch (error) {\n throw toIconRejection(error)\n }\n } else {\n await removeApplicationIcon(applicationId)\n }\n spin.succeed()\n } catch (error) {\n spin.clear()\n throw error\n }\n}\n\n/**\n * The slug is the one synced field the server validates — it must be free\n * within the organization, and a singleton app only accepts its reserved\n * identifiers — so a 4xx on the metadata patch is a rejected rename. Name the\n * slug and the server's reason; anything else propagates untouched.\n */\nfunction toSlugRejection(error: unknown, slug: string | undefined): unknown {\n const statusCode = (error as {statusCode?: number})?.statusCode\n if (!slug || statusCode === undefined || statusCode < 400 || statusCode >= 500) return error\n return new Error(\n `Slug \"${slug}\" was rejected: ${getErrorMessage(error)}. The deployment is live at the application's previous slug — change \\`app.slug\\` in sanity.cli.ts and deploy again.`,\n {cause: error},\n )\n}\n\n/** A 4xx on the icon upload is the image being rejected; name the server's reason. */\nfunction toIconRejection(error: unknown): unknown {\n const statusCode = (error as {statusCode?: number})?.statusCode\n if (statusCode === undefined || statusCode < 400 || statusCode >= 500) return error\n return new Error(\n `The app icon was rejected: ${getErrorMessage(error)}. The deployment is live with the application's previous icon. Change \\`app.icon\\` in sanity.cli.ts and deploy again.`,\n {cause: error},\n )\n}\n"],"names":["basename","dirname","createGzip","getErrorMessage","spinner","c","createTar","deriveInterfaces","createApplication","createDeployment","deleteApplication","removeApplicationIcon","setApplicationIcon","updateApplication","toBrettInterface","iface","id","_id","src","_src","declaration","surface","view","type","createCoreApp","options","spin","start","application","succeed","rollback","error","fail","createStudio","deployWorkbenchApp","access","app","applicationId","icon","isApp","isAutoUpdating","isExternal","label","mfManifest","onDeployed","slug","sourceDir","title","version","visibility","workspaces","tarball","undefined","cwd","pipe","interfaces","appTitle","map","toSlugRejection","toIconRejection","clear","statusCode","Error","cause"],"mappings":"AAAA,SAAQA,QAAQ,EAAEC,OAAO,QAAO,YAAW;AAC3C,SAAQC,UAAU,QAAO,YAAW;AAGpC,SAAQC,eAAe,QAAO,0BAAyB;AAEvD,SAAQC,OAAO,QAAO,sBAAqB;AAC3C,SAAQC,KAAKC,SAAS,QAAO,MAAK;AAElC,SAA+BC,gBAAgB,QAAO,4BAA2B;AACjF,SAKEC,iBAAiB,EACjBC,gBAAgB,EAChBC,iBAAiB,EACjBC,qBAAqB,EACrBC,kBAAkB,EAClBC,iBAAiB,QACZ,iCAAgC;AAWvC,SAASC,iBAAiBC,KAAuB;IAC/C,MAAM,EAACC,IAAIC,GAAG,EAAEC,KAAKC,IAAI,EAAE,GAAGC,aAAY,GAAGL;IAC7C,IAAI,UAAUK,aAAa,OAAOA;IAElC,OAAQA,YAAYC,OAAO;QACzB,KAAK;YAAgB;gBACnB,MAAM,EAACA,OAAO,EAAE,GAAGC,MAAK,GAAGF;gBAC3B,OAAO;oBAAC,GAAGE,IAAI;oBAAEC,MAAMF;gBAAO;YAChC;QACA,KAAK;YAAS;gBACZ,MAAM,EAACA,OAAO,EAAE,GAAGC,MAAK,GAAGF;gBAC3B,OAAO;oBAAC,GAAGE,IAAI;oBAAEC,MAAMF;gBAAO;YAChC;QACA,KAAK;YAAQ;gBACX,MAAM,EAACA,OAAO,EAAE,GAAGC,MAAK,GAAGF;gBAC3B,OAAO;oBAAC,GAAGE,IAAI;oB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,CAAC,2BAA2B,EAAE3D,gBAAgB4B,OAAO,qHAAqH,CAAC,EAC3K;QAACgC,OAAOhC;IAAK;AAEjB"}
@@ -58,7 +58,7 @@ import { resolveWorkbenchConfig } from '../../resolveWorkbenchConfig.js';
58
58
  * and the browser. `node:crypto` can't be used: the Vite dev server's dep scan
59
59
  * pulls this module into the browser graph.
60
60
  */ async function contentHash(input) {
61
- // eslint-disable-next-line n/no-unsupported-features/node-builtins -- the Web Crypto global is available on our Node target and in the browser
61
+ // eslint-disable-next-line n-js/no-unsupported-features/node-builtins -- the Web Crypto global is available on our Node target and in the browser
62
62
  const digest = await globalThis.crypto.subtle.digest('SHA-256', new TextEncoder().encode(input));
63
63
  return Array.from(new Uint8Array(digest), (byte)=>byte.toString(16).padStart(2, '0')).join('');
64
64
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/actions/dev/deriveConfigs.ts"],"sourcesContent":["import {type CliConfig} from '@sanity/cli-core'\n\nimport {MEDIA_LIBRARY_CONFIG_CONTRACT_VERSION} from '../../contract.js'\nimport {resolveWorkbenchConfig} from '../../resolveWorkbenchConfig.js'\nimport {type DevServerManifest} from './registry.js'\n\n/** One forwarded interface record on the dev-server registry entry. */\nexport type DevServerInterface = NonNullable<DevServerManifest['interfaces']>[number]\n\n/** One forwarded config on the dev-server registry entry. */\nexport type DevServerConfig = NonNullable<DevServerManifest['configs']>[number]\n\n/**\n * The named source files a config's generated module is built from, dispatched\n * per app type — the projection the exposes-set id keys on, so the generic HMR\n * tracker owns none of the per-type shape. Throws on an app type it can't\n * handle, so a new config family has to register its shape here.\n */\nexport function deriveConfigEntries(config: DevServerConfig): {name: string; src: string}[] {\n switch (config.appType) {\n case 'media-library': {\n return config.fields.map((field) => ({name: field.name, src: field.src}))\n }\n default: {\n throw new Error(`Cannot derive entries for unknown config appType: ${config.appType}`)\n }\n }\n}\n\n/**\n * The fields' schema *values* can't serialize — the workbench loads them from\n * the federation module. `src` stays on so the exposes-set id keys on it and a\n * repoint rebuilds. `appType` routes the config to the singleton (no app id to\n * key on) and names the federation `moduleName`, so the alias no longer borrows\n * the app slug. `id` is a content hash of the entry — it fills the\n * installation-config id slot deployed apps get from the applications API,\n * and the workbench keys change detection on it. `version` is a string, like\n * the one Brett returns on a deployed `activeConfig`.\n */\nexport async function deriveConfigs(\n cliConfig: CliConfig | null | undefined,\n): Promise<DevServerConfig[]> {\n // Keyed on the config brand (its target `appType`), not on having fields — an\n // empty config is still a config; dev just has nothing local to load for it.\n const config = resolveWorkbenchConfig(cliConfig)\n if (!config) return []\n const entry = {\n appType: config.appType,\n fields: config.fields.map((field) => ({\n name: field.name,\n public: field.public,\n src: field.src,\n title: field.title,\n })),\n // A config keys on its target `appType`, not a fabricated slug.\n moduleName: config.appType,\n version: String(MEDIA_LIBRARY_CONFIG_CONTRACT_VERSION),\n }\n return [{...entry, id: await contentHash(JSON.stringify(entry))}]\n}\n\n/**\n * SHA-256 of a string, as hex, via the Web Crypto API — available in both Node\n * and the browser. `node:crypto` can't be used: the Vite dev server's dep scan\n * pulls this module into the browser graph.\n */\nasync function contentHash(input: string): Promise<string> {\n // eslint-disable-next-line n/no-unsupported-features/node-builtins -- the Web Crypto global is available on our Node target and in the browser\n const digest = await globalThis.crypto.subtle.digest('SHA-256', new TextEncoder().encode(input))\n return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, '0')).join('')\n}\n"],"names":["MEDIA_LIBRARY_CONFIG_CONTRACT_VERSION","resolveWorkbenchConfig","deriveConfigEntries","config","appType","fields","map","field","name","src","Error","deriveConfigs","cliConfig","entry","public","title","moduleName","version","String","id","contentHash","JSON","stringify","input","digest","globalThis","crypto","subtle","TextEncoder","encode","Array","from","Uint8Array","byte","toString","padStart","join"],"mappings":"AAEA,SAAQA,qCAAqC,QAAO,oBAAmB;AACvE,SAAQC,sBAAsB,QAAO,kCAAiC;AAStE;;;;;CAKC,GACD,OAAO,SAASC,oBAAoBC,MAAuB;IACzD,OAAQA,OAAOC,OAAO;QACpB,KAAK;YAAiB;gBACpB,OAAOD,OAAOE,MAAM,CAACC,GAAG,CAAC,CAACC,QAAW,CAAA;wBAACC,MAAMD,MAAMC,IAAI;wBAAEC,KAAKF,MAAME,GAAG;oBAAA,CAAA;YACxE;QACA;YAAS;gBACP,MAAM,IAAIC,MAAM,CAAC,kDAAkD,EAAEP,OAAOC,OAAO,EAAE;YACvF;IACF;AACF;AAEA;;;;;;;;;CASC,GACD,OAAO,eAAeO,cACpBC,SAAuC;IAEvC,8EAA8E;IAC9E,6EAA6E;IAC7E,MAAMT,SAASF,uBAAuBW;IACtC,IAAI,CAACT,QAAQ,OAAO,EAAE;IACtB,MAAMU,QAAQ;QACZT,SAASD,OAAOC,OAAO;QACvBC,QAAQF,OAAOE,MAAM,CAACC,GAAG,CAAC,CAACC,QAAW,CAAA;gBACpCC,MAAMD,MAAMC,IAAI;gBAChBM,QAAQP,MAAMO,MAAM;gBACpBL,KAAKF,MAAME,GAAG;gBACdM,OAAOR,MAAMQ,KAAK;YACpB,CAAA;QACA,gEAAgE;QAChEC,YAAYb,OAAOC,OAAO;QAC1Ba,SAASC,OAAOlB;IAClB;IACA,OAAO;QAAC;YAAC,GAAGa,KAAK;YAAEM,IAAI,MAAMC,YAAYC,KAAKC,SAAS,CAACT;QAAO;KAAE;AACnE;AAEA;;;;CAIC,GACD,eAAeO,YAAYG,KAAa;IACtC,+IAA+I;IAC/I,MAAMC,SAAS,MAAMC,WAAWC,MAAM,CAACC,MAAM,CAACH,MAAM,CAAC,WAAW,IAAII,cAAcC,MAAM,CAACN;IACzF,OAAOO,MAAMC,IAAI,CAAC,IAAIC,WAAWR,SAAS,CAACS,OAASA,KAAKC,QAAQ,CAAC,IAAIC,QAAQ,CAAC,GAAG,MAAMC,IAAI,CAAC;AAC/F"}
1
+ {"version":3,"sources":["../../../src/actions/dev/deriveConfigs.ts"],"sourcesContent":["import {type CliConfig} from '@sanity/cli-core'\n\nimport {MEDIA_LIBRARY_CONFIG_CONTRACT_VERSION} from '../../contract.js'\nimport {resolveWorkbenchConfig} from '../../resolveWorkbenchConfig.js'\nimport {type DevServerManifest} from './registry.js'\n\n/** One forwarded interface record on the dev-server registry entry. */\nexport type DevServerInterface = NonNullable<DevServerManifest['interfaces']>[number]\n\n/** One forwarded config on the dev-server registry entry. */\nexport type DevServerConfig = NonNullable<DevServerManifest['configs']>[number]\n\n/**\n * The named source files a config's generated module is built from, dispatched\n * per app type — the projection the exposes-set id keys on, so the generic HMR\n * tracker owns none of the per-type shape. Throws on an app type it can't\n * handle, so a new config family has to register its shape here.\n */\nexport function deriveConfigEntries(config: DevServerConfig): {name: string; src: string}[] {\n switch (config.appType) {\n case 'media-library': {\n return config.fields.map((field) => ({name: field.name, src: field.src}))\n }\n default: {\n throw new Error(`Cannot derive entries for unknown config appType: ${config.appType}`)\n }\n }\n}\n\n/**\n * The fields' schema *values* can't serialize — the workbench loads them from\n * the federation module. `src` stays on so the exposes-set id keys on it and a\n * repoint rebuilds. `appType` routes the config to the singleton (no app id to\n * key on) and names the federation `moduleName`, so the alias no longer borrows\n * the app slug. `id` is a content hash of the entry — it fills the\n * installation-config id slot deployed apps get from the applications API,\n * and the workbench keys change detection on it. `version` is a string, like\n * the one Brett returns on a deployed `activeConfig`.\n */\nexport async function deriveConfigs(\n cliConfig: CliConfig | null | undefined,\n): Promise<DevServerConfig[]> {\n // Keyed on the config brand (its target `appType`), not on having fields — an\n // empty config is still a config; dev just has nothing local to load for it.\n const config = resolveWorkbenchConfig(cliConfig)\n if (!config) return []\n const entry = {\n appType: config.appType,\n fields: config.fields.map((field) => ({\n name: field.name,\n public: field.public,\n src: field.src,\n title: field.title,\n })),\n // A config keys on its target `appType`, not a fabricated slug.\n moduleName: config.appType,\n version: String(MEDIA_LIBRARY_CONFIG_CONTRACT_VERSION),\n }\n return [{...entry, id: await contentHash(JSON.stringify(entry))}]\n}\n\n/**\n * SHA-256 of a string, as hex, via the Web Crypto API — available in both Node\n * and the browser. `node:crypto` can't be used: the Vite dev server's dep scan\n * pulls this module into the browser graph.\n */\nasync function contentHash(input: string): Promise<string> {\n // eslint-disable-next-line n-js/no-unsupported-features/node-builtins -- the Web Crypto global is available on our Node target and in the browser\n const digest = await globalThis.crypto.subtle.digest('SHA-256', new TextEncoder().encode(input))\n return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, '0')).join('')\n}\n"],"names":["MEDIA_LIBRARY_CONFIG_CONTRACT_VERSION","resolveWorkbenchConfig","deriveConfigEntries","config","appType","fields","map","field","name","src","Error","deriveConfigs","cliConfig","entry","public","title","moduleName","version","String","id","contentHash","JSON","stringify","input","digest","globalThis","crypto","subtle","TextEncoder","encode","Array","from","Uint8Array","byte","toString","padStart","join"],"mappings":"AAEA,SAAQA,qCAAqC,QAAO,oBAAmB;AACvE,SAAQC,sBAAsB,QAAO,kCAAiC;AAStE;;;;;CAKC,GACD,OAAO,SAASC,oBAAoBC,MAAuB;IACzD,OAAQA,OAAOC,OAAO;QACpB,KAAK;YAAiB;gBACpB,OAAOD,OAAOE,MAAM,CAACC,GAAG,CAAC,CAACC,QAAW,CAAA;wBAACC,MAAMD,MAAMC,IAAI;wBAAEC,KAAKF,MAAME,GAAG;oBAAA,CAAA;YACxE;QACA;YAAS;gBACP,MAAM,IAAIC,MAAM,CAAC,kDAAkD,EAAEP,OAAOC,OAAO,EAAE;YACvF;IACF;AACF;AAEA;;;;;;;;;CASC,GACD,OAAO,eAAeO,cACpBC,SAAuC;IAEvC,8EAA8E;IAC9E,6EAA6E;IAC7E,MAAMT,SAASF,uBAAuBW;IACtC,IAAI,CAACT,QAAQ,OAAO,EAAE;IACtB,MAAMU,QAAQ;QACZT,SAASD,OAAOC,OAAO;QACvBC,QAAQF,OAAOE,MAAM,CAACC,GAAG,CAAC,CAACC,QAAW,CAAA;gBACpCC,MAAMD,MAAMC,IAAI;gBAChBM,QAAQP,MAAMO,MAAM;gBACpBL,KAAKF,MAAME,GAAG;gBACdM,OAAOR,MAAMQ,KAAK;YACpB,CAAA;QACA,gEAAgE;QAChEC,YAAYb,OAAOC,OAAO;QAC1Ba,SAASC,OAAOlB;IAClB;IACA,OAAO;QAAC;YAAC,GAAGa,KAAK;YAAEM,IAAI,MAAMC,YAAYC,KAAKC,SAAS,CAACT;QAAO;KAAE;AACnE;AAEA;;;;CAIC,GACD,eAAeO,YAAYG,KAAa;IACtC,kJAAkJ;IAClJ,MAAMC,SAAS,MAAMC,WAAWC,MAAM,CAACC,MAAM,CAACH,MAAM,CAAC,WAAW,IAAII,cAAcC,MAAM,CAACN;IACzF,OAAOO,MAAMC,IAAI,CAAC,IAAIC,WAAWR,SAAS,CAACS,OAASA,KAAKC,QAAQ,CAAC,IAAIC,QAAQ,CAAC,GAAG,MAAMC,IAAI,CAAC;AAC/F"}
@@ -1,6 +1,8 @@
1
+ import { relative } from 'node:path';
1
2
  import { getCliConfigUncached } from '@sanity/cli-core';
2
3
  import { isWorkbenchApp, isWorkbenchConfig } from '../../defineApp.js';
3
4
  import { deriveInterfaces } from '../../deriveInterfaces.js';
5
+ import { readAppIcon, toUrlPath } from '../../readAppIcon.js';
4
6
  import { resolveWorkbenchConfig } from '../../resolveWorkbenchConfig.js';
5
7
  import { formatWorkbenchAppErrors, validateWorkbenchApp } from '../../validateWorkbenchApp.js';
6
8
  import { deriveConfigs } from './deriveConfigs.js';
@@ -81,12 +83,23 @@ import { startDevManifestWatcher } from './startDevManifestWatcher.js';
81
83
  configs,
82
84
  interfaces
83
85
  });
86
+ let liveServer = server;
84
87
  const watcher = await startDevManifestWatcher({
85
88
  // Re-derive every pass (don't omit): the registry patch is a shallow merge,
86
89
  // so omitting would wipe the registered set.
87
90
  extract: async (params)=>{
88
91
  const nextConfig = await getCliConfigUncached(params.workDir);
89
92
  reportConfigErrors(nextConfig.app, output);
93
+ let iconUrl;
94
+ if (isApp && isWorkbenchApp(nextConfig.app) && nextConfig.app.icon) {
95
+ // Read in full so an image a deploy would reject warns here, while editing.
96
+ const { file } = await readAppIcon(workDir, nextConfig.app.icon);
97
+ // Vite serves `public/` at the root, and warns on every request for `/public/...`.
98
+ const { base, publicDir, root } = liveServer.config;
99
+ const inPublicDir = Boolean(publicDir) && !relative(publicDir, file).startsWith('..');
100
+ const { host, https, port } = serverAddress(liveServer);
101
+ iconUrl = `${https ? 'https' : 'http'}://${host}:${port}${base}${toUrlPath(inPublicDir ? publicDir : root, file)}`;
102
+ }
90
103
  return {
91
104
  configs: await deriveConfigs(nextConfig),
92
105
  interfaces: deriveInterfaces(nextConfig.app, {
@@ -94,7 +107,8 @@ import { startDevManifestWatcher } from './startDevManifestWatcher.js';
94
107
  }),
95
108
  manifest: await extractManifest({
96
109
  ...params,
97
- applicationId: id
110
+ applicationId: id,
111
+ iconUrl
98
112
  })
99
113
  };
100
114
  },
@@ -122,6 +136,7 @@ import { startDevManifestWatcher } from './startDevManifestWatcher.js';
122
136
  interfaces: patch.interfaces
123
137
  });
124
138
  // The recreated server can bind a different port (non-strict ports).
139
+ if (rebuiltServer) liveServer = rebuiltServer;
125
140
  registration.update(rebuiltServer ? {
126
141
  ...patch,
127
142
  ...serverAddress(rebuiltServer)
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/actions/dev/startDevServerRegistration.ts"],"sourcesContent":["import {type CliConfig, getCliConfigUncached, type Output} from '@sanity/cli-core'\nimport {type ViteDevServer} from 'vite'\n\nimport {isWorkbenchApp, isWorkbenchConfig} from '../../defineApp.js'\nimport {deriveInterfaces} from '../../deriveInterfaces.js'\nimport {resolveWorkbenchConfig} from '../../resolveWorkbenchConfig.js'\nimport {formatWorkbenchAppErrors, validateWorkbenchApp} from '../../validateWorkbenchApp.js'\nimport {deriveConfigs} from './deriveConfigs.js'\nimport {trackExposesSet} from './exposesSetId.js'\nimport {\n dashboardPath,\n type DevServerManifest,\n getRegisteredServers,\n localAppIdentity,\n registerDevServer,\n} from './registry.js'\nimport {startDevManifestWatcher} from './startDevManifestWatcher.js'\n\ninterface DevServerRegistrationOptions {\n cliConfig: CliConfig\n /**\n * Extract the project manifest to inline into the registry. The caller owns the\n * studio-vs-app split (manifest formats are CLI-domain); registration re-derives\n * the interface set alongside it.\n */\n extractManifest: (params: {\n applicationId?: string\n configPath: string\n workDir: string\n }) => Promise<DevServerManifest['manifest']>\n isApp: boolean\n output: Output\n server: ViteDevServer\n workDir: string\n\n /**\n * Rebuild the app's federation remote when its interface set changes, awaited\n * *before* the registry patch — the patch reloads the workbench page, which must\n * re-fetch a remote that already exposes the new interface. Resolves with the\n * recreated server so the entry gets its actual address (non-strict ports may\n * shift it); must reject if the restart produces no server, so the set stays\n * uncommitted and the next save retries instead of advertising a dead port.\n */\n onInterfaceSetChange?: () => Promise<ViteDevServer>\n}\n\ninterface DevServerRegistrationHandle {\n close: () => Promise<void>\n\n /** Where the Dashboard opens this server; unset when it can't open it there. */\n path?: string\n}\n\n/**\n * Log any app validation errors without aborting. Unlike build and deploy, dev\n * stays up on an invalid app so the author sees the errors and fixes them live on\n * the next save. A config is not an app — it isn't validated by the app schema\n * (which would spuriously demand a slug/title), so skip it here.\n */\nfunction reportConfigErrors(app: CliConfig['app'], output: Output): void {\n if (isWorkbenchConfig(app)) return\n const errors = validateWorkbenchApp(app)\n if (errors.length === 0) return\n output.warn(formatWorkbenchAppErrors(errors))\n}\n\n/** The address the server actually bound — the live socket, which can differ from the configured port under non-strict ports. */\nfunction serverAddress(server: ViteDevServer) {\n const resolvedHost = server.config.server.host\n const addr = server.httpServer?.address()\n return {\n host: typeof resolvedHost === 'string' ? resolvedHost : 'localhost',\n https: Boolean(server.config.server.https),\n port: typeof addr === 'object' && addr ? addr.port : server.config.server.port,\n }\n}\n\n/**\n * Register the dev server in the registry and watch its config for manifest +\n * interface changes. The workbench reads the entry to locate and render the\n * server; the watcher keeps it current as `sanity.cli.ts` is edited.\n */\nexport async function startDevServerRegistration(\n options: DevServerRegistrationOptions,\n): Promise<DevServerRegistrationHandle> {\n const {cliConfig, extractManifest, isApp, onInterfaceSetChange, output, server, workDir} = options\n\n const {host: appHost, https, port: appPort} = serverAddress(server)\n\n reportConfigErrors(cliConfig.app, output)\n\n // Forwarded alongside (not inside) the manifest so the workbench renders local\n // panels/workers and reads the configs without a deploy.\n const interfaces = deriveInterfaces(cliConfig.app, {isApp})\n const configs = await deriveConfigs(cliConfig)\n\n const workbenchApp = isWorkbenchApp(cliConfig.app) ? cliConfig.app : undefined\n const config = resolveWorkbenchConfig(cliConfig)\n // A config runs alongside the app it configures, so give it its own id\n // namespace — sharing the app's slug would make the two indistinguishable here.\n const id = config ? `config:${config.appType}` : workbenchApp?.slug\n const applicationId = workbenchApp ? cliConfig.deployment?.appId : undefined\n // Identity is resolved and the reference composed here, so the workbench reads\n // both off the registry entry instead of recomposing them.\n const identity = workbenchApp ? localAppIdentity(workbenchApp) : undefined\n\n // The Dashboard tells local apps apart by their bus id and by the application\n // they stand in for.\n const organizationId = cliConfig.app?.organizationId\n const devServer = getRegisteredServers().find(\n (server) =>\n server.organizationId === organizationId &&\n (server.id === id || (applicationId && server.applicationId === applicationId)),\n )\n\n if (id && devServer) {\n const served =\n devServer.id === id\n ? `\"${id}\" is already served`\n : `\"${id}\" is the same application as \"${devServer.id}\", served`\n output.error(\n `${served} by another dev server running on port ${devServer.port}, ` +\n \"so the Dashboard can't tell them apart and this one stays out of it. Stop that server first.\",\n {exit: false},\n )\n return {close: async () => {}}\n }\n\n const registration = registerDevServer({\n applicationId,\n configs,\n host: appHost,\n https,\n id,\n interfaces,\n organizationId,\n port: appPort,\n projectId: cliConfig?.api?.projectId,\n ...identity,\n type: isApp ? 'coreApp' : 'studio',\n workDir,\n })\n\n const exposesSet = trackExposesSet({configs, interfaces})\n\n const watcher = await startDevManifestWatcher({\n // Re-derive every pass (don't omit): the registry patch is a shallow merge,\n // so omitting would wipe the registered set.\n extract: async (params) => {\n const nextConfig = await getCliConfigUncached(params.workDir)\n reportConfigErrors(nextConfig.app, output)\n return {\n configs: await deriveConfigs(nextConfig),\n interfaces: deriveInterfaces(nextConfig.app, {isApp}),\n manifest: await extractManifest({...params, applicationId: id}),\n }\n },\n // A studio's root resolves to `sanity.config.*` but its interfaces live in\n // `sanity.cli.*` — watch that too. Apps already root at `sanity.cli.*`.\n extraWatchFilenames: isApp ? undefined : ['sanity.cli.js', 'sanity.cli.ts'],\n output,\n update: async (patch) => {\n if (\n !exposesSet.changed({\n configs: patch.configs,\n interfaces: patch.interfaces,\n })\n ) {\n registration.update(patch)\n return\n }\n // Rebuild the remote *before* patching the registry — the patch reloads the\n // page, which must re-fetch a remote that already exposes the new interface.\n const rebuiltServer = await onInterfaceSetChange?.()\n // Commit only after a successful rebuild, so a thrown one retries next pass.\n exposesSet.commit({\n configs: patch.configs,\n interfaces: patch.interfaces,\n })\n // The recreated server can bind a different port (non-strict ports).\n registration.update(rebuiltServer ? {...patch, ...serverAddress(rebuiltServer)} : patch)\n },\n workDir,\n })\n\n return {\n close: async () => {\n registration.release()\n await watcher.close()\n },\n path: dashboardPath({\n id,\n interfaces,\n slug: identity?.slug,\n type: isApp ? 'coreApp' : 'studio',\n }),\n }\n}\n"],"names":["getCliConfigUncached","isWorkbenchApp","isWorkbenchConfig","deriveInterfaces","resolveWorkbenchConfig","formatWorkbenchAppErrors","validateWorkbenchApp","deriveConfigs","trackExposesSet","dashboardPath","getRegisteredServers","localAppIdentity","registerDevServer","startDevManifestWatcher","reportConfigErrors","app","output","errors","length","warn","serverAddress","server","resolvedHost","config","host","addr","httpServer","address","https","Boolean","port","startDevServerRegistration","options","cliConfig","extractManifest","isApp","onInterfaceSetChange","workDir","appHost","appPort","interfaces","configs","workbenchApp","undefined","id","appType","slug","applicationId","deployment","appId","identity","organizationId","devServer","find","served","error","exit","close","registration","projectId","api","type","exposesSet","watcher","extract","params","nextConfig","manifest","extraWatchFilenames","update","patch","changed","rebuiltServer","commit","release","path"],"mappings":"AAAA,SAAwBA,oBAAoB,QAAoB,mBAAkB;AAGlF,SAAQC,cAAc,EAAEC,iBAAiB,QAAO,qBAAoB;AACpE,SAAQC,gBAAgB,QAAO,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;QAASD;IAAU;IAEvD,MAAMuB,UAAU,MAAMlD,wBAAwB;QAC5C,4EAA4E;QAC5E,6CAA6C;QAC7CmD,SAAS,OAAOC;YACd,MAAMC,aAAa,MAAMlE,qBAAqBiE,OAAO5B,OAAO;YAC5DvB,mBAAmBoD,WAAWnD,GAAG,EAAEC;YACnC,OAAO;gBACLyB,SAAS,MAAMlC,cAAc2D;gBAC7B1B,YAAYrC,iBAAiB+D,WAAWnD,GAAG,EAAE;oBAACoB;gBAAK;gBACnDgC,UAAU,MAAMjC,gBAAgB;oBAAC,GAAG+B,MAAM;oBAAElB,eAAeH;gBAAE;YAC/D;QACF;QACA,2EAA2E;QAC3E,wEAAwE;QACxEwB,qBAAqBjC,QAAQQ,YAAY;YAAC;YAAiB;SAAgB;QAC3E3B;QACAqD,QAAQ,OAAOC;YACb,IACE,CAACR,WAAWS,OAAO,CAAC;gBAClB9B,SAAS6B,MAAM7B,OAAO;gBACtBD,YAAY8B,MAAM9B,UAAU;YAC9B,IACA;gBACAkB,aAAaW,MAAM,CAACC;gBACpB;YACF;YACA,4EAA4E;YAC5E,6EAA6E;YAC7E,MAAME,gBAAgB,MAAMpC;YAC5B,6EAA6E;YAC7E0B,WAAWW,MAAM,CAAC;gBAChBhC,SAAS6B,MAAM7B,OAAO;gBACtBD,YAAY8B,MAAM9B,UAAU;YAC9B;YACA,qEAAqE;YACrEkB,aAAaW,MAAM,CAACG,gBAAgB;gBAAC,GAAGF,KAAK;gBAAE,GAAGlD,cAAcoD,cAAc;YAAA,IAAIF;QACpF;QACAjC;IACF;IAEA,OAAO;QACLoB,OAAO;YACLC,aAAagB,OAAO;YACpB,MAAMX,QAAQN,KAAK;QACrB;QACAkB,MAAMlE,cAAc;YAClBmC;YACAJ;YACAM,MAAMI,UAAUJ;YAChBe,MAAM1B,QAAQ,YAAY;QAC5B;IACF;AACF"}
1
+ {"version":3,"sources":["../../../src/actions/dev/startDevServerRegistration.ts"],"sourcesContent":["import {relative} from 'node:path'\n\nimport {type CliConfig, getCliConfigUncached, type Output} from '@sanity/cli-core'\nimport {type ViteDevServer} from 'vite'\n\nimport {isWorkbenchApp, isWorkbenchConfig} from '../../defineApp.js'\nimport {deriveInterfaces} from '../../deriveInterfaces.js'\nimport {readAppIcon, toUrlPath} from '../../readAppIcon.js'\nimport {resolveWorkbenchConfig} from '../../resolveWorkbenchConfig.js'\nimport {formatWorkbenchAppErrors, validateWorkbenchApp} from '../../validateWorkbenchApp.js'\nimport {deriveConfigs} from './deriveConfigs.js'\nimport {trackExposesSet} from './exposesSetId.js'\nimport {\n dashboardPath,\n type DevServerManifest,\n getRegisteredServers,\n localAppIdentity,\n registerDevServer,\n} from './registry.js'\nimport {startDevManifestWatcher} from './startDevManifestWatcher.js'\n\ninterface DevServerRegistrationOptions {\n cliConfig: CliConfig\n /**\n * Extract the project manifest to inline into the registry. The caller owns the\n * studio-vs-app split (manifest formats are CLI-domain); registration re-derives\n * the interface set alongside it.\n */\n extractManifest: (params: {\n applicationId?: string\n configPath: string\n /** Where this server serves the app's icon. */\n iconUrl?: string\n workDir: string\n }) => Promise<DevServerManifest['manifest']>\n isApp: boolean\n output: Output\n server: ViteDevServer\n workDir: string\n\n /**\n * Rebuild the app's federation remote when its interface set changes, awaited\n * *before* the registry patch — the patch reloads the workbench page, which must\n * re-fetch a remote that already exposes the new interface. Resolves with the\n * recreated server so the entry gets its actual address (non-strict ports may\n * shift it); must reject if the restart produces no server, so the set stays\n * uncommitted and the next save retries instead of advertising a dead port.\n */\n onInterfaceSetChange?: () => Promise<ViteDevServer>\n}\n\ninterface DevServerRegistrationHandle {\n close: () => Promise<void>\n\n /** Where the Dashboard opens this server; unset when it can't open it there. */\n path?: string\n}\n\n/**\n * Log any app validation errors without aborting. Unlike build and deploy, dev\n * stays up on an invalid app so the author sees the errors and fixes them live on\n * the next save. A config is not an app — it isn't validated by the app schema\n * (which would spuriously demand a slug/title), so skip it here.\n */\nfunction reportConfigErrors(app: CliConfig['app'], output: Output): void {\n if (isWorkbenchConfig(app)) return\n const errors = validateWorkbenchApp(app)\n if (errors.length === 0) return\n output.warn(formatWorkbenchAppErrors(errors))\n}\n\n/** The address the server actually bound — the live socket, which can differ from the configured port under non-strict ports. */\nfunction serverAddress(server: ViteDevServer) {\n const resolvedHost = server.config.server.host\n const addr = server.httpServer?.address()\n return {\n host: typeof resolvedHost === 'string' ? resolvedHost : 'localhost',\n https: Boolean(server.config.server.https),\n port: typeof addr === 'object' && addr ? addr.port : server.config.server.port,\n }\n}\n\n/**\n * Register the dev server in the registry and watch its config for manifest +\n * interface changes. The workbench reads the entry to locate and render the\n * server; the watcher keeps it current as `sanity.cli.ts` is edited.\n */\nexport async function startDevServerRegistration(\n options: DevServerRegistrationOptions,\n): Promise<DevServerRegistrationHandle> {\n const {cliConfig, extractManifest, isApp, onInterfaceSetChange, output, server, workDir} = options\n\n const {host: appHost, https, port: appPort} = serverAddress(server)\n\n reportConfigErrors(cliConfig.app, output)\n\n // Forwarded alongside (not inside) the manifest so the workbench renders local\n // panels/workers and reads the configs without a deploy.\n const interfaces = deriveInterfaces(cliConfig.app, {isApp})\n const configs = await deriveConfigs(cliConfig)\n\n const workbenchApp = isWorkbenchApp(cliConfig.app) ? cliConfig.app : undefined\n const config = resolveWorkbenchConfig(cliConfig)\n // A config runs alongside the app it configures, so give it its own id\n // namespace — sharing the app's slug would make the two indistinguishable here.\n const id = config ? `config:${config.appType}` : workbenchApp?.slug\n const applicationId = workbenchApp ? cliConfig.deployment?.appId : undefined\n // Identity is resolved and the reference composed here, so the workbench reads\n // both off the registry entry instead of recomposing them.\n const identity = workbenchApp ? localAppIdentity(workbenchApp) : undefined\n\n // The Dashboard tells local apps apart by their bus id and by the application\n // they stand in for.\n const organizationId = cliConfig.app?.organizationId\n const devServer = getRegisteredServers().find(\n (server) =>\n server.organizationId === organizationId &&\n (server.id === id || (applicationId && server.applicationId === applicationId)),\n )\n\n if (id && devServer) {\n const served =\n devServer.id === id\n ? `\"${id}\" is already served`\n : `\"${id}\" is the same application as \"${devServer.id}\", served`\n output.error(\n `${served} by another dev server running on port ${devServer.port}, ` +\n \"so the Dashboard can't tell them apart and this one stays out of it. Stop that server first.\",\n {exit: false},\n )\n return {close: async () => {}}\n }\n\n const registration = registerDevServer({\n applicationId,\n configs,\n host: appHost,\n https,\n id,\n interfaces,\n organizationId,\n port: appPort,\n projectId: cliConfig?.api?.projectId,\n ...identity,\n type: isApp ? 'coreApp' : 'studio',\n workDir,\n })\n\n const exposesSet = trackExposesSet({configs, interfaces})\n let liveServer = server\n\n const watcher = await startDevManifestWatcher({\n // Re-derive every pass (don't omit): the registry patch is a shallow merge,\n // so omitting would wipe the registered set.\n extract: async (params) => {\n const nextConfig = await getCliConfigUncached(params.workDir)\n reportConfigErrors(nextConfig.app, output)\n\n let iconUrl: string | undefined\n if (isApp && isWorkbenchApp(nextConfig.app) && nextConfig.app.icon) {\n // Read in full so an image a deploy would reject warns here, while editing.\n const {file} = await readAppIcon(workDir, nextConfig.app.icon)\n // Vite serves `public/` at the root, and warns on every request for `/public/...`.\n const {base, publicDir, root} = liveServer.config\n const inPublicDir = Boolean(publicDir) && !relative(publicDir, file).startsWith('..')\n const {host, https, port} = serverAddress(liveServer)\n iconUrl = `${https ? 'https' : 'http'}://${host}:${port}${base}${toUrlPath(inPublicDir ? publicDir : root, file)}`\n }\n\n return {\n configs: await deriveConfigs(nextConfig),\n interfaces: deriveInterfaces(nextConfig.app, {isApp}),\n manifest: await extractManifest({...params, applicationId: id, iconUrl}),\n }\n },\n // A studio's root resolves to `sanity.config.*` but its interfaces live in\n // `sanity.cli.*` — watch that too. Apps already root at `sanity.cli.*`.\n extraWatchFilenames: isApp ? undefined : ['sanity.cli.js', 'sanity.cli.ts'],\n output,\n update: async (patch) => {\n if (\n !exposesSet.changed({\n configs: patch.configs,\n interfaces: patch.interfaces,\n })\n ) {\n registration.update(patch)\n return\n }\n // Rebuild the remote *before* patching the registry — the patch reloads the\n // page, which must re-fetch a remote that already exposes the new interface.\n const rebuiltServer = await onInterfaceSetChange?.()\n // Commit only after a successful rebuild, so a thrown one retries next pass.\n exposesSet.commit({\n configs: patch.configs,\n interfaces: patch.interfaces,\n })\n // The recreated server can bind a different port (non-strict ports).\n if (rebuiltServer) liveServer = rebuiltServer\n registration.update(rebuiltServer ? {...patch, ...serverAddress(rebuiltServer)} : patch)\n },\n workDir,\n })\n\n return {\n close: async () => {\n registration.release()\n await watcher.close()\n },\n path: dashboardPath({\n id,\n interfaces,\n slug: identity?.slug,\n type: isApp ? 'coreApp' : 'studio',\n }),\n }\n}\n"],"names":["relative","getCliConfigUncached","isWorkbenchApp","isWorkbenchConfig","deriveInterfaces","readAppIcon","toUrlPath","resolveWorkbenchConfig","formatWorkbenchAppErrors","validateWorkbenchApp","deriveConfigs","trackExposesSet","dashboardPath","getRegisteredServers","localAppIdentity","registerDevServer","startDevManifestWatcher","reportConfigErrors","app","output","errors","length","warn","serverAddress","server","resolvedHost","config","host","addr","httpServer","address","https","Boolean","port","startDevServerRegistration","options","cliConfig","extractManifest","isApp","onInterfaceSetChange","workDir","appHost","appPort","interfaces","configs","workbenchApp","undefined","id","appType","slug","applicationId","deployment","appId","identity","organizationId","devServer","find","served","error","exit","close","registration","projectId","api","type","exposesSet","liveServer","watcher","extract","params","nextConfig","iconUrl","icon","file","base","publicDir","root","inPublicDir","startsWith","manifest","extraWatchFilenames","update","patch","changed","rebuiltServer","commit","release","path"],"mappings":"AAAA,SAAQA,QAAQ,QAAO,YAAW;AAElC,SAAwBC,oBAAoB,QAAoB,mBAAkB;AAGlF,SAAQC,cAAc,EAAEC,iBAAiB,QAAO,qBAAoB;AACpE,SAAQC,gBAAgB,QAAO,4BAA2B;AAC1D,SAAQC,WAAW,EAAEC,SAAS,QAAO,uBAAsB;AAC3D,SAAQC,sBAAsB,QAAO,kCAAiC;AACtE,SAAQC,wBAAwB,EAAEC,oBAAoB,QAAO,gCAA+B;AAC5F,SAAQC,aAAa,QAAO,qBAAoB;AAChD,SAAQC,eAAe,Q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