@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.
- package/README.md +14 -8
- package/dist/actions/build/buildApp.js +12 -4
- package/dist/actions/build/buildApp.js.map +1 -1
- package/dist/actions/build/buildStaticFiles.js +3 -1
- package/dist/actions/build/buildStaticFiles.js.map +1 -1
- package/dist/actions/build/buildStudio.js +29 -7
- package/dist/actions/build/buildStudio.js.map +1 -1
- package/dist/actions/build/buildVendorDependencies.js +7 -7
- package/dist/actions/build/buildVendorDependencies.js.map +1 -1
- package/dist/actions/build/checkRequiredDependencies.js +4 -4
- package/dist/actions/build/checkRequiredDependencies.js.map +1 -1
- package/dist/actions/build/checkStudioDependencyVersions.js +9 -9
- package/dist/actions/build/checkStudioDependencyVersions.js.map +1 -1
- package/dist/actions/build/getAutoUpdatesImportMap.js +9 -0
- package/dist/actions/build/getAutoUpdatesImportMap.js.map +1 -1
- package/dist/actions/build/getViteConfig.js +2 -1
- package/dist/actions/build/getViteConfig.js.map +1 -1
- package/dist/actions/build/renderDocument.js.map +1 -1
- package/dist/actions/build/renderDocumentWorker/addTimestampImportMapScriptToHtml.js +34 -14
- package/dist/actions/build/renderDocumentWorker/addTimestampImportMapScriptToHtml.js.map +1 -1
- package/dist/actions/build/renderDocumentWorker/getDocumentHtml.js +2 -2
- package/dist/actions/build/renderDocumentWorker/getDocumentHtml.js.map +1 -1
- package/dist/actions/build/renderDocumentWorker/renderDocumentWorker.js +2 -2
- package/dist/actions/build/renderDocumentWorker/renderDocumentWorker.js.map +1 -1
- package/dist/actions/codemods/reactIconsV3.js +2 -2
- package/dist/actions/codemods/reactIconsV3.js.map +1 -1
- package/dist/actions/dev/startStudioDevServer.js +2 -2
- package/dist/actions/dev/startStudioDevServer.js.map +1 -1
- package/dist/actions/doctor/types.js.map +1 -1
- package/dist/actions/graphql/resolveGraphQLApisFromWorkspaces.js.map +1 -1
- package/dist/actions/init/bootstrapTemplate.js.map +1 -1
- package/dist/actions/init/checkNextJsReactCompatibility.js +3 -3
- package/dist/actions/init/checkNextJsReactCompatibility.js.map +1 -1
- package/dist/actions/init/initAction.js +287 -0
- package/dist/actions/init/initAction.js.map +1 -0
- package/dist/actions/init/initApp.js +7 -16
- package/dist/actions/init/initApp.js.map +1 -1
- package/dist/actions/init/initError.js +10 -0
- package/dist/actions/init/initError.js.map +1 -0
- package/dist/actions/init/initHelpers.js +3 -12
- package/dist/actions/init/initHelpers.js.map +1 -1
- package/dist/actions/init/initNextJs.js +17 -20
- package/dist/actions/init/initNextJs.js.map +1 -1
- package/dist/actions/init/initStudio.js +11 -20
- package/dist/actions/init/initStudio.js.map +1 -1
- package/dist/actions/init/plan/getPlan.js +15 -0
- package/dist/actions/init/plan/getPlan.js.map +1 -0
- package/dist/actions/init/plan/verifyCoupon.js +35 -0
- package/dist/actions/init/plan/verifyCoupon.js.map +1 -0
- package/dist/actions/init/plan/verifyPlan.js +34 -0
- package/dist/actions/init/plan/verifyPlan.js.map +1 -0
- package/dist/actions/init/project/createProjectFromName.js +44 -0
- package/dist/actions/init/project/createProjectFromName.js.map +1 -0
- package/dist/actions/init/project/getOrCreateDataset.js +126 -0
- package/dist/actions/init/project/getOrCreateDataset.js.map +1 -0
- package/dist/actions/init/project/getOrCreateProject.js +128 -0
- package/dist/actions/init/project/getOrCreateProject.js.map +1 -0
- package/dist/actions/init/project/getProjectDetails.js +87 -0
- package/dist/actions/init/project/getProjectDetails.js.map +1 -0
- package/dist/actions/init/project/getProjectOutputPath.js +17 -0
- package/dist/actions/init/project/getProjectOutputPath.js.map +1 -0
- package/dist/actions/init/project/promptForAppTemplateSetup.js +112 -0
- package/dist/actions/init/project/promptForAppTemplateSetup.js.map +1 -0
- package/dist/actions/init/project/promptForProjectCreation.js +40 -0
- package/dist/actions/init/project/promptForProjectCreation.js.map +1 -0
- package/dist/actions/init/project/promptUserForNewOrganization.js +12 -0
- package/dist/actions/init/project/promptUserForNewOrganization.js.map +1 -0
- package/dist/actions/init/project/promptUserForOrganization.js +38 -0
- package/dist/actions/init/project/promptUserForOrganization.js.map +1 -0
- package/dist/actions/init/scaffoldTemplate.js +23 -29
- package/dist/actions/init/scaffoldTemplate.js.map +1 -1
- package/dist/actions/init/types.js +47 -1
- package/dist/actions/init/types.js.map +1 -1
- package/dist/actions/manifest/types.js +0 -1
- package/dist/actions/manifest/types.js.map +1 -1
- package/dist/actions/versions/buildPackageArray.js +2 -2
- package/dist/actions/versions/buildPackageArray.js.map +1 -1
- package/dist/actions/versions/findSanityModulesVersions.js +3 -3
- package/dist/actions/versions/findSanityModulesVersions.js.map +1 -1
- package/dist/commands/datasets/copy.js.map +1 -1
- package/dist/commands/init.js +11 -911
- package/dist/commands/init.js.map +1 -1
- package/dist/server/vite/plugin-sanity-build-entries.js +2 -1
- package/dist/server/vite/plugin-sanity-build-entries.js.map +1 -1
- package/dist/services/datasets.js.map +1 -1
- package/dist/telemetry/init.telemetry.js.map +1 -1
- package/dist/util/compareDependencyVersions.js +4 -4
- package/dist/util/compareDependencyVersions.js.map +1 -1
- package/dist/util/createExpiringConfig.js +1 -1
- package/dist/util/createExpiringConfig.js.map +1 -1
- package/dist/util/packageManager/installationInfo/analyzeIssues.js +7 -7
- package/dist/util/packageManager/installationInfo/analyzeIssues.js.map +1 -1
- package/dist/util/packageManager/installationInfo/types.js.map +1 -1
- package/dist/util/packageManager/packageManagerChoice.js +2 -2
- package/dist/util/packageManager/packageManagerChoice.js.map +1 -1
- package/dist/util/packageManager/preferredPm.js +106 -0
- package/dist/util/packageManager/preferredPm.js.map +1 -0
- package/oclif.manifest.json +526 -526
- package/package.json +23 -22
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import path from 'node:path';
|
|
2
2
|
import { readPackageJson } from '@sanity/cli-core';
|
|
3
3
|
import { oneline } from 'oneline';
|
|
4
|
-
import
|
|
4
|
+
import { minVersion, satisfies } from 'semver';
|
|
5
5
|
import { determineIsApp } from '../../util/determineIsApp.js';
|
|
6
6
|
import { getLocalPackageVersion } from '../../util/getLocalPackageVersion.js';
|
|
7
7
|
const defaultStudioManifestProps = {
|
|
@@ -67,7 +67,7 @@ const styledComponentsVersionRange = '^6.1.15';
|
|
|
67
67
|
// Theoretically the version specified in package.json could be incorrect, eg `foo`
|
|
68
68
|
let minDeclaredStyledComponentsVersion = null;
|
|
69
69
|
try {
|
|
70
|
-
minDeclaredStyledComponentsVersion =
|
|
70
|
+
minDeclaredStyledComponentsVersion = minVersion(declaredStyledComponentsVersion);
|
|
71
71
|
} catch {
|
|
72
72
|
// Intentional fall-through (variable will be left as null, throwing below)
|
|
73
73
|
}
|
|
@@ -88,7 +88,7 @@ const styledComponentsVersionRange = '^6.1.15';
|
|
|
88
88
|
// Exception: Ranges are hard to compare. `>=5.0.0 && <=5.3.2 || ^6`... Comparing this
|
|
89
89
|
// to anything is going to be challenging, so only compare "simple" ranges/versions
|
|
90
90
|
// (^x.x.x / ~x.x.x / x.x.x)
|
|
91
|
-
if (!isStyledComponentsVersionRangeInCatalog && isComparableRange(declaredStyledComponentsVersion) && !
|
|
91
|
+
if (!isStyledComponentsVersionRangeInCatalog && isComparableRange(declaredStyledComponentsVersion) && !satisfies(minDeclaredStyledComponentsVersion, wantedStyledComponentsVersionRange)) {
|
|
92
92
|
output.warn(oneline`
|
|
93
93
|
Declared version of styled-components (${declaredStyledComponentsVersion})
|
|
94
94
|
is not compatible with the version required by sanity (${wantedStyledComponentsVersionRange}).
|
|
@@ -109,7 +109,7 @@ const styledComponentsVersionRange = '^6.1.15';
|
|
|
109
109
|
}
|
|
110
110
|
// The studio should have an _installed_ version of `styled-components`, and it should
|
|
111
111
|
// be semver compatible with the version specified in `sanity` peer dependencies.
|
|
112
|
-
if (!
|
|
112
|
+
if (!satisfies(installedStyledComponentsVersion, wantedStyledComponentsVersionRange)) {
|
|
113
113
|
output.warn(oneline`
|
|
114
114
|
Installed version of styled-components (${installedStyledComponentsVersion})
|
|
115
115
|
is not compatible with the version required by sanity (${wantedStyledComponentsVersionRange}).
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/actions/build/checkRequiredDependencies.ts"],"sourcesContent":["import path from 'node:path'\n\nimport {type CliConfig, type Output, type PackageJson, readPackageJson} from '@sanity/cli-core'\nimport {oneline} from 'oneline'\nimport
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/build/checkRequiredDependencies.ts"],"sourcesContent":["import path from 'node:path'\n\nimport {type CliConfig, type Output, type PackageJson, readPackageJson} from '@sanity/cli-core'\nimport {oneline} from 'oneline'\nimport {minVersion, satisfies, type SemVer} from 'semver'\n\nimport {determineIsApp} from '../../util/determineIsApp.js'\nimport {getLocalPackageVersion} from '../../util/getLocalPackageVersion.js'\n\nconst defaultStudioManifestProps: Partial<PackageJson> = {\n name: 'studio',\n version: '1.0.0',\n}\n\ninterface CheckResult {\n installedSanityVersion: string\n}\n\ninterface CheckRequiredDependenciesOptions {\n cliConfig: CliConfig\n output: Output\n workDir: string\n}\n\nconst styledComponentsVersionRange = '^6.1.15'\n\n/**\n * Checks that the studio has declared and installed the required dependencies\n * needed by the Sanity modules. While we generally use regular, explicit\n * dependencies in modules, there are certain dependencies that are better\n * served being peer dependencies, such as react and styled-components.\n *\n * If these dependencies are not installed/declared, we report an error\n * and instruct the user to install them manually.\n *\n * Additionally, returns the version of the 'sanity' dependency from the package.json.\n */\nexport async function checkRequiredDependencies(\n options: CheckRequiredDependenciesOptions,\n): Promise<CheckResult> {\n const {cliConfig, output, workDir: studioPath} = options\n // currently there's no check needed for core apps,\n // but this should be removed once they are more mature\n const isApp = determineIsApp(cliConfig)\n if (isApp) {\n return {installedSanityVersion: ''}\n }\n\n const [studioPackageManifest, installedStyledComponentsVersion, installedSanityVersion] =\n await Promise.all([\n readPackageJson(path.join(studioPath, 'package.json'), {\n defaults: defaultStudioManifestProps,\n skipSchemaValidation: true,\n }),\n getLocalPackageVersion('styled-components', studioPath),\n getLocalPackageVersion('sanity', studioPath),\n ])\n\n const wantedStyledComponentsVersionRange = styledComponentsVersionRange\n\n // Retrieve the version of the 'sanity' dependency\n if (!installedSanityVersion) {\n output.error('Failed to read the installed sanity version.', {exit: 1})\n return {installedSanityVersion: ''}\n }\n\n // The studio _must_ now declare `styled-components` as a dependency. If it's not there,\n // we'll want to automatically _add it_ to the manifest and tell the user to reinstall\n // dependencies before running whatever command was being run\n const declaredStyledComponentsVersion =\n studioPackageManifest.dependencies?.['styled-components'] ||\n studioPackageManifest?.devDependencies?.['styled-components']\n\n if (!declaredStyledComponentsVersion) {\n output.error(\n oneline`\n Declared dependency \\`styled-components\\` is not installed - run\n \\`npm install\\`, \\`yarn install\\` or \\`pnpm install\\` to install it before re-running this command.\n `,\n {exit: 1},\n )\n return {installedSanityVersion}\n }\n\n // We ignore catalog identifiers since we check the actual version anyway\n const isStyledComponentsVersionRangeInCatalog =\n declaredStyledComponentsVersion.startsWith('catalog:')\n // Theoretically the version specified in package.json could be incorrect, eg `foo`\n let minDeclaredStyledComponentsVersion: SemVer | null = null\n try {\n minDeclaredStyledComponentsVersion = minVersion(declaredStyledComponentsVersion)\n } catch {\n // Intentional fall-through (variable will be left as null, throwing below)\n }\n\n if (!minDeclaredStyledComponentsVersion && !isStyledComponentsVersionRangeInCatalog) {\n output.error(\n oneline`\n Declared dependency \\`styled-components\\` has an invalid version range:\n \\`${declaredStyledComponentsVersion}\\`.\n `,\n {exit: 1},\n )\n return {installedSanityVersion}\n }\n\n // The declared version should be semver-compatible with the version specified as a\n // peer dependency in `sanity`. If not, we should tell the user to change it.\n //\n // Exception: Ranges are hard to compare. `>=5.0.0 && <=5.3.2 || ^6`... Comparing this\n // to anything is going to be challenging, so only compare \"simple\" ranges/versions\n // (^x.x.x / ~x.x.x / x.x.x)\n if (\n !isStyledComponentsVersionRangeInCatalog &&\n isComparableRange(declaredStyledComponentsVersion) &&\n !satisfies(minDeclaredStyledComponentsVersion!, wantedStyledComponentsVersionRange)\n ) {\n output.warn(oneline`\n Declared version of styled-components (${declaredStyledComponentsVersion})\n is not compatible with the version required by sanity (${wantedStyledComponentsVersionRange}).\n This might cause problems!\n `)\n }\n\n // Ensure the studio has _installed_ a version of `styled-components`\n if (!installedStyledComponentsVersion) {\n output.error(\n oneline`\n Declared dependency \\`styled-components\\` is not installed - run\n \\`npm install\\`, \\`yarn install\\` or \\`pnpm install\\` to install it before re-running this command.\n `,\n {exit: 1},\n )\n return {installedSanityVersion}\n }\n\n // The studio should have an _installed_ version of `styled-components`, and it should\n // be semver compatible with the version specified in `sanity` peer dependencies.\n if (!satisfies(installedStyledComponentsVersion, wantedStyledComponentsVersionRange)) {\n output.warn(oneline`\n Installed version of styled-components (${installedStyledComponentsVersion})\n is not compatible with the version required by sanity (${wantedStyledComponentsVersionRange}).\n This might cause problems!\n `)\n }\n\n return {installedSanityVersion}\n}\n\nfunction isComparableRange(range: string): boolean {\n return /^[\\^~]?\\d+(\\.\\d+)?(\\.\\d+)?$/.test(range)\n}\n"],"names":["path","readPackageJson","oneline","minVersion","satisfies","determineIsApp","getLocalPackageVersion","defaultStudioManifestProps","name","version","styledComponentsVersionRange","checkRequiredDependencies","options","cliConfig","output","workDir","studioPath","isApp","installedSanityVersion","studioPackageManifest","installedStyledComponentsVersion","Promise","all","join","defaults","skipSchemaValidation","wantedStyledComponentsVersionRange","error","exit","declaredStyledComponentsVersion","dependencies","devDependencies","isStyledComponentsVersionRangeInCatalog","startsWith","minDeclaredStyledComponentsVersion","isComparableRange","warn","range","test"],"mappings":"AAAA,OAAOA,UAAU,YAAW;AAE5B,SAAuDC,eAAe,QAAO,mBAAkB;AAC/F,SAAQC,OAAO,QAAO,UAAS;AAC/B,SAAQC,UAAU,EAAEC,SAAS,QAAoB,SAAQ;AAEzD,SAAQC,cAAc,QAAO,+BAA8B;AAC3D,SAAQC,sBAAsB,QAAO,uCAAsC;AAE3E,MAAMC,6BAAmD;IACvDC,MAAM;IACNC,SAAS;AACX;AAYA,MAAMC,+BAA+B;AAErC;;;;;;;;;;C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IAEA,mFAAmF;IACnF,6EAA6E;IAC7E,EAAE;IACF,sFAAsF;IACtF,mFAAmF;IACnF,4BAA4B;IAC5B,IACE,CAACc,2CACDG,kBAAkBN,oCAClB,CAACzB,UAAU8B,oCAAqCR,qCAChD;QACAZ,OAAOsB,IAAI,CAAClC,OAAO,CAAC;6CACqB,EAAE2B,gCAAgC;6DAClB,EAAEH,mCAAmC;;IAE9F,CAAC;IACH;IAEA,qEAAqE;IACrE,IAAI,CAACN,kCAAkC;QACrCN,OAAOa,KAAK,CACVzB,OAAO,CAAC;;;IAGV,CAAC,EACC;YAAC0B,MAAM;QAAC;QAEV,OAAO;YAACV;QAAsB;IAChC;IAEA,sFAAsF;IACtF,iFAAiF;IACjF,IAAI,CAACd,UAAUgB,kCAAkCM,qCAAqC;QACpFZ,OAAOsB,IAAI,CAAClC,OAAO,CAAC;8CACsB,EAAEkB,iCAAiC;6DACpB,EAAEM,mCAAmC;;IAE9F,CAAC;IACH;IAEA,OAAO;QAACR;IAAsB;AAChC;AAEA,SAASiB,kBAAkBE,KAAa;IACtC,OAAO,8BAA8BC,IAAI,CAACD;AAC5C"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import path from 'node:path';
|
|
2
2
|
import { readPackageJson } from '@sanity/cli-core';
|
|
3
|
-
import
|
|
3
|
+
import { coerce, gtr, ltr, rcompare, satisfies } from 'semver';
|
|
4
4
|
import { getLocalPackageVersion } from '../../util/getLocalPackageVersion.js';
|
|
5
5
|
// NOTE: when doing changes here, also remember to update versions in help docs at
|
|
6
6
|
// https://sanity.io/admin/structure/docs;helpArticle;upgrade-packages
|
|
@@ -49,7 +49,7 @@ export async function checkStudioDependencyVersions(workDir, output, { packages
|
|
|
49
49
|
return false;
|
|
50
50
|
}
|
|
51
51
|
const packageVersion = await getLocalPackageVersion(pkg.name, workDir);
|
|
52
|
-
const installed =
|
|
52
|
+
const installed = coerce(packageVersion ?? dependency.replaceAll(/[\D.]/g, ''));
|
|
53
53
|
if (!installed) {
|
|
54
54
|
return false;
|
|
55
55
|
}
|
|
@@ -58,13 +58,13 @@ export async function checkStudioDependencyVersions(workDir, output, { packages
|
|
|
58
58
|
// before a release, but given that is usually works in a backwards-compatible way, we want
|
|
59
59
|
// to indicate that it's _untested_, not necessarily _unsupported_
|
|
60
60
|
// Ex: Installed is react@20.0.0, but we've only _tested_ with react@^19
|
|
61
|
-
const isUntested = !
|
|
61
|
+
const isUntested = !satisfies(installed, supported) && gtr(installed, supported);
|
|
62
62
|
// "Unsupported" in that the installed version is _lower than_ the minimum version
|
|
63
63
|
// Ex: Installed is react@18.0.0, but we require react@^19.2
|
|
64
|
-
const isUnsupported = !
|
|
64
|
+
const isUnsupported = !satisfies(installed, supported) && !isUntested;
|
|
65
65
|
// "Deprecated" in that we will stop supporting it at some point in the near future,
|
|
66
66
|
// so users should be prompted to upgrade
|
|
67
|
-
const isDeprecated = pkg.deprecatedBelow ?
|
|
67
|
+
const isDeprecated = pkg.deprecatedBelow ? ltr(installed, pkg.deprecatedBelow) : false;
|
|
68
68
|
return {
|
|
69
69
|
...pkg,
|
|
70
70
|
installed,
|
|
@@ -113,9 +113,9 @@ function listPackages(pkgs) {
|
|
|
113
113
|
}
|
|
114
114
|
function getUpgradeInstructions(pkgs) {
|
|
115
115
|
const inst = pkgs.map((pkg)=>{
|
|
116
|
-
const [highestSupported] = pkg.supported.map((version)=>(
|
|
116
|
+
const [highestSupported] = pkg.supported.map((version)=>(coerce(version) || {
|
|
117
117
|
version: ''
|
|
118
|
-
}).version).toSorted(
|
|
118
|
+
}).version).toSorted(rcompare);
|
|
119
119
|
return `"${pkg.name}@^${highestSupported}"`;
|
|
120
120
|
}).join(' ');
|
|
121
121
|
return `To upgrade, run either:
|
|
@@ -135,9 +135,9 @@ Read more at https://www.sanity.io/docs/help/upgrade-packages`;
|
|
|
135
135
|
}
|
|
136
136
|
function getDowngradeInstructions(pkgs) {
|
|
137
137
|
const inst = pkgs.map((pkg)=>{
|
|
138
|
-
const [highestSupported] = pkg.supported.map((version)=>(
|
|
138
|
+
const [highestSupported] = pkg.supported.map((version)=>(coerce(version) || {
|
|
139
139
|
version: ''
|
|
140
|
-
}).version).toSorted(
|
|
140
|
+
}).version).toSorted(rcompare);
|
|
141
141
|
return `"${pkg.name}@^${highestSupported}"`;
|
|
142
142
|
}).join(' ');
|
|
143
143
|
return `To downgrade, run either:
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/actions/build/checkStudioDependencyVersions.ts"],"sourcesContent":["import path from 'node:path'\n\nimport {type Output, readPackageJson} from '@sanity/cli-core'\nimport
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/build/checkStudioDependencyVersions.ts"],"sourcesContent":["import path from 'node:path'\n\nimport {type Output, readPackageJson} from '@sanity/cli-core'\nimport {coerce, gtr, ltr, rcompare, satisfies, type SemVer} from 'semver'\n\nimport {getLocalPackageVersion} from '../../util/getLocalPackageVersion.js'\n\ninterface PackageInfo {\n deprecatedBelow: string | null\n installed: SemVer\n isDeprecated: boolean\n isUnsupported: boolean\n isUntested: boolean\n name: string\n supported: string[]\n}\n\ninterface TrackedPackage {\n deprecatedBelow: string | null\n name: string\n supported: string[]\n}\n\n// NOTE: when doing changes here, also remember to update versions in help docs at\n// https://sanity.io/admin/structure/docs;helpArticle;upgrade-packages\nconst DEFAULT_PACKAGES: TrackedPackage[] = [\n {deprecatedBelow: null, name: 'react', supported: ['^19.2.2']},\n {deprecatedBelow: null, name: 'react-dom', supported: ['^19.2.2']},\n {deprecatedBelow: null, name: 'styled-components', supported: ['^6']},\n {deprecatedBelow: '^3', name: '@sanity/ui', supported: ['^2', '^3']},\n]\n\nexport async function checkStudioDependencyVersions(\n workDir: string,\n output: Output,\n {packages = DEFAULT_PACKAGES}: {packages?: TrackedPackage[]} = {},\n): Promise<void> {\n const manifest = await readPackageJson(path.join(workDir, 'package.json'), {\n skipSchemaValidation: true,\n })\n const dependencies = {...manifest?.dependencies, ...manifest?.devDependencies}\n\n const packageInfo = packages.map(async (pkg): Promise<false | PackageInfo> => {\n const dependency = dependencies[pkg.name]\n if (!dependency) {\n return false\n }\n\n const packageVersion = await getLocalPackageVersion(pkg.name, workDir)\n const installed = coerce(packageVersion ?? dependency.replaceAll(/[\\D.]/g, ''))\n\n if (!installed) {\n return false\n }\n\n const supported = pkg.supported.join(' || ')\n\n // \"Untested\" is usually the case where we have not upgraded the React version requirements\n // before a release, but given that is usually works in a backwards-compatible way, we want\n // to indicate that it's _untested_, not necessarily _unsupported_\n // Ex: Installed is react@20.0.0, but we've only _tested_ with react@^19\n const isUntested = !satisfies(installed, supported) && gtr(installed, supported)\n\n // \"Unsupported\" in that the installed version is _lower than_ the minimum version\n // Ex: Installed is react@18.0.0, but we require react@^19.2\n const isUnsupported = !satisfies(installed, supported) && !isUntested\n\n // \"Deprecated\" in that we will stop supporting it at some point in the near future,\n // so users should be prompted to upgrade\n const isDeprecated = pkg.deprecatedBelow ? ltr(installed, pkg.deprecatedBelow) : false\n\n return {\n ...pkg,\n installed,\n isDeprecated,\n isUnsupported,\n isUntested,\n }\n })\n\n const installedPackages = (await Promise.all(packageInfo)).filter(\n (inp): inp is PackageInfo => inp !== false,\n )\n const unsupported = installedPackages.filter((pkg) => pkg.isUnsupported)\n const deprecated = installedPackages.filter((pkg) => !pkg.isUnsupported && pkg.isDeprecated)\n const untested = installedPackages.filter((pkg) => pkg.isUntested)\n\n if (deprecated.length > 0) {\n output.warn(`The following package versions have been deprecated and should be upgraded:\n\n ${listPackages(deprecated)}\n\nSupport for these will be removed in a future release!\n\n ${getUpgradeInstructions(deprecated)}\n`)\n }\n\n if (untested.length > 0) {\n output.warn(`The following package versions have not yet been marked as supported:\n\n ${listPackages(untested)}\n\nYou _may_ encounter bugs while using these versions.\n\n ${getDowngradeInstructions(untested)}\n`)\n }\n\n if (unsupported.length > 0) {\n output.error(\n `The following package versions are no longer supported and needs to be upgraded:\n\n ${listPackages(unsupported)}\n\n ${getUpgradeInstructions(unsupported)}\n`,\n {exit: 1},\n )\n }\n}\n\nfunction listPackages(pkgs: PackageInfo[]) {\n return pkgs\n .map(\n (pkg) =>\n `${pkg.name} (installed: ${pkg.installed}, want: ${\n pkg.deprecatedBelow || pkg.supported.join(' || ')\n })`,\n )\n .join('\\n ')\n}\n\nfunction getUpgradeInstructions(pkgs: PackageInfo[]) {\n const inst = pkgs\n .map((pkg) => {\n const [highestSupported] = pkg.supported\n .map((version) => (coerce(version) || {version: ''}).version)\n .toSorted(rcompare)\n\n return `\"${pkg.name}@^${highestSupported}\"`\n })\n .join(' ')\n\n return `To upgrade, run either:\n\n npm install ${inst}\n\n or\n\n yarn add ${inst}\n\n or\n\n pnpm add ${inst}\n\n\nRead more at https://www.sanity.io/docs/help/upgrade-packages`\n}\n\nfunction getDowngradeInstructions(pkgs: PackageInfo[]) {\n const inst = pkgs\n .map((pkg) => {\n const [highestSupported] = pkg.supported\n .map((version) => (coerce(version) || {version: ''}).version)\n .toSorted(rcompare)\n\n return `\"${pkg.name}@^${highestSupported}\"`\n })\n .join(' ')\n\n return `To downgrade, run either:\n\n yarn add ${inst}\n\n or\n\n npm install ${inst}\n\n or\n\n pnpm install ${inst}`\n}\n"],"names":["path","readPackageJson","coerce","gtr","ltr","rcompare","satisfies","getLocalPackageVersion","DEFAULT_PACKAGES","deprecatedBelow","name","supported","checkStudioDependencyVersions","workDir","output","packages","manifest","join","skipSchemaValidation","dependencies","devDependencies","packageInfo","map","pkg","dependency","packageVersion","installed","replaceAll","isUntested","isUnsupported","isDeprecated","installedPackages","Promise","all","filter","inp","unsupported","deprecated","untested","length","warn","listPackages","getUpgradeInstructions","getDowngradeInstructions","error","exit","pkgs","inst","highestSupported","version","toSorted"],"mappings":"AAAA,OAAOA,UAAU,YAAW;AAE5B,SAAqBC,eAAe,QAAO,mBAAkB;AAC7D,SAAQC,MAAM,EAAEC,GAAG,EAAEC,GAAG,EAAEC,QAAQ,EAAEC,SAAS,QAAoB,SAAQ;AAEzE,SAAQC,sBAAsB,QAA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OD,KACVxB,GAAG,CAAC,CAACC;QACJ,MAAM,CAACyB,iBAAiB,GAAGzB,IAAIZ,SAAS,CACrCW,GAAG,CAAC,CAAC2B,UAAY,AAAC/C,CAAAA,OAAO+C,YAAY;gBAACA,SAAS;YAAE,CAAA,EAAGA,OAAO,EAC3DC,QAAQ,CAAC7C;QAEZ,OAAO,CAAC,CAAC,EAAEkB,IAAIb,IAAI,CAAC,EAAE,EAAEsC,iBAAiB,CAAC,CAAC;IAC7C,GACC/B,IAAI,CAAC;IAER,OAAO,CAAC;;cAEI,EAAE8B,KAAK;;;;WAIV,EAAEA,KAAK;;;;WAIP,EAAEA,KAAK;;;6DAG2C,CAAC;AAC9D;AAEA,SAASJ,yBAAyBG,IAAmB;IACnD,MAAMC,OAAOD,KACVxB,GAAG,CAAC,CAACC;QACJ,MAAM,CAACyB,iBAAiB,GAAGzB,IAAIZ,SAAS,CACrCW,GAAG,CAAC,CAAC2B,UAAY,AAAC/C,CAAAA,OAAO+C,YAAY;gBAACA,SAAS;YAAE,CAAA,EAAGA,OAAO,EAC3DC,QAAQ,CAAC7C;QAEZ,OAAO,CAAC,CAAC,EAAEkB,IAAIb,IAAI,CAAC,EAAE,EAAEsC,iBAAiB,CAAC,CAAC;IAC7C,GACC/B,IAAI,CAAC;IAER,OAAO,CAAC;;WAEC,EAAE8B,KAAK;;;;cAIJ,EAAEA,KAAK;;;;eAIN,EAAEA,MAAM;AACvB"}
|
|
@@ -53,5 +53,14 @@ function getByAppModuleUrl(pkg, options) {
|
|
|
53
53
|
const [scope, ...pkg] = pkgName.split('/');
|
|
54
54
|
return `${scope}__${pkg.join('')}`;
|
|
55
55
|
}
|
|
56
|
+
/**
|
|
57
|
+
* Generate CDN CSS URLs for auto-updated packages.
|
|
58
|
+
* Uses the same URL pattern as JS module URLs so the module server
|
|
59
|
+
* resolves CSS and JS to the same version.
|
|
60
|
+
*
|
|
61
|
+
* @internal
|
|
62
|
+
*/ export function getAutoUpdatesCssUrls(packages, options = {}) {
|
|
63
|
+
return packages.filter((pkg)=>Boolean(pkg.cssFile)).map((pkg)=>`${getModuleUrl(pkg, options)}/${pkg.cssFile}`);
|
|
64
|
+
}
|
|
56
65
|
|
|
57
66
|
//# sourceMappingURL=getAutoUpdatesImportMap.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/actions/build/getAutoUpdatesImportMap.ts"],"sourcesContent":["const MODULES_HOST =\n process.env.SANITY_MODULES_HOST ||\n (process.env.SANITY_INTERNAL_ENV === 'staging'\n ? 'https://sanity-cdn.work'\n : 'https://sanity-cdn.com')\n\nfunction currentUnixTime(): number {\n return Math.floor(Date.now() / 1000)\n}\n\ntype Package = {name: string; version: string}\n/**\n * @internal\n */\nexport function getAutoUpdatesImportMap<const Pkg extends Package>(\n packages: Pkg[],\n options: {appId?: string; baseUrl?: string; timestamp?: number} = {},\n) {\n return Object.fromEntries(\n packages.flatMap((pkg) => getAppAutoUpdateImportMapForPackage(pkg, options)),\n ) as {[K in `${Pkg['name']}/` | Pkg['name']]: string}\n}\n\n/**\n * @internal\n */\nfunction getAppAutoUpdateImportMapForPackage<const Pkg extends Package>(\n pkg: Pkg,\n options: {appId?: string; baseUrl?: string; timestamp?: number} = {},\n): [[Pkg['name'], string], [`${Pkg['name']}/`, string]] {\n const moduleUrl = getModuleUrl(pkg, options)\n\n return [\n [pkg.name, moduleUrl],\n [`${pkg.name}/`, `${moduleUrl}/`],\n ]\n}\n\n/**\n * @internal\n */\nexport function getModuleUrl(\n pkg: Package,\n options: {appId?: string; baseUrl?: string; timestamp?: number} = {},\n) {\n const {timestamp = currentUnixTime()} = options\n return options.appId\n ? getByAppModuleUrl(pkg, {appId: options.appId, baseUrl: options.baseUrl, timestamp})\n : getLegacyModuleUrl(pkg, {baseUrl: options.baseUrl, timestamp})\n}\n\nfunction getLegacyModuleUrl(pkg: Package, options: {baseUrl?: string; timestamp: number}) {\n const encodedMinVer = encodeURIComponent(`^${pkg.version}`)\n return `${options.baseUrl || MODULES_HOST}/v1/modules/${rewriteScopedPackage(pkg.name)}/default/${encodedMinVer}/t${options.timestamp}`\n}\n\nfunction getByAppModuleUrl(\n pkg: Package,\n options: {appId: string; baseUrl?: string; timestamp: number},\n) {\n const encodedMinVer = encodeURIComponent(`^${pkg.version}`)\n return `${options.baseUrl || MODULES_HOST}/v1/modules/by-app/${options.appId}/t${options.timestamp}/${encodedMinVer}/${rewriteScopedPackage(pkg.name)}`\n}\n\n/**\n * replaces '/' with '__' similar to how eg `@types/scope__pkg` are rewritten\n * scoped packages are stored this way both in the manifest and in the cloud storage bucket\n */\nfunction rewriteScopedPackage(pkgName: string) {\n if (!pkgName.includes('@')) {\n return pkgName\n }\n const [scope, ...pkg] = pkgName.split('/')\n return `${scope}__${pkg.join('')}`\n}\n"],"names":["MODULES_HOST","process","env","SANITY_MODULES_HOST","SANITY_INTERNAL_ENV","currentUnixTime","Math","floor","Date","now","getAutoUpdatesImportMap","packages","options","Object","fromEntries","flatMap","pkg","getAppAutoUpdateImportMapForPackage","moduleUrl","getModuleUrl","name","timestamp","appId","getByAppModuleUrl","baseUrl","getLegacyModuleUrl","encodedMinVer","encodeURIComponent","version","rewriteScopedPackage","pkgName","includes","scope","split","join"],"mappings":"AAAA,MAAMA,eACJC,QAAQC,GAAG,CAACC,mBAAmB,IAC9BF,CAAAA,QAAQC,GAAG,CAACE,mBAAmB,KAAK,YACjC,4BACA,wBAAuB;AAE7B,SAASC;IACP,OAAOC,KAAKC,KAAK,CAACC,KAAKC,GAAG,KAAK;AACjC;AAGA;;CAEC,GACD,OAAO,SAASC,wBACdC,QAAe,EACfC,UAAkE,CAAC,CAAC;IAEpE,OAAOC,OAAOC,WAAW,CACvBH,SAASI,OAAO,CAAC,CAACC,MAAQC,oCAAoCD,KAAKJ;AAEvE;AAEA;;CAEC,GACD,SAASK,oCACPD,GAAQ,EACRJ,UAAkE,CAAC,CAAC;IAEpE,MAAMM,YAAYC,aAAaH,KAAKJ;IAEpC,OAAO;Q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pC"}
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/build/getAutoUpdatesImportMap.ts"],"sourcesContent":["const MODULES_HOST =\n process.env.SANITY_MODULES_HOST ||\n (process.env.SANITY_INTERNAL_ENV === 'staging'\n ? 'https://sanity-cdn.work'\n : 'https://sanity-cdn.com')\n\nfunction currentUnixTime(): number {\n return Math.floor(Date.now() / 1000)\n}\n\ntype Package = {name: string; version: string}\n/**\n * @internal\n */\nexport function getAutoUpdatesImportMap<const Pkg extends Package>(\n packages: Pkg[],\n options: {appId?: string; baseUrl?: string; timestamp?: number} = {},\n) {\n return Object.fromEntries(\n packages.flatMap((pkg) => getAppAutoUpdateImportMapForPackage(pkg, options)),\n ) as {[K in `${Pkg['name']}/` | Pkg['name']]: string}\n}\n\n/**\n * @internal\n */\nfunction getAppAutoUpdateImportMapForPackage<const Pkg extends Package>(\n pkg: Pkg,\n options: {appId?: string; baseUrl?: string; timestamp?: number} = {},\n): [[Pkg['name'], string], [`${Pkg['name']}/`, string]] {\n const moduleUrl = getModuleUrl(pkg, options)\n\n return [\n [pkg.name, moduleUrl],\n [`${pkg.name}/`, `${moduleUrl}/`],\n ]\n}\n\n/**\n * @internal\n */\nexport function getModuleUrl(\n pkg: Package,\n options: {appId?: string; baseUrl?: string; timestamp?: number} = {},\n) {\n const {timestamp = currentUnixTime()} = options\n return options.appId\n ? getByAppModuleUrl(pkg, {appId: options.appId, baseUrl: options.baseUrl, timestamp})\n : getLegacyModuleUrl(pkg, {baseUrl: options.baseUrl, timestamp})\n}\n\nfunction getLegacyModuleUrl(pkg: Package, options: {baseUrl?: string; timestamp: number}) {\n const encodedMinVer = encodeURIComponent(`^${pkg.version}`)\n return `${options.baseUrl || MODULES_HOST}/v1/modules/${rewriteScopedPackage(pkg.name)}/default/${encodedMinVer}/t${options.timestamp}`\n}\n\nfunction getByAppModuleUrl(\n pkg: Package,\n options: {appId: string; baseUrl?: string; timestamp: number},\n) {\n const encodedMinVer = encodeURIComponent(`^${pkg.version}`)\n return `${options.baseUrl || MODULES_HOST}/v1/modules/by-app/${options.appId}/t${options.timestamp}/${encodedMinVer}/${rewriteScopedPackage(pkg.name)}`\n}\n\n/**\n * replaces '/' with '__' similar to how eg `@types/scope__pkg` are rewritten\n * scoped packages are stored this way both in the manifest and in the cloud storage bucket\n */\nfunction rewriteScopedPackage(pkgName: string) {\n if (!pkgName.includes('@')) {\n return pkgName\n }\n const [scope, ...pkg] = pkgName.split('/')\n return `${scope}__${pkg.join('')}`\n}\n\ntype PackageWithCss = Package & {cssFile?: string}\n\n/**\n * Generate CDN CSS URLs for auto-updated packages.\n * Uses the same URL pattern as JS module URLs so the module server\n * resolves CSS and JS to the same version.\n *\n * @internal\n */\nexport function getAutoUpdatesCssUrls<const Pkg extends PackageWithCss>(\n packages: Pkg[],\n options: {appId?: string; baseUrl?: string; timestamp?: number} = {},\n): string[] {\n return packages\n .filter((pkg) => Boolean(pkg.cssFile))\n .map((pkg) => `${getModuleUrl(pkg, options)}/${pkg.cssFile}`)\n}\n"],"names":["MODULES_HOST","process","env","SANITY_MODULES_HOST","SANITY_INTERNAL_ENV","currentUnixTime","Math","floor","Date","now","getAutoUpdatesImportMap","packages","options","Object","fromEntries","flatMap","pkg","getAppAutoUpdateImportMapForPackage","moduleUrl","getModuleUrl","name","timestamp","appId","getByAppModuleUrl","baseUrl","getLegacyModuleUrl","encodedMinVer","encodeURIComponent","version","rewriteScopedPackage","pkgName","includes","scope","split","join","getAutoUpdatesCssUrls","filter","Boolean","cssFile","map"],"mappings":"AAAA,MAAMA,eACJC,QAAQC,GAAG,CAACC,mBAAmB,IAC9BF,CAAAA,QAAQC,GAAG,CAACE,mBAAmB,KAAK,YACjC,4BACA,wBAAuB;AAE7B,SAASC;IACP,OAAOC,KAAKC,KAAK,CAACC,KAAKC,GAAG,KAAK;AACjC;AAGA;;CAEC,GACD,OAAO,SAASC,wBACdC,QAAe,EACfC,UAAkE,CAAC,CAAC;IAEpE,OAAOC,OAAOC,WAAW,CACvBH,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C,QAAQ,CAAC,MAAM;QAC1B,OAAOD;IACT;IACA,MAAM,CAACE,OAAO,GAAGhB,IAAI,GAAGc,QAAQG,KAAK,CAAC;IACtC,OAAO,GAAGD,MAAM,EAAE,EAAEhB,IAAIkB,IAAI,CAAC,KAAK;AACpC;AAIA;;;;;;CAMC,GACD,OAAO,SAASC,sBACdxB,QAAe,EACfC,UAAkE,CAAC,CAAC;IAEpE,OAAOD,SACJyB,MAAM,CAAC,CAACpB,MAAQqB,QAAQrB,IAAIsB,OAAO,GACnCC,GAAG,CAAC,CAACvB,MAAQ,GAAGG,aAAaH,KAAKJ,SAAS,CAAC,EAAEI,IAAIsB,OAAO,EAAE;AAChE"}
|
|
@@ -17,7 +17,7 @@ import { normalizeBasePath } from './normalizeBasePath.js';
|
|
|
17
17
|
*
|
|
18
18
|
* @internal Only meant for consumption inside of Sanity modules, do not depend on this externally
|
|
19
19
|
*/ export async function getViteConfig(options) {
|
|
20
|
-
const { basePath: rawBasePath = '/', cwd, importMap, isApp, minify, mode, outputDir, reactCompiler, schemaExtraction, server, // default to `true` when `mode=development`
|
|
20
|
+
const { autoUpdatesCssUrls, basePath: rawBasePath = '/', cwd, importMap, isApp, minify, mode, outputDir, reactCompiler, schemaExtraction, server, // default to `true` when `mode=development`
|
|
21
21
|
sourceMap = options.mode === 'development', typegen } = options;
|
|
22
22
|
const basePath = normalizeBasePath(rawBasePath);
|
|
23
23
|
const sanityCliPkgPath = (await readPackageUp({
|
|
@@ -87,6 +87,7 @@ import { normalizeBasePath } from './normalizeBasePath.js';
|
|
|
87
87
|
}),
|
|
88
88
|
sanityRuntimeRewritePlugin(),
|
|
89
89
|
sanityBuildEntries({
|
|
90
|
+
autoUpdatesCssUrls,
|
|
90
91
|
basePath,
|
|
91
92
|
cwd,
|
|
92
93
|
importMap,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/actions/build/getViteConfig.ts"],"sourcesContent":["import path from 'node:path'\n\nimport {\n type CliConfig,\n findProjectRoot,\n getCliTelemetry,\n type UserViteConfig,\n} from '@sanity/cli-core'\nimport viteReact from '@vitejs/plugin-react'\nimport {type PluginOptions as ReactCompilerConfig} from 'babel-plugin-react-compiler'\nimport debug from 'debug'\nimport {readPackageUp} from 'read-package-up'\nimport {type ConfigEnv, type InlineConfig, mergeConfig, type Rollup} from 'vite'\n\nimport {sanityBuildEntries} from '../../server/vite/plugin-sanity-build-entries.js'\nimport {sanityFaviconsPlugin} from '../../server/vite/plugin-sanity-favicons.js'\nimport {sanityRuntimeRewritePlugin} from '../../server/vite/plugin-sanity-runtime-rewrite.js'\nimport {sanitySchemaExtractionPlugin} from '../../server/vite/plugin-schema-extraction.js'\nimport {sanityTypegenPlugin} from '../../server/vite/plugin-typegen.js'\nimport {createExternalFromImportMap} from './createExternalFromImportMap.js'\nimport {\n getAppEnvironmentVariables,\n getStudioEnvironmentVariables,\n} from './getStudioEnvironmentVariables.js'\nimport {normalizeBasePath} from './normalizeBasePath.js'\n\ninterface ViteOptions {\n /**\n * Root path of the studio/sanity app\n */\n cwd: string\n\n /**\n * Mode to run vite in - eg development or production\n */\n mode: 'development' | 'production'\n\n reactCompiler: ReactCompilerConfig | undefined\n\n /**\n * Base path (eg under where to serve the app - `/studio` or similar)\n * Will be normalized to ensure it starts and ends with a `/`\n */\n basePath?: string\n\n importMap?: {imports?: Record<string, string>}\n\n isApp?: boolean\n\n /**\n * Whether or not to minify the output (only used in `mode: 'production'`)\n */\n minify?: boolean\n\n /**\n * Output directory (eg where to place the built files, if any)\n */\n outputDir?: string\n /**\n * Schema extraction configuration\n */\n schemaExtraction?: CliConfig['schemaExtraction']\n /**\n * HTTP development server configuration\n */\n server?: {host?: string; port?: number}\n /**\n * Whether or not to enable source maps\n */\n sourceMap?: boolean\n /**\n * Typegen configuration\n */\n typegen?: CliConfig['typegen']\n}\n\n/**\n * Get a configuration object for Vite based on the passed options\n *\n * @internal Only meant for consumption inside of Sanity modules, do not depend on this externally\n */\nexport async function getViteConfig(options: ViteOptions): Promise<InlineConfig> {\n const {\n basePath: rawBasePath = '/',\n cwd,\n importMap,\n isApp,\n minify,\n mode,\n outputDir,\n reactCompiler,\n schemaExtraction,\n server,\n // default to `true` when `mode=development`\n sourceMap = options.mode === 'development',\n typegen,\n } = options\n\n const basePath = normalizeBasePath(rawBasePath)\n\n const sanityCliPkgPath = (await readPackageUp({cwd: import.meta.dirname}))?.path\n if (!sanityCliPkgPath) {\n throw new Error('Unable to resolve `@sanity/cli` module root')\n }\n\n const configPath = (await findProjectRoot(cwd)).path\n\n const customFaviconsPath = path.join(cwd, 'static')\n const defaultFaviconsPath = path.join(path.dirname(sanityCliPkgPath), 'static', 'favicons')\n const staticPath = `${basePath}static`\n\n const envVars = isApp\n ? getAppEnvironmentVariables({jsonEncode: true, prefix: 'process.env.'})\n : getStudioEnvironmentVariables({jsonEncode: true, prefix: 'process.env.'})\n\n const viteConfig: InlineConfig = {\n base: basePath,\n build: {\n outDir: outputDir || path.resolve(cwd, 'dist'),\n sourcemap: sourceMap,\n },\n // Define a custom cache directory so that sanity's vite cache\n // does not conflict with any potential local vite projects\n cacheDir: 'node_modules/.sanity/vite',\n configFile: false,\n define: {\n __SANITY_BUILD_TIMESTAMP__: JSON.stringify(Date.now()),\n __SANITY_STAGING__: process.env.SANITY_INTERNAL_ENV === 'staging',\n 'process.env.MODE': JSON.stringify(mode),\n 'process.env.PKG_BUILD_VERSION': JSON.stringify(process.env.PKG_BUILD_VERSION),\n /**\n * Yes, double negatives are confusing.\n * The default value of `SC_DISABLE_SPEEDY` is `process.env.NODE_ENV === 'production'`: https://github.com/styled-components/styled-components/blob/99c02f52d69e8e509c0bf012cadee7f8e819a6dd/packages/styled-components/src/constants.ts#L34\n * Which means that in production, use the much faster way of inserting CSS rules, based on the CSSStyleSheet API (https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet/insertRule)\n * while in dev mode, use the slower way of inserting CSS rules, which appends text nodes to the `<style>` tag: https://github.com/styled-components/styled-components/blob/99c02f52d69e8e509c0bf012cadee7f8e819a6dd/packages/styled-components/src/sheet/Tag.ts#L74-L76\n * There are historical reasons for this, primarily that browsers initially did not support editing CSS rules in the DevTools inspector if `CSSStyleSheet.insetRule` were used.\n * However, that's no longer the case (since Chrome 81 back in April 2020: https://developer.chrome.com/docs/css-ui/css-in-js), the latest version of FireFox also supports it,\n * and there is no longer any reason to use the much slower method in dev mode.\n */\n 'process.env.SC_DISABLE_SPEEDY': JSON.stringify('false'),\n ...envVars,\n },\n envPrefix: isApp ? 'SANITY_APP_' : 'SANITY_STUDIO_',\n logLevel: mode === 'production' ? 'silent' : 'info',\n mode,\n plugins: [\n viteReact(\n reactCompiler\n ? {\n babel: {\n generatorOpts: {compact: true},\n plugins: [['babel-plugin-react-compiler', reactCompiler]],\n },\n }\n : {},\n ),\n sanityFaviconsPlugin({customFaviconsPath, defaultFaviconsPath, staticUrlPath: staticPath}),\n sanityRuntimeRewritePlugin(),\n sanityBuildEntries({basePath, cwd, importMap, isApp}),\n // Add schema extraction when enabled\n ...(schemaExtraction?.enabled\n ? [\n sanitySchemaExtractionPlugin({\n additionalPatterns: schemaExtraction.watchPatterns,\n configPath,\n enforceRequiredFields: schemaExtraction.enforceRequiredFields,\n outputPath: schemaExtraction.path,\n telemetryLogger: getCliTelemetry(),\n workDir: cwd,\n workspaceName: schemaExtraction.workspace,\n }),\n ]\n : []),\n // Add typegen when enabled\n ...(typegen?.enabled\n ? [\n sanityTypegenPlugin({\n config: typegen,\n telemetryLogger: getCliTelemetry(),\n workDir: cwd,\n }),\n ]\n : []),\n ],\n resolve: {\n dedupe: ['react', 'react-dom', 'sanity', 'styled-components'],\n },\n root: cwd,\n server: {\n host: server?.host,\n port: server?.port || 3333,\n // Only enable strict port for studio,\n // since apps can run on any port\n strictPort: isApp ? false : true,\n\n /**\n * Significantly speed up startup time,\n * and most importantly eliminates the `new dependencies optimized: foobar. optimized dependencies changed. reloading`\n * types of initial reload loops that otherwise happen as vite discovers deps that need to be optimized.\n * This option starts the traversal up front, and warms up the dep tree required to render the userland sanity.config.ts file,\n * and thus avoids frustrating reload loops.\n */\n warmup: {\n clientFiles: ['./.sanity/runtime/app.js'],\n },\n },\n }\n\n if (mode === 'production') {\n viteConfig.build = {\n ...viteConfig.build,\n\n assetsDir: 'static',\n emptyOutDir: false, // Rely on CLI to do this\n minify: minify ? 'esbuild' : false,\n\n rollupOptions: {\n external: createExternalFromImportMap(importMap),\n input: {\n sanity: path.join(cwd, '.sanity', 'runtime', 'app.js'),\n },\n onwarn: onRollupWarn,\n },\n }\n }\n\n return viteConfig\n}\n\nfunction onRollupWarn(warning: Rollup.RollupLog, warn: Rollup.LoggingFunction) {\n if (suppressUnusedImport(warning)) {\n return\n }\n\n warn(warning)\n}\n\nfunction suppressUnusedImport(warning: Rollup.RollupLog & {ids?: string[]}): boolean {\n if (warning.code !== 'UNUSED_EXTERNAL_IMPORT') return false\n\n // Suppress:\n // ```\n // \"useDebugValue\" is imported from external module \"react\"…\n // ```\n if (warning.names?.includes('useDebugValue')) {\n warning.names = warning.names.filter((n) => n !== 'useDebugValue')\n if (warning.names.length === 0) return true\n }\n\n // If some library does something unexpected, we suppress since it isn't actionable\n if (warning.ids?.every((id) => id.includes('/node_modules/') || id.includes('\\\\node_modules\\\\')))\n return true\n\n return false\n}\n\n/**\n * Ensure Sanity entry chunk is always loaded\n *\n * @param config - User-modified configuration\n * @returns Merged configuration\n * @internal\n */\nexport async function finalizeViteConfig(config: InlineConfig): Promise<InlineConfig> {\n if (typeof config.build?.rollupOptions?.input !== 'object') {\n throw new TypeError(\n 'Vite config must contain `build.rollupOptions.input`, and it must be an object',\n )\n }\n\n if (!config.root) {\n throw new Error(\n 'Vite config must contain `root` property, and must point to the Sanity root directory',\n )\n }\n\n return mergeConfig(config, {\n build: {\n rollupOptions: {\n input: {\n sanity: path.join(config.root, '.sanity', 'runtime', 'app.js'),\n },\n },\n },\n })\n}\n\n/**\n * Merge user-provided Vite configuration object or function\n *\n * @param defaultConfig - Default configuration object\n * @param userConfig - User-provided configuration object or function\n * @returns Merged configuration\n * @internal\n */\nexport async function extendViteConfigWithUserConfig(\n env: ConfigEnv,\n defaultConfig: InlineConfig,\n userConfig: UserViteConfig,\n): Promise<InlineConfig> {\n let config = defaultConfig\n\n if (typeof userConfig === 'function') {\n debug('Extending vite config using user-specified function')\n config = await userConfig(config, env)\n } else if (typeof userConfig === 'object') {\n debug('Merging vite config using user-specified object')\n config = mergeConfig(config, userConfig)\n }\n\n return config\n}\n"],"names":["path","findProjectRoot","getCliTelemetry","viteReact","debug","readPackageUp","mergeConfig","sanityBuildEntries","sanityFaviconsPlugin","sanityRuntimeRewritePlugin","sanitySchemaExtractionPlugin","sanityTypegenPlugin","createExternalFromImportMap","getAppEnvironmentVariables","getStudioEnvironmentVariables","normalizeBasePath","getViteConfig","options","basePath","rawBasePath","cwd","importMap","isApp","minify","mode","outputDir","reactCompiler","schemaExtraction","server","sourceMap","typegen","sanityCliPkgPath","dirname","Error","configPath","customFaviconsPath","join","defaultFaviconsPath","staticPath","envVars","jsonEncode","prefix","viteConfig","base","build","outDir","resolve","sourcemap","cacheDir","configFile","define","__SANITY_BUILD_TIMESTAMP__","JSON","stringify","Date","now","__SANITY_STAGING__","process","env","SANITY_INTERNAL_ENV","PKG_BUILD_VERSION","envPrefix","logLevel","plugins","babel","generatorOpts","compact","staticUrlPath","enabled","additionalPatterns","watchPatterns","enforceRequiredFields","outputPath","telemetryLogger","workDir","workspaceName","workspace","config","dedupe","root","host","port","strictPort","warmup","clientFiles","assetsDir","emptyOutDir","rollupOptions","external","input","sanity","onwarn","onRollupWarn","warning","warn","suppressUnusedImport","code","names","includes","filter","n","length","ids","every","id","finalizeViteConfig","TypeError","extendViteConfigWithUserConfig","defaultConfig","userConfig"],"mappings":"AAAA,OAAOA,UAAU,YAAW;AAE5B,SAEEC,eAAe,EACfC,eAAe,QAEV,mBAAkB;AACzB,OAAOC,eAAe,uBAAsB;AAE5C,OAAOC,WAAW,QAAO;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,OAAOjC,KAAK,EAAE2C,eAAeE,UAAU,UAAU;QAC1D,MAAM,IAAIiB,UACR;IAEJ;IAEA,IAAI,CAAC7B,OAAOE,IAAI,EAAE;QAChB,MAAM,IAAI9C,MACR;IAEJ;IAEA,OAAO3B,YAAYuE,QAAQ;QACzBjC,OAAO;YACL2C,eAAe;gBACbE,OAAO;oBACLC,QAAQ1F,KAAKoC,IAAI,CAACyC,OAAOE,IAAI,EAAE,WAAW,WAAW;gBACvD;YACF;QACF;IACF;AACF;AAEA;;;;;;;CAOC,GACD,OAAO,eAAe4B,+BACpBjD,GAAc,EACdkD,aAA2B,EAC3BC,UAA0B;IAE1B,IAAIhC,SAAS+B;IAEb,IAAI,OAAOC,eAAe,YAAY;QACpCzG,MAAM;QACNyE,SAAS,MAAMgC,WAAWhC,QAAQnB;IACpC,OAAO,IAAI,OAAOmD,eAAe,UAAU;QACzCzG,MAAM;QACNyE,SAASvE,YAAYuE,QAAQgC;IAC/B;IAEA,OAAOhC;AACT"}
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/build/getViteConfig.ts"],"sourcesContent":["import path from 'node:path'\n\nimport {\n type CliConfig,\n findProjectRoot,\n getCliTelemetry,\n type UserViteConfig,\n} from '@sanity/cli-core'\nimport viteReact from '@vitejs/plugin-react'\nimport {type PluginOptions as ReactCompilerConfig} from 'babel-plugin-react-compiler'\nimport debug from 'debug'\nimport {readPackageUp} from 'read-package-up'\nimport {type ConfigEnv, type InlineConfig, mergeConfig, type Rollup} from 'vite'\n\nimport {sanityBuildEntries} from '../../server/vite/plugin-sanity-build-entries.js'\nimport {sanityFaviconsPlugin} from '../../server/vite/plugin-sanity-favicons.js'\nimport {sanityRuntimeRewritePlugin} from '../../server/vite/plugin-sanity-runtime-rewrite.js'\nimport {sanitySchemaExtractionPlugin} from '../../server/vite/plugin-schema-extraction.js'\nimport {sanityTypegenPlugin} from '../../server/vite/plugin-typegen.js'\nimport {createExternalFromImportMap} from './createExternalFromImportMap.js'\nimport {\n getAppEnvironmentVariables,\n getStudioEnvironmentVariables,\n} from './getStudioEnvironmentVariables.js'\nimport {normalizeBasePath} from './normalizeBasePath.js'\n\ninterface ViteOptions {\n /**\n * Root path of the studio/sanity app\n */\n cwd: string\n\n /**\n * Mode to run vite in - eg development or production\n */\n mode: 'development' | 'production'\n\n reactCompiler: ReactCompilerConfig | undefined\n\n /**\n * CSS URLs for auto-updated packages (loaded via module server)\n */\n autoUpdatesCssUrls?: string[]\n\n /**\n * Base path (eg under where to serve the app - `/studio` or similar)\n * Will be normalized to ensure it starts and ends with a `/`\n */\n basePath?: string\n\n importMap?: {imports?: Record<string, string>}\n\n isApp?: boolean\n\n /**\n * Whether or not to minify the output (only used in `mode: 'production'`)\n */\n minify?: boolean\n\n /**\n * Output directory (eg where to place the built files, if any)\n */\n outputDir?: string\n /**\n * Schema extraction configuration\n */\n schemaExtraction?: CliConfig['schemaExtraction']\n /**\n * HTTP development server configuration\n */\n server?: {host?: string; port?: number}\n /**\n * Whether or not to enable source maps\n */\n sourceMap?: boolean\n /**\n * Typegen configuration\n */\n typegen?: CliConfig['typegen']\n}\n\n/**\n * Get a configuration object for Vite based on the passed options\n *\n * @internal Only meant for consumption inside of Sanity modules, do not depend on this externally\n */\nexport async function getViteConfig(options: ViteOptions): Promise<InlineConfig> {\n const {\n autoUpdatesCssUrls,\n basePath: rawBasePath = '/',\n cwd,\n importMap,\n isApp,\n minify,\n mode,\n outputDir,\n reactCompiler,\n schemaExtraction,\n server,\n // default to `true` when `mode=development`\n sourceMap = options.mode === 'development',\n typegen,\n } = options\n\n const basePath = normalizeBasePath(rawBasePath)\n\n const sanityCliPkgPath = (await readPackageUp({cwd: import.meta.dirname}))?.path\n if (!sanityCliPkgPath) {\n throw new Error('Unable to resolve `@sanity/cli` module root')\n }\n\n const configPath = (await findProjectRoot(cwd)).path\n\n const customFaviconsPath = path.join(cwd, 'static')\n const defaultFaviconsPath = path.join(path.dirname(sanityCliPkgPath), 'static', 'favicons')\n const staticPath = `${basePath}static`\n\n const envVars = isApp\n ? getAppEnvironmentVariables({jsonEncode: true, prefix: 'process.env.'})\n : getStudioEnvironmentVariables({jsonEncode: true, prefix: 'process.env.'})\n\n const viteConfig: InlineConfig = {\n base: basePath,\n build: {\n outDir: outputDir || path.resolve(cwd, 'dist'),\n sourcemap: sourceMap,\n },\n // Define a custom cache directory so that sanity's vite cache\n // does not conflict with any potential local vite projects\n cacheDir: 'node_modules/.sanity/vite',\n configFile: false,\n define: {\n __SANITY_BUILD_TIMESTAMP__: JSON.stringify(Date.now()),\n __SANITY_STAGING__: process.env.SANITY_INTERNAL_ENV === 'staging',\n 'process.env.MODE': JSON.stringify(mode),\n 'process.env.PKG_BUILD_VERSION': JSON.stringify(process.env.PKG_BUILD_VERSION),\n /**\n * Yes, double negatives are confusing.\n * The default value of `SC_DISABLE_SPEEDY` is `process.env.NODE_ENV === 'production'`: https://github.com/styled-components/styled-components/blob/99c02f52d69e8e509c0bf012cadee7f8e819a6dd/packages/styled-components/src/constants.ts#L34\n * Which means that in production, use the much faster way of inserting CSS rules, based on the CSSStyleSheet API (https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet/insertRule)\n * while in dev mode, use the slower way of inserting CSS rules, which appends text nodes to the `<style>` tag: https://github.com/styled-components/styled-components/blob/99c02f52d69e8e509c0bf012cadee7f8e819a6dd/packages/styled-components/src/sheet/Tag.ts#L74-L76\n * There are historical reasons for this, primarily that browsers initially did not support editing CSS rules in the DevTools inspector if `CSSStyleSheet.insetRule` were used.\n * However, that's no longer the case (since Chrome 81 back in April 2020: https://developer.chrome.com/docs/css-ui/css-in-js), the latest version of FireFox also supports it,\n * and there is no longer any reason to use the much slower method in dev mode.\n */\n 'process.env.SC_DISABLE_SPEEDY': JSON.stringify('false'),\n ...envVars,\n },\n envPrefix: isApp ? 'SANITY_APP_' : 'SANITY_STUDIO_',\n logLevel: mode === 'production' ? 'silent' : 'info',\n mode,\n plugins: [\n viteReact(\n reactCompiler\n ? {\n babel: {\n generatorOpts: {compact: true},\n plugins: [['babel-plugin-react-compiler', reactCompiler]],\n },\n }\n : {},\n ),\n sanityFaviconsPlugin({customFaviconsPath, defaultFaviconsPath, staticUrlPath: staticPath}),\n sanityRuntimeRewritePlugin(),\n sanityBuildEntries({autoUpdatesCssUrls, basePath, cwd, importMap, isApp}),\n // Add schema extraction when enabled\n ...(schemaExtraction?.enabled\n ? [\n sanitySchemaExtractionPlugin({\n additionalPatterns: schemaExtraction.watchPatterns,\n configPath,\n enforceRequiredFields: schemaExtraction.enforceRequiredFields,\n outputPath: schemaExtraction.path,\n telemetryLogger: getCliTelemetry(),\n workDir: cwd,\n workspaceName: schemaExtraction.workspace,\n }),\n ]\n : []),\n // Add typegen when enabled\n ...(typegen?.enabled\n ? [\n sanityTypegenPlugin({\n config: typegen,\n telemetryLogger: getCliTelemetry(),\n workDir: cwd,\n }),\n ]\n : []),\n ],\n resolve: {\n dedupe: ['react', 'react-dom', 'sanity', 'styled-components'],\n },\n root: cwd,\n server: {\n host: server?.host,\n port: server?.port || 3333,\n // Only enable strict port for studio,\n // since apps can run on any port\n strictPort: isApp ? false : true,\n\n /**\n * Significantly speed up startup time,\n * and most importantly eliminates the `new dependencies optimized: foobar. optimized dependencies changed. reloading`\n * types of initial reload loops that otherwise happen as vite discovers deps that need to be optimized.\n * This option starts the traversal up front, and warms up the dep tree required to render the userland sanity.config.ts file,\n * and thus avoids frustrating reload loops.\n */\n warmup: {\n clientFiles: ['./.sanity/runtime/app.js'],\n },\n },\n }\n\n if (mode === 'production') {\n viteConfig.build = {\n ...viteConfig.build,\n\n assetsDir: 'static',\n emptyOutDir: false, // Rely on CLI to do this\n minify: minify ? 'esbuild' : false,\n\n rollupOptions: {\n external: createExternalFromImportMap(importMap),\n input: {\n sanity: path.join(cwd, '.sanity', 'runtime', 'app.js'),\n },\n onwarn: onRollupWarn,\n },\n }\n }\n\n return viteConfig\n}\n\nfunction onRollupWarn(warning: Rollup.RollupLog, warn: Rollup.LoggingFunction) {\n if (suppressUnusedImport(warning)) {\n return\n }\n\n warn(warning)\n}\n\nfunction suppressUnusedImport(warning: Rollup.RollupLog & {ids?: string[]}): boolean {\n if (warning.code !== 'UNUSED_EXTERNAL_IMPORT') return false\n\n // Suppress:\n // ```\n // \"useDebugValue\" is imported from external module \"react\"…\n // ```\n if (warning.names?.includes('useDebugValue')) {\n warning.names = warning.names.filter((n) => n !== 'useDebugValue')\n if (warning.names.length === 0) return true\n }\n\n // If some library does something unexpected, we suppress since it isn't actionable\n if (warning.ids?.every((id) => id.includes('/node_modules/') || id.includes('\\\\node_modules\\\\')))\n return true\n\n return false\n}\n\n/**\n * Ensure Sanity entry chunk is always loaded\n *\n * @param config - User-modified configuration\n * @returns Merged configuration\n * @internal\n */\nexport async function finalizeViteConfig(config: InlineConfig): Promise<InlineConfig> {\n if (typeof config.build?.rollupOptions?.input !== 'object') {\n throw new TypeError(\n 'Vite config must contain `build.rollupOptions.input`, and it must be an object',\n )\n }\n\n if (!config.root) {\n throw new Error(\n 'Vite config must contain `root` property, and must point to the Sanity root directory',\n )\n }\n\n return mergeConfig(config, {\n build: {\n rollupOptions: {\n input: {\n sanity: path.join(config.root, '.sanity', 'runtime', 'app.js'),\n },\n },\n },\n })\n}\n\n/**\n * Merge user-provided Vite configuration object or function\n *\n * @param defaultConfig - Default configuration object\n * @param userConfig - User-provided configuration object or function\n * @returns Merged configuration\n * @internal\n */\nexport async function extendViteConfigWithUserConfig(\n env: ConfigEnv,\n defaultConfig: InlineConfig,\n userConfig: UserViteConfig,\n): Promise<InlineConfig> {\n let config = defaultConfig\n\n if (typeof userConfig === 'function') {\n debug('Extending vite config using user-specified function')\n config = await userConfig(config, env)\n } else if (typeof userConfig === 'object') {\n debug('Merging vite config using user-specified object')\n config = mergeConfig(config, userConfig)\n }\n\n return config\n}\n"],"names":["path","findProjectRoot","getCliTelemetry","viteReact","debug","readPackageUp","mergeConfig","sanityBuildEntries","sanityFaviconsPlugin","sanityRuntimeRewritePlugin","sanitySchemaExtractionPlugin","sanityTypegenPlugin","createExternalFromImportMap","getAppEnvironmentVariables","getStudioEnvironmentVariables","normalizeBasePath","getViteConfig","options","autoUpdatesCssUrls","basePath","rawBasePath","cwd","importMap","isApp","minify","mode","outputDir","reactCompiler","schemaExtraction","server","sourceMap","typegen","sanityCliPkgPath","dirname","Error","configPath","customFaviconsPath","join","defaultFaviconsPath","staticPath","envVars","jsonEncode","prefix","viteConfig","base","build","outDir","resolve","sourcemap","cacheDir","configFile","define","__SANITY_BUILD_TIMESTAMP__","JSON","stringify","Date","now","__SANITY_STAGING__","process","env","SANITY_INTERNAL_ENV","PKG_BUILD_VERSION","envPrefix","logLevel","plugins","babel","generatorOpts","compact","staticUrlPath","enabled","additionalPatterns","watchPatterns","enforceRequiredFields","outputPath","telemetryLogger","workDir","workspaceName","workspace","config","dedupe","root","host","port","strictPort","warmup","clientFiles","assetsDir","emptyOutDir","rollupOptions","external","input","sanity","onwarn","onRollupWarn","warning","warn","suppressUnusedImport","code","names","includes","filter","n","length","ids","every","id","finalizeViteConfig","TypeError","extendViteConfigWithUserConfig","defaultConfig","userConfig"],"mappings":"AAAA,OAAOA,UAAU,YAAW;AAE5B,SAEEC,eAAe,EACfC,eAAe,QAEV,mBAAkB;AACzB,OAAOC,eAAe,uBAAsB;AAE5C,OAAOC,WAAW,QAAO;AACzB,SAAQC,aAAa,QAAO,kBAAiB;AAC7C,SAA2CC,WAAW,QAAoB,OAAM;AAEhF,SAAQC,kBAAkB,QAAO,mDAAkD;AACnF,SAAQC,oBAAoB,QAAO,8CAA6C;AAChF,SAAQC,0BAA0B,QAAO,qDAAoD;AAC7F,SAAQC,4BAA4B,QAAO,gDAA+C;AAC1F,SAAQC,mBAAmB,QAAO,sCAAqC;AACvE,SAAQC,2BAA2B,QAAO,mCAAkC;AAC5E,SACEC,0BAA0B,EAC1BC,6BAA6B,QACxB,qCAAoC;AAC3C,SAAQC,iBAAiB,QAAO,yBAAwB;AAyDxD;;;;CAIC,GACD,OAAO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B,EAC3BC,UAA0B;IAE1B,IAAIhC,SAAS+B;IAEb,IAAI,OAAOC,eAAe,YAAY;QACpC1G,MAAM;QACN0E,SAAS,MAAMgC,WAAWhC,QAAQnB;IACpC,OAAO,IAAI,OAAOmD,eAAe,UAAU;QACzC1G,MAAM;QACN0E,SAASxE,YAAYwE,QAAQgC;IAC/B;IAEA,OAAOhC;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/actions/build/renderDocument.ts"],"sourcesContent":["import {ux} from '@oclif/core'\nimport {tsxWorkerTask} from '@sanity/cli-core'\n\nimport {buildDebug} from './buildDebug.js'\n\ninterface DocumentProps {\n basePath: string\n\n css?: string[]\n entryPath?: string\n title?: string\n}\n\ninterface RenderDocumentOptions {\n studioRootPath: string\n\n importMap?: {\n imports?: Record<string, string>\n }\n isApp?: boolean\n props?: DocumentProps\n}\n\nconst hasWarnedAbout = new Set<string>()\n\ninterface RenderDocumentWorkerResult {\n type: 'error' | 'result' | 'warning'\n\n html?: string\n message?: string | string[]\n warnKey?: string\n}\n\nexport async function renderDocument(options: RenderDocumentOptions): Promise<string> {\n buildDebug('Starting worker thread for %s', import.meta.url)\n try {\n const msg = await tsxWorkerTask<RenderDocumentWorkerResult>(\n new URL(`renderDocument.worker.js`, import.meta.url),\n {\n name: 'renderDocument',\n rootPath: options.studioRootPath,\n workerData: {...options, shouldWarn: true},\n },\n )\n\n if (msg.type === 'warning') {\n if (msg.warnKey && hasWarnedAbout.has(msg.warnKey)) {\n return ''\n }\n\n if (Array.isArray(msg.message)) {\n for (const warning of msg.message) {\n ux.warn(warning)\n }\n } else if (msg.message) {\n ux.warn(msg.message)\n }\n\n if (msg.warnKey) {\n hasWarnedAbout.add(msg.warnKey)\n }\n return ''\n }\n\n if (msg.type === 'error') {\n buildDebug('Error from worker: %s', msg.message || 'Unknown error')\n throw new Error(\n Array.isArray(msg.message)\n ? msg.message.join('\\n')\n : msg.message || 'Document rendering worker stopped with an unknown error',\n )\n }\n\n if (msg.type === 'result') {\n if (!msg.html) {\n throw new Error('Document rendering worker stopped with an unknown error')\n }\n\n buildDebug('Document HTML rendered, %d bytes', msg.html.length)\n return msg.html\n }\n\n throw new Error('Unknown message type')\n } catch (err) {\n buildDebug('Worker errored: %s', err.message)\n throw err\n }\n}\n"],"names":["ux","tsxWorkerTask","buildDebug","hasWarnedAbout","Set","renderDocument","options","url","msg","URL","name","rootPath","studioRootPath","workerData","shouldWarn","type","warnKey","has","Array","isArray","message","warning","warn","add","Error","join","html","length","err"],"mappings":"AAAA,SAAQA,EAAE,QAAO,cAAa;AAC9B,SAAQC,aAAa,QAAO,mBAAkB;AAE9C,SAAQC,UAAU,QAAO,kBAAiB;
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/build/renderDocument.ts"],"sourcesContent":["import {ux} from '@oclif/core'\nimport {tsxWorkerTask} from '@sanity/cli-core'\n\nimport {buildDebug} from './buildDebug.js'\n\ninterface DocumentProps {\n basePath: string\n\n css?: string[]\n entryPath?: string\n title?: string\n}\n\ninterface RenderDocumentOptions {\n studioRootPath: string\n\n autoUpdatesCssUrls?: string[]\n importMap?: {\n imports?: Record<string, string>\n }\n isApp?: boolean\n props?: DocumentProps\n}\n\nconst hasWarnedAbout = new Set<string>()\n\ninterface RenderDocumentWorkerResult {\n type: 'error' | 'result' | 'warning'\n\n html?: string\n message?: string | string[]\n warnKey?: string\n}\n\nexport async function renderDocument(options: RenderDocumentOptions): Promise<string> {\n buildDebug('Starting worker thread for %s', import.meta.url)\n try {\n const msg = await tsxWorkerTask<RenderDocumentWorkerResult>(\n new URL(`renderDocument.worker.js`, import.meta.url),\n {\n name: 'renderDocument',\n rootPath: options.studioRootPath,\n workerData: {...options, shouldWarn: true},\n },\n )\n\n if (msg.type === 'warning') {\n if (msg.warnKey && hasWarnedAbout.has(msg.warnKey)) {\n return ''\n }\n\n if (Array.isArray(msg.message)) {\n for (const warning of msg.message) {\n ux.warn(warning)\n }\n } else if (msg.message) {\n ux.warn(msg.message)\n }\n\n if (msg.warnKey) {\n hasWarnedAbout.add(msg.warnKey)\n }\n return ''\n }\n\n if (msg.type === 'error') {\n buildDebug('Error from worker: %s', msg.message || 'Unknown error')\n throw new Error(\n Array.isArray(msg.message)\n ? msg.message.join('\\n')\n : msg.message || 'Document rendering worker stopped with an unknown error',\n )\n }\n\n if (msg.type === 'result') {\n if (!msg.html) {\n throw new Error('Document rendering worker stopped with an unknown error')\n }\n\n buildDebug('Document HTML rendered, %d bytes', msg.html.length)\n return msg.html\n }\n\n throw new Error('Unknown message type')\n } catch (err) {\n buildDebug('Worker errored: %s', err.message)\n throw err\n }\n}\n"],"names":["ux","tsxWorkerTask","buildDebug","hasWarnedAbout","Set","renderDocument","options","url","msg","URL","name","rootPath","studioRootPath","workerData","shouldWarn","type","warnKey","has","Array","isArray","message","warning","warn","add","Error","join","html","length","err"],"mappings":"AAAA,SAAQA,EAAE,QAAO,cAAa;AAC9B,SAAQC,aAAa,QAAO,mBAAkB;AAE9C,SAAQC,UAAU,QAAO,kBAAiB;AAqB1C,MAAMC,iBAAiB,IAAIC;AAU3B,OAAO,eAAeC,eAAeC,OAA8B;IACjEJ,WAAW,iCAAiC,YAAYK,GAAG;IAC3D,IAAI;QACF,MAAMC,MAAM,MAAMP,cAChB,IAAIQ,IAAI,CAAC,wBAAwB,CAAC,EAAE,YAAYF,GAAG,GACnD;YACEG,MAAM;YACNC,UAAUL,QAAQM,cAAc;YAChCC,YAAY;gBAAC,GAAGP,OAAO;gBAAEQ,YAAY;YAAI;QAC3C;QAGF,IAAIN,IAAIO,IAAI,KAAK,WAAW;YAC1B,IAAIP,IAAIQ,OAAO,IAAIb,eAAec,GAAG,CAACT,IAAIQ,OAAO,GAAG;gBAClD,OAAO;YACT;YAEA,IAAIE,MAAMC,OAAO,CAACX,IAAIY,OAAO,GAAG;gBAC9B,KAAK,MAAMC,WAAWb,IAAIY,OAAO,CAAE;oBACjCpB,GAAGsB,IAAI,CAACD;gBACV;YACF,OAAO,IAAIb,IAAIY,OAAO,EAAE;gBACtBpB,GAAGsB,IAAI,CAACd,IAAIY,OAAO;YACrB;YAEA,IAAIZ,IAAIQ,OAAO,EAAE;gBACfb,eAAeoB,GAAG,CAACf,IAAIQ,OAAO;YAChC;YACA,OAAO;QACT;QAEA,IAAIR,IAAIO,IAAI,KAAK,SAAS;YACxBb,WAAW,yBAAyBM,IAAIY,OAAO,IAAI;YACnD,MAAM,IAAII,MACRN,MAAMC,OAAO,CAACX,IAAIY,OAAO,IACrBZ,IAAIY,OAAO,CAACK,IAAI,CAAC,QACjBjB,IAAIY,OAAO,IAAI;QAEvB;QAEA,IAAIZ,IAAIO,IAAI,KAAK,UAAU;YACzB,IAAI,CAACP,IAAIkB,IAAI,EAAE;gBACb,MAAM,IAAIF,MAAM;YAClB;YAEAtB,WAAW,oCAAoCM,IAAIkB,IAAI,CAACC,MAAM;YAC9D,OAAOnB,IAAIkB,IAAI;QACjB;QAEA,MAAM,IAAIF,MAAM;IAClB,EAAE,OAAOI,KAAK;QACZ1B,WAAW,sBAAsB0B,IAAIR,OAAO;QAC5C,MAAMQ;IACR;AACF"}
|
|
@@ -5,6 +5,9 @@ import { parse as parseHtml } from 'node-html-parser';
|
|
|
5
5
|
* the existing timestamp in the sanity-cdn URLs with a new runtime timestamp,
|
|
6
6
|
* and injects the modified import map back into the HTML.
|
|
7
7
|
*
|
|
8
|
+
* It also synchronously creates `<link rel="stylesheet">` tags for each CDN
|
|
9
|
+
* CSS URL with a fresh timestamp.
|
|
10
|
+
*
|
|
8
11
|
* This will be injected into the HTML of the user's bundle.
|
|
9
12
|
*
|
|
10
13
|
* Note that this is in a separate constants file to prevent "Cannot access
|
|
@@ -12,31 +15,42 @@ import { parse as parseHtml } from 'node-html-parser';
|
|
|
12
15
|
*/ const TIMESTAMPED_IMPORTMAP_INJECTOR_SCRIPT = `<script>
|
|
13
16
|
// auto-generated script to add import map with timestamp
|
|
14
17
|
const importsJson = document.getElementById('__imports')?.textContent;
|
|
15
|
-
const { imports = {}, ...rest } = importsJson ? JSON.parse(importsJson) : {};
|
|
18
|
+
const { imports = {}, css = [], ...rest } = importsJson ? JSON.parse(importsJson) : {};
|
|
16
19
|
const importMapEl = document.createElement('script');
|
|
17
20
|
importMapEl.type = 'importmap';
|
|
18
21
|
const newTimestamp = \`/t\${Math.floor(Date.now() / 1000)}\`;
|
|
22
|
+
|
|
23
|
+
function replaceTimestamp(urlStr) {
|
|
24
|
+
try {
|
|
25
|
+
const url = new URL(urlStr);
|
|
26
|
+
if (/^sanity-cdn\\.[a-zA-Z]+$/.test(url.hostname)) {
|
|
27
|
+
url.pathname = url.pathname.replace(/\\/t\\d+/, newTimestamp);
|
|
28
|
+
}
|
|
29
|
+
return url.toString();
|
|
30
|
+
} catch {
|
|
31
|
+
return urlStr;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
19
35
|
importMapEl.textContent = JSON.stringify({
|
|
20
36
|
imports: Object.fromEntries(
|
|
21
|
-
Object.entries(imports).map(([specifier, path]) =>
|
|
22
|
-
try {
|
|
23
|
-
const url = new URL(path);
|
|
24
|
-
if (/^sanity-cdn\\.[a-zA-Z]+$/.test(url.hostname)) {
|
|
25
|
-
url.pathname = url.pathname.replace(/\\/t\\d+/, newTimestamp);
|
|
26
|
-
}
|
|
27
|
-
return [specifier, url.toString()];
|
|
28
|
-
} catch {
|
|
29
|
-
return [specifier, path];
|
|
30
|
-
}
|
|
31
|
-
})
|
|
37
|
+
Object.entries(imports).map(([specifier, path]) => [specifier, replaceTimestamp(path)])
|
|
32
38
|
),
|
|
33
39
|
...rest,
|
|
34
40
|
});
|
|
35
41
|
document.head.appendChild(importMapEl);
|
|
42
|
+
|
|
43
|
+
// Creates <link rel="stylesheet"> tags with fresh timestamps.
|
|
44
|
+
for (const cssUrl of css) {
|
|
45
|
+
const linkEl = document.createElement('link');
|
|
46
|
+
linkEl.rel = 'stylesheet';
|
|
47
|
+
linkEl.href = replaceTimestamp(cssUrl);
|
|
48
|
+
document.head.appendChild(linkEl);
|
|
49
|
+
}
|
|
36
50
|
</script>`;
|
|
37
51
|
/**
|
|
38
52
|
* @internal
|
|
39
|
-
*/ export function addTimestampedImportMapScriptToHtml(html, importMap) {
|
|
53
|
+
*/ export function addTimestampedImportMapScriptToHtml(html, importMap, autoUpdatesCssUrls) {
|
|
40
54
|
if (!importMap) return html;
|
|
41
55
|
let root = parseHtml(html);
|
|
42
56
|
let htmlEl = root.querySelector('html');
|
|
@@ -51,7 +65,13 @@ import { parse as parseHtml } from 'node-html-parser';
|
|
|
51
65
|
htmlEl.insertAdjacentHTML('afterbegin', '<head></head>');
|
|
52
66
|
headEl = root.querySelector('head');
|
|
53
67
|
}
|
|
54
|
-
|
|
68
|
+
// Include CSS URLs in the __imports JSON so the runtime script can create
|
|
69
|
+
// <link> tags with fresh timestamps synchronously during head parsing.
|
|
70
|
+
const importMapWithCss = autoUpdatesCssUrls && autoUpdatesCssUrls.length > 0 ? {
|
|
71
|
+
...importMap,
|
|
72
|
+
css: autoUpdatesCssUrls
|
|
73
|
+
} : importMap;
|
|
74
|
+
headEl.insertAdjacentHTML('beforeend', `<script type="application/json" id="__imports">${JSON.stringify(importMapWithCss)}</script>`);
|
|
55
75
|
headEl.insertAdjacentHTML('beforeend', TIMESTAMPED_IMPORTMAP_INJECTOR_SCRIPT);
|
|
56
76
|
return root.outerHTML;
|
|
57
77
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/actions/build/renderDocumentWorker/addTimestampImportMapScriptToHtml.ts"],"sourcesContent":["import {parse as parseHtml} from 'node-html-parser'\n\n/**\n * This script takes the import map from the `#__imports` script tag,\n * modifies relevant URLs that match the sanity-cdn hostname by replacing\n * the existing timestamp in the sanity-cdn URLs with a new runtime timestamp,\n * and injects the modified import map back into the HTML.\n *\n * This will be injected into the HTML of the user's bundle.\n *\n * Note that this is in a separate constants file to prevent \"Cannot access\n * before initialization\" errors.\n */\nconst TIMESTAMPED_IMPORTMAP_INJECTOR_SCRIPT = `<script>\n // auto-generated script to add import map with timestamp\n const importsJson = document.getElementById('__imports')?.textContent;\n const { imports = {}, ...rest } = importsJson ? JSON.parse(importsJson) : {};\n const importMapEl = document.createElement('script');\n importMapEl.type = 'importmap';\n const newTimestamp = \\`/t\\${Math.floor(Date.now() / 1000)}\\`;\n
|
|
1
|
+
{"version":3,"sources":["../../../../src/actions/build/renderDocumentWorker/addTimestampImportMapScriptToHtml.ts"],"sourcesContent":["import {parse as parseHtml} from 'node-html-parser'\n\n/**\n * This script takes the import map from the `#__imports` script tag,\n * modifies relevant URLs that match the sanity-cdn hostname by replacing\n * the existing timestamp in the sanity-cdn URLs with a new runtime timestamp,\n * and injects the modified import map back into the HTML.\n *\n * It also synchronously creates `<link rel=\"stylesheet\">` tags for each CDN\n * CSS URL with a fresh timestamp.\n *\n * This will be injected into the HTML of the user's bundle.\n *\n * Note that this is in a separate constants file to prevent \"Cannot access\n * before initialization\" errors.\n */\nconst TIMESTAMPED_IMPORTMAP_INJECTOR_SCRIPT = `<script>\n // auto-generated script to add import map with timestamp\n const importsJson = document.getElementById('__imports')?.textContent;\n const { imports = {}, css = [], ...rest } = importsJson ? JSON.parse(importsJson) : {};\n const importMapEl = document.createElement('script');\n importMapEl.type = 'importmap';\n const newTimestamp = \\`/t\\${Math.floor(Date.now() / 1000)}\\`;\n\n function replaceTimestamp(urlStr) {\n try {\n const url = new URL(urlStr);\n if (/^sanity-cdn\\\\.[a-zA-Z]+$/.test(url.hostname)) {\n url.pathname = url.pathname.replace(/\\\\/t\\\\d+/, newTimestamp);\n }\n return url.toString();\n } catch {\n return urlStr;\n }\n }\n\n importMapEl.textContent = JSON.stringify({\n imports: Object.fromEntries(\n Object.entries(imports).map(([specifier, path]) => [specifier, replaceTimestamp(path)])\n ),\n ...rest,\n });\n document.head.appendChild(importMapEl);\n\n // Creates <link rel=\"stylesheet\"> tags with fresh timestamps.\n for (const cssUrl of css) {\n const linkEl = document.createElement('link');\n linkEl.rel = 'stylesheet';\n linkEl.href = replaceTimestamp(cssUrl);\n document.head.appendChild(linkEl);\n }\n</script>`\n\n/**\n * @internal\n */\nexport function addTimestampedImportMapScriptToHtml(\n html: string,\n importMap?: {imports?: Record<string, string>},\n autoUpdatesCssUrls?: string[],\n): string {\n if (!importMap) return html\n\n let root = parseHtml(html)\n let htmlEl = root.querySelector('html')\n if (!htmlEl) {\n const oldRoot = root\n root = parseHtml('<html></html>')\n htmlEl = root.querySelector('html')!\n htmlEl.append(oldRoot)\n }\n\n let headEl = htmlEl.querySelector('head')\n\n if (!headEl) {\n htmlEl.insertAdjacentHTML('afterbegin', '<head></head>')\n headEl = root.querySelector('head')!\n }\n\n // Include CSS URLs in the __imports JSON so the runtime script can create\n // <link> tags with fresh timestamps synchronously during head parsing.\n const importMapWithCss =\n autoUpdatesCssUrls && autoUpdatesCssUrls.length > 0\n ? {...importMap, css: autoUpdatesCssUrls}\n : importMap\n\n headEl.insertAdjacentHTML(\n 'beforeend',\n `<script type=\"application/json\" id=\"__imports\">${JSON.stringify(importMapWithCss)}</script>`,\n )\n\n headEl.insertAdjacentHTML('beforeend', TIMESTAMPED_IMPORTMAP_INJECTOR_SCRIPT)\n return root.outerHTML\n}\n"],"names":["parse","parseHtml","TIMESTAMPED_IMPORTMAP_INJECTOR_SCRIPT","addTimestampedImportMapScriptToHtml","html","importMap","autoUpdatesCssUrls","root","htmlEl","querySelector","oldRoot","append","headEl","insertAdjacentHTML","importMapWithCss","length","css","JSON","stringify","outerHTML"],"mappings":"AAAA,SAAQA,SAASC,SAAS,QAAO,mBAAkB;AAEnD;;;;;;;;;;;;;CAaC,GACD,MAAMC,wCAAwC,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;SAmCtC,CAAC;AAEV;;CAEC,GACD,OAAO,SAASC,oCACdC,IAAY,EACZC,SAA8C,EAC9CC,kBAA6B;IAE7B,IAAI,CAACD,WAAW,OAAOD;IAEvB,IAAIG,OAAON,UAAUG;IACrB,IAAII,SAASD,KAAKE,aAAa,CAAC;IAChC,IAAI,CAACD,QAAQ;QACX,MAAME,UAAUH;QAChBA,OAAON,UAAU;QACjBO,SAASD,KAAKE,aAAa,CAAC;QAC5BD,OAAOG,MAAM,CAACD;IAChB;IAEA,IAAIE,SAASJ,OAAOC,aAAa,CAAC;IAElC,IAAI,CAACG,QAAQ;QACXJ,OAAOK,kBAAkB,CAAC,cAAc;QACxCD,SAASL,KAAKE,aAAa,CAAC;IAC9B;IAEA,0EAA0E;IAC1E,uEAAuE;IACvE,MAAMK,mBACJR,sBAAsBA,mBAAmBS,MAAM,GAAG,IAC9C;QAAC,GAAGV,SAAS;QAAEW,KAAKV;IAAkB,IACtCD;IAENO,OAAOC,kBAAkB,CACvB,aACA,CAAC,+CAA+C,EAAEI,KAAKC,SAAS,CAACJ,kBAAkB,SAAS,CAAC;IAG/FF,OAAOC,kBAAkB,CAAC,aAAaX;IACvC,OAAOK,KAAKY,SAAS;AACvB"}
|
|
@@ -27,7 +27,7 @@ import { getDocumentComponent } from './getDocumentComponent.js';
|
|
|
27
27
|
}
|
|
28
28
|
/**
|
|
29
29
|
* @internal
|
|
30
|
-
*/ export async function getDocumentHtml(parent, studioRootPath, props, importMap, isApp) {
|
|
30
|
+
*/ export async function getDocumentHtml(parent, studioRootPath, props, importMap, isApp, autoUpdatesCssUrls) {
|
|
31
31
|
const Document = await getDocumentComponent(parent, studioRootPath, isApp);
|
|
32
32
|
const defaultProps = {
|
|
33
33
|
entryPath: './.sanity/runtime/app.js'
|
|
@@ -48,7 +48,7 @@ import { getDocumentComponent } from './getDocumentComponent.js';
|
|
|
48
48
|
...defaultProps,
|
|
49
49
|
...props,
|
|
50
50
|
css: css
|
|
51
|
-
})), importMap);
|
|
51
|
+
})), importMap, autoUpdatesCssUrls);
|
|
52
52
|
return `<!DOCTYPE html>${result}`;
|
|
53
53
|
}
|
|
54
54
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/actions/build/renderDocumentWorker/getDocumentHtml.tsx"],"sourcesContent":["import {type MessagePort} from 'node:worker_threads'\n\nimport {renderToStaticMarkup} from 'react-dom/server'\n\nimport {buildDebug} from '../buildDebug.js'\nimport {addTimestampedImportMapScriptToHtml} from './addTimestampImportMapScriptToHtml.js'\nimport {getDocumentComponent} from './getDocumentComponent.js'\nimport {type DocumentProps} from './types.js'\n\n/**\n * Adds a base path to a URL if necessary, and returns the resulting URL.\n * @param url - The URL to prefix with a base path.\n * @param basePath - The base path to prefix the URL with. Default value is `/`.\n * @returns The resulting URL with the base path.\n * @internal\n */\nfunction _prefixUrlWithBasePath(url: string, basePath: string): string {\n // Normalize basePath by adding a leading slash if it's missing.\n const normalizedBasePath = basePath.startsWith('/') ? basePath : `/${basePath}`\n\n // If the URL starts with a slash, append it to the basePath, removing any trailing slash if present.\n if (url.startsWith('/')) {\n if (normalizedBasePath.endsWith('/')) {\n return `${normalizedBasePath.slice(0, -1)}${url}`\n }\n return `${normalizedBasePath}${url}`\n }\n\n // If the URL doesn't start with a slash, append it to the basePath with a slash in between.\n if (normalizedBasePath.endsWith('/')) {\n return `${normalizedBasePath}${url}`\n }\n return `${normalizedBasePath}/${url}`\n}\n\n/**\n * @internal\n */\nexport async function getDocumentHtml(\n parent: MessagePort,\n studioRootPath: string,\n props?: DocumentProps,\n importMap?: {imports?: Record<string, string>},\n isApp?: boolean,\n): Promise<string> {\n const Document = await getDocumentComponent(parent, studioRootPath, isApp)\n\n const defaultProps = {\n entryPath: './.sanity/runtime/app.js',\n }\n\n // NOTE: Validate the list of CSS paths so implementers of `_document.tsx` don't have to\n // - If the path is not a full URL, check if it starts with `/`\n // - If not, then prepend a `/` to the string\n const css = props?.css?.map((url) => {\n try {\n // If the URL is absolute, we don't need to prefix it\n return new URL(url).toString()\n } catch {\n return _prefixUrlWithBasePath(url, props.basePath)\n }\n })\n\n buildDebug('Rendering document component using React')\n const result = addTimestampedImportMapScriptToHtml(\n renderToStaticMarkup(<Document {...defaultProps} {...props} css={css} />),\n importMap,\n )\n\n return `<!DOCTYPE html>${result}`\n}\n"],"names":["renderToStaticMarkup","buildDebug","addTimestampedImportMapScriptToHtml","getDocumentComponent","_prefixUrlWithBasePath","url","basePath","normalizedBasePath","startsWith","endsWith","slice","getDocumentHtml","parent","studioRootPath","props","importMap","isApp","Document","defaultProps","entryPath","css","map","URL","toString","result"],"mappings":";AAEA,SAAQA,oBAAoB,QAAO,mBAAkB;AAErD,SAAQC,UAAU,QAAO,mBAAkB;AAC3C,SAAQC,mCAAmC,QAAO,yCAAwC;AAC1F,SAAQC,oBAAoB,QAAO,4BAA2B;AAG9D;;;;;;CAMC,GACD,SAASC,uBAAuBC,GAAW,EAAEC,QAAgB;IAC3D,gEAAgE;IAChE,MAAMC,qBAAqBD,SAASE,UAAU,CAAC,OAAOF,WAAW,CAAC,CAAC,EAAEA,UAAU;IAE/E,qGAAqG;IACrG,IAAID,IAAIG,UAAU,CAAC,MAAM;QACvB,IAAID,mBAAmBE,QAAQ,CAAC,MAAM;YACpC,OAAO,GAAGF,mBAAmBG,KAAK,CAAC,GAAG,CAAC,KAAKL,KAAK;QACnD;QACA,OAAO,GAAGE,qBAAqBF,KAAK;IACtC;IAEA,4FAA4F;IAC5F,IAAIE,mBAAmBE,QAAQ,CAAC,MAAM;QACpC,OAAO,GAAGF,qBAAqBF,KAAK;IACtC;IACA,OAAO,GAAGE,mBAAmB,CAAC,EAAEF,KAAK;AACvC;AAEA;;CAEC,GACD,OAAO,eAAeM,gBACpBC,MAAmB,EACnBC,cAAsB,EACtBC,KAAqB,EACrBC,SAA8C,EAC9CC,KAAe;
|
|
1
|
+
{"version":3,"sources":["../../../../src/actions/build/renderDocumentWorker/getDocumentHtml.tsx"],"sourcesContent":["import {type MessagePort} from 'node:worker_threads'\n\nimport {renderToStaticMarkup} from 'react-dom/server'\n\nimport {buildDebug} from '../buildDebug.js'\nimport {addTimestampedImportMapScriptToHtml} from './addTimestampImportMapScriptToHtml.js'\nimport {getDocumentComponent} from './getDocumentComponent.js'\nimport {type DocumentProps} from './types.js'\n\n/**\n * Adds a base path to a URL if necessary, and returns the resulting URL.\n * @param url - The URL to prefix with a base path.\n * @param basePath - The base path to prefix the URL with. Default value is `/`.\n * @returns The resulting URL with the base path.\n * @internal\n */\nfunction _prefixUrlWithBasePath(url: string, basePath: string): string {\n // Normalize basePath by adding a leading slash if it's missing.\n const normalizedBasePath = basePath.startsWith('/') ? basePath : `/${basePath}`\n\n // If the URL starts with a slash, append it to the basePath, removing any trailing slash if present.\n if (url.startsWith('/')) {\n if (normalizedBasePath.endsWith('/')) {\n return `${normalizedBasePath.slice(0, -1)}${url}`\n }\n return `${normalizedBasePath}${url}`\n }\n\n // If the URL doesn't start with a slash, append it to the basePath with a slash in between.\n if (normalizedBasePath.endsWith('/')) {\n return `${normalizedBasePath}${url}`\n }\n return `${normalizedBasePath}/${url}`\n}\n\n/**\n * @internal\n */\nexport async function getDocumentHtml(\n parent: MessagePort,\n studioRootPath: string,\n props?: DocumentProps,\n importMap?: {imports?: Record<string, string>},\n isApp?: boolean,\n autoUpdatesCssUrls?: string[],\n): Promise<string> {\n const Document = await getDocumentComponent(parent, studioRootPath, isApp)\n\n const defaultProps = {\n entryPath: './.sanity/runtime/app.js',\n }\n\n // NOTE: Validate the list of CSS paths so implementers of `_document.tsx` don't have to\n // - If the path is not a full URL, check if it starts with `/`\n // - If not, then prepend a `/` to the string\n const css = props?.css?.map((url) => {\n try {\n // If the URL is absolute, we don't need to prefix it\n return new URL(url).toString()\n } catch {\n return _prefixUrlWithBasePath(url, props.basePath)\n }\n })\n\n buildDebug('Rendering document component using React')\n const result = addTimestampedImportMapScriptToHtml(\n renderToStaticMarkup(<Document {...defaultProps} {...props} css={css} />),\n importMap,\n autoUpdatesCssUrls,\n )\n\n return `<!DOCTYPE html>${result}`\n}\n"],"names":["renderToStaticMarkup","buildDebug","addTimestampedImportMapScriptToHtml","getDocumentComponent","_prefixUrlWithBasePath","url","basePath","normalizedBasePath","startsWith","endsWith","slice","getDocumentHtml","parent","studioRootPath","props","importMap","isApp","autoUpdatesCssUrls","Document","defaultProps","entryPath","css","map","URL","toString","result"],"mappings":";AAEA,SAAQA,oBAAoB,QAAO,mBAAkB;AAErD,SAAQC,UAAU,QAAO,mBAAkB;AAC3C,SAAQC,mCAAmC,QAAO,yCAAwC;AAC1F,SAAQC,oBAAoB,QAAO,4BAA2B;AAG9D;;;;;;CAMC,GACD,SAASC,uBAAuBC,GAAW,EAAEC,QAAgB;IAC3D,gEAAgE;IAChE,MAAMC,qBAAqBD,SAASE,UAAU,CAAC,OAAOF,WAAW,CAAC,CAAC,EAAEA,UAAU;IAE/E,qGAAqG;IACrG,IAAID,IAAIG,UAAU,CAAC,MAAM;QACvB,IAAID,mBAAmBE,QAAQ,CAAC,MAAM;YACpC,OAAO,GAAGF,mBAAmBG,KAAK,CAAC,GAAG,CAAC,KAAKL,KAAK;QACnD;QACA,OAAO,GAAGE,qBAAqBF,KAAK;IACtC;IAEA,4FAA4F;IAC5F,IAAIE,mBAAmBE,QAAQ,CAAC,MAAM;QACpC,OAAO,GAAGF,qBAAqBF,KAAK;IACtC;IACA,OAAO,GAAGE,mBAAmB,CAAC,EAAEF,KAAK;AACvC;AAEA;;CAEC,GACD,OAAO,eAAeM,gBACpBC,MAAmB,EACnBC,cAAsB,EACtBC,KAAqB,EACrBC,SAA8C,EAC9CC,KAAe,EACfC,kBAA6B;IAE7B,MAAMC,WAAW,MAAMf,qBAAqBS,QAAQC,gBAAgBG;IAEpE,MAAMG,eAAe;QACnBC,WAAW;IACb;IAEA,wFAAwF;IACxF,+DAA+D;IAC/D,+CAA+C;IAC/C,MAAMC,MAAMP,OAAOO,KAAKC,IAAI,CAACjB;QAC3B,IAAI;YACF,qDAAqD;YACrD,OAAO,IAAIkB,IAAIlB,KAAKmB,QAAQ;QAC9B,EAAE,OAAM;YACN,OAAOpB,uBAAuBC,KAAKS,MAAMR,QAAQ;QACnD;IACF;IAEAL,WAAW;IACX,MAAMwB,SAASvB,oCACbF,mCAAqB,KAACkB;QAAU,GAAGC,YAAY;QAAG,GAAGL,KAAK;QAAEO,KAAKA;SACjEN,WACAE;IAGF,OAAO,CAAC,eAAe,EAAEQ,QAAQ;AACnC"}
|
|
@@ -6,7 +6,7 @@ import { getDocumentHtml } from './getDocumentHtml.js';
|
|
|
6
6
|
* @param options - The options for the document to render
|
|
7
7
|
* @returns - The rendered document
|
|
8
8
|
*/ export async function renderDocumentWorker(parent, options) {
|
|
9
|
-
const { importMap, isApp, props, studioRootPath } = options;
|
|
9
|
+
const { autoUpdatesCssUrls, importMap, isApp, props, studioRootPath } = options;
|
|
10
10
|
if (typeof studioRootPath !== 'string') {
|
|
11
11
|
parent.postMessage({
|
|
12
12
|
message: 'Missing/invalid `studioRootPath` option',
|
|
@@ -21,7 +21,7 @@ import { getDocumentHtml } from './getDocumentHtml.js';
|
|
|
21
21
|
});
|
|
22
22
|
return;
|
|
23
23
|
}
|
|
24
|
-
const html = await getDocumentHtml(parent, studioRootPath, props, importMap, isApp);
|
|
24
|
+
const html = await getDocumentHtml(parent, studioRootPath, props, importMap, isApp, autoUpdatesCssUrls);
|
|
25
25
|
parent.postMessage({
|
|
26
26
|
html,
|
|
27
27
|
type: 'result'
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/actions/build/renderDocumentWorker/renderDocumentWorker.ts"],"sourcesContent":["import {type MessagePort} from 'node:worker_threads'\n\nimport {getDocumentHtml} from './getDocumentHtml.js'\nimport {type DocumentProps} from './types.js'\n\n/**\n * @internal\n */\nexport interface RenderDocumentWorkerOptions {\n studioRootPath: string\n\n importMap?: {\n imports?: Record<string, string>\n }\n isApp?: boolean\n props?: DocumentProps\n}\n\n/**\n * Renders a document in a worker thread\n *\n * @param parent - The parent port to send messages to\n * @param options - The options for the document to render\n * @returns - The rendered document\n */\nexport async function renderDocumentWorker(\n parent: MessagePort,\n options: RenderDocumentWorkerOptions,\n) {\n const {importMap, isApp, props, studioRootPath} = options\n\n if (typeof studioRootPath !== 'string') {\n parent.postMessage({\n message: 'Missing/invalid `studioRootPath` option',\n type: 'error',\n })\n return\n }\n\n if (props && typeof props !== 'object') {\n parent.postMessage({\n message: '`props` must be an object if provided',\n type: 'error',\n })\n return\n }\n\n const html = await getDocumentHtml(parent
|
|
1
|
+
{"version":3,"sources":["../../../../src/actions/build/renderDocumentWorker/renderDocumentWorker.ts"],"sourcesContent":["import {type MessagePort} from 'node:worker_threads'\n\nimport {getDocumentHtml} from './getDocumentHtml.js'\nimport {type DocumentProps} from './types.js'\n\n/**\n * @internal\n */\nexport interface RenderDocumentWorkerOptions {\n studioRootPath: string\n\n autoUpdatesCssUrls?: string[]\n importMap?: {\n imports?: Record<string, string>\n }\n isApp?: boolean\n props?: DocumentProps\n}\n\n/**\n * Renders a document in a worker thread\n *\n * @param parent - The parent port to send messages to\n * @param options - The options for the document to render\n * @returns - The rendered document\n */\nexport async function renderDocumentWorker(\n parent: MessagePort,\n options: RenderDocumentWorkerOptions,\n) {\n const {autoUpdatesCssUrls, importMap, isApp, props, studioRootPath} = options\n\n if (typeof studioRootPath !== 'string') {\n parent.postMessage({\n message: 'Missing/invalid `studioRootPath` option',\n type: 'error',\n })\n return\n }\n\n if (props && typeof props !== 'object') {\n parent.postMessage({\n message: '`props` must be an object if provided',\n type: 'error',\n })\n return\n }\n\n const html = await getDocumentHtml(\n parent,\n studioRootPath,\n props,\n importMap,\n isApp,\n autoUpdatesCssUrls,\n )\n\n parent.postMessage({\n html,\n type: 'result',\n })\n}\n"],"names":["getDocumentHtml","renderDocumentWorker","parent","options","autoUpdatesCssUrls","importMap","isApp","props","studioRootPath","postMessage","message","type","html"],"mappings":"AAEA,SAAQA,eAAe,QAAO,uBAAsB;AAiBpD;;;;;;CAMC,GACD,OAAO,eAAeC,qBACpBC,MAAmB,EACnBC,OAAoC;IAEpC,MAAM,EAACC,kBAAkB,EAAEC,SAAS,EAAEC,KAAK,EAAEC,KAAK,EAAEC,cAAc,EAAC,GAAGL;IAEtE,IAAI,OAAOK,mBAAmB,UAAU;QACtCN,OAAOO,WAAW,CAAC;YACjBC,SAAS;YACTC,MAAM;QACR;QACA;IACF;IAEA,IAAIJ,SAAS,OAAOA,UAAU,UAAU;QACtCL,OAAOO,WAAW,CAAC;YACjBC,SAAS;YACTC,MAAM;QACR;QACA;IACF;IAEA,MAAMC,OAAO,MAAMZ,gBACjBE,QACAM,gBACAD,OACAF,WACAC,OACAF;IAGFF,OAAOO,WAAW,CAAC;QACjBG;QACAD,MAAM;IACR;AACF"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import
|
|
1
|
+
import { compare } from 'semver';
|
|
2
2
|
import { getLocalPackageVersion } from '../../util/getLocalPackageVersion.js';
|
|
3
3
|
const purpose = 'Transform react-icons v2 imports to v3 form';
|
|
4
4
|
const description = `
|
|
@@ -21,7 +21,7 @@ export const reactIconsV3 = {
|
|
|
21
21
|
if (!dependencyVersion) {
|
|
22
22
|
throw new Error('Could not find react-icons declared as dependency in package.json');
|
|
23
23
|
}
|
|
24
|
-
if (
|
|
24
|
+
if (compare(dependencyVersion, '3.0.0') < 0) {
|
|
25
25
|
throw new Error('react-icons declared in package.json dependencies is lower than 3.0.0');
|
|
26
26
|
}
|
|
27
27
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/actions/codemods/reactIconsV3.ts"],"sourcesContent":["import
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/codemods/reactIconsV3.ts"],"sourcesContent":["import {compare} from 'semver'\n\nimport {getLocalPackageVersion} from '../../util/getLocalPackageVersion.js'\nimport {type CodeMod} from './types.js'\n\nconst purpose = 'Transform react-icons v2 imports to v3 form'\nconst description = `\nModifies all found react-icons import and require statements from their v2 form\nto the path structure used in react-icons v3. For instance:\n\nfrom: import {MdPerson} from 'react-icons/lib/md'\n to: import {MdPerson} from 'react-icons/md'\n\nfrom: import PersonIcon from 'react-icons/lib/md/person'\n to: import {MdPerson as PersonIcon} from 'react-icons/md'\n`.trim()\n\nexport const reactIconsV3: CodeMod = {\n description,\n filename: 'reactIconsV3.js',\n purpose,\n verify: async (context) => {\n const {workDir} = context\n\n const dependencyVersion = await getLocalPackageVersion('react-icons', workDir)\n if (!dependencyVersion) {\n throw new Error('Could not find react-icons declared as dependency in package.json')\n }\n\n if (compare(dependencyVersion, '3.0.0') < 0) {\n throw new Error('react-icons declared in package.json dependencies is lower than 3.0.0')\n }\n },\n}\n"],"names":["compare","getLocalPackageVersion","purpose","description","trim","reactIconsV3","filename","verify","context","workDir","dependencyVersion","Error"],"mappings":"AAAA,SAAQA,OAAO,QAAO,SAAQ;AAE9B,SAAQC,sBAAsB,QAAO,uCAAsC;AAG3E,MAAMC,UAAU;AAChB,MAAMC,cAAc,CAAC;;;;;;;;;AASrB,CAAC,CAACC,IAAI;AAEN,OAAO,MAAMC,eAAwB;IACnCF;IACAG,UAAU;IACVJ;IACAK,QAAQ,OAAOC;QACb,MAAM,EAACC,OAAO,EAAC,GAAGD;QAElB,MAAME,oBAAoB,MAAMT,uBAAuB,eAAeQ;QACtE,IAAI,CAACC,mBAAmB;YACtB,MAAM,IAAIC,MAAM;QAClB;QAEA,IAAIX,QAAQU,mBAAmB,WAAW,GAAG;YAC3C,MAAM,IAAIC,MAAM;QAClB;IACF;AACF,EAAC"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { styleText } from 'node:util';
|
|
2
2
|
import { isInteractive } from '@sanity/cli-core';
|
|
3
3
|
import { confirm, logSymbols, spinner } from '@sanity/cli-core/ux';
|
|
4
|
-
import
|
|
4
|
+
import { parse as semverParse } from 'semver';
|
|
5
5
|
import { startDevServer } from '../../server/devServer.js';
|
|
6
6
|
import { gracefulServerDeath } from '../../server/gracefulServerDeath.js';
|
|
7
7
|
import { getProjectById } from '../../services/projects.js';
|
|
@@ -32,7 +32,7 @@ export async function startStudioDevServer(options) {
|
|
|
32
32
|
});
|
|
33
33
|
if (autoUpdatesEnabled) {
|
|
34
34
|
// Get the clean version without build metadata: https://semver.org/#spec-item-10
|
|
35
|
-
const cleanSanityVersion =
|
|
35
|
+
const cleanSanityVersion = semverParse(installedSanityVersion)?.version;
|
|
36
36
|
if (!cleanSanityVersion) {
|
|
37
37
|
throw new Error(`Failed to parse installed Sanity version: ${installedSanityVersion}`);
|
|
38
38
|
}
|