@sanity/workbench-cli 2.14.0 → 2.15.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 (48) hide show
  1. package/dist/_exports/_internal_auto_updates.d.ts +14 -0
  2. package/dist/_exports/_internal_auto_updates.js +3 -0
  3. package/dist/_exports/_internal_auto_updates.js.map +1 -0
  4. package/dist/_exports/_internal_worker_bus.d.ts +1 -1
  5. package/dist/_exports/build.d.ts +8 -0
  6. package/dist/_exports/{defineService-D_DFLM8x.d.ts → defineService-DPZwNN6_.d.ts} +5 -2
  7. package/dist/_exports/deploy.d.ts +15 -1
  8. package/dist/_exports/deploy.js +1 -0
  9. package/dist/_exports/deploy.js.map +1 -1
  10. package/dist/_exports/dev.d.ts +23 -2
  11. package/dist/_exports/dev.js +1 -0
  12. package/dist/_exports/dev.js.map +1 -1
  13. package/dist/_exports/index.d.ts +1 -1
  14. package/dist/_exports/preview.d.ts +1 -1
  15. package/dist/_exports/{registry-DCjjQ1sS.d.ts → registry-NvtHmoN1.d.ts} +3 -1
  16. package/dist/actions/build/autoUpdatesLoader.js +36 -0
  17. package/dist/actions/build/autoUpdatesLoader.js.map +1 -0
  18. package/dist/actions/build/render-remote.js +22 -7
  19. package/dist/actions/build/render-remote.js.map +1 -1
  20. package/dist/actions/build/services/workerBus.js +6 -7
  21. package/dist/actions/build/services/workerBus.js.map +1 -1
  22. package/dist/actions/build/vite/plugin.js +3 -1
  23. package/dist/actions/build/vite/plugin.js.map +1 -1
  24. package/dist/actions/build/vite/plugins/plugin-sanity-auto-updates.js +125 -0
  25. package/dist/actions/build/vite/plugins/plugin-sanity-auto-updates.js.map +1 -0
  26. package/dist/actions/build/vite/plugins/plugin-sanity-federation-runtime.js +3 -1
  27. package/dist/actions/build/vite/plugins/plugin-sanity-federation-runtime.js.map +1 -1
  28. package/dist/actions/build/vite/workbench-vite-plugins.js +5 -1
  29. package/dist/actions/build/vite/workbench-vite-plugins.js.map +1 -1
  30. package/dist/actions/deploy/selectWorkbenchAppId.js +31 -0
  31. package/dist/actions/deploy/selectWorkbenchAppId.js.map +1 -0
  32. package/dist/actions/dev/registry.js +20 -1
  33. package/dist/actions/dev/registry.js.map +1 -1
  34. package/dist/actions/dev/startDevManifestWatcher.js +33 -73
  35. package/dist/actions/dev/startDevManifestWatcher.js.map +1 -1
  36. package/dist/actions/dev/startDevServerRegistration.js +11 -19
  37. package/dist/actions/dev/startDevServerRegistration.js.map +1 -1
  38. package/dist/actions/dev/startWorkbenchDevServer.js +2 -1
  39. package/dist/actions/dev/startWorkbenchDevServer.js.map +1 -1
  40. package/dist/actions/dev/watchCliConfig.js +58 -0
  41. package/dist/actions/dev/watchCliConfig.js.map +1 -0
  42. package/dist/actions/dev/watchForWorkbenchOptIn.js +51 -0
  43. package/dist/actions/dev/watchForWorkbenchOptIn.js.map +1 -0
  44. package/dist/actions/preview/startWorkbenchPreview.js +3 -4
  45. package/dist/actions/preview/startWorkbenchPreview.js.map +1 -1
  46. package/dist/defineService.js +4 -1
  47. package/dist/defineService.js.map +1 -1
  48. package/package.json +8 -4
@@ -1,13 +1,7 @@
1
- import { watch } from 'node:fs';
2
1
  import { basename, dirname } from 'node:path';
3
2
  import { findProjectRoot, subdebug } from '@sanity/cli-core';
4
- import { canonicalizeWatchDir } from './canonicalizeWatchDir.js';
3
+ import { watchCliConfig } from './watchCliConfig.js';
5
4
  const devDebug = subdebug('dev');
6
- /**
7
- * Debounce window between config file events and the next manifest
8
- * regeneration. Coalesces rapid saves (e.g. editor auto-save) and
9
- * atomic-rename bursts emitted by tools like VS Code.
10
- */ const DEBOUNCE_MS = 250;
11
5
  /**
12
6
  * Generate the project manifest once and then keep it in sync with the
13
7
  * project's config file (`sanity.config.(ts|js)` for studios,
@@ -24,79 +18,45 @@ const devDebug = subdebug('dev');
24
18
  */ export async function startDevManifestWatcher({ extract, extraWatchFilenames, output, update, workDir }) {
25
19
  const projectRoot = await findProjectRoot(workDir);
26
20
  const configPath = projectRoot.path;
27
- let running = false;
28
- let pending = false;
29
21
  let closed = false;
30
- const regenerate = async ()=>{
31
- if (closed) return;
32
- if (running) {
33
- pending = true;
34
- return;
35
- }
36
- running = true;
37
- try {
38
- const { configs, interfaces, manifest } = await extract({
39
- configPath,
40
- workDir
41
- });
42
- if (closed) return;
43
- await update({
44
- configs,
45
- interfaces,
46
- manifest,
47
- manifestUpdatedAt: new Date().toISOString()
48
- });
49
- } catch (err) {
50
- // Extractors print their own spinner failure; log the reason here so
51
- // the user sees what went wrong alongside the spinner indicator.
52
- devDebug('Manifest regeneration failed: %O', err);
53
- output.warn(`Could not extract manifest for the Dashboard: ${err instanceof Error ? err.message : String(err)}`);
54
- } finally{
55
- running = false;
56
- if (pending && !closed) {
57
- pending = false;
58
- void regenerate();
22
+ const watcher = watchCliConfig({
23
+ dir: dirname(configPath),
24
+ filenames: [
25
+ basename(configPath),
26
+ ...extraWatchFilenames ?? []
27
+ ],
28
+ onChange: async ()=>{
29
+ try {
30
+ const { configs, interfaces, manifest } = await extract({
31
+ configPath,
32
+ workDir
33
+ });
34
+ if (closed) return;
35
+ await update({
36
+ configs,
37
+ interfaces,
38
+ manifest,
39
+ manifestUpdatedAt: new Date().toISOString()
40
+ });
41
+ } catch (err) {
42
+ // Extractors print their own spinner failure; log the reason here so
43
+ // the user sees what went wrong alongside the spinner indicator.
44
+ devDebug('Manifest regeneration failed: %O', err);
45
+ output.warn(`Could not extract manifest for the Dashboard: ${err instanceof Error ? err.message : String(err)}`);
59
46
  }
47
+ },
48
+ onError: (err)=>{
49
+ devDebug('Config watcher error: %O', err);
50
+ output.warn(`Manifest watcher error: ${err instanceof Error ? err.message : String(err)}`);
60
51
  }
61
- };
62
- // Route the initial extraction through `regenerate` too, so file-system
63
- // events arriving before it finishes get coalesced rather than racing it
64
- // for the shared output directory.
65
- void regenerate();
66
- // Watch the config file's parent directory and filter by filename.
67
- // Watching the file itself is unreliable across editors that perform
68
- // atomic-save (delete + rename) — the watcher loses its target once the
69
- // inode changes. Directory watches survive those transitions.
70
- // Canonicalize to the real long path so `fs.watch` doesn't abort on Windows
71
- // short-path dirs. See `canonicalizeWatchDir`.
72
- const configDir = canonicalizeWatchDir(dirname(configPath));
73
- const watchFilenames = new Set([
74
- basename(configPath),
75
- ...extraWatchFilenames ?? []
76
- ]);
77
- let debounceTimer;
78
- const onEvent = (_event, filename)=>{
79
- if (!filename) return;
80
- const name = typeof filename === 'string' ? filename : filename.toString('utf8');
81
- if (!watchFilenames.has(name)) return;
82
- clearTimeout(debounceTimer);
83
- debounceTimer = setTimeout(()=>{
84
- void regenerate();
85
- }, DEBOUNCE_MS);
86
- };
87
- const watcher = watch(configDir, onEvent);
88
- watcher.on('error', (err)=>{
89
- devDebug('Config watcher error: %O', err);
90
- output.warn(`Manifest watcher error: ${err instanceof Error ? err.message : String(err)}`);
91
52
  });
53
+ // Route the initial extraction through the watcher too, so file-system events
54
+ // arriving before it finishes get coalesced rather than racing it for the
55
+ // shared output directory.
56
+ watcher.run();
92
57
  return {
93
- // Idempotent — a repeat close (e.g. a signal handler racing an explicit
94
- // close) is a no-op, so we never clear an already-cleared timer or
95
- // double-close the underlying watcher.
96
58
  close: async ()=>{
97
- if (closed) return;
98
59
  closed = true;
99
- clearTimeout(debounceTimer);
100
60
  watcher.close();
101
61
  }
102
62
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/actions/dev/startDevManifestWatcher.ts"],"sourcesContent":["import {watch} from 'node:fs'\nimport {basename, dirname} from 'node:path'\n\nimport {findProjectRoot, type Output, subdebug} from '@sanity/cli-core'\n\nimport {canonicalizeWatchDir} from './canonicalizeWatchDir.js'\nimport {type DevServerConfig, type DevServerInterface} from './deriveConfigs.js'\n\nconst devDebug = subdebug('dev')\n\n/**\n * Debounce window between config file events and the next manifest\n * regeneration. Coalesces rapid saves (e.g. editor auto-save) and\n * atomic-rename bursts emitted by tools like VS Code.\n */\nconst DEBOUNCE_MS = 250\n\ninterface DevManifestWatcher {\n close: () => Promise<void>\n}\n\n/** Subset of registry fields the watcher is allowed to update. */\ninterface ManifestPatch<T> {\n manifest: T | undefined\n manifestUpdatedAt: string\n\n /** Same re-derive-don't-omit contract as `interfaces`. */\n configs?: DevServerConfig[] | undefined\n /**\n * Workbench interfaces (views/web workers/app view) re-derived from the config\n * on each change, so editing `views`/`webWorkers`/`entry` in `sanity.cli.ts`\n * re-syncs live like `title`/`icon`. `undefined` only for\n * non-branded configs — the registry patch is a shallow merge, so extractors\n * must re-derive rather than omit, or the registered set gets wiped.\n */\n interfaces?: DevServerInterface[] | undefined\n}\n\ninterface StartDevManifestWatcherOptions<T> {\n /**\n * Run the project-specific extraction and resolve to the manifest patch, which\n * the watcher stamps with `manifestUpdatedAt` before forwarding. Receives the\n * resolved config path (`sanity.config.ts` for studios, `sanity.cli.ts` for\n * core-apps) and the working directory.\n */\n extract: (params: {\n configPath: string\n workDir: string\n }) => Promise<Omit<ManifestPatch<T>, 'manifestUpdatedAt'>>\n output: Output\n /**\n * Called after every successful extraction with the inlined manifest +\n * interfaces. Awaited, so an interface-set change can rebuild the federation\n * remote before the registry is patched (which is what reloads the workbench).\n */\n update: (patch: ManifestPatch<T>) => Promise<void> | void\n workDir: string\n\n /**\n * Extra config filenames (basenames in the project root directory) that also\n * trigger a regeneration. Studios resolve their project root via\n * `sanity.config.*` but declare workbench interfaces in `sanity.cli.*`, so\n * their watcher needs to react to both files.\n */\n extraWatchFilenames?: readonly string[]\n}\n\n/**\n * Generate the project manifest once and then keep it in sync with the\n * project's config file (`sanity.config.(ts|js)` for studios,\n * `sanity.cli.(ts|js)` for core-apps) on disk. The initial generation runs\n * fire-and-forget so it doesn't block dev-server startup; subsequent\n * file-system events are coalesced behind it, so the extractor never has\n * overlapping writes to its shared output directory. Each successful\n * regeneration inlines the new manifest into the registry via the `update`\n * callback, so any running workbench rebroadcasts to its clients.\n *\n * Errors during extraction are logged as warnings and do not crash the dev\n * server — the previously extracted manifest (if any) stays in the\n * registry.\n */\nexport async function startDevManifestWatcher<T>({\n extract,\n extraWatchFilenames,\n output,\n update,\n workDir,\n}: StartDevManifestWatcherOptions<T>): Promise<DevManifestWatcher> {\n const projectRoot = await findProjectRoot(workDir)\n const configPath = projectRoot.path\n\n let running = false\n let pending = false\n let closed = false\n\n const regenerate = async () => {\n if (closed) return\n if (running) {\n pending = true\n return\n }\n running = true\n try {\n const {configs, interfaces, manifest} = await extract({configPath, workDir})\n if (closed) return\n await update({\n configs,\n interfaces,\n manifest,\n manifestUpdatedAt: new Date().toISOString(),\n })\n } catch (err) {\n // Extractors print their own spinner failure; log the reason here so\n // the user sees what went wrong alongside the spinner indicator.\n devDebug('Manifest regeneration failed: %O', err)\n output.warn(\n `Could not extract manifest for the Dashboard: ${err instanceof Error ? err.message : String(err)}`,\n )\n } finally {\n running = false\n if (pending && !closed) {\n pending = false\n void regenerate()\n }\n }\n }\n\n // Route the initial extraction through `regenerate` too, so file-system\n // events arriving before it finishes get coalesced rather than racing it\n // for the shared output directory.\n void regenerate()\n\n // Watch the config file's parent directory and filter by filename.\n // Watching the file itself is unreliable across editors that perform\n // atomic-save (delete + rename) — the watcher loses its target once the\n // inode changes. Directory watches survive those transitions.\n // Canonicalize to the real long path so `fs.watch` doesn't abort on Windows\n // short-path dirs. See `canonicalizeWatchDir`.\n const configDir = canonicalizeWatchDir(dirname(configPath))\n const watchFilenames = new Set([basename(configPath), ...(extraWatchFilenames ?? [])])\n\n let debounceTimer: ReturnType<typeof setTimeout> | undefined\n\n const onEvent = (_event: string, filename: Buffer | string | null) => {\n if (!filename) return\n const name = typeof filename === 'string' ? filename : filename.toString('utf8')\n if (!watchFilenames.has(name)) return\n clearTimeout(debounceTimer)\n debounceTimer = setTimeout(() => {\n void regenerate()\n }, DEBOUNCE_MS)\n }\n\n const watcher = watch(configDir, onEvent)\n\n watcher.on('error', (err) => {\n devDebug('Config watcher error: %O', err)\n output.warn(`Manifest watcher error: ${err instanceof Error ? err.message : String(err)}`)\n })\n\n return {\n // Idempotent — a repeat close (e.g. a signal handler racing an explicit\n // close) is a no-op, so we never clear an already-cleared timer or\n // double-close the underlying watcher.\n close: async () => {\n if (closed) return\n closed = true\n clearTimeout(debounceTimer)\n watcher.close()\n },\n }\n}\n"],"names":["watch","basename","dirname","findProjectRoot","subdebug","canonicalizeWatchDir","devDebug","DEBOUNCE_MS","startDevManifestWatcher","extract","extraWatchFilenames","output","update","workDir","projectRoot","configPath","path","running","pending","closed","regenerate","configs","interfaces","manifest","manifestUpdatedAt","Date","toISOString","err","warn","Error","message","String","configDir","watchFilenames","Set","debounceTimer","onEvent","_event","filename","name","toString","has","clearTimeout","setTimeout","watcher","on","close"],"mappings":"AAAA,SAAQA,KAAK,QAAO,UAAS;AAC7B,SAAQC,QAAQ,EAAEC,OAAO,QAAO,YAAW;AAE3C,SAAQC,eAAe,EAAeC,QAAQ,QAAO,mBAAkB;AAEvE,SAAQC,oBAAoB,QAAO,4BAA2B;AAG9D,MAAMC,WAAWF,SAAS;AAE1B;;;;CAIC,GACD,MAAMG,cAAc;AAoDpB;;;;;;;;;;;;;CAaC,GACD,OAAO,eAAeC,wBAA2B,EAC/CC,OAAO,EACPC,mBAAmB,EACnBC,MAAM,EACNC,MAAM,EACNC,OAAO,EAC2B;IAClC,MAAMC,cAAc,MAAMX,gBAAgBU;IAC1C,MAAME,aAAaD,YAAYE,IAAI;IAEnC,IAAIC,UAAU;IACd,IAAIC,UAAU;IACd,IAAIC,SAAS;IAEb,MAAMC,aAAa;QACjB,IAAID,QAAQ;QACZ,IAAIF,SAAS;YACXC,UAAU;YACV;QACF;QACAD,UAAU;QACV,IAAI;YACF,MAAM,EAACI,OAAO,EAAEC,UAAU,EAAEC,QAAQ,EAAC,GAAG,MAAMd,QAAQ;gBAACM;gBAAYF;YAAO;YAC1E,IAAIM,QAAQ;YACZ,MAAMP,OAAO;gBACXS;gBACAC;gBACAC;gBACAC,mBAAmB,IAAIC,OAAOC,WAAW;YAC3C;QACF,EAAE,OAAOC,KAAK;YACZ,qEAAqE;YACrE,iEAAiE;YACjErB,SAAS,oCAAoCqB;YAC7ChB,OAAOiB,IAAI,CACT,CAAC,8CAA8C,EAAED,eAAeE,QAAQF,IAAIG,OAAO,GAAGC,OAAOJ,MAAM;QAEvG,SAAU;YACRV,UAAU;YACV,IAAIC,WAAW,CAACC,QAAQ;gBACtBD,UAAU;gBACV,KAAKE;YACP;QACF;IACF;IAEA,wEAAwE;IACxE,yEAAyE;IACzE,mCAAmC;IACnC,KAAKA;IAEL,mEAAmE;IACnE,qEAAqE;IACrE,wEAAwE;IACxE,8DAA8D;IAC9D,4EAA4E;IAC5E,+CAA+C;IAC/C,MAAMY,YAAY3B,qBAAqBH,QAAQa;IAC/C,MAAMkB,iBAAiB,IAAIC,IAAI;QAACjC,SAASc;WAAiBL,uBAAuB,EAAE;KAAE;IAErF,IAAIyB;IAEJ,MAAMC,UAAU,CAACC,QAAgBC;QAC/B,IAAI,CAACA,UAAU;QACf,MAAMC,OAAO,OAAOD,aAAa,WAAWA,WAAWA,SAASE,QAAQ,CAAC;QACzE,IAAI,CAACP,eAAeQ,GAAG,CAACF,OAAO;QAC/BG,aAAaP;QACbA,gBAAgBQ,WAAW;YACzB,KAAKvB;QACP,GAAGb;IACL;IAEA,MAAMqC,UAAU5C,MAAMgC,WAAWI;IAEjCQ,QAAQC,EAAE,CAAC,SAAS,CAAClB;QACnBrB,SAAS,4BAA4BqB;QACrChB,OAAOiB,IAAI,CAAC,CAAC,wBAAwB,EAAED,eAAeE,QAAQF,IAAIG,OAAO,GAAGC,OAAOJ,MAAM;IAC3F;IAEA,OAAO;QACL,wEAAwE;QACxE,mEAAmE;QACnE,uCAAuC;QACvCmB,OAAO;YACL,IAAI3B,QAAQ;YACZA,SAAS;YACTuB,aAAaP;YACbS,QAAQE,KAAK;QACf;IACF;AACF"}
1
+ {"version":3,"sources":["../../../src/actions/dev/startDevManifestWatcher.ts"],"sourcesContent":["import {basename, dirname} from 'node:path'\n\nimport {findProjectRoot, type Output, subdebug} from '@sanity/cli-core'\n\nimport {type DevServerConfig, type DevServerInterface} from './deriveConfigs.js'\nimport {watchCliConfig} from './watchCliConfig.js'\n\nconst devDebug = subdebug('dev')\n\ninterface DevManifestWatcher {\n close: () => Promise<void>\n}\n\n/** Subset of registry fields the watcher is allowed to update. */\ninterface ManifestPatch<T> {\n manifest: T | undefined\n manifestUpdatedAt: string\n\n /** Same re-derive-don't-omit contract as `interfaces`. */\n configs?: DevServerConfig[] | undefined\n /**\n * Workbench interfaces (views/web workers/app view) re-derived from the config\n * on each change, so editing `views`/`webWorkers`/`entry` in `sanity.cli.ts`\n * re-syncs live like `title`/`icon`. `undefined` only for\n * non-branded configs — the registry patch is a shallow merge, so extractors\n * must re-derive rather than omit, or the registered set gets wiped.\n */\n interfaces?: DevServerInterface[] | undefined\n}\n\ninterface StartDevManifestWatcherOptions<T> {\n /**\n * Run the project-specific extraction and resolve to the manifest patch, which\n * the watcher stamps with `manifestUpdatedAt` before forwarding. Receives the\n * resolved config path (`sanity.config.ts` for studios, `sanity.cli.ts` for\n * core-apps) and the working directory.\n */\n extract: (params: {\n configPath: string\n workDir: string\n }) => Promise<Omit<ManifestPatch<T>, 'manifestUpdatedAt'>>\n output: Output\n /**\n * Called after every successful extraction with the inlined manifest +\n * interfaces. Awaited, so an interface-set change can rebuild the federation\n * remote before the registry is patched (which is what reloads the workbench).\n */\n update: (patch: ManifestPatch<T>) => Promise<void> | void\n workDir: string\n\n /**\n * Extra config filenames (basenames in the project root directory) that also\n * trigger a regeneration. Studios resolve their project root via\n * `sanity.config.*` but declare workbench interfaces in `sanity.cli.*`, so\n * their watcher needs to react to both files.\n */\n extraWatchFilenames?: readonly string[]\n}\n\n/**\n * Generate the project manifest once and then keep it in sync with the\n * project's config file (`sanity.config.(ts|js)` for studios,\n * `sanity.cli.(ts|js)` for core-apps) on disk. The initial generation runs\n * fire-and-forget so it doesn't block dev-server startup; subsequent\n * file-system events are coalesced behind it, so the extractor never has\n * overlapping writes to its shared output directory. Each successful\n * regeneration inlines the new manifest into the registry via the `update`\n * callback, so any running workbench rebroadcasts to its clients.\n *\n * Errors during extraction are logged as warnings and do not crash the dev\n * server — the previously extracted manifest (if any) stays in the\n * registry.\n */\nexport async function startDevManifestWatcher<T>({\n extract,\n extraWatchFilenames,\n output,\n update,\n workDir,\n}: StartDevManifestWatcherOptions<T>): Promise<DevManifestWatcher> {\n const projectRoot = await findProjectRoot(workDir)\n const configPath = projectRoot.path\n\n let closed = false\n\n const watcher = watchCliConfig({\n dir: dirname(configPath),\n filenames: [basename(configPath), ...(extraWatchFilenames ?? [])],\n onChange: async () => {\n try {\n const {configs, interfaces, manifest} = await extract({configPath, workDir})\n if (closed) return\n await update({\n configs,\n interfaces,\n manifest,\n manifestUpdatedAt: new Date().toISOString(),\n })\n } catch (err) {\n // Extractors print their own spinner failure; log the reason here so\n // the user sees what went wrong alongside the spinner indicator.\n devDebug('Manifest regeneration failed: %O', err)\n output.warn(\n `Could not extract manifest for the Dashboard: ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n },\n onError: (err) => {\n devDebug('Config watcher error: %O', err)\n output.warn(`Manifest watcher error: ${err instanceof Error ? err.message : String(err)}`)\n },\n })\n\n // Route the initial extraction through the watcher too, so file-system events\n // arriving before it finishes get coalesced rather than racing it for the\n // shared output directory.\n watcher.run()\n\n return {\n close: async () => {\n closed = true\n watcher.close()\n },\n }\n}\n"],"names":["basename","dirname","findProjectRoot","subdebug","watchCliConfig","devDebug","startDevManifestWatcher","extract","extraWatchFilenames","output","update","workDir","projectRoot","configPath","path","closed","watcher","dir","filenames","onChange","configs","interfaces","manifest","manifestUpdatedAt","Date","toISOString","err","warn","Error","message","String","onError","run","close"],"mappings":"AAAA,SAAQA,QAAQ,EAAEC,OAAO,QAAO,YAAW;AAE3C,SAAQC,eAAe,EAAeC,QAAQ,QAAO,mBAAkB;AAGvE,SAAQC,cAAc,QAAO,sBAAqB;AAElD,MAAMC,WAAWF,SAAS;AAoD1B;;;;;;;;;;;;;CAaC,GACD,OAAO,eAAeG,wBAA2B,EAC/CC,OAAO,EACPC,mBAAmB,EACnBC,MAAM,EACNC,MAAM,EACNC,OAAO,EAC2B;IAClC,MAAMC,cAAc,MAAMV,gBAAgBS;IAC1C,MAAME,aAAaD,YAAYE,IAAI;IAEnC,IAAIC,SAAS;IAEb,MAAMC,UAAUZ,eAAe;QAC7Ba,KAAKhB,QAAQY;QACbK,WAAW;YAAClB,SAASa;eAAiBL,uBAAuB,EAAE;SAAE;QACjEW,UAAU;YACR,IAAI;gBACF,MAAM,EAACC,OAAO,EAAEC,UAAU,EAAEC,QAAQ,EAAC,GAAG,MAAMf,QAAQ;oBAACM;oBAAYF;gBAAO;gBAC1E,IAAII,QAAQ;gBACZ,MAAML,OAAO;oBACXU;oBACAC;oBACAC;oBACAC,mBAAmB,IAAIC,OAAOC,WAAW;gBAC3C;YACF,EAAE,OAAOC,KAAK;gBACZ,qEAAqE;gBACrE,iEAAiE;gBACjErB,SAAS,oCAAoCqB;gBAC7CjB,OAAOkB,IAAI,CACT,CAAC,8CAA8C,EAAED,eAAeE,QAAQF,IAAIG,OAAO,GAAGC,OAAOJ,MAAM;YAEvG;QACF;QACAK,SAAS,CAACL;YACRrB,SAAS,4BAA4BqB;YACrCjB,OAAOkB,IAAI,CAAC,CAAC,wBAAwB,EAAED,eAAeE,QAAQF,IAAIG,OAAO,GAAGC,OAAOJ,MAAM;QAC3F;IACF;IAEA,8EAA8E;IAC9E,0EAA0E;IAC1E,2BAA2B;IAC3BV,QAAQgB,GAAG;IAEX,OAAO;QACLC,OAAO;YACLlB,SAAS;YACTC,QAAQiB,KAAK;QACf;IACF;AACF"}
@@ -1,12 +1,11 @@
1
1
  import { getCliConfigUncached } from '@sanity/cli-core';
2
- import { applicationReference } from '../../applicationReference.js';
3
2
  import { isWorkbenchApp, isWorkbenchConfig } from '../../defineApp.js';
4
3
  import { deriveInterfaces } from '../../deriveInterfaces.js';
5
4
  import { resolveWorkbenchConfig } from '../../resolveWorkbenchConfig.js';
6
5
  import { formatWorkbenchAppErrors, validateWorkbenchApp } from '../../validateWorkbenchApp.js';
7
6
  import { deriveConfigs } from './deriveConfigs.js';
8
7
  import { trackExposesSet } from './exposesSetId.js';
9
- import { dashboardPath, getRegisteredServers, registerDevServer } from './registry.js';
8
+ import { dashboardPath, getRegisteredServers, localAppIdentity, registerDevServer } from './registry.js';
10
9
  import { startDevManifestWatcher } from './startDevManifestWatcher.js';
11
10
  /**
12
11
  * Log any app validation errors without aborting. Unlike build and deploy, dev
@@ -46,22 +45,17 @@ import { startDevManifestWatcher } from './startDevManifestWatcher.js';
46
45
  // A config runs alongside the app it configures, so give it its own id
47
46
  // namespace — sharing the app's slug would make the two indistinguishable here.
48
47
  const id = config ? `config:${config.appType}` : workbenchApp?.slug;
48
+ const applicationId = workbenchApp ? cliConfig.deployment?.appId : undefined;
49
49
  // Identity is resolved and the reference composed here, so the workbench reads
50
- // both off the registry entry instead of recomposing them. Name defaults to the
51
- // slug, mirroring brett.
52
- const name = workbenchApp?.name ?? workbenchApp?.slug;
53
- const reference = workbenchApp && name ? // is a config, not an app — so its reference is always `<org>/<name>`.
54
- applicationReference({
55
- isSingleton: false,
56
- name,
57
- organizationId: workbenchApp.organizationId
58
- }) : undefined;
59
- // Separate namespaces mean a shared id is a genuine duplicate, so the gate is
60
- // an id match within the org — no config-vs-app role left to reconcile.
50
+ // both off the registry entry instead of recomposing them.
51
+ const identity = workbenchApp ? localAppIdentity(workbenchApp) : undefined;
52
+ // The Dashboard tells local apps apart by their bus id and by the application
53
+ // they stand in for.
61
54
  const organizationId = cliConfig.app?.organizationId;
62
- const devServer = id ? getRegisteredServers().find((server)=>server.id === id && server.organizationId === organizationId) : undefined;
55
+ const devServer = getRegisteredServers().find((server)=>server.organizationId === organizationId && (server.id === id || applicationId && server.applicationId === applicationId));
63
56
  if (id && devServer) {
64
- output.error(`"${id}" is already served by another dev server running on port ${devServer.port}, ` + "so the Dashboard can't tell them apart and this one stays out of it. Stop that server first.", {
57
+ const served = devServer.id === id ? `"${id}" is already served` : `"${id}" is the same application as "${devServer.id}", served`;
58
+ output.error(`${served} by another dev server running on port ${devServer.port}, ` + "so the Dashboard can't tell them apart and this one stays out of it. Stop that server first.", {
65
59
  exit: false
66
60
  });
67
61
  return {
@@ -69,18 +63,16 @@ import { startDevManifestWatcher } from './startDevManifestWatcher.js';
69
63
  };
70
64
  }
71
65
  const registration = registerDevServer({
66
+ applicationId,
72
67
  configs,
73
68
  host: appHost,
74
69
  id,
75
70
  interfaces,
76
- name,
77
71
  organizationId,
78
72
  port: appPort,
79
73
  projectId: cliConfig?.api?.projectId,
80
- reference,
81
- slug: workbenchApp?.slug,
74
+ ...identity,
82
75
  type: isApp ? 'coreApp' : 'studio',
83
- visibility: workbenchApp ? workbenchApp.visibility ?? 'default' : undefined,
84
76
  workDir
85
77
  });
86
78
  const exposesSet = trackExposesSet({
@@ -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 {applicationReference} from '../../applicationReference.js'\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 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 // Identity is resolved and the reference composed here, so the workbench reads\n // both off the registry entry instead of recomposing them. Name defaults to the\n // slug, mirroring brett.\n const name = workbenchApp?.name ?? workbenchApp?.slug\n const reference =\n workbenchApp && name\n ? // No workbench app is a singleton now that the only one (the Media Library)\n // is a config, not an app — so its reference is always `<org>/<name>`.\n applicationReference({\n isSingleton: false,\n name,\n organizationId: workbenchApp.organizationId,\n })\n : undefined\n\n // Separate namespaces mean a shared id is a genuine duplicate, so the gate is\n // an id match within the org — no config-vs-app role left to reconcile.\n const organizationId = cliConfig.app?.organizationId\n const devServer = id\n ? getRegisteredServers().find(\n (server) => server.id === id && server.organizationId === organizationId,\n )\n : undefined\n\n if (id && devServer) {\n output.error(\n `\"${id}\" is already 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 configs,\n host: appHost,\n id,\n interfaces,\n name,\n organizationId,\n port: appPort,\n projectId: cliConfig?.api?.projectId,\n reference,\n slug: workbenchApp?.slug,\n type: isApp ? 'coreApp' : 'studio',\n visibility: workbenchApp ? (workbenchApp.visibility ?? 'default') : undefined,\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({id, interfaces}),\n }\n}\n"],"names":["getCliConfigUncached","applicationReference","isWorkbenchApp","isWorkbenchConfig","deriveInterfaces","resolveWorkbenchConfig","formatWorkbenchAppErrors","validateWorkbenchApp","deriveConfigs","trackExposesSet","dashboardPath","getRegisteredServers","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","name","reference","isSingleton","organizationId","devServer","find","error","exit","close","registration","projectId","api","type","visibility","exposesSet","watcher","extract","params","nextConfig","manifest","applicationId","extraWatchFilenames","update","patch","changed","rebuiltServer","commit","release","path"],"mappings":"AAAA,SAAwBA,oBAAoB,QAAoB,mBAAkB;AAGlF,SAAQC,oBAAoB,QAAO,gCAA+B;AAClE,SAAQC,cAAc,EAAEC,iBAAiB,QAAO,qBAAoB;AACpE,SAAQC,gBAAgB,QAAO,4BAA2B;AAC1D,SAAQC,sBAAsB,QAAO,kCAAiC;AAC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OAAO;gBACLuB,SAAS,MAAM/B,cAAcuD;gBAC7BzB,YAAYlC,iBAAiB2D,WAAWhD,GAAG,EAAE;oBAACkB;gBAAK;gBACnD+B,UAAU,MAAMhC,gBAAgB;oBAAC,GAAG8B,MAAM;oBAAEG,eAAevB;gBAAE;YAC/D;QACF;QACA,2EAA2E;QAC3E,wEAAwE;QACxEwB,qBAAqBjC,QAAQQ,YAAY;YAAC;YAAiB;SAAgB;QAC3EzB;QACAmD,QAAQ,OAAOC;YACb,IACE,CAACT,WAAWU,OAAO,CAAC;gBAClB9B,SAAS6B,MAAM7B,OAAO;gBACtBD,YAAY8B,MAAM9B,UAAU;YAC9B,IACA;gBACAgB,aAAaa,MAAM,CAACC;gBACpB;YACF;YACA,4EAA4E;YAC5E,6EAA6E;YAC7E,MAAME,gBAAgB,MAAMpC;YAC5B,6EAA6E;YAC7EyB,WAAWY,MAAM,CAAC;gBAChBhC,SAAS6B,MAAM7B,OAAO;gBACtBD,YAAY8B,MAAM9B,UAAU;YAC9B;YACA,qEAAqE;YACrEgB,aAAaa,MAAM,CAACG,gBAAgB;gBAAC,GAAGF,KAAK;gBAAE,GAAGhD,cAAckD,cAAc;YAAA,IAAIF;QACpF;QACAjC;IACF;IAEA,OAAO;QACLkB,OAAO;YACLC,aAAakB,OAAO;YACpB,MAAMZ,QAAQP,KAAK;QACrB;QACAoB,MAAM/D,cAAc;YAACgC;YAAIJ;QAAU;IACrC;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 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({id, interfaces}),\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,SA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B,aAAapD,gBAAgB;QAAC+B;QAASD;IAAU;IAEvD,MAAMuB,UAAU,MAAMhD,wBAAwB;QAC5C,4EAA4E;QAC5E,6CAA6C;QAC7CiD,SAAS,OAAOC;YACd,MAAMC,aAAa,MAAMhE,qBAAqB+D,OAAO5B,OAAO;YAC5DrB,mBAAmBkD,WAAWjD,GAAG,EAAEC;YACnC,OAAO;gBACLuB,SAAS,MAAMhC,cAAcyD;gBAC7B1B,YAAYnC,iBAAiB6D,WAAWjD,GAAG,EAAE;oBAACkB;gBAAK;gBACnDgC,UAAU,MAAMjC,gBAAgB;oBAAC,GAAG+B,MAAM;oBAAElB,eAAeH;gBAAE;YAC/D;QACF;QACA,2EAA2E;QAC3E,wEAAwE;QACxEwB,qBAAqBjC,QAAQQ,YAAY;YAAC;YAAiB;SAAgB;QAC3EzB;QACAmD,QAAQ,OAAOC;YACb,IACE,CAACR,WAAWS,OAAO,CAAC;gBAClB9B,SAAS6B,MAAM7B,OAAO;gBACtBD,YAAY8B,MAAM9B,UAAU;YAC9B,IACA;gBACAkB,aAAaW,MAAM,CAACC;gBACpB;YACF;YACA,4EAA4E;YAC5E,6EAA6E;YAC7E,MAAME,gBAAgB,MAAMpC;YAC5B,6EAA6E;YAC7E0B,WAAWW,MAAM,CAAC;gBAChBhC,SAAS6B,MAAM7B,OAAO;gBACtBD,YAAY8B,MAAM9B,UAAU;YAC9B;YACA,qEAAqE;YACrEkB,aAAaW,MAAM,CAACG,gBAAgB;gBAAC,GAAGF,KAAK;gBAAE,GAAGhD,cAAckD,cAAc;YAAA,IAAIF;QACpF;QACAjC;IACF;IAEA,OAAO;QACLoB,OAAO;YACLC,aAAagB,OAAO;YACpB,MAAMX,QAAQN,KAAK;QACrB;QACAkB,MAAMhE,cAAc;YAACiC;YAAIJ;QAAU;IACrC;AACF"}
@@ -16,7 +16,8 @@ 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(({ host, id, interfaces, manifest, name, organizationId, port, projectId, reference, slug, type, visibility })=>({
19
+ applications: servers.filter((server)=>!isConfigOnlyServer(server)).map(({ applicationId, host, id, interfaces, manifest, name, organizationId, port, projectId, reference, slug, type, visibility })=>({
20
+ applicationId,
20
21
  host,
21
22
  id,
22
23
  // Views cross to the remote keyed on `type`, never the internal `surface`.
@@ -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 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 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","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":"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;YACF;QACF;QACA1G,MAAM;IACR;AACF"}
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,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,QAA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,OAAO;YACLG;YACA,MAAMtC,OAAOmC,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,kBAAkBzH,EAAEe,GAAG,CAAC;IAAC2G,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,iBAAgB5G,MAAM;YACpBA,OAAO6G,WAAW,CAACC,GAAG,CAAC,CAACC,KAAKC,KAAKC;gBAChC,MAAMC,WAAW,AAACH,CAAAA,IAAIrH,GAAG,IAAI,GAAE,EAAGyH,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,58 @@
1
+ import { watch } from 'node:fs';
2
+ import { canonicalizeWatchDir } from './canonicalizeWatchDir.js';
3
+ /**
4
+ * Debounce window between config file events and the next run. Coalesces rapid
5
+ * saves (e.g. editor auto-save) and atomic-rename bursts emitted by tools like
6
+ * VS Code.
7
+ */ const DEBOUNCE_MS = 250;
8
+ /**
9
+ * Run `onChange` after edits to config files, debounced and never overlapping: a
10
+ * change that lands mid-run queues exactly one more run once it settles.
11
+ *
12
+ * Watches the parent directory and filters by filename, because a watch on the
13
+ * file itself loses its target when an editor atomic-saves (delete + rename).
14
+ */ export function watchCliConfig({ dir, filenames, onChange, onError }) {
15
+ const watchFilenames = new Set(filenames);
16
+ let running = false;
17
+ let pending = false;
18
+ let closed = false;
19
+ let debounceTimer;
20
+ let changedFilename;
21
+ const run = async ()=>{
22
+ if (closed) return;
23
+ if (running) {
24
+ pending = true;
25
+ return;
26
+ }
27
+ running = true;
28
+ try {
29
+ await onChange(changedFilename);
30
+ } catch (err) {
31
+ onError(err);
32
+ } finally{
33
+ running = false;
34
+ if (pending && !closed) {
35
+ pending = false;
36
+ void run();
37
+ }
38
+ }
39
+ };
40
+ const watcher = watch(canonicalizeWatchDir(dir), (_event, filename)=>{
41
+ if (!filename || !watchFilenames.has(filename)) return;
42
+ changedFilename = filename;
43
+ clearTimeout(debounceTimer);
44
+ debounceTimer = setTimeout(()=>void run(), DEBOUNCE_MS);
45
+ });
46
+ watcher.on('error', onError);
47
+ return {
48
+ close: ()=>{
49
+ if (closed) return;
50
+ closed = true;
51
+ clearTimeout(debounceTimer);
52
+ watcher.close();
53
+ },
54
+ run: ()=>void run()
55
+ };
56
+ }
57
+
58
+ //# sourceMappingURL=watchCliConfig.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/actions/dev/watchCliConfig.ts"],"sourcesContent":["import {watch} from 'node:fs'\n\nimport {canonicalizeWatchDir} from './canonicalizeWatchDir.js'\n\n/**\n * Debounce window between config file events and the next run. Coalesces rapid\n * saves (e.g. editor auto-save) and atomic-rename bursts emitted by tools like\n * VS Code.\n */\nconst DEBOUNCE_MS = 250\n\ninterface CliConfigWatcher {\n /** Stop watching and drop any queued run. Idempotent. */\n close: () => void\n /** Run now, coalesced with config file events like any other change. */\n run: () => void\n}\n\ninterface WatchCliConfigOptions {\n dir: string\n filenames: Iterable<string>\n /** Receives the last changed filename; unset when `run()` fires before any change. */\n onChange: (filename: string | undefined) => Promise<void>\n /** Receives `fs.watch` errors and any rejection from `onChange`. */\n onError: (err: unknown) => void\n}\n\n/**\n * Run `onChange` after edits to config files, debounced and never overlapping: a\n * change that lands mid-run queues exactly one more run once it settles.\n *\n * Watches the parent directory and filters by filename, because a watch on the\n * file itself loses its target when an editor atomic-saves (delete + rename).\n */\nexport function watchCliConfig({\n dir,\n filenames,\n onChange,\n onError,\n}: WatchCliConfigOptions): CliConfigWatcher {\n const watchFilenames = new Set(filenames)\n\n let running = false\n let pending = false\n let closed = false\n let debounceTimer: ReturnType<typeof setTimeout> | undefined\n let changedFilename: string | undefined\n\n const run = async () => {\n if (closed) return\n\n if (running) {\n pending = true\n return\n }\n\n running = true\n try {\n await onChange(changedFilename)\n } catch (err) {\n onError(err)\n } finally {\n running = false\n if (pending && !closed) {\n pending = false\n void run()\n }\n }\n }\n\n const watcher = watch(canonicalizeWatchDir(dir), (_event, filename) => {\n if (!filename || !watchFilenames.has(filename)) return\n changedFilename = filename\n clearTimeout(debounceTimer)\n debounceTimer = setTimeout(() => void run(), DEBOUNCE_MS)\n })\n watcher.on('error', onError)\n\n return {\n close: () => {\n if (closed) return\n closed = true\n clearTimeout(debounceTimer)\n watcher.close()\n },\n run: () => void run(),\n }\n}\n"],"names":["watch","canonicalizeWatchDir","DEBOUNCE_MS","watchCliConfig","dir","filenames","onChange","onError","watchFilenames","Set","running","pending","closed","debounceTimer","changedFilename","run","err","watcher","_event","filename","has","clearTimeout","setTimeout","on","close"],"mappings":"AAAA,SAAQA,KAAK,QAAO,UAAS;AAE7B,SAAQC,oBAAoB,QAAO,4BAA2B;AAE9D;;;;CAIC,GACD,MAAMC,cAAc;AAkBpB;;;;;;CAMC,GACD,OAAO,SAASC,eAAe,EAC7BC,GAAG,EACHC,SAAS,EACTC,QAAQ,EACRC,OAAO,EACe;IACtB,MAAMC,iBAAiB,IAAIC,IAAIJ;IAE/B,IAAIK,UAAU;IACd,IAAIC,UAAU;IACd,IAAIC,SAAS;IACb,IAAIC;IACJ,IAAIC;IAEJ,MAAMC,MAAM;QACV,IAAIH,QAAQ;QAEZ,IAAIF,SAAS;YACXC,UAAU;YACV;QACF;QAEAD,UAAU;QACV,IAAI;YACF,MAAMJ,SAASQ;QACjB,EAAE,OAAOE,KAAK;YACZT,QAAQS;QACV,SAAU;YACRN,UAAU;YACV,IAAIC,WAAW,CAACC,QAAQ;gBACtBD,UAAU;gBACV,KAAKI;YACP;QACF;IACF;IAEA,MAAME,UAAUjB,MAAMC,qBAAqBG,MAAM,CAACc,QAAQC;QACxD,IAAI,CAACA,YAAY,CAACX,eAAeY,GAAG,CAACD,WAAW;QAChDL,kBAAkBK;QAClBE,aAAaR;QACbA,gBAAgBS,WAAW,IAAM,KAAKP,OAAOb;IAC/C;IACAe,QAAQM,EAAE,CAAC,SAAShB;IAEpB,OAAO;QACLiB,OAAO;YACL,IAAIZ,QAAQ;YACZA,SAAS;YACTS,aAAaR;YACbI,QAAQO,KAAK;QACf;QACAT,KAAK,IAAM,KAAKA;IAClB;AACF"}
@@ -0,0 +1,51 @@
1
+ import { getCliConfigUncached, subdebug } from '@sanity/cli-core';
2
+ import { isWorkbenchApp, isWorkbenchConfig } from '../../defineApp.js';
3
+ import { watchCliConfig } from './watchCliConfig.js';
4
+ const devDebug = subdebug('dev');
5
+ const noop = async ()=>{};
6
+ /**
7
+ * Hand a running plain `sanity dev` over to the workbench once `sanity.cli.*`
8
+ * opts in with `defineApplication`, so upgrading doesn't need a restart.
9
+ *
10
+ * Costs one directory watch until the handover, which then stops it. A failed
11
+ * handover leaves the watch running so the next save retries.
12
+ *
13
+ * @returns A close for whichever servers are running.
14
+ */ export function watchForWorkbenchOptIn({ closePlainServer, output, startWorkbench, workDir }) {
15
+ let closeCurrent = closePlainServer;
16
+ const watcher = watchCliConfig({
17
+ dir: workDir,
18
+ filenames: [
19
+ 'sanity.cli.js',
20
+ 'sanity.cli.ts'
21
+ ],
22
+ onChange: async (filename)=>{
23
+ // Mid-edit saves often don't load; the next save retries.
24
+ const cliConfig = await getCliConfigUncached(workDir).catch((err)=>{
25
+ devDebug('Could not load CLI config while watching for the workbench opt-in: %O', err);
26
+ });
27
+ if (!cliConfig) return;
28
+ if (!isWorkbenchApp(cliConfig.app) && !isWorkbenchConfig(cliConfig.app)) return;
29
+ output.log(`${filename} changed, restarting dev server`);
30
+ try {
31
+ await closeCurrent();
32
+ closeCurrent = noop;
33
+ const workbench = await startWorkbench(cliConfig);
34
+ closeCurrent = workbench.close;
35
+ watcher.close();
36
+ } catch (err) {
37
+ output.warn(`Failed to start dev server: ${err instanceof Error ? err.message : String(err)}`);
38
+ output.log(`No dev server is running. Save ${filename} to try again.`);
39
+ }
40
+ },
41
+ onError: (err)=>devDebug('CLI config watcher error: %O', err)
42
+ });
43
+ return {
44
+ close: async ()=>{
45
+ watcher.close();
46
+ await closeCurrent();
47
+ }
48
+ };
49
+ }
50
+
51
+ //# sourceMappingURL=watchForWorkbenchOptIn.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/actions/dev/watchForWorkbenchOptIn.ts"],"sourcesContent":["import {type CliConfig, getCliConfigUncached, type Output, subdebug} from '@sanity/cli-core'\n\nimport {isWorkbenchApp, isWorkbenchConfig} from '../../defineApp.js'\nimport {watchCliConfig} from './watchCliConfig.js'\n\nconst devDebug = subdebug('dev')\n\nconst noop = async () => {}\n\ninterface WatchForWorkbenchOptInOptions {\n /** Stop the plain dev server, freeing its port for the workbench. */\n closePlainServer: () => Promise<void>\n output: Output\n startWorkbench: (cliConfig: CliConfig) => Promise<{close: () => Promise<void>}>\n workDir: string\n}\n\n/**\n * Hand a running plain `sanity dev` over to the workbench once `sanity.cli.*`\n * opts in with `defineApplication`, so upgrading doesn't need a restart.\n *\n * Costs one directory watch until the handover, which then stops it. A failed\n * handover leaves the watch running so the next save retries.\n *\n * @returns A close for whichever servers are running.\n */\nexport function watchForWorkbenchOptIn({\n closePlainServer,\n output,\n startWorkbench,\n workDir,\n}: WatchForWorkbenchOptInOptions): {close: () => Promise<void>} {\n let closeCurrent = closePlainServer\n\n const watcher = watchCliConfig({\n dir: workDir,\n filenames: ['sanity.cli.js', 'sanity.cli.ts'],\n onChange: async (filename) => {\n // Mid-edit saves often don't load; the next save retries.\n const cliConfig = await getCliConfigUncached(workDir).catch((err) => {\n devDebug('Could not load CLI config while watching for the workbench opt-in: %O', err)\n })\n if (!cliConfig) return\n if (!isWorkbenchApp(cliConfig.app) && !isWorkbenchConfig(cliConfig.app)) return\n\n output.log(`${filename} changed, restarting dev server`)\n\n try {\n await closeCurrent()\n closeCurrent = noop\n const workbench = await startWorkbench(cliConfig)\n closeCurrent = workbench.close\n watcher.close()\n } catch (err) {\n output.warn(\n `Failed to start dev server: ${err instanceof Error ? err.message : String(err)}`,\n )\n output.log(`No dev server is running. Save ${filename} to try again.`)\n }\n },\n onError: (err) => devDebug('CLI config watcher error: %O', err),\n })\n\n return {\n close: async () => {\n watcher.close()\n await closeCurrent()\n },\n }\n}\n"],"names":["getCliConfigUncached","subdebug","isWorkbenchApp","isWorkbenchConfig","watchCliConfig","devDebug","noop","watchForWorkbenchOptIn","closePlainServer","output","startWorkbench","workDir","closeCurrent","watcher","dir","filenames","onChange","filename","cliConfig","catch","err","app","log","workbench","close","warn","Error","message","String","onError"],"mappings":"AAAA,SAAwBA,oBAAoB,EAAeC,QAAQ,QAAO,mBAAkB;AAE5F,SAAQC,cAAc,EAAEC,iBAAiB,QAAO,qBAAoB;AACpE,SAAQC,cAAc,QAAO,sBAAqB;AAElD,MAAMC,WAAWJ,SAAS;AAE1B,MAAMK,OAAO,WAAa;AAU1B;;;;;;;;CAQC,GACD,OAAO,SAASC,uBAAuB,EACrCC,gBAAgB,EAChBC,MAAM,EACNC,cAAc,EACdC,OAAO,EACuB;IAC9B,IAAIC,eAAeJ;IAEnB,MAAMK,UAAUT,eAAe;QAC7BU,KAAKH;QACLI,WAAW;YAAC;YAAiB;SAAgB;QAC7CC,UAAU,OAAOC;YACf,0DAA0D;YAC1D,MAAMC,YAAY,MAAMlB,qBAAqBW,SAASQ,KAAK,CAAC,CAACC;gBAC3Df,SAAS,yEAAyEe;YACpF;YACA,IAAI,CAACF,WAAW;YAChB,IAAI,CAAChB,eAAegB,UAAUG,GAAG,KAAK,CAAClB,kBAAkBe,UAAUG,GAAG,GAAG;YAEzEZ,OAAOa,GAAG,CAAC,GAAGL,SAAS,+BAA+B,CAAC;YAEvD,IAAI;gBACF,MAAML;gBACNA,eAAeN;gBACf,MAAMiB,YAAY,MAAMb,eAAeQ;gBACvCN,eAAeW,UAAUC,KAAK;gBAC9BX,QAAQW,KAAK;YACf,EAAE,OAAOJ,KAAK;gBACZX,OAAOgB,IAAI,CACT,CAAC,4BAA4B,EAAEL,eAAeM,QAAQN,IAAIO,OAAO,GAAGC,OAAOR,MAAM;gBAEnFX,OAAOa,GAAG,CAAC,CAAC,+BAA+B,EAAEL,SAAS,cAAc,CAAC;YACvE;QACF;QACAY,SAAS,CAACT,MAAQf,SAAS,gCAAgCe;IAC7D;IAEA,OAAO;QACLI,OAAO;YACLX,QAAQW,KAAK;YACb,MAAMZ;QACR;IACF;AACF"}
@@ -7,7 +7,7 @@ import { deriveInterfaces } from '../../deriveInterfaces.js';
7
7
  import { resolveWorkbenchApp } from '../../resolveWorkbenchApp.js';
8
8
  import { createServerLifecycle, toDisplayHost } from '../../util/serverOrchestration.js';
9
9
  import { deriveConfigs } from '../dev/deriveConfigs.js';
10
- import { dashboardPath, registerDevServer } from '../dev/registry.js';
10
+ import { dashboardPath, localAppIdentity, registerDevServer } from '../dev/registry.js';
11
11
  import { startWorkbenchDevServer } from '../dev/startWorkbenchDevServer.js';
12
12
  import { serveBuiltApplication } from './serveBuiltApplication.js';
13
13
  /**
@@ -62,6 +62,7 @@ import { serveBuiltApplication } from './serveBuiltApplication.js';
62
62
  isApp
63
63
  });
64
64
  const registration = registerDevServer({
65
+ applicationId: cliConfig.deployment?.appId,
65
66
  configs,
66
67
  host: remote.host,
67
68
  id,
@@ -72,12 +73,10 @@ import { serveBuiltApplication } from './serveBuiltApplication.js';
72
73
  workDir
73
74
  }),
74
75
  manifestUpdatedAt: new Date().toISOString(),
75
- organizationId: workbench.organizationId,
76
76
  port: remote.port,
77
77
  projectId: cliConfig?.api?.projectId,
78
- slug: workbench.slug,
78
+ ...localAppIdentity(workbench),
79
79
  type: isApp ? 'coreApp' : 'studio',
80
- visibility: workbench.visibility ?? 'default',
81
80
  workDir
82
81
  });
83
82
  closers.push(async ()=>registration.release());