@slotform/api 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (151) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +50 -2
  3. package/dist/client.d.ts +16 -0
  4. package/dist/client.d.ts.map +1 -0
  5. package/dist/client.js +98 -0
  6. package/dist/client.js.map +1 -0
  7. package/dist/error.d.ts +2 -0
  8. package/dist/error.d.ts.map +1 -0
  9. package/dist/error.js +2 -0
  10. package/dist/error.js.map +1 -0
  11. package/dist/index.d.ts +153 -0
  12. package/dist/index.d.ts.map +1 -0
  13. package/dist/index.js +640 -0
  14. package/dist/index.js.map +1 -0
  15. package/dist/lib/chosen.d.ts +12 -0
  16. package/dist/lib/chosen.d.ts.map +1 -0
  17. package/dist/lib/chosen.js +18 -0
  18. package/dist/lib/chosen.js.map +1 -0
  19. package/dist/lib/cursor.d.ts +68 -0
  20. package/dist/lib/cursor.d.ts.map +1 -0
  21. package/dist/lib/cursor.js +220 -0
  22. package/dist/lib/cursor.js.map +1 -0
  23. package/dist/lib/limits.d.ts +4 -0
  24. package/dist/lib/limits.d.ts.map +1 -0
  25. package/dist/lib/limits.js +10 -0
  26. package/dist/lib/limits.js.map +1 -0
  27. package/dist/lib/local-origin.d.ts +2 -0
  28. package/dist/lib/local-origin.d.ts.map +1 -0
  29. package/dist/lib/local-origin.js +17 -0
  30. package/dist/lib/local-origin.js.map +1 -0
  31. package/dist/lib/slugify.d.ts +4 -0
  32. package/dist/lib/slugify.d.ts.map +1 -0
  33. package/dist/lib/slugify.js +26 -0
  34. package/dist/lib/slugify.js.map +1 -0
  35. package/dist/lib/window.d.ts +52 -0
  36. package/dist/lib/window.d.ts.map +1 -0
  37. package/dist/lib/window.js +70 -0
  38. package/dist/lib/window.js.map +1 -0
  39. package/dist/mcp-path.d.ts +2 -0
  40. package/dist/mcp-path.d.ts.map +1 -0
  41. package/dist/mcp-path.js +3 -0
  42. package/dist/mcp-path.js.map +1 -0
  43. package/dist/mcp.d.ts +15 -0
  44. package/dist/mcp.d.ts.map +1 -0
  45. package/dist/mcp.js +5 -0
  46. package/dist/mcp.js.map +1 -0
  47. package/dist/node/barrel.d.ts +3 -0
  48. package/dist/node/barrel.d.ts.map +1 -0
  49. package/dist/node/barrel.js +70 -0
  50. package/dist/node/barrel.js.map +1 -0
  51. package/dist/node/codegen.d.ts +10 -0
  52. package/dist/node/codegen.d.ts.map +1 -0
  53. package/dist/node/codegen.js +132 -0
  54. package/dist/node/codegen.js.map +1 -0
  55. package/dist/node/procedure-codegen.d.ts +14 -0
  56. package/dist/node/procedure-codegen.d.ts.map +1 -0
  57. package/dist/node/procedure-codegen.js +95 -0
  58. package/dist/node/procedure-codegen.js.map +1 -0
  59. package/dist/node/schema-child.d.ts +2 -0
  60. package/dist/node/schema-child.d.ts.map +1 -0
  61. package/dist/node/schema-child.js +31 -0
  62. package/dist/node/schema-child.js.map +1 -0
  63. package/dist/node/schema-source.d.ts +3 -0
  64. package/dist/node/schema-source.d.ts.map +1 -0
  65. package/dist/node/schema-source.js +33 -0
  66. package/dist/node/schema-source.js.map +1 -0
  67. package/dist/node/server-client.d.ts +19 -0
  68. package/dist/node/server-client.d.ts.map +1 -0
  69. package/dist/node/server-client.js +45 -0
  70. package/dist/node/server-client.js.map +1 -0
  71. package/dist/node/types.d.ts +42 -0
  72. package/dist/node/types.d.ts.map +1 -0
  73. package/dist/node/types.js +13 -0
  74. package/dist/node/types.js.map +1 -0
  75. package/dist/not-found.d.ts +2 -0
  76. package/dist/not-found.d.ts.map +1 -0
  77. package/dist/not-found.js +6 -0
  78. package/dist/not-found.js.map +1 -0
  79. package/dist/procedure.d.ts +188 -0
  80. package/dist/procedure.d.ts.map +1 -0
  81. package/dist/procedure.js +392 -0
  82. package/dist/procedure.js.map +1 -0
  83. package/dist/query-invalidation.d.ts +20 -0
  84. package/dist/query-invalidation.d.ts.map +1 -0
  85. package/dist/query-invalidation.js +66 -0
  86. package/dist/query-invalidation.js.map +1 -0
  87. package/dist/schema.d.ts +32 -0
  88. package/dist/schema.d.ts.map +1 -0
  89. package/dist/schema.js +103 -0
  90. package/dist/schema.js.map +1 -0
  91. package/dist/types.d.ts +30 -0
  92. package/dist/types.d.ts.map +1 -0
  93. package/dist/types.js +2 -0
  94. package/dist/types.js.map +1 -0
  95. package/dist/wire.d.ts +11 -0
  96. package/dist/wire.d.ts.map +1 -0
  97. package/dist/wire.js +26 -0
  98. package/dist/wire.js.map +1 -0
  99. package/dist/worker/guards.d.ts +6 -0
  100. package/dist/worker/guards.d.ts.map +1 -0
  101. package/dist/worker/guards.js +29 -0
  102. package/dist/worker/guards.js.map +1 -0
  103. package/dist/worker/index.d.ts +57 -0
  104. package/dist/worker/index.d.ts.map +1 -0
  105. package/dist/worker/index.js +418 -0
  106. package/dist/worker/index.js.map +1 -0
  107. package/dist/worker/mcp.d.ts +28 -0
  108. package/dist/worker/mcp.d.ts.map +1 -0
  109. package/dist/worker/mcp.js +361 -0
  110. package/dist/worker/mcp.js.map +1 -0
  111. package/dist/worker/request-log.d.ts +10 -0
  112. package/dist/worker/request-log.d.ts.map +1 -0
  113. package/dist/worker/request-log.js +37 -0
  114. package/dist/worker/request-log.js.map +1 -0
  115. package/guide/add-a-procedure.md +42 -0
  116. package/guide/background.md +86 -0
  117. package/guide/client.md +93 -0
  118. package/guide/config.md +85 -0
  119. package/guide/mcp.md +68 -0
  120. package/guide/middleware.md +79 -0
  121. package/guide/procedures.md +95 -0
  122. package/guide/utilities.md +135 -0
  123. package/package.json +120 -3
  124. package/src/client.ts +129 -0
  125. package/src/error.ts +1 -0
  126. package/src/index.ts +787 -0
  127. package/src/lib/chosen.ts +31 -0
  128. package/src/lib/cursor.ts +354 -0
  129. package/src/lib/limits.ts +10 -0
  130. package/src/lib/local-origin.ts +18 -0
  131. package/src/lib/slugify.ts +29 -0
  132. package/src/lib/window.ts +155 -0
  133. package/src/mcp-path.ts +2 -0
  134. package/src/mcp.ts +30 -0
  135. package/src/node/barrel.ts +77 -0
  136. package/src/node/codegen.ts +173 -0
  137. package/src/node/procedure-codegen.ts +131 -0
  138. package/src/node/schema-child.ts +31 -0
  139. package/src/node/schema-source.ts +45 -0
  140. package/src/node/server-client.ts +67 -0
  141. package/src/node/types.ts +64 -0
  142. package/src/not-found.ts +6 -0
  143. package/src/procedure.ts +935 -0
  144. package/src/query-invalidation.ts +106 -0
  145. package/src/schema.ts +133 -0
  146. package/src/types.ts +72 -0
  147. package/src/wire.ts +34 -0
  148. package/src/worker/guards.ts +37 -0
  149. package/src/worker/index.ts +681 -0
  150. package/src/worker/mcp.ts +470 -0
  151. package/src/worker/request-log.ts +50 -0
@@ -0,0 +1,106 @@
1
+ import { SLOTFORM_READS_HEADER, SLOTFORM_WRITES_HEADER } from "./wire.ts";
2
+
3
+ // The client half of entity-based cache invalidation: docs/architecture/plugins/api.md, "Cache invalidation".
4
+
5
+ // The app's entity names: docs/architecture/plugins/api.md, "Cache invalidation".
6
+ // biome-ignore lint/suspicious/noEmptyInterface: an interface so `.slotform/procedure.ts` can merge into it
7
+ export interface Register {}
8
+
9
+ export type EntityName = Register extends {
10
+ entity: infer TEntity extends string;
11
+ }
12
+ ? TEntity
13
+ : string;
14
+
15
+ interface EntityEntry {
16
+ reads: string[];
17
+ writes: string[];
18
+ }
19
+
20
+ // Structural subset of `@tanstack/react-query`'s `QueryClient`, so `@slotform/api`
21
+ // depends on no query library.
22
+ export interface InvalidatableQueryClient {
23
+ invalidateQueries(filters: {
24
+ predicate: (query: {
25
+ queryKey: readonly unknown[];
26
+ meta?: Record<string, unknown> | undefined;
27
+ }) => boolean;
28
+ }): unknown;
29
+ }
30
+
31
+ // Declared reads of a query outside the API: docs/architecture/plugins/api.md, "Cache invalidation".
32
+ function declaredReads(
33
+ meta: Record<string, unknown> | undefined,
34
+ ): readonly string[] | undefined {
35
+ const reads = meta?.reads;
36
+ return Array.isArray(reads) &&
37
+ reads.every((entity) => typeof entity === "string")
38
+ ? reads
39
+ : undefined;
40
+ }
41
+
42
+ function splitHeaderValue(value: string): string[] {
43
+ return value
44
+ .split(",")
45
+ .map((entity) => entity.trim())
46
+ .filter((entity) => entity.length > 0);
47
+ }
48
+
49
+ // The "todos/list" pathKey sits at index 0 of the `[path, options]` tuple
50
+ // `@orpc/tanstack-query` produces for both query and mutation keys.
51
+ function pathKeyFromOperationKey(
52
+ key: readonly unknown[] | undefined,
53
+ ): string | undefined {
54
+ if (!key) return undefined;
55
+ const path = key[0];
56
+ if (!Array.isArray(path) || !path.every((seg) => typeof seg === "string")) {
57
+ return undefined;
58
+ }
59
+ return (path as string[]).join("/");
60
+ }
61
+
62
+ // The registry the client and the query plugin's query client share: docs/architecture/plugins/api.md, "Client". It assumes one client and one user per isolate.
63
+ const entries = new Map<string, EntityEntry>();
64
+
65
+ /** Parses `x-slotform-reads` / `x-slotform-writes` off `headers` for `pathKey`. An absent header leaves that side untouched. */
66
+ export function captureEntityHeaders(pathKey: string, headers: Headers): void {
67
+ const reads = headers.get(SLOTFORM_READS_HEADER);
68
+ const writes = headers.get(SLOTFORM_WRITES_HEADER);
69
+ if (reads === null && writes === null) return;
70
+
71
+ const entry = entries.get(pathKey) ?? { reads: [], writes: [] };
72
+ if (reads !== null) entry.reads = splitHeaderValue(reads);
73
+ if (writes !== null) entry.writes = splitHeaderValue(writes);
74
+ entries.set(pathKey, entry);
75
+ }
76
+
77
+ /** Invalidates every cached query whose recorded or declared (`meta.reads`) reads intersect `writes`. */
78
+ export function invalidateForWrites(
79
+ queryClient: InvalidatableQueryClient,
80
+ writes: readonly EntityName[],
81
+ ): void {
82
+ if (writes.length === 0) return;
83
+ const writeSet = new Set<string>(writes);
84
+
85
+ queryClient.invalidateQueries({
86
+ predicate: (query) => {
87
+ const pathKey = pathKeyFromOperationKey(query.queryKey);
88
+ const reads =
89
+ declaredReads(query.meta) ??
90
+ (pathKey ? entries.get(pathKey)?.reads : undefined);
91
+ return reads?.some((entity) => writeSet.has(entity)) ?? false;
92
+ },
93
+ });
94
+ }
95
+
96
+ /** Looks up the writes recorded for `mutationKey`'s pathKey and invalidates for them. No-op when nothing was recorded. */
97
+ export function handleMutationSuccess(
98
+ queryClient: InvalidatableQueryClient,
99
+ mutationKey: readonly unknown[] | undefined,
100
+ ): void {
101
+ const pathKey = pathKeyFromOperationKey(mutationKey);
102
+ if (!pathKey) return;
103
+ const writes = entries.get(pathKey)?.writes;
104
+ if (!writes || writes.length === 0) return;
105
+ invalidateForWrites(queryClient, writes);
106
+ }
package/src/schema.ts ADDED
@@ -0,0 +1,133 @@
1
+ import { z } from "zod";
2
+
3
+ export type { ZodObject, ZodRawShape, ZodType } from "zod";
4
+ export { z } from "zod";
5
+
6
+ /** Rows a mutation acts on, as a Table's `choose` hands them over: the ids ticked, or every row a read's query matches but the ids unticked. */
7
+ export type Selector<Q = unknown> =
8
+ | { ids: string[] }
9
+ | { query: Q; except: string[] };
10
+
11
+ /** The schema of a `Selector` over a read's query: `selector(listQuery)`, the object schema the list procedure's input extends. A mutation takes it as a field (`.input(z.object({ tasks: selector(listQuery) }))`) and resolves it with `chosenWhere` from `@slotform/api/lib/chosen`. */
12
+ export function selector<Q extends z.ZodType>(query: Q) {
13
+ return z.union([
14
+ z.object({ ids: z.array(z.string().min(1)) }).strict(),
15
+ z
16
+ .object({ query, except: z.array(z.string().min(1)).default([]) })
17
+ .strict(),
18
+ ]);
19
+ }
20
+
21
+ /** A JSON Schema (draft 2020-12) object. */
22
+ export type JsonSchema = { type?: string } & Record<string, unknown>;
23
+
24
+ /** One procedure as the client reads it: its input as JSON Schema (`null` when the input is not an object), whether it reads or writes, and the input key its scope adds (`organizationId`, null when it has none), which the client fills from the route's scope. */
25
+ export interface ProcedureSchema {
26
+ input: JsonSchema | null;
27
+ kind: "query" | "mutation";
28
+ scope: string | null;
29
+ }
30
+
31
+ // The kinds of schema JSON Schema cannot hold, which `toJSONSchema` would
32
+ // turn into `{}` under `unrepresentable: "any"`. A `z.date()` is the one
33
+ // exception, a `date-time` string.
34
+ const UNREPRESENTABLE = new Set([
35
+ "bigint",
36
+ "symbol",
37
+ "undefined",
38
+ "void",
39
+ "nan",
40
+ "map",
41
+ "set",
42
+ "custom",
43
+ "function",
44
+ "promise",
45
+ ]);
46
+
47
+ function jsonSchema(schema: z.ZodType): JsonSchema {
48
+ return z.toJSONSchema(schema, {
49
+ target: "draft-2020-12",
50
+ io: "input",
51
+ unrepresentable: "any",
52
+ override: ({ zodSchema, jsonSchema }) => {
53
+ const type = zodSchema._zod.def.type;
54
+ if (type === "date") {
55
+ jsonSchema.type = "string";
56
+ jsonSchema.format = "date-time";
57
+ } else if (UNREPRESENTABLE.has(type)) {
58
+ throw new Error(`a ${type} has no JSON Schema form`);
59
+ }
60
+ },
61
+ }) as JsonSchema;
62
+ }
63
+
64
+ // An input of `undefined` or `void`, or none, is the empty object.
65
+ function inputSchemaOf(schema: z.ZodType | undefined): JsonSchema {
66
+ if (schema === undefined) return { type: "object" };
67
+ const type = schema._zod.def.type;
68
+ return type === "undefined" || type === "void"
69
+ ? { type: "object" }
70
+ : jsonSchema(schema);
71
+ }
72
+
73
+ /** A procedure's zod input as the JSON Schema of an object, dates as `date-time` strings; an input of `undefined` or `void`, or none, is the empty object. Throws when a part has no JSON Schema form or the input is not an object. */
74
+ export function inputJsonSchema(schema: z.ZodType | undefined): JsonSchema {
75
+ const json = inputSchemaOf(schema);
76
+ if (json.type !== "object") {
77
+ throw new Error("its input is not an object schema");
78
+ }
79
+ return json;
80
+ }
81
+
82
+ // Reading a built procedure by shape: docs/architecture/plugins/api.md, "Schema".
83
+ interface Built {
84
+ "~orpc": { inputSchema?: unknown; meta?: unknown };
85
+ }
86
+
87
+ function isProcedure(node: unknown): node is Built {
88
+ return (
89
+ typeof node === "object" &&
90
+ node !== null &&
91
+ typeof (node as Built)["~orpc"] === "object" &&
92
+ (node as Built)["~orpc"] !== null
93
+ );
94
+ }
95
+
96
+ /** Every procedure of a router, by dotted path: what `slotform generate` writes to `.slotform/schema.ts`. An input of `undefined` or `void`, or none, is the empty object; an input that is not an object (a union) is `null`; a procedure that cannot be converted throws, naming its path. */
97
+ export function routerSchema(routes: unknown): Record<string, ProcedureSchema> {
98
+ const out: Record<string, ProcedureSchema> = {};
99
+ const walk = (node: unknown, path: string[]) => {
100
+ const name = path.join(".");
101
+ if (isProcedure(node)) {
102
+ const def = node["~orpc"];
103
+ const schema = def.inputSchema as z.ZodType | undefined;
104
+ try {
105
+ const json = inputSchemaOf(schema);
106
+ const { kind, scope } = (def.meta ?? {}) as {
107
+ kind?: string;
108
+ scope?: string;
109
+ };
110
+ if (kind !== "query" && kind !== "mutation") {
111
+ throw new Error("it has no kind (not built by `procedure`)");
112
+ }
113
+ const { $schema: _, ...input } = json;
114
+ out[name] = {
115
+ input: input.type === "object" ? input : null,
116
+ kind,
117
+ scope: scope ?? null,
118
+ };
119
+ } catch (error) {
120
+ const reason = error instanceof Error ? error.message : String(error);
121
+ throw new Error(`${name}: ${reason}`);
122
+ }
123
+ return;
124
+ }
125
+ if (typeof node === "object" && node !== null) {
126
+ for (const [key, child] of Object.entries(node)) {
127
+ walk(child, [...path, key]);
128
+ }
129
+ }
130
+ };
131
+ walk(routes, []);
132
+ return out;
133
+ }
package/src/types.ts ADDED
@@ -0,0 +1,72 @@
1
+ import type { Client } from "@orpc/client";
2
+
3
+ // `TScope`: docs/architecture/plugins/api.md, "Scope".
4
+ export interface Procedure<
5
+ TInput = unknown,
6
+ TOutput = unknown,
7
+ TScope extends string = string,
8
+ > {
9
+ readonly __brand: "Procedure";
10
+ readonly __input: TInput;
11
+ readonly __output: TOutput;
12
+ readonly __scope: TScope;
13
+ }
14
+ export type Router = {
15
+ [key: string]: Procedure<unknown, unknown> | Router;
16
+ };
17
+
18
+ // oRPC's own client type: its query utils read the input off `ClientRest`, so
19
+ // an input that accepts `undefined` (a schema's `.optional()`) may be left out
20
+ // of `.queryOptions()` as well as the call. A plain function with an optional
21
+ // parameter loses that.
22
+ type ClientCall<TInput, TOutput> = Client<
23
+ Record<never, never>,
24
+ TInput,
25
+ TOutput,
26
+ Error
27
+ >;
28
+
29
+ export type RouterClient<T> = {
30
+ [K in keyof T]: T[K] extends Procedure<infer TIn, infer TOut>
31
+ ? ClientCall<TIn, TOut>
32
+ : T[K] extends Record<string, unknown>
33
+ ? RouterClient<T[K]>
34
+ : never;
35
+ };
36
+
37
+ // A scoped procedure's input without its scope key, which the boundary above the
38
+ // call supplies; the key stays accepted for a call that names another scope
39
+ // (explicit wins). An input every key of which is then optional may be left out.
40
+ type ScopeOptional<TIn, TScope extends string> = [TScope] extends [never]
41
+ ? TIn
42
+ : TIn extends object
43
+ ? Omit<TIn, TScope> & Partial<Pick<TIn, TScope & keyof TIn>> extends infer R
44
+ ? Record<never, never> extends R
45
+ ? R | undefined
46
+ : R
47
+ : never
48
+ : TIn;
49
+
50
+ // What the query utils wrap: `RouterClient` with every scoped input's scope key
51
+ // optional.
52
+ export type ScopedRouterClient<T> = {
53
+ [K in keyof T]: T[K] extends Procedure<infer TIn, infer TOut, infer TScope>
54
+ ? ClientCall<ScopeOptional<TIn, TScope>, TOut>
55
+ : T[K] extends Record<string, unknown>
56
+ ? ScopedRouterClient<T[K]>
57
+ : never;
58
+ };
59
+
60
+ // Env value checks: docs/architecture/plugins/api.md, "Env vars".
61
+ export interface EnvValidation {
62
+ minLength?: number;
63
+ url?: boolean;
64
+ devLocalhost?: boolean;
65
+ }
66
+
67
+ // One env var the worker reads: plugins/api/guide/config.md, "Rules".
68
+ export interface EnvSpec {
69
+ name: string;
70
+ devDefault: string;
71
+ validate?: EnvValidation;
72
+ }
package/src/wire.ts ADDED
@@ -0,0 +1,34 @@
1
+ // Wire contract: docs/architecture/plugins/api.md, "Wire contract". Import-free so a client bundle never pulls in `procedure.ts`.
2
+ export const SLOTFORM_READS_HEADER = "x-slotform-reads";
3
+ export const SLOTFORM_WRITES_HEADER = "x-slotform-writes";
4
+
5
+ // Not found: docs/architecture/plugins/api.md, "Not found".
6
+ export const SLOTFORM_NOT_FOUND_HEADER = "x-slotform-not-found";
7
+
8
+ // Exposed headers: docs/architecture/plugins/api.md, "Entity headers".
9
+ export const SLOTFORM_EXPOSED_HEADERS = [
10
+ SLOTFORM_READS_HEADER,
11
+ SLOTFORM_WRITES_HEADER,
12
+ SLOTFORM_NOT_FOUND_HEADER,
13
+ ] as const;
14
+
15
+ // Entity names: docs/architecture/plugins/api.md, "Entities".
16
+ export const ENTITY_NAME_RE = /^[A-Za-z0-9_.-]+$/;
17
+
18
+ // Org-rules path: docs/architecture/plugins/api.md, "Framework-owned paths".
19
+ export const ORG_RULES_PATH = ["auth", "orgRules"] as const;
20
+
21
+ // Scope lookups path: docs/architecture/plugins/api.md, "Framework-owned paths".
22
+ export const SCOPE_ROUTES_PATH = ["auth", "scope"] as const;
23
+
24
+ // Listener contract: docs/architecture/plugins/api.md, "Listener contract".
25
+ export const LISTENER_ENV = "SLOTFORM_LISTENER";
26
+ export const ORIGIN_ENV = "SLOTFORM_ORIGIN";
27
+
28
+ // The origin the request's listener serves, or null when the env names none.
29
+ export function listenerOrigin(env: unknown): string | null {
30
+ const value = (env as Record<string, unknown> | null | undefined)?.[
31
+ ORIGIN_ENV
32
+ ];
33
+ return typeof value === "string" && value !== "" ? value : null;
34
+ }
@@ -0,0 +1,37 @@
1
+ import type { Context } from "hono";
2
+ import { extractIp, type RateLimitBinding } from "../procedure.ts";
3
+
4
+ // The `/rpc` limiter's binding name, the contract with the `cloudflare` plugin: docs/architecture/plugins/api.md, "Rate limiting".
5
+ export const RATE_LIMITER_RPC = "RATE_LIMITER_RPC";
6
+
7
+ // The Hono variable the worker sets to a request's effective CORS allow-list.
8
+ export const ORIGINS_VAR = "__slotformOrigins";
9
+
10
+ // The blanket per-IP `/rpc` limiter: docs/architecture/plugins/api.md, "Rate limiting". True when the limiter refuses.
11
+ export async function ipLimited(
12
+ c: Context,
13
+ ctx: Record<string, unknown>,
14
+ ): Promise<boolean> {
15
+ const limiter = (c.env as Record<string, unknown> | null | undefined)?.[
16
+ RATE_LIMITER_RPC
17
+ ] as RateLimitBinding | undefined;
18
+ if (!limiter || ctx._devMode) return false;
19
+ const result = await limiter.limit({ key: extractIp(c.req.raw.headers) });
20
+ return !result.success;
21
+ }
22
+
23
+ // The CSRF guard for raw routes: docs/architecture/plugins/api.md, "At runtime".
24
+ export function isForbiddenOrigin(c: Context): boolean {
25
+ const origin = c.req.header("origin");
26
+ if (!origin) return false;
27
+ const allowed = c.get(ORIGINS_VAR) as string[] | undefined;
28
+ // Wildcard CORS admits every origin; the guard must agree with the CORS
29
+ // layer instead of judging all real browser origins forbidden.
30
+ if (allowed?.includes("*")) return false;
31
+ if (!allowed) {
32
+ throw new Error(
33
+ "isForbiddenOrigin: no origin list on this request. Register the middleware with .useAfterContext() (src/worker/middleware.context.ts), not .use().",
34
+ );
35
+ }
36
+ return !allowed.includes(origin);
37
+ }