@valbuild/tanstack-build 0.150.12 → 0.153.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,7 +3,7 @@
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  var regeneratorValues = require('./regeneratorValues-f5d7ce8a.cjs.dev.js');
6
- var projectPaths = require('./projectPaths-f222255a.cjs.dev.js');
6
+ var projectPaths = require('./projectPaths-cb474a60.cjs.dev.js');
7
7
  var tailwindcss = require('tailwindcss');
8
8
  var artifactKeys = require('./artifactKeys-ad3e41fc.cjs.dev.js');
9
9
 
@@ -1210,7 +1210,7 @@ var packageJson = {
1210
1210
  url: "git+https://github.com/valbuild/val.git"
1211
1211
  },
1212
1212
  license: "MIT",
1213
- version: "0.150.12",
1213
+ version: "0.153.0",
1214
1214
  sideEffects: false,
1215
1215
  main: "dist/valbuild-tanstack-build.cjs.js",
1216
1216
  module: "dist/valbuild-tanstack-build.esm.js",
@@ -1374,7 +1374,14 @@ var LEGACY_CONTROL_HOST = "platform.internal";
1374
1374
  * existed -- which is every project already published, since a build in a tab
1375
1375
  * rewrites single lines of its `val.server.ts` and never regenerates it.
1376
1376
  */
1377
- var PROPOSAL_BLOCK = "/*\n * THE PROPOSAL this isolate serves the address of, when it does: its name and\n * content branch, and the content it has saved (`VAL_OVERLAY`: the save's\n * commit, its Source by module and its `.val.ts` text by path). Val reads\n * that Source instead of the bundle's, commits a save to the proposal, and\n * names the save as its position. valbuild/home `docs/proposals.md`,\n * \"Saving\".\n *\n * Parsed here rather than with `proposalFromEnv` from @valbuild/server,\n * because this file is compiled against whatever @valbuild/tanstack the\n * PROJECT installed, and one from before proposals has no such export -- it\n * also ignores the `proposal` key below, and serves the base build, which\n * is the best an old app can do. A snapshot that does not parse is thrown,\n * not served as the base: a reviewer must not be shown the wrong content as\n * though it were the proposal.\n */\nconst proposal = (() => {\n const name = secret(\"VAL_PROPOSAL\");\n const branch = secret(\"VAL_BRANCH\");\n if (!name || !branch) return undefined;\n const overlay: {\n commit?: string | null;\n modules?: Record<string, unknown>;\n files?: Record<string, string>;\n } = JSON.parse(secret(\"VAL_OVERLAY\") ?? \"{}\");\n return {\n name,\n branch,\n commit: overlay.commit ?? null,\n modules: overlay.modules ?? {},\n files: overlay.files ?? {},\n };\n})();\n";
1377
+ var PROPOSAL_BLOCK = "/*\n * THE PROPOSAL this isolate serves the address of, when it does: its name and\n * content branch, and the content it has saved (`VAL_OVERLAY`: the save's\n * commit, its Source by module, its `.val.ts` text by path, and which\n * modules' code is staged). Val reads that Source instead of the bundle's,\n * commits a save to the proposal, and names the save as its position. And\n * which staging this build was made of (`VAL_BUILD_INPUTS`), so Val can tell\n * a staged module this build evaluated from one staged after it.\n * valbuild/home `docs/proposals.md`, \"Saving\" and \"Staged schemas\".\n *\n * Parsed here rather than with `proposalFromEnv` from @valbuild/server,\n * because this file is compiled against whatever @valbuild/tanstack the\n * PROJECT installed, and one from before proposals has no such export -- it\n * also ignores the `proposal` key below, and serves the base build, which\n * is the best an old app can do. A snapshot that does not parse is thrown,\n * not served as the base: a reviewer must not be shown the wrong content as\n * though it were the proposal.\n */\nconst proposal = (() => {\n const name = secret(\"VAL_PROPOSAL\");\n const branch = secret(\"VAL_BRANCH\");\n if (!name || !branch) return undefined;\n const overlay: {\n commit?: string | null;\n modules?: Record<string, unknown>;\n files?: Record<string, string>;\n staged?: Record<string, string>;\n } = JSON.parse(secret(\"VAL_OVERLAY\") ?? \"{}\");\n // Checked as `proposalFromEnv` checks them: read wrong, a save would\n // apply to staged code as though the build had it, or the other way round.\n const staged = overlay.staged ?? {};\n for (const [path, version] of Object.entries(staged)) {\n if (\n !path.startsWith(\"/\") ||\n typeof version !== \"string\" ||\n !version.startsWith(\"staged:\")\n ) {\n throw new Error(\n `Val: proposal ${name}: VAL_OVERLAY's staged must name module files with staged:<inputs> versions (${JSON.stringify(path)})`,\n );\n }\n }\n const inputs = secret(\"VAL_BUILD_INPUTS\");\n if (inputs && !/^[0-9a-f]{64}$/.test(inputs)) {\n throw new Error(\n `Val: proposal ${name}: VAL_BUILD_INPUTS is not a build's staged inputs (64 hex)`,\n );\n }\n return {\n name,\n branch,\n commit: overlay.commit ?? null,\n modules: overlay.modules ?? {},\n files: overlay.files ?? {},\n staged,\n buildInputs: inputs || null,\n };\n})();\n";
1378
+ /**
1379
+ * {@link PROPOSAL_BLOCK} as it was generated before it read which modules
1380
+ * are staged and what the build was made of: rewritten to the current block
1381
+ * by {@link rebakeProposal}, exactly, so a site wired before it learns both
1382
+ * at its next build. Never generated.
1383
+ */
1384
+ var PROPOSAL_BLOCK_V1 = "/*\n * THE PROPOSAL this isolate serves the address of, when it does: its name and\n * content branch, and the content it has saved (`VAL_OVERLAY`: the save's\n * commit, its Source by module and its `.val.ts` text by path). Val reads\n * that Source instead of the bundle's, commits a save to the proposal, and\n * names the save as its position. valbuild/home `docs/proposals.md`,\n * \"Saving\".\n *\n * Parsed here rather than with `proposalFromEnv` from @valbuild/server,\n * because this file is compiled against whatever @valbuild/tanstack the\n * PROJECT installed, and one from before proposals has no such export -- it\n * also ignores the `proposal` key below, and serves the base build, which\n * is the best an old app can do. A snapshot that does not parse is thrown,\n * not served as the base: a reviewer must not be shown the wrong content as\n * though it were the proposal.\n */\nconst proposal = (() => {\n const name = secret(\"VAL_PROPOSAL\");\n const branch = secret(\"VAL_BRANCH\");\n if (!name || !branch) return undefined;\n const overlay: {\n commit?: string | null;\n modules?: Record<string, unknown>;\n files?: Record<string, string>;\n } = JSON.parse(secret(\"VAL_OVERLAY\") ?? \"{}\");\n return {\n name,\n branch,\n commit: overlay.commit ?? null,\n modules: overlay.modules ?? {},\n files: overlay.files ?? {},\n };\n})();\n";
1378
1385
  /**
1379
1386
  * THE CONTENT VERSION the site serves, when it differs from the one this build
1380
1387
  * bundles (\`VAL_CONTENT\`). See valbuild/home \`docs/hosted-publishing.md\`,
@@ -1382,6 +1389,16 @@ var PROPOSAL_BLOCK = "/*\n * THE PROPOSAL this isolate serves the address of, wh
1382
1389
  * arrives in files wired before it the same way: {@link rebakeContent}.
1383
1390
  */
1384
1391
  var CONTENT_BLOCK = "/*\n * THE CONTENT VERSION the site serves, when the platform says it differs from\n * the one this build bundles (`VAL_CONTENT`: its id, the publish that made\n * it, and the Source and Val files that differ). Val reads that Source instead\n * of the bundle's and names that publish as its position. valbuild/home\n * `docs/hosted-publishing.md`, step 2.\n *\n * Parsed here, like the proposal above, because this file is compiled against\n * whatever @valbuild/tanstack the PROJECT installed. One from before content\n * versions ignores the `contentVersion` key below and serves the bundle --\n * and never says it applied the version, which is how the platform knows not\n * to serve this build a version it does not bundle. A version that does not\n * parse is thrown, not served as the bundle.\n *\n * A version too large for one variable names others under `refs`\n * (`\"env://VAL_CONTENT_1\"`), each holding one module's Source or one file's\n * text. Only `refs` is resolved, never a string inside Source, and only\n * `VAL_CONTENT_<n>` is read: Source is text editors write, and resolving a\n * reference in there would read `VAL_SECRET` into a page. The same rules as\n * `contentFromEnv` in @valbuild/server.\n */\nconst contentVersion = (() => {\n const handed = secret(\"VAL_CONTENT\");\n if (!handed) return undefined;\n const isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n const parsed: unknown = JSON.parse(handed);\n if (!isRecord(parsed)) throw new Error(\"Val: VAL_CONTENT is not an object\");\n const id = parsed.id;\n if (typeof id !== \"string\" || id === \"\") {\n throw new Error(\"Val: VAL_CONTENT has no id\");\n }\n const where = \"Val: content version \" + id;\n const nullableString = (key: string): string | null => {\n const value = parsed[key] ?? null;\n if (value !== null && typeof value !== \"string\") {\n throw new Error(where + \": \" + key + \" must be a string or null\");\n }\n return value;\n };\n const record = (value: unknown, name: string): Record<string, unknown> => {\n const found = value ?? {};\n if (!isRecord(found)) throw new Error(where + \": \" + name + \" must be an object\");\n return found;\n };\n const job = nullableString(\"job\");\n const commit = nullableString(\"commit\");\n const modules: Record<string, unknown> = { ...record(parsed.modules, \"modules\") };\n const filesIn = record(parsed.files, \"files\");\n const files: Record<string, string> = {};\n for (const [path, text] of Object.entries(filesIn)) {\n if (typeof text === \"string\") files[path] = text;\n }\n const refs = record(parsed.refs, \"refs\");\n const read = (kind: string, path: string, ref: unknown): string => {\n const at = where + \": refs.\" + kind + \"[\" + path + \"]\";\n if (typeof ref !== \"string\" || !ref.startsWith(\"env://\")) {\n throw new Error(at + \" is \" + String(ref) + \": only env://VAL_CONTENT_<n> is read\");\n }\n const name = ref.slice(\"env://\".length);\n if (!/^VAL_CONTENT_[0-9]+$/.test(name)) {\n throw new Error(at + \" names \" + name + \": only VAL_CONTENT_<n> is read\");\n }\n const value = secret(name);\n if (value === undefined) {\n throw new Error(at + \" names \" + name + \", which is not set\");\n }\n return value;\n };\n for (const [path, ref] of Object.entries(record(refs.modules, \"refs.modules\"))) {\n if (Object.prototype.hasOwnProperty.call(modules, path)) {\n throw new Error(where + \": \" + path + \" is in modules and refs.modules\");\n }\n modules[path] = JSON.parse(read(\"modules\", path, ref));\n }\n for (const [path, ref] of Object.entries(record(refs.files, \"refs.files\"))) {\n if (Object.prototype.hasOwnProperty.call(filesIn, path)) {\n throw new Error(where + \": \" + path + \" is in files and refs.files\");\n }\n files[path] = read(\"files\", path, ref);\n }\n if (job === null && commit === null) {\n throw new Error(where + \" must name a job or a commit, or it would be placed at the build it runs in\");\n }\n return { id, job, commit, modules, files };\n})();\n";
1392
+ /**
1393
+ * What each Val module depends on, as the build resolved its imports
1394
+ * (`valModulesEntry` in this package): the build defines it as a global
1395
+ * (`MODULE_DEPENDENCIES_GLOBAL`), and this hands it to Val's server as
1396
+ * `moduleDependencies`. After {@link CONTENT_BLOCK}, where a rebake puts it
1397
+ * in a file wired before it.
1398
+ */
1399
+ var DEPENDENCIES_BLOCK = "/*\n * WHAT EACH VAL MODULE DEPENDS ON, as this build resolved its imports.\n *\n * At a proposal's address it is how Val knows that a module whose own file\n * is not staged is still of code this build was not made of, through a file\n * it imports. Defined by the build; `undefined` from a builder that\n * predates it, and then only staged module files count.\n */\nconst MODULE_DEPENDENCIES = globalThis.__VAL_MODULE_DEPENDENCIES__;\n\n";
1400
+ /** And the option that hands it to Val, after the content version's. */
1401
+ var DEPENDENCIES_OPTION = " ...(MODULE_DEPENDENCIES !== undefined\n ? { moduleDependencies: MODULE_DEPENDENCIES }\n : {}),\n";
1385
1402
  /** Where {@link PROPOSAL_BLOCK} goes: right after this line. */
1386
1403
  var SERVED_BUILD_LINE = 'const servedBuild = secret("VAL_BUILD");\n';
1387
1404
  /** And the option that hands it to Val, after the build's. */
@@ -1391,7 +1408,7 @@ var CONTENT_OPTION = " ...(contentVersion !== undefined ? { contentVersio
1391
1408
  var PUBLISH_BUILD_OPTION = " ...(servedBuild !== undefined ? { publishBuild: servedBuild } : {}),\n";
1392
1409
  var valServerSource = function valServerSource(_ref) {
1393
1410
  var git = _ref.git;
1394
- return "".concat(WIRED_MARKER, "\nimport {\n initValContent,\n initValServer,\n} from \"@valbuild/tanstack/server\";\nimport { config } from \"../../val.config\";\nimport valModules from \"../../val.modules\";\n/*\n * This build's own source, which a publish patches. A project with no\n * repository has no other copy of its `.val.ts` text: content keeps its\n * content as data. Ignored by a @valbuild/tanstack that predates it.\n */\nimport { FILES } from \"platform:project-source\";\n\n/**\n * A secret, as the platform hands it over at RUNTIME.\n *\n * Preferred over `process.env`, which the builder inlines as a literal into\n * this bundle: that puts the value in storage inside the code, copies it into\n * every isolate that loads it, and makes rotating it a republish.\n *\n * Falls back to the build-time value, so an app published before secrets\n * existed keeps working.\n */\nfunction secret(name: string): string | undefined {\n return (globalThis.__PLATFORM_SECRETS ?? {})[name] ?? process.env[name];\n}\n\n/**\n * The commit this build was made from, and the branch it commits to.\n *\n * Baked in rather than handed over at runtime, unlike a secret, because it is\n * not configuration -- it is a property OF THIS BUILD. Every read of a\n * `.val.ts` in http mode fetches that path from the content service at this\n * sha, so a build served with somebody else's commit renders and edits a\n * version of its files it was not compiled from. A secret can be rotated under\n * a running build; this cannot, and publishing again is how it changes.\n *\n * WHAT THIS IS NOT. It is not every read: a committed render reads the source\n * bundled into this build and asks the content service nothing. It is the\n * PUBLISH path -- turning pending patches into new `.val.ts` text means\n * fetching the current text to patch, and that is the read that happens at\n * this sha. The docblock used to say \"every read\", which sent readers looking\n * for a content call on the serving path that is not there.\n *\n * `null` when the source came from no commit -- a record assembled in a tab,\n * a fixture, or ANY build this platform makes, which is the common case rather\n * than the exception. Such a build has no repository to mirror commits into,\n * and does not need one: the content service is the store of record for\n * content and mints its own commit shas. Val is in http mode on credentials\n * alone.\n */\nconst BUILT_FROM = ").concat(git ? JSON.stringify(git) : "null", ";\n\n/**\n * The publish job this build was made for, when a Studio built it in a tab.\n *\n * A tab's build has no commit to bake -- the job's is minted at the seal, after\n * the build -- so this is how it says where it sits in the content service's\n * chain. Without it the service places it at whatever build is live, which is\n * a different build for a request this one is still serving when the pointer\n * moves. Set by the Studio (`rebakeGit`), `null` for any other build.\n */\nconst BUILT_FOR_JOB = null;\n\n/**\n * What puts Val in http mode: its content service owns the content.\n *\n * The same three things any deployed Val app is configured with. Note what is\n * NOT here: no `sourceFiles`, so patches are relayed to the content service\n * instead of being kept by this platform, and the browser uploads an image\n * straight there on a presigned URL instead of streaming it through here.\n *\n * `undefined` when a credential or the commit is missing, and deliberately not\n * a throw at module scope: that would take the isolate down with it, page\n * renders included. Val is left to refuse the request and name what it wanted\n * -- `VAL_ENV=app` is set on this build precisely so that a missing credential\n * is an error instead of a fall-through to `fs` mode, looking for a working\n * tree that is not in here.\n */\nconst apiKey = secret(\"VAL_API_KEY\");\nconst valSecret = secret(\"VAL_SECRET\");\n/*\n * Which content service, for a project that is not pointed at the real one.\n *\n * A secret rather than a baked literal, because unlike the commit this IS\n * configuration: the same build should be servable against a stand-in and\n * against production. It is what makes the editing path testable at all --\n * Val's own `e2e/mock-content-host` implements this wire protocol with no git\n * repository behind it -- and without it a build could only ever talk to\n * content.val.build.\n *\n * It does NOT redirect everything, and the gap is in Val rather than here:\n * `getSettings`, which remote FILES use, reads `process.env.VAL_CONTENT_URL`\n * at module scope inside @valbuild/server. This platform bundles its\n * dependencies separately from the app, so nothing it sets reaches that read --\n * the same reason `apiKey` has to be passed in rather than found. So patches,\n * commits and source reads go where this says, and remote file uploads still\n * address the real host.\n */\nconst valContentUrl = secret(\"VAL_CONTENT_URL\");\n/*\n * WHICH project's content this is, at the content service.\n *\n * Val's own name for the project (`org/name`), which is not the platform's\n * project id and cannot be derived from it. A repository that is deployed\n * anywhere else puts it in `val.config.ts`; one imported here need not have,\n * so it is configuration the platform can supply -- and it goes through\n * `secret` rather than `--env` for a second reason: a build-time literal\n * would have to be baked into the shared dependency layer, where\n * @valbuild/server reads `process.env.VAL_PROJECT`, and that layer is reused\n * by every project with the same dependencies.\n *\n * What the app configured wins over nothing at all, so a repository that does\n * name its project keeps working with no secret set.\n */\nconst valProject = secret(\"VAL_PROJECT\");\n/*\n * WHICH BUILD this is, as the platform running it says.\n *\n * Not baked like `BUILT_FROM`, because it cannot be: a build's hash is taken\n * of its output, this file included. The platform hands it over at runtime,\n * and Val sends it to the content service, which places this build's overlay\n * by it -- the one answer that holds for the minute after a publish in which\n * the edge still serves this build while the pointer already names the next.\n * Ignored by a @valbuild/tanstack that predates it.\n */\nconst servedBuild = secret(\"VAL_BUILD\");\n").concat(PROPOSAL_BLOCK).concat(CONTENT_BLOCK, "const valConfig = {\n ...config,\n ...(valProject !== undefined ? { project: valProject } : {}),\n};\n/*\n * CREDENTIALS ALONE. A commit is not part of what puts Val in http mode.\n *\n * It used to be: `GIT !== null` was in this condition, and a build with no\n * commit fell through to `undefined` -- which meant every site this platform\n * seeded was silently unable to edit, because a shared build cannot know a\n * commit. The binding that worked around it (`VAL_GIT_COMMIT` /\n * `VAL_GIT_BRANCH` out of the project's secrets) is gone with it: it named a\n * commit in the TEMPLATE's repository, which was true only for as long as\n * seeding and repository creation shared a template, and it was one more thing\n * in KV that could go stale.\n *\n * The commit is optional NOW, and it is still sent where there is one -- see\n * the note at the spread below. What is gone is the binding that supplied one\n * from KV, so there is one source per environment and no precedence rule\n * between a baked value and a bound one.\n */\nconst http =\n apiKey !== undefined && valSecret !== undefined\n ? {\n apiKey,\n valSecret,\n /*\n * BOTH SPELLINGS OF THE COMMIT, because the APP decides which one is\n * read and this file cannot know which app it is being written into.\n *\n * `ValHttpMode` has been renamed in both directions. Up to 0.132 it\n * took `gitCommit`/`gitBranch`; 0.133.0 replaced that pair with a\n * nested `git`; the version this package ships beside flattens it\n * back again. The generated file is compiled against whatever\n * `@valbuild/tanstack` the PROJECT installed -- the starter pins\n * 0.133.0 -- and a platform writing this file has no say in that. So\n * this is not one rename behind or ahead: it is on both sides of one at\n * once, and will be until every app it publishes has moved.\n *\n * Sending only the wrong one is SILENT, which is why this is belt and\n * braces rather than a version check. An unknown key on the options\n * object is ignored, so the commit is simply dropped and a build wired\n * FROM A COMMIT runs as though it had none -- which means a publish\n * produces no mirrored `.val.ts`, so a save commits and hands over\n * nothing, and the site keeps serving its old content with the patches\n * already consumed. Nothing reports it. valbuild/home's loop is the one\n * thing that sees it, and it was bisected there: 25/25 with the key the\n * installed version reads, 21/23 without, failing at exactly \"the save\n * left the file it rewrote pending\".\n *\n * Whichever version is installed reads its own key and ignores the\n * other two. Drop this to one spelling when every app this platform\n * publishes is past the rename -- not before, and not on the say-so of\n * a compiler in the Val repository, which is looking at a different\n * version of `@valbuild/tanstack` than the app is.\n */\n ...(BUILT_FROM !== null\n ? {\n git: BUILT_FROM,\n gitCommit: BUILT_FROM.commit,\n gitBranch: BUILT_FROM.branch,\n }\n : {}),\n ...(valContentUrl !== undefined ? { valContentUrl } : {}),\n projectSource: FILES,\n ...(BUILT_FOR_JOB !== null ? { publishJob: BUILT_FOR_JOB } : {}),\n ...(servedBuild !== undefined ? { publishBuild: servedBuild } : {}),\n").concat(PROPOSAL_OPTION).concat(CONTENT_OPTION, " }\n : undefined;\n\nconst { valApiHandler, draftMode } = initValServer(\n valModules,\n valConfig,\n {\n ...(http ? { http } : {}),\n },\n);\n\nconst content = initValContent(valConfig, valModules, {\n draftMode,\n /*\n * The SAME object the API got.\n *\n * These readers resolve content through a Val server of their own rather than\n * by calling the API over HTTP, so the mode question is put to them\n * separately -- configuring only `initValServer` left them inferring `fs`\n * mode, looking for a working tree that is not in here. `gitCommit` is the\n * field that would be silently wrong rather than loudly missing: two\n * different shas means the API edits one version of a file while the page\n * renders another.\n */\n ...(http ? { http } : {}),\n});\n\nconst {\n fetchValStega: fetchVal,\n fetchValKeyStega: fetchValKey,\n fetchValRouteStega: fetchValRoute,\n fetchValRouteUrl,\n} = content;\n\n/**\n * The draft a page renders with in preview: `<ValProvider draft>`, read in the\n * site layout's loader. The starter imports it from this file, so a file\n * without it fails the build with a missing export.\n *\n * Asked of the result rather than destructured, because this file is compiled\n * against whatever `@valbuild/tanstack` the PROJECT installed, and one from\n * before 0.140 has no such reader. There it is \"no draft\", which is the\n * render that version had anyway -- and it is still a function either way, so\n * a page that calls it compiles against both.\n */\nconst fetchValDraft = async () =>\n \"fetchValDraft\" in content && typeof content.fetchValDraft === \"function\"\n ? content.fetchValDraft()\n : null;\n\n/**\n * Content analytics for `<ValProvider analytics>`, read in the site layout's\n * loader beside `fetchValDraft`: whether it is on, and the content version.\n *\n * A setting of the project, which its owner turns on in the project's settings\n * and the platform hands over as the `VAL_ANALYTICS` secret -- at RUNTIME,\n * like every secret, so switching it is not a rebuild. The value reaches the\n * browser in the layout's loader data, which a prerendered page has baked in;\n * the platform keeps a prerendered page only for the secrets it was rendered\n * with, so after a switch pages render live until they are prerendered again.\n * Off unless that secret says `true`. A `@valbuild/tanstack` from before analytics ignores the\n * prop, so this is safe to call against any version.\n *\n * With it, the id of the content version this render serves\n * (`VAL_CONTENT_VERSION`, which the loader hands every isolate it starts for\n * the site, whether the version is the bundle's own or handed over), so every\n * count is stored with the version it was seen in.\n *\n * What the platform handed over ONLY, not `secret()`: that falls back to\n * `process.env`, which the builder bakes into this bundle, so a\n * `VAL_ANALYTICS` set at build time would be a second switch in the code --\n * and one that keeps counting after the owner has turned it off.\n */\nconst fetchValAnalytics = async (): Promise<{\n enabled: boolean;\n contentVersion?: string;\n}> => {\n const handed = globalThis.__PLATFORM_SECRETS ?? {};\n const contentVersion = handed[\"VAL_CONTENT_VERSION\"];\n return {\n enabled: handed[\"VAL_ANALYTICS\"] === \"true\",\n ...(contentVersion ? { contentVersion } : {}),\n };\n};\n\n/**\n * A build that is MEANT to edit and cannot, refusing instead of pretending to.\n *\n * `BUILT_FROM` being non-null says this build came from a commit, so it was\n * made to edit against a content service. If the credentials for that service are not\n * here, the configuration is broken -- and the failure that was reaching people\n * was not an error at all. Val picks its storage mode by inference, so an\n * isolate with no api key lands in a mode that ACCEPTS the write and keeps it\n * in the isolate. Cloudflare starts an isolate per concurrent request, so the\n * save answers 200 and the next request, served by a different isolate, has\n * never heard of it. The edit is simply gone, and nothing anywhere said so.\n *\n * That is the worst available outcome: a person is told their work is saved\n * when it is not. Refusing is strictly better, and naming the missing secret\n * turns an evening of reading logs into one line in a response body.\n *\n * WHY HERE rather than relying on `VAL_ENV=app`: that is a build-time\n * substitution into the shared dependency layer, so whether a build fails\n * loudly depends on which layer it happens to be pinned to. This file is\n * written on every build, by the platform, and cannot be missing from one.\n *\n * Only the editing API. Page renders do not come through here, and a site whose\n * content cannot be edited should still serve the content it has.\n */\nconst editingApiHandler =\n http === undefined\n ? async () => {\n const missing = [\n apiKey === undefined ? \"VAL_API_KEY\" : null,\n valSecret === undefined ? \"VAL_SECRET\" : null,\n /*\n * A build from no commit is listed the same way, because from the\n * outside the two are one state. It is not a secret somebody can set\n * -- a commit is a property OF THE BUILD, and the only cure is\n * publishing this project's own repository over whatever is serving\n * it. Named anyway, because \"it was built from no commit\" is the\n * sentence that ends the search.\n */\n BUILT_FROM === null ? \"a commit (this build was made from none)\" : null,\n ].filter(Boolean);\n return Response.json(\n {\n error:\n \"This site cannot be edited. Its content lives in a content service, and \" +\n missing.join(\", \") +\n \" \" +\n (missing.length > 1 ? \"are\" : \"is\") +\n \" missing, so there is nothing to edit against. Editing is refused rather \" +\n \"than kept in this isolate's memory, where it would be lost without being \" +\n \"reported.\" +\n (BUILT_FROM === null\n ? \" A build made from no commit is usually one SEEDED from a template: \" +\n \"publish this project's own repository to replace it.\"\n : \" This build was made from commit \" + BUILT_FROM.commit.slice(0, 8) + \".\"),\n missing,\n },\n { status: 503 },\n );\n }\n : valApiHandler;\n\nexport {\n editingApiHandler as valApiHandler,\n draftMode,\n fetchVal,\n fetchValKey,\n fetchValRoute,\n fetchValRouteUrl,\n fetchValDraft,\n fetchValAnalytics,\n};\n");
1411
+ return "".concat(WIRED_MARKER, "\nimport {\n initValContent,\n initValServer,\n} from \"@valbuild/tanstack/server\";\nimport { config } from \"../../val.config\";\nimport valModules from \"../../val.modules\";\n/*\n * This build's own source, which a publish patches. A project with no\n * repository has no other copy of its `.val.ts` text: content keeps its\n * content as data. Ignored by a @valbuild/tanstack that predates it.\n */\nimport { FILES } from \"platform:project-source\";\n\n/**\n * A secret, as the platform hands it over at RUNTIME.\n *\n * Preferred over `process.env`, which the builder inlines as a literal into\n * this bundle: that puts the value in storage inside the code, copies it into\n * every isolate that loads it, and makes rotating it a republish.\n *\n * Falls back to the build-time value, so an app published before secrets\n * existed keeps working.\n */\nfunction secret(name: string): string | undefined {\n return (globalThis.__PLATFORM_SECRETS ?? {})[name] ?? process.env[name];\n}\n\n/**\n * The commit this build was made from, and the branch it commits to.\n *\n * Baked in rather than handed over at runtime, unlike a secret, because it is\n * not configuration -- it is a property OF THIS BUILD. Every read of a\n * `.val.ts` in http mode fetches that path from the content service at this\n * sha, so a build served with somebody else's commit renders and edits a\n * version of its files it was not compiled from. A secret can be rotated under\n * a running build; this cannot, and publishing again is how it changes.\n *\n * WHAT THIS IS NOT. It is not every read: a committed render reads the source\n * bundled into this build and asks the content service nothing. It is the\n * PUBLISH path -- turning pending patches into new `.val.ts` text means\n * fetching the current text to patch, and that is the read that happens at\n * this sha. The docblock used to say \"every read\", which sent readers looking\n * for a content call on the serving path that is not there.\n *\n * `null` when the source came from no commit -- a record assembled in a tab,\n * a fixture, or ANY build this platform makes, which is the common case rather\n * than the exception. Such a build has no repository to mirror commits into,\n * and does not need one: the content service is the store of record for\n * content and mints its own commit shas. Val is in http mode on credentials\n * alone.\n */\nconst BUILT_FROM = ").concat(git ? JSON.stringify(git) : "null", ";\n\n/**\n * The publish job this build was made for, when a Studio built it in a tab.\n *\n * A tab's build has no commit to bake -- the job's is minted at the seal, after\n * the build -- so this is how it says where it sits in the content service's\n * chain. Without it the service places it at whatever build is live, which is\n * a different build for a request this one is still serving when the pointer\n * moves. Set by the Studio (`rebakeGit`), `null` for any other build.\n */\nconst BUILT_FOR_JOB = null;\n\n/**\n * What puts Val in http mode: its content service owns the content.\n *\n * The same three things any deployed Val app is configured with. Note what is\n * NOT here: no `sourceFiles`, so patches are relayed to the content service\n * instead of being kept by this platform, and the browser uploads an image\n * straight there on a presigned URL instead of streaming it through here.\n *\n * `undefined` when a credential or the commit is missing, and deliberately not\n * a throw at module scope: that would take the isolate down with it, page\n * renders included. Val is left to refuse the request and name what it wanted\n * -- `VAL_ENV=app` is set on this build precisely so that a missing credential\n * is an error instead of a fall-through to `fs` mode, looking for a working\n * tree that is not in here.\n */\nconst apiKey = secret(\"VAL_API_KEY\");\nconst valSecret = secret(\"VAL_SECRET\");\n/*\n * Which content service, for a project that is not pointed at the real one.\n *\n * A secret rather than a baked literal, because unlike the commit this IS\n * configuration: the same build should be servable against a stand-in and\n * against production. It is what makes the editing path testable at all --\n * Val's own `e2e/mock-content-host` implements this wire protocol with no git\n * repository behind it -- and without it a build could only ever talk to\n * content.val.build.\n *\n * It does NOT redirect everything, and the gap is in Val rather than here:\n * `getSettings`, which remote FILES use, reads `process.env.VAL_CONTENT_URL`\n * at module scope inside @valbuild/server. This platform bundles its\n * dependencies separately from the app, so nothing it sets reaches that read --\n * the same reason `apiKey` has to be passed in rather than found. So patches,\n * commits and source reads go where this says, and remote file uploads still\n * address the real host.\n */\nconst valContentUrl = secret(\"VAL_CONTENT_URL\");\n/*\n * WHICH project's content this is, at the content service.\n *\n * Val's own name for the project (`org/name`), which is not the platform's\n * project id and cannot be derived from it. A repository that is deployed\n * anywhere else puts it in `val.config.ts`; one imported here need not have,\n * so it is configuration the platform can supply -- and it goes through\n * `secret` rather than `--env` for a second reason: a build-time literal\n * would have to be baked into the shared dependency layer, where\n * @valbuild/server reads `process.env.VAL_PROJECT`, and that layer is reused\n * by every project with the same dependencies.\n *\n * What the app configured wins over nothing at all, so a repository that does\n * name its project keeps working with no secret set.\n */\nconst valProject = secret(\"VAL_PROJECT\");\n/*\n * WHICH BUILD this is, as the platform running it says.\n *\n * Not baked like `BUILT_FROM`, because it cannot be: a build's hash is taken\n * of its output, this file included. The platform hands it over at runtime,\n * and Val sends it to the content service, which places this build's overlay\n * by it -- the one answer that holds for the minute after a publish in which\n * the edge still serves this build while the pointer already names the next.\n * Ignored by a @valbuild/tanstack that predates it.\n */\nconst servedBuild = secret(\"VAL_BUILD\");\n").concat(PROPOSAL_BLOCK).concat(CONTENT_BLOCK).concat(DEPENDENCIES_BLOCK, "const valConfig = {\n ...config,\n ...(valProject !== undefined ? { project: valProject } : {}),\n};\n/*\n * CREDENTIALS ALONE. A commit is not part of what puts Val in http mode.\n *\n * It used to be: `GIT !== null` was in this condition, and a build with no\n * commit fell through to `undefined` -- which meant every site this platform\n * seeded was silently unable to edit, because a shared build cannot know a\n * commit. The binding that worked around it (`VAL_GIT_COMMIT` /\n * `VAL_GIT_BRANCH` out of the project's secrets) is gone with it: it named a\n * commit in the TEMPLATE's repository, which was true only for as long as\n * seeding and repository creation shared a template, and it was one more thing\n * in KV that could go stale.\n *\n * The commit is optional NOW, and it is still sent where there is one -- see\n * the note at the spread below. What is gone is the binding that supplied one\n * from KV, so there is one source per environment and no precedence rule\n * between a baked value and a bound one.\n */\nconst http =\n apiKey !== undefined && valSecret !== undefined\n ? {\n apiKey,\n valSecret,\n /*\n * BOTH SPELLINGS OF THE COMMIT, because the APP decides which one is\n * read and this file cannot know which app it is being written into.\n *\n * `ValHttpMode` has been renamed in both directions. Up to 0.132 it\n * took `gitCommit`/`gitBranch`; 0.133.0 replaced that pair with a\n * nested `git`; the version this package ships beside flattens it\n * back again. The generated file is compiled against whatever\n * `@valbuild/tanstack` the PROJECT installed -- the starter pins\n * 0.133.0 -- and a platform writing this file has no say in that. So\n * this is not one rename behind or ahead: it is on both sides of one at\n * once, and will be until every app it publishes has moved.\n *\n * Sending only the wrong one is SILENT, which is why this is belt and\n * braces rather than a version check. An unknown key on the options\n * object is ignored, so the commit is simply dropped and a build wired\n * FROM A COMMIT runs as though it had none -- which means a publish\n * produces no mirrored `.val.ts`, so a save commits and hands over\n * nothing, and the site keeps serving its old content with the patches\n * already consumed. Nothing reports it. valbuild/home's loop is the one\n * thing that sees it, and it was bisected there: 25/25 with the key the\n * installed version reads, 21/23 without, failing at exactly \"the save\n * left the file it rewrote pending\".\n *\n * Whichever version is installed reads its own key and ignores the\n * other two. Drop this to one spelling when every app this platform\n * publishes is past the rename -- not before, and not on the say-so of\n * a compiler in the Val repository, which is looking at a different\n * version of `@valbuild/tanstack` than the app is.\n */\n ...(BUILT_FROM !== null\n ? {\n git: BUILT_FROM,\n gitCommit: BUILT_FROM.commit,\n gitBranch: BUILT_FROM.branch,\n }\n : {}),\n ...(valContentUrl !== undefined ? { valContentUrl } : {}),\n projectSource: FILES,\n ...(BUILT_FOR_JOB !== null ? { publishJob: BUILT_FOR_JOB } : {}),\n ...(servedBuild !== undefined ? { publishBuild: servedBuild } : {}),\n").concat(PROPOSAL_OPTION).concat(CONTENT_OPTION).concat(DEPENDENCIES_OPTION, " }\n : undefined;\n\nconst { valApiHandler, draftMode } = initValServer(\n valModules,\n valConfig,\n {\n ...(http ? { http } : {}),\n },\n);\n\nconst content = initValContent(valConfig, valModules, {\n draftMode,\n /*\n * The SAME object the API got.\n *\n * These readers resolve content through a Val server of their own rather than\n * by calling the API over HTTP, so the mode question is put to them\n * separately -- configuring only `initValServer` left them inferring `fs`\n * mode, looking for a working tree that is not in here. `gitCommit` is the\n * field that would be silently wrong rather than loudly missing: two\n * different shas means the API edits one version of a file while the page\n * renders another.\n */\n ...(http ? { http } : {}),\n});\n\nconst {\n fetchValStega: fetchVal,\n fetchValKeyStega: fetchValKey,\n fetchValRouteStega: fetchValRoute,\n fetchValRouteUrl,\n} = content;\n\n/**\n * The draft a page renders with in preview: `<ValProvider draft>`, read in the\n * site layout's loader. The starter imports it from this file, so a file\n * without it fails the build with a missing export.\n *\n * Asked of the result rather than destructured, because this file is compiled\n * against whatever `@valbuild/tanstack` the PROJECT installed, and one from\n * before 0.140 has no such reader. There it is \"no draft\", which is the\n * render that version had anyway -- and it is still a function either way, so\n * a page that calls it compiles against both.\n */\nconst fetchValDraft = async () =>\n \"fetchValDraft\" in content && typeof content.fetchValDraft === \"function\"\n ? content.fetchValDraft()\n : null;\n\n/**\n * Content analytics for `<ValProvider analytics>`, read in the site layout's\n * loader beside `fetchValDraft`: whether it is on, and the content version.\n *\n * A setting of the project, which its owner turns on in the project's settings\n * and the platform hands over as the `VAL_ANALYTICS` secret -- at RUNTIME,\n * like every secret, so switching it is not a rebuild. The value reaches the\n * browser in the layout's loader data, which a prerendered page has baked in;\n * the platform keeps a prerendered page only for the secrets it was rendered\n * with, so after a switch pages render live until they are prerendered again.\n * Off unless that secret says `true`. A `@valbuild/tanstack` from before analytics ignores the\n * prop, so this is safe to call against any version.\n *\n * With it, the id of the content version this render serves\n * (`VAL_CONTENT_VERSION`, which the loader hands every isolate it starts for\n * the site, whether the version is the bundle's own or handed over), so every\n * count is stored with the version it was seen in.\n *\n * What the platform handed over ONLY, not `secret()`: that falls back to\n * `process.env`, which the builder bakes into this bundle, so a\n * `VAL_ANALYTICS` set at build time would be a second switch in the code --\n * and one that keeps counting after the owner has turned it off.\n */\nconst fetchValAnalytics = async (): Promise<{\n enabled: boolean;\n contentVersion?: string;\n}> => {\n const handed = globalThis.__PLATFORM_SECRETS ?? {};\n const contentVersion = handed[\"VAL_CONTENT_VERSION\"];\n return {\n enabled: handed[\"VAL_ANALYTICS\"] === \"true\",\n ...(contentVersion ? { contentVersion } : {}),\n };\n};\n\n/**\n * A build that is MEANT to edit and cannot, refusing instead of pretending to.\n *\n * `BUILT_FROM` being non-null says this build came from a commit, so it was\n * made to edit against a content service. If the credentials for that service are not\n * here, the configuration is broken -- and the failure that was reaching people\n * was not an error at all. Val picks its storage mode by inference, so an\n * isolate with no api key lands in a mode that ACCEPTS the write and keeps it\n * in the isolate. Cloudflare starts an isolate per concurrent request, so the\n * save answers 200 and the next request, served by a different isolate, has\n * never heard of it. The edit is simply gone, and nothing anywhere said so.\n *\n * That is the worst available outcome: a person is told their work is saved\n * when it is not. Refusing is strictly better, and naming the missing secret\n * turns an evening of reading logs into one line in a response body.\n *\n * WHY HERE rather than relying on `VAL_ENV=app`: that is a build-time\n * substitution into the shared dependency layer, so whether a build fails\n * loudly depends on which layer it happens to be pinned to. This file is\n * written on every build, by the platform, and cannot be missing from one.\n *\n * Only the editing API. Page renders do not come through here, and a site whose\n * content cannot be edited should still serve the content it has.\n */\nconst editingApiHandler =\n http === undefined\n ? async () => {\n const missing = [\n apiKey === undefined ? \"VAL_API_KEY\" : null,\n valSecret === undefined ? \"VAL_SECRET\" : null,\n /*\n * A build from no commit is listed the same way, because from the\n * outside the two are one state. It is not a secret somebody can set\n * -- a commit is a property OF THE BUILD, and the only cure is\n * publishing this project's own repository over whatever is serving\n * it. Named anyway, because \"it was built from no commit\" is the\n * sentence that ends the search.\n */\n BUILT_FROM === null ? \"a commit (this build was made from none)\" : null,\n ].filter(Boolean);\n return Response.json(\n {\n error:\n \"This site cannot be edited. Its content lives in a content service, and \" +\n missing.join(\", \") +\n \" \" +\n (missing.length > 1 ? \"are\" : \"is\") +\n \" missing, so there is nothing to edit against. Editing is refused rather \" +\n \"than kept in this isolate's memory, where it would be lost without being \" +\n \"reported.\" +\n (BUILT_FROM === null\n ? \" A build made from no commit is usually one SEEDED from a template: \" +\n \"publish this project's own repository to replace it.\"\n : \" This build was made from commit \" + BUILT_FROM.commit.slice(0, 8) + \".\"),\n missing,\n },\n { status: 503 },\n );\n }\n : valApiHandler;\n\nexport {\n editingApiHandler as valApiHandler,\n draftMode,\n fetchVal,\n fetchValKey,\n fetchValRoute,\n fetchValRouteUrl,\n fetchValDraft,\n fetchValAnalytics,\n};\n");
1395
1412
  };
1396
1413
 
1397
1414
  /**
@@ -1409,7 +1426,7 @@ var valServerSource = function valServerSource(_ref) {
1409
1426
  * declaration, and a top-level `declare var` is a global without needing
1410
1427
  * `declare global`, which a script may not contain.
1411
1428
  */
1412
- var PROJECT_SOURCE_DECLARATIONS = "// Generated by the Val studio when this project was wired up to the platform.\n// The build resolves this specifier to the project's own source, shipped into\n// the isolate as a module.\n//\n// Deliberately not a module: an `export` anywhere in this file would turn the\n// declaration below into an augmentation, and the import would stop resolving.\ndeclare module 'platform:project-source' {\n /** Every source file of this project, keyed by its path from the root. */\n export const FILES: Record<string, string>\n}\n\n/**\n * The project this isolate is serving, set per request by the platform from\n * the id the loader resolved off the hostname.\n *\n * Absent when server-rendering outside the platform, and in the browser.\n */\n// eslint-disable-next-line no-var\ndeclare var __PLATFORM_PROJECT_ID: string | undefined\n/**\n * This project's secrets, handed over per request rather than built in.\n *\n * SERVER ONLY -- set by the platform's Worker entry, which never runs in a\n * browser. Absent outside the platform.\n */\n// eslint-disable-next-line no-var\ndeclare var __PLATFORM_SECRETS: Record<string, string> | undefined\n";
1429
+ var PROJECT_SOURCE_DECLARATIONS = "// Generated by the Val studio when this project was wired up to the platform.\n// The build resolves this specifier to the project's own source, shipped into\n// the isolate as a module.\n//\n// Deliberately not a module: an `export` anywhere in this file would turn the\n// declaration below into an augmentation, and the import would stop resolving.\ndeclare module 'platform:project-source' {\n /** Every source file of this project, keyed by its path from the root. */\n export const FILES: Record<string, string>\n}\n\n/**\n * The project this isolate is serving, set per request by the platform from\n * the id the loader resolved off the hostname.\n *\n * Absent when server-rendering outside the platform, and in the browser.\n */\n// eslint-disable-next-line no-var\ndeclare var __PLATFORM_PROJECT_ID: string | undefined\n/**\n * This project's secrets, handed over per request rather than built in.\n *\n * SERVER ONLY -- set by the platform's Worker entry, which never runs in a\n * browser. Absent outside the platform.\n */\n// eslint-disable-next-line no-var\ndeclare var __PLATFORM_SECRETS: Record<string, string> | undefined\n/**\n * What each Val module of this build depends on, by path, as the build\n * resolved its imports. Defined by the platform's build; absent from a\n * builder that predates it.\n */\n// eslint-disable-next-line no-var\ndeclare var __VAL_MODULE_DEPENDENCIES__: Record<string, string[]> | undefined\n";
1413
1430
 
1414
1431
  /**
1415
1432
  * The wired `val.server.ts`, on its own.
@@ -1486,6 +1503,14 @@ function bakedJob(files) {
1486
1503
  * as it is, and serves a proposal's address as its base build.
1487
1504
  */
1488
1505
  function rebakeProposal(source) {
1506
+ // A block from before staged code was read: the current one in its place,
1507
+ // where it is exactly as generated.
1508
+ var at = source.indexOf(PROPOSAL_BLOCK_V1);
1509
+ if (at !== -1 && source.indexOf(PROPOSAL_BLOCK_V1, at + 1) === -1) {
1510
+ return source.replace(PROPOSAL_BLOCK_V1, function () {
1511
+ return PROPOSAL_BLOCK;
1512
+ });
1513
+ }
1489
1514
  if (source.includes("const proposal = (() => {")) return source;
1490
1515
  var once = function once(needle) {
1491
1516
  var at = source.indexOf(needle);
@@ -1521,6 +1546,38 @@ function rebakeContent(source) {
1521
1546
  });
1522
1547
  }
1523
1548
 
1549
+ /**
1550
+ * `source` handing Val each module's dependencies: {@link DEPENDENCIES_BLOCK}
1551
+ * and its option added after the content version's, to a file wired before
1552
+ * they existed. Idempotent, and only where both places are exactly as
1553
+ * generated -- a file somebody edited is left as it is, and Val counts only
1554
+ * staged module files at a proposal's address, as before.
1555
+ */
1556
+ function rebakeDependencies(source) {
1557
+ var once = function once(needle) {
1558
+ var at = source.indexOf(needle);
1559
+ return at !== -1 && source.indexOf(needle, at + 1) === -1;
1560
+ };
1561
+ if (!once(CONTENT_BLOCK) || !once(CONTENT_OPTION)) return source;
1562
+ var hasBlock = source.includes(DEPENDENCIES_BLOCK);
1563
+ var hasOption = source.includes(DEPENDENCIES_OPTION);
1564
+ if (hasBlock && hasOption) return source;
1565
+ // Each piece once, whatever left the other there: an option without its
1566
+ // block names a constant that does not exist.
1567
+ var next = source;
1568
+ if (!hasBlock) {
1569
+ next = next.replace(CONTENT_BLOCK, function () {
1570
+ return CONTENT_BLOCK + DEPENDENCIES_BLOCK;
1571
+ });
1572
+ }
1573
+ if (!hasOption) {
1574
+ next = next.replace(CONTENT_OPTION, function () {
1575
+ return CONTENT_OPTION + DEPENDENCIES_OPTION;
1576
+ });
1577
+ }
1578
+ return next;
1579
+ }
1580
+
1524
1581
  /** `source` with its job set, or `source` itself when it cannot carry one. */
1525
1582
  function rebakeJob(source, job) {
1526
1583
  var line = "const BUILT_FOR_JOB = ".concat(job === null ? "null" : JSON.stringify(job), ";");
@@ -1604,7 +1661,7 @@ job) {
1604
1661
  if (!BUILT_FROM_LINE.test(source)) return files;
1605
1662
  var withGit = source.replace(BUILT_FROM_LINE, "const BUILT_FROM = ".concat(git === null ? "null" : JSON.stringify(git), ";"));
1606
1663
  var withJob = job === undefined ? withGit : rebakeJob(withGit, job);
1607
- return regeneratorValues._objectSpread2(regeneratorValues._objectSpread2({}, files), {}, regeneratorValues._defineProperty({}, VAL_SERVER, rebakeContent(rebakeProposal(withJob))));
1664
+ return regeneratorValues._objectSpread2(regeneratorValues._objectSpread2({}, files), {}, regeneratorValues._defineProperty({}, VAL_SERVER, rebakeDependencies(rebakeContent(rebakeProposal(withJob)))));
1608
1665
  }
1609
1666
 
1610
1667
  /** Is this a Val project at all? */
@@ -1895,75 +1952,570 @@ function canonicalJson(value) {
1895
1952
  return JSON.stringify(value);
1896
1953
  }
1897
1954
 
1898
- /** Cheap pre-filter: skip the parse unless one of these appears in the source. */
1899
- var MARKERS = ["createIsomorphicFn", "createServerOnlyFn", "createClientOnlyFn", "createMiddleware", "ClientOnly"];
1900
-
1901
- /** Walks a `foo().bar().baz()` chain down to its root callee identifier. */
1902
- function chainRoot(node) {
1903
- var current = node;
1904
- while (current) {
1905
- if (current.type === "CallExpression") {
1906
- var callee = current.callee;
1907
- if ((callee === null || callee === void 0 ? void 0 : callee.type) === "Identifier") return String(callee.name);
1908
- if ((callee === null || callee === void 0 ? void 0 : callee.type) === "MemberExpression") {
1909
- current = callee.object;
1910
- continue;
1955
+ /**
1956
+ * JSON with comments and trailing commas, which is what tsconfig.json is.
1957
+ *
1958
+ * Written as a scanner rather than a regex on purpose: `"url": "https://x"`
1959
+ * contains `//`, and a regex that strips comments without tracking string state
1960
+ * truncates the file there and throws a parse error pointing at the wrong line.
1961
+ */
1962
+ function parseJsonc(text) {
1963
+ var out = "";
1964
+ var i = 0;
1965
+ while (i < text.length) {
1966
+ var ch = text[i];
1967
+ if (ch === '"') {
1968
+ // Copy the whole string literal, escapes included, untouched.
1969
+ out += ch;
1970
+ i++;
1971
+ while (i < text.length) {
1972
+ var c = text[i];
1973
+ out += c;
1974
+ i++;
1975
+ if (c === "\\") {
1976
+ if (i < text.length) out += text[i++];
1977
+ continue;
1978
+ }
1979
+ if (c === '"') break;
1911
1980
  }
1912
- return null;
1981
+ continue;
1913
1982
  }
1914
- return null;
1983
+ if (ch === "/" && text[i + 1] === "/") {
1984
+ while (i < text.length && text[i] !== "\n") i++;
1985
+ continue;
1986
+ }
1987
+ if (ch === "/" && text[i + 1] === "*") {
1988
+ i += 2;
1989
+ while (i < text.length && !(text[i] === "*" && text[i + 1] === "/")) i++;
1990
+ i += 2;
1991
+ continue;
1992
+ }
1993
+ out += ch;
1994
+ i++;
1915
1995
  }
1916
- return null;
1996
+ // Trailing commas, now that every remaining comma is structural.
1997
+ return JSON.parse(out.replace(/,(\s*[}\]])/g, "$1"));
1917
1998
  }
1918
1999
 
2000
+ /** One `paths` entry, pre-split on its wildcard. */
2001
+
1919
2002
  /**
1920
- * True when this call is the whole chain rather than a link in a longer one.
2003
+ * Reads tsconfig.json out of the file record and builds the matcher.
1921
2004
  *
1922
- * Without this, `createIsomorphicFn().client(a).server(b)` matches three times
1923
- * and the inner replacements land inside text the outer one is about to
1924
- * replace.
2005
+ * Returns null when the project configures no aliases, which is the common
2006
+ * case and costs nothing.
1925
2007
  */
1926
- function isOutermost(node, stack) {
1927
- var parent = stack[stack.length - 1];
1928
- var grandparent = stack[stack.length - 2];
1929
- return !((parent === null || parent === void 0 ? void 0 : parent.type) === "MemberExpression" && parent.object === node && (grandparent === null || grandparent === void 0 ? void 0 : grandparent.type) === "CallExpression");
1930
- }
2008
+ function aliasMap(files, warn) {
2009
+ var _config$compilerOptio, _config$compilerOptio2;
2010
+ var entry = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "tsconfig.json";
2011
+ var config = readConfig(files, entry, warn, new Set());
2012
+ var paths = config === null || config === void 0 || (_config$compilerOptio = config.compilerOptions) === null || _config$compilerOptio === void 0 ? void 0 : _config$compilerOptio.paths;
2013
+ var baseUrl = config === null || config === void 0 || (_config$compilerOptio2 = config.compilerOptions) === null || _config$compilerOptio2 === void 0 ? void 0 : _config$compilerOptio2.baseUrl;
2014
+ // A project can configure either one without the other, and baseUrl alone is
2015
+ // enough to change how a bare specifier resolves.
2016
+ if ((!paths || Object.keys(paths).length === 0) && baseUrl === undefined) return null;
1931
2017
 
1932
- /** Collects `.method(arg)` calls along a chain, nearest-root first. */
1933
- function methodsOf(node) {
1934
- var found = new Map();
1935
- var current = node;
1936
- while (((_current = current) === null || _current === void 0 ? void 0 : _current.type) === "CallExpression") {
1937
- var _current, _name, _callee$property, _current$arguments;
1938
- var callee = current.callee;
1939
- if ((callee === null || callee === void 0 ? void 0 : callee.type) !== "MemberExpression") break;
1940
- var name = String((_name = (_callee$property = callee.property) === null || _callee$property === void 0 ? void 0 : _callee$property.name) !== null && _name !== void 0 ? _name : "");
1941
- // Nearest-to-root wins, so a later duplicate does not shadow the first.
1942
- found.set(name, {
1943
- call: current,
1944
- arg: (_current$arguments = current.arguments) === null || _current$arguments === void 0 ? void 0 : _current$arguments[0],
1945
- objectEnd: callee.object.end
2018
+ // `baseUrl` is relative to the tsconfig that declared it. Since TS 4.1 paths
2019
+ // work without one, resolved against the tsconfig's own directory -- so the
2020
+ // fallback here is the directory, not the project root.
2021
+ var base = resolve(dirname(entry), baseUrl !== null && baseUrl !== void 0 ? baseUrl : ".");
2022
+ var patterns = [];
2023
+ for (var _i = 0, _Object$entries = Object.entries(paths !== null && paths !== void 0 ? paths : {}); _i < _Object$entries.length; _i++) {
2024
+ var _Object$entries$_i = regeneratorValues._slicedToArray(_Object$entries[_i], 2),
2025
+ pattern = _Object$entries$_i[0],
2026
+ targets = _Object$entries$_i[1];
2027
+ var star = pattern.indexOf("*");
2028
+ if (star !== pattern.lastIndexOf("*")) {
2029
+ warn("tsconfig paths pattern '".concat(pattern, "' has more than one '*' and is ignored."));
2030
+ continue;
2031
+ }
2032
+ patterns.push({
2033
+ prefix: star === -1 ? pattern : pattern.slice(0, star),
2034
+ suffix: star === -1 ? "" : pattern.slice(star + 1),
2035
+ wildcard: star !== -1,
2036
+ targets: targets.map(function (target) {
2037
+ return resolve(base, target);
2038
+ })
1946
2039
  });
1947
- current = callee.object;
1948
2040
  }
1949
- return found;
2041
+
2042
+ // TypeScript picks the pattern with the longest literal prefix, so `@/ui/*`
2043
+ // beats `@/*` for `@/ui/card` regardless of declaration order.
2044
+ patterns.sort(function (a, b) {
2045
+ return b.prefix.length - a.prefix.length;
2046
+ });
2047
+ return {
2048
+ patterns: Object.keys(paths !== null && paths !== void 0 ? paths : {}),
2049
+ baseUrlCandidate: function baseUrlCandidate(specifier) {
2050
+ return baseUrl === undefined ? null : resolve(base, specifier);
2051
+ },
2052
+ candidates: function candidates(specifier) {
2053
+ var _loop = function _loop() {
2054
+ var pattern = _patterns[_i2];
2055
+ if (!pattern.wildcard) {
2056
+ if (specifier === pattern.prefix) return {
2057
+ v: regeneratorValues._toConsumableArray(pattern.targets)
2058
+ };
2059
+ return 0; // continue
2060
+ }
2061
+ if (!specifier.startsWith(pattern.prefix) || !specifier.endsWith(pattern.suffix) || specifier.length < pattern.prefix.length + pattern.suffix.length) {
2062
+ return 0; // continue
2063
+ }
2064
+ var matched = specifier.slice(pattern.prefix.length, specifier.length - pattern.suffix.length);
2065
+ return {
2066
+ v: pattern.targets.map(function (target) {
2067
+ return target.replace("*", matched);
2068
+ })
2069
+ };
2070
+ },
2071
+ _ret;
2072
+ for (var _i2 = 0, _patterns = patterns; _i2 < _patterns.length; _i2++) {
2073
+ _ret = _loop();
2074
+ if (_ret === 0) continue;
2075
+ if (_ret) return _ret.v;
2076
+ }
2077
+ return [];
2078
+ }
2079
+ };
2080
+ }
2081
+
2082
+ /** Follows `extends` through the file record. Package extends cannot be read. */
2083
+ function readConfig(files, path, warn, seen) {
2084
+ var _config, _config$compilerOptio4, _config$compilerOptio5, _parent$compilerOptio;
2085
+ if (seen.has(path)) return null; // a cycle; whatever we have is enough
2086
+ seen.add(path);
2087
+ var text = files[path];
2088
+ if (text === undefined) return null;
2089
+ var config;
2090
+ try {
2091
+ config = parseJsonc(text);
2092
+ } catch (error) {
2093
+ var _message;
2094
+ warn("Could not parse ".concat(path, ": ").concat(String((_message = error === null || error === void 0 ? void 0 : error.message) !== null && _message !== void 0 ? _message : error)));
2095
+ return null;
2096
+ }
2097
+ if (!((_config = config) !== null && _config !== void 0 && _config["extends"])) return config;
2098
+
2099
+ // Only a relative extends can be followed: a package one ("extends":
2100
+ // "@tsconfig/node20/tsconfig.json") lives in node_modules, which a browser
2101
+ // build does not have. Worth saying out loud rather than silently resolving
2102
+ // half the aliases, because the base config is where a monorepo usually puts
2103
+ // them.
2104
+ if (!config["extends"].startsWith(".")) {
2105
+ var _config$compilerOptio3;
2106
+ if (!((_config$compilerOptio3 = config.compilerOptions) !== null && _config$compilerOptio3 !== void 0 && _config$compilerOptio3.paths)) {
2107
+ warn("".concat(path, " extends '").concat(config["extends"], "', which is a package and cannot be read here. ") + "Any 'paths' it declares will not apply -- declare them in ".concat(path, " instead."));
2108
+ }
2109
+ return config;
2110
+ }
2111
+ var parentPath = resolveConfigPath(files, resolve(dirname(path), config["extends"]));
2112
+ var parent = parentPath ? readConfig(files, parentPath, warn, seen) : null;
2113
+ if (!parent) return config;
2114
+
2115
+ // The child wins, and `paths` replaces rather than merges -- which is what
2116
+ // TypeScript does.
2117
+ return {
2118
+ compilerOptions: regeneratorValues._objectSpread2(regeneratorValues._objectSpread2(regeneratorValues._objectSpread2({}, parent.compilerOptions), config.compilerOptions), {}, {
2119
+ // baseUrl in the parent was relative to the *parent*, and readConfig
2120
+ // returns it unresolved, so a parent baseUrl with a child that sets none
2121
+ // is the one case this gets wrong. Rare enough to name rather than model.
2122
+ paths: (_config$compilerOptio4 = (_config$compilerOptio5 = config.compilerOptions) === null || _config$compilerOptio5 === void 0 ? void 0 : _config$compilerOptio5.paths) !== null && _config$compilerOptio4 !== void 0 ? _config$compilerOptio4 : (_parent$compilerOptio = parent.compilerOptions) === null || _parent$compilerOptio === void 0 ? void 0 : _parent$compilerOptio.paths
2123
+ })
2124
+ };
2125
+ }
2126
+
2127
+ /** `extends: './base'` may omit the .json. */
2128
+ function resolveConfigPath(files, path) {
2129
+ for (var _i3 = 0, _arr = [path, "".concat(path, ".json")]; _i3 < _arr.length; _i3++) {
2130
+ var candidate = _arr[_i3];
2131
+ if (candidate in files) return candidate;
2132
+ }
2133
+ return null;
1950
2134
  }
2135
+
1951
2136
  /**
1952
- * Rewrites the environment markers in one module for one target.
2137
+ * A project's `val.modules.ts`, bundled to run: every `.val.ts` it imports,
2138
+ * the `val.config` they share and the `.val.json` entries they name, as ONE
2139
+ * ES module -- so it can be imported from a `blob:` URL, which cannot resolve
2140
+ * a relative chunk -- with every npm import pointing at the site's own
2141
+ * vendor chunks, at absolute URLs under `origin`.
1953
2142
  *
1954
- * Returns `null` when the module contains none, so the caller leaves it alone
1955
- * and pays no parse.
2143
+ * What the builder tab evaluates to learn a tree's schemas: Update from the
2144
+ * site with code (valbuild/home `docs/hosted-publishing.md` step 8.2, slice
2145
+ * 1b). The project's own `@valbuild/*` and dependencies are what run, as the
2146
+ * site runs them -- the browser half of its layer, from `/_pvendor/<rev>/`,
2147
+ * and the base layer from `/_vendor/`. Whoever imports it should do so off
2148
+ * the Studio's page: `@valbuild/tanstack` brings React and patches its JSX.
2149
+ *
2150
+ * Nothing else of a build happens here: no route splitting, no server
2151
+ * functions, no CSS -- a `.val.ts` has none of it.
1956
2152
  */
1957
- function transformEnvMarkers(_x, _x2, _x3) {
1958
- return _transformEnvMarkers.apply(this, arguments);
2153
+ function bundleValModules(_x) {
2154
+ return _bundleValModules.apply(this, arguments);
1959
2155
  }
1960
- function _transformEnvMarkers() {
1961
- _transformEnvMarkers = regeneratorValues._asyncToGenerator(/*#__PURE__*/regeneratorValues._regenerator().m(function _callee(moduleId, code, target) {
1962
- var ast, imported, edits, applied, text;
1963
- return regeneratorValues._regenerator().w(function (_context) {
1964
- while (1) switch (_context.n) {
1965
- case 0:
1966
- if (MARKERS.some(function (marker) {
2156
+
2157
+ /**
2158
+ * For each module file (`*.val.ts` / `*.val.js`) the graph reaches, every
2159
+ * project file it depends on, transitively, sorted: what tells Val's server
2160
+ * at a proposal's address that a module whose own file is not staged is of
2161
+ * code the build was not made of, through a file it imports
2162
+ * (`moduleDependencies`, `stagedAfterBuild` in `@valbuild/server`). From the
2163
+ * imports as this bundle resolved them -- relative, tsconfig aliases,
2164
+ * whatever resolved -- so it cannot disagree with what the build evaluated.
2165
+ * An entry's `.val.json` is left out: it is content, and a record of 10,000
2166
+ * entries would make the map that long.
2167
+ */
2168
+ function _bundleValModules() {
2169
+ _bundleValModules = regeneratorValues._asyncToGenerator(/*#__PURE__*/regeneratorValues._regenerator().m(function _callee(input) {
2170
+ var _input$entry;
2171
+ var files, target, origin, entry, warnings, aliases, base, project, entryPath, resolveProjectPath, imports, _yield$loadRolldown, build, result, resolveOne, chunks, _t;
2172
+ return regeneratorValues._regenerator().w(function (_context) {
2173
+ while (1) switch (_context.p = _context.n) {
2174
+ case 0:
2175
+ resolveOne = function _resolveOne(source, importer) {
2176
+ if (source.startsWith(".")) {
2177
+ return resolveProjectPath(resolve(dirname(importer !== null && importer !== void 0 ? importer : entryPath), source));
2178
+ }
2179
+ if (source in files) return source;
2180
+ var baseChunk = target.base.modules[source];
2181
+ if (baseChunk) {
2182
+ return {
2183
+ id: "".concat(base).concat(baseChunk, ".js"),
2184
+ external: true
2185
+ };
2186
+ }
2187
+ var projectChunk = target.project.modules[source];
2188
+ if (projectChunk && project !== null) {
2189
+ if (target.project.workerOnly.includes(source)) {
2190
+ throw new Error("'".concat(source, "' is server-only in this project's vendor layer, so a .val.ts importing it cannot be read in the browser."));
2191
+ }
2192
+ return {
2193
+ id: "".concat(project).concat(projectChunk, ".js"),
2194
+ external: true
2195
+ };
2196
+ }
2197
+ if (aliases) {
2198
+ var _iterator4 = regeneratorValues._createForOfIteratorHelper(aliases.candidates(source)),
2199
+ _step4;
2200
+ try {
2201
+ for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
2202
+ var candidate = _step4.value;
2203
+ var _hit = resolveProjectPath(candidate);
2204
+ if (_hit) return _hit;
2205
+ }
2206
+ } catch (err) {
2207
+ _iterator4.e(err);
2208
+ } finally {
2209
+ _iterator4.f();
2210
+ }
2211
+ var fromBaseUrl = aliases.baseUrlCandidate(source);
2212
+ var hit = fromBaseUrl && resolveProjectPath(fromBaseUrl);
2213
+ if (hit) return hit;
2214
+ }
2215
+ // An error, not a warning: rolldown would otherwise leave the
2216
+ // specifier as it is, and it would fail when imported, unnamed.
2217
+ throw new Error("'".concat(source, "' is not an available dependency. Available: ").concat([].concat(regeneratorValues._toConsumableArray(Object.keys(target.base.modules)), regeneratorValues._toConsumableArray(Object.keys(target.project.modules))).join(", "), "."));
2218
+ };
2219
+ files = input.files, target = input.target, origin = input.origin;
2220
+ entry = (_input$entry = input.entry) !== null && _input$entry !== void 0 ? _input$entry : ["val.modules.ts", "val.modules.js"].find(function (path) {
2221
+ return path in files;
2222
+ });
2223
+ if (!(entry === undefined || !(entry in files))) {
2224
+ _context.n = 1;
2225
+ break;
2226
+ }
2227
+ throw new Error("This project has no val.modules.ts, so its Val modules cannot be read.");
2228
+ case 1:
2229
+ warnings = [];
2230
+ aliases = aliasMap(files, function (message) {
2231
+ return warnings.push(message);
2232
+ });
2233
+ base = "".concat(origin, "/_vendor/");
2234
+ project = target.project.rev === null ? null : "".concat(origin, "/_pvendor/").concat(target.project.rev, "/");
2235
+ entryPath = entry;
2236
+ resolveProjectPath = function resolveProjectPath(path) {
2237
+ return resolveInFiles(path, files);
2238
+ };
2239
+ /** Which project file imports which, as resolved: one edge per import. */
2240
+ imports = new Map();
2241
+ _context.n = 2;
2242
+ return loadRolldown();
2243
+ case 2:
2244
+ _yield$loadRolldown = _context.v;
2245
+ build = _yield$loadRolldown.build;
2246
+ _context.p = 3;
2247
+ _context.n = 4;
2248
+ return build({
2249
+ input: entry,
2250
+ // See `buildOnce`: required in the browser, inert here.
2251
+ cwd: "/",
2252
+ moduleTypes: {
2253
+ ".css": "empty"
2254
+ },
2255
+ plugins: [{
2256
+ name: "val:modules",
2257
+ resolveId: function resolveId(source, importer) {
2258
+ var resolved = resolveOne(source, importer);
2259
+ // A project file importing a project file: an edge of the graph
2260
+ // the dependencies are read from.
2261
+ if (importer !== undefined && importer in files && typeof resolved === "string" && resolved in files) {
2262
+ var from = imports.get(importer);
2263
+ if (from === undefined) {
2264
+ from = new Set();
2265
+ imports.set(importer, from);
2266
+ }
2267
+ from.add(resolved);
2268
+ }
2269
+ return resolved;
2270
+ },
2271
+ load: function load(id) {
2272
+ return id in files ? files[id] : null;
2273
+ }
2274
+ }],
2275
+ transform: {
2276
+ jsx: {
2277
+ runtime: "automatic",
2278
+ importSource: "react"
2279
+ }
2280
+ },
2281
+ output: {
2282
+ format: "esm",
2283
+ minify: false,
2284
+ // One module: `def: () => import("./x.val")` stays a dynamic import of
2285
+ // something already in the file.
2286
+ codeSplitting: false
2287
+ },
2288
+ write: false
2289
+ });
2290
+ case 4:
2291
+ result = _context.v;
2292
+ _context.n = 6;
2293
+ break;
2294
+ case 5:
2295
+ _context.p = 5;
2296
+ _t = _context.v;
2297
+ throw new Error(["The Val modules could not be bundled."].concat(warnings, [_t instanceof Error ? _t.message : String(_t)]).join("\n"), {
2298
+ cause: _t
2299
+ });
2300
+ case 6:
2301
+ chunks = result.output.filter(function (output) {
2302
+ return output.type === "chunk";
2303
+ });
2304
+ if (!(chunks.length !== 1)) {
2305
+ _context.n = 7;
2306
+ break;
2307
+ }
2308
+ throw new Error("Bundling the Val modules made ".concat(chunks.length, " chunks rather than one."));
2309
+ case 7:
2310
+ return _context.a(2, {
2311
+ code: chunks[0].code,
2312
+ dependencies: moduleDependenciesOf(imports)
2313
+ });
2314
+ }
2315
+ }, _callee, null, [[3, 5]]);
2316
+ }));
2317
+ return _bundleValModules.apply(this, arguments);
2318
+ }
2319
+ function moduleDependenciesOf(imports) {
2320
+ var dependencies = {};
2321
+ var isModule = function isModule(path) {
2322
+ return /\.val\.(ts|js)$/.test(path);
2323
+ };
2324
+ var isEntry = function isEntry(path) {
2325
+ return path.endsWith(".val.json");
2326
+ };
2327
+ var modules = new Set();
2328
+ var _iterator = regeneratorValues._createForOfIteratorHelper(imports),
2329
+ _step;
2330
+ try {
2331
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
2332
+ var _step$value = regeneratorValues._slicedToArray(_step.value, 2),
2333
+ from = _step$value[0],
2334
+ to = _step$value[1];
2335
+ if (isModule(from)) modules.add(from);
2336
+ var _iterator3 = regeneratorValues._createForOfIteratorHelper(to),
2337
+ _step3;
2338
+ try {
2339
+ for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
2340
+ var path = _step3.value;
2341
+ if (isModule(path)) modules.add(path);
2342
+ }
2343
+ } catch (err) {
2344
+ _iterator3.e(err);
2345
+ } finally {
2346
+ _iterator3.f();
2347
+ }
2348
+ }
2349
+ } catch (err) {
2350
+ _iterator.e(err);
2351
+ } finally {
2352
+ _iterator.f();
2353
+ }
2354
+ var _iterator2 = regeneratorValues._createForOfIteratorHelper(regeneratorValues._toConsumableArray(modules).sort()),
2355
+ _step2;
2356
+ try {
2357
+ for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
2358
+ var _imports$get;
2359
+ var module = _step2.value;
2360
+ var seen = new Set();
2361
+ var queue = regeneratorValues._toConsumableArray((_imports$get = imports.get(module)) !== null && _imports$get !== void 0 ? _imports$get : []);
2362
+ while (queue.length > 0) {
2363
+ var _imports$get2;
2364
+ var next = queue.pop();
2365
+ if (next === module || seen.has(next) || isEntry(next)) continue;
2366
+ seen.add(next);
2367
+ queue.push.apply(queue, regeneratorValues._toConsumableArray((_imports$get2 = imports.get(next)) !== null && _imports$get2 !== void 0 ? _imports$get2 : []));
2368
+ }
2369
+ dependencies[module] = regeneratorValues._toConsumableArray(seen).sort();
2370
+ }
2371
+ } catch (err) {
2372
+ _iterator2.e(err);
2373
+ } finally {
2374
+ _iterator2.f();
2375
+ }
2376
+ return dependencies;
2377
+ }
2378
+
2379
+ /**
2380
+ * A build's `val.modules` registry, as the build emits it beside its client
2381
+ * chunks: `{ "val-modules-<build>.js": code }`, served at `/_app/` with
2382
+ * them, its npm imports pointing at the site's vendor chunks on its own
2383
+ * origin (`/_vendor/`, `/_pvendor/<rev>/`) as the client bundle's do.
2384
+ *
2385
+ * What a Studio opened on an older build imports, once the server's
2386
+ * manifest names it (`registry`, from the build's name the platform hands
2387
+ * the server: `VAL_BUILD`), to take this build's schemas in WITHOUT
2388
+ * reloading the page: `HostStore.reloadCode` in `@valbuild/ui`, and phase 9
2389
+ * of `docs/plans/one-content-model.md` in valbuild/val.
2390
+ *
2391
+ * Empty -- and the build goes on -- for a project with no `val.modules.ts`,
2392
+ * or one whose Val modules cannot be bundled for the browser (a `.val.ts`
2393
+ * importing something server-only): such a build has no entry, and a Studio
2394
+ * that cannot import one reloads the page instead, as it did before. Said
2395
+ * in the build's warnings.
2396
+ */
2397
+ function valModulesEntry(_x2, _x3, _x4) {
2398
+ return _valModulesEntry.apply(this, arguments);
2399
+ }
2400
+ function _valModulesEntry() {
2401
+ _valModulesEntry = regeneratorValues._asyncToGenerator(/*#__PURE__*/regeneratorValues._regenerator().m(function _callee2(input, build, warnings) {
2402
+ var entry, _yield$bundleValModul, code, dependencies, _t2;
2403
+ return regeneratorValues._regenerator().w(function (_context2) {
2404
+ while (1) switch (_context2.p = _context2.n) {
2405
+ case 0:
2406
+ entry = ["val.modules.ts", "val.modules.js"].find(function (path) {
2407
+ return path in input.files;
2408
+ });
2409
+ if (!(entry === undefined)) {
2410
+ _context2.n = 1;
2411
+ break;
2412
+ }
2413
+ return _context2.a(2, {
2414
+ files: {},
2415
+ dependencies: null
2416
+ });
2417
+ case 1:
2418
+ _context2.p = 1;
2419
+ _context2.n = 2;
2420
+ return bundleValModules({
2421
+ files: input.files,
2422
+ target: input.target,
2423
+ // Root-relative, as the client bundle names its vendor chunks: the
2424
+ // entry is served on the site's own origin.
2425
+ origin: "",
2426
+ entry: entry
2427
+ });
2428
+ case 2:
2429
+ _yield$bundleValModul = _context2.v;
2430
+ code = _yield$bundleValModul.code;
2431
+ dependencies = _yield$bundleValModul.dependencies;
2432
+ return _context2.a(2, {
2433
+ files: regeneratorValues._defineProperty({}, projectPaths.valModulesEntryFile(build), code),
2434
+ dependencies: dependencies
2435
+ });
2436
+ case 3:
2437
+ _context2.p = 3;
2438
+ _t2 = _context2.v;
2439
+ warnings.push("The Val modules were not emitted for the Studio, so an open Studio reloads the page to take this build's code: ".concat(_t2 instanceof Error ? _t2.message : String(_t2)));
2440
+ return _context2.a(2, {
2441
+ files: {},
2442
+ dependencies: null
2443
+ });
2444
+ }
2445
+ }, _callee2, null, [[1, 3]]);
2446
+ }));
2447
+ return _valModulesEntry.apply(this, arguments);
2448
+ }
2449
+
2450
+ /** Cheap pre-filter: skip the parse unless one of these appears in the source. */
2451
+ var MARKERS = ["createIsomorphicFn", "createServerOnlyFn", "createClientOnlyFn", "createMiddleware", "ClientOnly"];
2452
+
2453
+ /** Walks a `foo().bar().baz()` chain down to its root callee identifier. */
2454
+ function chainRoot(node) {
2455
+ var current = node;
2456
+ while (current) {
2457
+ if (current.type === "CallExpression") {
2458
+ var callee = current.callee;
2459
+ if ((callee === null || callee === void 0 ? void 0 : callee.type) === "Identifier") return String(callee.name);
2460
+ if ((callee === null || callee === void 0 ? void 0 : callee.type) === "MemberExpression") {
2461
+ current = callee.object;
2462
+ continue;
2463
+ }
2464
+ return null;
2465
+ }
2466
+ return null;
2467
+ }
2468
+ return null;
2469
+ }
2470
+
2471
+ /**
2472
+ * True when this call is the whole chain rather than a link in a longer one.
2473
+ *
2474
+ * Without this, `createIsomorphicFn().client(a).server(b)` matches three times
2475
+ * and the inner replacements land inside text the outer one is about to
2476
+ * replace.
2477
+ */
2478
+ function isOutermost(node, stack) {
2479
+ var parent = stack[stack.length - 1];
2480
+ var grandparent = stack[stack.length - 2];
2481
+ return !((parent === null || parent === void 0 ? void 0 : parent.type) === "MemberExpression" && parent.object === node && (grandparent === null || grandparent === void 0 ? void 0 : grandparent.type) === "CallExpression");
2482
+ }
2483
+
2484
+ /** Collects `.method(arg)` calls along a chain, nearest-root first. */
2485
+ function methodsOf(node) {
2486
+ var found = new Map();
2487
+ var current = node;
2488
+ while (((_current = current) === null || _current === void 0 ? void 0 : _current.type) === "CallExpression") {
2489
+ var _current, _name, _callee$property, _current$arguments;
2490
+ var callee = current.callee;
2491
+ if ((callee === null || callee === void 0 ? void 0 : callee.type) !== "MemberExpression") break;
2492
+ var name = String((_name = (_callee$property = callee.property) === null || _callee$property === void 0 ? void 0 : _callee$property.name) !== null && _name !== void 0 ? _name : "");
2493
+ // Nearest-to-root wins, so a later duplicate does not shadow the first.
2494
+ found.set(name, {
2495
+ call: current,
2496
+ arg: (_current$arguments = current.arguments) === null || _current$arguments === void 0 ? void 0 : _current$arguments[0],
2497
+ objectEnd: callee.object.end
2498
+ });
2499
+ current = callee.object;
2500
+ }
2501
+ return found;
2502
+ }
2503
+ /**
2504
+ * Rewrites the environment markers in one module for one target.
2505
+ *
2506
+ * Returns `null` when the module contains none, so the caller leaves it alone
2507
+ * and pays no parse.
2508
+ */
2509
+ function transformEnvMarkers(_x, _x2, _x3) {
2510
+ return _transformEnvMarkers.apply(this, arguments);
2511
+ }
2512
+ function _transformEnvMarkers() {
2513
+ _transformEnvMarkers = regeneratorValues._asyncToGenerator(/*#__PURE__*/regeneratorValues._regenerator().m(function _callee(moduleId, code, target) {
2514
+ var ast, imported, edits, applied, text;
2515
+ return regeneratorValues._regenerator().w(function (_context) {
2516
+ while (1) switch (_context.n) {
2517
+ case 0:
2518
+ if (MARKERS.some(function (marker) {
1967
2519
  return code.includes(marker);
1968
2520
  })) {
1969
2521
  _context.n = 1;
@@ -2685,273 +3237,92 @@ function deleteProperties(code, properties, doomed) {
2685
3237
  });
2686
3238
  }
2687
3239
  i = j;
2688
- }
2689
- return edits;
2690
- }
2691
-
2692
- /**
2693
- * Removes server-only route options from one module.
2694
- *
2695
- * Returns `null` when there is nothing to do, so the caller pays no parse.
2696
- * Server and rsc targets always get `null`: they are the ones that need these.
2697
- */
2698
- function transformRouteNodes(_x, _x2, _x3) {
2699
- return _transformRouteNodes.apply(this, arguments);
2700
- }
2701
- function _transformRouteNodes() {
2702
- _transformRouteNodes = regeneratorValues._asyncToGenerator(/*#__PURE__*/regeneratorValues._regenerator().m(function _callee(moduleId, code, target) {
2703
- var ast, imported, edits, removed;
2704
- return regeneratorValues._regenerator().w(function (_context) {
2705
- while (1) switch (_context.n) {
2706
- case 0:
2707
- if (!(target !== "client")) {
2708
- _context.n = 1;
2709
- break;
2710
- }
2711
- return _context.a(2, null);
2712
- case 1:
2713
- if (shouldRun(code)) {
2714
- _context.n = 2;
2715
- break;
2716
- }
2717
- return _context.a(2, null);
2718
- case 2:
2719
- _context.n = 3;
2720
- return parse(moduleId, code);
2721
- case 3:
2722
- ast = _context.v;
2723
- imported = tanstackImports(ast);
2724
- if (!(imported.size === 0)) {
2725
- _context.n = 4;
2726
- break;
2727
- }
2728
- return _context.a(2, null);
2729
- case 4:
2730
- edits = [];
2731
- removed = [];
2732
- walk(ast, function (node, stack) {
2733
- var _options$properties;
2734
- if (node.type !== "CallExpression") return;
2735
- var callee = node.callee;
2736
- if ((callee === null || callee === void 0 ? void 0 : callee.type) !== "Identifier") return;
2737
- var name = String(callee.name);
2738
- if (!ROUTE_FNS.has(name) || !imported.has(name)) return;
2739
- var options = routeOptionsOf(node, stack);
2740
- if (!options) return;
2741
- var properties = (_options$properties = options.properties) !== null && _options$properties !== void 0 ? _options$properties : [];
2742
- var doomed = new Set();
2743
- var _iterator = regeneratorValues._createForOfIteratorHelper(properties),
2744
- _step;
2745
- try {
2746
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
2747
- var property = _step.value;
2748
- var key = propertyName(property);
2749
- if (!key || !SERVER_ONLY_OPTIONS.has(key)) continue;
2750
- doomed.add(property);
2751
- removed.push(key);
2752
- }
2753
- } catch (err) {
2754
- _iterator.e(err);
2755
- } finally {
2756
- _iterator.f();
2757
- }
2758
- if (doomed.size) edits.push.apply(edits, regeneratorValues._toConsumableArray(deleteProperties(code, properties, doomed)));
2759
- });
2760
- if (!(edits.length === 0)) {
2761
- _context.n = 5;
2762
- break;
2763
- }
2764
- return _context.a(2, null);
2765
- case 5:
2766
- return _context.a(2, {
2767
- code: applyEdits(code, edits),
2768
- removed: removed
2769
- });
2770
- }
2771
- }, _callee);
2772
- }));
2773
- return _transformRouteNodes.apply(this, arguments);
2774
- }
2775
-
2776
- /**
2777
- * JSON with comments and trailing commas, which is what tsconfig.json is.
2778
- *
2779
- * Written as a scanner rather than a regex on purpose: `"url": "https://x"`
2780
- * contains `//`, and a regex that strips comments without tracking string state
2781
- * truncates the file there and throws a parse error pointing at the wrong line.
2782
- */
2783
- function parseJsonc(text) {
2784
- var out = "";
2785
- var i = 0;
2786
- while (i < text.length) {
2787
- var ch = text[i];
2788
- if (ch === '"') {
2789
- // Copy the whole string literal, escapes included, untouched.
2790
- out += ch;
2791
- i++;
2792
- while (i < text.length) {
2793
- var c = text[i];
2794
- out += c;
2795
- i++;
2796
- if (c === "\\") {
2797
- if (i < text.length) out += text[i++];
2798
- continue;
2799
- }
2800
- if (c === '"') break;
2801
- }
2802
- continue;
2803
- }
2804
- if (ch === "/" && text[i + 1] === "/") {
2805
- while (i < text.length && text[i] !== "\n") i++;
2806
- continue;
2807
- }
2808
- if (ch === "/" && text[i + 1] === "*") {
2809
- i += 2;
2810
- while (i < text.length && !(text[i] === "*" && text[i + 1] === "/")) i++;
2811
- i += 2;
2812
- continue;
2813
- }
2814
- out += ch;
2815
- i++;
2816
- }
2817
- // Trailing commas, now that every remaining comma is structural.
2818
- return JSON.parse(out.replace(/,(\s*[}\]])/g, "$1"));
2819
- }
2820
-
2821
- /** One `paths` entry, pre-split on its wildcard. */
2822
-
2823
- /**
2824
- * Reads tsconfig.json out of the file record and builds the matcher.
2825
- *
2826
- * Returns null when the project configures no aliases, which is the common
2827
- * case and costs nothing.
2828
- */
2829
- function aliasMap(files, warn) {
2830
- var _config$compilerOptio, _config$compilerOptio2;
2831
- var entry = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "tsconfig.json";
2832
- var config = readConfig(files, entry, warn, new Set());
2833
- var paths = config === null || config === void 0 || (_config$compilerOptio = config.compilerOptions) === null || _config$compilerOptio === void 0 ? void 0 : _config$compilerOptio.paths;
2834
- var baseUrl = config === null || config === void 0 || (_config$compilerOptio2 = config.compilerOptions) === null || _config$compilerOptio2 === void 0 ? void 0 : _config$compilerOptio2.baseUrl;
2835
- // A project can configure either one without the other, and baseUrl alone is
2836
- // enough to change how a bare specifier resolves.
2837
- if ((!paths || Object.keys(paths).length === 0) && baseUrl === undefined) return null;
2838
-
2839
- // `baseUrl` is relative to the tsconfig that declared it. Since TS 4.1 paths
2840
- // work without one, resolved against the tsconfig's own directory -- so the
2841
- // fallback here is the directory, not the project root.
2842
- var base = resolve(dirname(entry), baseUrl !== null && baseUrl !== void 0 ? baseUrl : ".");
2843
- var patterns = [];
2844
- for (var _i = 0, _Object$entries = Object.entries(paths !== null && paths !== void 0 ? paths : {}); _i < _Object$entries.length; _i++) {
2845
- var _Object$entries$_i = regeneratorValues._slicedToArray(_Object$entries[_i], 2),
2846
- pattern = _Object$entries$_i[0],
2847
- targets = _Object$entries$_i[1];
2848
- var star = pattern.indexOf("*");
2849
- if (star !== pattern.lastIndexOf("*")) {
2850
- warn("tsconfig paths pattern '".concat(pattern, "' has more than one '*' and is ignored."));
2851
- continue;
2852
- }
2853
- patterns.push({
2854
- prefix: star === -1 ? pattern : pattern.slice(0, star),
2855
- suffix: star === -1 ? "" : pattern.slice(star + 1),
2856
- wildcard: star !== -1,
2857
- targets: targets.map(function (target) {
2858
- return resolve(base, target);
2859
- })
2860
- });
2861
- }
2862
-
2863
- // TypeScript picks the pattern with the longest literal prefix, so `@/ui/*`
2864
- // beats `@/*` for `@/ui/card` regardless of declaration order.
2865
- patterns.sort(function (a, b) {
2866
- return b.prefix.length - a.prefix.length;
2867
- });
2868
- return {
2869
- patterns: Object.keys(paths !== null && paths !== void 0 ? paths : {}),
2870
- baseUrlCandidate: function baseUrlCandidate(specifier) {
2871
- return baseUrl === undefined ? null : resolve(base, specifier);
2872
- },
2873
- candidates: function candidates(specifier) {
2874
- var _loop = function _loop() {
2875
- var pattern = _patterns[_i2];
2876
- if (!pattern.wildcard) {
2877
- if (specifier === pattern.prefix) return {
2878
- v: regeneratorValues._toConsumableArray(pattern.targets)
2879
- };
2880
- return 0; // continue
2881
- }
2882
- if (!specifier.startsWith(pattern.prefix) || !specifier.endsWith(pattern.suffix) || specifier.length < pattern.prefix.length + pattern.suffix.length) {
2883
- return 0; // continue
2884
- }
2885
- var matched = specifier.slice(pattern.prefix.length, specifier.length - pattern.suffix.length);
2886
- return {
2887
- v: pattern.targets.map(function (target) {
2888
- return target.replace("*", matched);
2889
- })
2890
- };
2891
- },
2892
- _ret;
2893
- for (var _i2 = 0, _patterns = patterns; _i2 < _patterns.length; _i2++) {
2894
- _ret = _loop();
2895
- if (_ret === 0) continue;
2896
- if (_ret) return _ret.v;
2897
- }
2898
- return [];
2899
- }
2900
- };
2901
- }
2902
-
2903
- /** Follows `extends` through the file record. Package extends cannot be read. */
2904
- function readConfig(files, path, warn, seen) {
2905
- var _config, _config$compilerOptio4, _config$compilerOptio5, _parent$compilerOptio;
2906
- if (seen.has(path)) return null; // a cycle; whatever we have is enough
2907
- seen.add(path);
2908
- var text = files[path];
2909
- if (text === undefined) return null;
2910
- var config;
2911
- try {
2912
- config = parseJsonc(text);
2913
- } catch (error) {
2914
- var _message;
2915
- warn("Could not parse ".concat(path, ": ").concat(String((_message = error === null || error === void 0 ? void 0 : error.message) !== null && _message !== void 0 ? _message : error)));
2916
- return null;
2917
- }
2918
- if (!((_config = config) !== null && _config !== void 0 && _config["extends"])) return config;
2919
-
2920
- // Only a relative extends can be followed: a package one ("extends":
2921
- // "@tsconfig/node20/tsconfig.json") lives in node_modules, which a browser
2922
- // build does not have. Worth saying out loud rather than silently resolving
2923
- // half the aliases, because the base config is where a monorepo usually puts
2924
- // them.
2925
- if (!config["extends"].startsWith(".")) {
2926
- var _config$compilerOptio3;
2927
- if (!((_config$compilerOptio3 = config.compilerOptions) !== null && _config$compilerOptio3 !== void 0 && _config$compilerOptio3.paths)) {
2928
- warn("".concat(path, " extends '").concat(config["extends"], "', which is a package and cannot be read here. ") + "Any 'paths' it declares will not apply -- declare them in ".concat(path, " instead."));
2929
- }
2930
- return config;
2931
- }
2932
- var parentPath = resolveConfigPath(files, resolve(dirname(path), config["extends"]));
2933
- var parent = parentPath ? readConfig(files, parentPath, warn, seen) : null;
2934
- if (!parent) return config;
2935
-
2936
- // The child wins, and `paths` replaces rather than merges -- which is what
2937
- // TypeScript does.
2938
- return {
2939
- compilerOptions: regeneratorValues._objectSpread2(regeneratorValues._objectSpread2(regeneratorValues._objectSpread2({}, parent.compilerOptions), config.compilerOptions), {}, {
2940
- // baseUrl in the parent was relative to the *parent*, and readConfig
2941
- // returns it unresolved, so a parent baseUrl with a child that sets none
2942
- // is the one case this gets wrong. Rare enough to name rather than model.
2943
- paths: (_config$compilerOptio4 = (_config$compilerOptio5 = config.compilerOptions) === null || _config$compilerOptio5 === void 0 ? void 0 : _config$compilerOptio5.paths) !== null && _config$compilerOptio4 !== void 0 ? _config$compilerOptio4 : (_parent$compilerOptio = parent.compilerOptions) === null || _parent$compilerOptio === void 0 ? void 0 : _parent$compilerOptio.paths
2944
- })
2945
- };
3240
+ }
3241
+ return edits;
2946
3242
  }
2947
3243
 
2948
- /** `extends: './base'` may omit the .json. */
2949
- function resolveConfigPath(files, path) {
2950
- for (var _i3 = 0, _arr = [path, "".concat(path, ".json")]; _i3 < _arr.length; _i3++) {
2951
- var candidate = _arr[_i3];
2952
- if (candidate in files) return candidate;
2953
- }
2954
- return null;
3244
+ /**
3245
+ * Removes server-only route options from one module.
3246
+ *
3247
+ * Returns `null` when there is nothing to do, so the caller pays no parse.
3248
+ * Server and rsc targets always get `null`: they are the ones that need these.
3249
+ */
3250
+ function transformRouteNodes(_x, _x2, _x3) {
3251
+ return _transformRouteNodes.apply(this, arguments);
3252
+ }
3253
+ function _transformRouteNodes() {
3254
+ _transformRouteNodes = regeneratorValues._asyncToGenerator(/*#__PURE__*/regeneratorValues._regenerator().m(function _callee(moduleId, code, target) {
3255
+ var ast, imported, edits, removed;
3256
+ return regeneratorValues._regenerator().w(function (_context) {
3257
+ while (1) switch (_context.n) {
3258
+ case 0:
3259
+ if (!(target !== "client")) {
3260
+ _context.n = 1;
3261
+ break;
3262
+ }
3263
+ return _context.a(2, null);
3264
+ case 1:
3265
+ if (shouldRun(code)) {
3266
+ _context.n = 2;
3267
+ break;
3268
+ }
3269
+ return _context.a(2, null);
3270
+ case 2:
3271
+ _context.n = 3;
3272
+ return parse(moduleId, code);
3273
+ case 3:
3274
+ ast = _context.v;
3275
+ imported = tanstackImports(ast);
3276
+ if (!(imported.size === 0)) {
3277
+ _context.n = 4;
3278
+ break;
3279
+ }
3280
+ return _context.a(2, null);
3281
+ case 4:
3282
+ edits = [];
3283
+ removed = [];
3284
+ walk(ast, function (node, stack) {
3285
+ var _options$properties;
3286
+ if (node.type !== "CallExpression") return;
3287
+ var callee = node.callee;
3288
+ if ((callee === null || callee === void 0 ? void 0 : callee.type) !== "Identifier") return;
3289
+ var name = String(callee.name);
3290
+ if (!ROUTE_FNS.has(name) || !imported.has(name)) return;
3291
+ var options = routeOptionsOf(node, stack);
3292
+ if (!options) return;
3293
+ var properties = (_options$properties = options.properties) !== null && _options$properties !== void 0 ? _options$properties : [];
3294
+ var doomed = new Set();
3295
+ var _iterator = regeneratorValues._createForOfIteratorHelper(properties),
3296
+ _step;
3297
+ try {
3298
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
3299
+ var property = _step.value;
3300
+ var key = propertyName(property);
3301
+ if (!key || !SERVER_ONLY_OPTIONS.has(key)) continue;
3302
+ doomed.add(property);
3303
+ removed.push(key);
3304
+ }
3305
+ } catch (err) {
3306
+ _iterator.e(err);
3307
+ } finally {
3308
+ _iterator.f();
3309
+ }
3310
+ if (doomed.size) edits.push.apply(edits, regeneratorValues._toConsumableArray(deleteProperties(code, properties, doomed)));
3311
+ });
3312
+ if (!(edits.length === 0)) {
3313
+ _context.n = 5;
3314
+ break;
3315
+ }
3316
+ return _context.a(2, null);
3317
+ case 5:
3318
+ return _context.a(2, {
3319
+ code: applyEdits(code, edits),
3320
+ removed: removed
3321
+ });
3322
+ }
3323
+ }, _callee);
3324
+ }));
3325
+ return _transformRouteNodes.apply(this, arguments);
2955
3326
  }
2956
3327
 
2957
3328
  // autoCodeSplitting.
@@ -3478,6 +3849,11 @@ var CSS_URL_ID = "\0platform:css-url";
3478
3849
  * would be both a leak and, for a real app, enormous.
3479
3850
  */
3480
3851
  var PROJECT_SOURCE = "platform:project-source";
3852
+ /**
3853
+ * The global the server build defines as each Val module's project
3854
+ * dependencies (`valModulesEntry`), read by the generated `val.server.ts`.
3855
+ */
3856
+ var MODULE_DEPENDENCIES_GLOBAL = "globalThis.__VAL_MODULE_DEPENDENCIES__";
3481
3857
  var PROJECT_SOURCE_ID = "\0platform:project-source";
3482
3858
  var PUBLIC_PREFIX = "PUBLIC_";
3483
3859
  var VALID_KEY = /^[A-Za-z_][A-Za-z0-9_]*$/;
@@ -3811,19 +4187,40 @@ function projectPlugin(files, projectSource, splitter, cssModules, aliases, asse
3811
4187
  }
3812
4188
 
3813
4189
  /**
3814
- * Build-time env substitution.
4190
+ * What `import.meta.env` is in a build: Vite's built-ins, inlined, and the
4191
+ * project's `PUBLIC_` variables, read at RUNTIME.
4192
+ *
4193
+ * Runtime because a hosted project's variables are set in Val Build, and a
4194
+ * build is made in an editor's browser tab: inlined, a value would sit in that
4195
+ * tab, and changing one would wait for somebody to build before it went live.
4196
+ * So `import.meta.env` is an identifier, and `inject` makes each module that
4197
+ * reads it import {@link RUNTIME_ENV_SPECIFIER} -- a real import, so it is
4198
+ * evaluated before any split chunk that reads it, top level included. That
4199
+ * module ({@link runtimeEnvSource}) reads the variables once:
3815
4200
  *
3816
- * Values are inlined as literals rather than read at runtime, which is why they
3817
- * cost nothing to use and why changing one produces a new build hash: the
3818
- * output genuinely differs.
4201
+ * - in the browser, from the `<head>` script the platform's loader writes
4202
+ * (`globalThis.__PLATFORM_PUBLIC_ENV`), which runs before any module does;
4203
+ * - on the server, from `process.env`, which the isolate's env fills before the
4204
+ * app's modules run.
3819
4205
  *
3820
- * Non-public keys resolve to `undefined` in the client bundle rather than being
3821
- * left alone. An untouched `import.meta.env.SECRET` would throw in the browser,
3822
- * and a silent `undefined` is both safer and easier to reason about.
4206
+ * Only `PUBLIC_` names, on both sides, as in Vite: a secret is
4207
+ * `process.env.NAME` on the server and nothing at all in the browser. The
4208
+ * platform refuses a secret by a `PUBLIC_` name, so nothing read here was ever
4209
+ * a secret.
4210
+ *
4211
+ * `env`, when a caller passes it, is still inlined as literals and wins -- the
4212
+ * CLI's `--env`, and every build from before this. Non-public keys of it
4213
+ * resolve to `undefined` in the client bundle rather than being left alone.
3823
4214
  */
3824
- function defineFor(env, target, warnings) {
4215
+ function envFor(env, target, warnings) {
3825
4216
  var define = {};
3826
- var visible = {};
4217
+ /**
4218
+ * What the `import.meta.env` OBJECT holds of `env`: the PUBLIC_ names, on
4219
+ * both sides, as Vite's does. A server-only name is still a literal where it
4220
+ * is read by name (above), and nowhere else -- in the object it would be in
4221
+ * the server bundle whether anything read it or not.
4222
+ */
4223
+ var inObject = {};
3827
4224
  for (var _i = 0, _Object$entries = Object.entries(env); _i < _Object$entries.length; _i++) {
3828
4225
  var _Object$entries$_i = regeneratorValues._slicedToArray(_Object$entries[_i], 2),
3829
4226
  key = _Object$entries$_i[0],
@@ -3836,7 +4233,7 @@ function defineFor(env, target, warnings) {
3836
4233
  var literal = exposed ? JSON.stringify(value) : "undefined";
3837
4234
  define["import.meta.env.".concat(key)] = literal;
3838
4235
  define["process.env.".concat(key)] = literal;
3839
- if (exposed) visible[key] = value;
4236
+ if (key.startsWith(PUBLIC_PREFIX)) inObject[key] = value;
3840
4237
  }
3841
4238
 
3842
4239
  // Vite's built-ins, and they win over a project env var of the same name as
@@ -3863,25 +4260,64 @@ function defineFor(env, target, warnings) {
3863
4260
  // "development" -- so a published site's code was told it was in dev.
3864
4261
  define["process.env.NODE_ENV"] = JSON.stringify("production");
3865
4262
 
3866
- // Always defined, even when empty: it makes `import.meta.env` destructuring
3867
- // work and stops a bare reference from throwing. Specific keys above take
3868
- // precedence over this object.
3869
- define["import.meta.env"] = JSON.stringify(regeneratorValues._objectSpread2(regeneratorValues._objectSpread2({}, visible), builtins));
3870
- return define;
4263
+ // Always defined: it makes `import.meta.env` destructuring work and stops a
4264
+ // bare reference from throwing. Specific keys above take precedence.
4265
+ define["import.meta.env"] = RUNTIME_ENV;
4266
+ // In the browser `process` does not exist, so an untouched
4267
+ // `process.env.PUBLIC_X` threw there. Read as the same object instead.
4268
+ if (target === "client") define["process.env"] = RUNTIME_ENV;
4269
+ return {
4270
+ define: define,
4271
+ runtime: runtimeEnvSource(target, regeneratorValues._objectSpread2(regeneratorValues._objectSpread2({}, inObject), builtins))
4272
+ };
4273
+ }
4274
+
4275
+ /**
4276
+ * The identifier `import.meta.env` becomes, and the module `inject` imports
4277
+ * for it. The specifier is resolved by {@link runtimeEnvPlugin} and nothing
4278
+ * else, and a project cannot name it: `platform:` is not a package.
4279
+ */
4280
+ var RUNTIME_ENV = "__PLATFORM_RUNTIME_ENV__";
4281
+ var RUNTIME_ENV_SPECIFIER = "platform:runtime-env";
4282
+ var RUNTIME_ENV_ID = "\0platform:runtime-env";
4283
+
4284
+ /**
4285
+ * The module {@link RUNTIME_ENV} imports. `fixed` -- the built-ins, and any
4286
+ * `env` the caller inlined -- wins over a runtime value of the same name.
4287
+ *
4288
+ * `globalThis.process?.env` rather than `process.env`: a server bundle that
4289
+ * runs where there is no `process` reads no variables instead of throwing.
4290
+ */
4291
+ function runtimeEnvSource(target, fixed) {
4292
+ var read = target === "client" ? "globalThis.__PLATFORM_PUBLIC_ENV" : "globalThis.process?.env";
4293
+ return "const source = ".concat(read, " ?? {};\n") + "const runtime = {};\n" + "for (const name of Object.keys(source)) {\n" + " if (name.startsWith(".concat(JSON.stringify(PUBLIC_PREFIX), ")) runtime[name] = source[name];\n") + "}\n" + "export default Object.freeze(Object.assign(runtime, ".concat(JSON.stringify(fixed, null, 2), "));\n");
4294
+ }
4295
+ function runtimeEnvPlugin(source) {
4296
+ return {
4297
+ name: "platform:runtime-env",
4298
+ resolveId: function resolveId(id) {
4299
+ return id === RUNTIME_ENV_SPECIFIER ? RUNTIME_ENV_ID : null;
4300
+ },
4301
+ load: function load(id) {
4302
+ return id === RUNTIME_ENV_ID ? source : null;
4303
+ }
4304
+ };
3871
4305
  }
3872
4306
  function buildOnce(_x, _x2, _x3, _x4, _x5) {
3873
4307
  return _buildOnce.apply(this, arguments);
3874
4308
  }
3875
4309
  function _buildOnce() {
3876
4310
  _buildOnce = regeneratorValues._asyncToGenerator(/*#__PURE__*/regeneratorValues._regenerator().m(function _callee2(input, vendorBase, projectVendorBase, target, warnings) {
3877
- var _input$projectSource, _input$assets, _input$env;
4311
+ var _input$env, _input$projectSource, _input$assets;
3878
4312
  var clientModules,
3879
4313
  isRsc,
3880
4314
  assetUrls,
3881
4315
  cssModules,
3882
4316
  aliases,
4317
+ moduleDependencies,
3883
4318
  vendor,
3884
4319
  projectVendor,
4320
+ env,
3885
4321
  _yield$loadRolldown,
3886
4322
  build,
3887
4323
  result,
@@ -3900,6 +4336,7 @@ function _buildOnce() {
3900
4336
  assetUrls = _args2.length > 7 && _args2[7] !== undefined ? _args2[7] : new Map();
3901
4337
  cssModules = _args2.length > 8 && _args2[8] !== undefined ? _args2[8] : {};
3902
4338
  aliases = _args2.length > 9 && _args2[9] !== undefined ? _args2[9] : null;
4339
+ moduleDependencies = _args2.length > 10 && _args2[10] !== undefined ? _args2[10] : null;
3903
4340
  vendor = vendorRules(input.target);
3904
4341
  /*
3905
4342
  * The project's own layer, in the shape the plugin already reads.
@@ -3913,7 +4350,8 @@ function _buildOnce() {
3913
4350
  modules: input.target.project.modules,
3914
4351
  css: input.target.project.css,
3915
4352
  workerOnly: input.target.project.workerOnly
3916
- }; // The RSC pass is a server build in every respect the transforms care about:
4353
+ };
4354
+ env = envFor((_input$env = input.env) !== null && _input$env !== void 0 ? _input$env : {}, target, warnings); // The RSC pass is a server build in every respect the transforms care about:
3917
4355
  // it runs on the server, so server-only code stays and client-only code goes.
3918
4356
  // Only the vendor layer differs.
3919
4357
  _context2.n = 1;
@@ -3936,7 +4374,7 @@ function _buildOnce() {
3936
4374
  moduleTypes: {
3937
4375
  ".css": "empty"
3938
4376
  },
3939
- plugins: [projectPlugin(input.files, (_input$projectSource = input.projectSource) !== null && _input$projectSource !== void 0 ? _input$projectSource : input.files, input.routeSplitter, cssModules, aliases, (_input$assets = input.assets) !== null && _input$assets !== void 0 ? _input$assets : {}, assetUrls, vendorBase, projectVendorBase, projectVendor, vendor, warnings, target, new Set(), clientModules, isRsc)],
4377
+ plugins: [runtimeEnvPlugin(env.runtime), projectPlugin(input.files, (_input$projectSource = input.projectSource) !== null && _input$projectSource !== void 0 ? _input$projectSource : input.files, input.routeSplitter, cssModules, aliases, (_input$assets = input.assets) !== null && _input$assets !== void 0 ? _input$assets : {}, assetUrls, vendorBase, projectVendorBase, projectVendor, vendor, warnings, target, new Set(), clientModules, isRsc)],
3940
4378
  // oxc handles TS and JSX natively, so there is no separate transform pass
3941
4379
  // and no type-checking on the publish path. Types are the editor's job.
3942
4380
  transform: {
@@ -3944,7 +4382,8 @@ function _buildOnce() {
3944
4382
  runtime: "automatic",
3945
4383
  importSource: "react"
3946
4384
  },
3947
- define: defineFor((_input$env = input.env) !== null && _input$env !== void 0 ? _input$env : {}, target, warnings)
4385
+ define: regeneratorValues._objectSpread2(regeneratorValues._objectSpread2({}, env.define), target === "server" && moduleDependencies !== null ? regeneratorValues._defineProperty({}, MODULE_DEPENDENCIES_GLOBAL, JSON.stringify(moduleDependencies)) : {}),
4386
+ inject: regeneratorValues._defineProperty({}, RUNTIME_ENV, RUNTIME_ENV_SPECIFIER)
3948
4387
  },
3949
4388
  output: {
3950
4389
  format: "esm",
@@ -4020,7 +4459,7 @@ function buildUserApp(_x6) {
4020
4459
  function _buildUserApp() {
4021
4460
  _buildUserApp = regeneratorValues._asyncToGenerator(/*#__PURE__*/regeneratorValues._regenerator().m(function _callee3(input) {
4022
4461
  var _input$target$project;
4023
- var warnings, started, rev, clientModules, assetUrls, assetFiles, _i3, _Object$entries3, _input$assets2, _Object$entries3$_i, path, base64, resolved, aliases, css, styles, tailwindMs, compiled, serverStarted, serverBuild, server, clientStarted, clientBuild, client, rscBuild, publicFiles, _i4, _Object$entries4, _input$publicFiles, _Object$entries4$_i, _path, _base, _t, _t2, _t3, _t4, _t5, _t6, _t7, _t8, _t9, _t0, _t1, _t10, _t11, _t12, _t13, _t14, _t15, _t16;
4462
+ var warnings, started, rev, clientModules, assetUrls, assetFiles, _i3, _Object$entries3, _input$assets2, _Object$entries3$_i, path, base64, resolved, aliases, css, styles, tailwindMs, compiled, hash, registryEntry, serverStarted, serverBuild, server, clientStarted, clientBuild, client, rscBuild, publicFiles, _i4, _Object$entries4, _input$publicFiles, _Object$entries4$_i, _path, _base, _t, _t2, _t3, _t4, _t5, _t6, _t7, _t8, _t9, _t0, _t1, _t10, _t11, _t12, _t13, _t14, _t15, _t16;
4024
4463
  return regeneratorValues._regenerator().w(function (_context3) {
4025
4464
  while (1) switch (_context3.n) {
4026
4465
  case 0:
@@ -4109,39 +4548,47 @@ function _buildUserApp() {
4109
4548
  tailwindMs = compiled.ms;
4110
4549
  warnings.push.apply(warnings, regeneratorValues._toConsumableArray(compiled.warnings));
4111
4550
  case 10:
4112
- serverStarted = performance.now();
4113
4551
  _context3.n = 11;
4114
- return buildOnce(input, "./vendor/", "./pvendor/", "server", warnings, clientModules, false, assetUrls, css.modules, aliases);
4552
+ return buildInputId(input);
4115
4553
  case 11:
4554
+ hash = _context3.v;
4555
+ _context3.n = 12;
4556
+ return valModulesEntry(input, hash, warnings);
4557
+ case 12:
4558
+ registryEntry = _context3.v;
4559
+ serverStarted = performance.now();
4560
+ _context3.n = 13;
4561
+ return buildOnce(input, "./vendor/", "./pvendor/", "server", warnings, clientModules, false, assetUrls, css.modules, aliases, registryEntry.dependencies);
4562
+ case 13:
4116
4563
  serverBuild = _context3.v;
4117
4564
  server = performance.now() - serverStarted;
4118
4565
  clientStarted = performance.now();
4119
- _context3.n = 12;
4566
+ _context3.n = 14;
4120
4567
  return buildOnce(input, "/_vendor/", "/_pvendor/".concat(rev, "/"), "client", warnings, clientModules, false, assetUrls, css.modules, aliases);
4121
- case 12:
4568
+ case 14:
4122
4569
  clientBuild = _context3.v;
4123
4570
  client = performance.now() - clientStarted; // Paths are relative to `rsc/app.js`, one directory down, so both layers are
4124
4571
  // addressed with a leading `../`. Getting this wrong does not fail the build;
4125
4572
  // the cold isolate simply refuses to boot.
4126
4573
  if (!input.rsc) {
4127
- _context3.n = 14;
4574
+ _context3.n = 16;
4128
4575
  break;
4129
4576
  }
4130
- _context3.n = 13;
4577
+ _context3.n = 15;
4131
4578
  return buildOnce(
4132
4579
  // `../pvendor/`, with no revision segment: the revision belongs in the
4133
4580
  // browser URL, where it buys immutable caching. Inside the module map
4134
4581
  // there is exactly one layer and the key is `pvendor/<name>.js`, so a
4135
4582
  // revision here is a path segment that does not exist -- and the cold
4136
4583
  // isolate is where you would find that out.
4137
- input, "../vendor-rsc/", "../pvendor/", "server", warnings, clientModules, true, assetUrls, css.modules, aliases);
4138
- case 13:
4584
+ input, "../vendor-rsc/", "../pvendor/", "server", warnings, clientModules, true, assetUrls, css.modules, aliases, registryEntry.dependencies);
4585
+ case 15:
4139
4586
  _t2 = _context3.v;
4140
- _context3.n = 15;
4587
+ _context3.n = 17;
4141
4588
  break;
4142
- case 14:
4589
+ case 16:
4143
4590
  _t2 = undefined;
4144
- case 15:
4591
+ case 17:
4145
4592
  rscBuild = _t2;
4146
4593
  // Stripped of the `public/` prefix here rather than at every consumer: the
4147
4594
  // prefix is a convention of the project layout, and what the loader needs is
@@ -4154,7 +4601,7 @@ function _buildUserApp() {
4154
4601
  _t3 = serverBuild.code;
4155
4602
  _t4 = clientBuild.code;
4156
4603
  _t5 = serverBuild.chunks;
4157
- _t6 = clientBuild.chunks;
4604
+ _t6 = regeneratorValues._objectSpread2(regeneratorValues._objectSpread2({}, clientBuild.chunks), registryEntry.files);
4158
4605
  _t7 = assetFiles;
4159
4606
  _t8 = publicFiles;
4160
4607
  _t9 = styles;
@@ -4165,15 +4612,12 @@ function _buildUserApp() {
4165
4612
  _t10 = rscBuild === null || rscBuild === void 0 ? void 0 : rscBuild.chunks;
4166
4613
  _t11 = input.rsc ? clientModules : undefined;
4167
4614
  _t12 = input.target.base.rev;
4168
- _context3.n = 16;
4169
- return buildInputId(input);
4170
- case 16:
4171
- _t13 = _context3.v;
4172
- _context3.n = 17;
4615
+ _t13 = hash;
4616
+ _context3.n = 18;
4173
4617
  return regeneratorValues.sha256Hex([input.target.base.rev, rev, styles].concat(regeneratorValues._toConsumableArray(Object.entries(assetFiles).flat()), regeneratorValues._toConsumableArray(Object.entries(publicFiles).flat()), regeneratorValues._toConsumableArray([serverBuild, clientBuild, rscBuild].flatMap(function (built) {
4174
4618
  return built ? [built.code].concat(regeneratorValues._toConsumableArray(Object.entries(built.chunks).flat())) : [];
4175
- }))).join("\0"));
4176
- case 17:
4619
+ })), regeneratorValues._toConsumableArray(Object.entries(registryEntry).flat())).join("\0"));
4620
+ case 18:
4177
4621
  _t14 = _context3.v.slice(0, 32);
4178
4622
  _t15 = {
4179
4623
  server: server,
@@ -4630,160 +5074,6 @@ function treeShaOfText(files) {
4630
5074
  })));
4631
5075
  }
4632
5076
 
4633
- /**
4634
- * A project's `val.modules.ts`, bundled to run: every `.val.ts` it imports,
4635
- * the `val.config` they share and the `.val.json` entries they name, as ONE
4636
- * ES module -- so it can be imported from a `blob:` URL, which cannot resolve
4637
- * a relative chunk -- with every npm import pointing at the site's own
4638
- * vendor chunks, at absolute URLs under `origin`.
4639
- *
4640
- * What the builder tab evaluates to learn a tree's schemas: Update from the
4641
- * site with code (valbuild/home `docs/hosted-publishing.md` step 8.2, slice
4642
- * 1b). The project's own `@valbuild/*` and dependencies are what run, as the
4643
- * site runs them -- the browser half of its layer, from `/_pvendor/<rev>/`,
4644
- * and the base layer from `/_vendor/`. Whoever imports it should do so off
4645
- * the Studio's page: `@valbuild/tanstack` brings React and patches its JSX.
4646
- *
4647
- * Nothing else of a build happens here: no route splitting, no server
4648
- * functions, no CSS -- a `.val.ts` has none of it.
4649
- */
4650
- function bundleValModules(_x) {
4651
- return _bundleValModules.apply(this, arguments);
4652
- }
4653
- function _bundleValModules() {
4654
- _bundleValModules = regeneratorValues._asyncToGenerator(/*#__PURE__*/regeneratorValues._regenerator().m(function _callee(input) {
4655
- var _input$entry;
4656
- var files, target, origin, entry, warnings, aliases, base, project, resolveProjectPath, _yield$loadRolldown, build, result, chunks, _t;
4657
- return regeneratorValues._regenerator().w(function (_context) {
4658
- while (1) switch (_context.p = _context.n) {
4659
- case 0:
4660
- files = input.files, target = input.target, origin = input.origin;
4661
- entry = (_input$entry = input.entry) !== null && _input$entry !== void 0 ? _input$entry : ["val.modules.ts", "val.modules.js"].find(function (path) {
4662
- return path in files;
4663
- });
4664
- if (!(entry === undefined || !(entry in files))) {
4665
- _context.n = 1;
4666
- break;
4667
- }
4668
- throw new Error("This project has no val.modules.ts, so its Val modules cannot be read.");
4669
- case 1:
4670
- warnings = [];
4671
- aliases = aliasMap(files, function (message) {
4672
- return warnings.push(message);
4673
- });
4674
- base = "".concat(origin, "/_vendor/");
4675
- project = target.project.rev === null ? null : "".concat(origin, "/_pvendor/").concat(target.project.rev, "/");
4676
- resolveProjectPath = function resolveProjectPath(path) {
4677
- return resolveInFiles(path, files);
4678
- };
4679
- _context.n = 2;
4680
- return loadRolldown();
4681
- case 2:
4682
- _yield$loadRolldown = _context.v;
4683
- build = _yield$loadRolldown.build;
4684
- _context.p = 3;
4685
- _context.n = 4;
4686
- return build({
4687
- input: entry,
4688
- // See `buildOnce`: required in the browser, inert here.
4689
- cwd: "/",
4690
- moduleTypes: {
4691
- ".css": "empty"
4692
- },
4693
- plugins: [{
4694
- name: "val:modules",
4695
- resolveId: function resolveId(source, importer) {
4696
- if (source.startsWith(".")) {
4697
- return resolveProjectPath(resolve(dirname(importer !== null && importer !== void 0 ? importer : entry), source));
4698
- }
4699
- if (source in files) return source;
4700
- var baseChunk = target.base.modules[source];
4701
- if (baseChunk) {
4702
- return {
4703
- id: "".concat(base).concat(baseChunk, ".js"),
4704
- external: true
4705
- };
4706
- }
4707
- var projectChunk = target.project.modules[source];
4708
- if (projectChunk && project !== null) {
4709
- if (target.project.workerOnly.includes(source)) {
4710
- throw new Error("'".concat(source, "' is server-only in this project's vendor layer, so a .val.ts importing it cannot be read in the browser."));
4711
- }
4712
- return {
4713
- id: "".concat(project).concat(projectChunk, ".js"),
4714
- external: true
4715
- };
4716
- }
4717
- if (aliases) {
4718
- var _iterator = regeneratorValues._createForOfIteratorHelper(aliases.candidates(source)),
4719
- _step;
4720
- try {
4721
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
4722
- var candidate = _step.value;
4723
- var _hit = resolveProjectPath(candidate);
4724
- if (_hit) return _hit;
4725
- }
4726
- } catch (err) {
4727
- _iterator.e(err);
4728
- } finally {
4729
- _iterator.f();
4730
- }
4731
- var fromBaseUrl = aliases.baseUrlCandidate(source);
4732
- var hit = fromBaseUrl && resolveProjectPath(fromBaseUrl);
4733
- if (hit) return hit;
4734
- }
4735
- // An error, not a warning: rolldown would otherwise leave the
4736
- // specifier as it is, and it would fail when imported, unnamed.
4737
- throw new Error("'".concat(source, "' is not an available dependency. Available: ").concat([].concat(regeneratorValues._toConsumableArray(Object.keys(target.base.modules)), regeneratorValues._toConsumableArray(Object.keys(target.project.modules))).join(", "), "."));
4738
- },
4739
- load: function load(id) {
4740
- return id in files ? files[id] : null;
4741
- }
4742
- }],
4743
- transform: {
4744
- jsx: {
4745
- runtime: "automatic",
4746
- importSource: "react"
4747
- }
4748
- },
4749
- output: {
4750
- format: "esm",
4751
- minify: false,
4752
- // One module: `def: () => import("./x.val")` stays a dynamic import of
4753
- // something already in the file.
4754
- codeSplitting: false
4755
- },
4756
- write: false
4757
- });
4758
- case 4:
4759
- result = _context.v;
4760
- _context.n = 6;
4761
- break;
4762
- case 5:
4763
- _context.p = 5;
4764
- _t = _context.v;
4765
- throw new Error(["The Val modules could not be bundled."].concat(warnings, [_t instanceof Error ? _t.message : String(_t)]).join("\n"), {
4766
- cause: _t
4767
- });
4768
- case 6:
4769
- chunks = result.output.filter(function (output) {
4770
- return output.type === "chunk";
4771
- });
4772
- if (!(chunks.length !== 1)) {
4773
- _context.n = 7;
4774
- break;
4775
- }
4776
- throw new Error("Bundling the Val modules made ".concat(chunks.length, " chunks rather than one."));
4777
- case 7:
4778
- return _context.a(2, {
4779
- code: chunks[0].code
4780
- });
4781
- }
4782
- }, _callee, null, [[3, 5]]);
4783
- }));
4784
- return _bundleValModules.apply(this, arguments);
4785
- }
4786
-
4787
5077
  exports.INLINE_LIMIT = regeneratorValues.INLINE_LIMIT;
4788
5078
  exports.base64Bytes = regeneratorValues.base64Bytes;
4789
5079
  exports.isAsset = regeneratorValues.isAsset;
@@ -4793,6 +5083,7 @@ exports.TREE = projectPaths.TREE;
4793
5083
  exports.ARTIFACT_KEYS = artifactKeys.ARTIFACT_KEYS;
4794
5084
  exports.ARTIFACT_PREFIXES = artifactKeys.ARTIFACT_PREFIXES;
4795
5085
  exports.ENTRY_CHUNK = ENTRY_CHUNK;
5086
+ exports.MODULE_DEPENDENCIES_GLOBAL = MODULE_DEPENDENCIES_GLOBAL;
4796
5087
  exports.PROJECT_SOURCE = PROJECT_SOURCE;
4797
5088
  exports.PUBLIC_PREFIX = PUBLIC_PREFIX;
4798
5089
  exports.VAL_SERVER_PATH = VAL_SERVER_PATH;