@rsc-kit/core 0.31.1 → 0.31.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/csp.d.ts CHANGED
@@ -25,22 +25,6 @@ export declare const DEFAULT_DIRECTIVES: Record<string, string[]>;
25
25
  * quietly not sent is a security header missing from every page.
26
26
  */
27
27
  export declare function normaliseContentSecurityPolicy(raw: ContentSecurityPolicyOptions | undefined): ContentSecurityPolicy | undefined;
28
- /**
29
- * The policy as `vite dev` sends it: the same one, so what it would refuse in
30
- * production is refused while you work, plus what only development needs.
31
- *
32
- * - `'unsafe-eval'` in script-src. React's development build evaluates code
33
- * for its debugging features (owner stacks, server logs replayed in the
34
- * browser) and says so in the console when it cannot. Never in a build.
35
- * - The dev server's origin, when the page is served from another one (a
36
- * backend in front, `devOrigin`): its modules, styles and fonts load from
37
- * there, and its HMR socket connects there.
38
- *
39
- * Every page renders per request in dev, so every page is allowed by its
40
- * nonce, where a build hashes the pages it stores. Vite's own inline styles -
41
- * a CSS update, the error overlay - take the nonce from a
42
- * `<meta property="csp-nonce">` the page's boot script writes.
43
- */
44
28
  export declare function devContentSecurityPolicy(policy: ContentSecurityPolicy, options?: {
45
29
  origin?: string;
46
30
  }): ContentSecurityPolicy;
package/dist/csp.js CHANGED
@@ -96,6 +96,7 @@ export function normaliseContentSecurityPolicy(raw) {
96
96
  * a CSS update, the error overlay - take the nonce from a
97
97
  * `<meta property="csp-nonce">` the page's boot script writes.
98
98
  */
99
+ const LOCAL_DEV_SOCKETS = ["ws://localhost:*", "ws://127.0.0.1:*", "http://localhost:*", "http://127.0.0.1:*"];
99
100
  export function devContentSecurityPolicy(policy, options = {}) {
100
101
  const map = new Map(policy.directives.map(([name, sources]) => [name, [...sources]]));
101
102
  const fallback = map.get("default-src");
@@ -117,12 +118,16 @@ export function devContentSecurityPolicy(policy, options = {}) {
117
118
  if (!map.has("script-src") && fallback)
118
119
  map.set("script-src", [...fallback]);
119
120
  plus("script-src", ["'unsafe-eval'"]);
121
+ // Vite's HMR client, on a page the backend serves (my-app.test), tries the
122
+ // page's own host first and then the dev server directly - ws://localhost:
123
+ // <port>. The port is chosen at runtime, so any; local only, and dev only.
124
+ if (!map.has("connect-src") && fallback)
125
+ map.set("connect-src", [...fallback]);
126
+ plus("connect-src", [...LOCAL_DEV_SOCKETS]);
120
127
  if (origin) {
121
128
  for (const name of ["default-src", "script-src", "script-src-elem", "style-src", "style-src-elem", "font-src", "img-src"]) {
122
129
  plus(name, [origin]);
123
130
  }
124
- if (!map.has("connect-src") && fallback)
125
- map.set("connect-src", [...fallback]);
126
131
  plus("connect-src", [origin, socket]);
127
132
  }
128
133
  return { ...policy, directives: [...map] };
package/dist/csp.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"csp.js","sourceRoot":"","sources":["../src/csp.ts"],"names":[],"mappings":"AAAA,+EAA+E;AAC/E,4EAA4E;AAC5E,EAAE;AACF,8EAA8E;AAC9E,+EAA+E;AAC/E,yDAAyD;AACzD,EAAE;AACF,2EAA2E;AAC3E,4EAA4E;AAC5E,2EAA2E;AAC3E,kBAAkB;AAClB,2EAA2E;AAC3E,+EAA+E;AAC/E,6EAA6E;AAC7E,sDAAsD;AACtD,EAAE;AACF,6EAA6E;AAC7E,yEAAyE;AACzE,8EAA8E;AAC9E,6EAA6E;AAC7E,yEAAyE;AACzE,EAAE;AACF,sEAAsE;AA0BtE,MAAM,CAAC,MAAM,kBAAkB,GAA6B;IAC1D,aAAa,EAAE,CAAC,QAAQ,CAAC;IACzB,UAAU,EAAE,CAAC,QAAQ,CAAC;IACtB,YAAY,EAAE,CAAC,QAAQ,CAAC;IACxB,2EAA2E;IAC3E,4DAA4D;IAC5D,gBAAgB,EAAE,CAAC,iBAAiB,CAAC;CACtC,CAAC;AAEF;;;GAGG;AACH,MAAM,WAAW,GAAG,IAAI,GAAG,CAAC,CAAC,iBAAiB,EAAE,YAAY,EAAE,WAAW,EAAE,SAAS,CAAC,CAA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AAS;QAE1B,MAAM,CAAC,GAAG,CAAC,MAAM,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC;IACjC,CAAC;IAED,OAAO,EAAE,OAAO,EAAE,CAAC,GAAG,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE,MAAM,EAAE,CAAC,GAAG,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC;AACtE,CAAC;AAED,6EAA6E;AAC7E,MAAM,UAAU,QAAQ;IACtB,MAAM,KAAK,GAAG,MAAM,CAAC,eAAe,CAAC,IAAI,UAAU,CAAC,EAAE,CAAC,CAAC,CAAC;IACzD,IAAI,MAAM,GAAG,EAAE,CAAC;IAEhB,KAAK,MAAM,IAAI,IAAI,KAAK;QAAE,MAAM,IAAI,MAAM,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC;IAE9D,OAAO,IAAI,CAAC,MAAM,CAAC,CAAC;AACtB,CAAC","sourcesContent":["// A Content-Security-Policy that allows the page's own inline code and nothing\n// else, on every host - a process, a Worker, a function, an edge, a bucket.\n//\n// The author names the policy; the engine adds what only it knows: the inline\n// scripts and styles each document carries. Two ways, and which one is decided\n// by whether the body is known before the headers leave:\n//\n// - A body that is whole first - a page the build stored, a kept page, a\n// shell - gets the hash of each inline script and style in it. The same\n// bytes for everyone, so the same header for everyone, and a cache may\n// share both.\n// - A body that streams - a page rendered per request, the holes resumed\n// after a shell - gets a nonce, new for each response, which React puts on\n// every script it writes. A shell's own scripts are already hashed, so a\n// stored shell stays the same bytes for everyone.\n//\n// The payload a document carries is data blocks (see inlineFlight.ts), which\n// no policy judges, so a nonce is needed only for what React writes as a\n// stream fills in: `$RC(\"B:1\",\"S:1\")` and its like, which differ by the shape\n// of each render and which no hash can know in advance. A nonce is never put\n// on anything a cache may share: it would be a secret given to everyone.\n//\n// Nothing here imports `node:` anything: it runs where the host runs.\n\n/** What `rscKit({ contentSecurityPolicy })` accepts. */\nexport interface ContentSecurityPolicyOptions {\n /**\n * The policy, one entry per directive: `{ 'img-src': [\"'self'\", 'data:'] }`.\n * Left out, `default-src 'self'; base-uri 'self'; object-src 'none';\n * style-src-attr 'unsafe-inline'`.\n */\n directives?: Record<string, string | readonly string[]>;\n /** Sent as Content-Security-Policy-Report-Only: reported, never enforced. */\n reportOnly?: boolean;\n}\n\n/** The policy as the build hands it to the host. */\nexport interface ContentSecurityPolicy {\n directives: [string, string[]][];\n reportOnly: boolean;\n}\n\n/** What a document's own inline code hashes to, as CSP source expressions. */\nexport interface InlineHashes {\n scripts: string[];\n styles: string[];\n}\n\nexport const DEFAULT_DIRECTIVES: Record<string, string[]> = {\n \"default-src\": [\"'self'\"],\n \"base-uri\": [\"'self'\"],\n \"object-src\": [\"'none'\"],\n // A style={{...}} React rendered on the server is a style attribute, which\n // no hash or nonce can allow. An attribute cannot run code.\n \"style-src-attr\": [\"'unsafe-inline'\"],\n};\n\n/**\n * Directives a `<meta>` policy cannot carry: a browser ignores them there and\n * says so in the console. Only a header delivers them.\n */\nconst HEADER_ONLY = new Set([\"frame-ancestors\", \"report-uri\", \"report-to\", \"sandbox\"]);\n\n/**\n * The policy, checked. Refused at build, never trimmed at runtime: a policy\n * quietly not sent is a security header missing from every page.\n */\nexport function normaliseContentSecurityPolicy(\n raw: ContentSecurityPolicyOptions | undefined,\n): ContentSecurityPolicy | undefined {\n if (raw === undefined) return undefined;\n\n const fail = (why: string): never => {\n throw new Error(`[rsc-kit] contentSecurityPolicy: ${why}`);\n };\n\n if (raw === null || typeof raw !== \"object\" || Array.isArray(raw))\n fail(\"an object, as in { directives: { 'img-src': [\\\"'self'\\\", 'data:'] } }.\");\n\n for (const key of Object.keys(raw)) {\n if (key !== \"directives\" && key !== \"reportOnly\") fail(`${JSON.stringify(key)} is not an option. It takes directives and reportOnly.`);\n }\n\n if (raw.reportOnly !== undefined && typeof raw.reportOnly !== \"boolean\") fail(\"reportOnly is true or false.\");\n\n const given = raw.directives ?? DEFAULT_DIRECTIVES;\n\n if (given === null || typeof given !== \"object\" || Array.isArray(given))\n fail(\"directives is an object of directive names to sources.\");\n\n const directives: [string, string[]][] = [];\n const seen = new Set<string>();\n\n for (const [rawName, value] of Object.entries(given)) {\n const name = rawName.toLowerCase();\n\n if (!/^[a-z][a-z-]*$/.test(name)) fail(`${JSON.stringify(rawName)} is not a directive name.`);\n if (seen.has(name)) fail(`${name} is named twice.`);\n seen.add(name);\n\n const list = typeof value === \"string\" ? value.split(/\\s+/) : Array.isArray(value) ? [...value] : fail(`${name} takes a string or a list of sources.`);\n const sources = list.map((source) => {\n if (typeof source !== \"string\") fail(`${name} takes a string or a list of sources.`);\n\n return source.trim();\n }).filter(Boolean);\n\n for (const source of sources) {\n if (/[\\s;,]/.test(source)) fail(`${name}: ${JSON.stringify(source)} is not one source. Give each its own entry.`);\n if (/^'nonce-/i.test(source))\n fail(`${name}: a nonce written into the config is the same on every response, which is no nonce at all. The engine adds one to each response that streams.`);\n }\n\n directives.push([name, sources]);\n }\n\n return { directives, reportOnly: raw.reportOnly === true };\n}\n\n/**\n * The policy as `vite dev` sends it: the same one, so what it would refuse in\n * production is refused while you work, plus what only development needs.\n *\n * - `'unsafe-eval'` in script-src. React's development build evaluates code\n * for its debugging features (owner stacks, server logs replayed in the\n * browser) and says so in the console when it cannot. Never in a build.\n * - The dev server's origin, when the page is served from another one (a\n * backend in front, `devOrigin`): its modules, styles and fonts load from\n * there, and its HMR socket connects there.\n *\n * Every page renders per request in dev, so every page is allowed by its\n * nonce, where a build hashes the pages it stores. Vite's own inline styles -\n * a CSS update, the error overlay - take the nonce from a\n * `<meta property=\"csp-nonce\">` the page's boot script writes.\n */\nexport function devContentSecurityPolicy(\n policy: ContentSecurityPolicy,\n options: { origin?: string } = {},\n): ContentSecurityPolicy {\n const map = new Map(policy.directives.map(([name, sources]) => [name, [...sources]]));\n const fallback = map.get(\"default-src\");\n const origin = options.origin ? new URL(options.origin).origin : \"\";\n const socket = origin ? origin.replace(/^http/, \"ws\") : \"\";\n // Only to a directive the policy has: one it leaves out falls back to\n // default-src, which gets the same. One the author closed with 'none' stays\n // closed: dev adds what it needs, never what the author refused.\n const plus = (name: string, sources: string[]) => {\n const list = map.get(name);\n\n if (!list || list.some((source) => /^'none'$/i.test(source))) return;\n\n for (const source of sources) if (!list.includes(source)) list.push(source);\n };\n\n // A script-src copied from default-src, as policyValue would, so eval has\n // somewhere to go; a policy restricting no scripts already allows it.\n if (!map.has(\"script-src\") && fallback) map.set(\"script-src\", [...fallback]);\n\n plus(\"script-src\", [\"'unsafe-eval'\"]);\n\n if (origin) {\n for (const name of [\"default-src\", \"script-src\", \"script-src-elem\", \"style-src\", \"style-src-elem\", \"font-src\", \"img-src\"]) {\n plus(name, [origin]);\n }\n\n if (!map.has(\"connect-src\") && fallback) map.set(\"connect-src\", [...fallback]);\n\n plus(\"connect-src\", [origin, socket]);\n }\n\n return { ...policy, directives: [...map] };\n}\n\n/** The header the policy goes out as. */\nexport function policyHeaderName(policy: ContentSecurityPolicy): string {\n return policy.reportOnly ? \"Content-Security-Policy-Report-Only\" : \"Content-Security-Policy\";\n}\n\n/**\n * The policy with what the document needs added: its hashes, and a nonce for\n * a response that streams.\n *\n * Added only where the policy restricts scripts (or styles) at all - a\n * script-src, or a default-src it falls back to. A policy that says nothing\n * about scripts allows every one, and a script-src with hashes in it would\n * take that away. And never where the author wrote 'unsafe-inline': a hash or\n * nonce beside it switches it off, which is the opposite of what they asked.\n */\nexport function policyValue(\n policy: ContentSecurityPolicy,\n extra: { hashes?: InlineHashes | null; nonce?: string | null; for?: \"header\" | \"meta\" } = {},\n): string {\n const map = new Map(policy.directives.map(([name, sources]) => [name, [...sources]]));\n const nonce = extra.nonce ? `'nonce-${extra.nonce}'` : null;\n\n const add = (kind: \"script\" | \"style\", hashes: readonly string[]) => {\n const own = `${kind}-src`;\n const fallback = map.get(\"default-src\");\n\n if (!map.has(own) && fallback) map.set(own, [...fallback]);\n\n for (const name of [own, `${own}-elem`]) {\n const sources = map.get(name);\n\n if (!sources) continue;\n if (sources.some((source) => /^'(unsafe-inline|none)'$/i.test(source))) continue;\n\n for (const source of [...hashes, ...(nonce ? [nonce] : [])]) {\n if (!sources.includes(source)) sources.push(source);\n }\n }\n };\n\n add(\"script\", extra.hashes?.scripts ?? []);\n add(\"style\", extra.hashes?.styles ?? []);\n\n return [...map]\n .filter(([name]) => extra.for !== \"meta\" || !HEADER_ONLY.has(name))\n .map(([name, sources]) => (sources.length ? `${name} ${sources.join(\" \")}` : name))\n .join(\"; \");\n}\n\n/**\n * The policy as a `<meta>`, for a page a host serves as a file and the engine\n * never answers - a static export. Without the directives only a header can\n * carry, and none at all for a report-only policy, which a `<meta>` cannot be.\n */\nexport function policyMeta(policy: ContentSecurityPolicy, hashes: InlineHashes): string {\n if (policy.reportOnly) return \"\";\n\n const value = policyValue(policy, { hashes, for: \"meta\" }).replace(/&/g, \"&amp;\").replace(/\"/g, \"&quot;\");\n\n return `<meta http-equiv=\"Content-Security-Policy\" content=\"${value}\">`;\n}\n\n/**\n * The document with its policy in `<head>`: after the charset, which must\n * stay inside the first 1024 bytes, and ahead of every script and style the\n * policy judges.\n */\nexport function withPolicyMeta(html: string, meta: string): string {\n if (!meta) return html;\n\n const charset = /<meta\\s[^>]*charset[^>]*>/i.exec(html);\n\n if (charset && charset.index < 1024) {\n const at = charset.index + charset[0].length;\n\n return html.slice(0, at) + meta + html.slice(at);\n }\n\n const head = /<head\\b[^>]*>/i.exec(html);\n\n if (!head) return html;\n\n const at = head.index + head[0].length;\n\n return html.slice(0, at) + meta + html.slice(at);\n}\n\nconst ATTRIBUTES = `((?:[^>\"']|\"[^\"]*\"|'[^']*')*)`;\nconst SCRIPT = new RegExp(`<script\\\\b${ATTRIBUTES}>([\\\\s\\\\S]*?)</script\\\\s*>`, \"gi\");\nconst STYLE = new RegExp(`<style\\\\b${ATTRIBUTES}>([\\\\s\\\\S]*?)</style\\\\s*>`, \"gi\");\n\n/** The types a browser runs, or that a policy judges as a script anyway. */\nconst RUN = new Set([\n \"\",\n \"module\",\n \"text/javascript\",\n \"application/javascript\",\n \"text/ecmascript\",\n \"application/ecmascript\",\n \"importmap\",\n \"speculationrules\",\n]);\n\nfunction attribute(attributes: string, name: string): string | null {\n const match = new RegExp(`(?:^|\\\\s)${name}\\\\s*=\\\\s*(?:\"([^\"]*)\"|'([^']*)'|([^\\\\s\"'=<>\\`]+))`, \"i\").exec(attributes);\n\n if (match) return match[1] ?? match[2] ?? match[3] ?? \"\";\n\n return new RegExp(`(?:^|\\\\s)${name}(?:\\\\s|$)`, \"i\").test(attributes) ? \"\" : null;\n}\n\nasync function sha256(text: string): Promise<string> {\n // The parser normalises line breaks before a browser hashes the element's text.\n const bytes = new TextEncoder().encode(text.replace(/\\r\\n?/g, \"\\n\"));\n const digest = new Uint8Array(await crypto.subtle.digest(\"SHA-256\", bytes));\n let binary = \"\";\n\n for (const byte of digest) binary += String.fromCharCode(byte);\n\n return `'sha256-${btoa(binary)}'`;\n}\n\n/**\n * The hash of every inline script and style in a document: what a policy\n * must name for the document to run as written. A script with a `src` is the\n * policy's origin rules' to judge, and a data block - JSON, a type no browser\n * runs - is not judged at all.\n */\nexport async function inlineHashes(html: string): Promise<InlineHashes> {\n const scripts = new Set<string>();\n const styles = new Set<string>();\n\n for (const [, attributes, body] of html.matchAll(SCRIPT)) {\n if (attribute(attributes, \"src\") !== null) continue;\n if (!RUN.has((attribute(attributes, \"type\") ?? \"\").trim().toLowerCase())) continue;\n if (body === \"\") continue;\n\n scripts.add(await sha256(body));\n }\n\n // Scripts out first: a style tag written inside a script's text is not one.\n for (const [, , body] of html.replace(SCRIPT, \"\").matchAll(STYLE)) {\n if (body === \"\") continue;\n\n styles.add(await sha256(body));\n }\n\n return { scripts: [...scripts].sort(), styles: [...styles].sort() };\n}\n\n/** A nonce: 128 random bits, base64. New for every response that streams. */\nexport function newNonce(): string {\n const bytes = crypto.getRandomValues(new Uint8Array(16));\n let binary = \"\";\n\n for (const byte of bytes) binary += String.fromCharCode(byte);\n\n return btoa(binary);\n}\n"]}
1
+ {"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AAU,QAAQ;IACtB,MAAM,KAAK,GAAG,MAAM,CAAC,eAAe,CAAC,IAAI,UAAU,CAAC,EAAE,CAAC,CAAC,CAAC;IACzD,IAAI,MAAM,GAAG,EAAE,CAAC;IAEhB,KAAK,MAAM,IAAI,IAAI,KAAK;QAAE,MAAM,IAAI,MAAM,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC;IAE9D,OAAO,IAAI,CAAC,MAAM,CAAC,CAAC;AACtB,CAAC","sourcesContent":["// A Content-Security-Policy that allows the page's own inline code and nothing\n// else, on every host - a process, a Worker, a function, an edge, a bucket.\n//\n// The author names the policy; the engine adds what only it knows: the inline\n// scripts and styles each document carries. Two ways, and which one is decided\n// by whether the body is known before the headers leave:\n//\n// - A body that is whole first - a page the build stored, a kept page, a\n// shell - gets the hash of each inline script and style in it. The same\n// bytes for everyone, so the same header for everyone, and a cache may\n// share both.\n// - A body that streams - a page rendered per request, the holes resumed\n// after a shell - gets a nonce, new for each response, which React puts on\n// every script it writes. A shell's own scripts are already hashed, so a\n// stored shell stays the same bytes for everyone.\n//\n// The payload a document carries is data blocks (see inlineFlight.ts), which\n// no policy judges, so a nonce is needed only for what React writes as a\n// stream fills in: `$RC(\"B:1\",\"S:1\")` and its like, which differ by the shape\n// of each render and which no hash can know in advance. A nonce is never put\n// on anything a cache may share: it would be a secret given to everyone.\n//\n// Nothing here imports `node:` anything: it runs where the host runs.\n\n/** What `rscKit({ contentSecurityPolicy })` accepts. */\nexport interface ContentSecurityPolicyOptions {\n /**\n * The policy, one entry per directive: `{ 'img-src': [\"'self'\", 'data:'] }`.\n * Left out, `default-src 'self'; base-uri 'self'; object-src 'none';\n * style-src-attr 'unsafe-inline'`.\n */\n directives?: Record<string, string | readonly string[]>;\n /** Sent as Content-Security-Policy-Report-Only: reported, never enforced. */\n reportOnly?: boolean;\n}\n\n/** The policy as the build hands it to the host. */\nexport interface ContentSecurityPolicy {\n directives: [string, string[]][];\n reportOnly: boolean;\n}\n\n/** What a document's own inline code hashes to, as CSP source expressions. */\nexport interface InlineHashes {\n scripts: string[];\n styles: string[];\n}\n\nexport const DEFAULT_DIRECTIVES: Record<string, string[]> = {\n \"default-src\": [\"'self'\"],\n \"base-uri\": [\"'self'\"],\n \"object-src\": [\"'none'\"],\n // A style={{...}} React rendered on the server is a style attribute, which\n // no hash or nonce can allow. An attribute cannot run code.\n \"style-src-attr\": [\"'unsafe-inline'\"],\n};\n\n/**\n * Directives a `<meta>` policy cannot carry: a browser ignores them there and\n * says so in the console. Only a header delivers them.\n */\nconst HEADER_ONLY = new Set([\"frame-ancestors\", \"report-uri\", \"report-to\", \"sandbox\"]);\n\n/**\n * The policy, checked. Refused at build, never trimmed at runtime: a policy\n * quietly not sent is a security header missing from every page.\n */\nexport function normaliseContentSecurityPolicy(\n raw: ContentSecurityPolicyOptions | undefined,\n): ContentSecurityPolicy | undefined {\n if (raw === undefined) return undefined;\n\n const fail = (why: string): never => {\n throw new Error(`[rsc-kit] contentSecurityPolicy: ${why}`);\n };\n\n if (raw === null || typeof raw !== \"object\" || Array.isArray(raw))\n fail(\"an object, as in { directives: { 'img-src': [\\\"'self'\\\", 'data:'] } }.\");\n\n for (const key of Object.keys(raw)) {\n if (key !== \"directives\" && key !== \"reportOnly\") fail(`${JSON.stringify(key)} is not an option. It takes directives and reportOnly.`);\n }\n\n if (raw.reportOnly !== undefined && typeof raw.reportOnly !== \"boolean\") fail(\"reportOnly is true or false.\");\n\n const given = raw.directives ?? DEFAULT_DIRECTIVES;\n\n if (given === null || typeof given !== \"object\" || Array.isArray(given))\n fail(\"directives is an object of directive names to sources.\");\n\n const directives: [string, string[]][] = [];\n const seen = new Set<string>();\n\n for (const [rawName, value] of Object.entries(given)) {\n const name = rawName.toLowerCase();\n\n if (!/^[a-z][a-z-]*$/.test(name)) fail(`${JSON.stringify(rawName)} is not a directive name.`);\n if (seen.has(name)) fail(`${name} is named twice.`);\n seen.add(name);\n\n const list = typeof value === \"string\" ? value.split(/\\s+/) : Array.isArray(value) ? [...value] : fail(`${name} takes a string or a list of sources.`);\n const sources = list.map((source) => {\n if (typeof source !== \"string\") fail(`${name} takes a string or a list of sources.`);\n\n return source.trim();\n }).filter(Boolean);\n\n for (const source of sources) {\n if (/[\\s;,]/.test(source)) fail(`${name}: ${JSON.stringify(source)} is not one source. Give each its own entry.`);\n if (/^'nonce-/i.test(source))\n fail(`${name}: a nonce written into the config is the same on every response, which is no nonce at all. The engine adds one to each response that streams.`);\n }\n\n directives.push([name, sources]);\n }\n\n return { directives, reportOnly: raw.reportOnly === true };\n}\n\n/**\n * The policy as `vite dev` sends it: the same one, so what it would refuse in\n * production is refused while you work, plus what only development needs.\n *\n * - `'unsafe-eval'` in script-src. React's development build evaluates code\n * for its debugging features (owner stacks, server logs replayed in the\n * browser) and says so in the console when it cannot. Never in a build.\n * - The dev server's origin, when the page is served from another one (a\n * backend in front, `devOrigin`): its modules, styles and fonts load from\n * there, and its HMR socket connects there.\n *\n * Every page renders per request in dev, so every page is allowed by its\n * nonce, where a build hashes the pages it stores. Vite's own inline styles -\n * a CSS update, the error overlay - take the nonce from a\n * `<meta property=\"csp-nonce\">` the page's boot script writes.\n */\nconst LOCAL_DEV_SOCKETS = [\"ws://localhost:*\", \"ws://127.0.0.1:*\", \"http://localhost:*\", \"http://127.0.0.1:*\"];\n\nexport function devContentSecurityPolicy(\n policy: ContentSecurityPolicy,\n options: { origin?: string } = {},\n): ContentSecurityPolicy {\n const map = new Map(policy.directives.map(([name, sources]) => [name, [...sources]]));\n const fallback = map.get(\"default-src\");\n const origin = options.origin ? new URL(options.origin).origin : \"\";\n const socket = origin ? origin.replace(/^http/, \"ws\") : \"\";\n // Only to a directive the policy has: one it leaves out falls back to\n // default-src, which gets the same. One the author closed with 'none' stays\n // closed: dev adds what it needs, never what the author refused.\n const plus = (name: string, sources: string[]) => {\n const list = map.get(name);\n\n if (!list || list.some((source) => /^'none'$/i.test(source))) return;\n\n for (const source of sources) if (!list.includes(source)) list.push(source);\n };\n\n // A script-src copied from default-src, as policyValue would, so eval has\n // somewhere to go; a policy restricting no scripts already allows it.\n if (!map.has(\"script-src\") && fallback) map.set(\"script-src\", [...fallback]);\n\n plus(\"script-src\", [\"'unsafe-eval'\"]);\n\n // Vite's HMR client, on a page the backend serves (my-app.test), tries the\n // page's own host first and then the dev server directly - ws://localhost:\n // <port>. The port is chosen at runtime, so any; local only, and dev only.\n if (!map.has(\"connect-src\") && fallback) map.set(\"connect-src\", [...fallback]);\n\n plus(\"connect-src\", [...LOCAL_DEV_SOCKETS]);\n\n if (origin) {\n for (const name of [\"default-src\", \"script-src\", \"script-src-elem\", \"style-src\", \"style-src-elem\", \"font-src\", \"img-src\"]) {\n plus(name, [origin]);\n }\n\n plus(\"connect-src\", [origin, socket]);\n }\n\n return { ...policy, directives: [...map] };\n}\n\n/** The header the policy goes out as. */\nexport function policyHeaderName(policy: ContentSecurityPolicy): string {\n return policy.reportOnly ? \"Content-Security-Policy-Report-Only\" : \"Content-Security-Policy\";\n}\n\n/**\n * The policy with what the document needs added: its hashes, and a nonce for\n * a response that streams.\n *\n * Added only where the policy restricts scripts (or styles) at all - a\n * script-src, or a default-src it falls back to. A policy that says nothing\n * about scripts allows every one, and a script-src with hashes in it would\n * take that away. And never where the author wrote 'unsafe-inline': a hash or\n * nonce beside it switches it off, which is the opposite of what they asked.\n */\nexport function policyValue(\n policy: ContentSecurityPolicy,\n extra: { hashes?: InlineHashes | null; nonce?: string | null; for?: \"header\" | \"meta\" } = {},\n): string {\n const map = new Map(policy.directives.map(([name, sources]) => [name, [...sources]]));\n const nonce = extra.nonce ? `'nonce-${extra.nonce}'` : null;\n\n const add = (kind: \"script\" | \"style\", hashes: readonly string[]) => {\n const own = `${kind}-src`;\n const fallback = map.get(\"default-src\");\n\n if (!map.has(own) && fallback) map.set(own, [...fallback]);\n\n for (const name of [own, `${own}-elem`]) {\n const sources = map.get(name);\n\n if (!sources) continue;\n if (sources.some((source) => /^'(unsafe-inline|none)'$/i.test(source))) continue;\n\n for (const source of [...hashes, ...(nonce ? [nonce] : [])]) {\n if (!sources.includes(source)) sources.push(source);\n }\n }\n };\n\n add(\"script\", extra.hashes?.scripts ?? []);\n add(\"style\", extra.hashes?.styles ?? []);\n\n return [...map]\n .filter(([name]) => extra.for !== \"meta\" || !HEADER_ONLY.has(name))\n .map(([name, sources]) => (sources.length ? `${name} ${sources.join(\" \")}` : name))\n .join(\"; \");\n}\n\n/**\n * The policy as a `<meta>`, for a page a host serves as a file and the engine\n * never answers - a static export. Without the directives only a header can\n * carry, and none at all for a report-only policy, which a `<meta>` cannot be.\n */\nexport function policyMeta(policy: ContentSecurityPolicy, hashes: InlineHashes): string {\n if (policy.reportOnly) return \"\";\n\n const value = policyValue(policy, { hashes, for: \"meta\" }).replace(/&/g, \"&amp;\").replace(/\"/g, \"&quot;\");\n\n return `<meta http-equiv=\"Content-Security-Policy\" content=\"${value}\">`;\n}\n\n/**\n * The document with its policy in `<head>`: after the charset, which must\n * stay inside the first 1024 bytes, and ahead of every script and style the\n * policy judges.\n */\nexport function withPolicyMeta(html: string, meta: string): string {\n if (!meta) return html;\n\n const charset = /<meta\\s[^>]*charset[^>]*>/i.exec(html);\n\n if (charset && charset.index < 1024) {\n const at = charset.index + charset[0].length;\n\n return html.slice(0, at) + meta + html.slice(at);\n }\n\n const head = /<head\\b[^>]*>/i.exec(html);\n\n if (!head) return html;\n\n const at = head.index + head[0].length;\n\n return html.slice(0, at) + meta + html.slice(at);\n}\n\nconst ATTRIBUTES = `((?:[^>\"']|\"[^\"]*\"|'[^']*')*)`;\nconst SCRIPT = new RegExp(`<script\\\\b${ATTRIBUTES}>([\\\\s\\\\S]*?)</script\\\\s*>`, \"gi\");\nconst STYLE = new RegExp(`<style\\\\b${ATTRIBUTES}>([\\\\s\\\\S]*?)</style\\\\s*>`, \"gi\");\n\n/** The types a browser runs, or that a policy judges as a script anyway. */\nconst RUN = new Set([\n \"\",\n \"module\",\n \"text/javascript\",\n \"application/javascript\",\n \"text/ecmascript\",\n \"application/ecmascript\",\n \"importmap\",\n \"speculationrules\",\n]);\n\nfunction attribute(attributes: string, name: string): string | null {\n const match = new RegExp(`(?:^|\\\\s)${name}\\\\s*=\\\\s*(?:\"([^\"]*)\"|'([^']*)'|([^\\\\s\"'=<>\\`]+))`, \"i\").exec(attributes);\n\n if (match) return match[1] ?? match[2] ?? match[3] ?? \"\";\n\n return new RegExp(`(?:^|\\\\s)${name}(?:\\\\s|$)`, \"i\").test(attributes) ? \"\" : null;\n}\n\nasync function sha256(text: string): Promise<string> {\n // The parser normalises line breaks before a browser hashes the element's text.\n const bytes = new TextEncoder().encode(text.replace(/\\r\\n?/g, \"\\n\"));\n const digest = new Uint8Array(await crypto.subtle.digest(\"SHA-256\", bytes));\n let binary = \"\";\n\n for (const byte of digest) binary += String.fromCharCode(byte);\n\n return `'sha256-${btoa(binary)}'`;\n}\n\n/**\n * The hash of every inline script and style in a document: what a policy\n * must name for the document to run as written. A script with a `src` is the\n * policy's origin rules' to judge, and a data block - JSON, a type no browser\n * runs - is not judged at all.\n */\nexport async function inlineHashes(html: string): Promise<InlineHashes> {\n const scripts = new Set<string>();\n const styles = new Set<string>();\n\n for (const [, attributes, body] of html.matchAll(SCRIPT)) {\n if (attribute(attributes, \"src\") !== null) continue;\n if (!RUN.has((attribute(attributes, \"type\") ?? \"\").trim().toLowerCase())) continue;\n if (body === \"\") continue;\n\n scripts.add(await sha256(body));\n }\n\n // Scripts out first: a style tag written inside a script's text is not one.\n for (const [, , body] of html.replace(SCRIPT, \"\").matchAll(STYLE)) {\n if (body === \"\") continue;\n\n styles.add(await sha256(body));\n }\n\n return { scripts: [...scripts].sort(), styles: [...styles].sort() };\n}\n\n/** A nonce: 128 random bits, base64. New for every response that streams. */\nexport function newNonce(): string {\n const bytes = crypto.getRandomValues(new Uint8Array(16));\n let binary = \"\";\n\n for (const byte of bytes) binary += String.fromCharCode(byte);\n\n return btoa(binary);\n}\n"]}
@@ -0,0 +1,41 @@
1
+ /**
2
+ * One dev server per app.
3
+ *
4
+ * Two `vite dev` processes in one project share everything that makes dev
5
+ * work: Vite's pre-bundle cache, rsc-host.json and the hot file the backend
6
+ * finds the renderer by. Each re-bundles the cache under the other, which
7
+ * answers its next request with ERR_OUTDATED_OPTIMIZED_DEP; each writes the
8
+ * hot file, and the one stopped first deletes it from under the one still
9
+ * running, so the backend reports no renderer at all. Nothing pointed at the
10
+ * cause. It happens easily: `artisan dev` started by an editor or Herd, and
11
+ * `bun run dev` in a terminal.
12
+ *
13
+ * So the first dev server holds a lock in Vite's cache directory - the thing
14
+ * they share - and a second one waits, naming the first, and starts when it
15
+ * stops. Waiting rather than exiting: `artisan dev` restarts a process that
16
+ * exits, so a refusal printed itself five times and gave up, and the app was
17
+ * left with no dev server once the first was stopped.
18
+ */
19
+ export interface DevServerHolder {
20
+ pid: number;
21
+ url?: string;
22
+ }
23
+ /**
24
+ * Takes the lock for this process, or returns the dev server that holds it.
25
+ * A lock left by a process that is gone - killed, crashed - is taken over.
26
+ * This process's own (a restart) is kept.
27
+ */
28
+ export declare function claimDevServer(cacheDir: string, pid?: number): DevServerHolder | null;
29
+ /** Records where this server listens, for the message a second one prints. */
30
+ export declare function recordDevServerUrl(cacheDir: string, url: string, pid?: number): void;
31
+ /** Lets go of the lock, if this process holds it. */
32
+ export declare function releaseDevServer(cacheDir: string, pid?: number): void;
33
+ /**
34
+ * Waits until this process holds the lock: the holder stopped, or is gone.
35
+ * Resolves at once when the lock was free.
36
+ */
37
+ export declare function waitForDevServer(cacheDir: string, { pid, every }?: {
38
+ pid?: number;
39
+ every?: number;
40
+ }): Promise<void>;
41
+ export declare function secondDevServerMessage(root: string, held: DevServerHolder): string;
@@ -0,0 +1,86 @@
1
+ /**
2
+ * One dev server per app.
3
+ *
4
+ * Two `vite dev` processes in one project share everything that makes dev
5
+ * work: Vite's pre-bundle cache, rsc-host.json and the hot file the backend
6
+ * finds the renderer by. Each re-bundles the cache under the other, which
7
+ * answers its next request with ERR_OUTDATED_OPTIMIZED_DEP; each writes the
8
+ * hot file, and the one stopped first deletes it from under the one still
9
+ * running, so the backend reports no renderer at all. Nothing pointed at the
10
+ * cause. It happens easily: `artisan dev` started by an editor or Herd, and
11
+ * `bun run dev` in a terminal.
12
+ *
13
+ * So the first dev server holds a lock in Vite's cache directory - the thing
14
+ * they share - and a second one waits, naming the first, and starts when it
15
+ * stops. Waiting rather than exiting: `artisan dev` restarts a process that
16
+ * exits, so a refusal printed itself five times and gave up, and the app was
17
+ * left with no dev server once the first was stopped.
18
+ */
19
+ import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
20
+ import { join } from "node:path";
21
+ const LOCK = "rsc-kit-dev.json";
22
+ const lockPath = (cacheDir) => join(cacheDir, LOCK);
23
+ function alive(pid) {
24
+ try {
25
+ process.kill(pid, 0);
26
+ return true;
27
+ }
28
+ catch (error) {
29
+ // EPERM: it exists, and belongs to someone else.
30
+ return error.code === "EPERM";
31
+ }
32
+ }
33
+ function read(cacheDir) {
34
+ try {
35
+ const held = JSON.parse(readFileSync(lockPath(cacheDir), "utf-8"));
36
+ return Number.isInteger(held?.pid) ? held : null;
37
+ }
38
+ catch {
39
+ return null;
40
+ }
41
+ }
42
+ /**
43
+ * Takes the lock for this process, or returns the dev server that holds it.
44
+ * A lock left by a process that is gone - killed, crashed - is taken over.
45
+ * This process's own (a restart) is kept.
46
+ */
47
+ export function claimDevServer(cacheDir, pid = process.pid) {
48
+ const held = read(cacheDir);
49
+ if (held && held.pid !== pid && alive(held.pid))
50
+ return held;
51
+ mkdirSync(cacheDir, { recursive: true });
52
+ writeFileSync(lockPath(cacheDir), JSON.stringify({ pid }));
53
+ return null;
54
+ }
55
+ /** Records where this server listens, for the message a second one prints. */
56
+ export function recordDevServerUrl(cacheDir, url, pid = process.pid) {
57
+ if (read(cacheDir)?.pid !== pid)
58
+ return;
59
+ writeFileSync(lockPath(cacheDir), JSON.stringify({ pid, url }));
60
+ }
61
+ /** Lets go of the lock, if this process holds it. */
62
+ export function releaseDevServer(cacheDir, pid = process.pid) {
63
+ if (read(cacheDir)?.pid !== pid)
64
+ return;
65
+ try {
66
+ rmSync(lockPath(cacheDir));
67
+ }
68
+ catch { }
69
+ }
70
+ /**
71
+ * Waits until this process holds the lock: the holder stopped, or is gone.
72
+ * Resolves at once when the lock was free.
73
+ */
74
+ export async function waitForDevServer(cacheDir, { pid = process.pid, every = 1000 } = {}) {
75
+ while (claimDevServer(cacheDir, pid)) {
76
+ await new Promise((resolve) => setTimeout(resolve, every));
77
+ }
78
+ }
79
+ export function secondDevServerMessage(root, held) {
80
+ return (`[rsc-kit] A dev server is already running for ${root} ` +
81
+ `(pid ${held.pid}${held.url ? `, ${held.url}` : ""}) - use that one. ` +
82
+ "This one waits and starts when it stops: two at once would share one pre-bundle cache " +
83
+ "and one hot file, and break each other (ERR_OUTDATED_OPTIMIZED_DEP). " +
84
+ "An editor, Herd or `artisan dev` may have started the first for you.");
85
+ }
86
+ //# sourceMappingURL=devLock.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"devLock.js","sourceRoot":"","sources":["../src/devLock.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,OAAO,EAAE,SAAS,EAAE,YAAY,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AACzE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEjC,MAAM,IAAI,GAAG,kBAAkB,CAAC;AAOhC,MAAM,QAAQ,GAAG,CAAC,QAAgB,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC;AAE5D,SAAS,KAAK,CAAC,GAAW;IACxB,IAAI,CAAC;QACH,OAAO,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC;QAErB,OAAO,IAAI,CAAC;IACd,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,iDAAiD;QACjD,OAAQ,KAA+B,CAAC,IAAI,KAAK,OAAO,CAAC;IAC3D,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,GAAG,OAAO,CAAC,GAAG;IAClE,IAAI,IAAI,CAAC,QAAQ,CAAC,EAAE,GAAG,KAAK,GAAG;QAAE,OAAO;IAExC,IAAI,CAAC;QACH,MAAM,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,CAAC;IAC7B,CAAC;IAAC,MAAM,CAAC,CAAA,CAAC;AACZ,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,gBAAgB,CACpC,QAAgB,EAChB,EAAE,GAAG,GAAG,OAAO,CAAC,GAAG,EAAE,KAAK,GAAG,IAAI,EAAE,GAAqC,EAAE;IAE1E,OAAO,cAAc,CAAC,QAAQ,EAAE,GAAG,CAAC,EAAE,CAAC;QACrC,MAAM,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC,CAAC;IAC7D,CAAC;AACH,CAAC;AAED,MAAM,UAAU,sBAAsB,CAAC,IAAY,EAAE,IAAqB;IACxE,OAAO,CACL,iDAAiD,IAAI,GAAG;QACxD,QAAQ,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,EAAE,oBAAoB;QACtE,wFAAwF;QACxF,uEAAuE;QACvE,sEAAsE,CACvE,CAAC;AACJ,CAAC","sourcesContent":["/**\n * One dev server per app.\n *\n * Two `vite dev` processes in one project share everything that makes dev\n * work: Vite's pre-bundle cache, rsc-host.json and the hot file the backend\n * finds the renderer by. Each re-bundles the cache under the other, which\n * answers its next request with ERR_OUTDATED_OPTIMIZED_DEP; each writes the\n * hot file, and the one stopped first deletes it from under the one still\n * running, so the backend reports no renderer at all. Nothing pointed at the\n * cause. It happens easily: `artisan dev` started by an editor or Herd, and\n * `bun run dev` in a terminal.\n *\n * So the first dev server holds a lock in Vite's cache directory - the thing\n * they share - and a second one waits, naming the first, and starts when it\n * stops. Waiting rather than exiting: `artisan dev` restarts a process that\n * exits, so a refusal printed itself five times and gave up, and the app was\n * left with no dev server once the first was stopped.\n */\n\nimport { mkdirSync, readFileSync, rmSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nconst LOCK = \"rsc-kit-dev.json\";\n\nexport interface DevServerHolder {\n pid: number;\n url?: string;\n}\n\nconst lockPath = (cacheDir: string) => join(cacheDir, LOCK);\n\nfunction alive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n\n return true;\n } catch (error) {\n // EPERM: it exists, and belongs to someone else.\n return (error as NodeJS.ErrnoException).code === \"EPERM\";\n }\n}\n\nfunction read(cacheDir: string): DevServerHolder | null {\n try {\n const held = JSON.parse(readFileSync(lockPath(cacheDir), \"utf-8\")) as DevServerHolder;\n\n return Number.isInteger(held?.pid) ? held : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Takes the lock for this process, or returns the dev server that holds it.\n * A lock left by a process that is gone - killed, crashed - is taken over.\n * This process's own (a restart) is kept.\n */\nexport function claimDevServer(cacheDir: string, pid = process.pid): DevServerHolder | null {\n const held = read(cacheDir);\n\n if (held && held.pid !== pid && alive(held.pid)) return held;\n\n mkdirSync(cacheDir, { recursive: true });\n writeFileSync(lockPath(cacheDir), JSON.stringify({ pid }));\n\n return null;\n}\n\n/** Records where this server listens, for the message a second one prints. */\nexport function recordDevServerUrl(cacheDir: string, url: string, pid = process.pid): void {\n if (read(cacheDir)?.pid !== pid) return;\n\n writeFileSync(lockPath(cacheDir), JSON.stringify({ pid, url }));\n}\n\n/** Lets go of the lock, if this process holds it. */\nexport function releaseDevServer(cacheDir: string, pid = process.pid): void {\n if (read(cacheDir)?.pid !== pid) return;\n\n try {\n rmSync(lockPath(cacheDir));\n } catch {}\n}\n\n/**\n * Waits until this process holds the lock: the holder stopped, or is gone.\n * Resolves at once when the lock was free.\n */\nexport async function waitForDevServer(\n cacheDir: string,\n { pid = process.pid, every = 1000 }: { pid?: number; every?: number } = {},\n): Promise<void> {\n while (claimDevServer(cacheDir, pid)) {\n await new Promise((resolve) => setTimeout(resolve, every));\n }\n}\n\nexport function secondDevServerMessage(root: string, held: DevServerHolder): string {\n return (\n `[rsc-kit] A dev server is already running for ${root} ` +\n `(pid ${held.pid}${held.url ? `, ${held.url}` : \"\"}) - use that one. ` +\n \"This one waits and starts when it stops: two at once would share one pre-bundle cache \" +\n \"and one hot file, and break each other (ERR_OUTDATED_OPTIMIZED_DEP). \" +\n \"An editor, Herd or `artisan dev` may have started the first for you.\"\n );\n}\n"]}
package/dist/vite.js CHANGED
@@ -26,6 +26,7 @@ import { stampDisplayNames } from "./stableNames.js";
26
26
  import { REPORT_FILE, buildReport } from "./buildReport.js";
27
27
  import { contractPath, edgeGuarded, edgeMarker, edgeShells, edgeStatic } from "./edgeShells.js";
28
28
  import { EDGE, EDGE_HEADERS } from "./headers.js";
29
+ import { claimDevServer, recordDevServerUrl, releaseDevServer, secondDevServerMessage, waitForDevServer } from "./devLock.js";
29
30
  import { devContentSecurityPolicy, normaliseContentSecurityPolicy, } from "./csp.js";
30
31
  import { MANIFEST_PATH, manifestWarning, webManifest } from "./webManifest.js";
31
32
  import { ASSET_BASE, allAppAssets, assetFile, appAssets, headTags, shareImageUrls, typeOf, } from "./appAssets.js";
@@ -263,6 +264,8 @@ function devPolicy() {
263
264
  return contentSecurityPolicy;
264
265
  return devContentSecurityPolicy(contentSecurityPolicy, { origin: devOrigin || undefined });
265
266
  }
267
+ /** The dev server lock this process holds, once it holds one - see devLock.ts. */
268
+ let devLockDir;
266
269
  /** Resolved from RscKitOptions.openapi; null when off. */
267
270
  let openapi = null;
268
271
  let foundAssets = {
@@ -617,7 +620,24 @@ function resolvePaths(options) {
617
620
  }
618
621
  loadHostManifest(options);
619
622
  }
623
+ /**
624
+ * rsc-host.json as this process last read it, null when there was none. The
625
+ * dev server restarts for a new manifest, not for a write: the backend's
626
+ * manifest command rewrites the file on every dev start, so a second process
627
+ * starting beside this one - `artisan dev` and a terminal - rewrote it with
628
+ * the same bytes and restarted this server for nothing.
629
+ */
630
+ let hostFileText = null;
631
+ function hostFileOnDisk() {
632
+ try {
633
+ return readFileSync(join(projectRoot, HOST_FILE), "utf-8");
634
+ }
635
+ catch {
636
+ return null;
637
+ }
638
+ }
620
639
  function loadHostManifest(options) {
640
+ hostFileText = hostFileOnDisk();
621
641
  const manifest = fileHostManifest(projectRoot);
622
642
  hostActions = options.hostActions ?? manifest.actions;
623
643
  hostFunctions = manifest.functions;
@@ -8045,7 +8065,27 @@ export function rscKit(options = {}) {
8045
8065
  nitro.options.plugins = [...(nitro.options.plugins ?? []), "#rsc-kit/startup"];
8046
8066
  },
8047
8067
  },
8048
- config(_config, env) {
8068
+ async config(_config, env) {
8069
+ // One dev server per app - see devLock.ts. Here, the first hook, and
8070
+ // not in configureServer: waiting there, other plugins carried on
8071
+ // around it - Nitro imported the entries before plugin-rsc had its
8072
+ // server, and the failed import answered every request with a 500
8073
+ // once this one started. Before any environment exists nothing runs.
8074
+ if (env.command === "serve" && !env.isPreview) {
8075
+ const lockDir = join(projectRoot, "node_modules", ".vite");
8076
+ const holder = claimDevServer(lockDir);
8077
+ if (holder) {
8078
+ log(secondDevServerMessage(projectRoot, holder).replace(/^\[rsc-kit\] /, ""));
8079
+ await waitForDevServer(lockDir);
8080
+ log("the other dev server stopped — starting this one");
8081
+ }
8082
+ // Released when the process exits, never when its http server
8083
+ // closes: a restart opens the new server before closing the old.
8084
+ if (!devLockDir) {
8085
+ devLockDir = lockDir;
8086
+ process.once("exit", () => releaseDevServer(lockDir));
8087
+ }
8088
+ }
8049
8089
  // Here and not only in configResolved: the entries below are written
8050
8090
  // in this hook, and the 404's policy in them is dev's or the build's.
8051
8091
  devServer = env.command === "serve";
@@ -8385,6 +8425,12 @@ export function rscKit(options = {}) {
8385
8425
  // Swapping the plugins in the app's config is not a fix: Nitro then loads
8386
8426
  // .env too late for the app's first request.
8387
8427
  configureServer: { order: "pre", handler(server) {
8428
+ // Where this one listens, for the message a second one prints.
8429
+ server.httpServer?.once("listening", () => {
8430
+ const url = server.resolvedUrls?.local?.[0];
8431
+ if (url && devLockDir)
8432
+ recordDevServerUrl(devLockDir, url.replace(/\/$/, ""));
8433
+ });
8388
8434
  // The rules an agent follows here say which rsc-kit wrote them. One
8389
8435
  // line when they are older than the rsc-kit running - never a rewrite:
8390
8436
  // the section is the app's to update, and git shows the change.
@@ -8475,9 +8521,13 @@ export function rscKit(options = {}) {
8475
8521
  // known. Removed on shutdown so a backend can tell a dev server that is
8476
8522
  // gone from one that is merely slow to answer.
8477
8523
  if (hotFile) {
8524
+ let written = null;
8525
+ // Only the url this server wrote: a file naming another server is
8526
+ // that server's, and deleting it tells the backend the renderer is
8527
+ // gone while it runs.
8478
8528
  const remove = () => {
8479
8529
  try {
8480
- if (existsSync(hotFile))
8530
+ if (written !== null && readFileSync(hotFile, "utf-8") === written)
8481
8531
  rmSync(hotFile);
8482
8532
  }
8483
8533
  catch { }
@@ -8497,7 +8547,8 @@ export function rscKit(options = {}) {
8497
8547
  if (!url)
8498
8548
  return;
8499
8549
  mkdirSync(dirname(hotFile), { recursive: true });
8500
- writeFileSync(hotFile, url.replace(/\/$/, ""));
8550
+ written = url.replace(/\/$/, "");
8551
+ writeFileSync(hotFile, written);
8501
8552
  });
8502
8553
  for (const signal of ["SIGINT", "SIGTERM", "exit"]) {
8503
8554
  process.once(signal, remove);
@@ -8537,7 +8588,7 @@ export function rscKit(options = {}) {
8537
8588
  // first action, changes on the next, and goes when the last is removed.
8538
8589
  const hostActionsPath = join(projectRoot, HOST_FILE);
8539
8590
  const hostActionsChanged = (file) => {
8540
- if (file !== hostActionsPath)
8591
+ if (file !== hostActionsPath || hostFileOnDisk() === hostFileText)
8541
8592
  return;
8542
8593
  server.config.logger.info(`[rsc-kit] ${relative(projectRoot, file)} changed — restarting`);
8543
8594
  void server.restart();