@parall/cli 1.81.0 → 1.82.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.
@@ -1,2 +1,2 @@
1
- export declare const ACTIONS_SDK_SOURCE = "/**\n * @parall/miniapp-sdk/actions \u2014 the action side of a Mini App\n * (docs/engineering-design/mini-app-action-design.md \u00A72): `defineActions`\n * turns the author's functions into the module entry the action loader\n * calls; `ActionError` is the error whose message the caller may see.\n *\n * This file runs inside the Cloudflare isolate, not in the page. It is the\n * only part of the SDK that imports `cloudflare:workers`, and an action\n * module is built from it into one file whose sole external import is that\n * one. Export the result as `ActionRunner` \u2014 the loader looks it up by name:\n *\n * export const ActionRunner = defineActions({\n * async addNote(ctx, { text }) {\n * const { rows } = await ctx.db.exec(\n * 'INSERT INTO notes (text, created_by) VALUES ($1, $2) RETURNING id',\n * [text, ctx.viewer.id],\n * );\n * return rows[0];\n * },\n * });\n *\n * Security does not depend on this wrapper: the loader accepts only the two\n * result shapes run() returns, whatever produced them (design \u00A73.1).\n *\n * An action that declares `\"clip\": true` in the manifest (write actions only)\n * may call connectors as the person who called the action\n * (docs/engineering-design/mini-app-clip-design.md):\n *\n * const profile = await ctx.clip.exec('linkedin', 'get-profile', { id }, { connection: 'sales-li' });\n *\n * `ctx.fetch` requests a public HTTP(S) address and returns a standard\n * `Response` (docs/engineering-design/mini-app-network-design.md):\n *\n * const res = await ctx.fetch('https://api.example.com/v1/items');\n * if (!res.ok) throw new ActionError(`the items API answered ${res.status}`);\n * return res.json();\n *\n * `ctx.env` holds the app's secrets by name. Online they are the org shared\n * secrets an org owner or admin gave this app (org settings \u2192 \u5171\u4EAB\u5BC6\u94A5 \u2192\n * \u7ED9\u54EA\u4E9B app); a name the app was not given is undefined:\n *\n * const key = ctx.env.EXAMPLE_API_KEY;\n * if (!key) throw new ActionError('EXAMPLE_API_KEY is missing: an org owner or admin can give it to this app');\n * const res = await ctx.fetch('https://api.example.com/v1/items', { headers: { Authorization: `Bearer ${key}` } });\n *\n * `ctx.parall.get(refs)` reads Parall files, tasks and members by reference,\n * as the caller and read-only (ActionParall below).\n */\n\nimport { WorkerEntrypoint } from 'cloudflare:workers';\n\n/** An error whose message reaches every caller as is (ACTION_FAILED with\n * error_kind action_error). Anything else thrown is an unexpected failure. */\nexport class ActionError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ActionError';\n }\n}\n\n/** A database call that was refused or failed. `code` is the platform's:\n * SQL_ERROR, SQL_REJECTED, ACTION_READ_ONLY, ACTION_LIMIT_EXCEEDED, \u2026 */\nexport class ActionDbError extends Error {\n readonly code: string;\n\n constructor(code: string, message: string) {\n super(message);\n this.name = 'ActionDbError';\n this.code = code;\n }\n}\n\n/** A connector call that was refused or failed. `code` is the platform's \u2014 the\n * same codes the caller gets running `parall connector exec` themselves\n * (CONNECTION_NOT_ALLOWED, SCRIPT_ERROR, MCP_TOOL_FAILED, \u2026) \u2014 or the\n * action's own: CLIP_NOT_DECLARED, ACTION_LIMIT_EXCEEDED, ACTION_DEADLINE.\n * OUTCOME_UNKNOWN means the command may have run: never retry it blindly. */\nexport class ClipError extends Error {\n readonly code: string;\n\n constructor(code: string, message: string) {\n super(message);\n this.name = 'ClipError';\n this.code = code;\n }\n}\n\n/** An outbound request (ctx.fetch) that was refused or failed \u2014 an HTTP\n * error status is not one: it comes back as a Response. `code` is the\n * platform's:\n *\n * - not sent: ACTION_INVALID_CALL (the URL, method, headers or body),\n * NET_ADDRESS_BLOCKED (an IP address or a loopback name such as localhost\n * written in the URL, the platform's own hosts), ACTION_LIMIT_EXCEEDED\n * (too many requests, or one too large), ACTION_DEADLINE (too little time\n * left), NET_BUSY (the platform is busy; try again shortly),\n * NET_UNAVAILABLE, USER_DISABLED, ACTION_HANDLE_REVOKED;\n * - sent, so it may have reached the server: NET_TIMEOUT, NET_FAILED,\n * NET_RESPONSE_TOO_LARGE (answers are at most 1 MiB).\n *\n * A host name that resolves to a private or loopback address is not refused\n * here: Cloudflare's edge refuses it, and ctx.fetch returns an ordinary\n * Response with status 530 (body like \"error code: 1016\"), not a NetError;\n * the outbound record shows it as answered with HTTP 530.\n *\n * The platform never retries; send an idempotency key where the other side\n * supports one. */\nexport class NetError extends Error {\n readonly code: string;\n\n constructor(code: string, message: string) {\n super(message);\n this.name = 'NetError';\n this.code = code;\n }\n}\n\n/** A ctx.parall.get refused as a whole (an item it cannot read is in the\n * result instead): ACTION_INVALID_CALL (refs not 1 to 100 strings),\n * ACTION_LIMIT_EXCEEDED, ACTION_DEADLINE, ACTION_HANDLE_REVOKED, USER_DISABLED,\n * ORG_FORBIDDEN (left the org), PARALL_READ_UNAVAILABLE (off or lost: retry). */\nexport class ParallError extends Error {\n readonly code: string;\n\n constructor(code: string, message: string) {\n super(message);\n this.name = 'ParallError';\n this.code = code;\n }\n}\n\n/** The caller, as the platform vouches for it (design \u00A72.2). */\nexport interface ActionViewer {\n id: string;\n display_name: string;\n is_agent: boolean;\n /** Organization role: owner, admin or member. */\n role: string;\n}\n\nexport interface ActionApp {\n id: string;\n version_seq: number;\n}\n\n/** A row as an object keyed by column name, in select-list order. */\nexport type ActionRow = Record<string, unknown>;\n\nexport interface ActionQueryResult {\n rows: ActionRow[];\n truncated: boolean;\n}\n\nexport interface ActionStatementResult {\n rows: ActionRow[];\n rows_affected: number;\n truncated: boolean;\n}\n\nexport interface ActionExecResult extends ActionStatementResult {\n data_seq: number;\n}\n\nexport interface ActionBatchStatement {\n sql: string;\n params?: unknown[];\n}\n\nexport interface ActionBatchResult {\n results: ActionStatementResult[];\n data_seq: number;\n}\n\n/** ctx.db: one statement per query / exec; a batch is one transaction. */\nexport interface ActionDb {\n query(sql: string, params?: unknown[]): Promise<ActionQueryResult>;\n /** Write actions only. */\n exec(sql: string, params?: unknown[]): Promise<ActionExecResult>;\n /** Write actions only; at most 50 statements, counted as one call. */\n batch(statements: ActionBatchStatement[]): Promise<ActionBatchResult>;\n}\n\nexport interface ActionClipOptions {\n /** The connection to run on: its alias or ccn_ id. The caller must be\n * allowed to use it, exactly as for their own `parall connector exec`. */\n connection: string;\n profile?: string;\n /** The command's timeout; 30 s by default, cut to what the action's\n * deadline leaves. */\n timeoutMs?: number;\n}\n\n/** ctx.clip: connector calls as the action's caller; actions that declare clip only. */\nexport interface ActionClip {\n /** Runs a command of a connector (its name or crg_ id) and returns the connector's\n * data; throws ClipError. */\n exec(clip: string, command: string, args: unknown, options: ActionClipOptions): Promise<unknown>;\n}\n\n/** A file (a chat attachment): no link, no uploader; width and height for images. */\nexport interface ParallFile {\n id: string;\n file_name: string;\n mime_type: string;\n file_size: number;\n width?: number;\n height?: number;\n}\n\n/** A task: due_date is YYYY-MM-DD or null; archived_at once it is archived. */\nexport interface ParallTask {\n id: string;\n identifier?: string;\n title: string;\n status: string;\n priority: string;\n assignee_id?: string;\n project_id?: string;\n due_date: string | null;\n created_at: string;\n updated_at: string;\n archived_at?: string;\n}\n\n/** An active member of the app's organization, person or agent; no email. */\nexport interface ParallMember {\n user_id: string;\n display_name: string;\n avatar_url?: string;\n type: 'human' | 'agent';\n role: string;\n title: string;\n joined_at: string;\n}\n\n/** One reference's answer; a refusal carries only its code: RESTRICTED (the\n * caller may not read it), NOT_FOUND (not in the app's organization: deleted,\n * another organization's, a member who left), INVALID_REF (not an att_, tsk_\n * or usr_ reference) or TOO_LARGE (past the get's 1 MiB). Others: unreadable. */\nexport type ParallItem =\n | { ok: true; type: 'file'; item: ParallFile }\n | { ok: true; type: 'task'; item: ParallTask }\n | { ok: true; type: 'member'; item: ParallMember }\n | { ok: false; code: string };\n\nexport interface ActionParall {\n /** Reads up to 100 references (prll://att_\u2026, tsk_\u2026, usr_\u2026 or bare IDs), one\n * item each in order, as the caller's own read now; read-only. The result\n * is the caller's view: store references, never the result across\n * invocations or in page storage. 20 gets per invocation, 10 s each. */\n get(refs: readonly string[]): Promise<ParallItem[]>;\n}\n\n/** ctx.fetch's options: the standard ones \u2014 method, headers, body, signal,\n * redirect \u2014 and the request's timeout. Others (cache, credentials, mode,\n * the Workers `cf`) are not looked at: every request is uncached and carries\n * only what the code sets. */\nexport interface ActionFetchInit extends RequestInit {\n /** This request's timeout; 30 s by default, cut to what the action's\n * deadline leaves. With redirects, each hop has it. */\n timeoutMs?: number;\n}\n\n/** ctx.fetch: a public HTTP(S) request from the platform, recorded in the\n * app's call record (host, method, status, size and time \u2014 never the query\n * string, headers or bodies). A local run (`parall app action run --local`,\n * `parall app dev`) sends it straight from your machine and records nothing.\n * Redirects are followed up to 5 times: within the same origin as Fetch\n * does; to another origin with only Accept, Accept-Language,\n * Content-Language and User-Agent kept, and not at all when the next request\n * would carry the body (307, 308, and 301 / 302 for a method other than GET,\n * HEAD or POST) or when it would go from https: to http: \u2014 then the redirect\n * itself comes back. Each hop is a request of its own and counts toward the\n * invocation's request limit (20 by default). At most 4 requests (by\n * default) run at once; more wait their turn. Request and answer bodies are\n * at most 1 MiB each. */\nexport type ActionFetch = (\n input: string | URL | Request,\n init?: ActionFetchInit,\n) => Promise<Response>;\n\nexport interface ActionContext {\n viewer: ActionViewer;\n app: ActionApp;\n db: ActionDb;\n clip: ActionClip;\n fetch: ActionFetch;\n parall: ActionParall;\n /** The app's secrets by name; read-only. Online they are the org shared\n * secrets an org owner or admin gave this app; a local run (`parall app\n * action run --local`) reads the project's .dev.vars instead. Never pass\n * them as params or write them to the Database or a result. */\n env: Readonly<Record<string, string>>;\n}\n\n// biome-ignore lint/suspicious/noExplicitAny: the platform validates params against the declared schema before the call\nexport type ActionFunction = (ctx: ActionContext, params: any) => unknown;\n\n/** What the loader passes run() (ts/actions-worker src/run.ts). A loader\n * before the network sends neither env nor net_in_flight. */\nexport interface ActionRunRequest {\n action: string;\n params: unknown;\n viewer: ActionViewer;\n app: ActionApp;\n env?: Record<string, string>;\n /** How many requests the handle takes at once. */\n net_in_flight?: number;\n}\n\n/** The only two shapes the loader accepts back (ts/actions-worker src/outcome.ts). */\nexport type ActionRunResult =\n | { ok: true; json: string }\n | { ok: false; error: { kind: 'action_error' | 'unexpected'; message: string; stack?: string } };\n\n/** What a handle method resolves to. Failures travel as values because\n * Workers RPC keeps only an exception's name and message (design \u00A76). */\nexport type ActionHandleResult =\n | { ok: true; value: unknown }\n | { ok: false; error: { code: string; message: string } };\n\n/** What the handle's clip method takes. */\nexport interface ActionHandleClipRequest {\n clip: string;\n command: string;\n args?: unknown;\n connection: string;\n profile?: string;\n timeout_ms?: number;\n}\n\n/** What the handle's request method takes: one request, rebuilt by the\n * loader from exactly these fields. */\nexport interface ActionHandleNetRequest {\n url: string;\n method: string;\n headers: [string, string][];\n body: ArrayBuffer | null;\n timeout_ms?: number;\n}\n\n/** What it answers with on success: the answer, never followed. */\nexport interface ActionHandleNetAnswer {\n status: number;\n status_text: string;\n headers: [string, string][];\n body: ArrayBuffer | null;\n}\n\n/** The per-invocation handle the loader passes run(). Loaders older than\n * Clip calls, the network or Parall reads lack clip, request or parall. */\nexport interface ActionHandle {\n query(sql: string, params: unknown[]): Promise<ActionHandleResult>;\n exec(sql: string, params: unknown[]): Promise<ActionHandleResult>;\n batch(statements: ActionBatchStatement[]): Promise<ActionHandleResult>;\n clip?(req: ActionHandleClipRequest): Promise<ActionHandleResult>;\n request?(req: ActionHandleNetRequest): Promise<ActionHandleResult>;\n parall?(req: { refs: string[] }): Promise<ActionHandleResult>;\n}\n\n/** What defineActions returns; export it as `ActionRunner`. */\nexport interface ActionRunnerClass {\n /** The actions the module implements, sorted; `parall app check` compares\n * them with the manifest. */\n readonly actions: readonly string[];\n new (\n ctx: unknown,\n env: unknown,\n ): { run(req: ActionRunRequest, handle: ActionHandle): Promise<ActionRunResult> };\n}\n\nfunction unwrap(result: ActionHandleResult): unknown {\n if (result?.ok === true) return result.value;\n if (result?.ok === false) throw new ActionDbError(result.error.code, result.error.message);\n throw new ActionDbError(\n 'ACTION_DB_UNAVAILABLE',\n 'the database handle answered in an unknown shape',\n );\n}\n\nfunction unwrapClip(result: ActionHandleResult): unknown {\n if (result?.ok === true) return result.value;\n if (result?.ok === false) throw new ClipError(result.error.code, result.error.message);\n throw new ClipError(\n 'OUTCOME_UNKNOWN',\n 'the connector call answered in an unknown shape; it may or may not have run',\n );\n}\n\nfunction unwrapParall(result: ActionHandleResult): ParallItem[] {\n if (result?.ok === false) throw new ParallError(result.error.code, result.error.message);\n if (result?.ok === true && Array.isArray(result.value)) return result.value as ParallItem[];\n throw new ParallError('PARALL_READ_UNAVAILABLE', 'the read answered in an unknown shape');\n}\n\n/** One get; the handle checks refs. Over RPC the handle is a stub that takes\n * any name for a method, so a loader without parall refuses the call itself. */\nasync function readParall(handle: ActionHandle, refs: unknown): Promise<ActionHandleResult> {\n try {\n return await (handle as Required<ActionHandle>).parall({ refs: refs as string[] });\n } catch {\n const message = 'this runtime cannot read Parall data yet';\n return { ok: false, error: { code: 'PARALL_READ_UNAVAILABLE', message } };\n }\n}\n\nfunction unwrapNet(result: ActionHandleResult): ActionHandleNetAnswer {\n if (result?.ok === false) throw new NetError(result.error.code, result.error.message);\n const a = (result?.ok === true ? result.value : null) as ActionHandleNetAnswer | null;\n if (\n !a ||\n typeof a.status !== 'number' ||\n !Array.isArray(a.headers) ||\n (a.body !== null && !(a.body instanceof ArrayBuffer))\n ) {\n throw new NetError(\n 'NET_FAILED',\n 'the request answered in an unknown shape; it may have reached the server',\n );\n }\n return a;\n}\n\n// Statuses whose Response has no body (Fetch's null body status).\nconst NULL_BODY_STATUS = new Set([101, 103, 204, 205, 304]);\nconst REDIRECT_STATUS = new Set([301, 302, 303, 307, 308]);\n// What a redirect to another origin keeps of the author's headers\n// (mini-app-network-design.md \u00A74): a key may be in any other one.\nconst CROSS_ORIGIN_HEADERS = new Set([\n 'accept',\n 'accept-language',\n 'content-language',\n 'user-agent',\n]);\n// Dropped with the body when a redirect turns the request into a GET.\nconst BODY_HEADERS = new Set([\n 'content-encoding',\n 'content-language',\n 'content-location',\n 'content-type',\n]);\nconst MAX_REDIRECTS = 5;\nconst DEFAULT_IN_FLIGHT = 4;\n\n/** One request of a ctx.fetch: the first, or a redirect's next hop. */\ninterface Hop {\n url: string;\n method: string;\n headers: [string, string][];\n body: ArrayBuffer | null;\n}\n\nfunction headerPairs(headers: Headers): [string, string][] {\n const out: [string, string][] = [];\n headers.forEach((value, name) => {\n out.push([name, value]);\n });\n return out;\n}\n\n/** The first hop, as a standard Request reads the input and init \u2014 only\n * the method, headers and body are taken from them. */\nasync function firstHop(input: string | URL | Request, init: ActionFetchInit | undefined) {\n let request: Request;\n try {\n request = new Request(input, {\n method: init?.method,\n headers: init?.headers,\n body: init?.body,\n });\n } catch (err) {\n throw new NetError(\n 'ACTION_INVALID_CALL',\n `ctx.fetch: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n const hop: Hop = {\n url: request.url,\n method: request.method,\n headers: headerPairs(request.headers),\n body: request.body ? await request.arrayBuffer() : null,\n };\n const fromInput = typeof input === 'object' && 'redirect' in input ? input.redirect : undefined;\n return {\n hop,\n redirect: (init?.redirect ?? fromInput ?? 'follow') as RequestRedirect,\n signal: init?.signal ?? (input instanceof Request ? input.signal : null),\n };\n}\n\n/** The next hop for a redirect, or null when it is not to be followed\n * (mini-app-network-design.md \u00A74). The handle checks the address of every\n * hop as it does the first: an IP address or loopback name in the Location,\n * or the platform, is refused there; a name that resolves to a private\n * address is left to Cloudflare's edge (status 530). */\nfunction nextHop(hop: Hop, status: number, location: string | undefined): Hop | null {\n if (!REDIRECT_STATUS.has(status) || location === undefined) return null;\n let from: URL;\n let to: URL;\n try {\n from = new URL(hop.url);\n to = new URL(location, hop.url);\n } catch {\n return null;\n }\n if (from.protocol === 'https:' && to.protocol === 'http:') return null;\n const sameOrigin = to.origin === from.origin && to.origin !== 'null';\n const toGet =\n (status === 303 && hop.method !== 'GET' && hop.method !== 'HEAD') ||\n ((status === 301 || status === 302) && hop.method === 'POST');\n if (!sameOrigin) {\n // The next request would carry the body to another origin.\n if (status === 307 || status === 308) return null;\n if ((status === 301 || status === 302) && !['GET', 'HEAD', 'POST'].includes(hop.method)) {\n return null;\n }\n }\n let { method, headers, body } = hop;\n if (toGet) {\n method = 'GET';\n body = null;\n headers = headers.filter(([name]) => !BODY_HEADERS.has(name.toLowerCase()));\n }\n if (!sameOrigin)\n headers = headers.filter(([name]) => CROSS_ORIGIN_HEADERS.has(name.toLowerCase()));\n return { url: to.href, method, headers, body };\n}\n\nfunction toResponse(answer: ActionHandleNetAnswer, hop: Hop, redirected: boolean): Response {\n if (answer.status < 200 || answer.status > 599) {\n throw new NetError('NET_FAILED', `the server answered with status ${answer.status}`);\n }\n // As Fetch does: no body for a HEAD request or a null body status.\n const body = hop.method === 'HEAD' || NULL_BODY_STATUS.has(answer.status) ? null : answer.body;\n let res: Response;\n try {\n res = new Response(body, {\n status: answer.status,\n statusText: answer.status_text,\n headers: answer.headers,\n });\n } catch {\n try {\n res = new Response(body, { status: answer.status, headers: answer.headers });\n } catch {\n throw new NetError('NET_FAILED', 'the answer could not be read');\n }\n }\n // As a fetch Response: the URL that answered, and whether it was reached\n // through a redirect.\n Object.defineProperty(res, 'url', { value: hop.url });\n if (redirected) Object.defineProperty(res, 'redirected', { value: true });\n return res;\n}\n\n/** p, or the signal's reason as soon as it aborts. A request already at\n * the handle runs on, and the loader waits for it before answering; one\n * still waiting for its turn is never sent. */\nfunction abortable<T>(p: Promise<T>, signal: AbortSignal | null | undefined): Promise<T> {\n if (!signal) return p;\n if (signal.aborted) return Promise.reject(signal.reason);\n return new Promise<T>((resolve, reject) => {\n const onAbort = () => reject(signal.reason);\n signal.addEventListener('abort', onAbort, { once: true });\n p.then(\n (v) => {\n signal.removeEventListener('abort', onAbort);\n resolve(v);\n },\n (e) => {\n signal.removeEventListener('abort', onAbort);\n reject(e);\n },\n );\n });\n}\n\n/** ctx.env: the secrets as a frozen object of strings. */\nfunction envOf(raw: unknown): Readonly<Record<string, string>> {\n const entries =\n raw && typeof raw === 'object' && !Array.isArray(raw)\n ? Object.entries(raw).filter((e): e is [string, string] => typeof e[1] === 'string')\n : [];\n return Object.freeze(Object.fromEntries(entries));\n}\n\nfunction failure(err: unknown): ActionRunResult {\n if (err instanceof ActionError || (err instanceof Error && err.name === 'ActionError')) {\n return { ok: false, error: { kind: 'action_error', message: err.message } };\n }\n const e = err instanceof Error ? err : new Error(String(err));\n const coded = [ActionDbError, ClipError, NetError, ParallError].some((c) => e instanceof c);\n const label = coded ? `${e.name} ${(e as ParallError).code}` : e.name;\n return {\n ok: false,\n error: { kind: 'unexpected', message: `${label}: ${e.message}`, stack: e.stack ?? '' },\n };\n}\n\n/** A database call as the author's code holds it. It notes whether the code\n * attached a rejection handler anywhere along its chain \u2014 `await`,\n * `try`/`catch`, `.catch()`, `.then(f).catch(g)`, `Promise.all` all do \u2014 so\n * a failure nobody looked at fails the action instead of being lost.\n * Promises derived from a call point back to it. */\nclass DbCall<T> extends Promise<T> {\n handled = false;\n origin?: DbCall<unknown>;\n #inFinally = false;\n\n override then<R1 = T, R2 = never>(\n onFulfilled?: ((value: T) => R1 | PromiseLike<R1>) | null,\n onRejected?: ((reason: unknown) => R2 | PromiseLike<R2>) | null,\n ): Promise<R1 | R2> {\n const origin = this.origin ?? this;\n if (typeof onRejected === 'function' && !this.#inFinally) origin.handled = true;\n const derived = super.then(onFulfilled, onRejected) as DbCall<R1 | R2>;\n derived.origin = origin;\n return derived;\n }\n\n // finally() calls then() with a rejection handler that throws the failure\n // on: it handles nothing. A catch on what it returns still counts.\n override finally(onFinally?: (() => void) | null): Promise<T> {\n this.#inFinally = true;\n try {\n return super.finally(onFinally);\n } finally {\n this.#inFinally = false;\n }\n }\n}\n\n// The wrapper's own bookkeeping on a DbCall, which must not count as the\n// author handling it.\nconst observe = Promise.prototype.then as <T>(\n this: Promise<T>,\n onFulfilled: (value: T) => unknown,\n onRejected?: (reason: unknown) => unknown,\n) => Promise<unknown>;\n\n/** Wraps the author's functions into the module entry the loader calls. */\nexport function defineActions(actions: Record<string, ActionFunction>): ActionRunnerClass {\n const names = Object.keys(actions).sort();\n // Not named ActionRunner: the author's export usually is, and a bundler\n // would rename this class to tell the two apart.\n class ActionEntrypoint extends WorkerEntrypoint {\n static readonly actions: readonly string[] = names;\n\n async run(req: ActionRunRequest, handle: ActionHandle): Promise<ActionRunResult> {\n // Database calls still in flight are waited for before answering \u2014 a\n // write the author forgot to await commits before the caller has the\n // result. Calls started from a finishing call are waited for too; the\n // loader refuses any that arrive after run() returns.\n const pending = new Set<Promise<unknown>>();\n const failed = new Map<DbCall<unknown>, unknown>();\n const track = <T>(\n call: Promise<ActionHandleResult>,\n open: (result: ActionHandleResult) => unknown = unwrap,\n ): Promise<T> => {\n const dbCall = new DbCall<T>((resolve, reject) => {\n call.then(open).then(resolve as (value: unknown) => void, reject);\n });\n const settled = observe.call(\n dbCall,\n () => undefined,\n (err) => {\n failed.set(dbCall, err);\n },\n );\n pending.add(settled);\n observe.call(settled, () => pending.delete(settled));\n return dbCall;\n };\n const drain = async () => {\n while (pending.size > 0) await Promise.allSettled([...pending]);\n };\n const db: ActionDb = {\n query: (sql, params = []) => track(handle.query(sql, params)),\n exec: (sql, params = []) => track(handle.exec(sql, params)),\n batch: (statements) => track(handle.batch(statements)),\n };\n // Clip calls are tracked like database calls: waited for before the\n // answer, and a failure nobody looked at fails the action.\n const clip: ActionClip = {\n exec: (clipName, command, args, options) => {\n const request: ActionHandleClipRequest = {\n clip: clipName,\n command,\n args,\n connection: options?.connection,\n profile: options?.profile,\n timeout_ms: options?.timeoutMs,\n };\n const sent =\n typeof handle.clip === 'function'\n ? handle.clip(request)\n : Promise.resolve<ActionHandleResult>({\n ok: false,\n error: {\n code: 'CLIP_UNAVAILABLE',\n message: 'this runtime cannot call connectors yet',\n },\n });\n return track(sent, unwrapClip);\n },\n };\n // Outbound requests: one handle call per hop, at most net_in_flight at\n // once (more wait their turn), tracked like database calls.\n const limit = Math.max(1, req.net_in_flight || DEFAULT_IN_FLIGHT);\n let active = 0;\n const waiting: (() => void)[] = [];\n const send = async (hop: Hop, timeoutMs: number | undefined, signal: AbortSignal | null) => {\n while (active >= limit) await new Promise<void>((resume) => waiting.push(resume));\n active++;\n try {\n // Aborted while it waited for its turn (the code has already had\n // the abort): it is never sent, and the turn passes on.\n if (signal?.aborted) throw signal.reason;\n if (typeof handle.request !== 'function') {\n throw new NetError('NET_UNAVAILABLE', 'this runtime cannot make requests yet');\n }\n return unwrapNet(\n await handle.request({\n ...hop,\n ...(timeoutMs === undefined ? {} : { timeout_ms: timeoutMs }),\n }),\n );\n } finally {\n active--;\n waiting.shift()?.();\n }\n };\n const request = async (input: string | URL | Request, init?: ActionFetchInit) => {\n const first = await firstHop(input, init);\n const { redirect, signal } = first;\n let hop = first.hop;\n for (let followed = 0; ; followed++) {\n // Aborted before this hop: it is never asked for.\n if (signal?.aborted) throw signal.reason;\n const answer = await abortable(send(hop, init?.timeoutMs, signal), signal);\n if (redirect !== 'manual' && REDIRECT_STATUS.has(answer.status)) {\n if (redirect === 'error') {\n throw new NetError(\n 'NET_FAILED',\n `the server redirected (${answer.status}) and redirect is \"error\"`,\n );\n }\n const location = answer.headers.find(\n ([name]) => name.toLowerCase() === 'location',\n )?.[1];\n const next = nextHop(hop, answer.status, location);\n if (next) {\n if (followed >= MAX_REDIRECTS) {\n throw new NetError(\n 'ACTION_LIMIT_EXCEEDED',\n `ctx.fetch follows at most ${MAX_REDIRECTS} redirects`,\n );\n }\n hop = next;\n continue;\n }\n }\n return toResponse(answer, hop, followed > 0);\n }\n };\n const ctxFetch: ActionFetch = (input, init) =>\n track<Response>(\n request(input, init).then((res) => ({ ok: true, value: res }) as ActionHandleResult),\n (result) => (result as { value: unknown }).value,\n );\n const parall: ActionParall = {\n get: (refs) => track<ParallItem[]>(readParall(handle, refs), unwrapParall),\n };\n const env = envOf(req.env);\n try {\n const fn = Object.hasOwn(actions, req.action) ? actions[req.action] : undefined;\n if (typeof fn !== 'function') {\n throw new Error(\n `this module does not implement the action ${JSON.stringify(req.action)}`,\n );\n }\n const value = await fn(\n { viewer: req.viewer, app: req.app, db, clip, fetch: ctxFetch, parall, env },\n req.params,\n );\n await drain();\n // A call that failed while the code never looked at it (a forgotten\n // await) fails the action: answering ok would claim a write that did\n // not happen.\n for (const [dbCall, err] of failed) if (!dbCall.handled) throw err;\n const json = JSON.stringify(value === undefined ? null : value);\n if (typeof json !== 'string') {\n throw new TypeError('the action returned a value JSON cannot represent');\n }\n return { ok: true, json };\n } catch (err) {\n await drain();\n return failure(err);\n }\n }\n }\n return ActionEntrypoint;\n}\n";
1
+ export declare const ACTIONS_SDK_SOURCE = "/**\n * @parall/miniapp-sdk/actions \u2014 the action side of a Mini App\n * (docs/engineering-design/mini-app-action-design.md \u00A72): `defineActions`\n * turns the author's functions into the module entry the action loader\n * calls; `ActionError` is the error whose message the caller may see.\n *\n * This file runs inside the Cloudflare isolate, not in the page. It is the\n * only part of the SDK that imports `cloudflare:workers`, and an action\n * module is built from it into one file whose sole external import is that\n * one. Export the result as `ActionRunner` \u2014 the loader looks it up by name:\n *\n * export const ActionRunner = defineActions({\n * async addNote(ctx, { text }) {\n * const { rows } = await ctx.db.exec(\n * 'INSERT INTO notes (text, created_by) VALUES ($1, $2) RETURNING id',\n * [text, ctx.viewer.id],\n * );\n * return rows[0];\n * },\n * });\n *\n * Security does not depend on this wrapper: the loader accepts only the two\n * result shapes run() returns, whatever produced them (design \u00A73.1).\n *\n * An action that declares `\"clip\": true` in the manifest (write actions only)\n * may call connectors as the person who called the action\n * (docs/engineering-design/mini-app-clip-design.md):\n *\n * const profile = await ctx.clip.exec('linkedin', 'get-profile', { id }, { connection: 'sales-li' });\n *\n * `ctx.fetch` requests a public HTTP(S) address and returns a standard\n * `Response` (docs/engineering-design/mini-app-network-design.md):\n *\n * const res = await ctx.fetch('https://api.example.com/v1/items');\n * if (!res.ok) throw new ActionError(`the items API answered ${res.status}`);\n * return res.json();\n *\n * `ctx.env` holds the app's secrets by name. Online they are the org shared\n * secrets an org owner or admin gave this app (org settings \u2192 \u5171\u4EAB\u5BC6\u94A5 \u2192\n * \u7ED9\u54EA\u4E9B app); a name the app was not given is undefined:\n *\n * const key = ctx.env.EXAMPLE_API_KEY;\n * if (!key) throw new ActionError('EXAMPLE_API_KEY is missing: an org owner or admin can give it to this app');\n * const res = await ctx.fetch('https://api.example.com/v1/items', { headers: { Authorization: `Bearer ${key}` } });\n *\n * `ctx.parall.get(refs)` reads Parall files, tasks and members by reference\n * and `ctx.parall.members()` lists the members, as the caller and read-only\n * (ActionParall below).\n */\n\nimport { WorkerEntrypoint } from 'cloudflare:workers';\n\n/** An error whose message reaches every caller as is (ACTION_FAILED with\n * error_kind action_error). Anything else thrown is an unexpected failure. */\nexport class ActionError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ActionError';\n }\n}\n\n/** An error that carries the platform's `code`: what ActionDbError,\n * ClipError, NetError and ParallError have in common. */\nexport class CodedError extends Error {\n readonly code: string;\n\n constructor(code: string, message: string) {\n super(message);\n this.code = code;\n }\n}\n\n/** A database call that was refused or failed. `code` is the platform's:\n * SQL_ERROR, SQL_REJECTED, ACTION_READ_ONLY, ACTION_LIMIT_EXCEEDED, \u2026 */\nexport class ActionDbError extends CodedError {\n override name = 'ActionDbError';\n}\n\n/** A connector call that was refused or failed. `code` is the platform's \u2014 the\n * same codes the caller gets running `parall connector exec` themselves\n * (CONNECTION_NOT_ALLOWED, SCRIPT_ERROR, MCP_TOOL_FAILED, \u2026) \u2014 or the\n * action's own: CLIP_NOT_DECLARED, ACTION_LIMIT_EXCEEDED, ACTION_DEADLINE.\n * OUTCOME_UNKNOWN means the command may have run: never retry it blindly. */\nexport class ClipError extends CodedError {\n override name = 'ClipError';\n}\n\n/** An outbound request (ctx.fetch) that was refused or failed \u2014 an HTTP\n * error status is not one: it comes back as a Response. `code` is the\n * platform's:\n *\n * - not sent: ACTION_INVALID_CALL (the URL, method, headers or body),\n * NET_ADDRESS_BLOCKED (an IP address or a loopback name such as localhost\n * written in the URL, the platform's own hosts), ACTION_LIMIT_EXCEEDED\n * (too many requests, or one too large), ACTION_DEADLINE (too little time\n * left), NET_BUSY (the platform is busy; try again shortly),\n * NET_UNAVAILABLE, USER_DISABLED, ACTION_HANDLE_REVOKED;\n * - sent, so it may have reached the server: NET_TIMEOUT, NET_FAILED,\n * NET_RESPONSE_TOO_LARGE (answers are at most 1 MiB).\n *\n * A host name that resolves to a private or loopback address is not refused\n * here: Cloudflare's edge refuses it, and ctx.fetch returns an ordinary\n * Response with status 530 (body like \"error code: 1016\"), not a NetError;\n * the outbound record shows it as answered with HTTP 530.\n *\n * The platform never retries; send an idempotency key where the other side\n * supports one. */\nexport class NetError extends CodedError {\n override name = 'NetError';\n}\n\n/** A ctx.parall.get or members() refused as a whole (an item a get cannot read\n * is in its result instead): ACTION_INVALID_CALL (refs not 1 to 100 strings),\n * ACTION_LIMIT_EXCEEDED, ACTION_DEADLINE, ACTION_HANDLE_REVOKED, USER_DISABLED,\n * ORG_FORBIDDEN (left the org), TOO_LARGE (the members past 1 MiB: read them\n * by reference), PARALL_READ_UNAVAILABLE (off or lost: retry). */\nexport class ParallError extends CodedError {\n override name = 'ParallError';\n}\n\n/** The caller, as the platform vouches for it (design \u00A72.2). */\nexport interface ActionViewer {\n id: string;\n display_name: string;\n is_agent: boolean;\n /** Organization role: owner, admin or member. */\n role: string;\n}\n\nexport interface ActionApp {\n id: string;\n version_seq: number;\n}\n\n/** A row as an object keyed by column name, in select-list order. */\nexport type ActionRow = Record<string, unknown>;\n\nexport interface ActionQueryResult {\n rows: ActionRow[];\n truncated: boolean;\n}\n\nexport interface ActionStatementResult {\n rows: ActionRow[];\n rows_affected: number;\n truncated: boolean;\n}\n\nexport interface ActionExecResult extends ActionStatementResult {\n data_seq: number;\n}\n\nexport interface ActionBatchStatement {\n sql: string;\n params?: unknown[];\n}\n\nexport interface ActionBatchResult {\n results: ActionStatementResult[];\n data_seq: number;\n}\n\n/** ctx.db: one statement per query / exec; a batch is one transaction. */\nexport interface ActionDb {\n query(sql: string, params?: unknown[]): Promise<ActionQueryResult>;\n /** Write actions only. */\n exec(sql: string, params?: unknown[]): Promise<ActionExecResult>;\n /** Write actions only; at most 50 statements, counted as one call. */\n batch(statements: ActionBatchStatement[]): Promise<ActionBatchResult>;\n}\n\nexport interface ActionClipOptions {\n /** The connection to run on: its alias or ccn_ id. The caller must be\n * allowed to use it, exactly as for their own `parall connector exec`. */\n connection: string;\n profile?: string;\n /** The command's timeout; 30 s by default, cut to what the action's\n * deadline leaves. */\n timeoutMs?: number;\n}\n\n/** ctx.clip: connector calls as the action's caller; actions that declare clip only. */\nexport interface ActionClip {\n /** Runs a command of a connector (its name or crg_ id) and returns the connector's\n * data; throws ClipError. */\n exec(clip: string, command: string, args: unknown, options: ActionClipOptions): Promise<unknown>;\n}\n\n/** A file (a chat attachment): no link, no uploader; width and height for images. */\nexport interface ParallFile {\n id: string;\n file_name: string;\n mime_type: string;\n file_size: number;\n width?: number;\n height?: number;\n}\n\n/** A task: due_date is YYYY-MM-DD or null; archived_at once it is archived. */\nexport interface ParallTask {\n id: string;\n identifier?: string;\n title: string;\n status: string;\n priority: string;\n assignee_id?: string;\n project_id?: string;\n due_date: string | null;\n created_at: string;\n updated_at: string;\n archived_at?: string;\n}\n\n/** An active member of the app's organization, person or agent; no email. */\nexport interface ParallMember {\n user_id: string;\n display_name: string;\n avatar_url?: string;\n type: 'human' | 'agent';\n role: string;\n title: string;\n joined_at: string;\n}\n\n/** One reference's answer; a refusal carries only its code: RESTRICTED (the\n * caller may not read it), NOT_FOUND (not in the app's organization: deleted,\n * another organization's, a member who left), INVALID_REF (not an att_, tsk_\n * or usr_ reference) or TOO_LARGE (past the get's 1 MiB). Others: unreadable. */\nexport type ParallItem =\n | { ok: true; type: 'file'; item: ParallFile }\n | { ok: true; type: 'task'; item: ParallTask }\n | { ok: true; type: 'member'; item: ParallMember }\n | { ok: false; code: string };\n\nexport interface ActionParall {\n /** Reads up to 100 references (prll://att_\u2026, tsk_\u2026, usr_\u2026 or bare IDs), one\n * item each in order, as the caller's own read now; read-only. The result\n * is the caller's view: store references, never the result across\n * invocations or in page storage. 20 gets per invocation, 10 s each. */\n get(refs: readonly string[]): Promise<ParallItem[]>;\n /** Every active member of the organization, people and agents, with a\n * get's member fields, in the order they joined; counts as one get. */\n members(): Promise<ParallMember[]>;\n}\n\n/** ctx.fetch's options: the standard ones \u2014 method, headers, body, signal,\n * redirect \u2014 and the request's timeout. Others (cache, credentials, mode,\n * the Workers `cf`) are not looked at: every request is uncached and carries\n * only what the code sets. */\nexport interface ActionFetchInit extends RequestInit {\n /** This request's timeout; 30 s by default, cut to what the action's\n * deadline leaves. With redirects, each hop has it. */\n timeoutMs?: number;\n}\n\n/** ctx.fetch: a public HTTP(S) request from the platform, recorded in the\n * app's call record (host, method, status, size and time \u2014 never the query\n * string, headers or bodies). A local run (`parall app action run --local`,\n * `parall app dev`) sends it straight from your machine and records nothing.\n * Redirects are followed up to 5 times: within the same origin as Fetch\n * does; to another origin with only Accept, Accept-Language,\n * Content-Language and User-Agent kept, and not at all when the next request\n * would carry the body (307, 308, and 301 / 302 for a method other than GET,\n * HEAD or POST) or when it would go from https: to http: \u2014 then the redirect\n * itself comes back. Each hop is a request of its own and counts toward the\n * invocation's request limit (20 by default). At most 4 requests (by\n * default) run at once; more wait their turn. Request and answer bodies are\n * at most 1 MiB each. */\nexport type ActionFetch = (\n input: string | URL | Request,\n init?: ActionFetchInit,\n) => Promise<Response>;\n\nexport interface ActionContext {\n viewer: ActionViewer;\n app: ActionApp;\n db: ActionDb;\n clip: ActionClip;\n fetch: ActionFetch;\n parall: ActionParall;\n /** The app's secrets by name; read-only. Online they are the org shared\n * secrets an org owner or admin gave this app; a local run (`parall app\n * action run --local`) reads the project's .dev.vars instead. Never pass\n * them as params or write them to the Database or a result. */\n env: Readonly<Record<string, string>>;\n}\n\n// biome-ignore lint/suspicious/noExplicitAny: the platform validates params against the declared schema before the call\nexport type ActionFunction = (ctx: ActionContext, params: any) => unknown;\n\n/** What the loader passes run() (ts/actions-worker src/run.ts). A loader\n * before the network sends neither env nor net_in_flight. */\nexport interface ActionRunRequest {\n action: string;\n params: unknown;\n viewer: ActionViewer;\n app: ActionApp;\n env?: Record<string, string>;\n /** How many requests the handle takes at once. */\n net_in_flight?: number;\n}\n\n/** The only two shapes the loader accepts back (ts/actions-worker src/outcome.ts). */\nexport type ActionRunResult =\n | { ok: true; json: string }\n | { ok: false; error: { kind: 'action_error' | 'unexpected'; message: string; stack?: string } };\n\n/** What a handle method resolves to. Failures travel as values because\n * Workers RPC keeps only an exception's name and message (design \u00A76). */\nexport type ActionHandleResult =\n | { ok: true; value: unknown }\n | { ok: false; error: { code: string; message: string } };\n\n/** What the handle's clip method takes. */\nexport interface ActionHandleClipRequest {\n clip: string;\n command: string;\n args?: unknown;\n connection: string;\n profile?: string;\n timeout_ms?: number;\n}\n\n/** What the handle's request method takes: one request, rebuilt by the\n * loader from exactly these fields. */\nexport interface ActionHandleNetRequest {\n url: string;\n method: string;\n headers: [string, string][];\n body: ArrayBuffer | null;\n timeout_ms?: number;\n}\n\n/** What it answers with on success: the answer, never followed. */\nexport interface ActionHandleNetAnswer {\n status: number;\n status_text: string;\n headers: [string, string][];\n body: ArrayBuffer | null;\n}\n\n/** The per-invocation handle the loader passes run(). Loaders older than Clip\n * calls, the network, Parall reads or the member list lack clip, request,\n * parall or parallMembers. */\nexport interface ActionHandle {\n query(sql: string, params: unknown[]): Promise<ActionHandleResult>;\n exec(sql: string, params: unknown[]): Promise<ActionHandleResult>;\n batch(statements: ActionBatchStatement[]): Promise<ActionHandleResult>;\n clip?(req: ActionHandleClipRequest): Promise<ActionHandleResult>;\n request?(req: ActionHandleNetRequest): Promise<ActionHandleResult>;\n parall?(req: { refs: string[] }): Promise<ActionHandleResult>;\n parallMembers?(): Promise<ActionHandleResult>;\n}\n\n/** What defineActions returns; export it as `ActionRunner`. */\nexport interface ActionRunnerClass {\n /** The actions the module implements, sorted; `parall app check` compares\n * them with the manifest. */\n readonly actions: readonly string[];\n new (\n ctx: unknown,\n env: unknown,\n ): { run(req: ActionRunRequest, handle: ActionHandle): Promise<ActionRunResult> };\n}\n\nfunction unwrap(result: ActionHandleResult): unknown {\n if (result?.ok === true) return result.value;\n if (result?.ok === false) throw new ActionDbError(result.error.code, result.error.message);\n throw new ActionDbError(\n 'ACTION_DB_UNAVAILABLE',\n 'the database handle answered in an unknown shape',\n );\n}\n\nfunction unwrapClip(result: ActionHandleResult): unknown {\n if (result?.ok === true) return result.value;\n if (result?.ok === false) throw new ClipError(result.error.code, result.error.message);\n throw new ClipError(\n 'OUTCOME_UNKNOWN',\n 'the connector call answered in an unknown shape; it may or may not have run',\n );\n}\n\nfunction unwrapParall(result: ActionHandleResult): unknown[] {\n if (result?.ok === false) throw new ParallError(result.error.code, result.error.message);\n if (result?.ok === true && Array.isArray(result.value)) return result.value;\n throw new ParallError('PARALL_READ_UNAVAILABLE', 'the read answered in an unknown shape');\n}\n\n/** One read (the handle checks it). Over RPC the handle is a stub that takes\n * any name for a method, so a loader without this one refuses the call. */\nasync function readParall(read: () => Promise<ActionHandleResult>): Promise<ActionHandleResult> {\n try {\n return await read();\n } catch {\n const message = 'this runtime cannot read Parall data yet';\n return { ok: false, error: { code: 'PARALL_READ_UNAVAILABLE', message } };\n }\n}\n\nfunction unwrapNet(result: ActionHandleResult): ActionHandleNetAnswer {\n if (result?.ok === false) throw new NetError(result.error.code, result.error.message);\n const a = (result?.ok === true ? result.value : null) as ActionHandleNetAnswer | null;\n if (\n !a ||\n typeof a.status !== 'number' ||\n !Array.isArray(a.headers) ||\n (a.body !== null && !(a.body instanceof ArrayBuffer))\n ) {\n throw new NetError(\n 'NET_FAILED',\n 'the request answered in an unknown shape; it may have reached the server',\n );\n }\n return a;\n}\n\n// Statuses whose Response has no body (Fetch's null body status).\nconst NULL_BODY_STATUS = new Set([101, 103, 204, 205, 304]);\nconst REDIRECT_STATUS = new Set([301, 302, 303, 307, 308]);\n// What a redirect to another origin keeps of the author's headers\n// (mini-app-network-design.md \u00A74): a key may be in any other one.\nconst CROSS_ORIGIN_HEADERS = new Set([\n 'accept',\n 'accept-language',\n 'content-language',\n 'user-agent',\n]);\n// Dropped with the body when a redirect turns the request into a GET.\nconst BODY_HEADERS = new Set([\n 'content-encoding',\n 'content-language',\n 'content-location',\n 'content-type',\n]);\nconst MAX_REDIRECTS = 5;\nconst DEFAULT_IN_FLIGHT = 4;\n\n/** One request of a ctx.fetch: the first, or a redirect's next hop. */\ninterface Hop {\n url: string;\n method: string;\n headers: [string, string][];\n body: ArrayBuffer | null;\n}\n\nfunction headerPairs(headers: Headers): [string, string][] {\n const out: [string, string][] = [];\n headers.forEach((value, name) => {\n out.push([name, value]);\n });\n return out;\n}\n\n/** The first hop, as a standard Request reads the input and init \u2014 only\n * the method, headers and body are taken from them. */\nasync function firstHop(input: string | URL | Request, init: ActionFetchInit | undefined) {\n let request: Request;\n try {\n request = new Request(input, {\n method: init?.method,\n headers: init?.headers,\n body: init?.body,\n });\n } catch (err) {\n throw new NetError(\n 'ACTION_INVALID_CALL',\n `ctx.fetch: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n const hop: Hop = {\n url: request.url,\n method: request.method,\n headers: headerPairs(request.headers),\n body: request.body ? await request.arrayBuffer() : null,\n };\n const fromInput = typeof input === 'object' && 'redirect' in input ? input.redirect : undefined;\n return {\n hop,\n redirect: (init?.redirect ?? fromInput ?? 'follow') as RequestRedirect,\n signal: init?.signal ?? (input instanceof Request ? input.signal : null),\n };\n}\n\n/** The next hop for a redirect, or null when it is not to be followed\n * (mini-app-network-design.md \u00A74). The handle checks the address of every\n * hop as it does the first: an IP address or loopback name in the Location,\n * or the platform, is refused there; a name that resolves to a private\n * address is left to Cloudflare's edge (status 530). */\nfunction nextHop(hop: Hop, status: number, location: string | undefined): Hop | null {\n if (!REDIRECT_STATUS.has(status) || location === undefined) return null;\n let from: URL;\n let to: URL;\n try {\n from = new URL(hop.url);\n to = new URL(location, hop.url);\n } catch {\n return null;\n }\n if (from.protocol === 'https:' && to.protocol === 'http:') return null;\n const sameOrigin = to.origin === from.origin && to.origin !== 'null';\n const toGet =\n (status === 303 && hop.method !== 'GET' && hop.method !== 'HEAD') ||\n ((status === 301 || status === 302) && hop.method === 'POST');\n if (!sameOrigin) {\n // The next request would carry the body to another origin.\n if (status === 307 || status === 308) return null;\n if ((status === 301 || status === 302) && !['GET', 'HEAD', 'POST'].includes(hop.method)) {\n return null;\n }\n }\n let { method, headers, body } = hop;\n if (toGet) {\n method = 'GET';\n body = null;\n headers = headers.filter(([name]) => !BODY_HEADERS.has(name.toLowerCase()));\n }\n if (!sameOrigin)\n headers = headers.filter(([name]) => CROSS_ORIGIN_HEADERS.has(name.toLowerCase()));\n return { url: to.href, method, headers, body };\n}\n\nfunction toResponse(answer: ActionHandleNetAnswer, hop: Hop, redirected: boolean): Response {\n if (answer.status < 200 || answer.status > 599) {\n throw new NetError('NET_FAILED', `the server answered with status ${answer.status}`);\n }\n // As Fetch does: no body for a HEAD request or a null body status.\n const body = hop.method === 'HEAD' || NULL_BODY_STATUS.has(answer.status) ? null : answer.body;\n let res: Response;\n try {\n res = new Response(body, {\n status: answer.status,\n statusText: answer.status_text,\n headers: answer.headers,\n });\n } catch {\n try {\n res = new Response(body, { status: answer.status, headers: answer.headers });\n } catch {\n throw new NetError('NET_FAILED', 'the answer could not be read');\n }\n }\n // As a fetch Response: the URL that answered, and whether it was reached\n // through a redirect.\n Object.defineProperty(res, 'url', { value: hop.url });\n if (redirected) Object.defineProperty(res, 'redirected', { value: true });\n return res;\n}\n\n/** p, or the signal's reason as soon as it aborts. A request already at\n * the handle runs on, and the loader waits for it before answering; one\n * still waiting for its turn is never sent. */\nfunction abortable<T>(p: Promise<T>, signal: AbortSignal | null | undefined): Promise<T> {\n if (!signal) return p;\n if (signal.aborted) return Promise.reject(signal.reason);\n return new Promise<T>((resolve, reject) => {\n const onAbort = () => reject(signal.reason);\n signal.addEventListener('abort', onAbort, { once: true });\n p.then(\n (v) => {\n signal.removeEventListener('abort', onAbort);\n resolve(v);\n },\n (e) => {\n signal.removeEventListener('abort', onAbort);\n reject(e);\n },\n );\n });\n}\n\n/** ctx.env: the secrets as a frozen object of strings. */\nfunction envOf(raw: unknown): Readonly<Record<string, string>> {\n const entries =\n raw && typeof raw === 'object' && !Array.isArray(raw)\n ? Object.entries(raw).filter((e): e is [string, string] => typeof e[1] === 'string')\n : [];\n return Object.freeze(Object.fromEntries(entries));\n}\n\nfunction failure(err: unknown): ActionRunResult {\n if (err instanceof ActionError || (err instanceof Error && err.name === 'ActionError')) {\n return { ok: false, error: { kind: 'action_error', message: err.message } };\n }\n const e = err instanceof Error ? err : new Error(String(err));\n const coded = [ActionDbError, ClipError, NetError, ParallError].some((c) => e instanceof c);\n const label = coded ? `${e.name} ${(e as ParallError).code}` : e.name;\n return {\n ok: false,\n error: { kind: 'unexpected', message: `${label}: ${e.message}`, stack: e.stack ?? '' },\n };\n}\n\n/** A database call as the author's code holds it. It notes whether the code\n * attached a rejection handler anywhere along its chain \u2014 `await`,\n * `try`/`catch`, `.catch()`, `.then(f).catch(g)`, `Promise.all` all do \u2014 so\n * a failure nobody looked at fails the action instead of being lost.\n * Promises derived from a call point back to it. */\nclass DbCall<T> extends Promise<T> {\n handled = false;\n origin?: DbCall<unknown>;\n #inFinally = false;\n\n override then<R1 = T, R2 = never>(\n onFulfilled?: ((value: T) => R1 | PromiseLike<R1>) | null,\n onRejected?: ((reason: unknown) => R2 | PromiseLike<R2>) | null,\n ): Promise<R1 | R2> {\n const origin = this.origin ?? this;\n if (typeof onRejected === 'function' && !this.#inFinally) origin.handled = true;\n const derived = super.then(onFulfilled, onRejected) as DbCall<R1 | R2>;\n derived.origin = origin;\n return derived;\n }\n\n // finally() calls then() with a rejection handler that throws the failure\n // on: it handles nothing. A catch on what it returns still counts.\n override finally(onFinally?: (() => void) | null): Promise<T> {\n this.#inFinally = true;\n try {\n return super.finally(onFinally);\n } finally {\n this.#inFinally = false;\n }\n }\n}\n\n// The wrapper's own bookkeeping on a DbCall, which must not count as the\n// author handling it.\nconst observe = Promise.prototype.then as <T>(\n this: Promise<T>,\n onFulfilled: (value: T) => unknown,\n onRejected?: (reason: unknown) => unknown,\n) => Promise<unknown>;\n\n/** Wraps the author's functions into the module entry the loader calls. */\nexport function defineActions(actions: Record<string, ActionFunction>): ActionRunnerClass {\n const names = Object.keys(actions).sort();\n // Not named ActionRunner: the author's export usually is, and a bundler\n // would rename this class to tell the two apart.\n class ActionEntrypoint extends WorkerEntrypoint {\n static readonly actions: readonly string[] = names;\n\n async run(req: ActionRunRequest, handle: ActionHandle): Promise<ActionRunResult> {\n // Database calls still in flight are waited for before answering \u2014 a\n // write the author forgot to await commits before the caller has the\n // result. Calls started from a finishing call are waited for too; the\n // loader refuses any that arrive after run() returns.\n const pending = new Set<Promise<unknown>>();\n const failed = new Map<DbCall<unknown>, unknown>();\n const track = <T>(\n call: Promise<ActionHandleResult>,\n open: (result: ActionHandleResult) => unknown = unwrap,\n ): Promise<T> => {\n const dbCall = new DbCall<T>((resolve, reject) => {\n call.then(open).then(resolve as (value: unknown) => void, reject);\n });\n const settled = observe.call(\n dbCall,\n () => undefined,\n (err) => {\n failed.set(dbCall, err);\n },\n );\n pending.add(settled);\n observe.call(settled, () => pending.delete(settled));\n return dbCall;\n };\n const drain = async () => {\n while (pending.size > 0) await Promise.allSettled([...pending]);\n };\n const db: ActionDb = {\n query: (sql, params = []) => track(handle.query(sql, params)),\n exec: (sql, params = []) => track(handle.exec(sql, params)),\n batch: (statements) => track(handle.batch(statements)),\n };\n // Clip calls are tracked like database calls: waited for before the\n // answer, and a failure nobody looked at fails the action.\n const clip: ActionClip = {\n exec: (clipName, command, args, options) => {\n const request: ActionHandleClipRequest = {\n clip: clipName,\n command,\n args,\n connection: options?.connection,\n profile: options?.profile,\n timeout_ms: options?.timeoutMs,\n };\n const sent =\n typeof handle.clip === 'function'\n ? handle.clip(request)\n : Promise.resolve<ActionHandleResult>({\n ok: false,\n error: {\n code: 'CLIP_UNAVAILABLE',\n message: 'this runtime cannot call connectors yet',\n },\n });\n return track(sent, unwrapClip);\n },\n };\n // Outbound requests: one handle call per hop, at most net_in_flight at\n // once (more wait their turn), tracked like database calls.\n const limit = Math.max(1, req.net_in_flight || DEFAULT_IN_FLIGHT);\n let active = 0;\n const waiting: (() => void)[] = [];\n const send = async (hop: Hop, timeoutMs: number | undefined, signal: AbortSignal | null) => {\n while (active >= limit) await new Promise<void>((resume) => waiting.push(resume));\n active++;\n try {\n // Aborted while it waited for its turn (the code has already had\n // the abort): it is never sent, and the turn passes on.\n if (signal?.aborted) throw signal.reason;\n if (typeof handle.request !== 'function') {\n throw new NetError('NET_UNAVAILABLE', 'this runtime cannot make requests yet');\n }\n return unwrapNet(\n await handle.request({\n ...hop,\n ...(timeoutMs === undefined ? {} : { timeout_ms: timeoutMs }),\n }),\n );\n } finally {\n active--;\n waiting.shift()?.();\n }\n };\n const request = async (input: string | URL | Request, init?: ActionFetchInit) => {\n const first = await firstHop(input, init);\n const { redirect, signal } = first;\n let hop = first.hop;\n for (let followed = 0; ; followed++) {\n // Aborted before this hop: it is never asked for.\n if (signal?.aborted) throw signal.reason;\n const answer = await abortable(send(hop, init?.timeoutMs, signal), signal);\n if (redirect !== 'manual' && REDIRECT_STATUS.has(answer.status)) {\n if (redirect === 'error') {\n throw new NetError(\n 'NET_FAILED',\n `the server redirected (${answer.status}) and redirect is \"error\"`,\n );\n }\n const location = answer.headers.find(\n ([name]) => name.toLowerCase() === 'location',\n )?.[1];\n const next = nextHop(hop, answer.status, location);\n if (next) {\n if (followed >= MAX_REDIRECTS) {\n throw new NetError(\n 'ACTION_LIMIT_EXCEEDED',\n `ctx.fetch follows at most ${MAX_REDIRECTS} redirects`,\n );\n }\n hop = next;\n continue;\n }\n }\n return toResponse(answer, hop, followed > 0);\n }\n };\n const ctxFetch: ActionFetch = (input, init) =>\n track<Response>(\n request(input, init).then((res) => ({ ok: true, value: res }) as ActionHandleResult),\n (result) => (result as { value: unknown }).value,\n );\n const reads = handle as Required<ActionHandle>;\n const read = <T>(r: () => Promise<ActionHandleResult>) =>\n track<T>(readParall(r), unwrapParall);\n const parall: ActionParall = {\n get: (refs) => read<ParallItem[]>(() => reads.parall({ refs: refs as string[] })),\n members: () => read<ParallMember[]>(() => reads.parallMembers()),\n };\n const env = envOf(req.env);\n try {\n const fn = Object.hasOwn(actions, req.action) ? actions[req.action] : undefined;\n if (typeof fn !== 'function') {\n throw new Error(\n `this module does not implement the action ${JSON.stringify(req.action)}`,\n );\n }\n const value = await fn(\n { viewer: req.viewer, app: req.app, db, clip, fetch: ctxFetch, parall, env },\n req.params,\n );\n await drain();\n // A call that failed while the code never looked at it (a forgotten\n // await) fails the action: answering ok would claim a write that did\n // not happen.\n for (const [dbCall, err] of failed) if (!dbCall.handled) throw err;\n const json = JSON.stringify(value === undefined ? null : value);\n if (typeof json !== 'string') {\n throw new TypeError('the action returned a value JSON cannot represent');\n }\n return { ok: true, json };\n } catch (err) {\n await drain();\n return failure(err);\n }\n }\n }\n return ActionEntrypoint;\n}\n";
2
2
  //# sourceMappingURL=apps-actions-sdk.generated.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"apps-actions-sdk.generated.d.ts","sourceRoot":"","sources":["../../src/commands/apps-actions-sdk.generated.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,kBAAkB,8x9BAAyn9B,CAAC"}
1
+ {"version":3,"file":"apps-actions-sdk.generated.d.ts","sourceRoot":"","sources":["../../src/commands/apps-actions-sdk.generated.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,kBAAkB,4q+BAAug+B,CAAC"}
@@ -1,3 +1,3 @@
1
1
  // Generated from ts/miniapp-sdk/src/actions.ts by scripts/generate-miniapp-sdk.mjs. Do not edit.
2
2
  // biome-ignore format: generated copy
3
- export const ACTIONS_SDK_SOURCE = "/**\n * @parall/miniapp-sdk/actions — the action side of a Mini App\n * (docs/engineering-design/mini-app-action-design.md §2): `defineActions`\n * turns the author's functions into the module entry the action loader\n * calls; `ActionError` is the error whose message the caller may see.\n *\n * This file runs inside the Cloudflare isolate, not in the page. It is the\n * only part of the SDK that imports `cloudflare:workers`, and an action\n * module is built from it into one file whose sole external import is that\n * one. Export the result as `ActionRunner` — the loader looks it up by name:\n *\n * export const ActionRunner = defineActions({\n * async addNote(ctx, { text }) {\n * const { rows } = await ctx.db.exec(\n * 'INSERT INTO notes (text, created_by) VALUES ($1, $2) RETURNING id',\n * [text, ctx.viewer.id],\n * );\n * return rows[0];\n * },\n * });\n *\n * Security does not depend on this wrapper: the loader accepts only the two\n * result shapes run() returns, whatever produced them (design §3.1).\n *\n * An action that declares `\"clip\": true` in the manifest (write actions only)\n * may call connectors as the person who called the action\n * (docs/engineering-design/mini-app-clip-design.md):\n *\n * const profile = await ctx.clip.exec('linkedin', 'get-profile', { id }, { connection: 'sales-li' });\n *\n * `ctx.fetch` requests a public HTTP(S) address and returns a standard\n * `Response` (docs/engineering-design/mini-app-network-design.md):\n *\n * const res = await ctx.fetch('https://api.example.com/v1/items');\n * if (!res.ok) throw new ActionError(`the items API answered ${res.status}`);\n * return res.json();\n *\n * `ctx.env` holds the app's secrets by name. Online they are the org shared\n * secrets an org owner or admin gave this app (org settings → 共享密钥 →\n * 给哪些 app); a name the app was not given is undefined:\n *\n * const key = ctx.env.EXAMPLE_API_KEY;\n * if (!key) throw new ActionError('EXAMPLE_API_KEY is missing: an org owner or admin can give it to this app');\n * const res = await ctx.fetch('https://api.example.com/v1/items', { headers: { Authorization: `Bearer ${key}` } });\n *\n * `ctx.parall.get(refs)` reads Parall files, tasks and members by reference,\n * as the caller and read-only (ActionParall below).\n */\n\nimport { WorkerEntrypoint } from 'cloudflare:workers';\n\n/** An error whose message reaches every caller as is (ACTION_FAILED with\n * error_kind action_error). Anything else thrown is an unexpected failure. */\nexport class ActionError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ActionError';\n }\n}\n\n/** A database call that was refused or failed. `code` is the platform's:\n * SQL_ERROR, SQL_REJECTED, ACTION_READ_ONLY, ACTION_LIMIT_EXCEEDED, … */\nexport class ActionDbError extends Error {\n readonly code: string;\n\n constructor(code: string, message: string) {\n super(message);\n this.name = 'ActionDbError';\n this.code = code;\n }\n}\n\n/** A connector call that was refused or failed. `code` is the platform's — the\n * same codes the caller gets running `parall connector exec` themselves\n * (CONNECTION_NOT_ALLOWED, SCRIPT_ERROR, MCP_TOOL_FAILED, …) — or the\n * action's own: CLIP_NOT_DECLARED, ACTION_LIMIT_EXCEEDED, ACTION_DEADLINE.\n * OUTCOME_UNKNOWN means the command may have run: never retry it blindly. */\nexport class ClipError extends Error {\n readonly code: string;\n\n constructor(code: string, message: string) {\n super(message);\n this.name = 'ClipError';\n this.code = code;\n }\n}\n\n/** An outbound request (ctx.fetch) that was refused or failed — an HTTP\n * error status is not one: it comes back as a Response. `code` is the\n * platform's:\n *\n * - not sent: ACTION_INVALID_CALL (the URL, method, headers or body),\n * NET_ADDRESS_BLOCKED (an IP address or a loopback name such as localhost\n * written in the URL, the platform's own hosts), ACTION_LIMIT_EXCEEDED\n * (too many requests, or one too large), ACTION_DEADLINE (too little time\n * left), NET_BUSY (the platform is busy; try again shortly),\n * NET_UNAVAILABLE, USER_DISABLED, ACTION_HANDLE_REVOKED;\n * - sent, so it may have reached the server: NET_TIMEOUT, NET_FAILED,\n * NET_RESPONSE_TOO_LARGE (answers are at most 1 MiB).\n *\n * A host name that resolves to a private or loopback address is not refused\n * here: Cloudflare's edge refuses it, and ctx.fetch returns an ordinary\n * Response with status 530 (body like \"error code: 1016\"), not a NetError;\n * the outbound record shows it as answered with HTTP 530.\n *\n * The platform never retries; send an idempotency key where the other side\n * supports one. */\nexport class NetError extends Error {\n readonly code: string;\n\n constructor(code: string, message: string) {\n super(message);\n this.name = 'NetError';\n this.code = code;\n }\n}\n\n/** A ctx.parall.get refused as a whole (an item it cannot read is in the\n * result instead): ACTION_INVALID_CALL (refs not 1 to 100 strings),\n * ACTION_LIMIT_EXCEEDED, ACTION_DEADLINE, ACTION_HANDLE_REVOKED, USER_DISABLED,\n * ORG_FORBIDDEN (left the org), PARALL_READ_UNAVAILABLE (off or lost: retry). */\nexport class ParallError extends Error {\n readonly code: string;\n\n constructor(code: string, message: string) {\n super(message);\n this.name = 'ParallError';\n this.code = code;\n }\n}\n\n/** The caller, as the platform vouches for it (design §2.2). */\nexport interface ActionViewer {\n id: string;\n display_name: string;\n is_agent: boolean;\n /** Organization role: owner, admin or member. */\n role: string;\n}\n\nexport interface ActionApp {\n id: string;\n version_seq: number;\n}\n\n/** A row as an object keyed by column name, in select-list order. */\nexport type ActionRow = Record<string, unknown>;\n\nexport interface ActionQueryResult {\n rows: ActionRow[];\n truncated: boolean;\n}\n\nexport interface ActionStatementResult {\n rows: ActionRow[];\n rows_affected: number;\n truncated: boolean;\n}\n\nexport interface ActionExecResult extends ActionStatementResult {\n data_seq: number;\n}\n\nexport interface ActionBatchStatement {\n sql: string;\n params?: unknown[];\n}\n\nexport interface ActionBatchResult {\n results: ActionStatementResult[];\n data_seq: number;\n}\n\n/** ctx.db: one statement per query / exec; a batch is one transaction. */\nexport interface ActionDb {\n query(sql: string, params?: unknown[]): Promise<ActionQueryResult>;\n /** Write actions only. */\n exec(sql: string, params?: unknown[]): Promise<ActionExecResult>;\n /** Write actions only; at most 50 statements, counted as one call. */\n batch(statements: ActionBatchStatement[]): Promise<ActionBatchResult>;\n}\n\nexport interface ActionClipOptions {\n /** The connection to run on: its alias or ccn_ id. The caller must be\n * allowed to use it, exactly as for their own `parall connector exec`. */\n connection: string;\n profile?: string;\n /** The command's timeout; 30 s by default, cut to what the action's\n * deadline leaves. */\n timeoutMs?: number;\n}\n\n/** ctx.clip: connector calls as the action's caller; actions that declare clip only. */\nexport interface ActionClip {\n /** Runs a command of a connector (its name or crg_ id) and returns the connector's\n * data; throws ClipError. */\n exec(clip: string, command: string, args: unknown, options: ActionClipOptions): Promise<unknown>;\n}\n\n/** A file (a chat attachment): no link, no uploader; width and height for images. */\nexport interface ParallFile {\n id: string;\n file_name: string;\n mime_type: string;\n file_size: number;\n width?: number;\n height?: number;\n}\n\n/** A task: due_date is YYYY-MM-DD or null; archived_at once it is archived. */\nexport interface ParallTask {\n id: string;\n identifier?: string;\n title: string;\n status: string;\n priority: string;\n assignee_id?: string;\n project_id?: string;\n due_date: string | null;\n created_at: string;\n updated_at: string;\n archived_at?: string;\n}\n\n/** An active member of the app's organization, person or agent; no email. */\nexport interface ParallMember {\n user_id: string;\n display_name: string;\n avatar_url?: string;\n type: 'human' | 'agent';\n role: string;\n title: string;\n joined_at: string;\n}\n\n/** One reference's answer; a refusal carries only its code: RESTRICTED (the\n * caller may not read it), NOT_FOUND (not in the app's organization: deleted,\n * another organization's, a member who left), INVALID_REF (not an att_, tsk_\n * or usr_ reference) or TOO_LARGE (past the get's 1 MiB). Others: unreadable. */\nexport type ParallItem =\n | { ok: true; type: 'file'; item: ParallFile }\n | { ok: true; type: 'task'; item: ParallTask }\n | { ok: true; type: 'member'; item: ParallMember }\n | { ok: false; code: string };\n\nexport interface ActionParall {\n /** Reads up to 100 references (prll://att_…, tsk_…, usr_… or bare IDs), one\n * item each in order, as the caller's own read now; read-only. The result\n * is the caller's view: store references, never the result across\n * invocations or in page storage. 20 gets per invocation, 10 s each. */\n get(refs: readonly string[]): Promise<ParallItem[]>;\n}\n\n/** ctx.fetch's options: the standard ones — method, headers, body, signal,\n * redirect — and the request's timeout. Others (cache, credentials, mode,\n * the Workers `cf`) are not looked at: every request is uncached and carries\n * only what the code sets. */\nexport interface ActionFetchInit extends RequestInit {\n /** This request's timeout; 30 s by default, cut to what the action's\n * deadline leaves. With redirects, each hop has it. */\n timeoutMs?: number;\n}\n\n/** ctx.fetch: a public HTTP(S) request from the platform, recorded in the\n * app's call record (host, method, status, size and time — never the query\n * string, headers or bodies). A local run (`parall app action run --local`,\n * `parall app dev`) sends it straight from your machine and records nothing.\n * Redirects are followed up to 5 times: within the same origin as Fetch\n * does; to another origin with only Accept, Accept-Language,\n * Content-Language and User-Agent kept, and not at all when the next request\n * would carry the body (307, 308, and 301 / 302 for a method other than GET,\n * HEAD or POST) or when it would go from https: to http: — then the redirect\n * itself comes back. Each hop is a request of its own and counts toward the\n * invocation's request limit (20 by default). At most 4 requests (by\n * default) run at once; more wait their turn. Request and answer bodies are\n * at most 1 MiB each. */\nexport type ActionFetch = (\n input: string | URL | Request,\n init?: ActionFetchInit,\n) => Promise<Response>;\n\nexport interface ActionContext {\n viewer: ActionViewer;\n app: ActionApp;\n db: ActionDb;\n clip: ActionClip;\n fetch: ActionFetch;\n parall: ActionParall;\n /** The app's secrets by name; read-only. Online they are the org shared\n * secrets an org owner or admin gave this app; a local run (`parall app\n * action run --local`) reads the project's .dev.vars instead. Never pass\n * them as params or write them to the Database or a result. */\n env: Readonly<Record<string, string>>;\n}\n\n// biome-ignore lint/suspicious/noExplicitAny: the platform validates params against the declared schema before the call\nexport type ActionFunction = (ctx: ActionContext, params: any) => unknown;\n\n/** What the loader passes run() (ts/actions-worker src/run.ts). A loader\n * before the network sends neither env nor net_in_flight. */\nexport interface ActionRunRequest {\n action: string;\n params: unknown;\n viewer: ActionViewer;\n app: ActionApp;\n env?: Record<string, string>;\n /** How many requests the handle takes at once. */\n net_in_flight?: number;\n}\n\n/** The only two shapes the loader accepts back (ts/actions-worker src/outcome.ts). */\nexport type ActionRunResult =\n | { ok: true; json: string }\n | { ok: false; error: { kind: 'action_error' | 'unexpected'; message: string; stack?: string } };\n\n/** What a handle method resolves to. Failures travel as values because\n * Workers RPC keeps only an exception's name and message (design §6). */\nexport type ActionHandleResult =\n | { ok: true; value: unknown }\n | { ok: false; error: { code: string; message: string } };\n\n/** What the handle's clip method takes. */\nexport interface ActionHandleClipRequest {\n clip: string;\n command: string;\n args?: unknown;\n connection: string;\n profile?: string;\n timeout_ms?: number;\n}\n\n/** What the handle's request method takes: one request, rebuilt by the\n * loader from exactly these fields. */\nexport interface ActionHandleNetRequest {\n url: string;\n method: string;\n headers: [string, string][];\n body: ArrayBuffer | null;\n timeout_ms?: number;\n}\n\n/** What it answers with on success: the answer, never followed. */\nexport interface ActionHandleNetAnswer {\n status: number;\n status_text: string;\n headers: [string, string][];\n body: ArrayBuffer | null;\n}\n\n/** The per-invocation handle the loader passes run(). Loaders older than\n * Clip calls, the network or Parall reads lack clip, request or parall. */\nexport interface ActionHandle {\n query(sql: string, params: unknown[]): Promise<ActionHandleResult>;\n exec(sql: string, params: unknown[]): Promise<ActionHandleResult>;\n batch(statements: ActionBatchStatement[]): Promise<ActionHandleResult>;\n clip?(req: ActionHandleClipRequest): Promise<ActionHandleResult>;\n request?(req: ActionHandleNetRequest): Promise<ActionHandleResult>;\n parall?(req: { refs: string[] }): Promise<ActionHandleResult>;\n}\n\n/** What defineActions returns; export it as `ActionRunner`. */\nexport interface ActionRunnerClass {\n /** The actions the module implements, sorted; `parall app check` compares\n * them with the manifest. */\n readonly actions: readonly string[];\n new (\n ctx: unknown,\n env: unknown,\n ): { run(req: ActionRunRequest, handle: ActionHandle): Promise<ActionRunResult> };\n}\n\nfunction unwrap(result: ActionHandleResult): unknown {\n if (result?.ok === true) return result.value;\n if (result?.ok === false) throw new ActionDbError(result.error.code, result.error.message);\n throw new ActionDbError(\n 'ACTION_DB_UNAVAILABLE',\n 'the database handle answered in an unknown shape',\n );\n}\n\nfunction unwrapClip(result: ActionHandleResult): unknown {\n if (result?.ok === true) return result.value;\n if (result?.ok === false) throw new ClipError(result.error.code, result.error.message);\n throw new ClipError(\n 'OUTCOME_UNKNOWN',\n 'the connector call answered in an unknown shape; it may or may not have run',\n );\n}\n\nfunction unwrapParall(result: ActionHandleResult): ParallItem[] {\n if (result?.ok === false) throw new ParallError(result.error.code, result.error.message);\n if (result?.ok === true && Array.isArray(result.value)) return result.value as ParallItem[];\n throw new ParallError('PARALL_READ_UNAVAILABLE', 'the read answered in an unknown shape');\n}\n\n/** One get; the handle checks refs. Over RPC the handle is a stub that takes\n * any name for a method, so a loader without parall refuses the call itself. */\nasync function readParall(handle: ActionHandle, refs: unknown): Promise<ActionHandleResult> {\n try {\n return await (handle as Required<ActionHandle>).parall({ refs: refs as string[] });\n } catch {\n const message = 'this runtime cannot read Parall data yet';\n return { ok: false, error: { code: 'PARALL_READ_UNAVAILABLE', message } };\n }\n}\n\nfunction unwrapNet(result: ActionHandleResult): ActionHandleNetAnswer {\n if (result?.ok === false) throw new NetError(result.error.code, result.error.message);\n const a = (result?.ok === true ? result.value : null) as ActionHandleNetAnswer | null;\n if (\n !a ||\n typeof a.status !== 'number' ||\n !Array.isArray(a.headers) ||\n (a.body !== null && !(a.body instanceof ArrayBuffer))\n ) {\n throw new NetError(\n 'NET_FAILED',\n 'the request answered in an unknown shape; it may have reached the server',\n );\n }\n return a;\n}\n\n// Statuses whose Response has no body (Fetch's null body status).\nconst NULL_BODY_STATUS = new Set([101, 103, 204, 205, 304]);\nconst REDIRECT_STATUS = new Set([301, 302, 303, 307, 308]);\n// What a redirect to another origin keeps of the author's headers\n// (mini-app-network-design.md §4): a key may be in any other one.\nconst CROSS_ORIGIN_HEADERS = new Set([\n 'accept',\n 'accept-language',\n 'content-language',\n 'user-agent',\n]);\n// Dropped with the body when a redirect turns the request into a GET.\nconst BODY_HEADERS = new Set([\n 'content-encoding',\n 'content-language',\n 'content-location',\n 'content-type',\n]);\nconst MAX_REDIRECTS = 5;\nconst DEFAULT_IN_FLIGHT = 4;\n\n/** One request of a ctx.fetch: the first, or a redirect's next hop. */\ninterface Hop {\n url: string;\n method: string;\n headers: [string, string][];\n body: ArrayBuffer | null;\n}\n\nfunction headerPairs(headers: Headers): [string, string][] {\n const out: [string, string][] = [];\n headers.forEach((value, name) => {\n out.push([name, value]);\n });\n return out;\n}\n\n/** The first hop, as a standard Request reads the input and init — only\n * the method, headers and body are taken from them. */\nasync function firstHop(input: string | URL | Request, init: ActionFetchInit | undefined) {\n let request: Request;\n try {\n request = new Request(input, {\n method: init?.method,\n headers: init?.headers,\n body: init?.body,\n });\n } catch (err) {\n throw new NetError(\n 'ACTION_INVALID_CALL',\n `ctx.fetch: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n const hop: Hop = {\n url: request.url,\n method: request.method,\n headers: headerPairs(request.headers),\n body: request.body ? await request.arrayBuffer() : null,\n };\n const fromInput = typeof input === 'object' && 'redirect' in input ? input.redirect : undefined;\n return {\n hop,\n redirect: (init?.redirect ?? fromInput ?? 'follow') as RequestRedirect,\n signal: init?.signal ?? (input instanceof Request ? input.signal : null),\n };\n}\n\n/** The next hop for a redirect, or null when it is not to be followed\n * (mini-app-network-design.md §4). The handle checks the address of every\n * hop as it does the first: an IP address or loopback name in the Location,\n * or the platform, is refused there; a name that resolves to a private\n * address is left to Cloudflare's edge (status 530). */\nfunction nextHop(hop: Hop, status: number, location: string | undefined): Hop | null {\n if (!REDIRECT_STATUS.has(status) || location === undefined) return null;\n let from: URL;\n let to: URL;\n try {\n from = new URL(hop.url);\n to = new URL(location, hop.url);\n } catch {\n return null;\n }\n if (from.protocol === 'https:' && to.protocol === 'http:') return null;\n const sameOrigin = to.origin === from.origin && to.origin !== 'null';\n const toGet =\n (status === 303 && hop.method !== 'GET' && hop.method !== 'HEAD') ||\n ((status === 301 || status === 302) && hop.method === 'POST');\n if (!sameOrigin) {\n // The next request would carry the body to another origin.\n if (status === 307 || status === 308) return null;\n if ((status === 301 || status === 302) && !['GET', 'HEAD', 'POST'].includes(hop.method)) {\n return null;\n }\n }\n let { method, headers, body } = hop;\n if (toGet) {\n method = 'GET';\n body = null;\n headers = headers.filter(([name]) => !BODY_HEADERS.has(name.toLowerCase()));\n }\n if (!sameOrigin)\n headers = headers.filter(([name]) => CROSS_ORIGIN_HEADERS.has(name.toLowerCase()));\n return { url: to.href, method, headers, body };\n}\n\nfunction toResponse(answer: ActionHandleNetAnswer, hop: Hop, redirected: boolean): Response {\n if (answer.status < 200 || answer.status > 599) {\n throw new NetError('NET_FAILED', `the server answered with status ${answer.status}`);\n }\n // As Fetch does: no body for a HEAD request or a null body status.\n const body = hop.method === 'HEAD' || NULL_BODY_STATUS.has(answer.status) ? null : answer.body;\n let res: Response;\n try {\n res = new Response(body, {\n status: answer.status,\n statusText: answer.status_text,\n headers: answer.headers,\n });\n } catch {\n try {\n res = new Response(body, { status: answer.status, headers: answer.headers });\n } catch {\n throw new NetError('NET_FAILED', 'the answer could not be read');\n }\n }\n // As a fetch Response: the URL that answered, and whether it was reached\n // through a redirect.\n Object.defineProperty(res, 'url', { value: hop.url });\n if (redirected) Object.defineProperty(res, 'redirected', { value: true });\n return res;\n}\n\n/** p, or the signal's reason as soon as it aborts. A request already at\n * the handle runs on, and the loader waits for it before answering; one\n * still waiting for its turn is never sent. */\nfunction abortable<T>(p: Promise<T>, signal: AbortSignal | null | undefined): Promise<T> {\n if (!signal) return p;\n if (signal.aborted) return Promise.reject(signal.reason);\n return new Promise<T>((resolve, reject) => {\n const onAbort = () => reject(signal.reason);\n signal.addEventListener('abort', onAbort, { once: true });\n p.then(\n (v) => {\n signal.removeEventListener('abort', onAbort);\n resolve(v);\n },\n (e) => {\n signal.removeEventListener('abort', onAbort);\n reject(e);\n },\n );\n });\n}\n\n/** ctx.env: the secrets as a frozen object of strings. */\nfunction envOf(raw: unknown): Readonly<Record<string, string>> {\n const entries =\n raw && typeof raw === 'object' && !Array.isArray(raw)\n ? Object.entries(raw).filter((e): e is [string, string] => typeof e[1] === 'string')\n : [];\n return Object.freeze(Object.fromEntries(entries));\n}\n\nfunction failure(err: unknown): ActionRunResult {\n if (err instanceof ActionError || (err instanceof Error && err.name === 'ActionError')) {\n return { ok: false, error: { kind: 'action_error', message: err.message } };\n }\n const e = err instanceof Error ? err : new Error(String(err));\n const coded = [ActionDbError, ClipError, NetError, ParallError].some((c) => e instanceof c);\n const label = coded ? `${e.name} ${(e as ParallError).code}` : e.name;\n return {\n ok: false,\n error: { kind: 'unexpected', message: `${label}: ${e.message}`, stack: e.stack ?? '' },\n };\n}\n\n/** A database call as the author's code holds it. It notes whether the code\n * attached a rejection handler anywhere along its chain — `await`,\n * `try`/`catch`, `.catch()`, `.then(f).catch(g)`, `Promise.all` all do — so\n * a failure nobody looked at fails the action instead of being lost.\n * Promises derived from a call point back to it. */\nclass DbCall<T> extends Promise<T> {\n handled = false;\n origin?: DbCall<unknown>;\n #inFinally = false;\n\n override then<R1 = T, R2 = never>(\n onFulfilled?: ((value: T) => R1 | PromiseLike<R1>) | null,\n onRejected?: ((reason: unknown) => R2 | PromiseLike<R2>) | null,\n ): Promise<R1 | R2> {\n const origin = this.origin ?? this;\n if (typeof onRejected === 'function' && !this.#inFinally) origin.handled = true;\n const derived = super.then(onFulfilled, onRejected) as DbCall<R1 | R2>;\n derived.origin = origin;\n return derived;\n }\n\n // finally() calls then() with a rejection handler that throws the failure\n // on: it handles nothing. A catch on what it returns still counts.\n override finally(onFinally?: (() => void) | null): Promise<T> {\n this.#inFinally = true;\n try {\n return super.finally(onFinally);\n } finally {\n this.#inFinally = false;\n }\n }\n}\n\n// The wrapper's own bookkeeping on a DbCall, which must not count as the\n// author handling it.\nconst observe = Promise.prototype.then as <T>(\n this: Promise<T>,\n onFulfilled: (value: T) => unknown,\n onRejected?: (reason: unknown) => unknown,\n) => Promise<unknown>;\n\n/** Wraps the author's functions into the module entry the loader calls. */\nexport function defineActions(actions: Record<string, ActionFunction>): ActionRunnerClass {\n const names = Object.keys(actions).sort();\n // Not named ActionRunner: the author's export usually is, and a bundler\n // would rename this class to tell the two apart.\n class ActionEntrypoint extends WorkerEntrypoint {\n static readonly actions: readonly string[] = names;\n\n async run(req: ActionRunRequest, handle: ActionHandle): Promise<ActionRunResult> {\n // Database calls still in flight are waited for before answering — a\n // write the author forgot to await commits before the caller has the\n // result. Calls started from a finishing call are waited for too; the\n // loader refuses any that arrive after run() returns.\n const pending = new Set<Promise<unknown>>();\n const failed = new Map<DbCall<unknown>, unknown>();\n const track = <T>(\n call: Promise<ActionHandleResult>,\n open: (result: ActionHandleResult) => unknown = unwrap,\n ): Promise<T> => {\n const dbCall = new DbCall<T>((resolve, reject) => {\n call.then(open).then(resolve as (value: unknown) => void, reject);\n });\n const settled = observe.call(\n dbCall,\n () => undefined,\n (err) => {\n failed.set(dbCall, err);\n },\n );\n pending.add(settled);\n observe.call(settled, () => pending.delete(settled));\n return dbCall;\n };\n const drain = async () => {\n while (pending.size > 0) await Promise.allSettled([...pending]);\n };\n const db: ActionDb = {\n query: (sql, params = []) => track(handle.query(sql, params)),\n exec: (sql, params = []) => track(handle.exec(sql, params)),\n batch: (statements) => track(handle.batch(statements)),\n };\n // Clip calls are tracked like database calls: waited for before the\n // answer, and a failure nobody looked at fails the action.\n const clip: ActionClip = {\n exec: (clipName, command, args, options) => {\n const request: ActionHandleClipRequest = {\n clip: clipName,\n command,\n args,\n connection: options?.connection,\n profile: options?.profile,\n timeout_ms: options?.timeoutMs,\n };\n const sent =\n typeof handle.clip === 'function'\n ? handle.clip(request)\n : Promise.resolve<ActionHandleResult>({\n ok: false,\n error: {\n code: 'CLIP_UNAVAILABLE',\n message: 'this runtime cannot call connectors yet',\n },\n });\n return track(sent, unwrapClip);\n },\n };\n // Outbound requests: one handle call per hop, at most net_in_flight at\n // once (more wait their turn), tracked like database calls.\n const limit = Math.max(1, req.net_in_flight || DEFAULT_IN_FLIGHT);\n let active = 0;\n const waiting: (() => void)[] = [];\n const send = async (hop: Hop, timeoutMs: number | undefined, signal: AbortSignal | null) => {\n while (active >= limit) await new Promise<void>((resume) => waiting.push(resume));\n active++;\n try {\n // Aborted while it waited for its turn (the code has already had\n // the abort): it is never sent, and the turn passes on.\n if (signal?.aborted) throw signal.reason;\n if (typeof handle.request !== 'function') {\n throw new NetError('NET_UNAVAILABLE', 'this runtime cannot make requests yet');\n }\n return unwrapNet(\n await handle.request({\n ...hop,\n ...(timeoutMs === undefined ? {} : { timeout_ms: timeoutMs }),\n }),\n );\n } finally {\n active--;\n waiting.shift()?.();\n }\n };\n const request = async (input: string | URL | Request, init?: ActionFetchInit) => {\n const first = await firstHop(input, init);\n const { redirect, signal } = first;\n let hop = first.hop;\n for (let followed = 0; ; followed++) {\n // Aborted before this hop: it is never asked for.\n if (signal?.aborted) throw signal.reason;\n const answer = await abortable(send(hop, init?.timeoutMs, signal), signal);\n if (redirect !== 'manual' && REDIRECT_STATUS.has(answer.status)) {\n if (redirect === 'error') {\n throw new NetError(\n 'NET_FAILED',\n `the server redirected (${answer.status}) and redirect is \"error\"`,\n );\n }\n const location = answer.headers.find(\n ([name]) => name.toLowerCase() === 'location',\n )?.[1];\n const next = nextHop(hop, answer.status, location);\n if (next) {\n if (followed >= MAX_REDIRECTS) {\n throw new NetError(\n 'ACTION_LIMIT_EXCEEDED',\n `ctx.fetch follows at most ${MAX_REDIRECTS} redirects`,\n );\n }\n hop = next;\n continue;\n }\n }\n return toResponse(answer, hop, followed > 0);\n }\n };\n const ctxFetch: ActionFetch = (input, init) =>\n track<Response>(\n request(input, init).then((res) => ({ ok: true, value: res }) as ActionHandleResult),\n (result) => (result as { value: unknown }).value,\n );\n const parall: ActionParall = {\n get: (refs) => track<ParallItem[]>(readParall(handle, refs), unwrapParall),\n };\n const env = envOf(req.env);\n try {\n const fn = Object.hasOwn(actions, req.action) ? actions[req.action] : undefined;\n if (typeof fn !== 'function') {\n throw new Error(\n `this module does not implement the action ${JSON.stringify(req.action)}`,\n );\n }\n const value = await fn(\n { viewer: req.viewer, app: req.app, db, clip, fetch: ctxFetch, parall, env },\n req.params,\n );\n await drain();\n // A call that failed while the code never looked at it (a forgotten\n // await) fails the action: answering ok would claim a write that did\n // not happen.\n for (const [dbCall, err] of failed) if (!dbCall.handled) throw err;\n const json = JSON.stringify(value === undefined ? null : value);\n if (typeof json !== 'string') {\n throw new TypeError('the action returned a value JSON cannot represent');\n }\n return { ok: true, json };\n } catch (err) {\n await drain();\n return failure(err);\n }\n }\n }\n return ActionEntrypoint;\n}\n";
3
+ export const ACTIONS_SDK_SOURCE = "/**\n * @parall/miniapp-sdk/actions — the action side of a Mini App\n * (docs/engineering-design/mini-app-action-design.md §2): `defineActions`\n * turns the author's functions into the module entry the action loader\n * calls; `ActionError` is the error whose message the caller may see.\n *\n * This file runs inside the Cloudflare isolate, not in the page. It is the\n * only part of the SDK that imports `cloudflare:workers`, and an action\n * module is built from it into one file whose sole external import is that\n * one. Export the result as `ActionRunner` — the loader looks it up by name:\n *\n * export const ActionRunner = defineActions({\n * async addNote(ctx, { text }) {\n * const { rows } = await ctx.db.exec(\n * 'INSERT INTO notes (text, created_by) VALUES ($1, $2) RETURNING id',\n * [text, ctx.viewer.id],\n * );\n * return rows[0];\n * },\n * });\n *\n * Security does not depend on this wrapper: the loader accepts only the two\n * result shapes run() returns, whatever produced them (design §3.1).\n *\n * An action that declares `\"clip\": true` in the manifest (write actions only)\n * may call connectors as the person who called the action\n * (docs/engineering-design/mini-app-clip-design.md):\n *\n * const profile = await ctx.clip.exec('linkedin', 'get-profile', { id }, { connection: 'sales-li' });\n *\n * `ctx.fetch` requests a public HTTP(S) address and returns a standard\n * `Response` (docs/engineering-design/mini-app-network-design.md):\n *\n * const res = await ctx.fetch('https://api.example.com/v1/items');\n * if (!res.ok) throw new ActionError(`the items API answered ${res.status}`);\n * return res.json();\n *\n * `ctx.env` holds the app's secrets by name. Online they are the org shared\n * secrets an org owner or admin gave this app (org settings → 共享密钥 →\n * 给哪些 app); a name the app was not given is undefined:\n *\n * const key = ctx.env.EXAMPLE_API_KEY;\n * if (!key) throw new ActionError('EXAMPLE_API_KEY is missing: an org owner or admin can give it to this app');\n * const res = await ctx.fetch('https://api.example.com/v1/items', { headers: { Authorization: `Bearer ${key}` } });\n *\n * `ctx.parall.get(refs)` reads Parall files, tasks and members by reference\n * and `ctx.parall.members()` lists the members, as the caller and read-only\n * (ActionParall below).\n */\n\nimport { WorkerEntrypoint } from 'cloudflare:workers';\n\n/** An error whose message reaches every caller as is (ACTION_FAILED with\n * error_kind action_error). Anything else thrown is an unexpected failure. */\nexport class ActionError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ActionError';\n }\n}\n\n/** An error that carries the platform's `code`: what ActionDbError,\n * ClipError, NetError and ParallError have in common. */\nexport class CodedError extends Error {\n readonly code: string;\n\n constructor(code: string, message: string) {\n super(message);\n this.code = code;\n }\n}\n\n/** A database call that was refused or failed. `code` is the platform's:\n * SQL_ERROR, SQL_REJECTED, ACTION_READ_ONLY, ACTION_LIMIT_EXCEEDED, … */\nexport class ActionDbError extends CodedError {\n override name = 'ActionDbError';\n}\n\n/** A connector call that was refused or failed. `code` is the platform's — the\n * same codes the caller gets running `parall connector exec` themselves\n * (CONNECTION_NOT_ALLOWED, SCRIPT_ERROR, MCP_TOOL_FAILED, …) — or the\n * action's own: CLIP_NOT_DECLARED, ACTION_LIMIT_EXCEEDED, ACTION_DEADLINE.\n * OUTCOME_UNKNOWN means the command may have run: never retry it blindly. */\nexport class ClipError extends CodedError {\n override name = 'ClipError';\n}\n\n/** An outbound request (ctx.fetch) that was refused or failed — an HTTP\n * error status is not one: it comes back as a Response. `code` is the\n * platform's:\n *\n * - not sent: ACTION_INVALID_CALL (the URL, method, headers or body),\n * NET_ADDRESS_BLOCKED (an IP address or a loopback name such as localhost\n * written in the URL, the platform's own hosts), ACTION_LIMIT_EXCEEDED\n * (too many requests, or one too large), ACTION_DEADLINE (too little time\n * left), NET_BUSY (the platform is busy; try again shortly),\n * NET_UNAVAILABLE, USER_DISABLED, ACTION_HANDLE_REVOKED;\n * - sent, so it may have reached the server: NET_TIMEOUT, NET_FAILED,\n * NET_RESPONSE_TOO_LARGE (answers are at most 1 MiB).\n *\n * A host name that resolves to a private or loopback address is not refused\n * here: Cloudflare's edge refuses it, and ctx.fetch returns an ordinary\n * Response with status 530 (body like \"error code: 1016\"), not a NetError;\n * the outbound record shows it as answered with HTTP 530.\n *\n * The platform never retries; send an idempotency key where the other side\n * supports one. */\nexport class NetError extends CodedError {\n override name = 'NetError';\n}\n\n/** A ctx.parall.get or members() refused as a whole (an item a get cannot read\n * is in its result instead): ACTION_INVALID_CALL (refs not 1 to 100 strings),\n * ACTION_LIMIT_EXCEEDED, ACTION_DEADLINE, ACTION_HANDLE_REVOKED, USER_DISABLED,\n * ORG_FORBIDDEN (left the org), TOO_LARGE (the members past 1 MiB: read them\n * by reference), PARALL_READ_UNAVAILABLE (off or lost: retry). */\nexport class ParallError extends CodedError {\n override name = 'ParallError';\n}\n\n/** The caller, as the platform vouches for it (design §2.2). */\nexport interface ActionViewer {\n id: string;\n display_name: string;\n is_agent: boolean;\n /** Organization role: owner, admin or member. */\n role: string;\n}\n\nexport interface ActionApp {\n id: string;\n version_seq: number;\n}\n\n/** A row as an object keyed by column name, in select-list order. */\nexport type ActionRow = Record<string, unknown>;\n\nexport interface ActionQueryResult {\n rows: ActionRow[];\n truncated: boolean;\n}\n\nexport interface ActionStatementResult {\n rows: ActionRow[];\n rows_affected: number;\n truncated: boolean;\n}\n\nexport interface ActionExecResult extends ActionStatementResult {\n data_seq: number;\n}\n\nexport interface ActionBatchStatement {\n sql: string;\n params?: unknown[];\n}\n\nexport interface ActionBatchResult {\n results: ActionStatementResult[];\n data_seq: number;\n}\n\n/** ctx.db: one statement per query / exec; a batch is one transaction. */\nexport interface ActionDb {\n query(sql: string, params?: unknown[]): Promise<ActionQueryResult>;\n /** Write actions only. */\n exec(sql: string, params?: unknown[]): Promise<ActionExecResult>;\n /** Write actions only; at most 50 statements, counted as one call. */\n batch(statements: ActionBatchStatement[]): Promise<ActionBatchResult>;\n}\n\nexport interface ActionClipOptions {\n /** The connection to run on: its alias or ccn_ id. The caller must be\n * allowed to use it, exactly as for their own `parall connector exec`. */\n connection: string;\n profile?: string;\n /** The command's timeout; 30 s by default, cut to what the action's\n * deadline leaves. */\n timeoutMs?: number;\n}\n\n/** ctx.clip: connector calls as the action's caller; actions that declare clip only. */\nexport interface ActionClip {\n /** Runs a command of a connector (its name or crg_ id) and returns the connector's\n * data; throws ClipError. */\n exec(clip: string, command: string, args: unknown, options: ActionClipOptions): Promise<unknown>;\n}\n\n/** A file (a chat attachment): no link, no uploader; width and height for images. */\nexport interface ParallFile {\n id: string;\n file_name: string;\n mime_type: string;\n file_size: number;\n width?: number;\n height?: number;\n}\n\n/** A task: due_date is YYYY-MM-DD or null; archived_at once it is archived. */\nexport interface ParallTask {\n id: string;\n identifier?: string;\n title: string;\n status: string;\n priority: string;\n assignee_id?: string;\n project_id?: string;\n due_date: string | null;\n created_at: string;\n updated_at: string;\n archived_at?: string;\n}\n\n/** An active member of the app's organization, person or agent; no email. */\nexport interface ParallMember {\n user_id: string;\n display_name: string;\n avatar_url?: string;\n type: 'human' | 'agent';\n role: string;\n title: string;\n joined_at: string;\n}\n\n/** One reference's answer; a refusal carries only its code: RESTRICTED (the\n * caller may not read it), NOT_FOUND (not in the app's organization: deleted,\n * another organization's, a member who left), INVALID_REF (not an att_, tsk_\n * or usr_ reference) or TOO_LARGE (past the get's 1 MiB). Others: unreadable. */\nexport type ParallItem =\n | { ok: true; type: 'file'; item: ParallFile }\n | { ok: true; type: 'task'; item: ParallTask }\n | { ok: true; type: 'member'; item: ParallMember }\n | { ok: false; code: string };\n\nexport interface ActionParall {\n /** Reads up to 100 references (prll://att_…, tsk_…, usr_… or bare IDs), one\n * item each in order, as the caller's own read now; read-only. The result\n * is the caller's view: store references, never the result across\n * invocations or in page storage. 20 gets per invocation, 10 s each. */\n get(refs: readonly string[]): Promise<ParallItem[]>;\n /** Every active member of the organization, people and agents, with a\n * get's member fields, in the order they joined; counts as one get. */\n members(): Promise<ParallMember[]>;\n}\n\n/** ctx.fetch's options: the standard ones — method, headers, body, signal,\n * redirect — and the request's timeout. Others (cache, credentials, mode,\n * the Workers `cf`) are not looked at: every request is uncached and carries\n * only what the code sets. */\nexport interface ActionFetchInit extends RequestInit {\n /** This request's timeout; 30 s by default, cut to what the action's\n * deadline leaves. With redirects, each hop has it. */\n timeoutMs?: number;\n}\n\n/** ctx.fetch: a public HTTP(S) request from the platform, recorded in the\n * app's call record (host, method, status, size and time — never the query\n * string, headers or bodies). A local run (`parall app action run --local`,\n * `parall app dev`) sends it straight from your machine and records nothing.\n * Redirects are followed up to 5 times: within the same origin as Fetch\n * does; to another origin with only Accept, Accept-Language,\n * Content-Language and User-Agent kept, and not at all when the next request\n * would carry the body (307, 308, and 301 / 302 for a method other than GET,\n * HEAD or POST) or when it would go from https: to http: — then the redirect\n * itself comes back. Each hop is a request of its own and counts toward the\n * invocation's request limit (20 by default). At most 4 requests (by\n * default) run at once; more wait their turn. Request and answer bodies are\n * at most 1 MiB each. */\nexport type ActionFetch = (\n input: string | URL | Request,\n init?: ActionFetchInit,\n) => Promise<Response>;\n\nexport interface ActionContext {\n viewer: ActionViewer;\n app: ActionApp;\n db: ActionDb;\n clip: ActionClip;\n fetch: ActionFetch;\n parall: ActionParall;\n /** The app's secrets by name; read-only. Online they are the org shared\n * secrets an org owner or admin gave this app; a local run (`parall app\n * action run --local`) reads the project's .dev.vars instead. Never pass\n * them as params or write them to the Database or a result. */\n env: Readonly<Record<string, string>>;\n}\n\n// biome-ignore lint/suspicious/noExplicitAny: the platform validates params against the declared schema before the call\nexport type ActionFunction = (ctx: ActionContext, params: any) => unknown;\n\n/** What the loader passes run() (ts/actions-worker src/run.ts). A loader\n * before the network sends neither env nor net_in_flight. */\nexport interface ActionRunRequest {\n action: string;\n params: unknown;\n viewer: ActionViewer;\n app: ActionApp;\n env?: Record<string, string>;\n /** How many requests the handle takes at once. */\n net_in_flight?: number;\n}\n\n/** The only two shapes the loader accepts back (ts/actions-worker src/outcome.ts). */\nexport type ActionRunResult =\n | { ok: true; json: string }\n | { ok: false; error: { kind: 'action_error' | 'unexpected'; message: string; stack?: string } };\n\n/** What a handle method resolves to. Failures travel as values because\n * Workers RPC keeps only an exception's name and message (design §6). */\nexport type ActionHandleResult =\n | { ok: true; value: unknown }\n | { ok: false; error: { code: string; message: string } };\n\n/** What the handle's clip method takes. */\nexport interface ActionHandleClipRequest {\n clip: string;\n command: string;\n args?: unknown;\n connection: string;\n profile?: string;\n timeout_ms?: number;\n}\n\n/** What the handle's request method takes: one request, rebuilt by the\n * loader from exactly these fields. */\nexport interface ActionHandleNetRequest {\n url: string;\n method: string;\n headers: [string, string][];\n body: ArrayBuffer | null;\n timeout_ms?: number;\n}\n\n/** What it answers with on success: the answer, never followed. */\nexport interface ActionHandleNetAnswer {\n status: number;\n status_text: string;\n headers: [string, string][];\n body: ArrayBuffer | null;\n}\n\n/** The per-invocation handle the loader passes run(). Loaders older than Clip\n * calls, the network, Parall reads or the member list lack clip, request,\n * parall or parallMembers. */\nexport interface ActionHandle {\n query(sql: string, params: unknown[]): Promise<ActionHandleResult>;\n exec(sql: string, params: unknown[]): Promise<ActionHandleResult>;\n batch(statements: ActionBatchStatement[]): Promise<ActionHandleResult>;\n clip?(req: ActionHandleClipRequest): Promise<ActionHandleResult>;\n request?(req: ActionHandleNetRequest): Promise<ActionHandleResult>;\n parall?(req: { refs: string[] }): Promise<ActionHandleResult>;\n parallMembers?(): Promise<ActionHandleResult>;\n}\n\n/** What defineActions returns; export it as `ActionRunner`. */\nexport interface ActionRunnerClass {\n /** The actions the module implements, sorted; `parall app check` compares\n * them with the manifest. */\n readonly actions: readonly string[];\n new (\n ctx: unknown,\n env: unknown,\n ): { run(req: ActionRunRequest, handle: ActionHandle): Promise<ActionRunResult> };\n}\n\nfunction unwrap(result: ActionHandleResult): unknown {\n if (result?.ok === true) return result.value;\n if (result?.ok === false) throw new ActionDbError(result.error.code, result.error.message);\n throw new ActionDbError(\n 'ACTION_DB_UNAVAILABLE',\n 'the database handle answered in an unknown shape',\n );\n}\n\nfunction unwrapClip(result: ActionHandleResult): unknown {\n if (result?.ok === true) return result.value;\n if (result?.ok === false) throw new ClipError(result.error.code, result.error.message);\n throw new ClipError(\n 'OUTCOME_UNKNOWN',\n 'the connector call answered in an unknown shape; it may or may not have run',\n );\n}\n\nfunction unwrapParall(result: ActionHandleResult): unknown[] {\n if (result?.ok === false) throw new ParallError(result.error.code, result.error.message);\n if (result?.ok === true && Array.isArray(result.value)) return result.value;\n throw new ParallError('PARALL_READ_UNAVAILABLE', 'the read answered in an unknown shape');\n}\n\n/** One read (the handle checks it). Over RPC the handle is a stub that takes\n * any name for a method, so a loader without this one refuses the call. */\nasync function readParall(read: () => Promise<ActionHandleResult>): Promise<ActionHandleResult> {\n try {\n return await read();\n } catch {\n const message = 'this runtime cannot read Parall data yet';\n return { ok: false, error: { code: 'PARALL_READ_UNAVAILABLE', message } };\n }\n}\n\nfunction unwrapNet(result: ActionHandleResult): ActionHandleNetAnswer {\n if (result?.ok === false) throw new NetError(result.error.code, result.error.message);\n const a = (result?.ok === true ? result.value : null) as ActionHandleNetAnswer | null;\n if (\n !a ||\n typeof a.status !== 'number' ||\n !Array.isArray(a.headers) ||\n (a.body !== null && !(a.body instanceof ArrayBuffer))\n ) {\n throw new NetError(\n 'NET_FAILED',\n 'the request answered in an unknown shape; it may have reached the server',\n );\n }\n return a;\n}\n\n// Statuses whose Response has no body (Fetch's null body status).\nconst NULL_BODY_STATUS = new Set([101, 103, 204, 205, 304]);\nconst REDIRECT_STATUS = new Set([301, 302, 303, 307, 308]);\n// What a redirect to another origin keeps of the author's headers\n// (mini-app-network-design.md §4): a key may be in any other one.\nconst CROSS_ORIGIN_HEADERS = new Set([\n 'accept',\n 'accept-language',\n 'content-language',\n 'user-agent',\n]);\n// Dropped with the body when a redirect turns the request into a GET.\nconst BODY_HEADERS = new Set([\n 'content-encoding',\n 'content-language',\n 'content-location',\n 'content-type',\n]);\nconst MAX_REDIRECTS = 5;\nconst DEFAULT_IN_FLIGHT = 4;\n\n/** One request of a ctx.fetch: the first, or a redirect's next hop. */\ninterface Hop {\n url: string;\n method: string;\n headers: [string, string][];\n body: ArrayBuffer | null;\n}\n\nfunction headerPairs(headers: Headers): [string, string][] {\n const out: [string, string][] = [];\n headers.forEach((value, name) => {\n out.push([name, value]);\n });\n return out;\n}\n\n/** The first hop, as a standard Request reads the input and init — only\n * the method, headers and body are taken from them. */\nasync function firstHop(input: string | URL | Request, init: ActionFetchInit | undefined) {\n let request: Request;\n try {\n request = new Request(input, {\n method: init?.method,\n headers: init?.headers,\n body: init?.body,\n });\n } catch (err) {\n throw new NetError(\n 'ACTION_INVALID_CALL',\n `ctx.fetch: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n const hop: Hop = {\n url: request.url,\n method: request.method,\n headers: headerPairs(request.headers),\n body: request.body ? await request.arrayBuffer() : null,\n };\n const fromInput = typeof input === 'object' && 'redirect' in input ? input.redirect : undefined;\n return {\n hop,\n redirect: (init?.redirect ?? fromInput ?? 'follow') as RequestRedirect,\n signal: init?.signal ?? (input instanceof Request ? input.signal : null),\n };\n}\n\n/** The next hop for a redirect, or null when it is not to be followed\n * (mini-app-network-design.md §4). The handle checks the address of every\n * hop as it does the first: an IP address or loopback name in the Location,\n * or the platform, is refused there; a name that resolves to a private\n * address is left to Cloudflare's edge (status 530). */\nfunction nextHop(hop: Hop, status: number, location: string | undefined): Hop | null {\n if (!REDIRECT_STATUS.has(status) || location === undefined) return null;\n let from: URL;\n let to: URL;\n try {\n from = new URL(hop.url);\n to = new URL(location, hop.url);\n } catch {\n return null;\n }\n if (from.protocol === 'https:' && to.protocol === 'http:') return null;\n const sameOrigin = to.origin === from.origin && to.origin !== 'null';\n const toGet =\n (status === 303 && hop.method !== 'GET' && hop.method !== 'HEAD') ||\n ((status === 301 || status === 302) && hop.method === 'POST');\n if (!sameOrigin) {\n // The next request would carry the body to another origin.\n if (status === 307 || status === 308) return null;\n if ((status === 301 || status === 302) && !['GET', 'HEAD', 'POST'].includes(hop.method)) {\n return null;\n }\n }\n let { method, headers, body } = hop;\n if (toGet) {\n method = 'GET';\n body = null;\n headers = headers.filter(([name]) => !BODY_HEADERS.has(name.toLowerCase()));\n }\n if (!sameOrigin)\n headers = headers.filter(([name]) => CROSS_ORIGIN_HEADERS.has(name.toLowerCase()));\n return { url: to.href, method, headers, body };\n}\n\nfunction toResponse(answer: ActionHandleNetAnswer, hop: Hop, redirected: boolean): Response {\n if (answer.status < 200 || answer.status > 599) {\n throw new NetError('NET_FAILED', `the server answered with status ${answer.status}`);\n }\n // As Fetch does: no body for a HEAD request or a null body status.\n const body = hop.method === 'HEAD' || NULL_BODY_STATUS.has(answer.status) ? null : answer.body;\n let res: Response;\n try {\n res = new Response(body, {\n status: answer.status,\n statusText: answer.status_text,\n headers: answer.headers,\n });\n } catch {\n try {\n res = new Response(body, { status: answer.status, headers: answer.headers });\n } catch {\n throw new NetError('NET_FAILED', 'the answer could not be read');\n }\n }\n // As a fetch Response: the URL that answered, and whether it was reached\n // through a redirect.\n Object.defineProperty(res, 'url', { value: hop.url });\n if (redirected) Object.defineProperty(res, 'redirected', { value: true });\n return res;\n}\n\n/** p, or the signal's reason as soon as it aborts. A request already at\n * the handle runs on, and the loader waits for it before answering; one\n * still waiting for its turn is never sent. */\nfunction abortable<T>(p: Promise<T>, signal: AbortSignal | null | undefined): Promise<T> {\n if (!signal) return p;\n if (signal.aborted) return Promise.reject(signal.reason);\n return new Promise<T>((resolve, reject) => {\n const onAbort = () => reject(signal.reason);\n signal.addEventListener('abort', onAbort, { once: true });\n p.then(\n (v) => {\n signal.removeEventListener('abort', onAbort);\n resolve(v);\n },\n (e) => {\n signal.removeEventListener('abort', onAbort);\n reject(e);\n },\n );\n });\n}\n\n/** ctx.env: the secrets as a frozen object of strings. */\nfunction envOf(raw: unknown): Readonly<Record<string, string>> {\n const entries =\n raw && typeof raw === 'object' && !Array.isArray(raw)\n ? Object.entries(raw).filter((e): e is [string, string] => typeof e[1] === 'string')\n : [];\n return Object.freeze(Object.fromEntries(entries));\n}\n\nfunction failure(err: unknown): ActionRunResult {\n if (err instanceof ActionError || (err instanceof Error && err.name === 'ActionError')) {\n return { ok: false, error: { kind: 'action_error', message: err.message } };\n }\n const e = err instanceof Error ? err : new Error(String(err));\n const coded = [ActionDbError, ClipError, NetError, ParallError].some((c) => e instanceof c);\n const label = coded ? `${e.name} ${(e as ParallError).code}` : e.name;\n return {\n ok: false,\n error: { kind: 'unexpected', message: `${label}: ${e.message}`, stack: e.stack ?? '' },\n };\n}\n\n/** A database call as the author's code holds it. It notes whether the code\n * attached a rejection handler anywhere along its chain — `await`,\n * `try`/`catch`, `.catch()`, `.then(f).catch(g)`, `Promise.all` all do — so\n * a failure nobody looked at fails the action instead of being lost.\n * Promises derived from a call point back to it. */\nclass DbCall<T> extends Promise<T> {\n handled = false;\n origin?: DbCall<unknown>;\n #inFinally = false;\n\n override then<R1 = T, R2 = never>(\n onFulfilled?: ((value: T) => R1 | PromiseLike<R1>) | null,\n onRejected?: ((reason: unknown) => R2 | PromiseLike<R2>) | null,\n ): Promise<R1 | R2> {\n const origin = this.origin ?? this;\n if (typeof onRejected === 'function' && !this.#inFinally) origin.handled = true;\n const derived = super.then(onFulfilled, onRejected) as DbCall<R1 | R2>;\n derived.origin = origin;\n return derived;\n }\n\n // finally() calls then() with a rejection handler that throws the failure\n // on: it handles nothing. A catch on what it returns still counts.\n override finally(onFinally?: (() => void) | null): Promise<T> {\n this.#inFinally = true;\n try {\n return super.finally(onFinally);\n } finally {\n this.#inFinally = false;\n }\n }\n}\n\n// The wrapper's own bookkeeping on a DbCall, which must not count as the\n// author handling it.\nconst observe = Promise.prototype.then as <T>(\n this: Promise<T>,\n onFulfilled: (value: T) => unknown,\n onRejected?: (reason: unknown) => unknown,\n) => Promise<unknown>;\n\n/** Wraps the author's functions into the module entry the loader calls. */\nexport function defineActions(actions: Record<string, ActionFunction>): ActionRunnerClass {\n const names = Object.keys(actions).sort();\n // Not named ActionRunner: the author's export usually is, and a bundler\n // would rename this class to tell the two apart.\n class ActionEntrypoint extends WorkerEntrypoint {\n static readonly actions: readonly string[] = names;\n\n async run(req: ActionRunRequest, handle: ActionHandle): Promise<ActionRunResult> {\n // Database calls still in flight are waited for before answering — a\n // write the author forgot to await commits before the caller has the\n // result. Calls started from a finishing call are waited for too; the\n // loader refuses any that arrive after run() returns.\n const pending = new Set<Promise<unknown>>();\n const failed = new Map<DbCall<unknown>, unknown>();\n const track = <T>(\n call: Promise<ActionHandleResult>,\n open: (result: ActionHandleResult) => unknown = unwrap,\n ): Promise<T> => {\n const dbCall = new DbCall<T>((resolve, reject) => {\n call.then(open).then(resolve as (value: unknown) => void, reject);\n });\n const settled = observe.call(\n dbCall,\n () => undefined,\n (err) => {\n failed.set(dbCall, err);\n },\n );\n pending.add(settled);\n observe.call(settled, () => pending.delete(settled));\n return dbCall;\n };\n const drain = async () => {\n while (pending.size > 0) await Promise.allSettled([...pending]);\n };\n const db: ActionDb = {\n query: (sql, params = []) => track(handle.query(sql, params)),\n exec: (sql, params = []) => track(handle.exec(sql, params)),\n batch: (statements) => track(handle.batch(statements)),\n };\n // Clip calls are tracked like database calls: waited for before the\n // answer, and a failure nobody looked at fails the action.\n const clip: ActionClip = {\n exec: (clipName, command, args, options) => {\n const request: ActionHandleClipRequest = {\n clip: clipName,\n command,\n args,\n connection: options?.connection,\n profile: options?.profile,\n timeout_ms: options?.timeoutMs,\n };\n const sent =\n typeof handle.clip === 'function'\n ? handle.clip(request)\n : Promise.resolve<ActionHandleResult>({\n ok: false,\n error: {\n code: 'CLIP_UNAVAILABLE',\n message: 'this runtime cannot call connectors yet',\n },\n });\n return track(sent, unwrapClip);\n },\n };\n // Outbound requests: one handle call per hop, at most net_in_flight at\n // once (more wait their turn), tracked like database calls.\n const limit = Math.max(1, req.net_in_flight || DEFAULT_IN_FLIGHT);\n let active = 0;\n const waiting: (() => void)[] = [];\n const send = async (hop: Hop, timeoutMs: number | undefined, signal: AbortSignal | null) => {\n while (active >= limit) await new Promise<void>((resume) => waiting.push(resume));\n active++;\n try {\n // Aborted while it waited for its turn (the code has already had\n // the abort): it is never sent, and the turn passes on.\n if (signal?.aborted) throw signal.reason;\n if (typeof handle.request !== 'function') {\n throw new NetError('NET_UNAVAILABLE', 'this runtime cannot make requests yet');\n }\n return unwrapNet(\n await handle.request({\n ...hop,\n ...(timeoutMs === undefined ? {} : { timeout_ms: timeoutMs }),\n }),\n );\n } finally {\n active--;\n waiting.shift()?.();\n }\n };\n const request = async (input: string | URL | Request, init?: ActionFetchInit) => {\n const first = await firstHop(input, init);\n const { redirect, signal } = first;\n let hop = first.hop;\n for (let followed = 0; ; followed++) {\n // Aborted before this hop: it is never asked for.\n if (signal?.aborted) throw signal.reason;\n const answer = await abortable(send(hop, init?.timeoutMs, signal), signal);\n if (redirect !== 'manual' && REDIRECT_STATUS.has(answer.status)) {\n if (redirect === 'error') {\n throw new NetError(\n 'NET_FAILED',\n `the server redirected (${answer.status}) and redirect is \"error\"`,\n );\n }\n const location = answer.headers.find(\n ([name]) => name.toLowerCase() === 'location',\n )?.[1];\n const next = nextHop(hop, answer.status, location);\n if (next) {\n if (followed >= MAX_REDIRECTS) {\n throw new NetError(\n 'ACTION_LIMIT_EXCEEDED',\n `ctx.fetch follows at most ${MAX_REDIRECTS} redirects`,\n );\n }\n hop = next;\n continue;\n }\n }\n return toResponse(answer, hop, followed > 0);\n }\n };\n const ctxFetch: ActionFetch = (input, init) =>\n track<Response>(\n request(input, init).then((res) => ({ ok: true, value: res }) as ActionHandleResult),\n (result) => (result as { value: unknown }).value,\n );\n const reads = handle as Required<ActionHandle>;\n const read = <T>(r: () => Promise<ActionHandleResult>) =>\n track<T>(readParall(r), unwrapParall);\n const parall: ActionParall = {\n get: (refs) => read<ParallItem[]>(() => reads.parall({ refs: refs as string[] })),\n members: () => read<ParallMember[]>(() => reads.parallMembers()),\n };\n const env = envOf(req.env);\n try {\n const fn = Object.hasOwn(actions, req.action) ? actions[req.action] : undefined;\n if (typeof fn !== 'function') {\n throw new Error(\n `this module does not implement the action ${JSON.stringify(req.action)}`,\n );\n }\n const value = await fn(\n { viewer: req.viewer, app: req.app, db, clip, fetch: ctxFetch, parall, env },\n req.params,\n );\n await drain();\n // A call that failed while the code never looked at it (a forgotten\n // await) fails the action: answering ok would claim a write that did\n // not happen.\n for (const [dbCall, err] of failed) if (!dbCall.handled) throw err;\n const json = JSON.stringify(value === undefined ? null : value);\n if (typeof json !== 'string') {\n throw new TypeError('the action returned a value JSON cannot represent');\n }\n return { ok: true, json };\n } catch (err) {\n await drain();\n return failure(err);\n }\n }\n }\n return ActionEntrypoint;\n}\n";
@@ -1,4 +1,4 @@
1
1
  export declare const LOCAL_RUNNER_COMPATIBILITY_DATE = "2026-04-01";
2
2
  export declare const LOCAL_RUNNER_BLOCKED_HOSTS = "parall.com,ponderai.workers.dev,prll.sh";
3
- export declare const LOCAL_RUNNER_SOURCE = "// ../actions-worker/src/contract.ts\nvar DEFAULT_NET_IN_FLIGHT = 4;\nvar INSTANCE = /^(default|pr-\\d{1,6})$/;\nvar APP_ID = /^app_[0-9a-z]{21}$/;\nvar SHA256 = /^[0-9a-f]{64}$/;\nvar ACTION_NAME = /^[a-zA-Z][a-zA-Z0-9_]{0,63}$/;\nvar INVOCATION_ID = /^[0-9A-Za-z_-]{1,64}$/;\nvar LIMIT_CEILINGS = {\n cpu_ms: 3e4,\n db_calls: 1e3,\n batch_statements: 1e3,\n batch_bytes: 8 * 1024 * 1024,\n result_bytes: 8 * 1024 * 1024,\n message_bytes: 64 * 1024,\n stack_bytes: 256 * 1024\n};\nvar CLIP_CALLS_CEILING = 100;\nvar NET_REQUESTS_CEILING = 100;\nvar NET_IN_FLIGHT_CEILING = 6;\nvar PARALL_READS_CEILING = 100;\nvar ENV_NAME = /^[A-Z_][A-Z0-9_]{0,127}$/;\nvar ENV_CEILING_BYTES = 256 * 1024;\nfunction isRecord(v) {\n return typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\nfunction positiveInt(v, max) {\n return typeof v === \"number\" && Number.isInteger(v) && v > 0 && v <= max;\n}\nfunction intInRange(v, min, max) {\n return typeof v === \"number\" && Number.isInteger(v) && v >= min && v <= max;\n}\nvar envEncoder = new TextEncoder();\nfunction validEnv(v) {\n if (!isRecord(v)) return false;\n let total = 0;\n for (const [name, value] of Object.entries(v)) {\n if (!ENV_NAME.test(name) || typeof value !== \"string\") return false;\n total += envEncoder.encode(name).byteLength + envEncoder.encode(value).byteLength;\n if (total > ENV_CEILING_BYTES) return false;\n }\n return true;\n}\nfunction parseInvokeRequest(raw, opts = {}) {\n if (!isRecord(raw)) return \"body is not an object\";\n const {\n invocation_id,\n instance,\n app,\n module,\n action,\n kind,\n clip,\n viewer,\n ticket,\n deadline_ms,\n limits\n } = raw;\n if (typeof invocation_id !== \"string\" || !INVOCATION_ID.test(invocation_id))\n return \"invocation_id\";\n if (typeof instance !== \"string\" || !INSTANCE.test(instance)) return \"instance\";\n if (!isRecord(app) || typeof app.id !== \"string\" || !APP_ID.test(app.id)) return \"app.id\";\n if (!(opts.unpublished && app.version_seq === 0) && !positiveInt(app.version_seq, 2 ** 31))\n return \"app.version_seq\";\n if (!isRecord(module) || typeof module.sha256 !== \"string\" || !SHA256.test(module.sha256))\n return \"module.sha256\";\n if (typeof action !== \"string\" || !ACTION_NAME.test(action)) return \"action\";\n if (kind !== \"read\" && kind !== \"write\") return \"kind\";\n if (clip !== void 0 && clip !== false && !(clip === true && kind === \"write\")) return \"clip\";\n if (!(\"params\" in raw)) return \"params\";\n if (!isRecord(viewer) || typeof viewer.id !== \"string\" || typeof viewer.display_name !== \"string\" || typeof viewer.is_agent !== \"boolean\" || typeof viewer.role !== \"string\") {\n return \"viewer\";\n }\n if (typeof ticket !== \"string\" || ticket.length === 0 || ticket.length > 4096) return \"ticket\";\n if (typeof deadline_ms !== \"number\" || !Number.isFinite(deadline_ms)) return \"deadline_ms\";\n if (!isRecord(limits)) return \"limits\";\n for (const key of Object.keys(LIMIT_CEILINGS)) {\n if (!positiveInt(limits[key], LIMIT_CEILINGS[key])) return `limits.${key}`;\n }\n const clipCalls = limits.clip_calls ?? 0;\n if (clipCalls !== 0 && !positiveInt(clipCalls, CLIP_CALLS_CEILING)) return \"limits.clip_calls\";\n const netRequests = limits.net_requests ?? 0;\n if (!intInRange(netRequests, 0, NET_REQUESTS_CEILING)) return \"limits.net_requests\";\n const netInFlight = limits.net_in_flight ?? DEFAULT_NET_IN_FLIGHT;\n if (!intInRange(netInFlight, 0, NET_IN_FLIGHT_CEILING) || netRequests > 0 && netInFlight === 0) {\n return \"limits.net_in_flight\";\n }\n if (!intInRange(limits.parall_reads ?? 0, 0, PARALL_READS_CEILING)) return \"limits.parall_reads\";\n if (raw.env !== void 0 && raw.env !== null && !validEnv(raw.env)) return \"env\";\n return {\n invocation_id,\n instance,\n app: { id: app.id, version_seq: app.version_seq },\n module: { sha256: module.sha256 },\n action,\n kind,\n clip: clip === true,\n params: raw.params,\n viewer: {\n id: viewer.id,\n display_name: viewer.display_name,\n is_agent: viewer.is_agent,\n role: viewer.role\n },\n ticket,\n deadline_ms,\n limits: { ...limits, clip_calls: clipCalls },\n ...raw.env === null ? { env: null } : {},\n ...isRecord(raw.env) ? { env: { ...raw.env } } : {}\n };\n}\nfunction parallReads(limits) {\n return limits.parall_reads ?? 0;\n}\nfunction netLimits(limits) {\n return {\n requests: limits.net_requests ?? 0,\n inFlight: limits.net_in_flight ?? DEFAULT_NET_IN_FLIGHT\n };\n}\n\n// ../actions-worker/src/net-address.ts\nvar BAD_PORTS = /* @__PURE__ */ new Set([\n 0,\n 1,\n 7,\n 9,\n 11,\n 13,\n 15,\n 17,\n 19,\n 20,\n 21,\n 22,\n 23,\n 25,\n 37,\n 42,\n 43,\n 53,\n 69,\n 77,\n 79,\n 87,\n 95,\n 101,\n 102,\n 103,\n 104,\n 109,\n 110,\n 111,\n 113,\n 115,\n 117,\n 119,\n 123,\n 135,\n 137,\n 139,\n 143,\n 161,\n 179,\n 389,\n 427,\n 465,\n 512,\n 513,\n 514,\n 515,\n 526,\n 530,\n 531,\n 532,\n 540,\n 548,\n 554,\n 556,\n 563,\n 587,\n 601,\n 636,\n 989,\n 990,\n 993,\n 995,\n 1719,\n 1720,\n 1723,\n 2049,\n 3659,\n 4045,\n 4190,\n 5060,\n 5061,\n 6e3,\n 6566,\n 6665,\n 6666,\n 6667,\n 6668,\n 6669,\n 6679,\n 6697,\n 10080\n]);\nvar NUMERIC_LABEL = /^(?:0x[0-9a-f]*|\\d+)$/i;\nvar HOST_NAME = /^[a-z0-9_-]+(?:\\.[a-z0-9_-]+)*$/;\nvar HOST_NAME_MAX_BYTES = 253;\nvar HOST_LABEL_MAX_BYTES = 63;\nfunction normalizeHost(host) {\n return host.toLowerCase().replace(/\\.+$/, \"\");\n}\nfunction isIpLiteral(host) {\n if (host.startsWith(\"[\") || host.includes(\":\")) return true;\n const labels = host.split(\".\");\n return NUMERIC_LABEL.test(labels[labels.length - 1] ?? \"\");\n}\nfunction isLoopbackName(host) {\n return host === \"localhost\" || host.endsWith(\".localhost\");\n}\nfunction isHostName(host) {\n return host.length <= HOST_NAME_MAX_BYTES && HOST_NAME.test(host) && host.split(\".\").every((label) => label.length <= HOST_LABEL_MAX_BYTES);\n}\nfunction isBlockedHost(host, blocked) {\n return blocked.some((name) => host === name || host.endsWith(`.${name}`));\n}\nfunction checkAddress(input, policy) {\n if (input.protocol !== \"https:\" && input.protocol !== \"http:\") {\n return { ok: false, reason: \"only https: and http: URLs can be requested\" };\n }\n if (input.username !== \"\" || input.password !== \"\") {\n return { ok: false, reason: \"a URL with credentials in it (user:pass@) cannot be requested\" };\n }\n const host = normalizeHost(input.hostname);\n if (host === \"\") return { ok: false, reason: \"the URL has no host\" };\n if (isIpLiteral(host)) {\n return { ok: false, reason: \"requests go to host names, not IP addresses\" };\n }\n if (!isHostName(host)) {\n return {\n ok: false,\n reason: `the URL host is not a host name (at most ${HOST_NAME_MAX_BYTES} bytes, ${HOST_LABEL_MAX_BYTES} per label)`\n };\n }\n if (input.port !== \"\" && BAD_PORTS.has(Number(input.port))) {\n return { ok: false, reason: `port ${input.port} cannot be requested` };\n }\n if (isLoopbackName(host) && !policy.allowLoopback) {\n return { ok: false, reason: \"loopback hosts cannot be requested\" };\n }\n if (isBlockedHost(host, policy.blockedHosts)) {\n return { ok: false, reason: \"the platform's own hosts cannot be requested\" };\n }\n const url = new URL(input.href);\n url.hostname = host;\n url.hash = \"\";\n return { ok: true, url, host: input.port === \"\" ? host : `${host}:${input.port}` };\n}\nfunction parseBlockedHosts(raw) {\n if (typeof raw !== \"string\") return null;\n const names = raw.split(\",\").map((s) => normalizeHost(s.trim())).filter((s) => s !== \"\");\n if (names.length === 0) return null;\n for (const name of names) {\n if (!isHostName(name) || isIpLiteral(name)) return null;\n }\n return names;\n}\nvar LOOPBACK_ORIGIN_HOSTS = /* @__PURE__ */ new Set([\"127.0.0.1\", \"localhost\", \"[::1]\"]);\nfunction loopbackAllowed(flag, callbackOrigin) {\n if (flag !== \"1\" && flag !== \"true\") return false;\n try {\n return LOOPBACK_ORIGIN_HOSTS.has(new URL(callbackOrigin).hostname);\n } catch {\n return false;\n }\n}\nfunction policyFrom(blockedHosts, loopbackFlag, callbackOrigin) {\n const blocked = parseBlockedHosts(blockedHosts);\n if (!blocked) return null;\n return { blockedHosts: blocked, allowLoopback: loopbackAllowed(loopbackFlag, callbackOrigin) };\n}\n\n// ../actions-worker/src/db-caller.ts\nvar USER_AGENT = \"parall-actions-worker/1\";\nvar TICKET_HEADER = \"X-Prll-Action-Ticket\";\nvar INVOCATION_HEADER = \"X-Prll-Action-Invocation\";\nvar SWIMLANE_HEADER = \"X-Prll-Swimlane\";\nvar MAX_SQL_BYTES = 256 * 1024;\nvar encoder = new TextEncoder();\nfunction handleError(code, message) {\n const err = new Error(message);\n err.name = \"ActionDbError\";\n err.code = code;\n return err;\n}\nfunction statementOf(v) {\n if (typeof v !== \"object\" || v === null) return null;\n const { sql, params } = v;\n if (typeof sql !== \"string\" || sql.length === 0 || encoder.encode(sql).byteLength > MAX_SQL_BYTES)\n return null;\n if (params !== void 0 && !Array.isArray(params)) return null;\n return { sql, params: params ?? [] };\n}\nfunction requestBody(op, payload, limits) {\n if (op === \"batch\") {\n const statements = payload?.statements;\n if (!Array.isArray(statements) || statements.length === 0) {\n throw handleError(\"ACTION_INVALID_CALL\", \"batch needs a non-empty array of { sql, params }\");\n }\n if (statements.length > limits.batch_statements) {\n throw handleError(\n \"ACTION_LIMIT_EXCEEDED\",\n `a batch may hold at most ${limits.batch_statements} statements`\n );\n }\n const parsed = statements.map(statementOf);\n if (parsed.some((s) => s === null)) {\n throw handleError(\n \"ACTION_INVALID_CALL\",\n \"every batch entry needs a non-empty sql string and a params array\"\n );\n }\n const body = JSON.stringify({ statements: parsed });\n if (encoder.encode(body).byteLength > limits.batch_bytes) {\n throw handleError(\n \"ACTION_LIMIT_EXCEEDED\",\n `a batch may be at most ${limits.batch_bytes} bytes`\n );\n }\n return body;\n }\n const statement = statementOf(payload);\n if (!statement)\n throw handleError(\n \"ACTION_INVALID_CALL\",\n `${op} needs a non-empty sql string and a params array`\n );\n return JSON.stringify(statement);\n}\nfunction trackDataSeq(state, result) {\n const seq = result?.data_seq;\n if (typeof seq !== \"number\" || !Number.isInteger(seq)) return;\n state.dataSeq = state.dataSeq ? { from: Math.min(state.dataSeq.from, seq), to: Math.max(state.dataSeq.to, seq) } : { from: seq, to: seq };\n}\nasync function readCapped(res, maxBytes) {\n if (!res.body) return \"\";\n const reader = res.body.getReader();\n const chunks = [];\n let total = 0;\n for (; ; ) {\n const { done, value } = await reader.read();\n if (done) break;\n total += value.byteLength;\n if (total > maxBytes) {\n await reader.cancel();\n throw handleError(\n \"ACTION_RESULT_TOO_LARGE\",\n `a database result may be at most ${maxBytes} bytes`\n );\n }\n chunks.push(value);\n }\n const out = new Uint8Array(total);\n let off = 0;\n for (const c of chunks) {\n out.set(c, off);\n off += c.byteLength;\n }\n return new TextDecoder().decode(out);\n}\nfunction createDbCaller(cfg) {\n const fetchImpl = cfg.fetchImpl ?? fetch;\n const now = cfg.now ?? Date.now;\n const state = {\n revoked: false,\n calls: 0,\n limitHit: false,\n inflight: /* @__PURE__ */ new Set(),\n dataSeq: null,\n indeterminate: false,\n clipCalls: 0,\n clipLimitHit: false,\n netRequests: 0,\n netLimitHit: false,\n netInFlight: 0,\n netCalls: [],\n parallReads: 0,\n parallLimitHit: false\n };\n const origin = cfg.callbackOrigin.replace(/\\/+$/, \"\");\n async function send(op, body) {\n const headers = {\n \"Content-Type\": \"application/json\",\n \"User-Agent\": USER_AGENT,\n [TICKET_HEADER]: cfg.ticket,\n [INVOCATION_HEADER]: cfg.invocationId\n };\n if (cfg.instance !== \"default\") headers[SWIMLANE_HEADER] = cfg.instance;\n const remaining = Math.max(1, cfg.deadlineMs - now());\n let res;\n try {\n res = await fetchImpl(`${origin}/api/v1/mini-app-actions/db/${op}`, {\n method: \"POST\",\n headers,\n body,\n signal: AbortSignal.timeout(remaining)\n });\n } catch {\n if (op !== \"query\") state.indeterminate = true;\n throw handleError(\"ACTION_DB_UNAVAILABLE\", \"the database could not be reached\");\n }\n let parsed;\n try {\n const text = await readCapped(res, cfg.limits.result_bytes + 64 * 1024);\n parsed = text ? JSON.parse(text) : null;\n } catch (err) {\n if (op !== \"query\") state.indeterminate = true;\n if (err.code === \"ACTION_RESULT_TOO_LARGE\") throw err;\n throw handleError(\"ACTION_DB_UNAVAILABLE\", \"the database returned an unreadable response\");\n }\n if (!res.ok) {\n const env = parsed?.error;\n if (typeof env?.code !== \"string\") {\n if (op !== \"query\") state.indeterminate = true;\n throw handleError(`HTTP_${res.status}`, `database call failed (${res.status})`);\n }\n const message = typeof env.message === \"string\" ? env.message : `database call failed (${res.status})`;\n throw handleError(env.code, message);\n }\n trackDataSeq(state, parsed);\n return parsed;\n }\n async function call(op, payload) {\n if (state.revoked)\n throw handleError(\"ACTION_HANDLE_REVOKED\", \"this database handle is no longer valid\");\n if (now() >= cfg.deadlineMs)\n throw handleError(\"ACTION_DEADLINE\", \"the action ran past its deadline\");\n if (cfg.kind === \"read\" && op !== \"query\") {\n throw handleError(\"ACTION_READ_ONLY\", \"a read action can only query\");\n }\n state.calls++;\n if (state.calls > cfg.limits.db_calls) {\n state.limitHit = true;\n throw handleError(\n \"ACTION_LIMIT_EXCEEDED\",\n `an action may make at most ${cfg.limits.db_calls} database calls`\n );\n }\n const body = requestBody(op, payload, cfg.limits);\n const pending = send(op, body);\n state.inflight.add(pending);\n try {\n return await pending;\n } finally {\n state.inflight.delete(pending);\n }\n }\n return { state, call };\n}\nfunction settleCall(caller, op, payload) {\n return settleWith(\n () => caller.call(op, payload),\n \"ACTION_DB_UNAVAILABLE\",\n \"the database call failed\"\n );\n}\nasync function settleWith(run, fallbackCode, fallbackMessage) {\n try {\n return { ok: true, value: await run() };\n } catch (err) {\n const { code, message } = err ?? {};\n return {\n ok: false,\n error: {\n code: typeof code === \"string\" ? code : fallbackCode,\n message: typeof message === \"string\" ? message : fallbackMessage\n }\n };\n }\n}\nasync function settle(caller, deadlineMs, now = Date.now) {\n caller.state.revoked = true;\n const inflight = [...caller.state.inflight];\n if (inflight.length === 0) return true;\n const remaining = deadlineMs - now();\n if (remaining > 0) {\n let timer = null;\n await Promise.race([\n Promise.allSettled(inflight),\n new Promise((r) => {\n timer = setTimeout(r, remaining);\n })\n ]);\n if (timer !== null) clearTimeout(timer);\n }\n return caller.state.inflight.size === 0;\n}\n\n// ../actions-worker/src/clip-caller.ts\nvar ENVELOPE_BYTES = 64 * 1024;\nvar MAX_FIELD_BYTES = 256;\nvar encoder2 = new TextEncoder();\nfunction unknownOutcome() {\n return handleError(\n \"OUTCOME_UNKNOWN\",\n \"the Clip call\\u2019s answer was lost \\u2014 it may or may not have run; do not retry it blindly\"\n );\n}\nfunction field(v, required) {\n if (v === void 0 || v === null) return required ? null : void 0;\n if (typeof v !== \"string\" || encoder2.encode(v).byteLength > MAX_FIELD_BYTES) return null;\n if (required && v.trim() === \"\") return null;\n return v;\n}\nfunction requestBody2(req, seq, maxBytes) {\n const r = typeof req === \"object\" && req !== null ? req : {};\n const clip = field(r.clip, true);\n const command = field(r.command, true);\n const connection = field(r.connection, false);\n const profile = field(r.profile, false);\n const timeout = r.timeout_ms;\n if (clip === null || command === null || connection === null || profile === null) {\n throw handleError(\n \"ACTION_INVALID_CALL\",\n \"clip.exec needs a Clip name or id, a command, and string connection and profile options of at most 256 bytes\"\n );\n }\n if (timeout !== void 0 && (typeof timeout !== \"number\" || !Number.isInteger(timeout) || timeout <= 0 || timeout > 12e4)) {\n throw handleError(\n \"ACTION_INVALID_CALL\",\n \"timeoutMs must be a whole number of milliseconds from 1 to 120000\"\n );\n }\n let body;\n try {\n body = JSON.stringify({\n seq,\n clip,\n command,\n args: r.args,\n connection: connection ?? \"\",\n profile,\n timeout_ms: timeout\n });\n } catch {\n throw handleError(\"ACTION_INVALID_CALL\", \"the Clip arguments cannot be sent as JSON\");\n }\n if (encoder2.encode(body).byteLength > maxBytes) {\n throw handleError(\n \"ACTION_LIMIT_EXCEEDED\",\n `a Clip call's arguments may be at most ${maxBytes} bytes`\n );\n }\n return body;\n}\nfunction createClipCaller(cfg, state) {\n const fetchImpl = cfg.fetchImpl ?? fetch;\n const now = cfg.now ?? Date.now;\n const url = `${cfg.callbackOrigin.replace(/\\/+$/, \"\")}/api/v1/mini-app-actions/clip/exec`;\n async function send(body) {\n const headers = {\n \"Content-Type\": \"application/json\",\n \"User-Agent\": USER_AGENT,\n [TICKET_HEADER]: cfg.ticket,\n [INVOCATION_HEADER]: cfg.invocationId\n };\n if (cfg.instance !== \"default\") headers[SWIMLANE_HEADER] = cfg.instance;\n let res;\n try {\n res = await fetchImpl(url, {\n method: \"POST\",\n headers,\n body,\n signal: AbortSignal.timeout(Math.max(1, cfg.deadlineMs - now()))\n });\n } catch {\n throw unknownOutcome();\n }\n let parsed;\n try {\n const text = await readCapped(res, cfg.maxBytes + ENVELOPE_BYTES);\n parsed = text ? JSON.parse(text) : null;\n } catch {\n throw unknownOutcome();\n }\n if (res.ok) {\n const a = parsed;\n if (a?.ok === true) return a.value ?? null;\n if (a?.ok === false && typeof a.error?.code === \"string\") {\n throw handleError(\n a.error.code,\n typeof a.error.message === \"string\" ? a.error.message : a.error.code\n );\n }\n throw unknownOutcome();\n }\n const env = parsed?.error;\n if (typeof env?.code !== \"string\") throw unknownOutcome();\n throw handleError(\n env.code,\n typeof env.message === \"string\" ? env.message : `Clip call refused (${res.status})`\n );\n }\n async function call(req) {\n if (state.revoked) throw handleError(\"ACTION_HANDLE_REVOKED\", \"this handle is no longer valid\");\n if (!cfg.enabled) {\n throw handleError(\n \"CLIP_NOT_DECLARED\",\n \"this action does not declare clip, so it cannot call Clip\"\n );\n }\n if (now() >= cfg.deadlineMs)\n throw handleError(\"ACTION_DEADLINE\", \"the action ran past its deadline\");\n if (state.clipCalls >= cfg.maxCalls) {\n state.clipLimitHit = true;\n throw handleError(\n \"ACTION_LIMIT_EXCEEDED\",\n `an action may make at most ${cfg.maxCalls} Clip calls`\n );\n }\n const body = requestBody2(req, state.clipCalls + 1, cfg.maxBytes);\n state.clipCalls++;\n const pending = send(body);\n state.inflight.add(pending);\n try {\n return await pending;\n } finally {\n state.inflight.delete(pending);\n }\n }\n return { call };\n}\n\n// ../actions-worker/src/handle.ts\nimport { RpcTarget } from \"cloudflare:workers\";\nvar ActionHandle = class extends RpcTarget {\n #caller;\n #clip;\n #net;\n #parall;\n constructor(caller, clip, net, parall) {\n super();\n this.#caller = caller;\n this.#clip = clip;\n this.#net = net;\n this.#parall = parall;\n }\n query(sql, params) {\n return settleCall(this.#caller, \"query\", { sql, params });\n }\n exec(sql, params) {\n return settleCall(this.#caller, \"exec\", { sql, params });\n }\n batch(statements) {\n return settleCall(this.#caller, \"batch\", { statements });\n }\n clip(req) {\n return settleWith(() => this.#clip.call(req), \"CLIP_UNAVAILABLE\", \"the Clip call failed\");\n }\n request(req) {\n return settleWith(() => this.#net.request(req), \"NET_FAILED\", \"the request failed\");\n }\n parall(req) {\n return settleWith(\n () => this.#parall.get(req),\n \"PARALL_READ_UNAVAILABLE\",\n \"Parall data could not be read\"\n );\n }\n};\nfunction makeHandle(caller, clip, net, parall) {\n return new ActionHandle(caller, clip, net, parall);\n}\n\n// ../actions-worker/src/net-begin.ts\nvar BEGIN_TIMEOUT_MS = 1e4;\nvar BEGIN_ANSWER_MAX_BYTES = 64 * 1024;\nvar ERROR_CODE = /^[A-Z][A-Z0-9_]{0,63}$/;\nfunction notRegistered() {\n return handleError(\n \"NET_UNAVAILABLE\",\n \"the request could not be registered with the platform, so it was not sent\"\n );\n}\nasync function begin(target, seq, fields, timeoutMs) {\n const headers = {\n \"Content-Type\": \"application/json\",\n \"User-Agent\": USER_AGENT,\n [TICKET_HEADER]: target.ticket,\n [INVOCATION_HEADER]: target.invocationId\n };\n if (target.instance !== \"default\") headers[SWIMLANE_HEADER] = target.instance;\n const url = `${target.callbackOrigin.replace(/\\/+$/, \"\")}/api/v1/mini-app-actions/net/begin`;\n const fetchImpl = target.fetchImpl;\n let res;\n try {\n res = await fetchImpl(url, {\n method: \"POST\",\n headers,\n body: JSON.stringify({ seq, method: fields.method, host: fields.host, path: fields.path }),\n signal: AbortSignal.timeout(timeoutMs)\n });\n } catch {\n throw notRegistered();\n }\n let parsed;\n try {\n const text = await readCapped(res, BEGIN_ANSWER_MAX_BYTES);\n parsed = text ? JSON.parse(text) : null;\n } catch {\n throw notRegistered();\n }\n const answer = parsed;\n if (res.status === 200 && answer?.ok === true) return;\n const error = res.ok ? answer?.ok === false ? answer.error : void 0 : answer?.error;\n if (typeof error?.code === \"string\" && ERROR_CODE.test(error.code)) {\n throw handleError(\n error.code,\n typeof error.message === \"string\" ? error.message : \"the platform refused the request\"\n );\n }\n throw notRegistered();\n}\n\n// ../actions-worker/src/net-request.ts\nvar NET_URL_MAX_BYTES = 8 * 1024;\nvar NET_HEADERS_MAX = 64;\nvar NET_HEADER_BYTES_MAX = 32 * 1024;\nvar NET_BODY_MAX_BYTES = 1024 * 1024;\nvar NET_TIMEOUT_MAX_MS = 12e4;\nvar FORBIDDEN_HEADERS = /* @__PURE__ */ new Set([\n \"host\",\n \"connection\",\n \"upgrade\",\n \"keep-alive\",\n \"te\",\n \"trailer\",\n \"transfer-encoding\"\n]);\nvar FORBIDDEN_HEADER_PREFIXES = [\"proxy-\", \"x-prll-\", \"cf-\"];\nvar DROPPED_HEADERS = /* @__PURE__ */ new Set([\"content-length\"]);\nvar METHOD = /^[!#$%&'*+.^_`|~0-9A-Za-z-]{1,16}$/;\nvar FORBIDDEN_METHODS = /* @__PURE__ */ new Set([\"CONNECT\", \"TRACE\", \"TRACK\"]);\nvar NORMALIZED_METHODS = /* @__PURE__ */ new Set([\"DELETE\", \"GET\", \"HEAD\", \"OPTIONS\", \"PATCH\", \"POST\", \"PUT\"]);\nvar HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;\nvar encoder3 = new TextEncoder();\nfunction isObject(v) {\n return typeof v === \"object\" && v !== null;\n}\nfunction normalizeMethod(method) {\n const upper = method.toUpperCase();\n return NORMALIZED_METHODS.has(upper) ? upper : method;\n}\nvar RECORD_HOST_MAX_BYTES = 300;\nfunction printableAscii(s) {\n return /^[\\x21-\\x7e]+$/.test(s);\n}\nfunction recordableHost(host) {\n return host.length <= RECORD_HOST_MAX_BYTES && printableAscii(host) && !/[/?#@\\\\]/.test(host);\n}\nfunction recordablePath(path) {\n return path.startsWith(\"/\") && path.length <= NET_URL_MAX_BYTES && printableAscii(path);\n}\nfunction describeRequest(raw) {\n const r = isObject(raw) ? raw : {};\n const fields = { method: \"\", host: \"\", path: \"\" };\n const method = r.method === void 0 ? \"GET\" : r.method;\n if (typeof method === \"string\" && METHOD.test(method)) fields.method = normalizeMethod(method);\n if (typeof r.url === \"string\" && r.url.length <= 4 * NET_URL_MAX_BYTES) {\n try {\n const url = new URL(r.url);\n const host = normalizeHost(url.hostname) + (url.port === \"\" ? \"\" : `:${url.port}`);\n if (recordableHost(host)) fields.host = host;\n if (recordablePath(url.pathname)) fields.path = url.pathname;\n } catch {\n }\n }\n return fields;\n}\nfunction readUrl(raw, policy) {\n if (typeof raw !== \"string\" || raw === \"\") {\n throw handleError(\"ACTION_INVALID_CALL\", \"a request needs an absolute http(s) URL\");\n }\n if (raw.length > 4 * NET_URL_MAX_BYTES) {\n throw handleError(\"ACTION_LIMIT_EXCEEDED\", `a URL may be at most ${NET_URL_MAX_BYTES} bytes`);\n }\n let parsed;\n try {\n parsed = new URL(raw);\n } catch {\n throw handleError(\"ACTION_INVALID_CALL\", \"a request needs an absolute http(s) URL\");\n }\n const verdict = checkAddress(parsed, policy);\n if (!verdict.ok) throw handleError(\"NET_ADDRESS_BLOCKED\", verdict.reason);\n if (encoder3.encode(verdict.url.href).byteLength > NET_URL_MAX_BYTES) {\n throw handleError(\"ACTION_LIMIT_EXCEEDED\", `a URL may be at most ${NET_URL_MAX_BYTES} bytes`);\n }\n return { url: verdict.url, host: verdict.host };\n}\nfunction readMethod(raw) {\n if (raw === void 0) return \"GET\";\n if (typeof raw !== \"string\" || !METHOD.test(raw)) {\n throw handleError(\"ACTION_INVALID_CALL\", \"the method must be an HTTP method name\");\n }\n const method = normalizeMethod(raw);\n if (FORBIDDEN_METHODS.has(method.toUpperCase())) {\n throw handleError(\"ACTION_INVALID_CALL\", `${method} requests cannot be made`);\n }\n return method;\n}\nfunction headerPairs(raw) {\n if (raw === void 0 || raw === null) return [];\n if (Array.isArray(raw)) {\n return raw.map(\n (pair) => Array.isArray(pair) && pair.length === 2 ? [pair[0], pair[1]] : [null, null]\n );\n }\n if (isObject(raw)) return Object.entries(raw);\n throw handleError(\"ACTION_INVALID_CALL\", \"headers must be [name, value] pairs or an object\");\n}\nfunction readHeaders(raw) {\n const pairs = headerPairs(raw);\n if (pairs.length > NET_HEADERS_MAX) {\n throw handleError(\n \"ACTION_LIMIT_EXCEEDED\",\n `a request may have at most ${NET_HEADERS_MAX} headers`\n );\n }\n let bytes = 0;\n const out = [];\n for (const [name, value] of pairs) {\n if (typeof name !== \"string\" || typeof value !== \"string\" || !HEADER_NAME.test(name)) {\n throw handleError(\"ACTION_INVALID_CALL\", \"each header needs a valid name and a string value\");\n }\n bytes += encoder3.encode(name).byteLength + encoder3.encode(value).byteLength;\n const lower = name.toLowerCase();\n if (FORBIDDEN_HEADERS.has(lower) || FORBIDDEN_HEADER_PREFIXES.some((prefix) => lower.startsWith(prefix))) {\n throw handleError(\"ACTION_INVALID_CALL\", `the ${name} header cannot be set`);\n }\n if (!DROPPED_HEADERS.has(lower)) out.push([name, value]);\n }\n if (bytes > NET_HEADER_BYTES_MAX) {\n throw handleError(\n \"ACTION_LIMIT_EXCEEDED\",\n `a request's headers may be at most ${NET_HEADER_BYTES_MAX} bytes in all`\n );\n }\n return out;\n}\nfunction readBody(raw, method) {\n if (raw === void 0 || raw === null) return null;\n let body;\n if (typeof raw === \"string\") body = encoder3.encode(raw);\n else if (raw instanceof ArrayBuffer) body = new Uint8Array(raw);\n else if (ArrayBuffer.isView(raw))\n body = new Uint8Array(raw.buffer, raw.byteOffset, raw.byteLength);\n else throw handleError(\"ACTION_INVALID_CALL\", \"the body must be a string or bytes\");\n if (body.byteLength > NET_BODY_MAX_BYTES) {\n throw handleError(\n \"ACTION_LIMIT_EXCEEDED\",\n `a request body may be at most ${NET_BODY_MAX_BYTES} bytes`\n );\n }\n if (method === \"GET\" || method === \"HEAD\") {\n throw handleError(\"ACTION_INVALID_CALL\", `a ${method} request cannot have a body`);\n }\n return body;\n}\nfunction readTimeout(raw) {\n if (raw === void 0 || raw === null) return null;\n if (typeof raw !== \"number\" || !Number.isInteger(raw) || raw <= 0 || raw > NET_TIMEOUT_MAX_MS) {\n throw handleError(\n \"ACTION_INVALID_CALL\",\n `timeoutMs must be a whole number of milliseconds from 1 to ${NET_TIMEOUT_MAX_MS}`\n );\n }\n return raw;\n}\nfunction parseOutgoing(raw, policy) {\n if (!isObject(raw) || Array.isArray(raw)) {\n throw handleError(\"ACTION_INVALID_CALL\", \"a request needs { url, method, headers, body }\");\n }\n const { url, host } = readUrl(raw.url, policy);\n const method = readMethod(raw.method);\n const headers = readHeaders(raw.headers);\n const body = readBody(raw.body, method);\n const timeoutMs = readTimeout(raw.timeout_ms);\n if (!recordableHost(host) || !recordablePath(url.pathname)) {\n throw handleError(\"ACTION_INVALID_CALL\", \"the request cannot be recorded, so it is not sent\");\n }\n return { url: url.href, method, host, path: url.pathname, headers, body, timeoutMs };\n}\n\n// ../actions-worker/src/net-caller.ts\nvar NET_RESPONSE_MAX_BYTES = 1024 * 1024;\nvar NET_DEFAULT_TIMEOUT_MS = 3e4;\nvar NET_DEADLINE_MARGIN_MS = 3e3;\nvar NET_MIN_TIME_MS = 1e3;\nvar LOADER_BODY_BUDGET = { limit: 32 * 1024 * 1024, used: 0 };\nfunction codeOf(err) {\n const code = err?.code;\n return typeof code === \"string\" ? code : void 0;\n}\nvar Ended = class extends Error {\n code;\n result;\n constructor(code, message, result) {\n super(message);\n this.name = \"Ended\";\n this.code = code;\n this.result = result;\n }\n};\nvar BODYLESS_STATUS = /* @__PURE__ */ new Set([204, 205, 304]);\nasync function readAnswer(res, method, max, counted) {\n const bodyless = method === \"HEAD\" || BODYLESS_STATUS.has(res.status);\n const declared = Number(res.headers.get(\"Content-Length\") ?? \"\");\n if (!bodyless && Number.isFinite(declared) && declared > max) {\n await res.body?.cancel().catch(() => {\n });\n throw handleError(\"NET_RESPONSE_TOO_LARGE\", `an answer may be at most ${max} bytes`);\n }\n if (!res.body) return new ArrayBuffer(0);\n const reader = res.body.getReader();\n const chunks = [];\n let total = 0;\n for (; ; ) {\n const { done, value } = await reader.read();\n if (done) break;\n total += value.byteLength;\n counted(total);\n if (total > max) {\n await reader.cancel().catch(() => {\n });\n throw handleError(\"NET_RESPONSE_TOO_LARGE\", `an answer may be at most ${max} bytes`);\n }\n chunks.push(value);\n }\n const out = new Uint8Array(total);\n let off = 0;\n for (const c of chunks) {\n out.set(c, off);\n off += c.byteLength;\n }\n return out.buffer;\n}\nfunction createNetCaller(cfg, state) {\n const fetchImpl = cfg.fetchImpl ?? fetch;\n const beginFetch = cfg.beginFetch ?? fetch;\n const now = cfg.now ?? Date.now;\n const budget = cfg.budget ?? LOADER_BODY_BUDGET;\n const beginTarget = {\n ticket: cfg.ticket,\n invocationId: cfg.invocationId,\n instance: cfg.instance,\n callbackOrigin: cfg.callbackOrigin,\n fetchImpl: beginFetch\n };\n function record(result) {\n if (cfg.mode === \"record\") state.netCalls.push(result);\n }\n function timeLeft() {\n return cfg.deadlineMs - NET_DEADLINE_MARGIN_MS - now();\n }\n async function send(seq, out, outbound, controller, started) {\n const base2 = {\n seq,\n method: out.method,\n host: out.host,\n path: out.path,\n request_bytes: out.body?.byteLength ?? 0\n };\n if (cfg.mode === \"record\") {\n try {\n await begin(beginTarget, seq, out, Math.max(1, Math.min(BEGIN_TIMEOUT_MS, timeLeft())));\n } catch (err) {\n throw new Ended(codeOf(err) ?? \"NET_UNAVAILABLE\", err.message, {\n ...base2,\n status: \"refused\"\n });\n }\n }\n const left = timeLeft();\n if (left < NET_MIN_TIME_MS) {\n throw new Ended(\"ACTION_DEADLINE\", \"too little time is left before the action deadline\", {\n ...base2,\n status: \"refused\"\n });\n }\n const timer = setTimeout(\n () => controller.abort(),\n Math.min(out.timeoutMs ?? NET_DEFAULT_TIMEOUT_MS, left)\n );\n let res = null;\n let received = 0;\n try {\n res = await fetchImpl(outbound);\n if (res.status < 200 || res.status > 599) {\n await res.body?.cancel().catch(() => {\n });\n throw handleError(\"NET_FAILED\", \"the server answered with a status code outside 200\\u2013599\");\n }\n const body = await readAnswer(res, out.method, NET_RESPONSE_MAX_BYTES, (n) => {\n received = n;\n });\n const answer = {\n status: res.status,\n status_text: res.statusText,\n headers: [...res.headers],\n body,\n url: out.url\n };\n record({\n ...base2,\n status: \"ok\",\n http_status: res.status,\n response_bytes: body.byteLength,\n duration_ms: now() - started\n });\n return answer;\n } catch (err) {\n const timedOut = controller.signal.aborted;\n const code = timedOut ? \"NET_TIMEOUT\" : codeOf(err) ?? \"NET_FAILED\";\n const message = timedOut ? \"the request timed out; it may have reached the server\" : code === \"NET_FAILED\" && !codeOf(err) ? \"the request failed (connection, DNS or TLS); it may have reached the server\" : err.message;\n const answered = res !== null && res.status >= 200 && res.status <= 599;\n throw new Ended(code, message, {\n ...base2,\n status: \"failed\",\n ...answered ? { http_status: res?.status } : {},\n ...received > 0 ? { response_bytes: received } : {}\n });\n } finally {\n clearTimeout(timer);\n }\n }\n async function take(raw) {\n if (state.revoked) throw handleError(\"ACTION_HANDLE_REVOKED\", \"this handle is no longer valid\");\n if (cfg.maxRequests <= 0 || cfg.policy === null) {\n throw handleError(\n \"NET_UNAVAILABLE\",\n \"actions cannot make outbound requests on this deployment yet\"\n );\n }\n const started = now();\n const seq = ++state.netRequests;\n let fields = describeRequest(raw);\n const refuse = (code, message) => {\n record({ seq, status: \"refused\", ...fields, error_code: code, duration_ms: now() - started });\n return handleError(code, message);\n };\n const overLimit = `an action may make at most ${cfg.maxRequests} outbound requests`;\n if (seq > cfg.maxRequests) {\n state.netLimitHit = true;\n if (seq === cfg.maxRequests + 1) throw refuse(\"ACTION_LIMIT_EXCEEDED\", overLimit);\n throw handleError(\"ACTION_LIMIT_EXCEEDED\", overLimit);\n }\n if (timeLeft() < NET_MIN_TIME_MS) {\n throw refuse(\"ACTION_DEADLINE\", \"too little time is left before the action deadline\");\n }\n let out;\n try {\n out = parseOutgoing(raw, cfg.policy);\n } catch (err) {\n throw refuse(codeOf(err) ?? \"ACTION_INVALID_CALL\", err.message);\n }\n fields = { method: out.method, host: out.host, path: out.path };\n if (state.netInFlight >= cfg.maxInFlight) {\n throw refuse(\n \"ACTION_LIMIT_EXCEEDED\",\n `at most ${cfg.maxInFlight} requests may be in flight at once; wait for one to finish`\n );\n }\n const controller = new AbortController();\n let outbound;\n try {\n outbound = new Request(out.url, {\n method: out.method,\n headers: out.headers,\n body: out.body,\n redirect: \"manual\",\n cache: \"no-store\",\n signal: controller.signal\n });\n } catch {\n throw refuse(\"ACTION_INVALID_CALL\", \"the request's method, headers or body are not valid\");\n }\n const reserved = (out.body?.byteLength ?? 0) + NET_RESPONSE_MAX_BYTES;\n if (budget.used + reserved > budget.limit) {\n throw refuse(\n \"NET_BUSY\",\n \"the platform has too many requests in flight right now; nothing was sent, try again shortly\"\n );\n }\n budget.used += reserved;\n state.netInFlight++;\n const pending = send(seq, out, outbound, controller, started);\n state.inflight.add(pending);\n try {\n return await pending;\n } catch (err) {\n if (err instanceof Ended) {\n record({\n seq,\n status: \"failed\",\n method: out.method,\n host: out.host,\n path: out.path,\n ...err.result,\n error_code: err.code,\n duration_ms: now() - started\n });\n throw handleError(err.code, err.message);\n }\n throw err;\n } finally {\n state.inflight.delete(pending);\n state.netInFlight--;\n budget.used -= reserved;\n }\n }\n return {\n async request(raw) {\n try {\n return await take(raw);\n } catch (err) {\n if (codeOf(err)) throw err;\n throw handleError(\"NET_FAILED\", \"the request failed\");\n }\n }\n };\n}\n\n// ../actions-worker/src/outcome.ts\nvar encoder4 = new TextEncoder();\nfunction truncateBytes(s, maxBytes) {\n const bytes = encoder4.encode(s);\n if (bytes.byteLength <= maxBytes) return s;\n return new TextDecoder().decode(bytes.subarray(0, maxBytes)).replace(/\uFFFD+$/u, \"\");\n}\nfunction base(state) {\n return {\n db_calls: state.calls,\n data_seq: state.dataSeq,\n clip_calls: state.clipCalls,\n // In seq order; each was added as it ended.\n net_calls: [...state.netCalls].sort((a, b) => a.seq - b.seq)\n };\n}\nfunction limitMessage(state) {\n if (state.limitHit) return \"the action made more database calls than allowed\";\n if (state.clipLimitHit) return \"the action made more connector calls than allowed\";\n if (state.netLimitHit) return \"the action made more outbound requests than allowed\";\n if (state.parallLimitHit) return \"the action read Parall data more times than allowed\";\n return null;\n}\nfunction failed(state, error) {\n const limit = limitMessage(state);\n if (limit) {\n return { status: \"limit_exceeded\", error: { kind: \"limit\", message: limit }, ...base(state) };\n }\n return { status: \"failed\", error, ...base(state) };\n}\nfunction asString(v) {\n return typeof v === \"string\" ? v : \"\";\n}\nfunction outcomeFromResult(raw, limits, state) {\n if (typeof raw === \"object\" && raw !== null && !Array.isArray(raw)) {\n const r = raw;\n if (r.ok === true && typeof r.json === \"string\") {\n if (encoder4.encode(r.json).byteLength > limits.result_bytes) {\n return failed(state, {\n kind: \"unexpected\",\n message: `the action result is larger than ${limits.result_bytes} bytes`\n });\n }\n return { status: \"ok\", result_json: r.json, ...base(state) };\n }\n if (r.ok === false && typeof r.error === \"object\" && r.error !== null) {\n const e = r.error;\n if (e.kind === \"action_error\") {\n return failed(state, {\n kind: \"action_error\",\n message: truncateBytes(asString(e.message), limits.message_bytes)\n });\n }\n return failed(state, {\n kind: \"unexpected\",\n message: truncateBytes(asString(e.message), limits.message_bytes),\n stack: truncateBytes(asString(e.stack), limits.stack_bytes)\n });\n }\n }\n return failed(state, {\n kind: \"unexpected\",\n message: \"the action returned a result in an unknown shape\"\n });\n}\nvar CPU_LIMIT = /exceeded (its )?cpu|cpu time limit|exceeded resource limits/i;\nfunction isCpuLimitError(err) {\n const message = err instanceof Error ? err.message : String(err);\n return CPU_LIMIT.test(message);\n}\nfunction outcomeFromThrown(err, limits, state) {\n if (isCpuLimitError(err)) {\n return {\n status: \"limit_exceeded\",\n error: { kind: \"limit\", message: \"the action ran past its CPU time limit\" },\n ...base(state)\n };\n }\n const message = err instanceof Error ? `${err.name}: ${err.message}` : String(err);\n return failed(state, {\n kind: \"unexpected\",\n message: truncateBytes(message, limits.message_bytes)\n });\n}\nfunction timeoutOutcome(state) {\n return {\n status: \"timeout\",\n error: {\n kind: \"timeout\",\n message: \"the action ran past its deadline or lost a database answer; writes it started may have committed\"\n },\n ...base(state)\n };\n}\n\n// ../actions-worker/src/parall-caller.ts\nvar PARALL_MAX_REFS = 100;\nvar PARALL_GET_TIMEOUT_MS = 12e3;\nvar ENVELOPE_BYTES2 = 64 * 1024;\nvar encoder5 = new TextEncoder();\nfunction unavailable() {\n return handleError(\n \"PARALL_READ_UNAVAILABLE\",\n \"Parall data could not be read just now; nothing changed, so the get can be retried\"\n );\n}\nfunction refsOf(req) {\n const refs = typeof req === \"object\" && req !== null ? req.refs : null;\n if (!Array.isArray(refs) || refs.length === 0 || refs.length > PARALL_MAX_REFS || !refs.every((ref) => typeof ref === \"string\")) {\n throw handleError(\n \"ACTION_INVALID_CALL\",\n `get takes a list of 1 to ${PARALL_MAX_REFS} references (strings)`\n );\n }\n return refs;\n}\nfunction isItem(v) {\n if (typeof v !== \"object\" || v === null) return false;\n const i = v;\n if (i.ok === true)\n return typeof i.type === \"string\" && typeof i.item === \"object\" && i.item !== null;\n return i.ok === false && typeof i.code === \"string\";\n}\nfunction createParallCaller(cfg, state) {\n const fetchImpl = cfg.fetchImpl ?? fetch;\n const now = cfg.now ?? Date.now;\n const url = `${cfg.callbackOrigin.replace(/\\/+$/, \"\")}/api/v1/mini-app-actions/parall/get`;\n async function send(body, count) {\n const headers = {\n \"Content-Type\": \"application/json\",\n \"User-Agent\": USER_AGENT,\n [TICKET_HEADER]: cfg.ticket,\n [INVOCATION_HEADER]: cfg.invocationId\n };\n if (cfg.instance !== \"default\") headers[SWIMLANE_HEADER] = cfg.instance;\n let res;\n try {\n res = await fetchImpl(url, {\n method: \"POST\",\n headers,\n body,\n signal: AbortSignal.timeout(\n Math.max(1, Math.min(PARALL_GET_TIMEOUT_MS, cfg.deadlineMs - now()))\n )\n });\n } catch {\n if (now() >= cfg.deadlineMs) {\n throw handleError(\"ACTION_DEADLINE\", \"the action ran past its deadline\");\n }\n throw unavailable();\n }\n let parsed;\n try {\n const text = await readCapped(res, cfg.maxBytes + ENVELOPE_BYTES2);\n parsed = text ? JSON.parse(text) : null;\n } catch {\n throw unavailable();\n }\n if (res.ok) {\n const a = parsed;\n if (a?.ok === true && Array.isArray(a.value) && a.value.length === count && a.value.every(isItem)) {\n return a.value;\n }\n throw unavailable();\n }\n const env = parsed?.error;\n if (typeof env?.code !== \"string\") throw unavailable();\n throw handleError(\n env.code,\n typeof env.message === \"string\" ? env.message : `the get was refused (${res.status})`\n );\n }\n async function get(req) {\n if (state.revoked) throw handleError(\"ACTION_HANDLE_REVOKED\", \"this handle is no longer valid\");\n if (cfg.maxReads <= 0) {\n throw handleError(\n \"PARALL_READ_UNAVAILABLE\",\n \"actions cannot read Parall data on this deployment\"\n );\n }\n if (now() >= cfg.deadlineMs)\n throw handleError(\"ACTION_DEADLINE\", \"the action ran past its deadline\");\n const refs = refsOf(req);\n if (state.parallReads >= cfg.maxReads) {\n state.parallLimitHit = true;\n throw handleError(\n \"ACTION_LIMIT_EXCEEDED\",\n `an action may read Parall data at most ${cfg.maxReads} times`\n );\n }\n const body = JSON.stringify({ refs });\n if (encoder5.encode(body).byteLength > cfg.maxBytes) {\n throw handleError(\n \"ACTION_INVALID_CALL\",\n `a get's references may be at most ${cfg.maxBytes} bytes in all`\n );\n }\n state.parallReads++;\n const pending = send(body, refs.length);\n state.inflight.add(pending);\n try {\n return await pending;\n } finally {\n state.inflight.delete(pending);\n }\n }\n return { get };\n}\n\n// ../actions-worker/src/sandbox.ts\nvar COMPATIBILITY_DATE = \"2026-04-01\";\nvar COMPATIBILITY_FLAGS = [];\nvar ENTRYPOINT = \"ActionRunner\";\nvar PRELUDE = `// Runs before the author module (see actions-worker src/sandbox.ts).\nfor (const name of ['caches', 'WebSocket']) {\n try {\n delete globalThis[name];\n } catch {}\n if (name in globalThis) {\n Object.defineProperty(globalThis, name, { value: undefined, writable: false, configurable: false });\n }\n}\n`;\nvar ENTRY = `import './prelude.js';\nexport * from './author.js';\n`;\nfunction workerCode(authorSource) {\n return {\n compatibilityDate: COMPATIBILITY_DATE,\n compatibilityFlags: COMPATIBILITY_FLAGS,\n mainModule: \"entry.js\",\n modules: { \"entry.js\": ENTRY, \"prelude.js\": PRELUDE, \"author.js\": authorSource },\n env: {},\n globalOutbound: null\n };\n}\nvar runtimeVersion = null;\nfunction runtimeVersionOf() {\n if (!runtimeVersion) {\n const material = JSON.stringify([\n COMPATIBILITY_DATE,\n COMPATIBILITY_FLAGS,\n ENTRYPOINT,\n PRELUDE,\n ENTRY,\n \"env:{}\",\n \"outbound:null\"\n ]);\n runtimeVersion = crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(material)).then(\n (d) => Array.from(new Uint8Array(d).slice(0, 8), (b) => b.toString(16).padStart(2, \"0\")).join(\"\")\n );\n }\n return runtimeVersion;\n}\nfunction isolateId(instance, appId, sha256, runtime) {\n return `${instance}:${appId}:${sha256}:${runtime}`;\n}\n\n// ../actions-worker/src/run.ts\nvar DEADLINE_MARGIN_MS = 250;\nasync function runWithDeadline(call, budgetMs) {\n if (budgetMs <= 0) return { kind: \"timeout\" };\n let timer = null;\n const timedOut = new Promise((resolve) => {\n timer = setTimeout(() => resolve({ kind: \"timeout\" }), budgetMs);\n });\n try {\n return await Promise.race([\n call().then(\n (value) => ({ kind: \"result\", value }),\n (error) => ({ kind: \"thrown\", error })\n ),\n timedOut\n ]);\n } finally {\n if (timer !== null) clearTimeout(timer);\n }\n}\nasync function runInvocation(worker, req, opts) {\n const { callbackOrigin, loadFailure = () => null } = opts;\n const effectiveDeadline = req.deadline_ms - DEADLINE_MARGIN_MS;\n const caller = createDbCaller({\n kind: req.kind,\n ticket: req.ticket,\n invocationId: req.invocation_id,\n instance: req.instance,\n callbackOrigin,\n deadlineMs: effectiveDeadline,\n limits: req.limits\n });\n const clip = createClipCaller(\n {\n enabled: req.clip,\n ticket: req.ticket,\n invocationId: req.invocation_id,\n instance: req.instance,\n callbackOrigin,\n deadlineMs: effectiveDeadline,\n maxCalls: req.limits.clip_calls,\n maxBytes: req.limits.result_bytes\n },\n caller.state\n );\n const net = netLimits(req.limits);\n const netCaller = createNetCaller(\n {\n mode: opts.netMode,\n ticket: req.ticket,\n invocationId: req.invocation_id,\n instance: req.instance,\n callbackOrigin,\n deadlineMs: effectiveDeadline,\n maxRequests: net.requests,\n maxInFlight: net.inFlight,\n policy: opts.netPolicy\n },\n caller.state\n );\n const parall = createParallCaller(\n {\n ticket: req.ticket,\n invocationId: req.invocation_id,\n instance: req.instance,\n callbackOrigin,\n deadlineMs: effectiveDeadline,\n maxReads: parallReads(req.limits),\n maxBytes: req.limits.result_bytes\n },\n caller.state\n );\n const handle = makeHandle(caller, clip, netCaller, parall);\n const entry = worker.getEntrypoint(ENTRYPOINT, { limits: { cpuMs: req.limits.cpu_ms } });\n const settled = await runWithDeadline(\n () => entry.run(\n {\n action: req.action,\n params: req.params,\n viewer: req.viewer,\n app: req.app,\n invocation_id: req.invocation_id,\n // The app's secrets, as ctx.env (mini-app-network-design.md \u00A77.4):\n // per call, never in the isolate's own env.\n env: req.env ?? {},\n // How many requests the SDK lets run at once; it queues the rest.\n net_in_flight: net.inFlight\n },\n handle\n ),\n effectiveDeadline - Date.now()\n );\n const drained = await settle(caller, effectiveDeadline);\n if (settled.kind === \"timeout\" || !drained || caller.state.indeterminate) {\n return timeoutOutcome(caller.state);\n }\n if (settled.kind === \"thrown\") {\n return loadFailure() ?? outcomeFromThrown(settled.error, req.limits, caller.state);\n }\n return outcomeFromResult(settled.value, req.limits, caller.state);\n}\n\n// ../actions-worker/src/local.ts\nvar local_default = {\n async fetch(request, env) {\n let body;\n try {\n body = await request.json();\n } catch {\n return Response.json({ error: \"body is not JSON\" }, { status: 400 });\n }\n const req = parseInvokeRequest(body?.request, { unpublished: true });\n if (typeof req === \"string\") return Response.json({ error: `invalid ${req}` }, { status: 400 });\n if (typeof body.source !== \"string\" || typeof body.callback_origin !== \"string\") {\n return Response.json({ error: \"source and callback_origin are required\" }, { status: 400 });\n }\n const runtime = await runtimeVersionOf();\n const worker = env.LOADER.get(\n isolateId(req.instance, req.app.id, req.module.sha256, runtime),\n async () => workerCode(body.source)\n );\n return Response.json(\n await runInvocation(worker, req, {\n callbackOrigin: body.callback_origin,\n netPolicy: policyFrom(\n env.NET_BLOCKED_HOSTS,\n env.NET_TEST_ALLOW_LOOPBACK,\n body.callback_origin\n ),\n netMode: \"direct\"\n })\n );\n }\n};\nexport {\n local_default as default\n};\n";
3
+ export declare const LOCAL_RUNNER_SOURCE = "// ../actions-worker/src/contract.ts\nvar DEFAULT_NET_IN_FLIGHT = 4;\nvar INSTANCE = /^(default|pr-\\d{1,6})$/;\nvar APP_ID = /^app_[0-9a-z]{21}$/;\nvar SHA256 = /^[0-9a-f]{64}$/;\nvar ACTION_NAME = /^[a-zA-Z][a-zA-Z0-9_]{0,63}$/;\nvar INVOCATION_ID = /^[0-9A-Za-z_-]{1,64}$/;\nvar LIMIT_CEILINGS = {\n cpu_ms: 3e4,\n db_calls: 1e3,\n batch_statements: 1e3,\n batch_bytes: 8 * 1024 * 1024,\n result_bytes: 8 * 1024 * 1024,\n message_bytes: 64 * 1024,\n stack_bytes: 256 * 1024\n};\nvar CLIP_CALLS_CEILING = 100;\nvar NET_REQUESTS_CEILING = 100;\nvar NET_IN_FLIGHT_CEILING = 6;\nvar PARALL_READS_CEILING = 100;\nvar ENV_NAME = /^[A-Z_][A-Z0-9_]{0,127}$/;\nvar ENV_CEILING_BYTES = 256 * 1024;\nfunction isRecord(v) {\n return typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\nfunction positiveInt(v, max) {\n return typeof v === \"number\" && Number.isInteger(v) && v > 0 && v <= max;\n}\nfunction intInRange(v, min, max) {\n return typeof v === \"number\" && Number.isInteger(v) && v >= min && v <= max;\n}\nvar envEncoder = new TextEncoder();\nfunction validEnv(v) {\n if (!isRecord(v)) return false;\n let total = 0;\n for (const [name, value] of Object.entries(v)) {\n if (!ENV_NAME.test(name) || typeof value !== \"string\") return false;\n total += envEncoder.encode(name).byteLength + envEncoder.encode(value).byteLength;\n if (total > ENV_CEILING_BYTES) return false;\n }\n return true;\n}\nfunction parseInvokeRequest(raw, opts = {}) {\n if (!isRecord(raw)) return \"body is not an object\";\n const {\n invocation_id,\n instance,\n app,\n module,\n action,\n kind,\n clip,\n viewer,\n ticket,\n deadline_ms,\n limits\n } = raw;\n if (typeof invocation_id !== \"string\" || !INVOCATION_ID.test(invocation_id))\n return \"invocation_id\";\n if (typeof instance !== \"string\" || !INSTANCE.test(instance)) return \"instance\";\n if (!isRecord(app) || typeof app.id !== \"string\" || !APP_ID.test(app.id)) return \"app.id\";\n if (!(opts.unpublished && app.version_seq === 0) && !positiveInt(app.version_seq, 2 ** 31))\n return \"app.version_seq\";\n if (!isRecord(module) || typeof module.sha256 !== \"string\" || !SHA256.test(module.sha256))\n return \"module.sha256\";\n if (typeof action !== \"string\" || !ACTION_NAME.test(action)) return \"action\";\n if (kind !== \"read\" && kind !== \"write\") return \"kind\";\n if (clip !== void 0 && clip !== false && !(clip === true && kind === \"write\")) return \"clip\";\n if (!(\"params\" in raw)) return \"params\";\n if (!isRecord(viewer) || typeof viewer.id !== \"string\" || typeof viewer.display_name !== \"string\" || typeof viewer.is_agent !== \"boolean\" || typeof viewer.role !== \"string\") {\n return \"viewer\";\n }\n if (typeof ticket !== \"string\" || ticket.length === 0 || ticket.length > 4096) return \"ticket\";\n if (typeof deadline_ms !== \"number\" || !Number.isFinite(deadline_ms)) return \"deadline_ms\";\n if (!isRecord(limits)) return \"limits\";\n for (const key of Object.keys(LIMIT_CEILINGS)) {\n if (!positiveInt(limits[key], LIMIT_CEILINGS[key])) return `limits.${key}`;\n }\n const clipCalls = limits.clip_calls ?? 0;\n if (clipCalls !== 0 && !positiveInt(clipCalls, CLIP_CALLS_CEILING)) return \"limits.clip_calls\";\n const netRequests = limits.net_requests ?? 0;\n if (!intInRange(netRequests, 0, NET_REQUESTS_CEILING)) return \"limits.net_requests\";\n const netInFlight = limits.net_in_flight ?? DEFAULT_NET_IN_FLIGHT;\n if (!intInRange(netInFlight, 0, NET_IN_FLIGHT_CEILING) || netRequests > 0 && netInFlight === 0) {\n return \"limits.net_in_flight\";\n }\n if (!intInRange(limits.parall_reads ?? 0, 0, PARALL_READS_CEILING)) return \"limits.parall_reads\";\n if (raw.env !== void 0 && raw.env !== null && !validEnv(raw.env)) return \"env\";\n return {\n invocation_id,\n instance,\n app: { id: app.id, version_seq: app.version_seq },\n module: { sha256: module.sha256 },\n action,\n kind,\n clip: clip === true,\n params: raw.params,\n viewer: {\n id: viewer.id,\n display_name: viewer.display_name,\n is_agent: viewer.is_agent,\n role: viewer.role\n },\n ticket,\n deadline_ms,\n limits: { ...limits, clip_calls: clipCalls },\n ...raw.env === null ? { env: null } : {},\n ...isRecord(raw.env) ? { env: { ...raw.env } } : {}\n };\n}\nfunction parallReads(limits) {\n return limits.parall_reads ?? 0;\n}\nfunction netLimits(limits) {\n return {\n requests: limits.net_requests ?? 0,\n inFlight: limits.net_in_flight ?? DEFAULT_NET_IN_FLIGHT\n };\n}\n\n// ../actions-worker/src/net-address.ts\nvar BAD_PORTS = /* @__PURE__ */ new Set([\n 0,\n 1,\n 7,\n 9,\n 11,\n 13,\n 15,\n 17,\n 19,\n 20,\n 21,\n 22,\n 23,\n 25,\n 37,\n 42,\n 43,\n 53,\n 69,\n 77,\n 79,\n 87,\n 95,\n 101,\n 102,\n 103,\n 104,\n 109,\n 110,\n 111,\n 113,\n 115,\n 117,\n 119,\n 123,\n 135,\n 137,\n 139,\n 143,\n 161,\n 179,\n 389,\n 427,\n 465,\n 512,\n 513,\n 514,\n 515,\n 526,\n 530,\n 531,\n 532,\n 540,\n 548,\n 554,\n 556,\n 563,\n 587,\n 601,\n 636,\n 989,\n 990,\n 993,\n 995,\n 1719,\n 1720,\n 1723,\n 2049,\n 3659,\n 4045,\n 4190,\n 5060,\n 5061,\n 6e3,\n 6566,\n 6665,\n 6666,\n 6667,\n 6668,\n 6669,\n 6679,\n 6697,\n 10080\n]);\nvar NUMERIC_LABEL = /^(?:0x[0-9a-f]*|\\d+)$/i;\nvar HOST_NAME = /^[a-z0-9_-]+(?:\\.[a-z0-9_-]+)*$/;\nvar HOST_NAME_MAX_BYTES = 253;\nvar HOST_LABEL_MAX_BYTES = 63;\nfunction normalizeHost(host) {\n return host.toLowerCase().replace(/\\.+$/, \"\");\n}\nfunction isIpLiteral(host) {\n if (host.startsWith(\"[\") || host.includes(\":\")) return true;\n const labels = host.split(\".\");\n return NUMERIC_LABEL.test(labels[labels.length - 1] ?? \"\");\n}\nfunction isLoopbackName(host) {\n return host === \"localhost\" || host.endsWith(\".localhost\");\n}\nfunction isHostName(host) {\n return host.length <= HOST_NAME_MAX_BYTES && HOST_NAME.test(host) && host.split(\".\").every((label) => label.length <= HOST_LABEL_MAX_BYTES);\n}\nfunction isBlockedHost(host, blocked) {\n return blocked.some((name) => host === name || host.endsWith(`.${name}`));\n}\nfunction checkAddress(input, policy) {\n if (input.protocol !== \"https:\" && input.protocol !== \"http:\") {\n return { ok: false, reason: \"only https: and http: URLs can be requested\" };\n }\n if (input.username !== \"\" || input.password !== \"\") {\n return { ok: false, reason: \"a URL with credentials in it (user:pass@) cannot be requested\" };\n }\n const host = normalizeHost(input.hostname);\n if (host === \"\") return { ok: false, reason: \"the URL has no host\" };\n if (isIpLiteral(host)) {\n return { ok: false, reason: \"requests go to host names, not IP addresses\" };\n }\n if (!isHostName(host)) {\n return {\n ok: false,\n reason: `the URL host is not a host name (at most ${HOST_NAME_MAX_BYTES} bytes, ${HOST_LABEL_MAX_BYTES} per label)`\n };\n }\n if (input.port !== \"\" && BAD_PORTS.has(Number(input.port))) {\n return { ok: false, reason: `port ${input.port} cannot be requested` };\n }\n if (isLoopbackName(host) && !policy.allowLoopback) {\n return { ok: false, reason: \"loopback hosts cannot be requested\" };\n }\n if (isBlockedHost(host, policy.blockedHosts)) {\n return { ok: false, reason: \"the platform's own hosts cannot be requested\" };\n }\n const url = new URL(input.href);\n url.hostname = host;\n url.hash = \"\";\n return { ok: true, url, host: input.port === \"\" ? host : `${host}:${input.port}` };\n}\nfunction parseBlockedHosts(raw) {\n if (typeof raw !== \"string\") return null;\n const names = raw.split(\",\").map((s) => normalizeHost(s.trim())).filter((s) => s !== \"\");\n if (names.length === 0) return null;\n for (const name of names) {\n if (!isHostName(name) || isIpLiteral(name)) return null;\n }\n return names;\n}\nvar LOOPBACK_ORIGIN_HOSTS = /* @__PURE__ */ new Set([\"127.0.0.1\", \"localhost\", \"[::1]\"]);\nfunction loopbackAllowed(flag, callbackOrigin) {\n if (flag !== \"1\" && flag !== \"true\") return false;\n try {\n return LOOPBACK_ORIGIN_HOSTS.has(new URL(callbackOrigin).hostname);\n } catch {\n return false;\n }\n}\nfunction policyFrom(blockedHosts, loopbackFlag, callbackOrigin) {\n const blocked = parseBlockedHosts(blockedHosts);\n if (!blocked) return null;\n return { blockedHosts: blocked, allowLoopback: loopbackAllowed(loopbackFlag, callbackOrigin) };\n}\n\n// ../actions-worker/src/db-caller.ts\nvar USER_AGENT = \"parall-actions-worker/1\";\nvar TICKET_HEADER = \"X-Prll-Action-Ticket\";\nvar INVOCATION_HEADER = \"X-Prll-Action-Invocation\";\nvar SWIMLANE_HEADER = \"X-Prll-Swimlane\";\nvar MAX_SQL_BYTES = 256 * 1024;\nvar encoder = new TextEncoder();\nfunction handleError(code, message) {\n const err = new Error(message);\n err.name = \"ActionDbError\";\n err.code = code;\n return err;\n}\nfunction statementOf(v) {\n if (typeof v !== \"object\" || v === null) return null;\n const { sql, params } = v;\n if (typeof sql !== \"string\" || sql.length === 0 || encoder.encode(sql).byteLength > MAX_SQL_BYTES)\n return null;\n if (params !== void 0 && !Array.isArray(params)) return null;\n return { sql, params: params ?? [] };\n}\nfunction requestBody(op, payload, limits) {\n if (op === \"batch\") {\n const statements = payload?.statements;\n if (!Array.isArray(statements) || statements.length === 0) {\n throw handleError(\"ACTION_INVALID_CALL\", \"batch needs a non-empty array of { sql, params }\");\n }\n if (statements.length > limits.batch_statements) {\n throw handleError(\n \"ACTION_LIMIT_EXCEEDED\",\n `a batch may hold at most ${limits.batch_statements} statements`\n );\n }\n const parsed = statements.map(statementOf);\n if (parsed.some((s) => s === null)) {\n throw handleError(\n \"ACTION_INVALID_CALL\",\n \"every batch entry needs a non-empty sql string and a params array\"\n );\n }\n const body = JSON.stringify({ statements: parsed });\n if (encoder.encode(body).byteLength > limits.batch_bytes) {\n throw handleError(\n \"ACTION_LIMIT_EXCEEDED\",\n `a batch may be at most ${limits.batch_bytes} bytes`\n );\n }\n return body;\n }\n const statement = statementOf(payload);\n if (!statement)\n throw handleError(\n \"ACTION_INVALID_CALL\",\n `${op} needs a non-empty sql string and a params array`\n );\n return JSON.stringify(statement);\n}\nfunction trackDataSeq(state, result) {\n const seq = result?.data_seq;\n if (typeof seq !== \"number\" || !Number.isInteger(seq)) return;\n state.dataSeq = state.dataSeq ? { from: Math.min(state.dataSeq.from, seq), to: Math.max(state.dataSeq.to, seq) } : { from: seq, to: seq };\n}\nasync function readCapped(res, maxBytes) {\n if (!res.body) return \"\";\n const reader = res.body.getReader();\n const chunks = [];\n let total = 0;\n for (; ; ) {\n const { done, value } = await reader.read();\n if (done) break;\n total += value.byteLength;\n if (total > maxBytes) {\n await reader.cancel();\n throw handleError(\n \"ACTION_RESULT_TOO_LARGE\",\n `a database result may be at most ${maxBytes} bytes`\n );\n }\n chunks.push(value);\n }\n const out = new Uint8Array(total);\n let off = 0;\n for (const c of chunks) {\n out.set(c, off);\n off += c.byteLength;\n }\n return new TextDecoder().decode(out);\n}\nfunction createDbCaller(cfg) {\n const fetchImpl = cfg.fetchImpl ?? fetch;\n const now = cfg.now ?? Date.now;\n const state = {\n revoked: false,\n calls: 0,\n limitHit: false,\n inflight: /* @__PURE__ */ new Set(),\n dataSeq: null,\n indeterminate: false,\n clipCalls: 0,\n clipLimitHit: false,\n netRequests: 0,\n netLimitHit: false,\n netInFlight: 0,\n netCalls: [],\n parallReads: 0,\n parallLimitHit: false\n };\n const origin = cfg.callbackOrigin.replace(/\\/+$/, \"\");\n async function send(op, body) {\n const headers = {\n \"Content-Type\": \"application/json\",\n \"User-Agent\": USER_AGENT,\n [TICKET_HEADER]: cfg.ticket,\n [INVOCATION_HEADER]: cfg.invocationId\n };\n if (cfg.instance !== \"default\") headers[SWIMLANE_HEADER] = cfg.instance;\n const remaining = Math.max(1, cfg.deadlineMs - now());\n let res;\n try {\n res = await fetchImpl(`${origin}/api/v1/mini-app-actions/db/${op}`, {\n method: \"POST\",\n headers,\n body,\n signal: AbortSignal.timeout(remaining)\n });\n } catch {\n if (op !== \"query\") state.indeterminate = true;\n throw handleError(\"ACTION_DB_UNAVAILABLE\", \"the database could not be reached\");\n }\n let parsed;\n try {\n const text = await readCapped(res, cfg.limits.result_bytes + 64 * 1024);\n parsed = text ? JSON.parse(text) : null;\n } catch (err) {\n if (op !== \"query\") state.indeterminate = true;\n if (err.code === \"ACTION_RESULT_TOO_LARGE\") throw err;\n throw handleError(\"ACTION_DB_UNAVAILABLE\", \"the database returned an unreadable response\");\n }\n if (!res.ok) {\n const env = parsed?.error;\n if (typeof env?.code !== \"string\") {\n if (op !== \"query\") state.indeterminate = true;\n throw handleError(`HTTP_${res.status}`, `database call failed (${res.status})`);\n }\n const message = typeof env.message === \"string\" ? env.message : `database call failed (${res.status})`;\n throw handleError(env.code, message);\n }\n trackDataSeq(state, parsed);\n return parsed;\n }\n async function call(op, payload) {\n if (state.revoked)\n throw handleError(\"ACTION_HANDLE_REVOKED\", \"this database handle is no longer valid\");\n if (now() >= cfg.deadlineMs)\n throw handleError(\"ACTION_DEADLINE\", \"the action ran past its deadline\");\n if (cfg.kind === \"read\" && op !== \"query\") {\n throw handleError(\"ACTION_READ_ONLY\", \"a read action can only query\");\n }\n state.calls++;\n if (state.calls > cfg.limits.db_calls) {\n state.limitHit = true;\n throw handleError(\n \"ACTION_LIMIT_EXCEEDED\",\n `an action may make at most ${cfg.limits.db_calls} database calls`\n );\n }\n const body = requestBody(op, payload, cfg.limits);\n const pending = send(op, body);\n state.inflight.add(pending);\n try {\n return await pending;\n } finally {\n state.inflight.delete(pending);\n }\n }\n return { state, call };\n}\nfunction settleCall(caller, op, payload) {\n return settleWith(\n () => caller.call(op, payload),\n \"ACTION_DB_UNAVAILABLE\",\n \"the database call failed\"\n );\n}\nasync function settleWith(run, fallbackCode, fallbackMessage) {\n try {\n return { ok: true, value: await run() };\n } catch (err) {\n const { code, message } = err ?? {};\n return {\n ok: false,\n error: {\n code: typeof code === \"string\" ? code : fallbackCode,\n message: typeof message === \"string\" ? message : fallbackMessage\n }\n };\n }\n}\nasync function settle(caller, deadlineMs, now = Date.now) {\n caller.state.revoked = true;\n const inflight = [...caller.state.inflight];\n if (inflight.length === 0) return true;\n const remaining = deadlineMs - now();\n if (remaining > 0) {\n let timer = null;\n await Promise.race([\n Promise.allSettled(inflight),\n new Promise((r) => {\n timer = setTimeout(r, remaining);\n })\n ]);\n if (timer !== null) clearTimeout(timer);\n }\n return caller.state.inflight.size === 0;\n}\n\n// ../actions-worker/src/clip-caller.ts\nvar ENVELOPE_BYTES = 64 * 1024;\nvar MAX_FIELD_BYTES = 256;\nvar encoder2 = new TextEncoder();\nfunction unknownOutcome() {\n return handleError(\n \"OUTCOME_UNKNOWN\",\n \"the Clip call\\u2019s answer was lost \\u2014 it may or may not have run; do not retry it blindly\"\n );\n}\nfunction field(v, required) {\n if (v === void 0 || v === null) return required ? null : void 0;\n if (typeof v !== \"string\" || encoder2.encode(v).byteLength > MAX_FIELD_BYTES) return null;\n if (required && v.trim() === \"\") return null;\n return v;\n}\nfunction requestBody2(req, seq, maxBytes) {\n const r = typeof req === \"object\" && req !== null ? req : {};\n const clip = field(r.clip, true);\n const command = field(r.command, true);\n const connection = field(r.connection, false);\n const profile = field(r.profile, false);\n const timeout = r.timeout_ms;\n if (clip === null || command === null || connection === null || profile === null) {\n throw handleError(\n \"ACTION_INVALID_CALL\",\n \"clip.exec needs a Clip name or id, a command, and string connection and profile options of at most 256 bytes\"\n );\n }\n if (timeout !== void 0 && (typeof timeout !== \"number\" || !Number.isInteger(timeout) || timeout <= 0 || timeout > 12e4)) {\n throw handleError(\n \"ACTION_INVALID_CALL\",\n \"timeoutMs must be a whole number of milliseconds from 1 to 120000\"\n );\n }\n let body;\n try {\n body = JSON.stringify({\n seq,\n clip,\n command,\n args: r.args,\n connection: connection ?? \"\",\n profile,\n timeout_ms: timeout\n });\n } catch {\n throw handleError(\"ACTION_INVALID_CALL\", \"the Clip arguments cannot be sent as JSON\");\n }\n if (encoder2.encode(body).byteLength > maxBytes) {\n throw handleError(\n \"ACTION_LIMIT_EXCEEDED\",\n `a Clip call's arguments may be at most ${maxBytes} bytes`\n );\n }\n return body;\n}\nfunction createClipCaller(cfg, state) {\n const fetchImpl = cfg.fetchImpl ?? fetch;\n const now = cfg.now ?? Date.now;\n const url = `${cfg.callbackOrigin.replace(/\\/+$/, \"\")}/api/v1/mini-app-actions/clip/exec`;\n async function send(body) {\n const headers = {\n \"Content-Type\": \"application/json\",\n \"User-Agent\": USER_AGENT,\n [TICKET_HEADER]: cfg.ticket,\n [INVOCATION_HEADER]: cfg.invocationId\n };\n if (cfg.instance !== \"default\") headers[SWIMLANE_HEADER] = cfg.instance;\n let res;\n try {\n res = await fetchImpl(url, {\n method: \"POST\",\n headers,\n body,\n signal: AbortSignal.timeout(Math.max(1, cfg.deadlineMs - now()))\n });\n } catch {\n throw unknownOutcome();\n }\n let parsed;\n try {\n const text = await readCapped(res, cfg.maxBytes + ENVELOPE_BYTES);\n parsed = text ? JSON.parse(text) : null;\n } catch {\n throw unknownOutcome();\n }\n if (res.ok) {\n const a = parsed;\n if (a?.ok === true) return a.value ?? null;\n if (a?.ok === false && typeof a.error?.code === \"string\") {\n throw handleError(\n a.error.code,\n typeof a.error.message === \"string\" ? a.error.message : a.error.code\n );\n }\n throw unknownOutcome();\n }\n const env = parsed?.error;\n if (typeof env?.code !== \"string\") throw unknownOutcome();\n throw handleError(\n env.code,\n typeof env.message === \"string\" ? env.message : `Clip call refused (${res.status})`\n );\n }\n async function call(req) {\n if (state.revoked) throw handleError(\"ACTION_HANDLE_REVOKED\", \"this handle is no longer valid\");\n if (!cfg.enabled) {\n throw handleError(\n \"CLIP_NOT_DECLARED\",\n \"this action does not declare clip, so it cannot call Clip\"\n );\n }\n if (now() >= cfg.deadlineMs)\n throw handleError(\"ACTION_DEADLINE\", \"the action ran past its deadline\");\n if (state.clipCalls >= cfg.maxCalls) {\n state.clipLimitHit = true;\n throw handleError(\n \"ACTION_LIMIT_EXCEEDED\",\n `an action may make at most ${cfg.maxCalls} Clip calls`\n );\n }\n const body = requestBody2(req, state.clipCalls + 1, cfg.maxBytes);\n state.clipCalls++;\n const pending = send(body);\n state.inflight.add(pending);\n try {\n return await pending;\n } finally {\n state.inflight.delete(pending);\n }\n }\n return { call };\n}\n\n// ../actions-worker/src/handle.ts\nimport { RpcTarget } from \"cloudflare:workers\";\nvar ActionHandle = class extends RpcTarget {\n #caller;\n #clip;\n #net;\n #parall;\n constructor(caller, clip, net, parall) {\n super();\n this.#caller = caller;\n this.#clip = clip;\n this.#net = net;\n this.#parall = parall;\n }\n query(sql, params) {\n return settleCall(this.#caller, \"query\", { sql, params });\n }\n exec(sql, params) {\n return settleCall(this.#caller, \"exec\", { sql, params });\n }\n batch(statements) {\n return settleCall(this.#caller, \"batch\", { statements });\n }\n clip(req) {\n return settleWith(() => this.#clip.call(req), \"CLIP_UNAVAILABLE\", \"the Clip call failed\");\n }\n request(req) {\n return settleWith(() => this.#net.request(req), \"NET_FAILED\", \"the request failed\");\n }\n parall(req) {\n return settleWith(\n () => this.#parall.get(req),\n \"PARALL_READ_UNAVAILABLE\",\n \"Parall data could not be read\"\n );\n }\n parallMembers() {\n return settleWith(\n () => this.#parall.members(),\n \"PARALL_READ_UNAVAILABLE\",\n \"Parall data could not be read\"\n );\n }\n};\nfunction makeHandle(caller, clip, net, parall) {\n return new ActionHandle(caller, clip, net, parall);\n}\n\n// ../actions-worker/src/net-begin.ts\nvar BEGIN_TIMEOUT_MS = 1e4;\nvar BEGIN_ANSWER_MAX_BYTES = 64 * 1024;\nvar ERROR_CODE = /^[A-Z][A-Z0-9_]{0,63}$/;\nfunction notRegistered() {\n return handleError(\n \"NET_UNAVAILABLE\",\n \"the request could not be registered with the platform, so it was not sent\"\n );\n}\nasync function begin(target, seq, fields, timeoutMs) {\n const headers = {\n \"Content-Type\": \"application/json\",\n \"User-Agent\": USER_AGENT,\n [TICKET_HEADER]: target.ticket,\n [INVOCATION_HEADER]: target.invocationId\n };\n if (target.instance !== \"default\") headers[SWIMLANE_HEADER] = target.instance;\n const url = `${target.callbackOrigin.replace(/\\/+$/, \"\")}/api/v1/mini-app-actions/net/begin`;\n const fetchImpl = target.fetchImpl;\n let res;\n try {\n res = await fetchImpl(url, {\n method: \"POST\",\n headers,\n body: JSON.stringify({ seq, method: fields.method, host: fields.host, path: fields.path }),\n signal: AbortSignal.timeout(timeoutMs)\n });\n } catch {\n throw notRegistered();\n }\n let parsed;\n try {\n const text = await readCapped(res, BEGIN_ANSWER_MAX_BYTES);\n parsed = text ? JSON.parse(text) : null;\n } catch {\n throw notRegistered();\n }\n const answer = parsed;\n if (res.status === 200 && answer?.ok === true) return;\n const error = res.ok ? answer?.ok === false ? answer.error : void 0 : answer?.error;\n if (typeof error?.code === \"string\" && ERROR_CODE.test(error.code)) {\n throw handleError(\n error.code,\n typeof error.message === \"string\" ? error.message : \"the platform refused the request\"\n );\n }\n throw notRegistered();\n}\n\n// ../actions-worker/src/net-request.ts\nvar NET_URL_MAX_BYTES = 8 * 1024;\nvar NET_HEADERS_MAX = 64;\nvar NET_HEADER_BYTES_MAX = 32 * 1024;\nvar NET_BODY_MAX_BYTES = 1024 * 1024;\nvar NET_TIMEOUT_MAX_MS = 12e4;\nvar FORBIDDEN_HEADERS = /* @__PURE__ */ new Set([\n \"host\",\n \"connection\",\n \"upgrade\",\n \"keep-alive\",\n \"te\",\n \"trailer\",\n \"transfer-encoding\"\n]);\nvar FORBIDDEN_HEADER_PREFIXES = [\"proxy-\", \"x-prll-\", \"cf-\"];\nvar DROPPED_HEADERS = /* @__PURE__ */ new Set([\"content-length\"]);\nvar METHOD = /^[!#$%&'*+.^_`|~0-9A-Za-z-]{1,16}$/;\nvar FORBIDDEN_METHODS = /* @__PURE__ */ new Set([\"CONNECT\", \"TRACE\", \"TRACK\"]);\nvar NORMALIZED_METHODS = /* @__PURE__ */ new Set([\"DELETE\", \"GET\", \"HEAD\", \"OPTIONS\", \"PATCH\", \"POST\", \"PUT\"]);\nvar HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;\nvar encoder3 = new TextEncoder();\nfunction isObject(v) {\n return typeof v === \"object\" && v !== null;\n}\nfunction normalizeMethod(method) {\n const upper = method.toUpperCase();\n return NORMALIZED_METHODS.has(upper) ? upper : method;\n}\nvar RECORD_HOST_MAX_BYTES = 300;\nfunction printableAscii(s) {\n return /^[\\x21-\\x7e]+$/.test(s);\n}\nfunction recordableHost(host) {\n return host.length <= RECORD_HOST_MAX_BYTES && printableAscii(host) && !/[/?#@\\\\]/.test(host);\n}\nfunction recordablePath(path) {\n return path.startsWith(\"/\") && path.length <= NET_URL_MAX_BYTES && printableAscii(path);\n}\nfunction describeRequest(raw) {\n const r = isObject(raw) ? raw : {};\n const fields = { method: \"\", host: \"\", path: \"\" };\n const method = r.method === void 0 ? \"GET\" : r.method;\n if (typeof method === \"string\" && METHOD.test(method)) fields.method = normalizeMethod(method);\n if (typeof r.url === \"string\" && r.url.length <= 4 * NET_URL_MAX_BYTES) {\n try {\n const url = new URL(r.url);\n const host = normalizeHost(url.hostname) + (url.port === \"\" ? \"\" : `:${url.port}`);\n if (recordableHost(host)) fields.host = host;\n if (recordablePath(url.pathname)) fields.path = url.pathname;\n } catch {\n }\n }\n return fields;\n}\nfunction readUrl(raw, policy) {\n if (typeof raw !== \"string\" || raw === \"\") {\n throw handleError(\"ACTION_INVALID_CALL\", \"a request needs an absolute http(s) URL\");\n }\n if (raw.length > 4 * NET_URL_MAX_BYTES) {\n throw handleError(\"ACTION_LIMIT_EXCEEDED\", `a URL may be at most ${NET_URL_MAX_BYTES} bytes`);\n }\n let parsed;\n try {\n parsed = new URL(raw);\n } catch {\n throw handleError(\"ACTION_INVALID_CALL\", \"a request needs an absolute http(s) URL\");\n }\n const verdict = checkAddress(parsed, policy);\n if (!verdict.ok) throw handleError(\"NET_ADDRESS_BLOCKED\", verdict.reason);\n if (encoder3.encode(verdict.url.href).byteLength > NET_URL_MAX_BYTES) {\n throw handleError(\"ACTION_LIMIT_EXCEEDED\", `a URL may be at most ${NET_URL_MAX_BYTES} bytes`);\n }\n return { url: verdict.url, host: verdict.host };\n}\nfunction readMethod(raw) {\n if (raw === void 0) return \"GET\";\n if (typeof raw !== \"string\" || !METHOD.test(raw)) {\n throw handleError(\"ACTION_INVALID_CALL\", \"the method must be an HTTP method name\");\n }\n const method = normalizeMethod(raw);\n if (FORBIDDEN_METHODS.has(method.toUpperCase())) {\n throw handleError(\"ACTION_INVALID_CALL\", `${method} requests cannot be made`);\n }\n return method;\n}\nfunction headerPairs(raw) {\n if (raw === void 0 || raw === null) return [];\n if (Array.isArray(raw)) {\n return raw.map(\n (pair) => Array.isArray(pair) && pair.length === 2 ? [pair[0], pair[1]] : [null, null]\n );\n }\n if (isObject(raw)) return Object.entries(raw);\n throw handleError(\"ACTION_INVALID_CALL\", \"headers must be [name, value] pairs or an object\");\n}\nfunction readHeaders(raw) {\n const pairs = headerPairs(raw);\n if (pairs.length > NET_HEADERS_MAX) {\n throw handleError(\n \"ACTION_LIMIT_EXCEEDED\",\n `a request may have at most ${NET_HEADERS_MAX} headers`\n );\n }\n let bytes = 0;\n const out = [];\n for (const [name, value] of pairs) {\n if (typeof name !== \"string\" || typeof value !== \"string\" || !HEADER_NAME.test(name)) {\n throw handleError(\"ACTION_INVALID_CALL\", \"each header needs a valid name and a string value\");\n }\n bytes += encoder3.encode(name).byteLength + encoder3.encode(value).byteLength;\n const lower = name.toLowerCase();\n if (FORBIDDEN_HEADERS.has(lower) || FORBIDDEN_HEADER_PREFIXES.some((prefix) => lower.startsWith(prefix))) {\n throw handleError(\"ACTION_INVALID_CALL\", `the ${name} header cannot be set`);\n }\n if (!DROPPED_HEADERS.has(lower)) out.push([name, value]);\n }\n if (bytes > NET_HEADER_BYTES_MAX) {\n throw handleError(\n \"ACTION_LIMIT_EXCEEDED\",\n `a request's headers may be at most ${NET_HEADER_BYTES_MAX} bytes in all`\n );\n }\n return out;\n}\nfunction readBody(raw, method) {\n if (raw === void 0 || raw === null) return null;\n let body;\n if (typeof raw === \"string\") body = encoder3.encode(raw);\n else if (raw instanceof ArrayBuffer) body = new Uint8Array(raw);\n else if (ArrayBuffer.isView(raw))\n body = new Uint8Array(raw.buffer, raw.byteOffset, raw.byteLength);\n else throw handleError(\"ACTION_INVALID_CALL\", \"the body must be a string or bytes\");\n if (body.byteLength > NET_BODY_MAX_BYTES) {\n throw handleError(\n \"ACTION_LIMIT_EXCEEDED\",\n `a request body may be at most ${NET_BODY_MAX_BYTES} bytes`\n );\n }\n if (method === \"GET\" || method === \"HEAD\") {\n throw handleError(\"ACTION_INVALID_CALL\", `a ${method} request cannot have a body`);\n }\n return body;\n}\nfunction readTimeout(raw) {\n if (raw === void 0 || raw === null) return null;\n if (typeof raw !== \"number\" || !Number.isInteger(raw) || raw <= 0 || raw > NET_TIMEOUT_MAX_MS) {\n throw handleError(\n \"ACTION_INVALID_CALL\",\n `timeoutMs must be a whole number of milliseconds from 1 to ${NET_TIMEOUT_MAX_MS}`\n );\n }\n return raw;\n}\nfunction parseOutgoing(raw, policy) {\n if (!isObject(raw) || Array.isArray(raw)) {\n throw handleError(\"ACTION_INVALID_CALL\", \"a request needs { url, method, headers, body }\");\n }\n const { url, host } = readUrl(raw.url, policy);\n const method = readMethod(raw.method);\n const headers = readHeaders(raw.headers);\n const body = readBody(raw.body, method);\n const timeoutMs = readTimeout(raw.timeout_ms);\n if (!recordableHost(host) || !recordablePath(url.pathname)) {\n throw handleError(\"ACTION_INVALID_CALL\", \"the request cannot be recorded, so it is not sent\");\n }\n return { url: url.href, method, host, path: url.pathname, headers, body, timeoutMs };\n}\n\n// ../actions-worker/src/net-caller.ts\nvar NET_RESPONSE_MAX_BYTES = 1024 * 1024;\nvar NET_DEFAULT_TIMEOUT_MS = 3e4;\nvar NET_DEADLINE_MARGIN_MS = 3e3;\nvar NET_MIN_TIME_MS = 1e3;\nvar LOADER_BODY_BUDGET = { limit: 32 * 1024 * 1024, used: 0 };\nfunction codeOf(err) {\n const code = err?.code;\n return typeof code === \"string\" ? code : void 0;\n}\nvar Ended = class extends Error {\n code;\n result;\n constructor(code, message, result) {\n super(message);\n this.name = \"Ended\";\n this.code = code;\n this.result = result;\n }\n};\nvar BODYLESS_STATUS = /* @__PURE__ */ new Set([204, 205, 304]);\nasync function readAnswer(res, method, max, counted) {\n const bodyless = method === \"HEAD\" || BODYLESS_STATUS.has(res.status);\n const declared = Number(res.headers.get(\"Content-Length\") ?? \"\");\n if (!bodyless && Number.isFinite(declared) && declared > max) {\n await res.body?.cancel().catch(() => {\n });\n throw handleError(\"NET_RESPONSE_TOO_LARGE\", `an answer may be at most ${max} bytes`);\n }\n if (!res.body) return new ArrayBuffer(0);\n const reader = res.body.getReader();\n const chunks = [];\n let total = 0;\n for (; ; ) {\n const { done, value } = await reader.read();\n if (done) break;\n total += value.byteLength;\n counted(total);\n if (total > max) {\n await reader.cancel().catch(() => {\n });\n throw handleError(\"NET_RESPONSE_TOO_LARGE\", `an answer may be at most ${max} bytes`);\n }\n chunks.push(value);\n }\n const out = new Uint8Array(total);\n let off = 0;\n for (const c of chunks) {\n out.set(c, off);\n off += c.byteLength;\n }\n return out.buffer;\n}\nfunction createNetCaller(cfg, state) {\n const fetchImpl = cfg.fetchImpl ?? fetch;\n const beginFetch = cfg.beginFetch ?? fetch;\n const now = cfg.now ?? Date.now;\n const budget = cfg.budget ?? LOADER_BODY_BUDGET;\n const beginTarget = {\n ticket: cfg.ticket,\n invocationId: cfg.invocationId,\n instance: cfg.instance,\n callbackOrigin: cfg.callbackOrigin,\n fetchImpl: beginFetch\n };\n function record(result) {\n if (cfg.mode === \"record\") state.netCalls.push(result);\n }\n function timeLeft() {\n return cfg.deadlineMs - NET_DEADLINE_MARGIN_MS - now();\n }\n async function send(seq, out, outbound, controller, started) {\n const base2 = {\n seq,\n method: out.method,\n host: out.host,\n path: out.path,\n request_bytes: out.body?.byteLength ?? 0\n };\n if (cfg.mode === \"record\") {\n try {\n await begin(beginTarget, seq, out, Math.max(1, Math.min(BEGIN_TIMEOUT_MS, timeLeft())));\n } catch (err) {\n throw new Ended(codeOf(err) ?? \"NET_UNAVAILABLE\", err.message, {\n ...base2,\n status: \"refused\"\n });\n }\n }\n const left = timeLeft();\n if (left < NET_MIN_TIME_MS) {\n throw new Ended(\"ACTION_DEADLINE\", \"too little time is left before the action deadline\", {\n ...base2,\n status: \"refused\"\n });\n }\n const timer = setTimeout(\n () => controller.abort(),\n Math.min(out.timeoutMs ?? NET_DEFAULT_TIMEOUT_MS, left)\n );\n let res = null;\n let received = 0;\n try {\n res = await fetchImpl(outbound);\n if (res.status < 200 || res.status > 599) {\n await res.body?.cancel().catch(() => {\n });\n throw handleError(\"NET_FAILED\", \"the server answered with a status code outside 200\\u2013599\");\n }\n const body = await readAnswer(res, out.method, NET_RESPONSE_MAX_BYTES, (n) => {\n received = n;\n });\n const answer = {\n status: res.status,\n status_text: res.statusText,\n headers: [...res.headers],\n body,\n url: out.url\n };\n record({\n ...base2,\n status: \"ok\",\n http_status: res.status,\n response_bytes: body.byteLength,\n duration_ms: now() - started\n });\n return answer;\n } catch (err) {\n const timedOut = controller.signal.aborted;\n const code = timedOut ? \"NET_TIMEOUT\" : codeOf(err) ?? \"NET_FAILED\";\n const message = timedOut ? \"the request timed out; it may have reached the server\" : code === \"NET_FAILED\" && !codeOf(err) ? \"the request failed (connection, DNS or TLS); it may have reached the server\" : err.message;\n const answered = res !== null && res.status >= 200 && res.status <= 599;\n throw new Ended(code, message, {\n ...base2,\n status: \"failed\",\n ...answered ? { http_status: res?.status } : {},\n ...received > 0 ? { response_bytes: received } : {}\n });\n } finally {\n clearTimeout(timer);\n }\n }\n async function take(raw) {\n if (state.revoked) throw handleError(\"ACTION_HANDLE_REVOKED\", \"this handle is no longer valid\");\n if (cfg.maxRequests <= 0 || cfg.policy === null) {\n throw handleError(\n \"NET_UNAVAILABLE\",\n \"actions cannot make outbound requests on this deployment yet\"\n );\n }\n const started = now();\n const seq = ++state.netRequests;\n let fields = describeRequest(raw);\n const refuse = (code, message) => {\n record({ seq, status: \"refused\", ...fields, error_code: code, duration_ms: now() - started });\n return handleError(code, message);\n };\n const overLimit = `an action may make at most ${cfg.maxRequests} outbound requests`;\n if (seq > cfg.maxRequests) {\n state.netLimitHit = true;\n if (seq === cfg.maxRequests + 1) throw refuse(\"ACTION_LIMIT_EXCEEDED\", overLimit);\n throw handleError(\"ACTION_LIMIT_EXCEEDED\", overLimit);\n }\n if (timeLeft() < NET_MIN_TIME_MS) {\n throw refuse(\"ACTION_DEADLINE\", \"too little time is left before the action deadline\");\n }\n let out;\n try {\n out = parseOutgoing(raw, cfg.policy);\n } catch (err) {\n throw refuse(codeOf(err) ?? \"ACTION_INVALID_CALL\", err.message);\n }\n fields = { method: out.method, host: out.host, path: out.path };\n if (state.netInFlight >= cfg.maxInFlight) {\n throw refuse(\n \"ACTION_LIMIT_EXCEEDED\",\n `at most ${cfg.maxInFlight} requests may be in flight at once; wait for one to finish`\n );\n }\n const controller = new AbortController();\n let outbound;\n try {\n outbound = new Request(out.url, {\n method: out.method,\n headers: out.headers,\n body: out.body,\n redirect: \"manual\",\n cache: \"no-store\",\n signal: controller.signal\n });\n } catch {\n throw refuse(\"ACTION_INVALID_CALL\", \"the request's method, headers or body are not valid\");\n }\n const reserved = (out.body?.byteLength ?? 0) + NET_RESPONSE_MAX_BYTES;\n if (budget.used + reserved > budget.limit) {\n throw refuse(\n \"NET_BUSY\",\n \"the platform has too many requests in flight right now; nothing was sent, try again shortly\"\n );\n }\n budget.used += reserved;\n state.netInFlight++;\n const pending = send(seq, out, outbound, controller, started);\n state.inflight.add(pending);\n try {\n return await pending;\n } catch (err) {\n if (err instanceof Ended) {\n record({\n seq,\n status: \"failed\",\n method: out.method,\n host: out.host,\n path: out.path,\n ...err.result,\n error_code: err.code,\n duration_ms: now() - started\n });\n throw handleError(err.code, err.message);\n }\n throw err;\n } finally {\n state.inflight.delete(pending);\n state.netInFlight--;\n budget.used -= reserved;\n }\n }\n return {\n async request(raw) {\n try {\n return await take(raw);\n } catch (err) {\n if (codeOf(err)) throw err;\n throw handleError(\"NET_FAILED\", \"the request failed\");\n }\n }\n };\n}\n\n// ../actions-worker/src/outcome.ts\nvar encoder4 = new TextEncoder();\nfunction truncateBytes(s, maxBytes) {\n const bytes = encoder4.encode(s);\n if (bytes.byteLength <= maxBytes) return s;\n return new TextDecoder().decode(bytes.subarray(0, maxBytes)).replace(/\uFFFD+$/u, \"\");\n}\nfunction base(state) {\n return {\n db_calls: state.calls,\n data_seq: state.dataSeq,\n clip_calls: state.clipCalls,\n // In seq order; each was added as it ended.\n net_calls: [...state.netCalls].sort((a, b) => a.seq - b.seq)\n };\n}\nfunction limitMessage(state) {\n if (state.limitHit) return \"the action made more database calls than allowed\";\n if (state.clipLimitHit) return \"the action made more connector calls than allowed\";\n if (state.netLimitHit) return \"the action made more outbound requests than allowed\";\n if (state.parallLimitHit) return \"the action read Parall data more times than allowed\";\n return null;\n}\nfunction failed(state, error) {\n const limit = limitMessage(state);\n if (limit) {\n return { status: \"limit_exceeded\", error: { kind: \"limit\", message: limit }, ...base(state) };\n }\n return { status: \"failed\", error, ...base(state) };\n}\nfunction asString(v) {\n return typeof v === \"string\" ? v : \"\";\n}\nfunction outcomeFromResult(raw, limits, state) {\n if (typeof raw === \"object\" && raw !== null && !Array.isArray(raw)) {\n const r = raw;\n if (r.ok === true && typeof r.json === \"string\") {\n if (encoder4.encode(r.json).byteLength > limits.result_bytes) {\n return failed(state, {\n kind: \"unexpected\",\n message: `the action result is larger than ${limits.result_bytes} bytes`\n });\n }\n return { status: \"ok\", result_json: r.json, ...base(state) };\n }\n if (r.ok === false && typeof r.error === \"object\" && r.error !== null) {\n const e = r.error;\n if (e.kind === \"action_error\") {\n return failed(state, {\n kind: \"action_error\",\n message: truncateBytes(asString(e.message), limits.message_bytes)\n });\n }\n return failed(state, {\n kind: \"unexpected\",\n message: truncateBytes(asString(e.message), limits.message_bytes),\n stack: truncateBytes(asString(e.stack), limits.stack_bytes)\n });\n }\n }\n return failed(state, {\n kind: \"unexpected\",\n message: \"the action returned a result in an unknown shape\"\n });\n}\nvar CPU_LIMIT = /exceeded (its )?cpu|cpu time limit|exceeded resource limits/i;\nfunction isCpuLimitError(err) {\n const message = err instanceof Error ? err.message : String(err);\n return CPU_LIMIT.test(message);\n}\nfunction outcomeFromThrown(err, limits, state) {\n if (isCpuLimitError(err)) {\n return {\n status: \"limit_exceeded\",\n error: { kind: \"limit\", message: \"the action ran past its CPU time limit\" },\n ...base(state)\n };\n }\n const message = err instanceof Error ? `${err.name}: ${err.message}` : String(err);\n return failed(state, {\n kind: \"unexpected\",\n message: truncateBytes(message, limits.message_bytes)\n });\n}\nfunction timeoutOutcome(state) {\n return {\n status: \"timeout\",\n error: {\n kind: \"timeout\",\n message: \"the action ran past its deadline or lost a database answer; writes it started may have committed\"\n },\n ...base(state)\n };\n}\n\n// ../actions-worker/src/parall-caller.ts\nvar PARALL_MAX_REFS = 100;\nvar PARALL_GET_TIMEOUT_MS = 12e3;\nvar ENVELOPE_BYTES2 = 64 * 1024;\nvar encoder5 = new TextEncoder();\nfunction unavailable() {\n return handleError(\n \"PARALL_READ_UNAVAILABLE\",\n \"Parall data could not be read just now; nothing changed, so the read can be retried\"\n );\n}\nfunction refsOf(req) {\n const refs = typeof req === \"object\" && req !== null ? req.refs : null;\n if (!Array.isArray(refs) || refs.length === 0 || refs.length > PARALL_MAX_REFS || !refs.every((ref) => typeof ref === \"string\")) {\n throw handleError(\n \"ACTION_INVALID_CALL\",\n `get takes a list of 1 to ${PARALL_MAX_REFS} references (strings)`\n );\n }\n return refs;\n}\nfunction isItem(v) {\n if (typeof v !== \"object\" || v === null) return false;\n const i = v;\n if (i.ok === true)\n return typeof i.type === \"string\" && typeof i.item === \"object\" && i.item !== null;\n return i.ok === false && typeof i.code === \"string\";\n}\nfunction isMember(v) {\n return typeof v === \"object\" && v !== null && typeof v.user_id === \"string\";\n}\nfunction createParallCaller(cfg, state) {\n const fetchImpl = cfg.fetchImpl ?? fetch;\n const now = cfg.now ?? Date.now;\n const origin = cfg.callbackOrigin.replace(/\\/+$/, \"\");\n async function send(path, body, fits) {\n const headers = {\n \"Content-Type\": \"application/json\",\n \"User-Agent\": USER_AGENT,\n [TICKET_HEADER]: cfg.ticket,\n [INVOCATION_HEADER]: cfg.invocationId\n };\n if (cfg.instance !== \"default\") headers[SWIMLANE_HEADER] = cfg.instance;\n let res;\n try {\n res = await fetchImpl(`${origin}/api/v1/mini-app-actions/parall/${path}`, {\n method: \"POST\",\n headers,\n body,\n signal: AbortSignal.timeout(\n Math.max(1, Math.min(PARALL_GET_TIMEOUT_MS, cfg.deadlineMs - now()))\n )\n });\n } catch {\n if (now() >= cfg.deadlineMs) {\n throw handleError(\"ACTION_DEADLINE\", \"the action ran past its deadline\");\n }\n throw unavailable();\n }\n let parsed;\n try {\n const text = await readCapped(res, cfg.maxBytes + ENVELOPE_BYTES2);\n parsed = text ? JSON.parse(text) : null;\n } catch {\n throw unavailable();\n }\n if (res.ok) {\n const a = parsed;\n if (a?.ok === true && Array.isArray(a.value) && fits(a.value)) return a.value;\n throw unavailable();\n }\n const env = parsed?.error;\n if (typeof env?.code !== \"string\") throw unavailable();\n throw handleError(\n env.code,\n typeof env.message === \"string\" ? env.message : `the read was refused (${res.status})`\n );\n }\n function admit() {\n if (state.revoked) throw handleError(\"ACTION_HANDLE_REVOKED\", \"this handle is no longer valid\");\n if (cfg.maxReads <= 0) {\n throw handleError(\n \"PARALL_READ_UNAVAILABLE\",\n \"actions cannot read Parall data on this deployment\"\n );\n }\n if (now() >= cfg.deadlineMs)\n throw handleError(\"ACTION_DEADLINE\", \"the action ran past its deadline\");\n }\n function withinLimit() {\n if (state.parallReads >= cfg.maxReads) {\n state.parallLimitHit = true;\n throw handleError(\n \"ACTION_LIMIT_EXCEEDED\",\n `an action may read Parall data at most ${cfg.maxReads} times`\n );\n }\n }\n async function sendCounted(path, body, fits) {\n state.parallReads++;\n const pending = send(path, body, fits);\n state.inflight.add(pending);\n try {\n return await pending;\n } finally {\n state.inflight.delete(pending);\n }\n }\n async function get(req) {\n admit();\n const refs = refsOf(req);\n withinLimit();\n const body = JSON.stringify({ refs });\n if (encoder5.encode(body).byteLength > cfg.maxBytes) {\n throw handleError(\n \"ACTION_INVALID_CALL\",\n `a get's references may be at most ${cfg.maxBytes} bytes in all`\n );\n }\n return sendCounted(\"get\", body, (value) => value.length === refs.length && value.every(isItem));\n }\n async function members() {\n admit();\n withinLimit();\n return sendCounted(\"members\", \"{}\", (value) => value.every(isMember));\n }\n return { get, members };\n}\n\n// ../actions-worker/src/sandbox.ts\nvar COMPATIBILITY_DATE = \"2026-04-01\";\nvar COMPATIBILITY_FLAGS = [];\nvar ENTRYPOINT = \"ActionRunner\";\nvar PRELUDE = `// Runs before the author module (see actions-worker src/sandbox.ts).\nfor (const name of ['caches', 'WebSocket']) {\n try {\n delete globalThis[name];\n } catch {}\n if (name in globalThis) {\n Object.defineProperty(globalThis, name, { value: undefined, writable: false, configurable: false });\n }\n}\n`;\nvar ENTRY = `import './prelude.js';\nexport * from './author.js';\n`;\nfunction workerCode(authorSource) {\n return {\n compatibilityDate: COMPATIBILITY_DATE,\n compatibilityFlags: COMPATIBILITY_FLAGS,\n mainModule: \"entry.js\",\n modules: { \"entry.js\": ENTRY, \"prelude.js\": PRELUDE, \"author.js\": authorSource },\n env: {},\n globalOutbound: null\n };\n}\nvar runtimeVersion = null;\nfunction runtimeVersionOf() {\n if (!runtimeVersion) {\n const material = JSON.stringify([\n COMPATIBILITY_DATE,\n COMPATIBILITY_FLAGS,\n ENTRYPOINT,\n PRELUDE,\n ENTRY,\n \"env:{}\",\n \"outbound:null\"\n ]);\n runtimeVersion = crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(material)).then(\n (d) => Array.from(new Uint8Array(d).slice(0, 8), (b) => b.toString(16).padStart(2, \"0\")).join(\"\")\n );\n }\n return runtimeVersion;\n}\nfunction isolateId(instance, appId, sha256, runtime) {\n return `${instance}:${appId}:${sha256}:${runtime}`;\n}\n\n// ../actions-worker/src/run.ts\nvar DEADLINE_MARGIN_MS = 250;\nasync function runWithDeadline(call, budgetMs) {\n if (budgetMs <= 0) return { kind: \"timeout\" };\n let timer = null;\n const timedOut = new Promise((resolve) => {\n timer = setTimeout(() => resolve({ kind: \"timeout\" }), budgetMs);\n });\n try {\n return await Promise.race([\n call().then(\n (value) => ({ kind: \"result\", value }),\n (error) => ({ kind: \"thrown\", error })\n ),\n timedOut\n ]);\n } finally {\n if (timer !== null) clearTimeout(timer);\n }\n}\nasync function runInvocation(worker, req, opts) {\n const { callbackOrigin, loadFailure = () => null } = opts;\n const effectiveDeadline = req.deadline_ms - DEADLINE_MARGIN_MS;\n const caller = createDbCaller({\n kind: req.kind,\n ticket: req.ticket,\n invocationId: req.invocation_id,\n instance: req.instance,\n callbackOrigin,\n deadlineMs: effectiveDeadline,\n limits: req.limits\n });\n const clip = createClipCaller(\n {\n enabled: req.clip,\n ticket: req.ticket,\n invocationId: req.invocation_id,\n instance: req.instance,\n callbackOrigin,\n deadlineMs: effectiveDeadline,\n maxCalls: req.limits.clip_calls,\n maxBytes: req.limits.result_bytes\n },\n caller.state\n );\n const net = netLimits(req.limits);\n const netCaller = createNetCaller(\n {\n mode: opts.netMode,\n ticket: req.ticket,\n invocationId: req.invocation_id,\n instance: req.instance,\n callbackOrigin,\n deadlineMs: effectiveDeadline,\n maxRequests: net.requests,\n maxInFlight: net.inFlight,\n policy: opts.netPolicy\n },\n caller.state\n );\n const parall = createParallCaller(\n {\n ticket: req.ticket,\n invocationId: req.invocation_id,\n instance: req.instance,\n callbackOrigin,\n deadlineMs: effectiveDeadline,\n maxReads: parallReads(req.limits),\n maxBytes: req.limits.result_bytes\n },\n caller.state\n );\n const handle = makeHandle(caller, clip, netCaller, parall);\n const entry = worker.getEntrypoint(ENTRYPOINT, { limits: { cpuMs: req.limits.cpu_ms } });\n const settled = await runWithDeadline(\n () => entry.run(\n {\n action: req.action,\n params: req.params,\n viewer: req.viewer,\n app: req.app,\n invocation_id: req.invocation_id,\n // The app's secrets, as ctx.env (mini-app-network-design.md \u00A77.4):\n // per call, never in the isolate's own env.\n env: req.env ?? {},\n // How many requests the SDK lets run at once; it queues the rest.\n net_in_flight: net.inFlight\n },\n handle\n ),\n effectiveDeadline - Date.now()\n );\n const drained = await settle(caller, effectiveDeadline);\n if (settled.kind === \"timeout\" || !drained || caller.state.indeterminate) {\n return timeoutOutcome(caller.state);\n }\n if (settled.kind === \"thrown\") {\n return loadFailure() ?? outcomeFromThrown(settled.error, req.limits, caller.state);\n }\n return outcomeFromResult(settled.value, req.limits, caller.state);\n}\n\n// ../actions-worker/src/local.ts\nvar local_default = {\n async fetch(request, env) {\n let body;\n try {\n body = await request.json();\n } catch {\n return Response.json({ error: \"body is not JSON\" }, { status: 400 });\n }\n const req = parseInvokeRequest(body?.request, { unpublished: true });\n if (typeof req === \"string\") return Response.json({ error: `invalid ${req}` }, { status: 400 });\n if (typeof body.source !== \"string\" || typeof body.callback_origin !== \"string\") {\n return Response.json({ error: \"source and callback_origin are required\" }, { status: 400 });\n }\n const runtime = await runtimeVersionOf();\n const worker = env.LOADER.get(\n isolateId(req.instance, req.app.id, req.module.sha256, runtime),\n async () => workerCode(body.source)\n );\n return Response.json(\n await runInvocation(worker, req, {\n callbackOrigin: body.callback_origin,\n netPolicy: policyFrom(\n env.NET_BLOCKED_HOSTS,\n env.NET_TEST_ALLOW_LOOPBACK,\n body.callback_origin\n ),\n netMode: \"direct\"\n })\n );\n }\n};\nexport {\n local_default as default\n};\n";
4
4
  //# sourceMappingURL=apps-local-runner.generated.d.ts.map