@sanity/cli-build 2.0.1 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/dist/_exports/_internal/build.d.ts +136 -86
  2. package/dist/_exports/_internal/build.js +3 -4
  3. package/dist/_exports/_internal/build.js.map +1 -1
  4. package/dist/_exports/_internal/extract.d.ts +1 -1
  5. package/dist/actions/build/buildApp.js +190 -0
  6. package/dist/actions/build/buildApp.js.map +1 -0
  7. package/dist/actions/build/buildDebug.js +1 -1
  8. package/dist/actions/build/buildDebug.js.map +1 -1
  9. package/dist/actions/build/buildStaticFiles.js +3 -3
  10. package/dist/actions/build/buildStaticFiles.js.map +1 -1
  11. package/dist/actions/build/buildStudio.js +222 -0
  12. package/dist/actions/build/buildStudio.js.map +1 -0
  13. package/dist/actions/build/checkRequiredDependencies.js +1 -1
  14. package/dist/actions/build/checkRequiredDependencies.js.map +1 -1
  15. package/dist/actions/build/checkStudioDependencyVersions.js +1 -1
  16. package/dist/actions/build/checkStudioDependencyVersions.js.map +1 -1
  17. package/dist/actions/build/decorateIndexWithStagingScript.js +1 -1
  18. package/dist/actions/build/decorateIndexWithStagingScript.js.map +1 -1
  19. package/dist/actions/build/getViteConfig.js +7 -6
  20. package/dist/actions/build/getViteConfig.js.map +1 -1
  21. package/dist/actions/build/handlePrereleaseVersions.js +44 -0
  22. package/dist/actions/build/handlePrereleaseVersions.js.map +1 -0
  23. package/dist/actions/build/renderDocument.js +1 -1
  24. package/dist/actions/build/renderDocument.js.map +1 -1
  25. package/dist/actions/build/renderDocumentWorker/addTimestampImportMapScriptToHtml.js +62 -1
  26. package/dist/actions/build/renderDocumentWorker/addTimestampImportMapScriptToHtml.js.map +1 -1
  27. package/dist/actions/build/renderDocumentWorker/tryLoadDocumentComponent.js +1 -1
  28. package/dist/actions/build/renderDocumentWorker/tryLoadDocumentComponent.js.map +1 -1
  29. package/dist/actions/build/resolveVendorBuildConfig.js +1 -1
  30. package/dist/actions/build/resolveVendorBuildConfig.js.map +1 -1
  31. package/dist/actions/build/writeFavicons.js +3 -3
  32. package/dist/actions/build/writeFavicons.js.map +1 -1
  33. package/dist/actions/build/writeSanityRuntime.js +5 -5
  34. package/dist/actions/build/writeSanityRuntime.js.map +1 -1
  35. package/dist/actions/schema/extractSanitySchema.worker.js +1 -1
  36. package/dist/actions/schema/extractSanitySchema.worker.js.map +1 -1
  37. package/dist/actions/schema/getExtractOptions.js.map +1 -1
  38. package/dist/actions/schema/runSchemaExtraction.js +1 -1
  39. package/dist/actions/schema/runSchemaExtraction.js.map +1 -1
  40. package/dist/actions/schema/utils/extractValidationFromSchemaError.js +1 -1
  41. package/dist/actions/schema/utils/extractValidationFromSchemaError.js.map +1 -1
  42. package/dist/actions/schema/vite/plugin-schema-extraction.js.map +1 -1
  43. package/dist/util/compareDependencyVersions.js +110 -0
  44. package/dist/util/compareDependencyVersions.js.map +1 -0
  45. package/package.json +6 -8
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/actions/build/buildStaticFiles.ts"],"sourcesContent":["import path from 'node:path'\n\nimport {type CliConfig, type UserViteConfig} from '@sanity/cli-core'\nimport {type DefineAppInput} from '@sanity/workbench-cli'\nimport {type PluginOptions as ReactCompilerConfig} from 'babel-plugin-react-compiler'\nimport {build, createBuilder} from 'vite'\n\nimport {copyDir} from '../../util/copyDir.js'\nimport {type AutoUpdatesBuildConfig} from './autoUpdates.js'\nimport {buildDebug} from './buildDebug.js'\nimport {\n getAppEnvironmentVariables,\n getStudioEnvironmentVariables,\n} from './getEnvironmentVariables.js'\nimport {extendViteConfigWithUserConfig, finalizeViteConfig, getViteConfig} from './getViteConfig.js'\nimport {writeFavicons} from './writeFavicons.js'\nimport {resolveEntries, writeSanityRuntime} from './writeSanityRuntime.js'\n\nexport interface ChunkModule {\n name: string\n renderedLength: number\n}\n\nexport interface ChunkStats {\n modules: ChunkModule[]\n name: string\n}\n\ninterface StaticBuildOptions {\n basePath: string\n cwd: string\n outputDir: string\n\n appTitle?: string\n autoUpdates?: AutoUpdatesBuildConfig\n entry?: string\n isApp?: boolean\n /** Workbench app (opted in via `unstable_defineApp`) — drives the federation build. */\n isWorkbenchApp?: boolean\n minify?: boolean\n profile?: boolean\n reactCompiler?: ReactCompilerConfig\n schemaExtraction?: CliConfig['schemaExtraction']\n services?: DefineAppInput['services']\n sourceMap?: boolean\n views?: DefineAppInput['views']\n vite?: UserViteConfig\n}\n\n/**\n * Builds static files\n *\n * @internal\n */\nexport async function buildStaticFiles(\n options: StaticBuildOptions,\n): Promise<{chunks: ChunkStats[]}> {\n const {\n appTitle,\n autoUpdates,\n basePath,\n cwd,\n entry,\n isApp,\n isWorkbenchApp,\n minify = true,\n outputDir,\n reactCompiler,\n schemaExtraction,\n services,\n sourceMap = false,\n views,\n vite: extendViteConfig,\n } = options\n\n const mode = 'production'\n\n /* Federation builds only produce the federation environment\n * (remote-entry, mf-manifest) — skip client-specific steps like\n * runtime generation, static file copies, and favicons.\n */\n if (isWorkbenchApp) {\n buildDebug('Resolving entries for federation build')\n const entries = await resolveEntries({cwd, entry, isApp, isWorkbenchApp})\n\n buildDebug('Resolving vite config (federation)')\n let viteConfig = await getViteConfig({\n basePath,\n cwd,\n entries,\n getEnvironmentVariables,\n isApp,\n isWorkbenchApp,\n minify,\n mode,\n outputDir,\n reactCompiler,\n // Schema extraction is a build-time artifact, not a client-specific step,\n // so a federated studio extracts its schema like the legacy studio build.\n schemaExtraction,\n services,\n sourceMap,\n views,\n })\n\n // Apply the user's Vite config so plugins like `@vanilla-extract/vite-plugin`\n // transform source files before the federation environment is bundled.\n // `finalizeViteConfig` is intentionally skipped: the federation environment\n // has its own entry and does not use `.sanity/runtime/app.js`.\n if (extendViteConfig) {\n viteConfig = await extendViteConfigWithUserConfig(\n {command: 'build', mode},\n viteConfig,\n extendViteConfig,\n )\n }\n\n buildDebug('Bundling federation environment')\n const builder = await createBuilder(viteConfig)\n await builder.buildApp()\n buildDebug('Bundling complete')\n // TODO: add stats here\n return {chunks: []}\n }\n\n buildDebug('Writing Sanity runtime files')\n const {entries} = await writeSanityRuntime({\n appTitle,\n basePath,\n cwd,\n entry,\n isApp,\n isWorkbenchApp,\n reactStrictMode: false,\n watch: false,\n })\n\n function getEnvironmentVariables() {\n return isApp\n ? getAppEnvironmentVariables({jsonEncode: true, prefix: 'process.env.'})\n : getStudioEnvironmentVariables({jsonEncode: true, prefix: 'process.env.'})\n }\n\n buildDebug('Resolving vite config')\n let viteConfig = await getViteConfig({\n autoUpdates,\n basePath,\n cwd,\n entries,\n getEnvironmentVariables,\n isApp,\n isWorkbenchApp,\n minify,\n mode,\n outputDir,\n reactCompiler,\n schemaExtraction,\n sourceMap,\n })\n\n if (extendViteConfig) {\n const defaultViteConfig = viteConfig\n viteConfig = await extendViteConfigWithUserConfig(\n {command: 'build', mode},\n viteConfig,\n extendViteConfig,\n )\n viteConfig = await finalizeViteConfig(viteConfig, defaultViteConfig)\n }\n\n const fromPath = path.join(cwd, 'static')\n // Copy files placed in /static to the built /static\n buildDebug(`Copying static files from ${fromPath} to output dir`)\n const staticPath = path.join(outputDir, 'static')\n await copyDir(fromPath, staticPath)\n\n // Write favicons, not overwriting ones that already exist, to static folder\n buildDebug('Writing favicons to output dir')\n const faviconBasePath = `${basePath.replace(/\\/+$/, '')}/static`\n await writeFavicons(faviconBasePath, staticPath)\n\n buildDebug('Bundling using vite')\n const bundle = await build(viteConfig)\n buildDebug('Bundling complete')\n\n // For typescript only - this shouldn't ever be the case given we're not watching\n if (Array.isArray(bundle) || !('output' in bundle)) {\n return {chunks: []}\n }\n\n const stats: ChunkStats[] = []\n for (const chunk of bundle.output) {\n if (chunk.type !== 'chunk') {\n continue\n }\n\n stats.push({\n modules: Object.entries(chunk.modules).map(([rawFilePath, chunkModule]) => {\n const filePath = rawFilePath.startsWith('\\u0000')\n ? rawFilePath.slice('\\u0000'.length)\n : rawFilePath\n\n return {\n name: path.isAbsolute(filePath) ? path.relative(cwd, filePath) : filePath,\n renderedLength: chunkModule.renderedLength,\n }\n }),\n name: chunk.name,\n })\n }\n\n return {chunks: stats}\n}\n"],"names":["path","build","createBuilder","copyDir","buildDebug","getAppEnvironmentVariables","getStudioEnvironmentVariables","extendViteConfigWithUserConfig","finalizeViteConfig","getViteConfig","writeFavicons","resolveEntries","writeSanityRuntime","buildStaticFiles","options","appTitle","autoUpdates","basePath","cwd","entry","isApp","isWorkbenchApp","minify","outputDir","reactCompiler","schemaExtraction","services","sourceMap","views","vite","extendViteConfig","mode","entries","viteConfig","getEnvironmentVariables","command","builder","buildApp","chunks","reactStrictMode","watch","jsonEncode","prefix","defaultViteConfig","fromPath","join","staticPath","faviconBasePath","replace","bundle","Array","isArray","stats","chunk","output","type","push","modules","Object","map","rawFilePath","chunkModule","filePath","startsWith","slice","length","name","isAbsolute","relative","renderedLength"],"mappings":"AAAA,OAAOA,UAAU,YAAW;AAK5B,SAAQC,KAAK,EAAEC,aAAa,QAAO,OAAM;AAEzC,SAAQC,OAAO,QAAO,wBAAuB;AAE7C,SAAQC,UAAU,QAAO,kBAAiB;AAC1C,SACEC,0BAA0B,EAC1BC,6BAA6B,QACxB,+BAA8B;AACrC,SAAQC,8BAA8B,EAAEC,kBAAkB,EAAEC,aAAa,QAAO,qBAAoB;AACpG,SAAQC,aAAa,QAAO,qBAAoB;AAChD,SAAQC,cAAc,EAAEC,kBAAkB,QAAO,0BAAyB;AAiC1E;;;;CAIC,GACD,OAAO,eAAeC,iBACpBC,OAA2B;IAE3B,MAAM,EACJC,QAAQ,EACRC,WAAW,EACXC,QAAQ,EACRC,GAAG,EACHC,KAAK,EACLC,KAAK,EACLC,cAAc,EACdC,SAAS,IAAI,EACbC,SAAS,EACTC,aAAa,EACbC,gBAAgB,EAChBC,QAAQ,EACRC,YAAY,KAAK,EACjBC,KAAK,EACLC,MAAMC,gBAAgB,EACvB,GAAGhB;IAEJ,MAAMiB,OAAO;IAEb;;;GAGC,GACD,IAAIV,gBAAgB;QAClBjB,W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CAAC;IAChE,MAAME,aAAa9C,KAAK6C,IAAI,CAACtB,WAAW;IACxC,MAAMpB,QAAQyC,UAAUE;IAExB,4EAA4E;IAC5E1C,WAAW;IACX,MAAM2C,kBAAkB,GAAG9B,SAAS+B,OAAO,CAAC,QAAQ,IAAI,OAAO,CAAC;IAChE,MAAMtC,cAAcqC,iBAAiBD;IAErC1C,WAAW;IACX,MAAM6C,SAAS,MAAMhD,MAAMgC;IAC3B7B,WAAW;IAEX,iFAAiF;IACjF,IAAI8C,MAAMC,OAAO,CAACF,WAAW,CAAE,CAAA,YAAYA,MAAK,GAAI;QAClD,OAAO;YAACX,QAAQ,EAAE;QAAA;IACpB;IAEA,MAAMc,QAAsB,EAAE;IAC9B,KAAK,MAAMC,SAASJ,OAAOK,MAAM,CAAE;QACjC,IAAID,MAAME,IAAI,KAAK,SAAS;YAC1B;QACF;QAEAH,MAAMI,IAAI,CAAC;YACTC,SAASC,OAAO1B,OAAO,CAACqB,MAAMI,OAAO,EAAEE,GAAG,CAAC,CAAC,CAACC,aAAaC,YAAY;gBACpE,MAAMC,WAAWF,YAAYG,UAAU,CAAC,YACpCH,YAAYI,KAAK,CAAC,SAASC,MAAM,IACjCL;gBAEJ,OAAO;oBACLM,MAAMlE,KAAKmE,UAAU,CAACL,YAAY9D,KAAKoE,QAAQ,CAAClD,KAAK4C,YAAYA;oBACjEO,gBAAgBR,YAAYQ,cAAc;gBAC5C;YACF;YACAH,MAAMb,MAAMa,IAAI;QAClB;IACF;IAEA,OAAO;QAAC5B,QAAQc;IAAK;AACvB"}
1
+ {"version":3,"sources":["../../../src/actions/build/buildStaticFiles.ts"],"sourcesContent":["import path from 'node:path'\n\nimport {type CliConfig, type UserViteConfig} from '@sanity/cli-core/types'\nimport {type WorkbenchExposes} from '@sanity/workbench-cli/build'\nimport {type PluginOptions as ReactCompilerConfig} from 'babel-plugin-react-compiler'\nimport {build, createBuilder} from 'vite'\n\nimport {copyDir} from '../../util/copyDir.js'\nimport {type AutoUpdatesBuildConfig} from './autoUpdates.js'\nimport {buildDebug} from './buildDebug.js'\nimport {\n getAppEnvironmentVariables,\n getStudioEnvironmentVariables,\n} from './getEnvironmentVariables.js'\nimport {extendViteConfigWithUserConfig, finalizeViteConfig, getViteConfig} from './getViteConfig.js'\nimport {writeFavicons} from './writeFavicons.js'\nimport {resolveEntries, writeSanityRuntime} from './writeSanityRuntime.js'\n\nexport interface ChunkModule {\n name: string\n renderedLength: number\n}\n\nexport interface ChunkStats {\n modules: ChunkModule[]\n name: string\n}\n\ninterface StaticBuildOptions {\n basePath: string\n cwd: string\n outputDir: string\n\n appTitle?: string\n autoUpdates?: AutoUpdatesBuildConfig\n entry?: string\n exposes?: WorkbenchExposes\n isApp?: boolean\n /** Workbench app (opted in via `unstable_defineApp`) — drives the federation build. */\n isWorkbenchApp?: boolean\n minify?: boolean\n profile?: boolean\n reactCompiler?: ReactCompilerConfig\n schemaExtraction?: CliConfig['schemaExtraction']\n sourceMap?: boolean\n vite?: UserViteConfig\n /** The workbench app's bus identity (`__SANITY_APP_ID__`). */\n workbenchAppId?: string\n}\n\n/**\n * Builds static files\n *\n * @internal\n */\nexport async function buildStaticFiles(\n options: StaticBuildOptions,\n): Promise<{chunks: ChunkStats[]}> {\n const {\n appTitle,\n autoUpdates,\n basePath,\n cwd,\n entry,\n exposes,\n isApp,\n isWorkbenchApp,\n minify = true,\n outputDir,\n reactCompiler,\n schemaExtraction,\n sourceMap = false,\n vite: extendViteConfig,\n workbenchAppId,\n } = options\n\n const mode = 'production'\n\n /* Federation builds only produce the federation environment\n * (remote-entry, mf-manifest) — skip client-specific steps like\n * runtime generation, static file copies, and favicons.\n */\n if (isWorkbenchApp) {\n buildDebug('Resolving entries for federation build')\n const entries = await resolveEntries({cwd, entry, isApp, isWorkbenchApp})\n\n buildDebug('Resolving vite config (federation)')\n let viteConfig = await getViteConfig({\n basePath,\n cwd,\n entries,\n exposes,\n getEnvironmentVariables,\n isApp,\n isWorkbenchApp,\n minify,\n mode,\n outputDir,\n reactCompiler,\n // Schema extraction is a build-time artifact, not a client-specific step,\n // so a federated studio extracts its schema like the legacy studio build.\n schemaExtraction,\n sourceMap,\n workbenchAppId,\n })\n\n // Apply the user's Vite config so plugins like `@vanilla-extract/vite-plugin`\n // transform source files before the federation environment is bundled.\n // `finalizeViteConfig` is intentionally skipped: the federation environment\n // has its own entry and does not use `.sanity/runtime/app.js`.\n if (extendViteConfig) {\n viteConfig = await extendViteConfigWithUserConfig(\n {command: 'build', mode},\n viteConfig,\n extendViteConfig,\n )\n }\n\n buildDebug('Bundling federation environment')\n const builder = await createBuilder(viteConfig)\n await builder.buildApp()\n buildDebug('Bundling complete')\n // TODO: add stats here\n return {chunks: []}\n }\n\n buildDebug('Writing Sanity runtime files')\n const {entries} = await writeSanityRuntime({\n appTitle,\n basePath,\n cwd,\n entry,\n isApp,\n isWorkbenchApp,\n reactStrictMode: false,\n watch: false,\n })\n\n function getEnvironmentVariables() {\n return isApp\n ? getAppEnvironmentVariables({jsonEncode: true, prefix: 'process.env.'})\n : getStudioEnvironmentVariables({jsonEncode: true, prefix: 'process.env.'})\n }\n\n buildDebug('Resolving vite config')\n let viteConfig = await getViteConfig({\n autoUpdates,\n basePath,\n cwd,\n entries,\n getEnvironmentVariables,\n isApp,\n isWorkbenchApp,\n minify,\n mode,\n outputDir,\n reactCompiler,\n schemaExtraction,\n sourceMap,\n })\n\n if (extendViteConfig) {\n const defaultViteConfig = viteConfig\n viteConfig = await extendViteConfigWithUserConfig(\n {command: 'build', mode},\n viteConfig,\n extendViteConfig,\n )\n viteConfig = await finalizeViteConfig(viteConfig, defaultViteConfig)\n }\n\n const fromPath = path.join(cwd, 'static')\n // Copy files placed in /static to the built /static\n buildDebug(`Copying static files from ${fromPath} to output dir`)\n const staticPath = path.join(outputDir, 'static')\n await copyDir(fromPath, staticPath)\n\n // Write favicons, not overwriting ones that already exist, to static folder\n buildDebug('Writing favicons to output dir')\n const faviconBasePath = `${basePath.replace(/\\/+$/, '')}/static`\n await writeFavicons(faviconBasePath, staticPath)\n\n buildDebug('Bundling using vite')\n const bundle = await build(viteConfig)\n buildDebug('Bundling complete')\n\n // For typescript only - this shouldn't ever be the case given we're not watching\n if (Array.isArray(bundle) || !('output' in bundle)) {\n return {chunks: []}\n }\n\n const stats: ChunkStats[] = []\n for (const chunk of bundle.output) {\n if (chunk.type !== 'chunk') {\n continue\n }\n\n stats.push({\n modules: Object.entries(chunk.modules).map(([rawFilePath, chunkModule]) => {\n const filePath = rawFilePath.startsWith('\\u0000')\n ? rawFilePath.slice('\\u0000'.length)\n : rawFilePath\n\n return {\n name: path.isAbsolute(filePath) ? path.relative(cwd, filePath) : filePath,\n renderedLength: chunkModule.renderedLength,\n }\n }),\n name: chunk.name,\n })\n }\n\n return {chunks: stats}\n}\n"],"names":["path","build","createBuilder","copyDir","buildDebug","getAppEnvironmentVariables","getStudioEnvironmentVariables","extendViteConfigWithUserConfig","finalizeViteConfig","getViteConfig","writeFavicons","resolveEntries","writeSanityRuntime","buildStaticFiles","options","appTitle","autoUpdates","basePath","cwd","entry","exposes","isApp","isWorkbenchApp","minify","outputDir","reactCompiler","schemaExtraction","sourceMap","vite","extendViteConfig","workbenchAppId","mode","entries","viteConfig","getEnvironmentVariables","command","builder","buildApp","chunks","reactStrictMode","watch","jsonEncode","prefix","defaultViteConfig","fromPath","join","staticPath","faviconBasePath","replace","bundle","Array","isArray","stats","chunk","output","type","push","modules","Object","map","rawFilePath","chunkModule","filePath","startsWith","slice","length","name","isAbsolute","relative","renderedLength"],"mappings":"AAAA,OAAOA,UAAU,YAAW;AAK5B,SAAQC,KAAK,EAAEC,aAAa,QAAO,OAAM;AAEzC,SAAQC,OAAO,QAAO,wBAAuB;AAE7C,SAAQC,UAAU,QAAO,kBAAiB;AAC1C,SACEC,0BAA0B,EAC1BC,6BAA6B,QACxB,+BAA8B;AACrC,SAAQC,8BAA8B,EAAEC,kBAAkB,EAAEC,aAAa,QAAO,qBAAoB;AACpG,SAAQC,aAAa,Q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,QAAQ,CAAClD,KAAK4C,YAAYA;oBACjEO,gBAAgBR,YAAYQ,cAAc;gBAC5C;YACF;YACAH,MAAMb,MAAMa,IAAI;QAClB;IACF;IAEA,OAAO;QAAC5B,QAAQc;IAAK;AACvB"}
@@ -0,0 +1,222 @@
1
+ import { rm } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { styleText } from 'node:util';
4
+ import { getLocalPackageVersion } from '@sanity/cli-core/package-manager';
5
+ import { getCliTelemetry } from '@sanity/cli-core/telemetry';
6
+ import { isInteractive } from '@sanity/cli-core/util';
7
+ import { confirm, getTimer, logSymbols, select, spinner } from '@sanity/cli-core/ux';
8
+ import { parse as semverParse } from 'semver';
9
+ import { StudioBuildTrace } from '../../telemetry/build.telemetry.js';
10
+ import { formatModuleSizes, sortModulesBySize } from '../../util/moduleFormatUtils.js';
11
+ import { buildDebug } from './buildDebug.js';
12
+ import { buildStaticFiles } from './buildStaticFiles.js';
13
+ import { checkRequiredDependencies } from './checkRequiredDependencies.js';
14
+ import { checkStudioDependencyVersions } from './checkStudioDependencyVersions.js';
15
+ import { getAutoUpdatesCssUrls, getAutoUpdatesImportMap } from './getAutoUpdatesImportMap.js';
16
+ import { getStudioEnvironmentVariables } from './getEnvironmentVariables.js';
17
+ import { handlePrereleaseVersions } from './handlePrereleaseVersions.js';
18
+ import { resolveVendorBuildConfig } from './resolveVendorBuildConfig.js';
19
+ /**
20
+ * Internal build studio that avoids depending on flags for CLI config.
21
+ * @param options - options for the build
22
+ */ export async function buildStudio(options) {
23
+ buildDebug(`Building studio`);
24
+ const timer = getTimer();
25
+ const { appId, determineBasePath, exposes, isApp, minify, outDir, output, reactCompiler, schemaExtraction, sourceMap, stats, unattendedMode, upgradePackages, vite, workDir } = options;
26
+ const defaultOutputDir = path.resolve(path.join(workDir, 'dist'));
27
+ const outputDir = path.resolve(outDir || defaultOutputDir);
28
+ await checkStudioDependencyVersions(workDir, output);
29
+ // If the check resulted in a dependency install, the CLI command will be re-run,
30
+ // thus we want to exit early
31
+ const { installedSanityVersion } = await checkRequiredDependencies({
32
+ isApp,
33
+ output,
34
+ workDir
35
+ });
36
+ let autoUpdatesEnabled = options.autoUpdatesEnabled;
37
+ let autoUpdatesImports = {};
38
+ let autoUpdatesCssUrls = [];
39
+ if (autoUpdatesEnabled) {
40
+ // Get the clean version without build metadata: https://semver.org/#spec-item-10
41
+ const cleanSanityVersion = semverParse(installedSanityVersion)?.version;
42
+ if (!cleanSanityVersion) {
43
+ throw new Error(`Failed to parse installed Sanity version: ${installedSanityVersion}`);
44
+ }
45
+ output.log(`${logSymbols.info} Building with auto-updates enabled`);
46
+ // Warn if auto updates enabled but no appId configured
47
+ options.checkAppId();
48
+ const installedVisionVersion = await getLocalPackageVersion('@sanity/vision', workDir);
49
+ const cleanVisionVersion = installedVisionVersion ? semverParse(installedVisionVersion)?.version : undefined;
50
+ const sanityDependencies = [
51
+ {
52
+ cssFile: 'index.css',
53
+ name: 'sanity',
54
+ version: cleanSanityVersion
55
+ },
56
+ ...cleanVisionVersion ? [
57
+ {
58
+ cssFile: 'index.css',
59
+ name: '@sanity/vision',
60
+ version: cleanVisionVersion
61
+ }
62
+ ] : [
63
+ {
64
+ name: '@sanity/vision',
65
+ version: cleanSanityVersion
66
+ }
67
+ ]
68
+ ];
69
+ autoUpdatesImports = getAutoUpdatesImportMap(sanityDependencies, {
70
+ appId
71
+ });
72
+ autoUpdatesCssUrls = getAutoUpdatesCssUrls(sanityDependencies, {
73
+ appId
74
+ });
75
+ // Check the versions
76
+ const { mismatched, unresolvedPrerelease } = await options.compareDependencyVersions(sanityDependencies);
77
+ if (unresolvedPrerelease.length > 0) {
78
+ await handlePrereleaseVersions({
79
+ output,
80
+ unattendedMode,
81
+ unresolvedPrerelease
82
+ });
83
+ autoUpdatesImports = {};
84
+ autoUpdatesCssUrls = [];
85
+ autoUpdatesEnabled = false;
86
+ }
87
+ if (mismatched.length > 0 && autoUpdatesEnabled) {
88
+ const versionMismatchWarning = `The following local package versions are different from the versions currently served at runtime.\n` + `When using auto updates, we recommend that you test locally with the same versions before deploying. \n\n` + `${mismatched.map((mod)=>` - ${mod.pkg} (local version: ${mod.installed}, runtime version: ${mod.remote})`).join('\n')}`;
89
+ // If it is non-interactive or in unattended mode, we don't want to prompt
90
+ if (isInteractive() && !unattendedMode) {
91
+ const choice = await select({
92
+ choices: [
93
+ {
94
+ name: `Upgrade local versions (recommended). You will need to run the build command again`,
95
+ value: 'upgrade'
96
+ },
97
+ {
98
+ name: `Upgrade and proceed with build`,
99
+ value: 'upgrade-and-proceed'
100
+ },
101
+ {
102
+ name: `Continue anyway`,
103
+ value: 'continue'
104
+ },
105
+ {
106
+ name: 'Cancel',
107
+ value: 'cancel'
108
+ }
109
+ ],
110
+ default: 'upgrade',
111
+ message: styleText('yellow', `${logSymbols.warning} ${versionMismatchWarning}\n\nDo you want to upgrade local versions before deploying?`)
112
+ });
113
+ if (choice === 'cancel') {
114
+ output.error('Declined to continue with build', {
115
+ exit: 1
116
+ });
117
+ return;
118
+ }
119
+ if (choice === 'upgrade' || choice === 'upgrade-and-proceed') {
120
+ await upgradePackages({
121
+ packages: mismatched.map((res)=>[
122
+ res.pkg,
123
+ res.remote
124
+ ])
125
+ });
126
+ if (choice === 'upgrade') {
127
+ return;
128
+ }
129
+ }
130
+ } else {
131
+ // if non-interactive or unattended, just show the warning
132
+ output.warn(versionMismatchWarning);
133
+ }
134
+ }
135
+ }
136
+ const envVarKeys = Object.keys(getStudioEnvironmentVariables());
137
+ if (envVarKeys.length > 0) {
138
+ output.log('\nIncluding the following environment variables as part of the JavaScript bundle:');
139
+ for (const key of envVarKeys){
140
+ output.log(`- ${key}`);
141
+ }
142
+ output.log('');
143
+ }
144
+ let shouldClean = true;
145
+ if (outputDir !== defaultOutputDir && !unattendedMode && isInteractive()) {
146
+ shouldClean = await confirm({
147
+ default: true,
148
+ message: `Do you want to delete the existing directory (${outputDir}) first?`
149
+ });
150
+ }
151
+ // Determine base path for built studio
152
+ const basePath = determineBasePath();
153
+ if (schemaExtraction?.enabled) {
154
+ output.log(`${logSymbols.info} Building with schema extraction enabled`);
155
+ }
156
+ let spin;
157
+ if (shouldClean) {
158
+ timer.start('cleanOutputFolder');
159
+ spin = spinner('Clean output folder').start();
160
+ await rm(outputDir, {
161
+ force: true,
162
+ recursive: true
163
+ });
164
+ const cleanDuration = timer.end('cleanOutputFolder');
165
+ spin.text = `Clean output folder (${cleanDuration.toFixed(0)}ms)`;
166
+ spin.succeed();
167
+ }
168
+ spin = spinner(`Build Sanity Studio`).start();
169
+ const trace = getCliTelemetry().trace(StudioBuildTrace);
170
+ trace.start();
171
+ let autoUpdates;
172
+ if (autoUpdatesEnabled && !options.isWorkbenchApp) {
173
+ autoUpdates = {
174
+ cssUrls: autoUpdatesCssUrls,
175
+ imports: autoUpdatesImports,
176
+ vendor: await resolveVendorBuildConfig({
177
+ cwd: workDir,
178
+ isApp: false
179
+ })
180
+ };
181
+ }
182
+ try {
183
+ timer.start('bundleStudio');
184
+ const bundle = await buildStaticFiles({
185
+ autoUpdates,
186
+ basePath,
187
+ cwd: workDir,
188
+ exposes,
189
+ isWorkbenchApp: options.isWorkbenchApp,
190
+ minify,
191
+ outputDir,
192
+ reactCompiler,
193
+ schemaExtraction,
194
+ sourceMap,
195
+ vite,
196
+ workbenchAppId: options.workbenchAppId
197
+ });
198
+ trace.log({
199
+ outputSize: bundle.chunks.flatMap((chunk)=>chunk.modules.flatMap((mod)=>mod.renderedLength)).reduce((sum, n)=>sum + n, 0)
200
+ });
201
+ const buildDuration = timer.end('bundleStudio');
202
+ spin.text = `Build Sanity Studio (${buildDuration.toFixed(0)}ms)`;
203
+ spin.succeed();
204
+ trace.complete();
205
+ if (stats) {
206
+ output.log('\nLargest module files:');
207
+ output.log(formatModuleSizes(sortModulesBySize(bundle.chunks).slice(0, 15)));
208
+ }
209
+ } catch (error) {
210
+ spin.fail();
211
+ trace.error(error);
212
+ const message = error instanceof Error ? error.message : String(error);
213
+ buildDebug(`Failed to build Sanity Studio`, {
214
+ error
215
+ });
216
+ output.error(`Failed to build Sanity Studio: ${message}`, {
217
+ exit: 1
218
+ });
219
+ }
220
+ }
221
+
222
+ //# sourceMappingURL=buildStudio.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/actions/build/buildStudio.ts"],"sourcesContent":["import {rm} from 'node:fs/promises'\nimport path from 'node:path'\nimport {styleText} from 'node:util'\n\nimport {getLocalPackageVersion} from '@sanity/cli-core/package-manager'\nimport {getCliTelemetry} from '@sanity/cli-core/telemetry'\nimport {type CliConfig, type Output, type UserViteConfig} from '@sanity/cli-core/types'\nimport {isInteractive} from '@sanity/cli-core/util'\nimport {\n confirm,\n getTimer,\n logSymbols,\n select,\n spinner,\n type SpinnerInstance,\n} from '@sanity/cli-core/ux'\nimport {type WorkbenchExposes} from '@sanity/workbench-cli/build'\nimport {parse as semverParse} from 'semver'\n\nimport {StudioBuildTrace} from '../../telemetry/build.telemetry.js'\nimport {CompareDependencyVersionsResult} from '../../util/compareDependencyVersions.js'\nimport {formatModuleSizes, sortModulesBySize} from '../../util/moduleFormatUtils.js'\nimport {buildDebug} from './buildDebug.js'\nimport {buildStaticFiles} from './buildStaticFiles.js'\nimport {checkRequiredDependencies} from './checkRequiredDependencies.js'\nimport {checkStudioDependencyVersions} from './checkStudioDependencyVersions.js'\nimport {getAutoUpdatesCssUrls, getAutoUpdatesImportMap} from './getAutoUpdatesImportMap.js'\nimport {getStudioEnvironmentVariables} from './getEnvironmentVariables.js'\nimport {handlePrereleaseVersions} from './handlePrereleaseVersions.js'\nimport {resolveVendorBuildConfig} from './resolveVendorBuildConfig.js'\n\nexport interface BuildOptions {\n appId: string | undefined\n autoUpdatesEnabled: boolean\n checkAppId: () => void\n compareDependencyVersions: (\n packages: {name: string; version: string}[],\n ) => Promise<CompareDependencyVersionsResult>\n determineBasePath: () => string\n isApp: boolean\n isWorkbenchApp: boolean\n minify: boolean\n outDir: string | undefined\n output: Output\n reactCompiler: CliConfig['reactCompiler']\n schemaExtraction: CliConfig['schemaExtraction']\n sourceMap: boolean\n stats: boolean\n unattendedMode: boolean\n upgradePackages(options: {packages: [name: string, version: string][]}): Promise<void>\n vite: UserViteConfig | undefined\n workDir: string\n\n exposes?: WorkbenchExposes\n\n /** The workbench app's bus identity (`__SANITY_APP_ID__`). */\n workbenchAppId?: string\n}\n\n/**\n * Internal build studio that avoids depending on flags for CLI config.\n * @param options - options for the build\n */\nexport async function buildStudio(options: BuildOptions): Promise<void> {\n buildDebug(`Building studio`)\n\n const timer = getTimer()\n const {\n appId,\n determineBasePath,\n exposes,\n isApp,\n minify,\n outDir,\n output,\n reactCompiler,\n schemaExtraction,\n sourceMap,\n stats,\n unattendedMode,\n upgradePackages,\n vite,\n workDir,\n } = options\n const defaultOutputDir = path.resolve(path.join(workDir, 'dist'))\n const outputDir = path.resolve(outDir || defaultOutputDir)\n\n await checkStudioDependencyVersions(workDir, output)\n\n // If the check resulted in a dependency install, the CLI command will be re-run,\n // thus we want to exit early\n const {installedSanityVersion} = await checkRequiredDependencies({\n isApp,\n output,\n workDir,\n })\n\n let autoUpdatesEnabled = options.autoUpdatesEnabled\n\n let autoUpdatesImports = {}\n let autoUpdatesCssUrls: string[] = []\n\n if (autoUpdatesEnabled) {\n // Get the clean version without build metadata: https://semver.org/#spec-item-10\n const cleanSanityVersion = semverParse(installedSanityVersion)?.version\n if (!cleanSanityVersion) {\n throw new Error(`Failed to parse installed Sanity version: ${installedSanityVersion}`)\n }\n\n output.log(`${logSymbols.info} Building with auto-updates enabled`)\n\n // Warn if auto updates enabled but no appId configured\n options.checkAppId()\n\n const installedVisionVersion = await getLocalPackageVersion('@sanity/vision', workDir)\n const cleanVisionVersion = installedVisionVersion\n ? semverParse(installedVisionVersion)?.version\n : undefined\n\n const sanityDependencies = [\n {cssFile: 'index.css', name: 'sanity', version: cleanSanityVersion},\n ...(cleanVisionVersion\n ? [{cssFile: 'index.css', name: '@sanity/vision' as const, version: cleanVisionVersion}]\n : [{name: '@sanity/vision' as const, version: cleanSanityVersion}]),\n ]\n autoUpdatesImports = getAutoUpdatesImportMap(sanityDependencies, {appId})\n\n autoUpdatesCssUrls = getAutoUpdatesCssUrls(sanityDependencies, {appId})\n\n // Check the versions\n const {mismatched, unresolvedPrerelease} =\n await options.compareDependencyVersions(sanityDependencies)\n\n if (unresolvedPrerelease.length > 0) {\n await handlePrereleaseVersions({output, unattendedMode, unresolvedPrerelease})\n autoUpdatesImports = {}\n autoUpdatesCssUrls = []\n autoUpdatesEnabled = false\n }\n\n if (mismatched.length > 0 && autoUpdatesEnabled) {\n const versionMismatchWarning =\n `The following local package versions are different from the versions currently served at runtime.\\n` +\n `When using auto updates, we recommend that you test locally with the same versions before deploying. \\n\\n` +\n `${mismatched.map((mod) => ` - ${mod.pkg} (local version: ${mod.installed}, runtime version: ${mod.remote})`).join('\\n')}`\n\n // If it is non-interactive or in unattended mode, we don't want to prompt\n if (isInteractive() && !unattendedMode) {\n const choice = await select({\n choices: [\n {\n name: `Upgrade local versions (recommended). You will need to run the build command again`,\n value: 'upgrade',\n },\n {\n name: `Upgrade and proceed with build`,\n value: 'upgrade-and-proceed',\n },\n {\n name: `Continue anyway`,\n value: 'continue',\n },\n {name: 'Cancel', value: 'cancel'},\n ],\n default: 'upgrade',\n message: styleText(\n 'yellow',\n `${logSymbols.warning} ${versionMismatchWarning}\\n\\nDo you want to upgrade local versions before deploying?`,\n ),\n })\n\n if (choice === 'cancel') {\n output.error('Declined to continue with build', {exit: 1})\n return\n }\n\n if (choice === 'upgrade' || choice === 'upgrade-and-proceed') {\n await upgradePackages({\n packages: mismatched.map((res) => [res.pkg, res.remote]),\n })\n\n if (choice === 'upgrade') {\n return\n }\n }\n } else {\n // if non-interactive or unattended, just show the warning\n output.warn(versionMismatchWarning)\n }\n }\n }\n\n const envVarKeys = Object.keys(getStudioEnvironmentVariables())\n if (envVarKeys.length > 0) {\n output.log('\\nIncluding the following environment variables as part of the JavaScript bundle:')\n for (const key of envVarKeys) {\n output.log(`- ${key}`)\n }\n output.log('')\n }\n\n let shouldClean = true\n if (outputDir !== defaultOutputDir && !unattendedMode && isInteractive()) {\n shouldClean = await confirm({\n default: true,\n message: `Do you want to delete the existing directory (${outputDir}) first?`,\n })\n }\n\n // Determine base path for built studio\n const basePath = determineBasePath()\n\n if (schemaExtraction?.enabled) {\n output.log(`${logSymbols.info} Building with schema extraction enabled`)\n }\n\n let spin: SpinnerInstance\n if (shouldClean) {\n timer.start('cleanOutputFolder')\n spin = spinner('Clean output folder').start()\n await rm(outputDir, {force: true, recursive: true})\n const cleanDuration = timer.end('cleanOutputFolder')\n spin.text = `Clean output folder (${cleanDuration.toFixed(0)}ms)`\n spin.succeed()\n }\n\n spin = spinner(`Build Sanity Studio`).start()\n\n const trace = getCliTelemetry().trace(StudioBuildTrace)\n trace.start()\n\n let autoUpdates\n if (autoUpdatesEnabled && !options.isWorkbenchApp) {\n autoUpdates = {\n cssUrls: autoUpdatesCssUrls,\n imports: autoUpdatesImports,\n vendor: await resolveVendorBuildConfig({cwd: workDir, isApp: false}),\n }\n }\n\n try {\n timer.start('bundleStudio')\n\n const bundle = await buildStaticFiles({\n autoUpdates,\n basePath,\n cwd: workDir,\n exposes,\n isWorkbenchApp: options.isWorkbenchApp,\n minify,\n outputDir,\n reactCompiler,\n schemaExtraction,\n sourceMap,\n vite,\n workbenchAppId: options.workbenchAppId,\n })\n\n trace.log({\n outputSize: bundle.chunks\n .flatMap((chunk) => chunk.modules.flatMap((mod) => mod.renderedLength))\n .reduce((sum, n) => sum + n, 0),\n })\n const buildDuration = timer.end('bundleStudio')\n\n spin.text = `Build Sanity Studio (${buildDuration.toFixed(0)}ms)`\n spin.succeed()\n\n trace.complete()\n if (stats) {\n output.log('\\nLargest module files:')\n output.log(formatModuleSizes(sortModulesBySize(bundle.chunks).slice(0, 15)))\n }\n } catch (error) {\n spin.fail()\n trace.error(error)\n const message = error instanceof Error ? error.message : String(error)\n buildDebug(`Failed to build Sanity Studio`, {error})\n output.error(`Failed to build Sanity Studio: ${message}`, {exit: 1})\n }\n}\n"],"names":["rm","path","styleText","getLocalPackageVersion","getCliTelemetry","isInteractive","confirm","getTimer","logSymbols","select","spinner","parse","semverParse","StudioBuildTrace","formatModuleSizes","sortModulesBySize","buildDebug","buildStaticFiles","checkRequiredDependencies","checkStudioDependencyVersions","getAutoUpdatesCssUrls","getAutoUpdatesImportMap","getStudioEnvironmentVariables","handlePrereleaseVersions","resolveVendorBuildConfig","buildStudio","options","timer","appId","determineBasePath","exposes","isApp","minify","outDir","output","reactCompiler","schemaExtraction","sourceMap","stats","unattendedMode","upgradePackages","vite","workDir","defaultOutputDir","resolve","join","outputDir","installedSanityVersion","autoUpdatesEnabled","autoUpdatesImports","autoUpdatesCssUrls","cleanSanityVersion","version","Error","log","info","checkAppId","installedVisionVersion","cleanVisionVersion","undefined","sanityDependencies","cssFile","name","mismatched","unresolvedPrerelease","compareDependencyVersions","length","versionMismatchWarning","map","mod","pkg","installed","remote","choice","choices","value","default","message","warning","error","exit","packages","res","warn","envVarKeys","Object","keys","key","shouldClean","basePath","enabled","spin","start","force","recursive","cleanDuration","end","text","toFixed","succeed","trace","autoUpdates","isWorkbenchApp","cssUrls","imports","vendor","cwd","bundle","workbenchAppId","outputSize","chunks","flatMap","chunk","modules","renderedLength","reduce","sum","n","buildDuration","complete","slice","fail","String"],"mappings":"AAAA,SAAQA,EAAE,QAAO,mBAAkB;AACnC,OAAOC,UAAU,YAAW;AAC5B,SAAQC,SAAS,QAAO,YAAW;AAEnC,SAAQC,sBAAsB,QAAO,mCAAkC;AACvE,SAAQC,eAAe,QAAO,6BAA4B;AAE1D,SAAQC,aAAa,QAAO,wBAAuB;AACnD,SACEC,OAAO,EACPC,QAAQ,EACRC,UAAU,EACVC,MAAM,EACNC,OAAO,QAEF,sBAAqB;AAE5B,SAAQC,SAASC,WAAW,QAAO,SAAQ;AAE3C,SAAQC,gBAAgB,QAAO,qCAAoC;AAEnE,SAAQC,iBAAiB,EAAEC,i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AO;QAEZC,MAAMmB,QAAQ;QACd,IAAIjF,OAAO;YACTJ,OAAOoB,GAAG,CAAC;YACXpB,OAAOoB,GAAG,CAACxC,kBAAkBC,kBAAkB4F,OAAOG,MAAM,EAAEU,KAAK,CAAC,GAAG;QACzE;IACF,EAAE,OAAOzC,OAAO;QACdY,KAAK8B,IAAI;QACTrB,MAAMrB,KAAK,CAACA;QACZ,MAAMF,UAAUE,iBAAiB1B,QAAQ0B,MAAMF,OAAO,GAAG6C,OAAO3C;QAChE/D,WAAW,CAAC,6BAA6B,CAAC,EAAE;YAAC+D;QAAK;QAClD7C,OAAO6C,KAAK,CAAC,CAAC,+BAA+B,EAAEF,SAAS,EAAE;YAACG,MAAM;QAAC;IACpE;AACF"}
@@ -1,5 +1,5 @@
1
1
  import path from 'node:path';
2
- import { getLocalPackageVersion, readPackageJson } from '@sanity/cli-core';
2
+ import { getLocalPackageVersion, readPackageJson } from '@sanity/cli-core/package-manager';
3
3
  import { oneline } from 'oneline';
4
4
  import { minVersion, satisfies } from 'semver';
5
5
  const defaultStudioManifestProps = {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/actions/build/checkRequiredDependencies.ts"],"sourcesContent":["import path from 'node:path'\n\nimport {\n getLocalPackageVersion,\n type Output,\n type PackageJson,\n readPackageJson,\n} from '@sanity/cli-core'\nimport {oneline} from 'oneline'\nimport {minVersion, satisfies, type SemVer} from 'semver'\n\nconst defaultStudioManifestProps: Partial<PackageJson> = {\n name: 'studio',\n version: '1.0.0',\n}\n\ninterface CheckResult {\n installedSanityVersion: string\n}\n\ninterface CheckRequiredDependenciesOptions {\n isApp: boolean\n output: Output\n workDir: string\n}\n\nconst styledComponentsVersionRange = '^6.1.15'\n\n/**\n * Checks that the studio has declared and installed the required dependencies\n * needed by the Sanity modules. While we generally use regular, explicit\n * dependencies in modules, there are certain dependencies that are better\n * served being peer dependencies, such as react and styled-components.\n *\n * If these dependencies are not installed/declared, we report an error\n * and instruct the user to install them manually.\n *\n * Additionally, returns the version of the 'sanity' dependency from the package.json.\n */\nexport async function checkRequiredDependencies(\n options: CheckRequiredDependenciesOptions,\n): Promise<CheckResult> {\n const {isApp, output, workDir: studioPath} = options\n // currently there's no check needed for core apps,\n // but this should be removed once they are more mature\n if (isApp) {\n return {installedSanityVersion: ''}\n }\n\n const [studioPackageManifest, installedStyledComponentsVersion, installedSanityVersion] =\n await Promise.all([\n readPackageJson(path.join(studioPath, 'package.json'), {\n defaults: defaultStudioManifestProps,\n skipSchemaValidation: true,\n }),\n getLocalPackageVersion('styled-components', studioPath),\n getLocalPackageVersion('sanity', studioPath),\n ])\n\n const wantedStyledComponentsVersionRange = styledComponentsVersionRange\n\n // Retrieve the version of the 'sanity' dependency\n if (!installedSanityVersion) {\n output.error('Failed to read the installed sanity version.', {exit: 1})\n return {installedSanityVersion: ''}\n }\n\n // The studio _must_ now declare `styled-components` as a dependency. If it's not there,\n // we'll want to automatically _add it_ to the manifest and tell the user to reinstall\n // dependencies before running whatever command was being run\n const declaredStyledComponentsVersion =\n studioPackageManifest.dependencies?.['styled-components'] ||\n studioPackageManifest?.devDependencies?.['styled-components']\n\n if (!declaredStyledComponentsVersion) {\n output.error(\n oneline`\n Declared dependency \\`styled-components\\` is not installed - run\n \\`npm install\\`, \\`yarn install\\` or \\`pnpm install\\` to install it before re-running this command.\n `,\n {exit: 1},\n )\n return {installedSanityVersion}\n }\n\n // We ignore catalog identifiers since we check the actual version anyway\n const isStyledComponentsVersionRangeInCatalog =\n declaredStyledComponentsVersion.startsWith('catalog:')\n // Theoretically the version specified in package.json could be incorrect, eg `foo`\n let minDeclaredStyledComponentsVersion: SemVer | null = null\n try {\n minDeclaredStyledComponentsVersion = minVersion(declaredStyledComponentsVersion)\n } catch {\n // Intentional fall-through (variable will be left as null, throwing below)\n }\n\n if (!minDeclaredStyledComponentsVersion && !isStyledComponentsVersionRangeInCatalog) {\n output.error(\n oneline`\n Declared dependency \\`styled-components\\` has an invalid version range:\n \\`${declaredStyledComponentsVersion}\\`.\n `,\n {exit: 1},\n )\n return {installedSanityVersion}\n }\n\n // The declared version should be semver-compatible with the version specified as a\n // peer dependency in `sanity`. If not, we should tell the user to change it.\n //\n // Exception: Ranges are hard to compare. `>=5.0.0 && <=5.3.2 || ^6`... Comparing this\n // to anything is going to be challenging, so only compare \"simple\" ranges/versions\n // (^x.x.x / ~x.x.x / x.x.x)\n if (\n !isStyledComponentsVersionRangeInCatalog &&\n isComparableRange(declaredStyledComponentsVersion) &&\n !satisfies(minDeclaredStyledComponentsVersion!, wantedStyledComponentsVersionRange)\n ) {\n output.warn(oneline`\n Declared version of styled-components (${declaredStyledComponentsVersion})\n is not compatible with the version required by sanity (${wantedStyledComponentsVersionRange}).\n This might cause problems!\n `)\n }\n\n // Ensure the studio has _installed_ a version of `styled-components`\n if (!installedStyledComponentsVersion) {\n output.error(\n oneline`\n Declared dependency \\`styled-components\\` is not installed - run\n \\`npm install\\`, \\`yarn install\\` or \\`pnpm install\\` to install it before re-running this command.\n `,\n {exit: 1},\n )\n return {installedSanityVersion}\n }\n\n // The studio should have an _installed_ version of `styled-components`, and it should\n // be semver compatible with the version specified in `sanity` peer dependencies.\n if (!satisfies(installedStyledComponentsVersion, wantedStyledComponentsVersionRange)) {\n output.warn(oneline`\n Installed version of styled-components (${installedStyledComponentsVersion})\n is not compatible with the version required by sanity (${wantedStyledComponentsVersionRange}).\n This might cause problems!\n `)\n }\n\n return {installedSanityVersion}\n}\n\nfunction isComparableRange(range: string): boolean {\n return /^[\\^~]?\\d+(\\.\\d+)?(\\.\\d+)?$/.test(range)\n}\n"],"names":["path","getLocalPackageVersion","readPackageJson","oneline","minVersion","satisfies","defaultStudioManifestProps","name","version","styledComponentsVersionRange","checkRequiredDependencies","options","isApp","output","workDir","studioPath","installedSanityVersion","studioPackageManifest","installedStyledComponentsVersion","Promise","all","join","defaults","skipSchemaValidation","wantedStyledComponentsVersionRange","error","exit","declaredStyledComponentsVersion","dependencies","devDependencies","isStyledComponentsVersionRangeInCatalog","startsWith","minDeclaredStyledComponentsVersion","isComparableRange","warn","range","test"],"mappings":"AAAA,OAAOA,UAAU,YAAW;AAE5B,SACEC,sBAAsB,EAGtBC,eAAe,QACV,mBAAkB;AACzB,SAAQC,OAAO,QAAO,UAAS;AAC/B,SAAQC,UAAU,EAAEC,SAAS,QAAoB,SAAQ;AAEzD,MAAMC,6BAAmD;IACvDC,MAAM;IACNC,SAAS;AACX;AAYA,MAAMC,+BAA+B;AAErC;;;;;;;;;;CAUC,GACD,OAAO,eAAeC,0BACpBC,OAAyC;IAEzC,MAAM,EAACC,KAAK,EAAEC,MAAM,EAAEC,SAASC,UAAU,EAAC,GAAGJ;IAC7C,mDAAmD;IACnD,uDAAuD;IACvD,IAAIC,OAAO;QACT,OAAO;YAACI,wBAAwB;QAAE;IACpC;IAEA,MAAM,CAACC,uBAAuBC,kCAAkCF,uBAAuB,GACrF,MAAMG,QAAQC,GAAG,CAAC;QAChBlB,gBAAgBF,KAAKqB,IAAI,CAACN,YAAY,iBAAiB;YACrDO,UAAUhB;YACViB,sBAAsB;QACxB;QACAtB,uBAAuB,qBAAqBc;QAC5Cd,uBAAuB,UAAUc;KAClC;IAEH,MAAMS,qCAAqCf;IAE3C,kDAAkD;IAClD,IAAI,CAACO,wBAAwB;QAC3BH,OAAOY,KAAK,CAAC,gDAAgD;YAACC,MAAM;QAAC;QACrE,OAAO;YAACV,wBAAwB;QAAE;IACpC;IAEA,wFAAwF;IACxF,sFAAsF;IACtF,6DAA6D;IAC7D,MAAMW,kCACJV,sBAAsBW,YAAY,EAAE,CAAC,oBAAoB,IACzDX,uBAAuBY,iBAAiB,CAAC,oBAAoB;IAE/D,IAAI,CAACF,iCAAiC;QACpCd,OAAOY,KAAK,CACVtB,OAAO,CAAC;;;IAGV,CAAC,EACC;YAACuB,MAAM;QAAC;QAEV,OAAO;YAACV;QAAsB;IAChC;IAEA,yEAAyE;IACzE,MAAMc,0CACJH,gCAAgCI,UAAU,CAAC;IAC7C,mFAAmF;IACnF,IAAIC,qCAAoD;IACxD,IAAI;QACFA,qCAAqC5B,WAAWuB;IAClD,EAAE,OAAM;IACN,2EAA2E;IAC7E;IAEA,IAAI,CAACK,sCAAsC,CAACF,yCAAyC;QACnFjB,OAAOY,KAAK,CACVtB,OAAO,CAAC;;QAEN,EAAEwB,gCAAgC;IACtC,CAAC,EACC;YAACD,MAAM;QAAC;QAEV,OAAO;YAACV;QAAsB;IAChC;IAEA,mFAAmF;IACnF,6EAA6E;IAC7E,EAAE;IACF,sFAAsF;IACtF,mFAAmF;IACnF,4BAA4B;IAC5B,IACE,CAACc,2CACDG,kBAAkBN,oCAClB,CAACtB,UAAU2B,oCAAqCR,qCAChD;QACAX,OAAOqB,IAAI,CAAC/B,OAAO,CAAC;6CACqB,EAAEwB,gCAAgC;6DAClB,EAAEH,mCAAmC;;IAE9F,CAAC;IACH;IAEA,qEAAqE;IACrE,IAAI,CAACN,kCAAkC;QACrCL,OAAOY,KAAK,CACVtB,OAAO,CAAC;;;IAGV,CAAC,EACC;YAACuB,MAAM;QAAC;QAEV,OAAO;YAACV;QAAsB;IAChC;IAEA,sFAAsF;IACtF,iFAAiF;IACjF,IAAI,CAACX,UAAUa,kCAAkCM,qCAAqC;QACpFX,OAAOqB,IAAI,CAAC/B,OAAO,CAAC;8CACsB,EAAEe,iCAAiC;6DACpB,EAAEM,mCAAmC;;IAE9F,CAAC;IACH;IAEA,OAAO;QAACR;IAAsB;AAChC;AAEA,SAASiB,kBAAkBE,KAAa;IACtC,OAAO,8BAA8BC,IAAI,CAACD;AAC5C"}
1
+ {"version":3,"sources":["../../../src/actions/build/checkRequiredDependencies.ts"],"sourcesContent":["import path from 'node:path'\n\nimport {getLocalPackageVersion, readPackageJson} from '@sanity/cli-core/package-manager'\nimport {type Output, type PackageJson} from '@sanity/cli-core/types'\nimport {oneline} from 'oneline'\nimport {minVersion, satisfies, type SemVer} from 'semver'\n\nconst defaultStudioManifestProps: Partial<PackageJson> = {\n name: 'studio',\n version: '1.0.0',\n}\n\ninterface CheckResult {\n installedSanityVersion: string\n}\n\ninterface CheckRequiredDependenciesOptions {\n isApp: boolean\n output: Output\n workDir: string\n}\n\nconst styledComponentsVersionRange = '^6.1.15'\n\n/**\n * Checks that the studio has declared and installed the required dependencies\n * needed by the Sanity modules. While we generally use regular, explicit\n * dependencies in modules, there are certain dependencies that are better\n * served being peer dependencies, such as react and styled-components.\n *\n * If these dependencies are not installed/declared, we report an error\n * and instruct the user to install them manually.\n *\n * Additionally, returns the version of the 'sanity' dependency from the package.json.\n */\nexport async function checkRequiredDependencies(\n options: CheckRequiredDependenciesOptions,\n): Promise<CheckResult> {\n const {isApp, output, workDir: studioPath} = options\n // currently there's no check needed for core apps,\n // but this should be removed once they are more mature\n if (isApp) {\n return {installedSanityVersion: ''}\n }\n\n const [studioPackageManifest, installedStyledComponentsVersion, installedSanityVersion] =\n await Promise.all([\n readPackageJson(path.join(studioPath, 'package.json'), {\n defaults: defaultStudioManifestProps,\n skipSchemaValidation: true,\n }),\n getLocalPackageVersion('styled-components', studioPath),\n getLocalPackageVersion('sanity', studioPath),\n ])\n\n const wantedStyledComponentsVersionRange = styledComponentsVersionRange\n\n // Retrieve the version of the 'sanity' dependency\n if (!installedSanityVersion) {\n output.error('Failed to read the installed sanity version.', {exit: 1})\n return {installedSanityVersion: ''}\n }\n\n // The studio _must_ now declare `styled-components` as a dependency. If it's not there,\n // we'll want to automatically _add it_ to the manifest and tell the user to reinstall\n // dependencies before running whatever command was being run\n const declaredStyledComponentsVersion =\n studioPackageManifest.dependencies?.['styled-components'] ||\n studioPackageManifest?.devDependencies?.['styled-components']\n\n if (!declaredStyledComponentsVersion) {\n output.error(\n oneline`\n Declared dependency \\`styled-components\\` is not installed - run\n \\`npm install\\`, \\`yarn install\\` or \\`pnpm install\\` to install it before re-running this command.\n `,\n {exit: 1},\n )\n return {installedSanityVersion}\n }\n\n // We ignore catalog identifiers since we check the actual version anyway\n const isStyledComponentsVersionRangeInCatalog =\n declaredStyledComponentsVersion.startsWith('catalog:')\n // Theoretically the version specified in package.json could be incorrect, eg `foo`\n let minDeclaredStyledComponentsVersion: SemVer | null = null\n try {\n minDeclaredStyledComponentsVersion = minVersion(declaredStyledComponentsVersion)\n } catch {\n // Intentional fall-through (variable will be left as null, throwing below)\n }\n\n if (!minDeclaredStyledComponentsVersion && !isStyledComponentsVersionRangeInCatalog) {\n output.error(\n oneline`\n Declared dependency \\`styled-components\\` has an invalid version range:\n \\`${declaredStyledComponentsVersion}\\`.\n `,\n {exit: 1},\n )\n return {installedSanityVersion}\n }\n\n // The declared version should be semver-compatible with the version specified as a\n // peer dependency in `sanity`. If not, we should tell the user to change it.\n //\n // Exception: Ranges are hard to compare. `>=5.0.0 && <=5.3.2 || ^6`... Comparing this\n // to anything is going to be challenging, so only compare \"simple\" ranges/versions\n // (^x.x.x / ~x.x.x / x.x.x)\n if (\n !isStyledComponentsVersionRangeInCatalog &&\n isComparableRange(declaredStyledComponentsVersion) &&\n !satisfies(minDeclaredStyledComponentsVersion!, wantedStyledComponentsVersionRange)\n ) {\n output.warn(oneline`\n Declared version of styled-components (${declaredStyledComponentsVersion})\n is not compatible with the version required by sanity (${wantedStyledComponentsVersionRange}).\n This might cause problems!\n `)\n }\n\n // Ensure the studio has _installed_ a version of `styled-components`\n if (!installedStyledComponentsVersion) {\n output.error(\n oneline`\n Declared dependency \\`styled-components\\` is not installed - run\n \\`npm install\\`, \\`yarn install\\` or \\`pnpm install\\` to install it before re-running this command.\n `,\n {exit: 1},\n )\n return {installedSanityVersion}\n }\n\n // The studio should have an _installed_ version of `styled-components`, and it should\n // be semver compatible with the version specified in `sanity` peer dependencies.\n if (!satisfies(installedStyledComponentsVersion, wantedStyledComponentsVersionRange)) {\n output.warn(oneline`\n Installed version of styled-components (${installedStyledComponentsVersion})\n is not compatible with the version required by sanity (${wantedStyledComponentsVersionRange}).\n This might cause problems!\n `)\n }\n\n return {installedSanityVersion}\n}\n\nfunction isComparableRange(range: string): boolean {\n return /^[\\^~]?\\d+(\\.\\d+)?(\\.\\d+)?$/.test(range)\n}\n"],"names":["path","getLocalPackageVersion","readPackageJson","oneline","minVersion","satisfies","defaultStudioManifestProps","name","version","styledComponentsVersionRange","checkRequiredDependencies","options","isApp","output","workDir","studioPath","installedSanityVersion","studioPackageManifest","installedStyledComponentsVersion","Promise","all","join","defaults","skipSchemaValidation","wantedStyledComponentsVersionRange","error","exit","declaredStyledComponentsVersion","dependencies","devDependencies","isStyledComponentsVersionRangeInCatalog","startsWith","minDeclaredStyledComponentsVersion","isComparableRange","warn","range","test"],"mappings":"AAAA,OAAOA,UAAU,YAAW;AAE5B,SAAQC,sBAAsB,EAAEC,eAAe,QAAO,mCAAkC;AAExF,SAAQC,OAAO,QAAO,UAAS;AAC/B,SAAQC,UAAU,EAAEC,SAAS,QAAoB,SAAQ;AAEzD,MAAMC,6BAAmD;IACvDC,MAAM;IACNC,SAAS;AACX;AAYA,MAAMC,+BAA+B;AAErC;;;;;;;;;;CAUC,GACD,OAAO,eAAeC,0BACpBC,OAAyC;IAEzC,MAAM,EAACC,KAAK,EAAEC,MAAM,EAAEC,SAASC,UAAU,EAAC,GAAGJ;IAC7C,mDAAmD;IACnD,uDAAuD;IACvD,IAAIC,OAAO;QACT,OAAO;YAACI,wBAAwB;QAAE;IACpC;IAEA,MAAM,CAACC,uBAAuBC,kCAAkCF,uBAAuB,GACrF,MAAMG,QAAQC,GAAG,CAAC;QAChBlB,gBAAgBF,KAAKqB,IAAI,CAACN,YAAY,iBAAiB;YACrDO,UAAUhB;YACViB,sBAAsB;QACxB;QACAtB,uBAAuB,qBAAqBc;QAC5Cd,uBAAuB,UAAUc;KAClC;IAEH,MAAMS,qCAAqCf;IAE3C,kDAAkD;IAClD,IAAI,CAACO,wBAAwB;QAC3BH,OAAOY,KAAK,CAAC,gDAAgD;YAACC,MAAM;QAAC;QACrE,OAAO;YAACV,wBAAwB;QAAE;IACpC;IAEA,wFAAwF;IACxF,sFAAsF;IACtF,6DAA6D;IAC7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,OAAO,8BAA8BC,IAAI,CAACD;AAC5C"}
@@ -1,5 +1,5 @@
1
1
  import path from 'node:path';
2
- import { getLocalPackageVersion, readPackageJson } from '@sanity/cli-core';
2
+ import { getLocalPackageVersion, readPackageJson } from '@sanity/cli-core/package-manager';
3
3
  import { coerce, gtr, ltr, rcompare, satisfies } from 'semver';
4
4
  // NOTE: when doing changes here, also remember to update versions in help docs at
5
5
  // https://sanity.io/admin/structure/docs;helpArticle;upgrade-packages
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/actions/build/checkStudioDependencyVersions.ts"],"sourcesContent":["import path from 'node:path'\n\nimport {getLocalPackageVersion, type Output, readPackageJson} from '@sanity/cli-core'\nimport {coerce, gtr, ltr, rcompare, satisfies, type SemVer} from 'semver'\n\ninterface PackageInfo {\n deprecatedBelow: string | null\n installed: SemVer\n isDeprecated: boolean\n isUnsupported: boolean\n isUntested: boolean\n name: string\n supported: string[]\n}\n\ninterface TrackedPackage {\n deprecatedBelow: string | null\n name: string\n supported: string[]\n}\n\n// NOTE: when doing changes here, also remember to update versions in help docs at\n// https://sanity.io/admin/structure/docs;helpArticle;upgrade-packages\nconst DEFAULT_PACKAGES: TrackedPackage[] = [\n {deprecatedBelow: null, name: 'react', supported: ['^19.2.2']},\n {deprecatedBelow: null, name: 'react-dom', supported: ['^19.2.2']},\n {deprecatedBelow: null, name: 'styled-components', supported: ['^6']},\n {deprecatedBelow: '^3', name: '@sanity/ui', supported: ['^2', '^3']},\n]\n\nexport async function checkStudioDependencyVersions(\n workDir: string,\n output: Output,\n {packages = DEFAULT_PACKAGES}: {packages?: TrackedPackage[]} = {},\n): Promise<void> {\n const manifest = await readPackageJson(path.join(workDir, 'package.json'), {\n skipSchemaValidation: true,\n })\n const dependencies = {...manifest?.dependencies, ...manifest?.devDependencies}\n\n const packageInfo = packages.map(async (pkg): Promise<false | PackageInfo> => {\n const dependency = dependencies[pkg.name]\n if (!dependency) {\n return false\n }\n\n const packageVersion = await getLocalPackageVersion(pkg.name, workDir)\n const installed = coerce(packageVersion ?? dependency.replaceAll(/[\\D.]/g, ''))\n\n if (!installed) {\n return false\n }\n\n const supported = pkg.supported.join(' || ')\n\n // \"Untested\" is usually the case where we have not upgraded the React version requirements\n // before a release, but given that is usually works in a backwards-compatible way, we want\n // to indicate that it's _untested_, not necessarily _unsupported_\n // Ex: Installed is react@20.0.0, but we've only _tested_ with react@^19\n const isUntested = !satisfies(installed, supported) && gtr(installed, supported)\n\n // \"Unsupported\" in that the installed version is _lower than_ the minimum version\n // Ex: Installed is react@18.0.0, but we require react@^19.2\n const isUnsupported = !satisfies(installed, supported) && !isUntested\n\n // \"Deprecated\" in that we will stop supporting it at some point in the near future,\n // so users should be prompted to upgrade\n const isDeprecated = pkg.deprecatedBelow ? ltr(installed, pkg.deprecatedBelow) : false\n\n return {\n ...pkg,\n installed,\n isDeprecated,\n isUnsupported,\n isUntested,\n }\n })\n\n const installedPackages = (await Promise.all(packageInfo)).filter(\n (inp): inp is PackageInfo => inp !== false,\n )\n const unsupported = installedPackages.filter((pkg) => pkg.isUnsupported)\n const deprecated = installedPackages.filter((pkg) => !pkg.isUnsupported && pkg.isDeprecated)\n const untested = installedPackages.filter((pkg) => pkg.isUntested)\n\n if (deprecated.length > 0) {\n output.warn(`The following package versions have been deprecated and should be upgraded:\n\n ${listPackages(deprecated)}\n\nSupport for these will be removed in a future release!\n\n ${getUpgradeInstructions(deprecated)}\n`)\n }\n\n if (untested.length > 0) {\n output.warn(`The following package versions have not yet been marked as supported:\n\n ${listPackages(untested)}\n\nYou _may_ encounter bugs while using these versions.\n\n ${getDowngradeInstructions(untested)}\n`)\n }\n\n if (unsupported.length > 0) {\n output.error(\n `The following package versions are no longer supported and needs to be upgraded:\n\n ${listPackages(unsupported)}\n\n ${getUpgradeInstructions(unsupported)}\n`,\n {exit: 1},\n )\n }\n}\n\nfunction listPackages(pkgs: PackageInfo[]) {\n return pkgs\n .map(\n (pkg) =>\n `${pkg.name} (installed: ${pkg.installed}, want: ${\n pkg.deprecatedBelow || pkg.supported.join(' || ')\n })`,\n )\n .join('\\n ')\n}\n\nfunction getUpgradeInstructions(pkgs: PackageInfo[]) {\n const inst = pkgs\n .map((pkg) => {\n const [highestSupported] = pkg.supported\n .map((version) => (coerce(version) || {version: ''}).version)\n .toSorted(rcompare)\n\n return `\"${pkg.name}@^${highestSupported}\"`\n })\n .join(' ')\n\n return `To upgrade, run either:\n\n npm install ${inst}\n\n or\n\n yarn add ${inst}\n\n or\n\n pnpm add ${inst}\n\n\nRead more at https://www.sanity.io/docs/help/upgrade-packages`\n}\n\nfunction getDowngradeInstructions(pkgs: PackageInfo[]) {\n const inst = pkgs\n .map((pkg) => {\n const [highestSupported] = pkg.supported\n .map((version) => (coerce(version) || {version: ''}).version)\n .toSorted(rcompare)\n\n return `\"${pkg.name}@^${highestSupported}\"`\n })\n .join(' ')\n\n return `To downgrade, run either:\n\n yarn add ${inst}\n\n or\n\n npm install ${inst}\n\n or\n\n pnpm install ${inst}`\n}\n"],"names":["path","getLocalPackageVersion","readPackageJson","coerce","gtr","ltr","rcompare","satisfies","DEFAULT_PACKAGES","deprecatedBelow","name","supported","checkStudioDependencyVersions","workDir","output","packages","manifest","join","skipSchemaValidation","dependencies","devDependencies","packageInfo","map","pkg","dependency","packageVersion","installed","replaceAll","isUntested","isUnsupported","isDeprecated","installedPackages","Promise","all","filter","inp","unsupported","deprecated","untested","length","warn","listPackages","getUpgradeInstructions","getDowngradeInstructions","error","exit","pkgs","inst","highestSupported","version","toSorted"],"mappings":"AAAA,OAAOA,UAAU,YAAW;AAE5B,SAAQC,sBAAsB,EAAeC,eAAe,QAAO,mBAAkB;AACrF,SAAQC,MAAM,EAAEC,GAAG,EAAEC,GAAG,EAAEC,QAAQ,EAAEC,SAAS,QAAoB,SAAQ;AAkBzE,kFAAkF;AAClF,sEAAsE;AACtE,MAAMC,mBAAqC;IACzC;QAACC,iBAAiB;QAAMC,MAAM;QAASC,WAAW;YAAC;SAAU;IAAA;IAC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AAO8C,YAAY;gBAACA,SAAS;YAAE,CAAA,EAAGA,OAAO,EAC3DC,QAAQ,CAAC5C;QAEZ,OAAO,CAAC,CAAC,EAAEiB,IAAIb,IAAI,CAAC,EAAE,EAAEsC,iBAAiB,CAAC,CAAC;IAC7C,GACC/B,IAAI,CAAC;IAER,OAAO,CAAC;;cAEI,EAAE8B,KAAK;;;;WAIV,EAAEA,KAAK;;;;WAIP,EAAEA,KAAK;;;6DAG2C,CAAC;AAC9D;AAEA,SAASJ,yBAAyBG,IAAmB;IACnD,MAAMC,OAAOD,KACVxB,GAAG,CAAC,CAACC;QACJ,MAAM,CAACyB,iBAAiB,GAAGzB,IAAIZ,SAAS,CACrCW,GAAG,CAAC,CAAC2B,UAAY,AAAC9C,CAAAA,OAAO8C,YAAY;gBAACA,SAAS;YAAE,CAAA,EAAGA,OAAO,EAC3DC,QAAQ,CAAC5C;QAEZ,OAAO,CAAC,CAAC,EAAEiB,IAAIb,IAAI,CAAC,EAAE,EAAEsC,iBAAiB,CAAC,CAAC;IAC7C,GACC/B,IAAI,CAAC;IAER,OAAO,CAAC;;WAEC,EAAE8B,KAAK;;;;cAIJ,EAAEA,KAAK;;;;eAIN,EAAEA,MAAM;AACvB"}
1
+ {"version":3,"sources":["../../../src/actions/build/checkStudioDependencyVersions.ts"],"sourcesContent":["import path from 'node:path'\n\nimport {getLocalPackageVersion, readPackageJson} from '@sanity/cli-core/package-manager'\nimport {type Output} from '@sanity/cli-core/types'\nimport {coerce, gtr, ltr, rcompare, satisfies, type SemVer} from 'semver'\n\ninterface PackageInfo {\n deprecatedBelow: string | null\n installed: SemVer\n isDeprecated: boolean\n isUnsupported: boolean\n isUntested: boolean\n name: string\n supported: string[]\n}\n\ninterface TrackedPackage {\n deprecatedBelow: string | null\n name: string\n supported: string[]\n}\n\n// NOTE: when doing changes here, also remember to update versions in help docs at\n// https://sanity.io/admin/structure/docs;helpArticle;upgrade-packages\nconst DEFAULT_PACKAGES: TrackedPackage[] = [\n {deprecatedBelow: null, name: 'react', supported: ['^19.2.2']},\n {deprecatedBelow: null, name: 'react-dom', supported: ['^19.2.2']},\n {deprecatedBelow: null, name: 'styled-components', supported: ['^6']},\n {deprecatedBelow: '^3', name: '@sanity/ui', supported: ['^2', '^3']},\n]\n\nexport async function checkStudioDependencyVersions(\n workDir: string,\n output: Output,\n {packages = DEFAULT_PACKAGES}: {packages?: TrackedPackage[]} = {},\n): Promise<void> {\n const manifest = await readPackageJson(path.join(workDir, 'package.json'), {\n skipSchemaValidation: true,\n })\n const dependencies = {...manifest?.dependencies, ...manifest?.devDependencies}\n\n const packageInfo = packages.map(async (pkg): Promise<false | PackageInfo> => {\n const dependency = dependencies[pkg.name]\n if (!dependency) {\n return false\n }\n\n const packageVersion = await getLocalPackageVersion(pkg.name, workDir)\n const installed = coerce(packageVersion ?? dependency.replaceAll(/[\\D.]/g, ''))\n\n if (!installed) {\n return false\n }\n\n const supported = pkg.supported.join(' || ')\n\n // \"Untested\" is usually the case where we have not upgraded the React version requirements\n // before a release, but given that is usually works in a backwards-compatible way, we want\n // to indicate that it's _untested_, not necessarily _unsupported_\n // Ex: Installed is react@20.0.0, but we've only _tested_ with react@^19\n const isUntested = !satisfies(installed, supported) && gtr(installed, supported)\n\n // \"Unsupported\" in that the installed version is _lower than_ the minimum version\n // Ex: Installed is react@18.0.0, but we require react@^19.2\n const isUnsupported = !satisfies(installed, supported) && !isUntested\n\n // \"Deprecated\" in that we will stop supporting it at some point in the near future,\n // so users should be prompted to upgrade\n const isDeprecated = pkg.deprecatedBelow ? ltr(installed, pkg.deprecatedBelow) : false\n\n return {\n ...pkg,\n installed,\n isDeprecated,\n isUnsupported,\n isUntested,\n }\n })\n\n const installedPackages = (await Promise.all(packageInfo)).filter(\n (inp): inp is PackageInfo => inp !== false,\n )\n const unsupported = installedPackages.filter((pkg) => pkg.isUnsupported)\n const deprecated = installedPackages.filter((pkg) => !pkg.isUnsupported && pkg.isDeprecated)\n const untested = installedPackages.filter((pkg) => pkg.isUntested)\n\n if (deprecated.length > 0) {\n output.warn(`The following package versions have been deprecated and should be upgraded:\n\n ${listPackages(deprecated)}\n\nSupport for these will be removed in a future release!\n\n ${getUpgradeInstructions(deprecated)}\n`)\n }\n\n if (untested.length > 0) {\n output.warn(`The following package versions have not yet been marked as supported:\n\n ${listPackages(untested)}\n\nYou _may_ encounter bugs while using these versions.\n\n ${getDowngradeInstructions(untested)}\n`)\n }\n\n if (unsupported.length > 0) {\n output.error(\n `The following package versions are no longer supported and needs to be upgraded:\n\n ${listPackages(unsupported)}\n\n ${getUpgradeInstructions(unsupported)}\n`,\n {exit: 1},\n )\n }\n}\n\nfunction listPackages(pkgs: PackageInfo[]) {\n return pkgs\n .map(\n (pkg) =>\n `${pkg.name} (installed: ${pkg.installed}, want: ${\n pkg.deprecatedBelow || pkg.supported.join(' || ')\n })`,\n )\n .join('\\n ')\n}\n\nfunction getUpgradeInstructions(pkgs: PackageInfo[]) {\n const inst = pkgs\n .map((pkg) => {\n const [highestSupported] = pkg.supported\n .map((version) => (coerce(version) || {version: ''}).version)\n .toSorted(rcompare)\n\n return `\"${pkg.name}@^${highestSupported}\"`\n })\n .join(' ')\n\n return `To upgrade, run either:\n\n npm install ${inst}\n\n or\n\n yarn add ${inst}\n\n or\n\n pnpm add ${inst}\n\n\nRead more at https://www.sanity.io/docs/help/upgrade-packages`\n}\n\nfunction getDowngradeInstructions(pkgs: PackageInfo[]) {\n const inst = pkgs\n .map((pkg) => {\n const [highestSupported] = pkg.supported\n .map((version) => (coerce(version) || {version: ''}).version)\n .toSorted(rcompare)\n\n return `\"${pkg.name}@^${highestSupported}\"`\n })\n .join(' ')\n\n return `To downgrade, run either:\n\n yarn add ${inst}\n\n or\n\n npm install ${inst}\n\n or\n\n pnpm install ${inst}`\n}\n"],"names":["path","getLocalPackageVersion","readPackageJson","coerce","gtr","ltr","rcompare","satisfies","DEFAULT_PACKAGES","deprecatedBelow","name","supported","checkStudioDependencyVersions","workDir","output","packages","manifest","join","skipSchemaValidation","dependencies","devDependencies","packageInfo","map","pkg","dependency","packageVersion","installed","replaceAll","isUntested","isUnsupported","isDeprecated","installedPackages","Promise","all","filter","inp","unsupported","deprecated","untested","length","warn","listPackages","getUpgradeInstructions","getDowngradeInstructions","error","exit","pkgs","inst","highestSupported","version","toSorted"],"mappings":"AAAA,OAAOA,UAAU,YAAW;AAE5B,SAAQC,sBAAsB,EAAEC,eAAe,QAAO,mCAAkC;AAExF,SAAQC,MAAM,EAAEC,GAAG,EAAEC,GAAG,EAAEC,QAAQ,EAAEC,SAAS,QAAoB,SAAQ;AAkBzE,kFAAkF;AAClF,sEAAsE;AACtE,MAAMC,mBAAqC;IACzC;QAACC,iBAAiB;QAAMC,MAAM;QAASC,WAAW;YAAC;SAAU;IAAA;IAC7D;QAACF,iBAAiB;QAAMC,MAAM;QAAaC,WAAW;YAAC;SAAU;IAAA;IACjE;QAACF,iBAAiB;QAAMC,MAAM;QAAqBC,WAAW;YAAC;SAAK;IAAA;IACpE;QAACF,iBAAiB;QAAMC,MAAM;QAAcC,WAAW;YAAC;YAAM;SAAK;IAAA;CACpE;AAED,OAAO,eAAeC,8BACpBC,OAAe,EACfC,MAAc,EACd,EAACC,WAAWP,gBAAgB,EAAgC,GAAG,CAAC,CAAC;IAEjE,MAAMQ,WAAW,MAAMd,gBAAgBF,KAAKiB,IAAI,CAACJ,SAAS,iBAAiB;QACzEK,sBAAsB;IACxB;IACA,MAAMC,eAAe;QAAC,GAAGH,UAAUG,YAAY;QAAE,GAAGH,UAAUI,eAAe;IAAA;IAE7E,MAAMC,cAAcN,SAASO,GAAG,CAAC,OAAOC;QACtC,MAAMC,aAAaL,YAAY,CAACI,IAAIb,IAAI,CAAC;QACzC,IAAI,CAACc,YAAY;YACf,OAAO;QACT;QAEA,MAAMC,iBAAiB,MAAMxB,uBAAuBsB,IAAIb,IAAI,EAAEG;QAC9D,MAAMa,YAAYvB,OAAOsB,kBAAkBD,WAAWG,UAAU,CAAC,UAAU;QAE3E,IAA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ACvB"}
@@ -1,4 +1,4 @@
1
- import { isStaging } from '@sanity/cli-core';
1
+ import { isStaging } from '@sanity/cli-core/util';
2
2
  /**
3
3
  * Decorates the given HTML template with a script tag that sets
4
4
  * `globalThis.__SANITY_STAGING__` to `true` when building in a
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/actions/build/decorateIndexWithStagingScript.ts"],"sourcesContent":["import {isStaging} from '@sanity/cli-core'\n\n/**\n * Decorates the given HTML template with a script tag that sets\n * `globalThis.__SANITY_STAGING__` to `true` when building in a\n * staging environment. The script is injected as the first child\n * of `<head>` so it runs before any module scripts.\n *\n * @internal\n */\nexport function decorateIndexWithStagingScript(template: string): string {\n if (!isStaging()) {\n return template\n }\n\n return template.replace(\n /<head([^>]*)>/,\n '<head$1>\\n<script>globalThis.__SANITY_STAGING__ = true</script>',\n )\n}\n"],"names":["isStaging","decorateIndexWithStagingScript","template","replace"],"mappings":"AAAA,SAAQA,SAAS,QAAO,mBAAkB;AAE1C;;;;;;;CAOC,GACD,OAAO,SAASC,+BAA+BC,QAAgB;IAC7D,IAAI,CAACF,aAAa;QAChB,OAAOE;IACT;IAEA,OAAOA,SAASC,OAAO,CACrB,iBACA;AAEJ"}
1
+ {"version":3,"sources":["../../../src/actions/build/decorateIndexWithStagingScript.ts"],"sourcesContent":["import {isStaging} from '@sanity/cli-core/util'\n\n/**\n * Decorates the given HTML template with a script tag that sets\n * `globalThis.__SANITY_STAGING__` to `true` when building in a\n * staging environment. The script is injected as the first child\n * of `<head>` so it runs before any module scripts.\n *\n * @internal\n */\nexport function decorateIndexWithStagingScript(template: string): string {\n if (!isStaging()) {\n return template\n }\n\n return template.replace(\n /<head([^>]*)>/,\n '<head$1>\\n<script>globalThis.__SANITY_STAGING__ = true</script>',\n )\n}\n"],"names":["isStaging","decorateIndexWithStagingScript","template","replace"],"mappings":"AAAA,SAAQA,SAAS,QAAO,wBAAuB;AAE/C;;;;;;;CAOC,GACD,OAAO,SAASC,+BAA+BC,QAAgB;IAC7D,IAAI,CAACF,aAAa;QAChB,OAAOE;IACT;IAEA,OAAOA,SAASC,OAAO,CACrB,iBACA;AAEJ"}
@@ -1,6 +1,7 @@
1
1
  import path from 'node:path';
2
2
  import babel from '@rolldown/plugin-babel';
3
- import { findProjectRoot, getCliTelemetry } from '@sanity/cli-core';
3
+ import { findProjectRoot } from '@sanity/cli-core/config';
4
+ import { getCliTelemetry } from '@sanity/cli-core/telemetry';
4
5
  import { workbenchVitePlugins } from '@sanity/workbench-cli/build';
5
6
  import viteReact, { reactCompilerPreset } from '@vitejs/plugin-react';
6
7
  import debug from 'debug';
@@ -20,8 +21,8 @@ import { getDefaultFaviconsPath } from './writeFavicons.js';
20
21
  *
21
22
  * @internal Only meant for consumption inside of Sanity modules, do not depend on this externally
22
23
  */ export async function getViteConfig(options) {
23
- const { additionalPlugins, autoUpdates, basePath: rawBasePath = '/', cwd, entries, isApp, isWorkbenchApp, minify, mode, outputDir, reactCompiler, schemaExtraction, server, services, // default to `true` when `mode=development`
24
- sourceMap = options.mode === 'development', views } = options;
24
+ const { additionalPlugins, autoUpdates, basePath: rawBasePath = '/', cwd, entries, exposes, isApp, isWorkbenchApp, minify, mode, outputDir, reactCompiler, schemaExtraction, server, // default to `true` when `mode=development`
25
+ sourceMap = options.mode === 'development', workbenchAppId } = options;
25
26
  const basePath = normalizeBasePath(rawBasePath);
26
27
  const configPath = (await findProjectRoot(cwd)).path;
27
28
  const customFaviconsPath = path.join(cwd, 'static');
@@ -84,11 +85,11 @@ import { getDefaultFaviconsPath } from './writeFavicons.js';
84
85
  ...isWorkbenchApp ? [
85
86
  ...sharedPlugins,
86
87
  await workbenchVitePlugins({
88
+ appId: workbenchAppId,
87
89
  cwd,
88
90
  entries,
89
- isApp,
90
- services,
91
- views
91
+ exposes,
92
+ isApp
92
93
  })
93
94
  ] : [
94
95
  ...sharedPlugins,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/actions/build/getViteConfig.ts"],"sourcesContent":["import path from 'node:path'\n\nimport babel from '@rolldown/plugin-babel'\nimport {\n type CliConfig,\n findProjectRoot,\n getCliTelemetry,\n type UserViteConfig,\n} from '@sanity/cli-core'\nimport {type DefineAppInput} from '@sanity/workbench-cli'\nimport {workbenchVitePlugins} from '@sanity/workbench-cli/build'\nimport viteReact, {reactCompilerPreset} from '@vitejs/plugin-react'\nimport {type PluginOptions as ReactCompilerConfig} from 'babel-plugin-react-compiler'\nimport debug from 'debug'\nimport {\n type ConfigEnv,\n esmExternalRequirePlugin,\n type InlineConfig,\n mergeConfig,\n type Plugin,\n type PluginOption,\n type Rolldown,\n} from 'vite'\n\nimport {SANITY_CACHE_DIR} from '../../constants.js'\nimport {sanitySchemaExtractionPlugin} from '../schema/vite/plugin-schema-extraction.js'\nimport {type AutoUpdatesBuildConfig} from './autoUpdates.js'\nimport {VENDOR_DIR} from './constants.js'\nimport {createExternalFromImportMap} from './createExternalFromImportMap.js'\nimport {normalizeBasePath} from './normalizeBasePath.js'\nimport {sanityBuildEntries} from './vite/plugin-sanity-build-entries.js'\nimport {sanityFaviconsPlugin} from './vite/plugin-sanity-favicons.js'\nimport {sanityRuntimeRewritePlugin} from './vite/plugin-sanity-runtime-rewrite.js'\nimport {createVendorNamedExportsPlugin} from './vite/plugin-sanity-vendor-named-exports.js'\nimport {getDefaultFaviconsPath} from './writeFavicons.js'\n\ninterface ViteOptions {\n /**\n * Root path of the studio/sanity app\n */\n cwd: string\n\n entries: {\n relativeConfigLocation: string | null\n // `null` when a branded app declares no `entry` (sanity-io/workbench spec 002-workbench-extension-api, US5) — no app view.\n relativeEntry: string | null\n }\n\n /**\n * Returns the environment variables to be injected into the config.\n */\n getEnvironmentVariables(): Record<string, string>\n\n /**\n * Mode to run vite in - eg development or production\n */\n mode: 'development' | 'production'\n\n reactCompiler: ReactCompilerConfig | undefined\n\n /**\n * Additional plugins when configured, eg. typegen\n */\n additionalPlugins?: Plugin[]\n\n /**\n * Auto-updates configuration (production builds only). When set, vendor\n * packages are emitted as hashed ESM chunks by this build and the import map\n * in `index.html` is derived from the build output.\n */\n autoUpdates?: AutoUpdatesBuildConfig\n\n /**\n * Base path (eg under where to serve the app - `/studio` or similar)\n * Will be normalized to ensure it starts and ends with a `/`\n */\n basePath?: string\n\n isApp?: boolean\n\n /**\n * Whether this is a workbench app (opted in via `unstable_defineApp`). Drives\n * the module-federation build.\n */\n isWorkbenchApp?: boolean\n\n /**\n * Whether or not to minify the output (only used in `mode: 'production'`)\n */\n minify?: boolean\n\n /**\n * Output directory (eg where to place the built files, if any)\n */\n outputDir?: string\n\n /**\n * Schema extraction configuration\n */\n schemaExtraction?: CliConfig['schemaExtraction']\n\n /**\n * HTTP development server configuration\n */\n server?: {host?: string; port?: number}\n /**\n * Background services the workbench app declares. Built into self-contained\n * worker bundles and exposed through module federation as `./services/<name>`.\n */\n services?: DefineAppInput['services']\n\n /**\n * Whether or not to enable source maps\n */\n sourceMap?: boolean\n\n /**\n * Views the workbench app declares. Built into render-contract artifacts and\n * exposed through module federation as `./views/<name>`.\n */\n views?: DefineAppInput['views']\n}\n\n/**\n * Get a configuration object for Vite based on the passed options\n *\n * @internal Only meant for consumption inside of Sanity modules, do not depend on this externally\n */\nexport async function getViteConfig(options: ViteOptions): Promise<InlineConfig> {\n const {\n additionalPlugins,\n autoUpdates,\n basePath: rawBasePath = '/',\n cwd,\n entries,\n isApp,\n isWorkbenchApp,\n minify,\n mode,\n outputDir,\n reactCompiler,\n schemaExtraction,\n server,\n services,\n // default to `true` when `mode=development`\n sourceMap = options.mode === 'development',\n views,\n } = options\n\n const basePath = normalizeBasePath(rawBasePath)\n\n const configPath = (await findProjectRoot(cwd)).path\n\n const customFaviconsPath = path.join(cwd, 'static')\n const defaultFaviconsPath = await getDefaultFaviconsPath()\n const staticPath = `${basePath}static`\n\n const envVars = options.getEnvironmentVariables()\n\n const sharedPlugins: PluginOption = [\n viteReact(),\n ...(reactCompiler ? [babel({presets: [reactCompilerPreset(reactCompiler)]})] : []),\n ...(schemaExtraction?.enabled\n ? [\n sanitySchemaExtractionPlugin({\n additionalPatterns: schemaExtraction.watchPatterns,\n configPath,\n enforceRequiredFields: schemaExtraction.enforceRequiredFields,\n outputPath: schemaExtraction.path,\n telemetryLogger: getCliTelemetry(),\n workDir: cwd,\n workspaceName: schemaExtraction.workspace,\n }),\n ]\n : []),\n ]\n\n const viteConfig: InlineConfig = {\n base: basePath,\n build: {\n outDir: outputDir || path.resolve(cwd, 'dist'),\n sourcemap: sourceMap,\n },\n // Define a custom cache directory so that sanity's vite cache\n // does not conflict with any potential local vite projects\n cacheDir: `${SANITY_CACHE_DIR}/vite`,\n configFile: false,\n define: {\n __SANITY_BUILD_TIMESTAMP__: JSON.stringify(Date.now()),\n __SANITY_STAGING__: process.env.SANITY_INTERNAL_ENV === 'staging',\n 'process.env.MODE': JSON.stringify(mode),\n 'process.env.PKG_BUILD_VERSION': JSON.stringify(process.env.PKG_BUILD_VERSION),\n /**\n * Yes, double negatives are confusing.\n * The default value of `SC_DISABLE_SPEEDY` is `process.env.NODE_ENV === 'production'`: https://github.com/styled-components/styled-components/blob/99c02f52d69e8e509c0bf012cadee7f8e819a6dd/packages/styled-components/src/constants.ts#L34\n * Which means that in production, use the much faster way of inserting CSS rules, based on the CSSStyleSheet API (https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet/insertRule)\n * while in dev mode, use the slower way of inserting CSS rules, which appends text nodes to the `<style>` tag: https://github.com/styled-components/styled-components/blob/99c02f52d69e8e509c0bf012cadee7f8e819a6dd/packages/styled-components/src/sheet/Tag.ts#L74-L76\n * There are historical reasons for this, primarily that browsers initially did not support editing CSS rules in the DevTools inspector if `CSSStyleSheet.insetRule` were used.\n * However, that's no longer the case (since Chrome 81 back in April 2020: https://developer.chrome.com/docs/css-ui/css-in-js), the latest version of FireFox also supports it,\n * and there is no longer any reason to use the much slower method in dev mode.\n */\n 'process.env.SC_DISABLE_SPEEDY': JSON.stringify('false'),\n ...envVars,\n },\n envPrefix: isApp ? 'SANITY_APP_' : 'SANITY_STUDIO_',\n logLevel: mode === 'production' ? 'silent' : 'info',\n mode,\n plugins: [\n // Federation builds only need the federation plugin — skip client-specific\n // plugins (favicons, runtime rewrite, build entries)\n ...(isWorkbenchApp\n ? [...sharedPlugins, await workbenchVitePlugins({cwd, entries, isApp, services, views})]\n : [\n ...sharedPlugins,\n sanityFaviconsPlugin({\n customFaviconsPath,\n defaultFaviconsPath,\n staticUrlPath: staticPath,\n }),\n sanityRuntimeRewritePlugin(),\n sanityBuildEntries({autoUpdates, basePath, cwd, isApp}),\n ]),\n // Caller-provided plugins (e.g. typegen in dev) aren't client-specific,\n // so they apply to federation builds too.\n ...(additionalPlugins || []),\n ],\n resolve: {\n dedupe: ['react', 'react-dom', 'sanity', 'styled-components'],\n // Honor the studio's tsconfig `paths`, consistent with studioWorkerLoader.worker.ts.\n tsconfigPaths: true,\n },\n root: cwd,\n server: {\n host: server?.host,\n port: server?.port || 3333,\n // Apps drift to a free port (the reported URL embeds whichever port was\n // claimed), and workbench runs stack servers on adjacent ports — both\n // need the fallback. Studios fail fast on a busy port.\n strictPort: !isApp && !isWorkbenchApp,\n\n /**\n * Significantly speed up startup time,\n * and most importantly eliminates the `new dependencies optimized: foobar. optimized dependencies changed. reloading`\n * types of initial reload loops that otherwise happen as vite discovers deps that need to be optimized.\n * This option starts the traversal up front, and warms up the dep tree required to render the userland sanity.config.ts file,\n * and thus avoids frustrating reload loops.\n */\n warmup: {\n clientFiles: ['./.sanity/runtime/app.js'],\n },\n },\n }\n\n // Federation builds don't produce a client bundle — the federation\n // plugin configures its own environment and build entry point.\n if (mode === 'production' && !isWorkbenchApp) {\n if (autoUpdates) {\n viteConfig.plugins!.push(\n // Re-expose CommonJS named exports (react, react-dom) as real ESM exports\n // on the emitted vendor chunks; Rolldown only emits `export default` for a\n // CommonJS entry.\n createVendorNamedExportsPlugin(autoUpdates.vendor.namesByChunkName),\n // The import map and vendor specifiers are externals of the studio/app\n // bundle, resolved by the browser at runtime. They are handed to\n // `esmExternalRequirePlugin` rather than `rolldownOptions.external`: the\n // plugin both marks them external AND rewrites bundled CommonJS\n // `require()` calls of an external (e.g. react-dom requiring react) into\n // ESM imports, while `rolldownOptions.external` would short-circuit that\n // rewrite and leave a runtime `require` shim that throws in the browser.\n esmExternalRequirePlugin({\n external: createExternalFromImportMap({\n imports: {\n ...autoUpdates.imports,\n ...Object.fromEntries(\n Object.values(autoUpdates.vendor.specifiersByChunkName).map((specifier) => [\n specifier,\n '',\n ]),\n ),\n },\n }),\n }),\n )\n }\n\n const vendorChunkNames = autoUpdates\n ? new Set(Object.keys(autoUpdates.vendor.specifiersByChunkName))\n : null\n\n viteConfig.build = {\n ...viteConfig.build,\n\n assetsDir: 'static',\n emptyOutDir: false, // Rely on CLI to do this\n minify: minify ? 'oxc' : false,\n\n rolldownOptions: {\n input: {\n sanity: path.join(cwd, '.sanity', 'runtime', 'app.js'),\n ...autoUpdates?.vendor.entries,\n },\n onwarn: onRolldownWarn,\n ...(autoUpdates\n ? {\n // Expose Rolldown's native MagicString on `renderChunk`'s `meta` so\n // the vendor named-exports plugin can edit chunks without a JS\n // dependency.\n experimental: {nativeMagicString: true},\n output: {\n entryFileNames: (chunk) =>\n vendorChunkNames!.has(chunk.name)\n ? `${VENDOR_DIR}/[name]-[hash].mjs`\n : 'static/[name]-[hash].js',\n exports: 'named',\n },\n // App-style builds default to `preserveEntrySignatures: false`, which\n // treeshakes the exports off entry chunks. Vendor chunks are loaded by\n // the browser via the import map, so their exports must survive (e.g.\n // styled-components' native ESM exports). `exports-only` keeps exports\n // for entries that have them, while the export-less `sanity` app entry\n // still bundles as before.\n preserveEntrySignatures: 'exports-only',\n }\n : {}),\n },\n }\n }\n\n return viteConfig\n}\n\nfunction onRolldownWarn(warning: Rolldown.RolldownLog, warn: Rolldown.LoggingFunction) {\n if (suppressUnusedImport(warning)) {\n return\n }\n\n warn(warning)\n}\n\nfunction suppressUnusedImport(warning: Rolldown.RolldownLog & {ids?: string[]}): boolean {\n if (warning.code !== 'UNUSED_EXTERNAL_IMPORT') return false\n\n // Suppress:\n // ```\n // \"useDebugValue\" is imported from external module \"react\"…\n // ```\n if (warning.names?.includes('useDebugValue')) {\n warning.names = warning.names.filter((n) => n !== 'useDebugValue')\n if (warning.names.length === 0) return true\n }\n\n // If some library does something unexpected, we suppress since it isn't actionable\n if (warning.ids?.every((id) => id.includes('/node_modules/') || id.includes('\\\\node_modules\\\\')))\n return true\n\n return false\n}\n\n/**\n * Re-asserts the critical parts of the default config after a userland vite\n * config (`vite` in `sanity.cli.ts`) has been applied.\n *\n * Everything `getViteConfig` sets under `build.rolldownOptions` is load-bearing:\n * the `input` entries (the studio entry plus, for auto-updating studios/apps,\n * the vendor entries), `preserveEntrySignatures`, the `experimental` flags the\n * vendor plugins rely on, and the `output` chunk naming. A userland config that\n * returns a brand-new object for any of these would silently break the build\n * (e.g. vendor chunks never emitted while the bundle still treats them as\n * external), so the default `rolldownOptions` are deep-merged back over the\n * userland config: userland additions survive, replacements of critical\n * options are healed.\n *\n * @param config - User-modified configuration\n * @param defaultConfig - The configuration produced by `getViteConfig`, before the userland config was applied\n * @returns Merged configuration\n * @internal\n */\nexport async function finalizeViteConfig(\n config: InlineConfig,\n defaultConfig: InlineConfig,\n): Promise<InlineConfig> {\n if (typeof config.build?.rolldownOptions?.input !== 'object') {\n throw new TypeError(\n 'Vite config must contain `build.rolldownOptions.input`, and it must be an object',\n )\n }\n\n if (!config.root) {\n throw new Error(\n 'Vite config must contain `root` property, and must point to the Sanity root directory',\n )\n }\n\n return mergeConfig(config, {\n build: {\n rolldownOptions: defaultConfig.build?.rolldownOptions ?? {},\n },\n })\n}\n\n/**\n * Merge user-provided Vite configuration object or function\n *\n * @param defaultConfig - Default configuration object\n * @param userConfig - User-provided configuration object or function\n * @returns Merged configuration\n * @internal\n */\nexport async function extendViteConfigWithUserConfig(\n env: ConfigEnv,\n defaultConfig: InlineConfig,\n userConfig: UserViteConfig,\n): Promise<InlineConfig> {\n let config = defaultConfig\n\n if (typeof userConfig === 'function') {\n debug('Extending vite config using user-specified function')\n config = await userConfig(config, env)\n } else if (typeof userConfig === 'object') {\n debug('Merging vite config using user-specified object')\n config = mergeConfig(config, userConfig)\n }\n\n return config\n}\n"],"names":["path","babel","findProjectRoot","getCliTelemetry","workbenchVitePlugins","viteReact","reactCompilerPreset","debug","esmExternalRequirePlugin","mergeConfig","SANITY_CACHE_DIR","sanitySchemaExtractionPlugin","VENDOR_DIR","createExternalFromImportMap","normalizeBasePath","sanityBuildEntries","sanityFaviconsPlugin","sanityRuntimeRewritePlugin","createVendorNamedExportsPlugin","getDefaultFaviconsPath","getViteConfig","options","additionalPlugins","autoUpdates","basePath","rawBasePath","cwd","entries","isApp","isWorkbenchApp","minify","mode","outputDir","reactCompiler","schemaExtraction","server","services","sourceMap","views","configPath","customFaviconsPath","join","defaultFaviconsPath","staticPath","envVars","getEnvironmentVariables","sharedPlugins","presets","enabled","additionalPatterns","watchPatterns","enforceRequiredFields","outputPath","telemetryLogger","workDir","workspaceName","workspace","viteConfig","base","build","outDir","resolve","sourcemap","cacheDir","configFile","define","__SANITY_BUILD_TIMESTAMP__","JSON","stringify","Date","now","__SANITY_STAGING__","process","env","SANITY_INTERNAL_ENV","PKG_BUILD_VERSION","envPrefix","logLevel","plugins","staticUrlPath","dedupe","tsconfigPaths","root","host","port","strictPort","warmup","clientFiles","push","vendor","namesByChunkName","external","imports","Object","fromEntries","values","specifiersByChunkName","map","specifier","vendorChunkNames","Set","keys","assetsDir","emptyOutDir","rolldownOptions","input","sanity","onwarn","onRolldownWarn","experimental","nativeMagicString","output","entryFileNames","chunk","has","name","exports","preserveEntrySignatures","warning","warn","suppressUnusedImport","code","names","includes","filter","n","length","ids","every","id","finalizeViteConfig","config","defaultConfig","TypeError","Error","extendViteConfigWithUserConfig","userConfig"],"mappings":"AAAA,OAAOA,UAAU,YAAW;AAE5B,OAAOC,WAAW,yBAAwB;AAC1C,SAEEC,eAAe,EACfC,eAAe,QAEV,mBAAk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;IAEJ;IAEA,OAAO7H,YAAY0H,QAAQ;QACzBxE,OAAO;YACL6C,iBAAiB4B,cAAczE,KAAK,EAAE6C,mBAAmB,CAAC;QAC5D;IACF;AACF;AAEA;;;;;;;CAOC,GACD,OAAO,eAAe+B,+BACpB9D,GAAc,EACd2D,aAA2B,EAC3BI,UAA0B;IAE1B,IAAIL,SAASC;IAEb,IAAI,OAAOI,eAAe,YAAY;QACpCjI,MAAM;QACN4H,SAAS,MAAMK,WAAWL,QAAQ1D;IACpC,OAAO,IAAI,OAAO+D,eAAe,UAAU;QACzCjI,MAAM;QACN4H,SAAS1H,YAAY0H,QAAQK;IAC/B;IAEA,OAAOL;AACT"}
1
+ {"version":3,"sources":["../../../src/actions/build/getViteConfig.ts"],"sourcesContent":["import path from 'node:path'\n\nimport babel from '@rolldown/plugin-babel'\nimport {findProjectRoot} from '@sanity/cli-core/config'\nimport {getCliTelemetry} from '@sanity/cli-core/telemetry'\nimport {type CliConfig, type UserViteConfig} from '@sanity/cli-core/types'\nimport {type WorkbenchExposes, workbenchVitePlugins} from '@sanity/workbench-cli/build'\nimport viteReact, {reactCompilerPreset} from '@vitejs/plugin-react'\nimport {type PluginOptions as ReactCompilerConfig} from 'babel-plugin-react-compiler'\nimport debug from 'debug'\nimport {\n type ConfigEnv,\n esmExternalRequirePlugin,\n type InlineConfig,\n mergeConfig,\n type Plugin,\n type PluginOption,\n type Rolldown,\n} from 'vite'\n\nimport {SANITY_CACHE_DIR} from '../../constants.js'\nimport {sanitySchemaExtractionPlugin} from '../schema/vite/plugin-schema-extraction.js'\nimport {type AutoUpdatesBuildConfig} from './autoUpdates.js'\nimport {VENDOR_DIR} from './constants.js'\nimport {createExternalFromImportMap} from './createExternalFromImportMap.js'\nimport {normalizeBasePath} from './normalizeBasePath.js'\nimport {sanityBuildEntries} from './vite/plugin-sanity-build-entries.js'\nimport {sanityFaviconsPlugin} from './vite/plugin-sanity-favicons.js'\nimport {sanityRuntimeRewritePlugin} from './vite/plugin-sanity-runtime-rewrite.js'\nimport {createVendorNamedExportsPlugin} from './vite/plugin-sanity-vendor-named-exports.js'\nimport {getDefaultFaviconsPath} from './writeFavicons.js'\n\ninterface ViteOptions {\n /**\n * Root path of the studio/sanity app\n */\n cwd: string\n\n entries: {\n relativeConfigLocation: string | null\n // `null` when a branded app declares no `entry` (sanity-io/workbench spec 002-workbench-extension-api, US5) — no app view.\n relativeEntry: string | null\n }\n\n /**\n * Returns the environment variables to be injected into the config.\n */\n getEnvironmentVariables(): Record<string, string>\n\n /**\n * Mode to run vite in - eg development or production\n */\n mode: 'development' | 'production'\n\n reactCompiler: ReactCompilerConfig | undefined\n\n /**\n * Additional plugins when configured, eg. typegen\n */\n additionalPlugins?: Plugin[]\n\n /**\n * Auto-updates configuration (production builds only). When set, vendor\n * packages are emitted as hashed ESM chunks by this build and the import map\n * in `index.html` is derived from the build output.\n */\n autoUpdates?: AutoUpdatesBuildConfig\n\n /**\n * Base path (eg under where to serve the app - `/studio` or similar)\n * Will be normalized to ensure it starts and ends with a `/`\n */\n basePath?: string\n\n exposes?: WorkbenchExposes\n\n isApp?: boolean\n\n /**\n * Whether this is a workbench app (opted in via `unstable_defineApp`). Drives\n * the module-federation build.\n */\n isWorkbenchApp?: boolean\n\n /**\n * Whether or not to minify the output (only used in `mode: 'production'`)\n */\n minify?: boolean\n\n /**\n * Output directory (eg where to place the built files, if any)\n */\n outputDir?: string\n\n /**\n * Schema extraction configuration\n */\n schemaExtraction?: CliConfig['schemaExtraction']\n\n /**\n * HTTP development server configuration\n */\n server?: {host?: string; port?: number}\n\n /**\n * Whether or not to enable source maps\n */\n sourceMap?: boolean\n\n /**\n * The workbench app's bus identity, stamped into its modules as\n * `__SANITY_APP_ID__` for `@sanity/runtime`. Only read for workbench apps.\n */\n workbenchAppId?: string\n}\n\n/**\n * Get a configuration object for Vite based on the passed options\n *\n * @internal Only meant for consumption inside of Sanity modules, do not depend on this externally\n */\nexport async function getViteConfig(options: ViteOptions): Promise<InlineConfig> {\n const {\n additionalPlugins,\n autoUpdates,\n basePath: rawBasePath = '/',\n cwd,\n entries,\n exposes,\n isApp,\n isWorkbenchApp,\n minify,\n mode,\n outputDir,\n reactCompiler,\n schemaExtraction,\n server,\n // default to `true` when `mode=development`\n sourceMap = options.mode === 'development',\n workbenchAppId,\n } = options\n\n const basePath = normalizeBasePath(rawBasePath)\n\n const configPath = (await findProjectRoot(cwd)).path\n\n const customFaviconsPath = path.join(cwd, 'static')\n const defaultFaviconsPath = await getDefaultFaviconsPath()\n const staticPath = `${basePath}static`\n\n const envVars = options.getEnvironmentVariables()\n\n const sharedPlugins: PluginOption = [\n viteReact(),\n ...(reactCompiler ? [babel({presets: [reactCompilerPreset(reactCompiler)]})] : []),\n ...(schemaExtraction?.enabled\n ? [\n sanitySchemaExtractionPlugin({\n additionalPatterns: schemaExtraction.watchPatterns,\n configPath,\n enforceRequiredFields: schemaExtraction.enforceRequiredFields,\n outputPath: schemaExtraction.path,\n telemetryLogger: getCliTelemetry(),\n workDir: cwd,\n workspaceName: schemaExtraction.workspace,\n }),\n ]\n : []),\n ]\n\n const viteConfig: InlineConfig = {\n base: basePath,\n build: {\n outDir: outputDir || path.resolve(cwd, 'dist'),\n sourcemap: sourceMap,\n },\n // Define a custom cache directory so that sanity's vite cache\n // does not conflict with any potential local vite projects\n cacheDir: `${SANITY_CACHE_DIR}/vite`,\n configFile: false,\n define: {\n __SANITY_BUILD_TIMESTAMP__: JSON.stringify(Date.now()),\n __SANITY_STAGING__: process.env.SANITY_INTERNAL_ENV === 'staging',\n 'process.env.MODE': JSON.stringify(mode),\n 'process.env.PKG_BUILD_VERSION': JSON.stringify(process.env.PKG_BUILD_VERSION),\n /**\n * Yes, double negatives are confusing.\n * The default value of `SC_DISABLE_SPEEDY` is `process.env.NODE_ENV === 'production'`: https://github.com/styled-components/styled-components/blob/99c02f52d69e8e509c0bf012cadee7f8e819a6dd/packages/styled-components/src/constants.ts#L34\n * Which means that in production, use the much faster way of inserting CSS rules, based on the CSSStyleSheet API (https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet/insertRule)\n * while in dev mode, use the slower way of inserting CSS rules, which appends text nodes to the `<style>` tag: https://github.com/styled-components/styled-components/blob/99c02f52d69e8e509c0bf012cadee7f8e819a6dd/packages/styled-components/src/sheet/Tag.ts#L74-L76\n * There are historical reasons for this, primarily that browsers initially did not support editing CSS rules in the DevTools inspector if `CSSStyleSheet.insetRule` were used.\n * However, that's no longer the case (since Chrome 81 back in April 2020: https://developer.chrome.com/docs/css-ui/css-in-js), the latest version of FireFox also supports it,\n * and there is no longer any reason to use the much slower method in dev mode.\n */\n 'process.env.SC_DISABLE_SPEEDY': JSON.stringify('false'),\n ...envVars,\n },\n envPrefix: isApp ? 'SANITY_APP_' : 'SANITY_STUDIO_',\n logLevel: mode === 'production' ? 'silent' : 'info',\n mode,\n plugins: [\n // Federation builds only need the federation plugin — skip client-specific\n // plugins (favicons, runtime rewrite, build entries)\n ...(isWorkbenchApp\n ? [\n ...sharedPlugins,\n await workbenchVitePlugins({appId: workbenchAppId, cwd, entries, exposes, isApp}),\n ]\n : [\n ...sharedPlugins,\n sanityFaviconsPlugin({\n customFaviconsPath,\n defaultFaviconsPath,\n staticUrlPath: staticPath,\n }),\n sanityRuntimeRewritePlugin(),\n sanityBuildEntries({autoUpdates, basePath, cwd, isApp}),\n ]),\n // Caller-provided plugins (e.g. typegen in dev) aren't client-specific,\n // so they apply to federation builds too.\n ...(additionalPlugins || []),\n ],\n resolve: {\n dedupe: ['react', 'react-dom', 'sanity', 'styled-components'],\n // Honor the studio's tsconfig `paths`, consistent with studioWorkerLoader.worker.ts.\n tsconfigPaths: true,\n },\n root: cwd,\n server: {\n host: server?.host,\n port: server?.port || 3333,\n // Apps drift to a free port (the reported URL embeds whichever port was\n // claimed), and workbench runs stack servers on adjacent ports — both\n // need the fallback. Studios fail fast on a busy port.\n strictPort: !isApp && !isWorkbenchApp,\n\n /**\n * Significantly speed up startup time,\n * and most importantly eliminates the `new dependencies optimized: foobar. optimized dependencies changed. reloading`\n * types of initial reload loops that otherwise happen as vite discovers deps that need to be optimized.\n * This option starts the traversal up front, and warms up the dep tree required to render the userland sanity.config.ts file,\n * and thus avoids frustrating reload loops.\n */\n warmup: {\n clientFiles: ['./.sanity/runtime/app.js'],\n },\n },\n }\n\n // Federation builds don't produce a client bundle — the federation\n // plugin configures its own environment and build entry point.\n if (mode === 'production' && !isWorkbenchApp) {\n if (autoUpdates) {\n viteConfig.plugins!.push(\n // Re-expose CommonJS named exports (react, react-dom) as real ESM exports\n // on the emitted vendor chunks; Rolldown only emits `export default` for a\n // CommonJS entry.\n createVendorNamedExportsPlugin(autoUpdates.vendor.namesByChunkName),\n // The import map and vendor specifiers are externals of the studio/app\n // bundle, resolved by the browser at runtime. They are handed to\n // `esmExternalRequirePlugin` rather than `rolldownOptions.external`: the\n // plugin both marks them external AND rewrites bundled CommonJS\n // `require()` calls of an external (e.g. react-dom requiring react) into\n // ESM imports, while `rolldownOptions.external` would short-circuit that\n // rewrite and leave a runtime `require` shim that throws in the browser.\n esmExternalRequirePlugin({\n external: createExternalFromImportMap({\n imports: {\n ...autoUpdates.imports,\n ...Object.fromEntries(\n Object.values(autoUpdates.vendor.specifiersByChunkName).map((specifier) => [\n specifier,\n '',\n ]),\n ),\n },\n }),\n }),\n )\n }\n\n const vendorChunkNames = autoUpdates\n ? new Set(Object.keys(autoUpdates.vendor.specifiersByChunkName))\n : null\n\n viteConfig.build = {\n ...viteConfig.build,\n\n assetsDir: 'static',\n emptyOutDir: false, // Rely on CLI to do this\n minify: minify ? 'oxc' : false,\n\n rolldownOptions: {\n input: {\n sanity: path.join(cwd, '.sanity', 'runtime', 'app.js'),\n ...autoUpdates?.vendor.entries,\n },\n onwarn: onRolldownWarn,\n ...(autoUpdates\n ? {\n // Expose Rolldown's native MagicString on `renderChunk`'s `meta` so\n // the vendor named-exports plugin can edit chunks without a JS\n // dependency.\n experimental: {nativeMagicString: true},\n output: {\n entryFileNames: (chunk) =>\n vendorChunkNames!.has(chunk.name)\n ? `${VENDOR_DIR}/[name]-[hash].mjs`\n : 'static/[name]-[hash].js',\n exports: 'named',\n },\n // App-style builds default to `preserveEntrySignatures: false`, which\n // treeshakes the exports off entry chunks. Vendor chunks are loaded by\n // the browser via the import map, so their exports must survive (e.g.\n // styled-components' native ESM exports). `exports-only` keeps exports\n // for entries that have them, while the export-less `sanity` app entry\n // still bundles as before.\n preserveEntrySignatures: 'exports-only',\n }\n : {}),\n },\n }\n }\n\n return viteConfig\n}\n\nfunction onRolldownWarn(warning: Rolldown.RolldownLog, warn: Rolldown.LoggingFunction) {\n if (suppressUnusedImport(warning)) {\n return\n }\n\n warn(warning)\n}\n\nfunction suppressUnusedImport(warning: Rolldown.RolldownLog & {ids?: string[]}): boolean {\n if (warning.code !== 'UNUSED_EXTERNAL_IMPORT') return false\n\n // Suppress:\n // ```\n // \"useDebugValue\" is imported from external module \"react\"…\n // ```\n if (warning.names?.includes('useDebugValue')) {\n warning.names = warning.names.filter((n) => n !== 'useDebugValue')\n if (warning.names.length === 0) return true\n }\n\n // If some library does something unexpected, we suppress since it isn't actionable\n if (warning.ids?.every((id) => id.includes('/node_modules/') || id.includes('\\\\node_modules\\\\')))\n return true\n\n return false\n}\n\n/**\n * Re-asserts the critical parts of the default config after a userland vite\n * config (`vite` in `sanity.cli.ts`) has been applied.\n *\n * Everything `getViteConfig` sets under `build.rolldownOptions` is load-bearing:\n * the `input` entries (the studio entry plus, for auto-updating studios/apps,\n * the vendor entries), `preserveEntrySignatures`, the `experimental` flags the\n * vendor plugins rely on, and the `output` chunk naming. A userland config that\n * returns a brand-new object for any of these would silently break the build\n * (e.g. vendor chunks never emitted while the bundle still treats them as\n * external), so the default `rolldownOptions` are deep-merged back over the\n * userland config: userland additions survive, replacements of critical\n * options are healed.\n *\n * @param config - User-modified configuration\n * @param defaultConfig - The configuration produced by `getViteConfig`, before the userland config was applied\n * @returns Merged configuration\n * @internal\n */\nexport async function finalizeViteConfig(\n config: InlineConfig,\n defaultConfig: InlineConfig,\n): Promise<InlineConfig> {\n if (typeof config.build?.rolldownOptions?.input !== 'object') {\n throw new TypeError(\n 'Vite config must contain `build.rolldownOptions.input`, and it must be an object',\n )\n }\n\n if (!config.root) {\n throw new Error(\n 'Vite config must contain `root` property, and must point to the Sanity root directory',\n )\n }\n\n return mergeConfig(config, {\n build: {\n rolldownOptions: defaultConfig.build?.rolldownOptions ?? {},\n },\n })\n}\n\n/**\n * Merge user-provided Vite configuration object or function\n *\n * @param defaultConfig - Default configuration object\n * @param userConfig - User-provided configuration object or function\n * @returns Merged configuration\n * @internal\n */\nexport async function extendViteConfigWithUserConfig(\n env: ConfigEnv,\n defaultConfig: InlineConfig,\n userConfig: UserViteConfig,\n): Promise<InlineConfig> {\n let config = defaultConfig\n\n if (typeof userConfig === 'function') {\n debug('Extending vite config using user-specified function')\n config = await userConfig(config, env)\n } else if (typeof userConfig === 'object') {\n debug('Merging vite config using user-specified object')\n config = mergeConfig(config, userConfig)\n }\n\n return config\n}\n"],"names":["path","babel","findProjectRoot","getCliTelemetry","workbenchVitePlugins","viteReact","reactCompilerPreset","debug","esmExternalRequirePlugin","mergeConfig","SANITY_CACHE_DIR","sanitySchemaExtractionPlugin","VENDOR_DIR","createExternalFromImportMap","normalizeBasePath","sanityBuildEntries","sanityFaviconsPlugin","sanityRuntimeRewritePlugin","createVendorNamedExportsPlugin","getDefaultFaviconsPath","getViteConfig","options","additionalPlugins","autoUpdates","basePath","rawBasePath","cwd","entries","exposes","isApp","isWorkbenchApp","minify","mode","outputDir","reactCompiler","schemaExtraction","server","sourceMap","workbenchAppId","configPath","customFaviconsPath","join","defaultFaviconsPath","staticPath","envVars","getEnvironmentVariables","sharedPlugins","presets","enabled","additionalPatterns","watchPatterns","enforceRequiredFields","outputPath","telemetryLogger","workDir","workspaceName","workspace","viteConfig","base","build","outDir","resolve","sourcemap","cacheDir","configFile","define","__SANITY_BUILD_TIMESTAMP__","JSON","stringify","Date","now","__SANITY_STAGING__","process","env","SANITY_INTERNAL_ENV","PKG_BUILD_VERSION","envPrefix","logLevel","plugins","appId","staticUrlPath","dedupe","tsconfigPaths","root","host","port","strictPort","warmup","clientFiles","push","vendor","namesByChunkName","external","imports","Object","fromEntries","values","specifiersByChunkName","map","specifier","vendorChunkNames","Set","keys","assetsDir","emptyOutDir","rolldownOptions","input","sanity","onwarn","onRolldownWarn","experimental","nativeMagicString","output","entryFileNames","chunk","has","name","exports","preserveEntrySignatures","warning","warn","suppressUnusedImport","code","names","includes","filter","n","length","ids","every","id","finalizeViteConfig","config","defaultConfig","TypeError","Error","extendViteConfigWithUserConfig","userConfig"],"mappings":"AAAA,OAAOA,UAAU,YAAW;AAE5B,OAAOC,WAAW,yBAAwB;AAC1C,SAAQC,eAAe,QAAO,0BAAyB;AACvD,SAAQC,eAAe,QAAO,6BAA4B;AAE1D,SAA+BC,oBAAoB,QAAO,8BAA6B;AACvF,OAAOC,aAAYC,mBAAmB,QAAO,uBAAsB;AAEnE,OAAOC,WAAW,QAAO;AACzB,SAEEC,wBAAwB,EAExBC,WAAW,QAIN,OAAM;AAEb,SAAQC,gBAAgB,QAAO,qBAAoB;AACnD,SAAQC,4BAA4B,QAAO,6CAA4C;AAEvF,SAAQC,UAAU,QAAO,iBAAgB;AACzC,SAAQC,2BAA2B,QAAO,mCAAkC;AAC5E,SAAQC,iBAAiB,QAAO,yBAAwB;AACxD,SAAQC,kBAAkB,QAAO,wCAAuC;AACxE,SAAQC,oBAAoB,QAAO,mCAAkC;AACrE,SAAQC,0BAA0B,QAAO,0CAAyC;AAClF,SAAQC,8BAA8B,QAAO,+CAA8C;AAC3F,SAAQC,sBAAsB,QAAO,qBAAoB;AAsFzD;;;;CAIC,GACD,OAAO,eAAeC,cAAcC,OAAoB;IACtD,MAAM,EACJC,iBAAiB,EACjBC,WAAW,EACXC,UAAUC,cAAc,GAAG,EAC3BC,GAAG,EACHC,OAAO,EACPC,OAAO,EACPC,KAAK,EACLC,cAAc,EACdC,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