theokit 0.11.7 → 0.12.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 (103) hide show
  1. package/LICENSE +201 -0
  2. package/dist/actions-virtual-module-SQDY3V5X.js +0 -0
  3. package/dist/add-W6FNTAFS.js +0 -0
  4. package/dist/app-typed-client-QG7BVZYW.js +0 -0
  5. package/dist/aws-lambda-7GSCNLPY.js +0 -0
  6. package/dist/broadcast-LUMOJIJT.js +0 -0
  7. package/dist/build-QFRLSEZ4.js +0 -0
  8. package/dist/build-request-body-preview-QMWD2IXK.js +0 -0
  9. package/dist/bun-KP2KES6S.js +0 -0
  10. package/dist/check-PD2FTKMM.js +0 -0
  11. package/dist/chunk-3LVRAGAZ.js +0 -0
  12. package/dist/chunk-43D6XNDR.js +0 -0
  13. package/dist/chunk-45C3WUQ7.js +0 -0
  14. package/dist/chunk-5ODOE6EF.js +0 -0
  15. package/dist/chunk-6FYD34NX.js +0 -0
  16. package/dist/chunk-7YZHAQU7.js +0 -0
  17. package/dist/{chunk-GEEMNDPH.js → chunk-AD74EAK3.js} +30 -1
  18. package/dist/chunk-AD74EAK3.js.map +1 -0
  19. package/dist/chunk-FOZIR3TG.js +0 -0
  20. package/dist/chunk-GFMQJHXX.js +0 -0
  21. package/dist/chunk-HGZL5EOI.js +0 -0
  22. package/dist/chunk-HNBWZKIQ.js +0 -0
  23. package/dist/chunk-IEES3CHD.js +0 -0
  24. package/dist/chunk-JAIKGP3Q.js +0 -0
  25. package/dist/chunk-JQSFBJR5.js +0 -0
  26. package/dist/chunk-NAZ4E2GT.js +0 -0
  27. package/dist/chunk-PBEH6NXR.js +0 -0
  28. package/dist/chunk-YJAUJXZS.js +0 -0
  29. package/dist/cloudflare-C6E5SPAE.js +0 -0
  30. package/dist/configure-agent-registry-ZOBVU3MV.js +0 -0
  31. package/dist/db-3UNAMSFK.js +0 -0
  32. package/dist/deno-deploy-RFZN56X4.js +0 -0
  33. package/dist/dev-GBXOTXUP.js +0 -0
  34. package/dist/dev-emit-FEFEDLZF.js +0 -0
  35. package/dist/dispatcher-EJHL6JMJ.js +0 -0
  36. package/dist/docker-LZZB4D5E.js +0 -0
  37. package/dist/generate-OMKHQ7OM.js +0 -0
  38. package/dist/info-OUEUZOT7.js +0 -0
  39. package/dist/netlify-PMLHVPN4.js +0 -0
  40. package/dist/node-BPJ3Z4DT.js +0 -0
  41. package/dist/openapi-VR6AFBLJ.js +0 -0
  42. package/dist/registry-Q2TZQLUH.js +0 -0
  43. package/dist/router-TLEAOFID.js +0 -0
  44. package/dist/routes-LRYOIIAI.js +0 -0
  45. package/dist/scan-7MJC6PYU.js +0 -0
  46. package/dist/schema-7CAY6IZR.js +0 -0
  47. package/dist/server/define/index.js +5 -3
  48. package/dist/server/index.js +4 -2
  49. package/dist/server/index.js.map +1 -1
  50. package/dist/server-error-to-envelope-UUXDSLAZ.js +0 -0
  51. package/dist/server-routes-hmr-VZXOP5YT.js +0 -0
  52. package/dist/services-json-Y3XODNB5.js +0 -0
  53. package/dist/services-typed-client-32KMTTXR.js +0 -0
  54. package/dist/start-3ZHAXSJE.js +0 -0
  55. package/dist/static-55G3LX2I.js +0 -0
  56. package/dist/storage-manager-ZSQFLEYT.js +0 -0
  57. package/dist/theo-cloud-DQRP6S6M.js +0 -0
  58. package/dist/upgrade-readiness-ACGW44JC.js +0 -0
  59. package/dist/vercel-J6G7ZHYQ.js +0 -0
  60. package/dist/vite-plugin-WO72VLYR.js +0 -0
  61. package/package.json +12 -8
  62. package/dist/adapters/web-shim.d.ts +0 -67
  63. package/dist/adapters/ws-shim.d.ts +0 -55
  64. package/dist/agent-events-DosDXkSV.d.ts +0 -94
  65. package/dist/audit-log-BQWM5YLG.d.ts +0 -60
  66. package/dist/boot/index.d.ts +0 -39
  67. package/dist/chunk-GEEMNDPH.js.map +0 -1
  68. package/dist/client/index.d.ts +0 -362
  69. package/dist/csrf-BBrEZSBW.d.ts +0 -107
  70. package/dist/csrf-readiness-store-CjIoub3U.d.ts +0 -43
  71. package/dist/define-websocket-CdK94O-D.d.ts +0 -64
  72. package/dist/devtools/entry.d.ts +0 -5
  73. package/dist/error-envelope-BsNzzAV5.d.ts +0 -62
  74. package/dist/health-route-C0hk64_U.d.ts +0 -57
  75. package/dist/index-B40qUSrQ.d.ts +0 -575
  76. package/dist/index.d.ts +0 -361
  77. package/dist/job-backend-CgC8Xf33.d.ts +0 -68
  78. package/dist/match-CfbEFRG4.d.ts +0 -26
  79. package/dist/plugin-runner-BGBkzgi0.d.ts +0 -95
  80. package/dist/plugin-types-DNJGxr4Z.d.ts +0 -79
  81. package/dist/rate-limit-BdNDZ3vt.d.ts +0 -58
  82. package/dist/rate-limit-store-BEJnhWdw.d.ts +0 -72
  83. package/dist/react-query/index.d.ts +0 -33
  84. package/dist/schema-BpH6ivDY.d.ts +0 -74
  85. package/dist/server/agent/index.d.ts +0 -229
  86. package/dist/server/auth/index.d.ts +0 -419
  87. package/dist/server/cost/index.d.ts +0 -177
  88. package/dist/server/cron/index.d.ts +0 -208
  89. package/dist/server/define/index.d.ts +0 -310
  90. package/dist/server/http/index.d.ts +0 -11
  91. package/dist/server/index.d.ts +0 -847
  92. package/dist/server/jobs/index.d.ts +0 -348
  93. package/dist/server/observability/index.d.ts +0 -324
  94. package/dist/server/plugins/index.d.ts +0 -17
  95. package/dist/server/rate-limit/index.d.ts +0 -105
  96. package/dist/server/realtime/index.d.ts +0 -15
  97. package/dist/server/scan/index.d.ts +0 -106
  98. package/dist/server/security/index.d.ts +0 -193
  99. package/dist/server/storage/index.d.ts +0 -22
  100. package/dist/server/webhook/index.d.ts +0 -148
  101. package/dist/storage-manager-C4jsO0Tp.d.ts +0 -89
  102. package/dist/storage-types-DsDTCPbp.d.ts +0 -96
  103. package/dist/vite-plugin/index.d.ts +0 -115
@@ -1,362 +0,0 @@
1
- import { z } from 'zod';
2
- import { T as TheoErrorEnvelope } from '../error-envelope-BsNzzAV5.js';
3
- export { FetchOptionsLike, Fetcher, QueryKey, UseTheoQueryConfig, buildUseTheoQueryConfig, stableQueryKey } from '../react-query/index.js';
4
- import { A as AgentEvent, a as AgentErrorEvent } from '../agent-events-DosDXkSV.js';
5
- export { b as AgentMessageEvent, c as AgentThinkingEvent, d as AgentToolCallEvent, e as AgentToolResultEvent } from '../agent-events-DosDXkSV.js';
6
- import * as react from 'react';
7
- import { LinkProps as LinkProps$1 } from 'react-router';
8
-
9
- /** Infer the response type from a route's handler return */
10
- type InferResponse<T> = T extends {
11
- handler: (...args: never[]) => infer R;
12
- } ? Awaited<R> : unknown;
13
- /** Extract the query Zod schema type, handling optional properties */
14
- type ExtractQuery<T> = T extends {
15
- query?: infer Q;
16
- } ? (Q extends z.ZodType ? Q : never) : never;
17
- /** Extract the body Zod schema type, handling optional properties */
18
- type ExtractBody<T> = T extends {
19
- body?: infer B;
20
- } ? (B extends z.ZodType ? B : never) : never;
21
- /** Infer query type from a route's query Zod schema */
22
- type InferQuery<T> = [ExtractQuery<T>] extends [never] ? undefined : ExtractQuery<T> extends z.ZodUndefined ? undefined : z.infer<ExtractQuery<T>>;
23
- /** Infer body type from a route's body Zod schema */
24
- type InferBody<T> = [ExtractBody<T>] extends [never] ? undefined : ExtractBody<T> extends z.ZodUndefined ? undefined : z.infer<ExtractBody<T>>;
25
- /** Build the options type based on what schemas the route has */
26
- type TheoFetchOptions<T> = Omit<RequestInit, 'body' | 'method'> & (InferQuery<T> extends undefined ? {
27
- query?: never;
28
- } : {
29
- query: InferQuery<T>;
30
- }) & (InferBody<T> extends undefined ? {
31
- body?: never;
32
- } : {
33
- body: InferBody<T>;
34
- });
35
- declare class TheoFetchError extends Error {
36
- status: number;
37
- code?: string;
38
- issues?: unknown[];
39
- /**
40
- * G5 T2.1 — canonical envelope view of the server-side error. Use this in
41
- * consumer code that wants to switch on a typed TheoErrorCode instead of
42
- * coupling to the legacy `.status` / `.code` flat fields.
43
- */
44
- readonly envelope: TheoErrorEnvelope;
45
- constructor(status: number, body?: unknown);
46
- }
47
- declare function theoFetch<T>(url: string, options?: TheoFetchOptions<T>): Promise<InferResponse<T>>;
48
-
49
- /**
50
- * Phase 3 of G1 (g1-client-codegen-plan.md):
51
- *
52
- * `createAppClient(baseUrl?, fetchImpl?)` returns a Proxy that walks property
53
- * access (`client.posts.id.get(...)`) into a `theoFetch` invocation against
54
- * `{baseUrl}/posts/{params.id}` with method `GET`.
55
- *
56
- * Type safety is delivered by the `.d.ts` file emitted in Phase 2 — this
57
- * runtime is structurally untyped. Power users may use `theoFetch` directly
58
- * when they need to escape the Proxy facade.
59
- *
60
- * Edge cases absorbed:
61
- * - EC-1 (thenable trap): `then` / `catch` / `finally` / `toJSON` / `Symbol.*`
62
- * return `undefined` so that accidental `await client.posts` resolves to a
63
- * plain Proxy value (it is NOT thenable) instead of looping.
64
- * - EC-7 (abort signal): `opts.signal` is spread through to the underlying
65
- * fetchImpl unchanged — verified in unit tests.
66
- *
67
- * Bundle target: ≤ 2KB gzipped.
68
- */
69
-
70
- type FetchImpl = typeof theoFetch;
71
- interface CreateAppClientOptions {
72
- /** Base URL for the API. Defaults to `/api`. */
73
- baseUrl?: string;
74
- /** Test-only fetch override. Production callers should not pass this. */
75
- fetchImpl?: FetchImpl;
76
- }
77
- declare function createAppClient<TAppClient = unknown>(baseUrlOrOptions?: string | CreateAppClientOptions, legacyFetchImpl?: FetchImpl): TAppClient;
78
-
79
- /**
80
- * T5.1 — client-side microtask batching.
81
- *
82
- * Collects all `dispatch` calls within the same microtask and sends them as a
83
- * single HTTP POST to the configured transport. Each caller's promise resolves
84
- * with its own result; one failed item does not break the others (per-item
85
- * error isolation).
86
- *
87
- * Designed as a transport-agnostic primitive so unit tests do not require
88
- * network access. The default transport (fetch to `/api/__theo_batch__`)
89
- * lives alongside this module but is created by the consumer (e.g., theoFetch).
90
- */
91
- interface BatchRequest {
92
- path: string;
93
- method: string;
94
- query?: Record<string, unknown>;
95
- body?: unknown;
96
- headers?: Record<string, string>;
97
- }
98
- type BatchResponse = {
99
- index: number;
100
- data: unknown;
101
- } | {
102
- index: number;
103
- error: {
104
- message: string;
105
- code?: string;
106
- };
107
- };
108
- type BatchTransport = (requests: BatchRequest[]) => Promise<BatchResponse[]>;
109
- interface BatcherOptions {
110
- transport: BatchTransport;
111
- /** Maximum batch size before flushing into multiple parallel batches. */
112
- max?: number;
113
- }
114
- interface Batcher {
115
- dispatch(req: BatchRequest): Promise<unknown>;
116
- }
117
- declare function createBatcher(options: BatcherOptions): Batcher;
118
-
119
- /**
120
- * Accumulated assistant text (M5-1): the concatenation of every `message`
121
- * event's `content`. Pure. Assumes append/delta semantics — a server that
122
- * emits full-snapshot messages should read `events` directly.
123
- */
124
- declare function deriveLiveText(events: readonly AgentEvent[]): string;
125
- /**
126
- * The current error (M5-1): the last `error` event, or `undefined`. Surfaces
127
- * the full `AgentErrorEvent` (with `code`/`retriable`) so the UI can branch.
128
- * Pure.
129
- */
130
- declare function deriveError(events: readonly AgentEvent[]): AgentErrorEvent | undefined;
131
- /**
132
- * T5.2 — useAgentStream
133
- *
134
- * React hook to consume an agent endpoint defined with `defineAgentEndpoint`.
135
- *
136
- * Transport (ADR D7, EC-3): fetch + ReadableStream — NOT EventSource.
137
- * EventSource is GET-only; agent endpoints need POST + body.
138
- *
139
- * Returns:
140
- * events — array of AgentEvents accumulated so far
141
- * send — call with a payload to (re)open a stream
142
- * status — 'idle' | 'streaming' | 'done' | 'error'
143
- * abort — manually cancel an in-flight stream
144
- *
145
- * Cleanup (EC-8): on unmount, the current AbortController fires .abort(),
146
- * which propagates to the underlying fetch and the ReadableStream reader.
147
- * Safe under React.StrictMode double-mount.
148
- */
149
- type AgentStreamStatus = 'idle' | 'streaming' | 'done' | 'error';
150
- interface UseAgentStreamReturn<TBody = unknown> {
151
- events: AgentEvent[];
152
- status: AgentStreamStatus;
153
- /** Accumulated assistant text — concatenation of all `message` contents (M5-1). */
154
- liveText: string;
155
- /** The last `error` event, or `undefined` (M5-1). */
156
- error: AgentErrorEvent | undefined;
157
- send: (body: TBody) => void;
158
- abort: () => void;
159
- reset: () => void;
160
- }
161
- interface UseAgentStreamOptions {
162
- /** Extra headers (e.g., auth). */
163
- headers?: Record<string, string>;
164
- /** Override fetch (rare — primarily for tests). */
165
- fetch?: typeof fetch;
166
- }
167
- declare function useAgentStream<TBody = unknown>(path: string, options?: UseAgentStreamOptions): UseAgentStreamReturn<TBody>;
168
-
169
- /**
170
- * A correlated, UI-facing view of one tool invocation (M5-2).
171
- *
172
- * `foldAgentToolCards` correlates a `tool_call` with its `tool_result` (by
173
- * `id`, falling back to FIFO-by-name) into a single card so consumers stop
174
- * hand-rolling `switch(event.type)`.
175
- */
176
- interface AgentToolCard {
177
- /** Correlation id (the event `id`, or a synthesized `tool-<index>`). */
178
- id: string;
179
- name: string;
180
- args: Record<string, unknown>;
181
- status: 'running' | 'success' | 'error';
182
- /** The `tool_result.data` payload, once the result arrives. */
183
- result?: unknown;
184
- }
185
- /**
186
- * Classifies a `tool_result.data` payload as success/error. Injectable so the
187
- * correlator is decoupled from any specific tool-result envelope shape.
188
- */
189
- type ToolEnvelopeResolver = (data: unknown) => {
190
- error: boolean;
191
- };
192
- interface FoldAgentToolCardsOptions {
193
- /** Override the default envelope classifier. */
194
- resolveEnvelope?: ToolEnvelopeResolver;
195
- }
196
- /**
197
- * Default envelope resolver: an object (or a JSON STRING parsing to an object)
198
- * with `ok === false` is an error; everything else is success (conservative).
199
- * sdk-tools handlers return a JSON STRING, so string parsing is intentional.
200
- */
201
- declare function defaultResolveEnvelope(data: unknown): {
202
- error: boolean;
203
- };
204
- /**
205
- * Fold an `AgentEvent[]` into correlated {@link AgentToolCard}s (M5-2). Pure.
206
- *
207
- * Correlation: a `tool_result` matches its `tool_call` by `id` when both carry
208
- * one; otherwise it matches the oldest still-`running` card with the same
209
- * `name` (FIFO). An unmatched `tool_result` becomes its own finished card.
210
- * A `tool_call` with no result stays `running`. The error status comes from
211
- * `options.resolveEnvelope` (default {@link defaultResolveEnvelope}).
212
- */
213
- declare function foldAgentToolCards(events: readonly AgentEvent[], options?: FoldAgentToolCardsOptions): AgentToolCard[];
214
-
215
- /** {@link useAgentToolCards} return — the stream result plus correlated tool cards. */
216
- interface UseAgentToolCardsReturn<TBody = unknown> extends UseAgentStreamReturn<TBody> {
217
- /** Correlated tool cards folded from the stream events (M5-2). */
218
- toolCards: AgentToolCard[];
219
- }
220
- /**
221
- * `useAgentStream` + correlated tool cards (M5-2). Composes the stream hook with
222
- * the pure {@link foldAgentToolCards} reducer; pass `resolveEnvelope` to classify
223
- * tool-result payloads (default flags `{ ok: false }` envelopes as errors).
224
- */
225
- declare function useAgentToolCards<TBody = unknown>(path: string, options?: UseAgentStreamOptions & FoldAgentToolCardsOptions): UseAgentToolCardsReturn<TBody>;
226
-
227
- /**
228
- * T5.2 — Pure SSE consumer used by useAgentStream.
229
- *
230
- * Split out from the React hook so the wire behavior can be tested
231
- * without a DOM. The hook is glue: useState + useEffect + this primitive.
232
- *
233
- * Transport (ADR D7, EC-3): fetch + ReadableStream — NOT EventSource.
234
- * EventSource is GET-only and cannot carry a body. Agent endpoints need
235
- * POST + JSON body, so we use fetch + manual SSE chunk parsing.
236
- */
237
- interface ConsumeOptions<TBody = unknown> {
238
- /** Request body — JSON-serialized into the POST. */
239
- body: TBody;
240
- /** Called once per SSE event parsed off the stream. */
241
- onEvent: (event: AgentEvent) => void;
242
- /** Optional fetch override (tests). */
243
- fetch?: typeof fetch;
244
- /** Optional abort signal — passed through to fetch. */
245
- signal?: AbortSignal;
246
- /** Extra headers (e.g., auth). */
247
- headers?: Record<string, string>;
248
- }
249
- /**
250
- * Parse a single SSE line of the form `data: <json>`.
251
- * Returns null for non-data lines, comments, or malformed JSON.
252
- */
253
- declare function parseSSEChunk(line: string): AgentEvent | null;
254
- /**
255
- * POSTs to `path` with `body`, reads the SSE response, and invokes
256
- * `onEvent` for each parsed AgentEvent. Resolves when the server
257
- * closes the stream or the signal aborts.
258
- *
259
- * T1.1 — Attaches `X-Theo-Action: '1'` so 0.3.0 strict CSRF mode accepts
260
- * the request. The user can override (or suppress) by passing the header
261
- * in `options.headers` — spread order ensures their value wins.
262
- */
263
- declare function consumeAgentStream<TBody = unknown>(path: string, options: ConsumeOptions<TBody>): Promise<void>;
264
-
265
- type PrefetchBehavior = 'none' | 'intent' | 'viewport';
266
- interface LinkProps extends LinkProps$1 {
267
- /** Prefetch strategy. Default: 'intent' (on hover + focus). */
268
- prefetch?: PrefetchBehavior;
269
- }
270
- /**
271
- * TheoKit Link — drop-in replacement for react-router Link with prefetch.
272
- *
273
- * @example
274
- * ```tsx
275
- * import { Link } from 'theokit/client'
276
- *
277
- * <Link to="/contacts">Contacts</Link>
278
- * <Link to="/dashboard" prefetch="viewport">Dashboard</Link>
279
- * <Link to="/settings" prefetch="none">Settings</Link>
280
- * ```
281
- */
282
- declare function Link({ prefetch, to, onMouseEnter, onFocus, ...rest }: LinkProps): react.JSX.Element;
283
-
284
- /**
285
- * <Metadata> — SEO-ready head tags from a single component.
286
- *
287
- * Uses React 19's native <title>/<meta>/<link> hoisting to <head>.
288
- * No build-time extraction needed — works in SSR and client.
289
- *
290
- * @example
291
- * ```tsx
292
- * import { Metadata } from 'theokit/client'
293
- *
294
- * export default function ContactsPage() {
295
- * return (
296
- * <>
297
- * <Metadata
298
- * title="Contacts | My CRM"
299
- * description="Manage your contacts"
300
- * ogImage="/og/contacts.png"
301
- * canonical="https://mycrm.com/contacts"
302
- * />
303
- * <h1>Contacts</h1>
304
- * </>
305
- * )
306
- * }
307
- * ```
308
- */
309
- interface MetadataProps {
310
- title?: string;
311
- description?: string;
312
- canonical?: string;
313
- ogTitle?: string;
314
- ogDescription?: string;
315
- ogImage?: string;
316
- ogType?: string;
317
- ogUrl?: string;
318
- twitterCard?: 'summary' | 'summary_large_image';
319
- /** Custom meta tags rendered as children */
320
- children?: React.ReactNode;
321
- }
322
- declare function Metadata(props: MetadataProps): react.JSX.Element;
323
-
324
- /**
325
- * <Image> — optimized image component with lazy loading.
326
- *
327
- * Renders a standard <img> with:
328
- * - loading="lazy" by default (eager with priority={true})
329
- * - decoding="async" for non-blocking decode
330
- * - width/height for CLS prevention
331
- * - srcSet/sizes forwarded for responsive images
332
- *
333
- * No CDN, no Sharp, no build-time optimization — pure HTML attributes
334
- * that deliver 80% of the performance value at zero complexity.
335
- *
336
- * @example
337
- * ```tsx
338
- * import { Image } from 'theokit/client'
339
- *
340
- * <Image src="/team.jpg" alt="Team photo" width={800} height={600} />
341
- * <Image src="/hero.jpg" alt="Hero" priority />
342
- * <Image
343
- * src="/product.jpg"
344
- * alt="Product"
345
- * width={400}
346
- * height={300}
347
- * srcSet="/product-400.jpg 400w, /product-800.jpg 800w"
348
- * sizes="(max-width: 768px) 100vw, 400px"
349
- * />
350
- * ```
351
- */
352
- interface ImageProps extends React.ImgHTMLAttributes<HTMLImageElement> {
353
- /** Image source URL (required). */
354
- src: string;
355
- /** Alt text for accessibility (required). */
356
- alt: string;
357
- /** If true, loading="eager" — use for above-the-fold images. */
358
- priority?: boolean;
359
- }
360
- declare function Image({ priority, loading, decoding, ...props }: ImageProps): react.JSX.Element;
361
-
362
- export { AgentErrorEvent, AgentEvent, type AgentStreamStatus, type AgentToolCard, type BatchRequest, type BatchResponse, type BatchTransport, type Batcher, type BatcherOptions, type ConsumeOptions, type CreateAppClientOptions, type FoldAgentToolCardsOptions, Image, type ImageProps, type InferBody, type InferQuery, type InferResponse, Link, type LinkProps, Metadata, type MetadataProps, type PrefetchBehavior, TheoFetchError, type TheoFetchOptions, type ToolEnvelopeResolver, type UseAgentStreamOptions, type UseAgentStreamReturn, type UseAgentToolCardsReturn, consumeAgentStream, createAppClient, createBatcher, defaultResolveEnvelope, deriveError, deriveLiveText, foldAgentToolCards, parseSSEChunk, theoFetch, useAgentStream, useAgentToolCards };
@@ -1,107 +0,0 @@
1
- import { IncomingMessage } from 'node:http';
2
- import { A as AuditLogger } from './audit-log-BQWM5YLG.js';
3
-
4
- /**
5
- * CSRF enforcement mode.
6
- *
7
- * - `off` — skip CSRF entirely. Use only when you have another defense
8
- * (e.g. you don't ship session cookies, all auth is bearer).
9
- * - `warn` — log a structured warning when the check would fail, but
10
- * still serve the request. Default for 0.2.0. Migration mode.
11
- * - `strict` — reject failing requests with 403 + code `CSRF_INVALID`.
12
- * Will become the default in 0.3.0.
13
- */
14
- type CsrfMode = 'off' | 'warn' | 'strict';
15
- /**
16
- * Per-request structured logger surface. Only `warn` is used by enforceCsrf;
17
- * we don't require a full Logger here so callers can pass a mock or the
18
- * console directly.
19
- */
20
- interface CsrfLogger {
21
- warn: (payload: CsrfWarnPayload) => void;
22
- /** Optional path the request was destined for — used for log correlation. */
23
- path?: string;
24
- }
25
- /**
26
- * T5.1 — Rails-inspired per-route escalation.
27
- *
28
- * `routes` accepts string (exact match) or RegExp entries. When a request
29
- * path matches AND the request would otherwise emit a warning, the
30
- * `behavior` field decides what happens:
31
- *
32
- * - `'warn'` → normal warn dispatch (no-op vs default)
33
- * - `'raise'` → escalate to 403 regardless of global `csrf` mode
34
- *
35
- * `'raise'` never downgrades: when global mode is `'off'`, validation is
36
- * skipped entirely and disallowed dispatch never runs.
37
- */
38
- interface DisallowedConfig {
39
- routes: (string | RegExp)[];
40
- behavior: 'warn' | 'raise';
41
- }
42
- /**
43
- * Test whether `path` matches any of the supplied patterns. String
44
- * patterns are EXACT (trailing slash matters — use RegExp for tolerance).
45
- *
46
- * EC-5: when a RegExp carries the `/g` flag, `.test()` mutates
47
- * `lastIndex` and the next invocation may miss. We reset `lastIndex`
48
- * before each test so the matcher is a pure function.
49
- */
50
- declare function matchDisallowed(path: string, patterns: readonly (string | RegExp)[]): boolean;
51
- /**
52
- * T2.2 — Stable cutover identifier shipped with every csrf.warn payload.
53
- *
54
- * Convention borrowed from Vite's `deprecations.ts:74` — a `code` plus a
55
- * `docsUrl` lets users (a) grep their logs for a single stable identifier
56
- * to find every csrf.warn line, and (b) click through directly to the
57
- * migration guide. Strings are exported constants so the analyzer (T2.3)
58
- * and migration guide can reference the same source of truth.
59
- */
60
- declare const CSRF_WARN_CODE: "CSRF_STRICT_CUTOVER";
61
- declare const CSRF_WARN_DOCS_URL: "https://theokit.dev/upgrade/csrf-strict-cutover";
62
- interface CsrfWarnPayload {
63
- event: 'csrf.warn';
64
- method: string;
65
- path: string | undefined;
66
- reason: string;
67
- /**
68
- * Stable identifier for the 0.2 → 0.3 CSRF strict cutover. Always
69
- * `'CSRF_STRICT_CUTOVER'`. Grep-able from prod logs.
70
- */
71
- code: string;
72
- /**
73
- * Link to the section of the migration guide explaining how to clear
74
- * this specific warning class.
75
- */
76
- docsUrl: string;
77
- }
78
- declare function validateCsrf(req: IncomingMessage): {
79
- valid: true;
80
- } | {
81
- valid: false;
82
- reason: string;
83
- };
84
- /**
85
- * T5a.2 Phase B (slice 1/6) — Web-Standards-shaped CSRF validator.
86
- *
87
- * Mirror of `validateCsrf(req: IncomingMessage)` for the Web `Request`
88
- * shape. Consumes `request.headers.get(name)` (native Web `Headers` API)
89
- * instead of `req.headers[name]` (Node `IncomingMessage` indexer). Same
90
- * CSRF policy + same return shape — the difference is only the input
91
- * extraction.
92
- *
93
- * Used by `executeWebRequest` (T5a.2 Phase A) to enforce CSRF on the
94
- * Web-Standards request handler entry-point.
95
- */
96
- declare function validateCsrfRequest(request: Request): {
97
- valid: true;
98
- } | {
99
- valid: false;
100
- reason: string;
101
- };
102
- declare function enforceCsrf(req: IncomingMessage, mode: CsrfMode, logger?: CsrfLogger, disallowed?: DisallowedConfig, auditLogger?: AuditLogger): {
103
- allow: boolean;
104
- reason?: string;
105
- };
106
-
107
- export { CSRF_WARN_CODE as C, type DisallowedConfig as D, CSRF_WARN_DOCS_URL as a, type CsrfLogger as b, type CsrfMode as c, type CsrfWarnPayload as d, enforceCsrf as e, validateCsrfRequest as f, matchDisallowed as m, validateCsrf as v };
@@ -1,43 +0,0 @@
1
- /**
2
- * T2.2 — In-memory bounded counter for CSRF warn events.
3
- *
4
- * Aggregates `csrf.warn` payloads by `(method, path, reason)` triple.
5
- * Used by the `/__theo/csrf-readiness` endpoint to expose a summary the
6
- * developer (or devtools tab) can inspect, so users do NOT need to grep
7
- * stdout to know which endpoints will break under 0.3.0 strict CSRF.
8
- *
9
- * Bounded at 1000 distinct keys (EC-22). Eviction is LRU-by-insertion —
10
- * when the cap is hit, the oldest key is dropped and a re-record of an
11
- * evicted key starts fresh (count: 1).
12
- *
13
- * Single-threaded by virtue of the JS event loop; Map operations are
14
- * atomic. NOT shared across processes — each worker has its own store.
15
- */
16
- interface CsrfWarnRecord {
17
- method: string;
18
- path: string;
19
- reason: string;
20
- }
21
- interface CsrfReadinessRouteSummary {
22
- method: string;
23
- path: string;
24
- reason: string;
25
- count: number;
26
- firstSeen: string;
27
- lastSeen: string;
28
- }
29
- interface CsrfReadinessSummary {
30
- generatedAt: string;
31
- totalEvents: number;
32
- routes: CsrfReadinessRouteSummary[];
33
- }
34
- declare class CsrfReadinessStore {
35
- static readonly MAX_ENTRIES = 1000;
36
- private readonly entries;
37
- private keyFor;
38
- record(event: CsrfWarnRecord): void;
39
- summary(): CsrfReadinessSummary;
40
- reset(): void;
41
- }
42
-
43
- export { CsrfReadinessStore as C, type CsrfReadinessRouteSummary as a, type CsrfReadinessSummary as b, type CsrfWarnRecord as c };
@@ -1,64 +0,0 @@
1
- import { IncomingMessage } from 'node:http';
2
-
3
- interface WebSocketLike {
4
- send(data: string | Buffer): void;
5
- close(code?: number, reason?: string): void;
6
- }
7
- interface WebSocketHandler {
8
- onOpen?: (ws: WebSocketLike, req: IncomingMessage) => void;
9
- onMessage?: (ws: WebSocketLike, data: string | Buffer) => void;
10
- onClose?: (ws: WebSocketLike, code: number, reason: Buffer) => void;
11
- onError?: (ws: WebSocketLike, error: Error) => void;
12
- }
13
- /**
14
- * Define a WebSocket endpoint handler.
15
- * Identity function — provides type inference for WebSocket handlers.
16
- */
17
- declare function defineWebSocket(handler: WebSocketHandler): WebSocketHandler;
18
- /**
19
- * T5a.2 Phase F slice 3/3 — Web-Standards WebSocket endpoint handler.
20
- *
21
- * Mirror of `WebSocketHandler` for the Web `Request` shape. `onOpen`
22
- * receives `request: Request` instead of `req: IncomingMessage`. The
23
- * rest of the lifecycle (onMessage, onClose, onError) is shape-agnostic
24
- * (`WebSocketLike` is already Web-standards-compatible per the existing
25
- * design — `send(string | Buffer)` works on both Node `ws` and Web
26
- * `WebSocket` instances; CF Workers / Bun / Deno coerce as needed at
27
- * the adapter boundary).
28
- *
29
- * Per `docs/plans/t5a2-incoming-message-to-request-shape-refactor-plan.md`
30
- * v1.0 § Phase F (closes Phase F).
31
- *
32
- * **Architectural note — WebSocket upgrade semantics differ across runtimes:**
33
- * - Node + `ws`: `WebSocketServer.handleUpgrade(req, socket, head, cb)` —
34
- * `req` is `IncomingMessage`. Use `WebSocketHandler`.
35
- * - CF Workers: `new WebSocketPair()` + `request.headers` (the upgrade
36
- * handshake IS a Web Request). Use `WebSocketHandlerWeb`.
37
- * - Bun: `server.upgrade(request, { data })` — same Web Request shape.
38
- * - Deno: `Deno.upgradeWebSocket(request)` — same Web Request shape.
39
- *
40
- * Cross-runtime WebSocket endpoints ship BOTH `WebSocketHandler` +
41
- * `WebSocketHandlerWeb` exports; the runtime adapter picks the matching
42
- * one. This is the canonical Hono / Nitric pattern.
43
- */
44
- interface WebSocketHandlerWeb {
45
- onOpen?: (ws: WebSocketLike, request: Request) => void;
46
- onMessage?: (ws: WebSocketLike, data: string | Uint8Array) => void;
47
- onClose?: (ws: WebSocketLike, code: number, reason: string) => void;
48
- onError?: (ws: WebSocketLike, error: Error) => void;
49
- }
50
- /**
51
- * Web-Standards `defineWebSocket` sibling. Identity function — provides
52
- * type inference for Web WebSocket handlers.
53
- *
54
- * **Type difference note vs Node path:**
55
- * - `onMessage` data is `string | Uint8Array` instead of `string | Buffer`
56
- * (Web standards have no `Buffer`; Node's Buffer is a Uint8Array
57
- * subclass so the Node path's Buffer values flow through unchanged
58
- * when adapters wrap them).
59
- * - `onClose` reason is `string` instead of `Buffer` (Web `CloseEvent`
60
- * exposes the reason as a UTF-8 string natively).
61
- */
62
- declare function defineWebSocketWeb(handler: WebSocketHandlerWeb): WebSocketHandlerWeb;
63
-
64
- export { type WebSocketHandler as W, type WebSocketHandlerWeb as a, type WebSocketLike as b, defineWebSocketWeb as c, defineWebSocket as d };
@@ -1,5 +0,0 @@
1
- declare global {
2
- interface Window {
3
- __theoDevtoolsMounted?: boolean;
4
- }
5
- }
@@ -1,62 +0,0 @@
1
- /**
2
- * Error envelope — canonical cross-layer contract for theokit framework, SDK,
3
- * and UI per plan g5-error-envelope-cross-layer v1.0 § Phase 1 / T1.1.
4
- *
5
- * Blueprint G5 (SHIPPABLE_WITH_CAVEATS 89/100) — Form 4 Hybrid: shared CODE
6
- * enum + per-domain extensions + 2-layer SDK boundary translation.
7
- *
8
- * 3/3 references convergence: code + message + cause base (trpc TRPCError
9
- * + hono HTTPException + encore Error). Wasp confirms ecosystem gap.
10
- *
11
- * Reference anchors (verified file:line):
12
- * - referencia: trpc/packages/server/src/unstable-core-do-not-import/error/TRPCError.ts:65-87
13
- * - referencia: trpc/packages/server/src/unstable-core-do-not-import/rpc/codes.ts:11-44,76-81
14
- * - referencia: hono/src/http-exception.ts:46-78
15
- * - referencia: encore/runtimes/go/beta/errs/error.go:38-55 (Go — D4 disclaimer applied)
16
- *
17
- * Per blueprint ADR D2: retryable + hint are extension slots, NOT base fields
18
- * (3/3 references derive retryability from code identity; no reference ships
19
- * a `retryable: boolean` on envelope; `hint` is novel).
20
- *
21
- * Per blueprint ADR D5: server-only `meta` filtered at serializer boundary
22
- * (encore `json:"-"` analog).
23
- *
24
- * Lives in `core/contracts/` per architecture.md v3 — canonical home for
25
- * shared client↔server types. Zero intra-monorepo deps; zero runtime deps
26
- * (trpc + hono ship envelope with zero runtime deps per blueprint Q5).
27
- */
28
- /**
29
- * Canonical TheoKit error code union. HTTP-status flavor + SDK/agent-domain
30
- * additions per blueprint Recommendations § concrete shape.
31
- *
32
- * String-literal union mirrors trpc's TRPC_ERROR_CODE_KEY pattern — enables
33
- * exhaustive `switch (env.code)` narrowing in consumer code (UI display
34
- * dispatch, retry-policy gates, telemetry classification).
35
- */
36
- type TheoErrorCode = 'BAD_REQUEST' | 'UNAUTHORIZED' | 'FORBIDDEN' | 'NOT_FOUND' | 'METHOD_NOT_ALLOWED' | 'CONFLICT' | 'PRECONDITION_FAILED' | 'PAYLOAD_TOO_LARGE' | 'UNSUPPORTED_MEDIA_TYPE' | 'UNPROCESSABLE_ENTITY' | 'TOO_MANY_REQUESTS' | 'INTERNAL_SERVER_ERROR' | 'NOT_IMPLEMENTED' | 'BAD_GATEWAY' | 'SERVICE_UNAVAILABLE' | 'GATEWAY_TIMEOUT' | 'AGENT_RUN_ERROR' | 'PROVIDER_KEY_MISSING' | 'BUDGET_EXCEEDED' | 'RATE_LIMITED' | 'CREDENTIAL_POOL_EXHAUSTED';
37
- /**
38
- * Base envelope shape — `{ code, message, cause?, meta?, ext? }`.
39
- *
40
- * `cause` follows TC39 proposal-error-cause (universal pattern, 3/3 references).
41
- * `meta` is server-only metadata filtered at serializer boundary per ADR D5
42
- * (`stack` is auto-stripped in non-dev builds — see T1.2 `TheoError.toJSON()`).
43
- * `ext` carries opt-in per-domain extensions (`ValidationFieldsExt`,
44
- * `RetryableExt`, `HintExt`, or arbitrary user-defined types via formatter hook).
45
- */
46
- interface TheoErrorEnvelope<TExt = unknown> {
47
- readonly code: TheoErrorCode;
48
- readonly message: string;
49
- readonly cause?: unknown;
50
- readonly meta?: Record<string, unknown>;
51
- readonly ext?: TExt;
52
- }
53
- /**
54
- * `ValidationFieldsExt` — validation-failure extension carrying the dot-notation
55
- * field map identical to G3 `ActionInputError.fields`. Empty-string key for
56
- * root-level errors (mirrors G3 EC-7). Multiple messages per key are preserved.
57
- */
58
- interface ValidationFieldsExt {
59
- readonly fields: Record<string, string[]>;
60
- }
61
-
62
- export type { TheoErrorEnvelope as T, ValidationFieldsExt as V, TheoErrorCode as a };