@sanity/workbench-cli 2.16.1 → 2.18.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 (33) hide show
  1. package/dist/_exports/deploy.d.ts +17 -1
  2. package/dist/_exports/deploy.js +1 -0
  3. package/dist/_exports/deploy.js.map +1 -1
  4. package/dist/_exports/dev.d.ts +3 -2
  5. package/dist/_exports/preview.d.ts +1 -1
  6. package/dist/_exports/{registry-NvtHmoN1.d.ts → registry-CbruhmxE.d.ts} +2 -1
  7. package/dist/actions/deploy/deploySummary.js +36 -0
  8. package/dist/actions/deploy/deploySummary.js.map +1 -0
  9. package/dist/actions/dev/appServerSupervisor.js +3 -1
  10. package/dist/actions/dev/appServerSupervisor.js.map +1 -1
  11. package/dist/actions/dev/bindDevShortcuts.js +33 -0
  12. package/dist/actions/dev/bindDevShortcuts.js.map +1 -0
  13. package/dist/actions/dev/devSummary.js +49 -0
  14. package/dist/actions/dev/devSummary.js.map +1 -0
  15. package/dist/actions/dev/registry.js +1 -0
  16. package/dist/actions/dev/registry.js.map +1 -1
  17. package/dist/actions/dev/startDevServerRegistration.js +3 -1
  18. package/dist/actions/dev/startDevServerRegistration.js.map +1 -1
  19. package/dist/actions/dev/startWorkbenchDev.js +46 -11
  20. package/dist/actions/dev/startWorkbenchDev.js.map +1 -1
  21. package/dist/actions/dev/startWorkbenchDevServer.js +4 -3
  22. package/dist/actions/dev/startWorkbenchDevServer.js.map +1 -1
  23. package/dist/actions/summary.js +19 -0
  24. package/dist/actions/summary.js.map +1 -0
  25. package/dist/renderDashboard.js +1 -1
  26. package/dist/renderDashboard.js.map +1 -1
  27. package/dist/services/applications.js +22 -0
  28. package/dist/services/applications.js.map +1 -1
  29. package/dist/services/organizations.js +14 -0
  30. package/dist/services/organizations.js.map +1 -0
  31. package/dist/services/users.js +24 -0
  32. package/dist/services/users.js.map +1 -0
  33. package/package.json +6 -5
@@ -61,6 +61,22 @@ declare function toWorkbenchPayload(workbench: DeployableWorkbenchApp | null, {
61
61
  } | null;
62
62
  title: string;
63
63
  }): Partial<WorkbenchDeployPayload>;
64
+ declare function fetchDeploySummaryDetails(organizationId: string): Promise<{
65
+ organizationName: string | null;
66
+ userName: string | null;
67
+ }>;
68
+ declare function formatDeploySummary(options: {
69
+ applicationId: string;
70
+ created: boolean;
71
+ durationMs: number;
72
+ isApp: boolean;
73
+ organizationId: string;
74
+ organizationName?: string | null;
75
+ showAppIdHint: boolean;
76
+ title: string;
77
+ url: string;
78
+ userName?: string | null;
79
+ }): string;
64
80
  type ApplicationType = 'coreApp' | 'studio';
65
81
  interface Application {
66
82
  id: string;
@@ -181,5 +197,5 @@ declare function selectWorkbenchAppId({ appId, flags, organizationId, type }: {
181
197
  organizationId: string | undefined;
182
198
  type: ApplicationType;
183
199
  }): 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 };
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 };
185
201
  //# sourceMappingURL=deploy.d.ts.map
@@ -1,5 +1,6 @@
1
1
  export { deployConfig, resolveInstallationId, summarizeConfig } from '../actions/deploy/deployConfig.js';
2
2
  export { toWorkbenchPayload } from '../actions/deploy/deployPayload.js';
3
+ export { fetchDeploySummaryDetails, formatDeploySummary } from '../actions/deploy/deploySummary.js';
3
4
  export { createCoreApp, createStudio, deployWorkbenchApp } from '../actions/deploy/deployWorkbenchApp.js';
4
5
  export { getWorkbench } from '../actions/deploy/getWorkbench.js';
5
6
  export { selectWorkbenchAppId } from '../actions/deploy/selectWorkbenchAppId.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 {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
+ {"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,4 +1,4 @@
1
- import { t as DevServerManifest } from "./registry-NvtHmoN1.js";
1
+ import { t as DevServerManifest } from "./registry-CbruhmxE.js";
2
2
  import { ViteDevServer } from "vite";
3
3
  import { CliConfig, Output } from "@sanity/cli-core";
4
4
  /**
@@ -33,9 +33,10 @@ interface StartWorkbenchDevOptions {
33
33
  reactStrictMode: boolean;
34
34
  /** Start the app/studio dev server — the CLI owns the server, this orchestrates it. */
35
35
  startAppServer: (params: {
36
- announceUrl: boolean;
37
36
  cliConfig: CliConfig;
38
37
  httpPort: number;
38
+ isRestarting?: boolean;
39
+ quiet?: boolean;
39
40
  }) => Promise<AppServerResult>;
40
41
  workDir: string;
41
42
  }
@@ -1,4 +1,4 @@
1
- import { t as DevServerManifest } from "./registry-NvtHmoN1.js";
1
+ import { t as DevServerManifest } from "./registry-CbruhmxE.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. */
@@ -15,6 +15,7 @@ declare const devServerManifestSchema: z.ZodMiniObject<{
15
15
  version: z.ZodMiniString<string>;
16
16
  }, z.core.$strip>>>;
17
17
  host: z.ZodMiniString<string>;
18
+ https: z.ZodMiniOptional<z.ZodMiniBoolean<boolean>>;
18
19
  id: z.ZodMiniOptional<z.ZodMiniString<string>>;
19
20
  interfaces: z.ZodMiniOptional<z.ZodMiniArray<z.ZodMiniUnion<readonly [z.ZodMiniDiscriminatedUnion<[z.ZodMiniObject<{
20
21
  metadata: z.ZodMiniNullable<z.ZodMiniObject<{
@@ -129,4 +130,4 @@ declare const devServerManifestSchema: z.ZodMiniObject<{
129
130
  */
130
131
  type DevServerManifest = z.infer<typeof devServerManifestSchema>;
131
132
  export { DevServerManifest as t };
132
- //# sourceMappingURL=registry-NvtHmoN1.d.ts.map
133
+ //# sourceMappingURL=registry-CbruhmxE.d.ts.map
@@ -0,0 +1,36 @@
1
+ import { styleText } from 'node:util';
2
+ import { logSymbols } from '@sanity/cli-core/ux';
3
+ import { getOrganization } from '../../services/organizations.js';
4
+ import { getCurrentUser } from '../../services/users.js';
5
+ import { formatSummary, SUMMARY_LOOKUP_TIMEOUT_MS } from '../summary.js';
6
+ export async function fetchDeploySummaryDetails(organizationId) {
7
+ const signal = AbortSignal.timeout(SUMMARY_LOOKUP_TIMEOUT_MS);
8
+ const [organizationName, userName] = await Promise.all([
9
+ getOrganization(organizationId, signal).then((org)=>org.name).catch(()=>null),
10
+ getCurrentUser(signal).then((user)=>user.name).catch(()=>null)
11
+ ]);
12
+ return {
13
+ organizationName,
14
+ userName
15
+ };
16
+ }
17
+ export function formatDeploySummary(options) {
18
+ const { applicationId, created, durationMs, isApp, showAppIdHint, title, url, userName } = options;
19
+ const summary = formatSummary({
20
+ durationMs,
21
+ heading: `${title} deployed`,
22
+ isApp,
23
+ organization: options.organizationName ?? options.organizationId,
24
+ title,
25
+ url,
26
+ version: userName ? `just now by ${userName}` : 'just now'
27
+ });
28
+ const result = created ? `Created ${title} as a new ${isApp ? 'application' : 'studio'}.` : `Updated ${title}.`;
29
+ const success = styleText('green', ` ${logSymbols.success} ${result}`);
30
+ const appIdHint = showAppIdHint ? `\n ${styleText('dim', 'Add')} deployment.appId: "${applicationId}" ${styleText('dim', 'to sanity.cli.ts so the next deploy updates it')}\n` : '';
31
+ return `${summary}
32
+ ${success}
33
+ ${appIdHint}`;
34
+ }
35
+
36
+ //# sourceMappingURL=deploySummary.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/actions/deploy/deploySummary.ts"],"sourcesContent":["import {styleText} from 'node:util'\n\nimport {logSymbols} from '@sanity/cli-core/ux'\n\nimport {getOrganization} from '../../services/organizations.js'\nimport {getCurrentUser} from '../../services/users.js'\nimport {formatSummary, SUMMARY_LOOKUP_TIMEOUT_MS} from '../summary.js'\n\nexport async function fetchDeploySummaryDetails(organizationId: string) {\n const signal = AbortSignal.timeout(SUMMARY_LOOKUP_TIMEOUT_MS)\n const [organizationName, userName] = await Promise.all([\n getOrganization(organizationId, signal)\n .then((org) => org.name)\n .catch(() => null),\n getCurrentUser(signal)\n .then((user) => user.name)\n .catch(() => null),\n ])\n\n return {organizationName, userName}\n}\n\nexport function formatDeploySummary(options: {\n applicationId: string\n created: boolean\n durationMs: number\n isApp: boolean\n organizationId: string\n organizationName?: string | null\n showAppIdHint: boolean\n title: string\n url: string\n userName?: string | null\n}): string {\n const {applicationId, created, durationMs, isApp, showAppIdHint, title, url, userName} = options\n\n const summary = formatSummary({\n durationMs,\n heading: `${title} deployed`,\n isApp,\n organization: options.organizationName ?? options.organizationId,\n title,\n url,\n version: userName ? `just now by ${userName}` : 'just now',\n })\n const result = created\n ? `Created ${title} as a new ${isApp ? 'application' : 'studio'}.`\n : `Updated ${title}.`\n const success = styleText('green', ` ${logSymbols.success} ${result}`)\n const appIdHint = showAppIdHint\n ? `\\n ${styleText('dim', 'Add')} deployment.appId: \"${applicationId}\" ${styleText('dim', 'to sanity.cli.ts so the next deploy updates it')}\\n`\n : ''\n\n return `${summary}\n${success}\n${appIdHint}`\n}\n"],"names":["styleText","logSymbols","getOrganization","getCurrentUser","formatSummary","SUMMARY_LOOKUP_TIMEOUT_MS","fetchDeploySummaryDetails","organizationId","signal","AbortSignal","timeout","organizationName","userName","Promise","all","then","org","name","catch","user","formatDeploySummary","options","applicationId","created","durationMs","isApp","showAppIdHint","title","url","summary","heading","organization","version","result","success","appIdHint"],"mappings":"AAAA,SAAQA,SAAS,QAAO,YAAW;AAEnC,SAAQC,UAAU,QAAO,sBAAqB;AAE9C,SAAQC,eAAe,QAAO,kCAAiC;AAC/D,SAAQC,cAAc,QAA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EC,WAAW;AACb"}
@@ -34,7 +34,9 @@ const noop = async ()=>{};
34
34
  const freshConfig = await getCliConfigUncached(workDir);
35
35
  await closeCurrent();
36
36
  closeCurrent = noop;
37
- const result = await start(freshConfig);
37
+ const result = await start(freshConfig, {
38
+ isRestarting: true
39
+ });
38
40
  if (!result.started) {
39
41
  // The server already reported why (e.g. organizationId was removed).
40
42
  throw new Error('Dev server did not restart after the view/web worker change');
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/actions/dev/appServerSupervisor.ts"],"sourcesContent":["import {type CliConfig, getCliConfigUncached} from '@sanity/cli-core'\nimport {type ViteDevServer} from 'vite'\n\n/**\n * Minimal shape the supervisor needs back from a started app/studio dev server.\n * The not-started arm is reserved for expected early exits the server already\n * reported (e.g. a missing organization id) — a failure to *boot* still throws.\n */\nexport type AppServerResult =\n | {close: () => Promise<void>; server: ViteDevServer; started: true}\n | {reason: string; started: false}\n\n/** Start the app/studio dev server for a given config (port + URL intent baked in by the caller). */\nexport type StartAppServer = (cliConfig: CliConfig) => Promise<AppServerResult>\n\nconst noop = async () => {}\n\nexport interface AppServerSupervisor {\n /** Stop the server once, waiting out any rebuild already in flight. */\n close: () => Promise<void>\n /** Tear down the running server and bring it back up with a freshly-loaded config. */\n rebuild: () => Promise<ViteDevServer>\n /** The currently-live dev server; re-points after a rebuild. */\n readonly server: ViteDevServer\n}\n\n/**\n * Own the app/studio dev server's lifecycle behind the dev-server registry seam.\n *\n * Adding or removing a view/web worker rebuilds the federation remote: its\n * module-federation `exposes` map and codegen artifacts are computed once at\n * server start, so a newly-declared interface has no expose until the server is\n * recreated — `server.restart()` can't do it (it reuses the inline config).\n * `rebuild` therefore tears the server down and starts a fresh one with a\n * reloaded config; the registry watcher calls it when the interface set changes.\n *\n * Returns the not-started result verbatim when the initial boot is an expected\n * early exit, so the caller can skip the rest of the orchestration.\n */\nexport async function startAppServerSupervisor(options: {\n cliConfig: CliConfig\n start: StartAppServer\n workDir: string\n}): Promise<{reason: string; started: false} | {started: true; supervisor: AppServerSupervisor}> {\n const {cliConfig, start, workDir} = options\n\n const initial = await start(cliConfig)\n if (!initial.started) return {reason: initial.reason, started: false}\n\n // `closeCurrent` repoints at the replacement only once a rebuild succeeds, so a\n // failed rebuild (old server already closed) leaves nothing for close() to re-close.\n let server = initial.server\n let closeCurrent = initial.close\n let closed = false\n // close() waits on this so a rebuild racing teardown can't orphan the replacement.\n // Rejections are the watcher's (warn + retry); the tracked copy is swallowed.\n let rebuildInFlight: Promise<unknown> = Promise.resolve()\n\n const runRebuild = async (): Promise<ViteDevServer> => {\n // Refuse once shutting down — a config save in the teardown window must not\n // boot a replacement nobody owns.\n if (closed) throw new Error('Dev server is shutting down')\n const freshConfig = await getCliConfigUncached(workDir)\n await closeCurrent()\n closeCurrent = noop\n const result = await start(freshConfig)\n if (!result.started) {\n // The server already reported why (e.g. organizationId was removed).\n throw new Error('Dev server did not restart after the view/web worker change')\n }\n server = result.server\n closeCurrent = result.close\n return server\n }\n\n return {\n started: true,\n supervisor: {\n async close() {\n closed = true\n await rebuildInFlight\n await closeCurrent()\n },\n rebuild() {\n const rebuild = runRebuild()\n rebuildInFlight = rebuild.catch(() => {})\n return rebuild\n },\n get server() {\n return server\n },\n },\n }\n}\n"],"names":["getCliConfigUncached","noop","startAppServerSupervisor","options","cliConfig","start","workDir","initial","started","reason","server","closeCurrent","close","closed","rebuildInFlight","Promise","resolve","runRebuild","Error","freshConfig","result","supervisor","rebuild","catch"],"mappings":"AAAA,SAAwBA,oBAAoB,QAAO,mBAAkB;AAerE,MAAMC,OAAO,WAAa;AAW1B;;;;;;;;;;;;CAYC,GACD,OAAO,eAAeC,yBAAyBC,OAI9C;IACC,MAAM,EAACC,SAAS,EAAEC,KAAK,EAAEC,OAAO,EAAC,GAAGH;IAEpC,MAAMI,UAAU,MAAMF,MAAMD;IAC5B,IAAI,CAACG,QAAQC,OAAO,EAAE,OAAO;QAACC,QAAQF,QAAQE,MAAM;QAAED,SAAS;IAAK;IAEpE,gFAAgF;IAChF,qFAAqF;IACrF,IAAIE,SAASH,QAAQG,MAAM;IAC3B,IAAIC,eAAeJ,QAAQK,KAAK;IAChC,IAAIC,SAAS;IACb,mFAAmF;IACnF,8EAA8E;IAC9E,IAAIC,kBAAoCC,QAAQC,OAAO;IAEvD,MAAMC,aAAa;QACjB,4EAA4E;QAC5E,kCAAkC;QAClC,IAAIJ,QAAQ,MAAM,IAAIK,MAAM;QAC5B,MAAMC,cAAc,MAAMnB,qBAAqBM;QAC/C,MAAMK;QACNA,eAAeV;QACf,MAAMmB,SAAS,MAAMf,MAAMc;QAC3B,IAAI,CAACC,OAAOZ,OAAO,EAAE;YACnB,qEAAqE;YACrE,MAAM,IAAIU,MAAM;QAClB;QACAR,SAASU,OAAOV,MAAM;QACtBC,eAAeS,OAAOR,KAAK;QAC3B,OAAOF;IACT;IAEA,OAAO;QACLF,SAAS;QACTa,YAAY;YACV,MAAMT;gBACJC,SAAS;gBACT,MAAMC;gBACN,MAAMH;YACR;YACAW;gBACE,MAAMA,UAAUL;gBAChBH,kBAAkBQ,QAAQC,KAAK,CAAC,KAAO;gBACvC,OAAOD;YACT;YACA,IAAIZ;gBACF,OAAOA;YACT;QACF;IACF;AACF"}
1
+ {"version":3,"sources":["../../../src/actions/dev/appServerSupervisor.ts"],"sourcesContent":["import {type CliConfig, getCliConfigUncached} from '@sanity/cli-core'\nimport {type ViteDevServer} from 'vite'\n\n/**\n * Minimal shape the supervisor needs back from a started app/studio dev server.\n * The not-started arm is reserved for expected early exits the server already\n * reported (e.g. a missing organization id) — a failure to *boot* still throws.\n */\nexport type AppServerResult =\n | {close: () => Promise<void>; server: ViteDevServer; started: true}\n | {reason: string; started: false}\n\n/** Start the app/studio dev server for a given config (port + URL intent baked in by the caller). */\nexport type StartAppServer = (\n cliConfig: CliConfig,\n options?: {isRestarting?: boolean},\n) => Promise<AppServerResult>\n\nconst noop = async () => {}\n\nexport interface AppServerSupervisor {\n /** Stop the server once, waiting out any rebuild already in flight. */\n close: () => Promise<void>\n /** Tear down the running server and bring it back up with a freshly-loaded config. */\n rebuild: () => Promise<ViteDevServer>\n /** The currently-live dev server; re-points after a rebuild. */\n readonly server: ViteDevServer\n}\n\n/**\n * Own the app/studio dev server's lifecycle behind the dev-server registry seam.\n *\n * Adding or removing a view/web worker rebuilds the federation remote: its\n * module-federation `exposes` map and codegen artifacts are computed once at\n * server start, so a newly-declared interface has no expose until the server is\n * recreated — `server.restart()` can't do it (it reuses the inline config).\n * `rebuild` therefore tears the server down and starts a fresh one with a\n * reloaded config; the registry watcher calls it when the interface set changes.\n *\n * Returns the not-started result verbatim when the initial boot is an expected\n * early exit, so the caller can skip the rest of the orchestration.\n */\nexport async function startAppServerSupervisor(options: {\n cliConfig: CliConfig\n start: StartAppServer\n workDir: string\n}): Promise<{reason: string; started: false} | {started: true; supervisor: AppServerSupervisor}> {\n const {cliConfig, start, workDir} = options\n\n const initial = await start(cliConfig)\n if (!initial.started) return {reason: initial.reason, started: false}\n\n // `closeCurrent` repoints at the replacement only once a rebuild succeeds, so a\n // failed rebuild (old server already closed) leaves nothing for close() to re-close.\n let server = initial.server\n let closeCurrent = initial.close\n let closed = false\n // close() waits on this so a rebuild racing teardown can't orphan the replacement.\n // Rejections are the watcher's (warn + retry); the tracked copy is swallowed.\n let rebuildInFlight: Promise<unknown> = Promise.resolve()\n\n const runRebuild = async (): Promise<ViteDevServer> => {\n // Refuse once shutting down — a config save in the teardown window must not\n // boot a replacement nobody owns.\n if (closed) throw new Error('Dev server is shutting down')\n const freshConfig = await getCliConfigUncached(workDir)\n await closeCurrent()\n closeCurrent = noop\n const result = await start(freshConfig, {isRestarting: true})\n if (!result.started) {\n // The server already reported why (e.g. organizationId was removed).\n throw new Error('Dev server did not restart after the view/web worker change')\n }\n server = result.server\n closeCurrent = result.close\n return server\n }\n\n return {\n started: true,\n supervisor: {\n async close() {\n closed = true\n await rebuildInFlight\n await closeCurrent()\n },\n rebuild() {\n const rebuild = runRebuild()\n rebuildInFlight = rebuild.catch(() => {})\n return rebuild\n },\n get server() {\n return server\n },\n },\n }\n}\n"],"names":["getCliConfigUncached","noop","startAppServerSupervisor","options","cliConfig","start","workDir","initial","started","reason","server","closeCurrent","close","closed","rebuildInFlight","Promise","resolve","runRebuild","Error","freshConfig","result","isRestarting","supervisor","rebuild","catch"],"mappings":"AAAA,SAAwBA,oBAAoB,QAAO,mBAAkB;AAkBrE,MAAMC,OAAO,WAAa;AAW1B;;;;;;;;;;;;CAYC,GACD,OAAO,eAAeC,yBAAyBC,OAI9C;IACC,MAAM,EAACC,SAAS,EAAEC,KAAK,EAAEC,OAAO,EAAC,GAAGH;IAEpC,MAAMI,UAAU,MAAMF,MAAMD;IAC5B,IAAI,CAACG,QAAQC,OAAO,EAAE,OAAO;QAACC,QAAQF,QAAQE,MAAM;QAAED,SAAS;IAAK;IAEpE,gFAAgF;IAChF,qFAAqF;IACrF,IAAIE,SAASH,QAAQG,MAAM;IAC3B,IAAIC,eAAeJ,QAAQK,KAAK;IAChC,IAAIC,SAAS;IACb,mFAAmF;IACnF,8EAA8E;IAC9E,IAAIC,kBAAoCC,QAAQC,OAAO;IAEvD,MAAMC,aAAa;QACjB,4EAA4E;QAC5E,kCAAkC;QAClC,IAAIJ,QAAQ,MAAM,IAAIK,MAAM;QAC5B,MAAMC,cAAc,MAAMnB,qBAAqBM;QAC/C,MAAMK;QACNA,eAAeV;QACf,MAAMmB,SAAS,MAAMf,MAAMc,aAAa;YAACE,cAAc;QAAI;QAC3D,IAAI,CAACD,OAAOZ,OAAO,EAAE;YACnB,qEAAqE;YACrE,MAAM,IAAIU,MAAM;QAClB;QACAR,SAASU,OAAOV,MAAM;QACtBC,eAAeS,OAAOR,KAAK;QAC3B,OAAOF;IACT;IAEA,OAAO;QACLF,SAAS;QACTc,YAAY;YACV,MAAMV;gBACJC,SAAS;gBACT,MAAMC;gBACN,MAAMH;YACR;YACAY;gBACE,MAAMA,UAAUN;gBAChBH,kBAAkBS,QAAQC,KAAK,CAAC,KAAO;gBACvC,OAAOD;YACT;YACA,IAAIb;gBACF,OAAOA;YACT;QACF;IACF;AACF"}
@@ -0,0 +1,33 @@
1
+ import { emitKeypressEvents } from 'node:readline';
2
+ import { styleText } from 'node:util';
3
+ import open from 'open';
4
+ export function bindDevShortcuts({ output, quit, url }) {
5
+ const { stdin } = process;
6
+ if (!stdin.isTTY) return async ()=>{};
7
+ const onKeypress = (_, key = {})=>{
8
+ const isWindows = process.platform === 'win32';
9
+ if (key.ctrl && key.name === 'c' && !isWindows) {
10
+ // Raw mode stops the terminal from signalling the process group, so the parent (pnpm) needs it too.
11
+ process.kill(0, 'SIGINT');
12
+ } else if (key.name === 'q' || key.ctrl && (key.name === 'c' || key.name === 'd')) {
13
+ quit();
14
+ } else if (key.ctrl && key.name === 'z' && !isWindows) {
15
+ stdin.setRawMode(false);
16
+ process.once('SIGCONT', ()=>stdin.setRawMode(true));
17
+ process.kill(0, 'SIGTSTP');
18
+ } else if (key.name === 'o') {
19
+ open(url).catch((err)=>output.warn(`Could not open ${url}: ${err.message}`));
20
+ }
21
+ };
22
+ emitKeypressEvents(stdin);
23
+ stdin.setRawMode(true);
24
+ stdin.on('keypress', onKeypress);
25
+ output.log(` ${styleText('dim', 'press')} o ${styleText('dim', 'to open ·')} q ${styleText('dim', 'to quit')}\n`);
26
+ return async ()=>{
27
+ stdin.off('keypress', onKeypress);
28
+ stdin.setRawMode(false);
29
+ stdin.pause();
30
+ };
31
+ }
32
+
33
+ //# sourceMappingURL=bindDevShortcuts.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/actions/dev/bindDevShortcuts.ts"],"sourcesContent":["import {emitKeypressEvents, type Key} from 'node:readline'\nimport {styleText} from 'node:util'\n\nimport {type Output} from '@sanity/cli-core'\nimport open from 'open'\n\nexport function bindDevShortcuts({\n output,\n quit,\n url,\n}: {\n output: Output\n quit: () => void\n url: string\n}): () => Promise<void> {\n const {stdin} = process\n if (!stdin.isTTY) return async () => {}\n\n const onKeypress = (_: string | undefined, key: Key = {}) => {\n const isWindows = process.platform === 'win32'\n\n if (key.ctrl && key.name === 'c' && !isWindows) {\n // Raw mode stops the terminal from signalling the process group, so the parent (pnpm) needs it too.\n process.kill(0, 'SIGINT')\n } else if (key.name === 'q' || (key.ctrl && (key.name === 'c' || key.name === 'd'))) {\n quit()\n } else if (key.ctrl && key.name === 'z' && !isWindows) {\n stdin.setRawMode(false)\n process.once('SIGCONT', () => stdin.setRawMode(true))\n process.kill(0, 'SIGTSTP')\n } else if (key.name === 'o') {\n open(url).catch((err) => output.warn(`Could not open ${url}: ${err.message}`))\n }\n }\n\n emitKeypressEvents(stdin)\n stdin.setRawMode(true)\n stdin.on('keypress', onKeypress)\n output.log(\n ` ${styleText('dim', 'press')} o ${styleText('dim', 'to open ·')} q ${styleText('dim', 'to quit')}\\n`,\n )\n\n return async () => {\n stdin.off('keypress', onKeypress)\n stdin.setRawMode(false)\n stdin.pause()\n }\n}\n"],"names":["emitKeypressEvents","styleText","open","bindDevShortcuts","output","quit","url","stdin","process","isTTY","onKeypress","_","key","isWindows","platform","ctrl","name","kill","setRawMode","once","catch","err","warn","message","on","log","off","pause"],"mappings":"AAAA,SAAQA,kBAAkB,QAAiB,gBAAe;AAC1D,SAAQC,SAAS,QAAO,YAAW;AAGnC,OAAOC,UAAU,OAAM;AAEvB,OAAO,SAASC,iBAAiB,EAC/BC,MAAM,EACNC,IAAI,EACJC,GAAG,EAKJ;IACC,MAAM,EAACC,KAAK,EAAC,GAAGC;IAChB,IAAI,CAACD,MAAME,KAAK,EAAE,OAAO,WAAa;IAEtC,MAAMC,aAAa,CAACC,GAAuBC,MAAW,CAAC,CAAC;QACtD,MAAMC,YAAYL,QAAQM,QAAQ,KAAK;QAEvC,IAAIF,IAAIG,IAAI,IAAIH,IAAII,IAAI,KAAK,OAAO,CAACH,WAAW;YAC9C,oGAAoG;YACpGL,QAAQS,IAAI,CAAC,GAAG;QAClB,OAAO,IAAIL,IAAII,IAAI,KAAK,OAAQJ,IAAIG,IAAI,IAAKH,CAAAA,IAAII,IAAI,KAAK,OAAOJ,IAAII,IAAI,KAAK,GAAE,GAAK;YACnFX;QACF,OAAO,IAAIO,IAAIG,IAAI,IAAIH,IAAII,IAAI,KAAK,OAAO,CAACH,WAAW;YACrDN,MAAMW,UAAU,CAAC;YACjBV,QAAQW,IAAI,CAAC,WAAW,IAAMZ,MAAMW,UAAU,CAAC;YAC/CV,QAAQS,IAAI,CAAC,GAAG;QAClB,OAAO,IAAIL,IAAII,IAAI,KAAK,KAAK;YAC3Bd,KAAKI,KAAKc,KAAK,CAAC,CAACC,MAAQjB,OAAOkB,IAAI,CAAC,CAAC,eAAe,EAAEhB,IAAI,EAAE,EAAEe,IAAIE,OAAO,EAAE;QAC9E;IACF;IAEAvB,mBAAmBO;IACnBA,MAAMW,UAAU,CAAC;IACjBX,MAAMiB,EAAE,CAAC,YAAYd;IACrBN,OAAOqB,GAAG,CACR,CAAC,EAAE,EAAExB,UAAU,OAAO,SAAS,GAAG,EAAEA,UAAU,OAAO,aAAa,GAAG,EAAEA,UAAU,OAAO,WAAW,EAAE,CAAC;IAGxG,OAAO;QACLM,MAAMmB,GAAG,CAAC,YAAYhB;QACtBH,MAAMW,UAAU,CAAC;QACjBX,MAAMoB,KAAK;IACb;AACF"}
@@ -0,0 +1,49 @@
1
+ import { spinner } from '@sanity/cli-core/ux';
2
+ import { getOrganizationApplication } from '../../services/applications.js';
3
+ import { getOrganization } from '../../services/organizations.js';
4
+ import { getUser } from '../../services/users.js';
5
+ import { SUMMARY_LOOKUP_TIMEOUT_MS } from '../summary.js';
6
+ const PENDING = Symbol('pending');
7
+ export async function fetchDevSummaryDetails({ idOrSlug, organizationId }) {
8
+ if (!organizationId) return {};
9
+ const signal = AbortSignal.timeout(SUMMARY_LOOKUP_TIMEOUT_MS);
10
+ const organizationName = getOrganization(organizationId, signal).then((org)=>org.name).catch(()=>null);
11
+ if (!idOrSlug) {
12
+ return {
13
+ organizationName: await organizationName
14
+ };
15
+ }
16
+ let deployment;
17
+ try {
18
+ const application = await getOrganizationApplication(organizationId, idOrSlug, signal);
19
+ const active = application?.activeDeployment;
20
+ if (active) {
21
+ const deployedBy = await getUser(active.deployedBy, signal).then((user)=>user.displayName).catch(()=>null);
22
+ deployment = {
23
+ createdAt: active.createdAt,
24
+ deployedBy
25
+ };
26
+ } else {
27
+ deployment = null;
28
+ }
29
+ } catch {
30
+ // Left undefined: a failed lookup must not read as "not deployed".
31
+ }
32
+ return {
33
+ deployment,
34
+ organizationName: await organizationName
35
+ };
36
+ }
37
+ export async function waitForDevSummaryDetails(details) {
38
+ const settled = await Promise.race([
39
+ details,
40
+ new Promise((resolve)=>setImmediate(resolve, PENDING))
41
+ ]);
42
+ if (settled !== PENDING) return settled;
43
+ const spin = spinner('Loading organization and deployment details').start();
44
+ const result = await details;
45
+ spin.stop();
46
+ return result;
47
+ }
48
+
49
+ //# sourceMappingURL=devSummary.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/actions/dev/devSummary.ts"],"sourcesContent":["import {spinner} from '@sanity/cli-core/ux'\n\nimport {getOrganizationApplication} from '../../services/applications.js'\nimport {getOrganization} from '../../services/organizations.js'\nimport {getUser} from '../../services/users.js'\nimport {SUMMARY_LOOKUP_TIMEOUT_MS} from '../summary.js'\n\nconst PENDING = Symbol('pending')\n\nexport interface DevSummaryDetails {\n /** `null` when the app has no active deployment, `undefined` when the lookup failed or was skipped. */\n deployment?: {createdAt: string; deployedBy: string | null} | null\n organizationName?: string | null\n}\n\nexport async function fetchDevSummaryDetails({\n idOrSlug,\n organizationId,\n}: {\n idOrSlug?: string\n organizationId?: string\n}): Promise<DevSummaryDetails> {\n if (!organizationId) return {}\n\n const signal = AbortSignal.timeout(SUMMARY_LOOKUP_TIMEOUT_MS)\n const organizationName = getOrganization(organizationId, signal)\n .then((org) => org.name)\n .catch(() => null)\n\n if (!idOrSlug) {\n return {organizationName: await organizationName}\n }\n\n let deployment: DevSummaryDetails['deployment']\n\n try {\n const application = await getOrganizationApplication(organizationId, idOrSlug, signal)\n const active = application?.activeDeployment\n\n if (active) {\n const deployedBy = await getUser(active.deployedBy, signal)\n .then((user) => user.displayName)\n .catch(() => null)\n deployment = {createdAt: active.createdAt, deployedBy}\n } else {\n deployment = null\n }\n } catch {\n // Left undefined: a failed lookup must not read as \"not deployed\".\n }\n\n return {deployment, organizationName: await organizationName}\n}\n\nexport async function waitForDevSummaryDetails(\n details: Promise<DevSummaryDetails>,\n): Promise<DevSummaryDetails> {\n const settled = await Promise.race([\n details,\n new Promise<typeof PENDING>((resolve) => setImmediate(resolve, PENDING)),\n ])\n\n if (settled !== PENDING) return settled\n\n const spin = spinner('Loading organization and deployment details').start()\n const result = await details\n spin.stop()\n\n return result\n}\n"],"names":["spinner","getOrganizationApplication","getOrganization","getUser","SUMMARY_LOOKUP_TIMEOUT_MS","PENDING","Symbol","fetchDevSummaryDetails","idOrSlug","organizationId","signal","AbortSignal","timeout","organizationName","then","org","name","catch","deployment","application","active","activeDeployment","deployedBy","user","displayName","createdAt","waitForDevSummaryDetails","details","settled","Promise","race","resolve","setImmediate","spin","start","result","stop"],"mappings":"AAAA,SAAQA,OAAO,QAAO,sBAAqB;AAE3C,SAAQC,0BAA0B,QAAO,iCAAgC;AACzE,SAAQC,eAAe,QAAO,kCAAiC;AAC/D,SAAQC,OAAO,QAAO,0BAAyB;AAC/C,SAAQC,yBAAyB,QAAO,gBAAe;AAEvD,MAAMC,UAAUC,OAAO;AAQvB,OAAO,eAAeC,uBAAuB,EAC3CC,QAAQ,EACRC,cAAc,EAIf;IACC,IAAI,CAACA,gBAAgB,OAAO,CAAC;IAE7B,MAAMC,SAASC,YAAYC,OAAO,CAACR;IACnC,MAAMS,mBAAmBX,gBAAgBO,gBAAgBC,QACtDI,IAAI,CAAC,CAACC,MAAQA,IAAIC,IAAI,EACtBC,KAAK,CAAC,IAAM;IAEf,IAAI,CAACT,UAAU;QACb,OAAO;YAACK,kBAAkB,MAAMA;QAAgB;IAClD;IAEA,IAAIK;IAEJ,IAAI;QACF,MAAMC,cAAc,MAAMlB,2BAA2BQ,gBAAgBD,UAAUE;QAC/E,MAAMU,SAASD,aAAaE;QAE5B,IAAID,QAAQ;YACV,MAAME,aAAa,MAAMnB,QAAQiB,OAAOE,UAAU,EAAEZ,QACjDI,IAAI,CAAC,CAACS,OAASA,KAAKC,WAAW,EAC/BP,KAAK,CAAC,IAAM;YACfC,aAAa;gBAACO,WAAWL,OAAOK,SAAS;gBAAEH;YAAU;QACvD,OAAO;YACLJ,aAAa;QACf;IACF,EAAE,OAAM;IACN,mEAAmE;IACrE;IAEA,OAAO;QAACA;QAAYL,kBAAkB,MAAMA;IAAgB;AAC9D;AAEA,OAAO,eAAea,yBACpBC,OAAmC;IAEnC,MAAMC,UAAU,MAAMC,QAAQC,IAAI,CAAC;QACjCH;QACA,IAAIE,QAAwB,CAACE,UAAYC,aAAaD,SAAS1B;KAChE;IAED,IAAIuB,YAAYvB,SAAS,OAAOuB;IAEhC,MAAMK,OAAOjC,QAAQ,+CAA+CkC,KAAK;IACzE,MAAMC,SAAS,MAAMR;IACrBM,KAAKG,IAAI;IAET,OAAOD;AACT"}
@@ -102,6 +102,7 @@ export const devServerManifestSchema = z.object({
102
102
  version: z.string()
103
103
  }))),
104
104
  host: z.string(),
105
+ https: z.optional(z.boolean()),
105
106
  /**
106
107
  * The id the app runs under on the bus. It stays apart from `applicationId`,
107
108
  * because Dashboards that predate `applicationId` key local apps on it.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/actions/dev/registry.ts"],"sourcesContent":["import {\n existsSync,\n mkdirSync,\n readdirSync,\n readFileSync,\n unlinkSync,\n watch,\n writeFileSync,\n} from 'node:fs'\nimport {join} from 'node:path'\n\nimport {\n coreAppManifestSchema,\n getSanityDataDir,\n studioManifestSchema,\n subdebug,\n} from '@sanity/cli-core'\nimport {z} from 'zod/mini'\n\nimport {applicationReference} from '../../applicationReference.js'\nimport {TileInterfaceMetadataSchema, ViewPlacementMetadataSchema} from '../../contract.js'\nimport {type WorkbenchApp} from '../../defineApp.js'\nimport {canonicalizeWatchDir} from './canonicalizeWatchDir.js'\nimport {getProcessStartTime, isOurProcess} from './processLiveness.js'\n\n/**\n * The dev-server registry: how a running `sanity dev` / `sanity start` process\n * advertises itself so the workbench on this machine can find and load it.\n *\n * Two kinds of file under `~/.sanity/dev-servers/` do the coordinating:\n *\n * - `<pid>.json` — one per running app/studio server, holding where it's served\n * plus its inlined manifest and interfaces. The workbench reads these to\n * discover and render local apps. Written by `registerDevServer`, watched by\n * `watchRegistry`.\n * - `workbench-<organizationId>.lock` — one lock per organization, so only one\n * workbench shell per org runs at a time and later `dev`s register into it\n * instead of starting their own. Managed by `acquireWorkbenchLock` / `readWorkbenchLock`.\n *\n * Both files belong to the process that created them and must not outlive it.\n * Three things keep that true: an explicit `release()` on clean shutdown, an\n * `exit` backstop for abrupt exits (`unlinkOnProcessExit`), and a dead-pid prune\n * on read (`isOurProcess`) that clears whatever a crashed process left behind.\n */\n\nconst devDebug = subdebug('dev')\n\n/** Bump when the manifest/lock shape changes in a breaking way. */\nconst REGISTRY_VERSION = 2\n\n/**\n * The current process's start time as reported by the OS, for the `startedAt`\n * that `isOurProcess` checks on re-read. Falls back to now when the OS time is\n * unavailable — `new Date()` alone records the write time, which drifts from\n * process start by enough to look stale and get pruned right after writing.\n */\nfunction ownStartedAt(): string {\n return (getProcessStartTime(process.pid) ?? new Date()).toISOString()\n}\n\nconst interfaceBaseFields = {\n /** CLI-minted for a local interface; a deployed one gets its id from Brett. */\n id: z.string(),\n moduleId: z.string(),\n name: z.string(),\n /** Raw source vite serves; a deployed interface carries only the `moduleId`. */\n src: z.string(),\n title: z.string(),\n version: z.optional(z.string()),\n}\n\n/**\n * A forwarded interface. Kept outside the manifest so\n * the workbench renders local panels and runs workers without a deploy.\n */\nconst devServerInterfaceSchema = z.union([\n z.discriminatedUnion('surface', [\n z.object({\n ...interfaceBaseFields,\n metadata: z.nullable(ViewPlacementMetadataSchema),\n surface: z.literal('window'),\n }),\n z.object({\n ...interfaceBaseFields,\n metadata: z.nullable(ViewPlacementMetadataSchema),\n surface: z.literal('panel'),\n }),\n z.object({...interfaceBaseFields, metadata: z.null(), surface: z.literal('asset_source')}),\n z.object({\n ...interfaceBaseFields,\n metadata: TileInterfaceMetadataSchema,\n surface: z.literal('tile'),\n }),\n ]),\n z.object({...interfaceBaseFields, metadata: z.null(), type: z.literal('worker')}),\n])\n\n// Exported so test fixtures can validate against the same schema the registry\n// parses with — see `aDevServerManifest`. Used internally by `getRegisteredServers`.\nexport const devServerManifestSchema = z.object({\n applicationId: z.optional(z.string()),\n /**\n * Field schema *values* load from the federation module; each field's `src`\n * rides along so a repoint bumps the exposes-set id and forces a rebuild.\n * Lenient — the workbench is the authority.\n */\n configs: z.optional(\n z.array(\n z.object({\n // Identifies the owning app when it has no app id (singletons).\n appType: z.optional(z.string()),\n fields: z.array(\n z.object({\n name: z.string(),\n public: z.optional(z.boolean()),\n src: z.string(),\n title: z.string(),\n }),\n ),\n // Content hash of the config — the workbench's change-detection key\n // (see deriveConfigs).\n id: z.string(),\n // The app's `defineApplication` slug — the module-federation alias the\n // workbench loads this config's live values from.\n moduleName: z.optional(z.string()),\n // The version the workbench federates this config's module under —\n // a string, like the one Brett returns on a deployed `activeConfig`.\n version: z.string(),\n }),\n ),\n ),\n host: z.string(),\n /**\n * The id the app runs under on the bus. It stays apart from `applicationId`,\n * because Dashboards that predate `applicationId` key local apps on it.\n */\n id: z.optional(z.string()),\n interfaces: z.optional(z.array(devServerInterfaceSchema)),\n /**\n * Inlined manifest — either a {@link StudioManifest} or {@link CoreAppManifest},\n * validated against the shared cli-core schemas. The registry stores and\n * rebroadcasts it; the CLI is what extracts and writes it.\n */\n manifest: z.optional(z.union([studioManifestSchema, coreAppManifestSchema])),\n /**\n * ISO timestamp of the most recent successful manifest extraction. Bumped\n * on every regeneration so re-writing this registry entry triggers the\n * workbench `watchRegistry` watcher and forces a rebroadcast to clients.\n */\n manifestUpdatedAt: z.optional(z.string()),\n // Stable identity + qualified reference, composed by the CLI (the authority for\n // local apps, which never reach brett) and read straight by the workbench.\n name: z.optional(z.string()),\n organizationId: z.optional(z.string()),\n pid: z.number(),\n port: z.number(),\n projectId: z.optional(z.string()),\n reference: z.optional(z.string()),\n slug: z.optional(z.string()),\n startedAt: z.string(),\n type: z.enum(['coreApp', 'studio']),\n version: z.literal(REGISTRY_VERSION),\n visibility: z.optional(z.enum(['default', 'unlisted', 'disabled'])),\n workDir: z.string(),\n})\n/**\n * A manifest describing a running dev server process (studio or app).\n * Stored as `~/.sanity/dev-servers/<pid>.json`.\n *\n * The workbench singleton is tracked separately via the lock file — see\n * `acquireWorkbenchLock` and `readWorkbenchLock` below.\n */\nexport type DevServerManifest = z.infer<typeof devServerManifestSchema>\n\n/**\n * A config-only server carries configs but no interfaces — e.g. a\n * media-library config app under development. The workbench never routes it\n * as an app; only its configs are published. It therefore plays a different\n * role than an app server, and the two may share a slug (a config app\n * developed alongside the locally served singleton it configures).\n */\nexport function isConfigOnlyServer(\n server: Pick<DevServerManifest, 'configs' | 'interfaces'>,\n): boolean {\n return Boolean(server.configs?.length) && !server.interfaces?.length\n}\n\nexport function localAppIdentity(\n app: Pick<WorkbenchApp, 'isSingleton' | 'name' | 'organizationId' | 'slug' | 'visibility'>,\n): Pick<DevServerManifest, 'name' | 'organizationId' | 'reference' | 'slug' | 'visibility'> {\n const name = app.name ?? app.slug\n\n return {\n name,\n organizationId: app.organizationId,\n reference: applicationReference({\n isSingleton: app.isSingleton ?? false,\n name,\n organizationId: app.organizationId,\n }),\n slug: app.slug,\n visibility: app.visibility ?? 'default',\n }\n}\n\n/**\n * Where the Dashboard shell opens a registered server, matching the Workbench's\n * `StudioApplication.href` and `CoreApplication.href`. Only servers with a\n * `surface: 'window'` interface get one (see toWireInterface): studios always do,\n * configs and panel-only apps don't, so they'd 404.\n */\nexport function dashboardPath(\n server: Pick<DevServerManifest, 'id' | 'interfaces' | 'slug' | 'type'>,\n): string | undefined {\n const hasAppView = (server.interfaces ?? []).some(\n (iface) => 'surface' in iface && iface.surface === 'window',\n )\n\n const segment = server.slug ?? server.id\n\n if (!segment || !hasAppView) {\n return undefined\n }\n\n const root = server.type === 'studio' ? 'studios' : 'applications'\n\n return `/${root}/${encodeURIComponent(segment)}`\n}\n\n/**\n * Path to the dev server registry directory. Lives under the shared Sanity\n * config directory to stay consistent with other CLI paths.\n */\nfunction getRegistryDir(): string {\n return join(getSanityDataDir(), 'dev-servers')\n}\n\n// One shared `exit` listener drives every registered cleanup, so N locks/entries\n// don't each add a listener and trip Node's MaxListeners warning.\nconst exitCleanups = new Set<() => void>()\nlet exitListenerInstalled = false\n\nfunction runExitCleanups(): void {\n for (const cleanup of exitCleanups) cleanup()\n}\n\n/** Exercise the exit backstop in tests without terminating the process; not part\n * of the package's public surface. */\nexport const runRegistryExitCleanupForTesting = runExitCleanups\n\n/**\n * Delete a registry file synchronously on process exit, as a backstop for abrupt\n * termination. Vite installs its own SIGTERM handler that calls `process.exit()`,\n * which can outrun the async server teardown and leave the lock or registry entry\n * behind — a stray dev-server that lingers until the dead-pid prune clears it. The\n * `exit` event only runs synchronous work, hence `unlinkSync`. `ownedByUs` guards\n * the shared lock so a successor that reacquired it isn't wiped. Returns a\n * detacher to call after a clean release.\n */\nfunction unlinkOnProcessExit(filePath: string, ownedByUs: () => boolean): () => void {\n const cleanup = () => {\n if (!ownedByUs()) return\n try {\n unlinkSync(filePath)\n } catch {\n // The file may already have been removed during shutdown.\n }\n }\n exitCleanups.add(cleanup)\n\n if (!exitListenerInstalled) {\n exitListenerInstalled = true\n process.once('exit', runExitCleanups)\n }\n\n return () => exitCleanups.delete(cleanup)\n}\n\ninterface DevServerRegistration {\n /** Remove the registry entry. */\n release: () => void\n /**\n * Rewrite the registry entry with partial updates merged in. Also bumps the\n * file's mtime, which fires `watchRegistry` in any workbench process and\n * triggers a rebroadcast to connected clients.\n */\n update: (patch: Partial<Omit<DevServerManifest, 'pid' | 'startedAt' | 'version'>>) => void\n}\n\n/**\n * Write a manifest file for the current process and return a handle with a\n * `release` function that removes it plus an `update` function for patching\n * fields post-registration. Uses synchronous I/O so the file exists before\n * any signal handler could fire.\n */\nexport function registerDevServer(\n manifest: Omit<DevServerManifest, 'pid' | 'startedAt' | 'version'>,\n): DevServerRegistration {\n const registryDir = getRegistryDir()\n mkdirSync(registryDir, {mode: 0o700, recursive: true})\n\n let current: DevServerManifest = {\n ...manifest,\n pid: process.pid,\n startedAt: ownStartedAt(),\n version: REGISTRY_VERSION,\n }\n\n const filePath = join(registryDir, `${process.pid}.json`)\n writeFileSync(filePath, JSON.stringify(current, null, 2), {mode: 0o600})\n\n // Guard against late updates from background tasks (e.g. the initial\n // manifest extraction) landing after `release()` has deleted the file —\n // without this, the update would re-create the registry entry and leak.\n let released = false\n\n // The file is pid-named, so it's always ours to remove on exit.\n const detachExitCleanup = unlinkOnProcessExit(filePath, () => !released)\n\n return {\n release() {\n released = true\n detachExitCleanup()\n try {\n unlinkSync(filePath)\n } catch {\n // ENOENT is fine — already cleaned up\n }\n },\n update(patch) {\n if (released) return\n current = {...current, ...patch}\n writeFileSync(filePath, JSON.stringify(current, null, 2), {mode: 0o600})\n },\n }\n}\n\n/**\n * Read all manifest files from the registry, prune stale entries (dead PIDs),\n * and return the live ones.\n */\nexport function getRegisteredServers(): DevServerManifest[] {\n const registryDir = getRegistryDir()\n\n if (!existsSync(registryDir)) {\n return []\n }\n\n const files = readdirSync(registryDir).filter((f) => f.endsWith('.json'))\n const servers: DevServerManifest[] = []\n\n for (const file of files) {\n const filePath = join(registryDir, file)\n let raw: unknown\n try {\n raw = JSON.parse(readFileSync(filePath, 'utf8'))\n } catch {\n continue\n }\n\n const {data, success} = devServerManifestSchema.safeParse(raw)\n if (!success) continue\n\n if (isOurProcess(data.pid, data.startedAt)) {\n servers.push(data)\n } else {\n try {\n unlinkSync(filePath)\n } catch {\n // Ignore — another process may have already cleaned it up\n }\n }\n }\n\n return servers\n}\n\ninterface RegistryWatcher {\n close(): void\n}\n\n/**\n * Watch the registry directory for changes and invoke the callback with the\n * current list of live servers whenever a change is detected.\n *\n * Uses `fs.watch` with a debounce to coalesce rapid file changes (e.g. a\n * server starting and writing its manifest triggers multiple FS events).\n */\nexport function watchRegistry(callback: (servers: DevServerManifest[]) => void): RegistryWatcher {\n const registryDir = getRegistryDir()\n mkdirSync(registryDir, {mode: 0o700, recursive: true})\n\n // Canonicalize to the real long path so `fs.watch` doesn't abort on Windows\n // short-path dirs. See `canonicalizeWatchDir`.\n const watchDir = canonicalizeWatchDir(registryDir)\n\n let debounceTimer: ReturnType<typeof setTimeout> | undefined\n\n const notify = () => {\n clearTimeout(debounceTimer)\n debounceTimer = setTimeout(() => {\n callback(getRegisteredServers())\n }, 50)\n }\n\n const watcher = watch(watchDir, notify)\n\n return {\n close() {\n clearTimeout(debounceTimer)\n watcher.close()\n },\n }\n}\n\n// The workbench singleton lock — \"one workbench per organization\". Lives in the same\n// registry dir and shares the liveness/prune model: a stale lock left by a\n// crashed process is pruned on read so the next acquire isn't blocked forever.\n\nconst workbenchLockSchema = z.object({\n host: z.string(),\n pid: z.number(),\n port: z.number(),\n ready: z.optional(z.boolean()),\n startedAt: z.string(),\n version: z.literal(REGISTRY_VERSION),\n})\n\n/**\n * Read the workbench lock file and return its contents if the holding\n * process is still alive. Prunes stale locks from crashed processes.\n */\nexport function readWorkbenchLock(\n organizationId: string,\n): z.infer<typeof workbenchLockSchema> | undefined {\n const file = readLockFile(organizationId)\n // File doesn't exist — nothing to prune, nothing to return\n if (!file) return undefined\n\n // Past this point the file exists. Anything that isn't a live, valid lock\n // (unparsable JSON, schema mismatch, dead/reused PID) is stale and must be\n // pruned — otherwise the next `acquireWorkbenchLock` call is blocked by\n // EEXIST forever and `sanity dev` silently no-ops the workbench server.\n const {data} = file\n devDebug('Read workbench lock: %o', data)\n if (data && isOurProcess(data.pid, data.startedAt)) {\n devDebug('Workbench process is alive at pid %d on port %d', data.pid, data.port)\n return data\n }\n\n pruneWorkbenchLock(getLockPath(organizationId))\n return undefined\n}\n\nconst LOCK_READY_TIMEOUT_MS = 10_000\nconst LOCK_READY_POLL_MS = 50\n\n/**\n * Read the workbench lock once its holder's shell is listening, so the port is\n * the bound one. Returns the lock as-is after {@link LOCK_READY_TIMEOUT_MS}.\n */\nexport async function waitForWorkbenchLock(\n organizationId: string,\n): Promise<z.infer<typeof workbenchLockSchema> | undefined> {\n const deadline = Date.now() + LOCK_READY_TIMEOUT_MS\n let lock = readWorkbenchLock(organizationId)\n // Read the raw file here: `readWorkbenchLock` spawns `ps`/PowerShell per call\n // and deletes a lock it catches half-written by `updatePort`.\n while (lock?.ready === false && Date.now() < deadline) {\n await new Promise((resolve) => setTimeout(resolve, LOCK_READY_POLL_MS))\n const file = readLockFile(organizationId)\n if (!file) break\n lock = file.data ?? lock\n }\n if (lock?.ready === false && Date.now() >= deadline) {\n devDebug(\n 'Workbench lock not ready after %d ms, using port %d',\n LOCK_READY_TIMEOUT_MS,\n lock.port,\n )\n }\n return readWorkbenchLock(organizationId)\n}\n\nconst getLockPath = (organizationId: string) =>\n join(getRegistryDir(), `workbench-${organizationId}.lock`)\n\n/**\n * Read the lock file with no liveness check and no pruning. `undefined` when\n * there is no file; `data` is `undefined` when its contents don't parse.\n */\nfunction readLockFile(\n organizationId: string,\n): {data: z.infer<typeof workbenchLockSchema> | undefined} | undefined {\n let contents: string\n try {\n contents = readFileSync(getLockPath(organizationId), 'utf8')\n } catch {\n return undefined\n }\n let json: unknown\n try {\n json = JSON.parse(contents)\n } catch {\n return {data: undefined}\n }\n const {data, success} = workbenchLockSchema.safeParse(json)\n return {data: success ? data : undefined}\n}\n\nfunction pruneWorkbenchLock(lockPath: string): void {\n try {\n devDebug('Removing stale workbench lock')\n unlinkSync(lockPath)\n devDebug('Stale workbench lock removed')\n } catch {\n // Another process may have already cleaned it up\n }\n}\n\ninterface WorkbenchLock {\n /** Release the lock file. */\n release: () => void\n /** Update the lock with the actual port after the server starts listening. */\n updatePort: (port: number) => void\n}\n\n/**\n * Attempt to acquire an exclusive lock for the workbench process.\n * Uses `O_EXCL` (the `wx` flag) which is atomic at the OS level — only one\n * process can create the file.\n *\n * The lock stores `{pid, host, port}` so other processes can find the\n * running workbench. Call `updatePort` after the Vite server starts to\n * write the actual port (Vite may pick a different one).\n *\n * @returns A {@link WorkbenchLock} if acquired, or `undefined` if another\n * live process already holds it.\n */\nexport function acquireWorkbenchLock(\n info: {host: string; organizationId: string; port: number},\n retries = 1,\n): WorkbenchLock | undefined {\n const registryDir = getRegistryDir()\n mkdirSync(registryDir, {mode: 0o700, recursive: true})\n\n const lockPath = getLockPath(info.organizationId)\n const startedAt = ownStartedAt()\n const lockData = {\n host: info.host,\n pid: process.pid,\n port: info.port,\n ready: false,\n startedAt,\n version: REGISTRY_VERSION,\n }\n\n devDebug('Acquiring workbench lock at %s', lockPath)\n\n try {\n writeFileSync(lockPath, JSON.stringify(lockData), {flag: 'wx', mode: 0o600})\n devDebug('Workbench lock acquired')\n\n let released = false\n // Only wipe the lock on exit if it's still ours — a successor that reacquired\n // it after our own release must not be clobbered.\n const detachExitCleanup = unlinkOnProcessExit(lockPath, () => {\n if (released) return false\n const disk = readLockFile(info.organizationId)?.data\n return disk?.pid === process.pid && disk.startedAt === startedAt\n })\n\n return {\n release() {\n released = true\n detachExitCleanup()\n try {\n unlinkSync(lockPath)\n } catch {\n // Already cleaned up\n }\n },\n updatePort(port: number) {\n writeFileSync(lockPath, JSON.stringify({...lockData, port, ready: true}), {mode: 0o600})\n },\n }\n } catch (err: unknown) {\n devDebug(\n 'Failed to acquire workbench lock: %s',\n err instanceof Error ? err.message : String(err),\n )\n if (!isNodeError(err) || err.code !== 'EEXIST') return undefined\n\n // Lock exists — check if the holder is still alive\n const existing = readWorkbenchLock(info.organizationId)\n if (existing) return undefined\n\n // Stale lock was pruned by readWorkbenchLock — retry (with guard against infinite recursion)\n if (retries <= 0) return undefined\n return acquireWorkbenchLock(info, retries - 1)\n }\n}\n\nfunction isNodeError(err: unknown): err is NodeJS.ErrnoException {\n return err instanceof Error && 'code' in err\n}\n"],"names":["existsSync","mkdirSync","readdirSync","readFileSync","unlinkSync","watch","writeFileSync","join","coreAppManifestSchema","getSanityDataDir","studioManifestSchema","subdebug","z","applicationReference","TileInterfaceMetadataSchema","ViewPlacementMetadataSchema","canonicalizeWatchDir","getProcessStartTime","isOurProcess","devDebug","REGISTRY_VERSION","ownStartedAt","process","pid","Date","toISOString","interfaceBaseFields","id","string","moduleId","name","src","title","version","optional","devServerInterfaceSchema","union","discriminatedUnion","object","metadata","nullable","surface","literal","null","type","devServerManifestSchema","applicationId","configs","array","appType","fields","public","boolean","moduleName","host","interfaces","manifest","manifestUpdatedAt","organizationId","number","port","projectId","reference","slug","startedAt","enum","visibility","workDir","isConfigOnlyServer","server","Boolean","length","localAppIdentity","app","isSingleton","dashboardPath","hasAppView","some","iface","segment","undefined","root","encodeURIComponent","getRegistryDir","exitCleanups","Set","exitListenerInstalled","runExitCleanups","cleanup","runRegistryExitCleanupForTesting","unlinkOnProcessExit","filePath","ownedByUs","add","once","delete","registerDevServer","registryDir","mode","recursive","current","JSON","stringify","released","detachExitCleanup","release","update","patch","getRegisteredServers","files","filter","f","endsWith","servers","file","raw","parse","data","success","safeParse","push","watchRegistry","callback","watchDir","debounceTimer","notify","clearTimeout","setTimeout","watcher","close","workbenchLockSchema","ready","readWorkbenchLock","readLockFile","pruneWorkbenchLock","getLockPath","LOCK_READY_TIMEOUT_MS","LOCK_READY_POLL_MS","waitForWorkbenchLock","deadline","now","lock","Promise","resolve","contents","json","lockPath","acquireWorkbenchLock","info","retries","lockData","flag","disk","updatePort","err","Error","message","String","isNodeError","code","existing"],"mappings":"AAAA,SACEA,UAAU,EACVC,SAAS,EACTC,WAAW,EACXC,YAAY,EACZC,UAAU,EACVC,KAAK,EACLC,aAAa,QACR,UAAS;AAChB,SAAQC,IAAI,QAAO,YAAW;AAE9B,SACEC,qBAAqB,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+ {"version":3,"sources":["../../../src/actions/dev/registry.ts"],"sourcesContent":["import {\n existsSync,\n mkdirSync,\n readdirSync,\n readFileSync,\n unlinkSync,\n watch,\n writeFileSync,\n} from 'node:fs'\nimport {join} from 'node:path'\n\nimport {\n coreAppManifestSchema,\n getSanityDataDir,\n studioManifestSchema,\n subdebug,\n} from '@sanity/cli-core'\nimport {z} from 'zod/mini'\n\nimport {applicationReference} from '../../applicationReference.js'\nimport {TileInterfaceMetadataSchema, ViewPlacementMetadataSchema} from '../../contract.js'\nimport {type WorkbenchApp} from '../../defineApp.js'\nimport {canonicalizeWatchDir} from './canonicalizeWatchDir.js'\nimport {getProcessStartTime, isOurProcess} from './processLiveness.js'\n\n/**\n * The dev-server registry: how a running `sanity dev` / `sanity start` process\n * advertises itself so the workbench on this machine can find and load it.\n *\n * Two kinds of file under `~/.sanity/dev-servers/` do the coordinating:\n *\n * - `<pid>.json` — one per running app/studio server, holding where it's served\n * plus its inlined manifest and interfaces. The workbench reads these to\n * discover and render local apps. Written by `registerDevServer`, watched by\n * `watchRegistry`.\n * - `workbench-<organizationId>.lock` — one lock per organization, so only one\n * workbench shell per org runs at a time and later `dev`s register into it\n * instead of starting their own. Managed by `acquireWorkbenchLock` / `readWorkbenchLock`.\n *\n * Both files belong to the process that created them and must not outlive it.\n * Three things keep that true: an explicit `release()` on clean shutdown, an\n * `exit` backstop for abrupt exits (`unlinkOnProcessExit`), and a dead-pid prune\n * on read (`isOurProcess`) that clears whatever a crashed process left behind.\n */\n\nconst devDebug = subdebug('dev')\n\n/** Bump when the manifest/lock shape changes in a breaking way. */\nconst REGISTRY_VERSION = 2\n\n/**\n * The current process's start time as reported by the OS, for the `startedAt`\n * that `isOurProcess` checks on re-read. Falls back to now when the OS time is\n * unavailable — `new Date()` alone records the write time, which drifts from\n * process start by enough to look stale and get pruned right after writing.\n */\nfunction ownStartedAt(): string {\n return (getProcessStartTime(process.pid) ?? new Date()).toISOString()\n}\n\nconst interfaceBaseFields = {\n /** CLI-minted for a local interface; a deployed one gets its id from Brett. */\n id: z.string(),\n moduleId: z.string(),\n name: z.string(),\n /** Raw source vite serves; a deployed interface carries only the `moduleId`. */\n src: z.string(),\n title: z.string(),\n version: z.optional(z.string()),\n}\n\n/**\n * A forwarded interface. Kept outside the manifest so\n * the workbench renders local panels and runs workers without a deploy.\n */\nconst devServerInterfaceSchema = z.union([\n z.discriminatedUnion('surface', [\n z.object({\n ...interfaceBaseFields,\n metadata: z.nullable(ViewPlacementMetadataSchema),\n surface: z.literal('window'),\n }),\n z.object({\n ...interfaceBaseFields,\n metadata: z.nullable(ViewPlacementMetadataSchema),\n surface: z.literal('panel'),\n }),\n z.object({...interfaceBaseFields, metadata: z.null(), surface: z.literal('asset_source')}),\n z.object({\n ...interfaceBaseFields,\n metadata: TileInterfaceMetadataSchema,\n surface: z.literal('tile'),\n }),\n ]),\n z.object({...interfaceBaseFields, metadata: z.null(), type: z.literal('worker')}),\n])\n\n// Exported so test fixtures can validate against the same schema the registry\n// parses with — see `aDevServerManifest`. Used internally by `getRegisteredServers`.\nexport const devServerManifestSchema = z.object({\n applicationId: z.optional(z.string()),\n /**\n * Field schema *values* load from the federation module; each field's `src`\n * rides along so a repoint bumps the exposes-set id and forces a rebuild.\n * Lenient — the workbench is the authority.\n */\n configs: z.optional(\n z.array(\n z.object({\n // Identifies the owning app when it has no app id (singletons).\n appType: z.optional(z.string()),\n fields: z.array(\n z.object({\n name: z.string(),\n public: z.optional(z.boolean()),\n src: z.string(),\n title: z.string(),\n }),\n ),\n // Content hash of the config — the workbench's change-detection key\n // (see deriveConfigs).\n id: z.string(),\n // The app's `defineApplication` slug — the module-federation alias the\n // workbench loads this config's live values from.\n moduleName: z.optional(z.string()),\n // The version the workbench federates this config's module under —\n // a string, like the one Brett returns on a deployed `activeConfig`.\n version: z.string(),\n }),\n ),\n ),\n host: z.string(),\n https: z.optional(z.boolean()),\n /**\n * The id the app runs under on the bus. It stays apart from `applicationId`,\n * because Dashboards that predate `applicationId` key local apps on it.\n */\n id: z.optional(z.string()),\n interfaces: z.optional(z.array(devServerInterfaceSchema)),\n /**\n * Inlined manifest — either a {@link StudioManifest} or {@link CoreAppManifest},\n * validated against the shared cli-core schemas. The registry stores and\n * rebroadcasts it; the CLI is what extracts and writes it.\n */\n manifest: z.optional(z.union([studioManifestSchema, coreAppManifestSchema])),\n /**\n * ISO timestamp of the most recent successful manifest extraction. Bumped\n * on every regeneration so re-writing this registry entry triggers the\n * workbench `watchRegistry` watcher and forces a rebroadcast to clients.\n */\n manifestUpdatedAt: z.optional(z.string()),\n // Stable identity + qualified reference, composed by the CLI (the authority for\n // local apps, which never reach brett) and read straight by the workbench.\n name: z.optional(z.string()),\n organizationId: z.optional(z.string()),\n pid: z.number(),\n port: z.number(),\n projectId: z.optional(z.string()),\n reference: z.optional(z.string()),\n slug: z.optional(z.string()),\n startedAt: z.string(),\n type: z.enum(['coreApp', 'studio']),\n version: z.literal(REGISTRY_VERSION),\n visibility: z.optional(z.enum(['default', 'unlisted', 'disabled'])),\n workDir: z.string(),\n})\n/**\n * A manifest describing a running dev server process (studio or app).\n * Stored as `~/.sanity/dev-servers/<pid>.json`.\n *\n * The workbench singleton is tracked separately via the lock file — see\n * `acquireWorkbenchLock` and `readWorkbenchLock` below.\n */\nexport type DevServerManifest = z.infer<typeof devServerManifestSchema>\n\n/**\n * A config-only server carries configs but no interfaces — e.g. a\n * media-library config app under development. The workbench never routes it\n * as an app; only its configs are published. It therefore plays a different\n * role than an app server, and the two may share a slug (a config app\n * developed alongside the locally served singleton it configures).\n */\nexport function isConfigOnlyServer(\n server: Pick<DevServerManifest, 'configs' | 'interfaces'>,\n): boolean {\n return Boolean(server.configs?.length) && !server.interfaces?.length\n}\n\nexport function localAppIdentity(\n app: Pick<WorkbenchApp, 'isSingleton' | 'name' | 'organizationId' | 'slug' | 'visibility'>,\n): Pick<DevServerManifest, 'name' | 'organizationId' | 'reference' | 'slug' | 'visibility'> {\n const name = app.name ?? app.slug\n\n return {\n name,\n organizationId: app.organizationId,\n reference: applicationReference({\n isSingleton: app.isSingleton ?? false,\n name,\n organizationId: app.organizationId,\n }),\n slug: app.slug,\n visibility: app.visibility ?? 'default',\n }\n}\n\n/**\n * Where the Dashboard shell opens a registered server, matching the Workbench's\n * `StudioApplication.href` and `CoreApplication.href`. Only servers with a\n * `surface: 'window'` interface get one (see toWireInterface): studios always do,\n * configs and panel-only apps don't, so they'd 404.\n */\nexport function dashboardPath(\n server: Pick<DevServerManifest, 'id' | 'interfaces' | 'slug' | 'type'>,\n): string | undefined {\n const hasAppView = (server.interfaces ?? []).some(\n (iface) => 'surface' in iface && iface.surface === 'window',\n )\n\n const segment = server.slug ?? server.id\n\n if (!segment || !hasAppView) {\n return undefined\n }\n\n const root = server.type === 'studio' ? 'studios' : 'applications'\n\n return `/${root}/${encodeURIComponent(segment)}`\n}\n\n/**\n * Path to the dev server registry directory. Lives under the shared Sanity\n * config directory to stay consistent with other CLI paths.\n */\nfunction getRegistryDir(): string {\n return join(getSanityDataDir(), 'dev-servers')\n}\n\n// One shared `exit` listener drives every registered cleanup, so N locks/entries\n// don't each add a listener and trip Node's MaxListeners warning.\nconst exitCleanups = new Set<() => void>()\nlet exitListenerInstalled = false\n\nfunction runExitCleanups(): void {\n for (const cleanup of exitCleanups) cleanup()\n}\n\n/** Exercise the exit backstop in tests without terminating the process; not part\n * of the package's public surface. */\nexport const runRegistryExitCleanupForTesting = runExitCleanups\n\n/**\n * Delete a registry file synchronously on process exit, as a backstop for abrupt\n * termination. Vite installs its own SIGTERM handler that calls `process.exit()`,\n * which can outrun the async server teardown and leave the lock or registry entry\n * behind — a stray dev-server that lingers until the dead-pid prune clears it. The\n * `exit` event only runs synchronous work, hence `unlinkSync`. `ownedByUs` guards\n * the shared lock so a successor that reacquired it isn't wiped. Returns a\n * detacher to call after a clean release.\n */\nfunction unlinkOnProcessExit(filePath: string, ownedByUs: () => boolean): () => void {\n const cleanup = () => {\n if (!ownedByUs()) return\n try {\n unlinkSync(filePath)\n } catch {\n // The file may already have been removed during shutdown.\n }\n }\n exitCleanups.add(cleanup)\n\n if (!exitListenerInstalled) {\n exitListenerInstalled = true\n process.once('exit', runExitCleanups)\n }\n\n return () => exitCleanups.delete(cleanup)\n}\n\ninterface DevServerRegistration {\n /** Remove the registry entry. */\n release: () => void\n /**\n * Rewrite the registry entry with partial updates merged in. Also bumps the\n * file's mtime, which fires `watchRegistry` in any workbench process and\n * triggers a rebroadcast to connected clients.\n */\n update: (patch: Partial<Omit<DevServerManifest, 'pid' | 'startedAt' | 'version'>>) => void\n}\n\n/**\n * Write a manifest file for the current process and return a handle with a\n * `release` function that removes it plus an `update` function for patching\n * fields post-registration. Uses synchronous I/O so the file exists before\n * any signal handler could fire.\n */\nexport function registerDevServer(\n manifest: Omit<DevServerManifest, 'pid' | 'startedAt' | 'version'>,\n): DevServerRegistration {\n const registryDir = getRegistryDir()\n mkdirSync(registryDir, {mode: 0o700, recursive: true})\n\n let current: DevServerManifest = {\n ...manifest,\n pid: process.pid,\n startedAt: ownStartedAt(),\n version: REGISTRY_VERSION,\n }\n\n const filePath = join(registryDir, `${process.pid}.json`)\n writeFileSync(filePath, JSON.stringify(current, null, 2), {mode: 0o600})\n\n // Guard against late updates from background tasks (e.g. the initial\n // manifest extraction) landing after `release()` has deleted the file —\n // without this, the update would re-create the registry entry and leak.\n let released = false\n\n // The file is pid-named, so it's always ours to remove on exit.\n const detachExitCleanup = unlinkOnProcessExit(filePath, () => !released)\n\n return {\n release() {\n released = true\n detachExitCleanup()\n try {\n unlinkSync(filePath)\n } catch {\n // ENOENT is fine — already cleaned up\n }\n },\n update(patch) {\n if (released) return\n current = {...current, ...patch}\n writeFileSync(filePath, JSON.stringify(current, null, 2), {mode: 0o600})\n },\n }\n}\n\n/**\n * Read all manifest files from the registry, prune stale entries (dead PIDs),\n * and return the live ones.\n */\nexport function getRegisteredServers(): DevServerManifest[] {\n const registryDir = getRegistryDir()\n\n if (!existsSync(registryDir)) {\n return []\n }\n\n const files = readdirSync(registryDir).filter((f) => f.endsWith('.json'))\n const servers: DevServerManifest[] = []\n\n for (const file of files) {\n const filePath = join(registryDir, file)\n let raw: unknown\n try {\n raw = JSON.parse(readFileSync(filePath, 'utf8'))\n } catch {\n continue\n }\n\n const {data, success} = devServerManifestSchema.safeParse(raw)\n if (!success) continue\n\n if (isOurProcess(data.pid, data.startedAt)) {\n servers.push(data)\n } else {\n try {\n unlinkSync(filePath)\n } catch {\n // Ignore — another process may have already cleaned it up\n }\n }\n }\n\n return servers\n}\n\ninterface RegistryWatcher {\n close(): void\n}\n\n/**\n * Watch the registry directory for changes and invoke the callback with the\n * current list of live servers whenever a change is detected.\n *\n * Uses `fs.watch` with a debounce to coalesce rapid file changes (e.g. a\n * server starting and writing its manifest triggers multiple FS events).\n */\nexport function watchRegistry(callback: (servers: DevServerManifest[]) => void): RegistryWatcher {\n const registryDir = getRegistryDir()\n mkdirSync(registryDir, {mode: 0o700, recursive: true})\n\n // Canonicalize to the real long path so `fs.watch` doesn't abort on Windows\n // short-path dirs. See `canonicalizeWatchDir`.\n const watchDir = canonicalizeWatchDir(registryDir)\n\n let debounceTimer: ReturnType<typeof setTimeout> | undefined\n\n const notify = () => {\n clearTimeout(debounceTimer)\n debounceTimer = setTimeout(() => {\n callback(getRegisteredServers())\n }, 50)\n }\n\n const watcher = watch(watchDir, notify)\n\n return {\n close() {\n clearTimeout(debounceTimer)\n watcher.close()\n },\n }\n}\n\n// The workbench singleton lock — \"one workbench per organization\". Lives in the same\n// registry dir and shares the liveness/prune model: a stale lock left by a\n// crashed process is pruned on read so the next acquire isn't blocked forever.\n\nconst workbenchLockSchema = z.object({\n host: z.string(),\n pid: z.number(),\n port: z.number(),\n ready: z.optional(z.boolean()),\n startedAt: z.string(),\n version: z.literal(REGISTRY_VERSION),\n})\n\n/**\n * Read the workbench lock file and return its contents if the holding\n * process is still alive. Prunes stale locks from crashed processes.\n */\nexport function readWorkbenchLock(\n organizationId: string,\n): z.infer<typeof workbenchLockSchema> | undefined {\n const file = readLockFile(organizationId)\n // File doesn't exist — nothing to prune, nothing to return\n if (!file) return undefined\n\n // Past this point the file exists. Anything that isn't a live, valid lock\n // (unparsable JSON, schema mismatch, dead/reused PID) is stale and must be\n // pruned — otherwise the next `acquireWorkbenchLock` call is blocked by\n // EEXIST forever and `sanity dev` silently no-ops the workbench server.\n const {data} = file\n devDebug('Read workbench lock: %o', data)\n if (data && isOurProcess(data.pid, data.startedAt)) {\n devDebug('Workbench process is alive at pid %d on port %d', data.pid, data.port)\n return data\n }\n\n pruneWorkbenchLock(getLockPath(organizationId))\n return undefined\n}\n\nconst LOCK_READY_TIMEOUT_MS = 10_000\nconst LOCK_READY_POLL_MS = 50\n\n/**\n * Read the workbench lock once its holder's shell is listening, so the port is\n * the bound one. Returns the lock as-is after {@link LOCK_READY_TIMEOUT_MS}.\n */\nexport async function waitForWorkbenchLock(\n organizationId: string,\n): Promise<z.infer<typeof workbenchLockSchema> | undefined> {\n const deadline = Date.now() + LOCK_READY_TIMEOUT_MS\n let lock = readWorkbenchLock(organizationId)\n // Read the raw file here: `readWorkbenchLock` spawns `ps`/PowerShell per call\n // and deletes a lock it catches half-written by `updatePort`.\n while (lock?.ready === false && Date.now() < deadline) {\n await new Promise((resolve) => setTimeout(resolve, LOCK_READY_POLL_MS))\n const file = readLockFile(organizationId)\n if (!file) break\n lock = file.data ?? lock\n }\n if (lock?.ready === false && Date.now() >= deadline) {\n devDebug(\n 'Workbench lock not ready after %d ms, using port %d',\n LOCK_READY_TIMEOUT_MS,\n lock.port,\n )\n }\n return readWorkbenchLock(organizationId)\n}\n\nconst getLockPath = (organizationId: string) =>\n join(getRegistryDir(), `workbench-${organizationId}.lock`)\n\n/**\n * Read the lock file with no liveness check and no pruning. `undefined` when\n * there is no file; `data` is `undefined` when its contents don't parse.\n */\nfunction readLockFile(\n organizationId: string,\n): {data: z.infer<typeof workbenchLockSchema> | undefined} | undefined {\n let contents: string\n try {\n contents = readFileSync(getLockPath(organizationId), 'utf8')\n } catch {\n return undefined\n }\n let json: unknown\n try {\n json = JSON.parse(contents)\n } catch {\n return {data: undefined}\n }\n const {data, success} = workbenchLockSchema.safeParse(json)\n return {data: success ? data : undefined}\n}\n\nfunction pruneWorkbenchLock(lockPath: string): void {\n try {\n devDebug('Removing stale workbench lock')\n unlinkSync(lockPath)\n devDebug('Stale workbench lock removed')\n } catch {\n // Another process may have already cleaned it up\n }\n}\n\ninterface WorkbenchLock {\n /** Release the lock file. */\n release: () => void\n /** Update the lock with the actual port after the server starts listening. */\n updatePort: (port: number) => void\n}\n\n/**\n * Attempt to acquire an exclusive lock for the workbench process.\n * Uses `O_EXCL` (the `wx` flag) which is atomic at the OS level — only one\n * process can create the file.\n *\n * The lock stores `{pid, host, port}` so other processes can find the\n * running workbench. Call `updatePort` after the Vite server starts to\n * write the actual port (Vite may pick a different one).\n *\n * @returns A {@link WorkbenchLock} if acquired, or `undefined` if another\n * live process already holds it.\n */\nexport function acquireWorkbenchLock(\n info: {host: string; organizationId: string; port: number},\n retries = 1,\n): WorkbenchLock | undefined {\n const registryDir = getRegistryDir()\n mkdirSync(registryDir, {mode: 0o700, recursive: true})\n\n const lockPath = getLockPath(info.organizationId)\n const startedAt = ownStartedAt()\n const lockData = {\n host: info.host,\n pid: process.pid,\n port: info.port,\n ready: false,\n startedAt,\n version: REGISTRY_VERSION,\n }\n\n devDebug('Acquiring workbench lock at %s', lockPath)\n\n try {\n writeFileSync(lockPath, JSON.stringify(lockData), {flag: 'wx', mode: 0o600})\n devDebug('Workbench lock acquired')\n\n let released = false\n // Only wipe the lock on exit if it's still ours — a successor that reacquired\n // it after our own release must not be clobbered.\n const detachExitCleanup = unlinkOnProcessExit(lockPath, () => {\n if (released) return false\n const disk = readLockFile(info.organizationId)?.data\n return disk?.pid === process.pid && disk.startedAt === startedAt\n })\n\n return {\n release() {\n released = true\n detachExitCleanup()\n try {\n unlinkSync(lockPath)\n } catch {\n // Already cleaned up\n }\n },\n updatePort(port: number) {\n writeFileSync(lockPath, JSON.stringify({...lockData, port, ready: true}), {mode: 0o600})\n },\n }\n } catch (err: unknown) {\n devDebug(\n 'Failed to acquire workbench lock: %s',\n err instanceof Error ? err.message : String(err),\n )\n if (!isNodeError(err) || err.code !== 'EEXIST') return undefined\n\n // Lock exists — check if the holder is still alive\n const existing = readWorkbenchLock(info.organizationId)\n if (existing) return undefined\n\n // Stale lock was pruned by readWorkbenchLock — retry (with guard against infinite recursion)\n if (retries <= 0) return undefined\n return acquireWorkbenchLock(info, retries - 1)\n }\n}\n\nfunction isNodeError(err: unknown): err is NodeJS.ErrnoException {\n return err instanceof Error && 'code' in err\n}\n"],"names":["existsSync","mkdirSync","readdirSync","readFileSync","unlinkSync","watch","writeFileSync","join","coreAppManifestSchema","getSanityDataDir","studioManifestSchema","subdebug","z","applicationReference","TileInterfaceMetadataSchema","ViewPlacementMetadataSchema","canonicalizeWatchDir","getProcessStartTime","isOurProcess","devDebug","REGISTRY_VERSION","ownStartedAt","process","pid","Date","toISOString","interfaceBaseFields","id","string","moduleId","name","src","title","version","optional","devServerInterfaceSchema","union","discriminatedUnion","object","metadata","nullable","surface","literal","null","type","devServerManifestSchema","applicationId","configs","array","appType","fields","public","boolean","moduleName","host","https","interfaces","manifest","manifestUpdatedAt","organizationId","number","port","projectId","reference","slug","startedAt","enum","visibility","workDir","isConfigOnlyServer","server","Boolean","length","localAppIdentity","app","isSingleton","dashboardPath","hasAppView","some","iface","segment","undefined","root","encodeURIComponent","getRegistryDir","exitCleanups","Set","exitListenerInstalled","runExitCleanups","cleanup","runRegistryExitCleanupForTesting","unlinkOnProcessExit","filePath","ownedByUs","add","once","delete","registerDevServer","registryDir","mode","recursive","current","JSON","stringify","released","detachExitCleanup","release","update","patch","getRegisteredServers","files","filter","f","endsWith","servers","file","raw","parse","data","success","safeParse","push","watchRegistry","callback","watchDir","debounceTimer","notify","clearTimeout","setTimeout","watcher","close","workbenchLockSchema","ready","readWorkbenchLock","readLockFile","pruneWorkbenchLock","getLockPath","LOCK_READY_TIMEOUT_MS","LOCK_READY_POLL_MS","waitForWorkbenchLock","deadline","now","lock","Promise","resolve","contents","json","lockPath","acquireWorkbenchLock","info","retries","lockData","flag","disk","updatePort","err","Error","message","String","isNodeError","code","existing"],"mappings":"AAAA,SACEA,UAAU,EACVC,SAAS,EACTC,WAAW,EACXC,YAAY,EACZC,UAAU,EACVC,KAAK,EACLC,aAAa,QACR,UAAS;AAChB,SAAQC,IAAI,QAAO,YAAW;AAE9B,SACEC,qBAAqB,EACrBC,gBAAgB,EAChBC,oBAAoB,EACpBC,QAAQ,QACH,mBAAkB;AACzB,SAAQC,CAAC,QAAO,WAAU;AAE1B,SAAQC,oBAAoB,QAAO,gCAA+B;AAClE,SAAQC,2BAA2B,EAAEC,2BAA2B,QAAO,oBAAmB;AAE1F,SAAQC,oBAAoB,QAAO,4BAA2B;AAC9D,SAAQC,mBAAmB,EAAEC,YAAY,QAAO,uBAAsB;AAEtE;;;;;;;;;;;;;;;;;;CAkBC,GAED,MAAMC,WAAWR,SAAS;AAE1B,iEAAiE,GACjE,MAAMS,mBAAmB;AAEzB;;;;;CAKC,GACD,SAASC;IACP,OAAO,AAACJ,CAAAA,oBAAoBK,QAAQC,GAAG,KAAK,IAAIC,MAAK,EAAGC,WAAW;AACrE;AAEA,MAAMC,sBAAsB;IAC1B,6EAA6E,GAC7EC,IAAIf,EAAEgB,MAAM;IACZC,UAAUjB,EAAEgB,MAAM;IAClBE,MAAMlB,EAAEgB,MAAM;IACd,8EAA8E,GAC9EG,KAAKnB,EAAEgB,MAAM;IACbI,OAAOpB,EAAEgB,MAAM;IACfK,SAASrB,EAAEsB,QAAQ,CAACtB,EAAEgB,MAAM;AAC9B;AAEA;;;CAGC,GACD,MAAMO,2BAA2BvB,EAAEwB,KAAK,CAAC;IACvCxB,EAAEyB,kBAAkB,CAAC,WAAW;QAC9BzB,EAAE0B,MAAM,CAAC;YACP,GAAGZ,mBAAmB;YACtBa,UAAU3B,EAAE4B,QAAQ,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I,eAAeC,QAAQD,IAAIE,OAAO,GAAGC,OAAOH;QAE9C,IAAI,CAACI,YAAYJ,QAAQA,IAAIK,IAAI,KAAK,UAAU,OAAO/E;QAEvD,mDAAmD;QACnD,MAAMgF,WAAW5B,kBAAkBgB,KAAK1F,cAAc;QACtD,IAAIsG,UAAU,OAAOhF;QAErB,6FAA6F;QAC7F,IAAIqE,WAAW,GAAG,OAAOrE;QACzB,OAAOmE,qBAAqBC,MAAMC,UAAU;IAC9C;AACF;AAEA,SAASS,YAAYJ,GAAY;IAC/B,OAAOA,eAAeC,SAAS,UAAUD;AAC3C"}
@@ -23,6 +23,7 @@ import { startDevManifestWatcher } from './startDevManifestWatcher.js';
23
23
  const addr = server.httpServer?.address();
24
24
  return {
25
25
  host: typeof resolvedHost === 'string' ? resolvedHost : 'localhost',
26
+ https: Boolean(server.config.server.https),
26
27
  port: typeof addr === 'object' && addr ? addr.port : server.config.server.port
27
28
  };
28
29
  }
@@ -32,7 +33,7 @@ import { startDevManifestWatcher } from './startDevManifestWatcher.js';
32
33
  * server; the watcher keeps it current as `sanity.cli.ts` is edited.
33
34
  */ export async function startDevServerRegistration(options) {
34
35
  const { cliConfig, extractManifest, isApp, onInterfaceSetChange, output, server, workDir } = options;
35
- const { host: appHost, port: appPort } = serverAddress(server);
36
+ const { host: appHost, https, port: appPort } = serverAddress(server);
36
37
  reportConfigErrors(cliConfig.app, output);
37
38
  // Forwarded alongside (not inside) the manifest so the workbench renders local
38
39
  // panels/workers and reads the configs without a deploy.
@@ -66,6 +67,7 @@ import { startDevManifestWatcher } from './startDevManifestWatcher.js';
66
67
  applicationId,
67
68
  configs,
68
69
  host: appHost,
70
+ https,
69
71
  id,
70
72
  interfaces,
71
73
  organizationId,
@@ -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 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, 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 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","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,4BAA2B;AAC1D,SAAQC,sBAAsB,QAAO,kCAAiC;AACtE,SAAQC,wBAAwB,EAAEC,oBAAoB,QAAO,gCAA+B;AAC5F,SAAQC,aAAa,QAAO,qBAAoB;AAChD,SAAQC,eAAe,QAAO,oBAAmB;AACjD,SACEC,aAAa,EAEbC,oBAAoB,EACpBC,gBAAgB,EAChBC,iBAAiB,QACZ,gBAAe;AACtB,SAAQC,uBAAuB,QAAO,+BAA8B;AAqCpE;;;;;CAKC,GACD,SAASC,mBAAmBC,GAAqB,EAAEC,MAAc;IAC/D,IAAId,kBAAkBa,MAAM;IAC5B,MAAME,SAASX,qBAAqBS;IACpC,IAAIE,OAAOC,MAAM,KAAK,GAAG;IACzBF,OAAOG,IAAI,CAACd,yBAAyBY;AACvC;AAEA,+HAA+H,GAC/H,SAASG,cAAcC,MAAqB;IAC1C,MAAMC,eAAeD,OAAOE,MAAM,CAACF,MAAM,CAACG,IAAI;IAC9C,MAAMC,OAAOJ,OAAOK,UAAU,EAAEC;IAChC,OAAO;QACLH,MAAM,OAAOF,iBAAiB,WAAWA,eAAe;QACxDM,MAAM,OAAOH,SAAS,YAAYA,OAAOA,KAAKG,IAAI,GAAGP,OAAOE,MAAM,CAACF,MAAM,CAACO,IAAI;IAChF;AACF;AAEA;;;;CAIC,GACD,OAAO,eAAeC,2BACpBC,OAAqC;IAErC,MAAM,EAACC,SAAS,EAAEC,eAAe,EAAEC,KAA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;IAEA,OAAO;QACLoB,OAAO;YACLC,aAAagB,OAAO;YACpB,MAAMX,QAAQN,KAAK;QACrB;QACAkB,MAAMhE,cAAc;YAClBiC;YACAJ;YACAM,MAAMI,UAAUJ;YAChBe,MAAM1B,QAAQ,YAAY;QAC5B;IACF;AACF"}
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,4BAA2B;AAC1D,SAAQC,sBAAsB,QAAO,kCAAiC;AACtE,SAAQC,wBAAwB,EAAEC,oBAAoB,QAAO,gCAA+B;AAC5F,SAAQC,aAAa,QAAO,qBAAoB;AAChD,SAAQC,eAAe,QAAO,oBAAmB;AACjD,SACEC,aAAa,EAEbC,oBAAoB,EACpBC,gBAAgB,EAChBC,iBAAiB,QACZ,gBAAe;AACtB,SAAQC,uBAAuB,QAAO,+BAA8B;AAqCpE;;;;;CAKC,GACD,SAASC,mBAAmBC,GAAqB,EAAEC,MAAc;IAC/D,IAAId,kBAAkBa,MAAM;IAC5B,MAAME,SAASX,qBAAqBS;IACpC,IAAIE,OAAOC,MAAM,KAAK,GAAG;IACzBF,OAAOG,IAAI,CAACd,yBAAyBY;AACvC;AAEA,+HAA+H,GAC/H,SAASG,cAAcC,MAA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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,6 +1,10 @@
1
1
  import { styleText } from 'node:util';
2
+ import { isWorkbenchApp } from '../../defineApp.js';
2
3
  import { createServerLifecycle, toDisplayHost } from '../../util/serverOrchestration.js';
4
+ import { formatSummary } from '../summary.js';
3
5
  import { startAppServerSupervisor } from './appServerSupervisor.js';
6
+ import { bindDevShortcuts } from './bindDevShortcuts.js';
7
+ import { fetchDevSummaryDetails, waitForDevSummaryDetails } from './devSummary.js';
4
8
  import { startDevServerRegistration } from './startDevServerRegistration.js';
5
9
  import { startWorkbenchDevServer, startWorkbenchRemoteCoordinator } from './startWorkbenchDevServer.js';
6
10
  /**
@@ -18,7 +22,6 @@ import { startWorkbenchDevServer, startWorkbenchRemoteCoordinator } from './star
18
22
  // shell) that still bridges the registry.
19
23
  if (process.env.SANITY_INTERNAL_IS_WORKBENCH_REMOTE === 'true') {
20
24
  const remote = await startAppServer({
21
- announceUrl: true,
22
25
  cliConfig,
23
26
  httpPort
24
27
  });
@@ -38,6 +41,13 @@ import { startWorkbenchDevServer, startWorkbenchRemoteCoordinator } from './star
38
41
  // Unwound in reverse on any failure or on close(): the watcher stops before
39
42
  // the app server, and the supervisor waits out an in-flight rebuild.
40
43
  const { close, closers, installSignalHandlers } = createServerLifecycle();
44
+ const startedAt = Date.now();
45
+ const app = isWorkbenchApp(cliConfig.app) ? cliConfig.app : undefined;
46
+ const organizationId = cliConfig.app?.organizationId;
47
+ const details = fetchDevSummaryDetails({
48
+ idOrSlug: app && (cliConfig.deployment?.appId ?? app.slug),
49
+ organizationId
50
+ });
41
51
  const workbench = await startWorkbenchDevServer({
42
52
  cacheDir,
43
53
  cliConfig,
@@ -51,13 +61,13 @@ import { startWorkbenchDevServer, startWorkbenchRemoteCoordinator } from './star
51
61
  // A running workbench owns the configured port; the app server takes the next.
52
62
  // Without one it claims the configured port and announces its own URL.
53
63
  const appPort = workbench.workbenchAvailable ? workbench.workbenchPort + 1 : httpPort;
54
- const announceUrl = !workbench.workbenchAvailable;
55
64
  const supervised = await startAppServerSupervisor({
56
65
  cliConfig,
57
- start: (config)=>startAppServer({
58
- announceUrl,
66
+ start: (config, { isRestarting } = {})=>startAppServer({
59
67
  cliConfig: config,
60
- httpPort: appPort
68
+ httpPort: appPort,
69
+ isRestarting,
70
+ quiet: workbench.workbenchAvailable
61
71
  }),
62
72
  workDir
63
73
  }).catch(async (err)=>{
@@ -94,14 +104,39 @@ import { startWorkbenchDevServer, startWorkbenchRemoteCoordinator } from './star
94
104
  await close();
95
105
  throw err;
96
106
  }
107
+ const durationMs = Date.now() - startedAt;
108
+ const { deployment, organizationName } = workbench.workbenchAvailable ? await waitForDevSummaryDetails(details) : {};
109
+ installSignalHandlers();
97
110
  if (workbench.workbenchAvailable) {
98
- const appUrl = `http://${toDisplayHost(workbench.httpHost)}:${workbench.workbenchPort}${dashboardAppPath ?? ''}`;
99
- output.log(`Dashboard dev server started at ${styleText([
100
- 'blue',
101
- 'underline'
102
- ], appUrl)}`);
111
+ const url = `http://${toDisplayHost(workbench.httpHost)}:${workbench.workbenchPort}${dashboardAppPath ?? ''}`;
112
+ let version = '';
113
+ if (deployment) {
114
+ const date = new Date(deployment.createdAt).toLocaleDateString('en-US', {
115
+ day: 'numeric',
116
+ month: 'short',
117
+ year: 'numeric'
118
+ });
119
+ const by = deployment.deployedBy ? ` by ${deployment.deployedBy}` : '';
120
+ version = `local preview ${styleText('dim', `· deployed ${date}${by}`)}`;
121
+ } else if (deployment === null) {
122
+ version = `local preview ${styleText('dim', '· not deployed')}`;
123
+ }
124
+ output.log(formatSummary({
125
+ durationMs,
126
+ heading: 'Sanity Dashboard ready',
127
+ isApp,
128
+ organization: organizationName ?? organizationId,
129
+ title: app?.title,
130
+ url,
131
+ version
132
+ }));
133
+ const quit = ()=>void close().then(()=>process.exit(0));
134
+ closers.push(bindDevShortcuts({
135
+ output,
136
+ quit,
137
+ url
138
+ }));
103
139
  }
104
- installSignalHandlers();
105
140
  return {
106
141
  close
107
142
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/actions/dev/startWorkbenchDev.ts"],"sourcesContent":["import {styleText} from 'node:util'\n\nimport {type CliConfig, type Output} from '@sanity/cli-core'\n\nimport {createServerLifecycle, toDisplayHost} from '../../util/serverOrchestration.js'\nimport {type AppServerResult, startAppServerSupervisor} from './appServerSupervisor.js'\nimport {type DevServerManifest} from './registry.js'\nimport {startDevServerRegistration} from './startDevServerRegistration.js'\nimport {\n startWorkbenchDevServer,\n startWorkbenchRemoteCoordinator,\n} from './startWorkbenchDevServer.js'\n\nexport interface StartWorkbenchDevOptions {\n /** Directory for the workbench Vite server's dependency cache. */\n cacheDir: string\n /** CLI-domain `app.id`/`deployment.appId` deprecation check, run before registering. */\n checkForDeprecatedAppId: () => void\n cliConfig: CliConfig\n /** Extract the project manifest to inline into the registry (studio-vs-app handled by the CLI). */\n extractManifest: (params: {\n applicationId?: string\n configPath: string\n workDir: string\n }) => Promise<DevServerManifest['manifest']>\n httpHost: string | undefined\n httpPort: number\n isApp: boolean\n output: Output\n reactStrictMode: boolean\n /** Start the app/studio dev server — the CLI owns the server, this orchestrates it. */\n startAppServer: (params: {\n announceUrl: boolean\n cliConfig: CliConfig\n httpPort: number\n }) => Promise<AppServerResult>\n workDir: string\n}\n\n/**\n * Orchestrate the dev servers a workbench project needs: a singleton workbench\n * Vite server plus the app/studio dev server it renders, wired to the dev-server\n * registry so view/web worker edits re-sync live.\n *\n * A running workbench claims the configured port, so the app server binds the\n * next one. If the workbench can't start (package or port unavailable), the app\n * server falls back to the configured port and announces its own URL, exactly as\n * a plain `sanity dev` would.\n */\nexport async function startWorkbenchDev(\n options: StartWorkbenchDevOptions,\n): Promise<{close: () => Promise<void>}> {\n const {\n cacheDir,\n checkForDeprecatedAppId,\n cliConfig,\n extractManifest,\n httpHost,\n httpPort,\n isApp,\n output,\n reactStrictMode,\n startAppServer,\n workDir,\n } = options\n\n // The remote can't render itself, so it runs as a plain app server (not the\n // shell) that still bridges the registry.\n if (process.env.SANITY_INTERNAL_IS_WORKBENCH_REMOTE === 'true') {\n const remote = await startAppServer({announceUrl: true, cliConfig, httpPort})\n if (!remote.started) return {close: async () => {}}\n\n const coordinator = startWorkbenchRemoteCoordinator({server: remote.server})\n\n return {\n close: async () => {\n await coordinator.close()\n await remote.close()\n },\n }\n }\n\n // Unwound in reverse on any failure or on close(): the watcher stops before\n // the app server, and the supervisor waits out an in-flight rebuild.\n const {close, closers, installSignalHandlers} = createServerLifecycle()\n\n const workbench = await startWorkbenchDevServer({\n cacheDir,\n cliConfig,\n httpHost,\n httpPort,\n output,\n reactStrictMode,\n workDir,\n })\n closers.push(workbench.close)\n\n // A running workbench owns the configured port; the app server takes the next.\n // Without one it claims the configured port and announces its own URL.\n const appPort = workbench.workbenchAvailable ? workbench.workbenchPort + 1 : httpPort\n const announceUrl = !workbench.workbenchAvailable\n\n const supervised = await startAppServerSupervisor({\n cliConfig,\n start: (config) => startAppServer({announceUrl, cliConfig: config, httpPort: appPort}),\n workDir,\n }).catch(async (err) => {\n await close()\n throw err\n })\n\n if (!supervised.started) {\n // The app server already reported why (e.g. missing organization id). Hand\n // back a close that releases the workbench lock; nothing else came up.\n return {close}\n }\n const {supervisor} = supervised\n closers.push(supervisor.close)\n\n let dashboardAppPath: string | undefined\n try {\n // The deprecated-id check and manifest extractor are CLI-domain, injected here.\n checkForDeprecatedAppId()\n const registration = await startDevServerRegistration({\n cliConfig,\n extractManifest,\n isApp,\n onInterfaceSetChange: () => supervisor.rebuild(),\n output,\n server: supervisor.server,\n workDir,\n })\n closers.push(registration.close)\n dashboardAppPath = registration.path\n } catch (err) {\n // Registration runs after both servers are up; a failure here would leak the\n // workbench lock and dev servers without this teardown.\n await close()\n throw err\n }\n\n if (workbench.workbenchAvailable) {\n const appUrl = `http://${toDisplayHost(workbench.httpHost)}:${workbench.workbenchPort}${dashboardAppPath ?? ''}`\n output.log(`Dashboard dev server started at ${styleText(['blue', 'underline'], appUrl)}`)\n }\n\n installSignalHandlers()\n\n return {close}\n}\n"],"names":["styleText","createServerLifecycle","toDisplayHost","startAppServerSupervisor","startDevServerRegistration","startWorkbenchDevServer","startWorkbenchRemoteCoordinator","startWorkbenchDev","options","cacheDir","checkForDeprecatedAppId","cliConfig","extractManifest","httpHost","httpPort","isApp","output","reactStrictMode","startAppServer","workDir","process","env","SANITY_INTERNAL_IS_WORKBENCH_REMOTE","remote","announceUrl","started","close","coordinator","server","closers","installSignalHandlers","workbench","push","appPort","workbenchAvailable","workbenchPort","supervised","start","config","catch","err","supervisor","dashboardAppPath","registration","onInterfaceSetChange","rebuild","path","appUrl","log"],"mappings":"AAAA,SAAQA,SAAS,QAAO,YAAW;AAInC,SAAQC,qBAAqB,EAAEC,aAAa,QAAO,oCAAmC;AACtF,SAA8BC,wBAAwB,QAAO,2BAA0B;AAEvF,SAAQC,0BAA0B,QAAO,kCAAiC;AAC1E,SACEC,uBAAuB,EACvBC,+BAA+B,QAC1B,+BAA8B;AA4BrC;;;;;;;;;CASC,GAC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ACf;IACA,MAAM,EAACe,UAAU,EAAC,GAAGL;IACrBP,QAAQG,IAAI,CAACS,WAAWf,KAAK;IAE7B,IAAIgB;IACJ,IAAI;QACF,gFAAgF;QAChFhC;QACA,MAAMiC,eAAe,MAAMvC,2BAA2B;YACpDO;YACAC;YACAG;YACA6B,sBAAsB,IAAMH,WAAWI,OAAO;YAC9C7B;YACAY,QAAQa,WAAWb,MAAM;YACzBT;QACF;QACAU,QAAQG,IAAI,CAACW,aAAajB,KAAK;QAC/BgB,mBAAmBC,aAAaG,IAAI;IACtC,EAAE,OAAON,KAAK;QACZ,6EAA6E;QAC7E,wDAAwD;QACxD,MAAMd;QACN,MAAMc;IACR;IAEA,IAAIT,UAAUG,kBAAkB,EAAE;QAChC,MAAMa,SAAS,CAAC,OAAO,EAAE7C,cAAc6B,UAAUlB,QAAQ,EAAE,CAAC,EAAEkB,UAAUI,aAAa,GAAGO,oBAAoB,IAAI;QAChH1B,OAAOgC,GAAG,CAAC,CAAC,gCAAgC,EAAEhD,UAAU;YAAC;YAAQ;SAAY,EAAE+C,SAAS;IAC1F;IAEAjB;IAEA,OAAO;QAACJ;IAAK;AACf"}
1
+ {"version":3,"sources":["../../../src/actions/dev/startWorkbenchDev.ts"],"sourcesContent":["import {styleText} from 'node:util'\n\nimport {type CliConfig, type Output} from '@sanity/cli-core'\n\nimport {isWorkbenchApp} from '../../defineApp.js'\nimport {createServerLifecycle, toDisplayHost} from '../../util/serverOrchestration.js'\nimport {formatSummary} from '../summary.js'\nimport {type AppServerResult, startAppServerSupervisor} from './appServerSupervisor.js'\nimport {bindDevShortcuts} from './bindDevShortcuts.js'\nimport {fetchDevSummaryDetails, waitForDevSummaryDetails} from './devSummary.js'\nimport {type DevServerManifest} from './registry.js'\nimport {startDevServerRegistration} from './startDevServerRegistration.js'\nimport {\n startWorkbenchDevServer,\n startWorkbenchRemoteCoordinator,\n} from './startWorkbenchDevServer.js'\n\nexport interface StartWorkbenchDevOptions {\n /** Directory for the workbench Vite server's dependency cache. */\n cacheDir: string\n /** CLI-domain `app.id`/`deployment.appId` deprecation check, run before registering. */\n checkForDeprecatedAppId: () => void\n cliConfig: CliConfig\n /** Extract the project manifest to inline into the registry (studio-vs-app handled by the CLI). */\n extractManifest: (params: {\n applicationId?: string\n configPath: string\n workDir: string\n }) => Promise<DevServerManifest['manifest']>\n httpHost: string | undefined\n httpPort: number\n isApp: boolean\n output: Output\n reactStrictMode: boolean\n /** Start the app/studio dev server — the CLI owns the server, this orchestrates it. */\n startAppServer: (params: {\n cliConfig: CliConfig\n httpPort: number\n isRestarting?: boolean\n quiet?: boolean\n }) => Promise<AppServerResult>\n workDir: string\n}\n\n/**\n * Orchestrate the dev servers a workbench project needs: a singleton workbench\n * Vite server plus the app/studio dev server it renders, wired to the dev-server\n * registry so view/web worker edits re-sync live.\n *\n * A running workbench claims the configured port, so the app server binds the\n * next one. If the workbench can't start (package or port unavailable), the app\n * server falls back to the configured port and announces its own URL, exactly as\n * a plain `sanity dev` would.\n */\nexport async function startWorkbenchDev(\n options: StartWorkbenchDevOptions,\n): Promise<{close: () => Promise<void>}> {\n const {\n cacheDir,\n checkForDeprecatedAppId,\n cliConfig,\n extractManifest,\n httpHost,\n httpPort,\n isApp,\n output,\n reactStrictMode,\n startAppServer,\n workDir,\n } = options\n\n // The remote can't render itself, so it runs as a plain app server (not the\n // shell) that still bridges the registry.\n if (process.env.SANITY_INTERNAL_IS_WORKBENCH_REMOTE === 'true') {\n const remote = await startAppServer({cliConfig, httpPort})\n if (!remote.started) return {close: async () => {}}\n\n const coordinator = startWorkbenchRemoteCoordinator({server: remote.server})\n\n return {\n close: async () => {\n await coordinator.close()\n await remote.close()\n },\n }\n }\n\n // Unwound in reverse on any failure or on close(): the watcher stops before\n // the app server, and the supervisor waits out an in-flight rebuild.\n const {close, closers, installSignalHandlers} = createServerLifecycle()\n const startedAt = Date.now()\n const app = isWorkbenchApp(cliConfig.app) ? cliConfig.app : undefined\n const organizationId = cliConfig.app?.organizationId\n const details = fetchDevSummaryDetails({\n idOrSlug: app && (cliConfig.deployment?.appId ?? app.slug),\n organizationId,\n })\n\n const workbench = await startWorkbenchDevServer({\n cacheDir,\n cliConfig,\n httpHost,\n httpPort,\n output,\n reactStrictMode,\n workDir,\n })\n closers.push(workbench.close)\n\n // A running workbench owns the configured port; the app server takes the next.\n // Without one it claims the configured port and announces its own URL.\n const appPort = workbench.workbenchAvailable ? workbench.workbenchPort + 1 : httpPort\n\n const supervised = await startAppServerSupervisor({\n cliConfig,\n start: (config, {isRestarting} = {}) =>\n startAppServer({\n cliConfig: config,\n httpPort: appPort,\n isRestarting,\n quiet: workbench.workbenchAvailable,\n }),\n workDir,\n }).catch(async (err) => {\n await close()\n throw err\n })\n\n if (!supervised.started) {\n // The app server already reported why (e.g. missing organization id). Hand\n // back a close that releases the workbench lock; nothing else came up.\n return {close}\n }\n const {supervisor} = supervised\n closers.push(supervisor.close)\n\n let dashboardAppPath: string | undefined\n try {\n // The deprecated-id check and manifest extractor are CLI-domain, injected here.\n checkForDeprecatedAppId()\n const registration = await startDevServerRegistration({\n cliConfig,\n extractManifest,\n isApp,\n onInterfaceSetChange: () => supervisor.rebuild(),\n output,\n server: supervisor.server,\n workDir,\n })\n closers.push(registration.close)\n dashboardAppPath = registration.path\n } catch (err) {\n // Registration runs after both servers are up; a failure here would leak the\n // workbench lock and dev servers without this teardown.\n await close()\n throw err\n }\n\n const durationMs = Date.now() - startedAt\n const {deployment, organizationName} = workbench.workbenchAvailable\n ? await waitForDevSummaryDetails(details)\n : {}\n\n installSignalHandlers()\n\n if (workbench.workbenchAvailable) {\n const url = `http://${toDisplayHost(workbench.httpHost)}:${workbench.workbenchPort}${dashboardAppPath ?? ''}`\n let version = ''\n\n if (deployment) {\n const date = new Date(deployment.createdAt).toLocaleDateString('en-US', {\n day: 'numeric',\n month: 'short',\n year: 'numeric',\n })\n const by = deployment.deployedBy ? ` by ${deployment.deployedBy}` : ''\n version = `local preview ${styleText('dim', `· deployed ${date}${by}`)}`\n } else if (deployment === null) {\n version = `local preview ${styleText('dim', '· not deployed')}`\n }\n\n output.log(\n formatSummary({\n durationMs,\n heading: 'Sanity Dashboard ready',\n isApp,\n organization: organizationName ?? organizationId,\n title: app?.title,\n url,\n version,\n }),\n )\n\n const quit = () => void close().then(() => process.exit(0))\n closers.push(bindDevShortcuts({output, quit, url}))\n }\n\n return {close}\n}\n"],"names":["styleText","isWorkbenchApp","createServerLifecycle","toDisplayHost","formatSummary","startAppServerSupervisor","bindDevShortcuts","fetchDevSummaryDetails","waitForDevSummaryDetails","startDevServerRegistration","startWorkbenchDevServer","startWorkbenchRemoteCoordinator","startWorkbenchDev","options","cacheDir","checkForDeprecatedAppId","cliConfig","extractManifest","httpHost","httpPort","isApp","output","reactStrictMode","startAppServer","workDir","process","env","SANITY_INTERNAL_IS_WORKBENCH_REMOTE","remote","started","close","coordinator","server","closers","installSignalHandlers","startedAt","Date","now","app","undefined","organizationId","details","idOrSlug","deployment","appId","slug","workbench","push","appPort","workbenchAvailable","workbenchPort","supervised","start","config","isRestarting","quiet","catch","err","supervisor","dashboardAppPath","registration","onInterfaceSetChange","rebuild","path","durationMs","organizationName","url","version","date","createdAt","toLocaleDateString","day","month","year","by","deployedBy","log","heading","organization","title","quit","then","exit"],"mappings":"AAAA,SAAQA,SAAS,QAAO,YAAW;AAInC,SAAQC,cAAc,QAAO,qBAAoB;AACjD,SAAQC,qBAAqB,EAAEC,aAAa,QAAO,oCAAmC;AACtF,SAAQC,aAAa,QAAO,gBAAe;AAC3C,SAA8BC,wBAAwB,QAAO,2BAA0B;AACvF,SAAQC,gBAAgB,QAAO,wBAAuB;AACtD,SAAQC,sBAAsB,EAAEC,wBAAwB,QAAO,kBAAiB;AAEhF,SAAQC,0BAA0B,QAAO,kCAAiC;AAC1E,SACEC,uBAAuB,EACvBC,+BAA+B,QAC1B,+BAA8B;AA6BrC;;;;;;;;;CASC,GACD,OAAO,eAAeC,kBACpBC,OAAiC;IAEjC,MAAM,EACJC,QA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U,EAAE,GAAG;YACpER,UAAU,CAAC,cAAc,EAAEnE,UAAU,OAAO,CAAC,WAAW,EAAEoE,OAAOM,IAAI,GAAG;QAC1E,OAAO,IAAI/B,eAAe,MAAM;YAC9BwB,UAAU,CAAC,cAAc,EAAEnE,UAAU,OAAO,mBAAmB;QACjE;QAEAqB,OAAOuD,GAAG,CACRxE,cAAc;YACZ4D;YACAa,SAAS;YACTzD;YACA0D,cAAcb,oBAAoBzB;YAClCuC,OAAOzC,KAAKyC;YACZb;YACAC;QACF;QAGF,MAAMa,OAAO,IAAM,KAAKlD,QAAQmD,IAAI,CAAC,IAAMxD,QAAQyD,IAAI,CAAC;QACxDjD,QAAQc,IAAI,CAACzC,iBAAiB;YAACe;YAAQ2D;YAAMd;QAAG;IAClD;IAEA,OAAO;QAACpC;IAAK;AACf"}
@@ -16,9 +16,10 @@ const noop = async ()=>{};
16
16
  // Every server is a local app except a config-only one — a config
17
17
  // with no interfaces (the media library). A server with both lands in both channels.
18
18
  const toApplicationsPayload = (servers)=>({
19
- applications: servers.filter((server)=>!isConfigOnlyServer(server)).map(({ applicationId, host, id, interfaces, manifest, name, organizationId, port, projectId, reference, slug, type, visibility })=>({
19
+ applications: servers.filter((server)=>!isConfigOnlyServer(server)).map(({ applicationId, host, https, id, interfaces, manifest, name, organizationId, port, projectId, reference, slug, type, visibility })=>({
20
20
  applicationId,
21
21
  host,
22
+ https,
22
23
  id,
23
24
  // Views cross to the remote keyed on `type`, never the internal `surface`.
24
25
  interfaces: interfaces?.map((iface)=>toWireInterface(iface)),
@@ -34,7 +35,7 @@ const toApplicationsPayload = (servers)=>({
34
35
  visibility
35
36
  } : {}
36
37
  })),
37
- configs: servers.flatMap(({ configs, host, port })=>// The registry stores the config flat; the workbench wire shape nests the
38
+ configs: servers.flatMap(({ configs, host, https, port })=>// The registry stores the config flat; the workbench wire shape nests the
38
39
  // type-specific payload (`fields` for a media library) under `config`, keyed
39
40
  // by the `appType` discriminator.
40
41
  (configs ?? []).map(({ appType, id, moduleName, version, ...config })=>({
@@ -42,7 +43,7 @@ const toApplicationsPayload = (servers)=>({
42
43
  config,
43
44
  id,
44
45
  moduleName,
45
- remoteURL: `http://${host}:${port}`,
46
+ remoteURL: `${https ? 'https' : 'http'}://${host}:${port}`,
46
47
  version
47
48
  })))
48
49
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/actions/dev/startWorkbenchDevServer.ts"],"sourcesContent":["import {fileURLToPath} from 'node:url'\n\nimport {type CliConfig, type Output, subdebug} from '@sanity/cli-core'\nimport {isStaging} from '@sanity/cli-core/util'\nimport viteReact from '@vitejs/plugin-react'\nimport {createServer, type InlineConfig, type Plugin, type ViteDevServer} from 'vite'\nimport {z} from 'zod/mini'\n\nimport {isWorkbenchApp, isWorkbenchConfig} from '../../defineApp.js'\nimport {createExposesTracker} from './exposesSetId.js'\nimport {\n acquireWorkbenchLock,\n type DevServerManifest,\n getRegisteredServers,\n isConfigOnlyServer,\n waitForWorkbenchLock,\n watchRegistry,\n} from './registry.js'\nimport {toWireInterface} from './toWireInterface.js'\nimport {writeWorkbenchRuntime} from './writeWorkbenchRuntime.js'\n\nconst devDebug = subdebug('dev')\nconst renderDashboardEntry = '@sanity/workbench-cli/_internal_render'\nconst renderDashboardPath = fileURLToPath(\n new URL('../../_exports/_internal_render.js', import.meta.url),\n)\n\nconst noop = async () => {}\n\n// Every server is a local app except a config-only one — a config\n// with no interfaces (the media library). A server with both lands in both channels.\nconst toApplicationsPayload = (servers: DevServerManifest[]) => ({\n applications: servers\n .filter((server) => !isConfigOnlyServer(server))\n .map(\n ({\n applicationId,\n host,\n id,\n interfaces,\n manifest,\n name,\n organizationId,\n port,\n projectId,\n reference,\n slug,\n type,\n visibility,\n }) => ({\n applicationId,\n host,\n id,\n // Views cross to the remote keyed on `type`, never the internal `surface`.\n interfaces: interfaces?.map((iface) => toWireInterface(iface)),\n manifest,\n name,\n port,\n projectId,\n reference,\n type,\n ...(organizationId && slug && visibility ? {organizationId, slug, visibility} : {}),\n }),\n ),\n configs: servers.flatMap(({configs, host, port}) =>\n // The registry stores the config flat; the workbench wire shape nests the\n // type-specific payload (`fields` for a media library) under `config`, keyed\n // by the `appType` discriminator.\n (configs ?? []).map(({appType, id, moduleName, version, ...config}) => ({\n appType,\n config,\n id,\n moduleName,\n remoteURL: `http://${host}:${port}`,\n version,\n })),\n ),\n})\n\n/**\n * Bridge the dev-server registry into a workbench Vite server's HMR channel so\n * the page tracks apps as they come and go. A changed interface set means a\n * rebuilt remote — full-reload to drop the stale remote-entry; otherwise\n * rebroadcast for a soft reconcile. Returns a detach fn.\n */\nfunction attachViteDevServerBridge(server: ViteDevServer, organizationId?: string): () => void {\n const ownServers = (servers: DevServerManifest[]) =>\n organizationId ? servers.filter((entry) => entry.organizationId === organizationId) : servers\n\n server.ws.on('sanity:workbench:get-local-applications', (_, client) => {\n client.send(\n 'sanity:workbench:local-applications',\n toApplicationsPayload(ownServers(getRegisteredServers())),\n )\n })\n\n const setTracker = createExposesTracker()\n const registryWatcher = watchRegistry((allServers) => {\n const servers = ownServers(allServers)\n if (setTracker.hasChanged(servers)) {\n server.ws.send({type: 'full-reload'})\n return\n }\n server.ws.send('sanity:workbench:local-applications', toApplicationsPayload(servers))\n })\n\n return () => registryWatcher.close()\n}\n\n/**\n * Bridge the registry into the workbench remote's HMR channel. The remote never\n * claims the workbench lock: a held lock tells the next `sanity dev` a shell is\n * running, and the remote only renders inside that shell.\n */\nexport function startWorkbenchRemoteCoordinator(options: {server: ViteDevServer}): {\n close: () => Promise<void>\n} {\n const detachBridge = attachViteDevServerBridge(options.server)\n\n return {\n close: async () => detachBridge(),\n }\n}\n\ninterface WorkbenchDevServerResult {\n close: () => Promise<void>\n httpHost: string | undefined\n workbenchAvailable: boolean\n workbenchPort: number\n}\n\nexport interface StartWorkbenchOptions {\n /** Dependency-cache dir for the workbench Vite server, kept apart from the user's own. */\n cacheDir: string\n cliConfig: CliConfig\n httpHost: string | undefined\n httpPort: number\n output: Output\n /** Wrap the workbench in React StrictMode; the CLI resolves it (unset collapses to `false`). */\n reactStrictMode: boolean\n workDir: string\n}\n\nexport async function startWorkbenchDevServer(\n options: StartWorkbenchOptions,\n): Promise<WorkbenchDevServerResult> {\n const {\n cacheDir,\n cliConfig,\n httpHost,\n httpPort: workbenchPort,\n output,\n reactStrictMode,\n workDir,\n } = options\n\n // Workbench is opted into by a `defineApplication` app or a config-only\n // `unstable_defineMediaLibrary` config — the latter still needs the shell to\n // render it.\n if (!isWorkbenchApp(cliConfig?.app) && !isWorkbenchConfig(cliConfig?.app)) {\n devDebug('Not a workbench app or config, skipping workbench dev server')\n return {close: noop, httpHost, workbenchAvailable: false, workbenchPort}\n }\n\n const organizationId = resolveOrganizationId(cliConfig)\n\n // Acquire an exclusive lock — only one workbench per organization.\n // Uses O_EXCL which is atomic at the OS level, preventing races when\n // multiple `sanity dev` processes start simultaneously (e.g. via turbo).\n const workbenchLock = acquireWorkbenchLock({\n host: httpHost || 'localhost',\n organizationId,\n port: workbenchPort,\n })\n if (!workbenchLock) {\n const existing = await waitForWorkbenchLock(organizationId)\n devDebug(\n 'Workbench already running at pid %d on port %d, skipping',\n existing?.pid,\n existing?.port,\n )\n return {\n close: noop,\n httpHost: existing?.host ?? httpHost,\n workbenchAvailable: true,\n workbenchPort: existing?.port ?? workbenchPort,\n }\n }\n\n // The lock is already held; an exception here (runtime-file write failure,\n // invalid remote URL) would otherwise leak it until the next acquire prunes\n // the stale PID.\n let result: Awaited<ReturnType<typeof createWorkbenchViteServer>>\n try {\n result = await createWorkbenchViteServer({\n cacheDir,\n httpHost,\n organizationId,\n output,\n reactStrictMode,\n workbenchPort,\n workDir,\n })\n } catch (err) {\n workbenchLock.release()\n throw err\n }\n\n if (!result) {\n workbenchLock.release()\n return {close: noop, httpHost, workbenchAvailable: false, workbenchPort}\n }\n\n const {actualPort, close} = result\n workbenchLock.updatePort(actualPort)\n\n return {\n close: async () => {\n workbenchLock.release()\n await close()\n },\n httpHost,\n workbenchAvailable: true,\n workbenchPort: actualPort,\n }\n}\n\ninterface CreateWorkbenchViteServerOptions {\n cacheDir: string\n httpHost: string | undefined\n organizationId: string\n output: Output\n reactStrictMode: boolean\n workbenchPort: number\n workDir: string\n}\n\ninterface CreateWorkbenchViteServerResult {\n actualPort: number\n close: () => Promise<void>\n}\n\nasync function createWorkbenchViteServer(\n options: CreateWorkbenchViteServerOptions,\n): Promise<CreateWorkbenchViteServerResult | undefined> {\n const {cacheDir, httpHost, organizationId, output, reactStrictMode, workbenchPort, workDir} =\n options\n\n const remoteUrl = parseRemoteUrl(process.env.SANITY_INTERNAL_WORKBENCH_REMOTE_URL)\n\n devDebug('Writing workbench runtime files')\n const root = await writeWorkbenchRuntime({\n cwd: workDir,\n organizationId,\n reactStrictMode,\n remoteUrl,\n })\n\n const viteConfig: InlineConfig = {\n // Custom cache directory so sanity's vite cache doesn't conflict with local vite projects\n cacheDir,\n configFile: false,\n define: {\n __SANITY_STAGING__: isStaging(),\n 'import.meta.env.SANITY_INTERNAL_WORKBENCH_REMOTE_URL': JSON.stringify(remoteUrl),\n },\n logLevel: 'warn',\n mode: 'development',\n optimizeDeps: {\n // Keep this entry out of pre-bundling so Vite injects its HMR context.\n exclude: [renderDashboardEntry],\n },\n // viteReact looks inert here — it transforms none of the host's own modules —\n // but it's load-bearing for the remotes. It serves the Fast Refresh runtime at\n // /@react-refresh and injects the preamble that defines window.$RefreshReg$. The\n // federated remotes loaded into this page are react-refresh transformed, so\n // without the preamble they throw \"can't detect preamble\", and without the\n // runtime their /@react-refresh import (wired by @module-federation/vite's\n // remoteHmr) fails. Dropping it as dead code broke every panel; see #1262.\n plugins: [viteReact(), ...(remoteUrl ? [remoteManifestPreloadHeaderPlugin(remoteUrl)] : [])],\n resolve: {\n // The generated Vite root cannot reliably resolve this package.\n alias: {[renderDashboardEntry]: renderDashboardPath},\n dedupe: ['react', 'react-dom'],\n },\n root,\n server: {\n host: httpHost,\n port: workbenchPort,\n strictPort: false,\n warmup: {\n clientFiles: ['./workbench.js'],\n },\n },\n }\n\n devDebug('Creating workbench vite server')\n const server = await createServer(viteConfig)\n try {\n await server.listen()\n } catch (err) {\n await server.close()\n output.warn(\n `Dashboard dev server failed to start: ${err instanceof Error ? err.message : String(err)}`,\n )\n return undefined\n }\n\n // Vite may have picked a different port if the desired one was occupied\n const addr = server.httpServer?.address()\n const actualPort = typeof addr === 'object' && addr ? addr.port : workbenchPort\n\n // Fire-and-forget: warm the workbench remote's Vite transform pipeline so\n // the first browser request hits a pre-populated module graph.\n if (remoteUrl) {\n fetch(remoteUrl)\n .then((r) => r.body?.cancel())\n .catch(() => {})\n devDebug('Warming workbench remote at %s', remoteUrl)\n }\n\n const detachBridge = attachViteDevServerBridge(server, organizationId)\n\n return {\n actualPort,\n close: async () => {\n detachBridge()\n await server.close()\n },\n }\n}\n\n// Workbench is opted into via `defineApplication`, which carries the\n// organization ID. Deliberately no fallback (e.g. resolving it from the\n// configured project): the lookup would need an authenticated user and an\n// API round-trip on every startup for something the opt-in already declares.\nconst resolveOrganizationId = (cliConfig: CliConfig): string => {\n if (cliConfig.app?.organizationId) {\n return cliConfig.app.organizationId\n }\n\n throw new Error(\n 'The Dashboard requires an organization ID. Pass \"organizationId\" to defineApplication() in sanity.cli.ts.',\n )\n}\n\n// Restricts protocol to http(s) so the URL is safe to interpolate into HTML\n// attributes and Link headers downstream.\nconst remoteUrlSchema = z.url({normalize: true, protocol: /^https?$/})\n\nfunction parseRemoteUrl(value: string | undefined): string | undefined {\n if (!value) return undefined\n\n const result = remoteUrlSchema.safeParse(value)\n\n if (!result.success) {\n throw new Error(\n `Invalid SANITY_INTERNAL_WORKBENCH_REMOTE_URL: ${value} (must be an http(s) URL)`,\n )\n }\n\n return result.data\n}\n\n/**\n * Sets a `Link: <remoteUrl>; rel=preload; as=fetch; crossorigin` response header\n * on the index document so the browser can start fetching the Module Federation\n * manifest as soon as response headers arrive — before HTML parsing reaches the\n * in-head preconnect hint. `as=fetch` matches how the federation runtime later\n * retrieves the JSON manifest, allowing the preload entry to satisfy that fetch.\n */\nfunction remoteManifestPreloadHeaderPlugin(remoteUrl: string): Plugin {\n return {\n apply: 'serve',\n configureServer(server) {\n server.middlewares.use((req, res, next) => {\n const pathname = (req.url || '/').split('?')[0]\n if (pathname === '/' || pathname === '/index.html') {\n res.setHeader('Link', `<${remoteUrl}>; rel=preload; as=fetch; crossorigin`)\n }\n next()\n })\n },\n name: 'sanity:workbench-remote-preload-header',\n }\n}\n"],"names":["fileURLToPath","subdebug","isStaging","viteReact","createServer","z","isWorkbenchApp","isWorkbenchConfig","createExposesTracker","acquireWorkbenchLock","getRegisteredServers","isConfigOnlyServer","waitForWorkbenchLock","watchRegistry","toWireInterface","writeWorkbenchRuntime","devDebug","renderDashboardEntry","renderDashboardPath","URL","url","noop","toApplicationsPayload","servers","applications","filter","server","map","applicationId","host","id","interfaces","manifest","name","organizationId","port","projectId","reference","slug","type","visibility","iface","configs","flatMap","appType","moduleName","version","config","remoteURL","attachViteDevServerBridge","ownServers","entry","ws","on","_","client","send","setTracker","registryWatcher","allServers","hasChanged","close","startWorkbenchRemoteCoordinator","options","detachBridge","startWorkbenchDevServer","cacheDir","cliConfig","httpHost","httpPort","workbenchPort","output","reactStrictMode","workDir","app","workbenchAvailable","resolveOrganizationId","workbenchLock","existing","pid","result","createWorkbenchViteServer","err","release","actualPort","updatePort","remoteUrl","parseRemoteUrl","process","env","SANITY_INTERNAL_WORKBENCH_REMOTE_URL","root","cwd","viteConfig","configFile","define","__SANITY_STAGING__","JSON","stringify","logLevel","mode","optimizeDeps","exclude","plugins","remoteManifestPreloadHeaderPlugin","resolve","alias","dedupe","strictPort","warmup","clientFiles","listen","warn","Error","message","String","undefined","addr","httpServer","address","fetch","then","r","body","cancel","catch","remoteUrlSchema","normalize","protocol","value","safeParse","success","data","apply","configureServer","middlewares","use","req","res","next","pathname","split","setHeader"],"mappings":"AAAA,SAAQA,aAAa,QAAO,WAAU;AAEtC,SAAqCC,QAAQ,QAAO,m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+ {"version":3,"sources":["../../../src/actions/dev/startWorkbenchDevServer.ts"],"sourcesContent":["import {fileURLToPath} from 'node:url'\n\nimport {type CliConfig, type Output, subdebug} from '@sanity/cli-core'\nimport {isStaging} from '@sanity/cli-core/util'\nimport viteReact from '@vitejs/plugin-react'\nimport {createServer, type InlineConfig, type Plugin, type ViteDevServer} from 'vite'\nimport {z} from 'zod/mini'\n\nimport {isWorkbenchApp, isWorkbenchConfig} from '../../defineApp.js'\nimport {createExposesTracker} from './exposesSetId.js'\nimport {\n acquireWorkbenchLock,\n type DevServerManifest,\n getRegisteredServers,\n isConfigOnlyServer,\n waitForWorkbenchLock,\n watchRegistry,\n} from './registry.js'\nimport {toWireInterface} from './toWireInterface.js'\nimport {writeWorkbenchRuntime} from './writeWorkbenchRuntime.js'\n\nconst devDebug = subdebug('dev')\nconst renderDashboardEntry = '@sanity/workbench-cli/_internal_render'\nconst renderDashboardPath = fileURLToPath(\n new URL('../../_exports/_internal_render.js', import.meta.url),\n)\n\nconst noop = async () => {}\n\n// Every server is a local app except a config-only one — a config\n// with no interfaces (the media library). A server with both lands in both channels.\nconst toApplicationsPayload = (servers: DevServerManifest[]) => ({\n applications: servers\n .filter((server) => !isConfigOnlyServer(server))\n .map(\n ({\n applicationId,\n host,\n https,\n id,\n interfaces,\n manifest,\n name,\n organizationId,\n port,\n projectId,\n reference,\n slug,\n type,\n visibility,\n }) => ({\n applicationId,\n host,\n https,\n id,\n // Views cross to the remote keyed on `type`, never the internal `surface`.\n interfaces: interfaces?.map((iface) => toWireInterface(iface)),\n manifest,\n name,\n port,\n projectId,\n reference,\n type,\n ...(organizationId && slug && visibility ? {organizationId, slug, visibility} : {}),\n }),\n ),\n configs: servers.flatMap(({configs, host, https, port}) =>\n // The registry stores the config flat; the workbench wire shape nests the\n // type-specific payload (`fields` for a media library) under `config`, keyed\n // by the `appType` discriminator.\n (configs ?? []).map(({appType, id, moduleName, version, ...config}) => ({\n appType,\n config,\n id,\n moduleName,\n remoteURL: `${https ? 'https' : 'http'}://${host}:${port}`,\n version,\n })),\n ),\n})\n\n/**\n * Bridge the dev-server registry into a workbench Vite server's HMR channel so\n * the page tracks apps as they come and go. A changed interface set means a\n * rebuilt remote — full-reload to drop the stale remote-entry; otherwise\n * rebroadcast for a soft reconcile. Returns a detach fn.\n */\nfunction attachViteDevServerBridge(server: ViteDevServer, organizationId?: string): () => void {\n const ownServers = (servers: DevServerManifest[]) =>\n organizationId ? servers.filter((entry) => entry.organizationId === organizationId) : servers\n\n server.ws.on('sanity:workbench:get-local-applications', (_, client) => {\n client.send(\n 'sanity:workbench:local-applications',\n toApplicationsPayload(ownServers(getRegisteredServers())),\n )\n })\n\n const setTracker = createExposesTracker()\n const registryWatcher = watchRegistry((allServers) => {\n const servers = ownServers(allServers)\n if (setTracker.hasChanged(servers)) {\n server.ws.send({type: 'full-reload'})\n return\n }\n server.ws.send('sanity:workbench:local-applications', toApplicationsPayload(servers))\n })\n\n return () => registryWatcher.close()\n}\n\n/**\n * Bridge the registry into the workbench remote's HMR channel. The remote never\n * claims the workbench lock: a held lock tells the next `sanity dev` a shell is\n * running, and the remote only renders inside that shell.\n */\nexport function startWorkbenchRemoteCoordinator(options: {server: ViteDevServer}): {\n close: () => Promise<void>\n} {\n const detachBridge = attachViteDevServerBridge(options.server)\n\n return {\n close: async () => detachBridge(),\n }\n}\n\ninterface WorkbenchDevServerResult {\n close: () => Promise<void>\n httpHost: string | undefined\n workbenchAvailable: boolean\n workbenchPort: number\n}\n\nexport interface StartWorkbenchOptions {\n /** Dependency-cache dir for the workbench Vite server, kept apart from the user's own. */\n cacheDir: string\n cliConfig: CliConfig\n httpHost: string | undefined\n httpPort: number\n output: Output\n /** Wrap the workbench in React StrictMode; the CLI resolves it (unset collapses to `false`). */\n reactStrictMode: boolean\n workDir: string\n}\n\nexport async function startWorkbenchDevServer(\n options: StartWorkbenchOptions,\n): Promise<WorkbenchDevServerResult> {\n const {\n cacheDir,\n cliConfig,\n httpHost,\n httpPort: workbenchPort,\n output,\n reactStrictMode,\n workDir,\n } = options\n\n // Workbench is opted into by a `defineApplication` app or a config-only\n // `unstable_defineMediaLibrary` config — the latter still needs the shell to\n // render it.\n if (!isWorkbenchApp(cliConfig?.app) && !isWorkbenchConfig(cliConfig?.app)) {\n devDebug('Not a workbench app or config, skipping workbench dev server')\n return {close: noop, httpHost, workbenchAvailable: false, workbenchPort}\n }\n\n const organizationId = resolveOrganizationId(cliConfig)\n\n // Acquire an exclusive lock — only one workbench per organization.\n // Uses O_EXCL which is atomic at the OS level, preventing races when\n // multiple `sanity dev` processes start simultaneously (e.g. via turbo).\n const workbenchLock = acquireWorkbenchLock({\n host: httpHost || 'localhost',\n organizationId,\n port: workbenchPort,\n })\n if (!workbenchLock) {\n const existing = await waitForWorkbenchLock(organizationId)\n devDebug(\n 'Workbench already running at pid %d on port %d, skipping',\n existing?.pid,\n existing?.port,\n )\n return {\n close: noop,\n httpHost: existing?.host ?? httpHost,\n workbenchAvailable: true,\n workbenchPort: existing?.port ?? workbenchPort,\n }\n }\n\n // The lock is already held; an exception here (runtime-file write failure,\n // invalid remote URL) would otherwise leak it until the next acquire prunes\n // the stale PID.\n let result: Awaited<ReturnType<typeof createWorkbenchViteServer>>\n try {\n result = await createWorkbenchViteServer({\n cacheDir,\n httpHost,\n organizationId,\n output,\n reactStrictMode,\n workbenchPort,\n workDir,\n })\n } catch (err) {\n workbenchLock.release()\n throw err\n }\n\n if (!result) {\n workbenchLock.release()\n return {close: noop, httpHost, workbenchAvailable: false, workbenchPort}\n }\n\n const {actualPort, close} = result\n workbenchLock.updatePort(actualPort)\n\n return {\n close: async () => {\n workbenchLock.release()\n await close()\n },\n httpHost,\n workbenchAvailable: true,\n workbenchPort: actualPort,\n }\n}\n\ninterface CreateWorkbenchViteServerOptions {\n cacheDir: string\n httpHost: string | undefined\n organizationId: string\n output: Output\n reactStrictMode: boolean\n workbenchPort: number\n workDir: string\n}\n\ninterface CreateWorkbenchViteServerResult {\n actualPort: number\n close: () => Promise<void>\n}\n\nasync function createWorkbenchViteServer(\n options: CreateWorkbenchViteServerOptions,\n): Promise<CreateWorkbenchViteServerResult | undefined> {\n const {cacheDir, httpHost, organizationId, output, reactStrictMode, workbenchPort, workDir} =\n options\n\n const remoteUrl = parseRemoteUrl(process.env.SANITY_INTERNAL_WORKBENCH_REMOTE_URL)\n\n devDebug('Writing workbench runtime files')\n const root = await writeWorkbenchRuntime({\n cwd: workDir,\n organizationId,\n reactStrictMode,\n remoteUrl,\n })\n\n const viteConfig: InlineConfig = {\n // Custom cache directory so sanity's vite cache doesn't conflict with local vite projects\n cacheDir,\n configFile: false,\n define: {\n __SANITY_STAGING__: isStaging(),\n 'import.meta.env.SANITY_INTERNAL_WORKBENCH_REMOTE_URL': JSON.stringify(remoteUrl),\n },\n logLevel: 'warn',\n mode: 'development',\n optimizeDeps: {\n // Keep this entry out of pre-bundling so Vite injects its HMR context.\n exclude: [renderDashboardEntry],\n },\n // viteReact looks inert here — it transforms none of the host's own modules —\n // but it's load-bearing for the remotes. It serves the Fast Refresh runtime at\n // /@react-refresh and injects the preamble that defines window.$RefreshReg$. The\n // federated remotes loaded into this page are react-refresh transformed, so\n // without the preamble they throw \"can't detect preamble\", and without the\n // runtime their /@react-refresh import (wired by @module-federation/vite's\n // remoteHmr) fails. Dropping it as dead code broke every panel; see #1262.\n plugins: [viteReact(), ...(remoteUrl ? [remoteManifestPreloadHeaderPlugin(remoteUrl)] : [])],\n resolve: {\n // The generated Vite root cannot reliably resolve this package.\n alias: {[renderDashboardEntry]: renderDashboardPath},\n dedupe: ['react', 'react-dom'],\n },\n root,\n server: {\n host: httpHost,\n port: workbenchPort,\n strictPort: false,\n warmup: {\n clientFiles: ['./workbench.js'],\n },\n },\n }\n\n devDebug('Creating workbench vite server')\n const server = await createServer(viteConfig)\n try {\n await server.listen()\n } catch (err) {\n await server.close()\n output.warn(\n `Dashboard dev server failed to start: ${err instanceof Error ? err.message : String(err)}`,\n )\n return undefined\n }\n\n // Vite may have picked a different port if the desired one was occupied\n const addr = server.httpServer?.address()\n const actualPort = typeof addr === 'object' && addr ? addr.port : workbenchPort\n\n // Fire-and-forget: warm the workbench remote's Vite transform pipeline so\n // the first browser request hits a pre-populated module graph.\n if (remoteUrl) {\n fetch(remoteUrl)\n .then((r) => r.body?.cancel())\n .catch(() => {})\n devDebug('Warming workbench remote at %s', remoteUrl)\n }\n\n const detachBridge = attachViteDevServerBridge(server, organizationId)\n\n return {\n actualPort,\n close: async () => {\n detachBridge()\n await server.close()\n },\n }\n}\n\n// Workbench is opted into via `defineApplication`, which carries the\n// organization ID. Deliberately no fallback (e.g. resolving it from the\n// configured project): the lookup would need an authenticated user and an\n// API round-trip on every startup for something the opt-in already declares.\nconst resolveOrganizationId = (cliConfig: CliConfig): string => {\n if (cliConfig.app?.organizationId) {\n return cliConfig.app.organizationId\n }\n\n throw new Error(\n 'The Dashboard requires an organization ID. Pass \"organizationId\" to defineApplication() in sanity.cli.ts.',\n )\n}\n\n// Restricts protocol to http(s) so the URL is safe to interpolate into HTML\n// attributes and Link headers downstream.\nconst remoteUrlSchema = z.url({normalize: true, protocol: /^https?$/})\n\nfunction parseRemoteUrl(value: string | undefined): string | undefined {\n if (!value) return undefined\n\n const result = remoteUrlSchema.safeParse(value)\n\n if (!result.success) {\n throw new Error(\n `Invalid SANITY_INTERNAL_WORKBENCH_REMOTE_URL: ${value} (must be an http(s) URL)`,\n )\n }\n\n return result.data\n}\n\n/**\n * Sets a `Link: <remoteUrl>; rel=preload; as=fetch; crossorigin` response header\n * on the index document so the browser can start fetching the Module Federation\n * manifest as soon as response headers arrive — before HTML parsing reaches the\n * in-head preconnect hint. `as=fetch` matches how the federation runtime later\n * retrieves the JSON manifest, allowing the preload entry to satisfy that fetch.\n */\nfunction remoteManifestPreloadHeaderPlugin(remoteUrl: string): Plugin {\n return {\n apply: 'serve',\n configureServer(server) {\n server.middlewares.use((req, res, next) => {\n const pathname = (req.url || '/').split('?')[0]\n if (pathname === '/' || pathname === '/index.html') {\n res.setHeader('Link', `<${remoteUrl}>; rel=preload; as=fetch; crossorigin`)\n }\n next()\n })\n },\n name: 'sanity:workbench-remote-preload-header',\n }\n}\n"],"names":["fileURLToPath","subdebug","isStaging","viteReact","createServer","z","isWorkbenchApp","isWorkbenchConfig","createExposesTracker","acquireWorkbenchLock","getRegisteredServers","isConfigOnlyServer","waitForWorkbenchLock","watchRegistry","toWireInterface","writeWorkbenchRuntime","devDebug","renderDashboardEntry","renderDashboardPath","URL","url","noop","toApplicationsPayload","servers","applications","filter","server","map","applicationId","host","https","id","interfaces","manifest","name","organizationId","port","projectId","reference","slug","type","visibility","iface","configs","flatMap","appType","moduleName","version","config","remoteURL","attachViteDevServerBridge","ownServers","entry","ws","on","_","client","send","setTracker","registryWatcher","allServers","hasChanged","close","startWorkbenchRemoteCoordinator","options","detachBridge","startWorkbenchDevServer","cacheDir","cliConfig","httpHost","httpPort","workbenchPort","output","reactStrictMode","workDir","app","workbenchAvailable","resolveOrganizationId","workbenchLock","existing","pid","result","createWorkbenchViteServer","err","release","actualPort","updatePort","remoteUrl","parseRemoteUrl","process","env","SANITY_INTERNAL_WORKBENCH_REMOTE_URL","root","cwd","viteConfig","configFile","define","__SANITY_STAGING__","JSON","stringify","logLevel","mode","optimizeDeps","exclude","plugins","remoteManifestPreloadHeaderPlugin","resolve","alias","dedupe","strictPort","warmup","clientFiles","listen","warn","Error","message","String","undefined","addr","httpServer","address","fetch","then","r","body","cancel","catch","remoteUrlSchema","normalize","protocol","value","safeParse","success","data","apply","configureServer","middlewares","use","req","res","next","pathname","split","setHeader"],"mappings":"AAAA,SAAQA,aAAa,QAAO,WAAU;AAEtC,SAAqCC,QAAQ,QAAO,mBAAkB;AACtE,SAAQC,SAAS,QAAO,wBAAuB;AAC/C,OAAOC,eAAe,uBAAsB;AAC5C,SAAQC,YAAY,QAA2D,OAAM;AACrF,SAAQC,CAAC,QAAO,WAAU;AAE1B,SAAQC,cAAc,EAAEC,iBAAiB,QAAO,qBAAo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ef,0BAA0BxB,QAAQS;IAEvD,OAAO;QACLkD;QACAvB,OAAO;YACLG;YACA,MAAMvC,OAAOoC,KAAK;QACpB;IACF;AACF;AAEA,qEAAqE;AACrE,wEAAwE;AACxE,0EAA0E;AAC1E,6EAA6E;AAC7E,MAAMe,wBAAwB,CAACT;IAC7B,IAAIA,UAAUO,GAAG,EAAExC,gBAAgB;QACjC,OAAOiC,UAAUO,GAAG,CAACxC,cAAc;IACrC;IAEA,MAAM,IAAI+E,MACR;AAEJ;AAEA,4EAA4E;AAC5E,0CAA0C;AAC1C,MAAMa,kBAAkB1H,EAAEe,GAAG,CAAC;IAAC4G,WAAW;IAAMC,UAAU;AAAU;AAEpE,SAASzC,eAAe0C,KAAyB;IAC/C,IAAI,CAACA,OAAO,OAAOb;IAEnB,MAAMpC,SAAS8C,gBAAgBI,SAAS,CAACD;IAEzC,IAAI,CAACjD,OAAOmD,OAAO,EAAE;QACnB,MAAM,IAAIlB,MACR,CAAC,8CAA8C,EAAEgB,MAAM,yBAAyB,CAAC;IAErF;IAEA,OAAOjD,OAAOoD,IAAI;AACpB;AAEA;;;;;;CAMC,GACD,SAAS5B,kCAAkClB,SAAiB;IAC1D,OAAO;QACL+C,OAAO;QACPC,iBAAgB7G,MAAM;YACpBA,OAAO8G,WAAW,CAACC,GAAG,CAAC,CAACC,KAAKC,KAAKC;gBAChC,MAAMC,WAAW,AAACH,CAAAA,IAAItH,GAAG,IAAI,GAAE,EAAG0H,KAAK,CAAC,IAAI,CAAC,EAAE;gBAC/C,IAAID,aAAa,OAAOA,aAAa,eAAe;oBAClDF,IAAII,SAAS,CAAC,QAAQ,CAAC,CAAC,EAAExD,UAAU,qCAAqC,CAAC;gBAC5E;gBACAqD;YACF;QACF;QACA1G,MAAM;IACR;AACF"}
@@ -0,0 +1,19 @@
1
+ import { styleText } from 'node:util';
2
+ export const SUMMARY_LOOKUP_TIMEOUT_MS = 3000;
3
+ export function formatSummary({ durationMs, heading, isApp, organization, title, url, version }) {
4
+ const seconds = (durationMs / 1000).toFixed(1);
5
+ const titleRow = title ? `\n ${(isApp ? 'App' : 'Studio').padEnd(12)} ${title}` : '';
6
+ const link = styleText([
7
+ 'blue',
8
+ 'underline'
9
+ ], url);
10
+ const versionRow = version ? `\n Version ${version}` : '';
11
+ return `
12
+ ${heading} in ${seconds}s
13
+
14
+ Organization ${organization}${titleRow}
15
+ URL ${link}${versionRow}
16
+ `;
17
+ }
18
+
19
+ //# sourceMappingURL=summary.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/actions/summary.ts"],"sourcesContent":["import {styleText} from 'node:util'\n\nexport const SUMMARY_LOOKUP_TIMEOUT_MS = 3000\n\nexport function formatSummary({\n durationMs,\n heading,\n isApp,\n organization,\n title,\n url,\n version,\n}: {\n durationMs: number\n heading: string\n isApp: boolean\n organization?: string\n title?: string\n url: string\n version?: string\n}): string {\n const seconds = (durationMs / 1000).toFixed(1)\n const titleRow = title ? `\\n ${(isApp ? 'App' : 'Studio').padEnd(12)} ${title}` : ''\n const link = styleText(['blue', 'underline'], url)\n const versionRow = version ? `\\n Version ${version}` : ''\n\n return `\n ${heading} in ${seconds}s\n\n Organization ${organization}${titleRow}\n URL ${link}${versionRow}\n`\n}\n"],"names":["styleText","SUMMARY_LOOKUP_TIMEOUT_MS","formatSummary","durationMs","heading","isApp","organization","title","url","version","seconds","toFixed","titleRow","padEnd","link","versionRow"],"mappings":"AAAA,SAAQA,SAAS,QAAO,YAAW;AAEnC,OAAO,MAAMC,4BAA4B,KAAI;AAE7C,OAAO,SAASC,cAAc,EAC5BC,UAAU,EACVC,OAAO,EACPC,KAAK,EACLC,YAAY,EACZC,KAAK,EACLC,GAAG,EACHC,OAAO,EASR;IACC,MAAMC,UAAU,AAACP,CAAAA,aAAa,IAAG,EAAGQ,OAAO,CAAC;IAC5C,MAAMC,WAAWL,QAAQ,CAAC,MAAM,EAAE,AAACF,CAAAA,QAAQ,QAAQ,QAAO,EAAGQ,MAAM,CAAC,IAAI,EAAE,EAAEN,OAAO,GAAG;IACtF,MAAMO,OAAOd,UAAU;QAAC;QAAQ;KAAY,EAAEQ;IAC9C,MAAMO,aAAaN,UAAU,CAAC,oBAAoB,EAAEA,SAAS,GAAG;IAEhE,OAAO,CAAC;EACR,EAAEL,QAAQ,IAAI,EAAEM,QAAQ;;kBAER,EAAEJ,eAAeM,SAAS;kBAC1B,EAAEE,OAAOC,WAAW;AACtC,CAAC;AACD"}
@@ -10,7 +10,7 @@ export async function renderDashboard(rootElement, config, options) {
10
10
  if (!rootElement) {
11
11
  throw new Error('Missing root element to mount application into');
12
12
  }
13
- const deployedDashboardHost = globalThis.__SANITY_STAGING__ === true ? 'workbench-apps-of5p8qpku.run.sanity.work' : 'workbench-apps-osyh1iet5.sanity.run';
13
+ const deployedDashboardHost = globalThis.__SANITY_STAGING__ === true ? 'workbench--apps--of5p8qpku.run.sanity.work' : 'workbench--apps--osyh1iet5.sanity.run';
14
14
  const remoteUrl = import.meta.env.SANITY_INTERNAL_WORKBENCH_REMOTE_URL ?? `https://${deployedDashboardHost}/mf-manifest.json`;
15
15
  const federation = createInstance({
16
16
  name: 'sanity-workbench',
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/renderDashboard.ts"],"sourcesContent":["/// <reference types=\"vite/client\" />\n\n// Keep this module browser-safe: Vite loads it directly in the generated dashboard runtime.\nimport {createInstance} from '@module-federation/runtime'\nimport {BehaviorSubject, type Observable} from 'rxjs'\n\ndeclare global {\n var __SANITY_STAGING__: boolean | undefined\n}\n\ninterface DashboardConfig {\n organizationId: string\n}\n\ninterface RenderDashboardOptions {\n reactStrictMode?: boolean\n}\n\ninterface DashboardRemoteModule {\n render: (\n rootElement: HTMLElement,\n props: {\n appConfigs?: Observable<unknown[]>\n config: DashboardConfig\n localApplications?: Observable<unknown[]>\n },\n options?: RenderDashboardOptions,\n ) => () => void\n}\n\nconst remoteName = 'workbench-remote'\nconst remoteModuleId = `${remoteName}/App`\nconst localApplicationsEvent = 'sanity:workbench:local-applications'\nconst noop = () => {}\n\nexport async function renderDashboard(\n rootElement: HTMLElement | null,\n config: DashboardConfig,\n options?: RenderDashboardOptions,\n): Promise<() => void> {\n if (!rootElement) {\n throw new Error('Missing root element to mount application into')\n }\n\n const deployedDashboardHost =\n globalThis.__SANITY_STAGING__ === true\n ? 'workbench-apps-of5p8qpku.run.sanity.work'\n : 'workbench-apps-osyh1iet5.sanity.run'\n const remoteUrl =\n import.meta.env.SANITY_INTERNAL_WORKBENCH_REMOTE_URL ??\n `https://${deployedDashboardHost}/mf-manifest.json`\n\n const federation = createInstance({\n name: 'sanity-workbench',\n remotes: [{entry: remoteUrl, name: remoteName}],\n })\n\n let remoteModule: DashboardRemoteModule | null\n try {\n remoteModule = await federation.loadRemote<DashboardRemoteModule>(remoteModuleId)\n } catch (error) {\n throw new Error(`Failed to load remote module \"${remoteModuleId}\"`, {cause: error})\n }\n\n if (!remoteModule || typeof remoteModule.render !== 'function') {\n throw new Error(`Remote module \"${remoteModuleId}\" did not expose a render function`)\n }\n\n let appConfigs: BehaviorSubject<unknown[]> | undefined\n let cleanupHmr = noop\n let localApplications: BehaviorSubject<unknown[]> | undefined\n\n if (import.meta.hot) {\n const hot = import.meta.hot\n const hmrLocalApplications = new BehaviorSubject<unknown[]>([])\n const hmrAppConfigs = new BehaviorSubject<unknown[]>([])\n const handler = (payload: {applications: unknown[]; configs?: unknown[]}) => {\n hmrLocalApplications.next(payload.applications)\n hmrAppConfigs.next(payload.configs ?? [])\n }\n\n localApplications = hmrLocalApplications\n appConfigs = hmrAppConfigs\n hot.on(localApplicationsEvent, handler)\n hot.send('sanity:workbench:get-local-applications')\n cleanupHmr = () => hot.off(localApplicationsEvent, handler)\n }\n\n const unmount = remoteModule.render(rootElement, {appConfigs, config, localApplications}, options)\n\n return () => {\n cleanupHmr()\n unmount()\n }\n}\n"],"names":["createInstance","BehaviorSubject","remoteName","remoteModuleId","localApplicationsEvent","noop","renderDashboard","rootElement","config","options","Error","deployedDashboardHost","globalThis","__SANITY_STAGING__","remoteUrl","env","SANITY_INTERNAL_WORKBENCH_REMOTE_URL","federation","name","remotes","entry","remoteModule","loadRemote","error","cause","render","appConfigs","cleanupHmr","localApplications","hot","hmrLocalApplications","hmrAppConfigs","handler","payload","next","applications","configs","on","send","off","unmount"],"mappings":"AAAA,qCAAqC;AAErC,4FAA4F;AAC5F,SAAQA,cAAc,QAAO,6BAA4B;AACzD,SAAQC,eAAe,QAAwB,OAAM;AA0BrD,MAAMC,aAAa;AACnB,MAAMC,iBAAiB,GAAGD,WAAW,IAAI,CAAC;AAC1C,MAAME,yBAAyB;AAC/B,MAAMC,OAAO,KAAO;AAEpB,OAAO,eAAeC,gBACpBC,WAA+B,EAC/BC,MAAuB,EACvBC,OAAgC;IAEhC,IAAI,CAACF,aAAa;QAChB,MAAM,IAAIG,MAAM;IAClB;IAEA,MAAMC,wBACJC,WAAWC,kBAAkB,KAAK,OAC9B,6CACA;IACN,MAAMC,YACJ,YAAYC,GAAG,CAACC,oCAAoC,IACpD,CAAC,QAAQ,EAAEL,sBAAsB,iBAAiB,CAAC;IAErD,MAAMM,aAAajB,eAAe;QAChCkB,MAAM;QACNC,SAAS;YAAC;gBAACC,OAAON;gBAAWI,MAAMhB;YAAU;SAAE;IACjD;IAEA,IAAImB;IACJ,IAAI;QACFA,eAAe,MAAMJ,WAAWK,UAAU,CAAwBnB;IACpE,EAAE,OAAOoB,OAAO;QACd,MAAM,IAAIb,MAAM,CAAC,8BAA8B,EAAEP,eAAe,CAAC,CAAC,EAAE;YAACqB,OAAOD;QAAK;IACnF;IAEA,IAAI,CAACF,gBAAgB,OAAOA,aAAaI,MAAM,KAAK,YAAY;QAC9D,MAAM,IAAIf,MAAM,CAAC,eAAe,EAAEP,eAAe,kCAAkC,CAAC;IACtF;IAEA,IAAIuB;IACJ,IAAIC,aAAatB;IACjB,IAAIuB;IAEJ,IAAI,YAAYC,GAAG,EAAE;QACnB,MAAMA,MAAM,YAAYA,GAAG;QAC3B,MAAMC,uBAAuB,IAAI7B,gBAA2B,EAAE;QAC9D,MAAM8B,gBAAgB,IAAI9B,gBAA2B,EAAE;QACvD,MAAM+B,UAAU,CAACC;YACfH,qBAAqBI,IAAI,CAACD,QAAQE,YAAY;YAC9CJ,cAAcG,IAAI,CAACD,QAAQG,OAAO,IAAI,EAAE;QAC1C;QAEAR,oBAAoBE;QACpBJ,aAAaK;QACbF,IAAIQ,EAAE,CAACjC,wBAAwB4B;QAC/BH,IAAIS,IAAI,CAAC;QACTX,aAAa,IAAME,IAAIU,GAAG,CAACnC,wBAAwB4B;IACrD;IAEA,MAAMQ,UAAUnB,aAAaI,MAAM,CAAClB,aAAa;QAACmB;QAAYlB;QAAQoB;IAAiB,GAAGnB;IAE1F,OAAO;QACLkB;QACAa;IACF;AACF"}
1
+ {"version":3,"sources":["../src/renderDashboard.ts"],"sourcesContent":["/// <reference types=\"vite/client\" />\n\n// Keep this module browser-safe: Vite loads it directly in the generated dashboard runtime.\nimport {createInstance} from '@module-federation/runtime'\nimport {BehaviorSubject, type Observable} from 'rxjs'\n\ndeclare global {\n var __SANITY_STAGING__: boolean | undefined\n}\n\ninterface DashboardConfig {\n organizationId: string\n}\n\ninterface RenderDashboardOptions {\n reactStrictMode?: boolean\n}\n\ninterface DashboardRemoteModule {\n render: (\n rootElement: HTMLElement,\n props: {\n appConfigs?: Observable<unknown[]>\n config: DashboardConfig\n localApplications?: Observable<unknown[]>\n },\n options?: RenderDashboardOptions,\n ) => () => void\n}\n\nconst remoteName = 'workbench-remote'\nconst remoteModuleId = `${remoteName}/App`\nconst localApplicationsEvent = 'sanity:workbench:local-applications'\nconst noop = () => {}\n\nexport async function renderDashboard(\n rootElement: HTMLElement | null,\n config: DashboardConfig,\n options?: RenderDashboardOptions,\n): Promise<() => void> {\n if (!rootElement) {\n throw new Error('Missing root element to mount application into')\n }\n\n const deployedDashboardHost =\n globalThis.__SANITY_STAGING__ === true\n ? 'workbench--apps--of5p8qpku.run.sanity.work'\n : 'workbench--apps--osyh1iet5.sanity.run'\n const remoteUrl =\n import.meta.env.SANITY_INTERNAL_WORKBENCH_REMOTE_URL ??\n `https://${deployedDashboardHost}/mf-manifest.json`\n\n const federation = createInstance({\n name: 'sanity-workbench',\n remotes: [{entry: remoteUrl, name: remoteName}],\n })\n\n let remoteModule: DashboardRemoteModule | null\n try {\n remoteModule = await federation.loadRemote<DashboardRemoteModule>(remoteModuleId)\n } catch (error) {\n throw new Error(`Failed to load remote module \"${remoteModuleId}\"`, {cause: error})\n }\n\n if (!remoteModule || typeof remoteModule.render !== 'function') {\n throw new Error(`Remote module \"${remoteModuleId}\" did not expose a render function`)\n }\n\n let appConfigs: BehaviorSubject<unknown[]> | undefined\n let cleanupHmr = noop\n let localApplications: BehaviorSubject<unknown[]> | undefined\n\n if (import.meta.hot) {\n const hot = import.meta.hot\n const hmrLocalApplications = new BehaviorSubject<unknown[]>([])\n const hmrAppConfigs = new BehaviorSubject<unknown[]>([])\n const handler = (payload: {applications: unknown[]; configs?: unknown[]}) => {\n hmrLocalApplications.next(payload.applications)\n hmrAppConfigs.next(payload.configs ?? [])\n }\n\n localApplications = hmrLocalApplications\n appConfigs = hmrAppConfigs\n hot.on(localApplicationsEvent, handler)\n hot.send('sanity:workbench:get-local-applications')\n cleanupHmr = () => hot.off(localApplicationsEvent, handler)\n }\n\n const unmount = remoteModule.render(rootElement, {appConfigs, config, localApplications}, options)\n\n return () => {\n cleanupHmr()\n unmount()\n }\n}\n"],"names":["createInstance","BehaviorSubject","remoteName","remoteModuleId","localApplicationsEvent","noop","renderDashboard","rootElement","config","options","Error","deployedDashboardHost","globalThis","__SANITY_STAGING__","remoteUrl","env","SANITY_INTERNAL_WORKBENCH_REMOTE_URL","federation","name","remotes","entry","remoteModule","loadRemote","error","cause","render","appConfigs","cleanupHmr","localApplications","hot","hmrLocalApplications","hmrAppConfigs","handler","payload","next","applications","configs","on","send","off","unmount"],"mappings":"AAAA,qCAAqC;AAErC,4FAA4F;AAC5F,SAAQA,cAA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AaK;QACbF,IAAIQ,EAAE,CAACjC,wBAAwB4B;QAC/BH,IAAIS,IAAI,CAAC;QACTX,aAAa,IAAME,IAAIU,GAAG,CAACnC,wBAAwB4B;IACrD;IAEA,MAAMQ,UAAUnB,aAAaI,MAAM,CAAClB,aAAa;QAACmB;QAAYlB;QAAQoB;IAAiB,GAAGnB;IAE1F,OAAO;QACLkB;QACAa;IACF;AACF"}
@@ -27,6 +27,28 @@ export async function getApplication(applicationId) {
27
27
  throw err;
28
28
  }
29
29
  }
30
+ export async function getOrganizationApplication(organizationId, idOrSlug, signal) {
31
+ const client = await getGlobalCliClient({
32
+ apiVersion: APP_WORKBENCH_API_VERSION,
33
+ ignoreWarnings: [
34
+ 'This is an experimental API version',
35
+ 'which will change without warning'
36
+ ],
37
+ requireUser: true
38
+ });
39
+ try {
40
+ return await client.request({
41
+ query: {
42
+ include: 'activeDeployment'
43
+ },
44
+ signal,
45
+ url: `/organizations/${organizationId}/applications/${idOrSlug}`
46
+ });
47
+ } catch (err) {
48
+ if (err?.statusCode === 404) return null;
49
+ throw err;
50
+ }
51
+ }
30
52
  /** Every application in an organization, in one page (`limit=none`). */ export async function listApplications(organizationId) {
31
53
  const client = await getClient();
32
54
  const { data } = await client.request({
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/services/applications.ts"],"sourcesContent":["import {PassThrough} from 'node:stream'\nimport {type Gzip} from 'node:zlib'\n\nimport {type AppVisibility, getGlobalCliClient} from '@sanity/cli-core'\nimport {isStaging} from '@sanity/cli-core/util'\nimport FormData from 'form-data'\n\nimport {type TileInterfaceMetadata, type ViewPlacementMetadata} from '../contract.js'\nimport {APP_WORKBENCH_API_VERSION} from './apiVersion.js'\n\nexport type ApplicationType = 'coreApp' | 'studio'\n\nexport interface Application {\n id: string\n organizationId: string\n slug: string | null\n title: string\n type: ApplicationType\n\n /** Set when the customer serves the build; such an application never receives a tarball. */\n externalUrl?: string\n}\n\ninterface BrettInterfaceBase {\n moduleId: string\n name: string\n title: string\n version: string\n}\n\n/**\n * An interface as Brett stores it, discriminated on `type`. `moduleId` is\n * remote-relative — the host prepends the app's id. Brett assigns the id.\n * @internal\n */\nexport type BrettInterface =\n | (BrettInterfaceBase & {metadata: null; type: 'asset_source'})\n | (BrettInterfaceBase & {metadata: null; type: 'worker'})\n | (BrettInterfaceBase & {metadata: TileInterfaceMetadata; type: 'tile'})\n | (BrettInterfaceBase & {metadata: ViewPlacementMetadata | null; type: 'app'})\n | (BrettInterfaceBase & {metadata: ViewPlacementMetadata | null; type: 'panel'})\n\n/**\n * A resource a deployment may interact with, as Brett stores it. Per-deployment\n * and forbidden for singletons (the server 400s).\n */\nexport interface BrettAccess {\n resourceId: string\n resourceType: 'canvas' | 'dashboard' | 'dataset' | 'media-library'\n}\n\n/** A studio workspace as Brett stores it. */\nexport interface BrettWorkspace {\n dataset: string\n projectId: string\n /** Lexicon schema descriptor id; Brett requires one per workspace. */\n schemaDescriptorId: string\n\n basePath?: string\n icon?: string\n name?: string\n subtitle?: string\n title?: string\n}\n\nexport function getWorkbenchUrl(organizationId: string): string {\n return `https://${organizationId}.${isStaging() ? 'run.sanity.work' : 'sanity.run'}`\n}\n\n/** Where a deployed application is served on its organization's workbench. */\nexport function getApplicationUrl(\n application: Pick<Application, 'id' | 'organizationId' | 'slug' | 'type'>,\n): string {\n const segment = application.type === 'studio' ? 'studios' : 'applications'\n return `${getWorkbenchUrl(application.organizationId)}/${segment}/${application.slug ?? application.id}`\n}\n\nasync function getClient() {\n return getGlobalCliClient({apiVersion: APP_WORKBENCH_API_VERSION, requireUser: true})\n}\n\nexport async function getApplication(applicationId: string): Promise<Application | null> {\n const client = await getClient()\n try {\n return await client.request({url: `/applications/${applicationId}`})\n } catch (err) {\n if ((err as {statusCode?: number})?.statusCode === 404) return null\n throw err\n }\n}\n\n/** Every application in an organization, in one page (`limit=none`). */\nexport async function listApplications(organizationId: string): Promise<Application[]> {\n const client = await getClient()\n const {data}: {data: Application[]} = await client.request({\n query: {limit: 'none', organizationId},\n url: '/applications',\n })\n return data\n}\n\n/**\n * Create an application record (no deployment), so the CLI can build with the\n * returned id, then ship it via {@link createDeployment}.\n */\nexport async function createApplication(options: {\n /** The origin a customer serves the build from; Brett then never hosts a bundle for it. */\n externalUrl?: string\n isSingleton?: boolean\n name?: string\n organizationId: string\n projectId?: string\n slug: string\n title: string\n type: ApplicationType\n visibility?: AppVisibility\n}): Promise<Application> {\n const {externalUrl, isSingleton, name, organizationId, projectId, slug, title, type, visibility} =\n options\n const client = await getClient()\n return client.request({\n body: {\n organizationId,\n slug,\n title,\n type,\n // Identity, distinct from the slug address. Omitted → Brett defaults it to slug.\n ...(name ? {name} : {}),\n // Brett requires `isSingleton` on `POST /applications`, so the request\n // builder keeps forwarding it even though the CLI itself never sets it.\n ...(isSingleton === undefined ? {} : {isSingleton}),\n ...(visibility ? {visibility} : {}),\n ...(externalUrl ? {externalUrl} : {}),\n // Studio config is set once, at create — it's immutable on redeploy.\n ...(projectId ? {config: {studio: {projectId}}} : {}),\n },\n method: 'POST',\n url: `/applications`,\n })\n}\n\n/** Mutable application fields the deploy flow patches after create. */\nexport interface ApplicationUpdate {\n icon?: string | null\n /** The address the application is served at; renaming moves it. */\n slug?: string\n title?: string\n visibility?: AppVisibility\n}\n\n// Patch an application's mutable fields.\nexport async function updateApplication(\n applicationId: string,\n update: ApplicationUpdate,\n): Promise<void> {\n const client = await getClient()\n await client.request({body: update, method: 'PATCH', url: `/applications/${applicationId}`})\n}\n\n/**\n * Deploy a new active version to an existing application. `mfManifest` is the\n * build's federation manifest; `tarball` is omitted for an external application,\n * whose build the customer serves themselves.\n */\nexport async function createDeployment(options: {\n access?: readonly BrettAccess[]\n applicationId: string\n interfaces: readonly BrettInterface[]\n isAutoUpdating: boolean\n mfManifest: Record<string, unknown>\n tarball?: Gzip\n version: string\n workspaces?: readonly BrettWorkspace[]\n}): Promise<{id: string}> {\n const {\n access,\n applicationId,\n interfaces,\n isAutoUpdating,\n mfManifest,\n tarball,\n version,\n workspaces,\n } = options\n const formData = new FormData()\n formData.append('isAutoUpdating', isAutoUpdating.toString())\n appendDeploymentParts(formData, {access, interfaces, mfManifest, tarball, version, workspaces})\n return request(`/applications/${applicationId}/deployments`, formData)\n}\n\n/** Soft-deletes the application and all its deployments; already deleted counts as done. */\nexport async function deleteApplication(applicationId: string): Promise<void> {\n const client = await getClient()\n try {\n await client.request({method: 'DELETE', url: `/applications/${applicationId}`})\n } catch (err) {\n if ((err as {statusCode?: number})?.statusCode !== 404) throw err\n }\n}\n\nfunction appendDeploymentParts(\n formData: FormData,\n {\n access,\n interfaces,\n mfManifest,\n tarball,\n version,\n workspaces,\n }: {\n access?: readonly BrettAccess[]\n interfaces: readonly BrettInterface[]\n mfManifest: Record<string, unknown>\n tarball?: Gzip\n version: string\n workspaces?: readonly BrettWorkspace[]\n },\n): void {\n formData.append('version', version)\n appendJson(formData, 'interfaces', interfaces)\n // Studio-only — the server rejects a workspaces part on non-studio types.\n if (workspaces?.length) appendJson(formData, 'workspaces', workspaces)\n // Per-deployment; forbidden for singletons, so callers omit it there.\n if (access?.length) appendJson(formData, 'access', access)\n appendJson(formData, 'mfManifest', mfManifest)\n // Last: the server requires every field part to precede the tarball.\n if (tarball) {\n formData.append('tarball', tarball, {contentType: 'application/gzip', filename: 'app.tar.gz'})\n }\n}\n\n/** Structured parts must arrive as JSON so the server parses them. */\nfunction appendJson(formData: FormData, name: string, value: unknown): void {\n formData.append(name, JSON.stringify(value), {contentType: 'application/json'})\n}\n\nasync function request<T>(url: string, formData: FormData): Promise<T> {\n const client = await getClient()\n return client.request({\n body: formData.pipe(new PassThrough()),\n headers: formData.getHeaders(),\n method: 'POST',\n url,\n })\n}\n"],"names":["PassThrough","getGlobalCliClient","isStaging","FormData","APP_WORKBENCH_API_VERSION","getWorkbenchUrl","organizationId","getApplicationUrl","application","segment","type","slug","id","getClient","apiVersion","requireUser","getApplication","applicationId","client","request","url","err","statusCode","listApplications","data","query","limit","createApplication","options","externalUrl","isSingleton","name","projectId","title","visibility","body","undefined","config","studio","method","updateApplication","update","createDeployment","access","interfaces","isAutoUpdating","mfManifest","tarball","version","workspaces","formData","append","toString","appendDeploymentParts","deleteApplication","appendJson","length","contentType","filename","value","JSON","stringify","pipe","headers","getHeaders"],"mappings":"AAAA,SAAQA,WAAW,QAAO,cAAa;AAGvC,SAA4BC,kBAAkB,QAAO,mBAAkB;AACvE,SAAQC,SAAS,QAAO,wBAAuB;AAC/C,OAAOC,cAAc,YAAW;AAGhC,SAAQC,yBAAyB,QAAO,kBAAiB;AAyDzD,OAAO,SAASC,gBAAgBC,cAAsB;IACpD,OAAO,CAAC,QAAQ,EAAEA,eAAe,CAAC,EAAEJ,cAAc,oBAAoB,cAAc;AACtF;AAEA,4EAA4E,GAC5E,OAAO,SAASK,kBACdC,WAAyE;IAEzE,MAAMC,UAAUD,YAAYE,IAAI,KAAK,WAAW,YAAY;IAC5D,OAAO,GAAGL,gBAAgBG,YAAYF,cAAc,EAAE,CAAC,EAAEG,QAAQ,CAAC,EAAED,YAAYG,IAAI,IAAIH,YAAYI,EAAE,EAAE;AAC1G;AAEA,eAAeC;IACb,OAAOZ,mBAAmB;QAACa,YAAYV;QAA2BW,aAAa;IAAI;AACrF;AAEA,OAAO,eAAeC,eAAeC,aAAqB;IACxD,MAAMC,SAAS,MAAML;IACrB,IAAI;QACF,OAAO,MAAMK,OAAOC,OAAO,CAAC;YAACC,KAAK,CAAC,cAAc,EAAEH,eAAe;QAAA;IACpE,EAAE,OAAOI,KAAK;QACZ,IAAI,AAACA,KAA+BC,eAAe,KAAK,OAAO;QAC/D,MAAMD;IACR;AACF;AAEA,sEAAsE,GACtE,OAAO,eAAeE,iBAAiBjB,cAAsB;IAC3D,MAAMY,SAAS,MAAML;IACrB,MAAM,EAACW,IAAI,EAAC,GAA0B,MAAMN,OAAOC,OAAO,CAAC;QACzDM,OAAO;YAACC,OAAO;YAAQpB;QAAc;QACrCc,KAAK;IACP;IACA,OAAOI;AACT;AAEA;;;CAGC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AAU;IAC7F,OAAO9B,QAAQ,CAAC,cAAc,EAAEF,cAAc,YAAY,CAAC,EAAEiC;AAC/D;AAEA,0FAA0F,GAC1F,OAAO,eAAeI,kBAAkBrC,aAAqB;IAC3D,MAAMC,SAAS,MAAML;IACrB,IAAI;QACF,MAAMK,OAAOC,OAAO,CAAC;YAACoB,QAAQ;YAAUnB,KAAK,CAAC,cAAc,EAAEH,eAAe;QAAA;IAC/E,EAAE,OAAOI,KAAK;QACZ,IAAI,AAACA,KAA+BC,eAAe,KAAK,MAAMD;IAChE;AACF;AAEA,SAASgC,sBACPH,QAAkB,EAClB,EACEP,MAAM,EACNC,UAAU,EACVE,UAAU,EACVC,OAAO,EACPC,OAAO,EACPC,UAAU,EAQX;IAEDC,SAASC,MAAM,CAAC,WAAWH;IAC3BO,WAAWL,UAAU,cAAcN;IACnC,0EAA0E;IAC1E,IAAIK,YAAYO,QAAQD,WAAWL,UAAU,cAAcD;IAC3D,sEAAsE;IACtE,IAAIN,QAAQa,QAAQD,WAAWL,UAAU,UAAUP;IACnDY,WAAWL,UAAU,cAAcJ;IACnC,qEAAqE;IACrE,IAAIC,SAAS;QACXG,SAASC,MAAM,CAAC,WAAWJ,SAAS;YAACU,aAAa;YAAoBC,UAAU;QAAY;IAC9F;AACF;AAEA,oEAAoE,GACpE,SAASH,WAAWL,QAAkB,EAAEnB,IAAY,EAAE4B,KAAc;IAClET,SAASC,MAAM,CAACpB,MAAM6B,KAAKC,SAAS,CAACF,QAAQ;QAACF,aAAa;IAAkB;AAC/E;AAEA,eAAetC,QAAWC,GAAW,EAAE8B,QAAkB;IACvD,MAAMhC,SAAS,MAAML;IACrB,OAAOK,OAAOC,OAAO,CAAC;QACpBgB,MAAMe,SAASY,IAAI,CAAC,IAAI9D;QACxB+D,SAASb,SAASc,UAAU;QAC5BzB,QAAQ;QACRnB;IACF;AACF"}
1
+ {"version":3,"sources":["../../src/services/applications.ts"],"sourcesContent":["import {PassThrough} from 'node:stream'\nimport {type Gzip} from 'node:zlib'\n\nimport {type AppVisibility, getGlobalCliClient} from '@sanity/cli-core'\nimport {isStaging} from '@sanity/cli-core/util'\nimport FormData from 'form-data'\n\nimport {type TileInterfaceMetadata, type ViewPlacementMetadata} from '../contract.js'\nimport {APP_WORKBENCH_API_VERSION} from './apiVersion.js'\n\nexport type ApplicationType = 'coreApp' | 'studio'\n\nexport interface Application {\n id: string\n organizationId: string\n slug: string | null\n title: string\n type: ApplicationType\n\n /** Set when the customer serves the build; such an application never receives a tarball. */\n externalUrl?: string\n}\n\ninterface BrettInterfaceBase {\n moduleId: string\n name: string\n title: string\n version: string\n}\n\n/**\n * An interface as Brett stores it, discriminated on `type`. `moduleId` is\n * remote-relative — the host prepends the app's id. Brett assigns the id.\n * @internal\n */\nexport type BrettInterface =\n | (BrettInterfaceBase & {metadata: null; type: 'asset_source'})\n | (BrettInterfaceBase & {metadata: null; type: 'worker'})\n | (BrettInterfaceBase & {metadata: TileInterfaceMetadata; type: 'tile'})\n | (BrettInterfaceBase & {metadata: ViewPlacementMetadata | null; type: 'app'})\n | (BrettInterfaceBase & {metadata: ViewPlacementMetadata | null; type: 'panel'})\n\n/**\n * A resource a deployment may interact with, as Brett stores it. Per-deployment\n * and forbidden for singletons (the server 400s).\n */\nexport interface BrettAccess {\n resourceId: string\n resourceType: 'canvas' | 'dashboard' | 'dataset' | 'media-library'\n}\n\n/** A studio workspace as Brett stores it. */\nexport interface BrettWorkspace {\n dataset: string\n projectId: string\n /** Lexicon schema descriptor id; Brett requires one per workspace. */\n schemaDescriptorId: string\n\n basePath?: string\n icon?: string\n name?: string\n subtitle?: string\n title?: string\n}\n\nexport function getWorkbenchUrl(organizationId: string): string {\n return `https://${organizationId}.${isStaging() ? 'run.sanity.work' : 'sanity.run'}`\n}\n\n/** Where a deployed application is served on its organization's workbench. */\nexport function getApplicationUrl(\n application: Pick<Application, 'id' | 'organizationId' | 'slug' | 'type'>,\n): string {\n const segment = application.type === 'studio' ? 'studios' : 'applications'\n return `${getWorkbenchUrl(application.organizationId)}/${segment}/${application.slug ?? application.id}`\n}\n\nasync function getClient() {\n return getGlobalCliClient({apiVersion: APP_WORKBENCH_API_VERSION, requireUser: true})\n}\n\nexport async function getApplication(applicationId: string): Promise<Application | null> {\n const client = await getClient()\n try {\n return await client.request({url: `/applications/${applicationId}`})\n } catch (err) {\n if ((err as {statusCode?: number})?.statusCode === 404) return null\n throw err\n }\n}\n\nexport async function getOrganizationApplication(\n organizationId: string,\n idOrSlug: string,\n signal?: AbortSignal,\n): Promise<\n (Application & {activeDeployment: {createdAt: string; deployedBy: string} | null}) | null\n> {\n const client = await getGlobalCliClient({\n apiVersion: APP_WORKBENCH_API_VERSION,\n ignoreWarnings: ['This is an experimental API version', 'which will change without warning'],\n requireUser: true,\n })\n try {\n return await client.request({\n query: {include: 'activeDeployment'},\n signal,\n url: `/organizations/${organizationId}/applications/${idOrSlug}`,\n })\n } catch (err) {\n if ((err as {statusCode?: number})?.statusCode === 404) return null\n throw err\n }\n}\n\n/** Every application in an organization, in one page (`limit=none`). */\nexport async function listApplications(organizationId: string): Promise<Application[]> {\n const client = await getClient()\n const {data}: {data: Application[]} = await client.request({\n query: {limit: 'none', organizationId},\n url: '/applications',\n })\n return data\n}\n\n/**\n * Create an application record (no deployment), so the CLI can build with the\n * returned id, then ship it via {@link createDeployment}.\n */\nexport async function createApplication(options: {\n /** The origin a customer serves the build from; Brett then never hosts a bundle for it. */\n externalUrl?: string\n isSingleton?: boolean\n name?: string\n organizationId: string\n projectId?: string\n slug: string\n title: string\n type: ApplicationType\n visibility?: AppVisibility\n}): Promise<Application> {\n const {externalUrl, isSingleton, name, organizationId, projectId, slug, title, type, visibility} =\n options\n const client = await getClient()\n return client.request({\n body: {\n organizationId,\n slug,\n title,\n type,\n // Identity, distinct from the slug address. Omitted → Brett defaults it to slug.\n ...(name ? {name} : {}),\n // Brett requires `isSingleton` on `POST /applications`, so the request\n // builder keeps forwarding it even though the CLI itself never sets it.\n ...(isSingleton === undefined ? {} : {isSingleton}),\n ...(visibility ? {visibility} : {}),\n ...(externalUrl ? {externalUrl} : {}),\n // Studio config is set once, at create — it's immutable on redeploy.\n ...(projectId ? {config: {studio: {projectId}}} : {}),\n },\n method: 'POST',\n url: `/applications`,\n })\n}\n\n/** Mutable application fields the deploy flow patches after create. */\nexport interface ApplicationUpdate {\n icon?: string | null\n /** The address the application is served at; renaming moves it. */\n slug?: string\n title?: string\n visibility?: AppVisibility\n}\n\n// Patch an application's mutable fields.\nexport async function updateApplication(\n applicationId: string,\n update: ApplicationUpdate,\n): Promise<void> {\n const client = await getClient()\n await client.request({body: update, method: 'PATCH', url: `/applications/${applicationId}`})\n}\n\n/**\n * Deploy a new active version to an existing application. `mfManifest` is the\n * build's federation manifest; `tarball` is omitted for an external application,\n * whose build the customer serves themselves.\n */\nexport async function createDeployment(options: {\n access?: readonly BrettAccess[]\n applicationId: string\n interfaces: readonly BrettInterface[]\n isAutoUpdating: boolean\n mfManifest: Record<string, unknown>\n tarball?: Gzip\n version: string\n workspaces?: readonly BrettWorkspace[]\n}): Promise<{id: string}> {\n const {\n access,\n applicationId,\n interfaces,\n isAutoUpdating,\n mfManifest,\n tarball,\n version,\n workspaces,\n } = options\n const formData = new FormData()\n formData.append('isAutoUpdating', isAutoUpdating.toString())\n appendDeploymentParts(formData, {access, interfaces, mfManifest, tarball, version, workspaces})\n return request(`/applications/${applicationId}/deployments`, formData)\n}\n\n/** Soft-deletes the application and all its deployments; already deleted counts as done. */\nexport async function deleteApplication(applicationId: string): Promise<void> {\n const client = await getClient()\n try {\n await client.request({method: 'DELETE', url: `/applications/${applicationId}`})\n } catch (err) {\n if ((err as {statusCode?: number})?.statusCode !== 404) throw err\n }\n}\n\nfunction appendDeploymentParts(\n formData: FormData,\n {\n access,\n interfaces,\n mfManifest,\n tarball,\n version,\n workspaces,\n }: {\n access?: readonly BrettAccess[]\n interfaces: readonly BrettInterface[]\n mfManifest: Record<string, unknown>\n tarball?: Gzip\n version: string\n workspaces?: readonly BrettWorkspace[]\n },\n): void {\n formData.append('version', version)\n appendJson(formData, 'interfaces', interfaces)\n // Studio-only — the server rejects a workspaces part on non-studio types.\n if (workspaces?.length) appendJson(formData, 'workspaces', workspaces)\n // Per-deployment; forbidden for singletons, so callers omit it there.\n if (access?.length) appendJson(formData, 'access', access)\n appendJson(formData, 'mfManifest', mfManifest)\n // Last: the server requires every field part to precede the tarball.\n if (tarball) {\n formData.append('tarball', tarball, {contentType: 'application/gzip', filename: 'app.tar.gz'})\n }\n}\n\n/** Structured parts must arrive as JSON so the server parses them. */\nfunction appendJson(formData: FormData, name: string, value: unknown): void {\n formData.append(name, JSON.stringify(value), {contentType: 'application/json'})\n}\n\nasync function request<T>(url: string, formData: FormData): Promise<T> {\n const client = await getClient()\n return client.request({\n body: formData.pipe(new PassThrough()),\n headers: formData.getHeaders(),\n method: 'POST',\n url,\n })\n}\n"],"names":["PassThrough","getGlobalCliClient","isStaging","FormData","APP_WORKBENCH_API_VERSION","getWorkbenchUrl","organizationId","getApplicationUrl","application","segment","type","slug","id","getClient","apiVersion","requireUser","getApplication","applicationId","client","request","url","err","statusCode","getOrganizationApplication","idOrSlug","signal","ignoreWarnings","query","include","listApplications","data","limit","createApplication","options","externalUrl","isSingleton","name","projectId","title","visibility","body","undefined","config","studio","method","updateApplication","update","createDeployment","access","interfaces","isAutoUpdating","mfManifest","tarball","version","workspaces","formData","append","toString","appendDeploymentParts","deleteApplication","appendJson","length","contentType","filename","value","JSON","stringify","pipe","headers","getHeaders"],"mappings":"AAAA,SAAQA,WAAW,QAAO,cAAa;AAGvC,SAA4BC,kBAAkB,QAAO,mBAAkB;AACvE,SAAQC,SAAS,QAAO,wBAAuB;AAC/C,OAAOC,cAAc,YAAW;AAGhC,SAAQC,yBAAyB,QAAO,kBAAiB;AAyDzD,OAAO,SAASC,gBAAgBC,cAAsB;IACpD,OAAO,CAAC,QAAQ,EAAEA,eAAe,CAAC,EAAEJ,cAAc,oBAAoB,cAAc;AACtF;AAEA,4E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AAc,EAAEF,cAAc,YAAY,CAAC,EAAEsC;AAC/D;AAEA,0FAA0F,GAC1F,OAAO,eAAeI,kBAAkB1C,aAAqB;IAC3D,MAAMC,SAAS,MAAML;IACrB,IAAI;QACF,MAAMK,OAAOC,OAAO,CAAC;YAACyB,QAAQ;YAAUxB,KAAK,CAAC,cAAc,EAAEH,eAAe;QAAA;IAC/E,EAAE,OAAOI,KAAK;QACZ,IAAI,AAACA,KAA+BC,eAAe,KAAK,MAAMD;IAChE;AACF;AAEA,SAASqC,sBACPH,QAAkB,EAClB,EACEP,MAAM,EACNC,UAAU,EACVE,UAAU,EACVC,OAAO,EACPC,OAAO,EACPC,UAAU,EAQX;IAEDC,SAASC,MAAM,CAAC,WAAWH;IAC3BO,WAAWL,UAAU,cAAcN;IACnC,0EAA0E;IAC1E,IAAIK,YAAYO,QAAQD,WAAWL,UAAU,cAAcD;IAC3D,sEAAsE;IACtE,IAAIN,QAAQa,QAAQD,WAAWL,UAAU,UAAUP;IACnDY,WAAWL,UAAU,cAAcJ;IACnC,qEAAqE;IACrE,IAAIC,SAAS;QACXG,SAASC,MAAM,CAAC,WAAWJ,SAAS;YAACU,aAAa;YAAoBC,UAAU;QAAY;IAC9F;AACF;AAEA,oEAAoE,GACpE,SAASH,WAAWL,QAAkB,EAAEnB,IAAY,EAAE4B,KAAc;IAClET,SAASC,MAAM,CAACpB,MAAM6B,KAAKC,SAAS,CAACF,QAAQ;QAACF,aAAa;IAAkB;AAC/E;AAEA,eAAe3C,QAAWC,GAAW,EAAEmC,QAAkB;IACvD,MAAMrC,SAAS,MAAML;IACrB,OAAOK,OAAOC,OAAO,CAAC;QACpBqB,MAAMe,SAASY,IAAI,CAAC,IAAInE;QACxBoE,SAASb,SAASc,UAAU;QAC5BzB,QAAQ;QACRxB;IACF;AACF"}
@@ -0,0 +1,14 @@
1
+ import { getGlobalCliClient } from '@sanity/cli-core';
2
+ const ORGANIZATIONS_API_VERSION = 'v2025-05-14';
3
+ export async function getOrganization(organizationId, signal) {
4
+ const client = await getGlobalCliClient({
5
+ apiVersion: ORGANIZATIONS_API_VERSION,
6
+ requireUser: true
7
+ });
8
+ return client.request({
9
+ signal,
10
+ url: `/organizations/${organizationId}`
11
+ });
12
+ }
13
+
14
+ //# sourceMappingURL=organizations.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/services/organizations.ts"],"sourcesContent":["import {getGlobalCliClient} from '@sanity/cli-core'\n\nconst ORGANIZATIONS_API_VERSION = 'v2025-05-14'\n\nexport async function getOrganization(\n organizationId: string,\n signal?: AbortSignal,\n): Promise<{name: string}> {\n const client = await getGlobalCliClient({\n apiVersion: ORGANIZATIONS_API_VERSION,\n requireUser: true,\n })\n\n return client.request({signal, url: `/organizations/${organizationId}`})\n}\n"],"names":["getGlobalCliClient","ORGANIZATIONS_API_VERSION","getOrganization","organizationId","signal","client","apiVersion","requireUser","request","url"],"mappings":"AAAA,SAAQA,kBAAkB,QAAO,mBAAkB;AAEnD,MAAMC,4BAA4B;AAElC,OAAO,eAAeC,gBACpBC,cAAsB,EACtBC,MAAoB;IAEpB,MAAMC,SAAS,MAAML,mBAAmB;QACtCM,YAAYL;QACZM,aAAa;IACf;IAEA,OAAOF,OAAOG,OAAO,CAAC;QAACJ;QAAQK,KAAK,CAAC,eAAe,EAAEN,gBAAgB;IAAA;AACxE"}
@@ -0,0 +1,24 @@
1
+ import { getGlobalCliClient } from '@sanity/cli-core';
2
+ const USERS_API_VERSION = 'v2025-05-14';
3
+ export async function getUser(userId, signal) {
4
+ const client = await getGlobalCliClient({
5
+ apiVersion: USERS_API_VERSION,
6
+ requireUser: true
7
+ });
8
+ return client.request({
9
+ signal,
10
+ url: `/users/${userId}`
11
+ });
12
+ }
13
+ export async function getCurrentUser(signal) {
14
+ const client = await getGlobalCliClient({
15
+ apiVersion: USERS_API_VERSION,
16
+ requireUser: true
17
+ });
18
+ return client.request({
19
+ signal,
20
+ url: '/users/me'
21
+ });
22
+ }
23
+
24
+ //# sourceMappingURL=users.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/services/users.ts"],"sourcesContent":["import {getGlobalCliClient} from '@sanity/cli-core'\n\nconst USERS_API_VERSION = 'v2025-05-14'\n\nexport async function getUser(\n userId: string,\n signal?: AbortSignal,\n): Promise<{displayName: string}> {\n const client = await getGlobalCliClient({apiVersion: USERS_API_VERSION, requireUser: true})\n\n return client.request({signal, url: `/users/${userId}`})\n}\n\nexport async function getCurrentUser(signal?: AbortSignal): Promise<{name: string}> {\n const client = await getGlobalCliClient({apiVersion: USERS_API_VERSION, requireUser: true})\n\n return client.request({signal, url: '/users/me'})\n}\n"],"names":["getGlobalCliClient","USERS_API_VERSION","getUser","userId","signal","client","apiVersion","requireUser","request","url","getCurrentUser"],"mappings":"AAAA,SAAQA,kBAAkB,QAAO,mBAAkB;AAEnD,MAAMC,oBAAoB;AAE1B,OAAO,eAAeC,QACpBC,MAAc,EACdC,MAAoB;IAEpB,MAAMC,SAAS,MAAML,mBAAmB;QAACM,YAAYL;QAAmBM,aAAa;IAAI;IAEzF,OAAOF,OAAOG,OAAO,CAAC;QAACJ;QAAQK,KAAK,CAAC,OAAO,EAAEN,QAAQ;IAAA;AACxD;AAEA,OAAO,eAAeO,eAAeN,MAAoB;IACvD,MAAMC,SAAS,MAAML,mBAAmB;QAACM,YAAYL;QAAmBM,aAAa;IAAI;IAEzF,OAAOF,OAAOG,OAAO,CAAC;QAACJ;QAAQK,KAAK;IAAW;AACjD"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sanity/workbench-cli",
3
- "version": "2.16.1",
3
+ "version": "2.18.0",
4
4
  "description": "Internal implementation detail of the Sanity CLI's unstable workbench support. Not intended for direct use.",
5
5
  "homepage": "https://github.com/sanity-io/cli",
6
6
  "bugs": "https://github.com/sanity-io/cli/issues",
@@ -66,15 +66,16 @@
66
66
  },
67
67
  "dependencies": {
68
68
  "@module-federation/runtime": "2.9.3",
69
- "@module-federation/vite": "1.23.11",
69
+ "@module-federation/vite": "1.24.0",
70
70
  "@sanity/cli-core": "^3.15.1",
71
71
  "@sanity/sdk": "^3.12.0",
72
72
  "@sanity/types": "^6.22.0",
73
73
  "@vitejs/plugin-react": "^6.3.0",
74
74
  "form-data": "^4.0.6",
75
+ "open": "^11.0.4",
75
76
  "rxjs": "^7.8.2",
76
77
  "semver": "^7.8.6",
77
- "tar": "^7.5.22",
78
+ "tar": "^7.5.23",
78
79
  "vite": "^8.3.8",
79
80
  "zod": "^4.6.7"
80
81
  },
@@ -94,8 +95,8 @@
94
95
  "eslint": "^10.7.0",
95
96
  "jsdom": "^29.1.1",
96
97
  "publint": "^0.3.21",
97
- "react": "^19.3.0",
98
- "react-dom": "^19.3.0",
98
+ "react": "^19.3.1",
99
+ "react-dom": "^19.3.1",
99
100
  "typescript": "^6.0.3",
100
101
  "vitest": "^5.1.0"
101
102
  },