@nifrajs/core 2.2.0 → 2.3.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.
Files changed (133) hide show
  1. package/README.md +2 -2
  2. package/dist/assurance.d.ts +48 -4
  3. package/dist/assurance.d.ts.map +1 -1
  4. package/dist/assurance.js +87 -9
  5. package/dist/assurance.js.map +1 -1
  6. package/dist/binary.d.ts +54 -0
  7. package/dist/binary.d.ts.map +1 -0
  8. package/dist/binary.js +90 -0
  9. package/dist/binary.js.map +1 -0
  10. package/dist/budget.d.ts +1 -1
  11. package/dist/budget.js +1 -1
  12. package/dist/capabilities.d.ts +19 -2
  13. package/dist/capabilities.d.ts.map +1 -1
  14. package/dist/capabilities.js +60 -8
  15. package/dist/capabilities.js.map +1 -1
  16. package/dist/classification.d.ts +1 -1
  17. package/dist/classification.js +1 -1
  18. package/dist/diff.d.ts +6 -6
  19. package/dist/diff.js +6 -6
  20. package/dist/durable-adapters.d.ts.map +1 -1
  21. package/dist/durable-adapters.js +36 -70
  22. package/dist/durable-adapters.js.map +1 -1
  23. package/dist/durable-execution.d.ts +2 -2
  24. package/dist/durable-execution.js +2 -2
  25. package/dist/idempotency.d.ts +3 -3
  26. package/dist/idempotency.js +4 -4
  27. package/dist/index.d.ts +3 -3
  28. package/dist/index.js +3 -3
  29. package/dist/internal/brand.d.ts +1 -1
  30. package/dist/internal/brand.js +1 -1
  31. package/dist/internal/route-catalog.d.ts +58 -0
  32. package/dist/internal/route-catalog.d.ts.map +1 -0
  33. package/dist/internal/route-catalog.js +58 -0
  34. package/dist/internal/route-catalog.js.map +1 -0
  35. package/dist/internal/route-execution.d.ts +75 -0
  36. package/dist/internal/route-execution.d.ts.map +1 -0
  37. package/dist/internal/route-execution.js +2 -0
  38. package/dist/internal/route-execution.js.map +1 -0
  39. package/dist/internal/same-origin.d.ts +29 -0
  40. package/dist/internal/same-origin.d.ts.map +1 -0
  41. package/dist/internal/same-origin.js +47 -0
  42. package/dist/internal/same-origin.js.map +1 -0
  43. package/dist/internal/secret.d.ts +1 -1
  44. package/dist/internal/secret.js +1 -1
  45. package/dist/ledger.d.ts +9 -9
  46. package/dist/ledger.js +5 -5
  47. package/dist/reflection.d.ts +1 -1
  48. package/dist/router/pattern.js +4 -4
  49. package/dist/router/router.js +3 -3
  50. package/dist/schema/standard.d.ts +2 -2
  51. package/dist/schema/standard.js +2 -2
  52. package/dist/seo.d.ts +3 -3
  53. package/dist/seo.js +4 -4
  54. package/dist/server/body.d.ts +2 -2
  55. package/dist/server/body.js +2 -2
  56. package/dist/server/context.d.ts +18 -18
  57. package/dist/server/contract.d.ts +7 -7
  58. package/dist/server/contract.js +3 -3
  59. package/dist/server/cookies.d.ts +4 -4
  60. package/dist/server/cookies.js +8 -8
  61. package/dist/server/edge.d.ts +83 -0
  62. package/dist/server/edge.d.ts.map +1 -0
  63. package/dist/server/edge.js +71 -0
  64. package/dist/server/edge.js.map +1 -0
  65. package/dist/server/install.d.ts +2 -0
  66. package/dist/server/install.d.ts.map +1 -1
  67. package/dist/server/install.js +2 -0
  68. package/dist/server/install.js.map +1 -1
  69. package/dist/server/logger.d.ts +7 -7
  70. package/dist/server/logger.js +4 -4
  71. package/dist/server/registry.d.ts +5 -5
  72. package/dist/server/response-contract-lane.d.ts +91 -0
  73. package/dist/server/response-contract-lane.d.ts.map +1 -0
  74. package/dist/server/response-contract-lane.js +81 -0
  75. package/dist/server/response-contract-lane.js.map +1 -0
  76. package/dist/server/server.d.ts +52 -91
  77. package/dist/server/server.d.ts.map +1 -1
  78. package/dist/server/server.js +130 -186
  79. package/dist/server/server.js.map +1 -1
  80. package/dist/server/sse.d.ts +4 -4
  81. package/dist/server/sse.js +7 -7
  82. package/dist/server/webhook.d.ts +1 -1
  83. package/dist/server/webhook.js +5 -5
  84. package/dist/server/websocket.d.ts +19 -19
  85. package/dist/server/websocket.js +9 -9
  86. package/dist/server/ws-bun.d.ts +4 -4
  87. package/dist/server/ws-bun.js +3 -3
  88. package/dist/server.d.ts +3 -1
  89. package/dist/server.d.ts.map +1 -1
  90. package/dist/server.js +3 -1
  91. package/dist/server.js.map +1 -1
  92. package/dist/transport-codec.d.ts +12 -0
  93. package/dist/transport-codec.d.ts.map +1 -1
  94. package/dist/transport-codec.js +19 -4
  95. package/dist/transport-codec.js.map +1 -1
  96. package/package.json +12 -2
  97. package/src/assurance.ts +154 -8
  98. package/src/binary.ts +128 -0
  99. package/src/budget.ts +1 -1
  100. package/src/capabilities.ts +71 -9
  101. package/src/classification.ts +1 -1
  102. package/src/diff.ts +8 -8
  103. package/src/durable-adapters.ts +40 -70
  104. package/src/durable-execution.ts +2 -2
  105. package/src/idempotency.ts +4 -4
  106. package/src/index.ts +3 -3
  107. package/src/internal/brand.ts +1 -1
  108. package/src/internal/route-catalog.ts +94 -0
  109. package/src/internal/route-execution.ts +106 -0
  110. package/src/internal/same-origin.ts +43 -0
  111. package/src/internal/secret.ts +1 -1
  112. package/src/ledger.ts +11 -11
  113. package/src/reflection.ts +1 -1
  114. package/src/router/pattern.ts +4 -4
  115. package/src/router/router.ts +5 -5
  116. package/src/schema/standard.ts +2 -2
  117. package/src/seo.ts +6 -6
  118. package/src/server/body.ts +2 -2
  119. package/src/server/context.ts +18 -18
  120. package/src/server/contract.ts +13 -13
  121. package/src/server/cookies.ts +8 -8
  122. package/src/server/edge.ts +150 -0
  123. package/src/server/install.ts +5 -0
  124. package/src/server/logger.ts +8 -8
  125. package/src/server/registry.ts +5 -5
  126. package/src/server/response-contract-lane.ts +164 -0
  127. package/src/server/server.ts +159 -366
  128. package/src/server/sse.ts +11 -11
  129. package/src/server/webhook.ts +5 -5
  130. package/src/server/websocket.ts +22 -22
  131. package/src/server/ws-bun.ts +4 -4
  132. package/src/server.ts +8 -5
  133. package/src/transport-codec.ts +24 -5
package/dist/ledger.d.ts CHANGED
@@ -4,7 +4,7 @@
4
4
  * Every owned effect seam (a repository write, an external call, an email send) records one entry via
5
5
  * the `useCapability` beacon. The entry type is deliberately **token-only**: capability ids, phase,
6
6
  * an adapter/resource token, dimensionless cost counters, an optional keyed digest, and an error code.
7
- * There is no free-form payload field — request bodies, rows, and values cannot enter the ledger, so
7
+ * There is no free-form payload field - request bodies, rows, and values cannot enter the ledger, so
8
8
  * redaction holds by construction rather than by filtering. The sealed ledger carries the **route
9
9
  * pattern** (`/users/:id`), never the concrete URL, so path parameters cannot leak either.
10
10
  *
@@ -22,7 +22,7 @@ export type EffectPhase = "intent" | "committed" | "failed" | "compensated";
22
22
  export type EffectCost = Readonly<Record<string, number>>;
23
23
  /** Token-only caller metadata shared by an effect intent and outcome. */
24
24
  export interface EffectMetadata {
25
- /** Adapter/resource token (`repo:orders`, `provider:payments`). A token — never a value or a row. */
25
+ /** Adapter/resource token (`repo:orders`, `provider:payments`). A token - never a value or a row. */
26
26
  readonly target?: string;
27
27
  /** Dimensionless counters; see {@link EffectCost}. At most {@link MAX_COST_AXES} axes. */
28
28
  readonly cost?: EffectCost;
@@ -37,7 +37,7 @@ export interface EffectEntryInput extends EffectMetadata {
37
37
  readonly capability: string;
38
38
  /** Default `"intent"`. Record `committed`/`failed`/`compensated` only after the outcome is known. */
39
39
  readonly phase?: EffectPhase;
40
- /** Outcome error as a bounded token code — never a message, never a stack. */
40
+ /** Outcome error as a bounded token code - never a message, never a stack. */
41
41
  readonly error?: {
42
42
  readonly code: string;
43
43
  };
@@ -68,10 +68,10 @@ export interface EffectChain {
68
68
  /** The immutable result of sealing a request's ledger. Token-only; safe to hand to any sink. */
69
69
  export interface SealedEffectLedger {
70
70
  readonly method: string;
71
- /** The registered route pattern (`/users/:id`) — never the concrete request URL. */
71
+ /** The registered route pattern (`/users/:id`) - never the concrete request URL. */
72
72
  readonly path: string;
73
73
  readonly entries: readonly EffectEntry[];
74
- /** The route's declared capability tokens — the runtime-enforcement view: recorded ⊆ declared is
74
+ /** The route's declared capability tokens - the runtime-enforcement view: recorded ⊆ declared is
75
75
  * guaranteed by the beacon, and `declared` minus the recorded ids is the unused declaration set. */
76
76
  readonly declared: readonly string[];
77
77
  /** Present when the ledger was created with `chain: true`. */
@@ -87,7 +87,7 @@ export declare class EffectLedgerOverflowError extends Error {
87
87
  readonly maxEntries: number;
88
88
  constructor(maxEntries: number);
89
89
  }
90
- /** Thrown by `append` after `seal()` — e.g. an effect attempted while streaming a response body. */
90
+ /** Thrown by `append` after `seal()` - e.g. an effect attempted while streaming a response body. */
91
91
  export declare class EffectLedgerSealedError extends Error {
92
92
  constructor();
93
93
  }
@@ -99,13 +99,13 @@ export interface RequestLedger {
99
99
  entries(): readonly EffectEntry[];
100
100
  readonly size: number;
101
101
  readonly sealed: boolean;
102
- /** Finalize the ledger (computing the chain when enabled). Idempotent — always the same result. */
102
+ /** Finalize the ledger (computing the chain when enabled). Idempotent - always the same result. */
103
103
  seal(): Promise<SealedEffectLedger>;
104
104
  }
105
105
  export interface CreateRequestLedgerOptions {
106
106
  /** HTTP method of the matched route. */
107
107
  readonly method: string;
108
- /** The registered route pattern — callers must never pass the concrete request URL. */
108
+ /** The registered route pattern - callers must never pass the concrete request URL. */
109
109
  readonly path: string;
110
110
  /** The route's declared capability tokens, surfaced verbatim on the sealed ledger. Default `[]`. */
111
111
  readonly declared?: readonly string[];
@@ -138,7 +138,7 @@ export interface MemoryLedgerSink {
138
138
  export declare function createMemoryLedgerSink(options?: MemoryLedgerSinkOptions): MemoryLedgerSink;
139
139
  /** Minimum digest key material. A short key would make the keyed digest brute-forceable. */
140
140
  export declare const MIN_DIGEST_KEY_BYTES = 16;
141
- /** Fresh random digest key (32 bytes). Per-process by default — persist one externally to correlate across restarts. */
141
+ /** Fresh random digest key (32 bytes). Per-process by default - persist one externally to correlate across restarts. */
142
142
  export declare function randomEffectDigestKey(): Uint8Array;
143
143
  /**
144
144
  * Keyed HMAC-SHA-256 digest (hex) of an effect payload, for replay/reconciliation matching without
package/dist/ledger.js CHANGED
@@ -4,7 +4,7 @@
4
4
  * Every owned effect seam (a repository write, an external call, an email send) records one entry via
5
5
  * the `useCapability` beacon. The entry type is deliberately **token-only**: capability ids, phase,
6
6
  * an adapter/resource token, dimensionless cost counters, an optional keyed digest, and an error code.
7
- * There is no free-form payload field — request bodies, rows, and values cannot enter the ledger, so
7
+ * There is no free-form payload field - request bodies, rows, and values cannot enter the ledger, so
8
8
  * redaction holds by construction rather than by filtering. The sealed ledger carries the **route
9
9
  * pattern** (`/users/:id`), never the concrete URL, so path parameters cannot leak either.
10
10
  *
@@ -24,7 +24,7 @@ export class EffectLedgerOverflowError extends Error {
24
24
  this.name = "EffectLedgerOverflowError";
25
25
  }
26
26
  }
27
- /** Thrown by `append` after `seal()` — e.g. an effect attempted while streaming a response body. */
27
+ /** Thrown by `append` after `seal()` - e.g. an effect attempted while streaming a response body. */
28
28
  export class EffectLedgerSealedError extends Error {
29
29
  constructor() {
30
30
  super("effect ledger is sealed: effects cannot be recorded after the response settles");
@@ -145,7 +145,7 @@ class BoundedRequestLedger {
145
145
  if (input.error !== undefined && !ERROR_CODE.test(input.error.code)) {
146
146
  throw new TypeError("effect ledger: error code must be a bounded lowercase token");
147
147
  }
148
- // Only the known token fields are copied — a stray `payload`-like property never survives append.
148
+ // Only the known token fields are copied - a stray `payload`-like property never survives append.
149
149
  const at = this.clock();
150
150
  if (!Number.isFinite(at) || at < 0) {
151
151
  throw new TypeError("effect ledger: clock must return a finite non-negative number");
@@ -199,7 +199,7 @@ class BoundedRequestLedger {
199
199
  export function createRequestLedger(options) {
200
200
  return new BoundedRequestLedger(options);
201
201
  }
202
- /** Canonical, key-ordered serialization of one entry — the hash-chain input. */
202
+ /** Canonical, key-ordered serialization of one entry - the hash-chain input. */
203
203
  function canonicalEntry(entry) {
204
204
  const cost = entry.cost === undefined
205
205
  ? ""
@@ -247,7 +247,7 @@ export function createMemoryLedgerSink(options = {}) {
247
247
  }
248
248
  /** Minimum digest key material. A short key would make the keyed digest brute-forceable. */
249
249
  export const MIN_DIGEST_KEY_BYTES = 16;
250
- /** Fresh random digest key (32 bytes). Per-process by default — persist one externally to correlate across restarts. */
250
+ /** Fresh random digest key (32 bytes). Per-process by default - persist one externally to correlate across restarts. */
251
251
  export function randomEffectDigestKey() {
252
252
  const bytes = new Uint8Array(32);
253
253
  crypto.getRandomValues(bytes);
@@ -30,7 +30,7 @@ export interface SchemaReflection {
30
30
  export interface ReflectedRouteSchema {
31
31
  readonly body?: SchemaReflection;
32
32
  readonly query?: SchemaReflection;
33
- /** Path-params schema — constraints (uuid format, integer min/max) declared via `params: t.object(…)`. */
33
+ /** Path-params schema - constraints (uuid format, integer min/max) declared via `params: t.object(…)`. */
34
34
  readonly params?: SchemaReflection;
35
35
  readonly response?: SchemaReflection;
36
36
  readonly errors?: Readonly<Record<string, SchemaReflection>>;
@@ -34,19 +34,19 @@ function validParamName(name) {
34
34
  *
35
35
  * The grammar is per-segment: a segment is wholly static or wholly a parameter, so everything after
36
36
  * the colon is the name. `/v/:id.json` therefore asks for a parameter literally named `id.json`,
37
- * which is not what anyone means by it — but the bare "invalid parameter" that produces reads as a
37
+ * which is not what anyone means by it - but the bare "invalid parameter" that produces reads as a
38
38
  * typo rather than as a rule, leaving the author to guess whether the dot, the length, or the casing
39
39
  * was the problem. Naming the actual limitation and showing the two ways out is the difference
40
40
  * between a five-second fix and a trip to the source.
41
41
  */
42
42
  function paramNameHint(name) {
43
43
  if (RESERVED_PARAM_NAMES.has(name))
44
- return ` — "${name}" is reserved (prototype key)`;
44
+ return ` - "${name}" is reserved (prototype key)`;
45
45
  if (name.length === 0)
46
- return ` — ":" needs a name after it`;
46
+ return ` - ":" needs a name after it`;
47
47
  // No "a segment is wholly static or wholly a parameter" case here any more: mixed segments made
48
48
  // that message obsolete. `:id.json` was the shape it explained, and `:id.json` now compiles.
49
- return ` — a name must match ${PARAM_NAME.source}`;
49
+ return ` - a name must match ${PARAM_NAME.source}`;
50
50
  }
51
51
  function escapeRegex(value) {
52
52
  return value.replace(/[.*+?^()|[\]\\{}$]/g, "\\$&");
@@ -45,7 +45,7 @@ function sameNames(a, b) {
45
45
  * instead of pre-splitting it into an array. `start` is the index of the first
46
46
  * char of the current segment; the segment runs to the next `/` (or end). Tries
47
47
  * static, then param, then wildcard; if a static branch dead-ends, param/wildcard
48
- * are still attempted — so `/a/b/c` and `/a/:x/d` coexist and `/a/b/d` resolves
48
+ * are still attempted - so `/a/b/c` and `/a/:x/d` coexist and `/a/b/d` resolves
49
49
  * to the param route. Fills `paramValues` along the successful path; abandoned
50
50
  * branches are popped. Avoiding the split keeps `find` allocation-light: only the
51
51
  * segment substrings needed for map lookups (and matched param values) are cut.
@@ -95,9 +95,9 @@ function matchNode(node, path, start, len, paramValues) {
95
95
  }
96
96
  }
97
97
  const paramChild = node.paramChild;
98
- // An empty segment (`/users//posts`) never matches a `:param` — matching would hand the handler
98
+ // An empty segment (`/users//posts`) never matches a `:param` - matching would hand the handler
99
99
  // `id: ""` and downstream code a `WHERE id = ''` class of bug. Peers (Hono, Elysia, Next) 404
100
- // here too; a static "" child can still match (none is ever registered — INVALID_PATH guards).
100
+ // here too; a static "" child can still match (none is ever registered - INVALID_PATH guards).
101
101
  if (paramChild !== undefined && seg.length > 0) {
102
102
  paramValues.push(seg);
103
103
  if (isLast) {
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * The Standard Schema v1 interface (https://standardschema.dev), vendored as
3
- * types + a tiny runtime helper so any compliant validator — zod, valibot,
4
- * arktype, … — validates requests without coupling the framework to one lib.
3
+ * types + a tiny runtime helper so any compliant validator - zod, valibot,
4
+ * arktype, … - validates requests without coupling the framework to one lib.
5
5
  * The spec is MIT-licensed and explicitly designed to be copied.
6
6
  */
7
7
  export interface StandardSchemaV1<Input = unknown, Output = Input> {
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * The Standard Schema v1 interface (https://standardschema.dev), vendored as
3
- * types + a tiny runtime helper so any compliant validator — zod, valibot,
4
- * arktype, … — validates requests without coupling the framework to one lib.
3
+ * types + a tiny runtime helper so any compliant validator - zod, valibot,
4
+ * arktype, … - validates requests without coupling the framework to one lib.
5
5
  * The spec is MIT-licensed and explicitly designed to be copied.
6
6
  */
7
7
  function normalizeStandardResult(result) {
package/dist/seo.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * `sitemap.xml` + `robots.txt` builders — pure, edge-safe string generators (no I/O, no runtime deps).
2
+ * `sitemap.xml` + `robots.txt` builders - pure, edge-safe string generators (no I/O, no runtime deps).
3
3
  * Wire them to a route on any runtime:
4
4
  *
5
5
  * app.get("/sitemap.xml", () =>
@@ -16,10 +16,10 @@ export type SitemapChangeFreq = "always" | "hourly" | "daily" | "weekly" | "mont
16
16
  export interface SitemapEntry {
17
17
  /** An absolute URL, or a path that `hostname` will make absolute. */
18
18
  readonly url: string;
19
- /** Last-modified — a `Date` (serialized as ISO 8601) or a pre-formatted W3C-datetime string. */
19
+ /** Last-modified - a `Date` (serialized as ISO 8601) or a pre-formatted W3C-datetime string. */
20
20
  readonly lastmod?: string | Date;
21
21
  readonly changefreq?: SitemapChangeFreq;
22
- /** Crawl priority, `0.0`–`1.0`. */
22
+ /** Crawl priority, `0.0`-`1.0`. */
23
23
  readonly priority?: number;
24
24
  }
25
25
  export interface SitemapOptions {
package/dist/seo.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * `sitemap.xml` + `robots.txt` builders — pure, edge-safe string generators (no I/O, no runtime deps).
2
+ * `sitemap.xml` + `robots.txt` builders - pure, edge-safe string generators (no I/O, no runtime deps).
3
3
  * Wire them to a route on any runtime:
4
4
  *
5
5
  * app.get("/sitemap.xml", () =>
@@ -19,7 +19,7 @@ const XML_ESCAPES = {
19
19
  '"': "&quot;",
20
20
  "'": "&apos;",
21
21
  };
22
- /** Escape the five XML metacharacters — `<loc>` and `<lastmod>` carry app- or DB-derived strings. */
22
+ /** Escape the five XML metacharacters - `<loc>` and `<lastmod>` carry app- or DB-derived strings. */
23
23
  function escapeXml(value) {
24
24
  return value.replace(/[&<>"']/g, (char) => XML_ESCAPES[char]);
25
25
  }
@@ -37,7 +37,7 @@ const SITEMAP_MAX_URLS = 50_000;
37
37
  /** Build a `<urlset>` sitemap XML document from `entries`. Throws on out-of-spec input (dev-time data). */
38
38
  export function sitemap(entries, options = {}) {
39
39
  if (entries.length > SITEMAP_MAX_URLS) {
40
- throw new RangeError(`sitemap: ${entries.length} entries exceeds the ${SITEMAP_MAX_URLS}-URL per-file limit — split into a sitemap index`);
40
+ throw new RangeError(`sitemap: ${entries.length} entries exceeds the ${SITEMAP_MAX_URLS}-URL per-file limit - split into a sitemap index`);
41
41
  }
42
42
  const base = options.hostname?.replace(/\/+$/, "");
43
43
  const urls = entries.map((entry) => {
@@ -66,7 +66,7 @@ function resolveLoc(url, base) {
66
66
  if (/^https?:\/\//i.test(url))
67
67
  return url; // already absolute
68
68
  if (base === undefined)
69
- return url; // relative — caller's choice (sitemaps prefer absolute)
69
+ return url; // relative - caller's choice (sitemaps prefer absolute)
70
70
  return `${base}${url.startsWith("/") ? "" : "/"}${url}`;
71
71
  }
72
72
  /** robots.txt is line-oriented, so a newline in any value could inject a forged directive. Flatten it. */
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Bounded request-body reading — the single source of truth for nifra's body-size cap. A lying or
2
+ * Bounded request-body reading - the single source of truth for nifra's body-size cap. A lying or
3
3
  * absent `Content-Length` can't force us to buffer an oversized payload: a declared length over the
4
4
  * cap is rejected *before* buffering, and a chunked / length-less body is aborted mid-stream once the
5
5
  * running byte count exceeds the cap. Shared by the server's schema path, `c.boundedBody`, and
@@ -13,7 +13,7 @@ interface BodySource {
13
13
  export declare function parseContentLength(value: string): number | undefined;
14
14
  /** The shared streaming byte-cap loop: read until done, or cancel + 413 once over `maxBytes`.
15
15
  * A single-chunk body (the common case for small chunked payloads) returns the runtime's own
16
- * chunk directly — no chunk array, no copy-merge. */
16
+ * chunk directly - no chunk array, no copy-merge. */
17
17
  export declare function drainCapped(body: ReadableStream<Uint8Array>, maxBytes: number): Promise<{
18
18
  ok: true;
19
19
  bytes: Uint8Array;
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Bounded request-body reading — the single source of truth for nifra's body-size cap. A lying or
2
+ * Bounded request-body reading - the single source of truth for nifra's body-size cap. A lying or
3
3
  * absent `Content-Length` can't force us to buffer an oversized payload: a declared length over the
4
4
  * cap is rejected *before* buffering, and a chunked / length-less body is aborted mid-stream once the
5
5
  * running byte count exceeds the cap. Shared by the server's schema path, `c.boundedBody`, and
@@ -21,7 +21,7 @@ export function parseContentLength(value) {
21
21
  }
22
22
  /** The shared streaming byte-cap loop: read until done, or cancel + 413 once over `maxBytes`.
23
23
  * A single-chunk body (the common case for small chunked payloads) returns the runtime's own
24
- * chunk directly — no chunk array, no copy-merge. */
24
+ * chunk directly - no chunk array, no copy-merge. */
25
25
  export async function drainCapped(body, maxBytes) {
26
26
  const reader = body.getReader();
27
27
  let first;
@@ -54,12 +54,12 @@ export interface RouteSchema {
54
54
  * Dedupe retries of this (mutating) route on an `Idempotency-Key` header. The first request runs and
55
55
  * its response is stored; a retry with the same key replays that response without re-running the
56
56
  * handler, and a key reused with a different body is rejected (409). A missing key on an
57
- * idempotency-required route fails closed (400). Off the hot path — routes without it are unchanged.
57
+ * idempotency-required route fails closed (400). Off the hot path - routes without it are unchanged.
58
58
  */
59
59
  readonly idempotency?: IdempotencyConfig;
60
60
  /**
61
61
  * Highest data-sensitivity this route's response body carries (`public` | `pii` | `secret`). A
62
- * declarative, compile-time + introspection fact — never validated at runtime. Reflected for tooling,
62
+ * declarative, compile-time + introspection fact - never validated at runtime. Reflected for tooling,
63
63
  * recorded in the capability lockfile (so a route that starts returning PII is a reviewable change),
64
64
  * and read by downstream policy (e.g. a partner-API surface refusing to expose `pii`/`secret`).
65
65
  */
@@ -96,20 +96,20 @@ export interface RouteSchema {
96
96
  readonly query?: StandardSchemaV1;
97
97
  /** Optional **response contract**. When declared: the handler's return is type-checked against it
98
98
  * (the implementation can't drift from the contract), the typed client sees THIS as the response type
99
- * (the contract — not the handler's incidental return), and it's emitted into OpenAPI/JSON-Schema so
99
+ * (the contract - not the handler's incidental return), and it's emitted into OpenAPI/JSON-Schema so
100
100
  * tooling and coding agents can read the exact shape. It is **not** validated at runtime (zero
101
- * hot-path cost) — purely a compile-time + introspection contract. */
101
+ * hot-path cost) - purely a compile-time + introspection contract. */
102
102
  readonly response?: StandardSchemaV1;
103
103
  /**
104
104
  * Optional **error-response contract**: a map of HTTP status code → the Standard Schema of that error's
105
105
  * body. Declares a route's failure modes so they flow into OpenAPI (as non-2xx `responses`), the
106
- * `/llms.txt` context, and other introspection — the whole contract, not just the happy path, is legible
106
+ * `/llms.txt` context, and other introspection - the whole contract, not just the happy path, is legible
107
107
  * to tooling and coding agents. Like `response`, it is **not** validated at runtime (zero hot-path cost);
108
108
  * it's a compile-time + introspection contract. Example: `{ 404: NotFound, 409: Conflict }`. */
109
109
  readonly errors?: Readonly<Record<number, StandardSchemaV1>>;
110
110
  /**
111
111
  * Optional **SSE event contract**: the Standard Schema of each event's `data` payload on a
112
- * streaming route (declared via `app.sse()`). Marks the route as a typed event stream — the
112
+ * streaming route (declared via `app.sse()`). Marks the route as a typed event stream - the
113
113
  * typed client grows a `.subscribe()` for it, and the schema flows into reflection. Like
114
114
  * `response`, it is **not** validated at runtime (zero hot-path cost); the server-side
115
115
  * `stream.send()` is compile-time-checked against it instead.
@@ -121,7 +121,7 @@ export interface RouteSchema {
121
121
  * - a **`Response`** → returned as-is, short-circuiting the route (custom error envelope, redirect, …).
122
122
  * - **any other value** → treated as a repaired payload and **re-validated once** against the same
123
123
  * schema. If it now passes, the handler runs with it; if it still fails, the original `422` stands.
124
- * Re-validation means a bad return can't bypass the schema — the trust boundary holds.
124
+ * Re-validation means a bad return can't bypass the schema - the trust boundary holds.
125
125
  * - **`undefined`** → give up; the original validation `422` is returned unchanged.
126
126
  * A route hook **overrides** the app-wide default set via `server({ onValidationError })`; return
127
127
  * `undefined` to fall through to the plain `422` even when an app default exists. Typical uses: a custom
@@ -147,8 +147,8 @@ export interface ResponseControls {
147
147
  status?: number;
148
148
  readonly headers: Record<string, string>;
149
149
  /**
150
- * Queue a `Set-Cookie` on the response. Defaults are **secure-by-default** —
151
- * `HttpOnly; Secure; SameSite=Lax; Path=/` — overridable per call (pass `{ secure: false }` for
150
+ * Queue a `Set-Cookie` on the response. Defaults are **secure-by-default** -
151
+ * `HttpOnly; Secure; SameSite=Lax; Path=/` - overridable per call (pass `{ secure: false }` for
152
152
  * local http dev). Multiple calls set multiple cookies (they're merged via a `Headers` object, so
153
153
  * they don't collapse the way the plain `headers` Record would). Sign the value with `signValue`
154
154
  * for tamper-evidence (what `@nifrajs/auth` sessions do).
@@ -165,7 +165,7 @@ export interface ResponseControls {
165
165
  */
166
166
  export interface Platform<Env = unknown> {
167
167
  /** Platform bindings (KV/D1/secrets on Workers). Typed as `Env` when the app declares them via
168
- * `server<Env>()`; otherwise `unknown` — validate before use. */
168
+ * `server<Env>()`; otherwise `unknown` - validate before use. */
169
169
  readonly env?: Env;
170
170
  /** Extend the response's lifetime for background work (Workers `ctx.waitUntil`). */
171
171
  readonly waitUntil?: (promise: Promise<unknown>) => void;
@@ -182,7 +182,7 @@ export interface Platform<Env = unknown> {
182
182
  export interface Context<Path extends string = string, S extends RouteSchema = RouteSchema> {
183
183
  readonly req: Request;
184
184
  /**
185
- * Alias of {@link req} — the same `Request`. Page loaders/actions receive their request as `request`;
185
+ * Alias of {@link req} - the same `Request`. Page loaders/actions receive their request as `request`;
186
186
  * this alias lets route handlers and loaders share one name, so `c.request` and `ctx.req` both work
187
187
  * everywhere (no more `c.req` vs `ctx.request` mismatch).
188
188
  */
@@ -191,12 +191,12 @@ export interface Context<Path extends string = string, S extends RouteSchema = R
191
191
  readonly query: QueryOf<S>;
192
192
  readonly body: BodyOf<S>;
193
193
  /** The request's cookies, parsed from the `Cookie` header (values URL-decoded). Parsed lazily on
194
- * first access + cached. Signed cookies arrive as `value.signature` — verify with `unsignValue`. */
194
+ * first access + cached. Signed cookies arrive as `value.signature` - verify with `unsignValue`. */
195
195
  readonly cookies: Readonly<Record<string, string>>;
196
196
  readonly set: ResponseControls;
197
197
  /**
198
198
  * Aborts when the server's `requestTimeoutMs` elapses (and never, when no timeout
199
- * is configured). Pass it to cancellation-aware work — DB drivers, `fetch` — so a
199
+ * is configured). Pass it to cancellation-aware work - DB drivers, `fetch` - so a
200
200
  * timed-out request stops doing work instead of running on after the 503.
201
201
  */
202
202
  readonly signal: AbortSignal;
@@ -206,14 +206,14 @@ export interface Context<Path extends string = string, S extends RouteSchema = R
206
206
  */
207
207
  readonly budget: RequestBudget;
208
208
  /**
209
- * Platform bindings from `app.fetch(request, { env })` — Workers `env` (KV/D1/secrets), etc.
209
+ * Platform bindings from `app.fetch(request, { env })` - Workers `env` (KV/D1/secrets), etc.
210
210
  * `undefined` off-edge (Bun/Node/Deno). Declare the shape with `server<Env>()` to read it typed
211
211
  * (`c.env: Env`); otherwise `unknown`. Validate at the trust boundary before use either way.
212
212
  */
213
213
  readonly env: unknown;
214
214
  /**
215
215
  * The caller's IP. By default the raw socket peer the serving adapter observed (`listen()`,
216
- * `@nifrajs/node`, `@nifrajs/deno`) — the one address a client cannot forge — or `undefined` when the
216
+ * `@nifrajs/node`, `@nifrajs/deno`) - the one address a client cannot forge - or `undefined` when the
217
217
  * runtime exposes no socket (Workers) and no trust is declared. Behind a proxy/CDN, set the
218
218
  * `clientIp` server option (`{ trustedHops }` or `{ header }`) to derive the real caller from the
219
219
  * forwarding chain as far as you trust it; unset, no forwarded header is ever believed. Safe to key
@@ -228,8 +228,8 @@ export interface Context<Path extends string = string, S extends RouteSchema = R
228
228
  readonly waitUntil: (promise: Promise<unknown>) => void;
229
229
  /**
230
230
  * Read the raw request body as bytes, **capped** at `maxBytes` (default: the server's
231
- * `maxBodyBytes`). For routes with **no body schema** — raw bodies, file uploads,
232
- * BYO-validation — where the automatic schema cap doesn't apply. An over-cap body (by
231
+ * `maxBodyBytes`). For routes with **no body schema** - raw bodies, file uploads,
232
+ * BYO-validation - where the automatic schema cap doesn't apply. An over-cap body (by
233
233
  * `Content-Length` or while streaming) throws a flat `413`; a malformed `Content-Length`
234
234
  * throws `400`. Consumes the body stream (call once). Pass a larger `maxBytes` for an
235
235
  * upload route, a smaller one to tighten a specific endpoint.
@@ -243,7 +243,7 @@ export interface Context<Path extends string = string, S extends RouteSchema = R
243
243
  readonly boundedJson: <T = unknown>(maxBytes?: number) => Promise<T>;
244
244
  /**
245
245
  * Build a JSON `Response`. Pass a status number or a full `ResponseInit` as the second arg. `return` it
246
- * from a handler, or `throw` it from `derive`/`beforeHandle` to short-circuit — both work:
246
+ * from a handler, or `throw` it from `derive`/`beforeHandle` to short-circuit - both work:
247
247
  * `throw c.json({ error: "unauthorized" }, 401)`. A terser alternative to
248
248
  * `new Response(JSON.stringify(...), { status, headers: { "content-type": "application/json" } })`.
249
249
  */
@@ -15,7 +15,7 @@ export interface ResponseDef {
15
15
  /**
16
16
  * One operation in a contract. Input schemas are any Standard Schema; `response` is optional.
17
17
  *
18
- * The fields below `response` are **optional OpenAPI metadata** — they don't affect runtime
18
+ * The fields below `response` are **optional OpenAPI metadata** - they don't affect runtime
19
19
  * validation or the inferred handler types, they enrich the document `toOpenAPI` emits. A contract is
20
20
  * the natural home for them: it's the versionable description of the API, decoupled from the impl.
21
21
  */
@@ -80,7 +80,7 @@ type OpErrors<O extends OperationDef> = O extends {
80
80
  * RouteInfo as a *decoupled consumer* sees it from the contract alone: the
81
81
  * `output` is the declared `response` schema's type, or `unknown` when none is
82
82
  * declared (the consumer can't know the response without the server). Path/method
83
- * levels are mutable and fields are `readonly` — matching the inline registry, so
83
+ * levels are mutable and fields are `readonly` - matching the inline registry, so
84
84
  * the two are mutually assignable.
85
85
  */
86
86
  type RouteInfoForOp<O extends OperationDef> = {
@@ -112,7 +112,7 @@ type SchemaForOp<O extends OperationDef> = (O extends {
112
112
  params: P;
113
113
  } : Record<never, never>);
114
114
  /**
115
- * The handler context for an op — identical to the inline `Context<Path, S>`, so a
115
+ * The handler context for an op - identical to the inline `Context<Path, S>`, so a
116
116
  * handler written for an inline route type-checks unchanged under `implement`
117
117
  * (the graduation guarantee).
118
118
  */
@@ -120,9 +120,9 @@ export type ContextForOp<O extends OperationDef> = Context<O["path"], SchemaForO
120
120
  type MaybePromise<T> = T | Promise<T>;
121
121
  /**
122
122
  * What a handler may return for an op. When the op declares a `response`, the return is constrained to
123
- * that contract shape (or a raw `Response`) — so an `implement`ed backend can't drift from the response
123
+ * that contract shape (or a raw `Response`) - so an `implement`ed backend can't drift from the response
124
124
  * the contract's client was built against. With no `response` it's unconstrained (`unknown`), identical
125
- * to before. Purely type-level — erased at compile time, zero runtime cost — and mirrors the inline
125
+ * to before. Purely type-level - erased at compile time, zero runtime cost - and mirrors the inline
126
126
  * route's `ResponseOf` constraint, so a handler graduates inline↔contract unchanged.
127
127
  */
128
128
  type HandlerReturnForOp<O extends OperationDef> = O extends {
@@ -148,7 +148,7 @@ export declare function defineContract<const C extends ContractShape>(contract:
148
148
  type AnyFn = (...args: never[]) => unknown;
149
149
  /**
150
150
  * The registry produced by `implement`: input from the contract op; `output` is the declared `response`
151
- * contract when present (it wins — exactly as in the inline path), else the bound HANDLER's return — so
151
+ * contract when present (it wins - exactly as in the inline path), else the bound HANDLER's return - so
152
152
  * the implemented server stays route-for-route identical to the equivalent inline server (the
153
153
  * mode-conformance guarantee), and a contract-typed client and a `typeof app`-typed client agree.
154
154
  */
@@ -169,7 +169,7 @@ export type RegistryFromImpl<C extends ContractShape, H extends HandlersFor<C, C
169
169
  /**
170
170
  * Bind handlers to a contract, producing a real {@link Server} you can `.listen()`
171
171
  * or `.fetch()`. Each op is registered through the same path as the inline
172
- * builder, so the result is identical to writing the routes inline — handlers
172
+ * builder, so the result is identical to writing the routes inline - handlers
173
173
  * lift over **unchanged** ("graduation"), and body/query schemas validate at the
174
174
  * request boundary exactly as in inline mode.
175
175
  *
@@ -33,7 +33,7 @@ export function defineContract(contract) {
33
33
  /**
34
34
  * Bind handlers to a contract, producing a real {@link Server} you can `.listen()`
35
35
  * or `.fetch()`. Each op is registered through the same path as the inline
36
- * builder, so the result is identical to writing the routes inline — handlers
36
+ * builder, so the result is identical to writing the routes inline - handlers
37
37
  * lift over **unchanged** ("graduation"), and body/query schemas validate at the
38
38
  * request boundary exactly as in inline mode.
39
39
  *
@@ -54,9 +54,9 @@ export function implement(contract, handlers, app) {
54
54
  const target = (app ?? new Server());
55
55
  const routes = Object.entries(contract).map(([name, op]) => {
56
56
  // body/query are validated at the request boundary; `response` is a type + introspection contract
57
- // ONLY — never validated at runtime and never read on the request hot path (the lifecycle reads
57
+ // ONLY - never validated at runtime and never read on the request hot path (the lifecycle reads
58
58
  // schema.body/query by name; the `bare`/bodyOnly/queryOnly fast-path gates ignore `response`). Built
59
- // once here at bind time, not per request — it just carries a reference to the op's existing schema.
59
+ // once here at bind time, not per request - it just carries a reference to the op's existing schema.
60
60
  // A response-less op still yields `undefined`, byte-identical to before.
61
61
  const schema = op.params !== undefined ||
62
62
  op.body !== undefined ||
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Cookie primitives — parse a request `Cookie` header, serialize a `Set-Cookie`, and sign/verify a
2
+ * Cookie primitives - parse a request `Cookie` header, serialize a `Set-Cookie`, and sign/verify a
3
3
  * value with HMAC-SHA256 via **WebCrypto** (`crypto.subtle`), so they're portable across Bun, Node,
4
4
  * Deno, and workerd with no `node:crypto` dependency. Pure + runtime-agnostic: `c.cookies` (read) and
5
5
  * `c.set.cookie` (write) build on these, and `@nifrajs/auth` builds sessions on top.
@@ -17,16 +17,16 @@ export interface CookieOptions {
17
17
  readonly partitioned?: boolean;
18
18
  }
19
19
  /** Parse a request `Cookie` header into a name→value map (values URL-decoded). Unparseable pairs are
20
- * skipped rather than throwing — a junk `Cookie` header shouldn't fail the request.
20
+ * skipped rather than throwing - a junk `Cookie` header shouldn't fail the request.
21
21
  *
22
22
  * Hand-rolled index walk instead of `split(";")` + `trim()` chains: those allocated an array + up
23
23
  * to three substrings per pair and showed up at ~6% of a realistic (auth + cookie) request. Same
24
24
  * semantics, two slices per pair, no intermediate array. */
25
25
  export declare function parseCookies(header: string | null | undefined): Record<string, string>;
26
26
  /**
27
- * Serialize a `Set-Cookie` header value. Pure — applies **no** security defaults (the caller, e.g.
27
+ * Serialize a `Set-Cookie` header value. Pure - applies **no** security defaults (the caller, e.g.
28
28
  * `c.set.cookie`, layers `HttpOnly`/`Secure`/`SameSite` on). Throws on an invalid cookie name, a
29
- * header-injecting `Path`/`Domain`, a non-integer `maxAge`, or an oversized result — a serialization
29
+ * header-injecting `Path`/`Domain`, a non-integer `maxAge`, or an oversized result - a serialization
30
30
  * bug should fail loudly, not silently emit a cookie the browser drops.
31
31
  */
32
32
  export declare function serializeCookie(name: string, value: string, options?: CookieOptions): string;
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Cookie primitives — parse a request `Cookie` header, serialize a `Set-Cookie`, and sign/verify a
2
+ * Cookie primitives - parse a request `Cookie` header, serialize a `Set-Cookie`, and sign/verify a
3
3
  * value with HMAC-SHA256 via **WebCrypto** (`crypto.subtle`), so they're portable across Bun, Node,
4
4
  * Deno, and workerd with no `node:crypto` dependency. Pure + runtime-agnostic: `c.cookies` (read) and
5
5
  * `c.set.cookie` (write) build on these, and `@nifrajs/auth` builds sessions on top.
@@ -7,8 +7,8 @@
7
7
  import { requireSecretBytes } from "../internal/secret.js";
8
8
  // RFC 6265 cookie-name token: visible ASCII minus separators/whitespace/controls.
9
9
  const COOKIE_NAME = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
10
- const MAX_COOKIE_BYTES = 4096; // browsers cap a cookie near 4 KB — reject oversized before the wire
11
- /** True if `v` contains a character illegal in a cookie attribute (control char or `;` separator) —
10
+ const MAX_COOKIE_BYTES = 4096; // browsers cap a cookie near 4 KB - reject oversized before the wire
11
+ /** True if `v` contains a character illegal in a cookie attribute (control char or `;` separator) -
12
12
  * the header-injection guard for dev-supplied `Path`/`Domain`. */
13
13
  const hasIllegalChar = (v) => {
14
14
  for (let i = 0; i < v.length; i++) {
@@ -19,7 +19,7 @@ const hasIllegalChar = (v) => {
19
19
  return false;
20
20
  };
21
21
  const safeDecode = (v) => {
22
- // No `%` ⇒ nothing to decode — skip the call AND its try frame (profiled: cookie values are
22
+ // No `%` ⇒ nothing to decode - skip the call AND its try frame (profiled: cookie values are
23
23
  // overwhelmingly plain; this was ~3% of a realistic request).
24
24
  if (!v.includes("%"))
25
25
  return v;
@@ -31,7 +31,7 @@ const safeDecode = (v) => {
31
31
  }
32
32
  };
33
33
  /** Parse a request `Cookie` header into a name→value map (values URL-decoded). Unparseable pairs are
34
- * skipped rather than throwing — a junk `Cookie` header shouldn't fail the request.
34
+ * skipped rather than throwing - a junk `Cookie` header shouldn't fail the request.
35
35
  *
36
36
  * Hand-rolled index walk instead of `split(";")` + `trim()` chains: those allocated an array + up
37
37
  * to three substrings per pair and showed up at ~6% of a realistic (auth + cookie) request. Same
@@ -86,9 +86,9 @@ export function parseCookies(header) {
86
86
  return out;
87
87
  }
88
88
  /**
89
- * Serialize a `Set-Cookie` header value. Pure — applies **no** security defaults (the caller, e.g.
89
+ * Serialize a `Set-Cookie` header value. Pure - applies **no** security defaults (the caller, e.g.
90
90
  * `c.set.cookie`, layers `HttpOnly`/`Secure`/`SameSite` on). Throws on an invalid cookie name, a
91
- * header-injecting `Path`/`Domain`, a non-integer `maxAge`, or an oversized result — a serialization
91
+ * header-injecting `Path`/`Domain`, a non-integer `maxAge`, or an oversized result - a serialization
92
92
  * bug should fail loudly, not silently emit a cookie the browser drops.
93
93
  */
94
94
  export function serializeCookie(name, value, options = {}) {
@@ -152,7 +152,7 @@ const fromBase64Url = (s) => {
152
152
  return bytes;
153
153
  }
154
154
  catch {
155
- return null; // not valid base64 — treat as a bad signature
155
+ return null; // not valid base64 - treat as a bad signature
156
156
  }
157
157
  };
158
158
  /** Append an HMAC-SHA256 signature to a value → `value.signature` (base64url). For signed cookies. */