@parall/cli 1.79.0 → 1.80.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.
Files changed (38) hide show
  1. package/dist/commands/apps-access.d.ts.map +1 -1
  2. package/dist/commands/apps-access.js +19 -9
  3. package/dist/commands/apps-actions-sdk.generated.d.ts +1 -1
  4. package/dist/commands/apps-actions-sdk.generated.d.ts.map +1 -1
  5. package/dist/commands/apps-actions-sdk.generated.js +1 -1
  6. package/dist/commands/apps-actions.js +6 -1
  7. package/dist/commands/apps-add.js +1 -1
  8. package/dist/commands/apps-blocks.d.ts.map +1 -1
  9. package/dist/commands/apps-blocks.js +8 -0
  10. package/dist/commands/apps-placement.d.ts +13 -0
  11. package/dist/commands/apps-placement.d.ts.map +1 -0
  12. package/dist/commands/apps-placement.js +20 -0
  13. package/dist/commands/apps-scaffold.d.ts +7 -1
  14. package/dist/commands/apps-scaffold.d.ts.map +1 -1
  15. package/dist/commands/apps-scaffold.js +88 -30
  16. package/dist/commands/apps-template-catalog.d.ts +85 -0
  17. package/dist/commands/apps-template-catalog.d.ts.map +1 -0
  18. package/dist/commands/apps-template-catalog.gen.d.ts +3 -0
  19. package/dist/commands/apps-template-catalog.gen.d.ts.map +1 -0
  20. package/dist/commands/apps-template-catalog.gen.js +228 -0
  21. package/dist/commands/apps-template-catalog.js +49 -0
  22. package/dist/commands/apps-template-init.d.ts +39 -0
  23. package/dist/commands/apps-template-init.d.ts.map +1 -0
  24. package/dist/commands/apps-template-init.js +118 -0
  25. package/dist/commands/apps-template.d.ts +11 -0
  26. package/dist/commands/apps-template.d.ts.map +1 -1
  27. package/dist/commands/apps-template.js +18 -7
  28. package/dist/commands/apps-templates.gen.d.ts +1 -0
  29. package/dist/commands/apps-templates.gen.d.ts.map +1 -1
  30. package/dist/commands/apps-templates.gen.js +10 -1
  31. package/dist/commands/apps.d.ts.map +1 -1
  32. package/dist/commands/apps.js +6 -2
  33. package/dist/commands/db-plane.d.ts.map +1 -1
  34. package/dist/commands/db-plane.js +10 -6
  35. package/dist/commands/dbs.d.ts +3 -2
  36. package/dist/commands/dbs.d.ts.map +1 -1
  37. package/dist/commands/dbs.js +10 -5
  38. package/package.json +5 -5
@@ -1 +1 @@
1
- {"version":3,"file":"apps-access.d.ts","sourceRoot":"","sources":["../../src/commands/apps-access.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AACtD,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAwCzC,mDAAmD;AACnD,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,EAAE,IAAI,EAAE,MAAM,GAAG,kBAAkB,CAI1F;AAED,oDAAoD;AACpD,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,GAAG,OAAO,CAIzE;AAED,wBAAgB,yBAAyB,CAAC,GAAG,EAAE,OAAO,QA2GrD"}
1
+ {"version":3,"file":"apps-access.d.ts","sourceRoot":"","sources":["../../src/commands/apps-access.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AACtD,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAkDzC,mDAAmD;AACnD,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,EAAE,IAAI,EAAE,MAAM,GAAG,kBAAkB,CAI1F;AAED,oDAAoD;AACpD,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,GAAG,OAAO,CAIzE;AAED,wBAAgB,yBAAyB,CAAC,GAAG,EAAE,OAAO,QA2GrD"}
@@ -6,12 +6,15 @@ import { appAndArg, appIdFrom, withApp } from './apps-args.js';
6
6
  * of the organization reaches into an app, the people given more one by
7
7
  * one, and the record of every change. The server decides who may see and
8
8
  * change what; these commands only name the request. */
9
- /** The levels the help and the local errors name. `parseMemberLevel` also
10
- * passes `none` through as the API spells it — the server decides whether
11
- * it takes it — so this CLI keeps working once the server accepts it. */
9
+ /** The levels the help and the local errors name: everyone else in the
10
+ * organization can be held at any of the three, a person added one by one
11
+ * at read or write. */
12
+ const MEMBER_LEVELS = 'none, read or write';
12
13
  const LEVELS = 'read or write';
13
14
  const ACCESS_HELP = `
14
15
  Levels:
16
+ none not in their app list and does not open; references to it show as
17
+ restricted, and they cannot see its call record or its Database
15
18
  read open the app, call its read actions and see its call record
16
19
  write also call its write actions — every app's default
17
20
 
@@ -26,19 +29,26 @@ Anyone who can open the app sees the member level and their own level
26
29
  every change, author changes included (log).
27
30
 
28
31
  Keep in mind:
32
+ - An app meant to stay private should be made with
33
+ parall app create --members none: made open and restricted later, its
34
+ name has already reached the organization.
29
35
  - Only write actions are refused to people who can only read. A read
30
36
  action does whatever its code does for every reader — an outbound
31
37
  request included — so put anything with a side effect in a write action.
32
38
  - Taking access away refuses the person's next call, but a browser that
33
39
  already loaded the page can fetch that version's files for up to an
34
40
  hour. Nothing bundled into the page is protected by this setting: keep
35
- what must stay private in the Database and return it from a read action.`;
41
+ what must stay private in the Database and return it from a read action.
42
+ - Permissions belong to apps, data to the Database: whoever can use
43
+ another app on the same Database reaches its data through that app.
44
+ Keep private data in a Database only private apps use — a new app gets
45
+ one of its own.`;
36
46
  /** A member level as given on the command line. */
37
47
  export function parseMemberLevel(raw, what) {
38
48
  const level = raw?.trim();
39
49
  if (level === 'read' || level === 'write' || level === 'none')
40
50
  return level;
41
- throw new Error(`${what} must be ${LEVELS}`);
51
+ throw new Error(`${what} must be ${MEMBER_LEVELS}`);
42
52
  }
43
53
  /** A level on the access list: never below read. */
44
54
  export function parseGrantLevel(raw) {
@@ -50,7 +60,7 @@ export function parseGrantLevel(raw) {
50
60
  export function registerAppAccessCommands(app) {
51
61
  const access = app
52
62
  .command('access')
53
- .description('Who can use an app: everyone else in the organization, and people added one by one (read or write)')
63
+ .description('Who can use an app: everyone else in the organization (none, read or write), and people added one by one (read or write)')
54
64
  .addHelpText('after', ACCESS_HELP);
55
65
  withApp(access
56
66
  .command('list')
@@ -66,13 +76,13 @@ export function registerAppAccessCommands(app) {
66
76
  });
67
77
  access
68
78
  .command('members')
69
- .description("Set how far everyone else in the organization reaches into the app: read or write (the app's authors or an org owner/admin)")
79
+ .description("Set how far everyone else in the organization reaches into the app: none, read or write (the app's authors or an org owner/admin)")
70
80
  .argument('[appId]', 'App ID (app_… or prll://app_…); or pass --app')
71
- .argument('[level]', LEVELS)
81
+ .argument('[level]', MEMBER_LEVELS)
72
82
  .option('--app <appId>', 'App ID, in place of the first argument')
73
83
  .action(async (first, second, opts) => {
74
84
  try {
75
- const [id, raw] = appAndArg(first, second, opts.app, `level (${LEVELS})`);
85
+ const [id, raw] = appAndArg(first, second, opts.app, `level (${MEMBER_LEVELS})`);
76
86
  const level = parseMemberLevel(raw, 'The level');
77
87
  const { client, orgId } = resolveCredentials();
78
88
  printJson(await client.setMiniAppMemberAccess(orgId, id, level));
@@ -1,2 +1,2 @@
1
- export declare const ACTIONS_SDK_SOURCE = "/**\n * @parall/miniapp-sdk/actions \u2014 the action side of a Mini App\n * (docs/engineering-design/mini-app-action-design.md \u00A72): `defineActions`\n * turns the author's functions into the module entry the action loader\n * calls; `ActionError` is the error whose message the caller may see.\n *\n * This file runs inside the Cloudflare isolate, not in the page. It is the\n * only part of the SDK that imports `cloudflare:workers`, and an action\n * module is built from it into one file whose sole external import is that\n * one. Export the result as `ActionRunner` \u2014 the loader looks it up by name:\n *\n * export const ActionRunner = defineActions({\n * async addNote(ctx, { text }) {\n * const { rows } = await ctx.db.exec(\n * 'INSERT INTO notes (text, created_by) VALUES ($1, $2) RETURNING id',\n * [text, ctx.viewer.id],\n * );\n * return rows[0];\n * },\n * });\n *\n * Security does not depend on this wrapper: the loader accepts only the two\n * result shapes run() returns, whatever produced them (design \u00A73.1).\n *\n * An action that declares `\"clip\": true` in the manifest (write actions only)\n * may call 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 * `ctx.fetch` requests a public HTTP(S) address and returns a standard\n * `Response`; `ctx.env` holds the app's secrets by name\n * (docs/engineering-design/mini-app-network-design.md):\n *\n * const res = await ctx.fetch('https://api.example.com/v1/items', {\n * headers: { Authorization: `Bearer ${ctx.env.EXAMPLE_API_KEY}` },\n * });\n * if (!res.ok) throw new ActionError(`the items API answered ${res.status}`);\n * return res.json();\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/** An outbound request (ctx.fetch) that was refused or failed \u2014 an HTTP\n * error status is not one: it comes back as a Response. `code` is the\n * platform's:\n *\n * - not sent: ACTION_INVALID_CALL (the URL, method, headers or body),\n * NET_ADDRESS_BLOCKED (private and loopback addresses, IP literals, the\n * platform's own hosts), ACTION_LIMIT_EXCEEDED (too many requests, or one\n * too large), ACTION_DEADLINE (too little time left), NET_BUSY (the\n * platform is busy; try again shortly), NET_UNAVAILABLE, USER_DISABLED,\n * ACTION_HANDLE_REVOKED;\n * - sent, so it may have reached the server: NET_TIMEOUT, NET_FAILED,\n * NET_RESPONSE_TOO_LARGE (answers are at most 1 MiB).\n *\n * The platform never retries; send an idempotency key where the other side\n * supports one. */\nexport class NetError extends Error {\n readonly code: string;\n\n constructor(code: string, message: string) {\n super(message);\n this.name = 'NetError';\n this.code = code;\n }\n}\n\n/** 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\n/** ctx.fetch's options: the standard ones \u2014 method, headers, body, signal,\n * redirect \u2014 and the request's timeout. Others (cache, credentials, mode,\n * the Workers `cf`) are not looked at: every request is uncached and carries\n * only what the code sets. */\nexport interface ActionFetchInit extends RequestInit {\n /** This request's timeout; 30 s by default, cut to what the action's\n * deadline leaves. With redirects, each hop has it. */\n timeoutMs?: number;\n}\n\n/** ctx.fetch: a public HTTP(S) request from the platform, recorded in the\n * app's call record (host, method, status, size and time \u2014 never the query\n * string, headers or bodies). Redirects are followed up to 5 times: within\n * the same origin as Fetch does; to another origin with only Accept,\n * Accept-Language, Content-Language and User-Agent kept, and not at all when\n * the next request would carry the body (307, 308, and 301 / 302 for a\n * method other than GET, HEAD or POST) or when it would go from https: to\n * http: \u2014 then the redirect itself comes back. Each hop is a request of its\n * own. At most a few requests run at once; more wait their turn. */\nexport type ActionFetch = (\n input: string | URL | Request,\n init?: ActionFetchInit,\n) => Promise<Response>;\n\nexport interface ActionContext {\n viewer: ActionViewer;\n app: ActionApp;\n db: ActionDb;\n clip: ActionClip;\n fetch: ActionFetch;\n /** The app's secrets by name, as people with the app's publish right set\n * them; read-only. A local run (`parall app action run --local`) reads\n * them from the project's .dev.vars instead. Never pass them as params or\n * write them to the Database or a result. */\n env: Readonly<Record<string, string>>;\n}\n\n// biome-ignore lint/suspicious/noExplicitAny: the platform validates params against the declared schema before the call\nexport type ActionFunction = (ctx: ActionContext, params: any) => unknown;\n\n/** What the loader passes run() (ts/actions-worker src/run.ts). A loader\n * before the network sends neither env nor net_in_flight. */\nexport interface ActionRunRequest {\n action: string;\n params: unknown;\n viewer: ActionViewer;\n app: ActionApp;\n env?: Record<string, string>;\n /** How many requests the handle takes at once. */\n net_in_flight?: number;\n}\n\n/** The only two shapes the loader accepts back (ts/actions-worker src/outcome.ts). */\nexport type ActionRunResult =\n | { ok: true; json: string }\n | { ok: false; error: { kind: 'action_error' | 'unexpected'; message: string; stack?: string } };\n\n/** What a handle method resolves to. Failures travel as values because\n * Workers RPC keeps only an exception's name and message (design \u00A76). */\nexport type ActionHandleResult =\n | { ok: true; value: unknown }\n | { ok: false; error: { code: string; message: string } };\n\n/** What the handle's clip method takes. */\nexport interface ActionHandleClipRequest {\n clip: string;\n command: string;\n args?: unknown;\n connection: string;\n profile?: string;\n timeout_ms?: number;\n}\n\n/** What the handle's request method takes: one request, rebuilt by the\n * loader from exactly these fields. */\nexport interface ActionHandleNetRequest {\n url: string;\n method: string;\n headers: [string, string][];\n body: ArrayBuffer | null;\n timeout_ms?: number;\n}\n\n/** What it answers with on success: the answer, never followed. */\nexport interface ActionHandleNetAnswer {\n status: number;\n status_text: string;\n headers: [string, string][];\n body: ArrayBuffer | null;\n}\n\n/** The per-invocation handle the loader passes run(). A loader before Clip\n * calls has no clip method; one before the network has no request 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 request?(req: ActionHandleNetRequest): 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 unwrapNet(result: ActionHandleResult): ActionHandleNetAnswer {\n if (result?.ok === false) throw new NetError(result.error.code, result.error.message);\n const a = (result?.ok === true ? result.value : null) as ActionHandleNetAnswer | null;\n if (\n !a ||\n typeof a.status !== 'number' ||\n !Array.isArray(a.headers) ||\n (a.body !== null && !(a.body instanceof ArrayBuffer))\n ) {\n throw new NetError(\n 'NET_FAILED',\n 'the request answered in an unknown shape; it may have reached the server',\n );\n }\n return a;\n}\n\n// Statuses whose Response has no body (Fetch's null body status).\nconst NULL_BODY_STATUS = new Set([101, 103, 204, 205, 304]);\nconst REDIRECT_STATUS = new Set([301, 302, 303, 307, 308]);\n// What a redirect to another origin keeps of the author's headers\n// (mini-app-network-design.md \u00A74): a key may be in any other one.\nconst CROSS_ORIGIN_HEADERS = new Set([\n 'accept',\n 'accept-language',\n 'content-language',\n 'user-agent',\n]);\n// Dropped with the body when a redirect turns the request into a GET.\nconst BODY_HEADERS = new Set([\n 'content-encoding',\n 'content-language',\n 'content-location',\n 'content-type',\n]);\nconst MAX_REDIRECTS = 5;\nconst DEFAULT_IN_FLIGHT = 4;\n\n/** One request of a ctx.fetch: the first, or a redirect's next hop. */\ninterface Hop {\n url: string;\n method: string;\n headers: [string, string][];\n body: ArrayBuffer | null;\n}\n\nfunction headerPairs(headers: Headers): [string, string][] {\n const out: [string, string][] = [];\n headers.forEach((value, name) => {\n out.push([name, value]);\n });\n return out;\n}\n\n/** The first hop, as a standard Request reads the input and init \u2014 only\n * the method, headers and body are taken from them. */\nasync function firstHop(input: string | URL | Request, init: ActionFetchInit | undefined) {\n let request: Request;\n try {\n request = new Request(input, {\n method: init?.method,\n headers: init?.headers,\n body: init?.body,\n });\n } catch (err) {\n throw new NetError(\n 'ACTION_INVALID_CALL',\n `ctx.fetch: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n const hop: Hop = {\n url: request.url,\n method: request.method,\n headers: headerPairs(request.headers),\n body: request.body ? await request.arrayBuffer() : null,\n };\n const fromInput = typeof input === 'object' && 'redirect' in input ? input.redirect : undefined;\n return {\n hop,\n redirect: (init?.redirect ?? fromInput ?? 'follow') as RequestRedirect,\n signal: init?.signal ?? (input instanceof Request ? input.signal : null),\n };\n}\n\n/** The next hop for a redirect, or null when it is not to be followed\n * (mini-app-network-design.md \u00A74). The handle checks the address of every\n * hop: one into a private network or the platform is refused there. */\nfunction nextHop(hop: Hop, status: number, location: string | undefined): Hop | null {\n if (!REDIRECT_STATUS.has(status) || location === undefined) return null;\n let from: URL;\n let to: URL;\n try {\n from = new URL(hop.url);\n to = new URL(location, hop.url);\n } catch {\n return null;\n }\n if (from.protocol === 'https:' && to.protocol === 'http:') return null;\n const sameOrigin = to.origin === from.origin && to.origin !== 'null';\n const toGet =\n (status === 303 && hop.method !== 'GET' && hop.method !== 'HEAD') ||\n ((status === 301 || status === 302) && hop.method === 'POST');\n if (!sameOrigin) {\n // The next request would carry the body to another origin.\n if (status === 307 || status === 308) return null;\n if ((status === 301 || status === 302) && !['GET', 'HEAD', 'POST'].includes(hop.method)) {\n return null;\n }\n }\n let { method, headers, body } = hop;\n if (toGet) {\n method = 'GET';\n body = null;\n headers = headers.filter(([name]) => !BODY_HEADERS.has(name.toLowerCase()));\n }\n if (!sameOrigin)\n headers = headers.filter(([name]) => CROSS_ORIGIN_HEADERS.has(name.toLowerCase()));\n return { url: to.href, method, headers, body };\n}\n\nfunction toResponse(answer: ActionHandleNetAnswer, hop: Hop, redirected: boolean): Response {\n if (answer.status < 200 || answer.status > 599) {\n throw new NetError('NET_FAILED', `the server answered with status ${answer.status}`);\n }\n // As Fetch does: no body for a HEAD request or a null body status.\n const body = hop.method === 'HEAD' || NULL_BODY_STATUS.has(answer.status) ? null : answer.body;\n let res: Response;\n try {\n res = new Response(body, {\n status: answer.status,\n statusText: answer.status_text,\n headers: answer.headers,\n });\n } catch {\n try {\n res = new Response(body, { status: answer.status, headers: answer.headers });\n } catch {\n throw new NetError('NET_FAILED', 'the answer could not be read');\n }\n }\n // As a fetch Response: the URL that answered, and whether it was reached\n // through a redirect.\n Object.defineProperty(res, 'url', { value: hop.url });\n if (redirected) Object.defineProperty(res, 'redirected', { value: true });\n return res;\n}\n\n/** p, or the signal's reason as soon as it aborts. A request already at\n * the handle runs on, and the loader waits for it before answering; one\n * still waiting for its turn is never sent. */\nfunction abortable<T>(p: Promise<T>, signal: AbortSignal | null | undefined): Promise<T> {\n if (!signal) return p;\n if (signal.aborted) return Promise.reject(signal.reason);\n return new Promise<T>((resolve, reject) => {\n const onAbort = () => reject(signal.reason);\n signal.addEventListener('abort', onAbort, { once: true });\n p.then(\n (v) => {\n signal.removeEventListener('abort', onAbort);\n resolve(v);\n },\n (e) => {\n signal.removeEventListener('abort', onAbort);\n reject(e);\n },\n );\n });\n}\n\n/** ctx.env: the secrets as a frozen object of strings. */\nfunction envOf(raw: unknown): Readonly<Record<string, string>> {\n const entries =\n raw && typeof raw === 'object' && !Array.isArray(raw)\n ? Object.entries(raw).filter((e): e is [string, string] => typeof e[1] === 'string')\n : [];\n return Object.freeze(Object.fromEntries(entries));\n}\n\nfunction failure(err: unknown): ActionRunResult {\n if (err instanceof ActionError || (err instanceof Error && err.name === 'ActionError')) {\n return { ok: false, error: { kind: 'action_error', message: err.message } };\n }\n const e = err instanceof Error ? err : new Error(String(err));\n const label =\n e instanceof ActionDbError || e instanceof ClipError || e instanceof NetError\n ? `${e.name} ${e.code}`\n : 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 // Outbound requests: one handle call per hop, at most net_in_flight at\n // once (more wait their turn), tracked like database calls.\n const limit = Math.max(1, req.net_in_flight || DEFAULT_IN_FLIGHT);\n let active = 0;\n const waiting: (() => void)[] = [];\n const send = async (hop: Hop, timeoutMs: number | undefined, signal: AbortSignal | null) => {\n while (active >= limit) await new Promise<void>((resume) => waiting.push(resume));\n active++;\n try {\n // Aborted while it waited for its turn (the code has already had\n // the abort): it is never sent, and the turn passes on.\n if (signal?.aborted) throw signal.reason;\n if (typeof handle.request !== 'function') {\n throw new NetError('NET_UNAVAILABLE', 'this runtime cannot make requests yet');\n }\n return unwrapNet(\n await handle.request({\n ...hop,\n ...(timeoutMs === undefined ? {} : { timeout_ms: timeoutMs }),\n }),\n );\n } finally {\n active--;\n waiting.shift()?.();\n }\n };\n const request = async (input: string | URL | Request, init?: ActionFetchInit) => {\n const first = await firstHop(input, init);\n const { redirect, signal } = first;\n let hop = first.hop;\n for (let followed = 0; ; followed++) {\n // Aborted before this hop: it is never asked for.\n if (signal?.aborted) throw signal.reason;\n const answer = await abortable(send(hop, init?.timeoutMs, signal), signal);\n if (redirect !== 'manual' && REDIRECT_STATUS.has(answer.status)) {\n if (redirect === 'error') {\n throw new NetError(\n 'NET_FAILED',\n `the server redirected (${answer.status}) and redirect is \"error\"`,\n );\n }\n const location = answer.headers.find(\n ([name]) => name.toLowerCase() === 'location',\n )?.[1];\n const next = nextHop(hop, answer.status, location);\n if (next) {\n if (followed >= MAX_REDIRECTS) {\n throw new NetError(\n 'ACTION_LIMIT_EXCEEDED',\n `ctx.fetch follows at most ${MAX_REDIRECTS} redirects`,\n );\n }\n hop = next;\n continue;\n }\n }\n return toResponse(answer, hop, followed > 0);\n }\n };\n const ctxFetch: ActionFetch = (input, init) =>\n track<Response>(\n request(input, init).then((res) => ({ ok: true, value: res }) as ActionHandleResult),\n (result) => (result as { value: unknown }).value,\n );\n const env = envOf(req.env);\n try {\n const fn = Object.hasOwn(actions, req.action) ? actions[req.action] : undefined;\n if (typeof fn !== 'function') {\n throw new Error(\n `this module does not implement the action ${JSON.stringify(req.action)}`,\n );\n }\n const value = await fn(\n { viewer: req.viewer, app: req.app, db, clip, fetch: ctxFetch, env },\n req.params,\n );\n await drain();\n // A call that failed while the code never looked at it (a forgotten\n // await) fails the action: answering ok would claim a write that did\n // not happen.\n for (const [dbCall, err] of failed) if (!dbCall.handled) throw err;\n const json = JSON.stringify(value === undefined ? null : value);\n if (typeof json !== 'string') {\n throw new TypeError('the action returned a value JSON cannot represent');\n }\n return { ok: true, json };\n } catch (err) {\n await drain();\n return failure(err);\n }\n }\n }\n return ActionEntrypoint;\n}\n";
1
+ export declare const ACTIONS_SDK_SOURCE = "/**\n * @parall/miniapp-sdk/actions \u2014 the action side of a Mini App\n * (docs/engineering-design/mini-app-action-design.md \u00A72): `defineActions`\n * turns the author's functions into the module entry the action loader\n * calls; `ActionError` is the error whose message the caller may see.\n *\n * This file runs inside the Cloudflare isolate, not in the page. It is the\n * only part of the SDK that imports `cloudflare:workers`, and an action\n * module is built from it into one file whose sole external import is that\n * one. Export the result as `ActionRunner` \u2014 the loader looks it up by name:\n *\n * export const ActionRunner = defineActions({\n * async addNote(ctx, { text }) {\n * const { rows } = await ctx.db.exec(\n * 'INSERT INTO notes (text, created_by) VALUES ($1, $2) RETURNING id',\n * [text, ctx.viewer.id],\n * );\n * return rows[0];\n * },\n * });\n *\n * Security does not depend on this wrapper: the loader accepts only the two\n * result shapes run() returns, whatever produced them (design \u00A73.1).\n *\n * An action that declares `\"clip\": true` in the manifest (write actions only)\n * may call 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 * `ctx.fetch` requests a public HTTP(S) address and returns a standard\n * `Response` (docs/engineering-design/mini-app-network-design.md):\n *\n * const res = await ctx.fetch('https://api.example.com/v1/items');\n * if (!res.ok) throw new ActionError(`the items API answered ${res.status}`);\n * return res.json();\n *\n * `ctx.env` holds the app's secrets by name. Online they are the org shared\n * secrets an org owner or admin gave this app (org settings \u2192 \u5171\u4EAB\u5BC6\u94A5 \u2192\n * \u7ED9\u54EA\u4E9B app); a name the app was not given is undefined:\n *\n * const key = ctx.env.EXAMPLE_API_KEY;\n * if (!key) throw new ActionError('EXAMPLE_API_KEY is missing: an org owner or admin can give it to this app');\n * const res = await ctx.fetch('https://api.example.com/v1/items', { headers: { Authorization: `Bearer ${key}` } });\n */\n\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/** An outbound request (ctx.fetch) that was refused or failed \u2014 an HTTP\n * error status is not one: it comes back as a Response. `code` is the\n * platform's:\n *\n * - not sent: ACTION_INVALID_CALL (the URL, method, headers or body),\n * NET_ADDRESS_BLOCKED (an IP address or a loopback name such as localhost\n * written in the URL, the platform's own hosts), ACTION_LIMIT_EXCEEDED\n * (too many requests, or one too large), ACTION_DEADLINE (too little time\n * left), NET_BUSY (the platform is busy; try again shortly),\n * NET_UNAVAILABLE, USER_DISABLED, ACTION_HANDLE_REVOKED;\n * - sent, so it may have reached the server: NET_TIMEOUT, NET_FAILED,\n * NET_RESPONSE_TOO_LARGE (answers are at most 1 MiB).\n *\n * A host name that resolves to a private or loopback address is not refused\n * here: Cloudflare's edge refuses it, and ctx.fetch returns an ordinary\n * Response with status 530 (body like \"error code: 1016\"), not a NetError;\n * the outbound record shows it as answered with HTTP 530.\n *\n * The platform never retries; send an idempotency key where the other side\n * supports one. */\nexport class NetError extends Error {\n readonly code: string;\n\n constructor(code: string, message: string) {\n super(message);\n this.name = 'NetError';\n this.code = code;\n }\n}\n\n/** 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\n/** ctx.fetch's options: the standard ones \u2014 method, headers, body, signal,\n * redirect \u2014 and the request's timeout. Others (cache, credentials, mode,\n * the Workers `cf`) are not looked at: every request is uncached and carries\n * only what the code sets. */\nexport interface ActionFetchInit extends RequestInit {\n /** This request's timeout; 30 s by default, cut to what the action's\n * deadline leaves. With redirects, each hop has it. */\n timeoutMs?: number;\n}\n\n/** ctx.fetch: a public HTTP(S) request from the platform, recorded in the\n * app's call record (host, method, status, size and time \u2014 never the query\n * string, headers or bodies). A local run (`parall app action run --local`,\n * `parall app dev`) sends it straight from your machine and records nothing.\n * Redirects are followed up to 5 times: within the same origin as Fetch\n * does; to another origin with only Accept, Accept-Language,\n * Content-Language and User-Agent kept, and not at all when the next request\n * would carry the body (307, 308, and 301 / 302 for a method other than GET,\n * HEAD or POST) or when it would go from https: to http: \u2014 then the redirect\n * itself comes back. Each hop is a request of its own and counts toward the\n * invocation's request limit (20 by default). At most 4 requests (by\n * default) run at once; more wait their turn. Request and answer bodies are\n * at most 1 MiB each. */\nexport type ActionFetch = (\n input: string | URL | Request,\n init?: ActionFetchInit,\n) => Promise<Response>;\n\nexport interface ActionContext {\n viewer: ActionViewer;\n app: ActionApp;\n db: ActionDb;\n clip: ActionClip;\n fetch: ActionFetch;\n /** The app's secrets by name; read-only. Online they are the org shared\n * secrets an org owner or admin gave this app; a local run (`parall app\n * action run --local`) reads the project's .dev.vars instead. Never pass\n * them as params or write them to the Database or a result. */\n env: Readonly<Record<string, string>>;\n}\n\n// biome-ignore lint/suspicious/noExplicitAny: the platform validates params against the declared schema before the call\nexport type ActionFunction = (ctx: ActionContext, params: any) => unknown;\n\n/** What the loader passes run() (ts/actions-worker src/run.ts). A loader\n * before the network sends neither env nor net_in_flight. */\nexport interface ActionRunRequest {\n action: string;\n params: unknown;\n viewer: ActionViewer;\n app: ActionApp;\n env?: Record<string, string>;\n /** How many requests the handle takes at once. */\n net_in_flight?: number;\n}\n\n/** The only two shapes the loader accepts back (ts/actions-worker src/outcome.ts). */\nexport type ActionRunResult =\n | { ok: true; json: string }\n | { ok: false; error: { kind: 'action_error' | 'unexpected'; message: string; stack?: string } };\n\n/** What a handle method resolves to. Failures travel as values because\n * Workers RPC keeps only an exception's name and message (design \u00A76). */\nexport type ActionHandleResult =\n | { ok: true; value: unknown }\n | { ok: false; error: { code: string; message: string } };\n\n/** What the handle's clip method takes. */\nexport interface ActionHandleClipRequest {\n clip: string;\n command: string;\n args?: unknown;\n connection: string;\n profile?: string;\n timeout_ms?: number;\n}\n\n/** What the handle's request method takes: one request, rebuilt by the\n * loader from exactly these fields. */\nexport interface ActionHandleNetRequest {\n url: string;\n method: string;\n headers: [string, string][];\n body: ArrayBuffer | null;\n timeout_ms?: number;\n}\n\n/** What it answers with on success: the answer, never followed. */\nexport interface ActionHandleNetAnswer {\n status: number;\n status_text: string;\n headers: [string, string][];\n body: ArrayBuffer | null;\n}\n\n/** The per-invocation handle the loader passes run(). A loader before Clip\n * calls has no clip method; one before the network has no request 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 request?(req: ActionHandleNetRequest): 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 unwrapNet(result: ActionHandleResult): ActionHandleNetAnswer {\n if (result?.ok === false) throw new NetError(result.error.code, result.error.message);\n const a = (result?.ok === true ? result.value : null) as ActionHandleNetAnswer | null;\n if (\n !a ||\n typeof a.status !== 'number' ||\n !Array.isArray(a.headers) ||\n (a.body !== null && !(a.body instanceof ArrayBuffer))\n ) {\n throw new NetError(\n 'NET_FAILED',\n 'the request answered in an unknown shape; it may have reached the server',\n );\n }\n return a;\n}\n\n// Statuses whose Response has no body (Fetch's null body status).\nconst NULL_BODY_STATUS = new Set([101, 103, 204, 205, 304]);\nconst REDIRECT_STATUS = new Set([301, 302, 303, 307, 308]);\n// What a redirect to another origin keeps of the author's headers\n// (mini-app-network-design.md \u00A74): a key may be in any other one.\nconst CROSS_ORIGIN_HEADERS = new Set([\n 'accept',\n 'accept-language',\n 'content-language',\n 'user-agent',\n]);\n// Dropped with the body when a redirect turns the request into a GET.\nconst BODY_HEADERS = new Set([\n 'content-encoding',\n 'content-language',\n 'content-location',\n 'content-type',\n]);\nconst MAX_REDIRECTS = 5;\nconst DEFAULT_IN_FLIGHT = 4;\n\n/** One request of a ctx.fetch: the first, or a redirect's next hop. */\ninterface Hop {\n url: string;\n method: string;\n headers: [string, string][];\n body: ArrayBuffer | null;\n}\n\nfunction headerPairs(headers: Headers): [string, string][] {\n const out: [string, string][] = [];\n headers.forEach((value, name) => {\n out.push([name, value]);\n });\n return out;\n}\n\n/** The first hop, as a standard Request reads the input and init \u2014 only\n * the method, headers and body are taken from them. */\nasync function firstHop(input: string | URL | Request, init: ActionFetchInit | undefined) {\n let request: Request;\n try {\n request = new Request(input, {\n method: init?.method,\n headers: init?.headers,\n body: init?.body,\n });\n } catch (err) {\n throw new NetError(\n 'ACTION_INVALID_CALL',\n `ctx.fetch: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n const hop: Hop = {\n url: request.url,\n method: request.method,\n headers: headerPairs(request.headers),\n body: request.body ? await request.arrayBuffer() : null,\n };\n const fromInput = typeof input === 'object' && 'redirect' in input ? input.redirect : undefined;\n return {\n hop,\n redirect: (init?.redirect ?? fromInput ?? 'follow') as RequestRedirect,\n signal: init?.signal ?? (input instanceof Request ? input.signal : null),\n };\n}\n\n/** The next hop for a redirect, or null when it is not to be followed\n * (mini-app-network-design.md \u00A74). The handle checks the address of every\n * hop as it does the first: an IP address or loopback name in the Location,\n * or the platform, is refused there; a name that resolves to a private\n * address is left to Cloudflare's edge (status 530). */\nfunction nextHop(hop: Hop, status: number, location: string | undefined): Hop | null {\n if (!REDIRECT_STATUS.has(status) || location === undefined) return null;\n let from: URL;\n let to: URL;\n try {\n from = new URL(hop.url);\n to = new URL(location, hop.url);\n } catch {\n return null;\n }\n if (from.protocol === 'https:' && to.protocol === 'http:') return null;\n const sameOrigin = to.origin === from.origin && to.origin !== 'null';\n const toGet =\n (status === 303 && hop.method !== 'GET' && hop.method !== 'HEAD') ||\n ((status === 301 || status === 302) && hop.method === 'POST');\n if (!sameOrigin) {\n // The next request would carry the body to another origin.\n if (status === 307 || status === 308) return null;\n if ((status === 301 || status === 302) && !['GET', 'HEAD', 'POST'].includes(hop.method)) {\n return null;\n }\n }\n let { method, headers, body } = hop;\n if (toGet) {\n method = 'GET';\n body = null;\n headers = headers.filter(([name]) => !BODY_HEADERS.has(name.toLowerCase()));\n }\n if (!sameOrigin)\n headers = headers.filter(([name]) => CROSS_ORIGIN_HEADERS.has(name.toLowerCase()));\n return { url: to.href, method, headers, body };\n}\n\nfunction toResponse(answer: ActionHandleNetAnswer, hop: Hop, redirected: boolean): Response {\n if (answer.status < 200 || answer.status > 599) {\n throw new NetError('NET_FAILED', `the server answered with status ${answer.status}`);\n }\n // As Fetch does: no body for a HEAD request or a null body status.\n const body = hop.method === 'HEAD' || NULL_BODY_STATUS.has(answer.status) ? null : answer.body;\n let res: Response;\n try {\n res = new Response(body, {\n status: answer.status,\n statusText: answer.status_text,\n headers: answer.headers,\n });\n } catch {\n try {\n res = new Response(body, { status: answer.status, headers: answer.headers });\n } catch {\n throw new NetError('NET_FAILED', 'the answer could not be read');\n }\n }\n // As a fetch Response: the URL that answered, and whether it was reached\n // through a redirect.\n Object.defineProperty(res, 'url', { value: hop.url });\n if (redirected) Object.defineProperty(res, 'redirected', { value: true });\n return res;\n}\n\n/** p, or the signal's reason as soon as it aborts. A request already at\n * the handle runs on, and the loader waits for it before answering; one\n * still waiting for its turn is never sent. */\nfunction abortable<T>(p: Promise<T>, signal: AbortSignal | null | undefined): Promise<T> {\n if (!signal) return p;\n if (signal.aborted) return Promise.reject(signal.reason);\n return new Promise<T>((resolve, reject) => {\n const onAbort = () => reject(signal.reason);\n signal.addEventListener('abort', onAbort, { once: true });\n p.then(\n (v) => {\n signal.removeEventListener('abort', onAbort);\n resolve(v);\n },\n (e) => {\n signal.removeEventListener('abort', onAbort);\n reject(e);\n },\n );\n });\n}\n\n/** ctx.env: the secrets as a frozen object of strings. */\nfunction envOf(raw: unknown): Readonly<Record<string, string>> {\n const entries =\n raw && typeof raw === 'object' && !Array.isArray(raw)\n ? Object.entries(raw).filter((e): e is [string, string] => typeof e[1] === 'string')\n : [];\n return Object.freeze(Object.fromEntries(entries));\n}\n\nfunction failure(err: unknown): ActionRunResult {\n if (err instanceof ActionError || (err instanceof Error && err.name === 'ActionError')) {\n return { ok: false, error: { kind: 'action_error', message: err.message } };\n }\n const e = err instanceof Error ? err : new Error(String(err));\n const label =\n e instanceof ActionDbError || e instanceof ClipError || e instanceof NetError\n ? `${e.name} ${e.code}`\n : 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 // Outbound requests: one handle call per hop, at most net_in_flight at\n // once (more wait their turn), tracked like database calls.\n const limit = Math.max(1, req.net_in_flight || DEFAULT_IN_FLIGHT);\n let active = 0;\n const waiting: (() => void)[] = [];\n const send = async (hop: Hop, timeoutMs: number | undefined, signal: AbortSignal | null) => {\n while (active >= limit) await new Promise<void>((resume) => waiting.push(resume));\n active++;\n try {\n // Aborted while it waited for its turn (the code has already had\n // the abort): it is never sent, and the turn passes on.\n if (signal?.aborted) throw signal.reason;\n if (typeof handle.request !== 'function') {\n throw new NetError('NET_UNAVAILABLE', 'this runtime cannot make requests yet');\n }\n return unwrapNet(\n await handle.request({\n ...hop,\n ...(timeoutMs === undefined ? {} : { timeout_ms: timeoutMs }),\n }),\n );\n } finally {\n active--;\n waiting.shift()?.();\n }\n };\n const request = async (input: string | URL | Request, init?: ActionFetchInit) => {\n const first = await firstHop(input, init);\n const { redirect, signal } = first;\n let hop = first.hop;\n for (let followed = 0; ; followed++) {\n // Aborted before this hop: it is never asked for.\n if (signal?.aborted) throw signal.reason;\n const answer = await abortable(send(hop, init?.timeoutMs, signal), signal);\n if (redirect !== 'manual' && REDIRECT_STATUS.has(answer.status)) {\n if (redirect === 'error') {\n throw new NetError(\n 'NET_FAILED',\n `the server redirected (${answer.status}) and redirect is \"error\"`,\n );\n }\n const location = answer.headers.find(\n ([name]) => name.toLowerCase() === 'location',\n )?.[1];\n const next = nextHop(hop, answer.status, location);\n if (next) {\n if (followed >= MAX_REDIRECTS) {\n throw new NetError(\n 'ACTION_LIMIT_EXCEEDED',\n `ctx.fetch follows at most ${MAX_REDIRECTS} redirects`,\n );\n }\n hop = next;\n continue;\n }\n }\n return toResponse(answer, hop, followed > 0);\n }\n };\n const ctxFetch: ActionFetch = (input, init) =>\n track<Response>(\n request(input, init).then((res) => ({ ok: true, value: res }) as ActionHandleResult),\n (result) => (result as { value: unknown }).value,\n );\n const env = envOf(req.env);\n try {\n const fn = Object.hasOwn(actions, req.action) ? actions[req.action] : undefined;\n if (typeof fn !== 'function') {\n throw new Error(\n `this module does not implement the action ${JSON.stringify(req.action)}`,\n );\n }\n const value = await fn(\n { viewer: req.viewer, app: req.app, db, clip, fetch: ctxFetch, env },\n req.params,\n );\n await drain();\n // A call that failed while the code never looked at it (a forgotten\n // await) fails the action: answering ok would claim a write that did\n // not happen.\n for (const [dbCall, err] of failed) if (!dbCall.handled) throw err;\n const json = JSON.stringify(value === undefined ? null : value);\n if (typeof json !== 'string') {\n throw new TypeError('the action returned a value JSON cannot represent');\n }\n return { ok: true, json };\n } catch (err) {\n await drain();\n return failure(err);\n }\n }\n }\n return ActionEntrypoint;\n}\n";
2
2
  //# sourceMappingURL=apps-actions-sdk.generated.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"apps-actions-sdk.generated.d.ts","sourceRoot":"","sources":["../../src/commands/apps-actions-sdk.generated.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,kBAAkB,wi0BAA+7zB,CAAC"}
1
+ {"version":3,"file":"apps-actions-sdk.generated.d.ts","sourceRoot":"","sources":["../../src/commands/apps-actions-sdk.generated.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,kBAAkB,8p2BAAwg2B,CAAC"}
@@ -1,3 +1,3 @@
1
1
  // Generated from ts/miniapp-sdk/src/actions.ts by scripts/generate-miniapp-sdk.mjs. Do not edit.
2
2
  // biome-ignore format: generated copy
3
- export const ACTIONS_SDK_SOURCE = "/**\n * @parall/miniapp-sdk/actions — the action side of a Mini App\n * (docs/engineering-design/mini-app-action-design.md §2): `defineActions`\n * turns the author's functions into the module entry the action loader\n * calls; `ActionError` is the error whose message the caller may see.\n *\n * This file runs inside the Cloudflare isolate, not in the page. It is the\n * only part of the SDK that imports `cloudflare:workers`, and an action\n * module is built from it into one file whose sole external import is that\n * one. Export the result as `ActionRunner` — the loader looks it up by name:\n *\n * export const ActionRunner = defineActions({\n * async addNote(ctx, { text }) {\n * const { rows } = await ctx.db.exec(\n * 'INSERT INTO notes (text, created_by) VALUES ($1, $2) RETURNING id',\n * [text, ctx.viewer.id],\n * );\n * return rows[0];\n * },\n * });\n *\n * Security does not depend on this wrapper: the loader accepts only the two\n * result shapes run() returns, whatever produced them (design §3.1).\n *\n * An action that declares `\"clip\": true` in the manifest (write actions only)\n * may call 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 * `ctx.fetch` requests a public HTTP(S) address and returns a standard\n * `Response`; `ctx.env` holds the app's secrets by name\n * (docs/engineering-design/mini-app-network-design.md):\n *\n * const res = await ctx.fetch('https://api.example.com/v1/items', {\n * headers: { Authorization: `Bearer ${ctx.env.EXAMPLE_API_KEY}` },\n * });\n * if (!res.ok) throw new ActionError(`the items API answered ${res.status}`);\n * return res.json();\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/** An outbound request (ctx.fetch) that was refused or failed — an HTTP\n * error status is not one: it comes back as a Response. `code` is the\n * platform's:\n *\n * - not sent: ACTION_INVALID_CALL (the URL, method, headers or body),\n * NET_ADDRESS_BLOCKED (private and loopback addresses, IP literals, the\n * platform's own hosts), ACTION_LIMIT_EXCEEDED (too many requests, or one\n * too large), ACTION_DEADLINE (too little time left), NET_BUSY (the\n * platform is busy; try again shortly), NET_UNAVAILABLE, USER_DISABLED,\n * ACTION_HANDLE_REVOKED;\n * - sent, so it may have reached the server: NET_TIMEOUT, NET_FAILED,\n * NET_RESPONSE_TOO_LARGE (answers are at most 1 MiB).\n *\n * The platform never retries; send an idempotency key where the other side\n * supports one. */\nexport class NetError extends Error {\n readonly code: string;\n\n constructor(code: string, message: string) {\n super(message);\n this.name = 'NetError';\n this.code = code;\n }\n}\n\n/** 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\n/** ctx.fetch's options: the standard ones — method, headers, body, signal,\n * redirect — and the request's timeout. Others (cache, credentials, mode,\n * the Workers `cf`) are not looked at: every request is uncached and carries\n * only what the code sets. */\nexport interface ActionFetchInit extends RequestInit {\n /** This request's timeout; 30 s by default, cut to what the action's\n * deadline leaves. With redirects, each hop has it. */\n timeoutMs?: number;\n}\n\n/** ctx.fetch: a public HTTP(S) request from the platform, recorded in the\n * app's call record (host, method, status, size and time — never the query\n * string, headers or bodies). Redirects are followed up to 5 times: within\n * the same origin as Fetch does; to another origin with only Accept,\n * Accept-Language, Content-Language and User-Agent kept, and not at all when\n * the next request would carry the body (307, 308, and 301 / 302 for a\n * method other than GET, HEAD or POST) or when it would go from https: to\n * http: — then the redirect itself comes back. Each hop is a request of its\n * own. At most a few requests run at once; more wait their turn. */\nexport type ActionFetch = (\n input: string | URL | Request,\n init?: ActionFetchInit,\n) => Promise<Response>;\n\nexport interface ActionContext {\n viewer: ActionViewer;\n app: ActionApp;\n db: ActionDb;\n clip: ActionClip;\n fetch: ActionFetch;\n /** The app's secrets by name, as people with the app's publish right set\n * them; read-only. A local run (`parall app action run --local`) reads\n * them from the project's .dev.vars instead. Never pass them as params or\n * write them to the Database or a result. */\n env: Readonly<Record<string, string>>;\n}\n\n// biome-ignore lint/suspicious/noExplicitAny: the platform validates params against the declared schema before the call\nexport type ActionFunction = (ctx: ActionContext, params: any) => unknown;\n\n/** What the loader passes run() (ts/actions-worker src/run.ts). A loader\n * before the network sends neither env nor net_in_flight. */\nexport interface ActionRunRequest {\n action: string;\n params: unknown;\n viewer: ActionViewer;\n app: ActionApp;\n env?: Record<string, string>;\n /** How many requests the handle takes at once. */\n net_in_flight?: number;\n}\n\n/** The only two shapes the loader accepts back (ts/actions-worker src/outcome.ts). */\nexport type ActionRunResult =\n | { ok: true; json: string }\n | { ok: false; error: { kind: 'action_error' | 'unexpected'; message: string; stack?: string } };\n\n/** What a handle method resolves to. Failures travel as values because\n * Workers RPC keeps only an exception's name and message (design §6). */\nexport type ActionHandleResult =\n | { ok: true; value: unknown }\n | { ok: false; error: { code: string; message: string } };\n\n/** What the handle's clip method takes. */\nexport interface ActionHandleClipRequest {\n clip: string;\n command: string;\n args?: unknown;\n connection: string;\n profile?: string;\n timeout_ms?: number;\n}\n\n/** What the handle's request method takes: one request, rebuilt by the\n * loader from exactly these fields. */\nexport interface ActionHandleNetRequest {\n url: string;\n method: string;\n headers: [string, string][];\n body: ArrayBuffer | null;\n timeout_ms?: number;\n}\n\n/** What it answers with on success: the answer, never followed. */\nexport interface ActionHandleNetAnswer {\n status: number;\n status_text: string;\n headers: [string, string][];\n body: ArrayBuffer | null;\n}\n\n/** The per-invocation handle the loader passes run(). A loader before Clip\n * calls has no clip method; one before the network has no request 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 request?(req: ActionHandleNetRequest): 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 unwrapNet(result: ActionHandleResult): ActionHandleNetAnswer {\n if (result?.ok === false) throw new NetError(result.error.code, result.error.message);\n const a = (result?.ok === true ? result.value : null) as ActionHandleNetAnswer | null;\n if (\n !a ||\n typeof a.status !== 'number' ||\n !Array.isArray(a.headers) ||\n (a.body !== null && !(a.body instanceof ArrayBuffer))\n ) {\n throw new NetError(\n 'NET_FAILED',\n 'the request answered in an unknown shape; it may have reached the server',\n );\n }\n return a;\n}\n\n// Statuses whose Response has no body (Fetch's null body status).\nconst NULL_BODY_STATUS = new Set([101, 103, 204, 205, 304]);\nconst REDIRECT_STATUS = new Set([301, 302, 303, 307, 308]);\n// What a redirect to another origin keeps of the author's headers\n// (mini-app-network-design.md §4): a key may be in any other one.\nconst CROSS_ORIGIN_HEADERS = new Set([\n 'accept',\n 'accept-language',\n 'content-language',\n 'user-agent',\n]);\n// Dropped with the body when a redirect turns the request into a GET.\nconst BODY_HEADERS = new Set([\n 'content-encoding',\n 'content-language',\n 'content-location',\n 'content-type',\n]);\nconst MAX_REDIRECTS = 5;\nconst DEFAULT_IN_FLIGHT = 4;\n\n/** One request of a ctx.fetch: the first, or a redirect's next hop. */\ninterface Hop {\n url: string;\n method: string;\n headers: [string, string][];\n body: ArrayBuffer | null;\n}\n\nfunction headerPairs(headers: Headers): [string, string][] {\n const out: [string, string][] = [];\n headers.forEach((value, name) => {\n out.push([name, value]);\n });\n return out;\n}\n\n/** The first hop, as a standard Request reads the input and init — only\n * the method, headers and body are taken from them. */\nasync function firstHop(input: string | URL | Request, init: ActionFetchInit | undefined) {\n let request: Request;\n try {\n request = new Request(input, {\n method: init?.method,\n headers: init?.headers,\n body: init?.body,\n });\n } catch (err) {\n throw new NetError(\n 'ACTION_INVALID_CALL',\n `ctx.fetch: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n const hop: Hop = {\n url: request.url,\n method: request.method,\n headers: headerPairs(request.headers),\n body: request.body ? await request.arrayBuffer() : null,\n };\n const fromInput = typeof input === 'object' && 'redirect' in input ? input.redirect : undefined;\n return {\n hop,\n redirect: (init?.redirect ?? fromInput ?? 'follow') as RequestRedirect,\n signal: init?.signal ?? (input instanceof Request ? input.signal : null),\n };\n}\n\n/** The next hop for a redirect, or null when it is not to be followed\n * (mini-app-network-design.md §4). The handle checks the address of every\n * hop: one into a private network or the platform is refused there. */\nfunction nextHop(hop: Hop, status: number, location: string | undefined): Hop | null {\n if (!REDIRECT_STATUS.has(status) || location === undefined) return null;\n let from: URL;\n let to: URL;\n try {\n from = new URL(hop.url);\n to = new URL(location, hop.url);\n } catch {\n return null;\n }\n if (from.protocol === 'https:' && to.protocol === 'http:') return null;\n const sameOrigin = to.origin === from.origin && to.origin !== 'null';\n const toGet =\n (status === 303 && hop.method !== 'GET' && hop.method !== 'HEAD') ||\n ((status === 301 || status === 302) && hop.method === 'POST');\n if (!sameOrigin) {\n // The next request would carry the body to another origin.\n if (status === 307 || status === 308) return null;\n if ((status === 301 || status === 302) && !['GET', 'HEAD', 'POST'].includes(hop.method)) {\n return null;\n }\n }\n let { method, headers, body } = hop;\n if (toGet) {\n method = 'GET';\n body = null;\n headers = headers.filter(([name]) => !BODY_HEADERS.has(name.toLowerCase()));\n }\n if (!sameOrigin)\n headers = headers.filter(([name]) => CROSS_ORIGIN_HEADERS.has(name.toLowerCase()));\n return { url: to.href, method, headers, body };\n}\n\nfunction toResponse(answer: ActionHandleNetAnswer, hop: Hop, redirected: boolean): Response {\n if (answer.status < 200 || answer.status > 599) {\n throw new NetError('NET_FAILED', `the server answered with status ${answer.status}`);\n }\n // As Fetch does: no body for a HEAD request or a null body status.\n const body = hop.method === 'HEAD' || NULL_BODY_STATUS.has(answer.status) ? null : answer.body;\n let res: Response;\n try {\n res = new Response(body, {\n status: answer.status,\n statusText: answer.status_text,\n headers: answer.headers,\n });\n } catch {\n try {\n res = new Response(body, { status: answer.status, headers: answer.headers });\n } catch {\n throw new NetError('NET_FAILED', 'the answer could not be read');\n }\n }\n // As a fetch Response: the URL that answered, and whether it was reached\n // through a redirect.\n Object.defineProperty(res, 'url', { value: hop.url });\n if (redirected) Object.defineProperty(res, 'redirected', { value: true });\n return res;\n}\n\n/** p, or the signal's reason as soon as it aborts. A request already at\n * the handle runs on, and the loader waits for it before answering; one\n * still waiting for its turn is never sent. */\nfunction abortable<T>(p: Promise<T>, signal: AbortSignal | null | undefined): Promise<T> {\n if (!signal) return p;\n if (signal.aborted) return Promise.reject(signal.reason);\n return new Promise<T>((resolve, reject) => {\n const onAbort = () => reject(signal.reason);\n signal.addEventListener('abort', onAbort, { once: true });\n p.then(\n (v) => {\n signal.removeEventListener('abort', onAbort);\n resolve(v);\n },\n (e) => {\n signal.removeEventListener('abort', onAbort);\n reject(e);\n },\n );\n });\n}\n\n/** ctx.env: the secrets as a frozen object of strings. */\nfunction envOf(raw: unknown): Readonly<Record<string, string>> {\n const entries =\n raw && typeof raw === 'object' && !Array.isArray(raw)\n ? Object.entries(raw).filter((e): e is [string, string] => typeof e[1] === 'string')\n : [];\n return Object.freeze(Object.fromEntries(entries));\n}\n\nfunction failure(err: unknown): ActionRunResult {\n if (err instanceof ActionError || (err instanceof Error && err.name === 'ActionError')) {\n return { ok: false, error: { kind: 'action_error', message: err.message } };\n }\n const e = err instanceof Error ? err : new Error(String(err));\n const label =\n e instanceof ActionDbError || e instanceof ClipError || e instanceof NetError\n ? `${e.name} ${e.code}`\n : 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 // Outbound requests: one handle call per hop, at most net_in_flight at\n // once (more wait their turn), tracked like database calls.\n const limit = Math.max(1, req.net_in_flight || DEFAULT_IN_FLIGHT);\n let active = 0;\n const waiting: (() => void)[] = [];\n const send = async (hop: Hop, timeoutMs: number | undefined, signal: AbortSignal | null) => {\n while (active >= limit) await new Promise<void>((resume) => waiting.push(resume));\n active++;\n try {\n // Aborted while it waited for its turn (the code has already had\n // the abort): it is never sent, and the turn passes on.\n if (signal?.aborted) throw signal.reason;\n if (typeof handle.request !== 'function') {\n throw new NetError('NET_UNAVAILABLE', 'this runtime cannot make requests yet');\n }\n return unwrapNet(\n await handle.request({\n ...hop,\n ...(timeoutMs === undefined ? {} : { timeout_ms: timeoutMs }),\n }),\n );\n } finally {\n active--;\n waiting.shift()?.();\n }\n };\n const request = async (input: string | URL | Request, init?: ActionFetchInit) => {\n const first = await firstHop(input, init);\n const { redirect, signal } = first;\n let hop = first.hop;\n for (let followed = 0; ; followed++) {\n // Aborted before this hop: it is never asked for.\n if (signal?.aborted) throw signal.reason;\n const answer = await abortable(send(hop, init?.timeoutMs, signal), signal);\n if (redirect !== 'manual' && REDIRECT_STATUS.has(answer.status)) {\n if (redirect === 'error') {\n throw new NetError(\n 'NET_FAILED',\n `the server redirected (${answer.status}) and redirect is \"error\"`,\n );\n }\n const location = answer.headers.find(\n ([name]) => name.toLowerCase() === 'location',\n )?.[1];\n const next = nextHop(hop, answer.status, location);\n if (next) {\n if (followed >= MAX_REDIRECTS) {\n throw new NetError(\n 'ACTION_LIMIT_EXCEEDED',\n `ctx.fetch follows at most ${MAX_REDIRECTS} redirects`,\n );\n }\n hop = next;\n continue;\n }\n }\n return toResponse(answer, hop, followed > 0);\n }\n };\n const ctxFetch: ActionFetch = (input, init) =>\n track<Response>(\n request(input, init).then((res) => ({ ok: true, value: res }) as ActionHandleResult),\n (result) => (result as { value: unknown }).value,\n );\n const env = envOf(req.env);\n try {\n const fn = Object.hasOwn(actions, req.action) ? actions[req.action] : undefined;\n if (typeof fn !== 'function') {\n throw new Error(\n `this module does not implement the action ${JSON.stringify(req.action)}`,\n );\n }\n const value = await fn(\n { viewer: req.viewer, app: req.app, db, clip, fetch: ctxFetch, env },\n req.params,\n );\n await drain();\n // A call that failed while the code never looked at it (a forgotten\n // await) fails the action: answering ok would claim a write that did\n // not happen.\n for (const [dbCall, err] of failed) if (!dbCall.handled) throw err;\n const json = JSON.stringify(value === undefined ? null : value);\n if (typeof json !== 'string') {\n throw new TypeError('the action returned a value JSON cannot represent');\n }\n return { ok: true, json };\n } catch (err) {\n await drain();\n return failure(err);\n }\n }\n }\n return ActionEntrypoint;\n}\n";
3
+ export const ACTIONS_SDK_SOURCE = "/**\n * @parall/miniapp-sdk/actions — the action side of a Mini App\n * (docs/engineering-design/mini-app-action-design.md §2): `defineActions`\n * turns the author's functions into the module entry the action loader\n * calls; `ActionError` is the error whose message the caller may see.\n *\n * This file runs inside the Cloudflare isolate, not in the page. It is the\n * only part of the SDK that imports `cloudflare:workers`, and an action\n * module is built from it into one file whose sole external import is that\n * one. Export the result as `ActionRunner` — the loader looks it up by name:\n *\n * export const ActionRunner = defineActions({\n * async addNote(ctx, { text }) {\n * const { rows } = await ctx.db.exec(\n * 'INSERT INTO notes (text, created_by) VALUES ($1, $2) RETURNING id',\n * [text, ctx.viewer.id],\n * );\n * return rows[0];\n * },\n * });\n *\n * Security does not depend on this wrapper: the loader accepts only the two\n * result shapes run() returns, whatever produced them (design §3.1).\n *\n * An action that declares `\"clip\": true` in the manifest (write actions only)\n * may call 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 * `ctx.fetch` requests a public HTTP(S) address and returns a standard\n * `Response` (docs/engineering-design/mini-app-network-design.md):\n *\n * const res = await ctx.fetch('https://api.example.com/v1/items');\n * if (!res.ok) throw new ActionError(`the items API answered ${res.status}`);\n * return res.json();\n *\n * `ctx.env` holds the app's secrets by name. Online they are the org shared\n * secrets an org owner or admin gave this app (org settings → 共享密钥 →\n * 给哪些 app); a name the app was not given is undefined:\n *\n * const key = ctx.env.EXAMPLE_API_KEY;\n * if (!key) throw new ActionError('EXAMPLE_API_KEY is missing: an org owner or admin can give it to this app');\n * const res = await ctx.fetch('https://api.example.com/v1/items', { headers: { Authorization: `Bearer ${key}` } });\n */\n\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/** An outbound request (ctx.fetch) that was refused or failed — an HTTP\n * error status is not one: it comes back as a Response. `code` is the\n * platform's:\n *\n * - not sent: ACTION_INVALID_CALL (the URL, method, headers or body),\n * NET_ADDRESS_BLOCKED (an IP address or a loopback name such as localhost\n * written in the URL, the platform's own hosts), ACTION_LIMIT_EXCEEDED\n * (too many requests, or one too large), ACTION_DEADLINE (too little time\n * left), NET_BUSY (the platform is busy; try again shortly),\n * NET_UNAVAILABLE, USER_DISABLED, ACTION_HANDLE_REVOKED;\n * - sent, so it may have reached the server: NET_TIMEOUT, NET_FAILED,\n * NET_RESPONSE_TOO_LARGE (answers are at most 1 MiB).\n *\n * A host name that resolves to a private or loopback address is not refused\n * here: Cloudflare's edge refuses it, and ctx.fetch returns an ordinary\n * Response with status 530 (body like \"error code: 1016\"), not a NetError;\n * the outbound record shows it as answered with HTTP 530.\n *\n * The platform never retries; send an idempotency key where the other side\n * supports one. */\nexport class NetError extends Error {\n readonly code: string;\n\n constructor(code: string, message: string) {\n super(message);\n this.name = 'NetError';\n this.code = code;\n }\n}\n\n/** 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\n/** ctx.fetch's options: the standard ones — method, headers, body, signal,\n * redirect — and the request's timeout. Others (cache, credentials, mode,\n * the Workers `cf`) are not looked at: every request is uncached and carries\n * only what the code sets. */\nexport interface ActionFetchInit extends RequestInit {\n /** This request's timeout; 30 s by default, cut to what the action's\n * deadline leaves. With redirects, each hop has it. */\n timeoutMs?: number;\n}\n\n/** ctx.fetch: a public HTTP(S) request from the platform, recorded in the\n * app's call record (host, method, status, size and time — never the query\n * string, headers or bodies). A local run (`parall app action run --local`,\n * `parall app dev`) sends it straight from your machine and records nothing.\n * Redirects are followed up to 5 times: within the same origin as Fetch\n * does; to another origin with only Accept, Accept-Language,\n * Content-Language and User-Agent kept, and not at all when the next request\n * would carry the body (307, 308, and 301 / 302 for a method other than GET,\n * HEAD or POST) or when it would go from https: to http: — then the redirect\n * itself comes back. Each hop is a request of its own and counts toward the\n * invocation's request limit (20 by default). At most 4 requests (by\n * default) run at once; more wait their turn. Request and answer bodies are\n * at most 1 MiB each. */\nexport type ActionFetch = (\n input: string | URL | Request,\n init?: ActionFetchInit,\n) => Promise<Response>;\n\nexport interface ActionContext {\n viewer: ActionViewer;\n app: ActionApp;\n db: ActionDb;\n clip: ActionClip;\n fetch: ActionFetch;\n /** The app's secrets by name; read-only. Online they are the org shared\n * secrets an org owner or admin gave this app; a local run (`parall app\n * action run --local`) reads the project's .dev.vars instead. Never pass\n * them as params or write them to the Database or a result. */\n env: Readonly<Record<string, string>>;\n}\n\n// biome-ignore lint/suspicious/noExplicitAny: the platform validates params against the declared schema before the call\nexport type ActionFunction = (ctx: ActionContext, params: any) => unknown;\n\n/** What the loader passes run() (ts/actions-worker src/run.ts). A loader\n * before the network sends neither env nor net_in_flight. */\nexport interface ActionRunRequest {\n action: string;\n params: unknown;\n viewer: ActionViewer;\n app: ActionApp;\n env?: Record<string, string>;\n /** How many requests the handle takes at once. */\n net_in_flight?: number;\n}\n\n/** The only two shapes the loader accepts back (ts/actions-worker src/outcome.ts). */\nexport type ActionRunResult =\n | { ok: true; json: string }\n | { ok: false; error: { kind: 'action_error' | 'unexpected'; message: string; stack?: string } };\n\n/** What a handle method resolves to. Failures travel as values because\n * Workers RPC keeps only an exception's name and message (design §6). */\nexport type ActionHandleResult =\n | { ok: true; value: unknown }\n | { ok: false; error: { code: string; message: string } };\n\n/** What the handle's clip method takes. */\nexport interface ActionHandleClipRequest {\n clip: string;\n command: string;\n args?: unknown;\n connection: string;\n profile?: string;\n timeout_ms?: number;\n}\n\n/** What the handle's request method takes: one request, rebuilt by the\n * loader from exactly these fields. */\nexport interface ActionHandleNetRequest {\n url: string;\n method: string;\n headers: [string, string][];\n body: ArrayBuffer | null;\n timeout_ms?: number;\n}\n\n/** What it answers with on success: the answer, never followed. */\nexport interface ActionHandleNetAnswer {\n status: number;\n status_text: string;\n headers: [string, string][];\n body: ArrayBuffer | null;\n}\n\n/** The per-invocation handle the loader passes run(). A loader before Clip\n * calls has no clip method; one before the network has no request 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 request?(req: ActionHandleNetRequest): 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 unwrapNet(result: ActionHandleResult): ActionHandleNetAnswer {\n if (result?.ok === false) throw new NetError(result.error.code, result.error.message);\n const a = (result?.ok === true ? result.value : null) as ActionHandleNetAnswer | null;\n if (\n !a ||\n typeof a.status !== 'number' ||\n !Array.isArray(a.headers) ||\n (a.body !== null && !(a.body instanceof ArrayBuffer))\n ) {\n throw new NetError(\n 'NET_FAILED',\n 'the request answered in an unknown shape; it may have reached the server',\n );\n }\n return a;\n}\n\n// Statuses whose Response has no body (Fetch's null body status).\nconst NULL_BODY_STATUS = new Set([101, 103, 204, 205, 304]);\nconst REDIRECT_STATUS = new Set([301, 302, 303, 307, 308]);\n// What a redirect to another origin keeps of the author's headers\n// (mini-app-network-design.md §4): a key may be in any other one.\nconst CROSS_ORIGIN_HEADERS = new Set([\n 'accept',\n 'accept-language',\n 'content-language',\n 'user-agent',\n]);\n// Dropped with the body when a redirect turns the request into a GET.\nconst BODY_HEADERS = new Set([\n 'content-encoding',\n 'content-language',\n 'content-location',\n 'content-type',\n]);\nconst MAX_REDIRECTS = 5;\nconst DEFAULT_IN_FLIGHT = 4;\n\n/** One request of a ctx.fetch: the first, or a redirect's next hop. */\ninterface Hop {\n url: string;\n method: string;\n headers: [string, string][];\n body: ArrayBuffer | null;\n}\n\nfunction headerPairs(headers: Headers): [string, string][] {\n const out: [string, string][] = [];\n headers.forEach((value, name) => {\n out.push([name, value]);\n });\n return out;\n}\n\n/** The first hop, as a standard Request reads the input and init — only\n * the method, headers and body are taken from them. */\nasync function firstHop(input: string | URL | Request, init: ActionFetchInit | undefined) {\n let request: Request;\n try {\n request = new Request(input, {\n method: init?.method,\n headers: init?.headers,\n body: init?.body,\n });\n } catch (err) {\n throw new NetError(\n 'ACTION_INVALID_CALL',\n `ctx.fetch: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n const hop: Hop = {\n url: request.url,\n method: request.method,\n headers: headerPairs(request.headers),\n body: request.body ? await request.arrayBuffer() : null,\n };\n const fromInput = typeof input === 'object' && 'redirect' in input ? input.redirect : undefined;\n return {\n hop,\n redirect: (init?.redirect ?? fromInput ?? 'follow') as RequestRedirect,\n signal: init?.signal ?? (input instanceof Request ? input.signal : null),\n };\n}\n\n/** The next hop for a redirect, or null when it is not to be followed\n * (mini-app-network-design.md §4). The handle checks the address of every\n * hop as it does the first: an IP address or loopback name in the Location,\n * or the platform, is refused there; a name that resolves to a private\n * address is left to Cloudflare's edge (status 530). */\nfunction nextHop(hop: Hop, status: number, location: string | undefined): Hop | null {\n if (!REDIRECT_STATUS.has(status) || location === undefined) return null;\n let from: URL;\n let to: URL;\n try {\n from = new URL(hop.url);\n to = new URL(location, hop.url);\n } catch {\n return null;\n }\n if (from.protocol === 'https:' && to.protocol === 'http:') return null;\n const sameOrigin = to.origin === from.origin && to.origin !== 'null';\n const toGet =\n (status === 303 && hop.method !== 'GET' && hop.method !== 'HEAD') ||\n ((status === 301 || status === 302) && hop.method === 'POST');\n if (!sameOrigin) {\n // The next request would carry the body to another origin.\n if (status === 307 || status === 308) return null;\n if ((status === 301 || status === 302) && !['GET', 'HEAD', 'POST'].includes(hop.method)) {\n return null;\n }\n }\n let { method, headers, body } = hop;\n if (toGet) {\n method = 'GET';\n body = null;\n headers = headers.filter(([name]) => !BODY_HEADERS.has(name.toLowerCase()));\n }\n if (!sameOrigin)\n headers = headers.filter(([name]) => CROSS_ORIGIN_HEADERS.has(name.toLowerCase()));\n return { url: to.href, method, headers, body };\n}\n\nfunction toResponse(answer: ActionHandleNetAnswer, hop: Hop, redirected: boolean): Response {\n if (answer.status < 200 || answer.status > 599) {\n throw new NetError('NET_FAILED', `the server answered with status ${answer.status}`);\n }\n // As Fetch does: no body for a HEAD request or a null body status.\n const body = hop.method === 'HEAD' || NULL_BODY_STATUS.has(answer.status) ? null : answer.body;\n let res: Response;\n try {\n res = new Response(body, {\n status: answer.status,\n statusText: answer.status_text,\n headers: answer.headers,\n });\n } catch {\n try {\n res = new Response(body, { status: answer.status, headers: answer.headers });\n } catch {\n throw new NetError('NET_FAILED', 'the answer could not be read');\n }\n }\n // As a fetch Response: the URL that answered, and whether it was reached\n // through a redirect.\n Object.defineProperty(res, 'url', { value: hop.url });\n if (redirected) Object.defineProperty(res, 'redirected', { value: true });\n return res;\n}\n\n/** p, or the signal's reason as soon as it aborts. A request already at\n * the handle runs on, and the loader waits for it before answering; one\n * still waiting for its turn is never sent. */\nfunction abortable<T>(p: Promise<T>, signal: AbortSignal | null | undefined): Promise<T> {\n if (!signal) return p;\n if (signal.aborted) return Promise.reject(signal.reason);\n return new Promise<T>((resolve, reject) => {\n const onAbort = () => reject(signal.reason);\n signal.addEventListener('abort', onAbort, { once: true });\n p.then(\n (v) => {\n signal.removeEventListener('abort', onAbort);\n resolve(v);\n },\n (e) => {\n signal.removeEventListener('abort', onAbort);\n reject(e);\n },\n );\n });\n}\n\n/** ctx.env: the secrets as a frozen object of strings. */\nfunction envOf(raw: unknown): Readonly<Record<string, string>> {\n const entries =\n raw && typeof raw === 'object' && !Array.isArray(raw)\n ? Object.entries(raw).filter((e): e is [string, string] => typeof e[1] === 'string')\n : [];\n return Object.freeze(Object.fromEntries(entries));\n}\n\nfunction failure(err: unknown): ActionRunResult {\n if (err instanceof ActionError || (err instanceof Error && err.name === 'ActionError')) {\n return { ok: false, error: { kind: 'action_error', message: err.message } };\n }\n const e = err instanceof Error ? err : new Error(String(err));\n const label =\n e instanceof ActionDbError || e instanceof ClipError || e instanceof NetError\n ? `${e.name} ${e.code}`\n : 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 // Outbound requests: one handle call per hop, at most net_in_flight at\n // once (more wait their turn), tracked like database calls.\n const limit = Math.max(1, req.net_in_flight || DEFAULT_IN_FLIGHT);\n let active = 0;\n const waiting: (() => void)[] = [];\n const send = async (hop: Hop, timeoutMs: number | undefined, signal: AbortSignal | null) => {\n while (active >= limit) await new Promise<void>((resume) => waiting.push(resume));\n active++;\n try {\n // Aborted while it waited for its turn (the code has already had\n // the abort): it is never sent, and the turn passes on.\n if (signal?.aborted) throw signal.reason;\n if (typeof handle.request !== 'function') {\n throw new NetError('NET_UNAVAILABLE', 'this runtime cannot make requests yet');\n }\n return unwrapNet(\n await handle.request({\n ...hop,\n ...(timeoutMs === undefined ? {} : { timeout_ms: timeoutMs }),\n }),\n );\n } finally {\n active--;\n waiting.shift()?.();\n }\n };\n const request = async (input: string | URL | Request, init?: ActionFetchInit) => {\n const first = await firstHop(input, init);\n const { redirect, signal } = first;\n let hop = first.hop;\n for (let followed = 0; ; followed++) {\n // Aborted before this hop: it is never asked for.\n if (signal?.aborted) throw signal.reason;\n const answer = await abortable(send(hop, init?.timeoutMs, signal), signal);\n if (redirect !== 'manual' && REDIRECT_STATUS.has(answer.status)) {\n if (redirect === 'error') {\n throw new NetError(\n 'NET_FAILED',\n `the server redirected (${answer.status}) and redirect is \"error\"`,\n );\n }\n const location = answer.headers.find(\n ([name]) => name.toLowerCase() === 'location',\n )?.[1];\n const next = nextHop(hop, answer.status, location);\n if (next) {\n if (followed >= MAX_REDIRECTS) {\n throw new NetError(\n 'ACTION_LIMIT_EXCEEDED',\n `ctx.fetch follows at most ${MAX_REDIRECTS} redirects`,\n );\n }\n hop = next;\n continue;\n }\n }\n return toResponse(answer, hop, followed > 0);\n }\n };\n const ctxFetch: ActionFetch = (input, init) =>\n track<Response>(\n request(input, init).then((res) => ({ ok: true, value: res }) as ActionHandleResult),\n (result) => (result as { value: unknown }).value,\n );\n const env = envOf(req.env);\n try {\n const fn = Object.hasOwn(actions, req.action) ? actions[req.action] : undefined;\n if (typeof fn !== 'function') {\n throw new Error(\n `this module does not implement the action ${JSON.stringify(req.action)}`,\n );\n }\n const value = await fn(\n { viewer: req.viewer, app: req.app, db, clip, fetch: ctxFetch, env },\n req.params,\n );\n await drain();\n // A call that failed while the code never looked at it (a forgotten\n // await) fails the action: answering ok would claim a write that did\n // not happen.\n for (const [dbCall, err] of failed) if (!dbCall.handled) throw err;\n const json = JSON.stringify(value === undefined ? null : value);\n if (typeof json !== 'string') {\n throw new TypeError('the action returned a value JSON cannot represent');\n }\n return { ok: true, json };\n } catch (err) {\n await drain();\n return failure(err);\n }\n }\n }\n return ActionEntrypoint;\n}\n";
@@ -230,7 +230,12 @@ async function explainFailure(err, ctx) {
230
230
  const details = err.extras?.details;
231
231
  const invocation = typeof details?.invocation_id === 'string' ? details.invocation_id : undefined;
232
232
  if (err.code === 'ACTION_TIMEOUT' && ctx.kind === 'read') {
233
- return `${invocation ?? 'The call'} did not finish within its deadline. A read action cannot write, so nothing changed: it is safe to run it again.`;
233
+ // A read cannot write, but it can send requests (ctx.fetch). A deployed
234
+ // call records them under its invocation; a local run records none.
235
+ const listed = ctx.localSha256 === undefined && invocation
236
+ ? ` (\`parall app action log ${ctx.appId} --invocation ${invocation}\` lists them)`
237
+ : '';
238
+ return `${invocation ?? 'The call'} did not finish within its deadline. A read action cannot write, so its Database is unchanged and running it again is safe — unless it sent requests with ctx.fetch: those may have taken effect${listed}.`;
234
239
  }
235
240
  if (err.code === 'ACTION_TIMEOUT') {
236
241
  return `The outcome of ${invocation ?? 'the call'} is unknown: writes it started may have committed. See what it committed with \`parall app db log --app ${ctx.appId}${invocation ? ` --invocation ${invocation}` : ''}\` before running it again.`;
@@ -7,7 +7,7 @@ import { applyBlock, blockNames, conflictMessage, findBlock, listBlocks, planBlo
7
7
  export function registerAppAddCommand(app) {
8
8
  app
9
9
  .command('add')
10
- .description('Add ready-made blocks (calendar, kanban, …) to an `app init --actions` project: pages, actions, SQL and manifest declarations')
10
+ .description('Add ready-made blocks (calendar, kanban, …) to an `app init --actions` project: pages, actions, SQL and manifest declarations, written for PostgreSQL (a project scaffolded for a Database on TiDB is refused)')
11
11
  .argument('[blocks...]', 'Blocks to add (see --list)')
12
12
  .option('--dir <dir>', 'The app project (default: the current directory)', '.')
13
13
  .option('--list', 'List the available blocks')
@@ -1 +1 @@
1
- {"version":3,"file":"apps-blocks.d.ts","sourceRoot":"","sources":["../../src/commands/apps-blocks.ts"],"names":[],"mappings":"AAKA;;;;;;;;GAQG;AAEH,MAAM,WAAW,YAAY;IAC3B,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,eAAe;IAC9B;gCAC4B;IAC5B,IAAI,EAAE;QAAE,MAAM,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,CAAC;IACxC;4CACwC;IACxC,OAAO,EAAE;QAAE,MAAM,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,CAAC;IAC3C,0DAA0D;IAC1D,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACnC,iEAAiE;IACjE,GAAG,EAAE,MAAM,CAAC;CACb;AAED,MAAM,WAAW,YAAY;IAC3B,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;IACd,WAAW,EAAE,MAAM,CAAC;IACpB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,4CAA4C;IAC5C,YAAY,CAAC,EAAE,MAAM,EAAE,CAAC;IACxB,oBAAoB,CAAC,EAAE,MAAM,EAAE,CAAC;IAChC,KAAK,EAAE,YAAY,EAAE,CAAC;IACtB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,IAAI,EAAE;QAAE,MAAM,EAAE,eAAe,CAAA;KAAE,CAAC;CACnC;AAED,wBAAgB,SAAS,CAAC,IAAI,EAAE,MAAM,GAAG,YAAY,GAAG,SAAS,CAEhE;AAED,wBAAgB,UAAU,IAAI,MAAM,EAAE,CAErC;AAED,2CAA2C;AAC3C,wBAAgB,UAAU;;;;;;;IASzB;AAsBD,MAAM,WAAW,SAAS;IACxB,KAAK,EAAE,MAAM,CAAC;IACd,GAAG,EAAE,MAAM,CAAC;IACZ,KAAK,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,QAAQ,GAAG,WAAW,GAAG,WAAW,CAAA;KAAE,CAAC,CAAC;IAC7F,qEAAqE;IACrE,SAAS,EAAE,MAAM,EAAE,CAAC;IACpB,YAAY,EAAE;QAAE,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;QAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;KAAE,CAAC;IAC9E,OAAO,EAAE;QAAE,KAAK,EAAE,MAAM,EAAE,CAAC;QAAC,SAAS,EAAE,MAAM,EAAE,CAAC;QAAC,SAAS,EAAE,MAAM,EAAE,CAAA;KAAE,CAAC;IACvE,8EAA8E;IAC9E,KAAK,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAChD,iEAAiE;IACjE,MAAM,EAAE,MAAM,EAAE,CAAC;IACjB,GAAG,EAAE,MAAM,CAAC;CACb;AAWD,2EAA2E;AAC3E,wBAAsB,SAAS,CAC7B,GAAG,EAAE,MAAM,EACX,KAAK,EAAE,YAAY,EACnB,OAAO,GAAE;IAAE,KAAK,CAAC,EAAE,OAAO,CAAA;CAAO,GAChC,OAAO,CAAC,SAAS,CAAC,CAmGpB;AAkCD,iDAAiD;AACjD,wBAAsB,UAAU,CAAC,IAAI,EAAE,SAAS,GAAG,OAAO,CAAC,IAAI,CAAC,CAW/D;AAED,wBAAgB,eAAe,CAAC,IAAI,EAAE,SAAS,GAAG,MAAM,CAWvD"}
1
+ {"version":3,"file":"apps-blocks.d.ts","sourceRoot":"","sources":["../../src/commands/apps-blocks.ts"],"names":[],"mappings":"AAKA;;;;;;;;GAQG;AAEH,MAAM,WAAW,YAAY;IAC3B,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,eAAe;IAC9B;gCAC4B;IAC5B,IAAI,EAAE;QAAE,MAAM,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,CAAC;IACxC;4CACwC;IACxC,OAAO,EAAE;QAAE,MAAM,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,CAAC;IAC3C,0DAA0D;IAC1D,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACnC,iEAAiE;IACjE,GAAG,EAAE,MAAM,CAAC;CACb;AAED,MAAM,WAAW,YAAY;IAC3B,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;IACd,WAAW,EAAE,MAAM,CAAC;IACpB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,4CAA4C;IAC5C,YAAY,CAAC,EAAE,MAAM,EAAE,CAAC;IACxB,oBAAoB,CAAC,EAAE,MAAM,EAAE,CAAC;IAChC,KAAK,EAAE,YAAY,EAAE,CAAC;IACtB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,IAAI,EAAE;QAAE,MAAM,EAAE,eAAe,CAAA;KAAE,CAAC;CACnC;AAED,wBAAgB,SAAS,CAAC,IAAI,EAAE,MAAM,GAAG,YAAY,GAAG,SAAS,CAEhE;AAED,wBAAgB,UAAU,IAAI,MAAM,EAAE,CAErC;AAED,2CAA2C;AAC3C,wBAAgB,UAAU;;;;;;;IASzB;AAsBD,MAAM,WAAW,SAAS;IACxB,KAAK,EAAE,MAAM,CAAC;IACd,GAAG,EAAE,MAAM,CAAC;IACZ,KAAK,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,QAAQ,GAAG,WAAW,GAAG,WAAW,CAAA;KAAE,CAAC,CAAC;IAC7F,qEAAqE;IACrE,SAAS,EAAE,MAAM,EAAE,CAAC;IACpB,YAAY,EAAE;QAAE,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;QAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;KAAE,CAAC;IAC9E,OAAO,EAAE;QAAE,KAAK,EAAE,MAAM,EAAE,CAAC;QAAC,SAAS,EAAE,MAAM,EAAE,CAAC;QAAC,SAAS,EAAE,MAAM,EAAE,CAAA;KAAE,CAAC;IACvE,8EAA8E;IAC9E,KAAK,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAChD,iEAAiE;IACjE,MAAM,EAAE,MAAM,EAAE,CAAC;IACjB,GAAG,EAAE,MAAM,CAAC;CACb;AAWD,2EAA2E;AAC3E,wBAAsB,SAAS,CAC7B,GAAG,EAAE,MAAM,EACX,KAAK,EAAE,YAAY,EACnB,OAAO,GAAE;IAAE,KAAK,CAAC,EAAE,OAAO,CAAA;CAAO,GAChC,OAAO,CAAC,SAAS,CAAC,CA6GpB;AAkCD,iDAAiD;AACjD,wBAAsB,UAAU,CAAC,IAAI,EAAE,SAAS,GAAG,OAAO,CAAC,IAAI,CAAC,CAW/D;AAED,wBAAgB,eAAe,CAAC,IAAI,EAAE,SAAS,GAAG,MAAM,CAWvD"}
@@ -58,6 +58,14 @@ export async function planBlock(dir, block, options = {}) {
58
58
  if (missing.length > 0) {
59
59
  throw new Error(`${root} is not a Mini App project with actions (missing ${missing.join(', ')}). Blocks plug into the scaffold of \`parall app init <dir> --actions\`.`);
60
60
  }
61
+ // The blocks' SQL and actions are PostgreSQL. A project scaffolded for a
62
+ // Database on TiDB (`app init --app`, package.json parall.dialect) speaks
63
+ // MySQL: adding one would hand it SQL its Database refuses.
64
+ const dialect = JSON.parse((await readIfExists(join(root, 'package.json'))) ?? '{}')?.parall
65
+ ?.dialect;
66
+ if (dialect === 'mysql') {
67
+ throw new Error(`cannot add ${block.name}: blocks are written for PostgreSQL, and ${root} is scaffolded for a Database on TiDB, which speaks MySQL (package.json parall.dialect). Nothing was written; build the page after src/pages/items and actions/items.ts instead.`);
68
+ }
61
69
  const meta = block.meta.parall;
62
70
  const plan = {
63
71
  block: block.name,
@@ -0,0 +1,13 @@
1
+ import type { MiniAppPlacement } from '@parall/sdk';
2
+ import type { SqlDialect } from './apps-template.js';
3
+ /** Where a Database keeps its data decides the SQL it speaks
4
+ * (mini-app-tidb-placement-design.md §5.1, §6.7): `apps` is its
5
+ * organization's PostgreSQL database, `tidb` the TiDB cluster, which speaks
6
+ * MySQL. A server older than placements sends none: that is `apps`. */
7
+ export declare function dialectOf(placement: MiniAppPlacement | undefined): SqlDialect;
8
+ /** The line `app create`, `db create` and `db get` print on stderr next to
9
+ * their JSON: the Database's placement and the SQL it speaks — for a
10
+ * Database on TiDB with how MySQL differs and, when the Database came with
11
+ * an app, how to scaffold for it. */
12
+ export declare function placementHint(databaseId: string, placement: MiniAppPlacement | undefined, appId?: string): string;
13
+ //# sourceMappingURL=apps-placement.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"apps-placement.d.ts","sourceRoot":"","sources":["../../src/commands/apps-placement.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AACpD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAErD;;;uEAGuE;AACvE,wBAAgB,SAAS,CAAC,SAAS,EAAE,gBAAgB,GAAG,SAAS,GAAG,UAAU,CAE7E;AAED;;;qCAGqC;AACrC,wBAAgB,aAAa,CAC3B,UAAU,EAAE,MAAM,EAClB,SAAS,EAAE,gBAAgB,GAAG,SAAS,EACvC,KAAK,CAAC,EAAE,MAAM,GACb,MAAM,CAQR"}
@@ -0,0 +1,20 @@
1
+ /** Where a Database keeps its data decides the SQL it speaks
2
+ * (mini-app-tidb-placement-design.md §5.1, §6.7): `apps` is its
3
+ * organization's PostgreSQL database, `tidb` the TiDB cluster, which speaks
4
+ * MySQL. A server older than placements sends none: that is `apps`. */
5
+ export function dialectOf(placement) {
6
+ return placement === 'tidb' ? 'mysql' : 'postgres';
7
+ }
8
+ /** The line `app create`, `db create` and `db get` print on stderr next to
9
+ * their JSON: the Database's placement and the SQL it speaks — for a
10
+ * Database on TiDB with how MySQL differs and, when the Database came with
11
+ * an app, how to scaffold for it. */
12
+ export function placementHint(databaseId, placement, appId) {
13
+ if (dialectOf(placement) === 'postgres') {
14
+ return `Database ${databaseId}: placement apps — PostgreSQL`;
15
+ }
16
+ const scaffold = appId
17
+ ? ` Scaffold for it with parall app init <dir> --actions --app ${appId}.`
18
+ : '';
19
+ return `Database ${databaseId}: placement tidb — TiDB, MySQL: ? parameters (one value each), no RETURNING, one schema change per exec and no dry run for it.${scaffold}`;
20
+ }
@@ -2,7 +2,13 @@ import type { Command } from 'commander';
2
2
  /** `parall app init`: the scaffold of design §7.4 — Vite + React + TS +
3
3
  * Tailwind + shadcn/ui with the host bridge wired (apps-template.ts);
4
4
  * `--actions` adds the server-side actions, the schema and an example list
5
- * that reads and writes through them. Blocks go on top with `parall app add`
5
+ * that reads and writes through them. `--app` names the app the project is
6
+ * for: the scaffold's SQL is written in the dialect of that app's Database
7
+ * (MySQL on TiDB, PostgreSQL otherwise; mini-app-tidb-placement-design.md
8
+ * §6.7) and the next steps name the app. Without it the SQL is PostgreSQL,
9
+ * as before. `--template` starts from an app template instead of the
10
+ * example (apps-template-init.ts), listed by `parall app templates`
11
+ * (apps-template-catalog.ts). Blocks go on top with `parall app add`
6
12
  * (apps-add.ts). */
7
13
  export declare function registerAppScaffoldCommands(app: Command): void;
8
14
  //# sourceMappingURL=apps-scaffold.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"apps-scaffold.d.ts","sourceRoot":"","sources":["../../src/commands/apps-scaffold.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAIzC;;;;oBAIoB;AACpB,wBAAgB,2BAA2B,CAAC,GAAG,EAAE,OAAO,QAuDvD"}
1
+ {"version":3,"file":"apps-scaffold.d.ts","sourceRoot":"","sources":["../../src/commands/apps-scaffold.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAoBzC;;;;;;;;;;oBAUoB;AACpB,wBAAgB,2BAA2B,CAAC,GAAG,EAAE,OAAO,QA0DvD"}