@ngrok/app-server 0.4.1 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/README.md +223 -64
  2. package/dist/brotli-only-BVAagKt3.js +63 -0
  3. package/dist/build-id-CwMbED1n.js +245 -0
  4. package/dist/{build-manifest-DBMWe3Lx.js → build-manifest-CoBztw_6.js} +13 -4
  5. package/dist/bun-BCz6K_Xv.js +1 -2
  6. package/dist/check-count-DQl5z_qe.js +17 -0
  7. package/dist/cli.js +9 -6
  8. package/dist/client-browser.d.ts +2 -3
  9. package/dist/client-browser.js +1 -1
  10. package/dist/client.d.ts +5 -4
  11. package/dist/client.js +9 -6
  12. package/dist/{compress-Cp5NfXCC.js → compress-2w3jqBh7.js} +2 -3
  13. package/dist/{compression-CT2mWlKM.js → compression-uJxu0JVb.js} +32 -5
  14. package/dist/content-types-Le-5BNEC.js +10 -0
  15. package/dist/{create-server-Bp1yILQk.js → create-server-DVTZun6D.js} +617 -306
  16. package/dist/create-server-PA0qniaK.js +3 -0
  17. package/dist/{create-server-X2GR-U6t.d.ts → create-server-UVsHFQyK.d.ts} +116 -54
  18. package/dist/deno-aqhikNMG.js +1 -2
  19. package/dist/{entry-BoxCqc6w.js → entry-CMhX3yf8.js} +85 -65
  20. package/dist/entry-CvZ4U0ia.js +3 -0
  21. package/dist/{entry-DZTCaL3d.d.ts → entry-DBq_3s8X.d.ts} +10 -36
  22. package/dist/entry-protocol-C30UPXzy.js +14 -0
  23. package/dist/entry-source-DSE5NAJu.js +70 -0
  24. package/dist/entry-source-SHoE-DUP.js +3 -0
  25. package/dist/exit-Hh-O3gp4.js +83 -0
  26. package/dist/{header-hook-Vzw9J9BY.js → header-hook-JfqaTt34.js} +69 -23
  27. package/dist/{index-B8LsM6Mh.d.ts → index-gzGs53Ue.d.ts} +43 -38
  28. package/dist/index.d.ts +88 -44
  29. package/dist/index.js +216 -84
  30. package/dist/listen-options-7TaXjyrk.js +1 -2
  31. package/dist/{load-entry-CCPWbsrj.js → load-entry-Bgq1_HDV.js} +11 -12
  32. package/dist/{log-DQAS5gGT.js → log-DfC9D5_T.js} +70 -49
  33. package/dist/{node-D6m6e6EI.js → node-DQPrMFyc.js} +20 -8
  34. package/dist/node-DyKDFII0.js +263 -0
  35. package/dist/node-vite.d.ts +2 -3
  36. package/dist/node-vite.js +1 -1
  37. package/dist/node.d.ts +41 -64
  38. package/dist/node.js +3 -3
  39. package/dist/react-router-vite.d.ts +2 -3
  40. package/dist/react-router-vite.js +1 -1
  41. package/dist/react-router.d.ts +6 -17
  42. package/dist/react-router.js +9 -14
  43. package/dist/request-context-Cslbrscf.js +163 -0
  44. package/dist/{response-edge-CU8ZvL_F.js → response-edge-Ow5Pi5qF.js} +13 -10
  45. package/dist/{response-writer-D7KHfr8n.js → response-writer-Dd4Ey99f.js} +57 -21
  46. package/dist/{script-hashes-CU7P9oZU.js → script-hashes-BdvJ0QI_.js} +2 -3
  47. package/dist/serve-AatMo9k6.js +26 -0
  48. package/dist/{stale-build-navigation-rg5xxmTr.js → stale-build-navigation-Qf_Lem39.js} +4 -5
  49. package/dist/{stale-build-navigation-ypV7Ow4o.d.ts → stale-build-navigation-WjhD8zHi.d.ts} +4 -4
  50. package/dist/start-DYFyGKsM.js +470 -0
  51. package/dist/static-files-BdTPam5b.js +438 -0
  52. package/dist/static-pages-6IBHdYQc.d.ts +30 -0
  53. package/dist/tanstack-start-vite.d.ts +2 -3
  54. package/dist/tanstack-start-vite.js +1 -1
  55. package/dist/tanstack-start.d.ts +3 -4
  56. package/dist/tanstack-start.js +2 -3
  57. package/dist/tcp-3v4pmnYU.js +58 -0
  58. package/dist/testing.d.ts +8 -6
  59. package/dist/testing.js +19 -17
  60. package/dist/{trailing-slash-D2QWKWEu.d.ts → trailing-slash-C-yBKCib.d.ts} +2 -3
  61. package/dist/{types-MgFtkNQW.d.ts → types-KsKRDwAv.d.ts} +97 -46
  62. package/dist/vercel-pages.d.ts +3 -16
  63. package/dist/vercel-pages.js +1 -2
  64. package/dist/vercel-vite.d.ts +4 -5
  65. package/dist/vercel-vite.js +48 -44
  66. package/dist/vercel.d.ts +13 -10
  67. package/dist/vercel.js +48 -35
  68. package/dist/{vite-D4hfj3ph.js → vite-Brb8YR9I.js} +2 -7
  69. package/dist/{vite-B-GfswoH.js → vite-CHppJWp_.js} +5 -7
  70. package/dist/{vite-DyrhyKEr.js → vite-DjlHdyTM.js} +2 -7
  71. package/dist/vite.d.ts +2 -2
  72. package/dist/vite.js +885 -2
  73. package/package.json +13 -12
  74. package/dist/brotli-only-DrA29Ecw.js +0 -97
  75. package/dist/brotli-only-DrA29Ecw.js.map +0 -1
  76. package/dist/build-id-B0448vZH.js +0 -151
  77. package/dist/build-id-B0448vZH.js.map +0 -1
  78. package/dist/build-manifest-DBMWe3Lx.js.map +0 -1
  79. package/dist/bun-BCz6K_Xv.js.map +0 -1
  80. package/dist/cli.js.map +0 -1
  81. package/dist/client.js.map +0 -1
  82. package/dist/compress-Cp5NfXCC.js.map +0 -1
  83. package/dist/compression-CT2mWlKM.js.map +0 -1
  84. package/dist/create-server-Bp1yILQk.js.map +0 -1
  85. package/dist/deno-aqhikNMG.js.map +0 -1
  86. package/dist/entry-BoxCqc6w.js.map +0 -1
  87. package/dist/header-hook-Vzw9J9BY.js.map +0 -1
  88. package/dist/index.js.map +0 -1
  89. package/dist/listen-options-7TaXjyrk.js.map +0 -1
  90. package/dist/load-entry-CCPWbsrj.js.map +0 -1
  91. package/dist/log-DQAS5gGT.js.map +0 -1
  92. package/dist/node-CVVdk2N6.js +0 -334
  93. package/dist/node-CVVdk2N6.js.map +0 -1
  94. package/dist/node-D6m6e6EI.js.map +0 -1
  95. package/dist/react-router.js.map +0 -1
  96. package/dist/request-context-Bxdbk5P1.js +0 -80
  97. package/dist/request-context-Bxdbk5P1.js.map +0 -1
  98. package/dist/response-edge-CU8ZvL_F.js.map +0 -1
  99. package/dist/response-writer-D7KHfr8n.js.map +0 -1
  100. package/dist/script-hashes-CU7P9oZU.js.map +0 -1
  101. package/dist/serve-W4WacdOw.js +0 -29
  102. package/dist/serve-W4WacdOw.js.map +0 -1
  103. package/dist/stale-build-navigation-rg5xxmTr.js.map +0 -1
  104. package/dist/start-j0VlxeiI.js +0 -324
  105. package/dist/start-j0VlxeiI.js.map +0 -1
  106. package/dist/static-files-C2ea8KQ6.js +0 -310
  107. package/dist/static-files-C2ea8KQ6.js.map +0 -1
  108. package/dist/tanstack-start.js.map +0 -1
  109. package/dist/tcp-BgDXbjOG.js +0 -42
  110. package/dist/tcp-BgDXbjOG.js.map +0 -1
  111. package/dist/testing.js.map +0 -1
  112. package/dist/vercel-pages.js.map +0 -1
  113. package/dist/vercel-vite.js.map +0 -1
  114. package/dist/vercel.js.map +0 -1
  115. package/dist/vite-B-GfswoH.js.map +0 -1
  116. package/dist/vite-D4hfj3ph.js.map +0 -1
  117. package/dist/vite-DPiSKHDn.js +0 -870
  118. package/dist/vite-DPiSKHDn.js.map +0 -1
  119. package/dist/vite-DyrhyKEr.js.map +0 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ngrok/app-server",
3
- "version": "0.4.1",
3
+ "version": "0.5.1",
4
4
  "description": "A composable Hono app server for React Router and TanStack Start: prerendered pages, streamed compression, structured logs, and clean shutdown on Node, Bun, Deno, and Vercel.",
5
5
  "homepage": "https://github.com/ngrok/app-server#readme",
6
6
  "bugs": {
@@ -73,9 +73,8 @@
73
73
  "./package.json": "./package.json"
74
74
  },
75
75
  "dependencies": {
76
- "@hono/node-server": "2.1.5",
77
- "@vercel/nft": "1.11.0",
78
- "hono": "4.13.14"
76
+ "@hono/node-server": "2.1.8",
77
+ "@vercel/nft": "1.11.2"
79
78
  },
80
79
  "devDependencies": {
81
80
  "@changesets/changelog-github": "1.0.1",
@@ -84,24 +83,26 @@
84
83
  "@react-router/dev": "8.5.1",
85
84
  "@react-router/serve": "8.5.1",
86
85
  "@tanstack/react-router": "1.170.46",
87
- "@tanstack/react-start": "1.169.4",
86
+ "@tanstack/react-start": "1.169.5",
88
87
  "@types/node": "26.6.6",
89
- "@vitejs/plugin-react": "6.1.2",
88
+ "@vitejs/plugin-react": "6.3.0",
90
89
  "happy-dom": "20.14.6",
91
- "oxfmt": "0.75.0",
92
- "oxlint": "1.90.0",
93
- "oxlint-tsgolint": "7.0.2005",
90
+ "hono": "4.13.18",
91
+ "oxfmt": "0.78.0",
92
+ "oxlint": "1.93.0",
93
+ "oxlint-tsgolint": "7.0.2007",
94
94
  "react": "19.3.1",
95
95
  "react-dom": "19.3.1",
96
96
  "react-router": "8.5.1",
97
- "tsdown": "0.23.3",
97
+ "tsdown": "0.23.7",
98
98
  "typescript": "7.0.2",
99
- "vite": "8.3.5",
100
- "vitest": "5.0.5",
99
+ "vite": "8.3.8",
100
+ "vitest": "5.1.0",
101
101
  "zod": "4.6.7"
102
102
  },
103
103
  "peerDependencies": {
104
104
  "@tanstack/react-router": "^1.170.0",
105
+ "hono": "^4.13.16",
105
106
  "react-router": "^8.5.0",
106
107
  "vite": "^8.3.0"
107
108
  },
@@ -1,97 +0,0 @@
1
- import { r as copyName } from "./compression-CT2mWlKM.js";
2
- import { createBrotliDecompress } from "node:zlib";
3
- import { Duplex } from "node:stream";
4
-
5
- // src/vercel/brotli-only.ts
6
- /**
7
- * The URL path of the list that `vercel()` writes in the function's client
8
- * build: the size of each file whose only copy in the function is its brotli
9
- * copy, by the URL path of the file. Why a dotfile: the static stages never
10
- * serve one.
11
- */
12
- const BROTLI_ONLY_LIST = "/.app-server-brotli.json";
13
- /** The URL path of the brotli copy of the file at `path`. */
14
- function brotliCopy(path) {
15
- const slash = path.lastIndexOf("/");
16
- return `${path.slice(0, slash + 1)}${copyName(path.slice(slash + 1), "br")}`;
17
- }
18
- /** The bytes of `range` in `stream`. It cancels `stream` after the last byte. */
19
- function sliced(stream, { start, end }) {
20
- let position = 0;
21
- return stream.pipeThrough(new TransformStream({ transform(chunk, controller) {
22
- const from = Math.max(start - position, 0);
23
- const to = Math.min(end + 1 - position, chunk.byteLength);
24
- position += chunk.byteLength;
25
- if (to > from) controller.enqueue(chunk.subarray(from, to));
26
- if (position > end) controller.terminate();
27
- } }));
28
- }
29
- /**
30
- * The bytes of the stream that `open` gives, with `open` called on the first
31
- * read. Why: a pipe reads its source at once, and a stage can drop a response
32
- * that no one reads.
33
- */
34
- function decodedOnRead(open) {
35
- let reader;
36
- return new ReadableStream({
37
- async pull(controller) {
38
- reader ??= open().then((stream) => stream.getReader());
39
- const { done, value } = await (await reader).read();
40
- if (done) controller.close();
41
- else controller.enqueue(value);
42
- },
43
- async cancel(reason) {
44
- await (await reader)?.cancel(reason);
45
- }
46
- }, { highWaterMark: 0 });
47
- }
48
- /**
49
- * `files` that also find each file in {@link BROTLI_ONLY_LIST}, with the
50
- * size from the list and the time of its brotli copy. Each read of such a
51
- * file decompresses its brotli copy. Why: a function then keeps one copy of
52
- * the file, not three, and a client that accepts brotli, as each browser
53
- * does, gets the copy with no work.
54
- *
55
- * @example
56
- * brotliOnlyFiles(nodeFiles("build/client")).open("/blog/index.html");
57
- */
58
- function brotliOnlyFiles(files) {
59
- let sizes;
60
- const readSizes = async () => {
61
- sizes ??= files.stat(BROTLI_ONLY_LIST).then(async (info) => {
62
- if (info?.kind !== "file") return /* @__PURE__ */ new Map();
63
- const text = await new Response(await files.open(BROTLI_ONLY_LIST)).text();
64
- return new Map(Object.entries(JSON.parse(text)));
65
- });
66
- return sizes;
67
- };
68
- const wrap = (inner) => {
69
- const { snapshot } = inner;
70
- return {
71
- stat: async (path) => {
72
- const info = await inner.stat(path);
73
- const size = info == null ? (await readSizes()).get(path) : void 0;
74
- if (size == null) return info;
75
- const copy = await inner.stat(brotliCopy(path));
76
- return copy?.kind === "file" ? {
77
- kind: "file",
78
- size,
79
- mtimeMs: copy.mtimeMs
80
- } : void 0;
81
- },
82
- open: async (path, range) => {
83
- if (!(await readSizes()).has(path)) return inner.open(path, range);
84
- return decodedOnRead(async () => {
85
- const decompress = Duplex.toWeb(createBrotliDecompress());
86
- const decoded = (await inner.open(brotliCopy(path))).pipeThrough(decompress);
87
- return range == null ? decoded : sliced(decoded, range);
88
- });
89
- },
90
- ...snapshot == null ? {} : { snapshot: async () => wrap(await snapshot()) }
91
- };
92
- };
93
- return wrap(files);
94
- }
95
-
96
- export { brotliOnlyFiles as n, BROTLI_ONLY_LIST as t };
97
- //# sourceMappingURL=brotli-only-DrA29Ecw.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"brotli-only-DrA29Ecw.js","names":[],"sources":["../src/vercel/brotli-only.ts"],"sourcesContent":["import { Duplex } from \"node:stream\";\nimport { createBrotliDecompress } from \"node:zlib\";\nimport { copyName } from \"../core/compression.js\";\nimport type { ByteRange, StaticFiles } from \"../core/types.js\";\n\n/**\n * The URL path of the list that `vercel()` writes in the function's client\n * build: the size of each file whose only copy in the function is its brotli\n * copy, by the URL path of the file. Why a dotfile: the static stages never\n * serve one.\n */\nexport const BROTLI_ONLY_LIST = \"/.app-server-brotli.json\";\n\n/** The URL path of the brotli copy of the file at `path`. */\nfunction brotliCopy(path: string): string {\n\tconst slash = path.lastIndexOf(\"/\");\n\treturn `${path.slice(0, slash + 1)}${copyName(path.slice(slash + 1), \"br\")}`;\n}\n\n/** The bytes of `range` in `stream`. It cancels `stream` after the last byte. */\nfunction sliced(stream: ReadableStream<Uint8Array>, { start, end }: ByteRange) {\n\tlet position = 0;\n\treturn stream.pipeThrough(\n\t\tnew TransformStream<Uint8Array, Uint8Array>({\n\t\t\ttransform(chunk, controller) {\n\t\t\t\tconst from = Math.max(start - position, 0);\n\t\t\t\tconst to = Math.min(end + 1 - position, chunk.byteLength);\n\t\t\t\tposition += chunk.byteLength;\n\t\t\t\tif (to > from) {\n\t\t\t\t\tcontroller.enqueue(chunk.subarray(from, to));\n\t\t\t\t}\n\t\t\t\tif (position > end) {\n\t\t\t\t\tcontroller.terminate();\n\t\t\t\t}\n\t\t\t},\n\t\t}),\n\t);\n}\n\n/**\n * The bytes of the stream that `open` gives, with `open` called on the first\n * read. Why: a pipe reads its source at once, and a stage can drop a response\n * that no one reads.\n */\nfunction decodedOnRead(\n\topen: () => Promise<ReadableStream<Uint8Array>>,\n): ReadableStream<Uint8Array> {\n\tlet reader: Promise<ReadableStreamDefaultReader<Uint8Array>> | undefined;\n\treturn new ReadableStream<Uint8Array>(\n\t\t{\n\t\t\tasync pull(controller) {\n\t\t\t\treader ??= open().then((stream) => stream.getReader());\n\t\t\t\tconst { done, value } = await (await reader).read();\n\t\t\t\tif (done) {\n\t\t\t\t\tcontroller.close();\n\t\t\t\t} else {\n\t\t\t\t\tcontroller.enqueue(value);\n\t\t\t\t}\n\t\t\t},\n\t\t\tasync cancel(reason) {\n\t\t\t\tawait (await reader)?.cancel(reason);\n\t\t\t},\n\t\t},\n\t\t{ highWaterMark: 0 },\n\t);\n}\n\n/**\n * `files` that also find each file in {@link BROTLI_ONLY_LIST}, with the\n * size from the list and the time of its brotli copy. Each read of such a\n * file decompresses its brotli copy. Why: a function then keeps one copy of\n * the file, not three, and a client that accepts brotli, as each browser\n * does, gets the copy with no work.\n *\n * @example\n * brotliOnlyFiles(nodeFiles(\"build/client\")).open(\"/blog/index.html\");\n */\nexport function brotliOnlyFiles(files: StaticFiles): StaticFiles {\n\tlet sizes: Promise<ReadonlyMap<string, number>> | undefined;\n\t// Why once and late: the list does not change while the function runs, and a file found on\n\t// disk does not need it.\n\tconst readSizes = async () => {\n\t\tsizes ??= files.stat(BROTLI_ONLY_LIST).then(async (info) => {\n\t\t\tif (info?.kind !== \"file\") {\n\t\t\t\treturn new Map<string, number>();\n\t\t\t}\n\t\t\tconst text = await new Response(await files.open(BROTLI_ONLY_LIST)).text();\n\t\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- `vercel()` of this package wrote the file.\n\t\t\treturn new Map(Object.entries(JSON.parse(text) as Record<string, number>));\n\t\t});\n\t\treturn sizes;\n\t};\n\tconst wrap = (inner: StaticFiles): StaticFiles => {\n\t\tconst { snapshot } = inner;\n\t\treturn {\n\t\t\tstat: async (path) => {\n\t\t\t\tconst info = await inner.stat(path);\n\t\t\t\tconst size = info == null ? (await readSizes()).get(path) : undefined;\n\t\t\t\tif (size == null) {\n\t\t\t\t\treturn info;\n\t\t\t\t}\n\t\t\t\tconst copy = await inner.stat(brotliCopy(path));\n\t\t\t\treturn copy?.kind === \"file\" ? { kind: \"file\", size, mtimeMs: copy.mtimeMs } : undefined;\n\t\t\t},\n\t\t\topen: async (path, range) => {\n\t\t\t\tif (!(await readSizes()).has(path)) {\n\t\t\t\t\treturn inner.open(path, range);\n\t\t\t\t}\n\t\t\t\treturn decodedOnRead(async () => {\n\t\t\t\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Node.js types its web streams apart from the global ones.\n\t\t\t\t\tconst decompress = Duplex.toWeb(createBrotliDecompress()) as ReadableWritablePair<\n\t\t\t\t\t\tUint8Array,\n\t\t\t\t\t\tUint8Array\n\t\t\t\t\t>;\n\t\t\t\t\tconst decoded = (await inner.open(brotliCopy(path))).pipeThrough(decompress);\n\t\t\t\t\treturn range == null ? decoded : sliced(decoded, range);\n\t\t\t\t});\n\t\t\t},\n\t\t\t...(snapshot == null ? {} : { snapshot: async () => wrap(await snapshot()) }),\n\t\t};\n\t};\n\treturn wrap(files);\n}\n"],"mappings":";;;;;;;;;;;AAWA,MAAa,mBAAmB;;AAGhC,SAAS,WAAW,MAAsB;CACzC,MAAM,QAAQ,KAAK,YAAY,GAAG;CAClC,OAAO,GAAG,KAAK,MAAM,GAAG,QAAQ,CAAC,IAAI,SAAS,KAAK,MAAM,QAAQ,CAAC,GAAG,IAAI;AAC1E;;AAGA,SAAS,OAAO,QAAoC,EAAE,OAAO,OAAkB;CAC9E,IAAI,WAAW;CACf,OAAO,OAAO,YACb,IAAI,gBAAwC,EAC3C,UAAU,OAAO,YAAY;EAC5B,MAAM,OAAO,KAAK,IAAI,QAAQ,UAAU,CAAC;EACzC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,WAAW,IAAI,CAAC;IAC9C,OAAO,MAAM,SAAS,SAAS;KAAE,MAAM;KAAQ;KAAM,SAAS,KAAK;IAAQ,IAAI;GAChF;GACA,MAAM,OAAO,MAAM,UAAU;IAC5B,IAAI,EAAE,MAAM,UAAU,EAAC,CAAE,IAAI,IAAI,GAChC,OAAO,MAAM,KAAK,MAAM,KAAK;IAE9B,OAAO,cAAc,YAAY;KAEhC,MAAM,aAAa,OAAO,MAAM,uBAAuB,CAAC;KAIxD,MAAM,WAAW,MAAM,MAAM,KAAK,WAAW,IAAI,CAAC,EAAC,CAAE,YAAY,UAAU;KAC3E,OAAO,SAAS,OAAO,UAAU,OAAO,SAAS,KAAK;IACvD,CAAC;GACF;GACA,GAAI,YAAY,OAAO,CAAC,IAAI,EAAE,UAAU,YAAY,KAAK,MAAM,SAAS,CAAC,EAAE;EAC5E;CACD;CACA,OAAO,KAAK,KAAK;AAClB"}
@@ -1,151 +0,0 @@
1
- import { o as withHeaderHook } from "./header-hook-Vzw9J9BY.js";
2
-
3
- // src/core/plugin-options.ts
4
- /**
5
- * The option of `defaultPlugins()` that places each plugin, by plugin
6
- * object. Why the object, not the name: an app plugin can have any name.
7
- */
8
- const options = /* @__PURE__ */ new WeakMap();
9
- /**
10
- * Marks `plugin` as the plugin of the `option` of `defaultPlugins()`, so
11
- * `createServer` finds it in the plugin list.
12
- *
13
- * @example
14
- * return optionPlugin("noindex", { name: "noindex", middleware });
15
- */
16
- function optionPlugin(option, plugin) {
17
- options.set(plugin, option);
18
- return plugin;
19
- }
20
- /**
21
- * Stops startup when `plugins` has two plugins of one option of
22
- * `defaultPlugins()`, such as two `buildId()`. Why: two copies do not fail.
23
- * One sets its headers over the other, so a value that the app gave is lost.
24
- *
25
- * @example
26
- * checkOptionPlugins([...defaultPlugins(), buildId({ value: "v42" })]); // throws
27
- */
28
- function checkOptionPlugins(plugins) {
29
- const seen = /* @__PURE__ */ new Set();
30
- for (const plugin of plugins) {
31
- const option = options.get(plugin);
32
- if (option != null && seen.has(option)) throw new Error(`The plugin list has the ${plugin.name} plugin two times, so one replaces the other. Keep one: set the "${option}" option of defaultPlugins(), and do not also add the plugin.`);
33
- if (option != null) seen.add(option);
34
- }
35
- }
36
- /** The request headers whose presence alone changes the answer of each plugin, by plugin object. */
37
- const presence = /* @__PURE__ */ new WeakMap();
38
- /**
39
- * Marks `plugin` as one whose changes to a response depend only on whether
40
- * each of `headers` is present in the request. Why: the build can then put
41
- * one static answer for each case on a CDN, which picks the answer by the
42
- * same headers.
43
- *
44
- * @example
45
- * return presenceHeaders(["x-ngrok-edge"], { name: "noindex", middleware });
46
- */
47
- function presenceHeaders(headers, plugin) {
48
- presence.set(plugin, headers);
49
- return plugin;
50
- }
51
- /**
52
- * The headers that {@link presenceHeaders} marked on `plugins`, in lowercase,
53
- * once each.
54
- *
55
- * @example
56
- * presenceHeadersOf(defaultPlugins({ noindex: { unlessHeader: "X-Ngrok-Edge" } })); // => ["x-ngrok-edge"]
57
- */
58
- function presenceHeadersOf(plugins) {
59
- return [...new Set(plugins.flatMap((plugin) => presence.get(plugin) ?? []).map((name) => name.toLowerCase()))];
60
- }
61
-
62
- // src/core/plugins/build-id.ts
63
- /** The header that {@link buildId} sets by default. */
64
- const BUILD_ID_HEADER = "X-Build-Id";
65
- /**
66
- * The `Server-Timing` metric that holds the build of a response. Why
67
- * `Server-Timing`: a script can read it from the performance entries, with no
68
- * request and no change to the document's HTML.
69
- */
70
- const BUILD_ID_METRIC = "build";
71
- /**
72
- * Whether a cache can use the response again without the server: it has a
73
- * fresh time, a stale time, or a date that a cache can guess a fresh time from.
74
- */
75
- function isReusable(response) {
76
- const cacheControl = response.get("Cache-Control") ?? "";
77
- if (/\b(?:no-store|no-cache)\b/iu.test(cacheControl)) return false;
78
- return /\b(?:max-age|s-maxage|stale-while-revalidate|stale-if-error)\s*=\s*"?0*[1-9]/iu.test(cacheControl) || /\bpublic\b/iu.test(cacheControl) || Date.parse(response.get("Expires") ?? "") > Date.now() || response.has("Last-Modified");
79
- }
80
- /** The metrics of a `Server-Timing` header, such as `build;desc="v42"`. */
81
- function serverTimingMetrics(header) {
82
- return (header?.match(/(?:[^",]|"(?:[^"\\]|\\.)*")+/gu) ?? []).map((metric) => metric.trim()).filter((metric) => metric !== "");
83
- }
84
- /** Whether a `Server-Timing` metric is a build. */
85
- function isBuildMetric(metric) {
86
- return metric.split(";")[0]?.trim().toLowerCase() === BUILD_ID_METRIC;
87
- }
88
- /** The `Server-Timing` metrics of `header` that are not a build. */
89
- function otherMetrics(header) {
90
- return serverTimingMetrics(header).filter((metric) => !isBuildMetric(metric));
91
- }
92
- /** The data check before `setup` runs. */
93
- function noDataRequests() {
94
- return false;
95
- }
96
- /** A `Server-Timing` quoted string with the characters of `value`. */
97
- function quoted(value) {
98
- return `"${value.replaceAll(/["\\]/gu, String.raw`\$&`)}"`;
99
- }
100
- /** The `build` metric of `value`, or `undefined` for no build. */
101
- function buildMetric(value) {
102
- return value == null ? void 0 : `${BUILD_ID_METRIC};desc=${quoted(value)}`;
103
- }
104
- /**
105
- * Sets a build ID header on documents and on the framework's data responses,
106
- * such as React Router `.data` files, so a client can see that a deploy
107
- * happened under it. Each of them also gets the build as
108
- * `Server-Timing: build;desc="<value>"`. The `paths` option adds the metric
109
- * to more routes, such as API proxy routes. The plugin removes the build
110
- * header and the `build` metric of an upstream API from each other
111
- * response, so the client reads only this app's build.
112
- * `staleBuildReactRouter()` and `staleBuildTanStack()` from `@ngrok/app-server/client` read the metric
113
- * from the document, and from a response that the browser fetches with no
114
- * script, such as a prefetch.
115
- *
116
- * With no `value`, it sends the build ID that the `appServer` Vite plugin
117
- * derives from the client build. Development and a build with no
118
- * `.app-server.json` then get no build.
119
- *
120
- * @example
121
- * buildId({ value: process.env.IMAGE_TAG });
122
- */
123
- function buildId({ header = BUILD_ID_HEADER, value: given, paths } = {}) {
124
- const explicit = given === "" ? void 0 : given;
125
- let value = explicit;
126
- let timing = buildMetric(value);
127
- let isDataRequest = noDataRequests;
128
- return optionPlugin("buildId", {
129
- name: "build-id",
130
- setup: (info) => {
131
- ({isDataRequest} = info);
132
- value = explicit ?? info.buildId;
133
- timing = buildMetric(value);
134
- },
135
- etagPart: () => value,
136
- middleware: async (context, next) => withHeaderHook(context, next, (response) => {
137
- const { path } = context.req;
138
- const isRouter = (response.get("Content-Type")?.startsWith("text/html") ?? false) || isDataRequest(path);
139
- const isStamped = isRouter || paths?.(path) === true && !isReusable(response);
140
- const before = response.get("Server-Timing");
141
- const metrics = [...otherMetrics(before), ...isStamped && timing != null ? [timing] : []].join(", ");
142
- if (metrics === "") response.delete("Server-Timing");
143
- else if (metrics !== before) response.set("Server-Timing", metrics);
144
- if (isRouter && value != null) response.set(header, value);
145
- else response.delete(header);
146
- })
147
- });
148
- }
149
-
150
- export { serverTimingMetrics as a, presenceHeaders as c, isBuildMetric as i, presenceHeadersOf as l, BUILD_ID_METRIC as n, checkOptionPlugins as o, buildId as r, optionPlugin as s, BUILD_ID_HEADER as t };
151
- //# sourceMappingURL=build-id-B0448vZH.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"build-id-B0448vZH.js","names":[],"sources":["../src/core/plugin-options.ts","../src/core/plugins/build-id.ts"],"sourcesContent":["import type { Plugin } from \"./types.js\";\n\n/**\n * The option of `defaultPlugins()` that places each plugin, by plugin\n * object. Why the object, not the name: an app plugin can have any name.\n */\nconst options = new WeakMap<Plugin, string>();\n\n/**\n * Marks `plugin` as the plugin of the `option` of `defaultPlugins()`, so\n * `createServer` finds it in the plugin list.\n *\n * @example\n * return optionPlugin(\"noindex\", { name: \"noindex\", middleware });\n */\nexport function optionPlugin<P extends Plugin>(option: string, plugin: P): P {\n\toptions.set(plugin, option);\n\treturn plugin;\n}\n\n/**\n * Stops startup when `plugins` has two plugins of one option of\n * `defaultPlugins()`, such as two `buildId()`. Why: two copies do not fail.\n * One sets its headers over the other, so a value that the app gave is lost.\n *\n * @example\n * checkOptionPlugins([...defaultPlugins(), buildId({ value: \"v42\" })]); // throws\n */\nexport function checkOptionPlugins(plugins: readonly Plugin[]): void {\n\tconst seen = new Set<string>();\n\tfor (const plugin of plugins) {\n\t\tconst option = options.get(plugin);\n\t\tif (option != null && seen.has(option)) {\n\t\t\tthrow new Error(\n\t\t\t\t`The plugin list has the ${plugin.name} plugin two times, so one replaces the other. Keep one: set the \"${option}\" option of defaultPlugins(), and do not also add the plugin.`,\n\t\t\t);\n\t\t}\n\t\tif (option != null) {\n\t\t\tseen.add(option);\n\t\t}\n\t}\n}\n\n/** The request headers whose presence alone changes the answer of each plugin, by plugin object. */\nconst presence = new WeakMap<Plugin, readonly string[]>();\n\n/**\n * Marks `plugin` as one whose changes to a response depend only on whether\n * each of `headers` is present in the request. Why: the build can then put\n * one static answer for each case on a CDN, which picks the answer by the\n * same headers.\n *\n * @example\n * return presenceHeaders([\"x-ngrok-edge\"], { name: \"noindex\", middleware });\n */\nexport function presenceHeaders<P extends Plugin>(headers: readonly string[], plugin: P): P {\n\tpresence.set(plugin, headers);\n\treturn plugin;\n}\n\n/**\n * The headers that {@link presenceHeaders} marked on `plugins`, in lowercase,\n * once each.\n *\n * @example\n * presenceHeadersOf(defaultPlugins({ noindex: { unlessHeader: \"X-Ngrok-Edge\" } })); // => [\"x-ngrok-edge\"]\n */\nexport function presenceHeadersOf(plugins: readonly Plugin[]): string[] {\n\treturn [\n\t\t...new Set(\n\t\t\tplugins.flatMap((plugin) => presence.get(plugin) ?? []).map((name) => name.toLowerCase()),\n\t\t),\n\t];\n}\n","import { withHeaderHook } from \"../header-hook.js\";\nimport { optionPlugin } from \"../plugin-options.js\";\nimport type { Plugin, ResponseHeaders, SetupInfo } from \"../types.js\";\n\n/** The header that {@link buildId} sets by default. */\nexport const BUILD_ID_HEADER = \"X-Build-Id\";\n\n/**\n * The `Server-Timing` metric that holds the build of a response. Why\n * `Server-Timing`: a script can read it from the performance entries, with no\n * request and no change to the document's HTML.\n */\nexport const BUILD_ID_METRIC = \"build\";\n\n/** Options for {@link buildId}. */\nexport type BuildIdOptions = {\n\t/** @default \"X-Build-Id\" */\n\theader?: string;\n\t/**\n\t * The deployed build, such as the image tag. With no value or `\"\"`, the\n\t * plugin sends the ID that the `appServer` Vite plugin derives from the\n\t * client build. In development, it then sends no build.\n\t * @default the `buildId` of `.app-server.json` in the client build\n\t */\n\tvalue?: string | undefined;\n\t/**\n\t * More request paths whose responses carry the build in `Server-Timing`,\n\t * such as the app's proxy routes to its API. A tab then finds a new build\n\t * in the requests that it already sends. They get no build header, because\n\t * the header marks the router's own responses. A response that a cache can\n\t * use again without the server gets no build, so a cached copy never\n\t * reports an old build. It runs in a header hook, so it can run more than\n\t * once for one request.\n\t *\n\t * @example\n\t * buildId({ paths: (path) => path.startsWith(\"/api/\") });\n\t */\n\tpaths?: (path: string) => boolean;\n};\n\n/**\n * Whether a cache can use the response again without the server: it has a\n * fresh time, a stale time, or a date that a cache can guess a fresh time from.\n */\nfunction isReusable(response: ResponseHeaders): boolean {\n\tconst cacheControl = response.get(\"Cache-Control\") ?? \"\";\n\tif (/\\b(?:no-store|no-cache)\\b/iu.test(cacheControl)) {\n\t\treturn false;\n\t}\n\treturn (\n\t\t/\\b(?:max-age|s-maxage|stale-while-revalidate|stale-if-error)\\s*=\\s*\"?0*[1-9]/iu.test(\n\t\t\tcacheControl,\n\t\t) ||\n\t\t/\\bpublic\\b/iu.test(cacheControl) ||\n\t\tDate.parse(response.get(\"Expires\") ?? \"\") > Date.now() ||\n\t\tresponse.has(\"Last-Modified\")\n\t);\n}\n\n/** The metrics of a `Server-Timing` header, such as `build;desc=\"v42\"`. */\nexport function serverTimingMetrics(header: string | null): string[] {\n\t// Why match the quoted strings: a comma or an escaped quote in a description does not end a metric.\n\treturn (header?.match(/(?:[^\",]|\"(?:[^\"\\\\]|\\\\.)*\")+/gu) ?? [])\n\t\t.map((metric) => metric.trim())\n\t\t.filter((metric) => metric !== \"\");\n}\n\n/** Whether a `Server-Timing` metric is a build. */\nexport function isBuildMetric(metric: string): boolean {\n\treturn metric.split(\";\")[0]?.trim().toLowerCase() === BUILD_ID_METRIC;\n}\n\n/** The `Server-Timing` metrics of `header` that are not a build. */\nfunction otherMetrics(header: string | null): string[] {\n\treturn serverTimingMetrics(header).filter((metric) => !isBuildMetric(metric));\n}\n\n/** The data check before `setup` runs. */\nfunction noDataRequests(): boolean {\n\treturn false;\n}\n\n/** A `Server-Timing` quoted string with the characters of `value`. */\nfunction quoted(value: string): string {\n\treturn `\"${value.replaceAll(/[\"\\\\]/gu, String.raw`\\$&`)}\"`;\n}\n\n/** The `build` metric of `value`, or `undefined` for no build. */\nfunction buildMetric(value: string | undefined): string | undefined {\n\treturn value == null ? undefined : `${BUILD_ID_METRIC};desc=${quoted(value)}`;\n}\n\n/**\n * Sets a build ID header on documents and on the framework's data responses,\n * such as React Router `.data` files, so a client can see that a deploy\n * happened under it. Each of them also gets the build as\n * `Server-Timing: build;desc=\"<value>\"`. The `paths` option adds the metric\n * to more routes, such as API proxy routes. The plugin removes the build\n * header and the `build` metric of an upstream API from each other\n * response, so the client reads only this app's build.\n * `staleBuildReactRouter()` and `staleBuildTanStack()` from `@ngrok/app-server/client` read the metric\n * from the document, and from a response that the browser fetches with no\n * script, such as a prefetch.\n *\n * With no `value`, it sends the build ID that the `appServer` Vite plugin\n * derives from the client build. Development and a build with no\n * `.app-server.json` then get no build.\n *\n * @example\n * buildId({ value: process.env.IMAGE_TAG });\n */\nexport function buildId({\n\theader = BUILD_ID_HEADER,\n\tvalue: given,\n\tpaths,\n}: BuildIdOptions = {}): Plugin {\n\t// Why `\"\"` too: a deploy can set the variable with no value, such as `IMAGE_TAG=`.\n\tconst explicit = given === \"\" ? undefined : given;\n\tlet value = explicit;\n\tlet timing = buildMetric(value);\n\tlet isDataRequest: SetupInfo[\"isDataRequest\"] = noDataRequests;\n\treturn optionPlugin(\"buildId\", {\n\t\tname: \"build-id\",\n\t\tsetup: (info) => {\n\t\t\t({ isDataRequest } = info);\n\t\t\tvalue = explicit ?? info.buildId;\n\t\t\ttiming = buildMetric(value);\n\t\t},\n\t\t// Why: a 304 has no `Content-Type`, so a document that did not change on disk must still\n\t\t// answer 200 when the build ID changes.\n\t\tetagPart: () => value,\n\t\tmiddleware: async (context, next) =>\n\t\t\twithHeaderHook(context, next, (response) => {\n\t\t\t\tconst { path } = context.req;\n\t\t\t\tconst isRouter =\n\t\t\t\t\t(response.get(\"Content-Type\")?.startsWith(\"text/html\") ?? false) || isDataRequest(path);\n\t\t\t\tconst isStamped = isRouter || (paths?.(path) === true && !isReusable(response));\n\t\t\t\t// Why remove the build of an upstream API: the client must read only this app's build.\n\t\t\t\tconst before = response.get(\"Server-Timing\");\n\t\t\t\tconst metrics = [\n\t\t\t\t\t...otherMetrics(before),\n\t\t\t\t\t...(isStamped && timing != null ? [timing] : []),\n\t\t\t\t].join(\", \");\n\t\t\t\tif (metrics === \"\") {\n\t\t\t\t\tresponse.delete(\"Server-Timing\");\n\t\t\t\t} else if (metrics !== before) {\n\t\t\t\t\tresponse.set(\"Server-Timing\", metrics);\n\t\t\t\t}\n\t\t\t\tif (isRouter && value != null) {\n\t\t\t\t\tresponse.set(header, value);\n\t\t\t\t} else {\n\t\t\t\t\tresponse.delete(header);\n\t\t\t\t}\n\t\t\t}),\n\t});\n}\n"],"mappings":";;;;;;;AAMA,MAAM,0BAAU,IAAI,QAAwB;;;;;;;;AAS5C,SAAgB,aAA+B,QAAgB,QAAc;CAC5E,QAAQ,IAAI,QAAQ,MAAM;CAC1B,OAAO;AACR;;;;;;;;;AAUA,SAAgB,mBAAmB,SAAkC;CACpE,MAAM,uBAAO,IAAI,IAAY;CAC7B,KAAK,MAAM,UAAU,SAAS;EAC7B,MAAM,SAAS,QAAQ,IAAI,MAAM;EACjC,IAAI,UAAU,QAAQ,KAAK,IAAI,MAAM,GACpC,MAAM,IAAI,MACT,2BAA2B,OAAO,KAAK,mEAAmE,OAAO,8DAClH;EAED,IAAI,UAAU,MACb,KAAK,IAAI,MAAM;CAEjB;AACD;;AAGA,MAAM,2BA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;AAC3E;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,QAAQ,EACvB,SAAS,iBACT,OAAO,OACP,UACmB,CAAC,GAAW;CAE/B,MAAM,WAAW,UAAU,KAAK,SAAY;CAC5C,IAAI,QAAQ;CACZ,IAAI,SAAS,YAAY,KAAK;CAC9B,IAAI,gBAA4C;CAChD,OAAO,aAAa,WAAW;EAC9B,MAAM;EACN,QAAQ,SAAS;GAChB,CAAC,CAAE,iBAAkB;GACrB,QAAQ,YAAY,KAAK;GACzB,SAAS,YAAY,KAAK;EAC3B;EAGA,gBAAgB;EAChB,YAAY,OAAO,SAAS,SAC3B,eAAe,SAAS,OAAO,aAAa;GAC3C,MAAM,EAAE,SAAS,QAAQ;GACzB,MAAM,YACJ,SAAS,IAAI,cAAc,CAAC,EAAE,WAAW,WAAW,KAAK,UAAU,cAAc,IAAI;GACvF,MAAM,YAAY,YAAa,QAAQ,IAAI,MAAM,QAAQ,CAAC,WAAW,QAAQ;GAE7E,MAAM,SAAS,SAAS,IAAI,eAAe;GAC3C,MAAM,UAAU,CACf,GAAG,aAAa,MAAM,GACtB,GAAI,aAAa,UAAU,OAAO,CAAC,MAAM,IAAI,CAAC,CAC/C,CAAC,CAAC,KAAK,IAAI;GACX,IAAI,YAAY,IACf,SAAS,OAAO,eAAe;QACzB,IAAI,YAAY,QACtB,SAAS,IAAI,iBAAiB,OAAO;GAEtC,IAAI,YAAY,SAAS,MACxB,SAAS,IAAI,QAAQ,KAAK;QAE1B,SAAS,OAAO,MAAM;EAExB,CAAC;CACH,CAAC;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"build-manifest-DBMWe3Lx.js","names":[],"sources":["../src/core/build-manifest.ts"],"sourcesContent":["import type { StaticFiles } from \"./types.js\";\n\n/**\n * The file under the client build that the Vite plugin writes after the\n * client build and again after the prerender pass. It is a dotfile, so the\n * static stages never serve it.\n */\nexport const BUILD_MANIFEST_FILE = \".app-server.json\";\n\n/** The URL path of the hashed files of a build that records none: Vite's default `build.assetsDir`. */\nexport const DEFAULT_ASSETS_PATH = \"/assets/\";\n\n/** What the Vite plugin records about the client build. */\nexport type BuildManifest = {\n\t/**\n\t * The ID of the client build: a hash of the files that the client build\n\t * writes. The `buildId` plugin sends it by default.\n\t */\n\tbuildId?: string;\n\t/**\n\t * The URL path of Vite's `build.assetsDir`, such as `/assets/`. It starts\n\t * and ends with `/`. The `assets` plugin serves its files with a one-year\n\t * immutable cache.\n\t */\n\tassetsPath?: string;\n\t/** The URL paths that answered with a 2xx, sorted. */\n\tprerendered: string[];\n\t/** The headers of each prerendered file that is not an HTML document, by URL path. */\n\theaders: Record<string, Record<string, string>>;\n\t/**\n\t * The base64 `SHA-256` of each inline script of each HTML file in the client\n\t * build, by the file's URL path, such as `/about/index.html`. A CSP trusts\n\t * the scripts of a prerendered page by these hashes.\n\t */\n\tscriptHashes: Record<string, string[]>;\n};\n\n/**\n * The key for a URL path in {@link BuildManifest}: the path with no trailing\n * slash, so `/a/` and `/a` share headers. The root stays `/`.\n *\n * @example\n * manifestKey(\"/components/button/\"); // => \"/components/button\"\n */\nexport function manifestKey(pathname: string): string {\n\tconst trimmed = pathname.replace(/\\/+$/u, \"\");\n\treturn trimmed === \"\" ? \"/\" : trimmed;\n}\n\nfunction isStringRecord(value: unknown): value is Record<string, string> {\n\treturn (\n\t\ttypeof value === \"object\" &&\n\t\tvalue != null &&\n\t\t!Array.isArray(value) &&\n\t\tObject.values(value).every((entry) => typeof entry === \"string\")\n\t);\n}\n\nfunction isStringList(value: unknown): value is string[] {\n\treturn Array.isArray(value) && value.every((entry) => typeof entry === \"string\");\n}\n\n/** The `buildId` of a parsed manifest, which can have none. A value that is not a string throws. */\nfunction buildIdOf(manifest: object): Pick<BuildManifest, \"buildId\"> {\n\tif (!(\"buildId\" in manifest)) {\n\t\treturn {};\n\t}\n\tif (typeof manifest.buildId !== \"string\") {\n\t\tthrow new TypeError(`${BUILD_MANIFEST_FILE}: the \"buildId\" must be a string.`);\n\t}\n\treturn { buildId: manifest.buildId };\n}\n\n/** The `assetsPath` of a parsed manifest, which can have none. A value that is not a URL path prefix throws. */\nfunction assetsPathOf(manifest: object): Pick<BuildManifest, \"assetsPath\"> {\n\tif (!(\"assetsPath\" in manifest)) {\n\t\treturn {};\n\t}\n\tconst { assetsPath } = manifest;\n\tif (\n\t\ttypeof assetsPath !== \"string\" ||\n\t\tassetsPath === \"/\" ||\n\t\t!assetsPath.startsWith(\"/\") ||\n\t\t!assetsPath.endsWith(\"/\")\n\t) {\n\t\tthrow new TypeError(\n\t\t\t`${BUILD_MANIFEST_FILE}: the \"assetsPath\" must be a URL path that starts and ends with \"/\".`,\n\t\t);\n\t}\n\treturn { assetsPath };\n}\n\n/**\n * Reads the build manifest of a client build. A build with no file has an\n * empty one. A file in any other shape throws, so a bad build stops startup.\n */\nexport async function readBuildManifest(files: StaticFiles): Promise<BuildManifest> {\n\tconst path = `/${BUILD_MANIFEST_FILE}`;\n\tif ((await files.stat(path))?.kind !== \"file\") {\n\t\treturn { prerendered: [], headers: {}, scriptHashes: {} };\n\t}\n\tconst parsed: unknown = await new Response(await files.open(path)).json();\n\tif (\n\t\ttypeof parsed !== \"object\" ||\n\t\tparsed == null ||\n\t\t!(\"prerendered\" in parsed) ||\n\t\t!isStringList(parsed.prerendered) ||\n\t\t!(\"headers\" in parsed) ||\n\t\ttypeof parsed.headers !== \"object\" ||\n\t\tparsed.headers == null ||\n\t\t!(\"scriptHashes\" in parsed) ||\n\t\ttypeof parsed.scriptHashes !== \"object\" ||\n\t\tparsed.scriptHashes == null\n\t) {\n\t\tthrow new Error(\n\t\t\t`${BUILD_MANIFEST_FILE} must hold a \"prerendered\" list and the \"headers\" and \"scriptHashes\" objects.`,\n\t\t);\n\t}\n\tconst headers: Record<string, Record<string, string>> = {};\n\tfor (const [key, value] of Object.entries(parsed.headers)) {\n\t\tif (!isStringRecord(value)) {\n\t\t\tthrow new Error(`${BUILD_MANIFEST_FILE}: the headers for ${key} must be strings.`);\n\t\t}\n\t\theaders[key] = value;\n\t}\n\tconst scriptHashes: Record<string, string[]> = {};\n\tfor (const [key, value] of Object.entries(parsed.scriptHashes)) {\n\t\tif (!isStringList(value)) {\n\t\t\tthrow new Error(`${BUILD_MANIFEST_FILE}: the script hashes for ${key} must be strings.`);\n\t\t}\n\t\tscriptHashes[key] = value;\n\t}\n\treturn {\n\t\t...buildIdOf(parsed),\n\t\t...assetsPathOf(parsed),\n\t\tprerendered: parsed.prerendered,\n\t\theaders,\n\t\tscriptHashes,\n\t};\n}\n"],"mappings":";;;;;;AAOA,MAAa,sBAAsB;;AAGnC,MAAa,sBAAsB;;;;;;;;AAkCnC,SAAgB,YAAY,UAA0B;CACrD,MAAM,UAAU,SAAS,QAAQ,SAAS,EAAE;CAC5C,OAAO,YAAY,KAAK,MAAM;AAC/B;AAEA,SAAS,eAAe,OAAiD;CACxE,OACC,OAAO,UAAU,YACjB,SAAS,QACT,CAAC,MAAM,QAAQ,KAAK,KACpB,OAAO,OAAO,KAAK,CAAC,CAAC,OAAO,UAAU,OAAO,UAAU,QAAQ;AAEjE;AAEA,SAAS,aAAa,OAAmC;CACxD,OAAO,MAAM,QAAQ,KAAK,KAAK,MAAM,OAAO,UAAU,OAAO,UAAU,QAAQ;AAChF;;AAGA,SAAS,UAAU,UAAkD;CACpE,IAAI,EAAE,aAAa,WAClB,OAAO,CAAC;CAET,IAAI,OAAO,SAAS,YAAY,UAC/B,MAAM,IAAI,UAAU,GAAG,oBAAoB,kCAAkC;CAE9E,OAAO,EAAE,SAAS,SAAS,QAAQ;AACpC;;AAGA,SAAS,aAAa,UAAqD;CAC1E,IAAI,EAAE,gBAAgB,WACrB,OAAO,CAAC;CAET,MAAM,EAAE,eAAe;CACvB,IACC,OAAO,eAAe,YACtB,eAAe,OACf,CAAC,WAAW,WAAW,GAAG,KAC1B,CAAC,WAAW,SAAS,GAAG,GAExB,MAAM,IAAI,UACT,GAAG,oBAAoB,qEACxB;CAED,OAAO,EAAE,WAAW;AACrB;;;;;AAMA,eAAsB,kBAAkB,OAA4C;CACnF,MAAM,OAAO,IAAI;CACjB,KAAK,MAAM,MAAM,KAAK,IAAI,EAAC,EAAG,SAAS,QACtC,OAAO;EAAE,aAAa,CAAC;EAAG,SAAS,CAAC;EAAG,cAAc,CAAC;CAAE;CAEzD,MAAM,SAAkB,MAAM,IAAI,SAAS,MAAM,MAAM,KAAK,IAAI,CAAC,CAAC,CAAC,KAAK;CACxE,IACC,OAAO,WAAW,YAClB,UAAU,QACV,EAAE,iBAAiB,WACnB,CAAC,aAAa,OAAO,WAAW,KAChC,EAAE,aAAa,WACf,OAAO,OAAO,YAAY,YAC1B,OAAO,WAAW,QAClB,EAAE,kBAAkB,WACpB,OAAO,OAAO,iBAAiB,YAC/B,OAAO,gBAAgB,MAEvB,MAAM,IAAI,MACT,GAAG,oBAAoB,8EACxB;CAED,MAAM,UAAkD,CAAC;CACzD,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,OAAO,OAAO,GAAG;EAC1D,IAAI,CAAC,eAAe,KAAK,GACxB,MAAM,IAAI,MAAM,GAAG,oBAAoB,oBAAoB,IAAI,kBAAkB;EAElF,QAAQ,OAAO;CAChB;CACA,MAAM,eAAyC,CAAC;CAChD,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,OAAO,YAAY,GAAG;EAC/D,IAAI,CAAC,aAAa,KAAK,GACtB,MAAM,IAAI,MAAM,GAAG,oBAAoB,0BAA0B,IAAI,kBAAkB;EAExF,aAAa,OAAO;CACrB;CACA,OAAO;EACN,GAAG,UAAU,MAAM;EACnB,GAAG,aAAa,MAAM;EACtB,aAAa,OAAO;EACpB;EACA;CACD;AACD"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"bun-BCz6K_Xv.js","names":[],"sources":["../src/node/runtimes/bun.ts"],"sourcesContent":["import type { FetchHandler, StartedListener } from \"../../core/types.js\";\nimport { listenerUrl } from \"./listen-options.js\";\nimport type { ListenOptions } from \"./listen-options.js\";\n\n/** The part of Bun's server that the listener uses. */\ntype BunServer = {\n\tport: number;\n\trequestIP: (request: Request) => { address: string } | null;\n\tstop: (closeActiveConnections?: boolean) => Promise<void>;\n};\n\n/** The part of the `Bun` global that the listener uses. */\ntype BunGlobal = {\n\tserve: (options: {\n\t\tport: number;\n\t\thostname?: string;\n\t\tidleTimeout: number;\n\t\tfetch: (request: Request, server: BunServer) => Response | Promise<Response>;\n\t}) => BunServer;\n};\n\n/** Bun's largest `idleTimeout`, in seconds. */\nconst BUN_MAX_IDLE_TIMEOUT_S = 255;\n\n/** Listens with `Bun.serve`. */\nexport async function listen(\n\tfetch: FetchHandler,\n\toptions: ListenOptions,\n): Promise<StartedListener> {\n\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- `Bun` is a runtime global with no types in this package.\n\tconst bun = Reflect.get(globalThis, \"Bun\") as BunGlobal;\n\tconst server = bun.serve({\n\t\tport: options.port,\n\t\t...(options.hostname == null ? {} : { hostname: options.hostname }),\n\t\t// Why: Bun's 10 s default also closes a quiet event stream.\n\t\tidleTimeout: Math.min(BUN_MAX_IDLE_TIMEOUT_S, Math.ceil(options.idleTimeoutMs / 1_000)),\n\t\tfetch: async (request, bunServer) =>\n\t\t\tfetch(request, { remoteAddress: bunServer.requestIP(request)?.address }),\n\t});\n\treturn {\n\t\turl: listenerUrl(options.hostname, server.port),\n\t\tstop: async ({ deadlineMs }) => {\n\t\t\tlet deadline: ReturnType<typeof setTimeout> | undefined;\n\t\t\tconst deadlinePassed = new Promise<void>((resolve) => {\n\t\t\t\tdeadline = setTimeout(() => {\n\t\t\t\t\tvoid server.stop(true);\n\t\t\t\t\tresolve();\n\t\t\t\t}, deadlineMs);\n\t\t\t});\n\t\t\t// Why a race: on Bun 1.3, a response body that stays open keeps both stop promises\n\t\t\t// pending, and `stop(true)` leaves its connection open. The exit after shutdown closes it.\n\t\t\tawait Promise.race([server.stop(), deadlinePassed]);\n\t\t\tclearTimeout(deadline);\n\t\t},\n\t};\n}\n"],"mappings":";;;;AAsBA,MAAM,yBAAyB;;AAG/B,eAAsB,OACrB,OACA,SAC2B;CAG3B,MAAM,SADM,QAAQ,IAAI,YAAY,KACnB,CAAC,CAAC,MAAM;EACxB,MAAM,QAAQ;EACd,GAAI,QAAQ,YAAY,OAAO,CAAC,IAAI,EAAE,UAAU,QAAQ,SAAS;EAEjE,aAAa,KAAK,IAAI,wBAAwB,KAAK,KAAK,QAAQ,gBAAgB,GAAK,CAAC;EACtF,OAAO,OAAO,SAAS,cACtB,MAAM,SAAS,EAAE,eAAe,UAAU,UAAU,OAAO,CAAC,EAAE,QAAQ,CAAC;CACzE,CAAC;CACD,OAAO;EACN,KAAK,YAAY,QAAQ,UAAU,OAAO,IAAI;EAC9C,MAAM,OAAO,EAAE,iBAAiB;GAC/B,IAAI;GACJ,MAAM,iBAAiB,IAAI,SAAe,YAAY;IACrD,WAAW,iBAAiB;KAC3B,AAAK,OAAO,KAAK,IAAI;KACrB,QAAQ;IACT,GAAG,UAAU;GACd,CAAC;GAGD,MAAM,QAAQ,KAAK,CAAC,OAAO,KAAK,GAAG,cAAc,CAAC;GAClD,aAAa,QAAQ;EACtB;CACD;AACD"}
package/dist/cli.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"cli.js","names":[],"sources":["../src/cli/cli.ts"],"sourcesContent":["#!/usr/bin/env node\n// The `app-server` command: `app-server start` or `app-server serve [build/server/app-server.js]`,\n// each with an optional `--port`.\nimport process from \"node:process\";\nimport { parseArgs } from \"node:util\";\nimport { parsePort } from \"../node/tcp.js\";\n\nconst USAGE =\n\t\"Usage: app-server start [--port <port>] | app-server serve [--port <port>] [build/server/app-server.js]\";\n\n/** Writes `message` and the usage to stderr, and sets a failed exit code. */\nfunction fail(message: string): void {\n\tprocess.stderr.write(`${message}\\n${USAGE}\\n`);\n\tprocess.exitCode = 1;\n}\n\n/** The parsed arguments. A bad argument throws. */\nfunction parse() {\n\tconst { positionals, values } = parseArgs({\n\t\tallowPositionals: true,\n\t\tstrict: true,\n\t\toptions: { port: { type: \"string\", short: \"p\" }, help: { type: \"boolean\", short: \"h\" } },\n\t});\n\t// Why set `PORT`: the copy of this package in the build reads it, so the flag needs no change to\n\t// the entry protocol.\n\tif (values.port != null) {\n\t\tprocess.env.PORT = String(parsePort(values.port));\n\t}\n\treturn { command: positionals[0], buildPath: positionals[1], help: values.help === true };\n}\n\nlet args: ReturnType<typeof parse> | undefined;\ntry {\n\targs = parse();\n} catch (error) {\n\t// Why no stack: a bad argument is a usage error, not a crash.\n\tfail(String(error instanceof Error ? error.message : error).replace(/^PORT\\b/u, \"--port\"));\n}\n\n// Why dynamic imports: React reads `NODE_ENV` when it loads, and a static import runs first.\nif (args?.help === true) {\n\tprocess.stdout.write(`${USAGE}\\n`);\n} else if (args?.command === \"start\") {\n\tprocess.env.NODE_ENV ??= \"development\";\n\tconst { start } = await import(\"./start.js\");\n\tawait start();\n} else if (args?.command === \"serve\") {\n\tprocess.env.NODE_ENV ??= \"production\";\n\tif (typeof process.setSourceMapsEnabled === \"function\") {\n\t\tprocess.setSourceMapsEnabled(true);\n\t}\n\tconst { serve } = await import(\"./serve.js\");\n\tawait serve({ buildPath: args.buildPath });\n} else if (args != null) {\n\tfail(args.command == null ? \"Give a command.\" : `Unknown command: ${args.command}.`);\n}\n"],"mappings":";;;;;;AAOA,MAAM,QACL;;AAGD,SAAS,KAAK,SAAuB;CACpC,QAAQ,OAAO,MAAM,GAAG,QAAQ,IAAI,MAAM,GAAG;CAC7C,QAAQ,WAAW;AACpB;;AAGA,SAAS,QAAQ;CAChB,MAAM,EAAE,aAAa,WAAW,UAAU;EACzC,kBAAkB;EAClB,QAAQ;EACR,SAAS;GAAE,MAAM;IAAE,MAAM;IAAU,OAAO;GAAI;GAAG,MAAM;IAAE,MAAM;IAAW,OAAO;GAAI;EAAE;CACxF,CAAC;CAGD,IAAI,OAAO,QAAQ,MAClB,QAAQ,IAAI,OAAO,OAAO,UAAU,OAAO,IAAI,CAAC;CAEjD,OAAO;EAAE,SAAS,YAAY;EAAI,WAAW,YAAY;EAAI,MAAM,OAAO,SAAS;CAAK;AACzF;AAEA,IAAI;AACJ,IAAI;CACH,OAAO,MAAM;AACd,SAAS,OAAO;CAEf,KAAK,OAAO,iBAAiB,QAAQ,MAAM,UAAU,KAAK,CAAC,CAAC,QAAQ,YAAY,QAAQ,CAAC;AAC1F;AAGA,IAAI,MAAM,SAAS,MAClB,QAAQ,OAAO,MAAM,GAAG,MAAM,GAAG;KAC3B,IAAI,MAAM,YAAY,SAAS;CACrC,QAAQ,IAAI,aAAa;CACzB,MAAM,EAAE,UAAU,MAAM,OAAO;CAC/B,MAAM,MAAM;AACb,OAAO,IAAI,MAAM,YAAY,SAAS;CACrC,QAAQ,IAAI,aAAa;CACzB,IAAI,OAAO,QAAQ,yBAAyB,YAC3C,QAAQ,qBAAqB,IAAI;CAElC,MAAM,EAAE,UAAU,MAAM,OAAO;CAC/B,MAAM,MAAM,EAAE,WAAW,KAAK,UAAU,CAAC;AAC1C,OAAO,IAAI,QAAQ,MAClB,KAAK,KAAK,WAAW,OAAO,oBAAoB,oBAAoB,KAAK,QAAQ,EAAE"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"client.js","names":[],"sources":["../src/client/csp-nonce.ts"],"sourcesContent":["import { requestContext } from \"../core/request-context.js\";\nimport { documentNonce } from \"./document-nonce.js\";\n\n/**\n * The CSP nonce of the document, for the framework's render. It gives the\n * same value on the server and in the browser, so the hydration matches.\n *\n * - On the server, the nonce of the request that runs, from `requestContext()`.\n * - In the browser, the nonce of the document's first element with a nonce.\n * Why: React Router's `<HydratedRouter>` takes no nonce, so the app reads it\n * from the document.\n *\n * It gives `undefined` when the page has no nonce: with no\n * `contentSecurityPolicy` plugin, during a prerender, and on a prerendered page.\n * A bundler that resolves the `browser` condition, such as Vite for the\n * client, gets a build with no server code.\n *\n * @example\n * <Scripts nonce={cspNonce()} />\n */\nexport function cspNonce(): string | undefined {\n\treturn typeof document === \"undefined\" ? requestContext()?.cspNonce : documentNonce();\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,WAA+B;CAC9C,OAAO,OAAO,aAAa,cAAc,eAAe,CAAC,EAAE,WAAW,cAAc;AACrF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"compress-Cp5NfXCC.js","names":[],"sources":["../src/node/compress.ts"],"sourcesContent":["import type { Transform } from \"node:stream\";\nimport { setImmediate } from \"node:timers\";\nimport type { ReadResult } from \"../core/compression.js\";\nimport {\n\tbrotliCompressSync,\n\tconstants,\n\tcrc32,\n\tcreateBrotliCompress,\n\tcreateDeflateRaw,\n\tcreateGzip,\n} from \"node:zlib\";\n\n/**\n * A stream from {@link gzipStream} or {@link brotliStream}. Why a class: the\n * node response writer reads `busy` to hold the head for zlib's first chunk,\n * and a field costs less than a `WeakMap` entry for each response.\n */\nclass ZlibBody extends ReadableStream<Uint8Array> {\n\t/**\n\t * Whether the next chunk waits only on zlib, because the source gave the\n\t * bytes already. It stays set while a brotli stream holds the start of a\n\t * body, which ends when the source waits.\n\t */\n\tpublic busy = false;\n}\n\n/**\n * Whether the next chunk of `stream` waits only on zlib, because its source\n * gave the bytes already. It gives `undefined` for a stream that is not from\n * {@link gzipStream} or {@link brotliStream}.\n *\n * @example\n * waitsForZlib(gzipStream(source)); // => false, until the first read gives zlib a chunk\n */\nexport function waitsForZlib(stream: ReadableStream<Uint8Array>): boolean | undefined {\n\treturn stream instanceof ZlibBody ? stream.busy : undefined;\n}\n\n/**\n * The gzip header (RFC 1952): the magic number, deflate, no flags, no time,\n * and the Unix system code.\n */\nconst HEADER = Buffer.from([31, 139, 8, 0, 0, 0, 0, 0, 0, 3]);\n\n/** The gzip member of an empty body: the header, a final empty block, a CRC-32 of 0, and a size of 0. */\nconst EMPTY_MEMBER = Buffer.concat([HEADER, Buffer.from([3, 0, 0, 0, 0, 0, 0, 0, 0, 0])]);\n\n/**\n * The largest body that a pooled gzip stream compresses. Why a limit: above\n * about 64 KiB, the CRC-32 of a gzip body on the main thread costs more than\n * a new zlib stream does.\n */\nconst GZIP_POOLED_MAX_BYTES = 64 * 1024;\n\n/** The most zlib streams that wait for a body in each pool. Why a limit: an idle deflate stream keeps about 276 KiB of zlib state. */\nconst MAX_IDLE = 16;\n\nfunction ignore(): void {}\n\n/**\n * A zlib stream that compresses one body at a time, the target of its output\n * and of its failure, and the size of the longest body that it compressed.\n */\ntype Pooled = {\n\tstream: Transform;\n\toutput: (chunk: Buffer) => void;\n\tfail: (error: Error) => void;\n\tsize: number;\n};\n\n/** The idle zlib streams of one encoding, the last one given back last. */\ntype Pool = {\n\t/** A new zlib stream that finishes its output with each write. */\n\tcreate: () => Transform;\n\tidle: Pooled[];\n\t/**\n\t * Whether a reset keeps state of the earlier bodies, so a stream records\n\t * the size of its longest body (see {@link take}).\n\t */\n\tsized: boolean;\n\t/** Whether a reset lets the stream compress the next body. Else each body gets a new stream. */\n\treuses: boolean;\n};\n\nfunction newPooled(pool: Pool): Pooled {\n\tconst pooled: Pooled = { stream: pool.create(), output: ignore, fail: ignore, size: 0 };\n\tpooled.stream.on(\"data\", (chunk: Buffer) => {\n\t\tpooled.output(chunk);\n\t});\n\t// Why both: zlib destroys the stream at a failure, and then it never calls the write callback.\n\tpooled.stream.on(\"error\", (error) => {\n\t\tpooled.fail(error);\n\t});\n\tpooled.stream.on(\"close\", () => {\n\t\t// Why the check: a stream that the pool destroys has no body, and an error costs its stack.\n\t\tif (pooled.fail !== ignore) {\n\t\t\tpooled.fail(new Error(\"The zlib stream closed.\"));\n\t\t}\n\t});\n\treturn pooled;\n}\n\n/**\n * The deflate pool. Why `Z_FINISH`: when the output fills the buffer of the\n * stream exactly, the stream calls zlib again, and a sync flush then adds an\n * empty block. So the output would depend on earlier bodies.\n */\nconst DEFLATE_POOL: Pool = {\n\tcreate: () => createDeflateRaw({ flush: constants.Z_FINISH }),\n\tidle: [],\n\tsized: true,\n\treuses: true,\n};\n\n/**\n * The brotli quality of a response. Why 4: for HTML, its output is smaller\n * than gzip level 6, for the same CPU time. The `compression` middleware of\n * Express also uses 4.\n */\nconst BROTLI_QUALITY = 4;\n\n/**\n * The base-2 logarithm of the brotli window of a body up to\n * {@link BROTLI_HOLD_BYTES}, 256 KiB. Why not the default of 22 (4 MiB):\n * Node.js tells V8 the full size of each encoder's ring buffer as external\n * memory, and at 32 open encoders V8 then runs a full garbage collection for\n * every few responses.\n */\nconst BROTLI_WINDOW_BITS = 18;\n\n/**\n * The most bytes of a body that a brotli stream holds to pick the window: 256\n * KiB for a body that ends within them, else the default of 4 MiB. Why: a\n * stream has no length to pick from, and a repeat more than 256 KiB back costs\n * a page of 2.5 MB 30% more bytes.\n */\nconst BROTLI_HOLD_BYTES = 2 ** BROTLI_WINDOW_BITS;\n\nfunction brotliParams(windowBits: number): Record<number, number> {\n\treturn {\n\t\t[constants.BROTLI_PARAM_MODE]: constants.BROTLI_MODE_TEXT,\n\t\t[constants.BROTLI_PARAM_QUALITY]: BROTLI_QUALITY,\n\t\t[constants.BROTLI_PARAM_LGWIN]: windowBits,\n\t};\n}\n\nconst BROTLI_PARAMS = brotliParams(BROTLI_WINDOW_BITS);\nconst BROTLI_LARGE_PARAMS = brotliParams(constants.BROTLI_DEFAULT_WINDOW);\n\n/**\n * The brotli pool. Why not sized: a reset makes a new brotli encoder with the\n * same parameters, so the output of a body never depends on an earlier one.\n */\nconst BROTLI_POOL: Pool = {\n\tcreate: () =>\n\t\tcreateBrotliCompress({ flush: constants.BROTLI_OPERATION_FINISH, params: BROTLI_PARAMS }),\n\tidle: [],\n\tsized: false,\n\t// Why not on Bun or Deno: after a reset, a Bun encoder forgets its quality, and a Deno encoder gives no bytes.\n\treuses: !(\"Bun\" in globalThis) && !(\"Deno\" in globalThis),\n};\n\n/**\n * An idle stream of `pool` for a body of `size` bytes, else a new one. It\n * takes a stream whose bodies were each no longer than this one: the longest\n * such, and of those the last one given back, whose memory is still in the\n * cache.\n *\n * Why for deflate: a reset keeps the window of zlib, and zlib reads the bytes\n * after the end of a body to hash and match its last bytes. After a longer\n * body, these are bytes of that body, so they could change the output of this\n * one. A stream whose bodies were no longer has only the zeros that zlib\n * writes after each body there, as a new stream does.\n */\nfunction take(pool: Pool, size: number): Pooled {\n\tconst { idle } = pool;\n\tlet best = -1;\n\tlet bestSize = -1;\n\tfor (let index = idle.length - 1; index >= 0; index -= 1) {\n\t\tconst each = idle[index]?.size ?? Infinity;\n\t\tif (each <= size && each > bestSize) {\n\t\t\tbest = index;\n\t\t\tbestSize = each;\n\t\t}\n\t}\n\tif (best === -1) {\n\t\treturn newPooled(pool);\n\t}\n\tconst taken = idle[best];\n\tconst last = idle.pop();\n\tif (taken == null || last == null) {\n\t\treturn newPooled(pool);\n\t}\n\t// Why move the last one into the gap: the order of the others does not matter, and it costs no copy.\n\tif (last !== taken) {\n\t\tidle[best] = last;\n\t}\n\treturn taken;\n}\n\n/**\n * Gives back a stream of `pool` after its body. Why reset: the next body must\n * not use the bytes of this one as a dictionary. When the pool is full, it\n * keeps the streams of the shortest bodies, which more bodies can take.\n */\nfunction release(pool: Pool, pooled: Pooled): void {\n\tpooled.output = ignore;\n\tpooled.fail = ignore;\n\tconst { stream } = pooled;\n\t// Why check the queues: a stream with output or input still queued would give it to the next body.\n\tif (\n\t\t!pool.reuses ||\n\t\tstream.destroyed ||\n\t\tstream.readableLength !== 0 ||\n\t\tstream.writableLength !== 0\n\t) {\n\t\tstream.destroy();\n\t\treturn;\n\t}\n\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- each pool creates a zlib stream, which has `reset`.\n\t(stream as Transform & { reset: () => void }).reset();\n\t// Why the check: a reset that fails destroys the stream.\n\tif (stream.destroyed) {\n\t\treturn;\n\t}\n\tconst { idle } = pool;\n\tif (idle.length < MAX_IDLE) {\n\t\tidle.push(pooled);\n\t\treturn;\n\t}\n\tlet longest = 0;\n\tfor (let index = 1; index < idle.length; index += 1) {\n\t\tif ((idle[index]?.size ?? 0) > (idle[longest]?.size ?? 0)) {\n\t\t\tlongest = index;\n\t\t}\n\t}\n\tconst evicted = idle[longest];\n\tif (evicted != null && evicted.size > pooled.size) {\n\t\tidle[longest] = pooled;\n\t\tevicted.stream.destroy();\n\t} else {\n\t\tstream.destroy();\n\t}\n}\n\n/** Writes `chunk` to `stream`. zlib gives all the output of the chunk before this resolves. */\nasync function write(stream: Transform, chunk: Uint8Array): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tstream.write(chunk, (error) => {\n\t\t\tif (error == null) {\n\t\t\t\tresolve();\n\t\t\t} else {\n\t\t\t\treject(error);\n\t\t\t}\n\t\t});\n\t});\n}\n\n/**\n * The output of a stream of `pool` for a body of one chunk, in one zlib call.\n * `use` gets the stream while zlib compresses, so a cancel can destroy it,\n * and gets `undefined` before the stream goes back to the pool. Why only a\n * body of one chunk: a deflate reset keeps the old window, and a second write\n * reads its bytes as history. The output of one write is the same as from a\n * new stream, so it does not depend on an earlier body.\n */\nasync function compressOnce(\n\tpool: Pool,\n\tvalue: Uint8Array,\n\tuse: (pooled: Pooled | undefined) => void,\n): Promise<Buffer[]> {\n\tconst pooled = take(pool, value.byteLength);\n\tuse(pooled);\n\tconst parts: Buffer[] = [];\n\tpooled.output = (chunk) => {\n\t\tparts.push(chunk);\n\t};\n\ttry {\n\t\tawait new Promise<void>((resolve, reject) => {\n\t\t\tpooled.fail = reject;\n\t\t\tpooled.stream.write(value, (error) => {\n\t\t\t\tif (error != null) {\n\t\t\t\t\treject(error);\n\t\t\t\t} else if (pooled.stream.destroyed) {\n\t\t\t\t\treject(new Error(\"The zlib stream closed.\"));\n\t\t\t\t} else {\n\t\t\t\t\tresolve();\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t} catch (error) {\n\t\tpooled.output = ignore;\n\t\tpooled.fail = ignore;\n\t\tpooled.stream.destroy();\n\t\tthrow error;\n\t}\n\tif (pool.sized) {\n\t\tpooled.size = Math.max(pooled.size, value.byteLength);\n\t}\n\t// Why first: a cancel after this must not destroy a stream that the pool gives to another body.\n\tuse(undefined);\n\trelease(pool, pooled);\n\treturn parts;\n}\n\n/**\n * The gzip member of a body of one chunk: the raw deflate output of a pooled\n * stream, with the header and the trailer written here.\n */\nasync function gzipOnce(\n\tvalue: Uint8Array,\n\tuse: (pooled: Pooled | undefined) => void,\n): Promise<Buffer> {\n\tconst parts = await compressOnce(DEFLATE_POOL, value, use);\n\tconst trailer = Buffer.allocUnsafe(8);\n\ttrailer.writeUInt32LE(crc32(value), 0);\n\ttrailer.writeUInt32LE(value.byteLength, 4);\n\treturn Buffer.concat([HEADER, ...parts, trailer]);\n}\n\n/** The brotli stream of a body of one chunk, from a pooled encoder. */\nasync function brotliOnce(\n\tvalue: Uint8Array,\n\tuse: (pooled: Pooled | undefined) => void,\n): Promise<Buffer> {\n\treturn Buffer.concat(await compressOnce(BROTLI_POOL, value, use));\n}\n\n/** How {@link zlibStream} compresses a body. */\ntype Codec = {\n\t/** A new zlib stream that flushes after each write. */\n\tcreate: () => Transform;\n\t/** The output for a body with no bytes. */\n\tempty: Buffer;\n\t/**\n\t * The output for a body of one chunk, up to `onceMaxBytes`, with no new\n\t * zlib stream. `use` gets the zlib stream while it compresses.\n\t */\n\tonce: (value: Uint8Array, use: (pooled: Pooled | undefined) => void) => Promise<Buffer>;\n\tonceMaxBytes: number;\n\t/**\n\t * A new zlib stream for a body longer than `onceMaxBytes`, which\n\t * {@link zlibStream} holds until it knows that. Without it, the stream\n\t * holds nothing, and each body gets `create`.\n\t */\n\tcreateLarge?: () => Transform;\n};\n\n/**\n * The start of a body that {@link zlibStream} held, whether the source ended\n * with it, and whether the body is longer than the hold.\n */\ntype Start = { value: Uint8Array; done: boolean; large: boolean };\n\n/**\n * The most chunks that {@link zlibStream} holds. Why: a source that gives each\n * chunk at once keeps the hold in one turn of the event loop, and 262,144\n * chunks of 1 byte blocked it for 215 ms on an Apple M3 Max.\n */\nconst HOLD_MAX_CHUNKS = 1024;\n\nfunction join(chunks: Uint8Array[], size: number): Uint8Array {\n\tconst [first] = chunks;\n\treturn chunks.length === 1 && first != null ? first : Buffer.concat(chunks, size);\n}\n\n/**\n * Compresses a byte stream with `codec`. Each written chunk is readable at\n * once. It reads the next source chunk only when the consumer pulls, so a\n * slow client holds back the source. When the source ends by the time zlib\n * finishes a chunk, that chunk and the end of the stream go out as one. Why:\n * the host writes each chunk to the socket on its own, and a write costs more\n * than its few bytes.\n *\n * With `codec.createLarge`, it first holds the body up to\n * `codec.onceMaxBytes`, the end, or a wait of the source, and then writes\n * what it holds.\n */\nfunction zlibStream(source: ReadableStream<Uint8Array>, codec: Codec): ReadableStream<Uint8Array> {\n\tconst reader = source.getReader();\n\tlet ended = false;\n\tconst markEnded = () => {\n\t\tended = true;\n\t};\n\t// Why a flag: after each zlib write, it tells with no read whether the source ended meanwhile.\n\tvoid reader.closed.then(markEnded, () => {});\n\t/** The zlib stream of a body of more than one chunk. */\n\tlet zlib: Transform | undefined;\n\t/** The pooled zlib stream while it compresses the one chunk of a body. */\n\tlet pooled: Pooled | undefined;\n\tlet started = false;\n\tlet canceled = false;\n\t/** The source read that is still open after a hold. */\n\tlet pending: Promise<ReadResult> | undefined;\n\t/** The next source chunk with bytes, or the end. */\n\tconst read = async () => {\n\t\tlet chunk = await (pending ?? reader.read());\n\t\tpending = undefined;\n\t\t// Why skip empty chunks: zlib writes nothing for one, and a pull that enqueues nothing is not\n\t\t// called again.\n\t\twhile (!chunk.done && chunk.value.byteLength === 0) {\n\t\t\tchunk = await reader.read();\n\t\t}\n\t\treturn chunk;\n\t};\n\t/**\n\t * `first` and the chunks after it, up to `max` bytes, until the source ends,\n\t * gives an empty chunk, or leaves a read open for a turn of the event loop.\n\t * Why stop on a wait: the source waits for data, such as a React\n\t * `<Suspense>` boundary, and what it gave must reach the client now.\n\t */\n\tconst hold = async (first: Uint8Array, max: number): Promise<Start> => {\n\t\tconst parts = [first];\n\t\tlet size = first.byteLength;\n\t\t/** Resolves at the end of this turn of the event loop. Why one for each turn: an immediate costs more than a read. */\n\t\tlet turn: Promise<undefined> | undefined;\n\t\tconst endOfTurn = async () =>\n\t\t\tnew Promise<undefined>((resolve) => {\n\t\t\t\tsetImmediate(() => {\n\t\t\t\t\tturn = undefined;\n\t\t\t\t\tresolve(undefined);\n\t\t\t\t});\n\t\t\t});\n\t\twhile (size <= max && parts.length < HOLD_MAX_CHUNKS) {\n\t\t\tpending ??= reader.read();\n\t\t\tturn ??= endOfTurn();\n\t\t\t// oxlint-disable-next-line no-await-in-loop -- each read waits for the source.\n\t\t\tconst result = await Promise.race([pending, turn]);\n\t\t\tif (result == null) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tpending = undefined;\n\t\t\tif (result.done) {\n\t\t\t\treturn { value: join(parts, size), done: true, large: false };\n\t\t\t}\n\t\t\t// Why stop on an empty chunk: a read that resolves at once never lets the turn end.\n\t\t\tif (result.value.byteLength === 0) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t// Why give it to the next read: a join would copy the large chunk.\n\t\t\tif (size + result.value.byteLength > max) {\n\t\t\t\tpending = Promise.resolve(result);\n\t\t\t\treturn { value: join(parts, size), done: false, large: true };\n\t\t\t}\n\t\t\tparts.push(result.value);\n\t\t\tsize += result.value.byteLength;\n\t\t}\n\t\treturn { value: join(parts, size), done: false, large: size > max };\n\t};\n\t/** The zlib output that waits for the next enqueue. */\n\tlet held: Buffer[] = [];\n\tlet heldBytes = 0;\n\tconst enqueueHeld = (controller: ReadableStreamDefaultController<Uint8Array>) => {\n\t\tconst [first] = held;\n\t\tif (first == null) {\n\t\t\treturn;\n\t\t}\n\t\t// Why no copy for one chunk: zlib gives each chunk its own bytes, and it never writes them again.\n\t\tcontroller.enqueue(held.length === 1 ? first : Buffer.concat(held));\n\t\theld = [];\n\t\theldBytes = 0;\n\t};\n\tconst startZlib = (\n\t\tbody: ZlibBody,\n\t\tcontroller: ReadableStreamDefaultController<Uint8Array>,\n\t\tcreate: () => Transform,\n\t): Transform => {\n\t\tconst created = create();\n\t\tcreated.on(\"data\", (chunk: Buffer) => {\n\t\t\theld.push(chunk);\n\t\t\theldBytes += chunk.byteLength;\n\t\t\t// Why: the output of a large source chunk goes out while zlib still compresses the rest.\n\t\t\tif (heldBytes >= constants.Z_DEFAULT_CHUNK) {\n\t\t\t\tenqueueHeld(controller);\n\t\t\t}\n\t\t});\n\t\tcreated.on(\"end\", () => {\n\t\t\tbody.busy = false;\n\t\t\tenqueueHeld(controller);\n\t\t\tcontroller.close();\n\t\t});\n\t\tcreated.on(\"error\", (error) => {\n\t\t\tbody.busy = false;\n\t\t\tcontroller.error(error);\n\t\t});\n\t\treturn created;\n\t};\n\tconst stream: ZlibBody = new ZlibBody(\n\t\t{\n\t\t\tasync pull(controller) {\n\t\t\t\ttry {\n\t\t\t\t\tconst chunk = await read();\n\t\t\t\t\tlet create = codec.create;\n\t\t\t\t\tlet start: Start | undefined;\n\t\t\t\t\tif (!started) {\n\t\t\t\t\t\tstarted = true;\n\t\t\t\t\t\tif (chunk.done) {\n\t\t\t\t\t\t\tcontroller.enqueue(codec.empty);\n\t\t\t\t\t\t\tcontroller.close();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tstream.busy = true;\n\t\t\t\t\t\t// Why wait: a source that closes in the pull that gave this chunk ends one microtask later.\n\t\t\t\t\t\tawait Promise.resolve();\n\t\t\t\t\t\tconst { createLarge, onceMaxBytes } = codec;\n\t\t\t\t\t\tstart =\n\t\t\t\t\t\t\tended || createLarge == null\n\t\t\t\t\t\t\t\t? { value: chunk.value, done: ended, large: chunk.value.byteLength > onceMaxBytes }\n\t\t\t\t\t\t\t\t: await hold(chunk.value, onceMaxBytes);\n\t\t\t\t\t\t// Why: a cancel during the hold ran before this stream had an encoder to destroy.\n\t\t\t\t\t\tif (canceled) {\n\t\t\t\t\t\t\tstream.busy = false;\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (start.done && !start.large) {\n\t\t\t\t\t\t\tconst output = await codec.once(start.value, (each) => {\n\t\t\t\t\t\t\t\tpooled = each;\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tstream.busy = false;\n\t\t\t\t\t\t\tcontroller.enqueue(output);\n\t\t\t\t\t\t\tcontroller.close();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (createLarge != null && start.large) {\n\t\t\t\t\t\t\tcreate = createLarge;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tzlib ??= startZlib(stream, controller, create);\n\t\t\t\t\tstream.busy = true;\n\t\t\t\t\tif (chunk.done) {\n\t\t\t\t\t\tzlib.end();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tawait write(zlib, start?.value ?? chunk.value);\n\t\t\t\t\tended ||= start?.done === true;\n\t\t\t\t\t// Why check `pending`: an open read can hold the last chunk when the source closes.\n\t\t\t\t\tif (ended && pending == null) {\n\t\t\t\t\t\tzlib.end();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tstream.busy = false;\n\t\t\t\t\t// Why the output is here: zlib emits the output of a chunk before it calls the write\n\t\t\t\t\t// callback, so this pull enqueues a chunk and the consumer's read does not wait.\n\t\t\t\t\tenqueueHeld(controller);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tstream.busy = false;\n\t\t\t\t\tzlib?.destroy();\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t},\n\t\t\t// Why cancel the source: a client disconnect must reach the handler, so it stops its work.\n\t\t\tasync cancel(reason) {\n\t\t\t\tcanceled = true;\n\t\t\t\tzlib?.destroy();\n\t\t\t\t// Why destroy: a stream that a write still uses must never go back to the pool.\n\t\t\t\tpooled?.stream.destroy();\n\t\t\t\treturn reader.cancel(reason);\n\t\t\t},\n\t\t},\n\t\t// Why 0: the stream reads its source only when the consumer reads.\n\t\t{ highWaterMark: 0 },\n\t);\n\treturn stream;\n}\n\nconst GZIP: Codec = {\n\tcreate: () => createGzip({ flush: constants.Z_SYNC_FLUSH }),\n\tempty: EMPTY_MEMBER,\n\tonce: gzipOnce,\n\tonceMaxBytes: GZIP_POOLED_MAX_BYTES,\n};\n\n/**\n * Gzips a byte stream. `Z_SYNC_FLUSH` makes each written chunk readable at\n * once. It reads the next source chunk only when the consumer pulls, so a slow\n * client holds back the source. When the source ends by the time zlib\n * finishes a chunk, that chunk and the gzip trailer go out as one.\n *\n * A body that ends with its first chunk, up to 64 KiB, takes a pooled raw\n * deflate stream. Why: a new zlib stream costs more main-thread time than\n * zlib takes for a small page.\n *\n * @example\n * new Response(gzipStream(response.body), response);\n */\nexport function gzipStream(source: ReadableStream<Uint8Array>): ReadableStream<Uint8Array> {\n\treturn zlibStream(source, GZIP);\n}\n\nconst BROTLI: Codec = {\n\tcreate: () =>\n\t\tcreateBrotliCompress({ flush: constants.BROTLI_OPERATION_FLUSH, params: BROTLI_PARAMS }),\n\tempty: brotliCompressSync(new Uint8Array(), { params: BROTLI_PARAMS }),\n\tonce: brotliOnce,\n\tonceMaxBytes: BROTLI_HOLD_BYTES,\n\tcreateLarge: () =>\n\t\tcreateBrotliCompress({\n\t\t\tflush: constants.BROTLI_OPERATION_FLUSH,\n\t\t\tparams: BROTLI_LARGE_PARAMS,\n\t\t}),\n};\n\n/**\n * Compresses a byte stream with brotli, quality 4. `BROTLI_OPERATION_FLUSH`\n * makes each written chunk readable at once. It reads and ends as\n * {@link gzipStream} does.\n *\n * It holds the start of a body to pick the window, as\n * {@link BROTLI_HOLD_BYTES} says. When the source waits for its next chunk\n * first, the stream sends what it holds with the 256 KiB window.\n *\n * @example\n * new Response(brotliStream(response.body), response);\n */\nexport function brotliStream(source: ReadableStream<Uint8Array>): ReadableStream<Uint8Array> {\n\treturn zlibStream(source, BROTLI);\n}\n"],"mappings":";;;;;;;;;AAiBA,IAAM,WAAN,cAAuB,eAA2B;;;;;;CAMjD,AAAO,OAAO;AACf;;;;;;;;;AAUA,SAAgB,aAAa,QAAyD;CACrF,OAAO,kBAAkB,WAAW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AAgE;CAC5F,OAAO,WAAW,QAAQ,MAAM;AACjC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"compression-CT2mWlKM.js","names":[],"sources":["../src/core/compression.ts"],"sourcesContent":["import { parseAccept } from \"hono/utils/accept\";\n\n/**\n * The content types that the server and the build compress: each text type,\n * each type with a `+json` or `+xml` suffix, and the other types that\n * `mime-db` marks compressible and that a site sends, such as `image/x-icon`\n * and `font/ttf`. Why not `font/woff` and `font/woff2`: they are compressed\n * already.\n */\nconst COMPRESSIBLE =\n\t/^(?:text\\/|[\\w-]+\\/[\\w.-]+\\+(?:json|xml)|application\\/(?:json|xml|javascript|x-ndjson|wasm|yaml|x-yaml|x-sh\\b|vnd\\.ms-fontobject)|image\\/(?:x-icon|vnd\\.microsoft\\.icon|bmp)|font\\/(?:ttf|otf))/u;\n\n/**\n * The smallest body that the server or the build compresses. Why: gzip\n * makes a smaller body larger, and each gzip stream allocates about 300\n * kibibytes (KiB) of zlib state. `hono/compress` uses the same value.\n */\nexport const MIN_COMPRESS_BYTES = 1024;\n\n/** A content coding of a compressed copy that the build writes. */\nexport type Encoding = \"br\" | \"gzip\";\n\n/**\n * The encodings of the copies, in the order that the server prefers them.\n * Why brotli first: its copy is smaller, such as 45 KB in place of 56 KB\n * for a docs page of 417 KB.\n */\nexport const COPY_ENCODINGS: readonly Encoding[] = [\"br\", \"gzip\"];\n\nconst COPY_EXTENSIONS: Readonly<Record<Encoding, string>> = { br: \"br\", gzip: \"gz\" };\n\n/**\n * The name of the `encoding` copy of the file `name`, which the build writes\n * next to it.\n *\n * Why a dotfile: the static stages never serve a dotfile, so the copy has no\n * URL of its own. A request gets the copy only through the URL of its file,\n * which `skip` and an auth check can block. The build also never replaces or\n * removes a `.gz` or `.br` file of the app.\n *\n * @example\n * copyName(\"app-abc.js\", \"br\"); // => \".app-abc.js.br\"\n */\nexport function copyName(name: string, encoding: Encoding): string {\n\treturn `.${name}.${COPY_EXTENSIONS[encoding]}`;\n}\n\n/**\n * Whether the server compresses a body of the content type `type`.\n *\n * @example\n * isCompressible(\"text/html; charset=utf-8\"); // => true\n * isCompressible(\"image/png\"); // => false\n */\nexport function isCompressible(type: string): boolean {\n\treturn COMPRESSIBLE.test(type);\n}\n\n/**\n * The encoding in `offered` that an `Accept-Encoding` header prefers, or\n * `undefined` for the body as it is. Each encoding gets the `q` of its own\n * entry, else of `*`. The highest `q` above 0 wins, and a tie goes to the\n * first encoding in `offered`. An `identity` entry with a higher `q` keeps\n * the body as it is.\n *\n * @example\n * preferredEncoding(\"gzip, deflate, br\", [\"br\", \"gzip\"]); // => \"br\"\n * preferredEncoding(\"br;q=0, gzip\", [\"br\", \"gzip\"]); // => \"gzip\"\n */\nexport function preferredEncoding(\n\theader: string | undefined,\n\toffered: readonly Encoding[],\n): Encoding | undefined {\n\tconst entries = parseAccept(header ?? \"\");\n\tconst quality = (coding: string) =>\n\t\t(\n\t\t\tentries.find((entry) => entry.type.toLowerCase() === coding) ??\n\t\t\tentries.find((entry) => entry.type === \"*\")\n\t\t)?.q ?? 0;\n\tlet best: Encoding | undefined;\n\tlet bestQuality = 0;\n\tfor (const encoding of offered) {\n\t\tconst value = quality(encoding);\n\t\tif (value > bestQuality) {\n\t\t\tbest = encoding;\n\t\t\tbestQuality = value;\n\t\t}\n\t}\n\t// Why only an `identity` entry: with no entry, identity is acceptable, but the client prefers a coding that it names.\n\tconst identity = entries.find((entry) => entry.type.toLowerCase() === \"identity\")?.q;\n\treturn identity != null && identity > bestQuality ? undefined : best;\n}\n\n/**\n * Whether a `Cache-Control` value forbids a change to the body, such as gzip.\n *\n * @example\n * forbidsTransform(\"public, no-transform\"); // => true\n * forbidsTransform(\"public, max-age=3600\"); // => false\n */\nexport function forbidsTransform(cacheControl: string | null): boolean {\n\treturn /\\bno-transform\\b/u.test(cacheControl ?? \"\");\n}\n\n/** The result of one read of a byte stream. */\nexport type ReadResult = ReadableStreamReadResult<Uint8Array>;\n\n/**\n * The next result if `reader` has it queued, or the read that is still open.\n * It never waits for the source.\n *\n * @example\n * const next = await readIfQueued(reader); // => { result: { done: false, value } } or { pending }\n */\nexport async function readIfQueued(\n\treader: ReadableStreamDefaultReader<Uint8Array>,\n): Promise<{ result: ReadResult } | { pending: Promise<ReadResult> }> {\n\tconst pending = reader.read();\n\t// Why: a client that leaves before the body is read must not cause an unhandled rejection.\n\tpending.catch(() => {});\n\tconst result = await Promise.race([pending, Promise.resolve().then(async () => undefined)]);\n\treturn result == null ? { pending } : { result };\n}\n"],"mappings":";;;;;;;;;;AASA,MAAM,eACL;;;;;;AAOD,MAAa,qBAAqB;;;;;;AAUlC,MAAa,iBAAsC,CAAC,MAAM,MAAM;AAEhE,MAAM,kBAAsD;CAAE,IAAI;CAAM,MAAM;AAAK;;;;;;;;;;;;;AAcnF,SAAgB,SAAS,MAAc,UAA4B;CAClE,OAAO,IAAI,KAAK,GAAG,gBAAgB;AACpC;;;;;;;;AASA,SAAgB,eAAe,MAAuB;CACrD,OAAO,aAAa,KAAK,IAAI;AAC9B;;;;;;;;;;;;AAaA,SAAgB,kBACf,QACA,SACuB;CACvB,MAAM,UAAU,YAAY,UAAU,EAAE;CACxC,MAAM,WAAW,YAEf,QAAQ,MAAM,UAAU,MAAM,KAAK,YAAY,MAAM,MAAM,KAC3D,QAAQ,MAAM,UAAU,MAAM,SAAS,GAAG,EAAC,EACzC,KAAK;CACT,IAAI;CACJ,IAAI,cAAc;CAClB,KAAK,MAAM,YAAY,SAAS;EAC/B,MAAM,QAAQ,QAAQ,QAAQ;EAC9B,IAAI,QAAQ,aAAa;GACxB,OAAO;GACP,cAAc;EACf;CACD;CAEA,MAAM,WAAW,QAAQ,MAAM,UAAU,MAAM,KAAK,YAAY,MAAM,UAAU,CAAC,EAAE;CACnF,OAAO,YAAY,QAAQ,WAAW,cAAc,SAAY;AACjE;;;;;;;;AASA,SAAgB,iBAAiB,cAAsC;CACtE,OAAO,oBAAoB,KAAK,gBAAgB,EAAE;AACnD;;;;;;;;AAYA,eAAsB,aACrB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