@wervt/core 0.0.0-stage → 0.0.2

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/README.md CHANGED
@@ -1,3 +1,27 @@
1
- # Temporary Holding Version
1
+ # @wervt/core
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The server side of an app on [wervt](https://wervt.app), on web standards (`Request`, `Response`,
4
+ `fetch`), so it works with Nitro (through `@wervt/nitro`), Nuxt (`@wervt/nuxt` builds on it) or a
5
+ plain `export default { fetch }`.
6
+
7
+ ```ts
8
+ import {
9
+ createTaskHandler,
10
+ defineTask,
11
+ getUser,
12
+ proxyShape,
13
+ requireRole,
14
+ sendMail,
15
+ } from '@wervt/core'
16
+ import { useDb } from '@wervt/core/db'
17
+ import { getAnthropic } from '@wervt/core/anthropic'
18
+ ```
19
+
20
+ - `getUser(request)`, `requireRole(request, ...roles)`: the signed-in user the runtime vouches for.
21
+ - `proxyShape(request, { table, where, params })`: live data from Electric, through the runtime.
22
+ - `sendMail({ to, subject, html, text })`, `appAccess(request)`, `workloadIdentity()`.
23
+ - `createTaskHandler(tasks)`: the routes the control plane runs tasks through.
24
+ - `useDb()`, `seedTable()` (`@wervt/core/db`): Drizzle on the app's database.
25
+ - `getAnthropic()` (`@wervt/core/anthropic`): Claude without an API key, through the app's identity.
26
+
27
+ Failed platform calls throw a `WervtError` with the HTTP status to answer.
@@ -0,0 +1,32 @@
1
+ export interface WervtInvite {
2
+ email: string;
3
+ /** Who invited them. */
4
+ by: string;
5
+ /** ISO time. */
6
+ at: string;
7
+ }
8
+ export interface WervtAccess {
9
+ /** Lets `email` into the app. `invited` is false when they could already get in. */
10
+ invite(email: string): Promise<{
11
+ email: string;
12
+ invited: boolean;
13
+ }>;
14
+ /** Takes back an invite (not the owner's allow list). */
15
+ revoke(email: string): Promise<{
16
+ email: string;
17
+ revoked: boolean;
18
+ }>;
19
+ /** Everyone the app invited, with who invited them and when. */
20
+ list(): Promise<WervtInvite[]>;
21
+ }
22
+ /**
23
+ * Invites on an invite-only app (`wervt access <app> --invite`), as the user of `request`: the
24
+ * runtime vouches for them with the user proof, and only someone with access can invite. Everyone
25
+ * with access may invite, or only the owner, members and admins with
26
+ * `wervt access <app> --invite-by owners`; restrict it further if the app has its own roles.
27
+ *
28
+ * Throws a WervtError with the platform's status: 401 without a signed-in user, 403 when they may
29
+ * not invite, 409 when the app isn't invite-only, 429 past the limits (25 invites per person and
30
+ * day, 500 per app), 503 in local dev.
31
+ */
32
+ export declare function appAccess(request: Request): WervtAccess;
package/dist/access.js ADDED
@@ -0,0 +1,30 @@
1
+ import { callRuntime } from "./runtime.js";
2
+ import { USER_HEADER, USER_PROOF_HEADER } from "./user.js";
3
+ // src/access.ts
4
+ /**
5
+ * Invites on an invite-only app (`wervt access <app> --invite`), as the user of `request`: the
6
+ * runtime vouches for them with the user proof, and only someone with access can invite. Everyone
7
+ * with access may invite, or only the owner, members and admins with
8
+ * `wervt access <app> --invite-by owners`; restrict it further if the app has its own roles.
9
+ *
10
+ * Throws a WervtError with the platform's status: 401 without a signed-in user, 403 when they may
11
+ * not invite, 409 when the app isn't invite-only, 429 past the limits (25 invites per person and
12
+ * day, 500 per app), 503 in local dev.
13
+ */
14
+ function appAccess(request) {
15
+ const headers = {
16
+ [USER_HEADER]: request.headers.get("x-wervt-user") ?? "",
17
+ [USER_PROOF_HEADER]: request.headers.get("x-wervt-user-proof") ?? ""
18
+ };
19
+ const call = (method, body) => callRuntime("/_wervt/access", {
20
+ method,
21
+ body,
22
+ headers
23
+ });
24
+ return {
25
+ invite: (email) => call("POST", { email }),
26
+ revoke: (email) => call("DELETE", { email }),
27
+ list: async () => (await call("GET")).invited
28
+ };
29
+ }
30
+ export { appAccess };
@@ -0,0 +1,19 @@
1
+ import Anthropic from "@anthropic-ai/sdk";
2
+ export interface AnthropicOptions {
3
+ /**
4
+ * The key for local dev, where there is no workload identity. Default: `ANTHROPIC_API_KEY`.
5
+ * Never used on wervt.
6
+ */
7
+ devApiKey?: string;
8
+ }
9
+ /**
10
+ * An Anthropic client that authenticates as this app through its wervt identity: no API key, only
11
+ * IDs from the Anthropic Console in the app's env (`ANTHROPIC_FEDERATION_RULE_ID`,
12
+ * `ANTHROPIC_ORGANIZATION_ID`, optionally `ANTHROPIC_SERVICE_ACCOUNT_ID` and
13
+ * `ANTHROPIC_WORKSPACE_ID`). The SDK trades an identity token for an Anthropic token and renews it
14
+ * before it runs out.
15
+ *
16
+ * Needs `wervt identity enable <app>` and a federation rule for the app's subject
17
+ * (`wervt identity status <app>`). In local dev it uses `options.devApiKey` instead.
18
+ */
19
+ export declare function getAnthropic(options?: AnthropicOptions): Anthropic;
@@ -0,0 +1,47 @@
1
+ import { WervtError } from "./errors.js";
2
+ import { runtimeUrl } from "./runtime.js";
3
+ import { workloadIdentity } from "./identity.js";
4
+ import Anthropic from "@anthropic-ai/sdk";
5
+ import { oidcFederationProvider } from "@anthropic-ai/sdk/lib/credentials/oidc-federation";
6
+ // src/anthropic.ts
7
+ const BASE_URL = "https://api.anthropic.com";
8
+ let client;
9
+ /**
10
+ * An Anthropic client that authenticates as this app through its wervt identity: no API key, only
11
+ * IDs from the Anthropic Console in the app's env (`ANTHROPIC_FEDERATION_RULE_ID`,
12
+ * `ANTHROPIC_ORGANIZATION_ID`, optionally `ANTHROPIC_SERVICE_ACCOUNT_ID` and
13
+ * `ANTHROPIC_WORKSPACE_ID`). The SDK trades an identity token for an Anthropic token and renews it
14
+ * before it runs out.
15
+ *
16
+ * Needs `wervt identity enable <app>` and a federation rule for the app's subject
17
+ * (`wervt identity status <app>`). In local dev it uses `options.devApiKey` instead.
18
+ */
19
+ function getAnthropic(options = {}) {
20
+ return client ??= create(options);
21
+ }
22
+ function create(options) {
23
+ if (!runtimeUrl()) {
24
+ const apiKey = options.devApiKey ?? process.env.ANTHROPIC_API_KEY;
25
+ if (!apiKey) throw new WervtError(503, "The Anthropic client in local dev needs an API key (ANTHROPIC_API_KEY or devApiKey).");
26
+ return new Anthropic({ apiKey });
27
+ }
28
+ const federationRuleId = process.env.ANTHROPIC_FEDERATION_RULE_ID;
29
+ const organizationId = process.env.ANTHROPIC_ORGANIZATION_ID;
30
+ if (!federationRuleId || !organizationId) throw new WervtError(503, "The Anthropic client needs ANTHROPIC_FEDERATION_RULE_ID and ANTHROPIC_ORGANIZATION_ID (wervt env <app> --set …).");
31
+ const identity = workloadIdentity();
32
+ return new Anthropic({
33
+ apiKey: null,
34
+ authToken: null,
35
+ baseURL: BASE_URL,
36
+ credentials: oidcFederationProvider({
37
+ identityTokenProvider: () => identity.token(BASE_URL),
38
+ federationRuleId,
39
+ organizationId,
40
+ serviceAccountId: process.env.ANTHROPIC_SERVICE_ACCOUNT_ID || void 0,
41
+ workspaceId: process.env.ANTHROPIC_WORKSPACE_ID || void 0,
42
+ baseURL: BASE_URL,
43
+ fetch: (...args) => fetch(...args)
44
+ })
45
+ });
46
+ }
47
+ export { getAnthropic };
package/dist/db.d.ts ADDED
@@ -0,0 +1,22 @@
1
+ import { AnyRelations, EmptyRelations, InferInsertModel } from "drizzle-orm";
2
+ import { PostgresJsDatabase } from "drizzle-orm/postgres-js";
3
+ import { PgTable } from "drizzle-orm/pg-core";
4
+ /**
5
+ * Drizzle client for the app's database. On wervt the runtime injects DATABASE_URL for the app's
6
+ * own role, whose search_path is its own schema, so tables are declared without a schema.
7
+ *
8
+ * Pass the app's relations (from `defineRelations`) to use `db.query.*`. All clients
9
+ * share one connection pool.
10
+ *
11
+ * @example
12
+ * const db = useDb({ relations })
13
+ * const room = await db.query.rooms.findFirst({ where: { id }, with: { players: true } })
14
+ */
15
+ export declare function useDb<TRelations extends AnyRelations = EmptyRelations>(options?: {
16
+ relations?: TRelations;
17
+ }): PostgresJsDatabase<TRelations>;
18
+ /**
19
+ * Inserts `rows` into `table` only while it is empty, so a seed task can run again without
20
+ * duplicating data or touching what users created. Returns how many rows it inserted.
21
+ */
22
+ export declare function seedTable<T extends PgTable>(table: T, rows: InferInsertModel<T>[]): Promise<number>;
package/dist/db.js ADDED
@@ -0,0 +1,48 @@
1
+ import { sql } from "drizzle-orm";
2
+ import { drizzle } from "drizzle-orm/postgres-js";
3
+ import postgres from "postgres";
4
+ // src/db.ts
5
+ let client;
6
+ const clients = /* @__PURE__ */ new Map();
7
+ /**
8
+ * Drizzle client for the app's database. On wervt the runtime injects DATABASE_URL for the app's
9
+ * own role, whose search_path is its own schema, so tables are declared without a schema.
10
+ *
11
+ * Pass the app's relations (from `defineRelations`) to use `db.query.*`. All clients
12
+ * share one connection pool.
13
+ *
14
+ * @example
15
+ * const db = useDb({ relations })
16
+ * const room = await db.query.rooms.findFirst({ where: { id }, with: { players: true } })
17
+ */
18
+ function useDb(options) {
19
+ if (!process.env.DATABASE_URL) throw new Error("DATABASE_URL is not set");
20
+ client ??= postgres(process.env.DATABASE_URL, {
21
+ max: 2,
22
+ idle_timeout: 20
23
+ });
24
+ const relations = options?.relations;
25
+ let db = clients.get(relations);
26
+ if (!db) {
27
+ db = drizzle({
28
+ client,
29
+ relations
30
+ });
31
+ clients.set(relations, db);
32
+ }
33
+ return db;
34
+ }
35
+ /**
36
+ * Inserts `rows` into `table` only while it is empty, so a seed task can run again without
37
+ * duplicating data or touching what users created. Returns how many rows it inserted.
38
+ */
39
+ async function seedTable(table, rows) {
40
+ if (rows.length === 0) return 0;
41
+ const db = useDb();
42
+ const target = table;
43
+ const [existing] = await db.select({ one: sql`1` }).from(target).limit(1);
44
+ if (existing) return 0;
45
+ await db.insert(target).values(rows);
46
+ return rows.length;
47
+ }
48
+ export { seedTable, useDb };
@@ -0,0 +1,11 @@
1
+ /**
2
+ * A failed platform call or check, with the HTTP status to answer. Framework adapters turn it into
3
+ * their own error type (h3's `createError` in @wervt/nuxt); a plain fetch handler can
4
+ * answer it with `errorResponse`.
5
+ */
6
+ export declare class WervtError extends Error {
7
+ readonly status: number;
8
+ constructor(status: number, message: string);
9
+ }
10
+ /** `{ error }` with the error's status, 500 for anything that isn't a WervtError. */
11
+ export declare function errorResponse(error: unknown): Response;
package/dist/errors.js ADDED
@@ -0,0 +1,20 @@
1
+ // src/errors.ts
2
+ /**
3
+ * A failed platform call or check, with the HTTP status to answer. Framework adapters turn it into
4
+ * their own error type (h3's `createError` in @wervt/nuxt); a plain fetch handler can
5
+ * answer it with `errorResponse`.
6
+ */
7
+ var WervtError = class extends Error {
8
+ status;
9
+ constructor(status, message) {
10
+ super(message);
11
+ this.name = "WervtError";
12
+ this.status = status;
13
+ }
14
+ };
15
+ /** `{ error }` with the error's status, 500 for anything that isn't a WervtError. */
16
+ function errorResponse(error) {
17
+ if (error instanceof WervtError) return Response.json({ error: error.message }, { status: error.status });
18
+ return Response.json({ error: "internal error" }, { status: 500 });
19
+ }
20
+ export { WervtError, errorResponse };
@@ -0,0 +1,18 @@
1
+ export interface WorkloadIdentity {
2
+ /**
3
+ * A fresh JWT that says "I am this wervt app", for `audience` (a provider on wervt's list, e.g.
4
+ * `https://api.anthropic.com`). Valid for 5 minutes and single-use: trade it for a provider
5
+ * token right away. Each call signs a new one; providers' SDKs cache what they get for it.
6
+ */
7
+ token(audience: string): Promise<string>;
8
+ }
9
+ /**
10
+ * The app's workload identity: tokens signed by wervt's issuer, so the app can authenticate to an
11
+ * AI provider (Anthropic's Workload Identity Federation) without an API key. Its owner turns it
12
+ * on with `wervt identity enable <app>`; `getAnthropic()` (`@wervt/core/anthropic`) uses it.
13
+ *
14
+ * Throws a WervtError with the platform's status: 403 when the app has no identity, 400 for an
15
+ * audience wervt doesn't sign for, 429 past 10 tokens a minute, 503 when the issuer is off. In
16
+ * local dev there is no issuer, so it always throws.
17
+ */
18
+ export declare function workloadIdentity(): WorkloadIdentity;
@@ -0,0 +1,21 @@
1
+ import { WervtError } from "./errors.js";
2
+ import { callRuntime, runtimeUrl } from "./runtime.js";
3
+ // src/identity.ts
4
+ /**
5
+ * The app's workload identity: tokens signed by wervt's issuer, so the app can authenticate to an
6
+ * AI provider (Anthropic's Workload Identity Federation) without an API key. Its owner turns it
7
+ * on with `wervt identity enable <app>`; `getAnthropic()` (`@wervt/core/anthropic`) uses it.
8
+ *
9
+ * Throws a WervtError with the platform's status: 403 when the app has no identity, 400 for an
10
+ * audience wervt doesn't sign for, 429 past 10 tokens a minute, 503 when the issuer is off. In
11
+ * local dev there is no issuer, so it always throws.
12
+ */
13
+ function workloadIdentity() {
14
+ return { async token(audience) {
15
+ if (!runtimeUrl()) throw new WervtError(503, "Workload identity only exists on wervt, not in local dev.");
16
+ const { token } = await callRuntime("/_wervt/identity-token", { body: { audience } });
17
+ if (!token) throw new WervtError(502, "identity token missing in the answer");
18
+ return token;
19
+ } };
20
+ }
21
+ export { workloadIdentity };
@@ -0,0 +1,10 @@
1
+ import { WervtAccess, WervtInvite, appAccess } from "./access.js";
2
+ import { WervtError, errorResponse } from "./errors.js";
3
+ import { WorkloadIdentity, workloadIdentity } from "./identity.js";
4
+ import { MailMessage, sendMail } from "./mail.js";
5
+ import { BUNDLE_MANIFEST, BrandManifest, BundleManifest, PreviewManifest, TaskSchedule, TasksManifest } from "./manifest.js";
6
+ import { appHeaders, callRuntime, runtimeUrl } from "./runtime.js";
7
+ import { ShapeRequest, ShapeResponse, ShapeRowOf, parseTimestamp, proxyShape, shapeParser } from "./shape.js";
8
+ import { ACCOUNT_MERGED_TASK, AccountMergedPayload, TASK_HEADER, Task, TaskEvent, TaskResult, createTaskHandler, defineTask, isTaskRequest, taskRunResponse } from "./tasks.js";
9
+ import { AGENT_TOKEN_HEADER, AgentToken, USER_HEADER, USER_PROOF_HEADER, WervtRole, WervtUser, checkRole, getAgentToken, getUser, parseAgentToken, parseWervtUser, requireRole, userFromClaims } from "./user.js";
10
+ export { ACCOUNT_MERGED_TASK, AGENT_TOKEN_HEADER, type AccountMergedPayload, type AgentToken, BUNDLE_MANIFEST, type BrandManifest, type BundleManifest, type MailMessage, type PreviewManifest, type ShapeRequest, type ShapeResponse, type ShapeRowOf, TASK_HEADER, type Task, type TaskEvent, type TaskResult, type TaskSchedule, type TasksManifest, USER_HEADER, USER_PROOF_HEADER, type WervtAccess, WervtError, type WervtInvite, type WervtRole, type WervtUser, type WorkloadIdentity, appAccess, appHeaders, callRuntime, checkRole, createTaskHandler, defineTask, errorResponse, getAgentToken, getUser, isTaskRequest, parseAgentToken, parseTimestamp, parseWervtUser, proxyShape, requireRole, runtimeUrl, sendMail, shapeParser, taskRunResponse, userFromClaims, workloadIdentity };
package/dist/index.js ADDED
@@ -0,0 +1,10 @@
1
+ import { WervtError, errorResponse } from "./errors.js";
2
+ import { appHeaders, callRuntime, runtimeUrl } from "./runtime.js";
3
+ import { AGENT_TOKEN_HEADER, USER_HEADER, USER_PROOF_HEADER, checkRole, getAgentToken, getUser, parseAgentToken, parseWervtUser, requireRole, userFromClaims } from "./user.js";
4
+ import { appAccess } from "./access.js";
5
+ import { workloadIdentity } from "./identity.js";
6
+ import { sendMail } from "./mail.js";
7
+ import { BUNDLE_MANIFEST } from "./manifest.js";
8
+ import { parseTimestamp, proxyShape, shapeParser } from "./shape.js";
9
+ import { ACCOUNT_MERGED_TASK, TASK_HEADER, createTaskHandler, defineTask, isTaskRequest, taskRunResponse } from "./tasks.js";
10
+ export { ACCOUNT_MERGED_TASK, AGENT_TOKEN_HEADER, BUNDLE_MANIFEST, TASK_HEADER, USER_HEADER, USER_PROOF_HEADER, WervtError, appAccess, appHeaders, callRuntime, checkRole, createTaskHandler, defineTask, errorResponse, getAgentToken, getUser, isTaskRequest, parseAgentToken, parseTimestamp, parseWervtUser, proxyShape, requireRole, runtimeUrl, sendMail, shapeParser, taskRunResponse, userFromClaims, workloadIdentity };
package/dist/mail.d.ts ADDED
@@ -0,0 +1,26 @@
1
+ export interface MailMessage {
2
+ /** One recipient. */
3
+ to: string;
4
+ subject: string;
5
+ html: string;
6
+ /** The same as plain text, for mail clients that don't show HTML. */
7
+ text: string;
8
+ /** Where replies go. The sender is always `<app> <mail@wervt.app>`. */
9
+ replyTo?: string;
10
+ /**
11
+ * The sender's display name instead of the app's. Only the wervt login may set it (for the app
12
+ * someone signs in to); for every other app the platform ignores it.
13
+ */
14
+ fromName?: string;
15
+ /** Which template it came from, for the app's mail log. */
16
+ template?: string;
17
+ }
18
+ /**
19
+ * Sends a mail through wervt. Throws a WervtError with the platform's status on failure: 400
20
+ * (invalid mail), 429 (the app's or the recipient's hourly limit), 502/503.
21
+ *
22
+ * In local dev nothing is sent: the mail is printed to the console.
23
+ */
24
+ export declare function sendMail(message: MailMessage): Promise<{
25
+ id: string;
26
+ }>;
package/dist/mail.js ADDED
@@ -0,0 +1,17 @@
1
+ import { callRuntime, runtimeUrl } from "./runtime.js";
2
+ // src/mail.ts
3
+ /**
4
+ * Sends a mail through wervt. Throws a WervtError with the platform's status on failure: 400
5
+ * (invalid mail), 429 (the app's or the recipient's hourly limit), 502/503.
6
+ *
7
+ * In local dev nothing is sent: the mail is printed to the console.
8
+ */
9
+ async function sendMail(message) {
10
+ if (!runtimeUrl()) {
11
+ console.info(`[mail] to ${message.to}: ${message.subject}\n${message.text}`);
12
+ return { id: "dev" };
13
+ }
14
+ const { id } = await callRuntime("/_wervt/mail", { body: message });
15
+ return { id: id ?? "" };
16
+ }
17
+ export { sendMail };
@@ -0,0 +1,62 @@
1
+ export interface TaskSchedule {
2
+ /** Cron expression, in `timezone`. */
3
+ cron: string;
4
+ tasks: string[];
5
+ }
6
+ export interface TasksManifest {
7
+ tasks: {
8
+ name: string;
9
+ description?: string;
10
+ }[];
11
+ schedules: TaskSchedule[];
12
+ /** IANA time zone the schedules run in, UTC when missing. */
13
+ timezone?: string;
14
+ }
15
+ /** A private app's link preview, shown to visitors who aren't signed in. */
16
+ export interface PreviewManifest {
17
+ title?: string;
18
+ description?: string;
19
+ /** A file in `public/` (`/og.png`) or an absolute https URL. */
20
+ image?: string;
21
+ icon?: string;
22
+ themeColor?: string;
23
+ }
24
+ /** The login's look for this app instead of wervt's. */
25
+ export interface BrandManifest {
26
+ name: string;
27
+ /** A file in `public/` (`/logo.svg`) or an absolute https URL. */
28
+ logo?: string;
29
+ icon?: string;
30
+ /** A hex color like `#2f5bff`. */
31
+ color?: string;
32
+ /** `false` hides the login's "Secured by wervt". */
33
+ securedByWervt?: false;
34
+ /** The sign-in options the login offers, e.g. `['twitch', 'email']`. All of them by default. */
35
+ signIn?: string[];
36
+ }
37
+ /** The bundle's `wervt-bundle.json`, next to `server/` and `public/`. */
38
+ export declare const BUNDLE_MANIFEST = "wervt-bundle.json";
39
+ export interface BundleManifest {
40
+ version: 2;
41
+ /** What built it, e.g. `nuxt`, `nitro`, `static`. Shown in the dashboard. */
42
+ framework?: string;
43
+ /**
44
+ * Whether the app gets a database. Defaults to whether the bundle has `drizzle/` migrations;
45
+ * `true` without them gives an empty schema.
46
+ */
47
+ database?: boolean;
48
+ public?: {
49
+ /**
50
+ * Path prefixes of files that never change (hashed build assets), cached for a year, e.g.
51
+ * `['/assets/']`. Defaults to Nuxt's `/_nuxt/` for Nuxt and bundles without a framework.
52
+ */
53
+ immutable?: string[];
54
+ /** Paths browsers must check again every time, e.g. a file naming the newest build. */
55
+ noCache?: string[];
56
+ };
57
+ tasks?: TasksManifest;
58
+ /** Shape routes without parameters, requested once after a deploy to check they work. */
59
+ shapes?: string[];
60
+ preview?: PreviewManifest;
61
+ brand?: BrandManifest;
62
+ }
@@ -0,0 +1,4 @@
1
+ // src/manifest.ts
2
+ /** The bundle's `wervt-bundle.json`, next to `server/` and `public/`. */
3
+ const BUNDLE_MANIFEST = "wervt-bundle.json";
4
+ export { BUNDLE_MANIFEST };
@@ -0,0 +1,13 @@
1
+ /** The runtime's URL, `undefined` outside wervt (local dev). */
2
+ export declare function runtimeUrl(): string | undefined;
3
+ /** The app's credentials for runtime services. */
4
+ export declare function appHeaders(): Record<string, string>;
5
+ /**
6
+ * Calls a runtime service as this app and returns its JSON. Throws a WervtError with the
7
+ * service's status and `error` message when it fails.
8
+ */
9
+ export declare function callRuntime<T>(path: string, init?: {
10
+ method?: string;
11
+ body?: unknown;
12
+ headers?: Record<string, string>;
13
+ }): Promise<T>;
@@ -0,0 +1,34 @@
1
+ import { WervtError } from "./errors.js";
2
+ // src/runtime.ts
3
+ /** The runtime's URL, `undefined` outside wervt (local dev). */
4
+ function runtimeUrl() {
5
+ return process.env.WERVT_RUNTIME_URL || void 0;
6
+ }
7
+ /** The app's credentials for runtime services. */
8
+ function appHeaders() {
9
+ return {
10
+ "x-wervt-app": process.env.WERVT_APP ?? "",
11
+ "x-wervt-token": process.env.WERVT_TOKEN ?? ""
12
+ };
13
+ }
14
+ /**
15
+ * Calls a runtime service as this app and returns its JSON. Throws a WervtError with the
16
+ * service's status and `error` message when it fails.
17
+ */
18
+ async function callRuntime(path, init = {}) {
19
+ const runtime = runtimeUrl();
20
+ if (!runtime) throw new WervtError(503, `${path} only exists on wervt, not in local dev`);
21
+ const res = await fetch(new URL(path, runtime), {
22
+ method: init.method ?? (init.body === void 0 ? "GET" : "POST"),
23
+ headers: {
24
+ "content-type": "application/json",
25
+ ...appHeaders(),
26
+ ...init.headers
27
+ },
28
+ body: init.body === void 0 ? void 0 : JSON.stringify(init.body)
29
+ });
30
+ const data = await res.json().catch(() => ({}));
31
+ if (!res.ok) throw new WervtError(res.status, data.error ?? `${path} failed (${res.status})`);
32
+ return data;
33
+ }
34
+ export { appHeaders, callRuntime, runtimeUrl };
@@ -0,0 +1,34 @@
1
+ declare const shapeRow: unique symbol;
2
+ export type ShapeResponse<Row> = Response & {
3
+ readonly [shapeRow]?: Row;
4
+ };
5
+ /** The row type of a shape route's handler, `never` if it doesn't serve a typed shape. */
6
+ export type ShapeRowOf<Handler> = Handler extends ((...args: never[]) => infer Result) ? Awaited<Result> extends ShapeResponse<infer Row> ? Row : never : never;
7
+ export interface ShapeRequest {
8
+ /** The table's name, without schema. */
9
+ table: string;
10
+ /** SQL where clause. Use `$1`, `$2`, … placeholders with `params` for values. */
11
+ where?: string;
12
+ /** Values for the `$n` placeholders in `where`. */
13
+ params?: (string | number | boolean)[];
14
+ columns?: string[];
15
+ }
16
+ /**
17
+ * Serves an Electric shape for `request` (the client's request to the app's shape route). Do
18
+ * auth checks before calling it.
19
+ *
20
+ * On wervt the shape goes through the runtime's gateway. In local dev it goes to Electric directly
21
+ * (ELECTRIC_URL, ELECTRIC_SECRET, the table in WERVT_DB_SCHEMA).
22
+ */
23
+ export declare function proxyShape<Row = Record<string, unknown>>(request: Request, { table, where, params, columns }: ShapeRequest): Promise<ShapeResponse<Row>>;
24
+ /**
25
+ * Postgres text of a `timestamp`/`timestamptz` as a Date, like Drizzle's default `mode: 'date'`
26
+ * reads it. Drizzle stores `timestamp` without time zone as UTC, so it's read as UTC too.
27
+ */
28
+ export declare function parseTimestamp(value: string): Date;
29
+ /** Electric parsers for the types Drizzle reads differently from Electric's defaults. */
30
+ export declare const shapeParser: {
31
+ timestamp: typeof parseTimestamp;
32
+ timestamptz: typeof parseTimestamp;
33
+ };
34
+ export {};
package/dist/shape.js ADDED
@@ -0,0 +1,64 @@
1
+ import { appHeaders, runtimeUrl } from "./runtime.js";
2
+ // src/shape.ts
3
+ const CLIENT_PARAMS = [
4
+ "offset",
5
+ "handle",
6
+ "live",
7
+ "live_sse",
8
+ "cursor",
9
+ "replica",
10
+ "log"
11
+ ];
12
+ /**
13
+ * Serves an Electric shape for `request` (the client's request to the app's shape route). Do
14
+ * auth checks before calling it.
15
+ *
16
+ * On wervt the shape goes through the runtime's gateway. In local dev it goes to Electric directly
17
+ * (ELECTRIC_URL, ELECTRIC_SECRET, the table in WERVT_DB_SCHEMA).
18
+ */
19
+ async function proxyShape(request, { table, where, params, columns }) {
20
+ const runtime = runtimeUrl();
21
+ const url = runtime ? new URL("/_wervt/electric/v1/shape", runtime) : new URL("/v1/shape", process.env.ELECTRIC_URL ?? "http://localhost:3000");
22
+ const query = new URL(request.url).searchParams;
23
+ for (const key of CLIENT_PARAMS) {
24
+ const value = query.get(key);
25
+ if (value !== null) url.searchParams.set(key, value);
26
+ }
27
+ url.searchParams.set("table", runtime ? table : devTable(table));
28
+ if (where) url.searchParams.set("where", where);
29
+ params?.forEach((value, i) => url.searchParams.set(`params[${i + 1}]`, String(value)));
30
+ if (columns) url.searchParams.set("columns", columns.map(quoteIdentifier).join(","));
31
+ if (!runtime && process.env.ELECTRIC_SECRET) url.searchParams.set("secret", process.env.ELECTRIC_SECRET);
32
+ const res = await fetch(url, {
33
+ headers: runtime ? appHeaders() : {},
34
+ signal: request.signal
35
+ });
36
+ const out = new Headers(res.headers);
37
+ out.delete("content-encoding");
38
+ out.delete("content-length");
39
+ return new Response(res.body, {
40
+ status: res.status,
41
+ headers: out
42
+ });
43
+ }
44
+ function devTable(table) {
45
+ const schema = process.env.WERVT_DB_SCHEMA;
46
+ return schema ? `${schema}.${table}` : table;
47
+ }
48
+ function quoteIdentifier(name) {
49
+ return /^[a-z_][a-z0-9_]*$/.test(name) ? name : `"${name.replaceAll("\"", "\"\"")}"`;
50
+ }
51
+ /**
52
+ * Postgres text of a `timestamp`/`timestamptz` as a Date, like Drizzle's default `mode: 'date'`
53
+ * reads it. Drizzle stores `timestamp` without time zone as UTC, so it's read as UTC too.
54
+ */
55
+ function parseTimestamp(value) {
56
+ const iso = value.replace(" ", "T").replace(/([+-]\d{2})$/, "$1:00");
57
+ return new Date(/(Z|[+-]\d{2}:\d{2})$/.test(iso) ? iso : `${iso}Z`);
58
+ }
59
+ /** Electric parsers for the types Drizzle reads differently from Electric's defaults. */
60
+ const shapeParser = {
61
+ timestamp: parseTimestamp,
62
+ timestamptz: parseTimestamp
63
+ };
64
+ export { parseTimestamp, proxyShape, shapeParser };
@@ -0,0 +1,53 @@
1
+ export declare const TASK_HEADER = "x-wervt-task";
2
+ /** Only the runtime's own task calls carry the mark. */
3
+ export declare function isTaskRequest(request: Request): boolean;
4
+ export interface TaskEvent<P = Record<string, unknown>> {
5
+ name: string;
6
+ /** `{ scheduledTime }` for scheduled runs, or what was passed to a manual run. */
7
+ payload: P;
8
+ context: Record<string, unknown>;
9
+ }
10
+ /**
11
+ * Payload of the `wervt:account-merged` task: one person had two wervt accounts and an admin
12
+ * merged `from` into `into`. `from` no longer exists; move its rows over to `into`.
13
+ */
14
+ export interface AccountMergedPayload {
15
+ from: {
16
+ id: string;
17
+ email: string;
18
+ };
19
+ into: {
20
+ id: string;
21
+ email: string;
22
+ };
23
+ }
24
+ /** The task the control plane runs after merging two accounts, when the app has it. */
25
+ export declare const ACCOUNT_MERGED_TASK = "wervt:account-merged";
26
+ export interface TaskResult<R = unknown> {
27
+ result?: R;
28
+ }
29
+ export interface Task<R = unknown, P = Record<string, unknown>> {
30
+ meta?: {
31
+ name?: string;
32
+ description?: string;
33
+ };
34
+ run(event: TaskEvent<P>): TaskResult<R> | Promise<TaskResult<R>>;
35
+ }
36
+ export declare function defineTask<R = unknown, P = Record<string, unknown>>(task: Task<R, P>): Task<R, P>;
37
+ /** The answer to a task run: `{ result }`, or `{ error }` with the task's status (default 500). */
38
+ export declare function taskRunResponse(name: string, run: () => Promise<TaskResult>): Promise<Response>;
39
+ /**
40
+ * The task routes as a fetch handler: `GET /_wervt/tasks` lists the tasks with their
41
+ * descriptions, `POST /_wervt/tasks/<name>` runs one with `{ payload }`. Answers `undefined` for
42
+ * any other request, so it can sit in front of the app's own handler:
43
+ *
44
+ * @example
45
+ * const tasks = createTaskHandler({ cleanup: defineTask({ run: async () => ({ result: 'ok' }) }) })
46
+ * export default {
47
+ * fetch: async (request) => (await tasks(request)) ?? app.fetch(request),
48
+ * }
49
+ *
50
+ * List the tasks and their schedules in the bundle's manifest too, the control plane runs only
51
+ * what it names there.
52
+ */
53
+ export declare function createTaskHandler(tasks: Record<string, Task<unknown, never>>): (request: Request) => Promise<Response | undefined>;
package/dist/tasks.js ADDED
@@ -0,0 +1,67 @@
1
+ // src/tasks.ts
2
+ const TASK_HEADER = "x-wervt-task";
3
+ /** Only the runtime's own task calls carry the mark. */
4
+ function isTaskRequest(request) {
5
+ return request.headers.get(TASK_HEADER) === "1";
6
+ }
7
+ /** The task the control plane runs after merging two accounts, when the app has it. */
8
+ const ACCOUNT_MERGED_TASK = "wervt:account-merged";
9
+ function defineTask(task) {
10
+ if (typeof task.run !== "function") task.run = () => {
11
+ throw new TypeError("Task must implement a `run` method!");
12
+ };
13
+ return task;
14
+ }
15
+ /** The answer to a task run: `{ result }`, or `{ error }` with the task's status (default 500). */
16
+ async function taskRunResponse(name, run) {
17
+ const headers = { "cache-control": "no-store" };
18
+ try {
19
+ return Response.json({ result: (await run()).result ?? null }, { headers });
20
+ } catch (e) {
21
+ console.error(`Task ${name} failed:`, e);
22
+ const status = e.status ?? e.statusCode ?? 500;
23
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, {
24
+ status,
25
+ headers
26
+ });
27
+ }
28
+ }
29
+ /**
30
+ * The task routes as a fetch handler: `GET /_wervt/tasks` lists the tasks with their
31
+ * descriptions, `POST /_wervt/tasks/<name>` runs one with `{ payload }`. Answers `undefined` for
32
+ * any other request, so it can sit in front of the app's own handler:
33
+ *
34
+ * @example
35
+ * const tasks = createTaskHandler({ cleanup: defineTask({ run: async () => ({ result: 'ok' }) }) })
36
+ * export default {
37
+ * fetch: async (request) => (await tasks(request)) ?? app.fetch(request),
38
+ * }
39
+ *
40
+ * List the tasks and their schedules in the bundle's manifest too, the control plane runs only
41
+ * what it names there.
42
+ */
43
+ function createTaskHandler(tasks) {
44
+ return async (request) => {
45
+ const { pathname } = new URL(request.url);
46
+ if (pathname !== "/_wervt/tasks" && !pathname.startsWith("/_wervt/tasks/")) return void 0;
47
+ if (!isTaskRequest(request)) return Response.json({ error: "not found" }, { status: 404 });
48
+ if (pathname === "/_wervt/tasks") {
49
+ if (request.method !== "GET") return Response.json({ error: "method not allowed" }, { status: 405 });
50
+ return Response.json(Object.entries(tasks).map(([name, task]) => ({
51
+ name,
52
+ description: task.meta?.description
53
+ })), { headers: { "cache-control": "no-store" } });
54
+ }
55
+ if (request.method !== "POST") return Response.json({ error: "method not allowed" }, { status: 405 });
56
+ const name = decodeURIComponent(pathname.slice(14));
57
+ const task = Object.hasOwn(tasks, name) ? tasks[name] : void 0;
58
+ if (!task) return Response.json({ error: `no task ${name}` }, { status: 404 });
59
+ const body = await request.json().catch(() => ({}));
60
+ return taskRunResponse(name, async () => task.run({
61
+ name,
62
+ payload: body.payload ?? {},
63
+ context: {}
64
+ }));
65
+ };
66
+ }
67
+ export { ACCOUNT_MERGED_TASK, TASK_HEADER, createTaskHandler, defineTask, isTaskRequest, taskRunResponse };
package/dist/user.d.ts ADDED
@@ -0,0 +1,49 @@
1
+ export declare const USER_HEADER = "x-wervt-user";
2
+ export declare const USER_PROOF_HEADER = "x-wervt-user-proof";
3
+ export declare const AGENT_TOKEN_HEADER = "x-wervt-agent-token";
4
+ /**
5
+ * What the user is to this app: its `owner` or one of its `member`s (`wervt members`), a wervt
6
+ * `admin`, someone `invited` through the app (invite-only apps) or `allowed` by the app's list
7
+ * (`wervt access --add`). `public` is anyone else signed in to a public app.
8
+ */
9
+ export type WervtRole = 'owner' | 'member' | 'admin' | 'invited' | 'allowed' | 'public';
10
+ export interface WervtUser {
11
+ id: string;
12
+ email: string;
13
+ name?: string;
14
+ image?: string;
15
+ /** Linked login accounts, provider id to the user's id there, e.g. `{ twitch: '1234' }`. */
16
+ accounts?: Record<string, string>;
17
+ /** Missing only for users an app's own `/mcp` tokens stand for. */
18
+ role?: WervtRole;
19
+ }
20
+ /** Parses the `x-wervt-user` header the runtime sets. */
21
+ export declare function parseWervtUser(header: string | null | undefined): WervtUser | undefined;
22
+ /**
23
+ * The signed-in wervt user, or `undefined` when nobody is signed in. Private apps always have one;
24
+ * public apps get one when the visitor is signed in. Send people to `/_wervt/login` to sign in.
25
+ */
26
+ export declare function getUser(request: Request): WervtUser | undefined;
27
+ /**
28
+ * `user` if their role is one of `roles`. Throws 401 without a user, 403 with another role.
29
+ * Takes the user rather than the request, so adapters can pass the one they resolved (dev login,
30
+ * MCP token).
31
+ */
32
+ export declare function checkRole(user: WervtUser | undefined, roles: WervtRole[]): WervtUser;
33
+ /**
34
+ * The signed-in user if their role is one of `roles`, e.g.
35
+ * `requireRole(request, 'owner', 'member', 'admin')` for the app's own admin features.
36
+ * Throws a WervtError: 401 without a signed-in user, 403 with another role.
37
+ */
38
+ export declare function requireRole(request: Request, ...roles: WervtRole[]): WervtUser;
39
+ /** Who minted the agent token a request came with, and its id (the control plane's log). */
40
+ export interface AgentToken {
41
+ id: string;
42
+ by: string;
43
+ }
44
+ /** Parses the `x-wervt-agent-token` header the runtime sets. */
45
+ export declare function parseAgentToken(header: string | null | undefined): AgentToken | undefined;
46
+ /** The agent token a request came with: a headless browser or script acting for its minter. */
47
+ export declare function getAgentToken(request: Request): AgentToken | undefined;
48
+ /** The wervt user an access token's claims name, or undefined when they're incomplete. */
49
+ export declare function userFromClaims(claims: Record<string, unknown>): WervtUser | undefined;
package/dist/user.js ADDED
@@ -0,0 +1,73 @@
1
+ import { WervtError } from "./errors.js";
2
+ // src/user.ts
3
+ const USER_HEADER = "x-wervt-user";
4
+ const USER_PROOF_HEADER = "x-wervt-user-proof";
5
+ const AGENT_TOKEN_HEADER = "x-wervt-agent-token";
6
+ /** Parses the `x-wervt-user` header the runtime sets. */
7
+ function parseWervtUser(header) {
8
+ if (!header) return void 0;
9
+ try {
10
+ return JSON.parse(decodeURIComponent(header));
11
+ } catch {
12
+ return;
13
+ }
14
+ }
15
+ /**
16
+ * The signed-in wervt user, or `undefined` when nobody is signed in. Private apps always have one;
17
+ * public apps get one when the visitor is signed in. Send people to `/_wervt/login` to sign in.
18
+ */
19
+ function getUser(request) {
20
+ return parseWervtUser(request.headers.get(USER_HEADER));
21
+ }
22
+ /**
23
+ * `user` if their role is one of `roles`. Throws 401 without a user, 403 with another role.
24
+ * Takes the user rather than the request, so adapters can pass the one they resolved (dev login,
25
+ * MCP token).
26
+ */
27
+ function checkRole(user, roles) {
28
+ if (!user) throw new WervtError(401, "sign in at /_wervt/login first");
29
+ if (!user.role || !roles.includes(user.role)) throw new WervtError(403, `needs role ${roles.join(", ")}`);
30
+ return user;
31
+ }
32
+ /**
33
+ * The signed-in user if their role is one of `roles`, e.g.
34
+ * `requireRole(request, 'owner', 'member', 'admin')` for the app's own admin features.
35
+ * Throws a WervtError: 401 without a signed-in user, 403 with another role.
36
+ */
37
+ function requireRole(request, ...roles) {
38
+ return checkRole(getUser(request), roles);
39
+ }
40
+ /** Parses the `x-wervt-agent-token` header the runtime sets. */
41
+ function parseAgentToken(header) {
42
+ if (!header) return void 0;
43
+ try {
44
+ const value = JSON.parse(decodeURIComponent(header));
45
+ if (typeof value?.id !== "string" || typeof value.by !== "string") return void 0;
46
+ return {
47
+ id: value.id,
48
+ by: value.by
49
+ };
50
+ } catch {
51
+ return;
52
+ }
53
+ }
54
+ /** The agent token a request came with: a headless browser or script acting for its minter. */
55
+ function getAgentToken(request) {
56
+ return parseAgentToken(request.headers.get(AGENT_TOKEN_HEADER));
57
+ }
58
+ /** The wervt user an access token's claims name, or undefined when they're incomplete. */
59
+ function userFromClaims(claims) {
60
+ const { sub, email, name, picture, accounts } = claims;
61
+ if (typeof sub !== "string" || !sub || typeof email !== "string") return void 0;
62
+ return {
63
+ id: sub,
64
+ email: email.toLowerCase(),
65
+ name: typeof name === "string" ? name : void 0,
66
+ image: typeof picture === "string" ? picture : void 0,
67
+ accounts: isAccounts(accounts) ? accounts : void 0
68
+ };
69
+ }
70
+ function isAccounts(value) {
71
+ return typeof value === "object" && value !== null && !Array.isArray(value) && Object.values(value).every((id) => typeof id === "string");
72
+ }
73
+ export { AGENT_TOKEN_HEADER, USER_HEADER, USER_PROOF_HEADER, checkRole, getAgentToken, getUser, parseAgentToken, parseWervtUser, requireRole, userFromClaims };
package/package.json CHANGED
@@ -1,6 +1,61 @@
1
1
  {
2
2
  "name": "@wervt/core",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.0.2",
4
+ "description": "Server SDK for apps on wervt, on web standards: the signed-in user, live data, mail, tasks and workload identity, for any framework.",
5
+ "keywords": [
6
+ "electric",
7
+ "nitro",
8
+ "wervt"
9
+ ],
10
+ "homepage": "https://wervt.app",
11
+ "license": "MIT",
12
+ "author": "Niki2k1",
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "git+https://github.com/wervt-app/wervt.git",
16
+ "directory": "packages/core"
17
+ },
18
+ "files": [
19
+ "dist",
20
+ "README.md"
21
+ ],
22
+ "type": "module",
23
+ "exports": {
24
+ ".": {
25
+ "types": "./dist/index.d.ts",
26
+ "default": "./dist/index.js"
27
+ },
28
+ "./db": {
29
+ "types": "./dist/db.d.ts",
30
+ "default": "./dist/db.js"
31
+ },
32
+ "./anthropic": {
33
+ "types": "./dist/anthropic.d.ts",
34
+ "default": "./dist/anthropic.js"
35
+ }
36
+ },
37
+ "devDependencies": {
38
+ "@anthropic-ai/sdk": "^1.3.0",
39
+ "drizzle-orm": "1.0.0-rc.5",
40
+ "postgres": "^3.4.9"
41
+ },
42
+ "peerDependencies": {
43
+ "@anthropic-ai/sdk": ">=0.97.1",
44
+ "drizzle-orm": ">=1.0.0-rc.5 <2",
45
+ "postgres": "^3.4.9"
46
+ },
47
+ "peerDependenciesMeta": {
48
+ "@anthropic-ai/sdk": {
49
+ "optional": true
50
+ },
51
+ "drizzle-orm": {
52
+ "optional": true
53
+ },
54
+ "postgres": {
55
+ "optional": true
56
+ }
57
+ },
58
+ "scripts": {
59
+ "build": "vp pack"
60
+ }
6
61
  }