sanity 3.72.2-coreui.15 → 3.72.2-server-side-schemas.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (27) hide show
  1. package/lib/_chunks-cjs/_internal.js +111 -69
  2. package/lib/_chunks-cjs/_internal.js.map +1 -1
  3. package/lib/_chunks-cjs/deployAction.js +10 -3
  4. package/lib/_chunks-cjs/deployAction.js.map +1 -1
  5. package/lib/_chunks-cjs/fetchSchemaAction.js +18 -0
  6. package/lib/_chunks-cjs/fetchSchemaAction.js.map +1 -0
  7. package/lib/_chunks-cjs/runtime.js +2 -6
  8. package/lib/_chunks-cjs/runtime.js.map +1 -1
  9. package/lib/_chunks-cjs/storeManifestSchemasAction.js +52 -0
  10. package/lib/_chunks-cjs/storeManifestSchemasAction.js.map +1 -0
  11. package/lib/_chunks-cjs/storeSchemaAction.js +7 -0
  12. package/lib/_chunks-cjs/storeSchemaAction.js.map +1 -0
  13. package/lib/_chunks-cjs/version.js +1 -1
  14. package/lib/_chunks-es/version.mjs +1 -1
  15. package/lib/_legacy/version.esm.js +1 -1
  16. package/package.json +10 -10
  17. package/src/_internal/cli/actions/deploy/deployAction.ts +14 -2
  18. package/src/_internal/cli/actions/manifest/storeManifestSchemasAction.ts +88 -0
  19. package/src/_internal/cli/actions/schema/fetchSchemaAction.ts +36 -0
  20. package/src/_internal/cli/actions/schema/storeSchemaAction.ts +17 -0
  21. package/src/_internal/cli/commands/build/buildCommand.ts +2 -0
  22. package/src/_internal/cli/commands/deploy/deployCommand.ts +1 -0
  23. package/src/_internal/cli/commands/index.ts +4 -0
  24. package/src/_internal/cli/commands/schema/fetchSchemaCommand.ts +32 -0
  25. package/src/_internal/cli/commands/schema/storeSchemaCommand.ts +33 -0
  26. package/src/_internal/cli/server/renderDocument.tsx +0 -12
  27. package/src/_internal/cli/server/runtime.ts +9 -12
@@ -1,5 +1,5 @@
1
1
  "use strict";
2
- var path = require("node:path"), zlib = require("node:zlib"), tar = require("tar-fs"), buildAction = require("./buildAction.js"), extractManifestAction = require("./extractManifestAction.js"), helpers = require("./helpers.js");
2
+ var path = require("node:path"), zlib = require("node:zlib"), tar = require("tar-fs"), buildAction = require("./buildAction.js"), extractManifestAction = require("./extractManifestAction.js"), storeManifestSchemasAction = require("./storeManifestSchemasAction.js"), helpers = require("./helpers.js");
3
3
  function _interopDefaultCompat(e) {
4
4
  return e && typeof e == "object" && "default" in e ? e : { default: e };
5
5
  }
@@ -70,11 +70,18 @@ async function deployStudioAction(args, context) {
70
70
  });
71
71
  if (!didCompile)
72
72
  return;
73
- await extractManifestAction.extractManifestSafe({
73
+ const extractManifestError = await extractManifestAction.extractManifestSafe({
74
74
  ...buildArgs,
75
75
  extOptions: {},
76
76
  extraArguments: []
77
- }, context);
77
+ }, context), storeManifestSchemasArgs = {
78
+ ...args,
79
+ extOptions: {
80
+ "schema-path": flags["schema-path"]
81
+ },
82
+ extraArguments: []
83
+ };
84
+ extractManifestError || await storeManifestSchemasAction.storeManifestSchemas(storeManifestSchemasArgs, context);
78
85
  }
79
86
  spinner = output.spinner("Verifying local content").start();
80
87
  try {
@@ -1 +1 @@
1
- {"version":3,"file":"deployAction.js","sources":["../../src/_internal/cli/actions/deploy/deployAction.ts"],"sourcesContent":["/* eslint-disable max-statements */\nimport path from 'node:path'\nimport zlib from 'node:zlib'\n\nimport {type CliCommandArguments, type CliCommandContext} from '@sanity/cli'\nimport tar from 'tar-fs'\n\nimport {shouldAutoUpdate} from '../../util/shouldAutoUpdate'\nimport buildSanityStudio, {type BuildSanityStudioCommandFlags} from '../build/buildAction'\nimport {extractManifestSafe} from '../manifest/extractManifestAction'\nimport {\n checkDir,\n createDeployment,\n debug,\n dirIsEmptyOrNonExistent,\n getInstalledSanityVersion,\n getOrCreateUserApplication,\n getOrCreateUserApplicationFromConfig,\n type UserApplication,\n} from './helpers'\n\nexport interface DeployStudioActionFlags extends BuildSanityStudioCommandFlags {\n build?: boolean\n}\n\nexport default async function deployStudioAction(\n args: CliCommandArguments<DeployStudioActionFlags>,\n context: CliCommandContext,\n): Promise<void> {\n const {apiClient, workDir, chalk, output, prompt, cliConfig} = context\n const flags = {build: true, ...args.extOptions}\n const customSourceDir = args.argsWithoutOptions[0]\n const sourceDir = path.resolve(process.cwd(), customSourceDir || path.join(workDir, 'dist'))\n const isAutoUpdating = shouldAutoUpdate({flags, cliConfig})\n\n const installedSanityVersion = await getInstalledSanityVersion()\n const configStudioHost = cliConfig && 'studioHost' in cliConfig && cliConfig.studioHost\n\n const client = apiClient({\n requireUser: true,\n requireProject: true,\n }).withConfig({apiVersion: 'v2024-08-01'})\n\n if (customSourceDir === 'graphql') {\n throw new Error('Did you mean `sanity graphql deploy`?')\n }\n\n if (customSourceDir) {\n let relativeOutput = path.relative(process.cwd(), sourceDir)\n if (relativeOutput[0] !== '.') {\n relativeOutput = `./${relativeOutput}`\n }\n\n const isEmpty = await dirIsEmptyOrNonExistent(sourceDir)\n const shouldProceed =\n isEmpty ||\n (await prompt.single({\n type: 'confirm',\n message: `\"${relativeOutput}\" is not empty, do you want to proceed?`,\n default: false,\n }))\n\n if (!shouldProceed) {\n output.print('Cancelled.')\n return\n }\n\n output.print(`Building to ${relativeOutput}\\n`)\n }\n\n // Check that the project has a studio hostname\n let spinner = output.spinner('Checking project info').start()\n\n let userApplication: UserApplication\n\n try {\n // If the user has provided a studioHost in the config, use that\n if (configStudioHost) {\n userApplication = await getOrCreateUserApplicationFromConfig({\n client,\n context,\n spinner,\n appHost: configStudioHost,\n })\n } else {\n userApplication = await getOrCreateUserApplication({\n client,\n context,\n spinner,\n })\n }\n } catch (err) {\n if (err.message) {\n output.error(chalk.red(err.message))\n return\n }\n\n debug('Error creating user application', err)\n throw err\n }\n\n // Always build the project, unless --no-build is passed\n const shouldBuild = flags.build\n if (shouldBuild) {\n const buildArgs = {\n ...args,\n extOptions: flags,\n argsWithoutOptions: [customSourceDir].filter(Boolean),\n }\n const {didCompile} = await buildSanityStudio(buildArgs, context, {basePath: '/'})\n\n if (!didCompile) {\n return\n }\n\n await extractManifestSafe(\n {\n ...buildArgs,\n extOptions: {},\n extraArguments: [],\n },\n context,\n )\n }\n\n // Ensure that the directory exists, is a directory and seems to have valid content\n spinner = output.spinner('Verifying local content').start()\n try {\n await checkDir(sourceDir)\n spinner.succeed()\n } catch (err) {\n spinner.fail()\n debug('Error checking directory', err)\n throw err\n }\n\n // Now create a tarball of the given directory\n const parentDir = path.dirname(sourceDir)\n const base = path.basename(sourceDir)\n const tarball = tar.pack(parentDir, {entries: [base]}).pipe(zlib.createGzip())\n\n spinner = output.spinner('Deploying to Sanity.Studio').start()\n try {\n const {location} = await createDeployment({\n client,\n applicationId: userApplication.id,\n version: installedSanityVersion,\n isAutoUpdating,\n tarball,\n })\n\n spinner.succeed()\n\n // And let the user know we're done\n output.print(`\\nSuccess! Studio deployed to ${chalk.cyan(location)}`)\n\n if (!configStudioHost) {\n output.print(`\\nAdd ${chalk.cyan(`studioHost: '${userApplication.appHost}'`)}`)\n output.print('to defineCliConfig root properties in sanity.cli.js or sanity.cli.ts')\n output.print('to avoid prompting for hostname on next deploy.')\n }\n } catch (err) {\n spinner.fail()\n debug('Error deploying studio', err)\n throw err\n }\n}\n"],"names":["deployStudioAction","args","context","apiClient","workDir","chalk","output","prompt","cliConfig","flags","build","extOptions","customSourceDir","argsWithoutOptions","sourceDir","path","resolve","process","cwd","join","isAutoUpdating","shouldAutoUpdate","installedSanityVersion","getInstalledSanityVersion","configStudioHost","studioHost","client","requireUser","requireProject","withConfig","apiVersion","Error","relativeOutput","relative","dirIsEmptyOrNonExistent","single","type","message","default","print","spinner","start","userApplication","getOrCreateUserApplicationFromConfig","appHost","getOrCreateUserApplication","err","error","red","debug","buildArgs","filter","Boolean","didCompile","buildSanityStudio","basePath","extractManifestSafe","extraArguments","checkDir","succeed","fail","parentDir","dirname","base","basename","tarball","tar","pack","entries","pipe","zlib","createGzip","location","createDeployment","applicationId","id","version","cyan"],"mappings":";;;;;;AAy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AE7E/B,YAAUlC,OAAOkC,QAAQ,4BAA4B,EAAEC,MAAM;AACzD,MAAA;AACI,UAAA;AAAA,MAAC+B;AAAAA,IAAQ,IAAI,MAAMC,QAAAA,iBAAiB;AAAA,MACxC/C;AAAAA,MACAgD,eAAehC,gBAAgBiC;AAAAA,MAC/BC,SAAStD;AAAAA,MACTF;AAAAA,MACA6C;AAAAA,IAAAA,CACD;AAEON,YAAAA,QAAAA,GAGRrD,OAAOiC,MAAM;AAAA,8BAAiClC,MAAMwE,KAAKL,QAAQ,CAAC,EAAE,GAE/DhD,qBACHlB,OAAOiC,MAAM;AAAA,MAASlC,MAAMwE,KAAK,gBAAgBnC,gBAAgBE,OAAO,GAAG,CAAC,EAAE,GAC9EtC,OAAOiC,MAAM,sEAAsE,GACnFjC,OAAOiC,MAAM,iDAAiD;AAAA,WAEzDO,KAAK;AACZN,UAAAA,QAAQoB,KAAK,GACbX,QAAM,MAAA,0BAA0BH,GAAG,GAC7BA;AAAAA,EAAAA;AAEV;;"}
1
+ {"version":3,"file":"deployAction.js","sources":["../../src/_internal/cli/actions/deploy/deployAction.ts"],"sourcesContent":["/* eslint-disable max-statements */\nimport path from 'node:path'\nimport zlib from 'node:zlib'\n\nimport {type CliCommandArguments, type CliCommandContext} from '@sanity/cli'\nimport tar from 'tar-fs'\n\nimport {shouldAutoUpdate} from '../../util/shouldAutoUpdate'\nimport buildSanityStudio, {type BuildSanityStudioCommandFlags} from '../build/buildAction'\nimport {extractManifestSafe} from '../manifest/extractManifestAction'\nimport {storeManifestSchemas} from '../manifest/storeManifestSchemasAction'\nimport {\n checkDir,\n createDeployment,\n debug,\n dirIsEmptyOrNonExistent,\n getInstalledSanityVersion,\n getOrCreateUserApplication,\n getOrCreateUserApplicationFromConfig,\n type UserApplication,\n} from './helpers'\n\nexport interface DeployStudioActionFlags extends BuildSanityStudioCommandFlags {\n 'schema-path'?: string\n 'build'?: boolean\n}\n\nexport default async function deployStudioAction(\n args: CliCommandArguments<DeployStudioActionFlags>,\n context: CliCommandContext,\n): Promise<void> {\n const {apiClient, workDir, chalk, output, prompt, cliConfig} = context\n const flags = {build: true, ...args.extOptions}\n const customSourceDir = args.argsWithoutOptions[0]\n const sourceDir = path.resolve(process.cwd(), customSourceDir || path.join(workDir, 'dist'))\n const isAutoUpdating = shouldAutoUpdate({flags, cliConfig})\n\n const installedSanityVersion = await getInstalledSanityVersion()\n const configStudioHost = cliConfig && 'studioHost' in cliConfig && cliConfig.studioHost\n\n const client = apiClient({\n requireUser: true,\n requireProject: true,\n }).withConfig({apiVersion: 'v2024-08-01'})\n\n if (customSourceDir === 'graphql') {\n throw new Error('Did you mean `sanity graphql deploy`?')\n }\n\n if (customSourceDir) {\n let relativeOutput = path.relative(process.cwd(), sourceDir)\n if (relativeOutput[0] !== '.') {\n relativeOutput = `./${relativeOutput}`\n }\n\n const isEmpty = await dirIsEmptyOrNonExistent(sourceDir)\n const shouldProceed =\n isEmpty ||\n (await prompt.single({\n type: 'confirm',\n message: `\"${relativeOutput}\" is not empty, do you want to proceed?`,\n default: false,\n }))\n\n if (!shouldProceed) {\n output.print('Cancelled.')\n return\n }\n\n output.print(`Building to ${relativeOutput}\\n`)\n }\n\n // Check that the project has a studio hostname\n let spinner = output.spinner('Checking project info').start()\n\n let userApplication: UserApplication\n\n try {\n // If the user has provided a studioHost in the config, use that\n if (configStudioHost) {\n userApplication = await getOrCreateUserApplicationFromConfig({\n client,\n context,\n spinner,\n appHost: configStudioHost,\n })\n } else {\n userApplication = await getOrCreateUserApplication({\n client,\n context,\n spinner,\n })\n }\n } catch (err) {\n if (err.message) {\n output.error(chalk.red(err.message))\n return\n }\n\n debug('Error creating user application', err)\n throw err\n }\n\n // Always build the project, unless --no-build is passed\n const shouldBuild = flags.build\n if (shouldBuild) {\n const buildArgs = {\n ...args,\n extOptions: flags,\n argsWithoutOptions: [customSourceDir].filter(Boolean),\n }\n const {didCompile} = await buildSanityStudio(buildArgs, context, {basePath: '/'})\n\n if (!didCompile) {\n return\n }\n\n const extractManifestError = await extractManifestSafe(\n {\n ...buildArgs,\n extOptions: {},\n extraArguments: [],\n },\n context,\n )\n\n const storeManifestSchemasArgs = {\n ...args,\n extOptions: {\n 'schema-path': flags['schema-path'],\n },\n extraArguments: [],\n }\n\n if (!extractManifestError) await storeManifestSchemas(storeManifestSchemasArgs, context)\n }\n\n // Ensure that the directory exists, is a directory and seems to have valid content\n spinner = output.spinner('Verifying local content').start()\n try {\n await checkDir(sourceDir)\n spinner.succeed()\n } catch (err) {\n spinner.fail()\n debug('Error checking directory', err)\n throw err\n }\n\n // Now create a tarball of the given directory\n const parentDir = path.dirname(sourceDir)\n const base = path.basename(sourceDir)\n const tarball = tar.pack(parentDir, {entries: [base]}).pipe(zlib.createGzip())\n\n spinner = output.spinner('Deploying to Sanity.Studio').start()\n try {\n const {location} = await createDeployment({\n client,\n applicationId: userApplication.id,\n version: installedSanityVersion,\n isAutoUpdating,\n tarball,\n })\n\n spinner.succeed()\n\n // And let the user know we're done\n output.print(`\\nSuccess! Studio deployed to ${chalk.cyan(location)}`)\n\n if (!configStudioHost) {\n output.print(`\\nAdd ${chalk.cyan(`studioHost: '${userApplication.appHost}'`)}`)\n output.print('to defineCliConfig root properties in sanity.cli.js or sanity.cli.ts')\n output.print('to avoid prompting for hostname on next deploy.')\n }\n } catch (err) {\n spinner.fail()\n debug('Error deploying studio', err)\n throw err\n }\n}\n"],"names":["deployStudioAction","args","context","apiClient","workDir","chalk","output","prompt","cliConfig","flags","build","extOptions","customSourceDir","argsWithoutOptions","sourceDir","path","resolve","process","cwd","join","isAutoUpdating","shouldAutoUpdate","installedSanityVersion","getInstalledSanityVersion","configStudioHost","studioHost","client","requireUser","requireProject","withConfig","apiVersion","Error","relativeOutput","relative","dirIsEmptyOrNonExistent","single","type","message","default","print","spinner","start","userApplication","getOrCreateUserApplicationFromConfig","appHost","getOrCreateUserApplication","err","error","red","debug","buildArgs","filter","Boolean","didCompile","buildSanityStudio","basePath","extractManifestError","extractManifestSafe","extraArguments","storeManifestSchemasArgs","storeManifestSchemas","checkDir","succeed","fail","parentDir","dirname","base","basename","tarball","tar","pack","entries","pipe","zlib","createGzip","location","createDeployment","applicationId","id","version","cyan"],"mappings":";;;;;;AA2B8BA,eAAAA,mBAC5BC,MACAC,SACe;AACT,QAAA;AAAA,IAACC;AAAAA,IAAWC;AAAAA,IAASC;AAAAA,IAAOC;AAAAA,IAAQC;AAAAA,IAAQC;AAAAA,EAAAA,IAAaN,SACzDO,QAAQ;AAAA,IAACC,OAAO;AAAA,IAAM,GAAGT,KAAKU;AAAAA,EAAAA,GAC9BC,kBAAkBX,KAAKY,mBAAmB,CAAC,GAC3CC,YAAYC,cAAAA,QAAKC,QAAQC,QAAQC,OAAON,mBAAmBG,sBAAKI,KAAKf,SAAS,MAAM,CAAC,GACrFgB,iBAAiBC,6BAAiB;AAAA,IAACZ;AAAAA,IAAOD;AAAAA,EAAU,CAAA,GAEpDc,yBAAyB,MAAMC,QAA0B,0BAAA,GACzDC,mBAAmBhB,aAAa,gBAAgBA,aAAaA,UAAUiB,YAEvEC,SAASvB,UAAU;AAAA,IACvBwB,aAAa;AAAA,IACbC,gBAAgB;AAAA,EACjB,CAAA,EAAEC,WAAW;AAAA,IAACC,YAAY;AAAA,EAAA,CAAc;AAEzC,MAAIlB,oBAAoB;AAChB,UAAA,IAAImB,MAAM,uCAAuC;AAGzD,MAAInB,iBAAiB;AACnB,QAAIoB,iBAAiBjB,cAAAA,QAAKkB,SAAShB,QAAQC,OAAOJ,SAAS;AAc3D,QAbIkB,eAAe,CAAC,MAAM,QACxBA,iBAAiB,KAAKA,cAAc,KAYlC,EATY,MAAME,QAAwBpB,wBAAAA,SAAS,KAGpD,MAAMP,OAAO4B,OAAO;AAAA,MACnBC,MAAM;AAAA,MACNC,SAAS,IAAIL,cAAc;AAAA,MAC3BM,SAAS;AAAA,IACV,CAAA,IAEiB;AAClBhC,aAAOiC,MAAM,YAAY;AACzB;AAAA,IAAA;AAGKA,WAAAA,M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B,iBAAS/C,SAAS,GACxB0B,QAAQsB,QAAQ;AAAA,WACThB,KAAK;AACZN,UAAAA,QAAQuB,KAAK,GACbd,QAAM,MAAA,4BAA4BH,GAAG,GAC/BA;AAAAA,EAAAA;AAIR,QAAMkB,YAAYjD,cAAAA,QAAKkD,QAAQnD,SAAS,GAClCoD,OAAOnD,cAAAA,QAAKoD,SAASrD,SAAS,GAC9BsD,UAAUC,aAAAA,QAAIC,KAAKN,WAAW;AAAA,IAACO,SAAS,CAACL,IAAI;AAAA,EAAE,CAAA,EAAEM,KAAKC,sBAAKC,YAAY;AAE7ElC,YAAUlC,OAAOkC,QAAQ,4BAA4B,EAAEC,MAAM;AACzD,MAAA;AACI,UAAA;AAAA,MAACkC;AAAAA,IAAQ,IAAI,MAAMC,QAAAA,iBAAiB;AAAA,MACxClD;AAAAA,MACAmD,eAAenC,gBAAgBoC;AAAAA,MAC/BC,SAASzD;AAAAA,MACTF;AAAAA,MACAgD;AAAAA,IAAAA,CACD;AAEON,YAAAA,QAAAA,GAGRxD,OAAOiC,MAAM;AAAA,8BAAiClC,MAAM2E,KAAKL,QAAQ,CAAC,EAAE,GAE/DnD,qBACHlB,OAAOiC,MAAM;AAAA,MAASlC,MAAM2E,KAAK,gBAAgBtC,gBAAgBE,OAAO,GAAG,CAAC,EAAE,GAC9EtC,OAAOiC,MAAM,sEAAsE,GACnFjC,OAAOiC,MAAM,iDAAiD;AAAA,WAEzDO,KAAK;AACZN,UAAAA,QAAQuB,KAAK,GACbd,QAAM,MAAA,0BAA0BH,GAAG,GAC7BA;AAAAA,EAAAA;AAEV;;"}
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ async function fetchSchemaAction(args, context) {
3
+ const {
4
+ apiClient,
5
+ output
6
+ } = context, flags = args.extOptions, schemaId = flags["schema-id"], dataset = flags.dataset, spinner = output.spinner({}).start("Fetching schema"), client = apiClient({
7
+ requireUser: !0,
8
+ requireProject: !0
9
+ }).withConfig({
10
+ apiVersion: "v2024-08-01"
11
+ }), projectId = client.config().projectId, schema = await client.withConfig({
12
+ dataset,
13
+ projectId
14
+ }).fetch(`*[_type == "sanity.workspace.schema" && _id == "${schemaId}"]`);
15
+ spinner.succeed("Schema fetched"), output.success(JSON.stringify(schema, null, 2));
16
+ }
17
+ exports.default = fetchSchemaAction;
18
+ //# sourceMappingURL=fetchSchemaAction.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fetchSchemaAction.js","sources":["../../src/_internal/cli/actions/schema/fetchSchemaAction.ts"],"sourcesContent":["import {type CliCommandArguments, type CliCommandContext} from '@sanity/cli'\n\nimport {type ManifestSchemaType} from '../../../manifest/manifestTypes'\n\nexport interface FetchSchemaFlags {\n 'schema-id': string\n 'dataset': string\n}\n\nexport default async function fetchSchemaAction(\n args: CliCommandArguments<FetchSchemaFlags>,\n context: CliCommandContext,\n): Promise<void> {\n const {apiClient, output} = context\n const flags = args.extOptions\n const schemaId = flags['schema-id']\n const dataset = flags.dataset\n const spinner = output.spinner({}).start('Fetching schema')\n const client = apiClient({\n requireUser: true,\n requireProject: true,\n }).withConfig({apiVersion: 'v2024-08-01'})\n\n const projectId = client.config().projectId\n\n const schema = await client\n .withConfig({\n dataset: dataset,\n projectId: projectId,\n })\n .fetch<ManifestSchemaType>(`*[_type == \"sanity.workspace.schema\" && _id == \"${schemaId}\"]`)\n\n spinner.succeed('Schema fetched')\n // print schema as json\n output.success(JSON.stringify(schema, null, 2))\n}\n"],"names":["fetchSchemaAction","args","context","apiClient","output","flags","extOptions","schemaId","dataset","spinner","start","client","requireUser","requireProject","withConfig","apiVersion","projectId","config","schema","fetch","succeed","success","JSON","stringify"],"mappings":";AAS8BA,eAAAA,kBAC5BC,MACAC,SACe;AACT,QAAA;AAAA,IAACC;AAAAA,IAAWC;AAAAA,EAAAA,IAAUF,SACtBG,QAAQJ,KAAKK,YACbC,WAAWF,MAAM,WAAW,GAC5BG,UAAUH,MAAMG,SAChBC,UAAUL,OAAOK,QAAQ,CAAE,CAAA,EAAEC,MAAM,iBAAiB,GACpDC,SAASR,UAAU;AAAA,IACvBS,aAAa;AAAA,IACbC,gBAAgB;AAAA,EACjB,CAAA,EAAEC,WAAW;AAAA,IAACC,YAAY;AAAA,EAAA,CAAc,GAEnCC,YAAYL,OAAOM,OAAAA,EAASD,WAE5BE,SAAS,MAAMP,OAClBG,WAAW;AAAA,IACVN;AAAAA,IACAQ;AAAAA,EACD,CAAA,EACAG,MAA0B,mDAAmDZ,QAAQ,IAAI;AAEpFa,UAAAA,QAAQ,gBAAgB,GAEhChB,OAAOiB,QAAQC,KAAKC,UAAUL,QAAQ,MAAM,CAAC,CAAC;AAChD;;"}
@@ -144,10 +144,6 @@ ${autoGeneratedWarning}
144
144
  -->
145
145
  <head`);
146
146
  }
147
- function decorateIndexWithBridgeScript(template) {
148
- return template.replace("</head>", `<script src="https://core.sanity-cdn.com/bridge.js" async type="module"><\/script>
149
- </head>`);
150
- }
151
147
  function getPossibleDocumentComponentLocations(studioRootPath) {
152
148
  return [path__default.default.join(studioRootPath, "_document.js"), path__default.default.join(studioRootPath, "_document.tsx")];
153
149
  }
@@ -577,14 +573,14 @@ async function writeSanityRuntime({
577
573
  });
578
574
  async function renderAndWriteDocument() {
579
575
  debug("Rendering document template");
580
- const indexHtml = decorateIndexWithBridgeScript(decorateIndexWithAutoGeneratedWarning(await renderDocument({
576
+ const indexHtml = decorateIndexWithAutoGeneratedWarning(await renderDocument({
581
577
  studioRootPath: cwd,
582
578
  monorepo,
583
579
  props: {
584
580
  entryPath: `/${path__default.default.relative(cwd, path__default.default.join(runtimeDir, "app.js"))}`,
585
581
  basePath: basePath || "/"
586
582
  }
587
- })));
583
+ }));
588
584
  debug("Writing index.html to runtime directory"), await fs__default$1.default.writeFile(path__default.default.join(runtimeDir, "index.html"), indexHtml);
589
585
  }
590
586
  watch && chokidar__default.default.watch(getPossibleDocumentComponentLocations(cwd)).on("all", () => renderAndWriteDocument()), await renderAndWriteDocument(), debug("Writing app.js to runtime directory");
@@ -1 +1 @@
1
- {"version":3,"file":"runtime.js","sources":["../../src/_internal/cli/server/debug.ts","../../src/_internal/cli/server/createExternalFromImportMap.ts","../../src/_internal/cli/server/getBrowserAliases.ts","../../src/_internal/cli/server/helpers.ts","../../src/_internal/cli/server/sanityMonorepo.ts","../../src/_internal/cli/server/constants.ts","../../src/_internal/cli/server/renderDocument.tsx","../../src/_internal/cli/server/vite/plugin-sanity-build-entries.ts","../../src/_internal/cli/server/webManifest.ts","../../src/_internal/cli/server/vite/plugin-sanity-favicons.ts","../../src/_internal/cli/server/vite/plugin-sanity-runtime-rewrite.ts","../../src/_internal/cli/server/getViteConfig.ts","../../src/_internal/cli/server/getEntryModule.ts","../../src/_internal/cli/server/sanityConfig.ts","../../src/_internal/cli/server/runtime.ts"],"sourcesContent":["import debugIt from 'debug'\n\nexport const debug = debugIt('sanity:server')\n","import {escapeRegExp} from 'lodash'\n\ntype ImportMap = {imports?: Record<string, string>}\n\n/**\n * Generates a Rollup `external` configuration array based on the provided\n * import map. We derive externals from the import map because this ensures that\n * modules listed in the import map are not bundled into the Rollup output so\n * the browser can load these bare specifiers according to the import map.\n */\nexport function createExternalFromImportMap({imports = {}}: ImportMap = {}): (string | RegExp)[] {\n return Object.keys(imports).map((specifier) =>\n specifier.endsWith('/') ? new RegExp(`^${escapeRegExp(specifier)}.+`) : specifier,\n )\n}\n","import path from 'node:path'\n\nimport {escapeRegExp} from 'lodash'\nimport resolve from 'resolve.exports'\nimport {type Alias} from 'vite'\n\n/**\n * The following are the specifiers that are expected/allowed to be used within\n * a built Sanity studio in the browser. These are used in combination with\n * `resolve.exports` to determine the final entry point locations for each allowed specifier.\n *\n * There is also a corresponding test for this file that expects these to be\n * included in the `sanity` package.json. That test is meant to keep this list\n * in sync in the event we add another package subpath.\n *\n * @internal\n */\nexport const browserCompatibleSanityPackageSpecifiers = [\n 'sanity',\n 'sanity/_createContext',\n 'sanity/_singletons',\n 'sanity/desk',\n 'sanity/presentation',\n 'sanity/router',\n 'sanity/structure',\n 'sanity/package.json',\n]\n\n/**\n * These conditions should align with the conditions present in the\n * `package.json` of the `'sanity'` module. they are given to `resolve.exports`\n * in order to determine the correct entrypoint for the browser-compatible\n * package specifiers listed above.\n */\nconst conditions = ['import', 'browser', 'default']\n\n// locate the entry points for each subpath the Sanity module exports\nexport function getSanityPkgExportAliases(sanityPkgPath: string) {\n // Load the package.json of the Sanity package\n // eslint-disable-next-line import/no-dynamic-require\n const pkg = require(sanityPkgPath)\n const dirname = path.dirname(sanityPkgPath)\n\n // Resolve the entry points for each allowed specifier\n const unifiedSanityAliases = browserCompatibleSanityPackageSpecifiers.reduce<Alias[]>(\n (acc, next) => {\n // Resolve the export path for the specifier using resolve.exports\n const dest = resolve.exports(pkg, next, {browser: true, conditions})?.[0]\n if (!dest) return acc\n\n // Map the specifier to its resolved path\n acc.push({\n find: new RegExp(`^${escapeRegExp(next)}$`),\n replacement: path.resolve(dirname, dest),\n })\n return acc\n },\n [],\n )\n\n // Return the aliases configuration for external projects\n return unifiedSanityAliases\n}\n","import path from 'node:path'\n\nimport readPkgUp from 'read-pkg-up'\nimport resolveFrom from 'resolve-from'\n\n/**\n * Given a module name such as \"styled-components\", will resolve the _module path_,\n * eg if require.resolve(`styled-components`) resolves to:\n * `/some/node_modules/styled-components/lib/cjs/styled.js`\n * this function will instead return\n * `/some/node_modules/styled-components`\n *\n * This is done in order for aliases to be pointing to the right module in terms of\n * _file-system location_, without pointing to a specific commonjs/browser/module variant\n *\n * @internal\n */\nexport async function getModulePath(mod: string, fromDir: string): Promise<string> {\n const modulePath = resolveFrom(fromDir, mod)\n const pkg = await readPkgUp({cwd: path.dirname(modulePath)})\n\n return pkg ? path.dirname(pkg.path) : modulePath\n}\n\n/**\n * @internal\n */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === 'object' && !Array.isArray(value)\n}\n\n/**\n * Ensures that the given path both starts and ends with a single slash\n *\n * @internal\n */\nexport function normalizeBasePath(pathName: string): string {\n return `/${pathName}/`.replace(/^\\/+/, '/').replace(/\\/+$/, '/')\n}\n","import path from 'node:path'\n\nimport readPkgUp from 'read-pkg-up'\n\n/**\n * @internal\n */\nexport interface SanityMonorepo {\n path: string\n}\n\nexport async function getMonorepoAliases(monorepoPath: string) {\n const {default: aliases} = await import('@repo/dev-aliases')\n return Object.fromEntries(\n Object.entries(aliases).map(([pkgName, pkgPath]) => {\n return [pkgName, path.resolve(monorepoPath, path.join('packages', pkgPath))]\n }),\n )\n}\n\n/**\n * Load information about the `sanity-io/sanity` monorepo (if applicable)\n *\n * @internal\n */\nexport async function loadSanityMonorepo(cwd: string): Promise<SanityMonorepo | undefined> {\n let p = cwd\n\n while (p !== '/') {\n const readResult = await readPkgUp({cwd: p})\n\n if (!readResult) {\n return undefined\n }\n\n if (readResult.packageJson.isSanityMonorepo) {\n return {path: path.dirname(readResult.path)}\n }\n\n p = path.dirname(path.dirname(readResult.path))\n }\n\n return undefined\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 */\nexport const 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 importMapEl.textContent = JSON.stringify({\n imports: Object.fromEntries(\n Object.entries(imports).map(([specifier, path]) => {\n try {\n const url = new URL(path);\n if (/^sanity-cdn\\\\.[a-zA-Z]+$/.test(url.hostname)) {\n url.pathname = url.pathname.replace(/\\\\/t\\\\d+/, newTimestamp);\n }\n return [specifier, url.toString()];\n } catch {\n return [specifier, path];\n }\n })\n ),\n ...rest,\n });\n document.head.appendChild(importMapEl);\n</script>`\n","/**\n * Looks for and imports (in preferred order):\n * - src/_document.js\n * - src/_document.tsx\n *\n * Then renders using ReactDOM to a string, which is sent back to the parent\n * process over the worker `postMessage` channel.\n */\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport {isMainThread, parentPort, Worker, workerData} from 'node:worker_threads'\n\nimport chalk from 'chalk'\nimport importFresh from 'import-fresh'\nimport {parse as parseHtml} from 'node-html-parser'\nimport {renderToStaticMarkup} from 'react-dom/server'\n\nimport {TIMESTAMPED_IMPORTMAP_INJECTOR_SCRIPT} from './constants'\nimport {debug as serverDebug} from './debug'\nimport {getMonorepoAliases, type SanityMonorepo} from './sanityMonorepo'\n\nconst debug = serverDebug.extend('renderDocument')\n\n// Don't use threads in the jest world\n// eslint-disable-next-line no-process-env, turbo/no-undeclared-env-vars\nconst useThreads = typeof process.env.JEST_WORKER_ID === 'undefined'\nconst hasWarnedAbout = new Set<string>()\n\nconst defaultProps = {\n entryPath: './.sanity/runtime/app.js',\n}\n\nconst autoGeneratedWarning = `\nThis file is auto-generated from \"sanity dev\".\nModifications to this file are automatically discarded.\n`.trim()\n\ninterface DocumentProps {\n basePath: string\n entryPath?: string\n css?: string[]\n}\n\ninterface RenderDocumentOptions {\n monorepo?: SanityMonorepo\n studioRootPath: string\n props?: DocumentProps\n importMap?: {\n imports?: Record<string, string>\n }\n}\n\nexport function renderDocument(options: RenderDocumentOptions): Promise<string> {\n return new Promise((resolve, reject) => {\n if (!useThreads) {\n resolve(getDocumentHtml(options.studioRootPath, options.props, options.importMap))\n return\n }\n\n debug('Starting worker thread for %s', __filename)\n const worker = new Worker(__filename, {\n execArgv: __DEV__ ? ['-r', `${__dirname}/esbuild-register.js`] : undefined,\n workerData: {...options, dev: __DEV__, shouldWarn: true},\n // eslint-disable-next-line no-process-env\n env: process.env,\n })\n\n worker.on('message', (msg) => {\n if (msg.type === 'warning') {\n if (hasWarnedAbout.has(msg.warnKey)) {\n return\n }\n\n if (Array.isArray(msg.message)) {\n msg.message.forEach((warning: string) =>\n console.warn(`${chalk.yellow('[warn]')} ${warning}`),\n )\n } else {\n console.warn(`${chalk.yellow('[warn]')} ${msg.message}`)\n }\n\n hasWarnedAbout.add(msg.warnKey)\n return\n }\n\n if (msg.type === 'error') {\n debug('Error from worker: %s', msg.error || 'Unknown error')\n reject(new Error(msg.error || 'Document rendering worker stopped with an unknown error'))\n return\n }\n\n if (msg.type === 'result') {\n debug('Document HTML rendered, %d bytes', msg.html.length)\n resolve(msg.html)\n }\n })\n worker.on('error', (err) => {\n debug('Worker errored: %s', err.message)\n reject(err)\n })\n worker.on('exit', (code) => {\n if (code !== 0) {\n debug('Worker stopped with code %d', code)\n reject(new Error(`Document rendering worker stopped with exit code ${code}`))\n }\n })\n })\n}\n\nexport function decorateIndexWithAutoGeneratedWarning(template: string): string {\n return template.replace(/<head/, `\\n<!--\\n${autoGeneratedWarning}\\n-->\\n<head`)\n}\n\n/**\n * Decorates the given HTML template with a script\n * tag that loads the bridge component to communicate\n * with core-ui.\n */\nexport function decorateIndexWithBridgeScript(template: string): string {\n return template.replace(\n '</head>',\n '<script src=\"https://core.sanity-cdn.com/bridge.js\" async type=\"module\"></script>\\n</head>',\n )\n}\n\nexport function getPossibleDocumentComponentLocations(studioRootPath: string): string[] {\n return [path.join(studioRootPath, '_document.js'), path.join(studioRootPath, '_document.tsx')]\n}\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 */\nexport function _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\nif (!isMainThread && parentPort) {\n renderDocumentFromWorkerData()\n}\n\nfunction renderDocumentFromWorkerData() {\n if (!parentPort || !workerData) {\n throw new Error('Must be used as a Worker with a valid options object in worker data')\n }\n\n const {monorepo, studioRootPath, props, importMap}: RenderDocumentOptions = workerData || {}\n\n if (workerData?.dev) {\n // Define `__DEV__` in the worker thread as well\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ;(global as any).__DEV__ = true\n }\n\n if (typeof studioRootPath !== 'string') {\n parentPort.postMessage({type: 'error', message: 'Missing/invalid `studioRootPath` option'})\n return\n }\n\n if (props && typeof props !== 'object') {\n parentPort.postMessage({type: 'error', message: '`props` must be an object if provided'})\n return\n }\n\n // Require hook #1\n // Alias monorepo modules\n debug('Registering potential aliases')\n if (monorepo) {\n require('module-alias').addAliases(getMonorepoAliases(monorepo.path))\n }\n\n // Require hook #2\n // Use `esbuild` to allow JSX/TypeScript and modern JS features\n debug('Registering esbuild for node %s', process.version)\n const {unregister} = __DEV__\n ? {unregister: () => undefined}\n : require('esbuild-register/dist/node').register({\n target: `node${process.version.slice(1)}`,\n supported: {'dynamic-import': true},\n jsx: 'automatic',\n extensions: ['.jsx', '.ts', '.tsx', '.mjs'],\n })\n\n // Require hook #3\n // Same as above, but we don't want to enforce a .jsx extension for anything with JSX\n debug('Registering esbuild for .js files using jsx loader')\n const {unregister: unregisterJs} = __DEV__\n ? {unregister: () => undefined}\n : require('esbuild-register/dist/node').register({\n target: `node${process.version.slice(1)}`,\n supported: {'dynamic-import': true},\n extensions: ['.js'],\n jsx: 'automatic',\n loader: 'jsx',\n })\n\n const html = getDocumentHtml(studioRootPath, props, importMap)\n\n parentPort.postMessage({type: 'result', html})\n\n // Be polite and clean up after esbuild-register\n unregister()\n unregisterJs()\n}\n\nfunction getDocumentHtml(\n studioRootPath: string,\n props?: DocumentProps,\n importMap?: {imports?: Record<string, string>},\n): string {\n const Document = getDocumentComponent(studioRootPath)\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 debug('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\n/**\n * @internal\n */\nexport function addTimestampedImportMapScriptToHtml(\n html: string,\n importMap?: {imports?: Record<string, 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.appendChild(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 headEl.insertAdjacentHTML(\n 'beforeend',\n `<script type=\"application/json\" id=\"__imports\">${JSON.stringify(importMap)}</script>`,\n )\n headEl.insertAdjacentHTML('beforeend', TIMESTAMPED_IMPORTMAP_INJECTOR_SCRIPT)\n return root.outerHTML\n}\n\nfunction getDocumentComponent(studioRootPath: string) {\n debug('Loading default document component from `sanity` module')\n const {DefaultDocument} = __DEV__\n ? require('../../../core/components/DefaultDocument')\n : require('sanity')\n\n debug('Attempting to load user-defined document component from %s', studioRootPath)\n const userDefined = tryLoadDocumentComponent(studioRootPath)\n\n if (!userDefined) {\n debug('Using default document component')\n return DefaultDocument\n }\n\n debug('Found user defined document component at %s', userDefined.path)\n\n const DocumentComp = userDefined.component.default || userDefined.component // CommonJS\n if (typeof DocumentComp === 'function') {\n debug('User defined document component is a function, assuming valid')\n return DocumentComp\n }\n\n debug('User defined document component did not have a default export')\n const userExports = Object.keys(userDefined.component).join(', ') || 'None'\n const relativePath = path.relative(process.cwd(), userDefined.path)\n const typeHint =\n typeof userDefined.component.default === 'undefined'\n ? ''\n : ` (type was ${typeof userDefined.component.default})`\n\n const warnKey = `${relativePath}/${userDefined.modified}`\n\n parentPort?.postMessage({\n type: 'warning',\n message: [\n `${relativePath} did not have a default export that is a React component${typeHint}`,\n `Named exports/properties found: ${userExports}`.trim(),\n `Using default document component from \"sanity\".`,\n ],\n warnKey,\n })\n\n return DefaultDocument\n}\n\nfunction tryLoadDocumentComponent(studioRootPath: string) {\n const locations = getPossibleDocumentComponentLocations(studioRootPath)\n\n for (const componentPath of locations) {\n debug('Trying to load document component from %s', componentPath)\n try {\n return {\n // eslint-disable-next-line import/no-dynamic-require\n component: importFresh<any>(componentPath),\n path: componentPath,\n // eslint-disable-next-line no-sync\n modified: Math.floor(fs.statSync(componentPath)?.mtimeMs),\n }\n } catch (err) {\n // Allow \"not found\" errors\n if (err.code !== 'MODULE_NOT_FOUND') {\n debug('Failed to load document component: %s', err.message)\n throw err\n }\n\n debug('Document component not found at %s', componentPath)\n }\n }\n\n return null\n}\n","import {type ChunkMetadata, type Plugin} from 'vite'\n\nimport {renderDocument} from '../renderDocument'\nimport {type SanityMonorepo} from '../sanityMonorepo'\n\ninterface ViteOutputBundle {\n [fileName: string]: ViteRenderedChunk | ViteRenderedAsset\n}\n\ninterface ViteRenderedAsset {\n type: 'asset'\n}\n\ninterface ViteRenderedChunk {\n type: 'chunk'\n name: string\n fileName: string\n facadeModuleId: string | null\n code: string\n imports: string[]\n viteMetadata: ChunkMetadata\n}\n\nconst entryChunkId = '.sanity/runtime/app.js'\n\nexport function sanityBuildEntries(options: {\n cwd: string\n monorepo: SanityMonorepo | undefined\n basePath: string\n importMap?: {imports?: Record<string, string>}\n}): Plugin {\n const {cwd, monorepo, basePath, importMap} = options\n\n return {\n name: 'sanity/server/build-entries',\n apply: 'build',\n\n buildStart() {\n this.emitFile({\n type: 'chunk',\n id: entryChunkId,\n name: 'sanity',\n })\n },\n\n async generateBundle(_options, outputBundle) {\n const bundle = outputBundle as unknown as ViteOutputBundle\n const entryFile = Object.values(bundle).find(\n (file) =>\n file.type === 'chunk' &&\n file.name === 'sanity' &&\n file.facadeModuleId?.endsWith(entryChunkId),\n )\n\n if (!entryFile) {\n throw new Error(`Failed to find entry file in bundle (${entryChunkId})`)\n }\n\n if (entryFile.type !== 'chunk') {\n throw new Error('Entry file is not a chunk')\n }\n\n const entryFileName = entryFile.fileName\n const entryPath = [basePath.replace(/\\/+$/, ''), entryFileName].join('/')\n\n let css: string[] = []\n if (entryFile.viteMetadata?.importedCss) {\n // Check all the top-level imports of the entryPoint to see if they have\n // static CSS assets that need loading\n css = [...entryFile.viteMetadata.importedCss]\n for (const key of entryFile.imports) {\n // Traverse all CSS assets that isn't loaded by the runtime and\n // need <link> tags in the HTML template\n const entry = bundle[key]\n const importedCss =\n entry && entry.type === 'chunk' ? entry.viteMetadata.importedCss : undefined\n\n if (importedCss) {\n css.push(...importedCss)\n }\n }\n }\n\n this.emitFile({\n type: 'asset',\n fileName: 'index.html',\n source: await renderDocument({\n monorepo,\n studioRootPath: cwd,\n importMap,\n props: {\n basePath,\n entryPath,\n css,\n },\n }),\n })\n },\n }\n}\n","export interface WebManifest {\n icons: {\n src: string\n type: string\n sizes: string\n }[]\n}\n\nexport function generateWebManifest(basePath: string): WebManifest {\n return {\n icons: [\n {src: `${basePath}/favicon-192.png`, type: 'image/png', sizes: '192x192'},\n {src: `${basePath}/favicon-512.png`, type: 'image/png', sizes: '512x512'},\n ],\n }\n}\n","import fs from 'node:fs/promises'\nimport path from 'node:path'\n\nimport {type Plugin} from 'vite'\n\nimport {generateWebManifest} from '../webManifest'\n\nconst mimeTypes: Record<string, string | undefined> = {\n '.ico': 'image/x-icon',\n '.svg': 'image/svg+xml',\n '.png': 'image/png',\n}\n\n/**\n * Fallback favicons plugin for Sanity.\n *\n * If a favicon is not found in the static folder, this plugin will serve the default\n * Sanity favicons from the npm bundle. If a custom `favicon.ico` is found in the static\n * folder, it will also be served for a root `/favicon.ico` request.\n *\n * @param options - Options for the plugin\n * @returns A Vite plugin\n * @internal\n */\nexport function sanityFaviconsPlugin({\n defaultFaviconsPath,\n customFaviconsPath,\n staticUrlPath,\n}: {\n defaultFaviconsPath: string\n customFaviconsPath: string\n staticUrlPath: string\n}): Plugin {\n const cache: {favicons?: string[]} = {}\n\n async function getFavicons(): Promise<string[]> {\n if (cache.favicons) {\n return cache.favicons\n }\n\n cache.favicons = await fs.readdir(defaultFaviconsPath)\n return cache.favicons\n }\n\n async function hasCustomFavicon(fileName: string): Promise<boolean> {\n try {\n await fs.access(path.join(customFaviconsPath, fileName))\n return true\n } catch (err) {\n return false\n }\n }\n\n return {\n name: 'sanity/server/sanity-favicons',\n apply: 'serve',\n configureServer(viteDevServer) {\n const webManifest = JSON.stringify(generateWebManifest(staticUrlPath), null, 2)\n const webManifestPath = `${staticUrlPath}/manifest.webmanifest`\n\n viteDevServer.middlewares.use(async (req, res, next) => {\n if (req.url?.endsWith(webManifestPath)) {\n res.writeHead(200, 'OK', {'content-type': 'application/manifest+json'})\n res.write(webManifest)\n res.end()\n return\n }\n\n const parsedUrl =\n ((req as any)._parsedUrl as URL) || new URL(req.url || '/', 'http://localhost:3333')\n\n const pathName = parsedUrl.pathname || ''\n const fileName = path.basename(pathName || '')\n const icons = await getFavicons()\n const isIconRequest =\n pathName.startsWith('/favicon.ico') ||\n (icons.includes(fileName) && pathName.includes(staticUrlPath))\n\n if (!isIconRequest) {\n next()\n return\n }\n\n const faviconPath = (await hasCustomFavicon(fileName))\n ? path.join(customFaviconsPath, fileName)\n : path.join(defaultFaviconsPath, fileName)\n\n const mimeType = mimeTypes[path.extname(fileName)] || 'application/octet-stream'\n res.writeHead(200, 'OK', {'content-type': mimeType})\n res.write(await fs.readFile(faviconPath))\n res.end()\n })\n },\n }\n}\n","import {type Plugin} from 'vite'\n\nexport function sanityRuntimeRewritePlugin(): Plugin {\n return {\n name: 'sanity/server/sanity-runtime-rewrite',\n apply: 'serve',\n configureServer(viteDevServer) {\n return () => {\n viteDevServer.middlewares.use((req, res, next) => {\n if (req.url === '/index.html') {\n req.url = '/.sanity/runtime/index.html'\n }\n\n next()\n })\n }\n },\n }\n}\n","import path from 'node:path'\n\nimport {type ReactCompilerConfig, type UserViteConfig} from '@sanity/cli'\nimport debug from 'debug'\nimport readPkgUp from 'read-pkg-up'\nimport {type ConfigEnv, type InlineConfig, type Rollup} from 'vite'\n\nimport {createExternalFromImportMap} from './createExternalFromImportMap'\nimport {getSanityPkgExportAliases} from './getBrowserAliases'\nimport {getStudioEnvironmentVariables} from './getStudioEnvironmentVariables'\nimport {normalizeBasePath} from './helpers'\nimport {getMonorepoAliases, loadSanityMonorepo} from './sanityMonorepo'\nimport {sanityBuildEntries} from './vite/plugin-sanity-build-entries'\nimport {sanityFaviconsPlugin} from './vite/plugin-sanity-favicons'\nimport {sanityRuntimeRewritePlugin} from './vite/plugin-sanity-runtime-rewrite'\n\nexport interface ViteOptions {\n /**\n * Root path of the studio/sanity app\n */\n cwd: 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 /**\n * Output directory (eg where to place the built files, if any)\n */\n outputDir?: string\n\n /**\n * Whether or not to enable source maps\n */\n sourceMap?: boolean\n\n /**\n * Whether or not to minify the output (only used in `mode: 'production'`)\n */\n minify?: boolean\n\n /**\n * HTTP development server configuration\n */\n server?: {port?: number; host?: string}\n\n /**\n * Mode to run vite in - eg development or production\n */\n mode: 'development' | 'production'\n\n importMap?: {imports?: Record<string, string>}\n reactCompiler: ReactCompilerConfig | undefined\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 cwd,\n mode,\n outputDir,\n // default to `true` when `mode=development`\n sourceMap = options.mode === 'development',\n server,\n minify,\n basePath: rawBasePath = '/',\n importMap,\n reactCompiler,\n } = options\n\n const monorepo = await loadSanityMonorepo(cwd)\n const basePath = normalizeBasePath(rawBasePath)\n\n const sanityPkgPath = (await readPkgUp({cwd: __dirname}))?.path\n if (!sanityPkgPath) {\n throw new Error('Unable to resolve `sanity` module root')\n }\n\n const customFaviconsPath = path.join(cwd, 'static')\n const defaultFaviconsPath = path.join(path.dirname(sanityPkgPath), 'static', 'favicons')\n const staticPath = `${basePath}static`\n\n const {default: viteReact} = await import('@vitejs/plugin-react')\n const viteConfig: InlineConfig = {\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 root: cwd,\n base: basePath,\n build: {\n outDir: outputDir || path.resolve(cwd, 'dist'),\n sourcemap: sourceMap,\n },\n server: {\n host: server?.host,\n port: server?.port || 3333,\n strictPort: true,\n },\n configFile: false,\n mode,\n plugins: [\n viteReact(\n reactCompiler ? {babel: {plugins: [['babel-plugin-react-compiler', reactCompiler]]}} : {},\n ),\n sanityFaviconsPlugin({defaultFaviconsPath, customFaviconsPath, staticUrlPath: staticPath}),\n sanityRuntimeRewritePlugin(),\n sanityBuildEntries({basePath, cwd, monorepo, importMap}),\n ],\n envPrefix: 'SANITY_STUDIO_',\n logLevel: mode === 'production' ? 'silent' : 'info',\n resolve: {\n alias: monorepo?.path\n ? await getMonorepoAliases(monorepo.path)\n : getSanityPkgExportAliases(sanityPkgPath),\n dedupe: ['styled-components'],\n },\n define: {\n // eslint-disable-next-line no-process-env\n '__SANITY_STAGING__': process.env.SANITY_INTERNAL_ENV === 'staging',\n 'process.env.MODE': JSON.stringify(mode),\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 ...getStudioEnvironmentVariables({prefix: 'process.env.', jsonEncode: true}),\n },\n }\n\n if (mode === 'production') {\n viteConfig.build = {\n ...viteConfig.build,\n\n assetsDir: 'static',\n minify: minify ? 'esbuild' : false,\n emptyOutDir: false, // Rely on CLI to do this\n\n rollupOptions: {\n onwarn: onRollupWarn,\n external: createExternalFromImportMap(importMap),\n input: {\n sanity: path.join(cwd, '.sanity', 'runtime', 'app.js'),\n },\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/'))) 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 Error(\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 const {mergeConfig} = await import('vite')\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 const {mergeConfig} = await import('vite')\n config = mergeConfig(config, userConfig)\n }\n\n return config\n}\n","const entryModule = `\n// This file is auto-generated on 'sanity dev'\n// Modifications to this file is automatically discarded\nimport {renderStudio} from \"sanity\"\nimport studioConfig from %STUDIO_CONFIG_LOCATION%\n\nrenderStudio(\n document.getElementById(\"sanity\"),\n studioConfig,\n {reactStrictMode: %STUDIO_REACT_STRICT_MODE%, basePath: %STUDIO_BASE_PATH%}\n)\n`\n\nconst noConfigEntryModule = `\n// This file is auto-generated on 'sanity dev'\n// Modifications to this file is automatically discarded\nimport {renderStudio} from \"sanity\"\n\nconst studioConfig = {missingConfigFile: true}\n\nrenderStudio(\n document.getElementById(\"sanity\"),\n studioConfig,\n {reactStrictMode: %STUDIO_REACT_STRICT_MODE%, basePath: %STUDIO_BASE_PATH%}\n)\n`\n\nexport function getEntryModule(options: {\n reactStrictMode: boolean\n relativeConfigLocation: string | null\n basePath?: string\n}): string {\n const {reactStrictMode, relativeConfigLocation, basePath} = options\n const sourceModule = relativeConfigLocation ? entryModule : noConfigEntryModule\n\n return sourceModule\n .replace(/%STUDIO_REACT_STRICT_MODE%/, JSON.stringify(Boolean(reactStrictMode)))\n .replace(/%STUDIO_CONFIG_LOCATION%/, JSON.stringify(relativeConfigLocation))\n .replace(/%STUDIO_BASE_PATH%/, JSON.stringify(basePath || '/'))\n}\n","import fs from 'node:fs/promises'\nimport path from 'node:path'\n\nimport {debug as serverDebug} from './debug'\n\nconst debug = serverDebug.extend('config')\n\n/**\n * Resolves the path to the studio configuration file with the following extensions,\n * in preferred order: '.mjs', '.js', '.ts', '.jsx', '.tsx' (aligns with vite)\n *\n * Falls back to the default studio configuration exported by `sanity` if none is found\n *\n * @internal\n */\nexport async function getSanityStudioConfigPath(studioRootPath: string): Promise<string | null> {\n const configPaths = [\n path.join(studioRootPath, 'sanity.config.mjs'),\n path.join(studioRootPath, 'sanity.config.js'),\n path.join(studioRootPath, 'sanity.config.ts'),\n path.join(studioRootPath, 'sanity.config.jsx'),\n path.join(studioRootPath, 'sanity.config.tsx'),\n ]\n\n debug('Looking for configuration file in %d possible locations', configPaths.length)\n const configs = await Promise.all(\n configPaths.map(async (configPath) => ({\n path: configPath,\n exists: await fileExists(configPath),\n })),\n )\n\n const availableConfigs = configs.filter((config) => config.exists)\n debug('Found %d available configuration files', availableConfigs.length)\n\n // No config file exists?\n if (availableConfigs.length === 0) {\n console.warn('No `sanity.config.js`/`sanity.config.ts` found - using default studio config')\n return null\n }\n\n if (availableConfigs.length > 1) {\n console.warn('Found multiple potential studio configs:')\n availableConfigs.forEach((config) => console.warn(` - ${config.path}`))\n console.warn(`Using ${availableConfigs[0].path}`)\n }\n\n return availableConfigs[0].path\n}\n\n/**\n * Asynchronously checks if a file exists. This is prone to race conditions,\n * as the file can exist/not exist by the time this resolves, but in this\n * case this is an acceptable trade-off. Best effort, and all that.\n */\nfunction fileExists(filePath: string): Promise<boolean> {\n return fs.stat(filePath).then(\n () => true,\n () => false,\n )\n}\n","import fs from 'node:fs/promises'\nimport path from 'node:path'\n\nimport chokidar from 'chokidar'\n\nimport {debug as serverDebug} from './debug'\nimport {getEntryModule} from './getEntryModule'\nimport {\n decorateIndexWithAutoGeneratedWarning,\n decorateIndexWithBridgeScript,\n getPossibleDocumentComponentLocations,\n renderDocument,\n} from './renderDocument'\nimport {getSanityStudioConfigPath} from './sanityConfig'\nimport {loadSanityMonorepo} from './sanityMonorepo'\n\nconst debug = serverDebug.extend('runtime')\n\nexport interface RuntimeOptions {\n cwd: string\n reactStrictMode: boolean\n watch: boolean\n basePath?: string\n}\n\n/**\n * Generates the `.sanity/runtime` directory, and optionally watches for custom\n * document files, rebuilding when they change\n *\n * @param options - Current working directory (Sanity root dir), and whether or not to watch\n * @internal\n */\nexport async function writeSanityRuntime({\n cwd,\n reactStrictMode,\n watch,\n basePath,\n}: RuntimeOptions): Promise<void> {\n debug('Resolving Sanity monorepo information')\n const monorepo = await loadSanityMonorepo(cwd)\n const runtimeDir = path.join(cwd, '.sanity', 'runtime')\n\n debug('Making runtime directory')\n await fs.mkdir(runtimeDir, {recursive: true})\n\n async function renderAndWriteDocument() {\n debug('Rendering document template')\n const indexHtml = decorateIndexWithBridgeScript(\n decorateIndexWithAutoGeneratedWarning(\n await renderDocument({\n studioRootPath: cwd,\n monorepo,\n props: {\n entryPath: `/${path.relative(cwd, path.join(runtimeDir, 'app.js'))}`,\n basePath: basePath || '/',\n },\n }),\n ),\n )\n\n debug('Writing index.html to runtime directory')\n await fs.writeFile(path.join(runtimeDir, 'index.html'), indexHtml)\n }\n\n if (watch) {\n chokidar\n .watch(getPossibleDocumentComponentLocations(cwd))\n .on('all', () => renderAndWriteDocument())\n }\n\n await renderAndWriteDocument()\n\n debug('Writing app.js to runtime directory')\n const studioConfigPath = await getSanityStudioConfigPath(cwd)\n const relativeConfigLocation = studioConfigPath\n ? path.relative(runtimeDir, studioConfigPath)\n : null\n\n await fs.writeFile(\n path.join(runtimeDir, 'app.js'),\n getEntryModule({reactStrictMode, relativeConfigLocation, basePath}),\n )\n}\n"],"names":["debug","debugIt","createExternalFromImportMap","imports","Object","keys","map","specifier","endsWith","RegExp","escapeRegExp","browserCompatibleSanityPackageSpecifiers","conditions","getSanityPkgExportAliases","sanityPkgPath","pkg","require","dirname","path","reduce","acc","next","dest","resolve","exports","browser","push","find","replacement","normalizeBasePath","pathName","replace","getMonorepoAliases","monorepoPath","default","aliases","fromEntries","entries","pkgName","pkgPath","join","loadSanityMonorepo","cwd","p","readResult","readPkgUp","packageJson","isSanityMonorepo","TIMESTAMPED_IMPORTMAP_INJECTOR_SCRIPT","serverDebug","extend","useThreads","process","env","JEST_WORKER_ID","hasWarnedAbout","Set","defaultProps","entryPath","autoGeneratedWarning","trim","renderDocument","options","Promise","reject","getDocumentHtml","studioRootPath","props","importMap","__filename","worker","Worker","execArgv","undefined","workerData","dev","shouldWarn","on","msg","type","has","warnKey","Array","isArray","message","forEach","warning","console","warn","chalk","yellow","add","error","Error","html","length","err","code","decorateIndexWithAutoGeneratedWarning","template","decorateIndexWithBridgeScript","getPossibleDocumentComponentLocations","_prefixUrlWithBasePath","url","basePath","normalizedBasePath","startsWith","slice","isMainThread","parentPort","renderDocumentFromWorkerData","monorepo","global","__DEV__","postMessage","addAliases","version","unregister","register","target","supported","jsx","extensions","unregisterJs","loader","Document","getDocumentComponent","css","URL","toString","addTimestampedImportMapScriptToHtml","renderToStaticMarkup","root","parseHtml","htmlEl","querySelector","oldRoot","appendChild","headEl","insertAdjacentHTML","JSON","stringify","outerHTML","DefaultDocument","userDefined","tryLoadDocumentComponent","DocumentComp","component","userExports","relativePath","relative","typeHint","modified","locations","componentPath","importFresh","Math","floor","fs","statSync","mtimeMs","entryChunkId","sanityBuildEntries","name","apply","buildStart","emitFile","id","generateBundle","_options","outputBundle","bundle","entryFile","values","file","facadeModuleId","entryFileName","fileName","viteMetadata","importedCss","key","entry","source","generateWebManifest","icons","src","sizes","mimeTypes","sanityFaviconsPlugin","defaultFaviconsPath","customFaviconsPath","staticUrlPath","cache","getFavicons","favicons","readdir","hasCustomFavicon","access","configureServer","viteDevServer","webManifest","webManifestPath","middlewares","use","req","res","writeHead","write","end","_parsedUrl","pathname","basename","includes","faviconPath","mimeType","extname","readFile","sanityRuntimeRewritePlugin","getViteConfig","mode","outputDir","sourceMap","server","minify","rawBasePath","reactCompiler","__dirname","staticPath","viteReact","viteConfig","cacheDir","base","build","outDir","sourcemap","host","port","strictPort","configFile","plugins","babel","envPrefix","logLevel","alias","dedupe","define","SANITY_INTERNAL_ENV","getStudioEnvironmentVariables","prefix","jsonEncode","assetsDir","emptyOutDir","rollupOptions","onwarn","onRollupWarn","external","input","sanity","suppressUnusedImport","names","filter","n","ids","every","finalizeViteConfig","config","mergeConfig","extendViteConfigWithUserConfig","defaultConfig","userConfig","entryModule","noConfigEntryModule","getEntryModule","reactStrictMode","relativeConfigLocation","Boolean","getSanityStudioConfigPath","configPaths","availableConfigs","all","configPath","exists","fileExists","filePath","stat","then","writeSanityRuntime","watch","runtimeDir","mkdir","recursive","renderAndWriteDocument","indexHtml","writeFile","chokidar","studioConfigPath"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAEaA,MAAAA,UAAQC,uBAAQ,eAAe;ACQrC,SAASC,4BAA4B;AAAA,EAACC,UAAU,CAAA;AAAa,IAAI,IAAyB;AAC/F,SAAOC,OAAOC,KAAKF,OAAO,EAAEG,IAAKC,CAAAA,cAC/BA,UAAUC,SAAS,GAAG,IAAI,IAAIC,OAAO,IAAIC,sBAAAA,QAAaH,SAAS,CAAC,IAAI,IAAIA,SAC1E;AACF;ACGaI,MAAAA,2CAA2C,CACtD,UACA,yBACA,sBACA,eACA,uBACA,iBACA,oBACA,qBAAqB,GASjBC,aAAa,CA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AA,QACLT,WAAW,IAAIxC,cAAAA,QAAKoI,SAAS5G,KAAKxB,sBAAKsB,KAAKwP,YAAY,QAAQ,CAAC,CAAC;AAAA,QAClExL,UAAUA,YAAY;AAAA,MAAA;AAAA,IAEzB,CAAA,CACH,CACF;AAEM,UAAA,yCAAyC,GAC/C,MAAMsD,cAAAA,QAAGuI,UAAUnR,sBAAKsB,KAAKwP,YAAY,YAAY,GAAGI,SAAS;AAAA,EAAA;AAG/DL,WACFO,kBACGP,QAAAA,MAAM1L,sCAAsC3D,GAAG,CAAC,EAChDmC,GAAG,OAAO,MAAMsN,uBAAwB,CAAA,GAG7C,MAAMA,uBAAuB,GAE7BnS,MAAM,qCAAqC;AACrCuS,QAAAA,mBAAmB,MAAMnB,0BAA0B1O,GAAG,GACtDwO,yBAAyBqB,mBAC3BrR,cAAAA,QAAKoI,SAAS0I,YAAYO,gBAAgB,IAC1C;AAEJ,QAAMzI,cAAAA,QAAGuI,UACPnR,cAAAA,QAAKsB,KAAKwP,YAAY,QAAQ,GAC9BhB,eAAe;AAAA,IAACC;AAAAA,IAAiBC;AAAAA,IAAwB1K;AAAAA,EAAAA,CAAS,CACpE;AACF;;;;;;;;"}
1
+ {"version":3,"file":"runtime.js","sources":["../../src/_internal/cli/server/debug.ts","../../src/_internal/cli/server/createExternalFromImportMap.ts","../../src/_internal/cli/server/getBrowserAliases.ts","../../src/_internal/cli/server/helpers.ts","../../src/_internal/cli/server/sanityMonorepo.ts","../../src/_internal/cli/server/constants.ts","../../src/_internal/cli/server/renderDocument.tsx","../../src/_internal/cli/server/vite/plugin-sanity-build-entries.ts","../../src/_internal/cli/server/webManifest.ts","../../src/_internal/cli/server/vite/plugin-sanity-favicons.ts","../../src/_internal/cli/server/vite/plugin-sanity-runtime-rewrite.ts","../../src/_internal/cli/server/getViteConfig.ts","../../src/_internal/cli/server/getEntryModule.ts","../../src/_internal/cli/server/sanityConfig.ts","../../src/_internal/cli/server/runtime.ts"],"sourcesContent":["import debugIt from 'debug'\n\nexport const debug = debugIt('sanity:server')\n","import {escapeRegExp} from 'lodash'\n\ntype ImportMap = {imports?: Record<string, string>}\n\n/**\n * Generates a Rollup `external` configuration array based on the provided\n * import map. We derive externals from the import map because this ensures that\n * modules listed in the import map are not bundled into the Rollup output so\n * the browser can load these bare specifiers according to the import map.\n */\nexport function createExternalFromImportMap({imports = {}}: ImportMap = {}): (string | RegExp)[] {\n return Object.keys(imports).map((specifier) =>\n specifier.endsWith('/') ? new RegExp(`^${escapeRegExp(specifier)}.+`) : specifier,\n )\n}\n","import path from 'node:path'\n\nimport {escapeRegExp} from 'lodash'\nimport resolve from 'resolve.exports'\nimport {type Alias} from 'vite'\n\n/**\n * The following are the specifiers that are expected/allowed to be used within\n * a built Sanity studio in the browser. These are used in combination with\n * `resolve.exports` to determine the final entry point locations for each allowed specifier.\n *\n * There is also a corresponding test for this file that expects these to be\n * included in the `sanity` package.json. That test is meant to keep this list\n * in sync in the event we add another package subpath.\n *\n * @internal\n */\nexport const browserCompatibleSanityPackageSpecifiers = [\n 'sanity',\n 'sanity/_createContext',\n 'sanity/_singletons',\n 'sanity/desk',\n 'sanity/presentation',\n 'sanity/router',\n 'sanity/structure',\n 'sanity/package.json',\n]\n\n/**\n * These conditions should align with the conditions present in the\n * `package.json` of the `'sanity'` module. they are given to `resolve.exports`\n * in order to determine the correct entrypoint for the browser-compatible\n * package specifiers listed above.\n */\nconst conditions = ['import', 'browser', 'default']\n\n// locate the entry points for each subpath the Sanity module exports\nexport function getSanityPkgExportAliases(sanityPkgPath: string) {\n // Load the package.json of the Sanity package\n // eslint-disable-next-line import/no-dynamic-require\n const pkg = require(sanityPkgPath)\n const dirname = path.dirname(sanityPkgPath)\n\n // Resolve the entry points for each allowed specifier\n const unifiedSanityAliases = browserCompatibleSanityPackageSpecifiers.reduce<Alias[]>(\n (acc, next) => {\n // Resolve the export path for the specifier using resolve.exports\n const dest = resolve.exports(pkg, next, {browser: true, conditions})?.[0]\n if (!dest) return acc\n\n // Map the specifier to its resolved path\n acc.push({\n find: new RegExp(`^${escapeRegExp(next)}$`),\n replacement: path.resolve(dirname, dest),\n })\n return acc\n },\n [],\n )\n\n // Return the aliases configuration for external projects\n return unifiedSanityAliases\n}\n","import path from 'node:path'\n\nimport readPkgUp from 'read-pkg-up'\nimport resolveFrom from 'resolve-from'\n\n/**\n * Given a module name such as \"styled-components\", will resolve the _module path_,\n * eg if require.resolve(`styled-components`) resolves to:\n * `/some/node_modules/styled-components/lib/cjs/styled.js`\n * this function will instead return\n * `/some/node_modules/styled-components`\n *\n * This is done in order for aliases to be pointing to the right module in terms of\n * _file-system location_, without pointing to a specific commonjs/browser/module variant\n *\n * @internal\n */\nexport async function getModulePath(mod: string, fromDir: string): Promise<string> {\n const modulePath = resolveFrom(fromDir, mod)\n const pkg = await readPkgUp({cwd: path.dirname(modulePath)})\n\n return pkg ? path.dirname(pkg.path) : modulePath\n}\n\n/**\n * @internal\n */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === 'object' && !Array.isArray(value)\n}\n\n/**\n * Ensures that the given path both starts and ends with a single slash\n *\n * @internal\n */\nexport function normalizeBasePath(pathName: string): string {\n return `/${pathName}/`.replace(/^\\/+/, '/').replace(/\\/+$/, '/')\n}\n","import path from 'node:path'\n\nimport readPkgUp from 'read-pkg-up'\n\n/**\n * @internal\n */\nexport interface SanityMonorepo {\n path: string\n}\n\nexport async function getMonorepoAliases(monorepoPath: string) {\n const {default: aliases} = await import('@repo/dev-aliases')\n return Object.fromEntries(\n Object.entries(aliases).map(([pkgName, pkgPath]) => {\n return [pkgName, path.resolve(monorepoPath, path.join('packages', pkgPath))]\n }),\n )\n}\n\n/**\n * Load information about the `sanity-io/sanity` monorepo (if applicable)\n *\n * @internal\n */\nexport async function loadSanityMonorepo(cwd: string): Promise<SanityMonorepo | undefined> {\n let p = cwd\n\n while (p !== '/') {\n const readResult = await readPkgUp({cwd: p})\n\n if (!readResult) {\n return undefined\n }\n\n if (readResult.packageJson.isSanityMonorepo) {\n return {path: path.dirname(readResult.path)}\n }\n\n p = path.dirname(path.dirname(readResult.path))\n }\n\n return undefined\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 */\nexport const 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 importMapEl.textContent = JSON.stringify({\n imports: Object.fromEntries(\n Object.entries(imports).map(([specifier, path]) => {\n try {\n const url = new URL(path);\n if (/^sanity-cdn\\\\.[a-zA-Z]+$/.test(url.hostname)) {\n url.pathname = url.pathname.replace(/\\\\/t\\\\d+/, newTimestamp);\n }\n return [specifier, url.toString()];\n } catch {\n return [specifier, path];\n }\n })\n ),\n ...rest,\n });\n document.head.appendChild(importMapEl);\n</script>`\n","/**\n * Looks for and imports (in preferred order):\n * - src/_document.js\n * - src/_document.tsx\n *\n * Then renders using ReactDOM to a string, which is sent back to the parent\n * process over the worker `postMessage` channel.\n */\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport {isMainThread, parentPort, Worker, workerData} from 'node:worker_threads'\n\nimport chalk from 'chalk'\nimport importFresh from 'import-fresh'\nimport {parse as parseHtml} from 'node-html-parser'\nimport {renderToStaticMarkup} from 'react-dom/server'\n\nimport {TIMESTAMPED_IMPORTMAP_INJECTOR_SCRIPT} from './constants'\nimport {debug as serverDebug} from './debug'\nimport {getMonorepoAliases, type SanityMonorepo} from './sanityMonorepo'\n\nconst debug = serverDebug.extend('renderDocument')\n\n// Don't use threads in the jest world\n// eslint-disable-next-line no-process-env, turbo/no-undeclared-env-vars\nconst useThreads = typeof process.env.JEST_WORKER_ID === 'undefined'\nconst hasWarnedAbout = new Set<string>()\n\nconst defaultProps = {\n entryPath: './.sanity/runtime/app.js',\n}\n\nconst autoGeneratedWarning = `\nThis file is auto-generated from \"sanity dev\".\nModifications to this file are automatically discarded.\n`.trim()\n\ninterface DocumentProps {\n basePath: string\n entryPath?: string\n css?: string[]\n}\n\ninterface RenderDocumentOptions {\n monorepo?: SanityMonorepo\n studioRootPath: string\n props?: DocumentProps\n importMap?: {\n imports?: Record<string, string>\n }\n}\n\nexport function renderDocument(options: RenderDocumentOptions): Promise<string> {\n return new Promise((resolve, reject) => {\n if (!useThreads) {\n resolve(getDocumentHtml(options.studioRootPath, options.props, options.importMap))\n return\n }\n\n debug('Starting worker thread for %s', __filename)\n const worker = new Worker(__filename, {\n execArgv: __DEV__ ? ['-r', `${__dirname}/esbuild-register.js`] : undefined,\n workerData: {...options, dev: __DEV__, shouldWarn: true},\n // eslint-disable-next-line no-process-env\n env: process.env,\n })\n\n worker.on('message', (msg) => {\n if (msg.type === 'warning') {\n if (hasWarnedAbout.has(msg.warnKey)) {\n return\n }\n\n if (Array.isArray(msg.message)) {\n msg.message.forEach((warning: string) =>\n console.warn(`${chalk.yellow('[warn]')} ${warning}`),\n )\n } else {\n console.warn(`${chalk.yellow('[warn]')} ${msg.message}`)\n }\n\n hasWarnedAbout.add(msg.warnKey)\n return\n }\n\n if (msg.type === 'error') {\n debug('Error from worker: %s', msg.error || 'Unknown error')\n reject(new Error(msg.error || 'Document rendering worker stopped with an unknown error'))\n return\n }\n\n if (msg.type === 'result') {\n debug('Document HTML rendered, %d bytes', msg.html.length)\n resolve(msg.html)\n }\n })\n worker.on('error', (err) => {\n debug('Worker errored: %s', err.message)\n reject(err)\n })\n worker.on('exit', (code) => {\n if (code !== 0) {\n debug('Worker stopped with code %d', code)\n reject(new Error(`Document rendering worker stopped with exit code ${code}`))\n }\n })\n })\n}\n\nexport function decorateIndexWithAutoGeneratedWarning(template: string): string {\n return template.replace(/<head/, `\\n<!--\\n${autoGeneratedWarning}\\n-->\\n<head`)\n}\n\nexport function getPossibleDocumentComponentLocations(studioRootPath: string): string[] {\n return [path.join(studioRootPath, '_document.js'), path.join(studioRootPath, '_document.tsx')]\n}\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 */\nexport function _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\nif (!isMainThread && parentPort) {\n renderDocumentFromWorkerData()\n}\n\nfunction renderDocumentFromWorkerData() {\n if (!parentPort || !workerData) {\n throw new Error('Must be used as a Worker with a valid options object in worker data')\n }\n\n const {monorepo, studioRootPath, props, importMap}: RenderDocumentOptions = workerData || {}\n\n if (workerData?.dev) {\n // Define `__DEV__` in the worker thread as well\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ;(global as any).__DEV__ = true\n }\n\n if (typeof studioRootPath !== 'string') {\n parentPort.postMessage({type: 'error', message: 'Missing/invalid `studioRootPath` option'})\n return\n }\n\n if (props && typeof props !== 'object') {\n parentPort.postMessage({type: 'error', message: '`props` must be an object if provided'})\n return\n }\n\n // Require hook #1\n // Alias monorepo modules\n debug('Registering potential aliases')\n if (monorepo) {\n require('module-alias').addAliases(getMonorepoAliases(monorepo.path))\n }\n\n // Require hook #2\n // Use `esbuild` to allow JSX/TypeScript and modern JS features\n debug('Registering esbuild for node %s', process.version)\n const {unregister} = __DEV__\n ? {unregister: () => undefined}\n : require('esbuild-register/dist/node').register({\n target: `node${process.version.slice(1)}`,\n supported: {'dynamic-import': true},\n jsx: 'automatic',\n extensions: ['.jsx', '.ts', '.tsx', '.mjs'],\n })\n\n // Require hook #3\n // Same as above, but we don't want to enforce a .jsx extension for anything with JSX\n debug('Registering esbuild for .js files using jsx loader')\n const {unregister: unregisterJs} = __DEV__\n ? {unregister: () => undefined}\n : require('esbuild-register/dist/node').register({\n target: `node${process.version.slice(1)}`,\n supported: {'dynamic-import': true},\n extensions: ['.js'],\n jsx: 'automatic',\n loader: 'jsx',\n })\n\n const html = getDocumentHtml(studioRootPath, props, importMap)\n\n parentPort.postMessage({type: 'result', html})\n\n // Be polite and clean up after esbuild-register\n unregister()\n unregisterJs()\n}\n\nfunction getDocumentHtml(\n studioRootPath: string,\n props?: DocumentProps,\n importMap?: {imports?: Record<string, string>},\n): string {\n const Document = getDocumentComponent(studioRootPath)\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 debug('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\n/**\n * @internal\n */\nexport function addTimestampedImportMapScriptToHtml(\n html: string,\n importMap?: {imports?: Record<string, 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.appendChild(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 headEl.insertAdjacentHTML(\n 'beforeend',\n `<script type=\"application/json\" id=\"__imports\">${JSON.stringify(importMap)}</script>`,\n )\n headEl.insertAdjacentHTML('beforeend', TIMESTAMPED_IMPORTMAP_INJECTOR_SCRIPT)\n return root.outerHTML\n}\n\nfunction getDocumentComponent(studioRootPath: string) {\n debug('Loading default document component from `sanity` module')\n const {DefaultDocument} = __DEV__\n ? require('../../../core/components/DefaultDocument')\n : require('sanity')\n\n debug('Attempting to load user-defined document component from %s', studioRootPath)\n const userDefined = tryLoadDocumentComponent(studioRootPath)\n\n if (!userDefined) {\n debug('Using default document component')\n return DefaultDocument\n }\n\n debug('Found user defined document component at %s', userDefined.path)\n\n const DocumentComp = userDefined.component.default || userDefined.component // CommonJS\n if (typeof DocumentComp === 'function') {\n debug('User defined document component is a function, assuming valid')\n return DocumentComp\n }\n\n debug('User defined document component did not have a default export')\n const userExports = Object.keys(userDefined.component).join(', ') || 'None'\n const relativePath = path.relative(process.cwd(), userDefined.path)\n const typeHint =\n typeof userDefined.component.default === 'undefined'\n ? ''\n : ` (type was ${typeof userDefined.component.default})`\n\n const warnKey = `${relativePath}/${userDefined.modified}`\n\n parentPort?.postMessage({\n type: 'warning',\n message: [\n `${relativePath} did not have a default export that is a React component${typeHint}`,\n `Named exports/properties found: ${userExports}`.trim(),\n `Using default document component from \"sanity\".`,\n ],\n warnKey,\n })\n\n return DefaultDocument\n}\n\nfunction tryLoadDocumentComponent(studioRootPath: string) {\n const locations = getPossibleDocumentComponentLocations(studioRootPath)\n\n for (const componentPath of locations) {\n debug('Trying to load document component from %s', componentPath)\n try {\n return {\n // eslint-disable-next-line import/no-dynamic-require\n component: importFresh<any>(componentPath),\n path: componentPath,\n // eslint-disable-next-line no-sync\n modified: Math.floor(fs.statSync(componentPath)?.mtimeMs),\n }\n } catch (err) {\n // Allow \"not found\" errors\n if (err.code !== 'MODULE_NOT_FOUND') {\n debug('Failed to load document component: %s', err.message)\n throw err\n }\n\n debug('Document component not found at %s', componentPath)\n }\n }\n\n return null\n}\n","import {type ChunkMetadata, type Plugin} from 'vite'\n\nimport {renderDocument} from '../renderDocument'\nimport {type SanityMonorepo} from '../sanityMonorepo'\n\ninterface ViteOutputBundle {\n [fileName: string]: ViteRenderedChunk | ViteRenderedAsset\n}\n\ninterface ViteRenderedAsset {\n type: 'asset'\n}\n\ninterface ViteRenderedChunk {\n type: 'chunk'\n name: string\n fileName: string\n facadeModuleId: string | null\n code: string\n imports: string[]\n viteMetadata: ChunkMetadata\n}\n\nconst entryChunkId = '.sanity/runtime/app.js'\n\nexport function sanityBuildEntries(options: {\n cwd: string\n monorepo: SanityMonorepo | undefined\n basePath: string\n importMap?: {imports?: Record<string, string>}\n}): Plugin {\n const {cwd, monorepo, basePath, importMap} = options\n\n return {\n name: 'sanity/server/build-entries',\n apply: 'build',\n\n buildStart() {\n this.emitFile({\n type: 'chunk',\n id: entryChunkId,\n name: 'sanity',\n })\n },\n\n async generateBundle(_options, outputBundle) {\n const bundle = outputBundle as unknown as ViteOutputBundle\n const entryFile = Object.values(bundle).find(\n (file) =>\n file.type === 'chunk' &&\n file.name === 'sanity' &&\n file.facadeModuleId?.endsWith(entryChunkId),\n )\n\n if (!entryFile) {\n throw new Error(`Failed to find entry file in bundle (${entryChunkId})`)\n }\n\n if (entryFile.type !== 'chunk') {\n throw new Error('Entry file is not a chunk')\n }\n\n const entryFileName = entryFile.fileName\n const entryPath = [basePath.replace(/\\/+$/, ''), entryFileName].join('/')\n\n let css: string[] = []\n if (entryFile.viteMetadata?.importedCss) {\n // Check all the top-level imports of the entryPoint to see if they have\n // static CSS assets that need loading\n css = [...entryFile.viteMetadata.importedCss]\n for (const key of entryFile.imports) {\n // Traverse all CSS assets that isn't loaded by the runtime and\n // need <link> tags in the HTML template\n const entry = bundle[key]\n const importedCss =\n entry && entry.type === 'chunk' ? entry.viteMetadata.importedCss : undefined\n\n if (importedCss) {\n css.push(...importedCss)\n }\n }\n }\n\n this.emitFile({\n type: 'asset',\n fileName: 'index.html',\n source: await renderDocument({\n monorepo,\n studioRootPath: cwd,\n importMap,\n props: {\n basePath,\n entryPath,\n css,\n },\n }),\n })\n },\n }\n}\n","export interface WebManifest {\n icons: {\n src: string\n type: string\n sizes: string\n }[]\n}\n\nexport function generateWebManifest(basePath: string): WebManifest {\n return {\n icons: [\n {src: `${basePath}/favicon-192.png`, type: 'image/png', sizes: '192x192'},\n {src: `${basePath}/favicon-512.png`, type: 'image/png', sizes: '512x512'},\n ],\n }\n}\n","import fs from 'node:fs/promises'\nimport path from 'node:path'\n\nimport {type Plugin} from 'vite'\n\nimport {generateWebManifest} from '../webManifest'\n\nconst mimeTypes: Record<string, string | undefined> = {\n '.ico': 'image/x-icon',\n '.svg': 'image/svg+xml',\n '.png': 'image/png',\n}\n\n/**\n * Fallback favicons plugin for Sanity.\n *\n * If a favicon is not found in the static folder, this plugin will serve the default\n * Sanity favicons from the npm bundle. If a custom `favicon.ico` is found in the static\n * folder, it will also be served for a root `/favicon.ico` request.\n *\n * @param options - Options for the plugin\n * @returns A Vite plugin\n * @internal\n */\nexport function sanityFaviconsPlugin({\n defaultFaviconsPath,\n customFaviconsPath,\n staticUrlPath,\n}: {\n defaultFaviconsPath: string\n customFaviconsPath: string\n staticUrlPath: string\n}): Plugin {\n const cache: {favicons?: string[]} = {}\n\n async function getFavicons(): Promise<string[]> {\n if (cache.favicons) {\n return cache.favicons\n }\n\n cache.favicons = await fs.readdir(defaultFaviconsPath)\n return cache.favicons\n }\n\n async function hasCustomFavicon(fileName: string): Promise<boolean> {\n try {\n await fs.access(path.join(customFaviconsPath, fileName))\n return true\n } catch (err) {\n return false\n }\n }\n\n return {\n name: 'sanity/server/sanity-favicons',\n apply: 'serve',\n configureServer(viteDevServer) {\n const webManifest = JSON.stringify(generateWebManifest(staticUrlPath), null, 2)\n const webManifestPath = `${staticUrlPath}/manifest.webmanifest`\n\n viteDevServer.middlewares.use(async (req, res, next) => {\n if (req.url?.endsWith(webManifestPath)) {\n res.writeHead(200, 'OK', {'content-type': 'application/manifest+json'})\n res.write(webManifest)\n res.end()\n return\n }\n\n const parsedUrl =\n ((req as any)._parsedUrl as URL) || new URL(req.url || '/', 'http://localhost:3333')\n\n const pathName = parsedUrl.pathname || ''\n const fileName = path.basename(pathName || '')\n const icons = await getFavicons()\n const isIconRequest =\n pathName.startsWith('/favicon.ico') ||\n (icons.includes(fileName) && pathName.includes(staticUrlPath))\n\n if (!isIconRequest) {\n next()\n return\n }\n\n const faviconPath = (await hasCustomFavicon(fileName))\n ? path.join(customFaviconsPath, fileName)\n : path.join(defaultFaviconsPath, fileName)\n\n const mimeType = mimeTypes[path.extname(fileName)] || 'application/octet-stream'\n res.writeHead(200, 'OK', {'content-type': mimeType})\n res.write(await fs.readFile(faviconPath))\n res.end()\n })\n },\n }\n}\n","import {type Plugin} from 'vite'\n\nexport function sanityRuntimeRewritePlugin(): Plugin {\n return {\n name: 'sanity/server/sanity-runtime-rewrite',\n apply: 'serve',\n configureServer(viteDevServer) {\n return () => {\n viteDevServer.middlewares.use((req, res, next) => {\n if (req.url === '/index.html') {\n req.url = '/.sanity/runtime/index.html'\n }\n\n next()\n })\n }\n },\n }\n}\n","import path from 'node:path'\n\nimport {type ReactCompilerConfig, type UserViteConfig} from '@sanity/cli'\nimport debug from 'debug'\nimport readPkgUp from 'read-pkg-up'\nimport {type ConfigEnv, type InlineConfig, type Rollup} from 'vite'\n\nimport {createExternalFromImportMap} from './createExternalFromImportMap'\nimport {getSanityPkgExportAliases} from './getBrowserAliases'\nimport {getStudioEnvironmentVariables} from './getStudioEnvironmentVariables'\nimport {normalizeBasePath} from './helpers'\nimport {getMonorepoAliases, loadSanityMonorepo} from './sanityMonorepo'\nimport {sanityBuildEntries} from './vite/plugin-sanity-build-entries'\nimport {sanityFaviconsPlugin} from './vite/plugin-sanity-favicons'\nimport {sanityRuntimeRewritePlugin} from './vite/plugin-sanity-runtime-rewrite'\n\nexport interface ViteOptions {\n /**\n * Root path of the studio/sanity app\n */\n cwd: 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 /**\n * Output directory (eg where to place the built files, if any)\n */\n outputDir?: string\n\n /**\n * Whether or not to enable source maps\n */\n sourceMap?: boolean\n\n /**\n * Whether or not to minify the output (only used in `mode: 'production'`)\n */\n minify?: boolean\n\n /**\n * HTTP development server configuration\n */\n server?: {port?: number; host?: string}\n\n /**\n * Mode to run vite in - eg development or production\n */\n mode: 'development' | 'production'\n\n importMap?: {imports?: Record<string, string>}\n reactCompiler: ReactCompilerConfig | undefined\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 cwd,\n mode,\n outputDir,\n // default to `true` when `mode=development`\n sourceMap = options.mode === 'development',\n server,\n minify,\n basePath: rawBasePath = '/',\n importMap,\n reactCompiler,\n } = options\n\n const monorepo = await loadSanityMonorepo(cwd)\n const basePath = normalizeBasePath(rawBasePath)\n\n const sanityPkgPath = (await readPkgUp({cwd: __dirname}))?.path\n if (!sanityPkgPath) {\n throw new Error('Unable to resolve `sanity` module root')\n }\n\n const customFaviconsPath = path.join(cwd, 'static')\n const defaultFaviconsPath = path.join(path.dirname(sanityPkgPath), 'static', 'favicons')\n const staticPath = `${basePath}static`\n\n const {default: viteReact} = await import('@vitejs/plugin-react')\n const viteConfig: InlineConfig = {\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 root: cwd,\n base: basePath,\n build: {\n outDir: outputDir || path.resolve(cwd, 'dist'),\n sourcemap: sourceMap,\n },\n server: {\n host: server?.host,\n port: server?.port || 3333,\n strictPort: true,\n },\n configFile: false,\n mode,\n plugins: [\n viteReact(\n reactCompiler ? {babel: {plugins: [['babel-plugin-react-compiler', reactCompiler]]}} : {},\n ),\n sanityFaviconsPlugin({defaultFaviconsPath, customFaviconsPath, staticUrlPath: staticPath}),\n sanityRuntimeRewritePlugin(),\n sanityBuildEntries({basePath, cwd, monorepo, importMap}),\n ],\n envPrefix: 'SANITY_STUDIO_',\n logLevel: mode === 'production' ? 'silent' : 'info',\n resolve: {\n alias: monorepo?.path\n ? await getMonorepoAliases(monorepo.path)\n : getSanityPkgExportAliases(sanityPkgPath),\n dedupe: ['styled-components'],\n },\n define: {\n // eslint-disable-next-line no-process-env\n '__SANITY_STAGING__': process.env.SANITY_INTERNAL_ENV === 'staging',\n 'process.env.MODE': JSON.stringify(mode),\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 ...getStudioEnvironmentVariables({prefix: 'process.env.', jsonEncode: true}),\n },\n }\n\n if (mode === 'production') {\n viteConfig.build = {\n ...viteConfig.build,\n\n assetsDir: 'static',\n minify: minify ? 'esbuild' : false,\n emptyOutDir: false, // Rely on CLI to do this\n\n rollupOptions: {\n onwarn: onRollupWarn,\n external: createExternalFromImportMap(importMap),\n input: {\n sanity: path.join(cwd, '.sanity', 'runtime', 'app.js'),\n },\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/'))) 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 Error(\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 const {mergeConfig} = await import('vite')\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 const {mergeConfig} = await import('vite')\n config = mergeConfig(config, userConfig)\n }\n\n return config\n}\n","const entryModule = `\n// This file is auto-generated on 'sanity dev'\n// Modifications to this file is automatically discarded\nimport {renderStudio} from \"sanity\"\nimport studioConfig from %STUDIO_CONFIG_LOCATION%\n\nrenderStudio(\n document.getElementById(\"sanity\"),\n studioConfig,\n {reactStrictMode: %STUDIO_REACT_STRICT_MODE%, basePath: %STUDIO_BASE_PATH%}\n)\n`\n\nconst noConfigEntryModule = `\n// This file is auto-generated on 'sanity dev'\n// Modifications to this file is automatically discarded\nimport {renderStudio} from \"sanity\"\n\nconst studioConfig = {missingConfigFile: true}\n\nrenderStudio(\n document.getElementById(\"sanity\"),\n studioConfig,\n {reactStrictMode: %STUDIO_REACT_STRICT_MODE%, basePath: %STUDIO_BASE_PATH%}\n)\n`\n\nexport function getEntryModule(options: {\n reactStrictMode: boolean\n relativeConfigLocation: string | null\n basePath?: string\n}): string {\n const {reactStrictMode, relativeConfigLocation, basePath} = options\n const sourceModule = relativeConfigLocation ? entryModule : noConfigEntryModule\n\n return sourceModule\n .replace(/%STUDIO_REACT_STRICT_MODE%/, JSON.stringify(Boolean(reactStrictMode)))\n .replace(/%STUDIO_CONFIG_LOCATION%/, JSON.stringify(relativeConfigLocation))\n .replace(/%STUDIO_BASE_PATH%/, JSON.stringify(basePath || '/'))\n}\n","import fs from 'node:fs/promises'\nimport path from 'node:path'\n\nimport {debug as serverDebug} from './debug'\n\nconst debug = serverDebug.extend('config')\n\n/**\n * Resolves the path to the studio configuration file with the following extensions,\n * in preferred order: '.mjs', '.js', '.ts', '.jsx', '.tsx' (aligns with vite)\n *\n * Falls back to the default studio configuration exported by `sanity` if none is found\n *\n * @internal\n */\nexport async function getSanityStudioConfigPath(studioRootPath: string): Promise<string | null> {\n const configPaths = [\n path.join(studioRootPath, 'sanity.config.mjs'),\n path.join(studioRootPath, 'sanity.config.js'),\n path.join(studioRootPath, 'sanity.config.ts'),\n path.join(studioRootPath, 'sanity.config.jsx'),\n path.join(studioRootPath, 'sanity.config.tsx'),\n ]\n\n debug('Looking for configuration file in %d possible locations', configPaths.length)\n const configs = await Promise.all(\n configPaths.map(async (configPath) => ({\n path: configPath,\n exists: await fileExists(configPath),\n })),\n )\n\n const availableConfigs = configs.filter((config) => config.exists)\n debug('Found %d available configuration files', availableConfigs.length)\n\n // No config file exists?\n if (availableConfigs.length === 0) {\n console.warn('No `sanity.config.js`/`sanity.config.ts` found - using default studio config')\n return null\n }\n\n if (availableConfigs.length > 1) {\n console.warn('Found multiple potential studio configs:')\n availableConfigs.forEach((config) => console.warn(` - ${config.path}`))\n console.warn(`Using ${availableConfigs[0].path}`)\n }\n\n return availableConfigs[0].path\n}\n\n/**\n * Asynchronously checks if a file exists. This is prone to race conditions,\n * as the file can exist/not exist by the time this resolves, but in this\n * case this is an acceptable trade-off. Best effort, and all that.\n */\nfunction fileExists(filePath: string): Promise<boolean> {\n return fs.stat(filePath).then(\n () => true,\n () => false,\n )\n}\n","import fs from 'node:fs/promises'\nimport path from 'node:path'\n\nimport chokidar from 'chokidar'\n\nimport {debug as serverDebug} from './debug'\nimport {getEntryModule} from './getEntryModule'\nimport {\n decorateIndexWithAutoGeneratedWarning,\n getPossibleDocumentComponentLocations,\n renderDocument,\n} from './renderDocument'\nimport {getSanityStudioConfigPath} from './sanityConfig'\nimport {loadSanityMonorepo} from './sanityMonorepo'\n\nconst debug = serverDebug.extend('runtime')\n\nexport interface RuntimeOptions {\n cwd: string\n reactStrictMode: boolean\n watch: boolean\n basePath?: string\n}\n\n/**\n * Generates the `.sanity/runtime` directory, and optionally watches for custom\n * document files, rebuilding when they change\n *\n * @param options - Current working directory (Sanity root dir), and whether or not to watch\n * @internal\n */\nexport async function writeSanityRuntime({\n cwd,\n reactStrictMode,\n watch,\n basePath,\n}: RuntimeOptions): Promise<void> {\n debug('Resolving Sanity monorepo information')\n const monorepo = await loadSanityMonorepo(cwd)\n const runtimeDir = path.join(cwd, '.sanity', 'runtime')\n\n debug('Making runtime directory')\n await fs.mkdir(runtimeDir, {recursive: true})\n\n async function renderAndWriteDocument() {\n debug('Rendering document template')\n const indexHtml = decorateIndexWithAutoGeneratedWarning(\n await renderDocument({\n studioRootPath: cwd,\n monorepo,\n props: {\n entryPath: `/${path.relative(cwd, path.join(runtimeDir, 'app.js'))}`,\n basePath: basePath || '/',\n },\n }),\n )\n\n debug('Writing index.html to runtime directory')\n await fs.writeFile(path.join(runtimeDir, 'index.html'), indexHtml)\n }\n\n if (watch) {\n chokidar\n .watch(getPossibleDocumentComponentLocations(cwd))\n .on('all', () => renderAndWriteDocument())\n }\n\n await renderAndWriteDocument()\n\n debug('Writing app.js to runtime directory')\n const studioConfigPath = await getSanityStudioConfigPath(cwd)\n const relativeConfigLocation = studioConfigPath\n ? path.relative(runtimeDir, studioConfigPath)\n : null\n\n await fs.writeFile(\n path.join(runtimeDir, 'app.js'),\n getEntryModule({reactStrictMode, relativeConfigLocation, basePath}),\n )\n}\n"],"names":["debug","debugIt","createExternalFromImportMap","imports","Object","keys","map","specifier","endsWith","RegExp","escapeRegExp","browserCompatibleSanityPackageSpecifiers","conditions","getSanityPkgExportAliases","sanityPkgPath","pkg","require","dirname","path","reduce","acc","next","dest","resolve","exports","browser","push","find","replacement","normalizeBasePath","pathName","replace","getMonorepoAliases","monorepoPath","default","aliases","fromEntries","entries","pkgName","pkgPath","join","loadSanityMonorepo","cwd","p","readResult","readPkgUp","packageJson","isSanityMonorepo","TIMESTAMPED_IMPORTMAP_INJECTOR_SCRIPT","serverDebug","extend","useThreads","process","env","JEST_WORKER_ID","hasWarnedAbout","Set","defaultProps","entryPath","autoGeneratedWarning","trim","renderDocument","options","Promise","reject","getDocumentHtml","studioRootPath","props","importMap","__filename","worker","Worker","execArgv","undefined","workerData","dev","shouldWarn","on","msg","type","has","warnKey","Array","isArray","message","forEach","warning","console","warn","chalk","yellow","add","error","Error","html","length","err","code","decorateIndexWithAutoGeneratedWarning","template","getPossibleDocumentComponentLocations","_prefixUrlWithBasePath","url","basePath","normalizedBasePath","startsWith","slice","isMainThread","parentPort","renderDocumentFromWorkerData","monorepo","global","__DEV__","postMessage","addAliases","version","unregister","register","target","supported","jsx","extensions","unregisterJs","loader","Document","getDocumentComponent","css","URL","toString","addTimestampedImportMapScriptToHtml","renderToStaticMarkup","root","parseHtml","htmlEl","querySelector","oldRoot","appendChild","headEl","insertAdjacentHTML","JSON","stringify","outerHTML","DefaultDocument","userDefined","tryLoadDocumentComponent","DocumentComp","component","userExports","relativePath","relative","typeHint","modified","locations","componentPath","importFresh","Math","floor","fs","statSync","mtimeMs","entryChunkId","sanityBuildEntries","name","apply","buildStart","emitFile","id","generateBundle","_options","outputBundle","bundle","entryFile","values","file","facadeModuleId","entryFileName","fileName","viteMetadata","importedCss","key","entry","source","generateWebManifest","icons","src","sizes","mimeTypes","sanityFaviconsPlugin","defaultFaviconsPath","customFaviconsPath","staticUrlPath","cache","getFavicons","favicons","readdir","hasCustomFavicon","access","configureServer","viteDevServer","webManifest","webManifestPath","middlewares","use","req","res","writeHead","write","end","_parsedUrl","pathname","basename","includes","faviconPath","mimeType","extname","readFile","sanityRuntimeRewritePlugin","getViteConfig","mode","outputDir","sourceMap","server","minify","rawBasePath","reactCompiler","__dirname","staticPath","viteReact","viteConfig","cacheDir","base","build","outDir","sourcemap","host","port","strictPort","configFile","plugins","babel","envPrefix","logLevel","alias","dedupe","define","SANITY_INTERNAL_ENV","getStudioEnvironmentVariables","prefix","jsonEncode","assetsDir","emptyOutDir","rollupOptions","onwarn","onRollupWarn","external","input","sanity","suppressUnusedImport","names","filter","n","ids","every","finalizeViteConfig","config","mergeConfig","extendViteConfigWithUserConfig","defaultConfig","userConfig","entryModule","noConfigEntryModule","getEntryModule","reactStrictMode","relativeConfigLocation","Boolean","getSanityStudioConfigPath","configPaths","availableConfigs","all","configPath","exists","fileExists","filePath","stat","then","writeSanityRuntime","watch","runtimeDir","mkdir","recursive","renderAndWriteDocument","indexHtml","writeFile","chokidar","studioConfigPath"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAEaA,MAAAA,UAAQC,uBAAQ,eAAe;ACQrC,SAASC,4BAA4B;AAAA,EAACC,UAAU,CAAA;AAAa,IAAI,IAAyB;AAC/F,SAAOC,OAAOC,KAAKF,OAAO,EAAEG,IAAKC,CAAAA,cAC/BA,UAAUC,SAAS,GAAG,IAAI,IAAIC,OAAO,IAAIC,sBAAAA,QAAaH,SAAS,CAAC,IAAI,IAAIA,SAC1E;AACF;ACGaI,MAAAA,2CAA2C,CACtD,UACA,yBACA,sBACA,eACA,uBACA,iBACA,oBACA,qBAAqB,GASjBC,aAAa,CAAC,UAAU,WAAW,SAAS;AAG3C,SAASC,0BAA0BC,eAAuB;AAG/D,QAAMC,MAAMC,QAAQF,aAAa,GAC3BG,UAAUC,cAAAA,QAAKD,QAAQH,aAAa;AAoB1C,SAjB6BH,yCAAyCQ,OACpE,CAACC,KAAKC,SAAS;AAEb,UAAMC,OAAOC,iBAAAA,QAAQC,QAAQT,KAAKM,MAAM;AAAA,MAACI,SAAS;AAAA,MAAMb;AAAAA,IAAW,CAAA,IAAI,CAAC;AACnEU,WAAAA,QAGLF,IAAIM,KAAK;AAAA,MACPC,MAAM,IAAIlB,OAAO,IAAIC,sBAAAA,QAAaW,IAAI,CAAC,GAAG;AAAA,MAC1CO,aAAaV,cAAAA,QAAKK,QAAQN,SAASK,IAAI;AAAA,IACxC,CAAA,GACMF;AAAAA,EACT,GACA,EACF;AAIF;AC1BO,SAASS,kBAAkBC,UAA0B;AACnD,SAAA,IAAIA,QAAQ,IAAIC,QAAQ,QAAQ,GAAG,EAAEA,QAAQ,QAAQ,GAAG;AACjE;AC3BA,eAAsBC,mBAAmBC,cAAsB;AACvD,QAAA;AAAA,IAACC,SAASC;AAAAA,EAAAA,IAAW,MAAM,QAAO,QAAA,EA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eof e == "object" && "default" in e ? e : { default: e };
5
+ }
6
+ var path__default = /* @__PURE__ */ _interopDefaultCompat(path);
7
+ async function storeManifestSchemas(args, context) {
8
+ const flags = args.extOptions, schemaPath = flags["schema-path"], workspaceName = flags["workspace-name"], {
9
+ output,
10
+ workDir,
11
+ apiClient
12
+ } = context;
13
+ try {
14
+ const manifestPath = path__default.default.resolve(process.cwd(), schemaPath || path__default.default.join(workDir, "dist/static")), client = apiClient({
15
+ requireUser: !0,
16
+ requireProject: !0
17
+ }).withConfig({
18
+ apiVersion: "v2024-08-01"
19
+ }), projectId = client.config().projectId, manifest = JSON.parse(fs.readFileSync(`${manifestPath}/create-manifest.json`, "utf-8")), saveSchema = async (workspace) => {
20
+ const spinner = output.spinner({}).start("Storing schemas"), id = `sanity.workspace.schema.${workspace.name}`;
21
+ try {
22
+ if (workspace.projectId !== projectId && workspaceName !== workspace.name) {
23
+ spinner.fail(`Cannot store schema for ${workspace.name} because manifest projectId does not match: ${projectId} !== ${workspace.projectId}`);
24
+ return;
25
+ }
26
+ const schema = JSON.parse(fs.readFileSync(`${manifestPath}/${workspace.schema}`, "utf-8"));
27
+ await client.withConfig({
28
+ dataset: workspace.dataset,
29
+ projectId: workspace.projectId
30
+ }).transaction().createOrReplace({
31
+ _type: "sanity.workspace.schema",
32
+ _id: id,
33
+ workspace,
34
+ schema
35
+ }).commit(), spinner.succeed(`Schema stored for workspace ${workspace.name} (shcemaId: ${id}, projectId: ${projectId}, dataset: ${workspace.dataset})`);
36
+ } catch (error) {
37
+ spinner.fail(`Error storing schema for workspace ${workspace.name}: ${error}`);
38
+ }
39
+ };
40
+ if (workspaceName) {
41
+ const schemaToSave = manifest.workspaces.find((workspace) => workspace.name === workspaceName);
42
+ schemaToSave ? await saveSchema(schemaToSave) : output.error(`Workspace ${workspaceName} not found in manifest: projectID: ${projectId}`);
43
+ } else
44
+ await Promise.all(manifest.workspaces.map(async (workspace) => {
45
+ await saveSchema(workspace);
46
+ }));
47
+ } catch (err) {
48
+ output.error(err);
49
+ }
50
+ }
51
+ exports.storeManifestSchemas = storeManifestSchemas;
52
+ //# sourceMappingURL=storeManifestSchemasAction.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"storeManifestSchemasAction.js","sources":["../../src/_internal/cli/actions/manifest/storeManifestSchemasAction.ts"],"sourcesContent":["import {readFileSync} from 'node:fs'\nimport path from 'node:path'\n\nimport {type CliCommandArguments, type CliCommandContext} from '@sanity/cli'\n\nimport {\n type CreateManifest,\n type ManifestSchemaType,\n type ManifestWorkspaceFile,\n} from '../../../manifest/manifestTypes'\n\nexport interface StoreManifestSchemasFlags {\n 'schema-path'?: string\n 'workspace-name'?: string\n}\n\nexport async function storeManifestSchemas(\n args: CliCommandArguments<StoreManifestSchemasFlags>,\n context: CliCommandContext,\n): Promise<void> {\n const flags = args.extOptions\n const schemaPath = flags['schema-path']\n const workspaceName = flags['workspace-name']\n const {output, workDir, apiClient} = context\n\n try {\n const manifestPath = path.resolve(\n process.cwd(),\n schemaPath || path.join(workDir, 'dist/static'),\n )\n const client = apiClient({\n requireUser: true,\n requireProject: true,\n }).withConfig({apiVersion: 'v2024-08-01'})\n\n const projectId = client.config().projectId\n\n const manifest: CreateManifest = JSON.parse(\n readFileSync(`${manifestPath}/create-manifest.json`, 'utf-8'),\n )\n\n const saveSchema = async (workspace: ManifestWorkspaceFile) => {\n const spinner = output.spinner({}).start('Storing schemas')\n const id = `sanity.workspace.schema.${workspace.name}`\n try {\n if (workspace.projectId !== projectId && workspaceName !== workspace.name) {\n spinner.fail(\n `Cannot store schema for ${workspace.name} because manifest projectId does not match: ${projectId} !== ${workspace.projectId}`,\n )\n return\n }\n const schema = JSON.parse(\n readFileSync(`${manifestPath}/${workspace.schema}`, 'utf-8'),\n ) as ManifestSchemaType\n await client\n .withConfig({\n dataset: workspace.dataset,\n projectId: workspace.projectId,\n })\n .transaction()\n .createOrReplace({_type: 'sanity.workspace.schema', _id: id, workspace, schema})\n .commit()\n spinner.succeed(\n `Schema stored for workspace ${workspace.name} (shcemaId: ${id}, projectId: ${projectId}, dataset: ${workspace.dataset})`,\n )\n } catch (error) {\n spinner.fail(`Error storing schema for workspace ${workspace.name}: ${error}`)\n }\n }\n\n if (workspaceName) {\n const schemaToSave = manifest.workspaces.find((workspace) => workspace.name === workspaceName)\n if (schemaToSave) {\n await saveSchema(schemaToSave)\n } else {\n output.error(`Workspace ${workspaceName} not found in manifest: projectID: ${projectId}`)\n }\n } else {\n await Promise.all(\n manifest.workspaces.map(async (workspace): Promise<void> => {\n await saveSchema(workspace)\n }),\n )\n }\n } catch (err) {\n output.error(err)\n }\n}\n"],"names":["storeManifestSchemas","args","context","flags","extOptions","schemaPath","workspaceName","output","workDir","apiClient","manifestPath","path","resolve","process","cwd","join","client","requireUser","requireProject","withConfig","apiVersion","projectId","config","manifest","JSON","parse","readFileSync","saveSchema","workspace","spinner","start","id","name","fail","schema","dataset","transaction","createOrReplace","_type","_id","commit","succeed","error","schemaToSave","workspaces","find","Promise","all","map","err"],"mappings":";;;;;;AAgBsBA,eAAAA,qBACpBC,MACAC,SACe;AACTC,QAAAA,QAAQF,KAAKG,YACbC,aAAaF,MAAM,aAAa,GAChCG,gBAAgBH,MAAM,gBAAgB,GACtC;AAAA,IAACI;AAAAA,IAAQC;AAAAA,IAASC;AAAAA,EAAAA,IAAaP;AAEjC,MAAA;AACF,UAAMQ,eAAeC,cAAAA,QAAKC,QACxBC,QAAQC,OACRT,cAAcM,cAAAA,QAAKI,KAAKP,SAAS,aAAa,CAChD,GACMQ,SAASP,UAAU;AAAA,MACvBQ,aAAa;AAAA,MACbC,gBAAgB;AAAA,IACjB,CAAA,EAAEC,WAAW;AAAA,MAACC,YAAY;AAAA,IAAA,CAAc,GAEnCC,YAAYL,OAAOM,OAAO,EAAED,WAE5BE,WAA2BC,KAAKC,MACpCC,GAAa,aAAA,GAAGhB,YAAY,yBAAyB,OAAO,CAC9D,GAEMiB,aAAa,OAAOC,cAAqC;AAC7D,YAAMC,UAA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";
2
+ var storeManifestSchemasAction = require("./storeManifestSchemasAction.js");
3
+ async function storeSchemaAction(args, context) {
4
+ storeManifestSchemasAction.storeManifestSchemas(args, context);
5
+ }
6
+ exports.default = storeSchemaAction;
7
+ //# sourceMappingURL=storeSchemaAction.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"storeSchemaAction.js","sources":["../../src/_internal/cli/actions/schema/storeSchemaAction.ts"],"sourcesContent":["import {type CliCommandArguments, type CliCommandContext} from '@sanity/cli'\n\nimport {\n storeManifestSchemas,\n type StoreManifestSchemasFlags,\n} from '../manifest/storeManifestSchemasAction'\n\nexport interface StoreSchemaFlags extends StoreManifestSchemasFlags {\n 'workspace-name': string\n}\n\nexport default async function storeSchemaAction(\n args: CliCommandArguments<StoreSchemaFlags>,\n context: CliCommandContext,\n): Promise<void> {\n storeManifestSchemas(args, context)\n}\n"],"names":["storeSchemaAction","args","context","storeManifestSchemas"],"mappings":";;AAW8BA,eAAAA,kBAC5BC,MACAC,SACe;AACfC,6BAAAA,qBAAqBF,MAAMC,OAAO;AACpC;;"}
@@ -1,4 +1,4 @@
1
1
  "use strict";
2
- const SANITY_VERSION = "3.72.2-coreui.15+190795cd18";
2
+ const SANITY_VERSION = "3.72.2-server-side-schemas.17+260ef73ae7";
3
3
  exports.SANITY_VERSION = SANITY_VERSION;
4
4
  //# sourceMappingURL=version.js.map
@@ -1,4 +1,4 @@
1
- const SANITY_VERSION = "3.72.2-coreui.15+190795cd18";
1
+ const SANITY_VERSION = "3.72.2-server-side-schemas.17+260ef73ae7";
2
2
  export {
3
3
  SANITY_VERSION
4
4
  };
@@ -1,4 +1,4 @@
1
- const SANITY_VERSION = "3.72.2-coreui.15+190795cd18";
1
+ const SANITY_VERSION = "3.72.2-server-side-schemas.17+260ef73ae7";
2
2
  export {
3
3
  SANITY_VERSION
4
4
  };