@sanity/workbench-cli 1.2.0 → 1.4.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 (61) hide show
  1. package/dist/_exports/build.d.ts +22 -17
  2. package/dist/_exports/deploy.d.ts +169 -23
  3. package/dist/_exports/deploy.js +4 -1
  4. package/dist/_exports/deploy.js.map +1 -1
  5. package/dist/_exports/dev.d.ts +9 -5
  6. package/dist/_exports/index.d.ts +19 -15
  7. package/dist/_exports/undeploy.d.ts +248 -0
  8. package/dist/_exports/undeploy.js +3 -0
  9. package/dist/_exports/undeploy.js.map +1 -0
  10. package/dist/actions/build/artifact.js +2 -2
  11. package/dist/actions/build/artifact.js.map +1 -1
  12. package/dist/actions/build/configs/artifact.js +5 -5
  13. package/dist/actions/build/configs/artifact.js.map +1 -1
  14. package/dist/actions/build/vite/plugin.js +5 -0
  15. package/dist/actions/build/vite/plugin.js.map +1 -1
  16. package/dist/actions/build/vite/plugins/plugin-sanity-app-id.js +5 -3
  17. package/dist/actions/build/vite/plugins/plugin-sanity-app-id.js.map +1 -1
  18. package/dist/actions/build/vite/plugins/plugin-sanity-environment.js +26 -2
  19. package/dist/actions/build/vite/plugins/plugin-sanity-environment.js.map +1 -1
  20. package/dist/actions/deploy/buildExposes.js +59 -0
  21. package/dist/actions/deploy/buildExposes.js.map +1 -0
  22. package/dist/actions/deploy/checkBuiltOutput.js +4 -3
  23. package/dist/actions/deploy/checkBuiltOutput.js.map +1 -1
  24. package/dist/actions/deploy/deployConfig.js +63 -0
  25. package/dist/actions/deploy/deployConfig.js.map +1 -0
  26. package/dist/actions/deploy/deployWorkbenchApp.js +108 -0
  27. package/dist/actions/deploy/deployWorkbenchApp.js.map +1 -0
  28. package/dist/actions/deploy/getWorkbench.js +4 -4
  29. package/dist/actions/deploy/getWorkbench.js.map +1 -1
  30. package/dist/actions/dev/deriveInterfaces.js +43 -32
  31. package/dist/actions/dev/deriveInterfaces.js.map +1 -1
  32. package/dist/actions/dev/exposesSetId.js +8 -8
  33. package/dist/actions/dev/exposesSetId.js.map +1 -1
  34. package/dist/actions/dev/registry.js +22 -12
  35. package/dist/actions/dev/registry.js.map +1 -1
  36. package/dist/actions/dev/startDevManifestWatcher.js +2 -2
  37. package/dist/actions/dev/startDevManifestWatcher.js.map +1 -1
  38. package/dist/actions/dev/startDevServerRegistration.js +7 -7
  39. package/dist/actions/dev/startDevServerRegistration.js.map +1 -1
  40. package/dist/actions/dev/startWorkbenchDevServer.js +9 -6
  41. package/dist/actions/dev/startWorkbenchDevServer.js.map +1 -1
  42. package/dist/actions/dev/writeWorkbenchRuntime.js +4 -1
  43. package/dist/actions/dev/writeWorkbenchRuntime.js.map +1 -1
  44. package/dist/actions/undeploy/workbenchUndeployAdapter.js +150 -0
  45. package/dist/actions/undeploy/workbenchUndeployAdapter.js.map +1 -0
  46. package/dist/contract.js +16 -8
  47. package/dist/contract.js.map +1 -1
  48. package/dist/defineApp.js +25 -20
  49. package/dist/defineApp.js.map +1 -1
  50. package/dist/defineView.js.map +1 -1
  51. package/dist/resolveWorkbenchApp.js +4 -3
  52. package/dist/resolveWorkbenchApp.js.map +1 -1
  53. package/dist/services/apiVersion.js +5 -0
  54. package/dist/services/apiVersion.js.map +1 -0
  55. package/dist/services/applications.js +100 -0
  56. package/dist/services/applications.js.map +1 -0
  57. package/dist/services/installations.js +63 -0
  58. package/dist/services/installations.js.map +1 -0
  59. package/package.json +7 -3
  60. package/dist/actions/deploy/deployInstallationConfig.js +0 -91
  61. package/dist/actions/deploy/deployInstallationConfig.js.map +0 -1
@@ -0,0 +1,63 @@
1
+ import { basename, dirname } from 'node:path';
2
+ import { styleText } from 'node:util';
3
+ import { createGzip } from 'node:zlib';
4
+ import { subdebug } from '@sanity/cli-core';
5
+ import { pack } from 'tar-fs';
6
+ import { getWorkbenchUrl } from '../../services/applications.js';
7
+ import { createConfig, resolveSingletonInstallationId } from '../../services/installations.js';
8
+ import { summarizeExposeGroup } from './buildExposes.js';
9
+ const debug = subdebug('deploy');
10
+ /**
11
+ * The org's active installation for an app type, or `undefined` when none is
12
+ * installed. Read-only, so `--dry-run` can report deployability.
13
+ * @internal
14
+ */ export async function resolveInstallationId(options) {
15
+ switch(options.appType){
16
+ case 'media-library':
17
+ {
18
+ return resolveSingletonInstallationId(options.organizationId, 'media-library');
19
+ }
20
+ default:
21
+ {
22
+ throw new Error(`Cannot create config for unknown app type: ${options.appType}`);
23
+ }
24
+ }
25
+ }
26
+ /**
27
+ * A report heading and item list for a config; a media library's `fields` are
28
+ * one of potentially many shapes.
29
+ * @internal
30
+ */ export function summarizeConfig(config) {
31
+ switch(config.appType){
32
+ case 'media-library':
33
+ {
34
+ return summarizeExposeGroup('Media library fields', config.fields);
35
+ }
36
+ default:
37
+ {
38
+ throw new Error(`Cannot create config for unknown app type: ${config.appType}`);
39
+ }
40
+ }
41
+ }
42
+ /**
43
+ * Upload the built module-federation remote to the installation as its config
44
+ * snapshot. `installationId` is resolved by the caller so `--dry-run` never
45
+ * reaches this mutating step.
46
+ * @internal
47
+ */ export async function deployConfig(options) {
48
+ const { appType, installationId, organizationId, output, sourceDir, version } = options;
49
+ const tarball = pack(dirname(sourceDir), {
50
+ entries: [
51
+ basename(sourceDir)
52
+ ]
53
+ }).pipe(createGzip());
54
+ await createConfig(installationId, {
55
+ tarball,
56
+ version
57
+ });
58
+ debug('Deployed config for app type: %s', appType);
59
+ const url = getWorkbenchUrl(organizationId);
60
+ output.log(`\n🚀 ${styleText('bold', 'Success!')} Config deployed to ${styleText('cyan', url)}`);
61
+ }
62
+
63
+ //# sourceMappingURL=deployConfig.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/actions/deploy/deployConfig.ts"],"sourcesContent":["import {basename, dirname} from 'node:path'\nimport {styleText} from 'node:util'\nimport {createGzip} from 'node:zlib'\n\nimport {type Output, subdebug} from '@sanity/cli-core'\nimport {pack} from 'tar-fs'\n\nimport {getWorkbenchUrl} from '../../services/applications.js'\nimport {createConfig, resolveSingletonInstallationId} from '../../services/installations.js'\nimport {summarizeExposeGroup} from './buildExposes.js'\n\nconst debug = subdebug('deploy')\n\n/**\n * The org's active installation for an app type, or `undefined` when none is\n * installed. Read-only, so `--dry-run` can report deployability.\n * @internal\n */\nexport async function resolveInstallationId(options: {\n appType: string\n organizationId: string\n}): Promise<string | undefined> {\n switch (options.appType) {\n case 'media-library': {\n return resolveSingletonInstallationId(options.organizationId, 'media-library')\n }\n default: {\n throw new Error(`Cannot create config for unknown app type: ${options.appType}`)\n }\n }\n}\n\n/**\n * A report heading and item list for a config; a media library's `fields` are\n * one of potentially many shapes.\n * @internal\n */\nexport function summarizeConfig(config: {\n appType: string\n fields: {name: string; src: string; title: string}[]\n}): string {\n switch (config.appType) {\n case 'media-library': {\n return summarizeExposeGroup('Media library fields', config.fields)\n }\n default: {\n throw new Error(`Cannot create config for unknown app type: ${config.appType}`)\n }\n }\n}\n\n/**\n * Upload the built module-federation remote to the installation as its config\n * snapshot. `installationId` is resolved by the caller so `--dry-run` never\n * reaches this mutating step.\n * @internal\n */\nexport async function deployConfig(options: {\n appType: string\n installationId: string\n organizationId: string\n output: Output\n sourceDir: string\n version: string\n}): Promise<void> {\n const {appType, installationId, organizationId, output, sourceDir, version} = options\n const tarball = pack(dirname(sourceDir), {entries: [basename(sourceDir)]}).pipe(createGzip())\n await createConfig(installationId, {tarball, version})\n\n debug('Deployed config for app type: %s', appType)\n const url = getWorkbenchUrl(organizationId)\n output.log(`\\n🚀 ${styleText('bold', 'Success!')} Config deployed to ${styleText('cyan', url)}`)\n}\n"],"names":["basename","dirname","styleText","createGzip","subdebug","pack","getWorkbenchUrl","createConfig","resolveSingletonInstallationId","summarizeExposeGroup","debug","resolveInstallationId","options","appType","organizationId","Error","summarizeConfig","config","fields","deployConfig","installationId","output","sourceDir","version","tarball","entries","pipe","url","log"],"mappings":"AAAA,SAAQA,QAAQ,EAAEC,OAAO,QAAO,YAAW;AAC3C,SAAQC,SAAS,QAAO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1
+ import { basename, dirname } from 'node:path';
2
+ import { createGzip } from 'node:zlib';
3
+ import { exitCodes } from '@sanity/cli-core';
4
+ import { spinner } from '@sanity/cli-core/ux';
5
+ import { pack } from 'tar-fs';
6
+ import { createApplication, createDeployment } from '../../services/applications.js';
7
+ /**
8
+ * Deploy a workbench coreApp through Brett: redeploy when `appId` is set,
9
+ * otherwise create the application at `slug`. Returns the application id for the
10
+ * shell to report.
11
+ * @internal
12
+ */ export async function deployCoreApp(options) {
13
+ const { appId, interfaces, isAutoUpdating, isSingleton, organizationId, slug, sourceDir, title, version } = options;
14
+ const tarball = pack(dirname(sourceDir), {
15
+ entries: [
16
+ basename(sourceDir)
17
+ ]
18
+ }).pipe(createGzip());
19
+ const spin = spinner('Deploying...').start();
20
+ try {
21
+ if (appId) {
22
+ await createDeployment({
23
+ applicationId: appId,
24
+ interfaces,
25
+ isAutoUpdating,
26
+ tarball,
27
+ version
28
+ });
29
+ spin.succeed();
30
+ return {
31
+ applicationId: appId
32
+ };
33
+ }
34
+ const { id } = await createApplication({
35
+ interfaces,
36
+ isSingleton,
37
+ organizationId,
38
+ slug,
39
+ tarball,
40
+ title,
41
+ type: 'coreApp',
42
+ version
43
+ });
44
+ spin.succeed();
45
+ return {
46
+ applicationId: id
47
+ };
48
+ } catch (error) {
49
+ spin.clear();
50
+ throw error;
51
+ }
52
+ }
53
+ /**
54
+ * Deploy a workbench studio through Brett: redeploy when `appId` is set,
55
+ * otherwise create the studio at `studioHost`. Returns the application id for
56
+ * the shell to report; a missing `studioHost` on create is a usage error.
57
+ * @internal
58
+ */ export async function deployStudio(options) {
59
+ const { appId, interfaces, isAutoUpdating, organizationId, output, projectId, sourceDir, studioHost, title, version, workspaces } = options;
60
+ const tarball = pack(dirname(sourceDir), {
61
+ entries: [
62
+ basename(sourceDir)
63
+ ]
64
+ }).pipe(createGzip());
65
+ const spin = spinner('Deploying to sanity.studio').start();
66
+ try {
67
+ if (appId) {
68
+ await createDeployment({
69
+ applicationId: appId,
70
+ interfaces,
71
+ isAutoUpdating,
72
+ tarball,
73
+ version,
74
+ workspaces
75
+ });
76
+ spin.succeed();
77
+ return {
78
+ applicationId: appId
79
+ };
80
+ }
81
+ if (!studioHost) {
82
+ spin.fail();
83
+ return output.error('No studio hostname configured. Set `studioHost` in sanity.cli.ts to create a studio.', {
84
+ exit: exitCodes.USAGE_ERROR
85
+ });
86
+ }
87
+ const application = await createApplication({
88
+ interfaces,
89
+ organizationId,
90
+ projectId,
91
+ slug: studioHost,
92
+ tarball,
93
+ title,
94
+ type: 'studio',
95
+ version,
96
+ workspaces
97
+ });
98
+ spin.succeed();
99
+ return {
100
+ applicationId: application.id
101
+ };
102
+ } catch (error) {
103
+ spin.fail();
104
+ throw error;
105
+ }
106
+ }
107
+
108
+ //# sourceMappingURL=deployWorkbenchApp.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/actions/deploy/deployWorkbenchApp.ts"],"sourcesContent":["import {basename, dirname} from 'node:path'\nimport {createGzip} from 'node:zlib'\n\nimport {exitCodes, type Output} from '@sanity/cli-core'\nimport {spinner} from '@sanity/cli-core/ux'\nimport {pack} from 'tar-fs'\n\nimport {\n type BrettInterface,\n type BrettWorkspace,\n createApplication,\n createDeployment,\n} from '../../services/applications.js'\n\n/**\n * Deploy a workbench coreApp through Brett: redeploy when `appId` is set,\n * otherwise create the application at `slug`. Returns the application id for the\n * shell to report.\n * @internal\n */\nexport async function deployCoreApp(options: {\n appId: string | undefined\n interfaces: readonly BrettInterface[]\n isAutoUpdating: boolean\n isSingleton?: boolean\n organizationId: string\n slug: string\n sourceDir: string\n title: string\n version: string\n}): Promise<{applicationId: string}> {\n const {\n appId,\n interfaces,\n isAutoUpdating,\n isSingleton,\n organizationId,\n slug,\n sourceDir,\n title,\n version,\n } = options\n const tarball = pack(dirname(sourceDir), {entries: [basename(sourceDir)]}).pipe(createGzip())\n\n const spin = spinner('Deploying...').start()\n try {\n if (appId) {\n await createDeployment({applicationId: appId, interfaces, isAutoUpdating, tarball, version})\n spin.succeed()\n return {applicationId: appId}\n }\n\n const {id} = await createApplication({\n interfaces,\n isSingleton,\n organizationId,\n slug,\n tarball,\n title,\n type: 'coreApp',\n version,\n })\n spin.succeed()\n return {applicationId: id}\n } catch (error) {\n spin.clear()\n throw error\n }\n}\n\n/**\n * Deploy a workbench studio through Brett: redeploy when `appId` is set,\n * otherwise create the studio at `studioHost`. Returns the application id for\n * the shell to report; a missing `studioHost` on create is a usage error.\n * @internal\n */\nexport async function deployStudio(options: {\n appId: string | undefined\n interfaces: readonly BrettInterface[]\n isAutoUpdating: boolean\n organizationId: string\n output: Output\n projectId: string | undefined\n sourceDir: string\n studioHost: string | undefined\n title: string\n version: string\n workspaces: readonly BrettWorkspace[]\n}): Promise<{applicationId: string}> {\n const {\n appId,\n interfaces,\n isAutoUpdating,\n organizationId,\n output,\n projectId,\n sourceDir,\n studioHost,\n title,\n version,\n workspaces,\n } = options\n const tarball = pack(dirname(sourceDir), {entries: [basename(sourceDir)]}).pipe(createGzip())\n\n const spin = spinner('Deploying to sanity.studio').start()\n try {\n if (appId) {\n await createDeployment({\n applicationId: appId,\n interfaces,\n isAutoUpdating,\n tarball,\n version,\n workspaces,\n })\n spin.succeed()\n return {applicationId: appId}\n }\n\n if (!studioHost) {\n spin.fail()\n return output.error(\n 'No studio hostname configured. Set `studioHost` in sanity.cli.ts to create a studio.',\n {exit: exitCodes.USAGE_ERROR},\n )\n }\n\n const application = await createApplication({\n interfaces,\n organizationId,\n projectId,\n slug: studioHost,\n tarball,\n title,\n type: 'studio',\n version,\n workspaces,\n })\n spin.succeed()\n return {applicationId: application.id}\n } catch (error) {\n spin.fail()\n throw error\n }\n}\n"],"names":["basename","dirname","createGzip","exitCodes","spinner","pack","createApplication","createDeployment","deployCoreApp","options","appId","interfaces","isAutoUpdating","isSingleton","organizationId","slug","sourceDir","title","version","tarball","entries","pipe","spin","start","applicationId","succeed","id","type","error","clear","deployStudio","output","projectId","studioHost","workspaces","fail","exit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,YAAY;QAACI,SAAS;YAACpB,SAASgB;SAAW;IAAA,GAAGK,IAAI,CAACnB;IAEhF,MAAMoB,OAAOlB,QAAQ,8BAA8BmB,KAAK;IACxD,IAAI;QACF,IAAIb,OAAO;YACT,MAAMH,iBAAiB;gBACrBiB,eAAed;gBACfC;gBACAC;gBACAO;gBACAD;gBACAgB;YACF;YACAZ,KAAKG,OAAO;YACZ,OAAO;gBAACD,eAAed;YAAK;QAC9B;QAEA,IAAI,CAACuB,YAAY;YACfX,KAAKa,IAAI;YACT,OAAOJ,OAAOH,KAAK,CACjB,wFACA;gBAACQ,MAAMjC,UAAUkC,WAAW;YAAA;QAEhC;QAEA,MAAMC,cAAc,MAAMhC,kBAAkB;YAC1CK;YACAG;YACAkB;YACAjB,MAAMkB;YACNd;YACAF;YACAU,MAAM;YACNT;YACAgB;QACF;QACAZ,KAAKG,OAAO;QACZ,OAAO;YAACD,eAAec,YAAYZ,EAAE;QAAA;IACvC,EAAE,OAAOE,OAAO;QACdN,KAAKa,IAAI;QACT,MAAMP;IACR;AACF"}
@@ -7,14 +7,14 @@ import { buildViewDeploymentPayload } from './viewDeployment.js';
7
7
  export function getWorkbench(cliConfig) {
8
8
  const app = resolveWorkbenchApp(cliConfig);
9
9
  if (!app) return null;
10
- const { entry, installationConfig, isSingleton, services, views } = app;
10
+ const { config, entry, isSingleton, services, views } = app;
11
11
  return {
12
12
  ...app,
13
- deploySingletonInstallationConfig: isSingleton && !!installationConfig,
13
+ deploySingletonConfig: !!isSingleton && !!config,
14
14
  hasInterfaces: !!entry || views.length > 0 || services.length > 0,
15
15
  assertDeployable () {
16
- if (!entry && views.length === 0 && services.length === 0 && !installationConfig) {
17
- throw new Error('Nothing to deploy: the app declares no entry, views, services or installation config. ' + 'Add at least one to the app config.');
16
+ if (!entry && views.length === 0 && services.length === 0 && !config) {
17
+ throw new Error('Nothing to deploy: the app declares no entry, views, services or config. ' + 'Add at least one to the app config.');
18
18
  }
19
19
  },
20
20
  buildViewDeploymentPayload (applicationId) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/actions/deploy/getWorkbench.ts"],"sourcesContent":["// The deploy command's view of a workbench app: the resolved interfaces plus\n// the deploy-time guards that need the app's declarations. `sanity deploy` calls\n// `getWorkbench(config)` once and either gets `null` (plain project — normal\n// deploy) or an object it asks to validate the app before shipping.\n\nimport {type CliConfig} from '@sanity/cli-core'\n\nimport {type ResolvedWorkbenchApp, resolveWorkbenchApp} from '../../resolveWorkbenchApp.js'\nimport {buildViewDeploymentPayload, type ViewDeploymentPayload} from './viewDeployment.js'\n\ninterface DeployableWorkbenchApp extends ResolvedWorkbenchApp {\n /**\n * Throws when the app exposes nothing (no entry, view, service, or config) —\n * the remote would have nothing to load. Gated before any prompt or API call.\n */\n assertDeployable(): void\n /**\n * Validates the app's declared views into the application-service payload.\n * Throws when a view declaration is malformed.\n */\n buildViewDeploymentPayload(applicationId: string): ViewDeploymentPayload\n /**\n * A singleton (the Media Library) that carries an installation config — deploy\n * persists the config to the org's installation. Independent of the interfaces,\n * which register regardless; non-singletons never carry a config.\n */\n deploySingletonInstallationConfig: boolean\n /** Declares something to host as an application — an entry, view, or service. */\n hasInterfaces: boolean\n}\n\nexport function getWorkbench(\n cliConfig: CliConfig | null | undefined,\n): DeployableWorkbenchApp | null {\n const app = resolveWorkbenchApp(cliConfig)\n if (!app) return null\n\n const {entry, installationConfig, isSingleton, services, views} = app\n\n return {\n ...app,\n\n deploySingletonInstallationConfig: isSingleton && !!installationConfig,\n hasInterfaces: !!entry || views.length > 0 || services.length > 0,\n\n assertDeployable() {\n if (!entry && views.length === 0 && services.length === 0 && !installationConfig) {\n throw new Error(\n 'Nothing to deploy: the app declares no entry, views, services or installation config. ' +\n 'Add at least one to the app config.',\n )\n }\n },\n\n buildViewDeploymentPayload(applicationId) {\n return buildViewDeploymentPayload({applicationId, views})\n },\n }\n}\n"],"names":["resolveWorkbenchApp","buildViewDeploymentPayload","getWorkbench","cliConfig","app","entry","installationConfig","isSingleton","services","views","deploySingletonInstallationConfig","hasInterfaces","length","assertDeployable","Error","applicationId"],"mappings":"AAAA,6EAA6E;AAC7E,iFAAiF;AACjF,6EAA6E;AAC7E,oEAAoE;AAIpE,SAAmCA,mBAAmB,QAAO,+BAA8B;AAC3F,SAAQC,0BAA0B,QAAmC,sBAAqB;AAuB1F,OAAO,SAASC,aACdC,SAAuC;IAEvC,MAAMC,MAAMJ,oBAAoBG;IAChC,IAAI,CAACC,KAAK,OAAO;IAEjB,MAAM,EAACC,KAAK,EAAEC,kBAAkB,EAAEC,WAAW,EAAEC,QAAQ,EAAEC,KAAK,EAAC,GAAGL;IAElE,OAAO;QACL,GAAGA,GAAG;QAENM,mCAAmCH,eAAe,CAAC,CAACD;QACpDK,eAAe,CAAC,CAACN,SAASI,MAAMG,MAAM,GAAG,KAAKJ,SAASI,MAAM,GAAG;QAEhEC;YACE,IAAI,CAACR,SAASI,MAAMG,MAAM,KAAK,KAAKJ,SAASI,MAAM,KAAK,KAAK,CAACN,oBAAoB;gBAChF,MAAM,IAAIQ,MACR,2FACE;YAEN;QACF;QAEAb,4BAA2Bc,aAAa;YACtC,OAAOd,2BAA2B;gBAACc;gBAAeN;YAAK;QACzD;IACF;AACF"}
1
+ {"version":3,"sources":["../../../src/actions/deploy/getWorkbench.ts"],"sourcesContent":["// The deploy command's view of a workbench app: the resolved interfaces plus\n// the deploy-time guards that need the app's declarations. `sanity deploy` calls\n// `getWorkbench(config)` once and either gets `null` (plain project — normal\n// deploy) or an object it asks to validate the app before shipping.\n\nimport {type CliConfig} from '@sanity/cli-core'\n\nimport {type ResolvedWorkbenchApp, resolveWorkbenchApp} from '../../resolveWorkbenchApp.js'\nimport {buildViewDeploymentPayload, type ViewDeploymentPayload} from './viewDeployment.js'\n\nexport interface DeployableWorkbenchApp extends ResolvedWorkbenchApp {\n /**\n * Throws when the app exposes nothing (no entry, view, service, or config) —\n * the remote would have nothing to load. Gated before any prompt or API call.\n */\n assertDeployable(): void\n /**\n * Validates the app's declared views into the application-service payload.\n * Throws when a view declaration is malformed.\n */\n buildViewDeploymentPayload(applicationId: string): ViewDeploymentPayload\n /**\n * A singleton (the Media Library) that carries an config — deploy\n * persists the config to the org's installation. Independent of the interfaces,\n * which register regardless; non-singletons never carry a config.\n */\n deploySingletonConfig: boolean\n /** Declares something to host as an application — an entry, view, or service. */\n hasInterfaces: boolean\n}\n\nexport function getWorkbench(\n cliConfig: CliConfig | null | undefined,\n): DeployableWorkbenchApp | null {\n const app = resolveWorkbenchApp(cliConfig)\n if (!app) return null\n\n const {config, entry, isSingleton, services, views} = app\n\n return {\n ...app,\n\n deploySingletonConfig: !!isSingleton && !!config,\n hasInterfaces: !!entry || views.length > 0 || services.length > 0,\n\n assertDeployable() {\n if (!entry && views.length === 0 && services.length === 0 && !config) {\n throw new Error(\n 'Nothing to deploy: the app declares no entry, views, services or config. ' +\n 'Add at least one to the app config.',\n )\n }\n },\n\n buildViewDeploymentPayload(applicationId) {\n return buildViewDeploymentPayload({applicationId, views})\n },\n }\n}\n"],"names":["resolveWorkbenchApp","buildViewDeploymentPayload","getWorkbench","cliConfig","app","config","entry","isSingleton","services","views","deploySingletonConfig","hasInterfaces","length","assertDeployable","Error","applicationId"],"mappings":"AAAA,6EAA6E;AAC7E,iFAAiF;AACjF,6EAA6E;AAC7E,oEAAoE;AAIpE,SAAmCA,mBAAmB,QAAO,+BAA8B;AAC3F,SAAQC,0BAA0B,QAAmC,sBAAqB;AAuB1F,OAAO,SAASC,aACdC,SAAuC;IAEvC,MAAMC,MAAMJ,oBAAoBG;IAChC,IAAI,CAACC,KAAK,OAAO;IAEjB,MAAM,EAACC,MAAM,EAAEC,KAAK,EAAEC,WAAW,EAAEC,QAAQ,EAAEC,KAAK,EAAC,GAAGL;IAEtD,OAAO;QACL,GAAGA,GAAG;QAENM,uBAAuB,CAAC,CAACH,eAAe,CAAC,CAACF;QAC1CM,eAAe,CAAC,CAACL,SAASG,MAAMG,MAAM,GAAG,KAAKJ,SAASI,MAAM,GAAG;QAEhEC;YACE,IAAI,CAACP,SAASG,MAAMG,MAAM,KAAK,KAAKJ,SAASI,MAAM,KAAK,KAAK,CAACP,QAAQ;gBACpE,MAAM,IAAIS,MACR,8EACE;YAEN;QACF;QAEAb,4BAA2Bc,aAAa;YACtC,OAAOd,2BAA2B;gBAACc;gBAAeN;YAAK;QACzD;IACF;AACF"}
@@ -1,32 +1,35 @@
1
- import { isWorkbenchApp, readInstallationConfig } from '../../defineApp.js';
1
+ import { hash } from 'node:crypto';
2
+ import { MEDIA_LIBRARY_CONFIG_CONTRACT_VERSION, SERVICE_CONTRACT_VERSION, VIEW_CONTRACT_VERSION } from '../../contract.js';
3
+ import { isWorkbenchApp, readConfig } from '../../defineApp.js';
2
4
  /**
3
5
  * Map a workbench app's declarations to the interface records forwarded on its
4
6
  * registry entry: `views` → panels, `services` → workers, `entry` → the
5
- * navigable `app` view (`entry_point` is the raw `src`, not a resolved URL).
6
- * `undefined` for a non-branded app; a studio that declares `entry` is rejected
7
- * (studio app views are not implemented yet). The installation config is not an
8
- * interface — see {@link deriveInstallationConfigs}.
7
+ * navigable `app` view. `src` is the raw source, not a resolved URL. `undefined`
8
+ * for a non-branded app; a studio that declares `entry` is rejected (studio app
9
+ * views are not implemented yet). The config is not an interface — see
10
+ * {@link deriveConfigs}. `version` is the module's contract version; the app
11
+ * view has no versioned contract, so it carries none.
9
12
  */ export function deriveInterfaces(app, options) {
10
13
  if (!isWorkbenchApp(app)) return undefined;
11
14
  if (!options.isApp && app.entry !== undefined) {
12
15
  throw new Error('App views for studios are not implemented yet');
13
16
  }
17
+ const toInterface = ({ name, src, title, type }, version)=>({
18
+ name,
19
+ src,
20
+ title: title ?? name,
21
+ type,
22
+ version
23
+ });
14
24
  return [
15
- ...app.views?.map((view)=>({
16
- entry_point: view.src,
17
- interface_type: view.type,
18
- name: view.name
19
- })) ?? [],
20
- ...app.services?.map((service)=>({
21
- entry_point: service.src,
22
- interface_type: service.type,
23
- name: service.name
24
- })) ?? [],
25
+ ...(app.views ?? []).map((view)=>toInterface(view, VIEW_CONTRACT_VERSION)),
26
+ ...(app.services ?? []).map((service)=>toInterface(service, SERVICE_CONTRACT_VERSION)),
25
27
  ...app.entry === undefined ? [] : [
26
28
  {
27
- entry_point: app.entry,
28
- interface_type: 'app',
29
- name: app.name
29
+ name: app.name,
30
+ src: app.entry,
31
+ title: app.title,
32
+ type: 'app'
30
33
  }
31
34
  ]
32
35
  ];
@@ -36,7 +39,7 @@ import { isWorkbenchApp, readInstallationConfig } from '../../defineApp.js';
36
39
  * per app type — the projection the exposes-set id keys on, so the generic HMR
37
40
  * tracker owns none of the per-type shape. Throws on an app type it can't
38
41
  * handle, so a new config family has to register its shape here.
39
- */ export function deriveInstallationConfigEntries(config) {
42
+ */ export function deriveConfigEntries(config) {
40
43
  switch(config.appType){
41
44
  case 'media-library':
42
45
  {
@@ -47,7 +50,7 @@ import { isWorkbenchApp, readInstallationConfig } from '../../defineApp.js';
47
50
  }
48
51
  default:
49
52
  {
50
- throw new Error(`Cannot derive entries for unknown installation config appType: ${config.appType}`);
53
+ throw new Error(`Cannot derive entries for unknown config appType: ${config.appType}`);
51
54
  }
52
55
  }
53
56
  }
@@ -55,21 +58,29 @@ import { isWorkbenchApp, readInstallationConfig } from '../../defineApp.js';
55
58
  * The fields' schema *values* can't serialize — the workbench loads them from
56
59
  * the federation module. `src` stays on so the exposes-set id keys on it and a
57
60
  * repoint rebuilds. `appType` routes the config to the singleton (no app id to
58
- * key on).
59
- */ export function deriveInstallationConfigs(app) {
61
+ * key on). `id` is a content hash of the entry — it fills the
62
+ * installation-config id slot deployed apps get from the applications API,
63
+ * and the workbench keys change detection on it. `version` is the config
64
+ * contract version the generated module exports, known before the module runs.
65
+ */ export function deriveConfigs(app) {
60
66
  if (!isWorkbenchApp(app)) return [];
61
- const installationConfig = readInstallationConfig(app);
62
- if (!installationConfig) return [];
67
+ const config = readConfig(app);
68
+ if (!config) return [];
69
+ const entry = {
70
+ appType: config.appType,
71
+ fields: config.fields.map((field)=>({
72
+ name: field.name,
73
+ public: field.public,
74
+ src: field.src,
75
+ title: field.title
76
+ })),
77
+ moduleName: app.name,
78
+ version: MEDIA_LIBRARY_CONFIG_CONTRACT_VERSION
79
+ };
63
80
  return [
64
81
  {
65
- appType: installationConfig.appType,
66
- fields: installationConfig.fields.map((field)=>({
67
- name: field.name,
68
- public: field.public,
69
- src: field.src,
70
- title: field.title
71
- })),
72
- moduleName: app.name
82
+ ...entry,
83
+ id: hash('sha1', JSON.stringify(entry))
73
84
  }
74
85
  ];
75
86
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/actions/dev/deriveInterfaces.ts"],"sourcesContent":["import {type CliConfig} from '@sanity/cli-core'\n\nimport {isWorkbenchApp, readInstallationConfig} from '../../defineApp.js'\nimport {type DevServerManifest} from './registry.js'\n\n/** One forwarded interface record on the dev-server registry entry. */\nexport type DevServerInterface = NonNullable<DevServerManifest['interfaces']>[number]\n\n/** One forwarded installation config on the dev-server registry entry. */\nexport type DevServerConfig = NonNullable<DevServerManifest['installationConfigs']>[number]\n\n/**\n * Map a workbench app's declarations to the interface records forwarded on its\n * registry entry: `views` → panels, `services` → workers, `entry` → the\n * navigable `app` view (`entry_point` is the raw `src`, not a resolved URL).\n * `undefined` for a non-branded app; a studio that declares `entry` is rejected\n * (studio app views are not implemented yet). The installation config is not an\n * interface — see {@link deriveInstallationConfigs}.\n */\nexport function deriveInterfaces(\n app: CliConfig['app'],\n options: {isApp: boolean},\n): DevServerInterface[] | undefined {\n if (!isWorkbenchApp(app)) return undefined\n\n if (!options.isApp && app.entry !== undefined) {\n throw new Error('App views for studios are not implemented yet')\n }\n\n return [\n ...(app.views?.map((view) => ({\n entry_point: view.src,\n interface_type: view.type,\n name: view.name,\n })) ?? []),\n ...(app.services?.map((service) => ({\n entry_point: service.src,\n interface_type: service.type,\n name: service.name,\n })) ?? []),\n ...(app.entry === undefined\n ? []\n : [{entry_point: app.entry, interface_type: 'app' as const, name: app.name}]),\n ]\n}\n\n/**\n * The named source files a config's generated module is built from, dispatched\n * per app type — the projection the exposes-set id keys on, so the generic HMR\n * tracker owns none of the per-type shape. Throws on an app type it can't\n * handle, so a new config family has to register its shape here.\n */\nexport function deriveInstallationConfigEntries(\n config: DevServerConfig,\n): {name: string; src: string}[] {\n switch (config.appType) {\n case 'media-library': {\n return config.fields.map((field) => ({name: field.name, src: field.src}))\n }\n default: {\n throw new Error(\n `Cannot derive entries for unknown installation config appType: ${config.appType}`,\n )\n }\n }\n}\n\n/**\n * The fields' schema *values* can't serialize — the workbench loads them from\n * the federation module. `src` stays on so the exposes-set id keys on it and a\n * repoint rebuilds. `appType` routes the config to the singleton (no app id to\n * key on).\n */\nexport function deriveInstallationConfigs(app: CliConfig['app']): DevServerConfig[] {\n if (!isWorkbenchApp(app)) return []\n const installationConfig = readInstallationConfig(app)\n if (!installationConfig) return []\n return [\n {\n appType: installationConfig.appType,\n fields: installationConfig.fields.map((field) => ({\n name: field.name,\n public: field.public,\n src: field.src,\n title: field.title,\n })),\n moduleName: app.name,\n },\n ]\n}\n"],"names":["isWorkbenchApp","readInstallationConfig","deriveInterfaces","app","options","undefined","isApp","entry","Error","views","map","view","entry_point","src","interface_type","type","name","services","service","deriveInstallationConfigEntries","config","appType","fields","field","deriveInstallationConfigs","installationConfig","public","title","moduleName"],"mappings":"AAEA,SAAQA,cAAc,EAAEC,sBAAsB,QAAO,qBAAoB;AASzE;;;;;;;CAOC,GACD,OAAO,SAASC,iBACdC,GAAqB,EACrBC,OAAyB;IAEzB,IAAI,CAACJ,eAAeG,MAAM,OAAOE;IAEjC,IAAI,CAACD,QAAQE,KAAK,IAAIH,IAAII,KAAK,KAAKF,WAAW;QAC7C,MAAM,IAAIG,MAAM;IAClB;IAEA,OAAO;WACDL,IAAIM,KAAK,EAAEC,IAAI,CAACC,OAAU,CAAA;gBAC5BC,aAAaD,KAAKE,GAAG;gBACrBC,gBAAgBH,KAAKI,IAAI;gBACzBC,MAAML,KAAKK,IAAI;YACjB,CAAA,MAAO,EAAE;WACLb,IAAIc,QAAQ,EAAEP,IAAI,CAACQ,UAAa,CAAA;gBAClCN,aAAaM,QAAQL,GAAG;gBACxBC,gBAAgBI,QAAQH,IAAI;gBAC5BC,MAAME,QAAQF,IAAI;YACpB,CAAA,MAAO,EAAE;WACLb,IAAII,KAAK,KAAKF,YACd,EAAE,GACF;YAAC;gBAACO,aAAaT,IAAII,KAAK;gBAAEO,gBAAgB;gBAAgBE,MAAMb,IAAIa,IAAI;YAAA;SAAE;KAC/E;AACH;AAEA;;;;;CAKC,GACD,OAAO,SAASG,gCACdC,MAAuB;IAEvB,OAAQA,OAAOC,OAAO;QACpB,KAAK;YAAiB;gBACpB,OAAOD,OAAOE,MAAM,CAACZ,GAAG,CAAC,CAACa,QAAW,CAAA;wBAACP,MAAMO,MAAMP,IAAI;wBAAEH,KAAKU,MAAMV,GAAG;oBAAA,CAAA;YACxE;QACA;YAAS;gBACP,MAAM,IAAIL,MACR,CAAC,+DAA+D,EAAEY,OAAOC,OAAO,EAAE;YAEtF;IACF;AACF;AAEA;;;;;CAKC,GACD,OAAO,SAASG,0BAA0BrB,GAAqB;IAC7D,IAAI,CAACH,eAAeG,MAAM,OAAO,EAAE;IACnC,MAAMsB,qBAAqBxB,uBAAuBE;IAClD,IAAI,CAACsB,oBAAoB,OAAO,EAAE;IAClC,OAAO;QACL;YACEJ,SAASI,mBAAmBJ,OAAO;YACnCC,QAAQG,mBAAmBH,MAAM,CAACZ,GAAG,CAAC,CAACa,QAAW,CAAA;oBAChDP,MAAMO,MAAMP,IAAI;oBAChBU,QAAQH,MAAMG,MAAM;oBACpBb,KAAKU,MAAMV,GAAG;oBACdc,OAAOJ,MAAMI,KAAK;gBACpB,CAAA;YACAC,YAAYzB,IAAIa,IAAI;QACtB;KACD;AACH"}
1
+ {"version":3,"sources":["../../../src/actions/dev/deriveInterfaces.ts"],"sourcesContent":["import {hash} from 'node:crypto'\n\nimport {type CliConfig} from '@sanity/cli-core'\n\nimport {\n MEDIA_LIBRARY_CONFIG_CONTRACT_VERSION,\n SERVICE_CONTRACT_VERSION,\n VIEW_CONTRACT_VERSION,\n} from '../../contract.js'\nimport {isWorkbenchApp, readConfig} from '../../defineApp.js'\nimport {type DevServerManifest} from './registry.js'\n\n/** One forwarded interface record on the dev-server registry entry. */\nexport type DevServerInterface = NonNullable<DevServerManifest['interfaces']>[number]\n\n/** One forwarded config on the dev-server registry entry. */\nexport type DevServerConfig = NonNullable<DevServerManifest['configs']>[number]\n\n/**\n * Map a workbench app's declarations to the interface records forwarded on its\n * registry entry: `views` → panels, `services` → workers, `entry` → the\n * navigable `app` view. `src` is the raw source, not a resolved URL. `undefined`\n * for a non-branded app; a studio that declares `entry` is rejected (studio app\n * views are not implemented yet). The config is not an interface — see\n * {@link deriveConfigs}. `version` is the module's contract version; the app\n * view has no versioned contract, so it carries none.\n */\nexport function deriveInterfaces(\n app: CliConfig['app'],\n options: {isApp: boolean},\n): DevServerInterface[] | undefined {\n if (!isWorkbenchApp(app)) return undefined\n\n if (!options.isApp && app.entry !== undefined) {\n throw new Error('App views for studios are not implemented yet')\n }\n\n const toInterface = (\n {name, src, title, type}: {name: string; src: string; title?: string; type: string},\n version: number,\n ): DevServerInterface => ({name, src, title: title ?? name, type, version})\n\n return [\n ...(app.views ?? []).map((view) => toInterface(view, VIEW_CONTRACT_VERSION)),\n ...(app.services ?? []).map((service) => toInterface(service, SERVICE_CONTRACT_VERSION)),\n ...(app.entry === undefined\n ? []\n : [{name: app.name, src: app.entry, title: app.title, type: 'app' as const}]),\n ]\n}\n\n/**\n * The named source files a config's generated module is built from, dispatched\n * per app type — the projection the exposes-set id keys on, so the generic HMR\n * tracker owns none of the per-type shape. Throws on an app type it can't\n * handle, so a new config family has to register its shape here.\n */\nexport function deriveConfigEntries(config: DevServerConfig): {name: string; src: string}[] {\n switch (config.appType) {\n case 'media-library': {\n return config.fields.map((field) => ({name: field.name, src: field.src}))\n }\n default: {\n throw new Error(`Cannot derive entries for unknown config appType: ${config.appType}`)\n }\n }\n}\n\n/**\n * The fields' schema *values* can't serialize — the workbench loads them from\n * the federation module. `src` stays on so the exposes-set id keys on it and a\n * repoint rebuilds. `appType` routes the config to the singleton (no app id to\n * key on). `id` is a content hash of the entry — it fills the\n * installation-config id slot deployed apps get from the applications API,\n * and the workbench keys change detection on it. `version` is the config\n * contract version the generated module exports, known before the module runs.\n */\nexport function deriveConfigs(app: CliConfig['app']): DevServerConfig[] {\n if (!isWorkbenchApp(app)) return []\n const config = readConfig(app)\n if (!config) return []\n const entry = {\n appType: config.appType,\n fields: config.fields.map((field) => ({\n name: field.name,\n public: field.public,\n src: field.src,\n title: field.title,\n })),\n moduleName: app.name,\n version: MEDIA_LIBRARY_CONFIG_CONTRACT_VERSION,\n }\n return [{...entry, id: hash('sha1', JSON.stringify(entry))}]\n}\n"],"names":["hash","MEDIA_LIBRARY_CONFIG_CONTRACT_VERSION","SERVICE_CONTRACT_VERSION","VIEW_CONTRACT_VERSION","isWorkbenchApp","readConfig","deriveInterfaces","app","options","undefined","isApp","entry","Error","toInterface","name","src","title","type","version","views","map","view","services","service","deriveConfigEntries","config","appType","fields","field","deriveConfigs","public","moduleName","id","JSON","stringify"],"mappings":"AAAA,SAAQA,IAAI,QAAO,cAAa;AAIhC,SACEC,qCAAqC,EACrCC,wBAAwB,EACxBC,qBAAqB,QAChB,oBAAmB;AAC1B,SAAQC,cAAc,EAAEC,UAAU,QAAO,qBAAoB;AAS7D;;;;;;;;CAQC,GACD,OAAO,SAASC,iBACdC,GAAqB,EACrBC,OAAyB;IAEzB,IAAI,CAACJ,eAAeG,MAAM,OAAOE;IAEjC,IAAI,CAACD,QAAQE,KAAK,IAAIH,IAAII,KAAK,KAAKF,WAAW;QAC7C,MAAM,IAAIG,MAAM;IAClB;IAEA,MAAMC,cAAc,CAClB,EAACC,IAAI,EAAEC,GAAG,EAAEC,KAAK,EAAEC,IAAI,EAA4D,EACnFC,UACwB,CAAA;YAACJ;YAA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GAAGU,KAAK;YAAEqB,IAAIhC,KAAK,QAAQiC,KAAKC,SAAS,CAACvB;QAAO;KAAE;AAC9D"}
@@ -1,23 +1,23 @@
1
- import { deriveInstallationConfigEntries } from './deriveInterfaces.js';
1
+ import { deriveConfigEntries } from './deriveInterfaces.js';
2
2
  /**
3
3
  * Order-independent id of an app's exposed-module set. Keys each interface by
4
- * its type, name, and source file, and each installation config by its module
4
+ * its type, name, and source file, and each config by its module
5
5
  * identity plus one key per entry (a named source file), so the id changes on
6
6
  * any rebuild-worthy edit — add, remove, rename, repoint, or gaining/losing the
7
7
  * config module — while reordering and HMR content edits keep it stable.
8
- */ export function exposesSetId({ installationConfigs, interfaces }) {
8
+ */ export function exposesSetId({ configs, interfaces }) {
9
9
  const keys = [
10
10
  ...(interfaces ?? []).map((iface)=>[
11
- iface.interface_type,
11
+ iface.type,
12
12
  iface.name,
13
- iface.entry_point
13
+ iface.src
14
14
  ].join('::')),
15
- ...(installationConfigs ?? []).flatMap((config)=>[
15
+ ...(configs ?? []).flatMap((config)=>[
16
16
  [
17
17
  'config',
18
18
  config.appType
19
19
  ].join('::'),
20
- ...deriveInstallationConfigEntries(config).map((entry)=>[
20
+ ...deriveConfigEntries(config).map((entry)=>[
21
21
  'config',
22
22
  config.appType,
23
23
  entry.name,
@@ -42,7 +42,7 @@ import { deriveInstallationConfigEntries } from './deriveInterfaces.js';
42
42
  }
43
43
  const serverKey = (server)=>`${server.id ?? ''}@${server.host ?? ''}:${server.port}`;
44
44
  const serverExposesId = (server)=>exposesSetId({
45
- installationConfigs: server.installationConfigs,
45
+ configs: server.configs,
46
46
  interfaces: server.interfaces
47
47
  });
48
48
  /**
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/actions/dev/exposesSetId.ts"],"sourcesContent":["import {\n deriveInstallationConfigEntries,\n type DevServerConfig,\n type DevServerInterface,\n} from './deriveInterfaces.js'\nimport {type DevServerManifest} from './registry.js'\n\ninterface ExposeSet {\n installationConfigs?: readonly DevServerConfig[] | undefined\n interfaces?: readonly DevServerInterface[] | undefined\n}\n\n/**\n * Order-independent id of an app's exposed-module set. Keys each interface by\n * its type, name, and source file, and each installation config by its module\n * identity plus one key per entry (a named source file), so the id changes on\n * any rebuild-worthy edit — add, remove, rename, repoint, or gaining/losing the\n * config module — while reordering and HMR content edits keep it stable.\n */\nexport function exposesSetId({installationConfigs, interfaces}: ExposeSet): string {\n const keys = [\n ...(interfaces ?? []).map((iface) =>\n [iface.interface_type, iface.name, iface.entry_point].join('::'),\n ),\n ...(installationConfigs ?? []).flatMap((config) => [\n ['config', config.appType].join('::'),\n ...deriveInstallationConfigEntries(config).map((entry) =>\n ['config', config.appType, entry.name, entry.src].join('::'),\n ),\n ]),\n ]\n if (keys.length === 0) return ''\n return keys.toSorted().join('|')\n}\n\n/**\n * `changed`/`commit` are split so the caller commits only after the rebuild that\n * depends on the new set succeeds — a thrown rebuild retries on the next save.\n */\nexport function trackExposesSet(initial: ExposeSet): {\n changed: (next: ExposeSet) => boolean\n commit: (next: ExposeSet) => void\n} {\n let lastId = exposesSetId(initial)\n return {\n changed: (next) => exposesSetId(next) !== lastId,\n commit: (next) => {\n lastId = exposesSetId(next)\n },\n }\n}\n\nconst serverKey = (server: DevServerManifest): string =>\n `${server.id ?? ''}@${server.host ?? ''}:${server.port}`\n\nconst serverExposesId = (server: DevServerManifest): string =>\n exposesSetId({installationConfigs: server.installationConfigs, interfaces: server.interfaces})\n\n/**\n * Multi-app counterpart to {@link trackExposesSet}: true when a *known* app's\n * set changed — its remote was rebuilt, so the workbench must full-reload to\n * drop the stale remote-entry. A new/removed app isn't a rebuild.\n */\nexport function createExposesTracker(): {\n hasChanged: (servers: readonly DevServerManifest[]) => boolean\n} {\n let known = new Map<string, string>()\n return {\n hasChanged(servers) {\n const rebuilt = servers.some((server) => {\n const key = serverKey(server)\n return known.has(key) && known.get(key) !== serverExposesId(server)\n })\n known = new Map(servers.map((server) => [serverKey(server), serverExposesId(server)]))\n return rebuilt\n },\n }\n}\n"],"names":["deriveInstallationConfigEntries","exposesSetId","installationConfigs","interfaces","keys","map","iface","interface_type","name","entry_point","join","flatMap","config","appType","entry","src","length","toSorted","trackExposesSet","initial","lastId","changed","next","commit","serverKey","server","id","host","port","serverExposesId","createExposesTracker","known","Map","hasChanged","servers","rebuilt","some","key","has","get"],"mappings":"AAAA,SACEA,+BAA+B,QAG1B,wBAAuB;AAQ9B;;;;;;CAMC,GACD,OAAO,SAASC,aAAa,EAACC,mBAAmB,EAAEC,UAAU,EAAY;IACvE,MAAMC,OAAO;WACR,AAACD,CAAAA,cAAc,EAAE,AAAD,EAAGE,GAAG,CAAC,CAACC,QACzB;gBAACA,MAAMC,cAAc;gBAAED,MAAME,IAAI;gBAAEF,MAAMG,WAAW;aAAC,CAACC,IAAI,CAAC;WAE1D,AAACR,CAAAA,uBAAuB,EAAE,AAAD,EAAGS,OAAO,CAAC,CAACC,SAAW;gBACjD;oBAAC;oBAAUA,OAAOC,OAAO;iBAAC,CAACH,IAAI,CAAC;mBAC7BV,gCAAgCY,QAAQP,GAAG,CAAC,CAACS,QAC9C;wBAAC;wBAAUF,OAAOC,OAAO;wBAAEC,MAAMN,IAAI;wBAAEM,MAAMC,GAAG;qBAAC,CAACL,IAAI,CAAC;aAE1D;KACF;IACD,IAAIN,KAAKY,MAAM,KAAK,GAAG,OAAO;IAC9B,OAAOZ,KAAKa,QAAQ,GAAGP,IAAI,CAAC;AAC9B;AAEA;;;CAGC,GACD,OAAO,SAASQ,gBAAgBC,OAAkB;IAIhD,IAAIC,SAASnB,aAAakB;IAC1B,OAAO;QACLE,SAAS,CAACC,OAASrB,aAAaqB,UAAUF;QAC1CG,QAAQ,CAACD;YACPF,SAASnB,aAAaqB;QACxB;IACF;AACF;AAEA,MAAME,YAAY,CAACC,SACjB,GAAGA,OAAOC,EAAE,IAAI,GAAG,CAAC,EAAED,OAAOE,IAAI,IAAI,GAAG,CAAC,EAAEF,OAAOG,IAAI,EAAE;AAE1D,MAAMC,kBAAkB,CAACJ,SACvBxB,aAAa;QAACC,qBAAqBuB,OAAOvB,mBAAmB;QAAEC,YAAYsB,OAAOtB,UAAU;IAAA;AAE9F;;;;CAIC,GACD,OAAO,SAAS2B;IAGd,IAAIC,QAAQ,IAAIC;IAChB,OAAO;QACLC,YAAWC,OAAO;YAChB,MAAMC,UAAUD,QAAQE,IAAI,CAAC,CAACX;gBAC5B,MAAMY,MAAMb,UAAUC;gBACtB,OAAOM,MAAMO,GAAG,CAACD,QAAQN,MAAMQ,GAAG,CAACF,SAASR,gBAAgBJ;YAC9D;YACAM,QAAQ,IAAIC,IAAIE,QAAQ7B,GAAG,CAAC,CAACoB,SAAW;oBAACD,UAAUC;oBAASI,gBAAgBJ;iBAAQ;YACpF,OAAOU;QACT;IACF;AACF"}
1
+ {"version":3,"sources":["../../../src/actions/dev/exposesSetId.ts"],"sourcesContent":["import {\n deriveConfigEntries,\n type DevServerConfig,\n type DevServerInterface,\n} from './deriveInterfaces.js'\nimport {type DevServerManifest} from './registry.js'\n\ninterface ExposeSet {\n configs?: readonly DevServerConfig[] | undefined\n interfaces?: readonly DevServerInterface[] | undefined\n}\n\n/**\n * Order-independent id of an app's exposed-module set. Keys each interface by\n * its type, name, and source file, and each config by its module\n * identity plus one key per entry (a named source file), so the id changes on\n * any rebuild-worthy edit — add, remove, rename, repoint, or gaining/losing the\n * config module — while reordering and HMR content edits keep it stable.\n */\nexport function exposesSetId({configs, interfaces}: ExposeSet): string {\n const keys = [\n ...(interfaces ?? []).map((iface) => [iface.type, iface.name, iface.src].join('::')),\n ...(configs ?? []).flatMap((config) => [\n ['config', config.appType].join('::'),\n ...deriveConfigEntries(config).map((entry) =>\n ['config', config.appType, entry.name, entry.src].join('::'),\n ),\n ]),\n ]\n if (keys.length === 0) return ''\n return keys.toSorted().join('|')\n}\n\n/**\n * `changed`/`commit` are split so the caller commits only after the rebuild that\n * depends on the new set succeeds — a thrown rebuild retries on the next save.\n */\nexport function trackExposesSet(initial: ExposeSet): {\n changed: (next: ExposeSet) => boolean\n commit: (next: ExposeSet) => void\n} {\n let lastId = exposesSetId(initial)\n return {\n changed: (next) => exposesSetId(next) !== lastId,\n commit: (next) => {\n lastId = exposesSetId(next)\n },\n }\n}\n\nconst serverKey = (server: DevServerManifest): string =>\n `${server.id ?? ''}@${server.host ?? ''}:${server.port}`\n\nconst serverExposesId = (server: DevServerManifest): string =>\n exposesSetId({configs: server.configs, interfaces: server.interfaces})\n\n/**\n * Multi-app counterpart to {@link trackExposesSet}: true when a *known* app's\n * set changed — its remote was rebuilt, so the workbench must full-reload to\n * drop the stale remote-entry. A new/removed app isn't a rebuild.\n */\nexport function createExposesTracker(): {\n hasChanged: (servers: readonly DevServerManifest[]) => boolean\n} {\n let known = new Map<string, string>()\n return {\n hasChanged(servers) {\n const rebuilt = servers.some((server) => {\n const key = serverKey(server)\n return known.has(key) && known.get(key) !== serverExposesId(server)\n })\n known = new Map(servers.map((server) => [serverKey(server), serverExposesId(server)]))\n return rebuilt\n },\n }\n}\n"],"names":["deriveConfigEntries","exposesSetId","configs","interfaces","keys","map","iface","type","name","src","join","flatMap","config","appType","entry","length","toSorted","trackExposesSet","initial","lastId","changed","next","commit","serverKey","server","id","host","port","serverExposesId","createExposesTracker","known","Map","hasChanged","servers","rebuilt","some","key","has","get"],"mappings":"AAAA,SACEA,mBAAmB,QAGd,wBAAuB;AAQ9B;;;;;;CAMC,GACD,OAAO,SAASC,aAAa,EAACC,OAAO,EAAEC,UAAU,EAAY;IAC3D,MAAMC,OAAO;WACR,AAACD,CAAAA,cAAc,EAAE,AAAD,EAAGE,GAAG,CAAC,CAACC,QAAU;gBAACA,MAAMC,IAAI;gBAAED,MAAME,IAAI;gBAAEF,MAAMG,GAAG;aAAC,CAACC,IAAI,CAAC;WAC3E,AAACR,CAAAA,WAAW,EAAE,AAAD,EAAGS,OAAO,CAAC,CAACC,SAAW;gBACrC;oBAAC;oBAAUA,OAAOC,OAAO;iBAAC,CAACH,IAAI,CAAC;mBAC7BV,oBAAoBY,QAAQP,GAAG,CAAC,CAACS,QAClC;wBAAC;wBAAUF,OAAOC,OAAO;wBAAEC,MAAMN,IAAI;wBAAEM,MAAML,GAAG;qBAAC,CAACC,IAAI,CAAC;aAE1D;KACF;IACD,IAAIN,KAAKW,MAAM,KAAK,GAAG,OAAO;IAC9B,OAAOX,KAAKY,QAAQ,GAAGN,IAAI,CAAC;AAC9B;AAEA;;;CAGC,GACD,OAAO,SAASO,gBAAgBC,OAAkB;IAIhD,IAAIC,SAASlB,aAAaiB;IAC1B,OAAO;QACLE,SAAS,CAACC,OAASpB,aAAaoB,UAAUF;QAC1CG,QAAQ,CAACD;YACPF,SAASlB,aAAaoB;QACxB;IACF;AACF;AAEA,MAAME,YAAY,CAACC,SACjB,GAAGA,OAAOC,EAAE,IAAI,GAAG,CAAC,EAAED,OAAOE,IAAI,IAAI,GAAG,CAAC,EAAEF,OAAOG,IAAI,EAAE;AAE1D,MAAMC,kBAAkB,CAACJ,SACvBvB,aAAa;QAACC,SAASsB,OAAOtB,OAAO;QAAEC,YAAYqB,OAAOrB,UAAU;IAAA;AAEtE;;;;CAIC,GACD,OAAO,SAAS0B;IAGd,IAAIC,QAAQ,IAAIC;IAChB,OAAO;QACLC,YAAWC,OAAO;YAChB,MAAMC,UAAUD,QAAQE,IAAI,CAAC,CAACX;gBAC5B,MAAMY,MAAMb,UAAUC;gBACtB,OAAOM,MAAMO,GAAG,CAACD,QAAQN,MAAMQ,GAAG,CAACF,SAASR,gBAAgBJ;YAC9D;YACAM,QAAQ,IAAIC,IAAIE,QAAQ5B,GAAG,CAAC,CAACmB,SAAW;oBAACD,UAAUC;oBAASI,gBAAgBJ;iBAAQ;YACpF,OAAOU;QACT;IACF;AACF"}
@@ -15,13 +15,11 @@ const devDebug = subdebug('dev');
15
15
  return (getProcessStartTime(process.pid) ?? new Date()).toISOString();
16
16
  }
17
17
  const devServerManifestSchema = z.object({
18
- host: z.string(),
19
- id: z.optional(z.string()),
20
18
  /**
21
19
  * Field schema *values* load from the federation module; each field's `src`
22
20
  * rides along so a repoint bumps the exposes-set id and forces a rebuild.
23
21
  * Lenient — the workbench is the authority.
24
- */ installationConfigs: z.optional(z.array(z.object({
22
+ */ configs: z.optional(z.array(z.object({
25
23
  // Identifies the owning app when it has no app id (singletons).
26
24
  appType: z.optional(z.string()),
27
25
  fields: z.array(z.object({
@@ -30,23 +28,35 @@ const devServerManifestSchema = z.object({
30
28
  src: z.string(),
31
29
  title: z.string()
32
30
  })),
31
+ // Content hash of the config — the workbench's change-detection key
32
+ // (see deriveConfigs).
33
+ id: z.string(),
33
34
  // The app's `unstable_defineApp` name — the module-federation alias the
34
35
  // workbench loads this config's live values from.
35
- moduleName: z.optional(z.string())
36
+ moduleName: z.optional(z.string()),
37
+ // Config contract version the generated module exports, so the
38
+ // workbench knows what it can resolve before loading the module.
39
+ version: z.number()
36
40
  }))),
41
+ host: z.string(),
42
+ id: z.optional(z.string()),
37
43
  /**
38
44
  * Interfaces the app exposes, mapped from the declared `views` (dock panels,
39
- * `interface_type: "panel"`) and `services` (background workers,
40
- * `interface_type: "worker"`). A service is just an interface, so both live
45
+ * `type: "panel"`) and `services` (background workers,
46
+ * `type: "worker"`). A service is just an interface, so both live
41
47
  * in this one list. Carried separately from the manifest — interfaces live in
42
48
  * the application service, not the manifest — so the workbench can render
43
- * local panels and run local workers without a deploy. `entry_point` is the
44
- * declared `src`. Lenient by design; the workbench is the authority on the
45
- * interface shape.
49
+ * local panels and run local workers without a deploy. `src` is the
50
+ * declared source file; `title` defaults to `name`. Lenient by design; the
51
+ * workbench is the authority on the interface shape.
46
52
  */ interfaces: z.optional(z.array(z.object({
47
- entry_point: z.string(),
48
- interface_type: z.string(),
49
- name: z.string()
53
+ name: z.string(),
54
+ src: z.string(),
55
+ title: z.string(),
56
+ type: z.string(),
57
+ // Contract version the interface's generated module exports; the app
58
+ // view has no versioned contract and carries none.
59
+ version: z.optional(z.number())
50
60
  }))),
51
61
  /**
52
62
  * Inlined manifest — either a {@link StudioManifest} or {@link CoreAppManifest},
@@ -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 {canonicalizeWatchDir} from './canonicalizeWatchDir.js'\nimport {getProcessStartTime, isOurProcess} from './processLiveness.js'\n\nconst devDebug = subdebug('dev')\n\n/** Bump when the manifest/lock shape changes in a breaking way. */\nconst REGISTRY_VERSION = 1\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 devServerManifestSchema = z.object({\n host: z.string(),\n id: 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 installationConfigs: 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 // The app's `unstable_defineApp` name — the module-federation alias the\n // workbench loads this config's live values from.\n moduleName: z.optional(z.string()),\n }),\n ),\n ),\n /**\n * Interfaces the app exposes, mapped from the declared `views` (dock panels,\n * `interface_type: \"panel\"`) and `services` (background workers,\n * `interface_type: \"worker\"`). A service is just an interface, so both live\n * in this one list. Carried separately from the manifest — interfaces live in\n * the application service, not the manifest — so the workbench can render\n * local panels and run local workers without a deploy. `entry_point` is the\n * declared `src`. Lenient by design; the workbench is the authority on the\n * interface shape.\n */\n interfaces: z.optional(\n z.array(z.object({entry_point: z.string(), interface_type: z.string(), name: z.string()})),\n ),\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 pid: z.number(),\n port: z.number(),\n projectId: z.optional(z.string()),\n startedAt: z.string(),\n type: z.enum(['coreApp', 'studio']),\n version: z.literal(REGISTRY_VERSION),\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 * 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\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, {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))\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 return {\n release() {\n released = true\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))\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, {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 machine\". 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 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(): z.infer<typeof workbenchLockSchema> | undefined {\n const lockPath = join(getRegistryDir(), 'workbench.lock')\n\n let contents: string\n try {\n contents = readFileSync(lockPath, 'utf8')\n } catch {\n // File doesn't exist — nothing to prune, nothing to return\n return undefined\n }\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 = parseLockContents(contents)\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(lockPath)\n return undefined\n}\n\nfunction parseLockContents(contents: string): z.infer<typeof workbenchLockSchema> | undefined {\n try {\n const {data, success} = workbenchLockSchema.safeParse(JSON.parse(contents))\n return success ? data : undefined\n } catch {\n return undefined\n }\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; port: number},\n retries = 1,\n): WorkbenchLock | undefined {\n const registryDir = getRegistryDir()\n mkdirSync(registryDir, {recursive: true})\n\n const lockPath = join(registryDir, 'workbench.lock')\n const startedAt = ownStartedAt()\n const lockData = {\n host: info.host,\n pid: process.pid,\n port: info.port,\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'})\n devDebug('Workbench lock acquired')\n return {\n release() {\n try {\n unlinkSync(lockPath)\n } catch {\n // Already cleaned up\n }\n },\n updatePort(port: number) {\n writeFileSync(lockPath, JSON.stringify({...lockData, port}))\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()\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","canonicalizeWatchDir","getProcessStartTime","isOurProcess","devDebug","REGISTRY_VERSION","ownStartedAt","process","pid","Date","toISOString","devServerManifestSchema","object","host","string","id","optional","installationConfigs","array","appType","fields","name","public","boolean","src","title","moduleName","interfaces","entry_point","interface_type","manifest","union","manifestUpdatedAt","number","port","projectId","startedAt","type","enum","version","literal","workDir","getRegistryDir","registerDevServer","registryDir","recursive","current","filePath","JSON","stringify","released","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","readWorkbenchLock","lockPath","contents","undefined","parseLockContents","pruneWorkbenchLock","acquireWorkbenchLock","info","retries","lockData","flag","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,4BAA2B;AAC9D,SAAQC,mBAAmB,EAAEC,YAAY,QAAO,uBAAsB;AAEtE,MAAMC,WAAWL,SAAS;AAE1B,iEAAiE,GACjE,MAAMM,mBAAmB;AAEzB;;;;;CAKC,GACD,SAASC;IACP,OAAO,AAACJ,CAAAA,oBAAoBK,QAAQC,GAAG,KAAK,IAAIC,MAAK,EAAGC,WAAW;AACrE;AAEA,MAAMC,0BAA0BX,EAAEY,MAAM,CAAC;IACvCC,MAAMb,EAAEc,MAAM;IACdC,IAAIf,EAAEgB,QAAQ,CAAChB,EAAEc,MAAM;IACvB;;;;GAIC,GACDG,qBAAqBjB,EAAEgB,QAAQ,CAC7BhB,EAAEkB,KAAK,CACLlB,EAAEY,MAAM,CAAC;QACP,gEAAgE;QAChEO,SAASnB,EAAEgB,QAAQ,CAAChB,EAAE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kdirSync,\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 {canonicalizeWatchDir} from './canonicalizeWatchDir.js'\nimport {getProcessStartTime, isOurProcess} from './processLiveness.js'\n\nconst devDebug = subdebug('dev')\n\n/** Bump when the manifest/lock shape changes in a breaking way. */\nconst REGISTRY_VERSION = 1\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 devServerManifestSchema = z.object({\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 `unstable_defineApp` name — the module-federation alias the\n // workbench loads this config's live values from.\n moduleName: z.optional(z.string()),\n // Config contract version the generated module exports, so the\n // workbench knows what it can resolve before loading the module.\n version: z.number(),\n }),\n ),\n ),\n host: z.string(),\n id: z.optional(z.string()),\n /**\n * Interfaces the app exposes, mapped from the declared `views` (dock panels,\n * `type: \"panel\"`) and `services` (background workers,\n * `type: \"worker\"`). A service is just an interface, so both live\n * in this one list. Carried separately from the manifest — interfaces live in\n * the application service, not the manifest — so the workbench can render\n * local panels and run local workers without a deploy. `src` is the\n * declared source file; `title` defaults to `name`. Lenient by design; the\n * workbench is the authority on the interface shape.\n */\n interfaces: z.optional(\n z.array(\n z.object({\n name: z.string(),\n src: z.string(),\n title: z.string(),\n type: z.string(),\n // Contract version the interface's generated module exports; the app\n // view has no versioned contract and carries none.\n version: z.optional(z.number()),\n }),\n ),\n ),\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 pid: z.number(),\n port: z.number(),\n projectId: z.optional(z.string()),\n startedAt: z.string(),\n type: z.enum(['coreApp', 'studio']),\n version: z.literal(REGISTRY_VERSION),\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 * 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\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, {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))\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 return {\n release() {\n released = true\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))\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, {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 machine\". 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 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(): z.infer<typeof workbenchLockSchema> | undefined {\n const lockPath = join(getRegistryDir(), 'workbench.lock')\n\n let contents: string\n try {\n contents = readFileSync(lockPath, 'utf8')\n } catch {\n // File doesn't exist — nothing to prune, nothing to return\n return undefined\n }\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 = parseLockContents(contents)\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(lockPath)\n return undefined\n}\n\nfunction parseLockContents(contents: string): z.infer<typeof workbenchLockSchema> | undefined {\n try {\n const {data, success} = workbenchLockSchema.safeParse(JSON.parse(contents))\n return success ? data : undefined\n } catch {\n return undefined\n }\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; port: number},\n retries = 1,\n): WorkbenchLock | undefined {\n const registryDir = getRegistryDir()\n mkdirSync(registryDir, {recursive: true})\n\n const lockPath = join(registryDir, 'workbench.lock')\n const startedAt = ownStartedAt()\n const lockData = {\n host: info.host,\n pid: process.pid,\n port: info.port,\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'})\n devDebug('Workbench lock acquired')\n return {\n release() {\n try {\n unlinkSync(lockPath)\n } catch {\n // Already cleaned up\n }\n },\n updatePort(port: number) {\n writeFileSync(lockPath, JSON.stringify({...lockData, port}))\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()\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","canonicalizeWatchDir","getProcessStartTime","isOurProcess","devDebug","REGISTRY_VERSION","ownStartedAt","process","pid","Date","toISOString","devServerManifestSchema","object","configs","optional","array","appType","string","fields","name","public","boolean","src","title","id","moduleName","version","number","host","interfaces","type","manifest","union","manifestUpdatedAt","port","projectId","startedAt","enum","literal","workDir","getRegistryDir","registerDevServer","registryDir","recursive","current","filePath","JSON","stringify","released","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","readWorkbenchLock","lockPath","contents","undefined","parseLockContents","pruneWorkbenchLock","acquireWorkbenchLock","info","retries","lockData","flag","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,4BAA2B;AAC9D,SAAQC,mBAAmB,EAAEC,YAAY,QAAO,uBAAsB;AAEtE,MAAMC,WAAWL,SAAS;AAE1B,iEAAiE,GACjE,MAAMM,mBAAmB;AAEzB;;;;;CAKC,GACD,SAASC;IACP,OAAO,AAACJ,CAAAA,oBAAoBK,QAAQC,GAAG,KAAK,IAAIC,MAAK,EAAGC,WAAW;AACrE;AAEA,MAAMC,0BAA0BX,EAAEY,MAAM,CAAC;IACvC;;;;GAIC,GACDC,SAASb,EAAEc,QAAQ,CACjBd,EAAEe,KAAK,CACLf,EAAEY,MAAM,CAAC;QACP,gEAAgE;QAChEI,SAAShB,EAAEc,QAAQ,CAACd,EAAEiB,MAAM;QAC5BC,QAAQlB,EA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