@gusto/baerly-storage 0.5.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +47 -124
- package/dist/API.md +161 -511
- package/dist/CHANGELOG.md +1148 -307
- package/dist/RECIPES.md +398 -80
- package/dist/THIRD-PARTY-LICENSES.txt +5 -26
- package/dist/{app-config-DyiFK3_k.d.ts → app-config-C6qW7m8S.d.ts} +119 -111
- package/dist/app-config.d.ts +31 -1
- package/dist/app-config.js +1 -2
- package/dist/app-config.js.map +1 -1
- package/dist/auth.d.ts +33 -28
- package/dist/auth.js +549 -985
- package/dist/auth.js.map +1 -1
- package/dist/baerly.js +130 -138
- package/dist/baerly.js.map +1 -1
- package/dist/baerly.spec.json +97 -22
- package/dist/capacity-warning-header-BlVopyiI.js +16 -0
- package/dist/capacity-warning-header-BlVopyiI.js.map +1 -0
- package/dist/{client-Fe8CwB73.d.ts → client-CHQTXpef.d.ts} +121 -36
- package/dist/client-react.d.ts +67 -20
- package/dist/client-react.js +240 -54
- package/dist/client-react.js.map +1 -1
- package/dist/client.d.ts +5 -4
- package/dist/client.js +51 -16
- package/dist/client.js.map +1 -1
- package/dist/{cloudflare-DzKBrUlg.js → cloudflare-CKHYXccw.js} +504 -124
- package/dist/cloudflare-CKHYXccw.js.map +1 -0
- package/dist/cloudflare.d.ts +106 -71
- package/dist/cloudflare.js +334 -271
- package/dist/cloudflare.js.map +1 -1
- package/dist/code-resolution-CL_7L0wS.js +22 -0
- package/dist/code-resolution-CL_7L0wS.js.map +1 -0
- package/dist/collection-api-DbyhLAY8.d.ts +1001 -0
- package/dist/config-DEzInG6M.js +4035 -0
- package/dist/config-DEzInG6M.js.map +1 -0
- package/dist/constants-D3GSH3tc.js +469 -0
- package/dist/constants-D3GSH3tc.js.map +1 -0
- package/dist/{context-DRZ3tZ5l.js → context-rlpSnHFA.js} +17 -17
- package/dist/context-rlpSnHFA.js.map +1 -0
- package/dist/cost-B52llVDx.js +330 -0
- package/dist/cost-B52llVDx.js.map +1 -0
- package/dist/{current-json-C6nhPOm1.js → current-json-CC6lE4Aj.js} +115 -32
- package/dist/current-json-CC6lE4Aj.js.map +1 -0
- package/dist/db-plFUNTSF.d.ts +130 -0
- package/dist/db-read-seams-BSs0m1z1.js +3261 -0
- package/dist/db-read-seams-BSs0m1z1.js.map +1 -0
- package/dist/{deploy-DonTr-CV.js → deploy-Obj4nE-Z.js} +12 -16
- package/dist/deploy-Obj4nE-Z.js.map +1 -0
- package/dist/{dev-banner-CWHIk8tH.d.ts → dev-banner-B5AUHmu1.d.ts} +1 -4
- package/dist/dev-landing-BI5UdmOb.d.ts +32 -0
- package/dist/dev-landing-CD-si4dW.js +50 -0
- package/dist/dev-landing-CD-si4dW.js.map +1 -0
- package/dist/dev-vite.d.ts +38 -39
- package/dist/dev-vite.js +67 -36
- package/dist/dev-vite.js.map +1 -1
- package/dist/dev.d.ts +3 -2
- package/dist/dev.js +2 -1
- package/dist/doctor-BA0i-YAN.js +270 -0
- package/dist/doctor-BA0i-YAN.js.map +1 -0
- package/dist/dump-D1vX8ozg.js +133 -0
- package/dist/dump-D1vX8ozg.js.map +1 -0
- package/dist/errors-7Rk1HGCE.js +160 -0
- package/dist/errors-7Rk1HGCE.js.map +1 -0
- package/dist/{validate-DtljsCh1.js → export-BVL2EvYE.js} +409 -19
- package/dist/export-BVL2EvYE.js.map +1 -0
- package/dist/fsck-BWkPgov4.js +145 -0
- package/dist/fsck-BWkPgov4.js.map +1 -0
- package/dist/gcs-admin-Dso1HWQj.d.ts +127 -0
- package/dist/gcs.d.ts +30 -0
- package/dist/gcs.js +1 -0
- package/dist/goog4-signer-CeLIABoE.js +331 -0
- package/dist/goog4-signer-CeLIABoE.js.map +1 -0
- package/dist/{http-DGd5tbNs.js → http-Z5rZyYMX.js} +898 -271
- package/dist/http-Z5rZyYMX.js.map +1 -0
- package/dist/http-transport-DNUM8kU-.js +1299 -0
- package/dist/http-transport-DNUM8kU-.js.map +1 -0
- package/dist/http.d.ts +366 -294
- package/dist/http.js +2 -2
- package/dist/index-JJrIu1pO.d.ts +135 -0
- package/dist/index-LEgHN0qJ.d.ts +50 -0
- package/dist/{index-CuA9Mi3K.d.ts → index-RiEYj8t0.d.ts} +291 -78
- package/dist/index.d.ts +27 -6
- package/dist/index.js +3 -5
- package/dist/inspect-BTsVYZKd.js +196 -0
- package/dist/inspect-BTsVYZKd.js.map +1 -0
- package/dist/{key-Di6yyxFu.js → key-C4FPZ9Io.js} +3 -4
- package/dist/{key-Di6yyxFu.js.map → key-C4FPZ9Io.js.map} +1 -1
- package/dist/ledger-Dj_bGgo0.js +192 -0
- package/dist/ledger-Dj_bGgo0.js.map +1 -0
- package/dist/legacy-names-DgZBtgOh.js +47 -0
- package/dist/legacy-names-DgZBtgOh.js.map +1 -0
- package/dist/log-C9W15Dfo.d.ts +94 -0
- package/dist/log-tail-DWJbneBF.js +142 -0
- package/dist/log-tail-DWJbneBF.js.map +1 -0
- package/dist/log-walk-C-vA-WGJ.js +111 -0
- package/dist/log-walk-C-vA-WGJ.js.map +1 -0
- package/dist/maintenance-Dd-Yakqj.js +1709 -0
- package/dist/maintenance-Dd-Yakqj.js.map +1 -0
- package/dist/maintenance-DevB6z4e.js +2237 -0
- package/dist/maintenance-DevB6z4e.js.map +1 -0
- package/dist/maintenance.d.ts +100 -3
- package/dist/maintenance.js +1 -3
- package/dist/node.d.ts +130 -142
- package/dist/node.js +4 -3
- package/dist/{observability-BmflLCdF.js → observability-C-ISCCLE.js} +1275 -332
- package/dist/observability-C-ISCCLE.js.map +1 -0
- package/dist/observability.d.ts +27 -3
- package/dist/observability.js +3 -3
- package/dist/path-segment-DBXG26PW.js +363 -0
- package/dist/path-segment-DBXG26PW.js.map +1 -0
- package/dist/{plan-a7PJHBCy.js → plan-BvQbaNMe.js} +19 -11
- package/dist/plan-BvQbaNMe.js.map +1 -0
- package/dist/request-CRWiTrza.js +272 -0
- package/dist/request-CRWiTrza.js.map +1 -0
- package/dist/restore-U6Im8V1V.js +1467 -0
- package/dist/restore-U6Im8V1V.js.map +1 -0
- package/dist/retry-OBtLB2GC.js +126 -0
- package/dist/retry-OBtLB2GC.js.map +1 -0
- package/dist/rolldown-runtime-D3KUYPsf.js +12 -0
- package/dist/{runtime-spec-Dsw2-n8S.js → runtime-spec-B5mg3pHF.js} +189 -28
- package/dist/runtime-spec-B5mg3pHF.js.map +1 -0
- package/dist/{s3-http-B-z8th6O.d.ts → s3-http-DBC_wiCL.d.ts} +18 -10
- package/dist/s3.d.ts +20 -7
- package/dist/s3.js +4 -5
- package/dist/s3.js.map +1 -1
- package/dist/sha256-4FfGQNPw.js +22 -0
- package/dist/sha256-4FfGQNPw.js.map +1 -0
- package/dist/{shared-secret-DgEicd3x.js → shared-secret-Vkur-8r0.js} +27 -15
- package/dist/shared-secret-Vkur-8r0.js.map +1 -0
- package/dist/sigv4-sign-5IUflUD_.js +507 -0
- package/dist/sigv4-sign-5IUflUD_.js.map +1 -0
- package/dist/snapshot-CknzkDM0.js +148 -0
- package/dist/snapshot-CknzkDM0.js.map +1 -0
- package/dist/{src-BL_JoPTn.js → src-Actga-bO.js} +1004 -378
- package/dist/src-Actga-bO.js.map +1 -0
- package/dist/src-D0MQfvOp.js +812 -0
- package/dist/src-D0MQfvOp.js.map +1 -0
- package/dist/src-Dr9uo3dc.js +501 -0
- package/dist/src-Dr9uo3dc.js.map +1 -0
- package/dist/{subcommand-DoDA-K7d.js → subcommand-BLoF66dG.js} +89 -16
- package/dist/subcommand-BLoF66dG.js.map +1 -0
- package/dist/{time-DUqvFMHq.js → time-DRxTP9iv.js} +15 -34
- package/dist/time-DRxTP9iv.js.map +1 -0
- package/dist/types-suVbsEWS.d.ts +116 -0
- package/dist/{usage-DBV1eQHC.js → usage-CPzVhrQr.js} +40 -45
- package/dist/usage-CPzVhrQr.js.map +1 -0
- package/dist/uuid-BuT_c404.js +333 -0
- package/dist/uuid-BuT_c404.js.map +1 -0
- package/dist/verifier-Bmlmndzo.d.ts +95 -0
- package/dist/{wire-izfGZDvr.js → wire-DndvKU-K.js} +2 -3
- package/dist/wire-DndvKU-K.js.map +1 -0
- package/package.json +96 -69
- package/dist/aws4fetch.esm-p7eEzLCs.js +0 -1702
- package/dist/aws4fetch.esm-p7eEzLCs.js.map +0 -1
- package/dist/bytes-BXdamO3L.js +0 -11
- package/dist/bytes-BXdamO3L.js.map +0 -1
- package/dist/cloudflare-DzKBrUlg.js.map +0 -1
- package/dist/config-1tv0-Yzm.js +0 -2693
- package/dist/config-1tv0-Yzm.js.map +0 -1
- package/dist/constants-CfeMWQWk.js +0 -222
- package/dist/constants-CfeMWQWk.js.map +0 -1
- package/dist/context-DRZ3tZ5l.js.map +0 -1
- package/dist/cost-DSMIVqzL.js +0 -203
- package/dist/cost-DSMIVqzL.js.map +0 -1
- package/dist/current-json-C6nhPOm1.js.map +0 -1
- package/dist/db-DsPkOVEH.d.ts +0 -254
- package/dist/deploy-DonTr-CV.js.map +0 -1
- package/dist/doctor-DSIyCDg_.js +0 -346
- package/dist/doctor-DSIyCDg_.js.map +0 -1
- package/dist/dump-Bh5k26VQ.js +0 -94
- package/dist/dump-Bh5k26VQ.js.map +0 -1
- package/dist/errors-Dfa3p78c.js +0 -78
- package/dist/errors-Dfa3p78c.js.map +0 -1
- package/dist/export-DtF5tDIM.js +0 -401
- package/dist/export-DtF5tDIM.js.map +0 -1
- package/dist/fsck-D_djMO5D.js +0 -279
- package/dist/fsck-D_djMO5D.js.map +0 -1
- package/dist/http-DGd5tbNs.js.map +0 -1
- package/dist/index-0rZcMBwy.d.ts +0 -115
- package/dist/index-BNRh23K9.d.ts +0 -162
- package/dist/index-BYk9oCNf.d.ts +0 -1112
- package/dist/indexes-Dn9hbGQG.d.ts +0 -22
- package/dist/inspect-6WZ-pC7-.js +0 -133
- package/dist/inspect-6WZ-pC7-.js.map +0 -1
- package/dist/log-tail-D98U1JBo.js +0 -522
- package/dist/log-tail-D98U1JBo.js.map +0 -1
- package/dist/maintenance-B4Dki6Ig.js +0 -2157
- package/dist/maintenance-B4Dki6Ig.js.map +0 -1
- package/dist/maintenance-B_e0T99L.d.ts +0 -537
- package/dist/maintenance-C7coQp4c.js +0 -1418
- package/dist/maintenance-C7coQp4c.js.map +0 -1
- package/dist/normalize-rjnZLwS4.js +0 -133
- package/dist/normalize-rjnZLwS4.js.map +0 -1
- package/dist/observability-BmflLCdF.js.map +0 -1
- package/dist/plan-a7PJHBCy.js.map +0 -1
- package/dist/query-rAtXNQQB.js +0 -1773
- package/dist/query-rAtXNQQB.js.map +0 -1
- package/dist/rebuild-index-BVzQSZlm.js +0 -81
- package/dist/rebuild-index-BVzQSZlm.js.map +0 -1
- package/dist/request-u0M51mhJ.js +0 -72
- package/dist/request-u0M51mhJ.js.map +0 -1
- package/dist/restore-R-4rbciV.js +0 -778
- package/dist/restore-R-4rbciV.js.map +0 -1
- package/dist/rolldown-runtime-EAsCxrDo.js +0 -14
- package/dist/runtime-spec-Dsw2-n8S.js.map +0 -1
- package/dist/shared-secret-DgEicd3x.js.map +0 -1
- package/dist/src-BL_JoPTn.js.map +0 -1
- package/dist/src-CYHFDrKz.js +0 -536
- package/dist/src-CYHFDrKz.js.map +0 -1
- package/dist/src-DYZ4H1aF.js +0 -392
- package/dist/src-DYZ4H1aF.js.map +0 -1
- package/dist/subcommand-DoDA-K7d.js.map +0 -1
- package/dist/time-DUqvFMHq.js.map +0 -1
- package/dist/usage-DBV1eQHC.js.map +0 -1
- package/dist/validate-DtljsCh1.js.map +0 -1
- package/dist/wire-izfGZDvr.js.map +0 -1
|
@@ -1,22 +1,27 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import { r as
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
14
|
-
import {
|
|
1
|
+
import { i as withCredentialInvalidation, n as AwsClient, r as S3HttpStorage, t as signHeadersOnly } from "./sigv4-sign-5IUflUD_.js";
|
|
2
|
+
import { i as GcsHttpStorage, n as credentialResolver, t as goog4Signer } from "./goog4-signer-CeLIABoE.js";
|
|
3
|
+
import { r as LocalFsStorage } from "./src-D0MQfvOp.js";
|
|
4
|
+
import { i as isWriteConflict, t as BaerlyError } from "./errors-7Rk1HGCE.js";
|
|
5
|
+
import { r as isDeployedEnv, t as Db } from "./src-Dr9uo3dc.js";
|
|
6
|
+
import { o as uuid } from "./time-DRxTP9iv.js";
|
|
7
|
+
import { a as parseAssumeRoleWithWebIdentity, s as parseStsError } from "./http-transport-DNUM8kU-.js";
|
|
8
|
+
import { n as withNosniff, r as resolveVerifier, t as handleSpecRequest } from "./runtime-spec-B5mg3pHF.js";
|
|
9
|
+
import { n as createRouter, o as Hono, r as mapError, t as MAX_BODY_BYTES } from "./http-Z5rZyYMX.js";
|
|
10
|
+
import { a as flushUnauthorizedAndRespond, c as requestIdFrom, d as configureObservability, i as flushCanonicalLine, l as deriveOutcome, m as errorEnvelope, p as logMaintenanceWarning, r as observableStorage } from "./observability-C-ISCCLE.js";
|
|
11
|
+
import { t as renderDevLanding } from "./dev-landing-CD-si4dW.js";
|
|
12
|
+
import { _ as MAINTENANCE_PROFILE_NODE } from "./constants-D3GSH3tc.js";
|
|
13
|
+
import { t as RequestLedger } from "./ledger-Dj_bGgo0.js";
|
|
14
|
+
import { r as parseMaintenanceEnv } from "./maintenance-DevB6z4e.js";
|
|
15
|
+
import { i as runWithContext, t as createObservabilityContext } from "./context-rlpSnHFA.js";
|
|
16
|
+
import { isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
17
|
+
import { readFile } from "node:fs/promises";
|
|
18
|
+
import { STATUS_CODES, ServerResponse, createServer } from "node:http";
|
|
15
19
|
import { Http2ServerRequest, constants } from "node:http2";
|
|
16
20
|
import { Readable } from "node:stream";
|
|
17
|
-
import {
|
|
18
|
-
|
|
19
|
-
|
|
21
|
+
import { styleText } from "node:util";
|
|
22
|
+
import { createReadStream, existsSync, realpathSync, statSync } from "node:fs";
|
|
23
|
+
import { versions } from "node:process";
|
|
24
|
+
// packages/protocol/src/storage/probe-cas.ts
|
|
20
25
|
/**
|
|
21
26
|
* Runtime probe that a live `Storage` backend honours the conditional
|
|
22
27
|
* writes the protocol depends on. The storage conformance suite asserts
|
|
@@ -34,16 +39,16 @@ const isConflict = (error) => error instanceof BaerlyError && error.code === "Co
|
|
|
34
39
|
* Writes throwaway sentinels under `keyPrefix` and deletes them on
|
|
35
40
|
* the way out (even on failure). Three checks, mirroring the conformance
|
|
36
41
|
* suite:
|
|
37
|
-
* - `ifMatch-stale`: a PUT with a stale `ifMatch` must reject (
|
|
42
|
+
* - `ifMatch-stale`: a PUT with a stale `ifMatch` must reject (WriteConflict).
|
|
38
43
|
* - `ifNoneMatch-exists`: a PUT with `ifNoneMatch:"*"` over an existing
|
|
39
|
-
* key must reject (
|
|
44
|
+
* key must reject (WriteConflict).
|
|
40
45
|
* - `ifNoneMatch-concurrent`: at most one of N concurrent create-if-absent
|
|
41
46
|
* writes on a fresh key wins — the linearizability the writer's log-append
|
|
42
47
|
* commit already relies on (`writer.ts`).
|
|
43
48
|
*
|
|
44
|
-
* A rejected write surfaces as a `BaerlyError` with `code === "
|
|
49
|
+
* A rejected write surfaces as a `BaerlyError` with `code === "WriteConflict"`
|
|
45
50
|
* (the contract `Storage.put` documents); anything else — a resolved
|
|
46
|
-
* promise, or a non-
|
|
51
|
+
* promise, or a non-WriteConflict error — is reported as a failed or
|
|
47
52
|
* inconclusive check rather than thrown.
|
|
48
53
|
*/
|
|
49
54
|
const probeCas = async (storage, opts) => {
|
|
@@ -51,12 +56,13 @@ const probeCas = async (storage, opts) => {
|
|
|
51
56
|
const key = `${prefix}__baerly_cas_probe__/${uuid()}`;
|
|
52
57
|
const enc = new TextEncoder();
|
|
53
58
|
const signal = opts?.signal;
|
|
59
|
+
const staleEtag = opts?.staleEtag ?? "\"baerly-cas-probe-stale\"";
|
|
54
60
|
const checks = [];
|
|
55
61
|
try {
|
|
56
62
|
await storage.put(key, enc.encode("v1"), { signal });
|
|
57
63
|
try {
|
|
58
64
|
await storage.put(key, enc.encode("v2"), {
|
|
59
|
-
ifMatch:
|
|
65
|
+
ifMatch: staleEtag,
|
|
60
66
|
signal
|
|
61
67
|
});
|
|
62
68
|
checks.push({
|
|
@@ -65,14 +71,14 @@ const probeCas = async (storage, opts) => {
|
|
|
65
71
|
detail: "PUT with a stale If-Match was ACCEPTED — backend ignores If-Match (silent lost-update risk)."
|
|
66
72
|
});
|
|
67
73
|
} catch (error) {
|
|
68
|
-
checks.push(
|
|
74
|
+
checks.push(isWriteConflict(error) ? {
|
|
69
75
|
name: "ifMatch-stale",
|
|
70
76
|
ok: true,
|
|
71
|
-
detail: "stale If-Match rejected (
|
|
77
|
+
detail: "stale If-Match rejected (WriteConflict), as required."
|
|
72
78
|
} : {
|
|
73
79
|
name: "ifMatch-stale",
|
|
74
80
|
ok: false,
|
|
75
|
-
detail: `stale If-Match raised a non-
|
|
81
|
+
detail: `stale If-Match raised a non-WriteConflict error: ${error instanceof Error ? error.message : String(error)}`
|
|
76
82
|
});
|
|
77
83
|
}
|
|
78
84
|
try {
|
|
@@ -86,14 +92,14 @@ const probeCas = async (storage, opts) => {
|
|
|
86
92
|
detail: "PUT with If-None-Match:\"*\" over an existing key was ACCEPTED — backend ignores If-None-Match (create-only writes unsafe)."
|
|
87
93
|
});
|
|
88
94
|
} catch (error) {
|
|
89
|
-
checks.push(
|
|
95
|
+
checks.push(isWriteConflict(error) ? {
|
|
90
96
|
name: "ifNoneMatch-exists",
|
|
91
97
|
ok: true,
|
|
92
|
-
detail: "If-None-Match:\"*\" over an existing key rejected (
|
|
98
|
+
detail: "If-None-Match:\"*\" over an existing key rejected (WriteConflict), as required."
|
|
93
99
|
} : {
|
|
94
100
|
name: "ifNoneMatch-exists",
|
|
95
101
|
ok: false,
|
|
96
|
-
detail: `If-None-Match:"*" raised a non-
|
|
102
|
+
detail: `If-None-Match:"*" raised a non-WriteConflict error: ${error instanceof Error ? error.message : String(error)}`
|
|
97
103
|
});
|
|
98
104
|
}
|
|
99
105
|
const raceKey = `${prefix}__baerly_cas_probe__/${uuid()}`;
|
|
@@ -104,23 +110,24 @@ const probeCas = async (storage, opts) => {
|
|
|
104
110
|
signal
|
|
105
111
|
})));
|
|
106
112
|
const winners = outcomes.filter((o) => o.status === "fulfilled").length;
|
|
107
|
-
const transient = outcomes.filter((o) => o.status === "rejected" && !
|
|
113
|
+
const transient = outcomes.filter((o) => o.status === "rejected" && !isWriteConflict(o.reason)).length;
|
|
108
114
|
if (winners > 1) checks.push({
|
|
109
115
|
name: "ifNoneMatch-concurrent",
|
|
110
116
|
ok: false,
|
|
111
117
|
detail: `${winners} of ${RACERS} concurrent create-if-absent writes won (expected at most 1) — create-if-absent is NOT linearizable; the log-append commit would split-brain.`
|
|
112
118
|
});
|
|
113
|
-
else if (winners === 1)
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
119
|
+
else if (winners === 1) {
|
|
120
|
+
if (transient === 0) checks.push({
|
|
121
|
+
name: "ifNoneMatch-concurrent",
|
|
122
|
+
ok: true,
|
|
123
|
+
detail: `exactly one of ${RACERS} concurrent create-if-absent writes won; the rest rejected (WriteConflict), as required.`
|
|
124
|
+
});
|
|
125
|
+
else checks.push({
|
|
126
|
+
name: "ifNoneMatch-concurrent",
|
|
127
|
+
ok: false,
|
|
128
|
+
detail: `exactly one of ${RACERS} concurrent create-if-absent writes won, but ${transient} loser(s) returned a transient non-WriteConflict error — inconclusive; retry for a clean race.`
|
|
129
|
+
});
|
|
130
|
+
} else checks.push({
|
|
124
131
|
name: "ifNoneMatch-concurrent",
|
|
125
132
|
ok: false,
|
|
126
133
|
detail: `no create-if-absent write succeeded across ${RACERS} attempts — inconclusive (transient failure or outage), not a linearizability verdict; retry.`
|
|
@@ -140,9 +147,44 @@ const probeCas = async (storage, opts) => {
|
|
|
140
147
|
checks
|
|
141
148
|
};
|
|
142
149
|
};
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
150
|
+
// packages/adapter-node/src/gcs-admin.ts
|
|
151
|
+
/**
|
|
152
|
+
* GCS bucket-administration probes over the native XML API — read-only
|
|
153
|
+
* config checks that fall outside the four-verb `Storage` interface.
|
|
154
|
+
* Kept in the adapter so GCS wire details (endpoint/URL shape, the
|
|
155
|
+
* `?versioning` sub-resource, the XML response, GOOG4 signing) live
|
|
156
|
+
* behind the adapter boundary rather than leaking into the CLI.
|
|
157
|
+
*/
|
|
158
|
+
/** Case-sensitive per the GCS `?versioning` XML shape; tolerate surrounding whitespace. */
|
|
159
|
+
const VERSIONING_ENABLED_RE = /<Status>\s*Enabled\s*<\/Status>/;
|
|
160
|
+
/**
|
|
161
|
+
* Read a GCS bucket's Object Versioning setting over the native XML API
|
|
162
|
+
* (`GET <endpoint>/<bucket>?versioning`), signed with GOOG4-HMAC-SHA256.
|
|
163
|
+
* Never throws — a non-2xx response or a network error resolves to
|
|
164
|
+
* `{ kind: "inconclusive", reason }`, so callers (e.g. `baerly doctor`)
|
|
165
|
+
* can degrade gracefully instead of aborting.
|
|
166
|
+
*/
|
|
167
|
+
async function gcsVersioningStatus(opts) {
|
|
168
|
+
const endpoint = (opts.endpoint ?? "https://storage.googleapis.com").replace(/\/+$/, "");
|
|
169
|
+
const fetchImpl = opts.fetch ?? globalThis.fetch.bind(globalThis);
|
|
170
|
+
const sign = goog4Signer({ credentials: opts.credentials });
|
|
171
|
+
const url = `${endpoint}/${opts.bucket}?versioning`;
|
|
172
|
+
try {
|
|
173
|
+
const res = await fetchImpl(await sign(new Request(url, { method: "GET" })));
|
|
174
|
+
if (!res.ok) return {
|
|
175
|
+
kind: "inconclusive",
|
|
176
|
+
reason: `HTTP ${res.status}`
|
|
177
|
+
};
|
|
178
|
+
const body = await res.text();
|
|
179
|
+
return VERSIONING_ENABLED_RE.test(body) ? { kind: "enabled" } : { kind: "disabled" };
|
|
180
|
+
} catch (error) {
|
|
181
|
+
return {
|
|
182
|
+
kind: "inconclusive",
|
|
183
|
+
reason: error instanceof Error ? error.message : String(error)
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
// packages/adapter-node/src/credentials/signer.ts
|
|
146
188
|
function buildAwsClient(creds, region) {
|
|
147
189
|
return new AwsClient({
|
|
148
190
|
accessKeyId: creds.accessKeyId,
|
|
@@ -157,45 +199,33 @@ function refreshingSigner(opts) {
|
|
|
157
199
|
const now = opts.now ?? (() => Date.now());
|
|
158
200
|
if (typeof opts.credentials !== "function") {
|
|
159
201
|
const aws = buildAwsClient(opts.credentials, region);
|
|
160
|
-
return (req) => aws
|
|
161
|
-
}
|
|
162
|
-
const
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
try {
|
|
170
|
-
const creds = await provider();
|
|
171
|
-
const aws = buildAwsClient(creds, region);
|
|
172
|
-
cached = {
|
|
173
|
-
aws,
|
|
174
|
-
expiresAt: creds.expiration?.getTime() ?? Number.POSITIVE_INFINITY
|
|
175
|
-
};
|
|
176
|
-
return aws;
|
|
177
|
-
} finally {
|
|
178
|
-
inFlight = null;
|
|
179
|
-
}
|
|
180
|
-
})();
|
|
181
|
-
return inFlight;
|
|
182
|
-
};
|
|
183
|
-
return async (req) => {
|
|
184
|
-
return (await resolve()).sign(req);
|
|
202
|
+
return (req) => signHeadersOnly(aws, req);
|
|
203
|
+
}
|
|
204
|
+
const resolve = credentialResolver(opts.credentials, now, (creds) => buildAwsClient(creds, region));
|
|
205
|
+
const signedBy = /* @__PURE__ */ new WeakMap();
|
|
206
|
+
const sign = async (req) => {
|
|
207
|
+
const aws = await resolve();
|
|
208
|
+
const signed = await signHeadersOnly(aws, req);
|
|
209
|
+
signedBy.set(signed, aws);
|
|
210
|
+
return signed;
|
|
185
211
|
};
|
|
212
|
+
return Object.assign(sign, { invalidate(signed) {
|
|
213
|
+
const aws = signedBy.get(signed);
|
|
214
|
+
if (aws !== void 0) resolve.invalidate(aws);
|
|
215
|
+
} });
|
|
186
216
|
}
|
|
187
|
-
|
|
188
|
-
//#region packages/adapter-node/src/storage-factories.ts
|
|
217
|
+
// packages/adapter-node/src/storage-factories.ts
|
|
189
218
|
function buildS3Storage(opts) {
|
|
190
219
|
const sign = refreshingSigner({
|
|
191
220
|
region: opts.region,
|
|
192
221
|
credentials: opts.credentials
|
|
193
222
|
});
|
|
194
|
-
|
|
223
|
+
const storage = new S3HttpStorage({
|
|
195
224
|
endpoint: opts.endpoint,
|
|
196
225
|
bucket: opts.bucket,
|
|
197
226
|
sign
|
|
198
227
|
});
|
|
228
|
+
return sign.invalidate === void 0 ? storage : withCredentialInvalidation(storage, sign.invalidate);
|
|
199
229
|
}
|
|
200
230
|
/**
|
|
201
231
|
* AWS S3 `Storage` factory. Wraps `S3HttpStorage` with the standard
|
|
@@ -298,20 +328,19 @@ function minioStorage(opts) {
|
|
|
298
328
|
});
|
|
299
329
|
}
|
|
300
330
|
/**
|
|
301
|
-
* Google Cloud Storage `Storage` factory
|
|
302
|
-
* at `https://storage.googleapis.com`.
|
|
303
|
-
*
|
|
304
|
-
*
|
|
305
|
-
* `
|
|
331
|
+
* Google Cloud Storage `Storage` factory over the native GCS XML API
|
|
332
|
+
* at `https://storage.googleapis.com`. Wraps {@link GcsHttpStorage} with
|
|
333
|
+
* a GOOG4-HMAC-SHA256 signer, driving GCS's own generation-precondition
|
|
334
|
+
* conditional writes (`x-goog-if-generation-match: 0` for create-if-absent,
|
|
335
|
+
* `x-goog-if-generation-match: <generation>` for compare-and-swap), which
|
|
336
|
+
* return `412` on a lost write. The object `generation` is carried verbatim
|
|
337
|
+
* as the opaque `Storage` etag. This is the sanctioned GCS path — the
|
|
338
|
+
* S3-interop endpoint treats `If-Match`/`If-None-Match` as read-scoped only
|
|
339
|
+
* and cannot linearize the log, so it is not supported.
|
|
306
340
|
*
|
|
307
|
-
* GCS
|
|
308
|
-
*
|
|
309
|
-
*
|
|
310
|
-
* read-only (native conditional writes use `x-goog-if-generation-match`).
|
|
311
|
-
* Whether GCS's interop layer enforces S3-style conditional *writes* is
|
|
312
|
-
* unverified — run `baerly doctor --bucket=<your-gcs-bucket>` before
|
|
313
|
-
* relying on it; a backend that fails the CAS probe is not a safe baerly
|
|
314
|
-
* store. See ADR-002.
|
|
341
|
+
* Authentication uses GCS HMAC keys (Console → Settings → Interoperability)
|
|
342
|
+
* — mint an interop key, put the HMAC access key in `credentials.accessKeyId`
|
|
343
|
+
* and the HMAC secret in `credentials.secretAccessKey`.
|
|
315
344
|
*
|
|
316
345
|
* @example
|
|
317
346
|
* ```ts
|
|
@@ -327,15 +356,14 @@ function minioStorage(opts) {
|
|
|
327
356
|
* ```
|
|
328
357
|
*/
|
|
329
358
|
function gcsStorage(opts) {
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
region: "auto",
|
|
359
|
+
const sign = goog4Signer({ credentials: opts.credentials });
|
|
360
|
+
return new GcsHttpStorage({
|
|
333
361
|
bucket: opts.bucket,
|
|
334
|
-
|
|
362
|
+
sign,
|
|
363
|
+
...opts.endpoint !== void 0 && { endpoint: opts.endpoint }
|
|
335
364
|
});
|
|
336
365
|
}
|
|
337
|
-
|
|
338
|
-
//#region packages/adapter-node/src/local-fs-storage.ts
|
|
366
|
+
// packages/adapter-node/src/local-fs-storage.ts
|
|
339
367
|
/**
|
|
340
368
|
* Zero-config local `Storage` for single-node dev / self-hosted runs.
|
|
341
369
|
* Persists to the filesystem (content-addressed, atomic writes), so data
|
|
@@ -343,10 +371,12 @@ function gcsStorage(opts) {
|
|
|
343
371
|
* and lost on exit.
|
|
344
372
|
*
|
|
345
373
|
* NOT for multi-instance production: `LocalFsStorage`'s `ifMatch` CAS is
|
|
346
|
-
*
|
|
347
|
-
* atomic
|
|
348
|
-
*
|
|
349
|
-
*
|
|
374
|
+
* serialized within one process only, so a `current.json` CAS-advance is
|
|
375
|
+
* not atomic against a second process on the same directory (see its class
|
|
376
|
+
* JSDoc). Every call here returns a fresh instance, which is fine — the
|
|
377
|
+
* lock is keyed by resolved root, so instances sharing a directory share
|
|
378
|
+
* it. For horizontally-scaled deploys use `s3Storage` / `r2Storage`, whose
|
|
379
|
+
* cross-process guarantee the no-lease maintenance fold relies on.
|
|
350
380
|
*
|
|
351
381
|
* @example
|
|
352
382
|
* ```ts
|
|
@@ -358,8 +388,7 @@ function gcsStorage(opts) {
|
|
|
358
388
|
* ```
|
|
359
389
|
*/
|
|
360
390
|
const localFsStorage = (opts) => new LocalFsStorage({ root: opts?.dataDir ?? process.env["BAERLY_DATA_DIR"] ?? resolve(process.cwd(), ".baerly-data") });
|
|
361
|
-
|
|
362
|
-
//#region packages/adapter-node/src/resolve-storage.ts
|
|
391
|
+
// packages/adapter-node/src/resolve-storage.ts
|
|
363
392
|
/**
|
|
364
393
|
* Choose a Node `Storage` backend from environment variables, in priority
|
|
365
394
|
* order:
|
|
@@ -436,8 +465,7 @@ const resolveStorageFromEnv = (env = process.env) => {
|
|
|
436
465
|
"use SQLite + Litestream for a single-instance app."
|
|
437
466
|
].join("\n"));
|
|
438
467
|
};
|
|
439
|
-
|
|
440
|
-
//#region packages/adapter-node/src/assert-storage-reachable.ts
|
|
468
|
+
// packages/adapter-node/src/assert-storage-reachable.ts
|
|
441
469
|
/**
|
|
442
470
|
* Boot-time readiness check: confirm a live `Storage` backend is both
|
|
443
471
|
* reachable and honours the conditional writes the protocol depends on.
|
|
@@ -475,12 +503,14 @@ const assertStorageReachable = async (storage, opts) => {
|
|
|
475
503
|
try {
|
|
476
504
|
result = await probeCas(storage, opts);
|
|
477
505
|
} catch (error) {
|
|
478
|
-
throw new BaerlyError("NetworkError", `Storage readiness check failed: the backend could not be reached. Verify the bucket name, region/endpoint, and credentials. Cause: ${error instanceof Error ? error.message : String(error)}`, error);
|
|
506
|
+
throw new BaerlyError("NetworkError", `Storage readiness check failed: the backend could not be reached. Verify the bucket name, region/endpoint, and credentials. Cause: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
507
|
+
}
|
|
508
|
+
if (!result.ok) {
|
|
509
|
+
const failed = result.checks.filter((c) => !c.ok).map((c) => ` - ${c.name}: ${c.detail}`).join("\n");
|
|
510
|
+
throw new BaerlyError("InvalidConfig", `Storage readiness check failed — the backend does not honour the conditional writes baerly requires (data corruption risk). Use a store that honours them: AWS S3 or Cloudflare R2 (If-Match / If-None-Match), or native Google Cloud Storage via \`gcsStorage\` (x-goog-if-generation-match). GCS's S3-interop endpoint is not supported.\n${failed}`);
|
|
479
511
|
}
|
|
480
|
-
if (!result.ok) throw new BaerlyError("InvalidConfig", `Storage readiness check failed — the backend does not honour the conditional writes baerly requires (data corruption risk). Use a fully S3-conditional-compatible store:\n${result.checks.filter((c) => !c.ok).map((c) => ` - ${c.name}: ${c.detail}`).join("\n")}`);
|
|
481
512
|
};
|
|
482
|
-
|
|
483
|
-
//#region packages/adapter-node/src/credentials/token-file.ts
|
|
513
|
+
// packages/adapter-node/src/credentials/token-file.ts
|
|
484
514
|
/**
|
|
485
515
|
* Read and validate an EKS-projected service-account token file, shared by
|
|
486
516
|
* {@link fromWebIdentity} and {@link fromEksPodIdentity}. Reads the file,
|
|
@@ -489,7 +519,7 @@ const assertStorageReachable = async (storage, opts) => {
|
|
|
489
519
|
*
|
|
490
520
|
* A missing / unreadable / empty projected token is a deploy misconfig, not a
|
|
491
521
|
* transient fault — so every failure is `InvalidConfig`, which short-circuits
|
|
492
|
-
* the retry loop (see `
|
|
522
|
+
* the retry loop (see `PERMANENT_STORAGE_ERROR_CODES` in `@baerly/protocol`'s `storage/retry.ts`) instead of
|
|
493
523
|
* hammering the credential source. Error messages name the specific env var
|
|
494
524
|
* so the misconfig is debuggable.
|
|
495
525
|
*/
|
|
@@ -504,10 +534,33 @@ async function readProjectedToken(doReadFile, tokenPath, ctx) {
|
|
|
504
534
|
if (token === "") throw new BaerlyError("InvalidConfig", `${ctx.provider}: ${ctx.envVar} (${tokenPath}) is empty`);
|
|
505
535
|
return token;
|
|
506
536
|
}
|
|
507
|
-
|
|
508
|
-
//#region packages/adapter-node/src/credentials/from-eks-pod-identity.ts
|
|
537
|
+
// packages/adapter-node/src/credentials/from-eks-pod-identity.ts
|
|
509
538
|
const FETCH_TIMEOUT_MS$1 = 2e3;
|
|
510
539
|
/**
|
|
540
|
+
* Hosts the agent can live on: the ECS agent, the EKS Pod Identity agent
|
|
541
|
+
* (IPv4 and IPv6), and loopback. `127.0.0.0/8` is matched separately.
|
|
542
|
+
* WHATWG URL parsing canonicalizes the hostname first, so alternate
|
|
543
|
+
* spellings (`[0:0:0:0:0:0:0:1]`, `2130706433`) compare equal.
|
|
544
|
+
*/
|
|
545
|
+
const AGENT_HOSTS = /* @__PURE__ */ new Set([
|
|
546
|
+
"169.254.170.2",
|
|
547
|
+
"169.254.170.23",
|
|
548
|
+
"[fd00:ec2::23]",
|
|
549
|
+
"localhost",
|
|
550
|
+
"[::1]"
|
|
551
|
+
]);
|
|
552
|
+
const LOOPBACK_V4 = /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
|
|
553
|
+
function isAgentUri(uri) {
|
|
554
|
+
let url;
|
|
555
|
+
try {
|
|
556
|
+
url = new URL(uri);
|
|
557
|
+
} catch {
|
|
558
|
+
return false;
|
|
559
|
+
}
|
|
560
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") return false;
|
|
561
|
+
return AGENT_HOSTS.has(url.hostname) || LOOPBACK_V4.test(url.hostname);
|
|
562
|
+
}
|
|
563
|
+
/**
|
|
511
564
|
* Resolve AWS credentials from the EKS Pod Identity agent (the 2023
|
|
512
565
|
* successor to IRSA). The agent runs on each EKS node and exchanges
|
|
513
566
|
* the pod's projected service-account token for short-lived AWS
|
|
@@ -521,6 +574,11 @@ const FETCH_TIMEOUT_MS$1 = 2e3;
|
|
|
521
574
|
*
|
|
522
575
|
* Both are required. Agent should respond instantly on the node-local
|
|
523
576
|
* link — 2 s timeout protects against hangs.
|
|
577
|
+
*
|
|
578
|
+
* The URI must name the agent: loopback, or the ECS / EKS link-local
|
|
579
|
+
* addresses (the AWS SDK's container-credentials allow-list). Anything
|
|
580
|
+
* else throws `InvalidConfig` before the token file is read, so a
|
|
581
|
+
* misconfigured or injected env var never sends the token off-node.
|
|
524
582
|
*/
|
|
525
583
|
function fromEksPodIdentity(opts = {}) {
|
|
526
584
|
const doFetch = opts.fetch ?? fetch;
|
|
@@ -529,6 +587,7 @@ function fromEksPodIdentity(opts = {}) {
|
|
|
529
587
|
const uri = process.env["AWS_CONTAINER_CREDENTIALS_FULL_URI"];
|
|
530
588
|
const tokenPath = process.env["AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE"];
|
|
531
589
|
if (uri === void 0 || uri === "") throw new BaerlyError("InvalidConfig", "fromEksPodIdentity: AWS_CONTAINER_CREDENTIALS_FULL_URI not set");
|
|
590
|
+
if (!isAgentUri(uri)) throw new BaerlyError("InvalidConfig", "fromEksPodIdentity: AWS_CONTAINER_CREDENTIALS_FULL_URI must be an http(s) URL on loopback, 169.254.170.2, 169.254.170.23 or [fd00:ec2::23]");
|
|
532
591
|
if (tokenPath === void 0 || tokenPath === "") throw new BaerlyError("InvalidConfig", "fromEksPodIdentity: AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE not set");
|
|
533
592
|
const token = await readProjectedToken(doReadFile, tokenPath, {
|
|
534
593
|
provider: "fromEksPodIdentity",
|
|
@@ -564,8 +623,7 @@ function fromEksPodIdentity(opts = {}) {
|
|
|
564
623
|
};
|
|
565
624
|
};
|
|
566
625
|
}
|
|
567
|
-
|
|
568
|
-
//#region packages/adapter-node/src/credentials/from-web-identity.ts
|
|
626
|
+
// packages/adapter-node/src/credentials/from-web-identity.ts
|
|
569
627
|
const FETCH_TIMEOUT_MS = 5e3;
|
|
570
628
|
const DEFAULT_SESSION_NAME = "baerly-storage";
|
|
571
629
|
/**
|
|
@@ -641,8 +699,7 @@ function fromWebIdentity(opts = {}) {
|
|
|
641
699
|
};
|
|
642
700
|
};
|
|
643
701
|
}
|
|
644
|
-
|
|
645
|
-
//#region packages/adapter-node/src/credentials/from-eks.ts
|
|
702
|
+
// packages/adapter-node/src/credentials/from-eks.ts
|
|
646
703
|
/**
|
|
647
704
|
* Resolve AWS credentials on EKS regardless of which identity mechanism the
|
|
648
705
|
* cluster uses, so callers don't have to know. EKS injects credentials one of
|
|
@@ -669,27 +726,185 @@ function fromEks(opts = {}) {
|
|
|
669
726
|
throw new BaerlyError("InvalidConfig", "fromEks: no EKS credentials in env — set AWS_CONTAINER_CREDENTIALS_FULL_URI (Pod Identity) or AWS_WEB_IDENTITY_TOKEN_FILE + AWS_ROLE_ARN (IRSA)");
|
|
670
727
|
};
|
|
671
728
|
}
|
|
672
|
-
|
|
673
|
-
//#region node_modules/.pnpm/@hono+node-server@2.0.6_hono@4.12.27/node_modules/@hono/node-server/dist/index.mjs
|
|
729
|
+
// node_modules/.pnpm/@hono+node-server@2.1.8_hono@4.13.19/node_modules/@hono/node-server/dist/index.mjs
|
|
674
730
|
var RequestError = class extends Error {
|
|
675
731
|
constructor(message, options) {
|
|
676
732
|
super(message, options);
|
|
677
733
|
this.name = "RequestError";
|
|
678
734
|
}
|
|
679
735
|
};
|
|
736
|
+
const nonJoinedHeaders = /* @__PURE__ */ new Set([
|
|
737
|
+
"age",
|
|
738
|
+
"authorization",
|
|
739
|
+
"content-length",
|
|
740
|
+
"content-type",
|
|
741
|
+
"etag",
|
|
742
|
+
"expires",
|
|
743
|
+
"from",
|
|
744
|
+
"host",
|
|
745
|
+
"if-modified-since",
|
|
746
|
+
"if-unmodified-since",
|
|
747
|
+
"last-modified",
|
|
748
|
+
"location",
|
|
749
|
+
"max-forwards",
|
|
750
|
+
"proxy-authorization",
|
|
751
|
+
"referer",
|
|
752
|
+
"retry-after",
|
|
753
|
+
"server",
|
|
754
|
+
"user-agent"
|
|
755
|
+
]);
|
|
756
|
+
const validHeaderName = /^[!#$%&'*+\-.^_`|~\dA-Za-z]+$/;
|
|
757
|
+
const isHttpWhitespace = (code) => code === 9 || code === 10 || code === 13 || code === 32;
|
|
758
|
+
const normalizeHeaderValue = (value) => {
|
|
759
|
+
if (!isHttpWhitespace(value.charCodeAt(0)) && !isHttpWhitespace(value.charCodeAt(value.length - 1))) return value;
|
|
760
|
+
let start = 0;
|
|
761
|
+
let end = value.length;
|
|
762
|
+
while (start < end && isHttpWhitespace(value.charCodeAt(start))) start++;
|
|
763
|
+
while (end > start && isHttpWhitespace(value.charCodeAt(end - 1))) end--;
|
|
764
|
+
return value.slice(start, end);
|
|
765
|
+
};
|
|
766
|
+
const forbiddenHeaderValue = /[\0\r\n]/;
|
|
767
|
+
const GlobalHeaders = globalThis.Headers;
|
|
768
|
+
const materializeHeaders = (rawHeaders, HeadersCtor = GlobalHeaders) => {
|
|
769
|
+
const headers = new HeadersCtor();
|
|
770
|
+
for (let i = 0; i < rawHeaders.length; i += 2) {
|
|
771
|
+
const name = rawHeaders[i];
|
|
772
|
+
if (!name.startsWith(":")) headers.append(name, rawHeaders[i + 1]);
|
|
773
|
+
}
|
|
774
|
+
return headers;
|
|
775
|
+
};
|
|
776
|
+
var RequestHeaders = class {
|
|
777
|
+
#incoming;
|
|
778
|
+
#rawHeaders;
|
|
779
|
+
#headers;
|
|
780
|
+
#invalidValue;
|
|
781
|
+
constructor(incoming) {
|
|
782
|
+
this.#incoming = incoming;
|
|
783
|
+
if (incoming instanceof Http2ServerRequest) this.#rawHeaders = incoming.rawHeaders.slice();
|
|
784
|
+
}
|
|
785
|
+
get #lazyRawHeaders() {
|
|
786
|
+
return this.#rawHeaders ??= this.#incoming.rawHeaders.slice();
|
|
787
|
+
}
|
|
788
|
+
get #native() {
|
|
789
|
+
if (!this.#headers) {
|
|
790
|
+
this.#headers = materializeHeaders(this.#lazyRawHeaders);
|
|
791
|
+
this.#rawHeaders = void 0;
|
|
792
|
+
}
|
|
793
|
+
return this.#headers;
|
|
794
|
+
}
|
|
795
|
+
#normalizedName(name) {
|
|
796
|
+
if (typeof name !== "string") return;
|
|
797
|
+
if (!validHeaderName.test(name)) throw new TypeError(`Invalid header name: ${name}`);
|
|
798
|
+
return name.toLowerCase();
|
|
799
|
+
}
|
|
800
|
+
#lookupHttp1(lowerName) {
|
|
801
|
+
const headers = this.#incoming instanceof Http2ServerRequest ? void 0 : this.#incoming.headers;
|
|
802
|
+
if (!headers || nonJoinedHeaders.has(lowerName) || lowerName === "set-cookie" || lowerName === "__proto__") return;
|
|
803
|
+
if (!Object.hasOwn(headers, lowerName)) return null;
|
|
804
|
+
const rawValue = headers[lowerName];
|
|
805
|
+
if (typeof rawValue === "string") {
|
|
806
|
+
const value = normalizeHeaderValue(rawValue);
|
|
807
|
+
return forbiddenHeaderValue.test(value) ? void 0 : value;
|
|
808
|
+
}
|
|
809
|
+
}
|
|
810
|
+
#lookup(rawHeaders, lowerName) {
|
|
811
|
+
const separator = lowerName === "cookie" ? "; " : ", ";
|
|
812
|
+
let value = null;
|
|
813
|
+
for (let i = 0; i < rawHeaders.length; i += 2) {
|
|
814
|
+
const rawName = rawHeaders[i];
|
|
815
|
+
if (rawName.length === lowerName.length && rawName.toLowerCase() === lowerName) {
|
|
816
|
+
const rawValue = normalizeHeaderValue(rawHeaders[i + 1]);
|
|
817
|
+
if (forbiddenHeaderValue.test(rawValue)) {
|
|
818
|
+
this.#invalidValue = true;
|
|
819
|
+
return;
|
|
820
|
+
}
|
|
821
|
+
value = value === null ? rawValue : value + separator + rawValue;
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
return value;
|
|
825
|
+
}
|
|
826
|
+
append(name, value) {
|
|
827
|
+
this.#native.append(name, value);
|
|
828
|
+
}
|
|
829
|
+
delete(name) {
|
|
830
|
+
this.#native.delete(name);
|
|
831
|
+
}
|
|
832
|
+
get(name) {
|
|
833
|
+
const lowerName = this.#normalizedName(name);
|
|
834
|
+
if (lowerName && !this.#headers && !this.#invalidValue) {
|
|
835
|
+
const http1Value = this.#lookupHttp1(lowerName);
|
|
836
|
+
if (http1Value !== void 0) return http1Value;
|
|
837
|
+
const value = this.#lookup(this.#lazyRawHeaders, lowerName);
|
|
838
|
+
if (value !== void 0) return value;
|
|
839
|
+
}
|
|
840
|
+
return this.#native.get(name);
|
|
841
|
+
}
|
|
842
|
+
has(name) {
|
|
843
|
+
const lowerName = this.#normalizedName(name);
|
|
844
|
+
if (lowerName && !this.#headers && !this.#invalidValue) {
|
|
845
|
+
const http1Value = this.#lookupHttp1(lowerName);
|
|
846
|
+
if (http1Value !== void 0) return http1Value !== null;
|
|
847
|
+
const value = this.#lookup(this.#lazyRawHeaders, lowerName);
|
|
848
|
+
if (value !== void 0) return value !== null;
|
|
849
|
+
}
|
|
850
|
+
return this.#native.has(name);
|
|
851
|
+
}
|
|
852
|
+
set(name, value) {
|
|
853
|
+
this.#native.set(name, value);
|
|
854
|
+
}
|
|
855
|
+
getSetCookie() {
|
|
856
|
+
return this.#native.getSetCookie();
|
|
857
|
+
}
|
|
858
|
+
keys() {
|
|
859
|
+
return this.#native.keys();
|
|
860
|
+
}
|
|
861
|
+
values() {
|
|
862
|
+
return this.#native.values();
|
|
863
|
+
}
|
|
864
|
+
entries() {
|
|
865
|
+
return this.#native.entries();
|
|
866
|
+
}
|
|
867
|
+
forEach(callback, thisArg) {
|
|
868
|
+
this.#native.forEach((value, key) => {
|
|
869
|
+
callback.call(thisArg, value, key, this);
|
|
870
|
+
});
|
|
871
|
+
}
|
|
872
|
+
[Symbol.iterator]() {
|
|
873
|
+
return this.entries();
|
|
874
|
+
}
|
|
875
|
+
};
|
|
876
|
+
Object.defineProperty(RequestHeaders.prototype, Symbol.for("nodejs.util.inspect.custom"), { value: function(depth, options, inspectFn) {
|
|
877
|
+
return `Headers (lightweight) ${inspectFn(Object.fromEntries(this), {
|
|
878
|
+
...options,
|
|
879
|
+
depth: depth == null ? null : depth - 1
|
|
880
|
+
})}`;
|
|
881
|
+
} });
|
|
882
|
+
Object.setPrototypeOf(RequestHeaders.prototype, GlobalHeaders.prototype);
|
|
883
|
+
const newHeadersFromIncoming = (incoming) => globalThis.Headers === GlobalHeaders ? new RequestHeaders(incoming) : materializeHeaders(incoming.rawHeaders, globalThis.Headers);
|
|
680
884
|
const reValidRequestUrl = /^\/[!#$&-;=?-\[\]_a-z~]*$/;
|
|
681
885
|
const reDotSegment = /\/\.\.?(?:[/?#]|$)/;
|
|
682
886
|
const reValidHost = /^[a-z0-9._-]+(?::(?:[1-5]\d{3,4}|[6-9]\d{3}))?$/;
|
|
887
|
+
const validateRequestTarget = (target) => {
|
|
888
|
+
const backslash = target.indexOf("\\");
|
|
889
|
+
if (backslash !== -1) {
|
|
890
|
+
const query = target.indexOf("?");
|
|
891
|
+
if (query === -1 || backslash < query) throw new RequestError("Backslash in request path");
|
|
892
|
+
}
|
|
893
|
+
};
|
|
683
894
|
const buildUrl = (scheme, host, incomingUrl) => {
|
|
684
895
|
const url = `${scheme}://${host}${incomingUrl}`;
|
|
685
896
|
if (!reValidHost.test(host)) {
|
|
897
|
+
validateRequestTarget(incomingUrl);
|
|
686
898
|
const urlObj = new URL(url);
|
|
687
899
|
if (urlObj.hostname.length !== host.length && urlObj.hostname !== (host.includes(":") ? host.replace(/:\d+$/, "") : host).toLowerCase()) throw new RequestError("Invalid host header");
|
|
688
900
|
return urlObj.href;
|
|
689
901
|
} else if (incomingUrl.length === 0) return url + "/";
|
|
690
902
|
else {
|
|
691
903
|
if (incomingUrl.charCodeAt(0) !== 47) throw new RequestError("Invalid URL");
|
|
692
|
-
if (!reValidRequestUrl.test(incomingUrl) || reDotSegment.test(incomingUrl))
|
|
904
|
+
if (!reValidRequestUrl.test(incomingUrl) || reDotSegment.test(incomingUrl)) {
|
|
905
|
+
validateRequestTarget(incomingUrl);
|
|
906
|
+
return new URL(url).href;
|
|
907
|
+
}
|
|
693
908
|
return url;
|
|
694
909
|
}
|
|
695
910
|
};
|
|
@@ -709,16 +924,55 @@ var Request$1 = class extends GlobalRequest {
|
|
|
709
924
|
super(input, options);
|
|
710
925
|
}
|
|
711
926
|
};
|
|
712
|
-
const
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
927
|
+
const wrapBodyStream = Symbol("wrapBodyStream");
|
|
928
|
+
const byteExactEncodings = /* @__PURE__ */ new Set([
|
|
929
|
+
"latin1",
|
|
930
|
+
"binary",
|
|
931
|
+
"hex",
|
|
932
|
+
"base64",
|
|
933
|
+
"base64url"
|
|
934
|
+
]);
|
|
935
|
+
const isByteExactEncoding = (encoding) => encoding === null || byteExactEncodings.has(encoding);
|
|
936
|
+
const bodyBufferedBeforeDisconnectKey = Symbol("bodyBufferedBeforeDisconnect");
|
|
937
|
+
const bodyBufferedLengthBeforeDisconnectKey = Symbol("bodyBufferedLengthBeforeDisconnect");
|
|
938
|
+
const toBufferChunk = (chunk, encoding) => Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding ?? "utf8");
|
|
939
|
+
const isRecoverableDisconnectedIncoming = (incoming) => !(incoming instanceof Http2ServerRequest) && !!incoming.complete && !!incoming.readableAborted && typeof incoming.read === "function" && isByteExactEncoding(incoming.readableEncoding);
|
|
940
|
+
const recordBodyBufferedBeforeDisconnect = (incoming) => {
|
|
941
|
+
if (incoming.readableDidRead || !isRecoverableDisconnectedIncoming(incoming)) return;
|
|
942
|
+
const incomingWithRecovery = incoming;
|
|
943
|
+
incomingWithRecovery[bodyBufferedLengthBeforeDisconnectKey] ??= incoming.readableLength;
|
|
944
|
+
};
|
|
945
|
+
const readBodyBufferedBeforeDisconnect = (incoming, chunks) => {
|
|
946
|
+
if (incoming.readableDidRead && !chunks || !isRecoverableDisconnectedIncoming(incoming)) return;
|
|
947
|
+
const incomingWithRecovery = incoming;
|
|
948
|
+
if (incomingWithRecovery[bodyBufferedBeforeDisconnectKey] !== void 0) return incomingWithRecovery[bodyBufferedBeforeDisconnectKey];
|
|
949
|
+
let result;
|
|
950
|
+
const errored = incoming.errored;
|
|
951
|
+
if (errored && errored.code !== "ECONNRESET") result = errored;
|
|
952
|
+
else if (incomingWithRecovery[bodyBufferedLengthBeforeDisconnectKey] !== void 0 && incoming.readableLength !== incomingWithRecovery[bodyBufferedLengthBeforeDisconnectKey]) result = newBodyUnusableError();
|
|
953
|
+
else {
|
|
954
|
+
const bodyChunks = chunks ?? [];
|
|
955
|
+
const chunk = incoming.read();
|
|
956
|
+
if (chunk !== null) bodyChunks.push(toBufferChunk(chunk, incoming.readableEncoding));
|
|
957
|
+
const buffer = bodyChunks.length === 1 ? bodyChunks[0] : Buffer.concat(bodyChunks);
|
|
958
|
+
result = buffer;
|
|
959
|
+
const contentLength = incoming.headers["content-length"];
|
|
960
|
+
if (typeof contentLength === "string" && /^\d+$/.test(contentLength)) {
|
|
961
|
+
const expectedLength = Number(contentLength);
|
|
962
|
+
if (Number.isSafeInteger(expectedLength) && buffer.length !== expectedLength) result = newBodyUnusableError();
|
|
963
|
+
}
|
|
718
964
|
}
|
|
719
|
-
|
|
965
|
+
incomingWithRecovery[bodyBufferedBeforeDisconnectKey] = result;
|
|
966
|
+
return result;
|
|
967
|
+
};
|
|
968
|
+
const enqueueBufferedBody = (controller, buffered) => {
|
|
969
|
+
if (buffered instanceof Error) {
|
|
970
|
+
controller.error(buffered);
|
|
971
|
+
return;
|
|
972
|
+
}
|
|
973
|
+
if (buffered.length > 0) controller.enqueue(buffered);
|
|
974
|
+
controller.close();
|
|
720
975
|
};
|
|
721
|
-
const wrapBodyStream = Symbol("wrapBodyStream");
|
|
722
976
|
const newRequestFromIncoming = (method, url, headers, incoming, abortController) => {
|
|
723
977
|
const init = {
|
|
724
978
|
method,
|
|
@@ -741,6 +995,13 @@ const newRequestFromIncoming = (method, url, headers, incoming, abortController)
|
|
|
741
995
|
let reader;
|
|
742
996
|
init.body = new ReadableStream({ async pull(controller) {
|
|
743
997
|
try {
|
|
998
|
+
if (!reader) {
|
|
999
|
+
const buffered = readBodyBufferedBeforeDisconnect(incoming);
|
|
1000
|
+
if (buffered !== void 0) {
|
|
1001
|
+
enqueueBufferedBody(controller, buffered);
|
|
1002
|
+
return;
|
|
1003
|
+
}
|
|
1004
|
+
}
|
|
744
1005
|
reader ||= Readable.toWeb(incoming).getReader();
|
|
745
1006
|
const { done, value } = await reader.read();
|
|
746
1007
|
if (done) controller.close();
|
|
@@ -749,7 +1010,13 @@ const newRequestFromIncoming = (method, url, headers, incoming, abortController)
|
|
|
749
1010
|
controller.error(error);
|
|
750
1011
|
}
|
|
751
1012
|
} });
|
|
752
|
-
} else
|
|
1013
|
+
} else {
|
|
1014
|
+
const buffered = readBodyBufferedBeforeDisconnect(incoming);
|
|
1015
|
+
if (buffered !== void 0) init.body = new ReadableStream({ start(controller) {
|
|
1016
|
+
enqueueBufferedBody(controller, buffered);
|
|
1017
|
+
} });
|
|
1018
|
+
else init.body = Readable.toWeb(incoming);
|
|
1019
|
+
}
|
|
753
1020
|
return new Request$1(url, init);
|
|
754
1021
|
};
|
|
755
1022
|
const getRequestCache = Symbol("getRequestCache");
|
|
@@ -791,8 +1058,10 @@ const normalizeIncomingMethod = (method) => {
|
|
|
791
1058
|
case "GET":
|
|
792
1059
|
case "HEAD":
|
|
793
1060
|
case "OPTIONS":
|
|
1061
|
+
case "PATCH":
|
|
794
1062
|
case "POST":
|
|
795
|
-
case "PUT":
|
|
1063
|
+
case "PUT":
|
|
1064
|
+
case "QUERY": return method;
|
|
796
1065
|
}
|
|
797
1066
|
const upper = method.toUpperCase();
|
|
798
1067
|
switch (upper) {
|
|
@@ -837,11 +1106,23 @@ const readRawBodyIfAvailable = (request) => {
|
|
|
837
1106
|
const incoming = request[incomingKey];
|
|
838
1107
|
if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) return incoming.rawBody;
|
|
839
1108
|
};
|
|
1109
|
+
const normalizeAbortError = (request, incoming) => {
|
|
1110
|
+
if (incoming.errored) return incoming.errored;
|
|
1111
|
+
const reason = request[abortReasonKey];
|
|
1112
|
+
if (reason !== void 0) return reason instanceof Error ? reason : new Error(String(reason));
|
|
1113
|
+
return /* @__PURE__ */ new Error("Client connection prematurely closed.");
|
|
1114
|
+
};
|
|
840
1115
|
const readBodyDirect = (request) => {
|
|
841
1116
|
if (request[bodyBufferKey]) return Promise.resolve(request[bodyBufferKey]);
|
|
842
1117
|
if (request[bodyReadPromiseKey]) return request[bodyReadPromiseKey];
|
|
843
1118
|
const incoming = request[incomingKey];
|
|
844
|
-
if (
|
|
1119
|
+
if (incoming.readableDidRead) return rejectBodyUnusable();
|
|
1120
|
+
const buffered = readBodyBufferedBeforeDisconnect(incoming);
|
|
1121
|
+
if (buffered !== void 0) {
|
|
1122
|
+
if (buffered instanceof Error) return Promise.reject(buffered);
|
|
1123
|
+
request[bodyBufferKey] = buffered;
|
|
1124
|
+
return Promise.resolve(buffered);
|
|
1125
|
+
}
|
|
845
1126
|
const promise = new Promise((resolve, reject) => {
|
|
846
1127
|
const chunks = [];
|
|
847
1128
|
let settled = false;
|
|
@@ -851,8 +1132,22 @@ const readBodyDirect = (request) => {
|
|
|
851
1132
|
cleanup();
|
|
852
1133
|
callback();
|
|
853
1134
|
};
|
|
1135
|
+
const recoverCompleteBodyAfterDisconnect = (error) => {
|
|
1136
|
+
const streamError = incoming.errored ?? error;
|
|
1137
|
+
if (!isRecoverableDisconnectedIncoming(incoming) || streamError && streamError.code !== "ECONNRESET") return false;
|
|
1138
|
+
finish(() => {
|
|
1139
|
+
const recovered = readBodyBufferedBeforeDisconnect(incoming, chunks);
|
|
1140
|
+
if (recovered instanceof Error) reject(recovered);
|
|
1141
|
+
else if (recovered === void 0) reject(error ?? normalizeAbortError(request, incoming));
|
|
1142
|
+
else {
|
|
1143
|
+
request[bodyBufferKey] = recovered;
|
|
1144
|
+
resolve(recovered);
|
|
1145
|
+
}
|
|
1146
|
+
});
|
|
1147
|
+
return true;
|
|
1148
|
+
};
|
|
854
1149
|
const onData = (chunk) => {
|
|
855
|
-
chunks.push(
|
|
1150
|
+
chunks.push(toBufferChunk(chunk, incoming.readableEncoding));
|
|
856
1151
|
};
|
|
857
1152
|
const onEnd = () => {
|
|
858
1153
|
finish(() => {
|
|
@@ -862,6 +1157,7 @@ const readBodyDirect = (request) => {
|
|
|
862
1157
|
});
|
|
863
1158
|
};
|
|
864
1159
|
const onError = (error) => {
|
|
1160
|
+
if (recoverCompleteBodyAfterDisconnect(error)) return;
|
|
865
1161
|
finish(() => {
|
|
866
1162
|
reject(error);
|
|
867
1163
|
});
|
|
@@ -871,17 +1167,9 @@ const readBodyDirect = (request) => {
|
|
|
871
1167
|
onEnd();
|
|
872
1168
|
return;
|
|
873
1169
|
}
|
|
1170
|
+
if (recoverCompleteBodyAfterDisconnect()) return;
|
|
874
1171
|
finish(() => {
|
|
875
|
-
|
|
876
|
-
reject(incoming.errored);
|
|
877
|
-
return;
|
|
878
|
-
}
|
|
879
|
-
const reason = request[abortReasonKey];
|
|
880
|
-
if (reason !== void 0) {
|
|
881
|
-
reject(reason instanceof Error ? reason : new Error(String(reason)));
|
|
882
|
-
return;
|
|
883
|
-
}
|
|
884
|
-
reject(/* @__PURE__ */ new Error("Client connection prematurely closed."));
|
|
1172
|
+
reject(normalizeAbortError(request, incoming));
|
|
885
1173
|
});
|
|
886
1174
|
};
|
|
887
1175
|
const cleanup = () => {
|
|
@@ -969,6 +1257,7 @@ Object.defineProperty(requestPrototype, "signal", { get() {
|
|
|
969
1257
|
"cache",
|
|
970
1258
|
"credentials",
|
|
971
1259
|
"destination",
|
|
1260
|
+
"duplex",
|
|
972
1261
|
"integrity",
|
|
973
1262
|
"mode",
|
|
974
1263
|
"redirect",
|
|
@@ -1025,6 +1314,7 @@ const newRequest = (incoming, defaultHostname) => {
|
|
|
1025
1314
|
if (incomingUrl[0] !== "/" && (incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
|
|
1026
1315
|
if (incoming instanceof Http2ServerRequest) throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
|
|
1027
1316
|
try {
|
|
1317
|
+
validateRequestTarget(incomingUrl);
|
|
1028
1318
|
req[urlKey] = new URL(incomingUrl).href;
|
|
1029
1319
|
} catch (e) {
|
|
1030
1320
|
throw new RequestError("Invalid absolute URL", { cause: e });
|
|
@@ -1067,16 +1357,15 @@ var Response$1 = class Response$1 {
|
|
|
1067
1357
|
constructor(body, init) {
|
|
1068
1358
|
let headers;
|
|
1069
1359
|
this.#body = body;
|
|
1070
|
-
if (init instanceof
|
|
1360
|
+
if (init instanceof GlobalResponse) {
|
|
1071
1361
|
const cachedGlobalResponse = init[responseCache];
|
|
1072
1362
|
if (cachedGlobalResponse) {
|
|
1073
1363
|
this.#init = cachedGlobalResponse;
|
|
1074
1364
|
this[getResponseCache]();
|
|
1075
1365
|
return;
|
|
1076
|
-
} else {
|
|
1077
|
-
this.#init = init.#init;
|
|
1078
|
-
headers = new Headers(init.headers);
|
|
1079
1366
|
}
|
|
1367
|
+
this.#init = init instanceof Response$1 ? init.#init : init;
|
|
1368
|
+
headers = new Headers(init.headers);
|
|
1080
1369
|
} else this.#init = init;
|
|
1081
1370
|
if (body == null || typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) this[cacheKey] = [
|
|
1082
1371
|
init?.status || 200,
|
|
@@ -1188,6 +1477,11 @@ function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromi
|
|
|
1188
1477
|
const cancel = (error) => {
|
|
1189
1478
|
reader.cancel(error).catch(() => {});
|
|
1190
1479
|
};
|
|
1480
|
+
const stream = writable.stream;
|
|
1481
|
+
if (writable.destroyed || stream?.closed || stream?.destroyed) {
|
|
1482
|
+
cancel();
|
|
1483
|
+
return reader.closed;
|
|
1484
|
+
}
|
|
1191
1485
|
writable.on("close", cancel);
|
|
1192
1486
|
writable.on("error", cancel);
|
|
1193
1487
|
(currentReadPromise ?? reader.read()).then(flow, handleStreamError);
|
|
@@ -1205,7 +1499,7 @@ function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromi
|
|
|
1205
1499
|
try {
|
|
1206
1500
|
if (done) writable.end();
|
|
1207
1501
|
else if (!writable.write(value)) writable.once("drain", onDrain);
|
|
1208
|
-
else
|
|
1502
|
+
else reader.read().then(flow, handleStreamError);
|
|
1209
1503
|
} catch (e) {
|
|
1210
1504
|
handleStreamError(e);
|
|
1211
1505
|
}
|
|
@@ -1213,7 +1507,10 @@ function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromi
|
|
|
1213
1507
|
}
|
|
1214
1508
|
function writeFromReadableStream(stream, writable) {
|
|
1215
1509
|
if (stream.locked) throw new TypeError("ReadableStream is locked.");
|
|
1216
|
-
else if (writable.destroyed)
|
|
1510
|
+
else if (writable.destroyed) {
|
|
1511
|
+
stream.cancel().catch(() => {});
|
|
1512
|
+
return;
|
|
1513
|
+
}
|
|
1217
1514
|
return writeFromReadableStreamDefaultReader(stream.getReader(), writable);
|
|
1218
1515
|
}
|
|
1219
1516
|
const buildOutgoingHttpHeaders = (headers, defaultContentType) => {
|
|
@@ -1231,7 +1528,7 @@ const buildOutgoingHttpHeaders = (headers, defaultContentType) => {
|
|
|
1231
1528
|
const outgoingEnded = Symbol("outgoingEnded");
|
|
1232
1529
|
const incomingDraining = Symbol("incomingDraining");
|
|
1233
1530
|
const DRAIN_TIMEOUT_MS = 500;
|
|
1234
|
-
const MAX_DRAIN_BYTES =
|
|
1531
|
+
const MAX_DRAIN_BYTES = 67108864;
|
|
1235
1532
|
const drainIncoming = (incoming) => {
|
|
1236
1533
|
const incomingWithDrainState = incoming;
|
|
1237
1534
|
if (incoming.destroyed || incomingWithDrainState[incomingDraining]) return;
|
|
@@ -1252,7 +1549,10 @@ const drainIncoming = (incoming) => {
|
|
|
1252
1549
|
const forceClose = () => {
|
|
1253
1550
|
cleanup();
|
|
1254
1551
|
const socket = incoming.socket;
|
|
1255
|
-
if (socket && !socket.destroyed)
|
|
1552
|
+
if (socket && !socket.destroyed) {
|
|
1553
|
+
if (typeof socket.destroySoon === "function") socket.destroySoon();
|
|
1554
|
+
else if (typeof socket.destroy === "function") socket.destroy();
|
|
1555
|
+
}
|
|
1256
1556
|
};
|
|
1257
1557
|
const timer = setTimeout(forceClose, DRAIN_TIMEOUT_MS);
|
|
1258
1558
|
timer.unref?.();
|
|
@@ -1266,8 +1566,13 @@ const drainIncoming = (incoming) => {
|
|
|
1266
1566
|
incoming.resume();
|
|
1267
1567
|
};
|
|
1268
1568
|
const makeCloseHandler = (req, incoming, outgoing, needsBodyCleanup) => () => {
|
|
1269
|
-
if (incoming.errored)
|
|
1270
|
-
|
|
1569
|
+
if (incoming.errored) {
|
|
1570
|
+
recordBodyBufferedBeforeDisconnect(incoming);
|
|
1571
|
+
req[abortRequest](incoming.errored.toString());
|
|
1572
|
+
} else if (!outgoing.writableFinished || incoming instanceof Http2ServerRequest && incoming.aborted) {
|
|
1573
|
+
recordBodyBufferedBeforeDisconnect(incoming);
|
|
1574
|
+
req[abortRequest]("Client connection prematurely closed.");
|
|
1575
|
+
}
|
|
1271
1576
|
if (needsBodyCleanup && !incoming.readableEnded) setTimeout(() => {
|
|
1272
1577
|
if (!incoming.readableEnded) setTimeout(() => {
|
|
1273
1578
|
drainIncoming(incoming);
|
|
@@ -1286,7 +1591,10 @@ const handleResponseError = (e, outgoing) => {
|
|
|
1286
1591
|
if (err.code === "ERR_STREAM_PREMATURE_CLOSE") console.info("The user aborted a request.");
|
|
1287
1592
|
else {
|
|
1288
1593
|
console.error(e);
|
|
1289
|
-
if (!outgoing.headersSent)
|
|
1594
|
+
if (!outgoing.headersSent) {
|
|
1595
|
+
if (outgoing instanceof ServerResponse) outgoing._contentLength = null;
|
|
1596
|
+
outgoing.writeHead(500, { "Content-Type": "text/plain" });
|
|
1597
|
+
}
|
|
1290
1598
|
outgoing.end(`Error: ${err.message}`);
|
|
1291
1599
|
outgoing.destroy(err);
|
|
1292
1600
|
}
|
|
@@ -1294,6 +1602,21 @@ const handleResponseError = (e, outgoing) => {
|
|
|
1294
1602
|
const flushHeaders = (outgoing) => {
|
|
1295
1603
|
if ("flushHeaders" in outgoing && outgoing.writable) outgoing.flushHeaders();
|
|
1296
1604
|
};
|
|
1605
|
+
const trySetContentLength = (outgoing, status, length) => {
|
|
1606
|
+
const http1 = outgoing;
|
|
1607
|
+
if (http1._contentLength === null && http1._hasBody && http1.useChunkedEncodingByDefault && !http1._removedContLen && status >= 200 && status !== 204 && status !== 304 && !outgoing.hasHeader("content-length") && !outgoing.hasHeader("transfer-encoding") && !outgoing.hasHeader("trailer")) {
|
|
1608
|
+
http1._contentLength = length;
|
|
1609
|
+
return true;
|
|
1610
|
+
}
|
|
1611
|
+
return false;
|
|
1612
|
+
};
|
|
1613
|
+
const writeDefaultHeaders = (outgoing, status, length) => {
|
|
1614
|
+
if (trySetContentLength(outgoing, status, length)) outgoing.writeHead(status, { "Content-Type": defaultContentType });
|
|
1615
|
+
else outgoing.writeHead(status, {
|
|
1616
|
+
"Content-Type": defaultContentType,
|
|
1617
|
+
"Content-Length": length
|
|
1618
|
+
});
|
|
1619
|
+
};
|
|
1297
1620
|
const responseViaCache = async (res, outgoing) => {
|
|
1298
1621
|
let [status, body, header] = res[cacheKey];
|
|
1299
1622
|
if (!header) {
|
|
@@ -1301,22 +1624,13 @@ const responseViaCache = async (res, outgoing) => {
|
|
|
1301
1624
|
outgoing.writeHead(status);
|
|
1302
1625
|
outgoing.end();
|
|
1303
1626
|
} else if (typeof body === "string") {
|
|
1304
|
-
outgoing
|
|
1305
|
-
"Content-Type": defaultContentType,
|
|
1306
|
-
"Content-Length": Buffer.byteLength(body)
|
|
1307
|
-
});
|
|
1627
|
+
writeDefaultHeaders(outgoing, status, Buffer.byteLength(body));
|
|
1308
1628
|
outgoing.end(body);
|
|
1309
1629
|
} else if (body instanceof Uint8Array) {
|
|
1310
|
-
outgoing
|
|
1311
|
-
"Content-Type": defaultContentType,
|
|
1312
|
-
"Content-Length": body.byteLength
|
|
1313
|
-
});
|
|
1630
|
+
writeDefaultHeaders(outgoing, status, body.byteLength);
|
|
1314
1631
|
outgoing.end(body);
|
|
1315
1632
|
} else if (body instanceof Blob) {
|
|
1316
|
-
outgoing
|
|
1317
|
-
"Content-Type": defaultContentType,
|
|
1318
|
-
"Content-Length": body.size
|
|
1319
|
-
});
|
|
1633
|
+
writeDefaultHeaders(outgoing, status, body.size);
|
|
1320
1634
|
outgoing.end(new Uint8Array(await body.arrayBuffer()));
|
|
1321
1635
|
} else {
|
|
1322
1636
|
outgoing.writeHead(status, { "Content-Type": defaultContentType });
|
|
@@ -1327,6 +1641,8 @@ const responseViaCache = async (res, outgoing) => {
|
|
|
1327
1641
|
return;
|
|
1328
1642
|
}
|
|
1329
1643
|
let hasContentLength = false;
|
|
1644
|
+
let plainHeaders = false;
|
|
1645
|
+
let canAutoLength = true;
|
|
1330
1646
|
if (header instanceof Headers) {
|
|
1331
1647
|
hasContentLength = header.has("content-length");
|
|
1332
1648
|
header = buildOutgoingHttpHeaders(header, body === null ? void 0 : defaultContentType);
|
|
@@ -1334,14 +1650,25 @@ const responseViaCache = async (res, outgoing) => {
|
|
|
1334
1650
|
const headerObj = new Headers(header);
|
|
1335
1651
|
hasContentLength = headerObj.has("content-length");
|
|
1336
1652
|
header = buildOutgoingHttpHeaders(headerObj, body === null ? void 0 : defaultContentType);
|
|
1337
|
-
} else
|
|
1338
|
-
|
|
1339
|
-
|
|
1653
|
+
} else {
|
|
1654
|
+
plainHeaders = true;
|
|
1655
|
+
for (const key in header) {
|
|
1656
|
+
if (key.length === 14 && key.toLowerCase() === "content-length") {
|
|
1657
|
+
hasContentLength = true;
|
|
1658
|
+
break;
|
|
1659
|
+
}
|
|
1660
|
+
if (key.length === 17 && key.toLowerCase() === "transfer-encoding" || key.length === 7 && key.toLowerCase() === "trailer") canAutoLength = false;
|
|
1661
|
+
}
|
|
1340
1662
|
}
|
|
1341
1663
|
if (!hasContentLength) {
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
else if (body instanceof
|
|
1664
|
+
let length;
|
|
1665
|
+
if (typeof body === "string") length = Buffer.byteLength(body);
|
|
1666
|
+
else if (body instanceof Uint8Array) length = body.byteLength;
|
|
1667
|
+
else if (body instanceof Blob) length = body.size;
|
|
1668
|
+
if (length !== void 0 && (!plainHeaders || !canAutoLength || !trySetContentLength(outgoing, status, length))) {
|
|
1669
|
+
if (plainHeaders) header = { ...header };
|
|
1670
|
+
header["Content-Length"] = length;
|
|
1671
|
+
}
|
|
1345
1672
|
}
|
|
1346
1673
|
outgoing.writeHead(status, header);
|
|
1347
1674
|
if (body == null) outgoing.end();
|
|
@@ -1374,10 +1701,7 @@ const responseViaResponseObject = async (res, outgoing, options = {}) => {
|
|
|
1374
1701
|
let maxReadCount = 2;
|
|
1375
1702
|
for (let i = 0; i < maxReadCount; i++) {
|
|
1376
1703
|
currentReadPromise ||= reader.read();
|
|
1377
|
-
const chunk = await readWithoutBlocking(currentReadPromise)
|
|
1378
|
-
console.error(e);
|
|
1379
|
-
done = true;
|
|
1380
|
-
});
|
|
1704
|
+
const chunk = await readWithoutBlocking(currentReadPromise);
|
|
1381
1705
|
if (!chunk) {
|
|
1382
1706
|
if (i === 1) {
|
|
1383
1707
|
await new Promise((resolve) => setTimeout(resolve));
|
|
@@ -1467,6 +1791,7 @@ const getRequestListener = (fetchCallback, options = {}) => {
|
|
|
1467
1791
|
};
|
|
1468
1792
|
};
|
|
1469
1793
|
globalThis.CloseEvent;
|
|
1794
|
+
globalThis.ErrorEvent;
|
|
1470
1795
|
const CONNECTION_SYMBOL_KEY = Symbol("CONNECTION_SYMBOL_KEY");
|
|
1471
1796
|
const WAIT_FOR_WEBSOCKET_SYMBOL = Symbol("WAIT_FOR_WEBSOCKET_SYMBOL");
|
|
1472
1797
|
const responseHeadersToSkip = /* @__PURE__ */ new Set([
|
|
@@ -1491,6 +1816,7 @@ const appendResponseHeaders = (headers, responseHeaders) => {
|
|
|
1491
1816
|
});
|
|
1492
1817
|
};
|
|
1493
1818
|
const rejectUpgradeRequest = (socket, status, responseHeaders) => {
|
|
1819
|
+
if (socket.destroyed) return;
|
|
1494
1820
|
const responseLines = ["Connection: close", "Content-Length: 0"];
|
|
1495
1821
|
appendResponseHeaders(responseLines, responseHeaders);
|
|
1496
1822
|
socket.end(`HTTP/1.1 ${status.toString()} ${STATUS_CODES[status] ?? ""}\r\n${responseLines.join("\r\n")}\r\n\r
|
|
@@ -1498,7 +1824,12 @@ const rejectUpgradeRequest = (socket, status, responseHeaders) => {
|
|
|
1498
1824
|
};
|
|
1499
1825
|
const createUpgradeRequest = (request) => {
|
|
1500
1826
|
const protocol = request.socket.encrypted ? "https" : "http";
|
|
1501
|
-
const
|
|
1827
|
+
const incomingUrl = request.url ?? "/";
|
|
1828
|
+
let url;
|
|
1829
|
+
if (incomingUrl[0] !== "/" && (incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
|
|
1830
|
+
validateRequestTarget(incomingUrl);
|
|
1831
|
+
url = new URL(incomingUrl).href;
|
|
1832
|
+
} else url = buildUrl(protocol, request.headers.host ?? "localhost", incomingUrl);
|
|
1502
1833
|
const headers = new Headers();
|
|
1503
1834
|
for (const key in request.headers) {
|
|
1504
1835
|
const value = request.headers[key];
|
|
@@ -1517,16 +1848,28 @@ const setupWebSocket = (options) => {
|
|
|
1517
1848
|
waiterMap.delete(request);
|
|
1518
1849
|
}
|
|
1519
1850
|
});
|
|
1851
|
+
const rejectWaiter = (request) => {
|
|
1852
|
+
const waiter = waiterMap.get(request);
|
|
1853
|
+
if (waiter) {
|
|
1854
|
+
waiterMap.delete(request);
|
|
1855
|
+
waiter.reject(/* @__PURE__ */ new Error("WebSocket handshake aborted"));
|
|
1856
|
+
}
|
|
1857
|
+
};
|
|
1520
1858
|
const waitForWebSocket = (request, connectionSymbol) => {
|
|
1521
|
-
return new Promise((resolve) => {
|
|
1859
|
+
return new Promise((resolve, reject) => {
|
|
1522
1860
|
waiterMap.set(request, {
|
|
1523
1861
|
resolve,
|
|
1862
|
+
reject,
|
|
1524
1863
|
connectionSymbol
|
|
1525
1864
|
});
|
|
1526
1865
|
});
|
|
1527
1866
|
};
|
|
1528
1867
|
server.on("upgrade", async (request, socket, head) => {
|
|
1529
1868
|
if (request.headers.upgrade?.toLowerCase() !== "websocket") return;
|
|
1869
|
+
const ignoreSocketError = () => {};
|
|
1870
|
+
const reclaimWaiterOnClose = () => rejectWaiter(request);
|
|
1871
|
+
socket.on("error", ignoreSocketError);
|
|
1872
|
+
socket.once("close", reclaimWaiterOnClose);
|
|
1530
1873
|
const env = {
|
|
1531
1874
|
incoming: request,
|
|
1532
1875
|
outgoing: void 0,
|
|
@@ -1541,13 +1884,17 @@ const setupWebSocket = (options) => {
|
|
|
1541
1884
|
status = response.status;
|
|
1542
1885
|
responseHeaders = response.headers;
|
|
1543
1886
|
}
|
|
1544
|
-
} catch {
|
|
1545
|
-
if (server.listenerCount("upgrade") === 1) rejectUpgradeRequest(socket, 500);
|
|
1887
|
+
} catch (error) {
|
|
1888
|
+
if (server.listenerCount("upgrade") === 1) rejectUpgradeRequest(socket, error instanceof RequestError ? 400 : 500);
|
|
1889
|
+
return;
|
|
1890
|
+
}
|
|
1891
|
+
if (socket.destroyed) {
|
|
1892
|
+
rejectWaiter(request);
|
|
1546
1893
|
return;
|
|
1547
1894
|
}
|
|
1548
1895
|
const waiter = waiterMap.get(request);
|
|
1549
1896
|
if (!waiter || waiter.connectionSymbol !== env[CONNECTION_SYMBOL_KEY]) {
|
|
1550
|
-
|
|
1897
|
+
rejectWaiter(request);
|
|
1551
1898
|
if (server.listenerCount("upgrade") === 1) rejectUpgradeRequest(socket, status, responseHeaders);
|
|
1552
1899
|
return;
|
|
1553
1900
|
}
|
|
@@ -1557,6 +1904,8 @@ const setupWebSocket = (options) => {
|
|
|
1557
1904
|
wss.on("headers", addResponseHeaders);
|
|
1558
1905
|
try {
|
|
1559
1906
|
wss.handleUpgrade(request, socket, head, (ws) => {
|
|
1907
|
+
socket.off("close", reclaimWaiterOnClose);
|
|
1908
|
+
socket.off("error", ignoreSocketError);
|
|
1560
1909
|
wss.emit("connection", ws, request);
|
|
1561
1910
|
});
|
|
1562
1911
|
} finally {
|
|
@@ -1585,24 +1934,15 @@ const createAdaptorServer = (options) => {
|
|
|
1585
1934
|
}
|
|
1586
1935
|
return server;
|
|
1587
1936
|
};
|
|
1588
|
-
|
|
1589
|
-
const server = createAdaptorServer(options);
|
|
1590
|
-
server.listen(options?.port ?? 3e3, options.hostname, () => {
|
|
1591
|
-
const serverInfo = server.address();
|
|
1592
|
-
listeningListener && listeningListener(serverInfo);
|
|
1593
|
-
});
|
|
1594
|
-
return server;
|
|
1595
|
-
};
|
|
1596
|
-
//#endregion
|
|
1597
|
-
//#region packages/adapter-node/src/middleware/body-cap.ts
|
|
1937
|
+
// packages/adapter-node/src/middleware/body-cap.ts
|
|
1598
1938
|
/**
|
|
1599
1939
|
* Body-cap enforcement for Node-hosted requests. Replaces the
|
|
1600
1940
|
* pre-pivot `bodyCapMiddleware` that attached `incoming.on("data",
|
|
1601
1941
|
* ...)` — that listener raced with `@hono/node-server`'s own body
|
|
1602
1942
|
* reader and dropped the first chunks of every POST. Wrapping
|
|
1603
1943
|
* `req.body` with a counting `TransformStream` puts the cap in the
|
|
1604
|
-
* same reader chain as the kernel router's `
|
|
1605
|
-
*
|
|
1944
|
+
* same reader chain as the kernel router's `readJsonBody`, which
|
|
1945
|
+
* reads `c.req.raw.body` itself, so there is no race.
|
|
1606
1946
|
*
|
|
1607
1947
|
* Two cap-trip paths, both drain the upstream `IncomingMessage`
|
|
1608
1948
|
* (`resume()`) so the client's body write completes and the 413
|
|
@@ -1662,8 +2002,7 @@ function cap413(max) {
|
|
|
1662
2002
|
headers: { "content-type": "application/json" }
|
|
1663
2003
|
});
|
|
1664
2004
|
}
|
|
1665
|
-
|
|
1666
|
-
//#region packages/adapter-node/src/middleware/dev-landing.ts
|
|
2005
|
+
// packages/adapter-node/src/middleware/dev-landing.ts
|
|
1667
2006
|
/**
|
|
1668
2007
|
* Opt-in dev landing-page short-circuit. Serves `GET /` with a
|
|
1669
2008
|
* human-readable HTML page that links to the configured UI URL, and
|
|
@@ -1674,10 +2013,6 @@ function cap413(max) {
|
|
|
1674
2013
|
* by {@link createApp} (in `app.ts`) ahead of `staticAssetsMiddleware`
|
|
1675
2014
|
* so the dev short-circuit wins over any on-disk `index.html` /
|
|
1676
2015
|
* `favicon.ico` that might live in `webRoot`.
|
|
1677
|
-
*
|
|
1678
|
-
* Mirrors the imperative dev-landing block in
|
|
1679
|
-
* `packages/adapter-node/src/server.ts` (which the hand-rolled
|
|
1680
|
-
* `handle()` bridge still uses until the bridge cutover).
|
|
1681
2016
|
*/
|
|
1682
2017
|
function devLandingMiddleware(opts) {
|
|
1683
2018
|
return async (c, next) => {
|
|
@@ -1697,159 +2032,369 @@ function devLandingMiddleware(opts) {
|
|
|
1697
2032
|
return next();
|
|
1698
2033
|
};
|
|
1699
2034
|
}
|
|
1700
|
-
|
|
1701
|
-
|
|
2035
|
+
// node_modules/.pnpm/@hono+node-server@2.1.8_hono@4.13.19/node_modules/@hono/node-server/dist/utils/stream.mjs
|
|
2036
|
+
const pr54206Applied = () => {
|
|
2037
|
+
const [major, minor] = versions.node.split(".").map((component) => parseInt(component));
|
|
2038
|
+
return major >= 23 || major === 22 && minor >= 7 || major === 20 && minor >= 18;
|
|
2039
|
+
};
|
|
2040
|
+
const useReadableToWeb = pr54206Applied();
|
|
2041
|
+
const createStreamBody = (stream, useNativeReadableToWeb = useReadableToWeb) => {
|
|
2042
|
+
if (useNativeReadableToWeb) return Readable.toWeb(stream);
|
|
2043
|
+
let controller;
|
|
2044
|
+
let settled = false;
|
|
2045
|
+
const cleanup = () => {
|
|
2046
|
+
stream.off("data", onData);
|
|
2047
|
+
stream.off("error", onError);
|
|
2048
|
+
stream.off("end", onTerminate);
|
|
2049
|
+
stream.off("close", onTerminate);
|
|
2050
|
+
};
|
|
2051
|
+
const settle = (callback) => {
|
|
2052
|
+
if (settled) return;
|
|
2053
|
+
settled = true;
|
|
2054
|
+
cleanup();
|
|
2055
|
+
callback?.();
|
|
2056
|
+
};
|
|
2057
|
+
const onData = (chunk) => {
|
|
2058
|
+
if (settled || !controller) return;
|
|
2059
|
+
controller.enqueue(chunk);
|
|
2060
|
+
if ((controller.desiredSize ?? 0) <= 0) stream.pause();
|
|
2061
|
+
};
|
|
2062
|
+
const onError = (error) => {
|
|
2063
|
+
settle(() => {
|
|
2064
|
+
controller?.error(error);
|
|
2065
|
+
});
|
|
2066
|
+
};
|
|
2067
|
+
const onTerminate = () => {
|
|
2068
|
+
settle(() => {
|
|
2069
|
+
controller?.close();
|
|
2070
|
+
});
|
|
2071
|
+
};
|
|
2072
|
+
return new ReadableStream({
|
|
2073
|
+
start(streamController) {
|
|
2074
|
+
controller = streamController;
|
|
2075
|
+
stream.on("data", onData);
|
|
2076
|
+
stream.on("error", onError);
|
|
2077
|
+
stream.on("end", onTerminate);
|
|
2078
|
+
stream.on("close", onTerminate);
|
|
2079
|
+
stream.pause();
|
|
2080
|
+
},
|
|
2081
|
+
pull() {
|
|
2082
|
+
if (!settled) stream.resume();
|
|
2083
|
+
},
|
|
2084
|
+
cancel() {
|
|
2085
|
+
settle();
|
|
2086
|
+
const ignoreError = () => {};
|
|
2087
|
+
stream.on("error", ignoreError);
|
|
2088
|
+
stream.once("close", () => stream.off("error", ignoreError));
|
|
2089
|
+
stream.destroy();
|
|
2090
|
+
}
|
|
2091
|
+
});
|
|
2092
|
+
};
|
|
2093
|
+
// node_modules/.pnpm/hono@4.13.19/node_modules/hono/dist/utils/mime.js
|
|
1702
2094
|
/**
|
|
1703
|
-
*
|
|
1704
|
-
*
|
|
1705
|
-
* pipeline actually emits. Unknown extensions fall back to
|
|
1706
|
-
* `application/octet-stream`, which keeps the browser from sniffing
|
|
1707
|
-
* untrusted bytes as HTML.
|
|
2095
|
+
* @module
|
|
2096
|
+
* MIME utility.
|
|
1708
2097
|
*/
|
|
1709
|
-
const
|
|
1710
|
-
|
|
1711
|
-
|
|
1712
|
-
|
|
1713
|
-
|
|
1714
|
-
|
|
1715
|
-
|
|
1716
|
-
|
|
1717
|
-
|
|
1718
|
-
|
|
1719
|
-
|
|
1720
|
-
|
|
1721
|
-
|
|
1722
|
-
|
|
1723
|
-
|
|
1724
|
-
|
|
1725
|
-
|
|
1726
|
-
|
|
2098
|
+
const getMimeType = (filename, mimes = baseMimes) => {
|
|
2099
|
+
const match = filename.match(/\.([a-zA-Z0-9]+?)$/);
|
|
2100
|
+
if (!match) return;
|
|
2101
|
+
return mimes[match[1].toLowerCase()];
|
|
2102
|
+
};
|
|
2103
|
+
const baseMimes = {
|
|
2104
|
+
aac: "audio/aac",
|
|
2105
|
+
avi: "video/x-msvideo",
|
|
2106
|
+
avif: "image/avif",
|
|
2107
|
+
av1: "video/av1",
|
|
2108
|
+
bin: "application/octet-stream",
|
|
2109
|
+
bmp: "image/bmp",
|
|
2110
|
+
css: "text/css; charset=utf-8",
|
|
2111
|
+
csv: "text/csv; charset=utf-8",
|
|
2112
|
+
eot: "application/vnd.ms-fontobject",
|
|
2113
|
+
epub: "application/epub+zip",
|
|
2114
|
+
gif: "image/gif",
|
|
2115
|
+
gz: "application/gzip",
|
|
2116
|
+
htm: "text/html; charset=utf-8",
|
|
2117
|
+
html: "text/html; charset=utf-8",
|
|
2118
|
+
ico: "image/x-icon",
|
|
2119
|
+
ics: "text/calendar; charset=utf-8",
|
|
2120
|
+
jpeg: "image/jpeg",
|
|
2121
|
+
jpg: "image/jpeg",
|
|
2122
|
+
js: "text/javascript; charset=utf-8",
|
|
2123
|
+
json: "application/json",
|
|
2124
|
+
jsonld: "application/ld+json",
|
|
2125
|
+
map: "application/json",
|
|
2126
|
+
mid: "audio/x-midi",
|
|
2127
|
+
midi: "audio/x-midi",
|
|
2128
|
+
mjs: "text/javascript; charset=utf-8",
|
|
2129
|
+
mp3: "audio/mpeg",
|
|
2130
|
+
mp4: "video/mp4",
|
|
2131
|
+
mpeg: "video/mpeg",
|
|
2132
|
+
oga: "audio/ogg",
|
|
2133
|
+
ogv: "video/ogg",
|
|
2134
|
+
ogx: "application/ogg",
|
|
2135
|
+
opus: "audio/opus",
|
|
2136
|
+
otf: "font/otf",
|
|
2137
|
+
pdf: "application/pdf",
|
|
2138
|
+
png: "image/png",
|
|
2139
|
+
rtf: "application/rtf",
|
|
2140
|
+
svg: "image/svg+xml; charset=utf-8",
|
|
2141
|
+
tif: "image/tiff",
|
|
2142
|
+
tiff: "image/tiff",
|
|
2143
|
+
ts: "video/mp2t",
|
|
2144
|
+
ttf: "font/ttf",
|
|
2145
|
+
txt: "text/plain; charset=utf-8",
|
|
2146
|
+
wasm: "application/wasm",
|
|
2147
|
+
webm: "video/webm",
|
|
2148
|
+
weba: "audio/webm",
|
|
2149
|
+
webmanifest: "application/manifest+json",
|
|
2150
|
+
webp: "image/webp",
|
|
2151
|
+
woff: "font/woff",
|
|
2152
|
+
woff2: "font/woff2",
|
|
2153
|
+
xhtml: "application/xhtml+xml; charset=utf-8",
|
|
2154
|
+
xml: "application/xml; charset=utf-8",
|
|
2155
|
+
zip: "application/zip",
|
|
2156
|
+
"3gp": "video/3gpp",
|
|
2157
|
+
"3g2": "video/3gpp2",
|
|
2158
|
+
gltf: "model/gltf+json",
|
|
2159
|
+
glb: "model/gltf-binary"
|
|
2160
|
+
};
|
|
2161
|
+
// node_modules/.pnpm/@hono+node-server@2.1.8_hono@4.13.19/node_modules/@hono/node-server/dist/serve-static.mjs
|
|
2162
|
+
const COMPRESSIBLE_CONTENT_TYPE_REGEX = /^\s*(?:text\/[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|wasm|x-httpd-php|x-javascript|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml))(?:[;\s]|$)/i;
|
|
2163
|
+
const ENCODINGS = {
|
|
2164
|
+
br: ".br",
|
|
2165
|
+
zstd: ".zst",
|
|
2166
|
+
gzip: ".gz"
|
|
2167
|
+
};
|
|
2168
|
+
const ENCODINGS_ORDERED_KEYS = Object.keys(ENCODINGS);
|
|
2169
|
+
const getStats = (path) => {
|
|
2170
|
+
let stats;
|
|
2171
|
+
try {
|
|
2172
|
+
stats = statSync(path);
|
|
2173
|
+
} catch {}
|
|
2174
|
+
return stats;
|
|
2175
|
+
};
|
|
2176
|
+
const BYTE_RANGE_PATTERN = /^(?:bytes=)?(?!-$)(\d*)-(\d*)$/;
|
|
2177
|
+
const parseByteRange = (range) => {
|
|
2178
|
+
const match = range.match(BYTE_RANGE_PATTERN);
|
|
2179
|
+
if (!match) return;
|
|
2180
|
+
const [, start, end] = match;
|
|
2181
|
+
if (start === "") return {
|
|
2182
|
+
type: "suffix",
|
|
2183
|
+
length: Number(end)
|
|
2184
|
+
};
|
|
2185
|
+
if (end === "") return {
|
|
2186
|
+
type: "open-ended",
|
|
2187
|
+
start: Number(start)
|
|
2188
|
+
};
|
|
2189
|
+
return {
|
|
2190
|
+
type: "bounded",
|
|
2191
|
+
start: Number(start),
|
|
2192
|
+
end: Number(end)
|
|
2193
|
+
};
|
|
2194
|
+
};
|
|
2195
|
+
const resolveByteRange = (spec, size) => {
|
|
2196
|
+
if (size === 0) return;
|
|
2197
|
+
if (spec.type === "suffix") {
|
|
2198
|
+
if (spec.length === 0) return;
|
|
2199
|
+
return {
|
|
2200
|
+
start: Math.max(size - spec.length, 0),
|
|
2201
|
+
end: size - 1
|
|
2202
|
+
};
|
|
2203
|
+
}
|
|
2204
|
+
const end = spec.type === "bounded" ? Math.min(spec.end, size - 1) : size - 1;
|
|
2205
|
+
if (spec.start >= size || spec.start > end) return;
|
|
2206
|
+
return {
|
|
2207
|
+
start: spec.start,
|
|
2208
|
+
end
|
|
2209
|
+
};
|
|
1727
2210
|
};
|
|
2211
|
+
const tryDecode = (str, decoder) => {
|
|
2212
|
+
try {
|
|
2213
|
+
return decoder(str);
|
|
2214
|
+
} catch {
|
|
2215
|
+
return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match) => {
|
|
2216
|
+
try {
|
|
2217
|
+
return decoder(match);
|
|
2218
|
+
} catch {
|
|
2219
|
+
return match;
|
|
2220
|
+
}
|
|
2221
|
+
});
|
|
2222
|
+
}
|
|
2223
|
+
};
|
|
2224
|
+
const tryDecodeURI = (str) => tryDecode(str, decodeURI);
|
|
2225
|
+
const serveStatic = (options = { root: "" }) => {
|
|
2226
|
+
const root = options.root || "";
|
|
2227
|
+
const optionPath = options.path;
|
|
2228
|
+
if (root !== "" && !existsSync(root)) console.error(`serveStatic: root path '${root}' is not found, are you sure it's correct?`);
|
|
2229
|
+
return async (c, next) => {
|
|
2230
|
+
if (c.finalized) return next();
|
|
2231
|
+
if (c.req.method !== "GET" && c.req.method !== "HEAD") return next();
|
|
2232
|
+
let filename;
|
|
2233
|
+
if (optionPath) filename = optionPath;
|
|
2234
|
+
else try {
|
|
2235
|
+
filename = tryDecodeURI(c.req.path);
|
|
2236
|
+
if (c.req.path.includes("%") && (!options.allowPercentInPath || filename !== c.req.path.replace(/%25/g, "%"))) throw new Error();
|
|
2237
|
+
if (/(?:^|[\/\\])\.{1,2}(?:$|[\/\\])|[\/\\]{2,}|\\/.test(filename)) throw new Error();
|
|
2238
|
+
} catch {
|
|
2239
|
+
await options.onNotFound?.(c.req.path, c);
|
|
2240
|
+
return next();
|
|
2241
|
+
}
|
|
2242
|
+
let path = join(root, !optionPath && options.rewriteRequestPath ? options.rewriteRequestPath(filename, c) : filename);
|
|
2243
|
+
let stats = getStats(path);
|
|
2244
|
+
if (stats && stats.isDirectory()) {
|
|
2245
|
+
const indexFile = options.index ?? "index.html";
|
|
2246
|
+
path = join(path, indexFile);
|
|
2247
|
+
stats = getStats(path);
|
|
2248
|
+
}
|
|
2249
|
+
if (!stats) {
|
|
2250
|
+
await options.onNotFound?.(path, c);
|
|
2251
|
+
return next();
|
|
2252
|
+
}
|
|
2253
|
+
const mimeType = getMimeType(path);
|
|
2254
|
+
c.header("Content-Type", mimeType || "application/octet-stream");
|
|
2255
|
+
if (options.precompressed && (!mimeType || mimeType === "application/octet-stream" || COMPRESSIBLE_CONTENT_TYPE_REGEX.test(mimeType))) {
|
|
2256
|
+
const acceptEncodingSet = new Set(c.req.header("Accept-Encoding")?.split(",").map((encoding) => encoding.trim()));
|
|
2257
|
+
for (const encoding of ENCODINGS_ORDERED_KEYS) {
|
|
2258
|
+
if (!acceptEncodingSet.has(encoding)) continue;
|
|
2259
|
+
const precompressedStats = getStats(path + ENCODINGS[encoding]);
|
|
2260
|
+
if (precompressedStats) {
|
|
2261
|
+
c.header("Content-Encoding", encoding);
|
|
2262
|
+
c.header("Vary", "Accept-Encoding", { append: true });
|
|
2263
|
+
stats = precompressedStats;
|
|
2264
|
+
path = path + ENCODINGS[encoding];
|
|
2265
|
+
break;
|
|
2266
|
+
}
|
|
2267
|
+
}
|
|
2268
|
+
}
|
|
2269
|
+
let result;
|
|
2270
|
+
const size = stats.size;
|
|
2271
|
+
const range = c.req.header("range") || "";
|
|
2272
|
+
c.header("Last-Modified", stats.mtime.toUTCString());
|
|
2273
|
+
if (c.req.method === "HEAD") {
|
|
2274
|
+
c.header("Content-Length", size.toString());
|
|
2275
|
+
c.status(200);
|
|
2276
|
+
result = c.body(null);
|
|
2277
|
+
} else if (!range) {
|
|
2278
|
+
c.header("Content-Length", size.toString());
|
|
2279
|
+
result = c.body(createStreamBody(createReadStream(path)), 200);
|
|
2280
|
+
} else {
|
|
2281
|
+
c.header("Accept-Ranges", "bytes");
|
|
2282
|
+
const resolvedRange = resolveByteRange(parseByteRange(range) ?? {
|
|
2283
|
+
type: "open-ended",
|
|
2284
|
+
start: 0
|
|
2285
|
+
}, size);
|
|
2286
|
+
if (!resolvedRange) {
|
|
2287
|
+
c.header("Content-Range", `bytes */${size}`);
|
|
2288
|
+
result = c.body(null, 416);
|
|
2289
|
+
} else {
|
|
2290
|
+
const { start, end } = resolvedRange;
|
|
2291
|
+
const chunkSize = end - start + 1;
|
|
2292
|
+
const stream = createReadStream(path, {
|
|
2293
|
+
start,
|
|
2294
|
+
end
|
|
2295
|
+
});
|
|
2296
|
+
c.header("Content-Length", chunkSize.toString());
|
|
2297
|
+
c.header("Content-Range", `bytes ${start}-${end}/${size}`);
|
|
2298
|
+
result = c.body(createStreamBody(stream), 206);
|
|
2299
|
+
}
|
|
2300
|
+
}
|
|
2301
|
+
await options.onFound?.(path, c);
|
|
2302
|
+
return result;
|
|
2303
|
+
};
|
|
2304
|
+
};
|
|
2305
|
+
// packages/adapter-node/src/middleware/static-assets.ts
|
|
1728
2306
|
/**
|
|
1729
|
-
* Serve files from `webRoot` for GET/HEAD requests that miss `/v1
|
|
1730
|
-
*
|
|
1731
|
-
* HTML navigation (`Accept: text/html`) that misses an on-disk file
|
|
1732
|
-
* falls back to `<webRoot>/index.html` (SPA shell). Non-HTML misses
|
|
1733
|
-
* pass through `next()` so the cascade emits its 404 envelope.
|
|
1734
|
-
*
|
|
1735
|
-
* Path resolution rejects `..` segments and absolute paths so the
|
|
1736
|
-
* middleware can't escape `webRoot`. Pure `node:fs` + `node:path` —
|
|
1737
|
-
* no new dependency.
|
|
2307
|
+
* Serve files from `webRoot` for GET/HEAD requests that miss `/v1/*`,
|
|
2308
|
+
* via `@hono/node-server/serve-static`.
|
|
1738
2309
|
*
|
|
1739
|
-
*
|
|
1740
|
-
*
|
|
1741
|
-
*
|
|
1742
|
-
*
|
|
1743
|
-
*
|
|
1744
|
-
*
|
|
2310
|
+
* That handler owns MIME types, `Content-Length`, `Last-Modified`,
|
|
2311
|
+
* Range requests, and request-path validation, falling through to the
|
|
2312
|
+
* cascade's 404 envelope on a rejected path. Hono hands it the path
|
|
2313
|
+
* already `decodeURI`'d, so `%20` and UTF-8 escapes name ordinary
|
|
2314
|
+
* files. What still holds a `%` after that decode is an encoded
|
|
2315
|
+
* reserved character (`%2F`, `%3F`, `%23`) or a literal `%` (`%25`),
|
|
2316
|
+
* and those are rejected, as are `.`/`..` segments and repeated or
|
|
2317
|
+
* back-slashes. This wrapper adds what it does not:
|
|
1745
2318
|
*
|
|
1746
|
-
*
|
|
1747
|
-
*
|
|
1748
|
-
*
|
|
2319
|
+
* - Dotfiles and dot-directories (`/.env`, `/.git/config`) fall
|
|
2320
|
+
* through, except `/.well-known/*`.
|
|
2321
|
+
* - A file whose real path (after symlinks) leaves `webRoot` falls
|
|
2322
|
+
* through.
|
|
2323
|
+
* - HTML navigation (`Accept: text/html`) that misses on disk gets
|
|
2324
|
+
* `<webRoot>/index.html` (SPA shell). Other misses fall through.
|
|
2325
|
+
* - `Cache-Control`: `public, max-age=3600` under `assets/` (Vite's
|
|
2326
|
+
* hashed bundles), `no-cache` everywhere else.
|
|
1749
2327
|
*/
|
|
1750
2328
|
function staticAssetsMiddleware(opts) {
|
|
2329
|
+
const root = resolve(opts.webRoot);
|
|
2330
|
+
const onFound = (path, c) => {
|
|
2331
|
+
const rel = relative(root, resolve(path)).split(sep).join("/");
|
|
2332
|
+
c.header("Cache-Control", rel.startsWith("assets/") ? "public, max-age=3600" : "no-cache");
|
|
2333
|
+
};
|
|
2334
|
+
const files = serveStatic({
|
|
2335
|
+
root,
|
|
2336
|
+
rewriteRequestPath: (path) => servesFromRoot(root, path) ? path : UNSERVABLE,
|
|
2337
|
+
onFound
|
|
2338
|
+
});
|
|
2339
|
+
const shell = serveStatic({
|
|
2340
|
+
root,
|
|
2341
|
+
path: "index.html",
|
|
2342
|
+
onFound
|
|
2343
|
+
});
|
|
1751
2344
|
return async (c, next) => {
|
|
1752
2345
|
const method = c.req.method;
|
|
1753
|
-
if (method !== "GET" && method !== "HEAD") return next();
|
|
1754
|
-
|
|
1755
|
-
|
|
1756
|
-
|
|
1757
|
-
|
|
1758
|
-
|
|
1759
|
-
|
|
1760
|
-
|
|
1761
|
-
|
|
1762
|
-
const cacheControl = relative(opts.webRoot, target).split(sep).join("/").startsWith("assets/") && target !== resolve(opts.webRoot, "index.html") ? "public, max-age=3600" : "no-cache";
|
|
1763
|
-
const headers = {
|
|
1764
|
-
"content-type": contentType,
|
|
1765
|
-
"content-length": String(stats.size),
|
|
1766
|
-
"cache-control": cacheControl
|
|
1767
|
-
};
|
|
1768
|
-
if (method === "HEAD") return new Response(null, {
|
|
1769
|
-
status: 200,
|
|
1770
|
-
headers
|
|
1771
|
-
});
|
|
1772
|
-
const nodeWeb = Readable.toWeb(createReadStream(target));
|
|
1773
|
-
return new Response(nodeWeb, {
|
|
1774
|
-
status: 200,
|
|
1775
|
-
headers
|
|
2346
|
+
if (method !== "GET" && method !== "HEAD" || c.req.path.startsWith("/v1/")) return next();
|
|
2347
|
+
if (hasDotSegment(c.req.path)) return next();
|
|
2348
|
+
return files(c, async () => {
|
|
2349
|
+
if (c.req.header("accept")?.includes("text/html") !== true || !servesFromRoot(root, "index.html")) {
|
|
2350
|
+
await next();
|
|
2351
|
+
return;
|
|
2352
|
+
}
|
|
2353
|
+
const res = await shell(c, next);
|
|
2354
|
+
if (res !== void 0) c.res = res;
|
|
1776
2355
|
});
|
|
1777
2356
|
};
|
|
1778
2357
|
}
|
|
1779
|
-
/**
|
|
1780
|
-
|
|
1781
|
-
|
|
1782
|
-
|
|
1783
|
-
|
|
1784
|
-
*/
|
|
1785
|
-
function resolveUnderWebRoot(reqPath, webRoot) {
|
|
1786
|
-
let relative$1 = reqPath;
|
|
1787
|
-
if (relative$1 === "" || relative$1 === "/") relative$1 = "/index.html";
|
|
1788
|
-
else if (relative$1.endsWith("/")) relative$1 = `${relative$1}index.html`;
|
|
1789
|
-
if (relative$1.includes("\0")) return null;
|
|
1790
|
-
const segments = [];
|
|
1791
|
-
for (const raw of relative$1.split("/")) {
|
|
1792
|
-
if (raw === "") continue;
|
|
1793
|
-
let decoded;
|
|
1794
|
-
try {
|
|
1795
|
-
decoded = decodeURIComponent(raw);
|
|
1796
|
-
} catch {
|
|
1797
|
-
return null;
|
|
1798
|
-
}
|
|
1799
|
-
if (decoded === "" || decoded === ".") continue;
|
|
1800
|
-
if (decoded === "..") return null;
|
|
1801
|
-
if (decoded.includes("\0")) return null;
|
|
1802
|
-
if (decoded.includes("/") || decoded.includes("\\")) return null;
|
|
1803
|
-
segments.push(decoded);
|
|
1804
|
-
}
|
|
1805
|
-
const resolved = resolve(webRoot, ...segments);
|
|
1806
|
-
const rel = relative(webRoot, resolved);
|
|
1807
|
-
if (rel === "" || rel.startsWith("..") || rel.startsWith(`..${sep}`)) return null;
|
|
1808
|
-
return resolved;
|
|
2358
|
+
/** A path `statSync` rejects (NUL byte), so `serveStatic` treats it as a miss. */
|
|
2359
|
+
const UNSERVABLE = "/\0";
|
|
2360
|
+
/** `.well-known` is the one dot-directory a web app is expected to publish (RFC 8615). */
|
|
2361
|
+
function hasDotSegment(path) {
|
|
2362
|
+
return path.split("/").some((segment) => segment.startsWith(".") && segment !== ".well-known");
|
|
1809
2363
|
}
|
|
1810
2364
|
/**
|
|
1811
|
-
*
|
|
1812
|
-
*
|
|
1813
|
-
*
|
|
1814
|
-
*
|
|
2365
|
+
* True when `requestPath` (already validated by `serveStatic`) names a
|
|
2366
|
+
* missing file, or an existing file or directory whose real path stays
|
|
2367
|
+
* inside `root`. For a directory, its `index.html` is checked too,
|
|
2368
|
+
* since that is what `serveStatic` opens.
|
|
1815
2369
|
*/
|
|
1816
|
-
function
|
|
1817
|
-
|
|
1818
|
-
|
|
2370
|
+
function servesFromRoot(root, requestPath) {
|
|
2371
|
+
const target = join(root, requestPath);
|
|
2372
|
+
const realRoot = realpathOrNull(root);
|
|
2373
|
+
if (realRoot === null) return true;
|
|
2374
|
+
const candidates = [target];
|
|
2375
|
+
if (isDirectory(target)) candidates.push(join(target, "index.html"));
|
|
2376
|
+
return candidates.every((candidate) => {
|
|
2377
|
+
const real = realpathOrNull(candidate);
|
|
2378
|
+
if (real === null) return true;
|
|
2379
|
+
const rel = relative(realRoot, real);
|
|
2380
|
+
return rel === "" || !rel.startsWith("..") && !isAbsolute(rel);
|
|
2381
|
+
});
|
|
1819
2382
|
}
|
|
1820
|
-
|
|
1821
|
-
|
|
1822
|
-
|
|
1823
|
-
|
|
1824
|
-
|
|
1825
|
-
}
|
|
1826
|
-
if (!wantsHtmlFallback(accept)) return null;
|
|
1827
|
-
const indexPath = resolve(webRoot, "index.html");
|
|
1828
|
-
const fallback = await statFile(indexPath);
|
|
1829
|
-
if (fallback === null) return null;
|
|
1830
|
-
return {
|
|
1831
|
-
target: indexPath,
|
|
1832
|
-
stats: fallback
|
|
1833
|
-
};
|
|
2383
|
+
function realpathOrNull(path) {
|
|
2384
|
+
try {
|
|
2385
|
+
return realpathSync(path);
|
|
2386
|
+
} catch {
|
|
2387
|
+
return null;
|
|
2388
|
+
}
|
|
1834
2389
|
}
|
|
1835
|
-
|
|
1836
|
-
* `fs.stat` that returns `null` for the missing-file cases that this
|
|
1837
|
-
* handler treats as a fall-through (ENOENT / ENOTDIR / non-file).
|
|
1838
|
-
* Other errors (EACCES, EIO, ...) propagate.
|
|
1839
|
-
*/
|
|
1840
|
-
async function statFile(target) {
|
|
2390
|
+
function isDirectory(path) {
|
|
1841
2391
|
try {
|
|
1842
|
-
|
|
1843
|
-
|
|
1844
|
-
|
|
1845
|
-
const code = error.code;
|
|
1846
|
-
if (code === "ENOENT" || code === "ENOTDIR") return null;
|
|
1847
|
-
throw error;
|
|
2392
|
+
return statSync(path).isDirectory();
|
|
2393
|
+
} catch {
|
|
2394
|
+
return false;
|
|
1848
2395
|
}
|
|
1849
2396
|
}
|
|
1850
|
-
|
|
1851
|
-
//#region packages/adapter-node/src/logger-pretty.ts
|
|
1852
|
-
var import_picocolors_browser = require_picocolors_browser();
|
|
2397
|
+
// packages/adapter-node/src/logger-pretty.ts
|
|
1853
2398
|
/**
|
|
1854
2399
|
* Metric keys the pretty sink reads off the canonical-line record.
|
|
1855
2400
|
* These names match `RequestScopedMetricsRecorder.summarize()` output
|
|
@@ -1861,8 +2406,7 @@ const CANONICAL_KEYS = {
|
|
|
1861
2406
|
classB: "db.storage.class_b_ops_total",
|
|
1862
2407
|
wamp: "db.write.class_a_ops_per_logical_write_sum",
|
|
1863
2408
|
put412: "db.r2.put.412_total",
|
|
1864
|
-
put429: "db.r2.put.429_total"
|
|
1865
|
-
cacheStatus: "cache_status"
|
|
2409
|
+
put429: "db.r2.put.429_total"
|
|
1866
2410
|
};
|
|
1867
2411
|
/**
|
|
1868
2412
|
* Fixed-width column sizes for the pretty sink's HTTP line.
|
|
@@ -1876,6 +2420,15 @@ const numProp = (props, key) => {
|
|
|
1876
2420
|
const v = pickProp(props, key);
|
|
1877
2421
|
return typeof v === "number" ? v : void 0;
|
|
1878
2422
|
};
|
|
2423
|
+
const createColors = (enabled) => {
|
|
2424
|
+
const paint = (format) => (s) => enabled ? styleText(format, s, { validateStream: false }) : s;
|
|
2425
|
+
return {
|
|
2426
|
+
red: paint("red"),
|
|
2427
|
+
yellow: paint("yellow"),
|
|
2428
|
+
cyan: paint("cyan"),
|
|
2429
|
+
dim: paint("dim")
|
|
2430
|
+
};
|
|
2431
|
+
};
|
|
1879
2432
|
const colorStatus = (statusStr, status, plain, pc) => {
|
|
1880
2433
|
if (plain || status === void 0) return statusStr;
|
|
1881
2434
|
if (status >= 500) return pc.red(statusStr);
|
|
@@ -1892,7 +2445,7 @@ const renderCanonical = (record, pc, plain) => {
|
|
|
1892
2445
|
const status = numProp(props, "status");
|
|
1893
2446
|
const method = typeof pickProp(props, "method") === "string" ? String(pickProp(props, "method")) : "";
|
|
1894
2447
|
const path = typeof pickProp(props, "path") === "string" ? String(pickProp(props, "path")) : "";
|
|
1895
|
-
const prefix = `${method.padEnd(METHOD_W)}${path.length > PATH_W ? `${path.slice(0,
|
|
2448
|
+
const prefix = `${method.padEnd(METHOD_W)}${path.length > PATH_W ? `${path.slice(0, 27)}…` : path.padEnd(PATH_W)} ${colorStatus(status === void 0 ? " " : String(status), status, plain, pc)} ${durationStr}`;
|
|
1896
2449
|
const tail = [];
|
|
1897
2450
|
if (reqId) tail.push(`req=${reqId}`);
|
|
1898
2451
|
const classA = numProp(props, CANONICAL_KEYS.classA);
|
|
@@ -1905,8 +2458,6 @@ const renderCanonical = (record, pc, plain) => {
|
|
|
1905
2458
|
if (c412 !== void 0 && c412 > 0) tail.push(`412=${c412}`);
|
|
1906
2459
|
const c429 = numProp(props, CANONICAL_KEYS.put429);
|
|
1907
2460
|
if (c429 !== void 0 && c429 > 0) tail.push(`429=${c429}`);
|
|
1908
|
-
const cacheStatus = pickProp(props, CANONICAL_KEYS.cacheStatus);
|
|
1909
|
-
if (typeof cacheStatus === "string") tail.push(`cache=${cacheStatus}`);
|
|
1910
2461
|
if (status !== void 0 && status >= 400) {
|
|
1911
2462
|
const outcome = pickProp(props, "outcome");
|
|
1912
2463
|
if (typeof outcome === "string") tail.push(`outcome=${outcome}`);
|
|
@@ -1934,7 +2485,7 @@ const isPlainEnv = () => {
|
|
|
1934
2485
|
*/
|
|
1935
2486
|
const prettyConsoleSink = () => {
|
|
1936
2487
|
const plain = isPlainEnv();
|
|
1937
|
-
const pc =
|
|
2488
|
+
const pc = createColors(!plain);
|
|
1938
2489
|
return (record) => {
|
|
1939
2490
|
if (isCanonicalRecord(record)) {
|
|
1940
2491
|
console.log(renderCanonical(record, pc, plain));
|
|
@@ -1947,8 +2498,7 @@ const prettyConsoleSink = () => {
|
|
|
1947
2498
|
console.log(`${ts} ${record.level.toUpperCase()} ${cat} ${msg}${props}`);
|
|
1948
2499
|
};
|
|
1949
2500
|
};
|
|
1950
|
-
|
|
1951
|
-
//#region packages/adapter-node/src/server.ts
|
|
2501
|
+
// packages/adapter-node/src/server.ts
|
|
1952
2502
|
/**
|
|
1953
2503
|
* Assemble the per-request {@link MaintenanceDispatch} for a Node host.
|
|
1954
2504
|
*
|
|
@@ -1976,9 +2526,13 @@ const prettyConsoleSink = () => {
|
|
|
1976
2526
|
* in tests — and a real process env in production — is observed:
|
|
1977
2527
|
*
|
|
1978
2528
|
* - `BAERLY_MAINTENANCE_MAX_FOLD_BYTES` → `maxFoldBytes` (the snapshot
|
|
1979
|
-
* ceiling `C`).
|
|
1980
|
-
*
|
|
1981
|
-
*
|
|
2529
|
+
* ceiling `C`). A plain positive decimal integer; unset or `""` falls
|
|
2530
|
+
* back to the profile default; any other value throws
|
|
2531
|
+
* `BaerlyError{code:"InvalidConfig"}`.
|
|
2532
|
+
* - `BAERLY_MAINTENANCE_DISABLE` → `disabled` (kill switch). Closed,
|
|
2533
|
+
* case-insensitive vocabulary: unset/`""`/`"0"`/`"false"` → `false`;
|
|
2534
|
+
* `"1"`/`"true"` → `true`; anything else throws
|
|
2535
|
+
* `BaerlyError{code:"InvalidConfig"}`.
|
|
1982
2536
|
*
|
|
1983
2537
|
* `readEnv` defaults to `process.env`; the parameter exists for direct
|
|
1984
2538
|
* unit coverage.
|
|
@@ -1988,12 +2542,23 @@ const nodeMaintenanceDispatch = (readEnv = (k) => process.env[k]) => {
|
|
|
1988
2542
|
return {
|
|
1989
2543
|
...disabled && { disabled: true },
|
|
1990
2544
|
...maxFoldBytes !== void 0 && { maxFoldBytes },
|
|
2545
|
+
warn: logMaintenanceWarning,
|
|
1991
2546
|
options: {
|
|
1992
2547
|
phasesPerTick: "both",
|
|
1993
2548
|
profile: MAINTENANCE_PROFILE_NODE
|
|
1994
2549
|
}
|
|
1995
2550
|
};
|
|
1996
2551
|
};
|
|
2552
|
+
const mappedErrorResponse = (error) => {
|
|
2553
|
+
const { status, envelope } = mapError(error);
|
|
2554
|
+
return {
|
|
2555
|
+
status,
|
|
2556
|
+
response: new Response(JSON.stringify(envelope), {
|
|
2557
|
+
status,
|
|
2558
|
+
headers: { "content-type": "application/json" }
|
|
2559
|
+
})
|
|
2560
|
+
};
|
|
2561
|
+
};
|
|
1997
2562
|
/**
|
|
1998
2563
|
* Build a `(req: Request) => Promise<Response>` handler that runs the
|
|
1999
2564
|
* baerly `/v1/*` cascade: healthz short-circuit → observability context
|
|
@@ -2023,36 +2588,72 @@ function createFetchHandler(opts) {
|
|
|
2023
2588
|
verifier: opts.verifier,
|
|
2024
2589
|
config: opts.config
|
|
2025
2590
|
}));
|
|
2591
|
+
const requestId = requestIdFrom(request.headers);
|
|
2592
|
+
let maintenance;
|
|
2593
|
+
try {
|
|
2594
|
+
maintenance = nodeMaintenanceDispatch();
|
|
2595
|
+
} catch (error) {
|
|
2596
|
+
const obsCtx = createObservabilityContext({ request_id: requestId });
|
|
2597
|
+
return await runWithContext(obsCtx, async () => {
|
|
2598
|
+
const { status, response } = mappedErrorResponse(error);
|
|
2599
|
+
flushCanonicalLine(obsCtx, obsCtx.recorder, {
|
|
2600
|
+
unit: "http",
|
|
2601
|
+
status,
|
|
2602
|
+
outcome: deriveOutcome(request.method, status, error),
|
|
2603
|
+
error,
|
|
2604
|
+
extra: {
|
|
2605
|
+
method: request.method,
|
|
2606
|
+
path
|
|
2607
|
+
}
|
|
2608
|
+
});
|
|
2609
|
+
return response;
|
|
2610
|
+
});
|
|
2611
|
+
}
|
|
2026
2612
|
const obsCtx = createObservabilityContext({
|
|
2027
|
-
request_id:
|
|
2028
|
-
maintenance
|
|
2613
|
+
request_id: requestId,
|
|
2614
|
+
maintenance,
|
|
2615
|
+
ledger: new RequestLedger()
|
|
2029
2616
|
});
|
|
2030
|
-
const result = await opts.verifier(request);
|
|
2031
|
-
if (result === null) return await runWithContext(obsCtx, async () => flushUnauthorizedAndRespond(obsCtx, request));
|
|
2032
2617
|
return await runWithContext(obsCtx, async () => {
|
|
2618
|
+
let result;
|
|
2619
|
+
try {
|
|
2620
|
+
result = await opts.verifier(request);
|
|
2621
|
+
} catch (error) {
|
|
2622
|
+
const { status, response } = mappedErrorResponse(error);
|
|
2623
|
+
flushCanonicalLine(obsCtx, obsCtx.recorder, {
|
|
2624
|
+
unit: "http",
|
|
2625
|
+
status,
|
|
2626
|
+
outcome: deriveOutcome(request.method, status, error),
|
|
2627
|
+
error,
|
|
2628
|
+
extra: {
|
|
2629
|
+
method: request.method,
|
|
2630
|
+
path
|
|
2631
|
+
}
|
|
2632
|
+
});
|
|
2633
|
+
return response;
|
|
2634
|
+
}
|
|
2635
|
+
if (result === null) return flushUnauthorizedAndRespond(obsCtx, request);
|
|
2033
2636
|
let outboundStatus = 500;
|
|
2034
2637
|
let caughtError;
|
|
2035
2638
|
let response;
|
|
2036
2639
|
try {
|
|
2640
|
+
const db = Db.create({
|
|
2641
|
+
storage: wrappedStorage,
|
|
2642
|
+
app: opts.app,
|
|
2643
|
+
tenant: result.tenantPrefix,
|
|
2644
|
+
config: opts.config
|
|
2645
|
+
});
|
|
2037
2646
|
response = await createRouter({
|
|
2038
|
-
db
|
|
2039
|
-
storage: wrappedStorage,
|
|
2040
|
-
app: opts.app,
|
|
2041
|
-
tenant: result.tenantPrefix,
|
|
2042
|
-
config: opts.config
|
|
2043
|
-
}),
|
|
2647
|
+
db,
|
|
2044
2648
|
...opts.sinceTimeoutMs !== void 0 && { sinceTimeoutMs: opts.sinceTimeoutMs },
|
|
2045
2649
|
...opts.sincePollIntervalMs !== void 0 && { sincePollIntervalMs: opts.sincePollIntervalMs }
|
|
2046
2650
|
}).fetch(request);
|
|
2047
2651
|
outboundStatus = response.status;
|
|
2048
2652
|
} catch (error) {
|
|
2049
2653
|
caughtError = error;
|
|
2050
|
-
const { status,
|
|
2654
|
+
const { status, response: mappedResponse } = mappedErrorResponse(error);
|
|
2051
2655
|
outboundStatus = status;
|
|
2052
|
-
response =
|
|
2053
|
-
status,
|
|
2054
|
-
headers: { "content-type": "application/json" }
|
|
2055
|
-
});
|
|
2656
|
+
response = mappedResponse;
|
|
2056
2657
|
} finally {
|
|
2057
2658
|
flushCanonicalLine(obsCtx, obsCtx.recorder, {
|
|
2058
2659
|
unit: "http",
|
|
@@ -2092,8 +2693,7 @@ const resolveDefaultSink = (config) => {
|
|
|
2092
2693
|
sink: isTty ? prettyConsoleSink() : "console-json"
|
|
2093
2694
|
};
|
|
2094
2695
|
};
|
|
2095
|
-
|
|
2096
|
-
//#region packages/adapter-node/src/app.ts
|
|
2696
|
+
// packages/adapter-node/src/app.ts
|
|
2097
2697
|
/**
|
|
2098
2698
|
* Build a Hono app that serves the baerly cascade plus Node-host
|
|
2099
2699
|
* middleware (dev-landing when `dev` is set, then static-assets when
|
|
@@ -2120,6 +2720,11 @@ const resolveDefaultSink = (config) => {
|
|
|
2120
2720
|
function createApp(opts) {
|
|
2121
2721
|
const fetchHandler = createFetchHandler(opts);
|
|
2122
2722
|
const app = new Hono();
|
|
2723
|
+
app.use("*", async (c, next) => {
|
|
2724
|
+
await next();
|
|
2725
|
+
const res = withNosniff(c.res);
|
|
2726
|
+
if (res !== c.res) c.res = res;
|
|
2727
|
+
});
|
|
2123
2728
|
if (opts.dev !== void 0) app.use("*", devLandingMiddleware({ dev: opts.dev }));
|
|
2124
2729
|
if (opts.webRoot !== void 0) app.use("*", staticAssetsMiddleware({ webRoot: opts.webRoot }));
|
|
2125
2730
|
app.all("*", async (c) => {
|
|
@@ -2129,15 +2734,14 @@ function createApp(opts) {
|
|
|
2129
2734
|
});
|
|
2130
2735
|
return app;
|
|
2131
2736
|
}
|
|
2132
|
-
|
|
2133
|
-
//#region packages/adapter-node/src/baerly-node.ts
|
|
2737
|
+
// packages/adapter-node/src/baerly-node.ts
|
|
2134
2738
|
/**
|
|
2135
2739
|
* Mount baerly on `node:http` with one call. Mirrors `baerlyWorker`
|
|
2136
2740
|
* from `@baerly/adapter-cloudflare`.
|
|
2137
2741
|
*
|
|
2138
2742
|
* Composes:
|
|
2139
2743
|
* - {@link createApp} → exposed as `handle.fetch` for in-process
|
|
2140
|
-
* embedding; wrapped in `@hono/node-server.
|
|
2744
|
+
* embedding; wrapped in `@hono/node-server.createAdaptorServer({ fetch, createServer })`
|
|
2141
2745
|
* lazily when `listen()` is called.
|
|
2142
2746
|
* - SIGTERM + SIGINT handlers installed on `listen()` that call
|
|
2143
2747
|
* `close()` and `process.exit(0)`. On any error during close,
|
|
@@ -2151,8 +2755,16 @@ function createApp(opts) {
|
|
|
2151
2755
|
* onto the per-request observability context, which the writer reads at
|
|
2152
2756
|
* its post-commit dispatch point. Reads never tick. Tune via the
|
|
2153
2757
|
* `BAERLY_MAINTENANCE_MAX_FOLD_BYTES` / `BAERLY_MAINTENANCE_DISABLE`
|
|
2154
|
-
* env vars
|
|
2155
|
-
* `
|
|
2758
|
+
* env vars. `BAERLY_MAINTENANCE_DISABLE` accepts unset / `""` / `"0"` /
|
|
2759
|
+
* `"false"` (enabled) or `"1"` / `"true"` (disabled), case-insensitively;
|
|
2760
|
+
* anything else throws `BaerlyError{code:"InvalidConfig"}`.
|
|
2761
|
+
* `BAERLY_MAINTENANCE_MAX_FOLD_BYTES` uses a plain positive decimal
|
|
2762
|
+
* integer as the override; unset or empty values use the Node profile
|
|
2763
|
+
* default, and any other value throws `InvalidConfig`. These
|
|
2764
|
+
* values are re-read for API/database requests that reach maintenance
|
|
2765
|
+
* dispatch; health/spec and configured dev/static short-circuits bypass
|
|
2766
|
+
* them. For an explicit out-of-band sweep, call
|
|
2767
|
+
* `runScheduledMaintenance` from `@gusto/baerly-storage/maintenance`.
|
|
2156
2768
|
*
|
|
2157
2769
|
* @example
|
|
2158
2770
|
* ```ts
|
|
@@ -2175,13 +2787,26 @@ function createApp(opts) {
|
|
|
2175
2787
|
* await handle.listen(Number(process.env["PORT"] ?? 8080));
|
|
2176
2788
|
* ```
|
|
2177
2789
|
*/
|
|
2790
|
+
/**
|
|
2791
|
+
* Host used to build the request URL when a request carries no Host
|
|
2792
|
+
* header (HTTP/1.0): the bound address, with an IPv6 literal bracketed
|
|
2793
|
+
* so the URL parses, or `0.0.0.0` for an all-interfaces bind.
|
|
2794
|
+
*/
|
|
2795
|
+
function fallbackHost(hostname) {
|
|
2796
|
+
if (hostname === void 0) return "0.0.0.0";
|
|
2797
|
+
return hostname.includes(":") ? `[${hostname}]` : hostname;
|
|
2798
|
+
}
|
|
2178
2799
|
function baerlyNode(opts) {
|
|
2179
2800
|
const verifier = resolveVerifier({
|
|
2180
2801
|
factoryVerifier: opts.verifier,
|
|
2181
2802
|
config: opts.config,
|
|
2182
2803
|
readEnv: (k) => process.env[k]
|
|
2183
2804
|
});
|
|
2184
|
-
if (opts.verifier === void 0 && opts.config.auth === "none")
|
|
2805
|
+
if (opts.verifier === void 0 && opts.config.auth === "none") {
|
|
2806
|
+
const tenant = JSON.stringify(opts.config.tenant);
|
|
2807
|
+
if (isDeployedEnv(process.env)) console.warn(`[baerly] auth=none in a deployed environment — every request, from any caller, gets full access to tenant=${tenant}`);
|
|
2808
|
+
else console.log(`[baerly] auth=none — all requests resolve to tenant=${tenant}`);
|
|
2809
|
+
}
|
|
2185
2810
|
const app = createApp({
|
|
2186
2811
|
app: opts.config.app,
|
|
2187
2812
|
storage: opts.storage,
|
|
@@ -2194,16 +2819,16 @@ function baerlyNode(opts) {
|
|
|
2194
2819
|
...opts.sincePollIntervalMs !== void 0 && { sincePollIntervalMs: opts.sincePollIntervalMs }
|
|
2195
2820
|
});
|
|
2196
2821
|
let server;
|
|
2822
|
+
let bind;
|
|
2197
2823
|
let signalHandler;
|
|
2198
|
-
let
|
|
2199
|
-
const
|
|
2200
|
-
if (closed) return;
|
|
2201
|
-
closed = true;
|
|
2824
|
+
let closing;
|
|
2825
|
+
const shutdown = async () => {
|
|
2202
2826
|
if (signalHandler !== void 0) {
|
|
2203
2827
|
process.off("SIGTERM", signalHandler);
|
|
2204
2828
|
process.off("SIGINT", signalHandler);
|
|
2205
2829
|
signalHandler = void 0;
|
|
2206
2830
|
}
|
|
2831
|
+
await bind?.catch(() => void 0);
|
|
2207
2832
|
await new Promise((resolve, reject) => {
|
|
2208
2833
|
if (server === void 0) {
|
|
2209
2834
|
resolve();
|
|
@@ -2219,36 +2844,38 @@ function baerlyNode(opts) {
|
|
|
2219
2844
|
});
|
|
2220
2845
|
});
|
|
2221
2846
|
};
|
|
2222
|
-
const
|
|
2223
|
-
|
|
2847
|
+
const close = () => {
|
|
2848
|
+
closing ??= shutdown();
|
|
2849
|
+
return closing;
|
|
2850
|
+
};
|
|
2851
|
+
const listen = async (port, options) => {
|
|
2852
|
+
if (closing !== void 0) throw new BaerlyError("InvalidConfig", "baerlyNode: listen() called after close(); create a new handle");
|
|
2853
|
+
const hostname = options?.hostname;
|
|
2854
|
+
server = createAdaptorServer({
|
|
2224
2855
|
fetch: app.fetch,
|
|
2225
|
-
|
|
2226
|
-
hostname: "0.0.0.0",
|
|
2856
|
+
hostname: fallbackHost(hostname),
|
|
2227
2857
|
createServer
|
|
2228
2858
|
});
|
|
2229
2859
|
const httpServer = server;
|
|
2230
|
-
|
|
2860
|
+
bind = new Promise((resolve, reject) => {
|
|
2231
2861
|
const onError = (err) => {
|
|
2232
2862
|
httpServer.off("listening", onListening);
|
|
2233
|
-
httpServer.off("close", onClose);
|
|
2234
2863
|
reject(err);
|
|
2235
2864
|
};
|
|
2236
2865
|
const onListening = () => {
|
|
2237
2866
|
httpServer.off("error", onError);
|
|
2238
|
-
httpServer.off("close", onClose);
|
|
2239
|
-
resolve();
|
|
2240
|
-
};
|
|
2241
|
-
const onClose = () => {
|
|
2242
|
-
httpServer.off("error", onError);
|
|
2243
|
-
httpServer.off("listening", onListening);
|
|
2244
2867
|
resolve();
|
|
2245
2868
|
};
|
|
2246
2869
|
httpServer.once("error", onError);
|
|
2247
2870
|
httpServer.once("listening", onListening);
|
|
2248
|
-
httpServer.
|
|
2249
|
-
httpServer.listen(port);
|
|
2871
|
+
if (hostname === void 0) httpServer.listen(port);
|
|
2872
|
+
else httpServer.listen(port, hostname);
|
|
2250
2873
|
});
|
|
2251
|
-
|
|
2874
|
+
await bind;
|
|
2875
|
+
if (closing !== void 0) {
|
|
2876
|
+
await close();
|
|
2877
|
+
return;
|
|
2878
|
+
}
|
|
2252
2879
|
signalHandler = (sig) => {
|
|
2253
2880
|
console.log(`Received ${sig}; closing baerlyNode server`);
|
|
2254
2881
|
close().then(() => process.exit(0)).catch((error) => {
|
|
@@ -2265,7 +2892,6 @@ function baerlyNode(opts) {
|
|
|
2265
2892
|
close
|
|
2266
2893
|
};
|
|
2267
2894
|
}
|
|
2268
|
-
|
|
2269
|
-
export { fromEksPodIdentity as a, localFsStorage as c, r2Storage as d, s3Storage as f, fromWebIdentity as i, gcsStorage as l, getRequestListener as n, assertStorageReachable as o, fromEks as r, resolveStorageFromEnv as s, baerlyNode as t, minioStorage as u };
|
|
2895
|
+
export { fromEksPodIdentity as a, localFsStorage as c, r2Storage as d, s3Storage as f, fromWebIdentity as i, gcsStorage as l, getRequestListener as n, assertStorageReachable as o, gcsVersioningStatus as p, fromEks as r, resolveStorageFromEnv as s, baerlyNode as t, minioStorage as u };
|
|
2270
2896
|
|
|
2271
|
-
//# sourceMappingURL=src-
|
|
2897
|
+
//# sourceMappingURL=src-Actga-bO.js.map
|