@parall/cli 1.72.0 → 1.74.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/commands/apps-action-local.d.ts.map +1 -1
- package/dist/commands/apps-action-local.js +1 -0
- package/dist/commands/apps-actions-sdk.generated.d.ts +1 -1
- package/dist/commands/apps-actions-sdk.generated.d.ts.map +1 -1
- package/dist/commands/apps-actions-sdk.generated.js +1 -1
- package/dist/commands/apps-local-runner.generated.d.ts +1 -1
- package/dist/commands/apps-local-runner.generated.d.ts.map +1 -1
- package/dist/commands/apps-local-runner.generated.js +1 -1
- package/dist/commands/apps-page-sdk.generated.d.ts +1 -1
- package/dist/commands/apps-page-sdk.generated.d.ts.map +1 -1
- package/dist/commands/apps-page-sdk.generated.js +1 -1
- package/dist/commands/apps-scaffold-actions.js +1 -0
- package/dist/lib/edge-exec.d.ts +1 -1
- package/dist/lib/edge-exec.js +1 -1
- package/package.json +4 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"apps-action-local.d.ts","sourceRoot":"","sources":["../../src/commands/apps-action-local.ts"],"names":[],"mappings":"AAGA,OAAO,EAEL,KAAK,yBAAyB,EAC9B,KAAK,iBAAiB,EACtB,KAAK,mBAAmB,EACzB,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAQ3D;;;;;;;;;;;;cAYc;AAEd,MAAM,WAAW,WAAW;IAC1B,+DAA+D;IAC/D,WAAW,EAAE,OAAO,CAAC;IACrB,IAAI,EAAE,iBAAiB,CAAC;IACxB,MAAM,EAAE,mBAAmB,GAAG,IAAI,CAAC;IACnC,qDAAqD;IACrD,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;CAChB;AAED;iEACiE;AACjE,wBAAsB,eAAe,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,CAAC,CAiBtF;AAED,KAAK,MAAM,GAAG,UAAU,CAAC,OAAO,kBAAkB,CAAC,CAAC,QAAQ,CAAC,CAAC;AAU9D;6BAC6B;AAC7B,MAAM,WAAW,gBAAgB;IAC/B,4DAA4D;IAC5D,OAAO,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;IACjC,qDAAqD;IACrD,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,EAAE,EAAE,MAAM,CAAA;KAAE,KAAK,IAAI,CAAC;CAC7D;AAMD;uEACuE;AACvE,wBAAsB,cAAc,CAClC,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,MAAM,EACb,KAAK,EAAE,MAAM,EACb,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,WAAW,EACnB,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC/B,OAAO,GAAE,gBAAqB,GAC7B,OAAO,CAAC,yBAAyB,CAAC,
|
|
1
|
+
{"version":3,"file":"apps-action-local.d.ts","sourceRoot":"","sources":["../../src/commands/apps-action-local.ts"],"names":[],"mappings":"AAGA,OAAO,EAEL,KAAK,yBAAyB,EAC9B,KAAK,iBAAiB,EACtB,KAAK,mBAAmB,EACzB,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAQ3D;;;;;;;;;;;;cAYc;AAEd,MAAM,WAAW,WAAW;IAC1B,+DAA+D;IAC/D,WAAW,EAAE,OAAO,CAAC;IACrB,IAAI,EAAE,iBAAiB,CAAC;IACxB,MAAM,EAAE,mBAAmB,GAAG,IAAI,CAAC;IACnC,qDAAqD;IACrD,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;CAChB;AAED;iEACiE;AACjE,wBAAsB,eAAe,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,CAAC,CAiBtF;AAED,KAAK,MAAM,GAAG,UAAU,CAAC,OAAO,kBAAkB,CAAC,CAAC,QAAQ,CAAC,CAAC;AAU9D;6BAC6B;AAC7B,MAAM,WAAW,gBAAgB;IAC/B,4DAA4D;IAC5D,OAAO,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;IACjC,qDAAqD;IACrD,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,EAAE,EAAE,MAAM,CAAA;KAAE,KAAK,IAAI,CAAC;CAC7D;AAMD;uEACuE;AACvE,wBAAsB,cAAc,CAClC,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,MAAM,EACb,KAAK,EAAE,MAAM,EACb,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,WAAW,EACnB,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC/B,OAAO,GAAE,gBAAqB,GAC7B,OAAO,CAAC,yBAAyB,CAAC,CAiEpC"}
|
|
@@ -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\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/** 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 ActionContext {\n viewer: ActionViewer;\n app: ActionApp;\n db: ActionDb;\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/invoke.ts). */\nexport interface ActionRunRequest {\n action: string;\n params: unknown;\n viewer: ActionViewer;\n app: ActionApp;\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/** The per-invocation database handle the loader passes run(). */\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}\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 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 label = e instanceof ActionDbError ? `${e.name} ${e.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>(call: Promise<ActionHandleResult>): Promise<T> => {\n const dbCall = new DbCall<T>((resolve, reject) => {\n call.then(unwrap).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 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({ viewer: req.viewer, app: req.app, db }, req.params);\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 Clip 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\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 Clip call that was refused or failed. `code` is the platform's \u2014 the\n * same codes the caller gets running `parall clip 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/** 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 clip 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: Clip calls as the action's caller; actions that declare clip only. */\nexport interface ActionClip {\n /** Runs a command of a Clip (its name or crg_ id) and returns the Clip's\n * data; throws ClipError. */\n exec(clip: string, command: string, args: unknown, options: ActionClipOptions): Promise<unknown>;\n}\n\nexport interface ActionContext {\n viewer: ActionViewer;\n app: ActionApp;\n db: ActionDb;\n clip: ActionClip;\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/invoke.ts). */\nexport interface ActionRunRequest {\n action: string;\n params: unknown;\n viewer: ActionViewer;\n app: ActionApp;\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/** The per-invocation handle the loader passes run(). A loader before Clip\n * calls has no clip method. */\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}\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 Clip call answered in an unknown shape; it may or may not have run',\n );\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 label =\n e instanceof ActionDbError || e instanceof ClipError ? `${e.name} ${e.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: { code: 'CLIP_UNAVAILABLE', message: 'this runtime cannot call Clip yet' },\n });\n return track(sent, unwrapClip);\n },\n };\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({ viewer: req.viewer, app: req.app, db, clip }, req.params);\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,
|
|
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,kqaAAima,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\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/** 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 ActionContext {\n viewer: ActionViewer;\n app: ActionApp;\n db: ActionDb;\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/invoke.ts). */\nexport interface ActionRunRequest {\n action: string;\n params: unknown;\n viewer: ActionViewer;\n app: ActionApp;\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/** The per-invocation database handle the loader passes run(). */\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}\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 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 label = e instanceof ActionDbError ? `${e.name} ${e.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>(call: Promise<ActionHandleResult>): Promise<T> => {\n const dbCall = new DbCall<T>((resolve, reject) => {\n call.then(unwrap).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 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({ viewer: req.viewer, app: req.app, db }, req.params);\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 Clip 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\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 Clip call that was refused or failed. `code` is the platform's — the\n * same codes the caller gets running `parall clip 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/** 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 clip 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: Clip calls as the action's caller; actions that declare clip only. */\nexport interface ActionClip {\n /** Runs a command of a Clip (its name or crg_ id) and returns the Clip's\n * data; throws ClipError. */\n exec(clip: string, command: string, args: unknown, options: ActionClipOptions): Promise<unknown>;\n}\n\nexport interface ActionContext {\n viewer: ActionViewer;\n app: ActionApp;\n db: ActionDb;\n clip: ActionClip;\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/invoke.ts). */\nexport interface ActionRunRequest {\n action: string;\n params: unknown;\n viewer: ActionViewer;\n app: ActionApp;\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/** The per-invocation handle the loader passes run(). A loader before Clip\n * calls has no clip method. */\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}\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 Clip call answered in an unknown shape; it may or may not have run',\n );\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 label =\n e instanceof ActionDbError || e instanceof ClipError ? `${e.name} ${e.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: { code: 'CLIP_UNAVAILABLE', message: 'this runtime cannot call Clip yet' },\n });\n return track(sent, unwrapClip);\n },\n };\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({ viewer: req.viewer, app: req.app, db, clip }, req.params);\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,3 +1,3 @@
|
|
|
1
1
|
export declare const LOCAL_RUNNER_COMPATIBILITY_DATE = "2026-04-01";
|
|
2
|
-
export declare const LOCAL_RUNNER_SOURCE = "// ../actions-worker/src/contract.ts\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};\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 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 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 (!(\"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 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 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\n };\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 };\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}\nasync function settleCall(caller, op, payload) {\n try {\n return { ok: true, value: await caller.call(op, payload) };\n } catch (err) {\n const { code, message } = err ?? {};\n return {\n ok: false,\n error: {\n code: typeof code === \"string\" ? code : \"ACTION_DB_UNAVAILABLE\",\n message: typeof message === \"string\" ? message : \"the database call failed\"\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/handle.ts\nimport { RpcTarget } from \"cloudflare:workers\";\nvar ActionDb = class extends RpcTarget {\n #caller;\n constructor(caller) {\n super();\n this.#caller = caller;\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};\nfunction makeHandle(caller) {\n return new ActionDb(caller);\n}\n\n// ../actions-worker/src/outcome.ts\nvar encoder2 = new TextEncoder();\nfunction truncateBytes(s, maxBytes) {\n const bytes = encoder2.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 { db_calls: state.calls, data_seq: state.dataSeq };\n}\nfunction failed(state, error) {\n if (state.limitHit) {\n return {\n status: \"limit_exceeded\",\n error: { kind: \"limit\", message: \"the action made more database calls than allowed\" },\n ...base(state)\n };\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 (encoder2.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/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, callbackOrigin, loadFailure = () => null) {\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 handle = makeHandle(caller);\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 },\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(await runInvocation(worker, req, body.callback_origin));\n }\n};\nexport {\n local_default as default\n};\n";
|
|
2
|
+
export declare const LOCAL_RUNNER_SOURCE = "// ../actions-worker/src/contract.ts\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;\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 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 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 };\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 };\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 constructor(caller, clip) {\n super();\n this.#caller = caller;\n this.#clip = clip;\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};\nfunction makeHandle(caller, clip) {\n return new ActionHandle(caller, clip);\n}\n\n// ../actions-worker/src/outcome.ts\nvar encoder3 = new TextEncoder();\nfunction truncateBytes(s, maxBytes) {\n const bytes = encoder3.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 { db_calls: state.calls, data_seq: state.dataSeq, clip_calls: state.clipCalls };\n}\nfunction failed(state, error) {\n if (state.limitHit || state.clipLimitHit) {\n return {\n status: \"limit_exceeded\",\n error: {\n kind: \"limit\",\n message: state.limitHit ? \"the action made more database calls than allowed\" : \"the action made more Clip calls than allowed\"\n },\n ...base(state)\n };\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 (encoder3.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/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, callbackOrigin, loadFailure = () => null) {\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 handle = makeHandle(caller, clip);\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 },\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(await runInvocation(worker, req, body.callback_origin));\n }\n};\nexport {\n local_default as default\n};\n";
|
|
3
3
|
//# sourceMappingURL=apps-local-runner.generated.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"apps-local-runner.generated.d.ts","sourceRoot":"","sources":["../../src/commands/apps-local-runner.generated.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,+BAA+B,eAAe,CAAC;AAE5D,eAAO,MAAM,mBAAmB,
|
|
1
|
+
{"version":3,"file":"apps-local-runner.generated.d.ts","sourceRoot":"","sources":["../../src/commands/apps-local-runner.generated.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,+BAA+B,eAAe,CAAC;AAE5D,eAAO,MAAM,mBAAmB,sitBAAiitB,CAAC"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// Generated from ts/actions-worker/src/local.ts by scripts/generate-local-runner.mjs. Do not edit.
|
|
2
2
|
export const LOCAL_RUNNER_COMPATIBILITY_DATE = '2026-04-01';
|
|
3
3
|
// biome-ignore format: generated copy
|
|
4
|
-
export const LOCAL_RUNNER_SOURCE = "// ../actions-worker/src/contract.ts\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};\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 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 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 (!(\"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 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 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\n };\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 };\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}\nasync function settleCall(caller, op, payload) {\n try {\n return { ok: true, value: await caller.call(op, payload) };\n } catch (err) {\n const { code, message } = err ?? {};\n return {\n ok: false,\n error: {\n code: typeof code === \"string\" ? code : \"ACTION_DB_UNAVAILABLE\",\n message: typeof message === \"string\" ? message : \"the database call failed\"\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/handle.ts\nimport { RpcTarget } from \"cloudflare:workers\";\nvar ActionDb = class extends RpcTarget {\n #caller;\n constructor(caller) {\n super();\n this.#caller = caller;\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};\nfunction makeHandle(caller) {\n return new ActionDb(caller);\n}\n\n// ../actions-worker/src/outcome.ts\nvar encoder2 = new TextEncoder();\nfunction truncateBytes(s, maxBytes) {\n const bytes = encoder2.encode(s);\n if (bytes.byteLength <= maxBytes) return s;\n return new TextDecoder().decode(bytes.subarray(0, maxBytes)).replace(/�+$/u, \"\");\n}\nfunction base(state) {\n return { db_calls: state.calls, data_seq: state.dataSeq };\n}\nfunction failed(state, error) {\n if (state.limitHit) {\n return {\n status: \"limit_exceeded\",\n error: { kind: \"limit\", message: \"the action made more database calls than allowed\" },\n ...base(state)\n };\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 (encoder2.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/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, callbackOrigin, loadFailure = () => null) {\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 handle = makeHandle(caller);\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 },\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(await runInvocation(worker, req, body.callback_origin));\n }\n};\nexport {\n local_default as default\n};\n";
|
|
4
|
+
export const LOCAL_RUNNER_SOURCE = "// ../actions-worker/src/contract.ts\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;\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 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 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 };\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 };\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 constructor(caller, clip) {\n super();\n this.#caller = caller;\n this.#clip = clip;\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};\nfunction makeHandle(caller, clip) {\n return new ActionHandle(caller, clip);\n}\n\n// ../actions-worker/src/outcome.ts\nvar encoder3 = new TextEncoder();\nfunction truncateBytes(s, maxBytes) {\n const bytes = encoder3.encode(s);\n if (bytes.byteLength <= maxBytes) return s;\n return new TextDecoder().decode(bytes.subarray(0, maxBytes)).replace(/�+$/u, \"\");\n}\nfunction base(state) {\n return { db_calls: state.calls, data_seq: state.dataSeq, clip_calls: state.clipCalls };\n}\nfunction failed(state, error) {\n if (state.limitHit || state.clipLimitHit) {\n return {\n status: \"limit_exceeded\",\n error: {\n kind: \"limit\",\n message: state.limitHit ? \"the action made more database calls than allowed\" : \"the action made more Clip calls than allowed\"\n },\n ...base(state)\n };\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 (encoder3.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/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, callbackOrigin, loadFailure = () => null) {\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 handle = makeHandle(caller, clip);\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 },\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(await runInvocation(worker, req, body.callback_origin));\n }\n};\nexport {\n local_default as default\n};\n";
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export declare const PAGE_SDK_SOURCE = "/**\n * @parall/miniapp-sdk \u2014 the page side of the Mini App bridge (design \u00A77.1):\n * host handshake, host\u2192page events, resize, and `action`, the page's only\n * data method: it calls one of the app's server-side actions through the\n * host, which adds the viewer's session and the version the page loaded\n * (Mini App Action design \u00A73.1). No db, files, clip or chat methods exist\n * on this surface. The transport is postMessage to window.parent; the host\n * validates our origin, we validate that messages come from our parent\n * and, after the first answer, pin the parent's origin.\n *\n * Protocol (request/response + events):\n * page \u2192 host {parall: 'v1', id, method: 'ready' | 'resize' | 'action' | 'report', params}\n * host \u2192 page {parall: 'v1', id, result} | {parall: 'v1', id, error: {code, message, details?}}\n * host \u2192 page {parall: 'v1', event: 'route.changed' | 'viewer.changed' | 'data.changed', data}\n */\n\nexport interface ViewerSummary {\n id: string;\n display_name: string;\n is_agent: boolean;\n /** The viewer's organization role (owner / admin / member) \u2014 the same\n * value an action sees as ctx.viewer.role. */\n role?: string;\n}\n\nexport interface AppSummary {\n id: string;\n name: string;\n version_seq: number;\n}\n\nexport interface ReadyResult {\n viewer: ViewerSummary;\n app: AppSummary;\n route: string;\n}\n\n/** A Database the app reads was written. It carries no data: read again. */\nexport interface DataChanged {\n database_id: string;\n data_seq: number;\n /** Sent once after the host's connection came back: writes in between\n * may have been missed, so read again whatever data_seq says. */\n catch_up?: boolean;\n}\n\nexport type HostEvent =\n | { event: 'route.changed'; data: { route: string } }\n | { event: 'viewer.changed'; data: { viewer: ViewerSummary } }\n | { event: 'data.changed'; data: DataChanged };\n\n/** A refusal or failure from the host, in the error-contract envelope. An\n * action's failure keeps the server's code and details (invocation_id,\n * error_kind, field, current_version_seq\u2026); APP_VERSION_CHANGED means the\n * app was updated and the host offers the viewer a reload. */\nexport interface BridgeError extends Error {\n code: string;\n details?: Record<string, unknown>;\n}\n\ninterface WireError {\n code: string;\n message: string;\n details?: Record<string, unknown>;\n}\n\ntype Pending = {\n resolve: (v: unknown) => void;\n reject: (e: Error) => void;\n timer: ReturnType<typeof setTimeout>;\n};\n\nconst PROTOCOL = 'v1';\n\n// How long the page waits for the host. An action waits longer than the\n// host's request timeout, which waits longer than the server takes to\n// answer at worst, so the page always gets the server's answer rather than\n// a timeout of its own (Mini App Action design \u00A73.1, \u00A715).\nconst HOST_TIMEOUT_MS = 10_000;\nconst ACTION_TIMEOUT_MS = 30_000;\n\n// Marks the errors the bridge itself rejects with: what the host or the\n// server answered, never the page's own bug.\nconst FROM_BRIDGE = Symbol.for('parall.bridge-error');\n\nfunction bridgeError(\n code: string,\n message: string,\n details?: Record<string, unknown>,\n): BridgeError {\n const err = Object.assign(new Error(message), { code, details }) as BridgeError;\n Object.defineProperty(err, FROM_BRIDGE, { value: true });\n return err;\n}\n\n/**\n * What a page reports when something goes wrong (Mini App design \u00A79): an\n * error thrown on the page, a promise rejected without a handler, and an\n * action call that failed unexpectedly, timed out or ran over its limits.\n * Never console.error, and never an ActionError \u2014 that is the author's own\n * message to the caller. The host adds the version the page loaded and\n * reports it in the viewer's name; the app's authors are told.\n */\ntype ErrorReport = {\n kind: 'exception' | 'rejection' | 'action';\n name?: string;\n message?: string;\n stack?: string;\n action?: string;\n code?: string;\n invocation_id?: string;\n};\n\n// Each kind of error once per page load, and only so many: a page stuck in\n// a loop must not flood its authors (the server keeps its own budgets).\nconst REPORTS_PER_LOAD = 10;\nconst REPORTED_ACTION_CODES = new Set(['ACTION_TIMEOUT', 'ACTION_LIMIT_EXCEEDED']);\n\nfunction clip(s: string | undefined, max: number): string | undefined {\n return s && s.length > max ? s.slice(0, max) : s;\n}\n\n// A stack line that names a place in the code (file:line[:col]).\nconst FRAME = /:\\d+(?::\\d+)?\\)?$/;\n\n/** What makes two reports the same error \u2014 the way the server groups them:\n * an action failure by its action and code; anything else by its kind, its\n * name and the places its stack names, or by its message when the stack\n * names none. One throw site with a changing message is one error. */\nfunction reportKey(r: ErrorReport): string {\n if (r.kind === 'action') return `action\\u0000${r.action}\\u0000${r.code}`;\n const frames = (r.stack ?? '')\n .split('\\n')\n .map((line) => line.trim())\n .filter((line) => line !== '' && FRAME.test(line));\n return frames.length > 0\n ? `${r.kind}\\u0000${r.name}\\u0000${frames.join('\\n')}`\n : `${r.kind}\\u0000${r.name}\\u0000message\\u0000${r.message}`;\n}\n\nfunction describe(value: unknown): string {\n if (typeof value === 'string') return value;\n try {\n return JSON.stringify(value) ?? String(value);\n } catch {\n return String(value);\n }\n}\n\nclass MiniAppBridge {\n private nextId = 1;\n private pending = new Map<number, Pending>();\n private listeners = new Set<(e: HostEvent) => void>();\n private hostOrigin: string | null = null;\n private started = false;\n private reported = new Set<string>();\n\n constructor() {\n if (typeof window === 'undefined' || typeof window.addEventListener !== 'function') return;\n window.addEventListener('error', (event: ErrorEvent) => {\n const err: unknown = event.error;\n if (err instanceof Error) {\n this.report({ kind: 'exception', name: err.name, message: err.message, stack: err.stack });\n } else {\n const where = event.filename\n ? ` at ${event.filename}:${event.lineno}:${event.colno}`\n : '';\n this.report({\n kind: 'exception',\n name: 'Error',\n message: String(event.message || 'Script error.'),\n stack: where,\n });\n }\n });\n window.addEventListener('unhandledrejection', (event: PromiseRejectionEvent) => {\n const reason: unknown = event.reason;\n // The bridge's own rejections are the host's or the server's answers:\n // a failed action is reported where it failed, by its own rules.\n if (reason !== null && typeof reason === 'object' && FROM_BRIDGE in reason) return;\n if (reason instanceof Error) {\n this.report({\n kind: 'rejection',\n name: reason.name,\n message: reason.message,\n stack: reason.stack,\n });\n } else {\n this.report({ kind: 'rejection', name: '', message: describe(reason) });\n }\n });\n }\n\n /** Sends one error report to the host; drops repeats, anything past the\n * page's share, and every failure of the report itself (an older host\n * answers NOT_GRANTED). */\n private report(r: ErrorReport): void {\n // Cut to what the host may send: the server takes at most 16 KiB.\n const params: ErrorReport = {\n ...r,\n name: clip(r.name, 100),\n message: clip(r.message, 500),\n stack: clip(r.stack, 3000),\n };\n const key = reportKey(params);\n if (this.reported.has(key) || this.reported.size >= REPORTS_PER_LOAD) return;\n this.reported.add(key);\n void this.call('report', params).catch(() => {});\n }\n\n private start(): void {\n if (this.started) return;\n this.started = true;\n window.addEventListener('message', (event: MessageEvent) => {\n // Only our embedding host: same source as window.parent, and once\n // the handshake pinned an origin, exactly that origin.\n if (event.source !== window.parent) return;\n if (this.hostOrigin !== null && event.origin !== this.hostOrigin) return;\n const msg = event.data as Record<string, unknown> | null;\n if (!msg || msg.parall !== PROTOCOL) return;\n if (typeof msg.id === 'number') {\n const pending = this.pending.get(msg.id);\n if (!pending) return;\n this.pending.delete(msg.id);\n clearTimeout(pending.timer);\n if (this.hostOrigin === null) this.hostOrigin = event.origin;\n if (msg.error) {\n const err = msg.error as WireError;\n pending.reject(bridgeError(err.code, err.message, err.details));\n } else {\n pending.resolve(msg.result);\n }\n return;\n }\n if (typeof msg.event === 'string') {\n for (const fn of this.listeners) fn(msg as unknown as HostEvent);\n }\n });\n }\n\n private call<T>(method: string, params?: unknown, timeoutMs = HOST_TIMEOUT_MS): Promise<T> {\n this.start();\n const id = this.nextId++;\n return new Promise<T>((resolve, reject) => {\n const timer = setTimeout(() => {\n if (this.pending.delete(id)) {\n reject(bridgeError('HOST_TIMEOUT', `${method} timed out waiting for the host`));\n }\n }, timeoutMs);\n this.pending.set(id, { resolve: resolve as (v: unknown) => void, reject, timer });\n window.parent.postMessage({ parall: PROTOCOL, id, method, params }, '*');\n });\n }\n\n /** Handshake with the host; resolves with the viewer, app and initial route. */\n ready(): Promise<ReadyResult> {\n return this.call<ReadyResult>('ready');\n }\n\n /** Ask the host to grow/shrink the iframe (fire-and-forget semantics). */\n resize(height: number): void {\n void this.call('resize', { height }).catch(() => {});\n }\n\n /**\n * Call one of the app's actions with the viewer's identity and resolve\n * with what the action returned. A failure rejects with a BridgeError\n * whose code is the server's (ACTION_FAILED, ACTION_TIMEOUT,\n * INVALID_ACTION_PARAMS, APP_VERSION_CHANGED\u2026); its message is the\n * action's ActionError message when it threw one. HOST_TIMEOUT and\n * HOST_UNAVAILABLE mean no answer came back: whether the action ran is\n * not known, so read again before retrying a write.\n */\n async action<T = unknown>(name: string, params?: Record<string, unknown>): Promise<T> {\n let answer: { invocation_id: string; result: T };\n try {\n answer = await this.call<{ invocation_id: string; result: T }>(\n 'action',\n { name, params: params ?? {} },\n ACTION_TIMEOUT_MS,\n );\n } catch (err) {\n // The app's authors hear of an action that failed unexpectedly, timed\n // out or ran over its limits \u2014 caught by the page or not. An\n // ActionError (error_kind \"action\") is the author's own answer.\n const e = err as BridgeError;\n const unexpected = e.code === 'ACTION_FAILED' && e.details?.error_kind === 'unexpected';\n if (unexpected || REPORTED_ACTION_CODES.has(e.code)) {\n const invocation = e.details?.invocation_id;\n this.report({\n kind: 'action',\n action: name,\n code: e.code,\n invocation_id: typeof invocation === 'string' ? invocation : undefined,\n });\n }\n throw err;\n }\n return answer.result;\n }\n\n /** Subscribe to host events; returns the unsubscribe function. */\n onEvent(fn: (e: HostEvent) => void): () => void {\n this.start();\n this.listeners.add(fn);\n return () => this.listeners.delete(fn);\n }\n\n /**\n * Call fn when a Database the app reads has new writes: once per new\n * (database_id, data_seq) \u2014 repeats and older ones are dropped \u2014 and\n * always on a catch-up after the host reconnected. Read again in fn.\n */\n onDataChanged(fn: (change: DataChanged) => void): () => void {\n const seen = new Map<string, number>();\n return this.onEvent((e) => {\n if (e.event !== 'data.changed') return;\n const { database_id, data_seq, catch_up } = e.data;\n const last = seen.get(database_id);\n if (!catch_up && last !== undefined && data_seq <= last) return;\n if (last === undefined || data_seq > last) seen.set(database_id, data_seq);\n fn(e.data);\n });\n }\n}\n\nexport const parall = new MiniAppBridge();\n";
|
|
1
|
+
export declare const PAGE_SDK_SOURCE = "/**\n * @parall/miniapp-sdk \u2014 the page side of the Mini App bridge (design \u00A77.1):\n * host handshake, host\u2192page events, resize, and `action`, the page's only\n * data method: it calls one of the app's server-side actions through the\n * host, which adds the viewer's session and the version the page loaded\n * (Mini App Action design \u00A73.1). No db, files, clip or chat methods exist\n * on this surface. The transport is postMessage to window.parent; the host\n * validates our origin, we validate that messages come from our parent\n * and, after the first answer, pin the parent's origin.\n *\n * Protocol (request/response + events):\n * page \u2192 host {parall: 'v1', id, method: 'ready' | 'resize' | 'action' | 'report', params}\n * host \u2192 page {parall: 'v1', id, result} | {parall: 'v1', id, error: {code, message, details?}}\n * host \u2192 page {parall: 'v1', event: 'route.changed' | 'viewer.changed' | 'data.changed', data}\n */\n\nexport interface ViewerSummary {\n id: string;\n display_name: string;\n is_agent: boolean;\n /** The viewer's organization role (owner / admin / member) \u2014 the same\n * value an action sees as ctx.viewer.role. */\n role?: string;\n}\n\nexport interface AppSummary {\n id: string;\n name: string;\n version_seq: number;\n}\n\nexport interface ReadyResult {\n viewer: ViewerSummary;\n app: AppSummary;\n route: string;\n}\n\n/** A Database the app reads was written. It carries no data: read again. */\nexport interface DataChanged {\n database_id: string;\n data_seq: number;\n /** Sent once after the host's connection came back: writes in between\n * may have been missed, so read again whatever data_seq says. */\n catch_up?: boolean;\n}\n\nexport type HostEvent =\n | { event: 'route.changed'; data: { route: string } }\n | { event: 'viewer.changed'; data: { viewer: ViewerSummary } }\n | { event: 'data.changed'; data: DataChanged };\n\n/** A refusal or failure from the host, in the error-contract envelope. An\n * action's failure keeps the server's code and details (invocation_id,\n * error_kind, field, current_version_seq\u2026); APP_VERSION_CHANGED means the\n * app was updated and the host offers the viewer a reload. */\nexport interface BridgeError extends Error {\n code: string;\n details?: Record<string, unknown>;\n}\n\ninterface WireError {\n code: string;\n message: string;\n details?: Record<string, unknown>;\n}\n\ntype Pending = {\n resolve: (v: unknown) => void;\n reject: (e: Error) => void;\n timer: ReturnType<typeof setTimeout>;\n};\n\nconst PROTOCOL = 'v1';\n\n// How long the page waits for the host. An action waits longer than the\n// host's request timeout, which waits longer than the server takes to\n// answer at worst \u2014 an action that calls Clip may run 100 s \u2014 so the page\n// always gets the server's answer rather than a timeout of its own (Mini\n// App Action design \u00A73.1, \u00A715; Clip design \u00A74.2).\nconst HOST_TIMEOUT_MS = 10_000;\nconst ACTION_TIMEOUT_MS = 120_000;\n\n// Marks the errors the bridge itself rejects with: what the host or the\n// server answered, never the page's own bug.\nconst FROM_BRIDGE = Symbol.for('parall.bridge-error');\n\nfunction bridgeError(\n code: string,\n message: string,\n details?: Record<string, unknown>,\n): BridgeError {\n const err = Object.assign(new Error(message), { code, details }) as BridgeError;\n Object.defineProperty(err, FROM_BRIDGE, { value: true });\n return err;\n}\n\n/**\n * What a page reports when something goes wrong (Mini App design \u00A79): an\n * error thrown on the page, a promise rejected without a handler, and an\n * action call that failed unexpectedly, timed out or ran over its limits.\n * Never console.error, and never an ActionError \u2014 that is the author's own\n * message to the caller. The host adds the version the page loaded and\n * reports it in the viewer's name; the app's authors are told.\n */\ntype ErrorReport = {\n kind: 'exception' | 'rejection' | 'action';\n name?: string;\n message?: string;\n stack?: string;\n action?: string;\n code?: string;\n invocation_id?: string;\n};\n\n// Each kind of error once per page load, and only so many: a page stuck in\n// a loop must not flood its authors (the server keeps its own budgets).\nconst REPORTS_PER_LOAD = 10;\nconst REPORTED_ACTION_CODES = new Set(['ACTION_TIMEOUT', 'ACTION_LIMIT_EXCEEDED']);\n\nfunction clip(s: string | undefined, max: number): string | undefined {\n return s && s.length > max ? s.slice(0, max) : s;\n}\n\n// A stack line that names a place in the code (file:line[:col]).\nconst FRAME = /:\\d+(?::\\d+)?\\)?$/;\n\n/** What makes two reports the same error \u2014 the way the server groups them:\n * an action failure by its action and code; anything else by its kind, its\n * name and the places its stack names, or by its message when the stack\n * names none. One throw site with a changing message is one error. */\nfunction reportKey(r: ErrorReport): string {\n if (r.kind === 'action') return `action\\u0000${r.action}\\u0000${r.code}`;\n const frames = (r.stack ?? '')\n .split('\\n')\n .map((line) => line.trim())\n .filter((line) => line !== '' && FRAME.test(line));\n return frames.length > 0\n ? `${r.kind}\\u0000${r.name}\\u0000${frames.join('\\n')}`\n : `${r.kind}\\u0000${r.name}\\u0000message\\u0000${r.message}`;\n}\n\nfunction describe(value: unknown): string {\n if (typeof value === 'string') return value;\n try {\n return JSON.stringify(value) ?? String(value);\n } catch {\n return String(value);\n }\n}\n\nclass MiniAppBridge {\n private nextId = 1;\n private pending = new Map<number, Pending>();\n private listeners = new Set<(e: HostEvent) => void>();\n private hostOrigin: string | null = null;\n private started = false;\n private reported = new Set<string>();\n\n constructor() {\n if (typeof window === 'undefined' || typeof window.addEventListener !== 'function') return;\n window.addEventListener('error', (event: ErrorEvent) => {\n const err: unknown = event.error;\n if (err instanceof Error) {\n this.report({ kind: 'exception', name: err.name, message: err.message, stack: err.stack });\n } else {\n const where = event.filename\n ? ` at ${event.filename}:${event.lineno}:${event.colno}`\n : '';\n this.report({\n kind: 'exception',\n name: 'Error',\n message: String(event.message || 'Script error.'),\n stack: where,\n });\n }\n });\n window.addEventListener('unhandledrejection', (event: PromiseRejectionEvent) => {\n const reason: unknown = event.reason;\n // The bridge's own rejections are the host's or the server's answers:\n // a failed action is reported where it failed, by its own rules.\n if (reason !== null && typeof reason === 'object' && FROM_BRIDGE in reason) return;\n if (reason instanceof Error) {\n this.report({\n kind: 'rejection',\n name: reason.name,\n message: reason.message,\n stack: reason.stack,\n });\n } else {\n this.report({ kind: 'rejection', name: '', message: describe(reason) });\n }\n });\n }\n\n /** Sends one error report to the host; drops repeats, anything past the\n * page's share, and every failure of the report itself (an older host\n * answers NOT_GRANTED). */\n private report(r: ErrorReport): void {\n // Cut to what the host may send: the server takes at most 16 KiB.\n const params: ErrorReport = {\n ...r,\n name: clip(r.name, 100),\n message: clip(r.message, 500),\n stack: clip(r.stack, 3000),\n };\n const key = reportKey(params);\n if (this.reported.has(key) || this.reported.size >= REPORTS_PER_LOAD) return;\n this.reported.add(key);\n void this.call('report', params).catch(() => {});\n }\n\n private start(): void {\n if (this.started) return;\n this.started = true;\n window.addEventListener('message', (event: MessageEvent) => {\n // Only our embedding host: same source as window.parent, and once\n // the handshake pinned an origin, exactly that origin.\n if (event.source !== window.parent) return;\n if (this.hostOrigin !== null && event.origin !== this.hostOrigin) return;\n const msg = event.data as Record<string, unknown> | null;\n if (!msg || msg.parall !== PROTOCOL) return;\n if (typeof msg.id === 'number') {\n const pending = this.pending.get(msg.id);\n if (!pending) return;\n this.pending.delete(msg.id);\n clearTimeout(pending.timer);\n if (this.hostOrigin === null) this.hostOrigin = event.origin;\n if (msg.error) {\n const err = msg.error as WireError;\n pending.reject(bridgeError(err.code, err.message, err.details));\n } else {\n pending.resolve(msg.result);\n }\n return;\n }\n if (typeof msg.event === 'string') {\n for (const fn of this.listeners) fn(msg as unknown as HostEvent);\n }\n });\n }\n\n private call<T>(method: string, params?: unknown, timeoutMs = HOST_TIMEOUT_MS): Promise<T> {\n this.start();\n const id = this.nextId++;\n return new Promise<T>((resolve, reject) => {\n const timer = setTimeout(() => {\n if (this.pending.delete(id)) {\n reject(bridgeError('HOST_TIMEOUT', `${method} timed out waiting for the host`));\n }\n }, timeoutMs);\n this.pending.set(id, { resolve: resolve as (v: unknown) => void, reject, timer });\n window.parent.postMessage({ parall: PROTOCOL, id, method, params }, '*');\n });\n }\n\n /** Handshake with the host; resolves with the viewer, app and initial route. */\n ready(): Promise<ReadyResult> {\n return this.call<ReadyResult>('ready');\n }\n\n /** Ask the host to grow/shrink the iframe (fire-and-forget semantics). */\n resize(height: number): void {\n void this.call('resize', { height }).catch(() => {});\n }\n\n /**\n * Call one of the app's actions with the viewer's identity and resolve\n * with what the action returned. A failure rejects with a BridgeError\n * whose code is the server's (ACTION_FAILED, ACTION_TIMEOUT,\n * INVALID_ACTION_PARAMS, APP_VERSION_CHANGED\u2026); its message is the\n * action's ActionError message when it threw one. HOST_TIMEOUT and\n * HOST_UNAVAILABLE mean no answer came back: whether the action ran is\n * not known, so read again before retrying a write.\n */\n async action<T = unknown>(name: string, params?: Record<string, unknown>): Promise<T> {\n let answer: { invocation_id: string; result: T };\n try {\n answer = await this.call<{ invocation_id: string; result: T }>(\n 'action',\n { name, params: params ?? {} },\n ACTION_TIMEOUT_MS,\n );\n } catch (err) {\n // The app's authors hear of an action that failed unexpectedly, timed\n // out or ran over its limits \u2014 caught by the page or not. An\n // ActionError (error_kind \"action\") is the author's own answer.\n const e = err as BridgeError;\n const unexpected = e.code === 'ACTION_FAILED' && e.details?.error_kind === 'unexpected';\n if (unexpected || REPORTED_ACTION_CODES.has(e.code)) {\n const invocation = e.details?.invocation_id;\n this.report({\n kind: 'action',\n action: name,\n code: e.code,\n invocation_id: typeof invocation === 'string' ? invocation : undefined,\n });\n }\n throw err;\n }\n return answer.result;\n }\n\n /** Subscribe to host events; returns the unsubscribe function. */\n onEvent(fn: (e: HostEvent) => void): () => void {\n this.start();\n this.listeners.add(fn);\n return () => this.listeners.delete(fn);\n }\n\n /**\n * Call fn when a Database the app reads has new writes: once per new\n * (database_id, data_seq) \u2014 repeats and older ones are dropped \u2014 and\n * always on a catch-up after the host reconnected. Read again in fn.\n */\n onDataChanged(fn: (change: DataChanged) => void): () => void {\n const seen = new Map<string, number>();\n return this.onEvent((e) => {\n if (e.event !== 'data.changed') return;\n const { database_id, data_seq, catch_up } = e.data;\n const last = seen.get(database_id);\n if (!catch_up && last !== undefined && data_seq <= last) return;\n if (last === undefined || data_seq > last) seen.set(database_id, data_seq);\n fn(e.data);\n });\n }\n}\n\nexport const parall = new MiniAppBridge();\n";
|
|
2
2
|
//# sourceMappingURL=apps-page-sdk.generated.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"apps-page-sdk.generated.d.ts","sourceRoot":"","sources":["../../src/commands/apps-page-sdk.generated.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,eAAe,
|
|
1
|
+
{"version":3,"file":"apps-page-sdk.generated.d.ts","sourceRoot":"","sources":["../../src/commands/apps-page-sdk.generated.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,eAAe,64YAAoyY,CAAC"}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// Generated from ts/miniapp-sdk/src/index.ts by scripts/generate-miniapp-sdk.mjs. Do not edit.
|
|
2
2
|
// biome-ignore format: generated copy
|
|
3
|
-
export const PAGE_SDK_SOURCE = "/**\n * @parall/miniapp-sdk — the page side of the Mini App bridge (design §7.1):\n * host handshake, host→page events, resize, and `action`, the page's only\n * data method: it calls one of the app's server-side actions through the\n * host, which adds the viewer's session and the version the page loaded\n * (Mini App Action design §3.1). No db, files, clip or chat methods exist\n * on this surface. The transport is postMessage to window.parent; the host\n * validates our origin, we validate that messages come from our parent\n * and, after the first answer, pin the parent's origin.\n *\n * Protocol (request/response + events):\n * page → host {parall: 'v1', id, method: 'ready' | 'resize' | 'action' | 'report', params}\n * host → page {parall: 'v1', id, result} | {parall: 'v1', id, error: {code, message, details?}}\n * host → page {parall: 'v1', event: 'route.changed' | 'viewer.changed' | 'data.changed', data}\n */\n\nexport interface ViewerSummary {\n id: string;\n display_name: string;\n is_agent: boolean;\n /** The viewer's organization role (owner / admin / member) — the same\n * value an action sees as ctx.viewer.role. */\n role?: string;\n}\n\nexport interface AppSummary {\n id: string;\n name: string;\n version_seq: number;\n}\n\nexport interface ReadyResult {\n viewer: ViewerSummary;\n app: AppSummary;\n route: string;\n}\n\n/** A Database the app reads was written. It carries no data: read again. */\nexport interface DataChanged {\n database_id: string;\n data_seq: number;\n /** Sent once after the host's connection came back: writes in between\n * may have been missed, so read again whatever data_seq says. */\n catch_up?: boolean;\n}\n\nexport type HostEvent =\n | { event: 'route.changed'; data: { route: string } }\n | { event: 'viewer.changed'; data: { viewer: ViewerSummary } }\n | { event: 'data.changed'; data: DataChanged };\n\n/** A refusal or failure from the host, in the error-contract envelope. An\n * action's failure keeps the server's code and details (invocation_id,\n * error_kind, field, current_version_seq…); APP_VERSION_CHANGED means the\n * app was updated and the host offers the viewer a reload. */\nexport interface BridgeError extends Error {\n code: string;\n details?: Record<string, unknown>;\n}\n\ninterface WireError {\n code: string;\n message: string;\n details?: Record<string, unknown>;\n}\n\ntype Pending = {\n resolve: (v: unknown) => void;\n reject: (e: Error) => void;\n timer: ReturnType<typeof setTimeout>;\n};\n\nconst PROTOCOL = 'v1';\n\n// How long the page waits for the host. An action waits longer than the\n// host's request timeout, which waits longer than the server takes to\n// answer at worst, so the page always gets the server's answer rather than\n// a timeout of its own (Mini App Action design §3.1, §15).\nconst HOST_TIMEOUT_MS = 10_000;\nconst ACTION_TIMEOUT_MS = 30_000;\n\n// Marks the errors the bridge itself rejects with: what the host or the\n// server answered, never the page's own bug.\nconst FROM_BRIDGE = Symbol.for('parall.bridge-error');\n\nfunction bridgeError(\n code: string,\n message: string,\n details?: Record<string, unknown>,\n): BridgeError {\n const err = Object.assign(new Error(message), { code, details }) as BridgeError;\n Object.defineProperty(err, FROM_BRIDGE, { value: true });\n return err;\n}\n\n/**\n * What a page reports when something goes wrong (Mini App design §9): an\n * error thrown on the page, a promise rejected without a handler, and an\n * action call that failed unexpectedly, timed out or ran over its limits.\n * Never console.error, and never an ActionError — that is the author's own\n * message to the caller. The host adds the version the page loaded and\n * reports it in the viewer's name; the app's authors are told.\n */\ntype ErrorReport = {\n kind: 'exception' | 'rejection' | 'action';\n name?: string;\n message?: string;\n stack?: string;\n action?: string;\n code?: string;\n invocation_id?: string;\n};\n\n// Each kind of error once per page load, and only so many: a page stuck in\n// a loop must not flood its authors (the server keeps its own budgets).\nconst REPORTS_PER_LOAD = 10;\nconst REPORTED_ACTION_CODES = new Set(['ACTION_TIMEOUT', 'ACTION_LIMIT_EXCEEDED']);\n\nfunction clip(s: string | undefined, max: number): string | undefined {\n return s && s.length > max ? s.slice(0, max) : s;\n}\n\n// A stack line that names a place in the code (file:line[:col]).\nconst FRAME = /:\\d+(?::\\d+)?\\)?$/;\n\n/** What makes two reports the same error — the way the server groups them:\n * an action failure by its action and code; anything else by its kind, its\n * name and the places its stack names, or by its message when the stack\n * names none. One throw site with a changing message is one error. */\nfunction reportKey(r: ErrorReport): string {\n if (r.kind === 'action') return `action\\u0000${r.action}\\u0000${r.code}`;\n const frames = (r.stack ?? '')\n .split('\\n')\n .map((line) => line.trim())\n .filter((line) => line !== '' && FRAME.test(line));\n return frames.length > 0\n ? `${r.kind}\\u0000${r.name}\\u0000${frames.join('\\n')}`\n : `${r.kind}\\u0000${r.name}\\u0000message\\u0000${r.message}`;\n}\n\nfunction describe(value: unknown): string {\n if (typeof value === 'string') return value;\n try {\n return JSON.stringify(value) ?? String(value);\n } catch {\n return String(value);\n }\n}\n\nclass MiniAppBridge {\n private nextId = 1;\n private pending = new Map<number, Pending>();\n private listeners = new Set<(e: HostEvent) => void>();\n private hostOrigin: string | null = null;\n private started = false;\n private reported = new Set<string>();\n\n constructor() {\n if (typeof window === 'undefined' || typeof window.addEventListener !== 'function') return;\n window.addEventListener('error', (event: ErrorEvent) => {\n const err: unknown = event.error;\n if (err instanceof Error) {\n this.report({ kind: 'exception', name: err.name, message: err.message, stack: err.stack });\n } else {\n const where = event.filename\n ? ` at ${event.filename}:${event.lineno}:${event.colno}`\n : '';\n this.report({\n kind: 'exception',\n name: 'Error',\n message: String(event.message || 'Script error.'),\n stack: where,\n });\n }\n });\n window.addEventListener('unhandledrejection', (event: PromiseRejectionEvent) => {\n const reason: unknown = event.reason;\n // The bridge's own rejections are the host's or the server's answers:\n // a failed action is reported where it failed, by its own rules.\n if (reason !== null && typeof reason === 'object' && FROM_BRIDGE in reason) return;\n if (reason instanceof Error) {\n this.report({\n kind: 'rejection',\n name: reason.name,\n message: reason.message,\n stack: reason.stack,\n });\n } else {\n this.report({ kind: 'rejection', name: '', message: describe(reason) });\n }\n });\n }\n\n /** Sends one error report to the host; drops repeats, anything past the\n * page's share, and every failure of the report itself (an older host\n * answers NOT_GRANTED). */\n private report(r: ErrorReport): void {\n // Cut to what the host may send: the server takes at most 16 KiB.\n const params: ErrorReport = {\n ...r,\n name: clip(r.name, 100),\n message: clip(r.message, 500),\n stack: clip(r.stack, 3000),\n };\n const key = reportKey(params);\n if (this.reported.has(key) || this.reported.size >= REPORTS_PER_LOAD) return;\n this.reported.add(key);\n void this.call('report', params).catch(() => {});\n }\n\n private start(): void {\n if (this.started) return;\n this.started = true;\n window.addEventListener('message', (event: MessageEvent) => {\n // Only our embedding host: same source as window.parent, and once\n // the handshake pinned an origin, exactly that origin.\n if (event.source !== window.parent) return;\n if (this.hostOrigin !== null && event.origin !== this.hostOrigin) return;\n const msg = event.data as Record<string, unknown> | null;\n if (!msg || msg.parall !== PROTOCOL) return;\n if (typeof msg.id === 'number') {\n const pending = this.pending.get(msg.id);\n if (!pending) return;\n this.pending.delete(msg.id);\n clearTimeout(pending.timer);\n if (this.hostOrigin === null) this.hostOrigin = event.origin;\n if (msg.error) {\n const err = msg.error as WireError;\n pending.reject(bridgeError(err.code, err.message, err.details));\n } else {\n pending.resolve(msg.result);\n }\n return;\n }\n if (typeof msg.event === 'string') {\n for (const fn of this.listeners) fn(msg as unknown as HostEvent);\n }\n });\n }\n\n private call<T>(method: string, params?: unknown, timeoutMs = HOST_TIMEOUT_MS): Promise<T> {\n this.start();\n const id = this.nextId++;\n return new Promise<T>((resolve, reject) => {\n const timer = setTimeout(() => {\n if (this.pending.delete(id)) {\n reject(bridgeError('HOST_TIMEOUT', `${method} timed out waiting for the host`));\n }\n }, timeoutMs);\n this.pending.set(id, { resolve: resolve as (v: unknown) => void, reject, timer });\n window.parent.postMessage({ parall: PROTOCOL, id, method, params }, '*');\n });\n }\n\n /** Handshake with the host; resolves with the viewer, app and initial route. */\n ready(): Promise<ReadyResult> {\n return this.call<ReadyResult>('ready');\n }\n\n /** Ask the host to grow/shrink the iframe (fire-and-forget semantics). */\n resize(height: number): void {\n void this.call('resize', { height }).catch(() => {});\n }\n\n /**\n * Call one of the app's actions with the viewer's identity and resolve\n * with what the action returned. A failure rejects with a BridgeError\n * whose code is the server's (ACTION_FAILED, ACTION_TIMEOUT,\n * INVALID_ACTION_PARAMS, APP_VERSION_CHANGED…); its message is the\n * action's ActionError message when it threw one. HOST_TIMEOUT and\n * HOST_UNAVAILABLE mean no answer came back: whether the action ran is\n * not known, so read again before retrying a write.\n */\n async action<T = unknown>(name: string, params?: Record<string, unknown>): Promise<T> {\n let answer: { invocation_id: string; result: T };\n try {\n answer = await this.call<{ invocation_id: string; result: T }>(\n 'action',\n { name, params: params ?? {} },\n ACTION_TIMEOUT_MS,\n );\n } catch (err) {\n // The app's authors hear of an action that failed unexpectedly, timed\n // out or ran over its limits — caught by the page or not. An\n // ActionError (error_kind \"action\") is the author's own answer.\n const e = err as BridgeError;\n const unexpected = e.code === 'ACTION_FAILED' && e.details?.error_kind === 'unexpected';\n if (unexpected || REPORTED_ACTION_CODES.has(e.code)) {\n const invocation = e.details?.invocation_id;\n this.report({\n kind: 'action',\n action: name,\n code: e.code,\n invocation_id: typeof invocation === 'string' ? invocation : undefined,\n });\n }\n throw err;\n }\n return answer.result;\n }\n\n /** Subscribe to host events; returns the unsubscribe function. */\n onEvent(fn: (e: HostEvent) => void): () => void {\n this.start();\n this.listeners.add(fn);\n return () => this.listeners.delete(fn);\n }\n\n /**\n * Call fn when a Database the app reads has new writes: once per new\n * (database_id, data_seq) — repeats and older ones are dropped — and\n * always on a catch-up after the host reconnected. Read again in fn.\n */\n onDataChanged(fn: (change: DataChanged) => void): () => void {\n const seen = new Map<string, number>();\n return this.onEvent((e) => {\n if (e.event !== 'data.changed') return;\n const { database_id, data_seq, catch_up } = e.data;\n const last = seen.get(database_id);\n if (!catch_up && last !== undefined && data_seq <= last) return;\n if (last === undefined || data_seq > last) seen.set(database_id, data_seq);\n fn(e.data);\n });\n }\n}\n\nexport const parall = new MiniAppBridge();\n";
|
|
3
|
+
export const PAGE_SDK_SOURCE = "/**\n * @parall/miniapp-sdk — the page side of the Mini App bridge (design §7.1):\n * host handshake, host→page events, resize, and `action`, the page's only\n * data method: it calls one of the app's server-side actions through the\n * host, which adds the viewer's session and the version the page loaded\n * (Mini App Action design §3.1). No db, files, clip or chat methods exist\n * on this surface. The transport is postMessage to window.parent; the host\n * validates our origin, we validate that messages come from our parent\n * and, after the first answer, pin the parent's origin.\n *\n * Protocol (request/response + events):\n * page → host {parall: 'v1', id, method: 'ready' | 'resize' | 'action' | 'report', params}\n * host → page {parall: 'v1', id, result} | {parall: 'v1', id, error: {code, message, details?}}\n * host → page {parall: 'v1', event: 'route.changed' | 'viewer.changed' | 'data.changed', data}\n */\n\nexport interface ViewerSummary {\n id: string;\n display_name: string;\n is_agent: boolean;\n /** The viewer's organization role (owner / admin / member) — the same\n * value an action sees as ctx.viewer.role. */\n role?: string;\n}\n\nexport interface AppSummary {\n id: string;\n name: string;\n version_seq: number;\n}\n\nexport interface ReadyResult {\n viewer: ViewerSummary;\n app: AppSummary;\n route: string;\n}\n\n/** A Database the app reads was written. It carries no data: read again. */\nexport interface DataChanged {\n database_id: string;\n data_seq: number;\n /** Sent once after the host's connection came back: writes in between\n * may have been missed, so read again whatever data_seq says. */\n catch_up?: boolean;\n}\n\nexport type HostEvent =\n | { event: 'route.changed'; data: { route: string } }\n | { event: 'viewer.changed'; data: { viewer: ViewerSummary } }\n | { event: 'data.changed'; data: DataChanged };\n\n/** A refusal or failure from the host, in the error-contract envelope. An\n * action's failure keeps the server's code and details (invocation_id,\n * error_kind, field, current_version_seq…); APP_VERSION_CHANGED means the\n * app was updated and the host offers the viewer a reload. */\nexport interface BridgeError extends Error {\n code: string;\n details?: Record<string, unknown>;\n}\n\ninterface WireError {\n code: string;\n message: string;\n details?: Record<string, unknown>;\n}\n\ntype Pending = {\n resolve: (v: unknown) => void;\n reject: (e: Error) => void;\n timer: ReturnType<typeof setTimeout>;\n};\n\nconst PROTOCOL = 'v1';\n\n// How long the page waits for the host. An action waits longer than the\n// host's request timeout, which waits longer than the server takes to\n// answer at worst — an action that calls Clip may run 100 s — so the page\n// always gets the server's answer rather than a timeout of its own (Mini\n// App Action design §3.1, §15; Clip design §4.2).\nconst HOST_TIMEOUT_MS = 10_000;\nconst ACTION_TIMEOUT_MS = 120_000;\n\n// Marks the errors the bridge itself rejects with: what the host or the\n// server answered, never the page's own bug.\nconst FROM_BRIDGE = Symbol.for('parall.bridge-error');\n\nfunction bridgeError(\n code: string,\n message: string,\n details?: Record<string, unknown>,\n): BridgeError {\n const err = Object.assign(new Error(message), { code, details }) as BridgeError;\n Object.defineProperty(err, FROM_BRIDGE, { value: true });\n return err;\n}\n\n/**\n * What a page reports when something goes wrong (Mini App design §9): an\n * error thrown on the page, a promise rejected without a handler, and an\n * action call that failed unexpectedly, timed out or ran over its limits.\n * Never console.error, and never an ActionError — that is the author's own\n * message to the caller. The host adds the version the page loaded and\n * reports it in the viewer's name; the app's authors are told.\n */\ntype ErrorReport = {\n kind: 'exception' | 'rejection' | 'action';\n name?: string;\n message?: string;\n stack?: string;\n action?: string;\n code?: string;\n invocation_id?: string;\n};\n\n// Each kind of error once per page load, and only so many: a page stuck in\n// a loop must not flood its authors (the server keeps its own budgets).\nconst REPORTS_PER_LOAD = 10;\nconst REPORTED_ACTION_CODES = new Set(['ACTION_TIMEOUT', 'ACTION_LIMIT_EXCEEDED']);\n\nfunction clip(s: string | undefined, max: number): string | undefined {\n return s && s.length > max ? s.slice(0, max) : s;\n}\n\n// A stack line that names a place in the code (file:line[:col]).\nconst FRAME = /:\\d+(?::\\d+)?\\)?$/;\n\n/** What makes two reports the same error — the way the server groups them:\n * an action failure by its action and code; anything else by its kind, its\n * name and the places its stack names, or by its message when the stack\n * names none. One throw site with a changing message is one error. */\nfunction reportKey(r: ErrorReport): string {\n if (r.kind === 'action') return `action\\u0000${r.action}\\u0000${r.code}`;\n const frames = (r.stack ?? '')\n .split('\\n')\n .map((line) => line.trim())\n .filter((line) => line !== '' && FRAME.test(line));\n return frames.length > 0\n ? `${r.kind}\\u0000${r.name}\\u0000${frames.join('\\n')}`\n : `${r.kind}\\u0000${r.name}\\u0000message\\u0000${r.message}`;\n}\n\nfunction describe(value: unknown): string {\n if (typeof value === 'string') return value;\n try {\n return JSON.stringify(value) ?? String(value);\n } catch {\n return String(value);\n }\n}\n\nclass MiniAppBridge {\n private nextId = 1;\n private pending = new Map<number, Pending>();\n private listeners = new Set<(e: HostEvent) => void>();\n private hostOrigin: string | null = null;\n private started = false;\n private reported = new Set<string>();\n\n constructor() {\n if (typeof window === 'undefined' || typeof window.addEventListener !== 'function') return;\n window.addEventListener('error', (event: ErrorEvent) => {\n const err: unknown = event.error;\n if (err instanceof Error) {\n this.report({ kind: 'exception', name: err.name, message: err.message, stack: err.stack });\n } else {\n const where = event.filename\n ? ` at ${event.filename}:${event.lineno}:${event.colno}`\n : '';\n this.report({\n kind: 'exception',\n name: 'Error',\n message: String(event.message || 'Script error.'),\n stack: where,\n });\n }\n });\n window.addEventListener('unhandledrejection', (event: PromiseRejectionEvent) => {\n const reason: unknown = event.reason;\n // The bridge's own rejections are the host's or the server's answers:\n // a failed action is reported where it failed, by its own rules.\n if (reason !== null && typeof reason === 'object' && FROM_BRIDGE in reason) return;\n if (reason instanceof Error) {\n this.report({\n kind: 'rejection',\n name: reason.name,\n message: reason.message,\n stack: reason.stack,\n });\n } else {\n this.report({ kind: 'rejection', name: '', message: describe(reason) });\n }\n });\n }\n\n /** Sends one error report to the host; drops repeats, anything past the\n * page's share, and every failure of the report itself (an older host\n * answers NOT_GRANTED). */\n private report(r: ErrorReport): void {\n // Cut to what the host may send: the server takes at most 16 KiB.\n const params: ErrorReport = {\n ...r,\n name: clip(r.name, 100),\n message: clip(r.message, 500),\n stack: clip(r.stack, 3000),\n };\n const key = reportKey(params);\n if (this.reported.has(key) || this.reported.size >= REPORTS_PER_LOAD) return;\n this.reported.add(key);\n void this.call('report', params).catch(() => {});\n }\n\n private start(): void {\n if (this.started) return;\n this.started = true;\n window.addEventListener('message', (event: MessageEvent) => {\n // Only our embedding host: same source as window.parent, and once\n // the handshake pinned an origin, exactly that origin.\n if (event.source !== window.parent) return;\n if (this.hostOrigin !== null && event.origin !== this.hostOrigin) return;\n const msg = event.data as Record<string, unknown> | null;\n if (!msg || msg.parall !== PROTOCOL) return;\n if (typeof msg.id === 'number') {\n const pending = this.pending.get(msg.id);\n if (!pending) return;\n this.pending.delete(msg.id);\n clearTimeout(pending.timer);\n if (this.hostOrigin === null) this.hostOrigin = event.origin;\n if (msg.error) {\n const err = msg.error as WireError;\n pending.reject(bridgeError(err.code, err.message, err.details));\n } else {\n pending.resolve(msg.result);\n }\n return;\n }\n if (typeof msg.event === 'string') {\n for (const fn of this.listeners) fn(msg as unknown as HostEvent);\n }\n });\n }\n\n private call<T>(method: string, params?: unknown, timeoutMs = HOST_TIMEOUT_MS): Promise<T> {\n this.start();\n const id = this.nextId++;\n return new Promise<T>((resolve, reject) => {\n const timer = setTimeout(() => {\n if (this.pending.delete(id)) {\n reject(bridgeError('HOST_TIMEOUT', `${method} timed out waiting for the host`));\n }\n }, timeoutMs);\n this.pending.set(id, { resolve: resolve as (v: unknown) => void, reject, timer });\n window.parent.postMessage({ parall: PROTOCOL, id, method, params }, '*');\n });\n }\n\n /** Handshake with the host; resolves with the viewer, app and initial route. */\n ready(): Promise<ReadyResult> {\n return this.call<ReadyResult>('ready');\n }\n\n /** Ask the host to grow/shrink the iframe (fire-and-forget semantics). */\n resize(height: number): void {\n void this.call('resize', { height }).catch(() => {});\n }\n\n /**\n * Call one of the app's actions with the viewer's identity and resolve\n * with what the action returned. A failure rejects with a BridgeError\n * whose code is the server's (ACTION_FAILED, ACTION_TIMEOUT,\n * INVALID_ACTION_PARAMS, APP_VERSION_CHANGED…); its message is the\n * action's ActionError message when it threw one. HOST_TIMEOUT and\n * HOST_UNAVAILABLE mean no answer came back: whether the action ran is\n * not known, so read again before retrying a write.\n */\n async action<T = unknown>(name: string, params?: Record<string, unknown>): Promise<T> {\n let answer: { invocation_id: string; result: T };\n try {\n answer = await this.call<{ invocation_id: string; result: T }>(\n 'action',\n { name, params: params ?? {} },\n ACTION_TIMEOUT_MS,\n );\n } catch (err) {\n // The app's authors hear of an action that failed unexpectedly, timed\n // out or ran over its limits — caught by the page or not. An\n // ActionError (error_kind \"action\") is the author's own answer.\n const e = err as BridgeError;\n const unexpected = e.code === 'ACTION_FAILED' && e.details?.error_kind === 'unexpected';\n if (unexpected || REPORTED_ACTION_CODES.has(e.code)) {\n const invocation = e.details?.invocation_id;\n this.report({\n kind: 'action',\n action: name,\n code: e.code,\n invocation_id: typeof invocation === 'string' ? invocation : undefined,\n });\n }\n throw err;\n }\n return answer.result;\n }\n\n /** Subscribe to host events; returns the unsubscribe function. */\n onEvent(fn: (e: HostEvent) => void): () => void {\n this.start();\n this.listeners.add(fn);\n return () => this.listeners.delete(fn);\n }\n\n /**\n * Call fn when a Database the app reads has new writes: once per new\n * (database_id, data_seq) — repeats and older ones are dropped — and\n * always on a catch-up after the host reconnected. Read again in fn.\n */\n onDataChanged(fn: (change: DataChanged) => void): () => void {\n const seen = new Map<string, number>();\n return this.onEvent((e) => {\n if (e.event !== 'data.changed') return;\n const { database_id, data_seq, catch_up } = e.data;\n const last = seen.get(database_id);\n if (!catch_up && last !== undefined && data_seq <= last) return;\n if (last === undefined || data_seq > last) seen.set(database_id, data_seq);\n fn(e.data);\n });\n }\n}\n\nexport const parall = new MiniAppBridge();\n";
|
|
@@ -156,6 +156,7 @@ const ACTIONS_AGENTS_NOTES = `
|
|
|
156
156
|
- \`ctx.viewer\` 是平台担保的调用者,行级规则写在 SQL 里(例:\`WHERE created_by = $1\` 传 \`ctx.viewer.id\`)。能打开 app 的人都能调全部 action。
|
|
157
157
|
- 给调用者看的错误抛 \`ActionError\`;其他异常只有作者与 owner / admin 看得到完整消息与堆栈。写类调用的参数记进全组织可查的调用记录:不要经参数传凭据。
|
|
158
158
|
- 没有网络、没有文件系统;模块级变量在调用者之间共享,不能存调用者的状态。每次 \`ctx.db\` 调用都是一次往返,能合并就合并。
|
|
159
|
+
- 要调 Clip:在 manifest 里给写类 action 加 \`"clip": true\`,代码里 \`await ctx.clip.exec('<clip>', '<command>', args, { connection: '<alias>', timeoutMs: 60_000 })\`。它以调用 action 的人的身份执行,那个人没有这个 connection 的权限就被拒(\`ClipError\`,\`code\` 如 \`CONNECTION_NOT_ALLOWED\`);接住它,换成给人看的 \`ActionError\`。\`OUTCOME_UNKNOWN\` 表示命令可能已经执行,不要自动重试。调 Clip 的 action 有 100 秒、最多 10 次 Clip 调用;单次命令默认只等 30 秒,命令慢就传 \`timeoutMs\`,并给之后的数据库写入留出时间(平台会把它截到 action 剩余时间减 8 秒)。给已有的 app 加 Clip 调用时,先从新跑的 \`parall app init --actions\` 里拷来 \`src/parall.ts\` 与 \`actions/parall-actions.ts\` 换掉旧副本再构建:旧的页面 SDK 等 action 只等 30 秒,旧的 action SDK 没有 \`ctx.clip\`。
|
|
159
160
|
- 调试:改完 \`pnpm build\` 后 \`parall app action run <app_…> whoami --local\` 在本机 workerd 里跑本地构建,不用先发布;它连的是 app 的真实 Database,**写会真的生效**,\`console.log\` 打到 stderr。出错时堆栈按本地 source map 映射回 \`actions/*.ts\`。要在线上运行时里试,\`parall app publish dist --app <app_…> --preview\` 后 \`parall app action run <app_…> whoami --v <seq>\`。调用记录 \`parall app action log <app_…>\`,执行过的 SQL \`parall app db log --app <app_…>\`(加 \`--invocation <aci_… 或 acd_…>\` 只看一次调用;本机运行的写入版本号为空)。
|
|
160
161
|
- 页面连本地 action:\`parall app dev --dist dist --app <app_…>\`,打开 CLI 打印的地址(带令牌)。页面调的 action 在本机运行,同样**写会真的生效**;右侧列出每次调用、结果与 \`console\` 输出,终端也各打一行。改完重新 \`pnpm build\` 即可,不用重启。
|
|
161
162
|
- 页面用 \`parall.action('whoami')\` 调(\`src/App.tsx\` 是例子)。失败时 \`err.code\` 是服务端的错误码:\`ACTION_FAILED\`(消息是 \`ActionError\` 的原文)、\`INVALID_ACTION_PARAMS\`、\`ACTION_TIMEOUT\`(写类可能已生效)、\`APP_VERSION_CHANGED\`(app 已更新,宿主会提示看的人重新加载);\`HOST_TIMEOUT\` / \`HOST_UNAVAILABLE\` 是没拿到答复,写类先重读再决定是否重试。\`parall.onDataChanged(fn)\` 在 Database 有新写入时调 fn,在里面重读。
|
package/dist/lib/edge-exec.d.ts
CHANGED
|
@@ -21,7 +21,7 @@ import type { EdgeClipExecResult, ExecEdgeClipRequest, ParallClient } from '@par
|
|
|
21
21
|
* error's code names which class of wait ran out.
|
|
22
22
|
*
|
|
23
23
|
* Everything else propagates on first occurrence — above all OUTCOME_UNKNOWN
|
|
24
|
-
* (
|
|
24
|
+
* (500): the command was dispatched and MAY HAVE EXECUTED; an automatic retry
|
|
25
25
|
* could post, order or delete twice. That decision belongs to the caller, with
|
|
26
26
|
* the request id from the error message, never to a loop in here.
|
|
27
27
|
*
|
package/dist/lib/edge-exec.js
CHANGED
|
@@ -22,7 +22,7 @@ import { ApiError } from '@parall/sdk';
|
|
|
22
22
|
* error's code names which class of wait ran out.
|
|
23
23
|
*
|
|
24
24
|
* Everything else propagates on first occurrence — above all OUTCOME_UNKNOWN
|
|
25
|
-
* (
|
|
25
|
+
* (500): the command was dispatched and MAY HAVE EXECUTED; an automatic retry
|
|
26
26
|
* could post, order or delete twice. That decision belongs to the caller, with
|
|
27
27
|
* the request id from the error message, never to a loop in here.
|
|
28
28
|
*
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@parall/cli",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.74.0",
|
|
4
4
|
"description": "CLI client for Parall — universal agent & human access to Parall API",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -42,8 +42,8 @@
|
|
|
42
42
|
"node-diff3": "3.2.1",
|
|
43
43
|
"tar-stream": "^3.2.1",
|
|
44
44
|
"zod": "^4.3.6",
|
|
45
|
-
"@parall/agent-core": "1.
|
|
46
|
-
"@parall/sdk": "1.
|
|
45
|
+
"@parall/agent-core": "1.74.0",
|
|
46
|
+
"@parall/sdk": "1.74.0"
|
|
47
47
|
},
|
|
48
48
|
"devDependencies": {
|
|
49
49
|
"@types/js-yaml": "^4.0.9",
|
|
@@ -51,7 +51,7 @@
|
|
|
51
51
|
"@types/tar-stream": "^3.1.4",
|
|
52
52
|
"esbuild": "^0.25.0",
|
|
53
53
|
"typescript": "^5.7.0",
|
|
54
|
-
"@parall/agent-core": "1.
|
|
54
|
+
"@parall/agent-core": "1.74.0"
|
|
55
55
|
},
|
|
56
56
|
"scripts": {
|
|
57
57
|
"build": "node scripts/generate-miniapp-sdk.mjs --check && node scripts/generate-local-runner.mjs --check && tsc",
|