sanity 3.74.2-corel.18 → 3.74.2-coreui.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/_chunks-cjs/runtime.js +8 -4
- package/lib/_chunks-cjs/runtime.js.map +1 -1
- package/lib/_chunks-cjs/version.js +1 -1
- package/lib/_chunks-es/version.mjs +1 -1
- package/lib/_legacy/version.esm.js +1 -1
- package/package.json +10 -11
- package/src/_internal/cli/server/renderDocument.tsx +12 -0
- package/src/_internal/cli/server/runtime.ts +13 -10
- package/src/_internal/cli/server/vite/plugin-sanity-build-entries.ts +14 -12
- package/dist/BroadcastDisplayedDocument-BHYI8o6u.mjs +0 -19
- package/dist/BroadcastDisplayedDocument-BHYI8o6u.mjs.map +0 -1
- package/dist/DisplayedDocumentBroadcaster-DfHPxc7C.mjs +0 -58
- package/dist/DisplayedDocumentBroadcaster-DfHPxc7C.mjs.map +0 -1
- package/dist/LiveQueries-sYvgBCKh.mjs +0 -267
- package/dist/LiveQueries-sYvgBCKh.mjs.map +0 -1
- package/dist/LoaderQueries-AQneabiG.mjs +0 -581
- package/dist/LoaderQueries-AQneabiG.mjs.map +0 -1
- package/dist/Observable-wwWYwtkh.mjs +0 -551
- package/dist/Observable-wwWYwtkh.mjs.map +0 -1
- package/dist/PostMessageDocuments-DLMdHDk6.mjs +0 -75
- package/dist/PostMessageDocuments-DLMdHDk6.mjs.map +0 -1
- package/dist/PostMessageFeatures-CazMQz3f.mjs +0 -21
- package/dist/PostMessageFeatures-CazMQz3f.mjs.map +0 -1
- package/dist/PostMessagePerspective-m4uZ6sI5.mjs +0 -23
- package/dist/PostMessagePerspective-m4uZ6sI5.mjs.map +0 -1
- package/dist/PostMessagePreviewSnapshots-Dr7CEAiM.mjs +0 -66
- package/dist/PostMessagePreviewSnapshots-Dr7CEAiM.mjs.map +0 -1
- package/dist/PostMessageRefreshMutations-CWb9UqSy.mjs +0 -66
- package/dist/PostMessageRefreshMutations-CWb9UqSy.mjs.map +0 -1
- package/dist/PostMessageSchema-BVFyZOH1.mjs +0 -514
- package/dist/PostMessageSchema-BVFyZOH1.mjs.map +0 -1
- package/dist/PostMessageTelemetry-CSluBvcC.mjs +0 -51
- package/dist/PostMessageTelemetry-CSluBvcC.mjs.map +0 -1
- package/dist/PresentationToolGrantsCheck-4zo266wj.mjs +0 -3919
- package/dist/PresentationToolGrantsCheck-4zo266wj.mjs.map +0 -1
- package/dist/QRCodeSVG-D6VfGEbM.mjs +0 -648
- package/dist/QRCodeSVG-D6VfGEbM.mjs.map +0 -1
- package/dist/SourceContext-T8zcpOpp.mjs +0 -33
- package/dist/SourceContext-T8zcpOpp.mjs.map +0 -1
- package/dist/StructureToolProvider-BMLps71e.mjs +0 -13815
- package/dist/StructureToolProvider-BMLps71e.mjs.map +0 -1
- package/dist/Subject-DP0DoUP_.mjs +0 -108
- package/dist/Subject-DP0DoUP_.mjs.map +0 -1
- package/dist/ViteDevServerStopped-DdibXNvO.mjs +0 -44
- package/dist/ViteDevServerStopped-DdibXNvO.mjs.map +0 -1
- package/dist/_createContext.mjs +0 -36
- package/dist/_createContext.mjs.map +0 -1
- package/dist/_singletons.mjs +0 -195
- package/dist/_singletons.mjs.map +0 -1
- package/dist/browser-BzDH2pyp.mjs +0 -455
- package/dist/browser-BzDH2pyp.mjs.map +0 -1
- package/dist/browser-DWCoWoiH.mjs +0 -3988
- package/dist/browser-DWCoWoiH.mjs.map +0 -1
- package/dist/debounceTime-BeoKrERE.mjs +0 -130
- package/dist/debounceTime-BeoKrERE.mjs.map +0 -1
- package/dist/desk.mjs +0 -52
- package/dist/desk.mjs.map +0 -1
- package/dist/first-Di4GZDIY.mjs +0 -42
- package/dist/first-Di4GZDIY.mjs.map +0 -1
- package/dist/get-psIoeD-z.mjs +0 -327
- package/dist/get-psIoeD-z.mjs.map +0 -1
- package/dist/hooks-4sgcd521.mjs +0 -90
- package/dist/hooks-4sgcd521.mjs.map +0 -1
- package/dist/index-9PJcXUTv.mjs +0 -87
- package/dist/index-9PJcXUTv.mjs.map +0 -1
- package/dist/index-ByFK-IwD.mjs +0 -528
- package/dist/index-ByFK-IwD.mjs.map +0 -1
- package/dist/index-C2OAo3To.mjs +0 -7079
- package/dist/index-C2OAo3To.mjs.map +0 -1
- package/dist/index-C3OvVLVP.mjs +0 -4636
- package/dist/index-C3OvVLVP.mjs.map +0 -1
- package/dist/index-DBPVDKJN.mjs +0 -1198
- package/dist/index-DBPVDKJN.mjs.map +0 -1
- package/dist/index-DkvUNBNf.mjs +0 -73
- package/dist/index-DkvUNBNf.mjs.map +0 -1
- package/dist/index-Sp9w8lMg.mjs +0 -118
- package/dist/index-Sp9w8lMg.mjs.map +0 -1
- package/dist/index.browser-BxT2qp9y.mjs +0 -104
- package/dist/index.browser-BxT2qp9y.mjs.map +0 -1
- package/dist/index.mjs +0 -129019
- package/dist/index.mjs.map +0 -1
- package/dist/isObservable-ByOheaM8.mjs +0 -8
- package/dist/isObservable-ByOheaM8.mjs.map +0 -1
- package/dist/never-ChKjLemk.mjs +0 -6
- package/dist/never-ChKjLemk.mjs.map +0 -1
- package/dist/pane-C4tskUPg.mjs +0 -5
- package/dist/pane-C4tskUPg.mjs.map +0 -1
- package/dist/pane-Dhx8FvsK.mjs +0 -5
- package/dist/pane-Dhx8FvsK.mjs.map +0 -1
- package/dist/presentation-CSS9GR9X.mjs +0 -984
- package/dist/presentation-CSS9GR9X.mjs.map +0 -1
- package/dist/presentation.mjs +0 -14
- package/dist/presentation.mjs.map +0 -1
- package/dist/resources-4cbq8YlR.mjs +0 -124
- package/dist/resources-4cbq8YlR.mjs.map +0 -1
- package/dist/resources-BVETz6Ur.mjs +0 -57
- package/dist/resources-BVETz6Ur.mjs.map +0 -1
- package/dist/resources-D4AaU75F.mjs +0 -434
- package/dist/resources-D4AaU75F.mjs.map +0 -1
- package/dist/resources-Dc-6ZcPg.mjs +0 -157
- package/dist/resources-Dc-6ZcPg.mjs.map +0 -1
- package/dist/resources-DgU0prBM.mjs +0 -179
- package/dist/resources-DgU0prBM.mjs.map +0 -1
- package/dist/resources-MD8RsYhH.mjs +0 -288
- package/dist/resources-MD8RsYhH.mjs.map +0 -1
- package/dist/router.mjs +0 -689
- package/dist/router.mjs.map +0 -1
- package/dist/share-bcOpIdQz.mjs +0 -71
- package/dist/share-bcOpIdQz.mjs.map +0 -1
- package/dist/shareReplay-Dj1O6fKV.mjs +0 -43
- package/dist/shareReplay-Dj1O6fKV.mjs.map +0 -1
- package/dist/stegaEncodeSourceMap-DXdUZQye.mjs +0 -342
- package/dist/stegaEncodeSourceMap-DXdUZQye.mjs.map +0 -1
- package/dist/structure.mjs +0 -56
- package/dist/structure.mjs.map +0 -1
- package/dist/takeUntil-CgZP1bze.mjs +0 -111
- package/dist/takeUntil-CgZP1bze.mjs.map +0 -1
- package/dist/v4-C78sE4Gb.mjs +0 -27082
- package/dist/v4-C78sE4Gb.mjs.map +0 -1
- package/dist/version-D7UZEoYI.mjs +0 -5
- package/dist/version-D7UZEoYI.mjs.map +0 -1
@@ -144,6 +144,10 @@ ${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
|
+
}
|
147
151
|
function getPossibleDocumentComponentLocations(studioRootPath) {
|
148
152
|
return [path__default.default.join(studioRootPath, "_document.js"), path__default.default.join(studioRootPath, "_document.tsx")];
|
149
153
|
}
|
@@ -304,7 +308,7 @@ function sanityBuildEntries(options) {
|
|
304
308
|
this.emitFile({
|
305
309
|
type: "asset",
|
306
310
|
fileName: "index.html",
|
307
|
-
source: await renderDocument({
|
311
|
+
source: decorateIndexWithBridgeScript(await renderDocument({
|
308
312
|
monorepo,
|
309
313
|
studioRootPath: cwd,
|
310
314
|
importMap,
|
@@ -314,7 +318,7 @@ function sanityBuildEntries(options) {
|
|
314
318
|
css
|
315
319
|
},
|
316
320
|
isCoreApp
|
317
|
-
})
|
321
|
+
}))
|
318
322
|
});
|
319
323
|
}
|
320
324
|
};
|
@@ -594,7 +598,7 @@ async function writeSanityRuntime({
|
|
594
598
|
});
|
595
599
|
async function renderAndWriteDocument() {
|
596
600
|
debug("Rendering document template");
|
597
|
-
const indexHtml = decorateIndexWithAutoGeneratedWarning(await renderDocument({
|
601
|
+
const indexHtml = decorateIndexWithBridgeScript(decorateIndexWithAutoGeneratedWarning(await renderDocument({
|
598
602
|
studioRootPath: cwd,
|
599
603
|
monorepo,
|
600
604
|
props: {
|
@@ -602,7 +606,7 @@ async function writeSanityRuntime({
|
|
602
606
|
basePath: basePath || "/"
|
603
607
|
},
|
604
608
|
isCoreApp
|
605
|
-
}));
|
609
|
+
})));
|
606
610
|
debug("Writing index.html to runtime directory"), await fs__default$1.default.writeFile(path__default.default.join(runtimeDir, "index.html"), indexHtml);
|
607
611
|
}
|
608
612
|
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 isCoreApp?: boolean\n}\n\nexport function renderDocument(options: RenderDocumentOptions): Promise<string> {\n return new Promise((resolve, reject) => {\n if (!useThreads) {\n resolve(\n getDocumentHtml(\n options.studioRootPath,\n options.props,\n options.importMap,\n options.isCoreApp,\n ),\n )\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, isCoreApp}: RenderDocumentOptions =\n 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, isCoreApp)\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 isCoreApp?: boolean,\n): string {\n const Document = getDocumentComponent(studioRootPath, isCoreApp)\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, isCoreApp?: boolean) {\n debug('Loading default document component from `sanity` module')\n\n const {BasicDocument} = __DEV__\n ? require('../../../core/components/BasicDocument')\n : require('sanity')\n\n const {DefaultDocument} = __DEV__\n ? require('../../../core/components/DefaultDocument')\n : require('sanity')\n\n const Document = isCoreApp ? BasicDocument : DefaultDocument\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 Document\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 isEntry: boolean\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 isCoreApp?: boolean\n}): Plugin {\n const {cwd, monorepo, basePath, importMap, isCoreApp} = 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 isCoreApp,\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 isCoreApp?: boolean\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 isCoreApp,\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, isCoreApp}),\n ],\n envPrefix: isCoreApp ? 'VITE_' : '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\nconst coreAppEntryModule = `\n// This file is auto-generated on 'sanity dev'\n// Modifications to this file is automatically discarded\nimport {createRoot} from 'react-dom/client'\nimport {createElement} from 'react'\nimport App from %APP_LOCATION%\n\nconst root = createRoot(document.getElementById('root'))\nconst element = createElement(App)\nroot.render(element)\n`\n\nexport function getEntryModule(options: {\n reactStrictMode: boolean\n relativeConfigLocation: string | null\n basePath?: string\n appLocation?: string\n isCoreApp?: boolean\n}): string {\n const {reactStrictMode, relativeConfigLocation, basePath, appLocation, isCoreApp} = options\n\n if (isCoreApp) {\n return coreAppEntryModule.replace(/%APP_LOCATION%/, JSON.stringify(appLocation || './src/App'))\n }\n\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 appLocation?: string\n isCoreApp?: boolean\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 appLocation,\n isCoreApp,\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 isCoreApp,\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 let relativeConfigLocation: string | null = null\n if (!isCoreApp) {\n const studioConfigPath = await getSanityStudioConfigPath(cwd)\n relativeConfigLocation = studioConfigPath ? path.relative(runtimeDir, studioConfigPath) : null\n }\n\n const relativeAppLocation = cwd ? path.resolve(cwd, appLocation || './src/App') : appLocation\n const appJsContent = getEntryModule({\n reactStrictMode,\n relativeConfigLocation,\n basePath,\n appLocation: relativeAppLocation,\n isCoreApp,\n })\n await fs.writeFile(path.join(runtimeDir, 'app.js'), appJsContent)\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","isCoreApp","__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","BasicDocument","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","coreAppEntryModule","getEntryModule","reactStrictMode","relativeConfigLocation","appLocation","Boolean","getSanityStudioConfigPath","configPaths","availableConfigs","all","configPath","exists","fileExists","filePath","stat","then","writeSanityRuntime","watch","runtimeDir","mkdir","recursive","renderAndWriteDocument","indexHtml","writeFile","chokidar","studioConfigPath","relativeAppLocation","appJsContent"],"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;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A,EAAAA,CACD;AACD,QAAM0F,cAAAA,QAAGyI,UAAUtR,cAAAA,QAAKsB,KAAK2P,YAAY,QAAQ,GAAGS,YAAY;AAClE;;;;;;;;"}
|
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 isCoreApp?: boolean\n}\n\nexport function renderDocument(options: RenderDocumentOptions): Promise<string> {\n return new Promise((resolve, reject) => {\n if (!useThreads) {\n resolve(\n getDocumentHtml(\n options.studioRootPath,\n options.props,\n options.importMap,\n options.isCoreApp,\n ),\n )\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, isCoreApp}: RenderDocumentOptions =\n 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, isCoreApp)\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 isCoreApp?: boolean,\n): string {\n const Document = getDocumentComponent(studioRootPath, isCoreApp)\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, isCoreApp?: boolean) {\n debug('Loading default document component from `sanity` module')\n\n const {BasicDocument} = __DEV__\n ? require('../../../core/components/BasicDocument')\n : require('sanity')\n\n const {DefaultDocument} = __DEV__\n ? require('../../../core/components/DefaultDocument')\n : require('sanity')\n\n const Document = isCoreApp ? BasicDocument : DefaultDocument\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 Document\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 {decorateIndexWithBridgeScript, 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 isEntry: boolean\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 isCoreApp?: boolean\n}): Plugin {\n const {cwd, monorepo, basePath, importMap, isCoreApp} = 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: decorateIndexWithBridgeScript(\n await renderDocument({\n monorepo,\n studioRootPath: cwd,\n importMap,\n props: {\n basePath,\n entryPath,\n css,\n },\n isCoreApp,\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 isCoreApp?: boolean\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 isCoreApp,\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, isCoreApp}),\n ],\n envPrefix: isCoreApp ? 'VITE_' : '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\nconst coreAppEntryModule = `\n// This file is auto-generated on 'sanity dev'\n// Modifications to this file is automatically discarded\nimport {createRoot} from 'react-dom/client'\nimport {createElement} from 'react'\nimport App from %APP_LOCATION%\n\nconst root = createRoot(document.getElementById('root'))\nconst element = createElement(App)\nroot.render(element)\n`\n\nexport function getEntryModule(options: {\n reactStrictMode: boolean\n relativeConfigLocation: string | null\n basePath?: string\n appLocation?: string\n isCoreApp?: boolean\n}): string {\n const {reactStrictMode, relativeConfigLocation, basePath, appLocation, isCoreApp} = options\n\n if (isCoreApp) {\n return coreAppEntryModule.replace(/%APP_LOCATION%/, JSON.stringify(appLocation || './src/App'))\n }\n\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 appLocation?: string\n isCoreApp?: boolean\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 appLocation,\n isCoreApp,\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 isCoreApp,\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 let relativeConfigLocation: string | null = null\n if (!isCoreApp) {\n const studioConfigPath = await getSanityStudioConfigPath(cwd)\n relativeConfigLocation = studioConfigPath ? path.relative(runtimeDir, studioConfigPath) : null\n }\n\n const relativeAppLocation = cwd ? path.resolve(cwd, appLocation || './src/App') : appLocation\n const appJsContent = getEntryModule({\n reactStrictMode,\n relativeConfigLocation,\n basePath,\n appLocation: relativeAppLocation,\n isCoreApp,\n })\n await fs.writeFile(path.join(runtimeDir, 'app.js'), appJsContent)\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","isCoreApp","__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","BasicDocument","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","coreAppEntryModule","getEntryModule","reactStrictMode","relativeConfigLocation","appLocation","Boolean","getSanityStudioConfigPath","configPaths","availableConfigs","all","configPath","exists","fileExists","filePath","stat","then","writeSanityRuntime","watch","runtimeDir","mkdir","recursive","renderAndWriteDocument","indexHtml","writeFile","chokidar","studioConfigPath","relativeAppLocation","appJsContent"],"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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"3.74.2-coreui.20+4d53d7e9e9",
|
4
4
|
"description": "Sanity is a real-time content infrastructure with a scalable, hosted backend featuring a Graph Oriented Query Language (GROQ), asset pipelines and fast edge caches",
|
5
5
|
"keywords": [
|
6
6
|
"sanity",
|
@@ -160,11 +160,11 @@
|
|
160
160
|
"@rexxars/react-json-inspector": "^9.0.1",
|
161
161
|
"@sanity/asset-utils": "^2.0.6",
|
162
162
|
"@sanity/bifur-client": "^0.4.1",
|
163
|
-
"@sanity/cli": "3.74.2-
|
163
|
+
"@sanity/cli": "3.74.2-coreui.20+4d53d7e9e9",
|
164
164
|
"@sanity/client": "^6.27.2",
|
165
165
|
"@sanity/color": "^3.0.0",
|
166
166
|
"@sanity/comlink": "^3.0.1",
|
167
|
-
"@sanity/diff": "3.74.2-
|
167
|
+
"@sanity/diff": "3.74.2-coreui.20+4d53d7e9e9",
|
168
168
|
"@sanity/diff-match-patch": "^3.1.1",
|
169
169
|
"@sanity/diff-patch": "^5.0.0",
|
170
170
|
"@sanity/eventsource": "^5.0.0",
|
@@ -174,15 +174,15 @@
|
|
174
174
|
"@sanity/import": "^3.37.9",
|
175
175
|
"@sanity/insert-menu": "1.0.20",
|
176
176
|
"@sanity/logos": "^2.1.13",
|
177
|
-
"@sanity/migrate": "3.74.2-
|
178
|
-
"@sanity/mutator": "3.74.2-
|
177
|
+
"@sanity/migrate": "3.74.2-coreui.20+4d53d7e9e9",
|
178
|
+
"@sanity/mutator": "3.74.2-coreui.20+4d53d7e9e9",
|
179
179
|
"@sanity/presentation-comlink": "^1.0.4",
|
180
180
|
"@sanity/preview-url-secret": "^2.1.4",
|
181
|
-
"@sanity/schema": "3.74.2-
|
181
|
+
"@sanity/schema": "3.74.2-coreui.20+4d53d7e9e9",
|
182
182
|
"@sanity/telemetry": "^0.7.7",
|
183
|
-
"@sanity/types": "3.74.2-
|
183
|
+
"@sanity/types": "3.74.2-coreui.20+4d53d7e9e9",
|
184
184
|
"@sanity/ui": "^2.11.8",
|
185
|
-
"@sanity/util": "3.74.2-
|
185
|
+
"@sanity/util": "3.74.2-coreui.20+4d53d7e9e9",
|
186
186
|
"@sanity/uuid": "^3.0.2",
|
187
187
|
"@sentry/react": "^8.33.0",
|
188
188
|
"@tanstack/react-table": "^8.16.0",
|
@@ -280,7 +280,7 @@
|
|
280
280
|
"@repo/dev-aliases": "3.74.1",
|
281
281
|
"@repo/package.config": "3.74.1",
|
282
282
|
"@repo/test-config": "3.74.1",
|
283
|
-
"@sanity/codegen": "3.74.2-
|
283
|
+
"@sanity/codegen": "3.74.2-coreui.20+4d53d7e9e9",
|
284
284
|
"@sanity/generate-help-url": "^3.0.0",
|
285
285
|
"@sanity/pkg-utils": "6.13.4",
|
286
286
|
"@sanity/tsdoc": "1.0.169",
|
@@ -305,7 +305,6 @@
|
|
305
305
|
"@types/semver": "^6.2.3",
|
306
306
|
"@types/tar-fs": "^2.0.1",
|
307
307
|
"@vitejs/plugin-react": "^4.3.4",
|
308
|
-
"@vitest/expect": "^3.0.5",
|
309
308
|
"@vvo/tzdb": "6.137.0",
|
310
309
|
"babel-plugin-react-compiler": "19.0.0-beta-714736e-20250131",
|
311
310
|
"blob-polyfill": "^9.0.20240710",
|
@@ -325,5 +324,5 @@
|
|
325
324
|
"engines": {
|
326
325
|
"node": ">=18"
|
327
326
|
},
|
328
|
-
"gitHead": "
|
327
|
+
"gitHead": "4d53d7e9e9ef2f9d55c07ea213cd875931058d32"
|
329
328
|
}
|
@@ -119,6 +119,18 @@ export function decorateIndexWithAutoGeneratedWarning(template: string): string
|
|
119
119
|
return template.replace(/<head/, `\n<!--\n${autoGeneratedWarning}\n-->\n<head`)
|
120
120
|
}
|
121
121
|
|
122
|
+
/**
|
123
|
+
* Decorates the given HTML template with a script
|
124
|
+
* tag that loads the bridge component to communicate
|
125
|
+
* with core-ui.
|
126
|
+
*/
|
127
|
+
export function decorateIndexWithBridgeScript(template: string): string {
|
128
|
+
return template.replace(
|
129
|
+
'</head>',
|
130
|
+
'<script src="https://core.sanity-cdn.com/bridge.js" async type="module"></script>\n</head>',
|
131
|
+
)
|
132
|
+
}
|
133
|
+
|
122
134
|
export function getPossibleDocumentComponentLocations(studioRootPath: string): string[] {
|
123
135
|
return [path.join(studioRootPath, '_document.js'), path.join(studioRootPath, '_document.tsx')]
|
124
136
|
}
|
@@ -7,6 +7,7 @@ import {debug as serverDebug} from './debug'
|
|
7
7
|
import {getEntryModule} from './getEntryModule'
|
8
8
|
import {
|
9
9
|
decorateIndexWithAutoGeneratedWarning,
|
10
|
+
decorateIndexWithBridgeScript,
|
10
11
|
getPossibleDocumentComponentLocations,
|
11
12
|
renderDocument,
|
12
13
|
} from './renderDocument'
|
@@ -48,16 +49,18 @@ export async function writeSanityRuntime({
|
|
48
49
|
|
49
50
|
async function renderAndWriteDocument() {
|
50
51
|
debug('Rendering document template')
|
51
|
-
const indexHtml =
|
52
|
-
|
53
|
-
|
54
|
-
|
55
|
-
|
56
|
-
|
57
|
-
|
58
|
-
|
59
|
-
|
60
|
-
|
52
|
+
const indexHtml = decorateIndexWithBridgeScript(
|
53
|
+
decorateIndexWithAutoGeneratedWarning(
|
54
|
+
await renderDocument({
|
55
|
+
studioRootPath: cwd,
|
56
|
+
monorepo,
|
57
|
+
props: {
|
58
|
+
entryPath: `/${path.relative(cwd, path.join(runtimeDir, 'app.js'))}`,
|
59
|
+
basePath: basePath || '/',
|
60
|
+
},
|
61
|
+
isCoreApp,
|
62
|
+
}),
|
63
|
+
),
|
61
64
|
)
|
62
65
|
|
63
66
|
debug('Writing index.html to runtime directory')
|
@@ -1,6 +1,6 @@
|
|
1
1
|
import {type ChunkMetadata, type Plugin} from 'vite'
|
2
2
|
|
3
|
-
import {renderDocument} from '../renderDocument'
|
3
|
+
import {decorateIndexWithBridgeScript, renderDocument} from '../renderDocument'
|
4
4
|
import {type SanityMonorepo} from '../sanityMonorepo'
|
5
5
|
|
6
6
|
interface ViteOutputBundle {
|
@@ -86,17 +86,19 @@ export function sanityBuildEntries(options: {
|
|
86
86
|
this.emitFile({
|
87
87
|
type: 'asset',
|
88
88
|
fileName: 'index.html',
|
89
|
-
source:
|
90
|
-
|
91
|
-
|
92
|
-
|
93
|
-
|
94
|
-
|
95
|
-
|
96
|
-
|
97
|
-
|
98
|
-
|
99
|
-
|
89
|
+
source: decorateIndexWithBridgeScript(
|
90
|
+
await renderDocument({
|
91
|
+
monorepo,
|
92
|
+
studioRootPath: cwd,
|
93
|
+
importMap,
|
94
|
+
props: {
|
95
|
+
basePath,
|
96
|
+
entryPath,
|
97
|
+
css,
|
98
|
+
},
|
99
|
+
isCoreApp,
|
100
|
+
}),
|
101
|
+
),
|
100
102
|
})
|
101
103
|
},
|
102
104
|
}
|
@@ -1,19 +0,0 @@
|
|
1
|
-
import { c as m, u as s } from "./presentation-CSS9GR9X.mjs";
|
2
|
-
import { memo as n, useEffect as i } from "react";
|
3
|
-
import { u as f } from "./DisplayedDocumentBroadcaster-DfHPxc7C.mjs";
|
4
|
-
function v(a) {
|
5
|
-
const e = m(7), t = f(), l = s(!1);
|
6
|
-
let u;
|
7
|
-
e[0] !== a.value || e[1] !== t ? (u = () => {
|
8
|
-
const r = setTimeout(() => t == null ? void 0 : t(a.value), 10);
|
9
|
-
return () => clearTimeout(r);
|
10
|
-
}, e[0] = a.value, e[1] = t, e[2] = u) : u = e[2];
|
11
|
-
const c = l == null ? void 0 : l.perspective;
|
12
|
-
let o;
|
13
|
-
return e[3] !== a.value || e[4] !== t || e[5] !== c ? (o = [c, a.value, t], e[3] = a.value, e[4] = t, e[5] = c, e[6] = o) : o = e[6], i(u, o), null;
|
14
|
-
}
|
15
|
-
var y = n(v);
|
16
|
-
export {
|
17
|
-
y as default
|
18
|
-
};
|
19
|
-
//# sourceMappingURL=BroadcastDisplayedDocument-BHYI8o6u.mjs.map
|
@@ -1 +0,0 @@
|
|
1
|
-
{"version":3,"file":"BroadcastDisplayedDocument-BHYI8o6u.mjs","sources":["../../../node_modules/.pnpm/@sanity+presentation@1.19.14-release.0_@emotion+is-prop-valid@1.3.1_@sanity+color@3.0.6_debug_vqegs67ktulknun2leapg5jvli/node_modules/@sanity/presentation/dist/_chunks-es/BroadcastDisplayedDocument.js"],"sourcesContent":["import { c } from \"react-compiler-runtime\";\nimport { memo, useEffect } from \"react\";\nimport { usePresentationParams } from \"./index.js\";\nimport { useDisplayedDocumentBroadcaster } from \"./DisplayedDocumentBroadcaster.js\";\nfunction BroadcastDisplayedDocument(props) {\n const $ = c(7), setDisplayedDocument = useDisplayedDocumentBroadcaster(), params = usePresentationParams(!1);\n let t0;\n $[0] !== props.value || $[1] !== setDisplayedDocument ? (t0 = () => {\n const timeout = setTimeout(() => setDisplayedDocument?.(props.value), 10);\n return () => clearTimeout(timeout);\n }, $[0] = props.value, $[1] = setDisplayedDocument, $[2] = t0) : t0 = $[2];\n const t1 = params?.perspective;\n let t2;\n return $[3] !== props.value || $[4] !== setDisplayedDocument || $[5] !== t1 ? (t2 = [t1, props.value, setDisplayedDocument], $[3] = props.value, $[4] = setDisplayedDocument, $[5] = t1, $[6] = t2) : t2 = $[6], useEffect(t0, t2), null;\n}\nvar BroadcastDisplayedDocument$1 = memo(BroadcastDisplayedDocument);\nexport {\n BroadcastDisplayedDocument$1 as default\n};\n//# sourceMappingURL=BroadcastDisplayedDocument.js.map\n"],"names":["BroadcastDisplayedDocument","props","$","c","setDisplayedDocument","useDisplayedDocumentBroadcaster","params","usePresentationParams","t0","timeout","t1","t2","useEffect","BroadcastDisplayedDocument$1","memo"],"mappings":";;;AAIA,SAASA,EAA2BC,GAAO;AACzC,QAAMC,IAAIC,EAAE,CAAC,GAAGC,IAAuBC,KAAmCC,IAASC,EAAsB,EAAE;AAC3G,MAAIC;AACJ,EAAAN,EAAE,CAAC,MAAMD,EAAM,SAASC,EAAE,CAAC,MAAME,KAAwBI,IAAK,MAAM;AAClE,UAAMC,IAAU,WAAW,MAAML,KAAA,gBAAAA,EAAuBH,EAAM,QAAQ,EAAE;AACxE,WAAO,MAAM,aAAaQ,CAAO;AAAA,EACrC,GAAKP,EAAE,CAAC,IAAID,EAAM,OAAOC,EAAE,CAAC,IAAIE,GAAsBF,EAAE,CAAC,IAAIM,KAAMA,IAAKN,EAAE,CAAC;AACzE,QAAMQ,IAAKJ,KAAA,gBAAAA,EAAQ;AACnB,MAAIK;AACJ,SAAOT,EAAE,CAAC,MAAMD,EAAM,SAASC,EAAE,CAAC,MAAME,KAAwBF,EAAE,CAAC,MAAMQ,KAAMC,IAAK,CAACD,GAAIT,EAAM,OAAOG,CAAoB,GAAGF,EAAE,CAAC,IAAID,EAAM,OAAOC,EAAE,CAAC,IAAIE,GAAsBF,EAAE,CAAC,IAAIQ,GAAIR,EAAE,CAAC,IAAIS,KAAMA,IAAKT,EAAE,CAAC,GAAGU,EAAUJ,GAAIG,CAAE,GAAG;AACtO;AACG,IAACE,IAA+BC,EAAKd,CAA0B;","x_google_ignoreList":[0]}
|