@sanity/cli-build 5.2.1 → 5.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/_exports/_internal/build.d.ts +2 -3
- package/dist/actions/build/buildApp.js +5 -4
- package/dist/actions/build/buildApp.js.map +1 -1
- package/dist/actions/build/buildStaticFiles.js.map +1 -1
- package/dist/actions/build/checkStudioDependencyVersions.js +2 -1
- package/dist/actions/build/checkStudioDependencyVersions.js.map +1 -1
- package/dist/actions/build/getViteConfig.js +35 -8
- package/dist/actions/build/getViteConfig.js.map +1 -1
- package/package.json +15 -10
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { CliConfig, Output, UserViteConfig } from "@sanity/cli-core/types";
|
|
2
2
|
import { WorkbenchExposes } from "@sanity/workbench-cli/build";
|
|
3
|
-
import { PluginOptions } from "babel-plugin-react-compiler";
|
|
4
3
|
import { ConfigEnv, InlineConfig, Plugin } from "vite";
|
|
5
4
|
import { FSWatcher } from "chokidar";
|
|
6
5
|
interface CompareDependencyVersions {
|
|
@@ -148,7 +147,7 @@ interface StaticBuildOptions {
|
|
|
148
147
|
isWorkbenchApp?: boolean;
|
|
149
148
|
minify?: boolean;
|
|
150
149
|
profile?: boolean;
|
|
151
|
-
reactCompiler?:
|
|
150
|
+
reactCompiler?: CliConfig['reactCompiler'];
|
|
152
151
|
schemaExtraction?: CliConfig['schemaExtraction'];
|
|
153
152
|
sourceMap?: boolean;
|
|
154
153
|
vite?: UserViteConfig;
|
|
@@ -271,7 +270,7 @@ interface ViteOptions {
|
|
|
271
270
|
* Mode to run vite in - eg development or production
|
|
272
271
|
*/
|
|
273
272
|
mode: 'development' | 'production';
|
|
274
|
-
reactCompiler:
|
|
273
|
+
reactCompiler: CliConfig['reactCompiler'];
|
|
275
274
|
/**
|
|
276
275
|
* Additional plugins when configured, eg. typegen
|
|
277
276
|
*/
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { rm } from 'node:fs/promises';
|
|
2
2
|
import path from 'node:path';
|
|
3
3
|
import { styleText } from 'node:util';
|
|
4
|
+
import { exitCodes } from '@sanity/cli-core/ExitCodes';
|
|
4
5
|
import { getLocalPackageVersion } from '@sanity/cli-core/package-manager';
|
|
5
6
|
import { getCliTelemetry } from '@sanity/cli-core/telemetry';
|
|
6
7
|
import { isInteractive } from '@sanity/cli-core/util';
|
|
@@ -29,7 +30,7 @@ import { resolveVendorBuildConfig } from './resolveVendorBuildConfig.js';
|
|
|
29
30
|
const installedSanityVersion = await getLocalPackageVersion('sanity', workDir);
|
|
30
31
|
if (!installedSdkVersion) {
|
|
31
32
|
output.error(`Failed to find installed @sanity/sdk-react version`, {
|
|
32
|
-
exit:
|
|
33
|
+
exit: exitCodes.RUNTIME_ERROR
|
|
33
34
|
});
|
|
34
35
|
return;
|
|
35
36
|
}
|
|
@@ -40,7 +41,7 @@ import { resolveVendorBuildConfig } from './resolveVendorBuildConfig.js';
|
|
|
40
41
|
const cleanSDKVersion = semverParse(installedSdkVersion)?.version;
|
|
41
42
|
if (!cleanSDKVersion) {
|
|
42
43
|
output.error(`Failed to parse installed SDK version: ${installedSdkVersion}`, {
|
|
43
|
-
exit:
|
|
44
|
+
exit: exitCodes.RUNTIME_ERROR
|
|
44
45
|
});
|
|
45
46
|
return;
|
|
46
47
|
}
|
|
@@ -95,7 +96,7 @@ import { resolveVendorBuildConfig } from './resolveVendorBuildConfig.js';
|
|
|
95
96
|
});
|
|
96
97
|
if (!shouldContinue) {
|
|
97
98
|
output.error('Declined to continue with build', {
|
|
98
|
-
exit:
|
|
99
|
+
exit: exitCodes.RUNTIME_ERROR
|
|
99
100
|
});
|
|
100
101
|
return;
|
|
101
102
|
}
|
|
@@ -183,7 +184,7 @@ import { resolveVendorBuildConfig } from './resolveVendorBuildConfig.js';
|
|
|
183
184
|
error
|
|
184
185
|
});
|
|
185
186
|
output.error(`Failed to build Sanity application: ${message}`, {
|
|
186
|
-
exit:
|
|
187
|
+
exit: exitCodes.RUNTIME_ERROR
|
|
187
188
|
});
|
|
188
189
|
}
|
|
189
190
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/actions/build/buildApp.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 {confirm, getTimer, logSymbols, spinner, type SpinnerInstance} from '@sanity/cli-core/ux'\nimport {type WorkbenchExposes} from '@sanity/workbench-cli/build'\nimport {parse as semverParse} from 'semver'\n\nimport {AppBuildTrace} 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 {BuildEventListener} from './eventListener.js'\nimport {getAutoUpdatesCssUrls, getAutoUpdatesImportMap} from './getAutoUpdatesImportMap.js'\nimport {getAppEnvironmentVariables} from './getEnvironmentVariables.js'\nimport {handlePrereleaseVersions} from './handlePrereleaseVersions.js'\nimport {resolveVendorBuildConfig} from './resolveVendorBuildConfig.js'\n\nexport type BuildAppEventListener = BuildEventListener\nexport interface BuildOptions {\n appId: string | undefined\n appTitle: string | undefined\n autoUpdatesEnabled: boolean\n checkAppId: () => void\n compareDependencyVersions: (\n packages: {name: string; version: string}[],\n ) => Promise<CompareDependencyVersionsResult>\n determineBasePath: () => string\n entry: string | undefined\n eventListener: Partial<BuildAppEventListener>\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 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 app that avoids depending on flags for CLI config.\n * @param options - options for the build\n */\nexport async function buildApp(options: BuildOptions): Promise<void> {\n buildDebug(`Building app`)\n\n const {appId, determineBasePath, eventListener, outDir, output, workDir} = options\n let {autoUpdatesEnabled} = options\n const unattendedMode = options.unattendedMode\n\n const timer = getTimer()\n\n const defaultOutputDir = path.resolve(path.join(workDir, 'dist'))\n const outputDir = path.resolve(outDir || defaultOutputDir)\n\n const installedSdkVersion = await getLocalPackageVersion('@sanity/sdk-react', workDir)\n const installedSanityVersion = await getLocalPackageVersion('sanity', workDir)\n\n if (!installedSdkVersion) {\n output.error(`Failed to find installed @sanity/sdk-react version`, {exit: 1})\n return\n }\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 cleanSDKVersion = semverParse(installedSdkVersion)?.version\n if (!cleanSDKVersion) {\n output.error(`Failed to parse installed SDK version: ${installedSdkVersion}`, {exit: 1})\n return\n }\n\n // Sanity might not be installed, but if it is, we want to auto update it.\n const cleanSanityVersion = semverParse(installedSanityVersion)?.version\n\n const autoUpdatedPackages = [\n {name: '@sanity/sdk', version: cleanSDKVersion},\n {name: '@sanity/sdk-react', version: cleanSDKVersion},\n ...(cleanSanityVersion\n ? [{cssFile: 'index.css', name: 'sanity' as const, version: cleanSanityVersion}]\n : []),\n ]\n autoUpdatesImports = getAutoUpdatesImportMap(autoUpdatedPackages, {appId})\n autoUpdatesCssUrls = getAutoUpdatesCssUrls(autoUpdatedPackages, {appId})\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 // Check the versions\n const {mismatched, unresolvedPrerelease} =\n await options.compareDependencyVersions(autoUpdatedPackages)\n\n if (unresolvedPrerelease.length > 0) {\n await handlePrereleaseVersions({\n onPreReleaseInInteractiveAutoUpdate: eventListener.onPreReleaseInInteractiveAutoUpdate,\n onPreReleaseInNonInteractiveAutoUpdate:\n eventListener.onPreReleaseInNonInteractiveAutoUpdate,\n unattendedMode,\n unresolvedPrerelease,\n })\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 shouldContinue = await confirm({\n default: false,\n message: styleText('yellow', `${versionMismatchWarning} \\n\\nContinue anyway?`),\n })\n\n if (!shouldContinue) {\n output.error('Declined to continue with build', {exit: 1})\n return\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(getAppEnvironmentVariables())\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) output.log(`- ${key}`)\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 const basePath = determineBasePath()\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(`Building Sanity application`).start()\n\n const trace = getCliTelemetry().trace(AppBuildTrace)\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: true}),\n }\n }\n\n try {\n timer.start('bundleStudio')\n\n const bundle = await buildStaticFiles({\n appTitle: options.appTitle,\n autoUpdates,\n basePath,\n cwd: workDir,\n entry: options.entry,\n exposes: options.exposes,\n isApp: true,\n isWorkbenchApp: options.isWorkbenchApp,\n minify: options.minify,\n outputDir,\n reactCompiler: options.reactCompiler,\n schemaExtraction: options.schemaExtraction,\n sourceMap: options.sourceMap,\n vite: options.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 application (${buildDuration.toFixed(0)}ms)`\n spin.succeed()\n\n if (options.stats) {\n output.log('\\nLargest module files:')\n output.log(formatModuleSizes(sortModulesBySize(bundle.chunks).slice(0, 15)))\n }\n\n trace.complete()\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 application`, {error})\n output.error(`Failed to build Sanity application: ${message}`, {exit: 1})\n }\n}\n"],"names":["rm","path","styleText","getLocalPackageVersion","getCliTelemetry","isInteractive","confirm","getTimer","logSymbols","spinner","parse","semverParse","AppBuildTrace","formatModuleSizes","sortModulesBySize","buildDebug","buildStaticFiles","getAutoUpdatesCssUrls","getAutoUpdatesImportMap","getAppEnvironmentVariables","handlePrereleaseVersions","resolveVendorBuildConfig","buildApp","options","appId","determineBasePath","eventListener","outDir","output","workDir","autoUpdatesEnabled","unattendedMode","timer","defaultOutputDir","resolve","join","outputDir","installedSdkVersion","installedSanityVersion","error","exit","autoUpdatesImports","autoUpdatesCssUrls","cleanSDKVersion","version","cleanSanityVersion","autoUpdatedPackages","name","cssFile","log","info","checkAppId","mismatched","unresolvedPrerelease","compareDependencyVersions","length","onPreReleaseInInteractiveAutoUpdate","onPreReleaseInNonInteractiveAutoUpdate","versionMismatchWarning","map","mod","pkg","installed","remote","shouldContinue","default","message","warn","envVarKeys","Object","keys","key","shouldClean","basePath","spin","start","force","recursive","cleanDuration","end","text","toFixed","succeed","trace","autoUpdates","isWorkbenchApp","cssUrls","imports","vendor","cwd","isApp","bundle","appTitle","entry","exposes","minify","reactCompiler","schemaExtraction","sourceMap","vite","workbenchAppId","outputSize","chunks","flatMap","chunk","modules","renderedLength","reduce","sum","n","buildDuration","stats","slice","complete","fail","Error","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,SAAQC,OAAO,EAAEC,QAAQ,EAAEC,UAAU,EAAEC,OAAO,QAA6B,sBAAqB;AAEhG,SAAQC,SAASC,WAAW,QAAO,SAAQ;AAE3C,SAAQC,aAAa,QAAO,qCAAoC;AAEhE,SAAQC,iBAAiB,EAAEC,iBAAiB,QAAO,kCAAiC;AACpF,SAAQC,UAAU,QAAO,kBAAiB;AAC1C,SAAQC,gBAAgB,QAAO,wBAAuB;AAEtD,SAAQC,qBAAqB,EAAEC,uBAAuB,QAAO,+BAA8B;AAC3F,SAAQC,0BAA0B,QAAO,+BAA8B;AACvE,SAAQC,wBAAwB,QAAO,gCAA+B;AACtE,SAAQC,wBAAwB,QAAO,gCAA+B;AAgCtE;;;CAGC,GACD,OAAO,eAAeC,SAASC,OAAqB;IAClDR,WAAW,CAAC,YAAY,CAAC;IAEzB,MAAM,EAACS,KAAK,EAAEC,iBAAiB,EAAEC,aAAa,EAAEC,MAAM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QAAQ6E,cAAc;QACxC;QAEAjB,MAAMlC,GAAG,CAAC;YACRoD,YAAYV,OAAOW,MAAM,CACtBC,OAAO,CAAC,CAACC,QAAUA,MAAMC,OAAO,CAACF,OAAO,CAAC,CAAC3C,MAAQA,IAAI8C,cAAc,GACpEC,MAAM,CAAC,CAACC,KAAKC,IAAMD,MAAMC,GAAG;QACjC;QACA,MAAMC,gBAAgB9E,MAAM+C,GAAG,CAAC;QAEhCL,KAAKM,IAAI,GAAG,CAAC,0BAA0B,EAAE8B,cAAc7B,OAAO,CAAC,GAAG,GAAG,CAAC;QACtEP,KAAKQ,OAAO;QAEZ,IAAI3D,QAAQwF,KAAK,EAAE;YACjBnF,OAAOqB,GAAG,CAAC;YACXrB,OAAOqB,GAAG,CAACpC,kBAAkBC,kBAAkB6E,OAAOW,MAAM,EAAEU,KAAK,CAAC,GAAG;QACzE;QAEA7B,MAAM8B,QAAQ;IAChB,EAAE,OAAO1E,OAAO;QACdmC,KAAKwC,IAAI;QACT/B,MAAM5C,KAAK,CAACA;QACZ,MAAM2B,UAAU3B,iBAAiB4E,QAAQ5E,MAAM2B,OAAO,GAAGkD,OAAO7E;QAChExB,WAAW,CAAC,kCAAkC,CAAC,EAAE;YAACwB;QAAK;QACvDX,OAAOW,KAAK,CAAC,CAAC,oCAAoC,EAAE2B,SAAS,EAAE;YAAC1B,MAAM;QAAC;IACzE;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/build/buildApp.ts"],"sourcesContent":["import {rm} from 'node:fs/promises'\nimport path from 'node:path'\nimport {styleText} from 'node:util'\n\nimport {exitCodes} from '@sanity/cli-core/ExitCodes'\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 {confirm, getTimer, logSymbols, spinner, type SpinnerInstance} from '@sanity/cli-core/ux'\nimport {type WorkbenchExposes} from '@sanity/workbench-cli/build'\nimport {parse as semverParse} from 'semver'\n\nimport {AppBuildTrace} 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 {BuildEventListener} from './eventListener.js'\nimport {getAutoUpdatesCssUrls, getAutoUpdatesImportMap} from './getAutoUpdatesImportMap.js'\nimport {getAppEnvironmentVariables} from './getEnvironmentVariables.js'\nimport {handlePrereleaseVersions} from './handlePrereleaseVersions.js'\nimport {resolveVendorBuildConfig} from './resolveVendorBuildConfig.js'\n\nexport type BuildAppEventListener = BuildEventListener\nexport interface BuildOptions {\n appId: string | undefined\n appTitle: string | undefined\n autoUpdatesEnabled: boolean\n checkAppId: () => void\n compareDependencyVersions: (\n packages: {name: string; version: string}[],\n ) => Promise<CompareDependencyVersionsResult>\n determineBasePath: () => string\n entry: string | undefined\n eventListener: Partial<BuildAppEventListener>\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 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 app that avoids depending on flags for CLI config.\n * @param options - options for the build\n */\nexport async function buildApp(options: BuildOptions): Promise<void> {\n buildDebug(`Building app`)\n\n const {appId, determineBasePath, eventListener, outDir, output, workDir} = options\n let {autoUpdatesEnabled} = options\n const unattendedMode = options.unattendedMode\n\n const timer = getTimer()\n\n const defaultOutputDir = path.resolve(path.join(workDir, 'dist'))\n const outputDir = path.resolve(outDir || defaultOutputDir)\n\n const installedSdkVersion = await getLocalPackageVersion('@sanity/sdk-react', workDir)\n const installedSanityVersion = await getLocalPackageVersion('sanity', workDir)\n\n if (!installedSdkVersion) {\n output.error(`Failed to find installed @sanity/sdk-react version`, {\n exit: exitCodes.RUNTIME_ERROR,\n })\n return\n }\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 cleanSDKVersion = semverParse(installedSdkVersion)?.version\n if (!cleanSDKVersion) {\n output.error(`Failed to parse installed SDK version: ${installedSdkVersion}`, {\n exit: exitCodes.RUNTIME_ERROR,\n })\n return\n }\n\n // Sanity might not be installed, but if it is, we want to auto update it.\n const cleanSanityVersion = semverParse(installedSanityVersion)?.version\n\n const autoUpdatedPackages = [\n {name: '@sanity/sdk', version: cleanSDKVersion},\n {name: '@sanity/sdk-react', version: cleanSDKVersion},\n ...(cleanSanityVersion\n ? [{cssFile: 'index.css', name: 'sanity' as const, version: cleanSanityVersion}]\n : []),\n ]\n autoUpdatesImports = getAutoUpdatesImportMap(autoUpdatedPackages, {appId})\n autoUpdatesCssUrls = getAutoUpdatesCssUrls(autoUpdatedPackages, {appId})\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 // Check the versions\n const {mismatched, unresolvedPrerelease} =\n await options.compareDependencyVersions(autoUpdatedPackages)\n\n if (unresolvedPrerelease.length > 0) {\n await handlePrereleaseVersions({\n onPreReleaseInInteractiveAutoUpdate: eventListener.onPreReleaseInInteractiveAutoUpdate,\n onPreReleaseInNonInteractiveAutoUpdate:\n eventListener.onPreReleaseInNonInteractiveAutoUpdate,\n unattendedMode,\n unresolvedPrerelease,\n })\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 shouldContinue = await confirm({\n default: false,\n message: styleText('yellow', `${versionMismatchWarning} \\n\\nContinue anyway?`),\n })\n\n if (!shouldContinue) {\n output.error('Declined to continue with build', {exit: exitCodes.RUNTIME_ERROR})\n return\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(getAppEnvironmentVariables())\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) output.log(`- ${key}`)\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 const basePath = determineBasePath()\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(`Building Sanity application`).start()\n\n const trace = getCliTelemetry().trace(AppBuildTrace)\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: true}),\n }\n }\n\n try {\n timer.start('bundleStudio')\n\n const bundle = await buildStaticFiles({\n appTitle: options.appTitle,\n autoUpdates,\n basePath,\n cwd: workDir,\n entry: options.entry,\n exposes: options.exposes,\n isApp: true,\n isWorkbenchApp: options.isWorkbenchApp,\n minify: options.minify,\n outputDir,\n reactCompiler: options.reactCompiler,\n schemaExtraction: options.schemaExtraction,\n sourceMap: options.sourceMap,\n vite: options.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 application (${buildDuration.toFixed(0)}ms)`\n spin.succeed()\n\n if (options.stats) {\n output.log('\\nLargest module files:')\n output.log(formatModuleSizes(sortModulesBySize(bundle.chunks).slice(0, 15)))\n }\n\n trace.complete()\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 application`, {error})\n output.error(`Failed to build Sanity application: ${message}`, {exit: exitCodes.RUNTIME_ERROR})\n }\n}\n"],"names":["rm","path","styleText","exitCodes","getLocalPackageVersion","getCliTelemetry","isInteractive","confirm","getTimer","logSymbols","spinner","parse","semverParse","AppBuildTrace","formatModuleSizes","sortModulesBySize","buildDebug","buildStaticFiles","getAutoUpdatesCssUrls","getAutoUpdatesImportMap","getAppEnvironmentVariables","handlePrereleaseVersions","resolveVendorBuildConfig","buildApp","options","appId","determineBasePath","eventListener","outDir","output","workDir","autoUpdatesEnabled","unattendedMode","timer","defaultOutputDir","resolve","join","outputDir","installedSdkVersion","installedSanityVersion","error","exit","RUNTIME_ERROR","autoUpdatesImports","autoUpdatesCssUrls","cleanSDKVersion","version","cleanSanityVersion","autoUpdatedPackages","name","cssFile","log","info","checkAppId","mismatched","unresolvedPrerelease","compareDependencyVersions","length","onPreReleaseInInteractiveAutoUpdate","onPreReleaseInNonInteractiveAutoUpdate","versionMismatchWarning","map","mod","pkg","installed","remote","shouldContinue","default","message","warn","envVarKeys","Object","keys","key","shouldClean","basePath","spin","start","force","recursive","cleanDuration","end","text","toFixed","succeed","trace","autoUpdates","isWorkbenchApp","cssUrls","imports","vendor","cwd","isApp","bundle","appTitle","entry","exposes","minify","reactCompiler","schemaExtraction","sourceMap","vite","workbenchAppId","outputSize","chunks","flatMap","chunk","modules","renderedLength","reduce","sum","n","buildDuration","stats","slice","complete","fail","Error","String"],"mappings":"AAAA,SAAQA,EAAE,QAAO,mBAAkB;AACnC,OAAOC,UAAU,YAAW;AAC5B,SAAQC,SAAS,QAAO,YAAW;AAEnC,SAAQC,SAAS,QAAO,6BAA4B;AACpD,SAAQC,sBAAsB,QAAO,mCAAkC;AACvE,SAAQC,eAAe,QAAO,6BAA4B;AAE1D,SAAQC,aAAa,QAAO,wBAAuB;AACnD,SAAQC,OAAO,EAAEC,QAAQ,EAAEC,UAAU,EAAEC,OAAO,QAA6B,sBAAqB;AAEhG,SAAQC,SAASC,WAAW,QAAO,SAAQ;AAE3C,SAAQC,aAAa,QAAO,qCAAoC;AAEhE,SAAQC,iBAAiB,EAAEC,iBAAiB,QAAO,kCAAiC;AACpF,SAAQC,UAAU,QAAO,kBAAiB;AAC1C,SAAQC,gBAAgB,QAAO,wBAAuB;AAEtD,SAAQC,qBAAqB,EAAEC,uBAAuB,QAAO,+BAA8B;AAC3F,SAAQC,0BAA0B,QAAO,+BAA8B;AACvE,SAAQC,wBAAwB,QAAO,gCAA+B;AACtE,SAAQC,wBAAwB,QAAO,gCAA+B;AAgCtE;;;CAGC,GACD,OAAO,eAAeC,SAASC,OAAqB;IAClDR,WAAW,CAAC,YAAY,CAAC;IAEzB,MAAM,EAACS,KAAK,EAAEC,iBAAiB,EAAEC,aAAa,EAAEC,MAAM,EAAEC,MAAM,EAAEC,OAAO,EAAC,GAAGN;IAC3E,IAAI,EAACO,kBAAkB,EAAC,GAAGP;IAC3B,MAAMQ,iBAAiBR,QAAQQ,cAAc;IAE7C,MAAMC,QAAQzB;IAEd,MAAM0B,mBAAmBjC,KAAKkC,OAAO,CAAClC,KAAKmC,IAAI,CAACN,SAAS;IACzD,MAAMO,YAAYpC,KAAKkC,OAAO,CAACP,UAAUM;IAEz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,GAAG;QACjC;QACA,MAAMC,gBAAgB/E,MAAMgD,GAAG,CAAC;QAEhCL,KAAKM,IAAI,GAAG,CAAC,0BAA0B,EAAE8B,cAAc7B,OAAO,CAAC,GAAG,GAAG,CAAC;QACtEP,KAAKQ,OAAO;QAEZ,IAAI5D,QAAQyF,KAAK,EAAE;YACjBpF,OAAOsB,GAAG,CAAC;YACXtB,OAAOsB,GAAG,CAACrC,kBAAkBC,kBAAkB8E,OAAOW,MAAM,EAAEU,KAAK,CAAC,GAAG;QACzE;QAEA7B,MAAM8B,QAAQ;IAChB,EAAE,OAAO3E,OAAO;QACdoC,KAAKwC,IAAI;QACT/B,MAAM7C,KAAK,CAACA;QACZ,MAAM4B,UAAU5B,iBAAiB6E,QAAQ7E,MAAM4B,OAAO,GAAGkD,OAAO9E;QAChExB,WAAW,CAAC,kCAAkC,CAAC,EAAE;YAACwB;QAAK;QACvDX,OAAOW,KAAK,CAAC,CAAC,oCAAoC,EAAE4B,SAAS,EAAE;YAAC3B,MAAMtC,UAAUuC,aAAa;QAAA;IAC/F;AACF"}
|
|
@@ -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/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?: boolean | 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 // A workbench remote can also serve itself standalone. When\n // `SANITY_INTERNAL_IS_WORKBENCH_REMOTE` is set, emit an SPA (index.html +\n // bootstrap + favicons) into the same `dist` as the federation output via a\n // dedicated `client` environment (see plugin-sanity-environment). Skipped for\n // a dock-only app (no `./App` to mount), matching `exposesApp` in plugin.ts.\n const emitSpa = process.env.SANITY_INTERNAL_IS_WORKBENCH_REMOTE === 'true' && !(isApp && !entry)\n\n let entries: Awaited<ReturnType<typeof resolveEntries>>\n if (emitSpa) {\n buildDebug('Writing Sanity runtime files (workbench remote SPA)')\n ;({entries} = await writeSanityRuntime({\n appTitle,\n basePath,\n cwd,\n entry,\n isApp,\n isWorkbenchApp,\n reactStrictMode: false,\n watch: false,\n }))\n } else {\n buildDebug('Resolving entries for federation build')\n entries = await resolveEntries({cwd, entry, isApp, isWorkbenchApp})\n }\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 if (emitSpa) {\n const fromPath = path.join(cwd, 'static')\n const staticPath = path.join(outputDir, 'static')\n buildDebug(`Copying static files from ${fromPath} to output dir`)\n await copyDir(fromPath, staticPath)\n buildDebug('Writing favicons to output dir')\n const faviconBasePath = `${basePath.replace(/\\/+$/, '')}/static`\n await writeFavicons(faviconBasePath, staticPath)\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","emitSpa","process","env","SANITY_INTERNAL_IS_WORKBENCH_REMOTE","entries","reactStrictMode","watch","viteConfig","getEnvironmentVariables","command","fromPath","join","staticPath","faviconBasePath","replace","builder","buildApp","chunks","jsonEncode","prefix","defaultViteConfig","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;AAkC1E;;;;CAIC,GACD,OAAO,eAAeC,iBACpBC,OAA2B;IAE3B,MAAM,EACJC,QAAQ,EACRC,WAAW,EACXC,QAAQ,EACRC,GAAG,EACHC,KAAK,EACLC,OAAO,EACPC,KAAK,EACLC,cAAc,EACdC,SAAS,IAAI,EACbC,SAAS,EACTC,aAAa,EACbC,gBAAgB,EAChBC,YAAY,KAAK,EACjBC,MAAMC,gBAAgB,EACtBC,cAAc,EACf,GAAGhB;IAEJ,MAAMiB,OAAO;IAEb;;;GAGC,GACD,IAAIT,gBAAgB;QAClB,4DAA4D;QAC5D,0EAA0E;QAC1E,4EAA4E;QAC5E,8EAA8E;QAC9E,6EAA6E;QAC7E,MAAMU,UAAUC,QAAQC,GAAG,CAACC,mCAAmC,KAAK,UAAU,CAAEd,CAAAA,SAAS,CAACF,KAAI;QAE9F,IAAIiB;QACJ,IAAIJ,SAAS;YACX5B,WAAW;YACT,CAAA,EAACgC,OAAO,EAAC,GAAG,MAAMxB,mBAAmB;gBACrCG;gBACAE;gBACAC;gBACAC;gBACAE;gBACAC;gBACAe,iBAAiB;gBACjBC,OAAO;YACT,EAAC;QACH,OAAO;Y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5C;YACF;YACAH,MAAMb,MAAMa,IAAI;QAClB;IACF;IAEA,OAAO;QAACrB,QAAQO;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 {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?: CliConfig['reactCompiler']\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 // A workbench remote can also serve itself standalone. When\n // `SANITY_INTERNAL_IS_WORKBENCH_REMOTE` is set, emit an SPA (index.html +\n // bootstrap + favicons) into the same `dist` as the federation output via a\n // dedicated `client` environment (see plugin-sanity-environment). Skipped for\n // a dock-only app (no `./App` to mount), matching `exposesApp` in plugin.ts.\n const emitSpa = process.env.SANITY_INTERNAL_IS_WORKBENCH_REMOTE === 'true' && !(isApp && !entry)\n\n let entries: Awaited<ReturnType<typeof resolveEntries>>\n if (emitSpa) {\n buildDebug('Writing Sanity runtime files (workbench remote SPA)')\n ;({entries} = await writeSanityRuntime({\n appTitle,\n basePath,\n cwd,\n entry,\n isApp,\n isWorkbenchApp,\n reactStrictMode: false,\n watch: false,\n }))\n } else {\n buildDebug('Resolving entries for federation build')\n entries = await resolveEntries({cwd, entry, isApp, isWorkbenchApp})\n }\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 if (emitSpa) {\n const fromPath = path.join(cwd, 'static')\n const staticPath = path.join(outputDir, 'static')\n buildDebug(`Copying static files from ${fromPath} to output dir`)\n await copyDir(fromPath, staticPath)\n buildDebug('Writing favicons to output dir')\n const faviconBasePath = `${basePath.replace(/\\/+$/, '')}/static`\n await writeFavicons(faviconBasePath, staticPath)\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","emitSpa","process","env","SANITY_INTERNAL_IS_WORKBENCH_REMOTE","entries","reactStrictMode","watch","viteConfig","getEnvironmentVariables","command","fromPath","join","staticPath","faviconBasePath","replace","builder","buildApp","chunks","jsonEncode","prefix","defaultViteConfig","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;AAI5B,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;AAkC1E;;;;CAIC,GACD,OAAO,eAAeC,iBACpBC,OAA2B;IAE3B,MAAM,EACJC,QAAQ,EACRC,WAAW,EACXC,QAAQ,EACRC,GAAG,EACHC,KAAK,EACLC,O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AiF;IACjF,IAAIkD,MAAMC,OAAO,CAACF,WAAW,CAAE,CAAA,YAAYA,MAAK,GAAI;QAClD,OAAO;YAACJ,QAAQ,EAAE;QAAA;IACpB;IAEA,MAAMO,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,MAAMtE,KAAKuE,UAAU,CAACL,YAAYlE,KAAKwE,QAAQ,CAACtD,KAAKgD,YAAYA;oBACjEO,gBAAgBR,YAAYQ,cAAc;gBAC5C;YACF;YACAH,MAAMb,MAAMa,IAAI;QAClB;IACF;IAEA,OAAO;QAACrB,QAAQO;IAAK;AACvB"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import path from 'node:path';
|
|
2
|
+
import { exitCodes } from '@sanity/cli-core/ExitCodes';
|
|
2
3
|
import { getLocalPackageVersion, readPackageJson } from '@sanity/cli-core/package-manager';
|
|
3
4
|
import { coerce, gtr, ltr, rcompare, satisfies } from 'semver';
|
|
4
5
|
// NOTE: when doing changes here, also remember to update versions in help docs at
|
|
@@ -104,7 +105,7 @@ You _may_ encounter bugs while using these versions.
|
|
|
104
105
|
|
|
105
106
|
${getUpgradeInstructions(unsupported)}
|
|
106
107
|
`, {
|
|
107
|
-
exit:
|
|
108
|
+
exit: exitCodes.RUNTIME_ERROR
|
|
108
109
|
});
|
|
109
110
|
}
|
|
110
111
|
}
|
|
@@ -1 +1 @@
|
|
|
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', '^4']},\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
|
+
{"version":3,"sources":["../../../src/actions/build/checkStudioDependencyVersions.ts"],"sourcesContent":["import path from 'node:path'\n\nimport {exitCodes} from '@sanity/cli-core/ExitCodes'\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', '^4']},\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: exitCodes.RUNTIME_ERROR},\n )\n }\n}\n\nfunction listPackages(pkgs: PackageInfo[]) {\n return pkgs\n .map((pkg) => {\n const want =\n pkg.isDeprecated && !pkg.isUnsupported && !pkg.isUntested\n ? pkg.deprecatedBelow\n : pkg.supported.join(' || ')\n\n return `${pkg.name} (installed: ${pkg.installed}, want: ${want})`\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","exitCodes","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","RUNTIME_ERROR","pkgs","want","inst","highestSupported","version","toSorted"],"mappings":"AAAA,OAAOA,UAAU,YAAW;AAE5B,SAAQC,SAAS,QAAO,6BAA4B;AACpD,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;YAAM;SAAK;IAAA;CAC1E;AAED,OAAO,eAAeC,8BACpBC,OAAe,EACfC,MAAc,EACd,EAACC,WAAWP,gBAAgB,EAAgC,GAAG,CAAC,CAAC;IAEjE,MAAMQ,WAAW,MAAMd,gBAAgBH,KAAKkB,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,CAAC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GAAG,CAAC,CAAC6B,UAAY,AAAChD,CAAAA,OAAOgD,YAAY;gBAACA,SAAS;YAAE,CAAA,EAAGA,OAAO,EAC3DC,QAAQ,CAAC9C;QAEZ,OAAO,CAAC,CAAC,EAAEiB,IAAIb,IAAI,CAAC,EAAE,EAAEwC,iBAAiB,CAAC,CAAC;IAC7C,GACCjC,IAAI,CAAC;IAER,OAAO,CAAC;;WAEC,EAAEgC,KAAK;;;;cAIJ,EAAEA,KAAK;;;;eAIN,EAAEA,MAAM;AACvB"}
|
|
@@ -31,14 +31,7 @@ import { getDefaultFaviconsPath } from './writeFavicons.js';
|
|
|
31
31
|
const staticPath = `${basePath}static`;
|
|
32
32
|
const envVars = options.getEnvironmentVariables();
|
|
33
33
|
const sharedPlugins = [
|
|
34
|
-
|
|
35
|
-
...reactCompiler ? [
|
|
36
|
-
babel({
|
|
37
|
-
presets: [
|
|
38
|
-
reactCompilerPreset(reactCompiler === true ? {} : reactCompiler)
|
|
39
|
-
]
|
|
40
|
-
})
|
|
41
|
-
] : [],
|
|
34
|
+
...getReactPlugins(reactCompiler),
|
|
42
35
|
...schemaExtraction?.enabled ? [
|
|
43
36
|
sanitySchemaExtractionPlugin({
|
|
44
37
|
additionalPatterns: schemaExtraction.watchPatterns,
|
|
@@ -233,6 +226,40 @@ import { getDefaultFaviconsPath } from './writeFavicons.js';
|
|
|
233
226
|
}
|
|
234
227
|
return viteConfig;
|
|
235
228
|
}
|
|
229
|
+
/**
|
|
230
|
+
* The React plugin(s) for the given `reactCompiler` configuration.
|
|
231
|
+
*
|
|
232
|
+
* With the (default) babel transform the compiler runs as a babel preset
|
|
233
|
+
* next to a plain `viteReact()`. With the experimental oxc transform,
|
|
234
|
+
* `viteReact`'s `compiler` option lets `oxc-transform-react` own the React
|
|
235
|
+
* Compiler, TypeScript/JSX and Fast Refresh transforms in one pass. The
|
|
236
|
+
* `transform` discriminator is stripped so neither compiler receives an
|
|
237
|
+
* option it does not know.
|
|
238
|
+
*/ function getReactPlugins(reactCompiler) {
|
|
239
|
+
const config = reactCompiler === true ? {} : reactCompiler || undefined;
|
|
240
|
+
if (!config) {
|
|
241
|
+
return [
|
|
242
|
+
viteReact()
|
|
243
|
+
];
|
|
244
|
+
}
|
|
245
|
+
if (config.transform === 'oxc') {
|
|
246
|
+
const { transform, ...compilerOptions } = config;
|
|
247
|
+
return [
|
|
248
|
+
viteReact({
|
|
249
|
+
compiler: compilerOptions
|
|
250
|
+
})
|
|
251
|
+
];
|
|
252
|
+
}
|
|
253
|
+
const { transform, ...compilerOptions } = config;
|
|
254
|
+
return [
|
|
255
|
+
viteReact(),
|
|
256
|
+
babel({
|
|
257
|
+
presets: [
|
|
258
|
+
reactCompilerPreset(compilerOptions)
|
|
259
|
+
]
|
|
260
|
+
})
|
|
261
|
+
];
|
|
262
|
+
}
|
|
236
263
|
function onRolldownWarn(warning, warn) {
|
|
237
264
|
if (suppressUnusedImport(warning)) {
|
|
238
265
|
return;
|
|
@@ -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 {findProjectRoot} from '@sanity/cli-core/config'\nimport {getCliTelemetry} from '@sanity/cli-core/telemetry'\nimport {type CliConfig, type UserViteConfig} from '@sanity/cli-core/types'\nimport {isStaging} from '@sanity/cli-core/util'\nimport {\n type WorkbenchExposes,\n workbenchOptimizeDeps,\n workbenchVitePlugins,\n} from '@sanity/workbench-cli/build'\nimport viteReact, {reactCompilerPreset} from '@vitejs/plugin-react'\nimport {type PluginOptions as ReactCompilerConfig} from 'babel-plugin-react-compiler'\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 {buildDebug} from './buildDebug.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: boolean | 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\n ? [babel({presets: [reactCompilerPreset(reactCompiler === true ? {} : reactCompiler)]})]\n : []),\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__: isStaging(),\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 skip the serve-only client plugins (favicons, runtime\n // rewrite) — they no-op at build. `sanityBuildEntries` is scoped to the\n // `client` environment so it emits the standalone SPA `index.html`\n // (bridge-free) when the workbench remote SPA is enabled, and no-ops in the\n // federation env / when no client env exists (see plugin-sanity-environment).\n ...(isWorkbenchApp\n ? [\n ...sharedPlugins,\n await workbenchVitePlugins({appId: workbenchAppId, cwd, entries, exposes, isApp}),\n {\n ...sanityBuildEntries({basePath, bridge: false, cwd, isApp}),\n applyToEnvironment: (env) => env.name === 'client',\n } satisfies Plugin,\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 // Front-load the deps the federation `exposes` reach only via the host's\n // dynamic imports, which Vite's dep scanner (crawling from the HTML entry)\n // otherwise misses — see `workbenchOptimizeDeps`. Dev-server only; Vite\n // ignores `optimizeDeps` at build. Set before the userland `vite` hook so an\n // app can still extend the list.\n if (isWorkbenchApp && mode === 'development') {\n const runtimeDir = path.join(cwd, '.sanity', 'runtime')\n const appSources = [entries.relativeEntry, entries.relativeConfigLocation]\n .filter((relativePath): relativePath is string => relativePath !== null)\n .map((relativePath) => path.resolve(runtimeDir, relativePath))\n viteConfig.optimizeDeps = workbenchOptimizeDeps({appSources, cwd, exposes})\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 buildDebug('Extending vite config using user-specified function')\n config = await userConfig(config, env)\n } else if (typeof userConfig === 'object') {\n buildDebug('Merging vite config using user-specified object')\n config = mergeConfig(config, userConfig)\n }\n\n return config\n}\n"],"names":["path","babel","findProjectRoot","getCliTelemetry","isStaging","workbenchOptimizeDeps","workbenchVitePlugins","viteReact","reactCompilerPreset","esmExternalRequirePlugin","mergeConfig","SANITY_CACHE_DIR","sanitySchemaExtractionPlugin","buildDebug","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","PKG_BUILD_VERSION","envPrefix","logLevel","plugins","appId","bridge","applyToEnvironment","name","staticUrlPath","dedupe","tsconfigPaths","root","host","port","strictPort","warmup","clientFiles","runtimeDir","appSources","relativeEntry","relativeConfigLocation","filter","relativePath","map","optimizeDeps","push","vendor","namesByChunkName","external","imports","Object","fromEntries","values","specifiersByChunkName","specifier","vendorChunkNames","Set","keys","assetsDir","emptyOutDir","rolldownOptions","input","sanity","onwarn","onRolldownWarn","experimental","nativeMagicString","output","entryFileNames","chunk","has","exports","preserveEntrySignatures","warning","warn","suppressUnusedImport","code","names","includes","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,SAAQC,SAAS,QAAO,wBAAuB;AAC/C,SAEEC,qBAAqB,EACrBC,oBAAoB,QACf,8BAA6B;AACpC,OAAOC,aAAYC,mBAAmB,QAAO,uBAAsB;AAEnE,SAEEC,wBAAwB,EAExBC,WAAW,QAIN,OAAM;AAEb,SAAQC,gBAAgB,QAAO,qBAAoB;AACnD,SAAQC,4BAA4B,QAAO,6CAA4C;AAEvF,SAAQC,UAAU,QAAO,kBAAiB;AAC1C,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,MAAM,EACNC,IAAI,EACJC,SAAS,EACTC,aAAa,EACbC,gBAAgB,EAChBC,MAAM,EACN,4CAA4C;IAC5CC,YAAYhB,QAAQW,IAAI,KAAK,aAAa,EAC1CM,cAAc,EACf,GAAGjB;IAEJ,MAAMG,WAAWV,kBAAkBW;IAEnC,MAAMc,aAAa,AAAC,CAAA,MAAMvC,gBAAgB0B,IAAG,EA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AOuE,eAAe,UAAU;QACzCrI,WAAW;QACXgI,SAASnI,YAAYmI,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 ReactCompilerConfig, type UserViteConfig} from '@sanity/cli-core/types'\nimport {isStaging} from '@sanity/cli-core/util'\nimport {\n type WorkbenchExposes,\n workbenchOptimizeDeps,\n workbenchVitePlugins,\n} from '@sanity/workbench-cli/build'\nimport viteReact, {reactCompilerPreset} from '@vitejs/plugin-react'\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 {buildDebug} from './buildDebug.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: CliConfig['reactCompiler']\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 ...getReactPlugins(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__: isStaging(),\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 skip the serve-only client plugins (favicons, runtime\n // rewrite) — they no-op at build. `sanityBuildEntries` is scoped to the\n // `client` environment so it emits the standalone SPA `index.html`\n // (bridge-free) when the workbench remote SPA is enabled, and no-ops in the\n // federation env / when no client env exists (see plugin-sanity-environment).\n ...(isWorkbenchApp\n ? [\n ...sharedPlugins,\n await workbenchVitePlugins({appId: workbenchAppId, cwd, entries, exposes, isApp}),\n {\n ...sanityBuildEntries({basePath, bridge: false, cwd, isApp}),\n applyToEnvironment: (env) => env.name === 'client',\n } satisfies Plugin,\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 // Front-load the deps the federation `exposes` reach only via the host's\n // dynamic imports, which Vite's dep scanner (crawling from the HTML entry)\n // otherwise misses — see `workbenchOptimizeDeps`. Dev-server only; Vite\n // ignores `optimizeDeps` at build. Set before the userland `vite` hook so an\n // app can still extend the list.\n if (isWorkbenchApp && mode === 'development') {\n const runtimeDir = path.join(cwd, '.sanity', 'runtime')\n const appSources = [entries.relativeEntry, entries.relativeConfigLocation]\n .filter((relativePath): relativePath is string => relativePath !== null)\n .map((relativePath) => path.resolve(runtimeDir, relativePath))\n viteConfig.optimizeDeps = workbenchOptimizeDeps({appSources, cwd, exposes})\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\n/**\n * The React plugin(s) for the given `reactCompiler` configuration.\n *\n * With the (default) babel transform the compiler runs as a babel preset\n * next to a plain `viteReact()`. With the experimental oxc transform,\n * `viteReact`'s `compiler` option lets `oxc-transform-react` own the React\n * Compiler, TypeScript/JSX and Fast Refresh transforms in one pass. The\n * `transform` discriminator is stripped so neither compiler receives an\n * option it does not know.\n */\nfunction getReactPlugins(reactCompiler: CliConfig['reactCompiler']): PluginOption[] {\n const config: ReactCompilerConfig | undefined =\n reactCompiler === true ? {} : reactCompiler || undefined\n\n if (!config) {\n return [viteReact()]\n }\n\n if (config.transform === 'oxc') {\n const {transform, ...compilerOptions} = config\n return [viteReact({compiler: compilerOptions})]\n }\n\n const {transform, ...compilerOptions} = config\n return [viteReact(), babel({presets: [reactCompilerPreset(compilerOptions)]})]\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 buildDebug('Extending vite config using user-specified function')\n config = await userConfig(config, env)\n } else if (typeof userConfig === 'object') {\n buildDebug('Merging vite config using user-specified object')\n config = mergeConfig(config, userConfig)\n }\n\n return config\n}\n"],"names":["path","babel","findProjectRoot","getCliTelemetry","isStaging","workbenchOptimizeDeps","workbenchVitePlugins","viteReact","reactCompilerPreset","esmExternalRequirePlugin","mergeConfig","SANITY_CACHE_DIR","sanitySchemaExtractionPlugin","buildDebug","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","getReactPlugins","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","PKG_BUILD_VERSION","envPrefix","logLevel","plugins","appId","bridge","applyToEnvironment","name","staticUrlPath","dedupe","tsconfigPaths","root","host","port","strictPort","warmup","clientFiles","runtimeDir","appSources","relativeEntry","relativeConfigLocation","filter","relativePath","map","optimizeDeps","push","vendor","namesByChunkName","external","imports","Object","fromEntries","values","specifiersByChunkName","specifier","vendorChunkNames","Set","keys","assetsDir","emptyOutDir","rolldownOptions","input","sanity","onwarn","onRolldownWarn","experimental","nativeMagicString","output","entryFileNames","chunk","has","exports","preserveEntrySignatures","config","undefined","transform","compilerOptions","compiler","presets","warning","warn","suppressUnusedImport","code","names","includes","n","length","ids","every","id","finalizeViteConfig","defaultConfig","TypeError","Error","extendViteConfigWithUserConf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,iBAAiB+B,cAActF,KAAK,EAAEuD,mBAAmB,CAAC;QAC5D;IACF;AACF;AAEA;;;;;;;CAOC,GACD,OAAO,eAAekC,+BACpB3E,GAAc,EACdwE,aAA2B,EAC3BI,UAA0B;IAE1B,IAAItB,SAASkB;IAEb,IAAI,OAAOI,eAAe,YAAY;QACpC1I,WAAW;QACXoH,SAAS,MAAMsB,WAAWtB,QAAQtD;IACpC,OAAO,IAAI,OAAO4E,eAAe,UAAU;QACzC1I,WAAW;QACXoH,SAASvH,YAAYuH,QAAQsB;IAC/B;IAEA,OAAOtB;AACT"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sanity/cli-build",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.3.0",
|
|
4
4
|
"description": "Internal Sanity package for building studios and apps",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cli",
|
|
@@ -52,7 +52,7 @@
|
|
|
52
52
|
"@sanity/schema": "^6.7.0",
|
|
53
53
|
"@sanity/telemetry": "^1.1.0",
|
|
54
54
|
"@sanity/types": "^6.7.0",
|
|
55
|
-
"@vitejs/plugin-react": "^6.0
|
|
55
|
+
"@vitejs/plugin-react": "^6.1.0",
|
|
56
56
|
"chokidar": "^5.0.0",
|
|
57
57
|
"cjs-module-lexer": "^2.2.0",
|
|
58
58
|
"empathic": "^2.0.1",
|
|
@@ -65,12 +65,12 @@
|
|
|
65
65
|
"semver": "^7.8.1",
|
|
66
66
|
"vite": "^8.2.1",
|
|
67
67
|
"zod": "^4.4.3",
|
|
68
|
-
"@sanity/cli-core": "^3.
|
|
69
|
-
"@sanity/workbench-cli": "^2.0.
|
|
68
|
+
"@sanity/cli-core": "^3.2.0",
|
|
69
|
+
"@sanity/workbench-cli": "^2.0.2"
|
|
70
70
|
},
|
|
71
71
|
"devDependencies": {
|
|
72
72
|
"@eslint/compat": "^2.1.0",
|
|
73
|
-
"@sanity/pkg-utils": "^12.
|
|
73
|
+
"@sanity/pkg-utils": "^12.2.0",
|
|
74
74
|
"@swc/cli": "^0.8.1",
|
|
75
75
|
"@swc/core": "^1.15.43",
|
|
76
76
|
"@types/lodash-es": "^4.17.12",
|
|
@@ -79,26 +79,31 @@
|
|
|
79
79
|
"@types/react": "^19.2.17",
|
|
80
80
|
"@types/react-dom": "^19.2.3",
|
|
81
81
|
"@types/semver": "^7.7.1",
|
|
82
|
-
"@vitest/coverage-istanbul": "^4.1.
|
|
82
|
+
"@vitest/coverage-istanbul": "^4.1.11",
|
|
83
83
|
"babel-plugin-react-compiler": "^1.0.0",
|
|
84
84
|
"eslint": "^10.7.0",
|
|
85
85
|
"magic-string": "^0.30.21",
|
|
86
|
+
"oxc-transform-react": "^0.145.0",
|
|
86
87
|
"publint": "^0.3.21",
|
|
87
88
|
"sanity": "^6.7.0",
|
|
88
89
|
"styled-components": "^6.4.3",
|
|
89
90
|
"typescript": "^6.0.3",
|
|
90
|
-
"vitest": "^4.1.
|
|
91
|
-
"@repo/tsconfig": "3.70.0",
|
|
91
|
+
"vitest": "^4.1.11",
|
|
92
92
|
"@repo/package.config": "0.0.1",
|
|
93
|
-
"@
|
|
93
|
+
"@repo/tsconfig": "3.70.0",
|
|
94
|
+
"@sanity/cli-test": "12.0.0",
|
|
94
95
|
"@sanity/eslint-config-cli": "^1.1.3"
|
|
95
96
|
},
|
|
96
97
|
"peerDependencies": {
|
|
97
|
-
"babel-plugin-react-compiler": "*"
|
|
98
|
+
"babel-plugin-react-compiler": "*",
|
|
99
|
+
"oxc-transform-react": "*"
|
|
98
100
|
},
|
|
99
101
|
"peerDependenciesMeta": {
|
|
100
102
|
"babel-plugin-react-compiler": {
|
|
101
103
|
"optional": true
|
|
104
|
+
},
|
|
105
|
+
"oxc-transform-react": {
|
|
106
|
+
"optional": true
|
|
102
107
|
}
|
|
103
108
|
},
|
|
104
109
|
"engines": {
|