@sanity/workbench-cli 2.7.0 → 2.8.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/actions/build/vite/discover-shared-dependencies.js +7 -2
- package/dist/actions/build/vite/discover-shared-dependencies.js.map +1 -1
- package/dist/actions/build/vite/plugin.js +3 -1
- package/dist/actions/build/vite/plugin.js.map +1 -1
- package/dist/actions/build/vite/plugins/plugin-federation-host.js +46 -0
- package/dist/actions/build/vite/plugins/plugin-federation-host.js.map +1 -0
- package/dist/actions/build/vite/plugins/plugin-sanity-environment.js +5 -5
- package/dist/actions/build/vite/plugins/plugin-sanity-environment.js.map +1 -1
- package/dist/actions/build/vite/shared-dependencies.js.map +1 -1
- package/package.json +3 -3
|
@@ -2,6 +2,7 @@ import { readFile } from 'node:fs/promises';
|
|
|
2
2
|
import path from 'node:path';
|
|
3
3
|
import { createBuilder, createLogger } from 'vite';
|
|
4
4
|
import { FEDERATION_DIR_NAME } from './constants.js';
|
|
5
|
+
import { getFederationHostApi } from './plugins/plugin-federation-host.js';
|
|
5
6
|
import { getFederationApi } from './plugins/plugin-module-federation.js';
|
|
6
7
|
import { aliasMayRewriteSharedImport, createFederationSharing, findSharedDependencyName } from './shared-dependencies.js';
|
|
7
8
|
export async function buildFederatedApp(config, { reuseStandaloneBuild = false } = {}) {
|
|
@@ -30,7 +31,10 @@ export async function buildFederatedApp(config, { reuseStandaloneBuild = false }
|
|
|
30
31
|
}
|
|
31
32
|
const firstFederationPlugin = plugins.find((plugin)=>plugin.api?.sanityFederation === federation);
|
|
32
33
|
const sharing = discovery.getSharing();
|
|
33
|
-
const
|
|
34
|
+
const enabledSharing = 'disabledReason' in sharing ? undefined : sharing;
|
|
35
|
+
const host = getFederationHostApi(plugins);
|
|
36
|
+
if (host) host.sharing = enabledSharing;
|
|
37
|
+
const replacement = federation.create(enabledSharing);
|
|
34
38
|
const builder = await createBuilder({
|
|
35
39
|
...config,
|
|
36
40
|
plugins: plugins.flatMap((plugin)=>{
|
|
@@ -48,7 +52,8 @@ export async function buildFederatedApp(config, { reuseStandaloneBuild = false }
|
|
|
48
52
|
customLogger: builder.config.customLogger
|
|
49
53
|
}).warn(`Dependency sharing disabled: ${sharing.disabledReason}. Dependencies will be bundled locally.`);
|
|
50
54
|
}
|
|
51
|
-
|
|
55
|
+
// A reused standalone build served the host module before discovery settled its providers.
|
|
56
|
+
await (reuseStandaloneBuild && !host?.requested ? builder.build(builder.environments[FEDERATION_DIR_NAME]) : builder.buildApp());
|
|
52
57
|
}
|
|
53
58
|
async function scanDependencies(config, plugins, discovery, inputs) {
|
|
54
59
|
const discoveryComplete = new Error('Shared dependency discovery complete');
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/actions/build/vite/discover-shared-dependencies.ts"],"sourcesContent":["import {readFile} from 'node:fs/promises'\nimport path from 'node:path'\n\nimport {createBuilder, createLogger, type InlineConfig, type Plugin, type PluginOption} from 'vite'\n\nimport {FEDERATION_DIR_NAME} from './constants.js'\nimport {getFederationApi} from './plugins/plugin-module-federation.js'\nimport {\n aliasMayRewriteSharedImport,\n createFederationSharing,\n findSharedDependencyName,\n type ResolvedDependency,\n} from './shared-dependencies.js'\n\nexport async function buildFederatedApp(\n config: InlineConfig,\n {\n reuseStandaloneBuild = false,\n }: {\n // Only the unmodified CLI config guarantees matching resolution in both environments.\n reuseStandaloneBuild?: boolean\n } = {},\n): Promise<void> {\n const plugins = await resolvePlugins(config.plugins ?? [])\n const federation = getFederationApi(plugins)\n if (!federation) {\n const builder = await createBuilder(config)\n await builder.buildApp()\n return\n }\n\n // Loading remote-only exposes in the SPA can emit worker bundles even when their imports are unused.\n reuseStandaloneBuild &&= !federation.hasAdditionalExposes\n const discovery = createSharedDependencyDiscovery(\n reuseStandaloneBuild ? 'client' : FEDERATION_DIR_NAME,\n )\n const localPlugins = plugins.filter((plugin) => plugin.api?.sanityFederation !== federation)\n\n if (reuseStandaloneBuild) {\n const standalone = await createBuilder({\n ...config,\n plugins: [...localPlugins, discovery.plugin],\n })\n await standalone.build(standalone.environments.client)\n } else {\n await scanDependencies(config, localPlugins, discovery.plugin, federation.inputs)\n }\n\n const firstFederationPlugin = plugins.find(\n (plugin) => plugin.api?.sanityFederation === federation,\n )\n const sharing = discovery.getSharing()\n const replacement = federation.create('disabledReason' in sharing ? undefined : sharing)\n const builder = await createBuilder({\n ...config,\n plugins: plugins.flatMap((plugin): PluginOption[] => {\n if (plugin === firstFederationPlugin) return [replacement]\n return plugin.api?.sanityFederation === federation ? [] : [plugin]\n }),\n })\n if ('disabledReason' in sharing) {\n // CLI builds silence Vite's progress output; keep the reason for disabled sharing visible.\n createLogger('warn', {customLogger: builder.config.customLogger}).warn(\n `Dependency sharing disabled: ${sharing.disabledReason}. Dependencies will be bundled locally.`,\n )\n }\n await (reuseStandaloneBuild\n ? builder.build(builder.environments[FEDERATION_DIR_NAME])\n : builder.buildApp())\n}\n\nasync function scanDependencies(\n config: InlineConfig,\n plugins: Plugin[],\n discovery: Plugin,\n inputs: string[],\n): Promise<void> {\n const discoveryComplete = new Error('Shared dependency discovery complete')\n const scanner = await createBuilder({\n ...config,\n // Vite would log our intentional stop as a build failure, so silence its logger during the scan.\n // The catch below ignores only that stop signal and rethrows real errors for the CLI to report.\n logLevel: 'silent',\n plugins: [\n ...plugins.map((plugin): Plugin => ({\n ...plugin,\n // The scan needs import hooks, while output hooks would emit or upload a second build.\n augmentChunkHash: undefined,\n buildEnd: undefined,\n closeBundle: undefined,\n generateBundle: undefined,\n outputOptions: undefined,\n renderChunk: undefined,\n renderError: undefined,\n renderStart: undefined,\n writeBundle: undefined,\n })),\n discovery,\n {\n buildEnd(error) {\n // Vite has no scan-only build API; stop after the graph, before generating unused chunks.\n if (!error) throw discoveryComplete\n },\n config: () => ({\n environments: {\n [FEDERATION_DIR_NAME]: {\n build: {\n minify: false,\n sourcemap: false,\n write: false,\n ...(inputs.length > 0 ? {rolldownOptions: {input: inputs}} : {}),\n },\n },\n },\n }),\n enforce: 'post',\n name: 'sanity/shared-discovery-build',\n },\n ],\n })\n try {\n await scanner.build(scanner.environments[FEDERATION_DIR_NAME])\n } catch (error) {\n // Rolldown groups hook errors; only suppress our marker when no other hook failed.\n const errors = error instanceof Error && 'errors' in error ? error.errors : [error]\n if (!Array.isArray(errors) || errors.length !== 1 || errors[0] !== discoveryComplete) {\n throw error\n }\n }\n}\n\nasync function resolvePlugins(options: PluginOption[]): Promise<Plugin[]> {\n // Vite flattens PluginOption internally, but discovery needs concrete plugins before createBuilder runs.\n const plugins = (await Promise.all(options))\n .flatMap((plugin) => (Array.isArray(plugin) ? plugin : [plugin]))\n .filter(Boolean)\n return plugins.some((plugin) => plugin instanceof Promise || Array.isArray(plugin))\n ? resolvePlugins(plugins)\n : (plugins as Plugin[])\n}\n\nfunction createSharedDependencyDiscovery(environmentName: string): {\n getSharing: () => ReturnType<typeof createFederationSharing>\n plugin: Plugin\n} {\n const dependencies: ResolvedDependency[] = []\n const packageCache = new Map<string, Promise<ResolvedDependency | undefined>>()\n let disabledReason: string | undefined\n\n async function findSharedPackage(id: string): Promise<ResolvedDependency | undefined> {\n let directory = path.dirname(id)\n while (directory !== path.dirname(directory)) {\n const manifest = await readPackageManifest(directory)\n if (!manifest) {\n directory = path.dirname(directory)\n continue\n }\n\n if (!manifest.name || findSharedDependencyName(manifest.name) !== manifest.name) return\n if (!manifest.version) {\n disabledReason ??= `${manifest.name} has no version in its package.json`\n return\n }\n return {name: manifest.name, root: directory, version: manifest.version}\n }\n }\n\n async function packageForModule(id: string): Promise<ResolvedDependency | undefined> {\n // Virtual module IDs and transform query suffixes do not map to a package.json on disk.\n if (!path.isAbsolute(id) || id.includes('?')) return\n const directory = path.dirname(id)\n const cached = packageCache.get(directory)\n if (cached) return cached\n\n const pending = findSharedPackage(id)\n packageCache.set(directory, pending)\n return pending\n }\n\n const plugin: Plugin = {\n apply: 'build',\n applyToEnvironment: (environment) => environment.name === environmentName,\n configResolved(config) {\n if (!config.isProduction) disabledReason ??= 'This is not a production build'\n const alias = config.resolve.alias.find(({find}) => aliasMayRewriteSharedImport(find))\n if (alias)\n disabledReason ??= `The Vite alias ${String(alias.find)} may rewrite a shared dependency import`\n },\n enforce: 'pre',\n // Relative imports can reach a second installed copy without a bare package import.\n async moduleParsed(module) {\n const dependency = await packageForModule(module.id)\n if (dependency) dependencies.push(dependency)\n },\n name: 'sanity/shared-discovery',\n async resolveId(source, importer, options) {\n const dependencyName = findSharedDependencyName(source)\n if (!dependencyName) return\n\n const resolved = await this.resolve(source, importer, {...options, skipSelf: true})\n if (!resolved || resolved.external) {\n disabledReason ??= resolved?.external\n ? `${source} is external to the build`\n : `${source} could not be resolved`\n return resolved\n }\n\n const dependency = await packageForModule(resolved.id)\n if (!dependency || dependency.name !== dependencyName) {\n disabledReason ??= `${source} does not resolve to an installed ${dependencyName} package`\n } else dependencies.push({...dependency, specifier: source})\n return resolved\n },\n }\n\n return {\n getSharing: () => (disabledReason ? {disabledReason} : createFederationSharing(dependencies)),\n plugin,\n }\n}\n\nasync function readPackageManifest(\n directory: string,\n): Promise<{name?: string; version?: string} | undefined> {\n try {\n return JSON.parse(await readFile(path.join(directory, 'package.json'), 'utf8')) as {\n name?: string\n version?: string\n }\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined\n throw error\n }\n}\n"],"names":["readFile","path","createBuilder","createLogger","FEDERATION_DIR_NAME","getFederationApi","aliasMayRewriteSharedImport","createFederationSharing","findSharedDependencyName","buildFederatedApp","config","reuseStandaloneBuild","plugins","resolvePlugins","federation","builder","buildApp","hasAdditionalExposes","discovery","createSharedDependencyDiscovery","localPlugins","filter","plugin","api","sanityFederation","standalone","build","environments","client","scanDependencies","inputs","firstFederationPlugin","find","sharing","getSharing","replacement","create","undefined","flatMap","customLogger","warn","disabledReason","discoveryComplete","Error","scanner","logLevel","map","augmentChunkHash","buildEnd","closeBundle","generateBundle","outputOptions","renderChunk","renderError","renderStart","writeBundle","error","minify","sourcemap","write","length","rolldownOptions","input","enforce","name","errors","Array","isArray","options","Promise","all","Boolean","some","environmentName","dependencies","packageCache","Map","findSharedPackage","id","directory","dirname","manifest","readPackageManifest","version","root","packageForModule","isAbsolute","includes","cached","get","pending","set","apply","applyToEnvironment","environment","configResolved","isProduction","alias","resolve","String","moduleParsed","module","dependency","push","resolveId","source","importer","dependencyName","resolved","skipSelf","external","specifier","JSON","parse","join","code"],"mappings":"AAAA,SAAQA,QAAQ,QAAO,mBAAkB;AACzC,OAAOC,UAAU,YAAW;AAE5B,SAAQC,aAAa,EAAEC,YAAY,QAA0D,OAAM;AAEnG,SAAQC,mBAAmB,QAAO,iBAAgB;AAClD,SAAQC,gBAAgB,QAAO,wCAAuC;AACtE,SACEC,2BAA2B,EAC3BC,uBAAuB,EACvBC,wBAAwB,QAEnB,2BAA0B;AAEjC,OAAO,eAAeC,kBACpBC,MAAoB,EACpB,EACEC,uBAAuB,KAAK,EAI7B,GAAG,CAAC,CAAC;IAEN,MAAMC,UAAU,MAAMC,eAAeH,OAAOE,OAAO,IAAI,EAAE;IACzD,MAAME,aAAaT,iBAAiBO;IACpC,IAAI,CAACE,YAAY;QACf,MAAMC,UAAU,MAAMb,cAAcQ;QACpC,MAAMK,QAAQC,QAAQ;QACtB;IACF;IAEA,qGAAqG;IACrGL,yBAAyB,CAACG,WAAWG,oBAAoB;IACzD,MAAMC,YAAYC,gCAChBR,uBAAuB,WAAWP;IAEpC,MAAMgB,eAAeR,QAAQS,MAAM,CAAC,CAACC,SAAWA,OAAOC,GAAG,EAAEC,qBAAqBV;IAEjF,IAAIH,sBAAsB;QACxB,MAAMc,aAAa,MAAMvB,cAAc;YACrC,GAAGQ,MAAM;YACTE,SAAS;mBAAIQ;gBAAcF,UAAUI,MAAM;aAAC;QAC9C;QACA,MAAMG,WAAWC,KAAK,CAACD,WAAWE,YAAY,CAACC,MAAM;IACvD,OAAO;QACL,MAAMC,iBAAiBnB,QAAQU,cAAcF,UAAUI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D,IAAIwB,YAAY5B,aAAa6B,IAAI,CAACD;QACpC;QACAtC,MAAM;QACN,MAAMwC,WAAUC,MAAM,EAAEC,QAAQ,EAAEtC,OAAO;YACvC,MAAMuC,iBAAiBnG,yBAAyBiG;YAChD,IAAI,CAACE,gBAAgB;YAErB,MAAMC,WAAW,MAAM,IAAI,CAACV,OAAO,CAACO,QAAQC,UAAU;gBAAC,GAAGtC,OAAO;gBAAEyC,UAAU;YAAI;YACjF,IAAI,CAACD,YAAYA,SAASE,QAAQ,EAAE;gBAClCrE,mBAAmBmE,UAAUE,WACzB,GAAGL,OAAO,yBAAyB,CAAC,GACpC,GAAGA,OAAO,sBAAsB,CAAC;gBACrC,OAAOG;YACT;YAEA,MAAMN,aAAa,MAAMjB,iBAAiBuB,SAAS9B,EAAE;YACrD,IAAI,CAACwB,cAAcA,WAAWtC,IAAI,KAAK2C,gBAAgB;gBACrDlE,mBAAmB,GAAGgE,OAAO,kCAAkC,EAAEE,eAAe,QAAQ,CAAC;YAC3F,OAAOjC,aAAa6B,IAAI,CAAC;gBAAC,GAAGD,UAAU;gBAAES,WAAWN;YAAM;YAC1D,OAAOG;QACT;IACF;IAEA,OAAO;QACL1E,YAAY,IAAOO,iBAAiB;gBAACA;YAAc,IAAIlC,wBAAwBmE;QAC/EpD;IACF;AACF;AAEA,eAAe4D,oBACbH,SAAiB;IAEjB,IAAI;QACF,OAAOiC,KAAKC,KAAK,CAAC,MAAMjH,SAASC,KAAKiH,IAAI,CAACnC,WAAW,iBAAiB;IAIzE,EAAE,OAAOvB,OAAO;QACd,IAAI,AAACA,MAAgC2D,IAAI,KAAK,UAAU,OAAO9E;QAC/D,MAAMmB;IACR;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../src/actions/build/vite/discover-shared-dependencies.ts"],"sourcesContent":["import {readFile} from 'node:fs/promises'\nimport path from 'node:path'\n\nimport {createBuilder, createLogger, type InlineConfig, type Plugin, type PluginOption} from 'vite'\n\nimport {FEDERATION_DIR_NAME} from './constants.js'\nimport {getFederationHostApi} from './plugins/plugin-federation-host.js'\nimport {getFederationApi} from './plugins/plugin-module-federation.js'\nimport {\n aliasMayRewriteSharedImport,\n createFederationSharing,\n findSharedDependencyName,\n type ResolvedDependency,\n} from './shared-dependencies.js'\n\nexport async function buildFederatedApp(\n config: InlineConfig,\n {\n reuseStandaloneBuild = false,\n }: {\n // Only the unmodified CLI config guarantees matching resolution in both environments.\n reuseStandaloneBuild?: boolean\n } = {},\n): Promise<void> {\n const plugins = await resolvePlugins(config.plugins ?? [])\n const federation = getFederationApi(plugins)\n if (!federation) {\n const builder = await createBuilder(config)\n await builder.buildApp()\n return\n }\n\n // Loading remote-only exposes in the SPA can emit worker bundles even when their imports are unused.\n reuseStandaloneBuild &&= !federation.hasAdditionalExposes\n const discovery = createSharedDependencyDiscovery(\n reuseStandaloneBuild ? 'client' : FEDERATION_DIR_NAME,\n )\n const localPlugins = plugins.filter((plugin) => plugin.api?.sanityFederation !== federation)\n\n if (reuseStandaloneBuild) {\n const standalone = await createBuilder({\n ...config,\n plugins: [...localPlugins, discovery.plugin],\n })\n await standalone.build(standalone.environments.client)\n } else {\n await scanDependencies(config, localPlugins, discovery.plugin, federation.inputs)\n }\n\n const firstFederationPlugin = plugins.find(\n (plugin) => plugin.api?.sanityFederation === federation,\n )\n const sharing = discovery.getSharing()\n const enabledSharing = 'disabledReason' in sharing ? undefined : sharing\n const host = getFederationHostApi(plugins)\n if (host) host.sharing = enabledSharing\n const replacement = federation.create(enabledSharing)\n const builder = await createBuilder({\n ...config,\n plugins: plugins.flatMap((plugin): PluginOption[] => {\n if (plugin === firstFederationPlugin) return [replacement]\n return plugin.api?.sanityFederation === federation ? [] : [plugin]\n }),\n })\n if ('disabledReason' in sharing) {\n // CLI builds silence Vite's progress output; keep the reason for disabled sharing visible.\n createLogger('warn', {customLogger: builder.config.customLogger}).warn(\n `Dependency sharing disabled: ${sharing.disabledReason}. Dependencies will be bundled locally.`,\n )\n }\n // A reused standalone build served the host module before discovery settled its providers.\n await (reuseStandaloneBuild && !host?.requested\n ? builder.build(builder.environments[FEDERATION_DIR_NAME])\n : builder.buildApp())\n}\n\nasync function scanDependencies(\n config: InlineConfig,\n plugins: Plugin[],\n discovery: Plugin,\n inputs: string[],\n): Promise<void> {\n const discoveryComplete = new Error('Shared dependency discovery complete')\n const scanner = await createBuilder({\n ...config,\n // Vite would log our intentional stop as a build failure, so silence its logger during the scan.\n // The catch below ignores only that stop signal and rethrows real errors for the CLI to report.\n logLevel: 'silent',\n plugins: [\n ...plugins.map((plugin): Plugin => ({\n ...plugin,\n // The scan needs import hooks, while output hooks would emit or upload a second build.\n augmentChunkHash: undefined,\n buildEnd: undefined,\n closeBundle: undefined,\n generateBundle: undefined,\n outputOptions: undefined,\n renderChunk: undefined,\n renderError: undefined,\n renderStart: undefined,\n writeBundle: undefined,\n })),\n discovery,\n {\n buildEnd(error) {\n // Vite has no scan-only build API; stop after the graph, before generating unused chunks.\n if (!error) throw discoveryComplete\n },\n config: () => ({\n environments: {\n [FEDERATION_DIR_NAME]: {\n build: {\n minify: false,\n sourcemap: false,\n write: false,\n ...(inputs.length > 0 ? {rolldownOptions: {input: inputs}} : {}),\n },\n },\n },\n }),\n enforce: 'post',\n name: 'sanity/shared-discovery-build',\n },\n ],\n })\n try {\n await scanner.build(scanner.environments[FEDERATION_DIR_NAME])\n } catch (error) {\n // Rolldown groups hook errors; only suppress our marker when no other hook failed.\n const errors = error instanceof Error && 'errors' in error ? error.errors : [error]\n if (!Array.isArray(errors) || errors.length !== 1 || errors[0] !== discoveryComplete) {\n throw error\n }\n }\n}\n\nasync function resolvePlugins(options: PluginOption[]): Promise<Plugin[]> {\n // Vite flattens PluginOption internally, but discovery needs concrete plugins before createBuilder runs.\n const plugins = (await Promise.all(options))\n .flatMap((plugin) => (Array.isArray(plugin) ? plugin : [plugin]))\n .filter(Boolean)\n return plugins.some((plugin) => plugin instanceof Promise || Array.isArray(plugin))\n ? resolvePlugins(plugins)\n : (plugins as Plugin[])\n}\n\nfunction createSharedDependencyDiscovery(environmentName: string): {\n getSharing: () => ReturnType<typeof createFederationSharing>\n plugin: Plugin\n} {\n const dependencies: ResolvedDependency[] = []\n const packageCache = new Map<string, Promise<ResolvedDependency | undefined>>()\n let disabledReason: string | undefined\n\n async function findSharedPackage(id: string): Promise<ResolvedDependency | undefined> {\n let directory = path.dirname(id)\n while (directory !== path.dirname(directory)) {\n const manifest = await readPackageManifest(directory)\n if (!manifest) {\n directory = path.dirname(directory)\n continue\n }\n\n if (!manifest.name || findSharedDependencyName(manifest.name) !== manifest.name) return\n if (!manifest.version) {\n disabledReason ??= `${manifest.name} has no version in its package.json`\n return\n }\n return {name: manifest.name, root: directory, version: manifest.version}\n }\n }\n\n async function packageForModule(id: string): Promise<ResolvedDependency | undefined> {\n // Virtual module IDs and transform query suffixes do not map to a package.json on disk.\n if (!path.isAbsolute(id) || id.includes('?')) return\n const directory = path.dirname(id)\n const cached = packageCache.get(directory)\n if (cached) return cached\n\n const pending = findSharedPackage(id)\n packageCache.set(directory, pending)\n return pending\n }\n\n const plugin: Plugin = {\n apply: 'build',\n applyToEnvironment: (environment) => environment.name === environmentName,\n configResolved(config) {\n if (!config.isProduction) disabledReason ??= 'This is not a production build'\n const alias = config.resolve.alias.find(({find}) => aliasMayRewriteSharedImport(find))\n if (alias)\n disabledReason ??= `The Vite alias ${String(alias.find)} may rewrite a shared dependency import`\n },\n enforce: 'pre',\n // Relative imports can reach a second installed copy without a bare package import.\n async moduleParsed(module) {\n const dependency = await packageForModule(module.id)\n if (dependency) dependencies.push(dependency)\n },\n name: 'sanity/shared-discovery',\n async resolveId(source, importer, options) {\n const dependencyName = findSharedDependencyName(source)\n if (!dependencyName) return\n\n const resolved = await this.resolve(source, importer, {...options, skipSelf: true})\n if (!resolved || resolved.external) {\n disabledReason ??= resolved?.external\n ? `${source} is external to the build`\n : `${source} could not be resolved`\n return resolved\n }\n\n const dependency = await packageForModule(resolved.id)\n if (!dependency || dependency.name !== dependencyName) {\n disabledReason ??= `${source} does not resolve to an installed ${dependencyName} package`\n } else dependencies.push({...dependency, specifier: source})\n return resolved\n },\n }\n\n return {\n getSharing: () => (disabledReason ? {disabledReason} : createFederationSharing(dependencies)),\n plugin,\n }\n}\n\nasync function readPackageManifest(\n directory: string,\n): Promise<{name?: string; version?: string} | undefined> {\n try {\n return JSON.parse(await readFile(path.join(directory, 'package.json'), 'utf8')) as {\n name?: string\n version?: string\n }\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined\n throw error\n }\n}\n"],"names":["readFile","path","createBuilder","createLogger","FEDERATION_DIR_NAME","getFederationHostApi","getFederationApi","aliasMayRewriteSharedImport","createFederationSharing","findSharedDependencyName","buildFederatedApp","config","reuseStandaloneBuild","plugins","resolvePlugins","federation","builder","buildApp","hasAdditionalExposes","discovery","createSharedDependencyDiscovery","localPlugins","filter","plugin","api","sanityFederation","standalone","build","environments","client","scanDependencies","inputs","firstFederationPlugin","find","sharing","getSharing","enabledSharing","undefined","host","replacement","create","flatMap","customLogger","warn","disabledReason","requested","discoveryComplete","Error","scanner","logLevel","map","augmentChunkHash","buildEnd","closeBundle","generateBundle","outputOptions","renderChunk","renderError","renderStart","writeBundle","error","minify","sourcemap","write","length","rolldownOptions","input","enforce","name","errors","Array","isArray","options","Promise","all","Boolean","some","environmentName","dependencies","packageCache","Map","findSharedPackage","id","directory","dirname","manifest","readPackageManifest","version","root","packageForModule","isAbsolute","includes","cached","get","pending","set","apply","applyToEnvironment","environment","configResolved","isProduction","alias","resolve","String","moduleParsed","module","dependency","push","resolveId","source","importer","dependencyName","resolved","skipSelf","external","specifier","JSON","parse","join","code"],"mappings":"AAAA,SAAQA,QAAQ,QAAO,mBAAkB;AACzC,OAAOC,UAAU,YAAW;AAE5B,SAAQC,aAAa,EAAEC,YAAY,QAA0D,OAAM;AAEnG,SAAQC,mBAAmB,QAAO,iBAAgB;AAClD,SAAQC,oBAAoB,QAAO,sCAAqC;AACxE,SAAQC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YA,SAASE,QAAQ,EAAE;gBAClCtE,mBAAmBoE,UAAUE,WACzB,GAAGL,OAAO,yBAAyB,CAAC,GACpC,GAAGA,OAAO,sBAAsB,CAAC;gBACrC,OAAOG;YACT;YAEA,MAAMN,aAAa,MAAMjB,iBAAiBuB,SAAS9B,EAAE;YACrD,IAAI,CAACwB,cAAcA,WAAWtC,IAAI,KAAK2C,gBAAgB;gBACrDnE,mBAAmB,GAAGiE,OAAO,kCAAkC,EAAEE,eAAe,QAAQ,CAAC;YAC3F,OAAOjC,aAAa6B,IAAI,CAAC;gBAAC,GAAGD,UAAU;gBAAES,WAAWN;YAAM;YAC1D,OAAOG;QACT;IACF;IAEA,OAAO;QACL7E,YAAY,IAAOS,iBAAiB;gBAACA;YAAc,IAAIpC,wBAAwBsE;QAC/EvD;IACF;AACF;AAEA,eAAe+D,oBACbH,SAAiB;IAEjB,IAAI;QACF,OAAOiC,KAAKC,KAAK,CAAC,MAAMrH,SAASC,KAAKqH,IAAI,CAACnC,WAAW,iBAAiB;IAIzE,EAAE,OAAOvB,OAAO;QACd,IAAI,AAACA,MAAgC2D,IAAI,KAAK,UAAU,OAAOlF;QAC/D,MAAMuB;IACR;AACF"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import path from 'node:path';
|
|
2
2
|
import { artifactExposes, workbenchArtifacts } from '../artifact.js';
|
|
3
3
|
import { FEDERATION_FILE_NAME, RUNTIME_DIR } from './constants.js';
|
|
4
|
+
import { sanityFederationHost } from './plugins/plugin-federation-host.js';
|
|
4
5
|
import { sanityModuleFederation } from './plugins/plugin-module-federation.js';
|
|
5
6
|
import { sanityEnvironmentPlugin } from './plugins/plugin-sanity-environment.js';
|
|
6
7
|
import { sanityExtensionArtifacts } from './plugins/plugin-sanity-extension-artifacts.js';
|
|
@@ -67,7 +68,8 @@ import { sanityFederationRuntime } from './plugins/plugin-sanity-federation-runt
|
|
|
67
68
|
sanityModuleFederation({
|
|
68
69
|
exposes: federationExposes,
|
|
69
70
|
name
|
|
70
|
-
})
|
|
71
|
+
}),
|
|
72
|
+
sanityFederationHost()
|
|
71
73
|
];
|
|
72
74
|
};
|
|
73
75
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/actions/build/vite/plugin.ts"],"sourcesContent":["import path from 'node:path'\n\nimport {type ModuleFederationOptions} from '@module-federation/vite'\nimport {type PackageJson} from '@sanity/cli-core'\nimport {type PluginOption} from 'vite'\n\nimport {type WorkbenchExposes} from '../../../resolveWorkbenchApp.js'\nimport {artifactExposes, workbenchArtifacts} from '../artifact.js'\nimport {FEDERATION_FILE_NAME, RUNTIME_DIR} from './constants.js'\nimport {type FederationOptions, sanityModuleFederation} from './plugins/plugin-module-federation.js'\nimport {sanityEnvironmentPlugin} from './plugins/plugin-sanity-environment.js'\nimport {sanityExtensionArtifacts} from './plugins/plugin-sanity-extension-artifacts.js'\nimport {\n type FederationRuntimeOptions,\n sanityFederationRuntime,\n} from './plugins/plugin-sanity-federation-runtime.js'\n\ninterface FederationPluginOptionsBase extends Omit<Partial<FederationOptions>, 'exposes'> {\n exposes?: WorkbenchExposes\n /** Blueprints build (via `@sanity/runtime-cli`) — emit the resource-bindings module. */\n isBlueprints?: boolean\n pkgJson?: PackageJson\n /**\n * Current working directory to read package.json from, defaults to process.cwd()\n */\n workDir?: string\n}\n\ninterface AppFederationPluginOptions extends FederationPluginOptionsBase {\n isApp: true\n\n /**\n * Relative path to the App entry from the runtime directory, e.g.\n * `../../src/App.tsx`. Omit it for a dock-only app that declares no `entry`:\n * no `./App` is exposed and the remote serves only its views.\n */\n appEntry?: string\n studioConfigPath?: never\n}\n\ninterface StudioFederationPluginOptions extends FederationPluginOptionsBase {\n /** relative path to the Studio config file from the runtime directory (e.g. `../../sanity.config.ts`). */\n studioConfigPath: string\n\n appEntry?: never\n /** @defaultValue false */\n isApp?: false\n}\n\n/**\n * Plugin options for the federation vite plugin.\n *\n * Discriminated on `isApp`:\n * - `isApp: true` → requires `appEntry`\n * - `isApp: false` (default) → requires `studioConfigPath`\n *\n * @internal\n */\ntype FederationPluginOptions = AppFederationPluginOptions | StudioFederationPluginOptions\n\n/**\n * @internal\n */\nexport const federation = (options: FederationPluginOptions): PluginOption => {\n const {exposes, isBlueprints, name: defaultName, pkgJson, workDir = process.cwd()} = options\n\n let name = defaultName\n\n if (!name) {\n name = pkgJson?.name\n }\n\n if (!name) {\n throw new Error('\"name\" option is required but could not be inferred from package.json')\n }\n\n const generatedEntry = `./${RUNTIME_DIR}/${FEDERATION_FILE_NAME}.jsx`\n\n function resolveEntryPath(entry: string) {\n const resolvedPath = path.resolve(workDir, entry)\n\n if (!resolvedPath) {\n throw new Error(\n `Could not resolve path for entry \"${entry}\". Please check that the file exists and the path is correct.`,\n )\n }\n\n return resolvedPath\n }\n\n const entryPath = resolveEntryPath(generatedEntry)\n\n // Each view component (`./views/<view>/<component>`) and each service loader\n // (`./services/<name>`) is exposed straight to the host, pointing at the file\n // the extension-artifacts plugin generates under RUNTIME_DIR. A service's\n // worker bundle carries no expose — the host reaches it through its loader.\n const artifacts = workbenchArtifacts(exposes ?? {})\n const artifactModuleExposes = artifactExposes(artifacts, (artifactPath) =>\n resolveEntryPath(`./${RUNTIME_DIR}/${artifactPath}`),\n )\n\n // A dock-only app (`isApp` with no `appEntry`) has no navigable full-page\n // view, so it exposes no `./App` — only its views. Studios and apps with an\n // entry expose `./App` (the generated render entry).\n const exposesApp = !options.isApp || options.appEntry !== undefined\n\n const federationExposes: NonNullable<ModuleFederationOptions['exposes']> = {\n ...(exposesApp ? {'./App': entryPath} : {}),\n ...artifactModuleExposes,\n }\n\n const runtimeOptions: FederationRuntimeOptions = options.isApp\n ? {appEntry: options.appEntry, isApp: true, isBlueprints}\n : {isApp: false, isBlueprints, studioConfigPath: options.studioConfigPath}\n\n // Every federated app and studio also serves itself standalone. Whenever there's\n // an `./App` to mount (never for a dock-only app), build the SPA client\n // environment from the runtime bootstrap cli-build writes.\n const clientInput = exposesApp ? path.join(workDir, '.sanity', 'runtime', 'app.js') : undefined\n\n return [\n sanityEnvironmentPlugin({clientInput, input: entryPath, isBlueprints}),\n sanityFederationRuntime(runtimeOptions),\n sanityExtensionArtifacts({artifacts}),\n sanityModuleFederation({exposes: federationExposes, name}),\n ]\n}\n"],"names":["path","artifactExposes","workbenchArtifacts","FEDERATION_FILE_NAME","RUNTIME_DIR","sanityModuleFederation","sanityEnvironmentPlugin","sanityExtensionArtifacts","sanityFederationRuntime","federation","options","exposes","isBlueprints","name","defaultName","pkgJson","workDir","process","cwd","Error","generatedEntry","resolveEntryPath","entry","resolvedPath","resolve","entryPath","artifacts","artifactModuleExposes","artifactPath","exposesApp","isApp","appEntry","undefined","federationExposes","runtimeOptions","studioConfigPath","clientInput","join","input"],"mappings":"AAAA,OAAOA,UAAU,YAAW;AAO5B,SAAQC,eAAe,EAAEC,kBAAkB,QAAO,iBAAgB;AAClE,SAAQC,oBAAoB,EAAEC,WAAW,QAAO,iBAAgB;AAChE,SAAgCC,sBAAsB,QAAO,wCAAuC;AACpG,SAAQC,uBAAuB,QAAO,yCAAwC;AAC9E,SAAQC,wBAAwB,QAAO,iDAAgD;AACvF,SAEEC,uBAAuB,QAClB,gDAA+C;AA6CtD;;CAEC,GACD,OAAO,MAAMC,aAAa,CAACC;IACzB,MAAM,EAACC,OAAO,EAAEC,YAAY,EAAEC,MAAMC,WAAW,EAAEC,OAAO,EAAEC,UAAUC,QAAQC,GAAG,EAAE,EAAC,GAAGR;IAErF,IAAIG,OAAOC;IAEX,IAAI,CAACD,MAAM;QACTA,OAAOE,SAASF;IAClB;IAEA,IAAI,CAACA,MAAM;QACT,MAAM,IAAIM,MAAM;IAClB;IAEA,MAAMC,iBAAiB,CAAC,EAAE,
|
|
1
|
+
{"version":3,"sources":["../../../../src/actions/build/vite/plugin.ts"],"sourcesContent":["import path from 'node:path'\n\nimport {type ModuleFederationOptions} from '@module-federation/vite'\nimport {type PackageJson} from '@sanity/cli-core'\nimport {type PluginOption} from 'vite'\n\nimport {type WorkbenchExposes} from '../../../resolveWorkbenchApp.js'\nimport {artifactExposes, workbenchArtifacts} from '../artifact.js'\nimport {FEDERATION_FILE_NAME, RUNTIME_DIR} from './constants.js'\nimport {sanityFederationHost} from './plugins/plugin-federation-host.js'\nimport {type FederationOptions, sanityModuleFederation} from './plugins/plugin-module-federation.js'\nimport {sanityEnvironmentPlugin} from './plugins/plugin-sanity-environment.js'\nimport {sanityExtensionArtifacts} from './plugins/plugin-sanity-extension-artifacts.js'\nimport {\n type FederationRuntimeOptions,\n sanityFederationRuntime,\n} from './plugins/plugin-sanity-federation-runtime.js'\n\ninterface FederationPluginOptionsBase extends Omit<Partial<FederationOptions>, 'exposes'> {\n exposes?: WorkbenchExposes\n /** Blueprints build (via `@sanity/runtime-cli`) — emit the resource-bindings module. */\n isBlueprints?: boolean\n pkgJson?: PackageJson\n /**\n * Current working directory to read package.json from, defaults to process.cwd()\n */\n workDir?: string\n}\n\ninterface AppFederationPluginOptions extends FederationPluginOptionsBase {\n isApp: true\n\n /**\n * Relative path to the App entry from the runtime directory, e.g.\n * `../../src/App.tsx`. Omit it for a dock-only app that declares no `entry`:\n * no `./App` is exposed and the remote serves only its views.\n */\n appEntry?: string\n studioConfigPath?: never\n}\n\ninterface StudioFederationPluginOptions extends FederationPluginOptionsBase {\n /** relative path to the Studio config file from the runtime directory (e.g. `../../sanity.config.ts`). */\n studioConfigPath: string\n\n appEntry?: never\n /** @defaultValue false */\n isApp?: false\n}\n\n/**\n * Plugin options for the federation vite plugin.\n *\n * Discriminated on `isApp`:\n * - `isApp: true` → requires `appEntry`\n * - `isApp: false` (default) → requires `studioConfigPath`\n *\n * @internal\n */\ntype FederationPluginOptions = AppFederationPluginOptions | StudioFederationPluginOptions\n\n/**\n * @internal\n */\nexport const federation = (options: FederationPluginOptions): PluginOption => {\n const {exposes, isBlueprints, name: defaultName, pkgJson, workDir = process.cwd()} = options\n\n let name = defaultName\n\n if (!name) {\n name = pkgJson?.name\n }\n\n if (!name) {\n throw new Error('\"name\" option is required but could not be inferred from package.json')\n }\n\n const generatedEntry = `./${RUNTIME_DIR}/${FEDERATION_FILE_NAME}.jsx`\n\n function resolveEntryPath(entry: string) {\n const resolvedPath = path.resolve(workDir, entry)\n\n if (!resolvedPath) {\n throw new Error(\n `Could not resolve path for entry \"${entry}\". Please check that the file exists and the path is correct.`,\n )\n }\n\n return resolvedPath\n }\n\n const entryPath = resolveEntryPath(generatedEntry)\n\n // Each view component (`./views/<view>/<component>`) and each service loader\n // (`./services/<name>`) is exposed straight to the host, pointing at the file\n // the extension-artifacts plugin generates under RUNTIME_DIR. A service's\n // worker bundle carries no expose — the host reaches it through its loader.\n const artifacts = workbenchArtifacts(exposes ?? {})\n const artifactModuleExposes = artifactExposes(artifacts, (artifactPath) =>\n resolveEntryPath(`./${RUNTIME_DIR}/${artifactPath}`),\n )\n\n // A dock-only app (`isApp` with no `appEntry`) has no navigable full-page\n // view, so it exposes no `./App` — only its views. Studios and apps with an\n // entry expose `./App` (the generated render entry).\n const exposesApp = !options.isApp || options.appEntry !== undefined\n\n const federationExposes: NonNullable<ModuleFederationOptions['exposes']> = {\n ...(exposesApp ? {'./App': entryPath} : {}),\n ...artifactModuleExposes,\n }\n\n const runtimeOptions: FederationRuntimeOptions = options.isApp\n ? {appEntry: options.appEntry, isApp: true, isBlueprints}\n : {isApp: false, isBlueprints, studioConfigPath: options.studioConfigPath}\n\n // Every federated app and studio also serves itself standalone. Whenever there's\n // an `./App` to mount (never for a dock-only app), build the SPA client\n // environment from the runtime bootstrap cli-build writes.\n const clientInput = exposesApp ? path.join(workDir, '.sanity', 'runtime', 'app.js') : undefined\n\n return [\n sanityEnvironmentPlugin({clientInput, input: entryPath, isBlueprints}),\n sanityFederationRuntime(runtimeOptions),\n sanityExtensionArtifacts({artifacts}),\n sanityModuleFederation({exposes: federationExposes, name}),\n sanityFederationHost(),\n ]\n}\n"],"names":["path","artifactExposes","workbenchArtifacts","FEDERATION_FILE_NAME","RUNTIME_DIR","sanityFederationHost","sanityModuleFederation","sanityEnvironmentPlugin","sanityExtensionArtifacts","sanityFederationRuntime","federation","options","exposes","isBlueprints","name","defaultName","pkgJson","workDir","process","cwd","Error","generatedEntry","resolveEntryPath","entry","resolvedPath","resolve","entryPath","artifacts","artifactModuleExposes","artifactPath","exposesApp","isApp","appEntry","undefined","federationExposes","runtimeOptions","studioConfigPath","clientInput","join","input"],"mappings":"AAAA,OAAOA,UAAU,YAAW;AAO5B,SAAQC,eAAe,EAAEC,kBAAkB,QAAO,iBAAgB;AAClE,SAAQC,oBAAoB,EAAEC,WAAW,QAAO,iBAAgB;AAChE,SAAQC,oBAAoB,QAAO,sCAAqC;AACxE,SAAgCC,sBAAsB,QAAO,wCAAuC;AACpG,SAAQC,uBAAuB,QAAO,yCAAwC;AAC9E,SAAQC,wBAAwB,QAAO,iDAAgD;AACvF,SAEEC,uBAAuB,QAClB,gDAA+C;AA6CtD;;CAEC,GACD,OAAO,MAAMC,aAAa,CAACC;IACzB,MAAM,EAACC,OAAO,EAAEC,YAAY,EAAEC,MAAMC,WAAW,EAAEC,OAAO,EAAEC,UAAUC,QAAQC,GAAG,EAAE,EAAC,GAAGR;IAErF,IAAIG,OAAOC;IAEX,IAAI,CAACD,MAAM;QACTA,OAAOE,SAASF;IAClB;IAEA,IAAI,CAACA,MAAM;QACT,MAAM,IAAIM,MAAM;IAClB;IAEA,MAAMC,iBAAiB,CAAC,EAAE,EAAEjB,YAAY,CAAC,EAAED,qBAAqB,IAAI,CAAC;IAErE,SAASmB,iBAAiBC,KAAa;QACrC,MAAMC,eAAexB,KAAKyB,OAAO,CAACR,SAASM;QAE3C,IAAI,CAACC,cAAc;YACjB,MAAM,IAAIJ,MACR,CAAC,kCAAkC,EAAEG,MAAM,6DAA6D,CAAC;QAE7G;QAEA,OAAOC;IACT;IAEA,MAAME,YAAYJ,iBAAiBD;IAEnC,6EAA6E;IAC7E,8EAA8E;IAC9E,0EAA0E;IAC1E,4EAA4E;IAC5E,MAAMM,YAAYzB,mBAAmBU,WAAW,CAAC;IACjD,MAAMgB,wBAAwB3B,gBAAgB0B,WAAW,CAACE,eACxDP,iBAAiB,CAAC,EAAE,EAAElB,YAAY,CAAC,EAAEyB,cAAc;IAGrD,0EAA0E;IAC1E,4EAA4E;IAC5E,qDAAqD;IACrD,MAAMC,aAAa,CAACnB,QAAQoB,KAAK,IAAIpB,QAAQqB,QAAQ,KAAKC;IAE1D,MAAMC,oBAAqE;QACzE,GAAIJ,aAAa;YAAC,SAASJ;QAAS,IAAI,CAAC,CAAC;QAC1C,GAAGE,qBAAqB;IAC1B;IAEA,MAAMO,iBAA2CxB,QAAQoB,KAAK,GAC1D;QAACC,UAAUrB,QAAQqB,QAAQ;QAAED,OAAO;QAAMlB;IAAY,IACtD;QAACkB,OAAO;QAAOlB;QAAcuB,kBAAkBzB,QAAQyB,gBAAgB;IAAA;IAE3E,iFAAiF;IACjF,wEAAwE;IACxE,2DAA2D;IAC3D,MAAMC,cAAcP,aAAa9B,KAAKsC,IAAI,CAACrB,SAAS,WAAW,WAAW,YAAYgB;IAEtF,OAAO;QACL1B,wBAAwB;YAAC8B;YAAaE,OAAOb;YAAWb;QAAY;QACpEJ,wBAAwB0B;QACxB3B,yBAAyB;YAACmB;QAAS;QACnCrB,uBAAuB;YAACM,SAASsB;YAAmBpB;QAAI;QACxDT;KACD;AACH,EAAC"}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
export const FEDERATION_HOST_ID = 'virtual:sanity/federation-host';
|
|
2
|
+
const RESOLVED_ID = `\0${FEDERATION_HOST_ID}`;
|
|
3
|
+
export function getFederationHostApi(plugins) {
|
|
4
|
+
return plugins.find((plugin)=>plugin.api?.sanityFederationHost)?.api.sanityFederationHost;
|
|
5
|
+
}
|
|
6
|
+
// Hands the standalone build's own copies of shared dependencies to the apps it loads: its SPA
|
|
7
|
+
// never initializes a federation container, so each app would otherwise download a second copy.
|
|
8
|
+
export function sanityFederationHost() {
|
|
9
|
+
const api = {
|
|
10
|
+
requested: false
|
|
11
|
+
};
|
|
12
|
+
return {
|
|
13
|
+
api: {
|
|
14
|
+
sanityFederationHost: api
|
|
15
|
+
},
|
|
16
|
+
load (id) {
|
|
17
|
+
if (id !== RESOLVED_ID) return;
|
|
18
|
+
api.requested = true;
|
|
19
|
+
return federationHostModule(this.environment.name === 'client' ? api.sharing : undefined);
|
|
20
|
+
},
|
|
21
|
+
name: 'sanity/federation-host',
|
|
22
|
+
resolveId: (id)=>id === FEDERATION_HOST_ID ? RESOLVED_ID : undefined
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
function federationHostModule(sharing) {
|
|
26
|
+
const entries = Object.entries(sharing?.shared ?? {});
|
|
27
|
+
const imports = entries.map(([specifier], index)=>`import * as m${index} from ${JSON.stringify(specifier)}\n`);
|
|
28
|
+
const providers = entries.map(([specifier, entry], index)=>{
|
|
29
|
+
const { requiredVersion, shareScope, singleton, strictVersion, version } = entry;
|
|
30
|
+
const options = {
|
|
31
|
+
scope: [
|
|
32
|
+
shareScope
|
|
33
|
+
],
|
|
34
|
+
shareConfig: {
|
|
35
|
+
requiredVersion,
|
|
36
|
+
singleton,
|
|
37
|
+
strictVersion
|
|
38
|
+
},
|
|
39
|
+
version
|
|
40
|
+
};
|
|
41
|
+
return ` ${JSON.stringify(specifier)}: {...${JSON.stringify(options)}, lib: () => m${index}, loaded: true},\n`;
|
|
42
|
+
});
|
|
43
|
+
return `${imports.join('')}export const shared = {\n${providers.join('')}}\n`;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
//# sourceMappingURL=plugin-federation-host.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../src/actions/build/vite/plugins/plugin-federation-host.ts"],"sourcesContent":["import {type Plugin} from 'vite'\n\nimport {type FederationSharing} from '../shared-dependencies.js'\n\nexport const FEDERATION_HOST_ID = 'virtual:sanity/federation-host'\nconst RESOLVED_ID = `\\0${FEDERATION_HOST_ID}`\n\nexport interface FederationHostApi {\n requested: boolean\n\n sharing?: FederationSharing\n}\n\nexport function getFederationHostApi(plugins: readonly Plugin[]): FederationHostApi | undefined {\n return plugins.find((plugin) => plugin.api?.sanityFederationHost)?.api.sanityFederationHost\n}\n\n// Hands the standalone build's own copies of shared dependencies to the apps it loads: its SPA\n// never initializes a federation container, so each app would otherwise download a second copy.\nexport function sanityFederationHost(): Plugin {\n const api: FederationHostApi = {requested: false}\n return {\n api: {sanityFederationHost: api},\n load(id) {\n if (id !== RESOLVED_ID) return\n api.requested = true\n return federationHostModule(this.environment.name === 'client' ? api.sharing : undefined)\n },\n name: 'sanity/federation-host',\n resolveId: (id) => (id === FEDERATION_HOST_ID ? RESOLVED_ID : undefined),\n }\n}\n\nfunction federationHostModule(sharing: FederationSharing | undefined): string {\n const entries = Object.entries(sharing?.shared ?? {})\n const imports = entries.map(\n ([specifier], index) => `import * as m${index} from ${JSON.stringify(specifier)}\\n`,\n )\n const providers = entries.map(([specifier, entry], index) => {\n const {requiredVersion, shareScope, singleton, strictVersion, version} = entry\n const options = {\n scope: [shareScope],\n shareConfig: {requiredVersion, singleton, strictVersion},\n version,\n }\n return ` ${JSON.stringify(specifier)}: {...${JSON.stringify(options)}, lib: () => m${index}, loaded: true},\\n`\n })\n return `${imports.join('')}export const shared = {\\n${providers.join('')}}\\n`\n}\n"],"names":["FEDERATION_HOST_ID","RESOLVED_ID","getFederationHostApi","plugins","find","plugin","api","sanityFederationHost","requested","load","id","federationHostModule","environment","name","sharing","undefined","resolveId","entries","Object","shared","imports","map","specifier","index","JSON","stringify","providers","entry","requiredVersion","shareScope","singleton","strictVersion","version","options","scope","shareConfig","join"],"mappings":"AAIA,OAAO,MAAMA,qBAAqB,iCAAgC;AAClE,MAAMC,cAAc,CAAC,EAAE,EAAED,oBAAoB;AAQ7C,OAAO,SAASE,qBAAqBC,OAA0B;IAC7D,OAAOA,QAAQC,IAAI,CAAC,CAACC,SAAWA,OAAOC,GAAG,EAAEC,uBAAuBD,IAAIC;AACzE;AAEA,+FAA+F;AAC/F,gGAAgG;AAChG,OAAO,SAASA;IACd,MAAMD,MAAyB;QAACE,WAAW;IAAK;IAChD,OAAO;QACLF,KAAK;YAACC,sBAAsBD;QAAG;QAC/BG,MAAKC,EAAE;YACL,IAAIA,OAAOT,aAAa;YACxBK,IAAIE,SAAS,GAAG;YAChB,OAAOG,qBAAqB,IAAI,CAACC,WAAW,CAACC,IAAI,KAAK,WAAWP,IAAIQ,OAAO,GAAGC;QACjF;QACAF,MAAM;QACNG,WAAW,CAACN,KAAQA,OAAOV,qBAAqBC,cAAcc;IAChE;AACF;AAEA,SAASJ,qBAAqBG,OAAsC;IAClE,MAAMG,UAAUC,OAAOD,OAAO,CAACH,SAASK,UAAU,CAAC;IACnD,MAAMC,UAAUH,QAAQI,GAAG,CACzB,CAAC,CAACC,UAAU,EAAEC,QAAU,CAAC,aAAa,EAAEA,MAAM,MAAM,EAAEC,KAAKC,SAAS,CAACH,WAAW,EAAE,CAAC;IAErF,MAAMI,YAAYT,QAAQI,GAAG,CAAC,CAAC,CAACC,WAAWK,MAAM,EAAEJ;QACjD,MAAM,EAACK,eAAe,EAAEC,UAAU,EAAEC,SAAS,EAAEC,aAAa,EAAEC,OAAO,EAAC,GAAGL;QACzE,MAAMM,UAAU;YACdC,OAAO;gBAACL;aAAW;YACnBM,aAAa;gBAACP;gBAAiBE;gBAAWC;YAAa;YACvDC;QACF;QACA,OAAO,CAAC,EAAE,EAAER,KAAKC,SAAS,CAACH,WAAW,MAAM,EAAEE,KAAKC,SAAS,CAACQ,SAAS,cAAc,EAAEV,MAAM,kBAAkB,CAAC;IACjH;IACA,OAAO,GAAGH,QAAQgB,IAAI,CAAC,IAAI,yBAAyB,EAAEV,UAAUU,IAAI,CAAC,IAAI,GAAG,CAAC;AAC/E"}
|
|
@@ -23,9 +23,11 @@ export function sanityEnvironmentPlugin(options) {
|
|
|
23
23
|
return {
|
|
24
24
|
builder: {
|
|
25
25
|
async buildApp (builder) {
|
|
26
|
-
//
|
|
27
|
-
//
|
|
28
|
-
//
|
|
26
|
+
// Both environments inherit the top-level `build.outDir` (`dist` by
|
|
27
|
+
// default, or the `outputDir` a caller such as Blueprints passes).
|
|
28
|
+
// `emptyOutDir` is false on both and the CLI clears the output dir
|
|
29
|
+
// once up-front, so the SPA and federation outputs coexist without
|
|
30
|
+
// either build wiping the other's files.
|
|
29
31
|
if (clientInput) {
|
|
30
32
|
await builder.build(builder.environments.client);
|
|
31
33
|
}
|
|
@@ -39,7 +41,6 @@ export function sanityEnvironmentPlugin(options) {
|
|
|
39
41
|
assetsDir: 'static',
|
|
40
42
|
copyPublicDir: false,
|
|
41
43
|
emptyOutDir: false,
|
|
42
|
-
outDir: `dist`,
|
|
43
44
|
rolldownOptions: {
|
|
44
45
|
input: {
|
|
45
46
|
sanity: clientInput
|
|
@@ -55,7 +56,6 @@ export function sanityEnvironmentPlugin(options) {
|
|
|
55
56
|
assetsDir: 'static',
|
|
56
57
|
copyPublicDir: false,
|
|
57
58
|
emptyOutDir: false,
|
|
58
|
-
outDir: `dist`,
|
|
59
59
|
rolldownOptions: {
|
|
60
60
|
input,
|
|
61
61
|
output
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/actions/build/vite/plugins/plugin-sanity-environment.ts"],"sourcesContent":["import {type Plugin} from 'vite'\n\nimport {\n resourceBindingsChunkFileName,\n resourceBindingsCodeSplittingGroup,\n} from '../../resource-bindings.js'\nimport {FEDERATION_DIR_NAME} from '../constants.js'\n\n// Keep the resource-bindings module in its own unhashed chunk at the bundle root\n// so Brett can rewrite it at deploy. `@module-federation/vite` preserves user\n// `codeSplitting` groups (clamped below its own), so this survives the federation\n// build. The chunk sizing lives on the group itself (see\n// `resourceBindingsCodeSplittingGroup`), so it only affects the bindings module.\nconst resourceBindingsOutput = {\n chunkFileNames: (chunk: {name: string}) =>\n resourceBindingsChunkFileName(chunk.name) ?? 'static/[name]-[hash].js',\n codeSplitting: {\n groups: [resourceBindingsCodeSplittingGroup],\n },\n}\n\ninterface EnvironmentOptions {\n input: string\n\n /**\n * When set, also build a standalone `client` SPA environment (its own\n * `index.html` + bootstrap) alongside the federation remote, from this entry.\n * Set for every federated app and studio; omitted only for a dock-only app.\n */\n clientInput?: string\n\n /** Blueprints build (via `@sanity/runtime-cli`) — emit the resource-bindings module. */\n isBlueprints?: boolean\n}\n\nexport function sanityEnvironmentPlugin(options: EnvironmentOptions): Plugin {\n const {clientInput, input, isBlueprints} = options\n\n // Blueprints only: force the resource-bindings module into its own unhashed\n // chunk so Brett can rewrite it at deploy. Off Blueprints, no such chunk.\n const output = isBlueprints ? resourceBindingsOutput : undefined\n\n return {\n config() {\n return {\n builder: {\n async buildApp(builder) {\n // `emptyOutDir` is false on both
|
|
1
|
+
{"version":3,"sources":["../../../../../src/actions/build/vite/plugins/plugin-sanity-environment.ts"],"sourcesContent":["import {type Plugin} from 'vite'\n\nimport {\n resourceBindingsChunkFileName,\n resourceBindingsCodeSplittingGroup,\n} from '../../resource-bindings.js'\nimport {FEDERATION_DIR_NAME} from '../constants.js'\n\n// Keep the resource-bindings module in its own unhashed chunk at the bundle root\n// so Brett can rewrite it at deploy. `@module-federation/vite` preserves user\n// `codeSplitting` groups (clamped below its own), so this survives the federation\n// build. The chunk sizing lives on the group itself (see\n// `resourceBindingsCodeSplittingGroup`), so it only affects the bindings module.\nconst resourceBindingsOutput = {\n chunkFileNames: (chunk: {name: string}) =>\n resourceBindingsChunkFileName(chunk.name) ?? 'static/[name]-[hash].js',\n codeSplitting: {\n groups: [resourceBindingsCodeSplittingGroup],\n },\n}\n\ninterface EnvironmentOptions {\n input: string\n\n /**\n * When set, also build a standalone `client` SPA environment (its own\n * `index.html` + bootstrap) alongside the federation remote, from this entry.\n * Set for every federated app and studio; omitted only for a dock-only app.\n */\n clientInput?: string\n\n /** Blueprints build (via `@sanity/runtime-cli`) — emit the resource-bindings module. */\n isBlueprints?: boolean\n}\n\nexport function sanityEnvironmentPlugin(options: EnvironmentOptions): Plugin {\n const {clientInput, input, isBlueprints} = options\n\n // Blueprints only: force the resource-bindings module into its own unhashed\n // chunk so Brett can rewrite it at deploy. Off Blueprints, no such chunk.\n const output = isBlueprints ? resourceBindingsOutput : undefined\n\n return {\n config() {\n return {\n builder: {\n async buildApp(builder) {\n // Both environments inherit the top-level `build.outDir` (`dist` by\n // default, or the `outputDir` a caller such as Blueprints passes).\n // `emptyOutDir` is false on both and the CLI clears the output dir\n // once up-front, so the SPA and federation outputs coexist without\n // either build wiping the other's files.\n if (clientInput) {\n await builder.build(builder.environments.client)\n }\n await builder.build(builder.environments[FEDERATION_DIR_NAME])\n },\n },\n environments: {\n ...(clientInput\n ? {\n client: {\n build: {\n assetsDir: 'static',\n copyPublicDir: false,\n emptyOutDir: false,\n rolldownOptions: {\n input: {sanity: clientInput},\n output,\n },\n },\n consumer: 'client',\n },\n }\n : {}),\n [FEDERATION_DIR_NAME]: {\n build: {\n assetsDir: 'static',\n copyPublicDir: false,\n emptyOutDir: false,\n rolldownOptions: {input, output},\n },\n consumer: 'client',\n },\n },\n }\n },\n name: 'sanity/environment',\n }\n}\n"],"names":["resourceBindingsChunkFileName","resourceBindingsCodeSplittingGroup","FEDERATION_DIR_NAME","resourceBindingsOutput","chunkFileNames","chunk","name","codeSplitting","groups","sanityEnvironmentPlugin","options","clientInput","input","isBlueprints","output","undefined","config","builder","buildApp","build","environments","client","assetsDir","copyPublicDir","emptyOutDir","rolldownOptions","sanity","consumer"],"mappings":"AAEA,SACEA,6BAA6B,EAC7BC,kCAAkC,QAC7B,6BAA4B;AACnC,SAAQC,mBAAmB,QAAO,kBAAiB;AAEnD,iFAAiF;AACjF,8EAA8E;AAC9E,kFAAkF;AAClF,yDAAyD;AACzD,iFAAiF;AACjF,MAAMC,yBAAyB;IAC7BC,gBAAgB,CAACC,QACfL,8BAA8BK,MAAMC,IAAI,KAAK;IAC/CC,eAAe;QACbC,QAAQ;YAACP;SAAmC;IAC9C;AACF;AAgBA,OAAO,SAASQ,wBAAwBC,OAA2B;IACjE,MAAM,EAACC,WAAW,EAAEC,KAAK,EAAEC,YAAY,EAAC,GAAGH;IAE3C,4EAA4E;IAC5E,0EAA0E;IAC1E,MAAMI,SAASD,eAAeV,yBAAyBY;IAEvD,OAAO;QACLC;YACE,OAAO;gBACLC,SAAS;oBACP,MAAMC,UAASD,OAAO;wBACpB,oEAAoE;wBACpE,mEAAmE;wBACnE,mEAAmE;wBACnE,mEAAmE;wBACnE,yCAAyC;wBACzC,IAAIN,aAAa;4BACf,MAAMM,QAAQE,KAAK,CAACF,QAAQG,YAAY,CAACC,MAAM;wBACjD;wBACA,MAAMJ,QAAQE,KAAK,CAACF,QAAQG,YAAY,CAAClB,oBAAoB;oBAC/D;gBACF;gBACAkB,cAAc;oBACZ,GAAIT,cACA;wBACEU,QAAQ;4BACNF,OAAO;gCACLG,WAAW;gCACXC,eAAe;gCACfC,aAAa;gCACbC,iBAAiB;oCACfb,OAAO;wCAACc,QAAQf;oCAAW;oCAC3BG;gCACF;4BACF;4BACAa,UAAU;wBACZ;oBACF,IACA,CAAC,CAAC;oBACN,CAACzB,oBAAoB,EAAE;wBACrBiB,OAAO;4BACLG,WAAW;4BACXC,eAAe;4BACfC,aAAa;4BACbC,iBAAiB;gCAACb;gCAAOE;4BAAM;wBACjC;wBACAa,UAAU;oBACZ;gBACF;YACF;QACF;QACArB,MAAM;IACR;AACF"}
|
|
@@ -1 +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:
|
|
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>\ntype SharedEntry = Extract<SharedEntries[string], object> & {shareScope: string}\n\nexport interface FederationSharing extends Pick<\n ModuleFederationOptions,\n 'shareScope' | 'shareStrategy'\n> {\n shared: Record<string, SharedEntry>\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): Record<string, SharedEntry> {\n const entries: Record<string, SharedEntry> = {}\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,OA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SAAS,WAAWQ,cAAc,UAAU;QACxF,OAAO;YAAC4B,gBAAgB;QAA6D;IACvF;IACA,IAAIvB,SAASM,GAAG,CAAC,aAAaN,SAASM,GAAG,CAAC,cAAc;QACvD,OAAO;YACLiB,gBAAgB,CAAC,OAAO,EAAEvB,SAASM,GAAG,CAAC,SAAS,iBAAiB,EAAEN,SAASM,GAAG,CAAC,aAAa,iBAAiB,CAAC;QACjH;IACF;IACA,OAAON;AACT;AAEA,SAASS,oBACPV,YAAkC,EAClCI,UAAkB;IAElB,MAAM2B,UAAuC,CAAC;IAC9C,MAAMC,YAAY,IAAIvC,IACpBN,mBAAmBkB,MAAM,CAAC,CAAC,EAAChB,KAAK,EAAC,GAAKA,UAAU,OAAOiB,GAAG,CAAC,CAAC,EAAClB,IAAI,EAAC,GAAKA;IAE1E,KAAK,MAAM,EAACA,IAAI,EAAEQ,SAAS,EAAE8B,OAAO,EAAC,IAAI1B,aAAc;QACrD,IAAI,CAACJ,aAAa,CAACoC,UAAUf,GAAG,CAAC7B,OAAO;QACxC2C,OAAO,CAACnC,UAAU,GAAG;YACnBqC,OAAO;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"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sanity/workbench-cli",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.8.0",
|
|
4
4
|
"description": "Internal implementation detail of the Sanity CLI's unstable workbench support. Not intended for direct use.",
|
|
5
5
|
"homepage": "https://github.com/sanity-io/cli",
|
|
6
6
|
"bugs": "https://github.com/sanity-io/cli/issues",
|
|
@@ -59,7 +59,7 @@
|
|
|
59
59
|
"dependencies": {
|
|
60
60
|
"@module-federation/runtime": "2.9.0",
|
|
61
61
|
"@module-federation/vite": "1.22.1",
|
|
62
|
-
"@sanity/cli-core": "^3.8.
|
|
62
|
+
"@sanity/cli-core": "^3.8.1",
|
|
63
63
|
"@sanity/types": "^6.15.0",
|
|
64
64
|
"@vitejs/plugin-react": "^6.1.1",
|
|
65
65
|
"form-data": "^4.0.5",
|
|
@@ -73,7 +73,7 @@
|
|
|
73
73
|
"@eslint/compat": "^2.1.0",
|
|
74
74
|
"@repo/package.config": "0.0.1",
|
|
75
75
|
"@repo/tsconfig": "3.70.0",
|
|
76
|
-
"@sanity/cli-test": "18.0.
|
|
76
|
+
"@sanity/cli-test": "18.0.1",
|
|
77
77
|
"@sanity/eslint-config-cli": "^1.1.3",
|
|
78
78
|
"@sanity/pkg-utils": "^12.3.4",
|
|
79
79
|
"@swc/cli": "^0.8.1",
|