@sanity/cli 6.4.0 → 6.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/README.md +14 -8
  2. package/dist/actions/build/buildApp.js +12 -4
  3. package/dist/actions/build/buildApp.js.map +1 -1
  4. package/dist/actions/build/buildStaticFiles.js +3 -1
  5. package/dist/actions/build/buildStaticFiles.js.map +1 -1
  6. package/dist/actions/build/buildStudio.js +29 -7
  7. package/dist/actions/build/buildStudio.js.map +1 -1
  8. package/dist/actions/build/buildVendorDependencies.js +7 -7
  9. package/dist/actions/build/buildVendorDependencies.js.map +1 -1
  10. package/dist/actions/build/checkRequiredDependencies.js +4 -4
  11. package/dist/actions/build/checkRequiredDependencies.js.map +1 -1
  12. package/dist/actions/build/checkStudioDependencyVersions.js +9 -9
  13. package/dist/actions/build/checkStudioDependencyVersions.js.map +1 -1
  14. package/dist/actions/build/getAutoUpdatesImportMap.js +9 -0
  15. package/dist/actions/build/getAutoUpdatesImportMap.js.map +1 -1
  16. package/dist/actions/build/getViteConfig.js +2 -1
  17. package/dist/actions/build/getViteConfig.js.map +1 -1
  18. package/dist/actions/build/renderDocument.js.map +1 -1
  19. package/dist/actions/build/renderDocumentWorker/addTimestampImportMapScriptToHtml.js +34 -14
  20. package/dist/actions/build/renderDocumentWorker/addTimestampImportMapScriptToHtml.js.map +1 -1
  21. package/dist/actions/build/renderDocumentWorker/getDocumentHtml.js +2 -2
  22. package/dist/actions/build/renderDocumentWorker/getDocumentHtml.js.map +1 -1
  23. package/dist/actions/build/renderDocumentWorker/renderDocumentWorker.js +2 -2
  24. package/dist/actions/build/renderDocumentWorker/renderDocumentWorker.js.map +1 -1
  25. package/dist/actions/codemods/reactIconsV3.js +2 -2
  26. package/dist/actions/codemods/reactIconsV3.js.map +1 -1
  27. package/dist/actions/dev/startStudioDevServer.js +2 -2
  28. package/dist/actions/dev/startStudioDevServer.js.map +1 -1
  29. package/dist/actions/doctor/types.js.map +1 -1
  30. package/dist/actions/graphql/resolveGraphQLApisFromWorkspaces.js.map +1 -1
  31. package/dist/actions/init/bootstrapTemplate.js.map +1 -1
  32. package/dist/actions/init/checkNextJsReactCompatibility.js +3 -3
  33. package/dist/actions/init/checkNextJsReactCompatibility.js.map +1 -1
  34. package/dist/actions/init/initAction.js +287 -0
  35. package/dist/actions/init/initAction.js.map +1 -0
  36. package/dist/actions/init/initApp.js +7 -16
  37. package/dist/actions/init/initApp.js.map +1 -1
  38. package/dist/actions/init/initError.js +10 -0
  39. package/dist/actions/init/initError.js.map +1 -0
  40. package/dist/actions/init/initHelpers.js +3 -12
  41. package/dist/actions/init/initHelpers.js.map +1 -1
  42. package/dist/actions/init/initNextJs.js +17 -20
  43. package/dist/actions/init/initNextJs.js.map +1 -1
  44. package/dist/actions/init/initStudio.js +11 -20
  45. package/dist/actions/init/initStudio.js.map +1 -1
  46. package/dist/actions/init/plan/getPlan.js +15 -0
  47. package/dist/actions/init/plan/getPlan.js.map +1 -0
  48. package/dist/actions/init/plan/verifyCoupon.js +35 -0
  49. package/dist/actions/init/plan/verifyCoupon.js.map +1 -0
  50. package/dist/actions/init/plan/verifyPlan.js +34 -0
  51. package/dist/actions/init/plan/verifyPlan.js.map +1 -0
  52. package/dist/actions/init/project/createProjectFromName.js +44 -0
  53. package/dist/actions/init/project/createProjectFromName.js.map +1 -0
  54. package/dist/actions/init/project/getOrCreateDataset.js +126 -0
  55. package/dist/actions/init/project/getOrCreateDataset.js.map +1 -0
  56. package/dist/actions/init/project/getOrCreateProject.js +128 -0
  57. package/dist/actions/init/project/getOrCreateProject.js.map +1 -0
  58. package/dist/actions/init/project/getProjectDetails.js +87 -0
  59. package/dist/actions/init/project/getProjectDetails.js.map +1 -0
  60. package/dist/actions/init/project/getProjectOutputPath.js +17 -0
  61. package/dist/actions/init/project/getProjectOutputPath.js.map +1 -0
  62. package/dist/actions/init/project/promptForAppTemplateSetup.js +112 -0
  63. package/dist/actions/init/project/promptForAppTemplateSetup.js.map +1 -0
  64. package/dist/actions/init/project/promptForProjectCreation.js +40 -0
  65. package/dist/actions/init/project/promptForProjectCreation.js.map +1 -0
  66. package/dist/actions/init/project/promptUserForNewOrganization.js +12 -0
  67. package/dist/actions/init/project/promptUserForNewOrganization.js.map +1 -0
  68. package/dist/actions/init/project/promptUserForOrganization.js +38 -0
  69. package/dist/actions/init/project/promptUserForOrganization.js.map +1 -0
  70. package/dist/actions/init/scaffoldTemplate.js +23 -29
  71. package/dist/actions/init/scaffoldTemplate.js.map +1 -1
  72. package/dist/actions/init/types.js +47 -1
  73. package/dist/actions/init/types.js.map +1 -1
  74. package/dist/actions/manifest/types.js +0 -1
  75. package/dist/actions/manifest/types.js.map +1 -1
  76. package/dist/actions/versions/buildPackageArray.js +2 -2
  77. package/dist/actions/versions/buildPackageArray.js.map +1 -1
  78. package/dist/actions/versions/findSanityModulesVersions.js +3 -3
  79. package/dist/actions/versions/findSanityModulesVersions.js.map +1 -1
  80. package/dist/commands/datasets/copy.js.map +1 -1
  81. package/dist/commands/init.js +11 -911
  82. package/dist/commands/init.js.map +1 -1
  83. package/dist/server/vite/plugin-sanity-build-entries.js +2 -1
  84. package/dist/server/vite/plugin-sanity-build-entries.js.map +1 -1
  85. package/dist/services/datasets.js.map +1 -1
  86. package/dist/telemetry/init.telemetry.js.map +1 -1
  87. package/dist/util/compareDependencyVersions.js +4 -4
  88. package/dist/util/compareDependencyVersions.js.map +1 -1
  89. package/dist/util/createExpiringConfig.js +1 -1
  90. package/dist/util/createExpiringConfig.js.map +1 -1
  91. package/dist/util/packageManager/installationInfo/analyzeIssues.js +7 -7
  92. package/dist/util/packageManager/installationInfo/analyzeIssues.js.map +1 -1
  93. package/dist/util/packageManager/installationInfo/types.js.map +1 -1
  94. package/dist/util/packageManager/packageManagerChoice.js +2 -2
  95. package/dist/util/packageManager/packageManagerChoice.js.map +1 -1
  96. package/dist/util/packageManager/preferredPm.js +106 -0
  97. package/dist/util/packageManager/preferredPm.js.map +1 -0
  98. package/oclif.manifest.json +526 -526
  99. package/package.json +23 -22
package/README.md CHANGED
@@ -251,7 +251,7 @@ EXAMPLES
251
251
 
252
252
  ## `sanity blueprints add TYPE`
253
253
 
254
- Add a function resource to a Blueprint
254
+ [deprecated] Use "functions add" instead
255
255
 
256
256
  ```
257
257
  USAGE
@@ -283,12 +283,13 @@ FLAGS
283
283
  --[no-]validate-resources Validate resources
284
284
 
285
285
  DESCRIPTION
286
- Add a function resource to a Blueprint
286
+ [deprecated] Use "functions add" instead
287
287
 
288
- Scaffolds a new Sanity Function in your Blueprint. Functions are serverless handlers triggered by document events
289
- (create, update, delete, publish) or media library events.
288
+ This command is deprecated. Use "functions add" instead.
290
289
 
291
- After adding a function, use 'functions dev' to test locally, then 'blueprints deploy' to publish it.
290
+ Equivalent usage:
291
+ $ sanity functions add
292
+ $ sanity functions add --name my-function --type document-create
292
293
 
293
294
  EXAMPLES
294
295
  $ sanity blueprints add function
@@ -482,7 +483,7 @@ Initialize a Blueprint and create a remote Stack
482
483
 
483
484
  ```
484
485
  USAGE
485
- $ sanity blueprints init [DIR] [--json] [--validate-resources] [--verbose] [--dir <value>] [--example <value> |
486
+ $ sanity blueprints init [DIR] [--json] [--validate-resources] [--dir <value>] [--example <value> |
486
487
  --blueprint-type json|js|ts | --stack-id <value> | --stack-name <value>] [--project-id <value>] [--organization-id
487
488
  <value>]
488
489
 
@@ -500,7 +501,6 @@ FLAGS
500
501
  --stack-id=<value> Existing Stack ID used to scope local Blueprint
501
502
  --stack-name=<value> Name to use for a new Stack provisioned during initialization
502
503
  --[no-]validate-resources Validate resources
503
- --verbose Verbose output
504
504
 
505
505
  DESCRIPTION
506
506
  Initialize a Blueprint and create a remote Stack
@@ -589,9 +589,11 @@ List remote Stack deployments for your project or organization
589
589
 
590
590
  ```
591
591
  USAGE
592
- $ sanity blueprints stacks [--json] [--validate-resources] [--project-id <value> | --organization-id <value>]
592
+ $ sanity blueprints stacks [--json] [--validate-resources] [--project-id <value> | --organization-id <value> |
593
+ --include-projects]
593
594
 
594
595
  FLAGS
596
+ --include-projects Include Stacks from all projects within the organization. Requires --organization-id.
595
597
  --json Format output as json
596
598
  --organization-id=<value> Sanity organization ID used to scope Blueprint and Stack
597
599
  --project-id=<value> Sanity project ID used to scope Blueprint and Stack
@@ -605,12 +607,16 @@ DESCRIPTION
605
607
  Use this to discover existing Stacks you can scope a local Blueprint to (using 'blueprints config --edit'), or to
606
608
  audit what's deployed across your project.
607
609
 
610
+ Use --include-projects with --organization-id to also list Stacks from all projects within the organization.
611
+
608
612
  EXAMPLES
609
613
  $ sanity blueprints stacks
610
614
 
611
615
  $ sanity blueprints stacks --project-id <projectId>
612
616
 
613
617
  $ sanity blueprints stacks --organization-id <organizationId>
618
+
619
+ $ sanity blueprints stacks --organization-id <organizationId> --include-projects
614
620
  ```
615
621
 
616
622
  ## `sanity build [OUTPUTDIR]`
@@ -3,7 +3,7 @@ import path from 'node:path';
3
3
  import { styleText } from 'node:util';
4
4
  import { getCliTelemetry, getTimer, isInteractive } from '@sanity/cli-core';
5
5
  import { confirm, logSymbols, spinner } from '@sanity/cli-core/ux';
6
- import semver from 'semver';
6
+ import { parse as semverParse } from 'semver';
7
7
  import { AppBuildTrace } from '../../telemetry/build.telemetry.js';
8
8
  import { getAppId } from '../../util/appId.js';
9
9
  import { compareDependencyVersions } from '../../util/compareDependencyVersions.js';
@@ -15,7 +15,7 @@ import { buildStaticFiles } from './buildStaticFiles.js';
15
15
  import { buildVendorDependencies } from './buildVendorDependencies.js';
16
16
  import { determineBasePath } from './determineBasePath.js';
17
17
  import { getAppEnvVars } from './getAppEnvVars.js';
18
- import { getAutoUpdatesImportMap } from './getAutoUpdatesImportMap.js';
18
+ import { getAutoUpdatesCssUrls, getAutoUpdatesImportMap } from './getAutoUpdatesImportMap.js';
19
19
  import { handlePrereleaseVersions } from './handlePrereleaseVersions.js';
20
20
  /**
21
21
  * Build the Sanity app.
@@ -38,9 +38,10 @@ import { handlePrereleaseVersions } from './handlePrereleaseVersions.js';
38
38
  return;
39
39
  }
40
40
  let autoUpdatesImports = {};
41
+ let autoUpdatesCssUrls = [];
41
42
  if (autoUpdatesEnabled) {
42
43
  // Get the clean version without build metadata: https://semver.org/#spec-item-10
43
- const cleanSDKVersion = semver.parse(installedSdkVersion)?.version;
44
+ const cleanSDKVersion = semverParse(installedSdkVersion)?.version;
44
45
  if (!cleanSDKVersion) {
45
46
  output.error(`Failed to parse installed SDK version: ${installedSdkVersion}`, {
46
47
  exit: 1
@@ -48,7 +49,7 @@ import { handlePrereleaseVersions } from './handlePrereleaseVersions.js';
48
49
  return;
49
50
  }
50
51
  // Sanity might not be installed, but if it is, we want to auto update it.
51
- const cleanSanityVersion = semver.parse(installedSanityVersion)?.version;
52
+ const cleanSanityVersion = semverParse(installedSanityVersion)?.version;
52
53
  const autoUpdatedPackages = [
53
54
  {
54
55
  name: '@sanity/sdk',
@@ -60,6 +61,7 @@ import { handlePrereleaseVersions } from './handlePrereleaseVersions.js';
60
61
  },
61
62
  ...cleanSanityVersion ? [
62
63
  {
64
+ cssFile: 'index.css',
63
65
  name: 'sanity',
64
66
  version: cleanSanityVersion
65
67
  }
@@ -68,6 +70,9 @@ import { handlePrereleaseVersions } from './handlePrereleaseVersions.js';
68
70
  autoUpdatesImports = getAutoUpdatesImportMap(autoUpdatedPackages, {
69
71
  appId
70
72
  });
73
+ autoUpdatesCssUrls = getAutoUpdatesCssUrls(autoUpdatedPackages, {
74
+ appId
75
+ });
71
76
  output.log(`${logSymbols.info} Building with auto-updates enabled`);
72
77
  // Warn if auto updates enabled but no appId configured.
73
78
  // Skip when called from deploy, since deploy handles appId itself
@@ -89,6 +94,7 @@ import { handlePrereleaseVersions } from './handlePrereleaseVersions.js';
89
94
  unresolvedPrerelease
90
95
  });
91
96
  autoUpdatesImports = {};
97
+ autoUpdatesCssUrls = [];
92
98
  autoUpdatesEnabled = false;
93
99
  }
94
100
  if (mismatched.length > 0 && autoUpdatesEnabled) {
@@ -159,6 +165,7 @@ import { handlePrereleaseVersions } from './handlePrereleaseVersions.js';
159
165
  timer.start('bundleStudio');
160
166
  const bundle = await buildStaticFiles({
161
167
  appTitle: cliConfig && 'app' in cliConfig ? cliConfig.app?.title : undefined,
168
+ autoUpdatesCssUrls: autoUpdatesCssUrls.length > 0 ? autoUpdatesCssUrls : undefined,
162
169
  basePath,
163
170
  cwd: workDir,
164
171
  entry: cliConfig && 'app' in cliConfig ? cliConfig.app?.entry : undefined,
@@ -167,6 +174,7 @@ import { handlePrereleaseVersions } from './handlePrereleaseVersions.js';
167
174
  minify: Boolean(flags.minify),
168
175
  outputDir,
169
176
  reactCompiler: cliConfig && 'reactCompiler' in cliConfig ? cliConfig.reactCompiler : undefined,
177
+ schemaExtraction: cliConfig?.schemaExtraction,
170
178
  sourceMap: Boolean(flags['source-maps']),
171
179
  vite: cliConfig && 'vite' in cliConfig ? cliConfig.vite : undefined
172
180
  });
@@ -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 {getCliTelemetry, getTimer, isInteractive} from '@sanity/cli-core'\nimport {confirm, logSymbols, spinner, type SpinnerInstance} from '@sanity/cli-core/ux'\nimport semver from 'semver'\n\nimport {AppBuildTrace} from '../../telemetry/build.telemetry.js'\nimport {getAppId} from '../../util/appId.js'\nimport {compareDependencyVersions} from '../../util/compareDependencyVersions.js'\nimport {getLocalPackageVersion} from '../../util/getLocalPackageVersion.js'\nimport {formatModuleSizes, sortModulesBySize} from '../../util/moduleFormatUtils.js'\nimport {warnAboutMissingAppId} from '../../util/warnAboutMissingAppId.js'\nimport {buildDebug} from './buildDebug.js'\nimport {buildStaticFiles} from './buildStaticFiles.js'\nimport {buildVendorDependencies} from './buildVendorDependencies.js'\nimport {determineBasePath} from './determineBasePath.js'\nimport {getAppEnvVars} from './getAppEnvVars.js'\nimport {getAutoUpdatesImportMap} from './getAutoUpdatesImportMap.js'\nimport {handlePrereleaseVersions} from './handlePrereleaseVersions.js'\nimport {type BuildOptions} from './types.js'\n\n/**\n * Build the Sanity app.\n *\n * @internal\n */\nexport async function buildApp(options: BuildOptions): Promise<void> {\n const {cliConfig, flags, outDir, output, workDir} = options\n let {autoUpdatesEnabled} = options\n const unattendedMode = flags.yes\n const timer = getTimer()\n\n const defaultOutputDir = path.resolve(path.join(workDir, 'dist'))\n const outputDir = path.resolve(outDir || defaultOutputDir)\n\n const appId = getAppId(cliConfig)\n\n const installedSdkVersion = await getLocalPackageVersion('@sanity/sdk-react', workDir)\n const installedSanityVersion = await getLocalPackageVersion('sanity', workDir)\n\n if (!installedSdkVersion) {\n output.error(`Failed to find installed @sanity/sdk-react version`, {exit: 1})\n return\n }\n\n let autoUpdatesImports = {}\n\n if (autoUpdatesEnabled) {\n // Get the clean version without build metadata: https://semver.org/#spec-item-10\n const cleanSDKVersion = semver.parse(installedSdkVersion)?.version\n if (!cleanSDKVersion) {\n output.error(`Failed to parse installed SDK version: ${installedSdkVersion}`, {exit: 1})\n return\n }\n\n // Sanity might not be installed, but if it is, we want to auto update it.\n const cleanSanityVersion = semver.parse(installedSanityVersion)?.version\n\n const autoUpdatedPackages = [\n {name: '@sanity/sdk', version: cleanSDKVersion},\n {name: '@sanity/sdk-react', version: cleanSDKVersion},\n ...(cleanSanityVersion ? [{name: 'sanity' as const, version: cleanSanityVersion}] : []),\n ]\n autoUpdatesImports = getAutoUpdatesImportMap(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 // Skip when called from deploy, since deploy handles appId itself\n // (prompts the user and tells them to add it to config).\n if (!appId && !options.calledFromDeploy) {\n warnAboutMissingAppId({appType: 'app', output})\n }\n\n // Check the versions\n const {mismatched, unresolvedPrerelease} = await compareDependencyVersions(\n autoUpdatedPackages,\n workDir,\n {appId},\n )\n\n if (unresolvedPrerelease.length > 0) {\n await handlePrereleaseVersions({output, unattendedMode, unresolvedPrerelease})\n autoUpdatesImports = {}\n autoUpdatesEnabled = false\n }\n\n if (mismatched.length > 0 && autoUpdatesEnabled) {\n const versionMismatchWarning =\n `The following local package versions are different from the versions currently served at runtime.\\n` +\n `When using auto updates, we recommend that you test locally with the same versions before deploying. \\n\\n` +\n `${mismatched.map((mod) => ` - ${mod.pkg} (local version: ${mod.installed}, runtime version: ${mod.remote})`).join('\\n')}`\n\n // If it is non-interactive or in unattended mode, we don't want to prompt\n if (isInteractive() && !unattendedMode) {\n const shouldContinue = await confirm({\n default: false,\n message: styleText('yellow', `${versionMismatchWarning} \\n\\nContinue anyway?`),\n })\n\n if (!shouldContinue) {\n output.error('Declined to continue with build', {exit: 1})\n return\n }\n } else {\n // if non-interactive or unattended, just show the warning\n output.warn(versionMismatchWarning)\n }\n }\n }\n\n const envVarKeys = getAppEnvVars()\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 // Determine base path for built app\n const basePath = determineBasePath(cliConfig, 'app', output)\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 importMap: {imports?: Record<string, string>} | undefined\n\n if (autoUpdatesEnabled) {\n importMap = {\n imports: {\n ...(await buildVendorDependencies({basePath, cwd: workDir, isApp: true, outputDir})),\n ...autoUpdatesImports,\n },\n }\n }\n\n try {\n timer.start('bundleStudio')\n\n const bundle = await buildStaticFiles({\n appTitle: cliConfig && 'app' in cliConfig ? cliConfig.app?.title : undefined,\n basePath,\n cwd: workDir,\n entry: cliConfig && 'app' in cliConfig ? cliConfig.app?.entry : undefined,\n importMap,\n isApp: true,\n minify: Boolean(flags.minify),\n outputDir,\n reactCompiler:\n cliConfig && 'reactCompiler' in cliConfig ? cliConfig.reactCompiler : undefined,\n sourceMap: Boolean(flags['source-maps']),\n vite: cliConfig && 'vite' in cliConfig ? cliConfig.vite : undefined,\n })\n\n trace.log({\n outputSize: bundle.chunks\n .flatMap((chunk) => chunk.modules.flatMap((mod) => mod.renderedLength))\n .reduce((sum, n) => sum + n, 0),\n })\n const buildDuration = timer.end('bundleStudio')\n\n spin.text = `Build Sanity application (${buildDuration.toFixed(0)}ms)`\n spin.succeed()\n\n if (flags.stats) {\n output.log('\\nLargest module files:')\n output.log(formatModuleSizes(sortModulesBySize(bundle.chunks).slice(0, 15)))\n }\n\n trace.complete()\n } catch (error) {\n spin.fail()\n trace.error(error)\n const message = error instanceof Error ? error.message : String(error)\n buildDebug(`Failed to build Sanity application`, {error})\n output.error(`Failed to build Sanity application: ${message}`, {exit: 1})\n }\n}\n"],"names":["rm","path","styleText","getCliTelemetry","getTimer","isInteractive","confirm","logSymbols","spinner","semver","AppBuildTrace","getAppId","compareDependencyVersions","getLocalPackageVersion","formatModuleSizes","sortModulesBySize","warnAboutMissingAppId","buildDebug","buildStaticFiles","buildVendorDependencies","determineBasePath","getAppEnvVars","getAutoUpdatesImportMap","handlePrereleaseVersions","buildApp","options","cliConfig","flags","outDir","output","workDir","autoUpdatesEnabled","unattendedMode","yes","timer","defaultOutputDir","resolve","join","outputDir","appId","installedSdkVersion","installedSanityVersion","error","exit","autoUpdatesImports","cleanSDKVersion","parse","version","cleanSanityVersion","autoUpdatedPackages","name","log","info","calledFromDeploy","appType","mismatched","unresolvedPrerelease","length","versionMismatchWarning","map","mod","pkg","installed","remote","shouldContinue","default","message","warn","envVarKeys","key","shouldClean","basePath","spin","start","force","recursive","cleanDuration","end","text","toFixed","succeed","trace","importMap","imports","cwd","isApp","bundle","appTitle","app","title","undefined","entry","minify","Boolean","reactCompiler","sourceMap","vite","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,eAAe,EAAEC,QAAQ,EAAEC,aAAa,QAAO,mBAAkB;AACzE,SAAQC,OAAO,EAAEC,UAAU,EAAEC,OAAO,QAA6B,sBAAqB;AACtF,OAAOC,YAAY,SAAQ;AAE3B,SAAQC,aAAa,QAAO,qCAAoC;AAChE,SAAQC,QAAQ,QAAO,sBAAqB;AAC5C,SAAQC,yBAAyB,QAAO,0CAAyC;AACjF,SAAQC,sBAAsB,QAAO,uCAAsC;AAC3E,SAAQC,iBAAiB,EAAEC,iBAAiB,QAAO,kCAAiC;AACpF,SAAQC,qBAAqB,QAAO,sCAAqC;AACzE,SAAQC,UAAU,QAAO,kBAAiB;AAC1C,SAAQC,gBAAgB,QAAO,wBAAuB;AACtD,SAAQC,uBAAuB,QAAO,+BAA8B;AACpE,SAAQC,iBAAiB,QAAO,yBAAwB;AACxD,SAAQC,aAAa,QAAO,qBAAoB;AAChD,SAAQC,uBAAuB,QAAO,+BAA8B;AACpE,SAAQC,wBAAwB,QAAO,gCAA+B;AAGtE;;;;CAIC,GACD,OAAO,eAAeC,SAASC,OAAqB;IAClD,MAAM,EAACC,SAAS,EAAEC,KAAK,EAAEC,MAAM,EAAEC,MAAM,EAAEC,OAAO,EAAC,GAAGL;IACpD,IAAI,EAACM,kBAAkB,EAAC,GAAGN;IAC3B,MAAMO,iBAAiBL,MAAMM,GAAG;IAChC,MAAMC,QAAQ9B;IAEd,MAAM+B,mBAAmBlC,KAAKmC,OAAO,CAACnC,KAAKoC,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GACpEC,MAAM,CAAC,CAACC,KAAKC,IAAMD,MAAMC,GAAG;QACjC;QACA,MAAMC,gBAAgBxE,MAAM2C,GAAG,CAAC;QAEhCL,KAAKM,IAAI,GAAG,CAAC,0BAA0B,EAAE4B,cAAc3B,OAAO,CAAC,GAAG,GAAG,CAAC;QACtEP,KAAKQ,OAAO;QAEZ,IAAIrD,MAAMgF,KAAK,EAAE;YACf9E,OAAOsB,GAAG,CAAC;YACXtB,OAAOsB,GAAG,CAACrC,kBAAkBC,kBAAkBuE,OAAOY,MAAM,EAAEU,KAAK,CAAC,GAAG;QACzE;QAEA3B,MAAM4B,QAAQ;IAChB,EAAE,OAAOnE,OAAO;QACd8B,KAAKsC,IAAI;QACT7B,MAAMvC,KAAK,CAACA;QACZ,MAAMwB,UAAUxB,iBAAiBqE,QAAQrE,MAAMwB,OAAO,GAAG8C,OAAOtE;QAChEzB,WAAW,CAAC,kCAAkC,CAAC,EAAE;YAACyB;QAAK;QACvDb,OAAOa,KAAK,CAAC,CAAC,oCAAoC,EAAEwB,SAAS,EAAE;YAACvB,MAAM;QAAC;IACzE;AACF"}
1
+ {"version":3,"sources":["../../../src/actions/build/buildApp.ts"],"sourcesContent":["import {rm} from 'node:fs/promises'\nimport path from 'node:path'\nimport {styleText} from 'node:util'\n\nimport {getCliTelemetry, getTimer, isInteractive} from '@sanity/cli-core'\nimport {confirm, logSymbols, spinner, type SpinnerInstance} from '@sanity/cli-core/ux'\nimport {parse as semverParse} from 'semver'\n\nimport {AppBuildTrace} from '../../telemetry/build.telemetry.js'\nimport {getAppId} from '../../util/appId.js'\nimport {compareDependencyVersions} from '../../util/compareDependencyVersions.js'\nimport {getLocalPackageVersion} from '../../util/getLocalPackageVersion.js'\nimport {formatModuleSizes, sortModulesBySize} from '../../util/moduleFormatUtils.js'\nimport {warnAboutMissingAppId} from '../../util/warnAboutMissingAppId.js'\nimport {buildDebug} from './buildDebug.js'\nimport {buildStaticFiles} from './buildStaticFiles.js'\nimport {buildVendorDependencies} from './buildVendorDependencies.js'\nimport {determineBasePath} from './determineBasePath.js'\nimport {getAppEnvVars} from './getAppEnvVars.js'\nimport {getAutoUpdatesCssUrls, getAutoUpdatesImportMap} from './getAutoUpdatesImportMap.js'\nimport {handlePrereleaseVersions} from './handlePrereleaseVersions.js'\nimport {type BuildOptions} from './types.js'\n\n/**\n * Build the Sanity app.\n *\n * @internal\n */\nexport async function buildApp(options: BuildOptions): Promise<void> {\n const {cliConfig, flags, outDir, output, workDir} = options\n let {autoUpdatesEnabled} = options\n const unattendedMode = flags.yes\n const timer = getTimer()\n\n const defaultOutputDir = path.resolve(path.join(workDir, 'dist'))\n const outputDir = path.resolve(outDir || defaultOutputDir)\n\n const appId = getAppId(cliConfig)\n\n const installedSdkVersion = await getLocalPackageVersion('@sanity/sdk-react', workDir)\n const installedSanityVersion = await getLocalPackageVersion('sanity', workDir)\n\n if (!installedSdkVersion) {\n output.error(`Failed to find installed @sanity/sdk-react version`, {exit: 1})\n return\n }\n\n let autoUpdatesImports = {}\n let autoUpdatesCssUrls: string[] = []\n\n if (autoUpdatesEnabled) {\n // Get the clean version without build metadata: https://semver.org/#spec-item-10\n const cleanSDKVersion = semverParse(installedSdkVersion)?.version\n if (!cleanSDKVersion) {\n output.error(`Failed to parse installed SDK version: ${installedSdkVersion}`, {exit: 1})\n return\n }\n\n // Sanity might not be installed, but if it is, we want to auto update it.\n const cleanSanityVersion = semverParse(installedSanityVersion)?.version\n\n const autoUpdatedPackages = [\n {name: '@sanity/sdk', version: cleanSDKVersion},\n {name: '@sanity/sdk-react', version: cleanSDKVersion},\n ...(cleanSanityVersion\n ? [{cssFile: 'index.css', name: 'sanity' as const, version: cleanSanityVersion}]\n : []),\n ]\n autoUpdatesImports = getAutoUpdatesImportMap(autoUpdatedPackages, {appId})\n autoUpdatesCssUrls = getAutoUpdatesCssUrls(autoUpdatedPackages, {appId})\n\n output.log(`${logSymbols.info} Building with auto-updates enabled`)\n\n // Warn if auto updates enabled but no appId configured.\n // Skip when called from deploy, since deploy handles appId itself\n // (prompts the user and tells them to add it to config).\n if (!appId && !options.calledFromDeploy) {\n warnAboutMissingAppId({appType: 'app', output})\n }\n\n // Check the versions\n const {mismatched, unresolvedPrerelease} = await compareDependencyVersions(\n autoUpdatedPackages,\n workDir,\n {appId},\n )\n\n if (unresolvedPrerelease.length > 0) {\n await handlePrereleaseVersions({output, unattendedMode, unresolvedPrerelease})\n autoUpdatesImports = {}\n autoUpdatesCssUrls = []\n autoUpdatesEnabled = false\n }\n\n if (mismatched.length > 0 && autoUpdatesEnabled) {\n const versionMismatchWarning =\n `The following local package versions are different from the versions currently served at runtime.\\n` +\n `When using auto updates, we recommend that you test locally with the same versions before deploying. \\n\\n` +\n `${mismatched.map((mod) => ` - ${mod.pkg} (local version: ${mod.installed}, runtime version: ${mod.remote})`).join('\\n')}`\n\n // If it is non-interactive or in unattended mode, we don't want to prompt\n if (isInteractive() && !unattendedMode) {\n const shouldContinue = await confirm({\n default: false,\n message: styleText('yellow', `${versionMismatchWarning} \\n\\nContinue anyway?`),\n })\n\n if (!shouldContinue) {\n output.error('Declined to continue with build', {exit: 1})\n return\n }\n } else {\n // if non-interactive or unattended, just show the warning\n output.warn(versionMismatchWarning)\n }\n }\n }\n\n const envVarKeys = getAppEnvVars()\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 // Determine base path for built app\n const basePath = determineBasePath(cliConfig, 'app', output)\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 importMap: {imports?: Record<string, string>} | undefined\n\n if (autoUpdatesEnabled) {\n importMap = {\n imports: {\n ...(await buildVendorDependencies({basePath, cwd: workDir, isApp: true, outputDir})),\n ...autoUpdatesImports,\n },\n }\n }\n\n try {\n timer.start('bundleStudio')\n\n const bundle = await buildStaticFiles({\n appTitle: cliConfig && 'app' in cliConfig ? cliConfig.app?.title : undefined,\n autoUpdatesCssUrls: autoUpdatesCssUrls.length > 0 ? autoUpdatesCssUrls : undefined,\n basePath,\n cwd: workDir,\n entry: cliConfig && 'app' in cliConfig ? cliConfig.app?.entry : undefined,\n importMap,\n isApp: true,\n minify: Boolean(flags.minify),\n outputDir,\n reactCompiler:\n cliConfig && 'reactCompiler' in cliConfig ? cliConfig.reactCompiler : undefined,\n schemaExtraction: cliConfig?.schemaExtraction,\n sourceMap: Boolean(flags['source-maps']),\n vite: cliConfig && 'vite' in cliConfig ? cliConfig.vite : undefined,\n })\n\n trace.log({\n outputSize: bundle.chunks\n .flatMap((chunk) => chunk.modules.flatMap((mod) => mod.renderedLength))\n .reduce((sum, n) => sum + n, 0),\n })\n const buildDuration = timer.end('bundleStudio')\n\n spin.text = `Build Sanity application (${buildDuration.toFixed(0)}ms)`\n spin.succeed()\n\n if (flags.stats) {\n output.log('\\nLargest module files:')\n output.log(formatModuleSizes(sortModulesBySize(bundle.chunks).slice(0, 15)))\n }\n\n trace.complete()\n } catch (error) {\n spin.fail()\n trace.error(error)\n const message = error instanceof Error ? error.message : String(error)\n buildDebug(`Failed to build Sanity application`, {error})\n output.error(`Failed to build Sanity application: ${message}`, {exit: 1})\n }\n}\n"],"names":["rm","path","styleText","getCliTelemetry","getTimer","isInteractive","confirm","logSymbols","spinner","parse","semverParse","AppBuildTrace","getAppId","compareDependencyVersions","getLocalPackageVersion","formatModuleSizes","sortModulesBySize","warnAboutMissingAppId","buildDebug","buildStaticFiles","buildVendorDependencies","determineBasePath","getAppEnvVars","getAutoUpdatesCssUrls","getAutoUpdatesImportMap","handlePrereleaseVersions","buildApp","options","cliConfig","flags","outDir","output","workDir","autoUpdatesEnabled","unattendedMode","yes","timer","defaultOutputDir","resolve","join","outputDir","appId","installedSdkVersion","installedSanityVersion","error","exit","autoUpdatesImports","autoUpdatesCssUrls","cleanSDKVersion","version","cleanSanityVersion","autoUpdatedPackages","name","cssFile","log","info","calledFromDeploy","appType","mismatched","unresolvedPrerelease","length","versionMismatchWarning","map","mod","pkg","installed","remote","shouldContinue","default","message","warn","envVarKeys","key","shouldClean","basePath","spin","start","force","recursive","cleanDuration","end","text","toFixed","succeed","trace","importMap","imports","cwd","isApp","bundle","appTitle","app","title","undefined","entry","minify","Boolean","reactCompiler","schemaExtraction","sourceMap","vite","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,eAAe,EAAEC,QAAQ,EAAEC,aAAa,QAAO,mBAAkB;AACzE,SAAQC,OAAO,EAAEC,UAAU,EAAEC,OAAO,QAA6B,sBAAqB;AACtF,SAAQC,SAASC,WAAW,QAAO,SAAQ;AAE3C,SAAQC,aAAa,QAAO,qCAAoC;AAChE,SAAQC,QAAQ,QAAO,sBAAqB;AAC5C,SAAQC,yBAAyB,QAAO,0CAAyC;AACjF,SAAQC,sBAAsB,QAAO,uCAAsC;AAC3E,SAAQC,iBAAiB,EAAEC,iBAAiB,QAAO,kCAAiC;AACpF,SAAQC,qBAAqB,QAAO,sCAAqC;AACzE,SAAQC,UAAU,QAAO,kBAAiB;AAC1C,SAAQC,gBAAgB,QAAO,wBAAuB;AACtD,SAAQC,uBAAuB,QAAO,+BAA8B;AACpE,SAAQC,iBAAiB,QAAO,yBAAw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B,SAAS,EAAE;YAACxB,MAAM;QAAC;IACzE;AACF"}
@@ -10,7 +10,7 @@ import { writeSanityRuntime } from './writeSanityRuntime.js';
10
10
  *
11
11
  * @internal
12
12
  */ export async function buildStaticFiles(options) {
13
- const { appTitle, basePath, cwd, entry, importMap, isApp, minify = true, outputDir, reactCompiler, sourceMap = false, vite: extendViteConfig } = options;
13
+ const { appTitle, autoUpdatesCssUrls, basePath, cwd, entry, importMap, isApp, minify = true, outputDir, reactCompiler, schemaExtraction, sourceMap = false, vite: extendViteConfig } = options;
14
14
  buildDebug('Writing Sanity runtime files');
15
15
  await writeSanityRuntime({
16
16
  appTitle,
@@ -24,6 +24,7 @@ import { writeSanityRuntime } from './writeSanityRuntime.js';
24
24
  buildDebug('Resolving vite config');
25
25
  const mode = 'production';
26
26
  let viteConfig = await getViteConfig({
27
+ autoUpdatesCssUrls,
27
28
  basePath,
28
29
  cwd,
29
30
  importMap,
@@ -32,6 +33,7 @@ import { writeSanityRuntime } from './writeSanityRuntime.js';
32
33
  mode,
33
34
  outputDir,
34
35
  reactCompiler,
36
+ schemaExtraction,
35
37
  sourceMap
36
38
  });
37
39
  if (extendViteConfig) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/actions/build/buildStaticFiles.ts"],"sourcesContent":["import path from 'node:path'\n\nimport {type UserViteConfig} from '@sanity/cli-core'\nimport {type PluginOptions as ReactCompilerConfig} from 'babel-plugin-react-compiler'\nimport {build} from 'vite'\n\nimport {copyDir} from '../../util/copyDir.js'\nimport {buildDebug} from './buildDebug.js'\nimport {extendViteConfigWithUserConfig, finalizeViteConfig, getViteConfig} from './getViteConfig.js'\nimport {writeFavicons} from './writeFavicons.js'\nimport {writeSanityRuntime} from './writeSanityRuntime.js'\n\nexport interface ChunkModule {\n name: string\n originalLength: number\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 entry?: string\n importMap?: {imports?: Record<string, string>}\n isApp?: boolean\n minify?: boolean\n profile?: boolean\n reactCompiler?: ReactCompilerConfig\n sourceMap?: boolean\n vite?: UserViteConfig\n}\n\n/**\n * Builds static files\n *\n * @internal\n */\nexport async function buildStaticFiles(\n options: StaticBuildOptions,\n): Promise<{chunks: ChunkStats[]}> {\n const {\n appTitle,\n basePath,\n cwd,\n entry,\n importMap,\n isApp,\n minify = true,\n outputDir,\n reactCompiler,\n sourceMap = false,\n vite: extendViteConfig,\n } = options\n\n buildDebug('Writing Sanity runtime files')\n await writeSanityRuntime({\n appTitle,\n basePath,\n cwd,\n entry,\n isApp,\n reactStrictMode: false,\n watch: false,\n })\n\n buildDebug('Resolving vite config')\n const mode = 'production'\n let viteConfig = await getViteConfig({\n basePath,\n cwd,\n importMap,\n isApp,\n minify,\n mode,\n outputDir,\n reactCompiler,\n sourceMap,\n })\n\n if (extendViteConfig) {\n viteConfig = await extendViteConfigWithUserConfig(\n {command: 'build', mode},\n viteConfig,\n extendViteConfig,\n )\n viteConfig = await finalizeViteConfig(viteConfig)\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 originalLength: chunkModule.originalLength,\n renderedLength: chunkModule.renderedLength,\n }\n }),\n name: chunk.name,\n })\n }\n\n return {chunks: stats}\n}\n"],"names":["path","build","copyDir","buildDebug","extendViteConfigWithUserConfig","finalizeViteConfig","getViteConfig","writeFavicons","writeSanityRuntime","buildStaticFiles","options","appTitle","basePath","cwd","entry","importMap","isApp","minify","outputDir","reactCompiler","sourceMap","vite","extendViteConfig","reactStrictMode","watch","mode","viteConfig","command","fromPath","join","staticPath","faviconBasePath","replace","bundle","Array","isArray","chunks","stats","chunk","output","type","push","modules","Object","entries","map","rawFilePath","chunkModule","filePath","startsWith","slice","length","name","isAbsolute","relative","originalLength","renderedLength"],"mappings":"AAAA,OAAOA,UAAU,YAAW;AAI5B,SAAQC,KAAK,QAAO,OAAM;AAE1B,SAAQC,OAAO,QAAO,wBAAuB;AAC7C,SAAQC,UAAU,QAAO,kBAAiB;AAC1C,SAAQC,8BAA8B,EAAEC,kBAAkB,EAAEC,aAAa,QAAO,qBAAoB;AACpG,SAAQC,aAAa,QAAO,qBAAoB;AAChD,SAAQC,kBAAkB,QAAO,0BAAyB;AA6B1D;;;;CAIC,GACD,OAAO,eAAeC,iBACpBC,OAA2B;IAE3B,MAAM,EACJC,QAAQ,EACRC,QAAQ,EACRC,GAAG,EACHC,KAAK,EACLC,SAAS,EACTC,KAAK,EACLC,SAAS,IAAI,EACbC,SAAS,EACTC,aAAa,EACbC,YAAY,KAAK,EACjBC,MAAMC,gBAAgB,EACvB,GAAGZ;IAEJP,WAAW;IACX,MAAMK,mBAAmB;QACvBG;QACAC;QACAC;QACAC;QACAE;QACAO,iBAAiB;QACjBC,OAAO;IACT;IAEArB,WAAW;IACX,MAAMsB,OAAO;IACb,IAAIC,aAAa,MAAMpB,cAAc;QACnCM;QACAC;QACAE;QACAC;QACAC;QACAQ;QACAP;QACAC;QAC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;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'\nimport {type PluginOptions as ReactCompilerConfig} from 'babel-plugin-react-compiler'\nimport {build} from 'vite'\n\nimport {copyDir} from '../../util/copyDir.js'\nimport {buildDebug} from './buildDebug.js'\nimport {extendViteConfigWithUserConfig, finalizeViteConfig, getViteConfig} from './getViteConfig.js'\nimport {writeFavicons} from './writeFavicons.js'\nimport {writeSanityRuntime} from './writeSanityRuntime.js'\n\nexport interface ChunkModule {\n name: string\n originalLength: number\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 autoUpdatesCssUrls?: string[]\n entry?: string\n importMap?: {imports?: Record<string, string>}\n isApp?: boolean\n minify?: boolean\n profile?: boolean\n reactCompiler?: ReactCompilerConfig\n schemaExtraction?: CliConfig['schemaExtraction']\n sourceMap?: boolean\n vite?: UserViteConfig\n}\n\n/**\n * Builds static files\n *\n * @internal\n */\nexport async function buildStaticFiles(\n options: StaticBuildOptions,\n): Promise<{chunks: ChunkStats[]}> {\n const {\n appTitle,\n autoUpdatesCssUrls,\n basePath,\n cwd,\n entry,\n importMap,\n isApp,\n minify = true,\n outputDir,\n reactCompiler,\n schemaExtraction,\n sourceMap = false,\n vite: extendViteConfig,\n } = options\n\n buildDebug('Writing Sanity runtime files')\n await writeSanityRuntime({\n appTitle,\n basePath,\n cwd,\n entry,\n isApp,\n reactStrictMode: false,\n watch: false,\n })\n\n buildDebug('Resolving vite config')\n const mode = 'production'\n let viteConfig = await getViteConfig({\n autoUpdatesCssUrls,\n basePath,\n cwd,\n importMap,\n isApp,\n minify,\n mode,\n outputDir,\n reactCompiler,\n schemaExtraction,\n sourceMap,\n })\n\n if (extendViteConfig) {\n viteConfig = await extendViteConfigWithUserConfig(\n {command: 'build', mode},\n viteConfig,\n extendViteConfig,\n )\n viteConfig = await finalizeViteConfig(viteConfig)\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 originalLength: chunkModule.originalLength,\n renderedLength: chunkModule.renderedLength,\n }\n }),\n name: chunk.name,\n })\n }\n\n return {chunks: stats}\n}\n"],"names":["path","build","copyDir","buildDebug","extendViteConfigWithUserConfig","finalizeViteConfig","getViteConfig","writeFavicons","writeSanityRuntime","buildStaticFiles","options","appTitle","autoUpdatesCssUrls","basePath","cwd","entry","importMap","isApp","minify","outputDir","reactCompiler","schemaExtraction","sourceMap","vite","extendViteConfig","reactStrictMode","watch","mode","viteConfig","command","fromPath","join","staticPath","faviconBasePath","replace","bundle","Array","isArray","chunks","stats","chunk","output","type","push","modules","Object","entries","map","rawFilePath","chunkModule","filePath","startsWith","slice","length","name","isAbsolute","relative","originalLength","renderedLength"],"mappings":"AAAA,OAAOA,UAAU,YAAW;AAI5B,SAAQC,KAAK,QAAO,OAAM;AAE1B,SA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,iFAAiF;IACjF,IAAIiC,MAAMC,OAAO,CAACF,WAAW,CAAE,CAAA,YAAYA,MAAK,GAAI;QAClD,OAAO;YAACG,QAAQ,EAAE;QAAA;IACpB;IAEA,MAAMC,QAAsB,EAAE;IAC9B,KAAK,MAAMC,SAASL,OAAOM,MAAM,CAAE;QACjC,IAAID,MAAME,IAAI,KAAK,SAAS;YAC1B;QACF;QAEAH,MAAMI,IAAI,CAAC;YACTC,SAASC,OAAOC,OAAO,CAACN,MAAMI,OAAO,EAAEG,GAAG,CAAC,CAAC,CAACC,aAAaC,YAAY;gBACpE,MAAMC,WAAWF,YAAYG,UAAU,CAAC,YACpCH,YAAYI,KAAK,CAAC,SAASC,MAAM,IACjCL;gBAEJ,OAAO;oBACLM,MAAMtD,KAAKuD,UAAU,CAACL,YAAYlD,KAAKwD,QAAQ,CAAC1C,KAAKoC,YAAYA;oBACjEO,gBAAgBR,YAAYQ,cAAc;oBAC1CC,gBAAgBT,YAAYS,cAAc;gBAC5C;YACF;YACAJ,MAAMd,MAAMc,IAAI;QAClB;IACF;IAEA,OAAO;QAAChB,QAAQC;IAAK;AACvB"}
@@ -3,10 +3,11 @@ import path from 'node:path';
3
3
  import { styleText } from 'node:util';
4
4
  import { getCliTelemetry, getTimer, isInteractive } from '@sanity/cli-core';
5
5
  import { confirm, logSymbols, select, spinner } from '@sanity/cli-core/ux';
6
- import semver from 'semver';
6
+ import { parse as semverParse } from 'semver';
7
7
  import { StudioBuildTrace } from '../../telemetry/build.telemetry.js';
8
8
  import { getAppId } from '../../util/appId.js';
9
9
  import { compareDependencyVersions } from '../../util/compareDependencyVersions.js';
10
+ import { getLocalPackageVersion } from '../../util/getLocalPackageVersion.js';
10
11
  import { formatModuleSizes, sortModulesBySize } from '../../util/moduleFormatUtils.js';
11
12
  import { getPackageManagerChoice } from '../../util/packageManager/packageManagerChoice.js';
12
13
  import { upgradePackages } from '../../util/packageManager/upgradePackages.js';
@@ -17,7 +18,7 @@ import { buildVendorDependencies } from './buildVendorDependencies.js';
17
18
  import { checkRequiredDependencies } from './checkRequiredDependencies.js';
18
19
  import { checkStudioDependencyVersions } from './checkStudioDependencyVersions.js';
19
20
  import { determineBasePath } from './determineBasePath.js';
20
- import { getAutoUpdatesImportMap } from './getAutoUpdatesImportMap.js';
21
+ import { getAutoUpdatesCssUrls, getAutoUpdatesImportMap } from './getAutoUpdatesImportMap.js';
21
22
  import { getStudioEnvVars } from './getStudioEnvVars.js';
22
23
  import { handlePrereleaseVersions } from './handlePrereleaseVersions.js';
23
24
  import { shouldAutoUpdate } from './shouldAutoUpdate.js';
@@ -45,9 +46,10 @@ import { shouldAutoUpdate } from './shouldAutoUpdate.js';
45
46
  output
46
47
  });
47
48
  let autoUpdatesImports = {};
49
+ let autoUpdatesCssUrls = [];
48
50
  if (autoUpdatesEnabled) {
49
51
  // Get the clean version without build metadata: https://semver.org/#spec-item-10
50
- const cleanSanityVersion = semver.parse(installedSanityVersion)?.version;
52
+ const cleanSanityVersion = semverParse(installedSanityVersion)?.version;
51
53
  if (!cleanSanityVersion) {
52
54
  throw new Error(`Failed to parse installed Sanity version: ${installedSanityVersion}`);
53
55
  }
@@ -64,19 +66,33 @@ import { shouldAutoUpdate } from './shouldAutoUpdate.js';
64
66
  projectId
65
67
  });
66
68
  }
69
+ const installedVisionVersion = await getLocalPackageVersion('@sanity/vision', workDir);
70
+ const cleanVisionVersion = installedVisionVersion ? semverParse(installedVisionVersion)?.version : undefined;
67
71
  const sanityDependencies = [
68
72
  {
73
+ cssFile: 'index.css',
69
74
  name: 'sanity',
70
75
  version: cleanSanityVersion
71
76
  },
72
- {
73
- name: '@sanity/vision',
74
- version: cleanSanityVersion
75
- }
77
+ ...cleanVisionVersion ? [
78
+ {
79
+ cssFile: 'index.css',
80
+ name: '@sanity/vision',
81
+ version: cleanVisionVersion
82
+ }
83
+ ] : [
84
+ {
85
+ name: '@sanity/vision',
86
+ version: cleanSanityVersion
87
+ }
88
+ ]
76
89
  ];
77
90
  autoUpdatesImports = getAutoUpdatesImportMap(sanityDependencies, {
78
91
  appId
79
92
  });
93
+ autoUpdatesCssUrls = getAutoUpdatesCssUrls(sanityDependencies, {
94
+ appId
95
+ });
80
96
  // Check the versions
81
97
  const { mismatched, unresolvedPrerelease } = await compareDependencyVersions(sanityDependencies, workDir, {
82
98
  appId
@@ -88,6 +104,7 @@ import { shouldAutoUpdate } from './shouldAutoUpdate.js';
88
104
  unresolvedPrerelease
89
105
  });
90
106
  autoUpdatesImports = {};
107
+ autoUpdatesCssUrls = [];
91
108
  autoUpdatesEnabled = false;
92
109
  }
93
110
  if (mismatched.length > 0 && autoUpdatesEnabled) {
@@ -162,6 +179,9 @@ import { shouldAutoUpdate } from './shouldAutoUpdate.js';
162
179
  }
163
180
  // Determine base path for built studio
164
181
  const basePath = determineBasePath(cliConfig, 'studio', output);
182
+ if (cliConfig?.schemaExtraction?.enabled) {
183
+ output.log(`${logSymbols.info} Building with schema extraction enabled`);
184
+ }
165
185
  let spin;
166
186
  if (shouldClean) {
167
187
  timer.start('cleanOutputFolder');
@@ -194,12 +214,14 @@ import { shouldAutoUpdate } from './shouldAutoUpdate.js';
194
214
  try {
195
215
  timer.start('bundleStudio');
196
216
  const bundle = await buildStaticFiles({
217
+ autoUpdatesCssUrls: autoUpdatesCssUrls.length > 0 ? autoUpdatesCssUrls : undefined,
197
218
  basePath,
198
219
  cwd: workDir,
199
220
  importMap,
200
221
  minify: Boolean(flags.minify),
201
222
  outputDir,
202
223
  reactCompiler: cliConfig && 'reactCompiler' in cliConfig ? cliConfig.reactCompiler : undefined,
224
+ schemaExtraction: cliConfig?.schemaExtraction,
203
225
  sourceMap: Boolean(flags['source-maps']),
204
226
  vite: cliConfig && 'vite' in cliConfig ? cliConfig.vite : undefined
205
227
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/actions/build/buildStudio.ts"],"sourcesContent":["import {rm} from 'node:fs/promises'\nimport path from 'node:path'\nimport {styleText} from 'node:util'\n\nimport {getCliTelemetry, getTimer, isInteractive} from '@sanity/cli-core'\nimport {confirm, logSymbols, select, spinner, type SpinnerInstance} from '@sanity/cli-core/ux'\nimport semver from 'semver'\n\nimport {StudioBuildTrace} from '../../telemetry/build.telemetry.js'\nimport {getAppId} from '../../util/appId.js'\nimport {compareDependencyVersions} from '../../util/compareDependencyVersions.js'\nimport {formatModuleSizes, sortModulesBySize} from '../../util/moduleFormatUtils.js'\nimport {getPackageManagerChoice} from '../../util/packageManager/packageManagerChoice.js'\nimport {upgradePackages} from '../../util/packageManager/upgradePackages.js'\nimport {warnAboutMissingAppId} from '../../util/warnAboutMissingAppId.js'\nimport {buildDebug} from './buildDebug.js'\nimport {buildStaticFiles} from './buildStaticFiles.js'\nimport {buildVendorDependencies} from './buildVendorDependencies.js'\nimport {checkRequiredDependencies} from './checkRequiredDependencies.js'\nimport {checkStudioDependencyVersions} from './checkStudioDependencyVersions.js'\nimport {determineBasePath} from './determineBasePath.js'\nimport {getAutoUpdatesImportMap} from './getAutoUpdatesImportMap.js'\nimport {getStudioEnvVars} from './getStudioEnvVars.js'\nimport {handlePrereleaseVersions} from './handlePrereleaseVersions.js'\nimport {shouldAutoUpdate} from './shouldAutoUpdate.js'\nimport {type BuildOptions} from './types.js'\n\n/**\n * Build the Sanity Studio.\n *\n * @internal\n */\nexport async function buildStudio(options: BuildOptions): Promise<void> {\n const timer = getTimer()\n const {cliConfig, flags, outDir, output, workDir} = options\n\n const unattendedMode = Boolean(flags.yes)\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 cliConfig,\n output,\n workDir,\n })\n\n let autoUpdatesEnabled = options.calledFromDeploy\n ? options.autoUpdatesEnabled\n : shouldAutoUpdate({cliConfig, flags, output})\n\n let autoUpdatesImports = {}\n\n if (autoUpdatesEnabled) {\n // Get the clean version without build metadata: https://semver.org/#spec-item-10\n const cleanSanityVersion = semver.parse(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 const projectId = cliConfig?.api?.projectId\n const appId = getAppId(cliConfig)\n\n // Warn if auto updates enabled but no appId configured.\n // Skip when called from deploy, since deploy handles appId itself\n // (prompts the user and tells them to add it to config).\n if (!appId && !options.calledFromDeploy) {\n warnAboutMissingAppId({appType: 'studio', output, projectId})\n }\n\n const sanityDependencies = [\n {name: 'sanity', version: cleanSanityVersion},\n {name: '@sanity/vision', version: cleanSanityVersion},\n ]\n autoUpdatesImports = getAutoUpdatesImportMap(sanityDependencies, {appId})\n\n // Check the versions\n const {mismatched, unresolvedPrerelease} = await compareDependencyVersions(\n sanityDependencies,\n workDir,\n {appId},\n )\n\n if (unresolvedPrerelease.length > 0) {\n await handlePrereleaseVersions({output, unattendedMode, unresolvedPrerelease})\n autoUpdatesImports = {}\n autoUpdatesEnabled = false\n }\n\n if (mismatched.length > 0 && autoUpdatesEnabled) {\n const versionMismatchWarning =\n `The following local package versions are different from the versions currently served at runtime.\\n` +\n `When using auto updates, we recommend that you test locally with the same versions before deploying. \\n\\n` +\n `${mismatched.map((mod) => ` - ${mod.pkg} (local version: ${mod.installed}, runtime version: ${mod.remote})`).join('\\n')}`\n\n // If it is non-interactive or in unattended mode, we don't want to prompt\n if (isInteractive() && !unattendedMode) {\n const choice = await select({\n choices: [\n {\n name: `Upgrade local versions (recommended). You will need to run the build command again`,\n value: 'upgrade',\n },\n {\n name: `Upgrade and proceed with build`,\n value: 'upgrade-and-proceed',\n },\n {\n name: `Continue anyway`,\n value: 'continue',\n },\n {name: 'Cancel', value: 'cancel'},\n ],\n default: 'upgrade',\n message: styleText(\n 'yellow',\n `${logSymbols.warning} ${versionMismatchWarning}\\n\\nDo you want to upgrade local versions before deploying?`,\n ),\n })\n\n if (choice === 'cancel') {\n output.error('Declined to continue with build', {exit: 1})\n return\n }\n\n if (choice === 'upgrade' || choice === 'upgrade-and-proceed') {\n await upgradePackages(\n {\n packageManager: (await getPackageManagerChoice(workDir, {interactive: false})).chosen,\n packages: mismatched.map((res) => [res.pkg, res.remote]),\n },\n {output, workDir},\n )\n\n if (choice === 'upgrade') {\n return\n }\n }\n } else {\n // if non-interactive or unattended, just show the warning\n output.warn(versionMismatchWarning)\n }\n }\n }\n\n const envVarKeys = getStudioEnvVars()\n if (envVarKeys.length > 0) {\n output.log('\\nIncluding the following environment variables as part of the JavaScript bundle:')\n for (const key of envVarKeys) {\n output.log(`- ${key}`)\n }\n output.log('')\n }\n\n let shouldClean = true\n if (outputDir !== defaultOutputDir && !unattendedMode && isInteractive()) {\n shouldClean = await confirm({\n default: true,\n message: `Do you want to delete the existing directory (${outputDir}) first?`,\n })\n }\n\n // Determine base path for built studio\n const basePath = determineBasePath(cliConfig, 'studio', output)\n\n let spin: SpinnerInstance\n if (shouldClean) {\n timer.start('cleanOutputFolder')\n spin = spinner('Clean output folder').start()\n await rm(outputDir, {force: true, recursive: true})\n const cleanDuration = timer.end('cleanOutputFolder')\n spin.text = `Clean output folder (${cleanDuration.toFixed(0)}ms)`\n spin.succeed()\n }\n\n spin = spinner(`Build Sanity Studio`).start()\n\n const trace = getCliTelemetry().trace(StudioBuildTrace)\n trace.start()\n\n let importMap\n\n if (autoUpdatesEnabled) {\n importMap = {\n imports: {\n ...(await buildVendorDependencies({basePath, cwd: workDir, isApp: false, outputDir})),\n ...autoUpdatesImports,\n },\n }\n }\n\n try {\n timer.start('bundleStudio')\n\n const bundle = await buildStaticFiles({\n basePath,\n cwd: workDir,\n importMap,\n minify: Boolean(flags.minify),\n outputDir,\n reactCompiler:\n cliConfig && 'reactCompiler' in cliConfig ? cliConfig.reactCompiler : undefined,\n sourceMap: Boolean(flags['source-maps']),\n vite: cliConfig && 'vite' in cliConfig ? cliConfig.vite : undefined,\n })\n\n trace.log({\n outputSize: bundle.chunks\n .flatMap((chunk) => chunk.modules.flatMap((mod) => mod.renderedLength))\n .reduce((sum, n) => sum + n, 0),\n })\n const buildDuration = timer.end('bundleStudio')\n\n spin.text = `Build Sanity Studio (${buildDuration.toFixed(0)}ms)`\n spin.succeed()\n\n trace.complete()\n if (flags.stats) {\n output.log('\\nLargest module files:')\n output.log(formatModuleSizes(sortModulesBySize(bundle.chunks).slice(0, 15)))\n }\n } catch (error) {\n spin.fail()\n trace.error(error)\n const message = error instanceof Error ? error.message : String(error)\n buildDebug(`Failed to build Sanity Studio`, {error})\n output.error(`Failed to build Sanity Studio: ${message}`, {exit: 1})\n }\n}\n"],"names":["rm","path","styleText","getCliTelemetry","getTimer","isInteractive","confirm","logSymbols","select","spinner","semver","StudioBuildTrace","getAppId","compareDependencyVersions","formatModuleSizes","sortModulesBySize","getPackageManagerChoice","upgradePackages","warnAboutMissingAppId","buildDebug","buildStaticFiles","buildVendorDependencies","checkRequiredDependencies","checkStudioDependencyVersions","determineBasePath","getAutoUpdatesImportMap","getStudioEnvVars","handlePrereleaseVersions","shouldAutoUpdate","buildStudio","options","timer","cliConfig","flags","outDir","output","workDir","unattendedMode","Boolean","yes","defaultOutputDir","resolve","join","outputDir","installedSanityVersion","autoUpdatesEnabled","calledFromDeploy","autoUpdatesImports","cleanSanityVersion","parse","version","Error","log","info","projectId","api","appId","appType","sanityDependencies","name","mismatched","unresolvedPrerelease","length","versionMismatchWarning","map","mod","pkg","installed","remote","choice","choices","value","default","message","warning","error","exit","packageManager","interactive","chosen","packages","res","warn","envVarKeys","key","shouldClean","basePath","spin","start","force","recursive","cleanDuration","end","text","toFixed","succeed","trace","importMap","imports","cwd","isApp","bundle","minify","reactCompiler","undefined","sourceMap","vite","outputSize","chunks","flatMap","chunk","modules","renderedLength","reduce","sum","n","buildDuration","complete","stats","slice","fail","String"],"mappings":"AAAA,SAAQA,EAAE,QAAO,mBAAkB;AACnC,OAAOC,UAAU,YAAW;AAC5B,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;YACxEC,WAAWnE,QAAQL,KAAK,CAAC,cAAc;YACvCyE,MAAM1E,aAAa,UAAUA,YAAYA,UAAU0E,IAAI,GAAGF;QAC5D;QAEAR,MAAM5C,GAAG,CAAC;YACRuD,YAAYN,OAAOO,MAAM,CACtBC,OAAO,CAAC,CAACC,QAAUA,MAAMC,OAAO,CAACF,OAAO,CAAC,CAAC5C,MAAQA,IAAI+C,cAAc,GACpEC,MAAM,CAAC,CAACC,KAAKC,IAAMD,MAAMC,GAAG;QACjC;QACA,MAAMC,gBAAgBrF,MAAM6D,GAAG,CAAC;QAEhCL,KAAKM,IAAI,GAAG,CAAC,qBAAqB,EAAEuB,cAActB,OAAO,CAAC,GAAG,GAAG,CAAC;QACjEP,KAAKQ,OAAO;QAEZC,MAAMqB,QAAQ;QACd,IAAIpF,MAAMqF,KAAK,EAAE;YACfnF,OAAOiB,GAAG,CAAC;YACXjB,OAAOiB,GAAG,CAACtC,kBAAkBC,kBAAkBsF,OAAOO,MAAM,EAAEW,KAAK,CAAC,GAAG;QACzE;IACF,EAAE,OAAO5C,OAAO;QACdY,KAAKiC,IAAI;QACTxB,MAAMrB,KAAK,CAACA;QACZ,MAAMF,UAAUE,iBAAiBxB,QAAQwB,MAAMF,OAAO,GAAGgD,OAAO9C;QAChExD,WAAW,CAAC,6BAA6B,CAAC,EAAE;YAACwD;QAAK;QAClDxC,OAAOwC,KAAK,CAAC,CAAC,+BAA+B,EAAEF,SAAS,EAAE;YAACG,MAAM;QAAC;IACpE;AACF"}
1
+ {"version":3,"sources":["../../../src/actions/build/buildStudio.ts"],"sourcesContent":["import {rm} from 'node:fs/promises'\nimport path from 'node:path'\nimport {styleText} from 'node:util'\n\nimport {getCliTelemetry, getTimer, isInteractive} from '@sanity/cli-core'\nimport {confirm, logSymbols, select, spinner, type SpinnerInstance} from '@sanity/cli-core/ux'\nimport {parse as semverParse} from 'semver'\n\nimport {StudioBuildTrace} from '../../telemetry/build.telemetry.js'\nimport {getAppId} from '../../util/appId.js'\nimport {compareDependencyVersions} from '../../util/compareDependencyVersions.js'\nimport {getLocalPackageVersion} from '../../util/getLocalPackageVersion.js'\nimport {formatModuleSizes, sortModulesBySize} from '../../util/moduleFormatUtils.js'\nimport {getPackageManagerChoice} from '../../util/packageManager/packageManagerChoice.js'\nimport {upgradePackages} from '../../util/packageManager/upgradePackages.js'\nimport {warnAboutMissingAppId} from '../../util/warnAboutMissingAppId.js'\nimport {buildDebug} from './buildDebug.js'\nimport {buildStaticFiles} from './buildStaticFiles.js'\nimport {buildVendorDependencies} from './buildVendorDependencies.js'\nimport {checkRequiredDependencies} from './checkRequiredDependencies.js'\nimport {checkStudioDependencyVersions} from './checkStudioDependencyVersions.js'\nimport {determineBasePath} from './determineBasePath.js'\nimport {getAutoUpdatesCssUrls, getAutoUpdatesImportMap} from './getAutoUpdatesImportMap.js'\nimport {getStudioEnvVars} from './getStudioEnvVars.js'\nimport {handlePrereleaseVersions} from './handlePrereleaseVersions.js'\nimport {shouldAutoUpdate} from './shouldAutoUpdate.js'\nimport {type BuildOptions} from './types.js'\n\n/**\n * Build the Sanity Studio.\n *\n * @internal\n */\nexport async function buildStudio(options: BuildOptions): Promise<void> {\n const timer = getTimer()\n const {cliConfig, flags, outDir, output, workDir} = options\n\n const unattendedMode = Boolean(flags.yes)\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 cliConfig,\n output,\n workDir,\n })\n\n let autoUpdatesEnabled = options.calledFromDeploy\n ? options.autoUpdatesEnabled\n : shouldAutoUpdate({cliConfig, flags, output})\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 const projectId = cliConfig?.api?.projectId\n const appId = getAppId(cliConfig)\n\n // Warn if auto updates enabled but no appId configured.\n // Skip when called from deploy, since deploy handles appId itself\n // (prompts the user and tells them to add it to config).\n if (!appId && !options.calledFromDeploy) {\n warnAboutMissingAppId({appType: 'studio', output, projectId})\n }\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} = await compareDependencyVersions(\n sanityDependencies,\n workDir,\n {appId},\n )\n\n if (unresolvedPrerelease.length > 0) {\n await handlePrereleaseVersions({output, unattendedMode, unresolvedPrerelease})\n autoUpdatesImports = {}\n autoUpdatesCssUrls = []\n autoUpdatesEnabled = false\n }\n\n if (mismatched.length > 0 && autoUpdatesEnabled) {\n const versionMismatchWarning =\n `The following local package versions are different from the versions currently served at runtime.\\n` +\n `When using auto updates, we recommend that you test locally with the same versions before deploying. \\n\\n` +\n `${mismatched.map((mod) => ` - ${mod.pkg} (local version: ${mod.installed}, runtime version: ${mod.remote})`).join('\\n')}`\n\n // If it is non-interactive or in unattended mode, we don't want to prompt\n if (isInteractive() && !unattendedMode) {\n const choice = await select({\n choices: [\n {\n name: `Upgrade local versions (recommended). You will need to run the build command again`,\n value: 'upgrade',\n },\n {\n name: `Upgrade and proceed with build`,\n value: 'upgrade-and-proceed',\n },\n {\n name: `Continue anyway`,\n value: 'continue',\n },\n {name: 'Cancel', value: 'cancel'},\n ],\n default: 'upgrade',\n message: styleText(\n 'yellow',\n `${logSymbols.warning} ${versionMismatchWarning}\\n\\nDo you want to upgrade local versions before deploying?`,\n ),\n })\n\n if (choice === 'cancel') {\n output.error('Declined to continue with build', {exit: 1})\n return\n }\n\n if (choice === 'upgrade' || choice === 'upgrade-and-proceed') {\n await upgradePackages(\n {\n packageManager: (await getPackageManagerChoice(workDir, {interactive: false})).chosen,\n packages: mismatched.map((res) => [res.pkg, res.remote]),\n },\n {output, workDir},\n )\n\n if (choice === 'upgrade') {\n return\n }\n }\n } else {\n // if non-interactive or unattended, just show the warning\n output.warn(versionMismatchWarning)\n }\n }\n }\n\n const envVarKeys = getStudioEnvVars()\n if (envVarKeys.length > 0) {\n output.log('\\nIncluding the following environment variables as part of the JavaScript bundle:')\n for (const key of envVarKeys) {\n output.log(`- ${key}`)\n }\n output.log('')\n }\n\n let shouldClean = true\n if (outputDir !== defaultOutputDir && !unattendedMode && isInteractive()) {\n shouldClean = await confirm({\n default: true,\n message: `Do you want to delete the existing directory (${outputDir}) first?`,\n })\n }\n\n // Determine base path for built studio\n const basePath = determineBasePath(cliConfig, 'studio', output)\n\n if (cliConfig?.schemaExtraction?.enabled) {\n output.log(`${logSymbols.info} Building with schema extraction enabled`)\n }\n\n let spin: SpinnerInstance\n if (shouldClean) {\n timer.start('cleanOutputFolder')\n spin = spinner('Clean output folder').start()\n await rm(outputDir, {force: true, recursive: true})\n const cleanDuration = timer.end('cleanOutputFolder')\n spin.text = `Clean output folder (${cleanDuration.toFixed(0)}ms)`\n spin.succeed()\n }\n\n spin = spinner(`Build Sanity Studio`).start()\n\n const trace = getCliTelemetry().trace(StudioBuildTrace)\n trace.start()\n\n let importMap\n\n if (autoUpdatesEnabled) {\n importMap = {\n imports: {\n ...(await buildVendorDependencies({basePath, cwd: workDir, isApp: false, outputDir})),\n ...autoUpdatesImports,\n },\n }\n }\n\n try {\n timer.start('bundleStudio')\n\n const bundle = await buildStaticFiles({\n autoUpdatesCssUrls: autoUpdatesCssUrls.length > 0 ? autoUpdatesCssUrls : undefined,\n basePath,\n cwd: workDir,\n importMap,\n minify: Boolean(flags.minify),\n outputDir,\n reactCompiler:\n cliConfig && 'reactCompiler' in cliConfig ? cliConfig.reactCompiler : undefined,\n schemaExtraction: cliConfig?.schemaExtraction,\n sourceMap: Boolean(flags['source-maps']),\n vite: cliConfig && 'vite' in cliConfig ? cliConfig.vite : undefined,\n })\n\n trace.log({\n outputSize: bundle.chunks\n .flatMap((chunk) => chunk.modules.flatMap((mod) => mod.renderedLength))\n .reduce((sum, n) => sum + n, 0),\n })\n const buildDuration = timer.end('bundleStudio')\n\n spin.text = `Build Sanity Studio (${buildDuration.toFixed(0)}ms)`\n spin.succeed()\n\n trace.complete()\n if (flags.stats) {\n output.log('\\nLargest module files:')\n output.log(formatModuleSizes(sortModulesBySize(bundle.chunks).slice(0, 15)))\n }\n } catch (error) {\n spin.fail()\n trace.error(error)\n const message = error instanceof Error ? error.message : String(error)\n buildDebug(`Failed to build Sanity Studio`, {error})\n output.error(`Failed to build Sanity Studio: ${message}`, {exit: 1})\n }\n}\n"],"names":["rm","path","styleText","getCliTelemetry","getTimer","isInteractive","confirm","logSymbols","select","spinner","parse","semverParse","StudioBuildTrace","getAppId","compareDependencyVersions","getLocalPackageVersion","formatModuleSizes","sortModulesBySize","getPackageManagerChoice","upgradePackages","warnAboutMissingAppId","buildDebug","buildStaticFiles","buildVendorDependencies","checkRequiredDependencies","checkStudioDependencyVersions","determineBasePath","getAutoUpdatesCssUrls","getAutoUpdatesImportMap","getStudioEnvVars","handlePrereleaseVersions","shouldAutoUpdate","buildStudio","options","timer","cliConfig","flags","outDir","output","workDir","unattendedMode","Boolean","yes","defaultOutputDir","resolve","join","outputDir","installedSanityVersion","autoUpdatesEnabled","calledFromDeploy","autoUpdatesImports","autoUpdatesCssUrls","cleanSanityVersion","version","Error","log","info","projectId","api","appId","appType","installedVisionVersion","cleanVisionVersion","undefined","sanityDependencies","cssFile","name","mismatched","unresolvedPrerelease","length","versionMismatchWarning","map","mod","pkg","installed","remote","choice","choices","value","default","message","warning","error","exit","packageManager","interactive","chosen","packages","res","warn","envVarKeys","key","shouldClean","basePath","schemaExtraction","enabled","spin","start","force","recursive","cleanDuration","end","text","toFixed","succeed","trace","importMap","imports","cwd","isApp","bundle","minify","reactCompiler","sourceMap","vite","outputSize","chunks","flatMap","chunk","modules","renderedLength","reduce","sum","n","buildDuration","complete","stats","slice","fail","String"],"mappings":"AAAA,SAAQA,EAAE,QAAO,mBAAkB;AACnC,OAAOC,UAAU,YAAW;AAC5B,SAAQC,SAAS,QAAO,YAAW;AAEnC,SAAQC,eAAe,EAAEC,QAAQ,EAAEC,aAAa,QAAO,mBAAkB;AACzE,SAAQC,OAAO,EAAEC,UAAU,EAAEC,MAAM,EAAEC,OAAO,QAA6B,sBAAqB;AAC9F,SAAQC,SAASC,WAAW,QAAO,SAAQ;AAE3C,SAAQC,gBAAgB,QAAO,qCAAoC;AACnE,SAAQC,QAAQ,QAAO,sBAAqB;AAC5C,SAAQC,yBAAyB,QAAO,0CAAyC;AACjF,SAAQC,sBAAsB,QAAO,uCAAsC;AAC3E,SAAQC,iBAAiB,EAAEC,iBAAiB,QAAO,kCAAiC;AACpF,SAAQC,uBAAuB,QAAO,oDAAmD;AACzF,SAAQC,eAAe,QAAO,+CAA8C;AAC5E,SAAQC,qBAAqB,QAAO,sCAAqC;AACzE,SAAQC,UAAU,QAAO,kBAAiB;AAC1C,SAAQC,gBAAgB,QAAO,wBAAuB;AACtD,SAAQC,uBAAuB,QAAO,+BAA8B;AACpE,SAAQC,yBAAyB,QAAO,iCAAgC;AACxE,SAAQC,6BAA6B,QAAO,qCAAoC;AAChF,SAAQC,iBAAiB,QAAO,yBAAwB;AACxD,SAAQC,qBAAqB,EAAEC,uBAAuB,QAAO,+BAA8B;AAC3F,SAAQ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AAO,CAACF,OAAO,CAAC,CAAC7C,MAAQA,IAAIgD,cAAc,GACpEC,MAAM,CAAC,CAACC,KAAKC,IAAMD,MAAMC,GAAG;QACjC;QACA,MAAMC,gBAAgB1F,MAAMmE,GAAG,CAAC;QAEhCL,KAAKM,IAAI,GAAG,CAAC,qBAAqB,EAAEsB,cAAcrB,OAAO,CAAC,GAAG,GAAG,CAAC;QACjEP,KAAKQ,OAAO;QAEZC,MAAMoB,QAAQ;QACd,IAAIzF,MAAM0F,KAAK,EAAE;YACfxF,OAAOiB,GAAG,CAAC;YACXjB,OAAOiB,GAAG,CAACvC,kBAAkBC,kBAAkB6F,OAAOM,MAAM,EAAEW,KAAK,CAAC,GAAG;QACzE;IACF,EAAE,OAAO7C,OAAO;QACdc,KAAKgC,IAAI;QACTvB,MAAMvB,KAAK,CAACA;QACZ,MAAMF,UAAUE,iBAAiB5B,QAAQ4B,MAAMF,OAAO,GAAGiD,OAAO/C;QAChE7D,WAAW,CAAC,6BAA6B,CAAC,EAAE;YAAC6D;QAAK;QAClD5C,OAAO4C,KAAK,CAAC,CAAC,+BAA+B,EAAEF,SAAS,EAAE;YAACG,MAAM;QAAC;IACpE;AACF"}
@@ -1,5 +1,5 @@
1
1
  import path from 'node:path';
2
- import semver from 'semver';
2
+ import { gt, minVersion, rcompare, satisfies } from 'semver';
3
3
  import { build } from 'vite';
4
4
  import { getLocalPackageDir, getLocalPackageVersion } from '../../util/getLocalPackageVersion.js';
5
5
  import { createExternalFromImportMap } from './createExternalFromImportMap.js';
@@ -55,21 +55,21 @@ const STYLED_COMPONENTS_IMPORTS = {
55
55
  }
56
56
  // Sort version ranges in descending order
57
57
  const sortedRanges = Object.keys(ranges).toSorted((range1, range2)=>{
58
- const min1 = semver.minVersion(range1);
59
- const min2 = semver.minVersion(range2);
58
+ const min1 = minVersion(range1);
59
+ const min2 = minVersion(range2);
60
60
  if (!min1) throw new Error(`Could not parse range '${range1}'`);
61
61
  if (!min2) throw new Error(`Could not parse range '${range2}'`);
62
62
  // sort them in reverse so we can rely on array `.find` below
63
- return semver.rcompare(min1.version, min2.version);
63
+ return rcompare(min1.version, min2.version);
64
64
  });
65
65
  // Find the first version range that satisfies the package version
66
- const matchedRange = sortedRanges.find((range)=>semver.satisfies(version, range));
66
+ const matchedRange = sortedRanges.find((range)=>satisfies(version, range));
67
67
  if (!matchedRange) {
68
- const min = semver.minVersion(sortedRanges.at(-1));
68
+ const min = minVersion(sortedRanges.at(-1));
69
69
  if (!min) {
70
70
  throw new Error(`Could not find a minimum version for package '${packageName}'`);
71
71
  }
72
- if (semver.gt(min.version, version)) {
72
+ if (gt(min.version, version)) {
73
73
  throw new Error(`Package '${packageName}' requires at least ${min.version}.`);
74
74
  }
75
75
  throw new Error(`Version '${version}' of package '${packageName}' is not supported yet.`);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/actions/build/buildVendorDependencies.ts"],"sourcesContent":["import path from 'node:path'\n\nimport semver from 'semver'\nimport {build} from 'vite'\n\nimport {getLocalPackageDir, getLocalPackageVersion} from '../../util/getLocalPackageVersion.js'\nimport {createExternalFromImportMap} from './createExternalFromImportMap.js'\n\n// Directory where vendor packages will be stored\nconst VENDOR_DIR = 'vendor'\n\n/**\n * A type representing the imports of vendor packages, defining specific entry\n * points for various versions and subpaths of the packages.\n *\n * The `VendorImports` object is used to build ESM browser-compatible versions\n * of the specified packages. This approach ensures that the appropriate version\n * and entry points are used for each package, enabling compatibility and proper\n * functionality in the browser environment.\n *\n * ## Rationale\n *\n * The rationale for this structure is to handle different versions of the\n * packages carefully, especially major versions. Major version bumps often\n * introduce breaking changes, so the module scheme for the package needs to be\n * checked when there is a major version update. However, minor and patch\n * versions are generally backward compatible, so they are handled more\n * leniently. By assuming that new minor versions are compatible, we avoid\n * unnecessary warnings and streamline the update process.\n *\n * If a new minor version introduces an additional subpath export within the\n * package of this version range, the corresponding package can add a more\n * specific version range that includes the new subpath. This design allows for\n * flexibility and ease of maintenance, ensuring that the latest features and\n * fixes are incorporated without extensive manual intervention.\n *\n * An additional subpath export within the package of this version range that\n * could cause the build to break if that new export is used, can be treated as\n * a bug fix. It might make more sense to our users that this new subpath isn't\n * supported yet until we address it as a bug fix. This approach helps maintain\n * stability and prevents unexpected issues during the build process.\n *\n * ## Structure\n * The `VendorImports` type is a nested object where:\n * - The keys at the first level represent the package names.\n * - The keys at the second level represent the version ranges (e.g., `^19.0.0`).\n * - The keys at the third level represent the subpaths within the package (e.g., `.` for the main entry point).\n * - The values at the third level are the relative paths to the corresponding entry points within the package.\n *\n * This structure allows for precise specification of the entry points for\n * different versions and subpaths, ensuring that the correct files are used\n * during the build process.\n */\ntype VendorImports = {\n [packageName: string]: {\n [versionRange: string]: {\n [subpath: string]: string\n }\n }\n}\n\n// Define the vendor packages and their corresponding versions and entry points\nconst VENDOR_IMPORTS: VendorImports = {\n react: {\n '^19.2.0': {\n '.': './cjs/react.production.js',\n './compiler-runtime': './cjs/react-compiler-runtime.production.js',\n './jsx-dev-runtime': './cjs/react-jsx-dev-runtime.production.js',\n './jsx-runtime': './cjs/react-jsx-runtime.production.js',\n './package.json': './package.json',\n },\n },\n 'react-dom': {\n '^19.2.0': {\n '.': './cjs/react-dom.production.js',\n './client': './cjs/react-dom-client.production.js',\n './package.json': './package.json',\n './server': './cjs/react-dom-server-legacy.browser.production.js',\n './server.browser': './cjs/react-dom-server-legacy.browser.production.js',\n './static': './cjs/react-dom-server.browser.production.js',\n './static.browser': './cjs/react-dom-server.browser.production.js',\n },\n },\n}\n\nconst STYLED_COMPONENTS_IMPORTS = {\n 'styled-components': {\n '^6.1.0': {\n '.': './dist/styled-components.browser.esm.js',\n './package.json': './package.json',\n },\n },\n}\n\ninterface VendorBuildOptions {\n basePath: string\n cwd: string\n isApp: boolean\n outputDir: string\n}\n\n/**\n * Builds the ESM browser compatible versions of the vendor packages\n * specified in VENDOR_IMPORTS. Returns the `imports` object of an import map.\n */\nexport async function buildVendorDependencies({\n basePath,\n cwd,\n isApp,\n outputDir,\n}: VendorBuildOptions): Promise<Record<string, string>> {\n const entry: Record<string, string> = {}\n const imports: Record<string, string> = {}\n\n // If we're building an app, we don't need to build the styled-components package\n const vendorImports = isApp ? VENDOR_IMPORTS : {...VENDOR_IMPORTS, ...STYLED_COMPONENTS_IMPORTS}\n\n // Iterate over each package and its version ranges in VENDOR_IMPORTS\n for (const [packageName, ranges] of Object.entries(vendorImports)) {\n const version = await getLocalPackageVersion(packageName, cwd)\n if (!version) {\n throw new Error(`Could not get version for '${packageName}'`)\n }\n\n // Sort version ranges in descending order\n const sortedRanges = Object.keys(ranges).toSorted((range1, range2) => {\n const min1 = semver.minVersion(range1)\n const min2 = semver.minVersion(range2)\n\n if (!min1) throw new Error(`Could not parse range '${range1}'`)\n if (!min2) throw new Error(`Could not parse range '${range2}'`)\n\n // sort them in reverse so we can rely on array `.find` below\n return semver.rcompare(min1.version, min2.version)\n })\n\n // Find the first version range that satisfies the package version\n const matchedRange = sortedRanges.find((range) => semver.satisfies(version, range))\n\n if (!matchedRange) {\n const min = semver.minVersion(sortedRanges.at(-1)!)\n if (!min) {\n throw new Error(`Could not find a minimum version for package '${packageName}'`)\n }\n\n if (semver.gt(min.version, version)) {\n throw new Error(`Package '${packageName}' requires at least ${min.version}.`)\n }\n\n throw new Error(`Version '${version}' of package '${packageName}' is not supported yet.`)\n }\n\n const subpaths = ranges[matchedRange]\n\n // Resolve the actual package directory using Node module resolution,\n // so that hoisted packages in monorepos/workspaces are found correctly\n const packageDir = getLocalPackageDir(packageName, cwd)\n\n // Iterate over each subpath and its corresponding entry point\n for (const [subpath, relativeEntryPoint] of Object.entries(subpaths)) {\n const specifier = path.posix.join(packageName, subpath)\n const chunkName = path.posix.join(\n packageName,\n path.relative(packageName, specifier) || 'index',\n )\n\n entry[chunkName] = path.join(packageDir, relativeEntryPoint)\n imports[specifier] = path.posix.join('/', basePath, VENDOR_DIR, `${chunkName}.mjs`)\n }\n }\n\n // removes the `RollupWatcher` type\n type BuildResult = Exclude<Awaited<ReturnType<typeof build>>, {close: unknown}>\n\n // Use Vite to build the packages into the output directory\n let buildResult = (await build({\n appType: 'custom',\n build: {\n commonjsOptions: {strictRequires: 'auto'},\n emptyOutDir: false, // Rely on CLI to do this\n lib: {entry, formats: ['es']},\n minify: true,\n outDir: path.join(outputDir, VENDOR_DIR),\n rollupOptions: {\n external: createExternalFromImportMap({imports}),\n output: {\n chunkFileNames: '[name]-[hash].mjs',\n entryFileNames: '[name]-[hash].mjs',\n exports: 'named',\n format: 'es',\n },\n treeshake: {preset: 'recommended'},\n },\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: 'node_modules/.sanity/vite-vendor',\n configFile: false,\n define: {'process.env.NODE_ENV': JSON.stringify('production')},\n logLevel: 'silent',\n mode: 'production',\n root: cwd,\n })) as BuildResult\n\n buildResult = Array.isArray(buildResult) ? buildResult : [buildResult]\n\n // Create a map of the original import specifiers to their hashed filenames\n const hashedImports: Record<string, string> = {}\n const output = buildResult.flatMap((i) => i.output)\n\n for (const chunk of output) {\n if (chunk.type === 'asset') continue\n\n for (const [specifier, originalPath] of Object.entries(imports)) {\n if (originalPath.endsWith(`${chunk.name}.mjs`)) {\n hashedImports[specifier] = path.posix.join('/', basePath, VENDOR_DIR, chunk.fileName)\n }\n }\n }\n\n return hashedImports\n}\n"],"names":["path","semver","build","getLocalPackageDir","getLocalPackageVersion","createExternalFromImportMap","VENDOR_DIR","VENDOR_IMPORTS","react","STYLED_COMPONENTS_IMPORTS","buildVendorDependencies","basePath","cwd","isApp","outputDir","entry","imports","vendorImports","packageName","ranges","Object","entries","version","Error","sortedRanges","keys","toSorted","range1","range2","min1","minVersion","min2","rcompare","matchedRange","find","range","satisfies","min","at","gt","subpaths","packageDir","subpath","relativeEntryPoint","specifier","posix","join","chunkName","relative","buildResult","appType","commonjsOptions","strictRequires","emptyOutDir","lib","formats","minify","outDir","rollupOptions","external","output","chunkFileNames","entryFileNames","exports","format","treeshake","preset","cacheDir","configFile","define","JSON","stringify","logLevel","mode","root","Array","isArray","hashedImports","flatMap","i","chunk","type","originalPath","endsWith","name","fileName"],"mappings":"AAAA,OAAOA,UAAU,YAAW;AAE5B,OAAOC,YAAY,SAAQ;AAC3B,SAAQC,KAAK,QAAO,OAAM;AAE1B,SAAQC,kBAAkB,EAAEC,sBAAsB,QAAO,uCAAsC;AAC/F,SAAQC,2BAA2B,QAAO,mCAAkC;AAE5E,iDAAiD;AACjD,MAAMC,aAAa;AAoDnB,+EAA+E;AAC/E,MAAMC,iBAAgC;IACpCC,OAAO;QACL,WAAW;YACT,KAAK;YACL,sBAAsB;YACtB,qBAAqB;YACrB,iBAAiB;YACjB,kBAAkB;QACpB;IACF;IACA,aAAa;QACX,WAAW;YACT,KAAK;YACL,YAAY;YACZ,kBAAkB;YAClB,YAAY;YACZ,oBAAoB;YACpB,YAAY;YACZ,oBAAoB;QACtB;IACF;AACF;AAEA,MAAMC,4BAA4B;IAChC,qBAAqB;QACnB,UAAU;YACR,KAAK;YACL,kBAAkB;QACpB;IACF;AACF;AASA;;;CAGC,GACD,OAAO,eAAeC,wBAAwB,EAC5CC,QAAQ,EACRC,GAAG,EACHC,KAAK,EACLC,SAAS,EACU;IACnB,MAAMC,QAAgC,CAAC;IACvC,MAAMC,UAAkC,CAAC;IAEzC,iFAAiF;IACjF,MAAMC,gBAAgBJ,QAAQN,iBAAiB;QAAC,GAAGA,cAAc;QAAE,GAAGE,yBAAyB;IAAA;IAE/F,qEAAqE;IACrE,KAAK,MAAM,CAACS,aAAaC,OAAO,IAAIC,OAAOC,OAAO,CAACJ,eAAgB;QACjE,MAAMK,UAAU,MAAMlB,uBAAuBc,aAAaN;QAC1D,IAAI,CAACU,SAAS;YACZ,MAAM,IAAIC,MAAM,CAAC,2BAA2B,EAAEL,YAAY,CAAC,CAAC;QAC9D;QAEA,0CAA0C;QAC1C,MAAMM,eAAeJ,OAAOK,IAAI,CAACN,QAAQO,QAAQ,CAAC,CAACC,QAAQC;YACzD,MAAMC,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G5C,KAAK6C,KAAK,CAACC,IAAI,CAAC,KAAKnC,UAAUL,YAAY0E,MAAMK,QAAQ;YACtF;QACF;IACF;IAEA,OAAOR;AACT"}
1
+ {"version":3,"sources":["../../../src/actions/build/buildVendorDependencies.ts"],"sourcesContent":["import path from 'node:path'\n\nimport {gt, minVersion, rcompare, satisfies} from 'semver'\nimport {build} from 'vite'\n\nimport {getLocalPackageDir, getLocalPackageVersion} from '../../util/getLocalPackageVersion.js'\nimport {createExternalFromImportMap} from './createExternalFromImportMap.js'\n\n// Directory where vendor packages will be stored\nconst VENDOR_DIR = 'vendor'\n\n/**\n * A type representing the imports of vendor packages, defining specific entry\n * points for various versions and subpaths of the packages.\n *\n * The `VendorImports` object is used to build ESM browser-compatible versions\n * of the specified packages. This approach ensures that the appropriate version\n * and entry points are used for each package, enabling compatibility and proper\n * functionality in the browser environment.\n *\n * ## Rationale\n *\n * The rationale for this structure is to handle different versions of the\n * packages carefully, especially major versions. Major version bumps often\n * introduce breaking changes, so the module scheme for the package needs to be\n * checked when there is a major version update. However, minor and patch\n * versions are generally backward compatible, so they are handled more\n * leniently. By assuming that new minor versions are compatible, we avoid\n * unnecessary warnings and streamline the update process.\n *\n * If a new minor version introduces an additional subpath export within the\n * package of this version range, the corresponding package can add a more\n * specific version range that includes the new subpath. This design allows for\n * flexibility and ease of maintenance, ensuring that the latest features and\n * fixes are incorporated without extensive manual intervention.\n *\n * An additional subpath export within the package of this version range that\n * could cause the build to break if that new export is used, can be treated as\n * a bug fix. It might make more sense to our users that this new subpath isn't\n * supported yet until we address it as a bug fix. This approach helps maintain\n * stability and prevents unexpected issues during the build process.\n *\n * ## Structure\n * The `VendorImports` type is a nested object where:\n * - The keys at the first level represent the package names.\n * - The keys at the second level represent the version ranges (e.g., `^19.0.0`).\n * - The keys at the third level represent the subpaths within the package (e.g., `.` for the main entry point).\n * - The values at the third level are the relative paths to the corresponding entry points within the package.\n *\n * This structure allows for precise specification of the entry points for\n * different versions and subpaths, ensuring that the correct files are used\n * during the build process.\n */\ntype VendorImports = {\n [packageName: string]: {\n [versionRange: string]: {\n [subpath: string]: string\n }\n }\n}\n\n// Define the vendor packages and their corresponding versions and entry points\nconst VENDOR_IMPORTS: VendorImports = {\n react: {\n '^19.2.0': {\n '.': './cjs/react.production.js',\n './compiler-runtime': './cjs/react-compiler-runtime.production.js',\n './jsx-dev-runtime': './cjs/react-jsx-dev-runtime.production.js',\n './jsx-runtime': './cjs/react-jsx-runtime.production.js',\n './package.json': './package.json',\n },\n },\n 'react-dom': {\n '^19.2.0': {\n '.': './cjs/react-dom.production.js',\n './client': './cjs/react-dom-client.production.js',\n './package.json': './package.json',\n './server': './cjs/react-dom-server-legacy.browser.production.js',\n './server.browser': './cjs/react-dom-server-legacy.browser.production.js',\n './static': './cjs/react-dom-server.browser.production.js',\n './static.browser': './cjs/react-dom-server.browser.production.js',\n },\n },\n}\n\nconst STYLED_COMPONENTS_IMPORTS = {\n 'styled-components': {\n '^6.1.0': {\n '.': './dist/styled-components.browser.esm.js',\n './package.json': './package.json',\n },\n },\n}\n\ninterface VendorBuildOptions {\n basePath: string\n cwd: string\n isApp: boolean\n outputDir: string\n}\n\n/**\n * Builds the ESM browser compatible versions of the vendor packages\n * specified in VENDOR_IMPORTS. Returns the `imports` object of an import map.\n */\nexport async function buildVendorDependencies({\n basePath,\n cwd,\n isApp,\n outputDir,\n}: VendorBuildOptions): Promise<Record<string, string>> {\n const entry: Record<string, string> = {}\n const imports: Record<string, string> = {}\n\n // If we're building an app, we don't need to build the styled-components package\n const vendorImports = isApp ? VENDOR_IMPORTS : {...VENDOR_IMPORTS, ...STYLED_COMPONENTS_IMPORTS}\n\n // Iterate over each package and its version ranges in VENDOR_IMPORTS\n for (const [packageName, ranges] of Object.entries(vendorImports)) {\n const version = await getLocalPackageVersion(packageName, cwd)\n if (!version) {\n throw new Error(`Could not get version for '${packageName}'`)\n }\n\n // Sort version ranges in descending order\n const sortedRanges = Object.keys(ranges).toSorted((range1, range2) => {\n const min1 = minVersion(range1)\n const min2 = minVersion(range2)\n\n if (!min1) throw new Error(`Could not parse range '${range1}'`)\n if (!min2) throw new Error(`Could not parse range '${range2}'`)\n\n // sort them in reverse so we can rely on array `.find` below\n return rcompare(min1.version, min2.version)\n })\n\n // Find the first version range that satisfies the package version\n const matchedRange = sortedRanges.find((range) => satisfies(version, range))\n\n if (!matchedRange) {\n const min = minVersion(sortedRanges.at(-1)!)\n if (!min) {\n throw new Error(`Could not find a minimum version for package '${packageName}'`)\n }\n\n if (gt(min.version, version)) {\n throw new Error(`Package '${packageName}' requires at least ${min.version}.`)\n }\n\n throw new Error(`Version '${version}' of package '${packageName}' is not supported yet.`)\n }\n\n const subpaths = ranges[matchedRange]\n\n // Resolve the actual package directory using Node module resolution,\n // so that hoisted packages in monorepos/workspaces are found correctly\n const packageDir = getLocalPackageDir(packageName, cwd)\n\n // Iterate over each subpath and its corresponding entry point\n for (const [subpath, relativeEntryPoint] of Object.entries(subpaths)) {\n const specifier = path.posix.join(packageName, subpath)\n const chunkName = path.posix.join(\n packageName,\n path.relative(packageName, specifier) || 'index',\n )\n\n entry[chunkName] = path.join(packageDir, relativeEntryPoint)\n imports[specifier] = path.posix.join('/', basePath, VENDOR_DIR, `${chunkName}.mjs`)\n }\n }\n\n // removes the `RollupWatcher` type\n type BuildResult = Exclude<Awaited<ReturnType<typeof build>>, {close: unknown}>\n\n // Use Vite to build the packages into the output directory\n let buildResult = (await build({\n appType: 'custom',\n build: {\n commonjsOptions: {strictRequires: 'auto'},\n emptyOutDir: false, // Rely on CLI to do this\n lib: {entry, formats: ['es']},\n minify: true,\n outDir: path.join(outputDir, VENDOR_DIR),\n rollupOptions: {\n external: createExternalFromImportMap({imports}),\n output: {\n chunkFileNames: '[name]-[hash].mjs',\n entryFileNames: '[name]-[hash].mjs',\n exports: 'named',\n format: 'es',\n },\n treeshake: {preset: 'recommended'},\n },\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: 'node_modules/.sanity/vite-vendor',\n configFile: false,\n define: {'process.env.NODE_ENV': JSON.stringify('production')},\n logLevel: 'silent',\n mode: 'production',\n root: cwd,\n })) as BuildResult\n\n buildResult = Array.isArray(buildResult) ? buildResult : [buildResult]\n\n // Create a map of the original import specifiers to their hashed filenames\n const hashedImports: Record<string, string> = {}\n const output = buildResult.flatMap((i) => i.output)\n\n for (const chunk of output) {\n if (chunk.type === 'asset') continue\n\n for (const [specifier, originalPath] of Object.entries(imports)) {\n if (originalPath.endsWith(`${chunk.name}.mjs`)) {\n hashedImports[specifier] = path.posix.join('/', basePath, VENDOR_DIR, chunk.fileName)\n }\n }\n }\n\n return hashedImports\n}\n"],"names":["path","gt","minVersion","rcompare","satisfies","build","getLocalPackageDir","getLocalPackageVersion","createExternalFromImportMap","VENDOR_DIR","VENDOR_IMPORTS","react","STYLED_COMPONENTS_IMPORTS","buildVendorDependencies","basePath","cwd","isApp","outputDir","entry","imports","vendorImports","packageName","ranges","Object","entries","version","Error","sortedRanges","keys","toSorted","range1","range2","min1","min2","matchedRange","find","range","min","at","subpaths","packageDir","subpath","relativeEntryPoint","specifier","posix","join","chunkName","relative","buildResult","appType","commonjsOptions","strictRequires","emptyOutDir","lib","formats","minify","outDir","rollupOptions","external","output","chunkFileNames","entryFileNames","exports","format","treeshake","preset","cacheDir","configFile","define","JSON","stringify","logLevel","mode","root","Array","isArray","hashedImports","flatMap","i","chunk","type","originalPath","endsWith","name","fileName"],"mappings":"AAAA,OAAOA,UAAU,YAAW;AAE5B,SAAQC,EAAE,EAAEC,UAAU,EAAEC,QAAQ,EAAEC,SAAS,QAAO,SAAQ;AAC1D,SAAQC,KAAK,QAAO,OAAM;AAE1B,SAAQC,kBAAkB,EAAEC,sBAAsB,QAAO,uCAAsC;AAC/F,SAAQC,2BAA2B,QAAO,mCAAkC;AAE5E,iDAAiD;AACjD,MAAMC,aAAa;AAoDnB,+EAA+E;AAC/E,MAAMC,iBAAgC;IACpCC,OAAO;QACL,WAAW;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