@sanity/cli-build 7.0.3 → 7.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/actions/build/buildApp.js +3 -2
- package/dist/actions/build/buildApp.js.map +1 -1
- package/dist/actions/build/buildStaticFiles.js +3 -2
- package/dist/actions/build/buildStaticFiles.js.map +1 -1
- package/dist/actions/build/buildStudio.js +1 -1
- package/dist/actions/build/buildStudio.js.map +1 -1
- package/dist/actions/build/getViteConfig.js +22 -62
- package/dist/actions/build/getViteConfig.js.map +1 -1
- package/dist/actions/build/vite/plugin-sanity-vendor-chunks.js +76 -0
- package/dist/actions/build/vite/plugin-sanity-vendor-chunks.js.map +1 -0
- package/dist/actions/manifest/extractCoreAppManifest.js +3 -0
- package/dist/actions/manifest/extractCoreAppManifest.js.map +1 -1
- package/package.json +14 -14
|
@@ -157,13 +157,14 @@ import { resolveVendorBuildConfig } from './resolveVendorBuildConfig.js';
|
|
|
157
157
|
const trace = getCliTelemetry().trace(AppBuildTrace);
|
|
158
158
|
trace.start();
|
|
159
159
|
let autoUpdates;
|
|
160
|
-
if (autoUpdatesEnabled && !
|
|
160
|
+
if (autoUpdatesEnabled && !isMediaLibraryConfigBuild) {
|
|
161
161
|
autoUpdates = {
|
|
162
162
|
cssUrls: autoUpdatesCssUrls,
|
|
163
163
|
imports: autoUpdatesImports,
|
|
164
|
+
// Module server `sanity` imports `styled-components` by name, so the app provides it when it has it.
|
|
164
165
|
vendor: await resolveVendorBuildConfig({
|
|
165
166
|
cwd: workDir,
|
|
166
|
-
isApp:
|
|
167
|
+
isApp: !await getLocalPackageVersion('styled-components', workDir)
|
|
167
168
|
})
|
|
168
169
|
};
|
|
169
170
|
}
|
|
@@ -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 {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 {readBuiltManifest, 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 build is running under Sanity Blueprints (invoked programmatically by\n * `@sanity/runtime-cli`), so emit the statically-imported resource-bindings\n * module Brett rewrites at deploy. Defaults to `false`, so a normal\n * `sanity build`/`dev`/`preview` never emits it.\n */\n isBlueprints?: boolean\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(\n options: BuildOptions,\n): Promise<{mfManifest: Record<string, unknown> | undefined}> {\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 // A Media Library config ships no SDK app — its inputs are island-rendered\n // by `sanity`, so verify that instead and skip the SDK auto-update\n // machinery. Checked via the `appType` discriminator, not the mere presence\n // of a config: a future `ConfigSchema` member must not inherit these\n // media-library build semantics by default.\n const isMediaLibraryConfigBuild = options.exposes?.config?.appType === 'media-library'\n\n if (!installedSdkVersion && !isMediaLibraryConfigBuild) {\n output.error(`Failed to find installed @sanity/sdk-react version`, {\n exit: exitCodes.RUNTIME_ERROR,\n })\n return {mfManifest: undefined}\n }\n\n if (isMediaLibraryConfigBuild && !installedSanityVersion) {\n output.error(`Failed to find installed sanity version`, {\n exit: exitCodes.RUNTIME_ERROR,\n })\n return {mfManifest: undefined}\n }\n\n let autoUpdatesImports = {}\n let autoUpdatesCssUrls: string[] = []\n\n if (autoUpdatesEnabled && !isMediaLibraryConfigBuild) {\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 {mfManifest: undefined}\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 {mfManifest: undefined}\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 isBlueprints: options.isBlueprints,\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 const mfManifest = options.isWorkbenchApp ? await readBuiltManifest(outputDir) : undefined\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 return {mfManifest}\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 return {mfManifest: undefined}\n }\n}\n"],"names":["rm","path","styleText","exitCodes","getLocalPackageVersion","getCliTelemetry","isInteractive","confirm","getTimer","logSymbols","spinner","readBuiltManifest","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","isMediaLibraryConfigBuild","exposes","config","appType","error","exit","RUNTIME_ERROR","mfManifest","undefined","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","isBlueprints","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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pF,QAAQoF,cAAc;QACxC;QACA,MAAM7D,aAAavB,QAAQqE,cAAc,GAAG,MAAMnF,kBAAkB2B,aAAaW;QAEjF2C,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,gBAAgBrF,MAAMsD,GAAG,CAAC;QAEhCL,KAAKM,IAAI,GAAG,CAAC,0BAA0B,EAAE8B,cAAc7B,OAAO,CAAC,GAAG,GAAG,CAAC;QACtEP,KAAKQ,OAAO;QAEZ,IAAIlE,QAAQ+F,KAAK,EAAE;YACjB1F,OAAO4B,GAAG,CAAC;YACX5B,OAAO4B,GAAG,CAAC3C,kBAAkBC,kBAAkBoF,OAAOW,MAAM,EAAEU,KAAK,CAAC,GAAG;QACzE;QAEA7B,MAAM8B,QAAQ;QACd,OAAO;YAAC1E;QAAU;IACpB,EAAE,OAAOH,OAAO;QACdsC,KAAKwC,IAAI;QACT/B,MAAM/C,KAAK,CAACA;QACZ,MAAM8B,UAAU9B,iBAAiB+E,QAAQ/E,MAAM8B,OAAO,GAAGkD,OAAOhF;QAChE5B,WAAW,CAAC,kCAAkC,CAAC,EAAE;YAAC4B;QAAK;QACvDf,OAAOe,KAAK,CAAC,CAAC,oCAAoC,EAAE8B,SAAS,EAAE;YAAC7B,MAAM3C,UAAU4C,aAAa;QAAA;QAC7F,OAAO;YAACC,YAAYC;QAAS;IAC/B;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 {readBuiltManifest, 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 build is running under Sanity Blueprints (invoked programmatically by\n * `@sanity/runtime-cli`), so emit the statically-imported resource-bindings\n * module Brett rewrites at deploy. Defaults to `false`, so a normal\n * `sanity build`/`dev`/`preview` never emits it.\n */\n isBlueprints?: boolean\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(\n options: BuildOptions,\n): Promise<{mfManifest: Record<string, unknown> | undefined}> {\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 // A Media Library config ships no SDK app — its inputs are island-rendered\n // by `sanity`, so verify that instead and skip the SDK auto-update\n // machinery. Checked via the `appType` discriminator, not the mere presence\n // of a config: a future `ConfigSchema` member must not inherit these\n // media-library build semantics by default.\n const isMediaLibraryConfigBuild = options.exposes?.config?.appType === 'media-library'\n\n if (!installedSdkVersion && !isMediaLibraryConfigBuild) {\n output.error(`Failed to find installed @sanity/sdk-react version`, {\n exit: exitCodes.RUNTIME_ERROR,\n })\n return {mfManifest: undefined}\n }\n\n if (isMediaLibraryConfigBuild && !installedSanityVersion) {\n output.error(`Failed to find installed sanity version`, {\n exit: exitCodes.RUNTIME_ERROR,\n })\n return {mfManifest: undefined}\n }\n\n let autoUpdatesImports = {}\n let autoUpdatesCssUrls: string[] = []\n\n if (autoUpdatesEnabled && !isMediaLibraryConfigBuild) {\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 {mfManifest: undefined}\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 {mfManifest: undefined}\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 && !isMediaLibraryConfigBuild) {\n autoUpdates = {\n cssUrls: autoUpdatesCssUrls,\n imports: autoUpdatesImports,\n // Module server `sanity` imports `styled-components` by name, so the app provides it when it has it.\n vendor: await resolveVendorBuildConfig({\n cwd: workDir,\n isApp: !(await getLocalPackageVersion('styled-components', workDir)),\n }),\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 isBlueprints: options.isBlueprints,\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 const mfManifest = options.isWorkbenchApp ? await readBuiltManifest(outputDir) : undefined\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 return {mfManifest}\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 return {mfManifest: undefined}\n }\n}\n"],"names":["rm","path","styleText","exitCodes","getLocalPackageVersion","getCliTelemetry","isInteractive","confirm","getTimer","logSymbols","spinner","readBuiltManifest","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","isMediaLibraryConfigBuild","exposes","config","appType","error","exit","RUNTIME_ERROR","mfManifest","undefined","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","cssUrls","imports","vendor","cwd","isApp","bundle","appTitle","entry","isBlueprints","isWorkbenchApp","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,6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MnF,QAAQmF,IAAI;YAClBC,gBAAgBpF,QAAQoF,cAAc;QACxC;QACA,MAAM7D,aAAavB,QAAQ8E,cAAc,GAAG,MAAM5F,kBAAkB2B,aAAaW;QAEjF2C,MAAMlC,GAAG,CAAC;YACRoD,YAAYX,OAAOY,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,gBAAgBrF,MAAMsD,GAAG,CAAC;QAEhCL,KAAKM,IAAI,GAAG,CAAC,0BAA0B,EAAE8B,cAAc7B,OAAO,CAAC,GAAG,GAAG,CAAC;QACtEP,KAAKQ,OAAO;QAEZ,IAAIlE,QAAQ+F,KAAK,EAAE;YACjB1F,OAAO4B,GAAG,CAAC;YACX5B,OAAO4B,GAAG,CAAC3C,kBAAkBC,kBAAkBmF,OAAOY,MAAM,EAAEU,KAAK,CAAC,GAAG;QACzE;QAEA7B,MAAM8B,QAAQ;QACd,OAAO;YAAC1E;QAAU;IACpB,EAAE,OAAOH,OAAO;QACdsC,KAAKwC,IAAI;QACT/B,MAAM/C,KAAK,CAACA;QACZ,MAAM8B,UAAU9B,iBAAiB+E,QAAQ/E,MAAM8B,OAAO,GAAGkD,OAAOhF;QAChE5B,WAAW,CAAC,kCAAkC,CAAC,EAAE;YAAC4B;QAAK;QACvDf,OAAOe,KAAK,CAAC,CAAC,oCAAoC,EAAE8B,SAAS,EAAE;YAAC7B,MAAM3C,UAAU4C,aAAa;QAAA;QAC7F,OAAO;YAACC,YAAYC;QAAS;IAC/B;AACF"}
|
|
@@ -49,6 +49,7 @@ import { resolveEntries, writeSanityRuntime } from './writeSanityRuntime.js';
|
|
|
49
49
|
}
|
|
50
50
|
buildDebug('Resolving vite config (federation)');
|
|
51
51
|
let viteConfig = await getViteConfig({
|
|
52
|
+
autoUpdates,
|
|
52
53
|
basePath,
|
|
53
54
|
cwd,
|
|
54
55
|
entries,
|
|
@@ -88,8 +89,8 @@ import { resolveEntries, writeSanityRuntime } from './writeSanityRuntime.js';
|
|
|
88
89
|
}
|
|
89
90
|
buildDebug('Bundling federation environment');
|
|
90
91
|
await buildFederatedApp(viteConfig, {
|
|
91
|
-
// Custom Vite hooks
|
|
92
|
-
reuseStandaloneBuild: emitSpa && !extendViteConfig
|
|
92
|
+
// Custom Vite hooks and auto-update externals resolve different dependencies in the two environments.
|
|
93
|
+
reuseStandaloneBuild: emitSpa && !extendViteConfig && !autoUpdates
|
|
93
94
|
});
|
|
94
95
|
buildDebug('Bundling complete');
|
|
95
96
|
// TODO: add stats here
|
|
@@ -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 {buildFederatedApp, type WorkbenchExposes} from '@sanity/workbench-cli/build'\nimport {build} 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 /** Blueprints build (via `@sanity/runtime-cli`) — emit the resource-bindings module. */\n isBlueprints?: boolean\n /** Workbench app (opted in via `defineApplication`) — 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 isBlueprints,\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 // Every federated app and studio also serves itself standalone: emit an SPA\n // (index.html + bootstrap + favicons) into the same `dist` as the federation\n // output via a dedicated `client` environment (see plugin-sanity-environment).\n // Skipped for a dock-only app (no `./App` to mount), matching `exposesApp` in\n // plugin.ts.\n const emitSpa = !(isApp && !entry)\n\n let entries: Awaited<ReturnType<typeof resolveEntries>>\n if (emitSpa) {\n buildDebug('Writing Sanity runtime files (standalone SPA)')\n ;({entries} = await writeSanityRuntime({\n appTitle,\n basePath,\n cwd,\n entry,\n isApp,\n isBlueprints,\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 isBlueprints,\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 await buildFederatedApp(viteConfig, {\n // Custom Vite hooks can resolve different dependencies in the two environments.\n reuseStandaloneBuild: emitSpa && !extendViteConfig,\n })\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 isBlueprints,\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 isBlueprints,\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","buildFederatedApp","build","copyDir","buildDebug","getAppEnvironmentVariables","getStudioEnvironmentVariables","extendViteConfigWithUserConfig","finalizeViteConfig","getViteConfig","writeFavicons","resolveEntries","writeSanityRuntime","buildStaticFiles","options","appTitle","autoUpdates","basePath","cwd","entry","exposes","isApp","isBlueprints","isWorkbenchApp","minify","outputDir","reactCompiler","schemaExtraction","sourceMap","vite","extendViteConfig","workbenchAppId","mode","emitSpa","entries","reactStrictMode","watch","viteConfig","getEnvironmentVariables","command","fromPath","join","staticPath","faviconBasePath","replace","reuseStandaloneBuild","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;AAG5B,SAAQC,iBAAiB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;QAEFO,aAAa,MAAM7B,mBAAmB6B,YAAYY;IACpD;IAEA,MAAMT,WAAWxC,KAAKyC,IAAI,CAACvB,KAAK;IAChC,oDAAoD;IACpDd,WAAW,CAAC,0BAA0B,EAAEoC,SAAS,cAAc,CAAC;IAChE,MAAME,aAAa1C,KAAKyC,IAAI,CAAChB,WAAW;IACxC,MAAMtB,QAAQqC,UAAUE;IAExB,4EAA4E;IAC5EtC,WAAW;IACX,MAAMuC,kBAAkB,GAAG1B,SAAS2B,OAAO,CAAC,QAAQ,IAAI,OAAO,CAAC;IAChE,MAAMlC,cAAciC,iBAAiBD;IAErCtC,WAAW;IACX,MAAM8C,SAAS,MAAMhD,MAAMmC;IAC3BjC,WAAW;IAEX,iFAAiF;IACjF,IAAI+C,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,OAAOzB,OAAO,CAACoB,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,MAAMnE,KAAKoE,UAAU,CAACL,YAAY/D,KAAKqE,QAAQ,CAACnD,KAAK6C,YAAYA;oBACjEO,gBAAgBR,YAAYQ,cAAc;gBAC5C;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 {buildFederatedApp, type WorkbenchExposes} from '@sanity/workbench-cli/build'\nimport {build} 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 /** Blueprints build (via `@sanity/runtime-cli`) — emit the resource-bindings module. */\n isBlueprints?: boolean\n /** Workbench app (opted in via `defineApplication`) — 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 isBlueprints,\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 // Every federated app and studio also serves itself standalone: emit an SPA\n // (index.html + bootstrap + favicons) into the same `dist` as the federation\n // output via a dedicated `client` environment (see plugin-sanity-environment).\n // Skipped for a dock-only app (no `./App` to mount), matching `exposesApp` in\n // plugin.ts.\n const emitSpa = !(isApp && !entry)\n\n let entries: Awaited<ReturnType<typeof resolveEntries>>\n if (emitSpa) {\n buildDebug('Writing Sanity runtime files (standalone SPA)')\n ;({entries} = await writeSanityRuntime({\n appTitle,\n basePath,\n cwd,\n entry,\n isApp,\n isBlueprints,\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 autoUpdates,\n basePath,\n cwd,\n entries,\n exposes,\n getEnvironmentVariables,\n isApp,\n isBlueprints,\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 await buildFederatedApp(viteConfig, {\n // Custom Vite hooks and auto-update externals resolve different dependencies in the two environments.\n reuseStandaloneBuild: emitSpa && !extendViteConfig && !autoUpdates,\n })\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 isBlueprints,\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 isBlueprints,\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","buildFederatedApp","build","copyDir","buildDebug","getAppEnvironmentVariables","getStudioEnvironmentVariables","extendViteConfigWithUserConfig","finalizeViteConfig","getViteConfig","writeFavicons","resolveEntries","writeSanityRuntime","buildStaticFiles","options","appTitle","autoUpdates","basePath","cwd","entry","exposes","isApp","isBlueprints","isWorkbenchApp","minify","outputDir","reactCompiler","schemaExtraction","sourceMap","vite","extendViteConfig","workbenchAppId","mode","emitSpa","entries","reactStrictMode","watch","viteConfig","getEnvironmentVariables","command","fromPath","join","staticPath","faviconBasePath","replace","reuseStandaloneBuild","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;AAG5B,SAAQC,iBAAiB,QAA8B,8BAA6B;AACpF,SAAQC,KAAK,QAAO,OAAM;AAE1B,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;AAoC1E;;;;CAIC,GACD,OAAO,eAAeC,iBACpBC,OAA2B;IAE3B,MAAM,EACJC,QAAQ,EACRC,WAAW,EACXC,QAAQ,EACRC,GAAG,EACHC,KAAK,EACLC,OAAO,EACPC,KAAK,EACLC,YAAY,EACZC,cAAc,EACdC,SAAS,IAAI,EACbC,SAAS,EACTC,aA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AAYA,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,OAAOzB,OAAO,CAACoB,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,MAAMnE,KAAKoE,UAAU,CAACL,YAAY/D,KAAKqE,QAAQ,CAACnD,KAAK6C,YAAYA;oBACjEO,gBAAgBR,YAAYQ,cAAc;gBAC5C;YACF;YACAH,MAAMb,MAAMa,IAAI;QAClB;IACF;IAEA,OAAO;QAACrB,QAAQO;IAAK;AACvB"}
|
|
@@ -150,7 +150,7 @@ import { resolveVendorBuildConfig } from './resolveVendorBuildConfig.js';
|
|
|
150
150
|
const trace = getCliTelemetry().trace(StudioBuildTrace);
|
|
151
151
|
trace.start();
|
|
152
152
|
let autoUpdates;
|
|
153
|
-
if (autoUpdatesEnabled
|
|
153
|
+
if (autoUpdatesEnabled) {
|
|
154
154
|
autoUpdates = {
|
|
155
155
|
cssUrls: autoUpdatesCssUrls,
|
|
156
156
|
imports: autoUpdatesImports,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/actions/build/buildStudio.ts"],"sourcesContent":["import {rm} from 'node:fs/promises'\nimport path from 'node:path'\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 {getTimer, logSymbols} from '@sanity/cli-core/ux'\nimport {readBuiltManifest, type WorkbenchExposes} from '@sanity/workbench-cli/build'\nimport {parse as semverParse} from 'semver'\n\nimport {StudioBuildTrace} from '../../telemetry/build.telemetry.js'\nimport {\n CompareDependencyVersions,\n CompareDependencyVersionsResult,\n} from '../../util/compareDependencyVersions.js'\nimport {formatModuleSizes, sortModulesBySize} from '../../util/moduleFormatUtils.js'\nimport {buildDebug} from './buildDebug.js'\nimport {buildStaticFiles} from './buildStaticFiles.js'\nimport {checkRequiredDependencies} from './checkRequiredDependencies.js'\nimport {checkStudioDependencyVersions} from './checkStudioDependencyVersions.js'\nimport {type BuildEventListener, type MessageFunc} from './eventListener.js'\nimport {getAutoUpdatesCssUrls, getAutoUpdatesImportMap} from './getAutoUpdatesImportMap.js'\nimport {getStudioEnvironmentVariables} from './getEnvironmentVariables.js'\nimport {handlePrereleaseVersions} from './handlePrereleaseVersions.js'\nimport {resolveVendorBuildConfig} from './resolveVendorBuildConfig.js'\n\nexport interface BuildStudioEventListener extends BuildEventListener {\n onBuildEnd: MessageFunc\n onBuildFail: MessageFunc\n onBuildStart: MessageFunc\n onCleanOutputDirEnd: MessageFunc\n onCleanOutputDirStart: MessageFunc\n onIncompatibleDeclaredStyledComponentsVersionRange: MessageFunc\n onIncompatibleInstalledStyledComponentsVersionRange: MessageFunc\n onInteractiveNonDefaultOutputDir({message}: {message: string}): Promise<{shouldClean: boolean}>\n onInvalidStyledComponentsVersionRange: MessageFunc\n onNoDeclaredStyledComponentsVersion: MessageFunc\n onNoInstalledSanityVersion: MessageFunc\n onNoInstalledStyledComponentsVersion: MessageFunc\n onVersionMismatchInInteractiveAutoUpdate(params: {\n mismatched: CompareDependencyVersions[]\n versionMismatchWarning: string\n }): Promise<{stopBuild: boolean}>\n onVersionMismatchInNonInteractiveAutoUpdate(params: {versionMismatchWarning: string}): void\n}\n\nexport interface BuildOptions {\n appId: string | undefined\n autoUpdatesEnabled: boolean\n checkAppId: () => void\n compareDependencyVersions: (\n packages: {name: string; version: string}[],\n ) => Promise<CompareDependencyVersionsResult>\n determineBasePath: () => string\n eventListener: Partial<BuildStudioEventListener>\n isApp: boolean\n isWorkbenchApp: boolean\n minify: boolean\n outDir: string | undefined\n output: Output\n reactCompiler: boolean | CliConfig['reactCompiler'] | undefined\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 build is running under Sanity Blueprints (invoked programmatically by\n * `@sanity/runtime-cli`), so emit the statically-imported resource-bindings\n * module Brett rewrites at deploy. Defaults to `false`, so a normal\n * `sanity build`/`dev`/`preview` never emits it.\n */\n isBlueprints?: boolean\n\n /** The workbench app's bus identity (`__SANITY_APP_ID__`). */\n workbenchAppId?: string\n}\n\n/**\n * Internal build studio that avoids depending on flags for CLI config.\n * @param options - options for the build\n */\nexport async function buildStudio(\n options: BuildOptions,\n): Promise<{mfManifest: Record<string, unknown> | undefined}> {\n buildDebug(`Building studio`)\n\n const timer = getTimer()\n const {\n appId,\n determineBasePath,\n eventListener,\n exposes,\n isApp,\n minify,\n outDir,\n output,\n reactCompiler,\n schemaExtraction,\n sourceMap,\n stats,\n unattendedMode,\n vite,\n workDir,\n } = options\n const defaultOutputDir = path.resolve(path.join(workDir, 'dist'))\n const outputDir = path.resolve(outDir || defaultOutputDir)\n\n await checkStudioDependencyVersions(workDir, output)\n\n // If the check resulted in a dependency install, the CLI command will be re-run,\n // thus we want to exit early\n const {installedSanityVersion} = await checkRequiredDependencies({\n isApp,\n workDir,\n\n ...eventListener,\n })\n\n let autoUpdatesEnabled = options.autoUpdatesEnabled\n\n let autoUpdatesImports = {}\n let autoUpdatesCssUrls: string[] = []\n\n if (autoUpdatesEnabled) {\n // Get the clean version without build metadata: https://semver.org/#spec-item-10\n const cleanSanityVersion = semverParse(installedSanityVersion)?.version\n if (!cleanSanityVersion) {\n throw new Error(`Failed to parse installed Sanity version: ${installedSanityVersion}`)\n }\n\n output.log(`${logSymbols.info} Building with auto-updates enabled`)\n\n // Warn if auto updates enabled but no appId configured\n options.checkAppId()\n\n const installedVisionVersion = await getLocalPackageVersion('@sanity/vision', workDir)\n const cleanVisionVersion = installedVisionVersion\n ? semverParse(installedVisionVersion)?.version\n : undefined\n\n const sanityDependencies = [\n {cssFile: 'index.css', name: 'sanity', version: cleanSanityVersion},\n ...(cleanVisionVersion\n ? [{cssFile: 'index.css', name: '@sanity/vision' as const, version: cleanVisionVersion}]\n : [{name: '@sanity/vision' as const, version: cleanSanityVersion}]),\n ]\n autoUpdatesImports = getAutoUpdatesImportMap(sanityDependencies, {appId})\n\n autoUpdatesCssUrls = getAutoUpdatesCssUrls(sanityDependencies, {appId})\n\n // Check the versions\n const {mismatched, unresolvedPrerelease} =\n await options.compareDependencyVersions(sanityDependencies)\n\n if (unresolvedPrerelease.length > 0) {\n await handlePrereleaseVersions({\n unattendedMode,\n unresolvedPrerelease,\n\n ...eventListener,\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 const {\n onVersionMismatchInInteractiveAutoUpdate = () => ({stopBuild: true}),\n onVersionMismatchInNonInteractiveAutoUpdate = () => {},\n } = eventListener\n\n // If it is non-interactive or in unattended mode, we don't want to prompt\n if (isInteractive() && !unattendedMode) {\n const {stopBuild} = await onVersionMismatchInInteractiveAutoUpdate({\n mismatched,\n versionMismatchWarning,\n })\n if (stopBuild) return {mfManifest: undefined}\n } else {\n // if non-interactive or unattended, just show the warning\n onVersionMismatchInNonInteractiveAutoUpdate({versionMismatchWarning})\n }\n }\n }\n\n const envVarKeys = Object.keys(getStudioEnvironmentVariables())\n if (envVarKeys.length > 0) {\n output.log('\\nIncluding the following environment variables as part of the JavaScript bundle:')\n for (const key of envVarKeys) {\n output.log(`- ${key}`)\n }\n output.log('')\n }\n\n let shouldClean = true\n if (outputDir !== defaultOutputDir && !unattendedMode && isInteractive()) {\n const {onInteractiveNonDefaultOutputDir = () => ({shouldClean: true})} = eventListener\n ;({shouldClean} = await onInteractiveNonDefaultOutputDir({\n message: `Do you want to delete the existing directory (${outputDir}) first?`,\n }))\n }\n\n // Determine base path for built studio\n const basePath = determineBasePath()\n\n if (schemaExtraction?.enabled) {\n output.log(`${logSymbols.info} Building with schema extraction enabled`)\n }\n\n if (shouldClean) {\n const {onCleanOutputDirEnd = () => {}, onCleanOutputDirStart = () => {}} = eventListener\n timer.start('cleanOutputFolder')\n onCleanOutputDirStart({message: 'Clean output folder'})\n\n await rm(outputDir, {force: true, recursive: true})\n const cleanDuration = timer.end('cleanOutputFolder')\n\n onCleanOutputDirEnd({\n message: `Clean output folder (${cleanDuration.toFixed(0)}ms)`,\n })\n }\n\n const {onBuildEnd = () => {}, onBuildFail = () => {}, onBuildStart = () => {}} = eventListener\n\n onBuildStart({message: `Build Sanity Studio`})\n\n const trace = getCliTelemetry().trace(StudioBuildTrace)\n trace.start()\n\n let autoUpdates\n if (autoUpdatesEnabled && !options.isWorkbenchApp) {\n autoUpdates = {\n cssUrls: autoUpdatesCssUrls,\n imports: autoUpdatesImports,\n vendor: await resolveVendorBuildConfig({cwd: workDir, isApp: false}),\n }\n }\n\n try {\n timer.start('bundleStudio')\n\n const bundle = await buildStaticFiles({\n autoUpdates,\n basePath,\n cwd: workDir,\n exposes,\n isBlueprints: options.isBlueprints,\n isWorkbenchApp: options.isWorkbenchApp,\n minify,\n outputDir,\n reactCompiler,\n schemaExtraction,\n sourceMap,\n vite,\n workbenchAppId: options.workbenchAppId,\n })\n const mfManifest = options.isWorkbenchApp ? await readBuiltManifest(outputDir) : undefined\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 onBuildEnd({message: `Build Sanity Studio (${buildDuration.toFixed(0)}ms)`})\n\n trace.complete()\n if (stats) {\n output.log('\\nLargest module files:')\n output.log(formatModuleSizes(sortModulesBySize(bundle.chunks).slice(0, 15)))\n }\n return {mfManifest}\n } catch (error) {\n trace.error(error)\n const message = error instanceof Error ? error.message : String(error)\n buildDebug(`Failed to build Sanity Studio`, {error})\n onBuildFail({message: `Failed to build Sanity Studio: ${message}`})\n return {mfManifest: undefined}\n }\n}\n"],"names":["rm","path","getLocalPackageVersion","getCliTelemetry","isInteractive","getTimer","logSymbols","readBuiltManifest","parse","semverParse","StudioBuildTrace","formatModuleSizes","sortModulesBySize","buildDebug","buildStaticFiles","checkRequiredDependencies","checkStudioDependencyVersions","getAutoUpdatesCssUrls","getAutoUpdatesImportMap","getStudioEnvironmentVariables","handlePrereleaseVersions","resolveVendorBuildConfig","buildStudio","options","timer","appId","determineBasePath","eventListener","exposes","isApp","minify","outDir","output","reactCompiler","schemaExtraction","sourceMap","stats","unattendedMode","vite","workDir","defaultOutputDir","resolve","join","outputDir","installedSanityVersion","autoUpdatesEnabled","autoUpdatesImports","autoUpdatesCssUrls","cleanSanityVersion","version","Error","log","info","checkAppId","installedVisionVersion","cleanVisionVersion","undefined","sanityDependencies","cssFile","name","mismatched","unresolvedPrerelease","compareDependencyVersions","length","versionMismatchWarning","map","mod","pkg","installed","remote","onVersionMismatchInInteractiveAutoUpdate","stopBuild","onVersionMismatchInNonInteractiveAutoUpdate","mfManifest","envVarKeys","Object","keys","key","shouldClean","onInteractiveNonDefaultOutputDir","message","basePath","enabled","onCleanOutputDirEnd","onCleanOutputDirStart","start","force","recursive","cleanDuration","end","toFixed","onBuildEnd","onBuildFail","onBuildStart","trace","autoUpdates","isWorkbenchApp","cssUrls","imports","vendor","cwd","bundle","isBlueprints","workbenchAppId","outputSize","chunks","flatMap","chunk","modules","renderedLength","reduce","sum","n","buildDuration","complete","slice","error","String"],"mappings":"AAAA,SAAQA,EAAE,QAAO,mBAAkB;AACnC,OAAOC,UAAU,YAAW;AAE5B,SAAQC,sBAAsB,QAAO,mCAAkC;AACvE,SAAQC,eAAe,QAAO,6BAA4B;AAE1D,SAAQC,aAAa,QAAO,wBAAuB;AACnD,SAAQC,QAAQ,EAAEC,UAAU,QAAO,sBAAqB;AACxD,SAAQC,iBAAiB,QAA8B,8BAA6B;AACpF,SAAQC,SAASC,WAAW,QAAO,SAAQ;AAE3C,SAAQC,gBAAgB,QAAO,qCAAoC;AAKnE,SAAQC,iBAAiB,EAAEC,iBAAiB,QAAO,kCAAiC;AACpF,SAAQC,UAAU,QAAO,kBAAiB;AAC1C,SAAQC,gBAAgB,QAAO,wBAAuB;AACtD,SAAQC,yBAAyB,QAAO,iCAAgC;AACxE,SAAQC,6BAA6B,QAAO,qCAAoC;AAEhF,SAAQC,qBAAqB,EAAEC,uBAAuB,QAAO,+BAA8B;AAC3F,SAAQC,6BAA6B,QAAO,+BAA8B;AAC1E,SAAQC,wBAAwB,QAAO,gCAA+B;AACtE,SAAQC,wBAAwB,QAAO,gCAA+B;AAyDtE;;;CAGC,GACD,OAAO,eAAeC,YACpBC,OAAqB;IAErBV,WAAW,CAAC,eAAe,CAAC;IAE5B,MAAMW,QAAQnB;IACd,MAAM,EACJoB,KAAK,EACLC,iBAAiB,EACjBC,aAAa,EACbC,OAAO,EACPC,KAAK,EACLC,MAAM,EACNC,MAAM,EACNC,MAAM,EACNC,aAAa,EACbC,gBAAgB,EAChBC,SAAS,EACTC,KAAK,EACLC,cAAc,EACdC,IAAI,EACJC,OAAO,EACR,GAAGhB;IACJ,MAAMiB,mBAAmBvC,KAAKwC,OAAO,CAACxC,KAAKyC,IAAI,CAACH,SAAS;IACzD,MAAMI,YAAY1C,KAAKwC,OAAO,CAACV,UAAUS;IAEzC,MAAMxB,8BAA8BuB,SAASP;IAE7C,iFAAiF;IACjF,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OAAOI,MAAM,CACtBC,OAAO,CAAC,CAACC,QAAUA,MAAMC,OAAO,CAACF,OAAO,CAAC,CAACxC,MAAQA,IAAI2C,cAAc,GACpEC,MAAM,CAAC,CAACC,KAAKC,IAAMD,MAAMC,GAAG;QACjC;QACA,MAAMC,gBAAgBzF,MAAMiE,GAAG,CAAC;QAEhCE,WAAW;YAACX,SAAS,CAAC,qBAAqB,EAAEiC,cAAcvB,OAAO,CAAC,GAAG,GAAG,CAAC;QAAA;QAE1EI,MAAMoB,QAAQ;QACd,IAAI9E,OAAO;YACTJ,OAAOmB,GAAG,CAAC;YACXnB,OAAOmB,GAAG,CAACxC,kBAAkBC,kBAAkByF,OAAOI,MAAM,EAAEU,KAAK,CAAC,GAAG;QACzE;QACA,OAAO;YAAC1C;QAAU;IACpB,EAAE,OAAO2C,OAAO;QACdtB,MAAMsB,KAAK,CAACA;QACZ,MAAMpC,UAAUoC,iBAAiBlE,QAAQkE,MAAMpC,OAAO,GAAGqC,OAAOD;QAChEvG,WAAW,CAAC,6BAA6B,CAAC,EAAE;YAACuG;QAAK;QAClDxB,YAAY;YAACZ,SAAS,CAAC,+BAA+B,EAAEA,SAAS;QAAA;QACjE,OAAO;YAACP,YAAYjB;QAAS;IAC/B;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/build/buildStudio.ts"],"sourcesContent":["import {rm} from 'node:fs/promises'\nimport path from 'node:path'\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 {getTimer, logSymbols} from '@sanity/cli-core/ux'\nimport {readBuiltManifest, type WorkbenchExposes} from '@sanity/workbench-cli/build'\nimport {parse as semverParse} from 'semver'\n\nimport {StudioBuildTrace} from '../../telemetry/build.telemetry.js'\nimport {\n CompareDependencyVersions,\n CompareDependencyVersionsResult,\n} from '../../util/compareDependencyVersions.js'\nimport {formatModuleSizes, sortModulesBySize} from '../../util/moduleFormatUtils.js'\nimport {buildDebug} from './buildDebug.js'\nimport {buildStaticFiles} from './buildStaticFiles.js'\nimport {checkRequiredDependencies} from './checkRequiredDependencies.js'\nimport {checkStudioDependencyVersions} from './checkStudioDependencyVersions.js'\nimport {type BuildEventListener, type MessageFunc} from './eventListener.js'\nimport {getAutoUpdatesCssUrls, getAutoUpdatesImportMap} from './getAutoUpdatesImportMap.js'\nimport {getStudioEnvironmentVariables} from './getEnvironmentVariables.js'\nimport {handlePrereleaseVersions} from './handlePrereleaseVersions.js'\nimport {resolveVendorBuildConfig} from './resolveVendorBuildConfig.js'\n\nexport interface BuildStudioEventListener extends BuildEventListener {\n onBuildEnd: MessageFunc\n onBuildFail: MessageFunc\n onBuildStart: MessageFunc\n onCleanOutputDirEnd: MessageFunc\n onCleanOutputDirStart: MessageFunc\n onIncompatibleDeclaredStyledComponentsVersionRange: MessageFunc\n onIncompatibleInstalledStyledComponentsVersionRange: MessageFunc\n onInteractiveNonDefaultOutputDir({message}: {message: string}): Promise<{shouldClean: boolean}>\n onInvalidStyledComponentsVersionRange: MessageFunc\n onNoDeclaredStyledComponentsVersion: MessageFunc\n onNoInstalledSanityVersion: MessageFunc\n onNoInstalledStyledComponentsVersion: MessageFunc\n onVersionMismatchInInteractiveAutoUpdate(params: {\n mismatched: CompareDependencyVersions[]\n versionMismatchWarning: string\n }): Promise<{stopBuild: boolean}>\n onVersionMismatchInNonInteractiveAutoUpdate(params: {versionMismatchWarning: string}): void\n}\n\nexport interface BuildOptions {\n appId: string | undefined\n autoUpdatesEnabled: boolean\n checkAppId: () => void\n compareDependencyVersions: (\n packages: {name: string; version: string}[],\n ) => Promise<CompareDependencyVersionsResult>\n determineBasePath: () => string\n eventListener: Partial<BuildStudioEventListener>\n isApp: boolean\n isWorkbenchApp: boolean\n minify: boolean\n outDir: string | undefined\n output: Output\n reactCompiler: boolean | CliConfig['reactCompiler'] | undefined\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 build is running under Sanity Blueprints (invoked programmatically by\n * `@sanity/runtime-cli`), so emit the statically-imported resource-bindings\n * module Brett rewrites at deploy. Defaults to `false`, so a normal\n * `sanity build`/`dev`/`preview` never emits it.\n */\n isBlueprints?: boolean\n\n /** The workbench app's bus identity (`__SANITY_APP_ID__`). */\n workbenchAppId?: string\n}\n\n/**\n * Internal build studio that avoids depending on flags for CLI config.\n * @param options - options for the build\n */\nexport async function buildStudio(\n options: BuildOptions,\n): Promise<{mfManifest: Record<string, unknown> | undefined}> {\n buildDebug(`Building studio`)\n\n const timer = getTimer()\n const {\n appId,\n determineBasePath,\n eventListener,\n exposes,\n isApp,\n minify,\n outDir,\n output,\n reactCompiler,\n schemaExtraction,\n sourceMap,\n stats,\n unattendedMode,\n vite,\n workDir,\n } = options\n const defaultOutputDir = path.resolve(path.join(workDir, 'dist'))\n const outputDir = path.resolve(outDir || defaultOutputDir)\n\n await checkStudioDependencyVersions(workDir, output)\n\n // If the check resulted in a dependency install, the CLI command will be re-run,\n // thus we want to exit early\n const {installedSanityVersion} = await checkRequiredDependencies({\n isApp,\n workDir,\n\n ...eventListener,\n })\n\n let autoUpdatesEnabled = options.autoUpdatesEnabled\n\n let autoUpdatesImports = {}\n let autoUpdatesCssUrls: string[] = []\n\n if (autoUpdatesEnabled) {\n // Get the clean version without build metadata: https://semver.org/#spec-item-10\n const cleanSanityVersion = semverParse(installedSanityVersion)?.version\n if (!cleanSanityVersion) {\n throw new Error(`Failed to parse installed Sanity version: ${installedSanityVersion}`)\n }\n\n output.log(`${logSymbols.info} Building with auto-updates enabled`)\n\n // Warn if auto updates enabled but no appId configured\n options.checkAppId()\n\n const installedVisionVersion = await getLocalPackageVersion('@sanity/vision', workDir)\n const cleanVisionVersion = installedVisionVersion\n ? semverParse(installedVisionVersion)?.version\n : undefined\n\n const sanityDependencies = [\n {cssFile: 'index.css', name: 'sanity', version: cleanSanityVersion},\n ...(cleanVisionVersion\n ? [{cssFile: 'index.css', name: '@sanity/vision' as const, version: cleanVisionVersion}]\n : [{name: '@sanity/vision' as const, version: cleanSanityVersion}]),\n ]\n autoUpdatesImports = getAutoUpdatesImportMap(sanityDependencies, {appId})\n\n autoUpdatesCssUrls = getAutoUpdatesCssUrls(sanityDependencies, {appId})\n\n // Check the versions\n const {mismatched, unresolvedPrerelease} =\n await options.compareDependencyVersions(sanityDependencies)\n\n if (unresolvedPrerelease.length > 0) {\n await handlePrereleaseVersions({\n unattendedMode,\n unresolvedPrerelease,\n\n ...eventListener,\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 const {\n onVersionMismatchInInteractiveAutoUpdate = () => ({stopBuild: true}),\n onVersionMismatchInNonInteractiveAutoUpdate = () => {},\n } = eventListener\n\n // If it is non-interactive or in unattended mode, we don't want to prompt\n if (isInteractive() && !unattendedMode) {\n const {stopBuild} = await onVersionMismatchInInteractiveAutoUpdate({\n mismatched,\n versionMismatchWarning,\n })\n if (stopBuild) return {mfManifest: undefined}\n } else {\n // if non-interactive or unattended, just show the warning\n onVersionMismatchInNonInteractiveAutoUpdate({versionMismatchWarning})\n }\n }\n }\n\n const envVarKeys = Object.keys(getStudioEnvironmentVariables())\n if (envVarKeys.length > 0) {\n output.log('\\nIncluding the following environment variables as part of the JavaScript bundle:')\n for (const key of envVarKeys) {\n output.log(`- ${key}`)\n }\n output.log('')\n }\n\n let shouldClean = true\n if (outputDir !== defaultOutputDir && !unattendedMode && isInteractive()) {\n const {onInteractiveNonDefaultOutputDir = () => ({shouldClean: true})} = eventListener\n ;({shouldClean} = await onInteractiveNonDefaultOutputDir({\n message: `Do you want to delete the existing directory (${outputDir}) first?`,\n }))\n }\n\n // Determine base path for built studio\n const basePath = determineBasePath()\n\n if (schemaExtraction?.enabled) {\n output.log(`${logSymbols.info} Building with schema extraction enabled`)\n }\n\n if (shouldClean) {\n const {onCleanOutputDirEnd = () => {}, onCleanOutputDirStart = () => {}} = eventListener\n timer.start('cleanOutputFolder')\n onCleanOutputDirStart({message: 'Clean output folder'})\n\n await rm(outputDir, {force: true, recursive: true})\n const cleanDuration = timer.end('cleanOutputFolder')\n\n onCleanOutputDirEnd({\n message: `Clean output folder (${cleanDuration.toFixed(0)}ms)`,\n })\n }\n\n const {onBuildEnd = () => {}, onBuildFail = () => {}, onBuildStart = () => {}} = eventListener\n\n onBuildStart({message: `Build Sanity Studio`})\n\n const trace = getCliTelemetry().trace(StudioBuildTrace)\n trace.start()\n\n let autoUpdates\n if (autoUpdatesEnabled) {\n autoUpdates = {\n cssUrls: autoUpdatesCssUrls,\n imports: autoUpdatesImports,\n vendor: await resolveVendorBuildConfig({cwd: workDir, isApp: false}),\n }\n }\n\n try {\n timer.start('bundleStudio')\n\n const bundle = await buildStaticFiles({\n autoUpdates,\n basePath,\n cwd: workDir,\n exposes,\n isBlueprints: options.isBlueprints,\n isWorkbenchApp: options.isWorkbenchApp,\n minify,\n outputDir,\n reactCompiler,\n schemaExtraction,\n sourceMap,\n vite,\n workbenchAppId: options.workbenchAppId,\n })\n const mfManifest = options.isWorkbenchApp ? await readBuiltManifest(outputDir) : undefined\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 onBuildEnd({message: `Build Sanity Studio (${buildDuration.toFixed(0)}ms)`})\n\n trace.complete()\n if (stats) {\n output.log('\\nLargest module files:')\n output.log(formatModuleSizes(sortModulesBySize(bundle.chunks).slice(0, 15)))\n }\n return {mfManifest}\n } catch (error) {\n trace.error(error)\n const message = error instanceof Error ? error.message : String(error)\n buildDebug(`Failed to build Sanity Studio`, {error})\n onBuildFail({message: `Failed to build Sanity Studio: ${message}`})\n return {mfManifest: undefined}\n }\n}\n"],"names":["rm","path","getLocalPackageVersion","getCliTelemetry","isInteractive","getTimer","logSymbols","readBuiltManifest","parse","semverParse","StudioBuildTrace","formatModuleSizes","sortModulesBySize","buildDebug","buildStaticFiles","checkRequiredDependencies","checkStudioDependencyVersions","getAutoUpdatesCssUrls","getAutoUpdatesImportMap","getStudioEnvironmentVariables","handlePrereleaseVersions","resolveVendorBuildConfig","buildStudio","options","timer","appId","determineBasePath","eventListener","exposes","isApp","minify","outDir","output","reactCompiler","schemaExtraction","sourceMap","stats","unattendedMode","vite","workDir","defaultOutputDir","resolve","join","outputDir","installedSanityVersion","autoUpdatesEnabled","autoUpdatesImports","autoUpdatesCssUrls","cleanSanityVersion","version","Error","log","info","checkAppId","installedVisionVersion","cleanVisionVersion","undefined","sanityDependencies","cssFile","name","mismatched","unresolvedPrerelease","compareDependencyVersions","length","versionMismatchWarning","map","mod","pkg","installed","remote","onVersionMismatchInInteractiveAutoUpdate","stopBuild","onVersionMismatchInNonInteractiveAutoUpdate","mfManifest","envVarKeys","Object","keys","key","shouldClean","onInteractiveNonDefaultOutputDir","message","basePath","enabled","onCleanOutputDirEnd","onCleanOutputDirStart","start","force","recursive","cleanDuration","end","toFixed","onBuildEnd","onBuildFail","onBuildStart","trace","autoUpdates","cssUrls","imports","vendor","cwd","bundle","isBlueprints","isWorkbenchApp","workbenchAppId","outputSize","chunks","flatMap","chunk","modules","renderedLength","reduce","sum","n","buildDuration","complete","slice","error","String"],"mappings":"AAAA,SAAQA,EAAE,QAAO,mBAAkB;AACnC,OAAOC,UAAU,YAAW;AAE5B,SAAQC,sBAAsB,QAAO,mCAAkC;AACvE,SAAQC,eAAe,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iE,GAAG,CAAC;QAEhCE,WAAW;YAACX,SAAS,CAAC,qBAAqB,EAAEiC,cAAcvB,OAAO,CAAC,GAAG,GAAG,CAAC;QAAA;QAE1EI,MAAMoB,QAAQ;QACd,IAAI9E,OAAO;YACTJ,OAAOmB,GAAG,CAAC;YACXnB,OAAOmB,GAAG,CAACxC,kBAAkBC,kBAAkBwF,OAAOK,MAAM,EAAEU,KAAK,CAAC,GAAG;QACzE;QACA,OAAO;YAAC1C;QAAU;IACpB,EAAE,OAAO2C,OAAO;QACdtB,MAAMsB,KAAK,CAACA;QACZ,MAAMpC,UAAUoC,iBAAiBlE,QAAQkE,MAAMpC,OAAO,GAAGqC,OAAOD;QAChEvG,WAAW,CAAC,6BAA6B,CAAC,EAAE;YAACuG;QAAK;QAClDxB,YAAY;YAACZ,SAAS,CAAC,+BAA+B,EAAEA,SAAS;QAAA;QACjE,OAAO;YAACP,YAAYjB;QAAS;IAC/B;AACF"}
|
|
@@ -6,17 +6,15 @@ import { isStaging } from '@sanity/cli-core/util';
|
|
|
6
6
|
import { resourceBindingsChunkFileName, resourceBindingsCodeSplittingGroup, workbenchOptimizeDeps, workbenchVitePlugins } from '@sanity/workbench-cli/build';
|
|
7
7
|
import viteReact, { reactCompilerPreset } from '@vitejs/plugin-react';
|
|
8
8
|
import { Features } from 'lightningcss';
|
|
9
|
-
import {
|
|
9
|
+
import { mergeConfig } from 'vite';
|
|
10
10
|
import { SANITY_CACHE_DIR } from '../../constants.js';
|
|
11
11
|
import { sanitySchemaExtractionPlugin } from '../schema/vite/plugin-schema-extraction.js';
|
|
12
12
|
import { buildDebug } from './buildDebug.js';
|
|
13
|
-
import { VENDOR_DIR } from './constants.js';
|
|
14
|
-
import { createExternalFromImportMap } from './createExternalFromImportMap.js';
|
|
15
13
|
import { normalizeBasePath } from './normalizeBasePath.js';
|
|
16
14
|
import { sanityBuildEntries } from './vite/plugin-sanity-build-entries.js';
|
|
17
15
|
import { sanityFaviconsPlugin } from './vite/plugin-sanity-favicons.js';
|
|
18
16
|
import { sanityRuntimeRewritePlugin } from './vite/plugin-sanity-runtime-rewrite.js';
|
|
19
|
-
import {
|
|
17
|
+
import { sanityVendorChunks } from './vite/plugin-sanity-vendor-chunks.js';
|
|
20
18
|
import { getDefaultFaviconsPath } from './writeFavicons.js';
|
|
21
19
|
/**
|
|
22
20
|
* Get a configuration object for Vite based on the passed options
|
|
@@ -92,6 +90,7 @@ import { getDefaultFaviconsPath } from './writeFavicons.js';
|
|
|
92
90
|
...sharedPlugins,
|
|
93
91
|
await workbenchVitePlugins({
|
|
94
92
|
appId: workbenchAppId,
|
|
93
|
+
autoUpdates,
|
|
95
94
|
cwd,
|
|
96
95
|
entries,
|
|
97
96
|
exposes,
|
|
@@ -100,13 +99,17 @@ import { getDefaultFaviconsPath } from './writeFavicons.js';
|
|
|
100
99
|
}),
|
|
101
100
|
{
|
|
102
101
|
...sanityBuildEntries({
|
|
102
|
+
autoUpdates,
|
|
103
103
|
basePath,
|
|
104
104
|
bridge: false,
|
|
105
105
|
cwd,
|
|
106
106
|
isApp
|
|
107
107
|
}),
|
|
108
108
|
applyToEnvironment: (env)=>env.name === 'client'
|
|
109
|
-
}
|
|
109
|
+
},
|
|
110
|
+
...autoUpdates ? [
|
|
111
|
+
sanityVendorChunks(autoUpdates)
|
|
112
|
+
] : []
|
|
110
113
|
] : [
|
|
111
114
|
...sharedPlugins,
|
|
112
115
|
sanityFaviconsPlugin({
|
|
@@ -178,29 +181,8 @@ import { getDefaultFaviconsPath } from './writeFavicons.js';
|
|
|
178
181
|
// plugin configures its own environment and build entry point.
|
|
179
182
|
if (mode === 'production' && !isWorkbenchApp) {
|
|
180
183
|
if (autoUpdates) {
|
|
181
|
-
viteConfig.plugins.push(
|
|
182
|
-
// on the emitted vendor chunks; Rolldown only emits `export default` for a
|
|
183
|
-
// CommonJS entry.
|
|
184
|
-
createVendorNamedExportsPlugin(autoUpdates.vendor.namesByChunkName), // The import map and vendor specifiers are externals of the studio/app
|
|
185
|
-
// bundle, resolved by the browser at runtime. They are handed to
|
|
186
|
-
// `esmExternalRequirePlugin` rather than `rolldownOptions.external`: the
|
|
187
|
-
// plugin both marks them external AND rewrites bundled CommonJS
|
|
188
|
-
// `require()` calls of an external (e.g. react-dom requiring react) into
|
|
189
|
-
// ESM imports, while `rolldownOptions.external` would short-circuit that
|
|
190
|
-
// rewrite and leave a runtime `require` shim that throws in the browser.
|
|
191
|
-
esmExternalRequirePlugin({
|
|
192
|
-
external: createExternalFromImportMap({
|
|
193
|
-
imports: {
|
|
194
|
-
...autoUpdates.imports,
|
|
195
|
-
...Object.fromEntries(Object.values(autoUpdates.vendor.specifiersByChunkName).map((specifier)=>[
|
|
196
|
-
specifier,
|
|
197
|
-
''
|
|
198
|
-
]))
|
|
199
|
-
}
|
|
200
|
-
})
|
|
201
|
-
}));
|
|
184
|
+
viteConfig.plugins.push(sanityVendorChunks(autoUpdates));
|
|
202
185
|
}
|
|
203
|
-
const vendorChunkNames = autoUpdates ? new Set(Object.keys(autoUpdates.vendor.specifiersByChunkName)) : null;
|
|
204
186
|
viteConfig.build = {
|
|
205
187
|
...viteConfig.build,
|
|
206
188
|
assetsDir: 'static',
|
|
@@ -208,45 +190,23 @@ import { getDefaultFaviconsPath } from './writeFavicons.js';
|
|
|
208
190
|
minify: minify ? 'oxc' : false,
|
|
209
191
|
rolldownOptions: {
|
|
210
192
|
input: {
|
|
211
|
-
sanity: path.join(cwd, '.sanity', 'runtime', 'app.js')
|
|
212
|
-
...autoUpdates?.vendor.entries
|
|
193
|
+
sanity: path.join(cwd, '.sanity', 'runtime', 'app.js')
|
|
213
194
|
},
|
|
214
195
|
onwarn: onRolldownWarn,
|
|
215
|
-
...isBlueprints
|
|
196
|
+
...isBlueprints ? {
|
|
216
197
|
output: {
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
}
|
|
229
|
-
} : {},
|
|
230
|
-
...autoUpdates ? {
|
|
231
|
-
entryFileNames: (chunk)=>vendorChunkNames.has(chunk.name) ? `${VENDOR_DIR}/[name]-[hash].mjs` : 'static/[name]-[hash].js',
|
|
232
|
-
exports: 'named'
|
|
233
|
-
} : {}
|
|
198
|
+
// Blueprints only: keep the resource-bindings module in its
|
|
199
|
+
// own unhashed chunk at the bundle root so Brett can rewrite
|
|
200
|
+
// it at deploy. The chunk sizing lives on the group itself
|
|
201
|
+
// (see `resourceBindingsCodeSplittingGroup`), so it only
|
|
202
|
+
// affects the bindings module and not automatic chunking.
|
|
203
|
+
chunkFileNames: (chunk)=>resourceBindingsChunkFileName(chunk.name) ?? 'static/[name]-[hash].js',
|
|
204
|
+
codeSplitting: {
|
|
205
|
+
groups: [
|
|
206
|
+
resourceBindingsCodeSplittingGroup
|
|
207
|
+
]
|
|
208
|
+
}
|
|
234
209
|
}
|
|
235
|
-
} : {},
|
|
236
|
-
...autoUpdates ? {
|
|
237
|
-
// Expose Rolldown's native MagicString on `renderChunk`'s `meta` so
|
|
238
|
-
// the vendor named-exports plugin can edit chunks without a JS
|
|
239
|
-
// dependency.
|
|
240
|
-
experimental: {
|
|
241
|
-
nativeMagicString: true
|
|
242
|
-
},
|
|
243
|
-
// App-style builds default to `preserveEntrySignatures: false`, which
|
|
244
|
-
// treeshakes the exports off entry chunks. Vendor chunks are loaded by
|
|
245
|
-
// the browser via the import map, so their exports must survive (e.g.
|
|
246
|
-
// styled-components' native ESM exports). `exports-only` keeps exports
|
|
247
|
-
// for entries that have them, while the export-less `sanity` app entry
|
|
248
|
-
// still bundles as before.
|
|
249
|
-
preserveEntrySignatures: 'exports-only'
|
|
250
210
|
} : {}
|
|
251
211
|
}
|
|
252
212
|
};
|
|
@@ -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 ReactCompilerConfig, type UserViteConfig} from '@sanity/cli-core/types'\nimport {isStaging} from '@sanity/cli-core/util'\nimport {\n resourceBindingsChunkFileName,\n resourceBindingsCodeSplittingGroup,\n type WorkbenchExposes,\n workbenchOptimizeDeps,\n workbenchVitePlugins,\n} from '@sanity/workbench-cli/build'\nimport viteReact, {reactCompilerPreset} from '@vitejs/plugin-react'\nimport {Features} from 'lightningcss'\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 * Blueprints build (invoked via `@sanity/runtime-cli`). When set, the\n * resource-bindings module is forced into its own unhashed chunk at the bundle\n * root; otherwise no such chunk is produced.\n */\n isBlueprints?: boolean\n\n /**\n * Whether this is a workbench app (opted in via `defineApplication`). 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 isBlueprints,\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 // Leave native `light-dark()` alone. Lightning CSS's polyfill\n // (`--lightningcss-light`/`--lightningcss-dark` + prefers-color-scheme)\n // ignores Studio theme / `color-scheme`. See lightningcss#873.\n css: {\n lightningcss: {\n exclude: Features.LightDark,\n },\n },\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({\n appId: workbenchAppId,\n cwd,\n entries,\n exposes,\n isApp,\n isBlueprints,\n }),\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 ...(isBlueprints || autoUpdates\n ? {\n output: {\n ...(isBlueprints\n ? {\n // Blueprints only: keep the resource-bindings module in its\n // own unhashed chunk at the bundle root so Brett can rewrite\n // it at deploy. The chunk sizing lives on the group itself\n // (see `resourceBindingsCodeSplittingGroup`), so it only\n // affects the bindings module and not automatic chunking.\n chunkFileNames: (chunk) =>\n resourceBindingsChunkFileName(chunk.name) ?? 'static/[name]-[hash].js',\n codeSplitting: {\n groups: [resourceBindingsCodeSplittingGroup],\n },\n }\n : {}),\n ...(autoUpdates\n ? {\n entryFileNames: (chunk) =>\n vendorChunkNames!.has(chunk.name)\n ? `${VENDOR_DIR}/[name]-[hash].mjs`\n : 'static/[name]-[hash].js',\n exports: 'named',\n }\n : {}),\n },\n }\n : {}),\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 // 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","resourceBindingsChunkFileName","resourceBindingsCodeSplittingGroup","workbenchOptimizeDeps","workbenchVitePlugins","viteReact","reactCompilerPreset","Features","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","isBlueprints","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","css","lightningcss","exclude","LightDark","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","output","chunkFileNames","chunk","codeSplitting","groups","entryFileNames","has","exports","experimental","nativeMagicString","preserveEntrySignatures","config","undefined","transform","compilerOptions","compiler","presets","warning","warn","suppressUnusedImport","code","names","includes","n","length","ids","every","id","finalizeViteConfig","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,SACEC,6BAA6B,EAC7BC,kCAAkC,EAElCC,qBAAqB,EACrBC,oBAAoB,QACf,8BAA6B;AACpC,OAAOC,aAAYC,mBAAmB,QAAO,uBAAsB;AACnE,SAAQC,QAAQ,QAAO,eAAc;AACrC,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,S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;;;;;CAOC,GACD,OAAO,eAAeqC,+BACpB9E,GAAc,EACd2E,aAA2B,EAC3BI,UAA0B;IAE1B,IAAItB,SAASkB;IAEb,IAAI,OAAOI,eAAe,YAAY;QACpClJ,WAAW;QACX4H,SAAS,MAAMsB,WAAWtB,QAAQzD;IACpC,OAAO,IAAI,OAAO+E,eAAe,UAAU;QACzClJ,WAAW;QACX4H,SAAS/H,YAAY+H,QAAQsB;IAC/B;IAEA,OAAOtB;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 resourceBindingsChunkFileName,\n resourceBindingsCodeSplittingGroup,\n type WorkbenchExposes,\n workbenchOptimizeDeps,\n workbenchVitePlugins,\n} from '@sanity/workbench-cli/build'\nimport viteReact, {reactCompilerPreset} from '@vitejs/plugin-react'\nimport {Features} from 'lightningcss'\nimport {\n type ConfigEnv,\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 {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 {sanityVendorChunks} from './vite/plugin-sanity-vendor-chunks.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 * Blueprints build (invoked via `@sanity/runtime-cli`). When set, the\n * resource-bindings module is forced into its own unhashed chunk at the bundle\n * root; otherwise no such chunk is produced.\n */\n isBlueprints?: boolean\n\n /**\n * Whether this is a workbench app (opted in via `defineApplication`). 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 isBlueprints,\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 // Leave native `light-dark()` alone. Lightning CSS's polyfill\n // (`--lightningcss-light`/`--lightningcss-dark` + prefers-color-scheme)\n // ignores Studio theme / `color-scheme`. See lightningcss#873.\n css: {\n lightningcss: {\n exclude: Features.LightDark,\n },\n },\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({\n appId: workbenchAppId,\n autoUpdates,\n cwd,\n entries,\n exposes,\n isApp,\n isBlueprints,\n }),\n {\n ...sanityBuildEntries({autoUpdates, basePath, bridge: false, cwd, isApp}),\n applyToEnvironment: (env) => env.name === 'client',\n } satisfies Plugin,\n ...(autoUpdates ? [sanityVendorChunks(autoUpdates)] : []),\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(sanityVendorChunks(autoUpdates))\n }\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 },\n onwarn: onRolldownWarn,\n ...(isBlueprints\n ? {\n output: {\n // Blueprints only: keep the resource-bindings module in its\n // own unhashed chunk at the bundle root so Brett can rewrite\n // it at deploy. The chunk sizing lives on the group itself\n // (see `resourceBindingsCodeSplittingGroup`), so it only\n // affects the bindings module and not automatic chunking.\n chunkFileNames: (chunk) =>\n resourceBindingsChunkFileName(chunk.name) ?? 'static/[name]-[hash].js',\n codeSplitting: {\n groups: [resourceBindingsCodeSplittingGroup],\n },\n },\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","resourceBindingsChunkFileName","resourceBindingsCodeSplittingGroup","workbenchOptimizeDeps","workbenchVitePlugins","viteReact","reactCompilerPreset","Features","mergeConfig","SANITY_CACHE_DIR","sanitySchemaExtractionPlugin","buildDebug","normalizeBasePath","sanityBuildEntries","sanityFaviconsPlugin","sanityRuntimeRewritePlugin","sanityVendorChunks","getDefaultFaviconsPath","getViteConfig","options","additionalPlugins","autoUpdates","basePath","rawBasePath","cwd","entries","exposes","isApp","isBlueprints","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","css","lightningcss","exclude","LightDark","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","assetsDir","emptyOutDir","rolldownOptions","input","sanity","onwarn","onRolldownWarn","output","chunkFileNames","chunk","codeSplitting","groups","config","undefined","transform","compilerOptions","compiler","presets","warning","warn","suppressUnusedImport","code","names","includes","n","length","ids","every","id","finalizeViteConfig","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,SACEC,6BAA6B,EAC7BC,kCAAkC,EAElCC,qBAAqB,EACrBC,oBAA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AAM,KAAK,GAAG,OAAO;IACzC;IAEA,mFAAmF;IACnF,IAAIP,QAAQQ,GAAG,EAAEC,MAAM,CAACC,KAAOA,GAAGL,QAAQ,CAAC,qBAAqBK,GAAGL,QAAQ,CAAC,sBAC1E,OAAO;IAET,OAAO;AACT;AAEA;;;;;;;;;;;;;;;;;;CAkBC,GACD,OAAO,eAAeM,mBACpBjB,MAAoB,EACpBkB,aAA2B;IAE3B,IAAI,OAAOlB,OAAOzD,KAAK,EAAE+C,iBAAiBC,UAAU,UAAU;QAC5D,MAAM,IAAI4B,UACR;IAEJ;IAEA,IAAI,CAACnB,OAAO3B,IAAI,EAAE;QAChB,MAAM,IAAI+C,MACR;IAEJ;IAEA,OAAO/H,YAAY2G,QAAQ;QACzBzD,OAAO;YACL+C,iBAAiB4B,cAAc3E,KAAK,EAAE+C,mBAAmB,CAAC;QAC5D;IACF;AACF;AAEA;;;;;;;CAOC,GACD,OAAO,eAAe+B,+BACpB5D,GAAc,EACdyD,aAA2B,EAC3BI,UAA0B;IAE1B,IAAItB,SAASkB;IAEb,IAAI,OAAOI,eAAe,YAAY;QACpC9H,WAAW;QACXwG,SAAS,MAAMsB,WAAWtB,QAAQvC;IACpC,OAAO,IAAI,OAAO6D,eAAe,UAAU;QACzC9H,WAAW;QACXwG,SAAS3G,YAAY2G,QAAQsB;IAC/B;IAEA,OAAOtB;AACT"}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
// Builds react, react-dom and styled-components as hashed ESM chunks in `vendor/` for the
|
|
2
|
+
// `index.html` import map. Emitted, not `input`: module federation bootstraps every input as an app.
|
|
3
|
+
import { esmExternalRequirePlugin } from 'vite';
|
|
4
|
+
import { VENDOR_DIR } from '../constants.js';
|
|
5
|
+
import { createExternalFromImportMap } from '../createExternalFromImportMap.js';
|
|
6
|
+
import { createVendorNamedExportsPlugin } from './plugin-sanity-vendor-named-exports.js';
|
|
7
|
+
export function sanityVendorChunks({ imports, vendor }) {
|
|
8
|
+
return {
|
|
9
|
+
applyToEnvironment: (env)=>env.name === 'client' && [
|
|
10
|
+
// Re-expose CommonJS named exports (react, react-dom) as real ESM exports
|
|
11
|
+
// on the emitted vendor chunks; Rolldown only emits `export default` for a
|
|
12
|
+
// CommonJS entry.
|
|
13
|
+
createVendorNamedExportsPlugin(vendor.namesByChunkName),
|
|
14
|
+
// The import map and vendor specifiers are externals of the studio/app
|
|
15
|
+
// bundle, resolved by the browser at runtime. They are handed to
|
|
16
|
+
// `esmExternalRequirePlugin` rather than `rolldownOptions.external`: the
|
|
17
|
+
// plugin both marks them external AND rewrites bundled CommonJS
|
|
18
|
+
// `require()` calls of an external (e.g. react-dom requiring react) into
|
|
19
|
+
// ESM imports, while `rolldownOptions.external` would short-circuit that
|
|
20
|
+
// rewrite and leave a runtime `require` shim that throws in the browser.
|
|
21
|
+
esmExternalRequirePlugin({
|
|
22
|
+
external: createExternalFromImportMap({
|
|
23
|
+
imports: {
|
|
24
|
+
...imports,
|
|
25
|
+
...Object.fromEntries(Object.values(vendor.specifiersByChunkName).map((specifier)=>[
|
|
26
|
+
specifier,
|
|
27
|
+
''
|
|
28
|
+
]))
|
|
29
|
+
}
|
|
30
|
+
})
|
|
31
|
+
}),
|
|
32
|
+
{
|
|
33
|
+
buildStart () {
|
|
34
|
+
for (const [name, id] of Object.entries(vendor.entries)){
|
|
35
|
+
this.emitFile({
|
|
36
|
+
id,
|
|
37
|
+
name,
|
|
38
|
+
type: 'chunk'
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
},
|
|
42
|
+
name: 'sanity/vendor-chunk-entries',
|
|
43
|
+
outputOptions: ({ chunkFileNames = 'static/[name]-[hash].js', ...options })=>({
|
|
44
|
+
...options,
|
|
45
|
+
chunkFileNames: (chunk)=>{
|
|
46
|
+
if (chunk.name in vendor.entries) return `${VENDOR_DIR}/[name]-[hash].mjs`;
|
|
47
|
+
return typeof chunkFileNames === 'function' ? chunkFileNames(chunk) : chunkFileNames;
|
|
48
|
+
},
|
|
49
|
+
exports: 'named'
|
|
50
|
+
})
|
|
51
|
+
}
|
|
52
|
+
],
|
|
53
|
+
configEnvironment: (name)=>name === 'client' ? {
|
|
54
|
+
build: {
|
|
55
|
+
rolldownOptions: {
|
|
56
|
+
// Expose Rolldown's native MagicString on `renderChunk`'s `meta` so
|
|
57
|
+
// the vendor named-exports plugin can edit chunks without a JS
|
|
58
|
+
// dependency.
|
|
59
|
+
experimental: {
|
|
60
|
+
nativeMagicString: true
|
|
61
|
+
},
|
|
62
|
+
// App-style builds default to `preserveEntrySignatures: false`, which
|
|
63
|
+
// treeshakes the exports off entry chunks. Vendor chunks are loaded by
|
|
64
|
+
// the browser via the import map, so their exports must survive (e.g.
|
|
65
|
+
// styled-components' native ESM exports). `exports-only` keeps exports
|
|
66
|
+
// for entries that have them, while the export-less `sanity` app entry
|
|
67
|
+
// still bundles as before.
|
|
68
|
+
preserveEntrySignatures: 'exports-only'
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
} : undefined,
|
|
72
|
+
name: 'sanity/vendor-chunks'
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
//# sourceMappingURL=plugin-sanity-vendor-chunks.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../src/actions/build/vite/plugin-sanity-vendor-chunks.ts"],"sourcesContent":["// Builds react, react-dom and styled-components as hashed ESM chunks in `vendor/` for the\n// `index.html` import map. Emitted, not `input`: module federation bootstraps every input as an app.\nimport {esmExternalRequirePlugin, type Plugin} from 'vite'\n\nimport {type AutoUpdatesBuildConfig} from '../autoUpdates.js'\nimport {VENDOR_DIR} from '../constants.js'\nimport {createExternalFromImportMap} from '../createExternalFromImportMap.js'\nimport {createVendorNamedExportsPlugin} from './plugin-sanity-vendor-named-exports.js'\n\nexport function sanityVendorChunks({imports, vendor}: AutoUpdatesBuildConfig): Plugin {\n return {\n applyToEnvironment: (env) =>\n env.name === 'client' && [\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(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 ...imports,\n ...Object.fromEntries(\n Object.values(vendor.specifiersByChunkName).map((specifier) => [specifier, '']),\n ),\n },\n }),\n }),\n {\n buildStart() {\n for (const [name, id] of Object.entries(vendor.entries)) {\n this.emitFile({id, name, type: 'chunk'})\n }\n },\n name: 'sanity/vendor-chunk-entries',\n outputOptions: ({chunkFileNames = 'static/[name]-[hash].js', ...options}) => ({\n ...options,\n chunkFileNames: (chunk) => {\n if (chunk.name in vendor.entries) return `${VENDOR_DIR}/[name]-[hash].mjs`\n\n return typeof chunkFileNames === 'function' ? chunkFileNames(chunk) : chunkFileNames\n },\n exports: 'named',\n }),\n },\n ],\n configEnvironment: (name) =>\n name === 'client'\n ? {\n build: {\n rolldownOptions: {\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 // 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 : undefined,\n name: 'sanity/vendor-chunks',\n }\n}\n"],"names":["esmExternalRequirePlugin","VENDOR_DIR","createExternalFromImportMap","createVendorNamedExportsPlugin","sanityVendorChunks","imports","vendor","applyToEnvironment","env","name","namesByChunkName","external","Object","fromEntries","values","specifiersByChunkName","map","specifier","buildStart","id","entries","emitFile","type","outputOptions","chunkFileNames","options","chunk","exports","configEnvironment","build","rolldownOptions","experimental","nativeMagicString","preserveEntrySignatures","undefined"],"mappings":"AAAA,0FAA0F;AAC1F,qGAAqG;AACrG,SAAQA,wBAAwB,QAAoB,OAAM;AAG1D,SAAQC,UAAU,QAAO,kBAAiB;AAC1C,SAAQC,2BAA2B,QAAO,oCAAmC;AAC7E,SAAQC,8BAA8B,QAAO,0CAAyC;AAEtF,OAAO,SAASC,mBAAmB,EAACC,OAAO,EAAEC,MAAM,EAAyB;IAC1E,OAAO;QACLC,oBAAoB,CAACC,MACnBA,IAAIC,IAAI,KAAK,YAAY;gBACvB,0EAA0E;gBAC1E,2EAA2E;gBAC3E,kBAAkB;gBAClBN,+BAA+BG,OAAOI,gBAAgB;gBACtD,uEAAuE;gBACvE,iEAAiE;gBACjE,yEAAyE;gBACzE,gEAAgE;gBAChE,yEAAyE;gBACzE,yEAAyE;gBACzE,yEAAyE;gBACzEV,yBAAyB;oBACvBW,UAAUT,4BAA4B;wBACpCG,SAAS;4BACP,GAAGA,OAAO;4BACV,GAAGO,OAAOC,WAAW,CACnBD,OAAOE,MAAM,CAACR,OAAOS,qBAAqB,EAAEC,GAAG,CAAC,CAACC,YAAc;oCAACA;oCAAW;iCAAG,EAC/E;wBACH;oBACF;gBACF;gBACA;oBACEC;wBACE,KAAK,MAAM,CAACT,MAAMU,GAAG,IAAIP,OAAOQ,OAAO,CAACd,OAAOc,OAAO,EAAG;4BACvD,IAAI,CAACC,QAAQ,CAAC;gCAACF;gCAAIV;gCAAMa,MAAM;4BAAO;wBACxC;oBACF;oBACAb,MAAM;oBACNc,eAAe,CAAC,EAACC,iBAAiB,yBAAyB,EAAE,GAAGC,SAAQ,GAAM,CAAA;4BAC5E,GAAGA,OAAO;4BACVD,gBAAgB,CAACE;gCACf,IAAIA,MAAMjB,IAAI,IAAIH,OAAOc,OAAO,EAAE,OAAO,GAAGnB,WAAW,kBAAkB,CAAC;gCAE1E,OAAO,OAAOuB,mBAAmB,aAAaA,eAAeE,SAASF;4BACxE;4BACAG,SAAS;wBACX,CAAA;gBACF;aACD;QACHC,mBAAmB,CAACnB,OAClBA,SAAS,WACL;gBACEoB,OAAO;oBACLC,iBAAiB;wBACf,oEAAoE;wBACpE,+DAA+D;wBAC/D,cAAc;wBACdC,cAAc;4BAACC,mBAAmB;wBAAI;wBACtC,sEAAsE;wBACtE,uEAAuE;wBACvE,sEAAsE;wBACtE,uEAAuE;wBACvE,uEAAuE;wBACvE,2BAA2B;wBAC3BC,yBAAyB;oBAC3B;gBACF;YACF,IACAC;QACNzB,MAAM;IACR;AACF"}
|
|
@@ -40,6 +40,9 @@ const sanitizeIconPath = new URL('sanitizeIcon.js', import.meta.url).href;
|
|
|
40
40
|
* same trusted subset of SVG markup.
|
|
41
41
|
* @internal
|
|
42
42
|
*/ export async function readIconFromPath(workDir, iconPath) {
|
|
43
|
+
if (!/\.svg$/i.test(iconPath)) {
|
|
44
|
+
throw new Error(`Icon path "${iconPath}" must point to an .svg file.`);
|
|
45
|
+
}
|
|
43
46
|
const resolvedPath = resolve(workDir, iconPath);
|
|
44
47
|
const pathRelativeToWorkDir = relative(workDir, resolvedPath);
|
|
45
48
|
if (pathRelativeToWorkDir.startsWith('..')) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/actions/manifest/extractCoreAppManifest.ts"],"sourcesContent":["import {readFile} from 'node:fs/promises'\nimport {relative, resolve} from 'node:path'\n\nimport {doImport, getCliConfigUncached} from '@sanity/cli-core'\nimport {getErrorMessage} from '@sanity/cli-core/errors'\nimport {spinner} from '@sanity/cli-core/ux'\nimport {isWorkbenchApp, isWorkbenchConfig} from '@sanity/workbench-cli'\n\nimport {type sanitizeIcon as sanitizeIconFn} from './sanitizeIcon.js'\nimport {type CoreAppManifest, coreAppManifestSchema} from './types.js'\n\ninterface ExtractCoreAppManifestOptions {\n workDir: string\n}\n\n/**\n * The title change a deploy would sync from the manifest to the user\n * application, or null when the titles already match (or none is set).\n *\n * @internal\n */\nexport function resolveTitleUpdate(\n manifest: CoreAppManifest | undefined,\n application: {title: string | null},\n): {from: string | null; to: string} | null {\n if (manifest?.title === undefined || manifest.title === application.title) {\n return null\n }\n return {from: application.title, to: manifest.title}\n}\n\nconst sanitizeIconPath = new URL('sanitizeIcon.js', import.meta.url).href\n\n/**\n * Lazy-load {@link sanitizeIconFn} so DOMPurify and its jsdom environment stay\n * out of the CLI's eager import graph. The studio manifest\n * resolver lazy-loads its icon machinery for the same reason; this path runs in\n * the main process (not the manifest worker), so only an app deploy that\n * actually has an icon pays the cost.\n */\nasync function lazySanitizeIcon(): Promise<typeof sanitizeIconFn> {\n const mod = await doImport(sanitizeIconPath)\n return mod.sanitizeIcon\n}\n\n/**\n * Resolves app.icon from config (a file path) to a sanitized SVG string. Used\n * both for the manifest and, on deploy, for the icon shipped to Brett — the\n * manifest expects the SVG inline, not a path.\n *\n * The file is sanitized through the same allowlist as the studio manifest's\n * icon resolver (see {@link lazySanitizeIcon}) so both manifest paths inline the\n * same trusted subset of SVG markup.\n * @internal\n */\nexport async function readIconFromPath(workDir: string, iconPath: string): Promise<string> {\n const resolvedPath = resolve(workDir, iconPath)\n const pathRelativeToWorkDir = relative(workDir, resolvedPath)\n if (pathRelativeToWorkDir.startsWith('..')) {\n throw new Error(\n `Icon path \"${iconPath}\" resolves outside the project directory and is not allowed.`,\n )\n }\n\n let content: string\n try {\n content = await readFile(resolvedPath, 'utf8')\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n throw new Error(\n `Could not read icon file at \"${iconPath}\" (resolved: ${resolvedPath}): ${message}`,\n {cause: err},\n )\n }\n\n const trimmed = content.trim()\n if (!/<svg[\\s>]/i.test(trimmed)) {\n throw new Error(\n `Icon file at \"${iconPath}\" does not contain an SVG element. App manifest icons must be SVG files.`,\n )\n }\n\n const sanitizeIcon = await lazySanitizeIcon()\n return sanitizeIcon(trimmed)\n}\n\n/**\n * Unlike studio manifest extraction, skips schema/tool parsing. The config's\n * `app.icon` is a file path; its content is read and inlined in the manifest.\n */\nexport async function extractCoreAppManifest(\n options: ExtractCoreAppManifestOptions,\n): Promise<CoreAppManifest | undefined> {\n const {workDir} = options\n const {app} = await getCliConfigUncached(workDir)\n if (!app) {\n return undefined\n }\n\n // A config-only project (the Media Library) carries no icon or title and has\n // no manifest by design — skip silently rather than warn about a missing one.\n if (isWorkbenchConfig(app)) {\n return undefined\n }\n\n const spin = spinner('Extracting manifest').start()\n\n try {\n let icon: string | undefined\n if (app.icon) {\n icon = await readIconFromPath(workDir, app.icon)\n }\n\n if (!icon && !app.title) {\n spin.info('Manifest creation skipped: no icon or title found in app configuration')\n return undefined\n }\n\n const workbench = isWorkbenchApp(app) ? app : undefined\n\n const manifest: CoreAppManifest = coreAppManifestSchema.parse({\n version: '1',\n ...(workbench?.dock ? {dock: workbench.dock} : {}),\n ...(icon ? {icon} : {}),\n ...(app.title ? {title: app.title} : {}),\n ...(workbench?.slug ? {slug: workbench.slug} : {}),\n })\n\n spin.succeed(`Extracted manifest`)\n\n return manifest\n } catch (err) {\n const message = getErrorMessage(err)\n spin.fail(message)\n throw err\n }\n}\n"],"names":["readFile","relative","resolve","doImport","getCliConfigUncached","getErrorMessage","spinner","isWorkbenchApp","isWorkbenchConfig","coreAppManifestSchema","resolveTitleUpdate","manifest","application","title","undefined","from","to","sanitizeIconPath","URL","url","href","lazySanitizeIcon","mod","sanitizeIcon","readIconFromPath","workDir","iconPath","resolvedPath","pathRelativeToWorkDir","startsWith","
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/manifest/extractCoreAppManifest.ts"],"sourcesContent":["import {readFile} from 'node:fs/promises'\nimport {relative, resolve} from 'node:path'\n\nimport {doImport, getCliConfigUncached} from '@sanity/cli-core'\nimport {getErrorMessage} from '@sanity/cli-core/errors'\nimport {spinner} from '@sanity/cli-core/ux'\nimport {isWorkbenchApp, isWorkbenchConfig} from '@sanity/workbench-cli'\n\nimport {type sanitizeIcon as sanitizeIconFn} from './sanitizeIcon.js'\nimport {type CoreAppManifest, coreAppManifestSchema} from './types.js'\n\ninterface ExtractCoreAppManifestOptions {\n workDir: string\n}\n\n/**\n * The title change a deploy would sync from the manifest to the user\n * application, or null when the titles already match (or none is set).\n *\n * @internal\n */\nexport function resolveTitleUpdate(\n manifest: CoreAppManifest | undefined,\n application: {title: string | null},\n): {from: string | null; to: string} | null {\n if (manifest?.title === undefined || manifest.title === application.title) {\n return null\n }\n return {from: application.title, to: manifest.title}\n}\n\nconst sanitizeIconPath = new URL('sanitizeIcon.js', import.meta.url).href\n\n/**\n * Lazy-load {@link sanitizeIconFn} so DOMPurify and its jsdom environment stay\n * out of the CLI's eager import graph. The studio manifest\n * resolver lazy-loads its icon machinery for the same reason; this path runs in\n * the main process (not the manifest worker), so only an app deploy that\n * actually has an icon pays the cost.\n */\nasync function lazySanitizeIcon(): Promise<typeof sanitizeIconFn> {\n const mod = await doImport(sanitizeIconPath)\n return mod.sanitizeIcon\n}\n\n/**\n * Resolves app.icon from config (a file path) to a sanitized SVG string. Used\n * both for the manifest and, on deploy, for the icon shipped to Brett — the\n * manifest expects the SVG inline, not a path.\n *\n * The file is sanitized through the same allowlist as the studio manifest's\n * icon resolver (see {@link lazySanitizeIcon}) so both manifest paths inline the\n * same trusted subset of SVG markup.\n * @internal\n */\nexport async function readIconFromPath(workDir: string, iconPath: string): Promise<string> {\n if (!/\\.svg$/i.test(iconPath)) {\n throw new Error(`Icon path \"${iconPath}\" must point to an .svg file.`)\n }\n\n const resolvedPath = resolve(workDir, iconPath)\n const pathRelativeToWorkDir = relative(workDir, resolvedPath)\n if (pathRelativeToWorkDir.startsWith('..')) {\n throw new Error(\n `Icon path \"${iconPath}\" resolves outside the project directory and is not allowed.`,\n )\n }\n\n let content: string\n try {\n content = await readFile(resolvedPath, 'utf8')\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n throw new Error(\n `Could not read icon file at \"${iconPath}\" (resolved: ${resolvedPath}): ${message}`,\n {cause: err},\n )\n }\n\n const trimmed = content.trim()\n if (!/<svg[\\s>]/i.test(trimmed)) {\n throw new Error(\n `Icon file at \"${iconPath}\" does not contain an SVG element. App manifest icons must be SVG files.`,\n )\n }\n\n const sanitizeIcon = await lazySanitizeIcon()\n return sanitizeIcon(trimmed)\n}\n\n/**\n * Unlike studio manifest extraction, skips schema/tool parsing. The config's\n * `app.icon` is a file path; its content is read and inlined in the manifest.\n */\nexport async function extractCoreAppManifest(\n options: ExtractCoreAppManifestOptions,\n): Promise<CoreAppManifest | undefined> {\n const {workDir} = options\n const {app} = await getCliConfigUncached(workDir)\n if (!app) {\n return undefined\n }\n\n // A config-only project (the Media Library) carries no icon or title and has\n // no manifest by design — skip silently rather than warn about a missing one.\n if (isWorkbenchConfig(app)) {\n return undefined\n }\n\n const spin = spinner('Extracting manifest').start()\n\n try {\n let icon: string | undefined\n if (app.icon) {\n icon = await readIconFromPath(workDir, app.icon)\n }\n\n if (!icon && !app.title) {\n spin.info('Manifest creation skipped: no icon or title found in app configuration')\n return undefined\n }\n\n const workbench = isWorkbenchApp(app) ? app : undefined\n\n const manifest: CoreAppManifest = coreAppManifestSchema.parse({\n version: '1',\n ...(workbench?.dock ? {dock: workbench.dock} : {}),\n ...(icon ? {icon} : {}),\n ...(app.title ? {title: app.title} : {}),\n ...(workbench?.slug ? {slug: workbench.slug} : {}),\n })\n\n spin.succeed(`Extracted manifest`)\n\n return manifest\n } catch (err) {\n const message = getErrorMessage(err)\n spin.fail(message)\n throw err\n }\n}\n"],"names":["readFile","relative","resolve","doImport","getCliConfigUncached","getErrorMessage","spinner","isWorkbenchApp","isWorkbenchConfig","coreAppManifestSchema","resolveTitleUpdate","manifest","application","title","undefined","from","to","sanitizeIconPath","URL","url","href","lazySanitizeIcon","mod","sanitizeIcon","readIconFromPath","workDir","iconPath","test","Error","resolvedPath","pathRelativeToWorkDir","startsWith","content","err","message","String","cause","trimmed","trim","extractCoreAppManifest","options","app","spin","start","icon","info","workbench","parse","version","dock","slug","succeed","fail"],"mappings":"AAAA,SAAQA,QAAQ,QAAO,mBAAkB;AACzC,SAAQC,QAAQ,EAAEC,OAAO,QAAO,YAAW;AAE3C,SAAQC,QAAQ,EAAEC,oBAAoB,QAAO,mBAAkB;AAC/D,SAAQC,eAAe,QAAO,0BAAyB;AACvD,SAAQC,OAAO,QAAO,sBAAqB;AAC3C,SAAQC,cAAc,EAAEC,iBAAiB,QAAO,wBAAuB;AAGvE,SAA8BC,qBAAqB,QAAO,aAAY;AAMtE;;;;;CAKC,GACD,OAAO,SAASC,mBACdC,QAAqC,EACrCC,WAAmC;IAEnC,IAAID,UAAUE,UAAUC,aAAaH,SAASE,KAAK,KAAKD,YAAYC,KAAK,EAAE;QACzE,OAAO;IACT;IACA,OAAO;QAACE,MAAMH,YAAYC,KAAK;QAAEG,IAAIL,SAASE,KAAK;IAAA;AACrD;AAEA,MAAMI,mBAAmB,IAAIC,IAAI,mBAAmB,YAAYC,GAAG,EAAEC,IAAI;AAEzE;;;;;;CAMC,GACD,eAAeC;IACb,MAAMC,MAAM,MAAMnB,SAASc;IAC3B,OAAOK,IAAIC,YAAY;AACzB;AAEA;;;;;;;;;CASC,GACD,OAAO,eAAeC,iBAAiBC,OAAe,EAAEC,QAAgB;IACtE,IAAI,CAAC,UAAUC,IAAI,CAACD,WAAW;QAC7B,MAAM,IAAIE,MAAM,CAAC,WAAW,EAAEF,SAAS,6BAA6B,CAAC;IACvE;IAEA,MAAMG,eAAe3B,QAAQuB,SAASC;IACtC,MAAMI,wBAAwB7B,SAASwB,SAASI;IAChD,IAAIC,sBAAsBC,UAAU,CAAC,OAAO;QAC1C,MAAM,IAAIH,MACR,CAAC,WAAW,EAAEF,SAAS,4DAA4D,CAAC;IAExF;IAEA,IAAIM;IACJ,IAAI;QACFA,UAAU,MAAMhC,SAAS6B,cAAc;IACzC,EAAE,OAAOI,KA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,CAAC;YACvC,GAAIiC,WAAWI,OAAO;gBAACA,MAAMJ,UAAUI,IAAI;YAAA,IAAI,CAAC,CAAC;QACnD;QAEAR,KAAKS,OAAO,CAAC,CAAC,kBAAkB,CAAC;QAEjC,OAAOxC;IACT,EAAE,OAAOsB,KAAK;QACZ,MAAMC,UAAU7B,gBAAgB4B;QAChCS,KAAKU,IAAI,CAAClB;QACV,MAAMD;IACR;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sanity/cli-build",
|
|
3
|
-
"version": "7.
|
|
3
|
+
"version": "7.1.1",
|
|
4
4
|
"description": "Internal Sanity package for building studios and apps",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cli",
|
|
@@ -52,13 +52,13 @@
|
|
|
52
52
|
"dependencies": {
|
|
53
53
|
"@oclif/core": "^4.11.14",
|
|
54
54
|
"@rolldown/plugin-babel": "^0.2.4",
|
|
55
|
-
"@sanity/cli-core": "^3.14.
|
|
55
|
+
"@sanity/cli-core": "^3.14.1",
|
|
56
56
|
"@sanity/generate-help-url": "^4.0.0",
|
|
57
|
-
"@sanity/schema": "^6.
|
|
57
|
+
"@sanity/schema": "^6.22.0",
|
|
58
58
|
"@sanity/telemetry": "^1.1.0",
|
|
59
|
-
"@sanity/types": "^6.
|
|
60
|
-
"@sanity/workbench-cli": "^2.
|
|
61
|
-
"@vitejs/plugin-react": "^6.1
|
|
59
|
+
"@sanity/types": "^6.22.0",
|
|
60
|
+
"@sanity/workbench-cli": "^2.15.1",
|
|
61
|
+
"@vitejs/plugin-react": "^6.2.1",
|
|
62
62
|
"chokidar": "^5.0.0",
|
|
63
63
|
"cjs-module-lexer": "^2.2.1",
|
|
64
64
|
"dompurify": "^3.4.14",
|
|
@@ -72,17 +72,17 @@
|
|
|
72
72
|
"react": "^19.3.0",
|
|
73
73
|
"react-is": "^19.3.0",
|
|
74
74
|
"semver": "^7.8.1",
|
|
75
|
-
"vite": "^8.3.
|
|
75
|
+
"vite": "^8.3.6",
|
|
76
76
|
"zod": "^4.5.2"
|
|
77
77
|
},
|
|
78
78
|
"devDependencies": {
|
|
79
79
|
"@eslint/compat": "^2.1.0",
|
|
80
80
|
"@repo/package.config": "0.0.1",
|
|
81
81
|
"@repo/tsconfig": "3.70.0",
|
|
82
|
-
"@sanity/cli-test": "24.0.
|
|
82
|
+
"@sanity/cli-test": "24.0.2",
|
|
83
83
|
"@sanity/eslint-config-cli": "^1.1.3",
|
|
84
84
|
"@sanity/pkg-utils": "^12.3.4",
|
|
85
|
-
"@sanity/ui": "^4.
|
|
85
|
+
"@sanity/ui": "^4.4.10",
|
|
86
86
|
"@swc/cli": "^0.8.1",
|
|
87
87
|
"@swc/core": "^1.15.43",
|
|
88
88
|
"@types/jsdom": "^28.0.3",
|
|
@@ -93,21 +93,21 @@
|
|
|
93
93
|
"@types/react-dom": "^19.3.0",
|
|
94
94
|
"@types/react-is": "^19.2.0",
|
|
95
95
|
"@types/semver": "^7.7.1",
|
|
96
|
-
"@vitest/coverage-istanbul": "^
|
|
96
|
+
"@vitest/coverage-istanbul": "^5.1.0",
|
|
97
97
|
"babel-plugin-react-compiler": "^1.0.0",
|
|
98
98
|
"eslint": "^10.7.0",
|
|
99
99
|
"magic-string": "^0.30.21",
|
|
100
|
-
"oxc-transform-react": "^0.
|
|
100
|
+
"oxc-transform-react": "^0.156.0",
|
|
101
101
|
"publint": "^0.3.21",
|
|
102
|
-
"sanity": "^6.
|
|
102
|
+
"sanity": "^6.22.0",
|
|
103
103
|
"styled-components": "^6.4.3",
|
|
104
104
|
"typescript": "^6.0.3",
|
|
105
|
-
"vitest": "^
|
|
105
|
+
"vitest": "^5.1.0"
|
|
106
106
|
},
|
|
107
107
|
"peerDependencies": {
|
|
108
108
|
"babel-plugin-react-compiler": "*",
|
|
109
109
|
"oxc-transform-react": "*",
|
|
110
|
-
"sanity": "^6.
|
|
110
|
+
"sanity": "^6.22.0"
|
|
111
111
|
},
|
|
112
112
|
"peerDependenciesMeta": {
|
|
113
113
|
"babel-plugin-react-compiler": {
|