@tangle-network/agent-app 0.45.21 → 0.45.22

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 (110) hide show
  1. package/dist/DesignCanvas-ZG7DJS7C.js +10 -0
  2. package/dist/DesignCanvasEditor-SLFMHOII.js +13 -0
  3. package/dist/app-auth/index.js +2 -2
  4. package/dist/assistant/index.d.ts +1 -1
  5. package/dist/assistant/index.js +5 -5
  6. package/dist/{attachment-validation-CsmUzuI3.d.ts → attachment-validation-BfJDBU1g.d.ts} +41 -5
  7. package/dist/{auth-DJjJBtYw.d.ts → auth-BYtiazA4.d.ts} +1 -1
  8. package/dist/chat-react/index.js +2 -2
  9. package/dist/chat-routes/index.d.ts +8 -4
  10. package/dist/chat-routes/index.js +21 -4
  11. package/dist/chat-routes/index.js.map +1 -1
  12. package/dist/{chunk-KPRBFNGT.js → chunk-3IHYJIDJ.js} +3 -3
  13. package/dist/{chunk-MYS7DHMM.js → chunk-4QVG4WJQ.js} +2 -2
  14. package/dist/{chunk-RMHZKMQ4.js → chunk-73CQJOIU.js} +5 -5
  15. package/dist/chunk-CCVG2TL6.js +327 -0
  16. package/dist/chunk-CCVG2TL6.js.map +1 -0
  17. package/dist/{chunk-U4BXAZCN.js → chunk-DRB77FYL.js} +2 -2
  18. package/dist/{chunk-6MUJROBT.js → chunk-E4DHYENH.js} +2 -2
  19. package/dist/chunk-F7VH4G5C.js +283 -0
  20. package/dist/chunk-F7VH4G5C.js.map +1 -0
  21. package/dist/chunk-I24YIKHO.js +183 -0
  22. package/dist/chunk-I24YIKHO.js.map +1 -0
  23. package/dist/{chunk-AH3IOSWF.js → chunk-NZVBJM73.js} +1432 -187
  24. package/dist/chunk-NZVBJM73.js.map +1 -0
  25. package/dist/{chunk-OO4DROKM.js → chunk-OASVAPRL.js} +3 -3
  26. package/dist/{chunk-ZSGTG6PK.js → chunk-P5PIAQVS.js} +2 -2
  27. package/dist/chunk-PC2WYTK7.js +405 -0
  28. package/dist/chunk-PC2WYTK7.js.map +1 -0
  29. package/dist/{chunk-YEFFHORB.js → chunk-TX6S7XXU.js} +8 -2
  30. package/dist/chunk-TX6S7XXU.js.map +1 -0
  31. package/dist/chunk-UGWQLQDS.js +35 -0
  32. package/dist/chunk-UGWQLQDS.js.map +1 -0
  33. package/dist/{chunk-O22STZ3P.js → chunk-X5DQ5QOP.js} +2 -2
  34. package/dist/{chunk-PCJHEZA7.js → chunk-YABHE2QY.js} +2 -2
  35. package/dist/design-canvas/index.d.ts +3 -3
  36. package/dist/design-canvas/index.js +2 -2
  37. package/dist/design-canvas-react/engine.js +4 -4
  38. package/dist/design-canvas-react/index.js +7 -7
  39. package/dist/design-canvas-react/lazy.js +1 -1
  40. package/dist/documents/index.d.ts +233 -0
  41. package/dist/documents/index.js +495 -0
  42. package/dist/documents/index.js.map +1 -0
  43. package/dist/documents/pdf-inspector.d.ts +60 -0
  44. package/dist/documents/pdf-inspector.js +100 -0
  45. package/dist/documents/pdf-inspector.js.map +1 -0
  46. package/dist/eval/index.d.ts +1 -1
  47. package/dist/fold-DACU7gtf.d.ts +320 -0
  48. package/dist/{mcp-BiKqnsJV.d.ts → mcp-xxoZZfor.d.ts} +2 -2
  49. package/dist/openui/index.d.ts +208 -0
  50. package/dist/openui/index.js +350 -0
  51. package/dist/openui/index.js.map +1 -0
  52. package/dist/openui-react/index.d.ts +119 -0
  53. package/dist/openui-react/index.js +149 -0
  54. package/dist/openui-react/index.js.map +1 -0
  55. package/dist/platform/index.js +2 -2
  56. package/dist/preset-cloudflare/index.d.ts +2 -2
  57. package/dist/rate-limit-BOVmJRXZ.d.ts +35 -0
  58. package/dist/record/drizzle.d.ts +682 -0
  59. package/dist/record/drizzle.js +579 -0
  60. package/dist/record/drizzle.js.map +1 -0
  61. package/dist/record/index.d.ts +16 -0
  62. package/dist/record/index.js +35 -0
  63. package/dist/record/index.js.map +1 -0
  64. package/dist/runtime/index.d.ts +3 -3
  65. package/dist/sandbox/index.d.ts +2 -2
  66. package/dist/sandbox/index.js +3 -2
  67. package/dist/sequences/index.d.ts +3 -3
  68. package/dist/sequences/index.js +1 -1
  69. package/dist/session-shell/index.d.ts +173 -1
  70. package/dist/session-shell/index.js +13 -1
  71. package/dist/teams/index.js +9 -9
  72. package/dist/teams/invitations-api.js +3 -3
  73. package/dist/tools/index.d.ts +5 -5
  74. package/dist/tools/index.js +3 -2
  75. package/dist/{types-DbU-oO5h.d.ts → types-B25Mib1r.d.ts} +11 -0
  76. package/dist/types-DrBidf3O.d.ts +123 -0
  77. package/dist/values-C7RidJuI.d.ts +156 -0
  78. package/dist/web/index.d.ts +197 -31
  79. package/dist/web/index.js +15 -3
  80. package/dist/web-react/async/index.d.ts +309 -0
  81. package/dist/web-react/async/index.js +327 -0
  82. package/dist/web-react/async/index.js.map +1 -0
  83. package/dist/web-react/index.d.ts +338 -2
  84. package/dist/web-react/index.js +52 -6
  85. package/dist/work-product/index.d.ts +1 -1
  86. package/dist/work-product/index.js +2 -1
  87. package/dist/work-product/index.js.map +1 -1
  88. package/dist/workspace-react/index.js +1 -1
  89. package/package.json +43 -3
  90. package/dist/DesignCanvas-NEIW3AER.js +0 -10
  91. package/dist/DesignCanvasEditor-QD33OI2W.js +0 -13
  92. package/dist/chunk-AH3IOSWF.js.map +0 -1
  93. package/dist/chunk-GINKOZFD.js +0 -214
  94. package/dist/chunk-GINKOZFD.js.map +0 -1
  95. package/dist/chunk-J25RST7G.js +0 -126
  96. package/dist/chunk-J25RST7G.js.map +0 -1
  97. package/dist/chunk-WBHPN5DY.js +0 -158
  98. package/dist/chunk-WBHPN5DY.js.map +0 -1
  99. package/dist/chunk-YEFFHORB.js.map +0 -1
  100. /package/dist/{DesignCanvas-NEIW3AER.js.map → DesignCanvas-ZG7DJS7C.js.map} +0 -0
  101. /package/dist/{DesignCanvasEditor-QD33OI2W.js.map → DesignCanvasEditor-SLFMHOII.js.map} +0 -0
  102. /package/dist/{chunk-KPRBFNGT.js.map → chunk-3IHYJIDJ.js.map} +0 -0
  103. /package/dist/{chunk-MYS7DHMM.js.map → chunk-4QVG4WJQ.js.map} +0 -0
  104. /package/dist/{chunk-RMHZKMQ4.js.map → chunk-73CQJOIU.js.map} +0 -0
  105. /package/dist/{chunk-U4BXAZCN.js.map → chunk-DRB77FYL.js.map} +0 -0
  106. /package/dist/{chunk-6MUJROBT.js.map → chunk-E4DHYENH.js.map} +0 -0
  107. /package/dist/{chunk-OO4DROKM.js.map → chunk-OASVAPRL.js.map} +0 -0
  108. /package/dist/{chunk-ZSGTG6PK.js.map → chunk-P5PIAQVS.js.map} +0 -0
  109. /package/dist/{chunk-O22STZ3P.js.map → chunk-X5DQ5QOP.js.map} +0 -0
  110. /package/dist/{chunk-PCJHEZA7.js.map → chunk-YABHE2QY.js.map} +0 -0
@@ -0,0 +1,123 @@
1
+ /**
2
+ * The shapes every documents-module boundary speaks: a typed outcome, a
3
+ * stage-named error, the normalized PDF classification, and the PDF engine
4
+ * port that keeps the wasm binding out of this module's import graph.
5
+ */
6
+ /** What kind of extraction a media type routes to. */
7
+ type DocumentFormat = 'pdf' | 'docx' | 'text';
8
+ /** Where extraction stopped. Surfaced on every error so a product can tell a
9
+ * user WHERE it failed rather than "extraction failed". */
10
+ type DocumentExtractionStage = 'size-check' | 'media-type' | 'classify' | 'extract' | 'decode';
11
+ /**
12
+ * Why extraction stopped.
13
+ *
14
+ * `pdf-needs-ocr` is the load-bearing one: a scanned PDF has no text layer, so
15
+ * the only honest outcomes are this code or a lie. It is never an empty string
16
+ * and never a generic failure — a caller matches on it to offer the OCR path
17
+ * (see {@link PdfClassification.pagesNeedingOcr} for which pages).
18
+ */
19
+ type DocumentExtractionErrorCode = 'too-large' | 'unsupported-media-type' | 'pdf-engine-unavailable' | 'pdf-needs-ocr' | 'classification-failed' | 'extraction-failed' | 'malformed-archive' | 'decode-failed' | 'empty-document';
20
+ interface DocumentExtractionError {
21
+ readonly code: DocumentExtractionErrorCode;
22
+ readonly stage: DocumentExtractionStage;
23
+ /** Human-readable and safe to show a user: names the stage's cause. */
24
+ readonly message: string;
25
+ /** The media type as resolved (or as declared, when resolution is what failed). */
26
+ readonly mediaType: string;
27
+ /** Present on `pdf-needs-ocr` — the page-level detail the OCR handoff needs. */
28
+ readonly classification?: PdfClassification;
29
+ }
30
+ type DocumentOutcome<T> = {
31
+ succeeded: true;
32
+ value: T;
33
+ } | {
34
+ succeeded: false;
35
+ error: DocumentExtractionError;
36
+ };
37
+ /**
38
+ * PDF content kinds, normalized away from the engine's own vocabulary.
39
+ *
40
+ * - `text-based` — every page carries an extractable text layer.
41
+ * - `scanned` — no text layer anywhere; the pages are page images.
42
+ * - `image-based` — image content with no usable text layer (the engine
43
+ * distinguishes this from `scanned` by how the images were produced; both
44
+ * need OCR).
45
+ * - `mixed` — some pages have text, some do not.
46
+ */
47
+ type PdfContentKind = 'text-based' | 'scanned' | 'image-based' | 'mixed';
48
+ interface PdfPageClassification {
49
+ /** 1-indexed, the number a person sees in a viewer. */
50
+ readonly pageNumber: number;
51
+ /** 0-indexed, for array math. */
52
+ readonly index: number;
53
+ readonly needsOcr: boolean;
54
+ /** Engine-reported reasons, e.g. `['scanned']`. Empty when the page is fine. */
55
+ readonly ocrReasons: readonly string[];
56
+ readonly hasTable: boolean;
57
+ readonly hasColumns: boolean;
58
+ }
59
+ interface PdfClassification {
60
+ readonly kind: PdfContentKind;
61
+ readonly pageCount: number;
62
+ /** Engine confidence in `kind`, 0..1. */
63
+ readonly confidence: number;
64
+ readonly pages: readonly PdfPageClassification[];
65
+ /** 1-indexed page numbers needing OCR. The engine's two entry points disagree
66
+ * on indexing (`classifyPdf` is 0-based, `detectPdf` is 1-based); this is
67
+ * always 1-based so a consumer never has to know which one produced it. */
68
+ readonly pagesNeedingOcr: readonly number[];
69
+ /** Every page needs OCR — there is no text to extract at all. */
70
+ readonly needsOcr: boolean;
71
+ /** Some but not all pages need OCR — text is recoverable from the rest. */
72
+ readonly partiallyScanned: boolean;
73
+ readonly complexLayout: boolean;
74
+ /** The engine hit character-encoding problems; extracted text may be garbled. */
75
+ readonly hasEncodingIssues: boolean;
76
+ }
77
+ /** Plain text preserves the source's line breaks; markdown carries structure
78
+ * (headings, page markers) but reflows lines into paragraphs. */
79
+ type PdfTextFormat = 'text' | 'markdown';
80
+ /**
81
+ * The seam that keeps `@firecrawl/pdf-inspector-wasm` out of this module.
82
+ *
83
+ * A Worker cannot compile wasm from bytes at runtime, so the `.wasm` has to
84
+ * arrive as a build-time module asset from the CONSUMER's bundler — which
85
+ * means a shared library cannot import it. Implementations are supplied by the
86
+ * caller; `@tangle-network/agent-app/documents/pdf-inspector` ships the one
87
+ * that binds the firecrawl engine.
88
+ */
89
+ interface PdfEngine {
90
+ /** Must not panic on scanned input — classification is what makes extraction
91
+ * safe, so it runs first on every document. */
92
+ readonly classify: (bytes: Uint8Array) => DocumentOutcome<PdfClassification>;
93
+ /** Called only after `classify` says the requested pages carry text. */
94
+ readonly extract: (bytes: Uint8Array, format: PdfTextFormat) => DocumentOutcome<string>;
95
+ }
96
+ interface PdfExtractionDetail {
97
+ readonly classification: PdfClassification;
98
+ /** What the text actually is — see {@link ExtractDocumentOptions.preferredPdfFormat}
99
+ * for the one case where it differs from what was asked for. */
100
+ readonly textFormat: PdfTextFormat;
101
+ /** Text came from a subset of pages; the rest need OCR. */
102
+ readonly partial: boolean;
103
+ }
104
+ interface DocxExtractionDetail {
105
+ /** The OPC part the text came from, resolved through `_rels/.rels`. */
106
+ readonly part: string;
107
+ readonly paragraphCount: number;
108
+ }
109
+ interface ExtractedDocument {
110
+ /** Never empty — an empty extraction is the `empty-document` error instead. */
111
+ readonly text: string;
112
+ readonly format: DocumentFormat;
113
+ /** Canonical media type, resolved from the declared type and/or filename. */
114
+ readonly mediaType: string;
115
+ readonly byteSize: number;
116
+ readonly characterCount: number;
117
+ readonly pdf?: PdfExtractionDetail;
118
+ readonly docx?: DocxExtractionDetail;
119
+ /** Non-fatal facts the caller should surface (e.g. pages left un-OCR'd). */
120
+ readonly warnings: readonly string[];
121
+ }
122
+
123
+ export type { DocumentOutcome as D, ExtractedDocument as E, PdfEngine as P, PdfTextFormat as a, PdfClassification as b, DocxExtractionDetail as c, DocumentFormat as d, DocumentExtractionError as e, DocumentExtractionErrorCode as f, DocumentExtractionStage as g, PdfContentKind as h, PdfExtractionDetail as i, PdfPageClassification as j };
@@ -0,0 +1,156 @@
1
+ /**
2
+ * Splitting an assistant message into prose and agent-authored UI.
3
+ *
4
+ * An agent emits a page by fencing it as ```` ```openui ```` in its reply (the
5
+ * inline path) or by calling `render_ui` (the persisted-artifact path). Every
6
+ * product that renders the inline path had forked the same scanner into its own
7
+ * chat-message body; this is that scanner, once, with no React and no renderer
8
+ * import — the node union stays owned by `@tangle-network/ui`'s `./openui`.
9
+ */
10
+ /**
11
+ * The narrowest thing a host can assert about a parsed node: it names a type.
12
+ * A renderer's node union satisfies this, so
13
+ * `parseOpenUISegments<OpenUIComponentNode>(text)` hands typed nodes straight
14
+ * to the renderer with no cast at the call site.
15
+ */
16
+ interface OpenUINode {
17
+ type: string;
18
+ id?: string;
19
+ }
20
+ /** One piece of an assistant message: prose, or a page to render. */
21
+ type OpenUISegment<TNode extends OpenUINode = OpenUINode> = {
22
+ type: 'markdown';
23
+ text: string;
24
+ } | {
25
+ type: 'openui';
26
+ nodes: TNode[];
27
+ };
28
+ /**
29
+ * Split message content into markdown and OpenUI segments, in source order.
30
+ *
31
+ * A fence whose body is not JSON, or whose JSON carries no node at all, is
32
+ * returned as a fenced `json` markdown segment rather than an empty page: the
33
+ * content is still streaming, or the agent wrote something malformed, and both
34
+ * cases are better shown than swallowed into a blank card.
35
+ *
36
+ * The type argument is the caller's assertion about the node union it will
37
+ * render; this function checks only that each node names a `type`, and the
38
+ * renderer rejects types it does not know.
39
+ */
40
+ declare function parseOpenUISegments<TNode extends OpenUINode = OpenUINode>(content: string): Array<OpenUISegment<TNode>>;
41
+ /** Whether a message carries any agent-authored page at all. */
42
+ declare function hasOpenUISegment(content: string): boolean;
43
+ /** A page read back out of the vault, and its title when one was stored. */
44
+ interface OpenUIArtifact<TNode extends OpenUINode = OpenUINode> {
45
+ title?: string;
46
+ nodes: TNode[];
47
+ }
48
+ /** Why a stored page could not be read. */
49
+ interface OpenUIArtifactError {
50
+ code: 'artifact_not_json' | 'artifact_no_nodes';
51
+ message: string;
52
+ }
53
+ /** Reading a stored page either produces nodes or says why it did not. */
54
+ type OpenUIArtifactResult<TNode extends OpenUINode = OpenUINode> = {
55
+ succeeded: true;
56
+ value: OpenUIArtifact<TNode>;
57
+ } | {
58
+ succeeded: false;
59
+ error: OpenUIArtifactError;
60
+ };
61
+ /**
62
+ * Read a `render_ui` artifact back out of the vault.
63
+ *
64
+ * Two shapes are in the wild and a product cannot tell them apart from the
65
+ * path: the bare node tree that `preset-cloudflare`'s handler writes
66
+ * (`JSON.stringify(args.schema)`), and the `{ title, schema }` envelope some
67
+ * products write themselves. Reading only one of them renders an empty panel
68
+ * for the other, with nothing on screen to say why — so this reads both and
69
+ * fails loud when it is neither.
70
+ */
71
+ declare function parseOpenUIArtifact<TNode extends OpenUINode = OpenUINode>(content: string): OpenUIArtifactResult<TNode>;
72
+
73
+ /**
74
+ * The value half of an interactive OpenUI page: what a field holds, and whether
75
+ * a submitted set of field values matches the form the agent authored.
76
+ *
77
+ * The NODE vocabulary (which fields exist, how they render) has one owner —
78
+ * `@tangle-network/ui`'s `./openui` entry. This module does not restate it. It
79
+ * declares the narrowest STRUCTURAL port a host needs to check a submission:
80
+ * the field's id, its kind, and the constraints that make a value legal. A
81
+ * renderer's richer node type satisfies this port by assignment, so the two
82
+ * packages stay in step without either importing the other.
83
+ */
84
+ /** A value one OpenUI field can hold. `string[]` is a multi-select. */
85
+ type OpenUIValue = string | number | boolean | string[];
86
+ /** Submitted field values, keyed by field id. */
87
+ type OpenUIFormValues = Record<string, OpenUIValue>;
88
+ /**
89
+ * Field ids the host will accept: identifier-safe, and never a key that would
90
+ * reach `Object.prototype`. A submission arrives from a browser and is used to
91
+ * index an object, so this is a boundary check, not a style rule.
92
+ */
93
+ declare function isSafeOpenUIFieldId(id: string): boolean;
94
+ /** The input kinds a form field can be. */
95
+ type OpenUIFieldKind = 'text' | 'number' | 'currency' | 'select' | 'checkbox' | 'slider';
96
+ /** Whether a string names an input kind this contract knows. */
97
+ declare function isOpenUIFieldKind(kind: string): kind is OpenUIFieldKind;
98
+ /**
99
+ * One field, reduced to what a value check needs. A renderer node carrying
100
+ * labels, placeholders, and layout is assignable to this — the extra
101
+ * presentation properties are simply not read here.
102
+ */
103
+ interface OpenUIFieldSpec {
104
+ id: string;
105
+ kind: OpenUIFieldKind;
106
+ required?: boolean;
107
+ /** `number` / `currency` / `slider` bounds, inclusive. */
108
+ min?: number;
109
+ max?: number;
110
+ /** Increment `number` / `currency` / `slider` values must land on, measured from `min ?? 0`. */
111
+ step?: number;
112
+ /** Longest accepted `text` value. */
113
+ maxLength?: number;
114
+ /** Accepted `select` values. */
115
+ options?: ReadonlyArray<{
116
+ value: string;
117
+ }>;
118
+ /** A `select` that accepts more than one option; its value is a `string[]`. */
119
+ multiple?: boolean;
120
+ }
121
+ /** A form the host can check a submission against. */
122
+ interface OpenUIFormSpec {
123
+ id: string;
124
+ fields: readonly OpenUIFieldSpec[];
125
+ }
126
+ /** Why one field's value was rejected. */
127
+ type OpenUIFieldIssueCode = 'required' | 'type' | 'range' | 'step' | 'option' | 'length' | 'unknown_field' | 'duplicate_field' | 'unsafe_field_id';
128
+ /** One rejected field, named so a card can mark exactly that input. */
129
+ interface OpenUIFieldIssue {
130
+ fieldId: string;
131
+ code: OpenUIFieldIssueCode;
132
+ message: string;
133
+ }
134
+ /** The outcome of checking a submission against a form. */
135
+ type OpenUIFormValidation = {
136
+ ok: true;
137
+ values: OpenUIFormValues;
138
+ } | {
139
+ ok: false;
140
+ issues: OpenUIFieldIssue[];
141
+ };
142
+ /**
143
+ * Check submitted values against the form the agent authored.
144
+ *
145
+ * Fails loud on both sides of the shape: a value the form never declared is an
146
+ * error (`unknown_field`), not a silently ignored extra, because a host that
147
+ * drops it would act on a form different from the one the user filled in. A
148
+ * `required` field with no value is an error even when the caller simply never
149
+ * sent the key.
150
+ *
151
+ * On success the returned `values` contain only declared fields, in the form's
152
+ * own field order — the object a handler should act on.
153
+ */
154
+ declare function validateOpenUIFormValues(spec: OpenUIFormSpec, values: OpenUIFormValues): OpenUIFormValidation;
155
+
156
+ export { type OpenUIFormValues as O, type OpenUIFieldIssue as a, type OpenUINode as b, type OpenUIValue as c, type OpenUIFormSpec as d, type OpenUIFieldKind as e, type OpenUIArtifact as f, type OpenUIArtifactError as g, type OpenUIArtifactResult as h, type OpenUIFieldIssueCode as i, type OpenUIFieldSpec as j, type OpenUIFormValidation as k, type OpenUISegment as l, hasOpenUISegment as m, isOpenUIFieldKind as n, isSafeOpenUIFieldId as o, parseOpenUIArtifact as p, parseOpenUISegments as q, validateOpenUIFormValues as v };
@@ -1,10 +1,203 @@
1
+ import { K as KvLike } from '../rate-limit-BOVmJRXZ.js';
2
+ export { R as RateLimitResult, c as checkRateLimit } from '../rate-limit-BOVmJRXZ.js';
3
+
4
+ /**
5
+ * Rate-limit policy for FREE routes: authenticated, unmetered, compute-bearing
6
+ * endpoints.
7
+ *
8
+ * Billing meters the chat turn. Everything deterministic a product adds beside
9
+ * it — a planning recompute fired on every slider drag, a redline diff, a
10
+ * deadline computation — runs unmetered, so nothing bounds how much worker CPU
11
+ * one authenticated caller can spend. `checkRateLimit` is the primitive; this
12
+ * is the policy around it, so a route declares a cost class instead of each one
13
+ * inventing a key format, a budget, and a denial response.
14
+ *
15
+ * Three rules this enforces that a hand-rolled call site usually does not:
16
+ *
17
+ * 1. **Identity is required.** A missing subject is denied, never pooled into a
18
+ * shared bucket and never quietly keyed by IP — a shared bucket makes one
19
+ * heavy user throttle everyone, and an IP key makes one NAT do the same.
20
+ * 2. **A limiter that throws denies.** KV `get`/`put` failures are transport
21
+ * failures; treating them as "allowed" converts a KV outage into an
22
+ * unbounded-compute hole, which is exactly when the limiter matters most.
23
+ * 3. **The denial is a typed, correctable outcome** — reason, HTTP status and
24
+ * `Retry-After` — so the caller answers the client rather than failing
25
+ * opaquely or, worse, continuing.
26
+ *
27
+ * ```ts
28
+ * export const action = withFreeRouteLimit(
29
+ * {
30
+ * route: 'tax.plan.recompute',
31
+ * costClass: 'interactive',
32
+ * kv: ({ context }) => context.cloudflare.env.RATE_LIMIT_KV,
33
+ * identify: async ({ request }) => {
34
+ * const session = await requireSession(request)
35
+ * return { subject: session.userId, workspace: session.workspaceId }
36
+ * },
37
+ * },
38
+ * async ({ request }) => Response.json(recompute(await request.json())),
39
+ * )
40
+ * ```
41
+ */
42
+
43
+ /** Requests allowed per identity inside a sliding window. */
44
+ interface RateLimitBudget {
45
+ limit: number;
46
+ windowSeconds: number;
47
+ }
48
+ /**
49
+ * How expensive one call is, which is what picks the default budget.
50
+ *
51
+ * - `interactive` — a control the user drags or types into, recomputed per
52
+ * tick. Sized for sustained two-per-second interaction, so a real slider
53
+ * never trips it and a script still stops.
54
+ * - `compute` — a derivation the user triggers deliberately (recalculate a
55
+ * plan, diff a document, compute a deadline set). The default.
56
+ * - `heavy` — whole-document or whole-matter work measured in seconds of CPU.
57
+ */
58
+ type FreeRouteClass = 'interactive' | 'compute' | 'heavy';
59
+ /** Default budget per cost class. A product overrides with an explicit
60
+ * `budget` when it has measured its own route. */
61
+ declare const FREE_ROUTE_BUDGETS: Readonly<Record<FreeRouteClass, RateLimitBudget>>;
62
+ /** A workspace's shared ceiling defaults to this many times one member's, so a
63
+ * multi-seat tenant is bounded without a single active member tripping it. */
64
+ declare const WORKSPACE_BUDGET_MULTIPLIER = 5;
65
+ /** Why a call was refused. Every value is a REFUSAL — there is no reason code
66
+ * that lets the handler run. */
67
+ type FreeRouteDenialReason =
68
+ /** No authenticated subject. Not correctable by waiting. */
69
+ 'unidentified'
70
+ /** The window is full for this subject or workspace. */
71
+ | 'rate-limited'
72
+ /** The limiter itself failed (KV read/write threw). Denied, not passed. */
73
+ | 'limiter-unavailable';
74
+ /** Which window refused the call. `null` when no window was consulted. */
75
+ type FreeRouteDimension = 'subject' | 'workspace' | null;
76
+ /**
77
+ * A correctable refusal: the caller maps `status` + `retryAfterSeconds` onto a
78
+ * response (see {@link freeRouteLimitResponse}) so the client learns what to do
79
+ * next. Carrying the limiter's own failure in `cause` keeps a KV outage
80
+ * diagnosable instead of collapsing into a generic 429.
81
+ */
82
+ declare class FreeRouteLimitError extends Error {
83
+ readonly reason: FreeRouteDenialReason;
84
+ readonly status: 401 | 429 | 503;
85
+ readonly retryAfterSeconds: number;
86
+ readonly dimension: FreeRouteDimension;
87
+ readonly route: string;
88
+ constructor(init: {
89
+ reason: FreeRouteDenialReason;
90
+ status: 401 | 429 | 503;
91
+ retryAfterSeconds: number;
92
+ dimension: FreeRouteDimension;
93
+ route: string;
94
+ message: string;
95
+ cause?: unknown;
96
+ });
97
+ }
98
+ /** What remains of the binding window after an allowed call. */
99
+ interface FreeRouteAllowance {
100
+ /** Remaining calls in whichever window is tightest. */
101
+ remaining: number;
102
+ /** Unix seconds at which that window resets. */
103
+ resetAt: number;
104
+ /** The budget that window enforces. */
105
+ budget: RateLimitBudget;
106
+ /** Which window is tightest — `subject` unless a workspace ceiling binds. */
107
+ dimension: Exclude<FreeRouteDimension, null>;
108
+ }
109
+ /** Typed outcome at the route boundary: an allowance, or a refusal that says
110
+ * how to correct it. There is no third state and no silent pass. */
111
+ type FreeRouteLimitOutcome = {
112
+ succeeded: true;
113
+ value: FreeRouteAllowance;
114
+ } | {
115
+ succeeded: false;
116
+ error: FreeRouteLimitError;
117
+ };
118
+ interface FreeRouteLimitInput {
119
+ kv: KvLike;
120
+ /** Stable route name. Part of the key, so two routes never share a window. */
121
+ route: string;
122
+ /** The authenticated subject (user id). Absent or blank ⇒ denied. */
123
+ subject: string | null | undefined;
124
+ /** Tenant the call belongs to. When present, a second, wider window bounds
125
+ * the workspace as a whole. */
126
+ workspace?: string | null;
127
+ /** Cost class picking the default budget. Ignored when `budget` is given.
128
+ * Default `'compute'`. */
129
+ costClass?: FreeRouteClass;
130
+ budget?: RateLimitBudget;
131
+ /** Workspace ceiling. Defaults to the subject budget's limit multiplied by
132
+ * {@link WORKSPACE_BUDGET_MULTIPLIER} over the same window. */
133
+ workspaceBudget?: RateLimitBudget;
134
+ }
135
+ /**
136
+ * Decide whether one authenticated, unmetered call may run.
137
+ *
138
+ * Checks the subject's window first, then the workspace ceiling when a
139
+ * workspace is supplied; the tighter of the two is what the allowance reports.
140
+ * Every failure path returns a refusal — none returns an allowance.
141
+ */
142
+ declare function checkFreeRouteLimit(input: FreeRouteLimitInput): Promise<FreeRouteLimitOutcome>;
143
+ interface FreeRouteLimitResponseOptions {
144
+ /** Extra response headers (a product's security headers, CORS). */
145
+ headers?: Record<string, string>;
146
+ /** Client-facing message. Defaults to the error's own message. */
147
+ message?: string;
148
+ }
149
+ /** The refusal as an HTTP response: the error's status, a JSON body carrying
150
+ * the machine-readable `reason`, and `Retry-After` when waiting can fix it. */
151
+ declare function freeRouteLimitResponse(error: FreeRouteLimitError, options?: FreeRouteLimitResponseOptions): Response;
152
+ /** The authenticated caller behind one request. */
153
+ interface FreeRouteIdentity {
154
+ subject: string;
155
+ workspace?: string | null;
156
+ }
157
+ interface WithFreeRouteLimitOptions<TArgs> {
158
+ /** Stable route name; part of the key. */
159
+ route: string;
160
+ costClass?: FreeRouteClass;
161
+ budget?: RateLimitBudget;
162
+ workspaceBudget?: RateLimitBudget;
163
+ /** The KV binding for this request. */
164
+ kv: (args: TArgs) => KvLike;
165
+ /**
166
+ * Resolve the authenticated caller. Return `null` for an unauthenticated
167
+ * request — the wrapper then refuses with 401 and the handler never runs.
168
+ *
169
+ * A THROW here propagates: an auth lookup that failed is not the same as an
170
+ * absent session, and the wrapper will not invent a status for it. The
171
+ * handler still does not run, so the failure stays closed.
172
+ */
173
+ identify: (args: TArgs) => Promise<FreeRouteIdentity | null> | FreeRouteIdentity | null;
174
+ /** Build the refusal response. Defaults to {@link freeRouteLimitResponse}. */
175
+ onDenied?: (error: FreeRouteLimitError, args: TArgs) => Response | Promise<Response>;
176
+ }
177
+ /**
178
+ * Wrap an authenticated, unmetered, compute-bearing route handler in its
179
+ * budget. The limit is applied BEFORE the handler is entered — including
180
+ * before the request body is read — so a refused call costs a KV read, not the
181
+ * compute the route exists to do.
182
+ *
183
+ * The handler's own response is returned untouched: this never rewrites status,
184
+ * body or headers on the success path, so it cannot break a streaming or
185
+ * pre-built response.
186
+ *
187
+ * `TArgs` is the router's handler-argument object (react-router's
188
+ * `ActionFunctionArgs`, or any single-object shape a product uses).
189
+ */
190
+ declare function withFreeRouteLimit<TArgs>(options: WithFreeRouteLimitOptions<TArgs>, handler: (args: TArgs) => Response | Promise<Response>): (args: TArgs) => Promise<Response>;
191
+
1
192
  /**
2
193
  * Web-boundary utilities every agent app's routes hand-roll: JSON body parsing
3
194
  * + narrowing, request-context extraction (real client IP behind Cloudflare),
4
- * a KV-backed sliding-window rate limiter, and security response headers. Pure
5
- * mechanism — no DB, no domain. The KV is a structural interface so this needs
6
- * no `@cloudflare/workers-types` dependency.
195
+ * a KV-backed sliding-window rate limiter, the free-route budget policy built
196
+ * on it, and security response headers. Pure mechanism — no DB, no domain. The
197
+ * KV is a structural interface so this needs no `@cloudflare/workers-types`
198
+ * dependency.
7
199
  */
200
+
8
201
  type JsonObject = Record<string, unknown>;
9
202
  /** Parse + object-narrow a Request body. `[body, null]` on success, `[null,
10
203
  * errorResponse]` on a non-object body (callers `if (err) return err`). */
@@ -21,33 +214,6 @@ interface RequestContext {
21
214
  /** Extract request context for audit trails. Uses `CF-Connecting-IP` for the
22
215
  * real client IP behind Cloudflare. */
23
216
  declare function extractRequestContext(request: Request): RequestContext;
24
- /** Minimal KV contract (Cloudflare `KVNamespace` satisfies it structurally). */
25
- interface KvLike {
26
- get(key: string): Promise<string | null>;
27
- put(key: string, value: string, options?: {
28
- expirationTtl?: number;
29
- }): Promise<void>;
30
- }
31
- /** Describe the outcome of a rate limit check including allowance, remaining count, and reset time */
32
- interface RateLimitResult {
33
- allowed: boolean;
34
- remaining: number;
35
- resetAt: number;
36
- }
37
- /** KV-backed sliding-window rate limit. Stores recent timestamps per key,
38
- * prunes the window, allows until `limit` is hit.
39
- *
40
- * Read-modify-write is best-effort, NOT atomic: KV has no compare-and-swap, so
41
- * two requests racing on the same key can each read the same pre-state and both
42
- * write — a concurrent burst can momentarily admit up to one extra request per
43
- * racing writer. This is acceptable for coarse abuse limiting; it is NOT a hard
44
- * quota gate.
45
- *
46
- * Fail-CLOSED on unreadable state: corrupt/non-array KV (a poisoned or
47
- * truncated value) is treated as a full window, so a tampered key cannot reset
48
- * the count and bypass the limiter. A bare `JSON.parse` here would throw and
49
- * abort the request handler, silently disabling the limit (fail-open). */
50
- declare function checkRateLimit(kv: KvLike, key: string, limit: number, windowSeconds: number): Promise<RateLimitResult>;
51
217
  /** Define options for configuring cookie attributes and behavior */
52
218
  interface CookieOptions {
53
219
  name: string;
@@ -106,4 +272,4 @@ declare function addSecurityHeaders(response: Response, opts?: SecurityHeaderOpt
106
272
  */
107
273
  declare function assertMediaUrl(url: string, what?: string): void;
108
274
 
109
- export { type CookieOptions, type JsonObject, type KvLike, type RateLimitResult, type RequestContext, STANDARD_SECURITY_HEADERS, type SecurityHeaderOptions, addSecurityHeaders, assertMediaUrl, checkRateLimit, clearCookieHeader, extractRequestContext, parseJsonObjectBody, readCookieValue, requireString, serializeCookie };
275
+ export { type CookieOptions, FREE_ROUTE_BUDGETS, type FreeRouteAllowance, type FreeRouteClass, type FreeRouteDenialReason, type FreeRouteDimension, type FreeRouteIdentity, FreeRouteLimitError, type FreeRouteLimitInput, type FreeRouteLimitOutcome, type FreeRouteLimitResponseOptions, type JsonObject, KvLike, type RateLimitBudget, type RequestContext, STANDARD_SECURITY_HEADERS, type SecurityHeaderOptions, WORKSPACE_BUDGET_MULTIPLIER, type WithFreeRouteLimitOptions, addSecurityHeaders, assertMediaUrl, checkFreeRouteLimit, clearCookieHeader, extractRequestContext, freeRouteLimitResponse, parseJsonObjectBody, readCookieValue, requireString, serializeCookie, withFreeRouteLimit };
package/dist/web/index.js CHANGED
@@ -1,25 +1,37 @@
1
1
  import {
2
+ FREE_ROUTE_BUDGETS,
3
+ FreeRouteLimitError,
2
4
  STANDARD_SECURITY_HEADERS,
5
+ WORKSPACE_BUDGET_MULTIPLIER,
3
6
  addSecurityHeaders,
4
7
  assertMediaUrl,
8
+ checkFreeRouteLimit,
5
9
  checkRateLimit,
6
10
  clearCookieHeader,
7
11
  extractRequestContext,
12
+ freeRouteLimitResponse,
8
13
  parseJsonObjectBody,
9
14
  readCookieValue,
10
15
  requireString,
11
- serializeCookie
12
- } from "../chunk-J25RST7G.js";
16
+ serializeCookie,
17
+ withFreeRouteLimit
18
+ } from "../chunk-F7VH4G5C.js";
13
19
  export {
20
+ FREE_ROUTE_BUDGETS,
21
+ FreeRouteLimitError,
14
22
  STANDARD_SECURITY_HEADERS,
23
+ WORKSPACE_BUDGET_MULTIPLIER,
15
24
  addSecurityHeaders,
16
25
  assertMediaUrl,
26
+ checkFreeRouteLimit,
17
27
  checkRateLimit,
18
28
  clearCookieHeader,
19
29
  extractRequestContext,
30
+ freeRouteLimitResponse,
20
31
  parseJsonObjectBody,
21
32
  readCookieValue,
22
33
  requireString,
23
- serializeCookie
34
+ serializeCookie,
35
+ withFreeRouteLimit
24
36
  };
25
37
  //# sourceMappingURL=index.js.map