@sanity/workbench-cli 2.5.1 → 2.6.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.
- package/dist/_exports/build.d.ts +5 -2
- package/dist/_exports/build.js +1 -0
- package/dist/_exports/build.js.map +1 -1
- package/dist/_exports/dev.d.ts +1 -1
- package/dist/actions/build/artifact.js.map +1 -1
- package/dist/actions/build/render-remote.js +23 -4
- package/dist/actions/build/render-remote.js.map +1 -1
- package/dist/actions/build/views/artifact.js +2 -1
- package/dist/actions/build/views/artifact.js.map +1 -1
- package/dist/actions/build/vite/discover-shared-dependencies.js +206 -0
- package/dist/actions/build/vite/discover-shared-dependencies.js.map +1 -0
- package/dist/actions/build/vite/plugins/plugin-module-federation.js +45 -23
- package/dist/actions/build/vite/plugins/plugin-module-federation.js.map +1 -1
- package/dist/actions/build/vite/plugins/plugin-sanity-extension-artifacts.js +8 -2
- package/dist/actions/build/vite/plugins/plugin-sanity-extension-artifacts.js.map +1 -1
- package/dist/actions/build/vite/plugins/plugin-sanity-federation-runtime.js +20 -13
- package/dist/actions/build/vite/plugins/plugin-sanity-federation-runtime.js.map +1 -1
- package/dist/actions/build/vite/shared-dependencies.js +116 -0
- package/dist/actions/build/vite/shared-dependencies.js.map +1 -0
- package/dist/actions/dev/startWorkbenchDev.js +0 -1
- package/dist/actions/dev/startWorkbenchDev.js.map +1 -1
- package/dist/actions/dev/startWorkbenchDevServer.js +3 -7
- package/dist/actions/dev/startWorkbenchDevServer.js.map +1 -1
- package/dist/actions/preview/startWorkbenchPreview.js +0 -1
- package/dist/actions/preview/startWorkbenchPreview.js.map +1 -1
- package/dist/services/applications.js +1 -1
- package/dist/services/applications.js.map +1 -1
- package/package.json +8 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/actions/build/vite/plugins/plugin-sanity-extension-artifacts.ts"],"sourcesContent":["import fs from 'node:fs'\nimport path from 'node:path'\n\nimport {type Plugin} from 'vite'\n\nimport {type GeneratedArtifact} from '../../artifact.js'\nimport {RUNTIME_DIR} from '../constants.js'\n\nfunction relativeImport(fromFile: string, toFile: string): string {\n const rel = path.relative(path.dirname(fromFile), toFile).split(path.sep).join('/')\n return rel.startsWith('.') ? rel : `./${rel}`\n}\n\nfunction writeArtifacts(root:
|
|
1
|
+
{"version":3,"sources":["../../../../../src/actions/build/vite/plugins/plugin-sanity-extension-artifacts.ts"],"sourcesContent":["import fs from 'node:fs'\nimport path from 'node:path'\n\nimport {type Plugin} from 'vite'\n\nimport {type GeneratedArtifact} from '../../artifact.js'\nimport {RUNTIME_DIR} from '../constants.js'\nimport {getFederationApi} from './plugin-module-federation.js'\n\nfunction relativeImport(fromFile: string, toFile: string): string {\n const rel = path.relative(path.dirname(fromFile), toFile).split(path.sep).join('/')\n return rel.startsWith('.') ? rel : `./${rel}`\n}\n\nfunction writeArtifacts({\n artifacts,\n isolateStyles,\n root,\n}: {\n artifacts: readonly GeneratedArtifact[]\n isolateStyles: boolean\n root: string\n}): void {\n for (const artifact of artifacts) {\n const artifactPath = path.resolve(root, RUNTIME_DIR, artifact.path)\n fs.mkdirSync(path.dirname(artifactPath), {recursive: true})\n fs.writeFileSync(\n artifactPath,\n artifact.source({\n isolateStyles,\n resolveImport: (src) => relativeImport(artifactPath, path.resolve(root, src)),\n }),\n )\n }\n}\n\n/**\n * Writes the federation runtime artifacts (view render-contract modules, service\n * worker bundles + loaders) into `RUNTIME_DIR`, resolving each artifact's import\n * paths relative to where it lands on disk. The set is expanded once by\n * `workbenchArtifacts` and handed in — this plugin only writes it.\n */\nexport function sanityExtensionArtifacts(options: {\n artifacts: readonly GeneratedArtifact[]\n}): Plugin {\n return {\n configResolved(config) {\n writeArtifacts({\n artifacts: options.artifacts,\n isolateStyles: getFederationApi(config.plugins)?.isolateStyles ?? false,\n root: config.root,\n })\n },\n name: 'sanity/extension-artifacts',\n }\n}\n"],"names":["fs","path","RUNTIME_DIR","getFederationApi","relativeImport","fromFile","toFile","rel","relative","dirname","split","sep","join","startsWith","writeArtifacts","artifacts","isolateStyles","root","artifact","artifactPath","resolve","mkdirSync","recursive","writeFileSync","source","resolveImport","src","sanityExtensionArtifacts","options","configResolved","config","plugins","name"],"mappings":"AAAA,OAAOA,QAAQ,UAAS;AACxB,OAAOC,UAAU,YAAW;AAK5B,SAAQC,WAAW,QAAO,kBAAiB;AAC3C,SAAQC,gBAAgB,QAAO,gCAA+B;AAE9D,SAASC,eAAeC,QAAgB,EAAEC,MAAc;IACtD,MAAMC,MAAMN,KAAKO,QAAQ,CAACP,KAAKQ,OAAO,CAACJ,WAAWC,QAAQI,KAAK,CAACT,KAAKU,GAAG,EAAEC,IAAI,CAAC;IAC/E,OAAOL,IAAIM,UAAU,CAAC,OAAON,MAAM,CAAC,EAAE,EAAEA,KAAK;AAC/C;AAEA,SAASO,eAAe,EACtBC,SAAS,EACTC,aAAa,EACbC,IAAI,EAKL;IACC,KAAK,MAAMC,YAAYH,UAAW;QAChC,MAAMI,eAAelB,KAAKmB,OAAO,CAACH,MAAMf,aAAagB,SAASjB,IAAI;QAClED,GAAGqB,SAAS,CAACpB,KAAKQ,OAAO,CAACU,eAAe;YAACG,WAAW;QAAI;QACzDtB,GAAGuB,aAAa,CACdJ,cACAD,SAASM,MAAM,CAAC;YACdR;YACAS,eAAe,CAACC,MAAQtB,eAAee,cAAclB,KAAKmB,OAAO,CAACH,MAAMS;QAC1E;IAEJ;AACF;AAEA;;;;;CAKC,GACD,OAAO,SAASC,yBAAyBC,OAExC;IACC,OAAO;QACLC,gBAAeC,MAAM;YACnBhB,eAAe;gBACbC,WAAWa,QAAQb,SAAS;gBAC5BC,eAAeb,iBAAiB2B,OAAOC,OAAO,GAAGf,iBAAiB;gBAClEC,MAAMa,OAAOb,IAAI;YACnB;QACF;QACAe,MAAM;IACR;AACF"}
|
|
@@ -3,21 +3,24 @@ import path from 'node:path';
|
|
|
3
3
|
import { renderRemote } from '../../render-remote.js';
|
|
4
4
|
import { RESOURCE_BINDINGS_ENTRY_IMPORT, RESOURCE_BINDINGS_FILENAME, RESOURCE_BINDINGS_MODULE_SOURCE } from '../../resource-bindings.js';
|
|
5
5
|
import { FEDERATION_FILE_NAME, RUNTIME_DIR } from '../constants.js';
|
|
6
|
+
import { getFederationApi } from './plugin-module-federation.js';
|
|
6
7
|
const REMOTE_ENTRY_FILE = `${FEDERATION_FILE_NAME}.jsx`;
|
|
7
8
|
// The studio wraps `Studio` with the user's config; HMR re-renders through the
|
|
8
9
|
// new module so a config edit takes effect. The `%RESOURCE_BINDINGS_IMPORT%`
|
|
9
10
|
// placeholder is filled in per-build (Blueprints only — see below).
|
|
10
|
-
const
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
11
|
+
const studioEntry = (isolateStyles)=>renderRemote({
|
|
12
|
+
app: `(props) => React.createElement(Studio, { config, ...props })`,
|
|
13
|
+
hmr: true,
|
|
14
|
+
isolateStyles,
|
|
15
|
+
preamble: `%RESOURCE_BINDINGS_IMPORT%import { Studio } from 'sanity'
|
|
14
16
|
import config from %STUDIO_CONFIG%`
|
|
15
|
-
});
|
|
17
|
+
});
|
|
16
18
|
// An SDK app's default export is the component; it Fast-Refreshes through its
|
|
17
19
|
// own dev server, so the wrapper needs no HMR boundary.
|
|
18
|
-
const
|
|
19
|
-
|
|
20
|
-
|
|
20
|
+
const appEntry = (isolateStyles)=>renderRemote({
|
|
21
|
+
isolateStyles,
|
|
22
|
+
preamble: `%RESOURCE_BINDINGS_IMPORT%import App from %APP_ENTRY%`
|
|
23
|
+
});
|
|
21
24
|
// A branded app that declares no `entry` (e.g. a dock-only panel/worker app)
|
|
22
25
|
// has no navigable full-page view, so there's no `App` to import. The runtime
|
|
23
26
|
// still needs a valid module for the federation build input, but it exposes no
|
|
@@ -31,19 +34,22 @@ const HEADLESS_APP_ENTRY = `\
|
|
|
31
34
|
throw new Error('This application has no app view: it declares no \`entry\`.')
|
|
32
35
|
}
|
|
33
36
|
`;
|
|
34
|
-
|
|
37
|
+
function renderEntry(options, isolateStyles) {
|
|
35
38
|
const { isBlueprints } = options;
|
|
36
39
|
let content;
|
|
37
40
|
if (options.isApp) {
|
|
38
|
-
content = options.appEntry ?
|
|
41
|
+
content = options.appEntry ? appEntry(isolateStyles).replace(/%APP_ENTRY%/, JSON.stringify(options.appEntry)) : HEADLESS_APP_ENTRY;
|
|
39
42
|
} else {
|
|
40
|
-
content =
|
|
43
|
+
content = studioEntry(isolateStyles).replace(/%STUDIO_CONFIG%/, JSON.stringify(options.studioConfigPath));
|
|
41
44
|
}
|
|
42
45
|
// Blueprints only: the remote entry statically imports the resource-bindings
|
|
43
46
|
// module first, so bindings evaluate before app code. Off Blueprints the
|
|
44
47
|
// placeholder resolves to nothing and the module is neither imported nor
|
|
45
48
|
// written below.
|
|
46
|
-
|
|
49
|
+
return content.replace(/%RESOURCE_BINDINGS_IMPORT%/, isBlueprints ? `${RESOURCE_BINDINGS_ENTRY_IMPORT}\n` : '');
|
|
50
|
+
}
|
|
51
|
+
export function sanityFederationRuntime(options) {
|
|
52
|
+
const { isBlueprints } = options;
|
|
47
53
|
let entryFileAbsPath = '';
|
|
48
54
|
return {
|
|
49
55
|
configResolved (config) {
|
|
@@ -52,7 +58,8 @@ export function sanityFederationRuntime(options) {
|
|
|
52
58
|
fs.mkdirSync(dir, {
|
|
53
59
|
recursive: true
|
|
54
60
|
});
|
|
55
|
-
|
|
61
|
+
const isolateStyles = getFederationApi(config.plugins)?.isolateStyles ?? false;
|
|
62
|
+
fs.writeFileSync(entryFileAbsPath, renderEntry(options, isolateStyles));
|
|
56
63
|
if (isBlueprints) {
|
|
57
64
|
// Brett bakes the resolved values into this module at deploy.
|
|
58
65
|
fs.writeFileSync(path.join(dir, RESOURCE_BINDINGS_FILENAME), RESOURCE_BINDINGS_MODULE_SOURCE);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/actions/build/vite/plugins/plugin-sanity-federation-runtime.ts"],"sourcesContent":["import fs from 'node:fs'\nimport path from 'node:path'\n\nimport {type EnvironmentModuleNode, type Plugin} from 'vite'\n\nimport {renderRemote} from '../../render-remote.js'\nimport {\n RESOURCE_BINDINGS_ENTRY_IMPORT,\n RESOURCE_BINDINGS_FILENAME,\n RESOURCE_BINDINGS_MODULE_SOURCE,\n} from '../../resource-bindings.js'\nimport {FEDERATION_FILE_NAME, RUNTIME_DIR} from '../constants.js'\n\nconst REMOTE_ENTRY_FILE = `${FEDERATION_FILE_NAME}.jsx`\n\n// The studio wraps `Studio` with the user's config; HMR re-renders through the\n// new module so a config edit takes effect. The `%RESOURCE_BINDINGS_IMPORT%`\n// placeholder is filled in per-build (Blueprints only — see below).\nconst
|
|
1
|
+
{"version":3,"sources":["../../../../../src/actions/build/vite/plugins/plugin-sanity-federation-runtime.ts"],"sourcesContent":["import fs from 'node:fs'\nimport path from 'node:path'\n\nimport {type EnvironmentModuleNode, type Plugin} from 'vite'\n\nimport {renderRemote} from '../../render-remote.js'\nimport {\n RESOURCE_BINDINGS_ENTRY_IMPORT,\n RESOURCE_BINDINGS_FILENAME,\n RESOURCE_BINDINGS_MODULE_SOURCE,\n} from '../../resource-bindings.js'\nimport {FEDERATION_FILE_NAME, RUNTIME_DIR} from '../constants.js'\nimport {getFederationApi} from './plugin-module-federation.js'\n\nconst REMOTE_ENTRY_FILE = `${FEDERATION_FILE_NAME}.jsx`\n\n// The studio wraps `Studio` with the user's config; HMR re-renders through the\n// new module so a config edit takes effect. The `%RESOURCE_BINDINGS_IMPORT%`\n// placeholder is filled in per-build (Blueprints only — see below).\nconst studioEntry = (isolateStyles: boolean) =>\n renderRemote({\n app: `(props) => React.createElement(Studio, { config, ...props })`,\n hmr: true,\n isolateStyles,\n preamble: `%RESOURCE_BINDINGS_IMPORT%import { Studio } from 'sanity'\nimport config from %STUDIO_CONFIG%`,\n })\n\n// An SDK app's default export is the component; it Fast-Refreshes through its\n// own dev server, so the wrapper needs no HMR boundary.\nconst appEntry = (isolateStyles: boolean) =>\n renderRemote({\n isolateStyles,\n preamble: `%RESOURCE_BINDINGS_IMPORT%import App from %APP_ENTRY%`,\n })\n\n// A branded app that declares no `entry` (e.g. a dock-only panel/worker app)\n// has no navigable full-page view, so there's no `App` to import. The runtime\n// still needs a valid module for the federation build input, but it exposes no\n// `./App` (see `plugin.ts`) — its `render` is unreachable and throws if reached.\nconst HEADLESS_APP_ENTRY = `\\\n// This file is auto-generated on 'sanity dev'\n// Modifications to this file are automatically discarded\n// This application declares no app view (no \\`entry\\`): it isn't navigable as a\n// full-page app, only its panels/web workers are exposed.\n%RESOURCE_BINDINGS_IMPORT%export function render() {\n throw new Error('This application has no app view: it declares no \\`entry\\`.')\n}\n`\n\nexport type FederationRuntimeOptions =\n | {appEntry?: string; isApp: true; isBlueprints?: boolean}\n | {isApp: false; isBlueprints?: boolean; studioConfigPath: string}\n\nfunction renderEntry(options: FederationRuntimeOptions, isolateStyles: boolean): string {\n const {isBlueprints} = options\n\n let content: string\n if (options.isApp) {\n content = options.appEntry\n ? appEntry(isolateStyles).replace(/%APP_ENTRY%/, JSON.stringify(options.appEntry))\n : HEADLESS_APP_ENTRY\n } else {\n content = studioEntry(isolateStyles).replace(\n /%STUDIO_CONFIG%/,\n JSON.stringify(options.studioConfigPath),\n )\n }\n\n // Blueprints only: the remote entry statically imports the resource-bindings\n // module first, so bindings evaluate before app code. Off Blueprints the\n // placeholder resolves to nothing and the module is neither imported nor\n // written below.\n return content.replace(\n /%RESOURCE_BINDINGS_IMPORT%/,\n isBlueprints ? `${RESOURCE_BINDINGS_ENTRY_IMPORT}\\n` : '',\n )\n}\n\nexport function sanityFederationRuntime(options: FederationRuntimeOptions): Plugin {\n const {isBlueprints} = options\n let entryFileAbsPath = ''\n\n return {\n configResolved(config) {\n const dir = path.resolve(config.root, RUNTIME_DIR)\n entryFileAbsPath = path.join(dir, REMOTE_ENTRY_FILE)\n\n fs.mkdirSync(dir, {recursive: true})\n const isolateStyles = getFederationApi(config.plugins)?.isolateStyles ?? false\n fs.writeFileSync(entryFileAbsPath, renderEntry(options, isolateStyles))\n\n if (isBlueprints) {\n // Brett bakes the resolved values into this module at deploy.\n fs.writeFileSync(\n path.join(dir, RESOURCE_BINDINGS_FILENAME),\n RESOURCE_BINDINGS_MODULE_SOURCE,\n )\n }\n },\n hotUpdate({file, modules, timestamp}) {\n if (options.isApp) return\n if (this.environment.name !== 'client') return\n\n const {moduleGraph} = this.environment\n const studioMods = moduleGraph.getModulesByFile(entryFileAbsPath)\n if (!studioMods?.size) return\n\n // Is the changed file reachable from the studio entry?\n const visited = new Set<EnvironmentModuleNode>()\n const queue: EnvironmentModuleNode[] = [...studioMods]\n while (queue.length > 0) {\n const mod = queue.pop()!\n if (visited.has(mod)) continue\n visited.add(mod)\n if (mod.file === file) {\n // The walk from `file` up through importers dead-ends at federation\n // gaps, so invalidate changed modules ourselves and route HMR to the\n // self-accepting studio entry.\n const seen = new Set<EnvironmentModuleNode>()\n for (const m of modules) {\n moduleGraph.invalidateModule(m, seen, timestamp, true)\n }\n return [...studioMods]\n }\n for (const dep of mod.importedModules) queue.push(dep)\n }\n },\n name: 'sanity/federation-runtime',\n }\n}\n"],"names":["fs","path","renderRemote","RESOURCE_BINDINGS_ENTRY_IMPORT","RESOURCE_BINDINGS_FILENAME","RESOURCE_BINDINGS_MODULE_SOURCE","FEDERATION_FILE_NAME","RUNTIME_DIR","getFederationApi","REMOTE_ENTRY_FILE","studioEntry","isolateStyles","app","hmr","preamble","appEntry","HEADLESS_APP_ENTRY","renderEntry","options","isBlueprints","content","isApp","replace","JSON","stringify","studioConfigPath","sanityFederationRuntime","entryFileAbsPath","configResolved","config","dir","resolve","root","join","mkdirSync","recursive","plugins","writeFileSync","hotUpdate","file","modules","timestamp","environment","name","moduleGraph","studioMods","getModulesByFile","size","visited","Set","queue","length","mod","pop","has","add","seen","m","invalidateModule","dep","importedModules","push"],"mappings":"AAAA,OAAOA,QAAQ,UAAS;AACxB,OAAOC,UAAU,YAAW;AAI5B,SAAQC,YAAY,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AAM;IACR;AACF"}
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { valid as validSemver } from 'semver';
|
|
2
|
+
// Add approved packages here; versions contribute to the scope unless explicitly excluded.
|
|
3
|
+
const sharedDependencies = [
|
|
4
|
+
{
|
|
5
|
+
name: 'react'
|
|
6
|
+
},
|
|
7
|
+
{
|
|
8
|
+
name: 'react-dom'
|
|
9
|
+
},
|
|
10
|
+
// React DOM owns scheduler's mutable queue, so only its version joins the scope.
|
|
11
|
+
{
|
|
12
|
+
name: 'scheduler',
|
|
13
|
+
share: false
|
|
14
|
+
},
|
|
15
|
+
{
|
|
16
|
+
name: 'styled-components',
|
|
17
|
+
optional: true,
|
|
18
|
+
scope: false
|
|
19
|
+
}
|
|
20
|
+
];
|
|
21
|
+
// Vite injects these aliases for its own modules; neither can redirect a shared package import.
|
|
22
|
+
const viteInternalAliases = new Set([
|
|
23
|
+
/^\/?@vite\/client/.source,
|
|
24
|
+
/^\/?@vite\/env/.source
|
|
25
|
+
]);
|
|
26
|
+
export function findSharedDependencyName(specifier) {
|
|
27
|
+
return sharedDependencies.find(({ name })=>specifier === name || specifier.startsWith(`${name}/`))?.name;
|
|
28
|
+
}
|
|
29
|
+
export function createFederationSharing(dependencies) {
|
|
30
|
+
const versions = resolveCompatibleVersions(dependencies);
|
|
31
|
+
if (!(versions instanceof Map)) return versions;
|
|
32
|
+
// React and its renderer must agree; styled-components selects its own exact version in this pool.
|
|
33
|
+
const shareScope = 'sanity-' + sharedDependencies.filter(({ scope })=>scope !== false).map(({ name })=>`${name}-${versions.get(name)}`).join('-');
|
|
34
|
+
return {
|
|
35
|
+
shared: createSharedEntries(dependencies, shareScope),
|
|
36
|
+
// The array form makes Module Federation use named pools instead of the host's default pool.
|
|
37
|
+
shareScope: [
|
|
38
|
+
shareScope
|
|
39
|
+
],
|
|
40
|
+
// Prefer a compatible provider that another app already loaded before downloading a local copy.
|
|
41
|
+
shareStrategy: 'loaded-first'
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
export function aliasMayRewriteSharedImport(find) {
|
|
45
|
+
if (typeof find === 'string') {
|
|
46
|
+
return Boolean(findSharedDependencyName(find)) || sharedDependencies.some(({ name })=>name.startsWith(`${find}/`));
|
|
47
|
+
}
|
|
48
|
+
if (find.ignoreCase || find.multiline) return true;
|
|
49
|
+
if (viteInternalAliases.has(find.source)) return false;
|
|
50
|
+
// Only accept a literal prefix like /^@app\//; more complex regexes may also match shared imports.
|
|
51
|
+
const namespace = find.source.match(/^\^([@\w-]+)\\\/$/u)?.[1];
|
|
52
|
+
if (!namespace) return true;
|
|
53
|
+
return sharedDependencies.some(({ name })=>name === namespace || name.startsWith(`${namespace}/`));
|
|
54
|
+
}
|
|
55
|
+
function resolveCompatibleVersions(dependencies) {
|
|
56
|
+
const versions = new Map();
|
|
57
|
+
for (const { name, optional } of sharedDependencies){
|
|
58
|
+
const copies = dependencies.filter((dependency)=>dependency.name === name);
|
|
59
|
+
if (copies.length === 0 && optional) {
|
|
60
|
+
versions.set(name, 'none');
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
if (copies.length === 0) return {
|
|
64
|
+
disabledReason: `No installed copy of ${name} was found`
|
|
65
|
+
};
|
|
66
|
+
const { root, version } = copies[0];
|
|
67
|
+
if (copies.some((copy)=>copy.root !== root || copy.version !== version)) {
|
|
68
|
+
return {
|
|
69
|
+
disabledReason: `Multiple installed copies of ${name} were found`
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
// pnpm patch hashes identify different package code under the same version, so patched copies stay local.
|
|
73
|
+
if (root.includes('patch_hash=')) return {
|
|
74
|
+
disabledReason: `${name} has a local pnpm patch`
|
|
75
|
+
};
|
|
76
|
+
// Semver ignores build metadata, so only its unchanged canonical form is safe to share.
|
|
77
|
+
if (validSemver(version) !== version) {
|
|
78
|
+
return {
|
|
79
|
+
disabledReason: `${name} has an unsupported version: ${JSON.stringify(version)}`
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
versions.set(name, version);
|
|
83
|
+
}
|
|
84
|
+
// Sharing the renderer without its React import would split hook and context identity.
|
|
85
|
+
if (!dependencies.some(({ name, specifier })=>name === 'react' && specifier === 'react')) {
|
|
86
|
+
return {
|
|
87
|
+
disabledReason: 'The react import could not be resolved to a shared provider'
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
if (versions.get('react') !== versions.get('react-dom')) {
|
|
91
|
+
return {
|
|
92
|
+
disabledReason: `React (${versions.get('react')}) and React DOM (${versions.get('react-dom')}) versions differ`
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
return versions;
|
|
96
|
+
}
|
|
97
|
+
function createSharedEntries(dependencies, shareScope) {
|
|
98
|
+
const entries = {};
|
|
99
|
+
const providers = new Set(sharedDependencies.filter(({ share })=>share !== false).map(({ name })=>name));
|
|
100
|
+
for (const { name, specifier, version } of dependencies){
|
|
101
|
+
if (!specifier || !providers.has(name)) continue;
|
|
102
|
+
entries[specifier] = {
|
|
103
|
+
eager: false,
|
|
104
|
+
requiredVersion: version,
|
|
105
|
+
// @module-federation/vite defaults providers to "default" unless each entry repeats this scope.
|
|
106
|
+
shareScope,
|
|
107
|
+
singleton: false,
|
|
108
|
+
strictVersion: true,
|
|
109
|
+
version
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
// Vite resolves imports concurrently, so sort providers to keep generated chunks reproducible.
|
|
113
|
+
return Object.fromEntries(Object.entries(entries).toSorted(([left], [right])=>left.localeCompare(right)));
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
//# sourceMappingURL=shared-dependencies.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../src/actions/build/vite/shared-dependencies.ts"],"sourcesContent":["import {type ModuleFederationOptions} from '@module-federation/vite'\nimport {valid as validSemver} from 'semver'\n\ninterface SharedDependency {\n // Package name used for import matching and in the share scope.\n name: string\n\n // Optional packages do not disable sharing when an app does not use them.\n optional?: boolean\n // `false` selects this package's exact version without splitting the React compatibility group.\n scope?: false\n // `false` checks compatibility without publishing the package as a provider.\n share?: false\n}\n\n// Add approved packages here; versions contribute to the scope unless explicitly excluded.\nconst sharedDependencies: readonly SharedDependency[] = [\n {name: 'react'},\n {name: 'react-dom'},\n // React DOM owns scheduler's mutable queue, so only its version joins the scope.\n {name: 'scheduler', share: false},\n {name: 'styled-components', optional: true, scope: false},\n]\n\n// Vite injects these aliases for its own modules; neither can redirect a shared package import.\nconst viteInternalAliases = new Set([/^\\/?@vite\\/client/.source, /^\\/?@vite\\/env/.source])\n\nexport interface ResolvedDependency {\n name: string\n root: string\n version: string\n\n specifier?: string\n}\n\ntype SharedEntries = Exclude<ModuleFederationOptions['shared'], string[] | undefined>\n\nexport interface FederationSharing extends Pick<\n ModuleFederationOptions,\n 'shareScope' | 'shareStrategy'\n> {\n shared: SharedEntries\n}\n\nexport function findSharedDependencyName(specifier: string): string | undefined {\n return sharedDependencies.find(({name}) => specifier === name || specifier.startsWith(`${name}/`))\n ?.name\n}\n\nexport function createFederationSharing(\n dependencies: ResolvedDependency[],\n): FederationSharing | {disabledReason: string} {\n const versions = resolveCompatibleVersions(dependencies)\n if (!(versions instanceof Map)) return versions\n\n // React and its renderer must agree; styled-components selects its own exact version in this pool.\n const shareScope =\n 'sanity-' +\n sharedDependencies\n .filter(({scope}) => scope !== false)\n .map(({name}) => `${name}-${versions.get(name)}`)\n .join('-')\n return {\n shared: createSharedEntries(dependencies, shareScope),\n // The array form makes Module Federation use named pools instead of the host's default pool.\n shareScope: [shareScope],\n // Prefer a compatible provider that another app already loaded before downloading a local copy.\n shareStrategy: 'loaded-first',\n }\n}\n\nexport function aliasMayRewriteSharedImport(find: RegExp | string): boolean {\n if (typeof find === 'string') {\n return (\n Boolean(findSharedDependencyName(find)) ||\n sharedDependencies.some(({name}) => name.startsWith(`${find}/`))\n )\n }\n\n if (find.ignoreCase || find.multiline) return true\n if (viteInternalAliases.has(find.source)) return false\n\n // Only accept a literal prefix like /^@app\\//; more complex regexes may also match shared imports.\n const namespace = find.source.match(/^\\^([@\\w-]+)\\\\\\/$/u)?.[1]\n if (!namespace) return true\n return sharedDependencies.some(({name}) => name === namespace || name.startsWith(`${namespace}/`))\n}\n\nfunction resolveCompatibleVersions(\n dependencies: ResolvedDependency[],\n): Map<string, string> | {disabledReason: string} {\n const versions = new Map<string, string>()\n for (const {name, optional} of sharedDependencies) {\n const copies = dependencies.filter((dependency) => dependency.name === name)\n if (copies.length === 0 && optional) {\n versions.set(name, 'none')\n continue\n }\n if (copies.length === 0) return {disabledReason: `No installed copy of ${name} was found`}\n const {root, version} = copies[0]\n if (copies.some((copy) => copy.root !== root || copy.version !== version)) {\n return {disabledReason: `Multiple installed copies of ${name} were found`}\n }\n // pnpm patch hashes identify different package code under the same version, so patched copies stay local.\n if (root.includes('patch_hash=')) return {disabledReason: `${name} has a local pnpm patch`}\n // Semver ignores build metadata, so only its unchanged canonical form is safe to share.\n if (validSemver(version) !== version) {\n return {disabledReason: `${name} has an unsupported version: ${JSON.stringify(version)}`}\n }\n versions.set(name, version)\n }\n\n // Sharing the renderer without its React import would split hook and context identity.\n if (!dependencies.some(({name, specifier}) => name === 'react' && specifier === 'react')) {\n return {disabledReason: 'The react import could not be resolved to a shared provider'}\n }\n if (versions.get('react') !== versions.get('react-dom')) {\n return {\n disabledReason: `React (${versions.get('react')}) and React DOM (${versions.get('react-dom')}) versions differ`,\n }\n }\n return versions\n}\n\nfunction createSharedEntries(\n dependencies: ResolvedDependency[],\n shareScope: string,\n): SharedEntries {\n const entries: SharedEntries = {}\n const providers = new Set(\n sharedDependencies.filter(({share}) => share !== false).map(({name}) => name),\n )\n for (const {name, specifier, version} of dependencies) {\n if (!specifier || !providers.has(name)) continue\n entries[specifier] = {\n eager: false,\n requiredVersion: version,\n // @module-federation/vite defaults providers to \"default\" unless each entry repeats this scope.\n shareScope,\n singleton: false,\n strictVersion: true,\n version,\n }\n }\n // Vite resolves imports concurrently, so sort providers to keep generated chunks reproducible.\n return Object.fromEntries(\n Object.entries(entries).toSorted(([left], [right]) => left.localeCompare(right)),\n )\n}\n"],"names":["valid","validSemver","sharedDependencies","name","share","optional","scope","viteInternalAliases","Set","source","findSharedDependencyName","specifier","find","startsWith","createFederationSharing","dependencies","versions","resolveCompatibleVersions","Map","shareScope","filter","map","get","join","shared","createSharedEntries","shareStrategy","aliasMayRewriteSharedImport","Boolean","some","ignoreCase","multiline","has","namespace","match","copies","dependency","length","set","disabledReason","root","version","copy","includes","JSON","stringify","entries","providers","eager","requiredVersion","singleton","strictVersion","Object","fromEntries","toSorted","left","right","localeCompare"],"mappings":"AACA,SAAQA,SAASC,WAAW,QAAO,SAAQ;AAc3C,2FAA2F;AAC3F,MAAMC,qBAAkD;IACtD;QAACC,MAAM;IAAO;IACd;QAACA,MAAM;IAAW;IAClB,iFAAiF;IACjF;QAACA,MAAM;QAAaC,OAAO;IAAK;IAChC;QAACD,MAAM;QAAqBE,UAAU;QAAMC,OAAO;IAAK;CACzD;AAED,gGAAgG;AAChG,MAAMC,sBAAsB,IAAIC,IAAI;IAAC,oBAAoBC,MAAM;IAAE,iBAAiBA,MAAM;CAAC;AAmBzF,OAAO,SAASC,yBAAyBC,SAAiB;IACxD,OAAOT,mBAAmBU,IAAI,CAAC,CAAC,EAACT,IAAI,EAAC,GAAKQ,cAAcR,QAAQQ,UAAUE,UAAU,CAAC,GAAGV,KAAK,CAAC,CAAC,IAC5FA;AACN;AAEA,OAAO,SAASW,wBACdC,YAAkC;IAElC,MAAMC,WAAWC,0BAA0BF;IAC3C,IAAI,CAAEC,CAAAA,oBAAoBE,GAAE,GAAI,OAAOF;IAEvC,mGAAmG;IACnG,MAAMG,aACJ,YACAjB,mBACGkB,MAAM,CAAC,CAAC,EAACd,KAAK,EAAC,GAAKA,UAAU,OAC9Be,GAAG,CAAC,CAAC,EAAClB,IAAI,EAAC,GAAK,GAAGA,KAAK,CAAC,EAAEa,SAASM,GAAG,CAACnB,OAAO,EAC/CoB,IAAI,CAAC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AAO;YACPC,iBAAiBR;YACjB,gGAAgG;YAChGtB;YACA+B,WAAW;YACXC,eAAe;YACfV;QACF;IACF;IACA,+FAA+F;IAC/F,OAAOW,OAAOC,WAAW,CACvBD,OAAON,OAAO,CAACA,SAASQ,QAAQ,CAAC,CAAC,CAACC,KAAK,EAAE,CAACC,MAAM,GAAKD,KAAKE,aAAa,CAACD;AAE7E"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/actions/dev/startWorkbenchDev.ts"],"sourcesContent":["import {styleText} from 'node:util'\n\nimport {type CliConfig, type Output} from '@sanity/cli-core'\n\nimport {createServerLifecycle, toDisplayHost} from '../../util/serverOrchestration.js'\nimport {type AppServerResult, startAppServerSupervisor} from './appServerSupervisor.js'\nimport {type DevServerManifest} from './registry.js'\nimport {startDevServerRegistration} from './startDevServerRegistration.js'\nimport {\n startWorkbenchDevServer,\n startWorkbenchRemoteCoordinator,\n} from './startWorkbenchDevServer.js'\n\nexport interface StartWorkbenchDevOptions {\n /** Directory for the workbench Vite server's dependency cache. */\n cacheDir: string\n /** CLI-domain `app.id`/`deployment.appId` deprecation check, run before registering. */\n checkForDeprecatedAppId: () => void\n cliConfig: CliConfig\n /** Extract the project manifest to inline into the registry (studio-vs-app handled by the CLI). */\n extractManifest: (params: {\n applicationId?: string\n configPath: string\n workDir: string\n }) => Promise<DevServerManifest['manifest']>\n httpHost: string | undefined\n httpPort: number\n isApp: boolean\n output: Output\n reactStrictMode: boolean\n /** Start the app/studio dev server — the CLI owns the server, this orchestrates it. */\n startAppServer: (params: {\n announceUrl: boolean\n cliConfig: CliConfig\n httpPort: number\n }) => Promise<AppServerResult>\n workDir: string\n}\n\n/**\n * Orchestrate the dev servers a workbench project needs: a singleton workbench\n * Vite server plus the app/studio dev server it renders, wired to the dev-server\n * registry so view/service edits re-sync live.\n *\n * A running workbench claims the configured port, so the app server binds the\n * next one. If the workbench can't start (package or port unavailable), the app\n * server falls back to the configured port and announces its own URL, exactly as\n * a plain `sanity dev` would.\n */\nexport async function startWorkbenchDev(\n options: StartWorkbenchDevOptions,\n): Promise<{close: () => Promise<void>}> {\n const {\n cacheDir,\n checkForDeprecatedAppId,\n cliConfig,\n extractManifest,\n httpHost,\n httpPort,\n isApp,\n output,\n reactStrictMode,\n startAppServer,\n workDir,\n } = options\n\n // The remote can't render itself, so it runs as a plain app server (not the\n // shell) that still claims the lock and bridges the registry, so app\n // `sanity dev`s register into it.\n if (process.env.SANITY_INTERNAL_IS_WORKBENCH_REMOTE === 'true') {\n const remote = await startAppServer({announceUrl: true, cliConfig, httpPort})\n if (!remote.started) return {close: async () => {}}\n\n const addr = remote.server.httpServer?.address()\n const port =\n (typeof addr === 'object' && addr ? addr.port : remote.server.config.server.port) ?? httpPort\n const coordinator = startWorkbenchRemoteCoordinator({httpHost, port, server: remote.server})\n\n return {\n close: async () => {\n await coordinator.close()\n await remote.close()\n },\n }\n }\n\n // Unwound in reverse on any failure or on close(): the watcher stops before\n // the app server, and the supervisor waits out an in-flight rebuild.\n const {close, closers, installSignalHandlers} = createServerLifecycle()\n\n const workbench = await startWorkbenchDevServer({\n cacheDir,\n cliConfig,\n httpHost,\n httpPort,\n
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/dev/startWorkbenchDev.ts"],"sourcesContent":["import {styleText} from 'node:util'\n\nimport {type CliConfig, type Output} from '@sanity/cli-core'\n\nimport {createServerLifecycle, toDisplayHost} from '../../util/serverOrchestration.js'\nimport {type AppServerResult, startAppServerSupervisor} from './appServerSupervisor.js'\nimport {type DevServerManifest} from './registry.js'\nimport {startDevServerRegistration} from './startDevServerRegistration.js'\nimport {\n startWorkbenchDevServer,\n startWorkbenchRemoteCoordinator,\n} from './startWorkbenchDevServer.js'\n\nexport interface StartWorkbenchDevOptions {\n /** Directory for the workbench Vite server's dependency cache. */\n cacheDir: string\n /** CLI-domain `app.id`/`deployment.appId` deprecation check, run before registering. */\n checkForDeprecatedAppId: () => void\n cliConfig: CliConfig\n /** Extract the project manifest to inline into the registry (studio-vs-app handled by the CLI). */\n extractManifest: (params: {\n applicationId?: string\n configPath: string\n workDir: string\n }) => Promise<DevServerManifest['manifest']>\n httpHost: string | undefined\n httpPort: number\n isApp: boolean\n output: Output\n reactStrictMode: boolean\n /** Start the app/studio dev server — the CLI owns the server, this orchestrates it. */\n startAppServer: (params: {\n announceUrl: boolean\n cliConfig: CliConfig\n httpPort: number\n }) => Promise<AppServerResult>\n workDir: string\n}\n\n/**\n * Orchestrate the dev servers a workbench project needs: a singleton workbench\n * Vite server plus the app/studio dev server it renders, wired to the dev-server\n * registry so view/service edits re-sync live.\n *\n * A running workbench claims the configured port, so the app server binds the\n * next one. If the workbench can't start (package or port unavailable), the app\n * server falls back to the configured port and announces its own URL, exactly as\n * a plain `sanity dev` would.\n */\nexport async function startWorkbenchDev(\n options: StartWorkbenchDevOptions,\n): Promise<{close: () => Promise<void>}> {\n const {\n cacheDir,\n checkForDeprecatedAppId,\n cliConfig,\n extractManifest,\n httpHost,\n httpPort,\n isApp,\n output,\n reactStrictMode,\n startAppServer,\n workDir,\n } = options\n\n // The remote can't render itself, so it runs as a plain app server (not the\n // shell) that still claims the lock and bridges the registry, so app\n // `sanity dev`s register into it.\n if (process.env.SANITY_INTERNAL_IS_WORKBENCH_REMOTE === 'true') {\n const remote = await startAppServer({announceUrl: true, cliConfig, httpPort})\n if (!remote.started) return {close: async () => {}}\n\n const addr = remote.server.httpServer?.address()\n const port =\n (typeof addr === 'object' && addr ? addr.port : remote.server.config.server.port) ?? httpPort\n const coordinator = startWorkbenchRemoteCoordinator({httpHost, port, server: remote.server})\n\n return {\n close: async () => {\n await coordinator.close()\n await remote.close()\n },\n }\n }\n\n // Unwound in reverse on any failure or on close(): the watcher stops before\n // the app server, and the supervisor waits out an in-flight rebuild.\n const {close, closers, installSignalHandlers} = createServerLifecycle()\n\n const workbench = await startWorkbenchDevServer({\n cacheDir,\n cliConfig,\n httpHost,\n httpPort,\n output,\n reactStrictMode,\n workDir,\n })\n closers.push(workbench.close)\n\n // A running workbench owns the configured port; the app server takes the next.\n // Without one it claims the configured port and announces its own URL.\n const appPort = workbench.workbenchAvailable ? workbench.workbenchPort + 1 : httpPort\n const announceUrl = !workbench.workbenchAvailable\n\n const supervised = await startAppServerSupervisor({\n cliConfig,\n start: (config) => startAppServer({announceUrl, cliConfig: config, httpPort: appPort}),\n workDir,\n }).catch(async (err) => {\n await close()\n throw err\n })\n\n if (!supervised.started) {\n // The app server already reported why (e.g. missing organization id). Hand\n // back a close that releases the workbench lock; nothing else came up.\n return {close}\n }\n const {supervisor} = supervised\n closers.push(supervisor.close)\n\n try {\n // The deprecated-id check and manifest extractor are CLI-domain, injected here.\n checkForDeprecatedAppId()\n const registration = await startDevServerRegistration({\n cliConfig,\n extractManifest,\n isApp,\n onInterfaceSetChange: () => supervisor.rebuild(),\n output,\n server: supervisor.server,\n workDir,\n })\n closers.push(registration.close)\n } catch (err) {\n // Registration runs after both servers are up; a failure here would leak the\n // workbench lock and dev servers without this teardown.\n await close()\n throw err\n }\n\n if (workbench.workbenchAvailable) {\n const workbenchUrl = `http://${toDisplayHost(workbench.httpHost)}:${workbench.workbenchPort}`\n const addr = supervisor.server.httpServer?.address()\n const port = typeof addr === 'object' && addr ? addr.port : supervisor.server.config.server.port\n output.log(\n `Workbench dev server started at ${styleText(['blue', 'underline'], workbenchUrl)} (app on port ${port})`,\n )\n }\n\n installSignalHandlers()\n\n return {close}\n}\n"],"names":["styleText","createServerLifecycle","toDisplayHost","startAppServerSupervisor","startDevServerRegistration","startWorkbenchDevServer","startWorkbenchRemoteCoordinator","startWorkbenchDev","options","cacheDir","checkForDeprecatedAppId","cliConfig","extractManifest","httpHost","httpPort","isApp","output","reactStrictMode","startAppServer","workDir","process","env","SANITY_INTERNAL_IS_WORKBENCH_REMOTE","remote","announceUrl","started","close","addr","server","httpServer","address","port","config","coordinator","closers","installSignalHandlers","workbench","push","appPort","workbenchAvailable","workbenchPort","supervised","start","catch","err","supervisor","registration","onInter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CAAC,gCAAgC,EAAElD,UAAU;YAAC;YAAQ;SAAY,EAAEiD,cAAc,cAAc,EAAElB,KAAK,CAAC,CAAC;IAE7G;IAEAI;IAEA,OAAO;QAACT;IAAK;AACf"}
|
|
@@ -90,7 +90,7 @@ const toApplicationsPayload = (servers)=>({
|
|
|
90
90
|
};
|
|
91
91
|
}
|
|
92
92
|
export async function startWorkbenchDevServer(options) {
|
|
93
|
-
const { cacheDir, cliConfig, httpHost, httpPort: workbenchPort,
|
|
93
|
+
const { cacheDir, cliConfig, httpHost, httpPort: workbenchPort, output, reactStrictMode, workDir } = options;
|
|
94
94
|
// Workbench is opted into by a `defineApplication` app or a config-only
|
|
95
95
|
// `unstable_defineMediaLibrary` config — the latter still needs the shell to
|
|
96
96
|
// render it.
|
|
@@ -129,7 +129,6 @@ export async function startWorkbenchDevServer(options) {
|
|
|
129
129
|
cacheDir,
|
|
130
130
|
cliConfig,
|
|
131
131
|
httpHost,
|
|
132
|
-
mode,
|
|
133
132
|
output,
|
|
134
133
|
reactStrictMode,
|
|
135
134
|
workbenchPort,
|
|
@@ -161,11 +160,8 @@ export async function startWorkbenchDevServer(options) {
|
|
|
161
160
|
};
|
|
162
161
|
}
|
|
163
162
|
async function createWorkbenchViteServer(options) {
|
|
164
|
-
const { cacheDir, cliConfig, httpHost,
|
|
165
|
-
|
|
166
|
-
// as production), which points the workbench UI at a local dev server that
|
|
167
|
-
// isn't running here. Ignore the override and load the deployed UI instead.
|
|
168
|
-
const remoteUrl = mode === 'preview' ? undefined : parseRemoteUrl(process.env.SANITY_INTERNAL_WORKBENCH_REMOTE_URL);
|
|
163
|
+
const { cacheDir, cliConfig, httpHost, output, reactStrictMode, workbenchPort, workDir } = options;
|
|
164
|
+
const remoteUrl = parseRemoteUrl(process.env.SANITY_INTERNAL_WORKBENCH_REMOTE_URL);
|
|
169
165
|
const organizationId = resolveOrganizationId(cliConfig);
|
|
170
166
|
devDebug('Writing workbench runtime files');
|
|
171
167
|
const root = await writeWorkbenchRuntime({
|
|
@@ -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 readWorkbenchLock,\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): () => void {\n server.ws.on('sanity:workbench:get-local-applications', (_, client) => {\n client.send(\n 'sanity:workbench:local-applications',\n toApplicationsPayload(getRegisteredServers()),\n )\n })\n\n const setTracker = createExposesTracker()\n const registryWatcher = watchRegistry((servers) => {\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 * Make the workbench remote act as the machine's workbench: claim the singleton\n * lock so app `sanity dev`s register into it instead of each starting their own,\n * and bridge the registry so the remote shows the local apps. No-op lock if one\n * is already held.\n */\nexport function startWorkbenchRemoteCoordinator(options: {\n httpHost: string | undefined\n port: number\n server: ViteDevServer\n}): {close: () => Promise<void>} {\n const {httpHost, port, server} = options\n\n const lock = acquireWorkbenchLock({host: httpHost || 'localhost', port})\n if (!lock) {\n const existing = readWorkbenchLock()\n devDebug(\n 'Workbench lock already held by pid %d on port %d; bridging the registry without claiming it',\n existing?.pid,\n existing?.port,\n )\n }\n\n const detachBridge = attachViteDevServerBridge(server)\n\n return {\n close: async () => {\n detachBridge()\n lock?.release()\n },\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 /** `dev` renders a live app and honors a local workbench-UI override; `preview`\n * (`sanity start`) previews a build and loads the deployed workbench UI. */\n mode: 'development' | 'preview'\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 mode,\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 // Acquire an exclusive lock — only one workbench per machine.\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({host: httpHost || 'localhost', port: workbenchPort})\n if (!workbenchLock) {\n const existing = readWorkbenchLock()\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 cliConfig,\n httpHost,\n mode,\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 cliConfig: CliConfig\n httpHost: string | undefined\n mode: 'development' | 'preview'\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, cliConfig, httpHost, mode, output, reactStrictMode, workbenchPort, workDir} =\n options\n\n // `preview` loads `.env.development` (the env hook treats only `build`/`deploy`\n // as production), which points the workbench UI at a local dev server that\n // isn't running here. Ignore the override and load the deployed UI instead.\n const remoteUrl =\n mode === 'preview'\n ? undefined\n : parseRemoteUrl(process.env.SANITY_INTERNAL_WORKBENCH_REMOTE_URL)\n\n const organizationId = resolveOrganizationId(cliConfig)\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 `Workbench 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)\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 'Workbench 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","readWorkbenchLock","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","ws","on","_","client","send","setTracker","registryWatcher","hasChanged","close","startWorkbenchRemoteCoordinator","options","httpHost","lock","existing","pid","detachBridge","release","startWorkbenchDevServer","cacheDir","cliConfig","httpPort","workbenchPort","mode","output","reactStrictMode","workDir","app","workbenchAvailable","workbenchLock","result","createWorkbenchViteServer","err","actualPort","updatePort","remoteUrl","undefined","parseRemoteUrl","process","env","SANITY_INTERNAL_WORKBENCH_REMOTE_URL","resolveOrganizationId","root","cwd","viteConfig","configFile","define","__SANITY_STAGING__","JSON","stringify","logLevel","optimizeDeps","exclude","plugins","remoteManifestPreloadHeaderPlugin","resolve","alias","dedupe","strictPort","warmup","clientFiles","listen","warn","Error","message","String","addr","httpServer","address","fetch","then","r","body","cancel","catch","remoteUrlSchema","normalize","protocol","value","safeParse","success","data","apply","configureServer","middlewares","use","req","res","next","pathname","split","setHeader"],"mappings":"AAAA,SAAQA,aAAa,QAAO,WAAU;AAEtC,SAAqCC,QAAQ,QAAO,mBAAkB;AACtE,SAAQC,SAAS,QAAO,wBAAuB;AAC/C,OAAOC,eAAe,uBAAsB;AAC5C,SAAQC,YAAY,QAA2D,OAAM;AACrF,SAAQC,CAAC,QAAO,WAAU;AAE1B,SAAQC,cAAc,EAAEC,iBAAiB,QAAO,qBAAoB;AACpE,SAAQC,oBAAoB,QAAO,oBAAmB;AACtD,SACEC,oBAAoB,EAEpBC,oBAAoB,EACpBC,kBAAkB,EAClBC,iBAAiB,EACjBC,aAAa,QACR,gBAAe;AACtB,SAAQC,eAAe,QAAO,uBAAsB;AACpD,SAAQC,qBAAqB,QAAO,6BAA4B;AAEhE,MAAMC,WAAWf,SAAS;AAC1B,MAAMgB,uBAAuB;AAC7B,MAAMC,sBAAsBlB,cAC1B,IAAImB,IAAI,sCAAsC,YAAYC,GAAG;AAG/D,MAAMC,OAAO,WAAa;AAE1B,kEAAkE;AAClE,qFAAqF;AACrF,MAAMC,wBAAwB,CAACC,UAAkC,CAAA;QAC/DC,cAAcD,QACXE,MAAM,CAAC,CAACC,SAAW,CAACf,mBAAmBe,SACvCC,GAAG,CACF,CAAC,EACCC,IAAI,EACJC,EAAE,EACFC,UAAU,EACVC,QAAQ,EACRC,IAAI,EACJC,cAAc,EACdC,IAAI,EACJC,SAAS,EACTC,SAAS,EACTC,IAAI,EACJC,IAAI,EACJC,UAAU,EACX,GAAM,CAAA;gBACLX;gBACAC;gBACA,2EAA2E;gBAC3EC,YAAYA,YAAYH,IAAI,CAACa,QAAU1B,gBAAgB0B;gBACvDT;gBACAC;gBACAE;gBACAC;gBACAC;gBACAE;gBACA,GAAIL,kBAAkBI,QAAQE,aAAa;oBAACN;oBAAgBI;oBAAME;gBAAU,IAAI,CAAC,CAAC;YACpF,CAAA;QAEJE,SAASlB,QAAQmB,OAAO,CAAC,CAAC,E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AIlH,GAAG,IAAI,GAAE,EAAGsH,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;QACAxG,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 readWorkbenchLock,\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): () => void {\n server.ws.on('sanity:workbench:get-local-applications', (_, client) => {\n client.send(\n 'sanity:workbench:local-applications',\n toApplicationsPayload(getRegisteredServers()),\n )\n })\n\n const setTracker = createExposesTracker()\n const registryWatcher = watchRegistry((servers) => {\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 * Make the workbench remote act as the machine's workbench: claim the singleton\n * lock so app `sanity dev`s register into it instead of each starting their own,\n * and bridge the registry so the remote shows the local apps. No-op lock if one\n * is already held.\n */\nexport function startWorkbenchRemoteCoordinator(options: {\n httpHost: string | undefined\n port: number\n server: ViteDevServer\n}): {close: () => Promise<void>} {\n const {httpHost, port, server} = options\n\n const lock = acquireWorkbenchLock({host: httpHost || 'localhost', port})\n if (!lock) {\n const existing = readWorkbenchLock()\n devDebug(\n 'Workbench lock already held by pid %d on port %d; bridging the registry without claiming it',\n existing?.pid,\n existing?.port,\n )\n }\n\n const detachBridge = attachViteDevServerBridge(server)\n\n return {\n close: async () => {\n detachBridge()\n lock?.release()\n },\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 // Acquire an exclusive lock — only one workbench per machine.\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({host: httpHost || 'localhost', port: workbenchPort})\n if (!workbenchLock) {\n const existing = readWorkbenchLock()\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 cliConfig,\n httpHost,\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 cliConfig: CliConfig\n httpHost: string | undefined\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, cliConfig, httpHost, output, reactStrictMode, workbenchPort, workDir} = options\n\n const remoteUrl = parseRemoteUrl(process.env.SANITY_INTERNAL_WORKBENCH_REMOTE_URL)\n\n const organizationId = resolveOrganizationId(cliConfig)\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 `Workbench 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)\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 'Workbench 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","readWorkbenchLock","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","ws","on","_","client","send","setTracker","registryWatcher","hasChanged","close","startWorkbenchRemoteCoordinator","options","httpHost","lock","existing","pid","detachBridge","release","startWorkbenchDevServer","cacheDir","cliConfig","httpPort","workbenchPort","output","reactStrictMode","workDir","app","workbenchAvailable","workbenchLock","result","createWorkbenchViteServer","err","actualPort","updatePort","remoteUrl","parseRemoteUrl","process","env","SANITY_INTERNAL_WORKBENCH_REMOTE_URL","resolveOrganizationId","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"],"m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AAEzD,UAAU,qCAAqC,CAAC;gBAC5E;gBACAsD;YACF;QACF;QACAxG,MAAM;IACR;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/actions/preview/startWorkbenchPreview.ts"],"sourcesContent":["import {readFile} from 'node:fs/promises'\nimport path from 'node:path'\nimport {styleText} from 'node:util'\n\nimport {type CliConfig, findProjectRoot, type Output} from '@sanity/cli-core'\n\nimport {buildAppId, SANITY_APP_ID_FILE} from '../../appId.js'\nimport {deriveInterfaces} from '../../deriveInterfaces.js'\nimport {resolveWorkbenchApp} from '../../resolveWorkbenchApp.js'\nimport {createServerLifecycle, toDisplayHost} from '../../util/serverOrchestration.js'\nimport {deriveConfigs} from '../dev/deriveConfigs.js'\nimport {type DevServerManifest, registerDevServer} from '../dev/registry.js'\nimport {startWorkbenchDevServer} from '../dev/startWorkbenchDevServer.js'\nimport {serveBuiltApplication} from './serveBuiltApplication.js'\n\nexport interface StartWorkbenchPreviewOptions {\n /** Directory for the workbench Vite server's dependency cache. */\n cacheDir: string\n /** CLI-domain `app.id`/`deployment.appId` deprecation check, run before registering. */\n checkForDeprecatedAppId: () => void\n cliConfig: CliConfig\n /** Extract the project manifest to inline into the registry (studio-vs-app handled by the CLI). */\n extractManifest: (params: {\n applicationId?: string\n configPath: string\n workDir: string\n }) => Promise<DevServerManifest['manifest']>\n httpHost: string\n httpPort: number\n isApp: boolean\n /** The built `dist` directory to serve as the federation remote. */\n outDir: string\n output: Output\n reactStrictMode: boolean\n workDir: string\n}\n\n/**\n * `sanity start` for a workbench app: serve a production build the way dev serves\n * a live one. The same singleton workbench shell renders it and the same registry\n * advertises it — only the remote differs, static files from the build output\n * instead of a live Vite dev server. There's no config watcher or rebuild: a\n * build is fixed, so nothing re-syncs.\n *\n * A running workbench claims the configured port, so the built remote binds the\n * next one. Without one the remote takes the configured port and announces its\n * own URL.\n */\nexport async function startWorkbenchPreview(\n options: StartWorkbenchPreviewOptions,\n): Promise<{close: () => Promise<void>}> {\n const {\n cacheDir,\n checkForDeprecatedAppId,\n cliConfig,\n extractManifest,\n httpHost,\n httpPort,\n isApp,\n outDir,\n output,\n reactStrictMode,\n workDir,\n } = options\n\n const {close, closers, installSignalHandlers} = createServerLifecycle()\n\n const workbench = await startWorkbenchDevServer({\n cacheDir,\n cliConfig,\n httpHost,\n httpPort,\n
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/preview/startWorkbenchPreview.ts"],"sourcesContent":["import {readFile} from 'node:fs/promises'\nimport path from 'node:path'\nimport {styleText} from 'node:util'\n\nimport {type CliConfig, findProjectRoot, type Output} from '@sanity/cli-core'\n\nimport {buildAppId, SANITY_APP_ID_FILE} from '../../appId.js'\nimport {deriveInterfaces} from '../../deriveInterfaces.js'\nimport {resolveWorkbenchApp} from '../../resolveWorkbenchApp.js'\nimport {createServerLifecycle, toDisplayHost} from '../../util/serverOrchestration.js'\nimport {deriveConfigs} from '../dev/deriveConfigs.js'\nimport {type DevServerManifest, registerDevServer} from '../dev/registry.js'\nimport {startWorkbenchDevServer} from '../dev/startWorkbenchDevServer.js'\nimport {serveBuiltApplication} from './serveBuiltApplication.js'\n\nexport interface StartWorkbenchPreviewOptions {\n /** Directory for the workbench Vite server's dependency cache. */\n cacheDir: string\n /** CLI-domain `app.id`/`deployment.appId` deprecation check, run before registering. */\n checkForDeprecatedAppId: () => void\n cliConfig: CliConfig\n /** Extract the project manifest to inline into the registry (studio-vs-app handled by the CLI). */\n extractManifest: (params: {\n applicationId?: string\n configPath: string\n workDir: string\n }) => Promise<DevServerManifest['manifest']>\n httpHost: string\n httpPort: number\n isApp: boolean\n /** The built `dist` directory to serve as the federation remote. */\n outDir: string\n output: Output\n reactStrictMode: boolean\n workDir: string\n}\n\n/**\n * `sanity start` for a workbench app: serve a production build the way dev serves\n * a live one. The same singleton workbench shell renders it and the same registry\n * advertises it — only the remote differs, static files from the build output\n * instead of a live Vite dev server. There's no config watcher or rebuild: a\n * build is fixed, so nothing re-syncs.\n *\n * A running workbench claims the configured port, so the built remote binds the\n * next one. Without one the remote takes the configured port and announces its\n * own URL.\n */\nexport async function startWorkbenchPreview(\n options: StartWorkbenchPreviewOptions,\n): Promise<{close: () => Promise<void>}> {\n const {\n cacheDir,\n checkForDeprecatedAppId,\n cliConfig,\n extractManifest,\n httpHost,\n httpPort,\n isApp,\n outDir,\n output,\n reactStrictMode,\n workDir,\n } = options\n\n const {close, closers, installSignalHandlers} = createServerLifecycle()\n\n const workbench = await startWorkbenchDevServer({\n cacheDir,\n cliConfig,\n httpHost,\n httpPort,\n output,\n reactStrictMode,\n workDir,\n })\n closers.push(workbench.close)\n\n const remotePort = workbench.workbenchAvailable ? workbench.workbenchPort + 1 : httpPort\n\n const remote = await serveBuiltApplication({\n cacheDir,\n httpHost,\n httpPort: remotePort,\n outDir,\n workDir,\n }).catch(async (err) => {\n await close()\n throw err\n })\n closers.push(remote.close)\n\n try {\n // Callers provide CLI-only validation and manifest extraction to keep them\n // out of workbench-cli.\n checkForDeprecatedAppId()\n const configPath = (await findProjectRoot(workDir)).path\n const workbench = resolveWorkbenchApp(cliConfig)\n\n if (!workbench) throw new Error('`sanity start` was invoked in a non-workbench application')\n const inlinedId = await readInlinedAppId(outDir)\n const configs = await deriveConfigs(cliConfig)\n const id = inlinedId ?? (await buildAppId(workbench))\n const registration = registerDevServer({\n configs,\n host: remote.host,\n id,\n interfaces: deriveInterfaces(cliConfig.app, {isApp}),\n manifest: await extractManifest({applicationId: id, configPath, workDir}),\n manifestUpdatedAt: new Date().toISOString(),\n organizationId: workbench.organizationId,\n port: remote.port,\n projectId: cliConfig?.api?.projectId,\n slug: workbench.slug,\n type: isApp ? 'coreApp' : 'studio',\n visibility: workbench.visibility ?? 'default',\n workDir,\n })\n closers.push(async () => registration.release())\n } catch (err) {\n await close()\n throw err\n }\n\n if (workbench.workbenchAvailable) {\n const workbenchUrl = `http://${toDisplayHost(workbench.httpHost)}:${workbench.workbenchPort}`\n output.log(\n `Workbench preview server started at ${styleText(['blue', 'underline'], workbenchUrl)} (serving build on port ${remote.port})`,\n )\n } else {\n const remoteUrl = `http://${toDisplayHost(remote.host)}:${remote.port}`\n output.log(`Serving build at ${styleText(['blue', 'underline'], remoteUrl)}`)\n }\n\n installSignalHandlers()\n\n return {close}\n}\n\n/** The id the build inlined into its bundle, or undefined when absent. */\nasync function readInlinedAppId(outDir: string): Promise<string | undefined> {\n try {\n return (await readFile(path.join(outDir, SANITY_APP_ID_FILE), 'utf8')).trim() || undefined\n } catch {\n return undefined\n }\n}\n"],"names":["readFile","path","styleText","findProjectRoot","buildAppId","SANITY_APP_ID_FILE","deriveInterfaces","resolveWorkbenchApp","createServerLifecycle","toDisplayHost","deriveConfigs","registerDevServer","startWorkbenchDevServer","serveBuiltApplication","startWorkbenchPreview","options","cacheDir","checkForDeprecatedAppId","cliConfig","extractManifest","httpHost","httpPort","isApp","outDir","output","reactStrictMode","workDir","close","closers","installSignalHandlers","workbench","push","remotePort","workbenchAvailable","workbenchPort","remote","catch","err","configPath","Error","inlinedId","readInlinedAppId","configs","id","registration","host","interfaces","app","manifest","applicationId","manifestUpdatedAt","Date","toISOString","organizationId","port","projectId","api","slug","type","visibility","release","workbenchUrl","log","remoteUrl","join","trim","undefined"],"mappings":"AAAA,SAAQA,QAAQ,QAAO,mBAAkB;AACzC,OAAOC,UAAU,YAAW;AAC5B,SAAQC,SAAS,QAAO,YAAW;AAEnC,SAAwBC,eAAe,QAAoB,mBAAkB;AAE7E,SAAQC,UAAU,EAAEC,kBAAkB,QAAO,iBAAgB;AAC7D,SAAQC,gBAAgB,QAAO,4BAA2B;AAC1D,SAAQC,mBAAmB,QAAO,+BAA8B;AAChE,SAAQC,qBAAqB,EAAEC,aAAa,QAAO,oCAAmC;AACtF,SAAQC,aAAa,QAAO,0BAAyB;AACrD,SAAgCC,iBAAiB,QAAO,qBAAoB;AAC5E,SAAQC,uBAAuB,QAAO,oCAAmC;AACzE,SAAQC,qBAAqB,QAAO,6BAA4B;AAwBhE;;;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uB,cAAc;YACxCC,MAAMnB,OAAOmB,IAAI;YACjBC,WAAWrC,WAAWsC,KAAKD;YAC3BE,MAAM3B,UAAU2B,IAAI;YACpBC,MAAMpC,QAAQ,YAAY;YAC1BqC,YAAY7B,UAAU6B,UAAU,IAAI;YACpCjC;QACF;QACAE,QAAQG,IAAI,CAAC,UAAYa,aAAagB,OAAO;IAC/C,EAAE,OAAOvB,KAAK;QACZ,MAAMV;QACN,MAAMU;IACR;IAEA,IAAIP,UAAUG,kBAAkB,EAAE;QAChC,MAAM4B,eAAe,CAAC,OAAO,EAAEpD,cAAcqB,UAAUV,QAAQ,EAAE,CAAC,EAAEU,UAAUI,aAAa,EAAE;QAC7FV,OAAOsC,GAAG,CACR,CAAC,oCAAoC,EAAE5D,UAAU;YAAC;YAAQ;SAAY,EAAE2D,cAAc,wBAAwB,EAAE1B,OAAOmB,IAAI,CAAC,CAAC,CAAC;IAElI,OAAO;QACL,MAAMS,YAAY,CAAC,OAAO,EAAEtD,cAAc0B,OAAOU,IAAI,EAAE,CAAC,EAAEV,OAAOmB,IAAI,EAAE;QACvE9B,OAAOsC,GAAG,CAAC,CAAC,iBAAiB,EAAE5D,UAAU;YAAC;YAAQ;SAAY,EAAE6D,YAAY;IAC9E;IAEAlC;IAEA,OAAO;QAACF;IAAK;AACf;AAEA,wEAAwE,GACxE,eAAec,iBAAiBlB,MAAc;IAC5C,IAAI;QACF,OAAO,AAAC,CAAA,MAAMvB,SAASC,KAAK+D,IAAI,CAACzC,QAAQlB,qBAAqB,OAAM,EAAG4D,IAAI,MAAMC;IACnF,EAAE,OAAM;QACN,OAAOA;IACT;AACF"}
|
|
@@ -7,7 +7,7 @@ export function getWorkbenchUrl(organizationId) {
|
|
|
7
7
|
return `https://${organizationId}.${isStaging() ? 'run.sanity.work' : 'sanity.run'}`;
|
|
8
8
|
}
|
|
9
9
|
/** Where a deployed application is served on its organization's workbench. */ export function getApplicationUrl(application) {
|
|
10
|
-
const segment = application.type === 'studio' ? '
|
|
10
|
+
const segment = application.type === 'studio' ? 'studios' : 'applications';
|
|
11
11
|
return `${getWorkbenchUrl(application.organizationId)}/${segment}/${application.id}`;
|
|
12
12
|
}
|
|
13
13
|
async function getClient() {
|