@ngrok/app-server 0.2.0 → 0.3.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.
- package/README.md +652 -77
- package/dist/build-id-C6sYO9Yp.js +126 -0
- package/dist/build-id-C6sYO9Yp.js.map +1 -0
- package/dist/{build-manifest-8NfD1wnO.js → build-manifest-UDNk81Ce.js} +24 -6
- package/dist/build-manifest-UDNk81Ce.js.map +1 -0
- package/dist/cli.js +45 -25
- package/dist/cli.js.map +1 -1
- package/dist/client-browser.d.ts +12 -0
- package/dist/client-browser.js +3 -0
- package/dist/client.d.ts +21 -0
- package/dist/client.js +27 -0
- package/dist/client.js.map +1 -0
- package/dist/compression-7_gToa8R.js +97 -0
- package/dist/compression-7_gToa8R.js.map +1 -0
- package/dist/create-server-DkTeIJ8L.js +1409 -0
- package/dist/create-server-DkTeIJ8L.js.map +1 -0
- package/dist/{deno-DNRgzHrk.js → deno-aqhikNMG.js} +2 -2
- package/dist/deno-aqhikNMG.js.map +1 -0
- package/dist/entry-CM6Ma-Tv.d.ts +626 -0
- package/dist/entry-CenmvESk.js +116 -0
- package/dist/entry-CenmvESk.js.map +1 -0
- package/dist/gzip-Doi4wqjX.js +294 -0
- package/dist/gzip-Doi4wqjX.js.map +1 -0
- package/dist/header-hook-Vzw9J9BY.js +159 -0
- package/dist/header-hook-Vzw9J9BY.js.map +1 -0
- package/dist/{index-oSE-tYRW.d.ts → index-Bo5G9LuQ.d.ts} +53 -14
- package/dist/index.d.ts +99 -269
- package/dist/index.js +47 -59
- package/dist/index.js.map +1 -1
- package/dist/listen-options-7TaXjyrk.js.map +1 -1
- package/dist/{load-entry-C03qqmhr.js → load-entry-CmkdlmDX.js} +8 -4
- package/dist/{load-entry-C03qqmhr.js.map → load-entry-CmkdlmDX.js.map} +1 -1
- package/dist/log-BP6xXXZl.js +122 -0
- package/dist/log-BP6xXXZl.js.map +1 -0
- package/dist/node-BFH82eeL.js +333 -0
- package/dist/node-BFH82eeL.js.map +1 -0
- package/dist/node-tBVQPjQv.js +41 -0
- package/dist/node-tBVQPjQv.js.map +1 -0
- package/dist/node-vite.d.ts +5 -4
- package/dist/node-vite.js +2 -17
- package/dist/node.d.ts +23 -4
- package/dist/node.js +2 -2
- package/dist/react-router-vite.d.ts +4 -3
- package/dist/react-router-vite.js +2 -20
- package/dist/react-router.d.ts +1 -1
- package/dist/react-router.js +8 -7
- package/dist/react-router.js.map +1 -1
- package/dist/request-context-BtQ87VYb.js +40 -0
- package/dist/request-context-BtQ87VYb.js.map +1 -0
- package/dist/response-edge-Bc1-C_Cx.js +327 -0
- package/dist/response-edge-Bc1-C_Cx.js.map +1 -0
- package/dist/response-writer-B7FoJjEE.js +289 -0
- package/dist/response-writer-B7FoJjEE.js.map +1 -0
- package/dist/script-hashes-hqUk6kG7.js +53 -0
- package/dist/script-hashes-hqUk6kG7.js.map +1 -0
- package/dist/{serve-Cleo8RMO.js → serve-Cc-ADdhZ.js} +3 -3
- package/dist/{serve-Cleo8RMO.js.map → serve-Cc-ADdhZ.js.map} +1 -1
- package/dist/stale-build-navigation-PnMLtTF8.js +339 -0
- package/dist/stale-build-navigation-PnMLtTF8.js.map +1 -0
- package/dist/stale-build-navigation-ypV7Ow4o.d.ts +141 -0
- package/dist/{start-CINALHxy.js → start-Cb3kknlF.js} +14 -19
- package/dist/start-Cb3kknlF.js.map +1 -0
- package/dist/static-files-Beju9riB.js +302 -0
- package/dist/static-files-Beju9riB.js.map +1 -0
- package/dist/tanstack-start-vite.d.ts +6 -5
- package/dist/tanstack-start-vite.js +2 -23
- package/dist/tanstack-start.d.ts +19 -2
- package/dist/tanstack-start.js +5 -14
- package/dist/tanstack-start.js.map +1 -1
- package/dist/{tcp-C-9AmFuM.js → tcp-Dd1Mt6sN.js} +6 -5
- package/dist/{tcp-C-9AmFuM.js.map → tcp-Dd1Mt6sN.js.map} +1 -1
- package/dist/trailing-slash-DX7NB88H.d.ts +36 -0
- package/dist/types-DLYxYS6M.d.ts +392 -0
- package/dist/vercel-vite.d.ts +35 -0
- package/dist/vercel-vite.js +142 -0
- package/dist/vercel-vite.js.map +1 -0
- package/dist/vercel.d.ts +35 -0
- package/dist/vercel.js +89 -0
- package/dist/vercel.js.map +1 -0
- package/dist/vite-B-GfswoH.js +22 -0
- package/dist/vite-B-GfswoH.js.map +1 -0
- package/dist/vite-D4hfj3ph.js +19 -0
- package/dist/vite-D4hfj3ph.js.map +1 -0
- package/dist/vite-DyrhyKEr.js +25 -0
- package/dist/vite-DyrhyKEr.js.map +1 -0
- package/dist/vite-iioAoxSt.js +752 -0
- package/dist/vite-iioAoxSt.js.map +1 -0
- package/dist/vite.d.ts +2 -2
- package/dist/vite.js +1 -1
- package/package.json +25 -4
- package/dist/build-manifest-8NfD1wnO.js.map +0 -1
- package/dist/deno-DNRgzHrk.js.map +0 -1
- package/dist/entry-BkdUub2S.js +0 -638
- package/dist/entry-BkdUub2S.js.map +0 -1
- package/dist/log-CsjaKM8U.js +0 -59
- package/dist/log-CsjaKM8U.js.map +0 -1
- package/dist/node-CG7qXuWZ.js +0 -58
- package/dist/node-CG7qXuWZ.js.map +0 -1
- package/dist/node-YWPGmzAk.js +0 -215
- package/dist/node-YWPGmzAk.js.map +0 -1
- package/dist/node-ZMowKZDB.js +0 -3
- package/dist/node-vite.js.map +0 -1
- package/dist/react-router-vite.js.map +0 -1
- package/dist/start-CINALHxy.js.map +0 -1
- package/dist/tanstack-start-vite.js.map +0 -1
- package/dist/types-BfCkS7kQ.d.ts +0 -203
- package/dist/vite-mYZ2Y69u.js +0 -144
- package/dist/vite-mYZ2Y69u.js.map +0 -1
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { t as errorAttributes } from "./log-BP6xXXZl.js";
|
|
2
|
+
import { _ as abortShutdownSignal, r as serverInternals } from "./create-server-DkTeIJ8L.js";
|
|
3
|
+
import { a as keptFiles } from "./static-files-Beju9riB.js";
|
|
4
|
+
import { r as readBuildManifest } from "./build-manifest-UDNk81Ce.js";
|
|
5
|
+
|
|
6
|
+
// src/core/entry.ts
|
|
7
|
+
/** The version of the contract between the CLI and the `appServer` export of a build. */
|
|
8
|
+
const ENTRY_PROTOCOL = 2;
|
|
9
|
+
/**
|
|
10
|
+
* The `appServer` export of a server build: an app from `createServer`, the
|
|
11
|
+
* host, and the framework adapter for each mode. The `appServer` Vite plugin
|
|
12
|
+
* generates this export. Call this for a build without the plugin.
|
|
13
|
+
*
|
|
14
|
+
* @example
|
|
15
|
+
* export const appServer = createEntry({ app, host, framework: (mode) => runtime(build, { mode }) });
|
|
16
|
+
*/
|
|
17
|
+
function createEntry({ app, host, framework, clientDirectory }) {
|
|
18
|
+
const internals = serverInternals(app);
|
|
19
|
+
if (internals == null) throw new Error("The app is not from `createServer()` of the copy of @ngrok/app-server in this build.");
|
|
20
|
+
internals.setRequestStore(host.storage);
|
|
21
|
+
const setupInfo = async (runtime) => {
|
|
22
|
+
const directory = clientDirectory ?? runtime.clientDirectory;
|
|
23
|
+
if (directory == null) throw new Error(`Give createEntry a clientDirectory: the ${runtime.name} adapter does not know the client build.`);
|
|
24
|
+
return {
|
|
25
|
+
files: host.files(directory),
|
|
26
|
+
isDataRequest: runtime.isDataRequest ?? (() => false),
|
|
27
|
+
contentTypes: runtime.contentTypes ?? {},
|
|
28
|
+
gzip: host.gzip,
|
|
29
|
+
logger: internals.logger
|
|
30
|
+
};
|
|
31
|
+
};
|
|
32
|
+
/** Runs each plugin's `setup` for production, and gives the framework's run side. */
|
|
33
|
+
const prepareProduction = async () => {
|
|
34
|
+
const runtime = framework("production");
|
|
35
|
+
const shared = await setupInfo(runtime);
|
|
36
|
+
const snapshot = await shared.files.snapshot?.();
|
|
37
|
+
const files = snapshot == null ? shared.files : keptFiles(snapshot);
|
|
38
|
+
const manifest = await readBuildManifest(files);
|
|
39
|
+
const info = {
|
|
40
|
+
...shared,
|
|
41
|
+
files,
|
|
42
|
+
mode: "production",
|
|
43
|
+
prerenderedPaths: runtime.prerenderedPaths ?? manifest.prerendered,
|
|
44
|
+
capturedHeaders: new Map(Object.entries(manifest.headers)),
|
|
45
|
+
scriptHashes: new Map(Object.entries(manifest.scriptHashes)),
|
|
46
|
+
buildId: manifest.buildId
|
|
47
|
+
};
|
|
48
|
+
await internals.prepare(info);
|
|
49
|
+
return runtime;
|
|
50
|
+
};
|
|
51
|
+
let preparing;
|
|
52
|
+
/**
|
|
53
|
+
* The production run side, set up once. Why forget a failure: a serverless
|
|
54
|
+
* instance stays up, so the next request runs each `setup` again.
|
|
55
|
+
*/
|
|
56
|
+
const production = async () => {
|
|
57
|
+
preparing ??= prepareProduction().catch((error) => {
|
|
58
|
+
preparing = void 0;
|
|
59
|
+
throw error;
|
|
60
|
+
});
|
|
61
|
+
return preparing;
|
|
62
|
+
};
|
|
63
|
+
let development;
|
|
64
|
+
return {
|
|
65
|
+
protocol: 2,
|
|
66
|
+
app,
|
|
67
|
+
start: async () => {
|
|
68
|
+
const runtime = await production();
|
|
69
|
+
const server = await internals.listen(runtime, host.listeners?.());
|
|
70
|
+
host.lifecycle?.onStop(async () => server.shutdown().catch((error) => {
|
|
71
|
+
internals.logger.log("error", "shutdown failed", errorAttributes(error));
|
|
72
|
+
throw error;
|
|
73
|
+
}));
|
|
74
|
+
},
|
|
75
|
+
fetch: async (request, bindings) => {
|
|
76
|
+
const runtime = await production().catch((error) => {
|
|
77
|
+
internals.logger.log("error", "setup failed", errorAttributes(error));
|
|
78
|
+
throw error;
|
|
79
|
+
});
|
|
80
|
+
return app.fetch(request, {
|
|
81
|
+
...bindings,
|
|
82
|
+
framework: runtime
|
|
83
|
+
});
|
|
84
|
+
},
|
|
85
|
+
fetchDev: async (request, bindings, devServer) => {
|
|
86
|
+
development ??= framework("development");
|
|
87
|
+
await internals.prepare({
|
|
88
|
+
...await setupInfo(development),
|
|
89
|
+
mode: "development",
|
|
90
|
+
devServer,
|
|
91
|
+
prerenderedPaths: development.prerenderedPaths,
|
|
92
|
+
capturedHeaders: /* @__PURE__ */ new Map(),
|
|
93
|
+
scriptHashes: /* @__PURE__ */ new Map(),
|
|
94
|
+
buildId: void 0
|
|
95
|
+
});
|
|
96
|
+
return app.fetch(request, {
|
|
97
|
+
...bindings,
|
|
98
|
+
framework: development
|
|
99
|
+
});
|
|
100
|
+
},
|
|
101
|
+
stopPlugins: internals.stopPlugins,
|
|
102
|
+
abortShutdownSignal
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Whether a value is an entry of this protocol version.
|
|
107
|
+
*
|
|
108
|
+
* @example
|
|
109
|
+
* isAppServerEntry((await import("./build/server/app-server.js")).appServer); // => true
|
|
110
|
+
*/
|
|
111
|
+
function isAppServerEntry(value) {
|
|
112
|
+
return typeof value === "object" && value != null && "protocol" in value && value.protocol === 2;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export { isAppServerEntry as n, createEntry as t };
|
|
116
|
+
//# sourceMappingURL=entry-CenmvESk.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"entry-CenmvESk.js","names":[],"sources":["../src/core/entry.ts"],"sourcesContent":["import type { MiddlewareHandler } from \"hono\";\nimport { readBuildManifest } from \"./build-manifest.js\";\nimport { serverInternals } from \"./create-server.js\";\nimport type { AppServer } from \"./create-server.js\";\nimport { errorAttributes } from \"./log.js\";\nimport { abortShutdownSignal } from \"./shutdown.js\";\nimport { keptFiles } from \"./static-files.js\";\nimport type {\n\tAppServerEnv,\n\tFetchHandler,\n\tFrameworkRuntime,\n\tHostRuntime,\n\tListenerBindings,\n\tMode,\n\tSetupInfo,\n} from \"./types.js\";\n\n/** The version of the contract between the CLI and the `appServer` export of a build. */\nexport const ENTRY_PROTOCOL = 2;\n\n/**\n * What a server build exports as `appServer`. The CLI calls it, so the copy\n * of this package in the build runs the server, and the CLI's copy runs\n * nothing.\n */\nexport type AppServerEntry = {\n\t/** The CLI refuses an entry with another version. */\n\tprotocol: typeof ENTRY_PROTOCOL;\n\t/** The app. Two entries with the same app share its plugins. */\n\tapp: AppServer;\n\t/**\n\t * Production: runs each plugin's `setup` and listens. When the host's\n\t * lifecycle stops, such as on `SIGTERM`, it shuts down.\n\t */\n\tstart: () => Promise<void>;\n\t/**\n\t * Production, for a serverless host: answers one request, and does not\n\t * listen. The first call runs each plugin's `setup`.\n\t */\n\tfetch: FetchHandler;\n\t/** Development: answers one request with the dev server inside the pipeline. */\n\tfetchDev: (\n\t\trequest: Request,\n\t\tbindings: ListenerBindings,\n\t\tdevServer: MiddlewareHandler<AppServerEnv>,\n\t) => Promise<Response>;\n\t/** Runs each plugin's `onShutdown` once, up to the shutdown deadline. */\n\tstopPlugins: () => Promise<void>;\n\t/** Aborts `shutdownSignal()` of this copy of the package. */\n\tabortShutdownSignal: () => void;\n};\n\n/** Options for {@link createEntry}. */\nexport type CreateEntryOptions = {\n\t/** The app from `createServer`. */\n\tapp: AppServer;\n\t/** The run side of the host adapter, such as `host` from `@ngrok/app-server/node`. */\n\thost: HostRuntime;\n\t/** Makes the run side of the framework adapter for a mode. */\n\tframework: (mode: Mode) => FrameworkRuntime;\n\t/**\n\t * The client build, as a file path or a `file:` URL. The entry that the\n\t * Vite plugin generates sets it.\n\t * @default the framework's `clientDirectory`\n\t */\n\tclientDirectory?: string;\n};\n\n/**\n * The `appServer` export of a server build: an app from `createServer`, the\n * host, and the framework adapter for each mode. The `appServer` Vite plugin\n * generates this export. Call this for a build without the plugin.\n *\n * @example\n * export const appServer = createEntry({ app, host, framework: (mode) => runtime(build, { mode }) });\n */\nexport function createEntry({\n\tapp,\n\thost,\n\tframework,\n\tclientDirectory,\n}: CreateEntryOptions): AppServerEntry {\n\tconst internals = serverInternals(app);\n\tif (internals == null) {\n\t\tthrow new Error(\n\t\t\t\"The app is not from `createServer()` of the copy of @ngrok/app-server in this build.\",\n\t\t);\n\t}\n\tinternals.setRequestStore(host.storage);\n\tconst setupInfo = async (runtime: FrameworkRuntime) => {\n\t\tconst directory = clientDirectory ?? runtime.clientDirectory;\n\t\tif (directory == null) {\n\t\t\tthrow new Error(\n\t\t\t\t`Give createEntry a clientDirectory: the ${runtime.name} adapter does not know the client build.`,\n\t\t\t);\n\t\t}\n\t\tconst files = host.files(directory);\n\t\treturn {\n\t\t\tfiles,\n\t\t\tisDataRequest: runtime.isDataRequest ?? (() => false),\n\t\t\tcontentTypes: runtime.contentTypes ?? {},\n\t\t\tgzip: host.gzip,\n\t\t\tlogger: internals.logger,\n\t\t};\n\t};\n\t/** Runs each plugin's `setup` for production, and gives the framework's run side. */\n\tconst prepareProduction = async (): Promise<FrameworkRuntime> => {\n\t\tconst runtime = framework(\"production\");\n\t\tconst shared = await setupInfo(runtime);\n\t\tconst snapshot = await shared.files.snapshot?.();\n\t\t// Why only with a snapshot: it promises that the client build does not change while the server runs.\n\t\tconst files = snapshot == null ? shared.files : keptFiles(snapshot);\n\t\tconst manifest = await readBuildManifest(files);\n\t\tconst info: SetupInfo = {\n\t\t\t...shared,\n\t\t\tfiles,\n\t\t\tmode: \"production\",\n\t\t\tprerenderedPaths: runtime.prerenderedPaths ?? manifest.prerendered,\n\t\t\tcapturedHeaders: new Map(Object.entries(manifest.headers)),\n\t\t\tscriptHashes: new Map(Object.entries(manifest.scriptHashes)),\n\t\t\tbuildId: manifest.buildId,\n\t\t};\n\t\tawait internals.prepare(info);\n\t\treturn runtime;\n\t};\n\tlet preparing: Promise<FrameworkRuntime> | undefined;\n\t/**\n\t * The production run side, set up once. Why forget a failure: a serverless\n\t * instance stays up, so the next request runs each `setup` again.\n\t */\n\tconst production = async (): Promise<FrameworkRuntime> => {\n\t\tpreparing ??= prepareProduction().catch((error: unknown) => {\n\t\t\tpreparing = undefined;\n\t\t\tthrow error;\n\t\t});\n\t\treturn preparing;\n\t};\n\tlet development: FrameworkRuntime | undefined;\n\treturn {\n\t\tprotocol: ENTRY_PROTOCOL,\n\t\tapp,\n\t\tstart: async () => {\n\t\t\tconst runtime = await production();\n\t\t\tconst server = await internals.listen(runtime, host.listeners?.());\n\t\t\thost.lifecycle?.onStop(async () =>\n\t\t\t\tserver.shutdown().catch((error: unknown) => {\n\t\t\t\t\tinternals.logger.log(\"error\", \"shutdown failed\", errorAttributes(error));\n\t\t\t\t\tthrow error;\n\t\t\t\t}),\n\t\t\t);\n\t\t},\n\t\tfetch: async (request, bindings) => {\n\t\t\t// Why log it: the host sends a 500 with no log, and no app handler runs before setup ends.\n\t\t\tconst runtime = await production().catch((error: unknown) => {\n\t\t\t\tinternals.logger.log(\"error\", \"setup failed\", errorAttributes(error));\n\t\t\t\tthrow error;\n\t\t\t});\n\t\t\treturn app.fetch(request, { ...bindings, framework: runtime });\n\t\t},\n\t\tfetchDev: async (request, bindings, devServer) => {\n\t\t\tdevelopment ??= framework(\"development\");\n\t\t\tawait internals.prepare({\n\t\t\t\t...(await setupInfo(development)),\n\t\t\t\tmode: \"development\",\n\t\t\t\tdevServer,\n\t\t\t\tprerenderedPaths: development.prerenderedPaths,\n\t\t\t\tcapturedHeaders: new Map(),\n\t\t\t\tscriptHashes: new Map(),\n\t\t\t\t// Why none: development has no client build, and Vite's HMR updates an open tab after each edit.\n\t\t\t\tbuildId: undefined,\n\t\t\t});\n\t\t\treturn app.fetch(request, { ...bindings, framework: development });\n\t\t},\n\t\tstopPlugins: internals.stopPlugins,\n\t\tabortShutdownSignal,\n\t};\n}\n\n/**\n * Whether a value is an entry of this protocol version.\n *\n * @example\n * isAppServerEntry((await import(\"./build/server/app-server.js\")).appServer); // => true\n */\nexport function isAppServerEntry(value: unknown): value is AppServerEntry {\n\treturn (\n\t\ttypeof value === \"object\" &&\n\t\tvalue != null &&\n\t\t\"protocol\" in value &&\n\t\tvalue.protocol === ENTRY_PROTOCOL\n\t);\n}\n"],"mappings":";;;;;;;AAkBA,MAAa,iBAAiB;;;;;;;;;AA0D9B,SAAgB,YAAY,EAC3B,KACA,MACA,WACA,mBACsC;CACtC,MAAM,YAAY,gBAAgB,GAAG;CACrC,IAAI,aAAa,MAChB,MAAM,IAAI,MACT,sFACD;CAED,UA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M;GACP,CAAC,CACF;EACD;EACA,OAAO,OAAO,SAAS,aAAa;GAEnC,MAAM,UAAU,MAAM,WAAW,CAAC,CAAC,OAAO,UAAmB;IAC5D,UAAU,OAAO,IAAI,SAAS,gBAAgB,gBAAgB,KAAK,CAAC;IACpE,MAAM;GACP,CAAC;GACD,OAAO,IAAI,MAAM,SAAS;IAAE,GAAG;IAAU,WAAW;GAAQ,CAAC;EAC9D;EACA,UAAU,OAAO,SAAS,UAAU,cAAc;GACjD,gBAAgB,UAAU,aAAa;GACvC,MAAM,UAAU,QAAQ;IACvB,GAAI,MAAM,UAAU,WAAW;IAC/B,MAAM;IACN;IACA,kBAAkB,YAAY;IAC9B,iCAAiB,IAAI,IAAI;IACzB,8BAAc,IAAI,IAAI;IAEtB,SAAS;GACV,CAAC;GACD,OAAO,IAAI,MAAM,SAAS;IAAE,GAAG;IAAU,WAAW;GAAY,CAAC;EAClE;EACA,aAAa,UAAU;EACvB;CACD;AACD;;;;;;;AAQA,SAAgB,iBAAiB,OAAyC;CACzE,OACC,OAAO,UAAU,YACjB,SAAS,QACT,cAAc,SACd,MAAM;AAER"}
|
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
import { constants, crc32, createDeflateRaw, createGzip } from "node:zlib";
|
|
2
|
+
|
|
3
|
+
// src/node/gzip.ts
|
|
4
|
+
/**
|
|
5
|
+
* A stream from {@link gzipStream}. Why a class: the node response writer
|
|
6
|
+
* reads `busy` to hold the head for zlib's first chunk, and a field costs
|
|
7
|
+
* less than a `WeakMap` entry for each response.
|
|
8
|
+
*/
|
|
9
|
+
var GzipBody = class extends ReadableStream {
|
|
10
|
+
/** Whether the next chunk waits only on zlib, because the source gave the bytes already. */
|
|
11
|
+
busy = false;
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* Whether the next chunk of `stream` waits only on zlib, because its source
|
|
15
|
+
* gave the bytes already. It gives `undefined` for a stream that is not from
|
|
16
|
+
* {@link gzipStream}.
|
|
17
|
+
*
|
|
18
|
+
* @example
|
|
19
|
+
* waitsForZlib(gzipStream(source)); // => false, until the first read gives zlib a chunk
|
|
20
|
+
*/
|
|
21
|
+
function waitsForZlib(stream) {
|
|
22
|
+
return stream instanceof GzipBody ? stream.busy : void 0;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* The gzip header (RFC 1952): the magic number, deflate, no flags, no time,
|
|
26
|
+
* and the Unix system code.
|
|
27
|
+
*/
|
|
28
|
+
const HEADER = Buffer.from([
|
|
29
|
+
31,
|
|
30
|
+
139,
|
|
31
|
+
8,
|
|
32
|
+
0,
|
|
33
|
+
0,
|
|
34
|
+
0,
|
|
35
|
+
0,
|
|
36
|
+
0,
|
|
37
|
+
0,
|
|
38
|
+
3
|
|
39
|
+
]);
|
|
40
|
+
/** The gzip member of an empty body: the header, a final empty block, a CRC-32 of 0, and a size of 0. */
|
|
41
|
+
const EMPTY_MEMBER = Buffer.concat([HEADER, Buffer.from([
|
|
42
|
+
3,
|
|
43
|
+
0,
|
|
44
|
+
0,
|
|
45
|
+
0,
|
|
46
|
+
0,
|
|
47
|
+
0,
|
|
48
|
+
0,
|
|
49
|
+
0,
|
|
50
|
+
0,
|
|
51
|
+
0
|
|
52
|
+
])]);
|
|
53
|
+
/**
|
|
54
|
+
* The largest body that a pooled deflate stream compresses. Why a limit: the
|
|
55
|
+
* CRC-32 of a pooled body runs on the main thread, and above about 64 KiB it
|
|
56
|
+
* costs more than a new zlib stream does.
|
|
57
|
+
*/
|
|
58
|
+
const POOLED_MAX_BYTES = 65536;
|
|
59
|
+
/** The most deflate streams that wait for a body. Why a limit: each one keeps about 276 KiB of zlib state. */
|
|
60
|
+
const MAX_IDLE = 16;
|
|
61
|
+
function ignore() {}
|
|
62
|
+
function newDeflater() {
|
|
63
|
+
const deflater = {
|
|
64
|
+
stream: createDeflateRaw({ flush: constants.Z_FINISH }),
|
|
65
|
+
output: ignore,
|
|
66
|
+
fail: ignore,
|
|
67
|
+
size: 0
|
|
68
|
+
};
|
|
69
|
+
deflater.stream.on("data", (chunk) => {
|
|
70
|
+
deflater.output(chunk);
|
|
71
|
+
});
|
|
72
|
+
deflater.stream.on("error", (error) => {
|
|
73
|
+
deflater.fail(error);
|
|
74
|
+
});
|
|
75
|
+
deflater.stream.on("close", () => {
|
|
76
|
+
if (deflater.fail !== ignore) deflater.fail(/* @__PURE__ */ new Error("The deflate stream closed."));
|
|
77
|
+
});
|
|
78
|
+
return deflater;
|
|
79
|
+
}
|
|
80
|
+
/** The deflate streams that wait for a body, the last one given back last. */
|
|
81
|
+
const idle = [];
|
|
82
|
+
/**
|
|
83
|
+
* An idle deflate stream for a body of `size` bytes, else a new one. It takes
|
|
84
|
+
* a stream whose bodies were each no longer than this one: the longest such,
|
|
85
|
+
* and of those the last one given back, whose memory is still in the cache.
|
|
86
|
+
*
|
|
87
|
+
* Why: a reset keeps the window of zlib, and zlib reads the bytes after the
|
|
88
|
+
* end of a body to hash and match its last bytes. After a longer body, these
|
|
89
|
+
* are bytes of that body, so they could change the output of this one. A
|
|
90
|
+
* stream whose bodies were no longer has only the zeros that zlib writes
|
|
91
|
+
* after each body there, as a new stream does.
|
|
92
|
+
*/
|
|
93
|
+
function takeDeflater(size) {
|
|
94
|
+
let best = -1;
|
|
95
|
+
let bestSize = -1;
|
|
96
|
+
for (let index = idle.length - 1; index >= 0; index -= 1) {
|
|
97
|
+
const each = idle[index]?.size ?? Infinity;
|
|
98
|
+
if (each <= size && each > bestSize) {
|
|
99
|
+
best = index;
|
|
100
|
+
bestSize = each;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
if (best === -1) return newDeflater();
|
|
104
|
+
const taken = idle[best];
|
|
105
|
+
const last = idle.pop();
|
|
106
|
+
if (taken == null || last == null) return newDeflater();
|
|
107
|
+
if (last !== taken) idle[best] = last;
|
|
108
|
+
return taken;
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Gives back a deflate stream after its body. Why reset: the next body must
|
|
112
|
+
* not use the bytes of this one as a dictionary. When the pool is full, it
|
|
113
|
+
* keeps the streams of the shortest bodies, which more bodies can take.
|
|
114
|
+
*/
|
|
115
|
+
function release(deflater) {
|
|
116
|
+
deflater.output = ignore;
|
|
117
|
+
deflater.fail = ignore;
|
|
118
|
+
const { stream } = deflater;
|
|
119
|
+
if (stream.destroyed || stream.readableLength !== 0 || stream.writableLength !== 0) {
|
|
120
|
+
stream.destroy();
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
stream.reset();
|
|
124
|
+
if (stream.destroyed) return;
|
|
125
|
+
if (idle.length < MAX_IDLE) {
|
|
126
|
+
idle.push(deflater);
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
let longest = 0;
|
|
130
|
+
for (let index = 1; index < idle.length; index += 1) if ((idle[index]?.size ?? 0) > (idle[longest]?.size ?? 0)) longest = index;
|
|
131
|
+
const evicted = idle[longest];
|
|
132
|
+
if (evicted != null && evicted.size > deflater.size) {
|
|
133
|
+
idle[longest] = deflater;
|
|
134
|
+
evicted.stream.destroy();
|
|
135
|
+
} else stream.destroy();
|
|
136
|
+
}
|
|
137
|
+
/** Writes `chunk` to `stream`. zlib gives all the output of the chunk before this resolves. */
|
|
138
|
+
async function write(stream, chunk) {
|
|
139
|
+
return new Promise((resolve, reject) => {
|
|
140
|
+
stream.write(chunk, (error) => {
|
|
141
|
+
if (error == null) resolve();
|
|
142
|
+
else reject(error);
|
|
143
|
+
});
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* The gzip member of a body of one chunk, from a pooled raw deflate stream,
|
|
148
|
+
* with the header and the trailer written here, so the body needs one zlib
|
|
149
|
+
* call. `use` gets the stream while zlib compresses, so a cancel can destroy
|
|
150
|
+
* it, and gets `undefined` before the stream goes back to the pool. Why only
|
|
151
|
+
* a body of one chunk: a reset keeps the old window, and a second write reads
|
|
152
|
+
* its bytes as history. The output of one write is the
|
|
153
|
+
* same as from a new stream, so it does not depend on an earlier body.
|
|
154
|
+
*/
|
|
155
|
+
async function gzipOnce(value, use) {
|
|
156
|
+
const deflater = takeDeflater(value.byteLength);
|
|
157
|
+
use(deflater);
|
|
158
|
+
const parts = [HEADER];
|
|
159
|
+
deflater.output = (chunk) => {
|
|
160
|
+
parts.push(chunk);
|
|
161
|
+
};
|
|
162
|
+
try {
|
|
163
|
+
await new Promise((resolve, reject) => {
|
|
164
|
+
deflater.fail = reject;
|
|
165
|
+
deflater.stream.write(value, (error) => {
|
|
166
|
+
if (error != null) reject(error);
|
|
167
|
+
else if (deflater.stream.destroyed) reject(/* @__PURE__ */ new Error("The deflate stream closed."));
|
|
168
|
+
else resolve();
|
|
169
|
+
});
|
|
170
|
+
});
|
|
171
|
+
} catch (error) {
|
|
172
|
+
deflater.output = ignore;
|
|
173
|
+
deflater.fail = ignore;
|
|
174
|
+
deflater.stream.destroy();
|
|
175
|
+
throw error;
|
|
176
|
+
}
|
|
177
|
+
deflater.size = Math.max(deflater.size, value.byteLength);
|
|
178
|
+
use(void 0);
|
|
179
|
+
release(deflater);
|
|
180
|
+
const trailer = Buffer.allocUnsafe(8);
|
|
181
|
+
trailer.writeUInt32LE(crc32(value), 0);
|
|
182
|
+
trailer.writeUInt32LE(value.byteLength, 4);
|
|
183
|
+
parts.push(trailer);
|
|
184
|
+
return Buffer.concat(parts);
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* Gzips a byte stream. `Z_SYNC_FLUSH` makes each written chunk readable at
|
|
188
|
+
* once. It reads the next source chunk only when the consumer pulls, so a slow
|
|
189
|
+
* client holds back the source. When the source ends by the time zlib
|
|
190
|
+
* finishes a chunk, that chunk and the gzip trailer go out as one. Why: the
|
|
191
|
+
* host writes each chunk to the socket on its own, and a write costs more
|
|
192
|
+
* than its few bytes.
|
|
193
|
+
*
|
|
194
|
+
* A body that ends with its first chunk, up to 64 KiB, takes a pooled raw
|
|
195
|
+
* deflate stream. Why: a new zlib stream costs more main-thread time than
|
|
196
|
+
* zlib takes for a small page.
|
|
197
|
+
*
|
|
198
|
+
* @example
|
|
199
|
+
* new Response(gzipStream(response.body), response);
|
|
200
|
+
*/
|
|
201
|
+
function gzipStream(source) {
|
|
202
|
+
const reader = source.getReader();
|
|
203
|
+
let ended = false;
|
|
204
|
+
const markEnded = () => {
|
|
205
|
+
ended = true;
|
|
206
|
+
};
|
|
207
|
+
reader.closed.then(markEnded, () => {});
|
|
208
|
+
/** The gzip stream of a body of more than one chunk. */
|
|
209
|
+
let gzip;
|
|
210
|
+
/** The pooled deflate stream while it compresses the one chunk of a body. */
|
|
211
|
+
let pooled;
|
|
212
|
+
let started = false;
|
|
213
|
+
/** The zlib output that waits for the next enqueue. */
|
|
214
|
+
let held = [];
|
|
215
|
+
let heldBytes = 0;
|
|
216
|
+
const enqueueHeld = (controller) => {
|
|
217
|
+
const [first] = held;
|
|
218
|
+
if (first == null) return;
|
|
219
|
+
controller.enqueue(held.length === 1 ? first : Buffer.concat(held));
|
|
220
|
+
held = [];
|
|
221
|
+
heldBytes = 0;
|
|
222
|
+
};
|
|
223
|
+
const startGzip = (body, controller) => {
|
|
224
|
+
const created = createGzip({ flush: constants.Z_SYNC_FLUSH });
|
|
225
|
+
created.on("data", (chunk) => {
|
|
226
|
+
held.push(chunk);
|
|
227
|
+
heldBytes += chunk.byteLength;
|
|
228
|
+
if (heldBytes >= constants.Z_DEFAULT_CHUNK) enqueueHeld(controller);
|
|
229
|
+
});
|
|
230
|
+
created.on("end", () => {
|
|
231
|
+
body.busy = false;
|
|
232
|
+
enqueueHeld(controller);
|
|
233
|
+
controller.close();
|
|
234
|
+
});
|
|
235
|
+
created.on("error", (error) => {
|
|
236
|
+
body.busy = false;
|
|
237
|
+
controller.error(error);
|
|
238
|
+
});
|
|
239
|
+
return created;
|
|
240
|
+
};
|
|
241
|
+
const stream = new GzipBody({
|
|
242
|
+
async pull(controller) {
|
|
243
|
+
try {
|
|
244
|
+
let chunk = await reader.read();
|
|
245
|
+
while (!chunk.done && chunk.value.byteLength === 0) chunk = await reader.read();
|
|
246
|
+
if (!started) {
|
|
247
|
+
started = true;
|
|
248
|
+
if (chunk.done) {
|
|
249
|
+
controller.enqueue(EMPTY_MEMBER);
|
|
250
|
+
controller.close();
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
stream.busy = true;
|
|
254
|
+
await Promise.resolve();
|
|
255
|
+
if (ended && chunk.value.byteLength <= POOLED_MAX_BYTES) {
|
|
256
|
+
const member = await gzipOnce(chunk.value, (deflater) => {
|
|
257
|
+
pooled = deflater;
|
|
258
|
+
});
|
|
259
|
+
stream.busy = false;
|
|
260
|
+
controller.enqueue(member);
|
|
261
|
+
controller.close();
|
|
262
|
+
return;
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
gzip ??= startGzip(stream, controller);
|
|
266
|
+
stream.busy = true;
|
|
267
|
+
if (chunk.done) {
|
|
268
|
+
gzip.end();
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
await write(gzip, chunk.value);
|
|
272
|
+
if (ended) {
|
|
273
|
+
gzip.end();
|
|
274
|
+
return;
|
|
275
|
+
}
|
|
276
|
+
stream.busy = false;
|
|
277
|
+
enqueueHeld(controller);
|
|
278
|
+
} catch (error) {
|
|
279
|
+
stream.busy = false;
|
|
280
|
+
gzip?.destroy();
|
|
281
|
+
throw error;
|
|
282
|
+
}
|
|
283
|
+
},
|
|
284
|
+
async cancel(reason) {
|
|
285
|
+
gzip?.destroy();
|
|
286
|
+
pooled?.stream.destroy();
|
|
287
|
+
return reader.cancel(reason);
|
|
288
|
+
}
|
|
289
|
+
}, { highWaterMark: 0 });
|
|
290
|
+
return stream;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
export { waitsForZlib as n, gzipStream as t };
|
|
294
|
+
//# sourceMappingURL=gzip-Doi4wqjX.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"gzip-Doi4wqjX.js","names":[],"sources":["../src/node/gzip.ts"],"sourcesContent":["import { constants, crc32, createDeflateRaw, createGzip } from \"node:zlib\";\nimport type { DeflateRaw, Gzip } from \"node:zlib\";\n\n/**\n * A stream from {@link gzipStream}. Why a class: the node response writer\n * reads `busy` to hold the head for zlib's first chunk, and a field costs\n * less than a `WeakMap` entry for each response.\n */\nclass GzipBody extends ReadableStream<Uint8Array> {\n\t/** Whether the next chunk waits only on zlib, because the source gave the bytes already. */\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}.\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 GzipBody ? 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 deflate stream compresses. Why a limit: the\n * CRC-32 of a pooled body runs on the main thread, and above about 64 KiB it\n * costs more than a new zlib stream does.\n */\nconst POOLED_MAX_BYTES = 64 * 1024;\n\n/** The most deflate streams that wait for a body. Why a limit: each one keeps about 276 KiB of zlib state. */\nconst MAX_IDLE = 16;\n\nfunction ignore(): void {}\n\n/**\n * A raw deflate stream that compresses one body at a time, the target of its\n * output and of its failure, and the size of the longest body that it\n * compressed.\n */\ntype Deflater = {\n\tstream: DeflateRaw;\n\toutput: (chunk: Buffer) => void;\n\tfail: (error: Error) => void;\n\tsize: number;\n};\n\nfunction newDeflater(): Deflater {\n\tconst deflater: Deflater = {\n\t\t// Why `Z_FINISH`: when the output fills the buffer of the stream exactly, the stream calls zlib\n\t\t// again, and a sync flush then adds an empty block. So the output would depend on earlier bodies.\n\t\tstream: createDeflateRaw({ flush: constants.Z_FINISH }),\n\t\toutput: ignore,\n\t\tfail: ignore,\n\t\tsize: 0,\n\t};\n\tdeflater.stream.on(\"data\", (chunk: Buffer) => {\n\t\tdeflater.output(chunk);\n\t});\n\t// Why both: zlib destroys the stream at a failure, and then it never calls the write callback.\n\tdeflater.stream.on(\"error\", (error) => {\n\t\tdeflater.fail(error);\n\t});\n\tdeflater.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 (deflater.fail !== ignore) {\n\t\t\tdeflater.fail(new Error(\"The deflate stream closed.\"));\n\t\t}\n\t});\n\treturn deflater;\n}\n\n/** The deflate streams that wait for a body, the last one given back last. */\nconst idle: Deflater[] = [];\n\n/**\n * An idle deflate stream for a body of `size` bytes, else a new one. It takes\n * a stream whose bodies were each no longer than this one: the longest such,\n * and of those the last one given back, whose memory is still in the cache.\n *\n * Why: a reset keeps the window of zlib, and zlib reads the bytes after the\n * end of a body to hash and match its last bytes. After a longer body, these\n * are bytes of that body, so they could change the output of this one. A\n * stream whose bodies were no longer has only the zeros that zlib writes\n * after each body there, as a new stream does.\n */\nfunction takeDeflater(size: number): Deflater {\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 newDeflater();\n\t}\n\tconst taken = idle[best];\n\tconst last = idle.pop();\n\tif (taken == null || last == null) {\n\t\treturn newDeflater();\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 deflate stream 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(deflater: Deflater): void {\n\tdeflater.output = ignore;\n\tdeflater.fail = ignore;\n\tconst { stream } = deflater;\n\t// Why check the queues: a stream with output or input still queued would give it to the next body.\n\tif (stream.destroyed || stream.readableLength !== 0 || stream.writableLength !== 0) {\n\t\tstream.destroy();\n\t\treturn;\n\t}\n\tstream.reset();\n\t// Why the check: a reset that fails destroys the stream.\n\tif (stream.destroyed) {\n\t\treturn;\n\t}\n\tif (idle.length < MAX_IDLE) {\n\t\tidle.push(deflater);\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 > deflater.size) {\n\t\tidle[longest] = deflater;\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: Gzip, 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 gzip member of a body of one chunk, from a pooled raw deflate stream,\n * with the header and the trailer written here, so the body needs one zlib\n * call. `use` gets the stream while zlib compresses, so a cancel can destroy\n * it, and gets `undefined` before the stream goes back to the pool. Why only\n * a body of one chunk: a reset keeps the old window, and a second write reads\n * its bytes as history. The output of one write is the\n * same as from a new stream, so it does not depend on an earlier body.\n */\nasync function gzipOnce(\n\tvalue: Uint8Array,\n\tuse: (deflater: Deflater | undefined) => void,\n): Promise<Buffer> {\n\tconst deflater = takeDeflater(value.byteLength);\n\tuse(deflater);\n\tconst parts: Buffer[] = [HEADER];\n\tdeflater.output = (chunk) => {\n\t\tparts.push(chunk);\n\t};\n\ttry {\n\t\tawait new Promise<void>((resolve, reject) => {\n\t\t\tdeflater.fail = reject;\n\t\t\tdeflater.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 (deflater.stream.destroyed) {\n\t\t\t\t\treject(new Error(\"The deflate 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\tdeflater.output = ignore;\n\t\tdeflater.fail = ignore;\n\t\tdeflater.stream.destroy();\n\t\tthrow error;\n\t}\n\tdeflater.size = Math.max(deflater.size, value.byteLength);\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(deflater);\n\tconst trailer = Buffer.allocUnsafe(8);\n\ttrailer.writeUInt32LE(crc32(value), 0);\n\ttrailer.writeUInt32LE(value.byteLength, 4);\n\tparts.push(trailer);\n\treturn Buffer.concat(parts);\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. Why: the\n * host writes each chunk to the socket on its own, and a write costs more\n * than its few bytes.\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\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 gzip stream of a body of more than one chunk. */\n\tlet gzip: Gzip | undefined;\n\t/** The pooled deflate stream while it compresses the one chunk of a body. */\n\tlet pooled: Deflater | undefined;\n\tlet started = false;\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 startGzip = (\n\t\tbody: GzipBody,\n\t\tcontroller: ReadableStreamDefaultController<Uint8Array>,\n\t): Gzip => {\n\t\tconst created = createGzip({ flush: constants.Z_SYNC_FLUSH });\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: GzipBody = new GzipBody(\n\t\t{\n\t\t\tasync pull(controller) {\n\t\t\t\ttry {\n\t\t\t\t\tlet chunk = await reader.read();\n\t\t\t\t\t// Why skip empty chunks: zlib writes nothing for one, and a pull that enqueues nothing\n\t\t\t\t\t// is not called again.\n\t\t\t\t\twhile (!chunk.done && chunk.value.byteLength === 0) {\n\t\t\t\t\t\tchunk = await reader.read();\n\t\t\t\t\t}\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(EMPTY_MEMBER);\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\tif (ended && chunk.value.byteLength <= POOLED_MAX_BYTES) {\n\t\t\t\t\t\t\tconst member = await gzipOnce(chunk.value, (deflater) => {\n\t\t\t\t\t\t\t\tpooled = deflater;\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(member);\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}\n\t\t\t\t\tgzip ??= startGzip(stream, controller);\n\t\t\t\t\tstream.busy = true;\n\t\t\t\t\tif (chunk.done) {\n\t\t\t\t\t\tgzip.end();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tawait write(gzip, chunk.value);\n\t\t\t\t\tif (ended) {\n\t\t\t\t\t\tgzip.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\tgzip?.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\tgzip?.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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ACZ,YAAY,UAAU;GACtB,WAAW,MAAM;EAClB,CAAC;EACD,QAAQ,GAAG,UAAU,UAAU;GAC9B,KAAK,OAAO;GACZ,WAAW,MAAM,KAAK;EACvB,CAAC;EACD,OAAO;CACR;CACA,MAAM,SAAmB,IAAI,SAC5B;EACC,MAAM,KAAK,YAAY;GACtB,IAAI;IACH,IAAI,QAAQ,MAAM,OAAO,KAAK;IAG9B,OAAO,CAAC,MAAM,QAAQ,MAAM,MAAM,eAAe,GAChD,QAAQ,MAAM,OAAO,KAAK;IAE3B,IAAI,CAAC,SAAS;KACb,UAAU;KACV,IAAI,MAAM,MAAM;MACf,WAAW,QAAQ,YAAY;MAC/B,WAAW,MAAM;MACjB;KACD;KACA,OAAO,OAAO;KAEd,MAAM,QAAQ,QAAQ;KACtB,IAAI,SAAS,MAAM,MAAM,cAAc,kBAAkB;MACxD,MAAM,SAAS,MAAM,SAAS,MAAM,QAAQ,aAAa;OACxD,SAAS;MACV,CAAC;MACD,OAAO,OAAO;MACd,WAAW,QAAQ,MAAM;MACzB,WAAW,MAAM;MACjB;KACD;IACD;IACA,SAAS,UAAU,QAAQ,UAAU;IACrC,OAAO,OAAO;IACd,IAAI,MAAM,MAAM;KACf,KAAK,IAAI;KACT;IACD;IACA,MAAM,MAAM,MAAM,MAAM,KAAK;IAC7B,IAAI,OAAO;KACV,KAAK,IAAI;KACT;IACD;IACA,OAAO,OAAO;IAGd,YAAY,UAAU;GACvB,SAAS,OAAO;IACf,OAAO,OAAO;IACd,MAAM,QAAQ;IACd,MAAM;GACP;EACD;EAEA,MAAM,OAAO,QAAQ;GACpB,MAAM,QAAQ;GAEd,QAAQ,OAAO,QAAQ;GACvB,OAAO,OAAO,OAAO,MAAM;EAC5B;CACD,GAEA,EAAE,eAAe,EAAE,CACpB;CACA,OAAO;AACR"}
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
// src/core/header-hook.ts
|
|
2
|
+
/**
|
|
3
|
+
* The response that each request made, so a later write can change it in
|
|
4
|
+
* place: a copy from {@link writableHeaders}, or a response from
|
|
5
|
+
* {@link replaceResponse}. Why by request: an app can send a response of an
|
|
6
|
+
* earlier request again, and this request must not change it.
|
|
7
|
+
*/
|
|
8
|
+
const owned = /* @__PURE__ */ new WeakMap();
|
|
9
|
+
/**
|
|
10
|
+
* Makes `response` the response of the request. It must be a new object,
|
|
11
|
+
* such as `new Response(body, context.res)`, so that later writes change it
|
|
12
|
+
* in place.
|
|
13
|
+
*
|
|
14
|
+
* Why clear first: Hono's setter copies the new response and sets each
|
|
15
|
+
* header of the old one, such as its length, on it again.
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* replaceResponse(context, new Response(gzip(context.res.body), context.res));
|
|
19
|
+
*/
|
|
20
|
+
function replaceResponse(context, response) {
|
|
21
|
+
context.res = void 0;
|
|
22
|
+
context.res = response;
|
|
23
|
+
owned.set(context, response);
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* The headers of `context.res`, to change after the later stages. The first
|
|
27
|
+
* call for a response copies it, and later calls give the same copy.
|
|
28
|
+
*
|
|
29
|
+
* Why a copy: the response can have immutable headers, such as one from
|
|
30
|
+
* `fetch()`, or be an object that the app sends again. Why one copy:
|
|
31
|
+
* `context.header` copies the whole response on each call.
|
|
32
|
+
*
|
|
33
|
+
* @example
|
|
34
|
+
* await next();
|
|
35
|
+
* writableHeaders(context).set("Vary", "Accept-Encoding");
|
|
36
|
+
*/
|
|
37
|
+
function writableHeaders(context) {
|
|
38
|
+
if (owned.get(context) !== context.res) replaceResponse(context, new Response(context.res.body, context.res));
|
|
39
|
+
return context.res.headers;
|
|
40
|
+
}
|
|
41
|
+
/** A view of the headers of `context.res` that copies the response at the first change. */
|
|
42
|
+
function responseHeaders(context) {
|
|
43
|
+
return {
|
|
44
|
+
get: (name) => context.res.headers.get(name),
|
|
45
|
+
has: (name) => context.res.headers.has(name),
|
|
46
|
+
set: (name, value) => {
|
|
47
|
+
writableHeaders(context).set(name, value);
|
|
48
|
+
},
|
|
49
|
+
append: (name, value) => {
|
|
50
|
+
writableHeaders(context).append(name, value);
|
|
51
|
+
},
|
|
52
|
+
delete: (name) => {
|
|
53
|
+
if (context.res.headers.has(name)) writableHeaders(context).delete(name);
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Runs `hook` on the response headers after the later stages. In an app
|
|
59
|
+
* server, the hook changes the head once, where the response leaves, so the
|
|
60
|
+
* response needs no copy. That run comes after the code that each stage runs
|
|
61
|
+
* after its `next()`, so a stage can decide there what its hook does. A hook
|
|
62
|
+
* that throws gives a 500. See {@link HeaderHook} for the order of the hooks
|
|
63
|
+
* and the views that also run them.
|
|
64
|
+
*
|
|
65
|
+
* @example
|
|
66
|
+
* const frameOptions: Plugin = {
|
|
67
|
+
* name: "frame-options",
|
|
68
|
+
* middleware: async (c, next) =>
|
|
69
|
+
* withHeaderHook(c, next, (response) => {
|
|
70
|
+
* response.set("X-Frame-Options", "DENY");
|
|
71
|
+
* }),
|
|
72
|
+
* };
|
|
73
|
+
*/
|
|
74
|
+
async function withHeaderHook(context, next, hook) {
|
|
75
|
+
const hooks = context.get("headerHooks");
|
|
76
|
+
if (hooks == null) {
|
|
77
|
+
await next();
|
|
78
|
+
hook(responseHeaders(context));
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
hooks.push(hook);
|
|
82
|
+
await next();
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* The index of the lowercase `name` in a flat `[name, value, …]` header list, or -1.
|
|
86
|
+
*
|
|
87
|
+
* @example
|
|
88
|
+
* headerIndex(["content-type", "text/html", "vary", "Accept"], "vary"); // => 2
|
|
89
|
+
*/
|
|
90
|
+
function headerIndex(head, name) {
|
|
91
|
+
for (let index = 0; index < head.length; index += 2) if (head[index] === name) return index;
|
|
92
|
+
return -1;
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* The flat `[name, value, …]` list of `headers`, with lowercase names.
|
|
96
|
+
*
|
|
97
|
+
* @example
|
|
98
|
+
* headerList(new Headers({ "Content-Type": "text/html" })); // => ["content-type", "text/html"]
|
|
99
|
+
*/
|
|
100
|
+
function headerList(headers) {
|
|
101
|
+
const head = [];
|
|
102
|
+
for (const [name, value] of headers) head.push(name, value);
|
|
103
|
+
return head;
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* A view of a flat `[name, value, …]` header list with lowercase names, for
|
|
107
|
+
* the header hooks. It reads and changes the list as `Headers` does.
|
|
108
|
+
*/
|
|
109
|
+
function listView(head) {
|
|
110
|
+
const remove = (name) => {
|
|
111
|
+
for (let index = head.length - 2; index >= 0; index -= 2) if (head[index] === name) head.splice(index, 2);
|
|
112
|
+
};
|
|
113
|
+
const get = (name) => {
|
|
114
|
+
const lower = name.toLowerCase();
|
|
115
|
+
let value = null;
|
|
116
|
+
for (let index = 0; index < head.length; index += 2) if (head[index] === lower) value = value == null ? head[index + 1] ?? "" : `${value}, ${head[index + 1] ?? ""}`;
|
|
117
|
+
return value;
|
|
118
|
+
};
|
|
119
|
+
return {
|
|
120
|
+
get,
|
|
121
|
+
has: (name) => headerIndex(head, name.toLowerCase()) !== -1,
|
|
122
|
+
set: (name, value) => {
|
|
123
|
+
const lower = name.toLowerCase();
|
|
124
|
+
remove(lower);
|
|
125
|
+
head.push(lower, value);
|
|
126
|
+
},
|
|
127
|
+
append: (name, value) => {
|
|
128
|
+
const lower = name.toLowerCase();
|
|
129
|
+
const index = lower === "set-cookie" ? -1 : headerIndex(head, lower);
|
|
130
|
+
if (index === -1) head.push(lower, value);
|
|
131
|
+
else head[index + 1] = `${head[index + 1] ?? ""}, ${value}`;
|
|
132
|
+
},
|
|
133
|
+
delete: (name) => {
|
|
134
|
+
remove(name.toLowerCase());
|
|
135
|
+
}
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* A view of `headers` after the header hook of each stage that the request
|
|
140
|
+
* passed, in the order that the server runs them. Why: a stage that picks a
|
|
141
|
+
* body by a header, such as `Cache-Control: no-transform`, must see the value
|
|
142
|
+
* that a hook sets where the response leaves. So a hook can run more than
|
|
143
|
+
* once. Why a view: the hooks change only the view, so `headers` needs no
|
|
144
|
+
* copy.
|
|
145
|
+
*
|
|
146
|
+
* @example
|
|
147
|
+
* forbidsTransform(hookedHeaders(context, headers).get("Cache-Control"));
|
|
148
|
+
*/
|
|
149
|
+
function hookedHeaders(context, headers) {
|
|
150
|
+
const view = listView(headerList(headers));
|
|
151
|
+
const hooks = context.get("headerHooks") ?? [];
|
|
152
|
+
for (let index = hooks.length - 1; index >= 0; index -= 1) try {
|
|
153
|
+
hooks[index]?.(view);
|
|
154
|
+
} catch {}
|
|
155
|
+
return view;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
export { replaceResponse as a, listView as i, headerList as n, withHeaderHook as o, hookedHeaders as r, writableHeaders as s, headerIndex as t };
|
|
159
|
+
//# sourceMappingURL=header-hook-Vzw9J9BY.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"header-hook-Vzw9J9BY.js","names":[],"sources":["../src/core/header-hook.ts"],"sourcesContent":["import type { Context, Next } from \"hono\";\nimport type { AppServerEnv, HeaderHook, ResponseHeaders } from \"./types.js\";\n\n/**\n * The response that each request made, so a later write can change it in\n * place: a copy from {@link writableHeaders}, or a response from\n * {@link replaceResponse}. Why by request: an app can send a response of an\n * earlier request again, and this request must not change it.\n */\nconst owned = new WeakMap<Context<AppServerEnv>, Response>();\n\n/**\n * Makes `response` the response of the request. It must be a new object,\n * such as `new Response(body, context.res)`, so that later writes change it\n * in place.\n *\n * Why clear first: Hono's setter copies the new response and sets each\n * header of the old one, such as its length, on it again.\n *\n * @example\n * replaceResponse(context, new Response(gzip(context.res.body), context.res));\n */\nexport function replaceResponse(context: Context<AppServerEnv>, response: Response): void {\n\tcontext.res = undefined;\n\tcontext.res = response;\n\towned.set(context, response);\n}\n\n/**\n * The headers of `context.res`, to change after the later stages. The first\n * call for a response copies it, and later calls give the same copy.\n *\n * Why a copy: the response can have immutable headers, such as one from\n * `fetch()`, or be an object that the app sends again. Why one copy:\n * `context.header` copies the whole response on each call.\n *\n * @example\n * await next();\n * writableHeaders(context).set(\"Vary\", \"Accept-Encoding\");\n */\nexport function writableHeaders(context: Context<AppServerEnv>): Headers {\n\tif (owned.get(context) !== context.res) {\n\t\treplaceResponse(context, new Response(context.res.body, context.res));\n\t}\n\treturn context.res.headers;\n}\n\n/** A view of the headers of `context.res` that copies the response at the first change. */\nfunction responseHeaders(context: Context<AppServerEnv>): ResponseHeaders {\n\treturn {\n\t\tget: (name) => context.res.headers.get(name),\n\t\thas: (name) => context.res.headers.has(name),\n\t\tset: (name, value) => {\n\t\t\twritableHeaders(context).set(name, value);\n\t\t},\n\t\tappend: (name, value) => {\n\t\t\twritableHeaders(context).append(name, value);\n\t\t},\n\t\tdelete: (name) => {\n\t\t\t// Why check first: the first write copies the response, and a missing header needs no copy.\n\t\t\tif (context.res.headers.has(name)) {\n\t\t\t\twritableHeaders(context).delete(name);\n\t\t\t}\n\t\t},\n\t};\n}\n\n/**\n * Runs `hook` on the response headers after the later stages. In an app\n * server, the hook changes the head once, where the response leaves, so the\n * response needs no copy. That run comes after the code that each stage runs\n * after its `next()`, so a stage can decide there what its hook does. A hook\n * that throws gives a 500. See {@link HeaderHook} for the order of the hooks\n * and the views that also run them.\n *\n * @example\n * const frameOptions: Plugin = {\n * \tname: \"frame-options\",\n * \tmiddleware: async (c, next) =>\n * \t\twithHeaderHook(c, next, (response) => {\n * \t\t\tresponse.set(\"X-Frame-Options\", \"DENY\");\n * \t\t}),\n * };\n */\nexport async function withHeaderHook(\n\tcontext: Context<AppServerEnv>,\n\tnext: Next,\n\thook: HeaderHook,\n): Promise<void> {\n\tconst hooks = context.get(\"headerHooks\");\n\t// Why: outside an app server, such as in a plain Hono app, nothing runs the hook later.\n\tif (hooks == null) {\n\t\tawait next();\n\t\thook(responseHeaders(context));\n\t\treturn;\n\t}\n\thooks.push(hook);\n\tawait next();\n}\n\n/**\n * The index of the lowercase `name` in a flat `[name, value, …]` header list, or -1.\n *\n * @example\n * headerIndex([\"content-type\", \"text/html\", \"vary\", \"Accept\"], \"vary\"); // => 2\n */\nexport function headerIndex(head: readonly string[], name: string): number {\n\tfor (let index = 0; index < head.length; index += 2) {\n\t\tif (head[index] === name) {\n\t\t\treturn index;\n\t\t}\n\t}\n\treturn -1;\n}\n\n/**\n * The flat `[name, value, …]` list of `headers`, with lowercase names.\n *\n * @example\n * headerList(new Headers({ \"Content-Type\": \"text/html\" })); // => [\"content-type\", \"text/html\"]\n */\nexport function headerList(headers: Headers): string[] {\n\tconst head: string[] = [];\n\tfor (const [name, value] of headers) {\n\t\thead.push(name, value);\n\t}\n\treturn head;\n}\n\n/**\n * A view of a flat `[name, value, …]` header list with lowercase names, for\n * the header hooks. It reads and changes the list as `Headers` does.\n */\nexport function listView(head: string[]): ResponseHeaders {\n\tconst remove = (name: string) => {\n\t\tfor (let index = head.length - 2; index >= 0; index -= 2) {\n\t\t\tif (head[index] === name) {\n\t\t\t\thead.splice(index, 2);\n\t\t\t}\n\t\t}\n\t};\n\tconst get = (name: string) => {\n\t\tconst lower = name.toLowerCase();\n\t\tlet value: string | null = null;\n\t\tfor (let index = 0; index < head.length; index += 2) {\n\t\t\tif (head[index] === lower) {\n\t\t\t\tvalue = value == null ? (head[index + 1] ?? \"\") : `${value}, ${head[index + 1] ?? \"\"}`;\n\t\t\t}\n\t\t}\n\t\treturn value;\n\t};\n\treturn {\n\t\tget,\n\t\thas: (name) => headerIndex(head, name.toLowerCase()) !== -1,\n\t\tset: (name, value) => {\n\t\t\tconst lower = name.toLowerCase();\n\t\t\tremove(lower);\n\t\t\thead.push(lower, value);\n\t\t},\n\t\tappend: (name, value) => {\n\t\t\tconst lower = name.toLowerCase();\n\t\t\tconst index = lower === \"set-cookie\" ? -1 : headerIndex(head, lower);\n\t\t\t// Why join: `Headers` sends the values of a name on one line, except each `Set-Cookie`.\n\t\t\tif (index === -1) {\n\t\t\t\thead.push(lower, value);\n\t\t\t} else {\n\t\t\t\thead[index + 1] = `${head[index + 1] ?? \"\"}, ${value}`;\n\t\t\t}\n\t\t},\n\t\tdelete: (name) => {\n\t\t\tremove(name.toLowerCase());\n\t\t},\n\t};\n}\n\n/**\n * A view of `headers` after the header hook of each stage that the request\n * passed, in the order that the server runs them. Why: a stage that picks a\n * body by a header, such as `Cache-Control: no-transform`, must see the value\n * that a hook sets where the response leaves. So a hook can run more than\n * once. Why a view: the hooks change only the view, so `headers` needs no\n * copy.\n *\n * @example\n * forbidsTransform(hookedHeaders(context, headers).get(\"Cache-Control\"));\n */\nexport function hookedHeaders(context: Context<AppServerEnv>, headers: Headers): ResponseHeaders {\n\tconst view = listView(headerList(headers));\n\tconst hooks = context.get(\"headerHooks\") ?? [];\n\t// Why reversed: the hook of an inner stage runs first, so an outer stage has the last word.\n\tfor (let index = hooks.length - 1; index >= 0; index -= 1) {\n\t\ttry {\n\t\t\thooks[index]?.(view);\n\t\t} catch {\n\t\t\t// Why drop it: the run where the response leaves answers the error, and logs it once. A hook\n\t\t\t// can also need state that its stage sets after `next()`, which a view can come before.\n\t\t}\n\t}\n\treturn view;\n}\n"],"mappings":";;;;;;;AASA,MAAM,wBAAQ,IAAI,QAAyC;;;;;;;;;;;;AAa3D,SAAgB,gBAAgB,SAAgC,UAA0B;CACzF,QAAQ,MAAM;CACd,QAAQ,MAAM;CACd,MAAM,IAAI,SAAS,QAAQ;AAC5B;;;;;;;;;;;;;AAcA,SAAgB,gBAAgB,SAAyC;CACxE,IAAI,MAAM,IAAI,OAAO,MAAM,QAAQ,KAClC,gBAAgB,SAAS,IAAI,SAAS,QAAQ,IAAI,MAAM,QAAQ,GAAG,CAAC;CAErE,OAAO,QAAQ,IAAI;AACpB;;AAGA,SAAS,gBAAgB,SAAiD;CACzE,OAAO;EACN,MAAM,SAAS,QAAQ,IAAI,QAAQ,IAAI,IAAI;EAC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