logic-sdk 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +129 -2
- package/bin/logic-sdk.js +14 -0
- package/dist/ai.d.ts +45 -0
- package/dist/ai.js +51 -0
- package/dist/drizzle.d.ts +18 -0
- package/dist/drizzle.js +23 -0
- package/dist/fetch.d.ts +24 -0
- package/dist/fetch.js +68 -0
- package/dist/index.d.ts +444 -0
- package/dist/index.js +388 -0
- package/dist/orpc.d.ts +31 -0
- package/dist/orpc.js +46 -0
- package/dist/testing.d.ts +29 -0
- package/dist/testing.js +61 -0
- package/package.json +106 -4
- package/src/ai.ts +84 -0
- package/src/drizzle.ts +39 -0
- package/src/fetch.ts +82 -0
- package/src/index.ts +736 -0
- package/src/orpc.ts +65 -0
- package/src/testing.ts +88 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Franco Romano Losada
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,130 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Logic SDK
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**Business logic for TypeScript apps, as queries, mutations, actions and events.**
|
|
4
|
+
|
|
5
|
+
Write the layer between your routes and your database once, as plain declarations. Call it from an HTTP route, a Server Action, a queue worker, a script, a test or an AI agent: same rules, same transaction, same events.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm i logic-sdk zod
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Node 24+, Bun or Cloudflare Workers. Postgres through Drizzle for mutations.
|
|
14
|
+
|
|
15
|
+
## Quick start
|
|
16
|
+
|
|
17
|
+
Declare your types once, and who may do what:
|
|
18
|
+
|
|
19
|
+
```ts
|
|
20
|
+
// src/logic.ts
|
|
21
|
+
export const { query, mutation, action, event, on, createRegistry } = init<Config>();
|
|
22
|
+
|
|
23
|
+
// src/policies.ts: sync type guards over the scope
|
|
24
|
+
export const anyone = () => true;
|
|
25
|
+
export const member = (s: Scope): s is MemberScope => s.actor !== null;
|
|
26
|
+
export const staff = (s: Scope): s is StaffScope => s.actor !== null && s.actor.role !== "guest";
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
Write a module:
|
|
30
|
+
|
|
31
|
+
```ts
|
|
32
|
+
// src/bookings/mutations.ts
|
|
33
|
+
export const confirm = mutation({
|
|
34
|
+
description: "Confirm a pending booking",
|
|
35
|
+
inputSchema: z.object({ bookingId: z.uuid() }),
|
|
36
|
+
outputSchema: Booking,
|
|
37
|
+
// Who may call it, on every call
|
|
38
|
+
authorize: staff,
|
|
39
|
+
// HTTP, oRPC and AI tools may publish it
|
|
40
|
+
expose: true,
|
|
41
|
+
|
|
42
|
+
async execute({ bookingId }, ctx) {
|
|
43
|
+
const booking = await findBooking(ctx, bookingId);
|
|
44
|
+
if (booking.status !== "pending") {
|
|
45
|
+
throw ctx.errors.reject("not_pending");
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// Another module, in the same transaction
|
|
49
|
+
await ctx.run(availability.hold, rangeOf(booking));
|
|
50
|
+
|
|
51
|
+
// Delivered to listeners only after commit
|
|
52
|
+
ctx.emit(confirmed, { bookingId });
|
|
53
|
+
|
|
54
|
+
return setStatus(ctx, booking.id, "confirmed");
|
|
55
|
+
},
|
|
56
|
+
});
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
Register your modules and call them from anywhere:
|
|
60
|
+
|
|
61
|
+
```ts
|
|
62
|
+
// src/registry.ts
|
|
63
|
+
export const registry = createRegistry({
|
|
64
|
+
modules: { bookings, availability },
|
|
65
|
+
database: drizzleAdapter(db),
|
|
66
|
+
services: { mailer, payments },
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
// a route, a job, a script, a test
|
|
70
|
+
const caller = registry.as({ actor, accountId });
|
|
71
|
+
await caller.run(bookings.confirm, { bookingId });
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
## What you get
|
|
75
|
+
|
|
76
|
+
- **One transaction across modules.** A failure anywhere rolls back everything, even if someone catches it.
|
|
77
|
+
- **Side effects after commit.** Mutations emit events; listeners send the email once the data is safe.
|
|
78
|
+
- **Lost races retried.** Deadlocks and serialization failures re-run the mutation in a fresh transaction.
|
|
79
|
+
- **Who is calling, everywhere.** The scope reaches every nested call and listener, and policies narrow its type.
|
|
80
|
+
- **Authorization on every call.** `authorize` runs whoever calls: HTTP, an agent, a job or another function. Record rules are sync `can*` predicates the CLI checks.
|
|
81
|
+
- **Internal by default.** Only `expose: true` functions reach HTTP, RPC or AI tools, with a required policy and output contract.
|
|
82
|
+
- **Agents included.** `toAITool` gives an agent your functions, under the same policies and transactions as your API. Opt-in, one function at a time or by `filter`.
|
|
83
|
+
- **Errors without HTTP.** `ctx.errors.reject`, `conflict`, `notFound`, `deny`; adapters map them to statuses.
|
|
84
|
+
- **Tests without mocks.** Each test is a real transaction on a real database, always rolled back.
|
|
85
|
+
- **No magic.** No decorators, classes, codegen, build step or `AsyncLocalStorage`.
|
|
86
|
+
|
|
87
|
+
## Adapters
|
|
88
|
+
|
|
89
|
+
| Import | |
|
|
90
|
+
|---|---|
|
|
91
|
+
| `logic-sdk/drizzle` | The database adapter |
|
|
92
|
+
| `logic-sdk/fetch` | A web-standard HTTP handler for exposed functions |
|
|
93
|
+
| `logic-sdk/orpc` | A typed oRPC v2 router and client |
|
|
94
|
+
| `logic-sdk/ai` | AI SDK tools: agents run your functions with the same rules |
|
|
95
|
+
| `logic-sdk/testing` | Rolled-back test transactions, stubs, frozen time |
|
|
96
|
+
|
|
97
|
+
## CLI
|
|
98
|
+
|
|
99
|
+
```bash
|
|
100
|
+
npm i -D @logic-sdk/cli
|
|
101
|
+
npx logic-sdk list # every function, its kind and policy
|
|
102
|
+
logic-sdk show bookings.confirm # schemas, what it runs and emits, who calls it
|
|
103
|
+
logic-sdk graph --format mermaid # who runs whom, who reacts to which event
|
|
104
|
+
logic-sdk check # module boundaries, run cycles, no network in transactions, can* checks
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
Read-only, `--json` everywhere, exit codes for CI. The `logic-sdk` command ships with the main package and hands off to `@logic-sdk/cli`, so apps that don't use the CLI never download it.
|
|
108
|
+
|
|
109
|
+
## Examples
|
|
110
|
+
|
|
111
|
+
- [`examples/node`](examples/node): a bookings app. Six modules, Hono, Postgres, and a race test on real Postgres.
|
|
112
|
+
- [`examples/workers`](examples/workers): a link shortener on Cloudflare Workers, Hyperdrive and `waitUntil`.
|
|
113
|
+
- [`examples/nextjs`](examples/nextjs): a Server Action and an AI agent calling the same `bookings.confirm`.
|
|
114
|
+
|
|
115
|
+
## Docs
|
|
116
|
+
|
|
117
|
+
The docs site lives in [`apps/web`](apps/web) (`bun run --filter web dev`). Start with the [introduction](apps/web/docs/index.mdx) and the [quickstart](apps/web/docs/02-quickstart.mdx). [`AGENTS.md`](AGENTS.md) is the short version for coding agents.
|
|
118
|
+
|
|
119
|
+
## Repository
|
|
120
|
+
|
|
121
|
+
```bash
|
|
122
|
+
bun install
|
|
123
|
+
bun run test # build, typecheck, lint, package checks, all tests
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
`packages/logic-sdk` is the library, tested with `bun test`. `examples/node` runs on PGlite by default and on real Postgres with `DATABASE_URL` (`bun run test:pg`), which CI always sets. `examples/workers` runs inside workerd. Decisions and their reasons are in [DESIGN.md](DESIGN.md); what's next is in [ROADMAP.md](ROADMAP.md).
|
|
127
|
+
|
|
128
|
+
## License
|
|
129
|
+
|
|
130
|
+
MIT
|
package/bin/logic-sdk.js
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// `npx logic-sdk check`. The CLI itself lives in @logic-sdk/cli, so apps that never use it
|
|
3
|
+
// (a Worker, a Next.js app) don't download its parser and loader.
|
|
4
|
+
const CLI = "@logic-sdk/cli";
|
|
5
|
+
|
|
6
|
+
let cli;
|
|
7
|
+
try {
|
|
8
|
+
cli = await import(CLI);
|
|
9
|
+
} catch (error) {
|
|
10
|
+
if (error?.code !== "ERR_MODULE_NOT_FOUND" || !String(error.message).includes(CLI)) throw error;
|
|
11
|
+
console.error(`The logic-sdk CLI isn't installed in this project. Add it with:\n\n npm i -D ${CLI}\n`);
|
|
12
|
+
process.exit(1);
|
|
13
|
+
}
|
|
14
|
+
await cli.main(process.argv.slice(2));
|
package/dist/ai.d.ts
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { type Tool } from "ai";
|
|
2
|
+
import { type Caller, type Fn, type FnIn, type FnOut, type Registry, type RegisteredFn } from "./index.ts";
|
|
3
|
+
type ExposedOf<T> = {
|
|
4
|
+
[N in keyof T as T[N] extends Fn<any, any, any, true> ? N : never]: T[N];
|
|
5
|
+
};
|
|
6
|
+
type UnionToIntersection<U> = (U extends unknown ? (u: U) => void : never) extends (i: infer I) => void ? I : never;
|
|
7
|
+
/** `{ bookings_confirm, pricing_priceStay, … }`: one AI SDK tool per exposed function, typed. */
|
|
8
|
+
export type AIToolsOf<Mods> = UnionToIntersection<{
|
|
9
|
+
[M in keyof Mods & string]: {
|
|
10
|
+
[N in keyof ExposedOf<Mods[M]> & string as `${M}_${N}`]: Tool<FnIn<Mods[M][N & keyof Mods[M]]>, FnOut<Mods[M][N & keyof Mods[M]]>>;
|
|
11
|
+
};
|
|
12
|
+
}[keyof Mods & string]>;
|
|
13
|
+
export interface AIToolOptions {
|
|
14
|
+
/** Unexpected (non-domain) errors. The model only sees "internal_error". Default: console.error. */
|
|
15
|
+
onError?: (error: unknown) => void;
|
|
16
|
+
}
|
|
17
|
+
export interface AIToolsOptions extends AIToolOptions {
|
|
18
|
+
/**
|
|
19
|
+
* Which exposed functions an agent may call. Required: the agent door is opt-in, so a function exposed
|
|
20
|
+
* for your UI doesn't become a tool by accident. E.g. `(f) => f.fn.meta?.agent === true`.
|
|
21
|
+
*/
|
|
22
|
+
filter: (fn: RegisteredFn) => boolean;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* One exposed function as an AI SDK tool, run as `caller`: the agent goes through the same policy,
|
|
26
|
+
* validation, transaction and events as your HTTP API. You name it, like any AI SDK tool.
|
|
27
|
+
*
|
|
28
|
+
* ```ts
|
|
29
|
+
* const caller = registry.as(await scopeFrom(request));
|
|
30
|
+
* await generateText({ model, prompt, tools: { confirmBooking: toAITool(caller, bookings.confirm) } });
|
|
31
|
+
* ```
|
|
32
|
+
*
|
|
33
|
+
* Domain errors reach the model (it sees the code and can react). Anything unexpected is reported
|
|
34
|
+
* to `onError` and the model gets "internal_error", so internals never land in its context.
|
|
35
|
+
*/
|
|
36
|
+
export declare function toAITool<F extends Fn<any, any, any, true>>(caller: Caller<any>, fn: F, options?: AIToolOptions): Tool<FnIn<F>, FnOut<F>>;
|
|
37
|
+
/**
|
|
38
|
+
* The exposed functions your `filter` picks, as AI SDK tools named `<module>_<function>`.
|
|
39
|
+
*
|
|
40
|
+
* ```ts
|
|
41
|
+
* tools: toAITools(registry, caller, { filter: (f) => f.fn.meta?.agent === true })
|
|
42
|
+
* ```
|
|
43
|
+
*/
|
|
44
|
+
export declare function toAITools<S extends object, Mods extends Record<string, object>>(registry: Registry<S, Mods>, caller: Caller<S>, options: AIToolsOptions): Partial<AIToolsOf<Mods>>;
|
|
45
|
+
export {};
|
package/dist/ai.js
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { tool } from "ai";
|
|
2
|
+
import { isDomainError } from "./index.js";
|
|
3
|
+
/**
|
|
4
|
+
* One exposed function as an AI SDK tool, run as `caller`: the agent goes through the same policy,
|
|
5
|
+
* validation, transaction and events as your HTTP API. You name it, like any AI SDK tool.
|
|
6
|
+
*
|
|
7
|
+
* ```ts
|
|
8
|
+
* const caller = registry.as(await scopeFrom(request));
|
|
9
|
+
* await generateText({ model, prompt, tools: { confirmBooking: toAITool(caller, bookings.confirm) } });
|
|
10
|
+
* ```
|
|
11
|
+
*
|
|
12
|
+
* Domain errors reach the model (it sees the code and can react). Anything unexpected is reported
|
|
13
|
+
* to `onError` and the model gets "internal_error", so internals never land in its context.
|
|
14
|
+
*/
|
|
15
|
+
export function toAITool(caller, fn, options = {}) {
|
|
16
|
+
const onError = options.onError ?? ((e) => console.error("[logic-sdk] tool failed unexpectedly", e));
|
|
17
|
+
if (fn.expose !== true)
|
|
18
|
+
throw new Error("[logic-sdk] toAITool needs a function with expose: true.");
|
|
19
|
+
return tool({
|
|
20
|
+
description: fn.description,
|
|
21
|
+
inputSchema: fn.inputSchema,
|
|
22
|
+
outputSchema: fn.outputSchema,
|
|
23
|
+
async execute(input) {
|
|
24
|
+
try {
|
|
25
|
+
return await caller.run(fn, input);
|
|
26
|
+
}
|
|
27
|
+
catch (e) {
|
|
28
|
+
if (isDomainError(e))
|
|
29
|
+
throw e;
|
|
30
|
+
onError(e);
|
|
31
|
+
throw new Error("internal_error");
|
|
32
|
+
}
|
|
33
|
+
},
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* The exposed functions your `filter` picks, as AI SDK tools named `<module>_<function>`.
|
|
38
|
+
*
|
|
39
|
+
* ```ts
|
|
40
|
+
* tools: toAITools(registry, caller, { filter: (f) => f.fn.meta?.agent === true })
|
|
41
|
+
* ```
|
|
42
|
+
*/
|
|
43
|
+
export function toAITools(registry, caller, options) {
|
|
44
|
+
if (typeof options?.filter !== "function")
|
|
45
|
+
throw new Error("[logic-sdk] toAITools needs a filter: the agent door is opt-in. E.g. { filter: (f) => f.fn.meta?.agent === true }");
|
|
46
|
+
const tools = {};
|
|
47
|
+
for (const f of registry.functions)
|
|
48
|
+
if (f.exposed && options.filter(f))
|
|
49
|
+
tools[`${f.module}_${f.name}`] = toAITool(caller, f.fn, options);
|
|
50
|
+
return tools;
|
|
51
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { DatabaseAdapter } from "./index.ts";
|
|
2
|
+
/** Anything with Drizzle's `transaction(fn)`: a database or a transaction (nested = savepoint). */
|
|
3
|
+
interface Transactional {
|
|
4
|
+
transaction<T>(fn: (tx: any) => Promise<T>, config?: any): Promise<T>;
|
|
5
|
+
}
|
|
6
|
+
/** The transaction type of a Drizzle database: `type Tx = DrizzleTx<typeof db>`. */
|
|
7
|
+
export type DrizzleTx<Db extends Transactional> = Parameters<Parameters<Db["transaction"]>[0]>[0];
|
|
8
|
+
/** What queries get: the database minus write methods. A type-level guard, not a runtime one. */
|
|
9
|
+
export type DrizzleReader<Db> = Omit<Db, "insert" | "update" | "delete" | "execute" | "transaction" | "batch" | "run" | "refreshMaterializedView">;
|
|
10
|
+
/**
|
|
11
|
+
* Use a Drizzle database for mutations. Needs a driver with interactive transactions
|
|
12
|
+
* (node-postgres, postgres.js, PGlite, Neon websocket, Hyperdrive, better-sqlite3, libsql...).
|
|
13
|
+
* Not D1 or HTTP drivers.
|
|
14
|
+
*/
|
|
15
|
+
export declare function drizzleAdapter<Db extends Transactional>(db: Db): DatabaseAdapter<Db, DrizzleTx<Db>>;
|
|
16
|
+
/** The SQLSTATE of a driver error, also when Drizzle wraps it (`DrizzleQueryError.cause`). Use it to map constraints. */
|
|
17
|
+
export declare function sqlState(error: unknown): string | undefined;
|
|
18
|
+
export {};
|
package/dist/drizzle.js
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Use a Drizzle database for mutations. Needs a driver with interactive transactions
|
|
3
|
+
* (node-postgres, postgres.js, PGlite, Neon websocket, Hyperdrive, better-sqlite3, libsql...).
|
|
4
|
+
* Not D1 or HTTP drivers.
|
|
5
|
+
*/
|
|
6
|
+
export function drizzleAdapter(db) {
|
|
7
|
+
return {
|
|
8
|
+
db,
|
|
9
|
+
transactions: "interactive",
|
|
10
|
+
transaction: (fn) => db.transaction(fn),
|
|
11
|
+
nest: (tx) => drizzleAdapter(tx),
|
|
12
|
+
retryable: (e) => RETRYABLE.has(sqlState(e) ?? ""),
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
/** Postgres: serialization_failure, deadlock_detected. The transaction lost a race; running it again is the fix. */
|
|
16
|
+
const RETRYABLE = new Set(["40001", "40P01"]);
|
|
17
|
+
/** The SQLSTATE of a driver error, also when Drizzle wraps it (`DrizzleQueryError.cause`). Use it to map constraints. */
|
|
18
|
+
export function sqlState(error) {
|
|
19
|
+
for (let e = error, i = 0; e && i < 5; e = e.cause, i++)
|
|
20
|
+
if (typeof e.code === "string")
|
|
21
|
+
return e.code;
|
|
22
|
+
return undefined;
|
|
23
|
+
}
|
package/dist/fetch.d.ts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { DomainError, type CallerOptions, type ErrorKind, type Registry } from "./index.ts";
|
|
2
|
+
/**
|
|
3
|
+
* Throw from `resolveScope` when this mount is session-only and there's no valid session: the client gets 401.
|
|
4
|
+
* For mounts that also serve public functions, return a scope with no actor instead, and let policies answer 403.
|
|
5
|
+
*/
|
|
6
|
+
export declare const unauthenticated: (code?: string, details?: unknown) => DomainError;
|
|
7
|
+
/** Error kind → HTTP status. The only place statuses exist: core errors know nothing about HTTP. */
|
|
8
|
+
export declare const statusOf: Record<ErrorKind, number>;
|
|
9
|
+
export interface FetchOptions<S extends object> {
|
|
10
|
+
/** Build the scope for this request (session → actor, account, locale...). */
|
|
11
|
+
resolveScope: (request: Request, ...rest: any[]) => S | Promise<S>;
|
|
12
|
+
/** Per-request caller options, e.g. `(req) => ({ signal: req.signal })`. */
|
|
13
|
+
callerOptions?: (request: Request, ...rest: any[]) => CallerOptions;
|
|
14
|
+
/** Mount point. Default "/". Functions live at `${basePath}${id}`, e.g. `/api/bookings.confirm`. */
|
|
15
|
+
basePath?: string;
|
|
16
|
+
/** Unexpected (non-domain) errors. Default: console.error. */
|
|
17
|
+
onError?: (error: unknown) => void;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* A web-standard handler (Workers, Bun, Node via Hono or srvx, SvelteKit, Next route handlers...).
|
|
21
|
+
* Publishes only functions with `expose: true`. POST `{base}{id}` with a JSON body (`content-type: application/json` required);
|
|
22
|
+
* queries also accept GET `?input=<json>`.
|
|
23
|
+
*/
|
|
24
|
+
export declare function toFetchHandler<S extends object>(registry: Registry<S, any>, options: FetchOptions<S>): (request: Request, ...rest: any[]) => Promise<Response>;
|
package/dist/fetch.js
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { DomainError, isDomainError } from "./index.js";
|
|
2
|
+
/**
|
|
3
|
+
* Throw from `resolveScope` when this mount is session-only and there's no valid session: the client gets 401.
|
|
4
|
+
* For mounts that also serve public functions, return a scope with no actor instead, and let policies answer 403.
|
|
5
|
+
*/
|
|
6
|
+
export const unauthenticated = (code = "unauthenticated", details) => new DomainError("unauthenticated", code, details);
|
|
7
|
+
/** Error kind → HTTP status. The only place statuses exist: core errors know nothing about HTTP. */
|
|
8
|
+
export const statusOf = {
|
|
9
|
+
invalid: 400,
|
|
10
|
+
unauthenticated: 401,
|
|
11
|
+
forbidden: 403,
|
|
12
|
+
not_found: 404,
|
|
13
|
+
conflict: 409,
|
|
14
|
+
rejected: 422,
|
|
15
|
+
};
|
|
16
|
+
const json = (body, status = 200) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
|
|
17
|
+
/**
|
|
18
|
+
* A web-standard handler (Workers, Bun, Node via Hono or srvx, SvelteKit, Next route handlers...).
|
|
19
|
+
* Publishes only functions with `expose: true`. POST `{base}{id}` with a JSON body (`content-type: application/json` required);
|
|
20
|
+
* queries also accept GET `?input=<json>`.
|
|
21
|
+
*/
|
|
22
|
+
export function toFetchHandler(registry, options) {
|
|
23
|
+
const base = (options.basePath ?? "/").replace(/\/?$/, "/");
|
|
24
|
+
const exposed = new Map(registry.functions.filter((f) => f.exposed).map((f) => [f.id, f]));
|
|
25
|
+
const onError = options.onError ?? ((e) => console.error("[logic-sdk] unexpected error", e));
|
|
26
|
+
return async (request, ...rest) => {
|
|
27
|
+
const path = new URL(request.url).pathname;
|
|
28
|
+
if (!path.startsWith(base))
|
|
29
|
+
return json({ error: { kind: "not_found", code: "route_not_found" } }, 404);
|
|
30
|
+
const id = path.slice(base.length);
|
|
31
|
+
const entry = exposed.get(id);
|
|
32
|
+
if (!entry)
|
|
33
|
+
return json({ error: { kind: "not_found", code: "function_not_found" } }, 404);
|
|
34
|
+
let input;
|
|
35
|
+
try {
|
|
36
|
+
if (request.method === "POST") {
|
|
37
|
+
// JSON only: blocks cross-site "simple" form posts (CSRF) because they can't send this content type without a preflight
|
|
38
|
+
if (!(request.headers.get("content-type") ?? "").toLowerCase().startsWith("application/json"))
|
|
39
|
+
return json({ error: { kind: "invalid", code: "unsupported_media_type" } }, 415);
|
|
40
|
+
const text = await request.text();
|
|
41
|
+
input = text ? JSON.parse(text) : undefined;
|
|
42
|
+
}
|
|
43
|
+
else if (request.method === "GET" && entry.kind === "query") {
|
|
44
|
+
const raw = new URL(request.url).searchParams.get("input");
|
|
45
|
+
input = raw ? JSON.parse(raw) : undefined;
|
|
46
|
+
}
|
|
47
|
+
else {
|
|
48
|
+
const res = json({ error: { kind: "invalid", code: "method_not_allowed" } }, 405);
|
|
49
|
+
res.headers.set("allow", entry.kind === "query" ? "GET, POST" : "POST");
|
|
50
|
+
return res;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
return json({ error: { kind: "invalid", code: "malformed_json" } }, 400);
|
|
55
|
+
}
|
|
56
|
+
try {
|
|
57
|
+
const scope = await options.resolveScope(request, ...rest);
|
|
58
|
+
const caller = registry.as(scope, options.callerOptions?.(request, ...rest));
|
|
59
|
+
return json({ data: await caller.run(entry.fn, input) });
|
|
60
|
+
}
|
|
61
|
+
catch (e) {
|
|
62
|
+
if (isDomainError(e))
|
|
63
|
+
return json({ error: { kind: e.kind, code: e.code, details: e.details } }, statusOf[e.kind]);
|
|
64
|
+
onError(e);
|
|
65
|
+
return json({ error: { kind: "internal", code: "internal_error" } }, 500);
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
}
|