@parall/cli 1.80.0 → 1.81.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"apps-local-runner.generated.d.ts","sourceRoot":"","sources":["../../src/commands/apps-local-runner.generated.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,+BAA+B,eAAe,CAAC;AAC5D,eAAO,MAAM,0BAA0B,4CAA4C,CAAC;AAEpF,eAAO,MAAM,mBAAmB,+z6CAAqz6C,CAAC"}
1
+ {"version":3,"file":"apps-local-runner.generated.d.ts","sourceRoot":"","sources":["../../src/commands/apps-local-runner.generated.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,+BAA+B,eAAe,CAAC;AAC5D,eAAO,MAAM,0BAA0B,4CAA4C,CAAC;AAEpF,eAAO,MAAM,mBAAmB,s+jDAA49jD,CAAC"}
@@ -2,4 +2,4 @@
2
2
  export const LOCAL_RUNNER_COMPATIBILITY_DATE = '2026-04-01';
3
3
  export const LOCAL_RUNNER_BLOCKED_HOSTS = 'parall.com,ponderai.workers.dev,prll.sh';
4
4
  // biome-ignore format: generated copy
5
- export const LOCAL_RUNNER_SOURCE = "// ../actions-worker/src/contract.ts\nvar DEFAULT_NET_IN_FLIGHT = 4;\nvar INSTANCE = /^(default|pr-\\d{1,6})$/;\nvar APP_ID = /^app_[0-9a-z]{21}$/;\nvar SHA256 = /^[0-9a-f]{64}$/;\nvar ACTION_NAME = /^[a-zA-Z][a-zA-Z0-9_]{0,63}$/;\nvar INVOCATION_ID = /^[0-9A-Za-z_-]{1,64}$/;\nvar LIMIT_CEILINGS = {\n cpu_ms: 3e4,\n db_calls: 1e3,\n batch_statements: 1e3,\n batch_bytes: 8 * 1024 * 1024,\n result_bytes: 8 * 1024 * 1024,\n message_bytes: 64 * 1024,\n stack_bytes: 256 * 1024\n};\nvar CLIP_CALLS_CEILING = 100;\nvar NET_REQUESTS_CEILING = 100;\nvar NET_IN_FLIGHT_CEILING = 6;\nvar ENV_NAME = /^[A-Z_][A-Z0-9_]{0,127}$/;\nvar ENV_CEILING_BYTES = 256 * 1024;\nfunction isRecord(v) {\n return typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\nfunction positiveInt(v, max) {\n return typeof v === \"number\" && Number.isInteger(v) && v > 0 && v <= max;\n}\nfunction intInRange(v, min, max) {\n return typeof v === \"number\" && Number.isInteger(v) && v >= min && v <= max;\n}\nvar envEncoder = new TextEncoder();\nfunction validEnv(v) {\n if (!isRecord(v)) return false;\n let total = 0;\n for (const [name, value] of Object.entries(v)) {\n if (!ENV_NAME.test(name) || typeof value !== \"string\") return false;\n total += envEncoder.encode(name).byteLength + envEncoder.encode(value).byteLength;\n if (total > ENV_CEILING_BYTES) return false;\n }\n return true;\n}\nfunction parseInvokeRequest(raw, opts = {}) {\n if (!isRecord(raw)) return \"body is not an object\";\n const {\n invocation_id,\n instance,\n app,\n module,\n action,\n kind,\n clip,\n viewer,\n ticket,\n deadline_ms,\n limits\n } = raw;\n if (typeof invocation_id !== \"string\" || !INVOCATION_ID.test(invocation_id))\n return \"invocation_id\";\n if (typeof instance !== \"string\" || !INSTANCE.test(instance)) return \"instance\";\n if (!isRecord(app) || typeof app.id !== \"string\" || !APP_ID.test(app.id)) return \"app.id\";\n if (!(opts.unpublished && app.version_seq === 0) && !positiveInt(app.version_seq, 2 ** 31))\n return \"app.version_seq\";\n if (!isRecord(module) || typeof module.sha256 !== \"string\" || !SHA256.test(module.sha256))\n return \"module.sha256\";\n if (typeof action !== \"string\" || !ACTION_NAME.test(action)) return \"action\";\n if (kind !== \"read\" && kind !== \"write\") return \"kind\";\n if (clip !== void 0 && clip !== false && !(clip === true && kind === \"write\")) return \"clip\";\n if (!(\"params\" in raw)) return \"params\";\n if (!isRecord(viewer) || typeof viewer.id !== \"string\" || typeof viewer.display_name !== \"string\" || typeof viewer.is_agent !== \"boolean\" || typeof viewer.role !== \"string\") {\n return \"viewer\";\n }\n if (typeof ticket !== \"string\" || ticket.length === 0 || ticket.length > 4096) return \"ticket\";\n if (typeof deadline_ms !== \"number\" || !Number.isFinite(deadline_ms)) return \"deadline_ms\";\n if (!isRecord(limits)) return \"limits\";\n for (const key of Object.keys(LIMIT_CEILINGS)) {\n if (!positiveInt(limits[key], LIMIT_CEILINGS[key])) return `limits.${key}`;\n }\n const clipCalls = limits.clip_calls ?? 0;\n if (clipCalls !== 0 && !positiveInt(clipCalls, CLIP_CALLS_CEILING)) return \"limits.clip_calls\";\n const netRequests = limits.net_requests ?? 0;\n if (!intInRange(netRequests, 0, NET_REQUESTS_CEILING)) return \"limits.net_requests\";\n const netInFlight = limits.net_in_flight ?? DEFAULT_NET_IN_FLIGHT;\n if (!intInRange(netInFlight, 0, NET_IN_FLIGHT_CEILING) || netRequests > 0 && netInFlight === 0) {\n return \"limits.net_in_flight\";\n }\n if (raw.env !== void 0 && raw.env !== null && !validEnv(raw.env)) return \"env\";\n return {\n invocation_id,\n instance,\n app: { id: app.id, version_seq: app.version_seq },\n module: { sha256: module.sha256 },\n action,\n kind,\n clip: clip === true,\n params: raw.params,\n viewer: {\n id: viewer.id,\n display_name: viewer.display_name,\n is_agent: viewer.is_agent,\n role: viewer.role\n },\n ticket,\n deadline_ms,\n limits: { ...limits, clip_calls: clipCalls },\n ...raw.env === null ? { env: null } : {},\n ...isRecord(raw.env) ? { env: { ...raw.env } } : {}\n };\n}\nfunction netLimits(limits) {\n return {\n requests: limits.net_requests ?? 0,\n inFlight: limits.net_in_flight ?? DEFAULT_NET_IN_FLIGHT\n };\n}\n\n// ../actions-worker/src/net-address.ts\nvar BAD_PORTS = /* @__PURE__ */ new Set([\n 0,\n 1,\n 7,\n 9,\n 11,\n 13,\n 15,\n 17,\n 19,\n 20,\n 21,\n 22,\n 23,\n 25,\n 37,\n 42,\n 43,\n 53,\n 69,\n 77,\n 79,\n 87,\n 95,\n 101,\n 102,\n 103,\n 104,\n 109,\n 110,\n 111,\n 113,\n 115,\n 117,\n 119,\n 123,\n 135,\n 137,\n 139,\n 143,\n 161,\n 179,\n 389,\n 427,\n 465,\n 512,\n 513,\n 514,\n 515,\n 526,\n 530,\n 531,\n 532,\n 540,\n 548,\n 554,\n 556,\n 563,\n 587,\n 601,\n 636,\n 989,\n 990,\n 993,\n 995,\n 1719,\n 1720,\n 1723,\n 2049,\n 3659,\n 4045,\n 4190,\n 5060,\n 5061,\n 6e3,\n 6566,\n 6665,\n 6666,\n 6667,\n 6668,\n 6669,\n 6679,\n 6697,\n 10080\n]);\nvar NUMERIC_LABEL = /^(?:0x[0-9a-f]*|\\d+)$/i;\nvar HOST_NAME = /^[a-z0-9_-]+(?:\\.[a-z0-9_-]+)*$/;\nvar HOST_NAME_MAX_BYTES = 253;\nvar HOST_LABEL_MAX_BYTES = 63;\nfunction normalizeHost(host) {\n return host.toLowerCase().replace(/\\.+$/, \"\");\n}\nfunction isIpLiteral(host) {\n if (host.startsWith(\"[\") || host.includes(\":\")) return true;\n const labels = host.split(\".\");\n return NUMERIC_LABEL.test(labels[labels.length - 1] ?? \"\");\n}\nfunction isLoopbackName(host) {\n return host === \"localhost\" || host.endsWith(\".localhost\");\n}\nfunction isHostName(host) {\n return host.length <= HOST_NAME_MAX_BYTES && HOST_NAME.test(host) && host.split(\".\").every((label) => label.length <= HOST_LABEL_MAX_BYTES);\n}\nfunction isBlockedHost(host, blocked) {\n return blocked.some((name) => host === name || host.endsWith(`.${name}`));\n}\nfunction checkAddress(input, policy) {\n if (input.protocol !== \"https:\" && input.protocol !== \"http:\") {\n return { ok: false, reason: \"only https: and http: URLs can be requested\" };\n }\n if (input.username !== \"\" || input.password !== \"\") {\n return { ok: false, reason: \"a URL with credentials in it (user:pass@) cannot be requested\" };\n }\n const host = normalizeHost(input.hostname);\n if (host === \"\") return { ok: false, reason: \"the URL has no host\" };\n if (isIpLiteral(host)) {\n return { ok: false, reason: \"requests go to host names, not IP addresses\" };\n }\n if (!isHostName(host)) {\n return {\n ok: false,\n reason: `the URL host is not a host name (at most ${HOST_NAME_MAX_BYTES} bytes, ${HOST_LABEL_MAX_BYTES} per label)`\n };\n }\n if (input.port !== \"\" && BAD_PORTS.has(Number(input.port))) {\n return { ok: false, reason: `port ${input.port} cannot be requested` };\n }\n if (isLoopbackName(host) && !policy.allowLoopback) {\n return { ok: false, reason: \"loopback hosts cannot be requested\" };\n }\n if (isBlockedHost(host, policy.blockedHosts)) {\n return { ok: false, reason: \"the platform's own hosts cannot be requested\" };\n }\n const url = new URL(input.href);\n url.hostname = host;\n url.hash = \"\";\n return { ok: true, url, host: input.port === \"\" ? host : `${host}:${input.port}` };\n}\nfunction parseBlockedHosts(raw) {\n if (typeof raw !== \"string\") return null;\n const names = raw.split(\",\").map((s) => normalizeHost(s.trim())).filter((s) => s !== \"\");\n if (names.length === 0) return null;\n for (const name of names) {\n if (!isHostName(name) || isIpLiteral(name)) return null;\n }\n return names;\n}\nvar LOOPBACK_ORIGIN_HOSTS = /* @__PURE__ */ new Set([\"127.0.0.1\", \"localhost\", \"[::1]\"]);\nfunction loopbackAllowed(flag, callbackOrigin) {\n if (flag !== \"1\" && flag !== \"true\") return false;\n try {\n return LOOPBACK_ORIGIN_HOSTS.has(new URL(callbackOrigin).hostname);\n } catch {\n return false;\n }\n}\nfunction policyFrom(blockedHosts, loopbackFlag, callbackOrigin) {\n const blocked = parseBlockedHosts(blockedHosts);\n if (!blocked) return null;\n return { blockedHosts: blocked, allowLoopback: loopbackAllowed(loopbackFlag, callbackOrigin) };\n}\n\n// ../actions-worker/src/db-caller.ts\nvar USER_AGENT = \"parall-actions-worker/1\";\nvar TICKET_HEADER = \"X-Prll-Action-Ticket\";\nvar INVOCATION_HEADER = \"X-Prll-Action-Invocation\";\nvar SWIMLANE_HEADER = \"X-Prll-Swimlane\";\nvar MAX_SQL_BYTES = 256 * 1024;\nvar encoder = new TextEncoder();\nfunction handleError(code, message) {\n const err = new Error(message);\n err.name = \"ActionDbError\";\n err.code = code;\n return err;\n}\nfunction statementOf(v) {\n if (typeof v !== \"object\" || v === null) return null;\n const { sql, params } = v;\n if (typeof sql !== \"string\" || sql.length === 0 || encoder.encode(sql).byteLength > MAX_SQL_BYTES)\n return null;\n if (params !== void 0 && !Array.isArray(params)) return null;\n return { sql, params: params ?? [] };\n}\nfunction requestBody(op, payload, limits) {\n if (op === \"batch\") {\n const statements = payload?.statements;\n if (!Array.isArray(statements) || statements.length === 0) {\n throw handleError(\"ACTION_INVALID_CALL\", \"batch needs a non-empty array of { sql, params }\");\n }\n if (statements.length > limits.batch_statements) {\n throw handleError(\n \"ACTION_LIMIT_EXCEEDED\",\n `a batch may hold at most ${limits.batch_statements} statements`\n );\n }\n const parsed = statements.map(statementOf);\n if (parsed.some((s) => s === null)) {\n throw handleError(\n \"ACTION_INVALID_CALL\",\n \"every batch entry needs a non-empty sql string and a params array\"\n );\n }\n const body = JSON.stringify({ statements: parsed });\n if (encoder.encode(body).byteLength > limits.batch_bytes) {\n throw handleError(\n \"ACTION_LIMIT_EXCEEDED\",\n `a batch may be at most ${limits.batch_bytes} bytes`\n );\n }\n return body;\n }\n const statement = statementOf(payload);\n if (!statement)\n throw handleError(\n \"ACTION_INVALID_CALL\",\n `${op} needs a non-empty sql string and a params array`\n );\n return JSON.stringify(statement);\n}\nfunction trackDataSeq(state, result) {\n const seq = result?.data_seq;\n if (typeof seq !== \"number\" || !Number.isInteger(seq)) return;\n state.dataSeq = state.dataSeq ? { from: Math.min(state.dataSeq.from, seq), to: Math.max(state.dataSeq.to, seq) } : { from: seq, to: seq };\n}\nasync function readCapped(res, maxBytes) {\n if (!res.body) return \"\";\n const reader = res.body.getReader();\n const chunks = [];\n let total = 0;\n for (; ; ) {\n const { done, value } = await reader.read();\n if (done) break;\n total += value.byteLength;\n if (total > maxBytes) {\n await reader.cancel();\n throw handleError(\n \"ACTION_RESULT_TOO_LARGE\",\n `a database result may be at most ${maxBytes} bytes`\n );\n }\n chunks.push(value);\n }\n const out = new Uint8Array(total);\n let off = 0;\n for (const c of chunks) {\n out.set(c, off);\n off += c.byteLength;\n }\n return new TextDecoder().decode(out);\n}\nfunction createDbCaller(cfg) {\n const fetchImpl = cfg.fetchImpl ?? fetch;\n const now = cfg.now ?? Date.now;\n const state = {\n revoked: false,\n calls: 0,\n limitHit: false,\n inflight: /* @__PURE__ */ new Set(),\n dataSeq: null,\n indeterminate: false,\n clipCalls: 0,\n clipLimitHit: false,\n netRequests: 0,\n netLimitHit: false,\n netInFlight: 0,\n netCalls: []\n };\n const origin = cfg.callbackOrigin.replace(/\\/+$/, \"\");\n async function send(op, body) {\n const headers = {\n \"Content-Type\": \"application/json\",\n \"User-Agent\": USER_AGENT,\n [TICKET_HEADER]: cfg.ticket,\n [INVOCATION_HEADER]: cfg.invocationId\n };\n if (cfg.instance !== \"default\") headers[SWIMLANE_HEADER] = cfg.instance;\n const remaining = Math.max(1, cfg.deadlineMs - now());\n let res;\n try {\n res = await fetchImpl(`${origin}/api/v1/mini-app-actions/db/${op}`, {\n method: \"POST\",\n headers,\n body,\n signal: AbortSignal.timeout(remaining)\n });\n } catch {\n if (op !== \"query\") state.indeterminate = true;\n throw handleError(\"ACTION_DB_UNAVAILABLE\", \"the database could not be reached\");\n }\n let parsed;\n try {\n const text = await readCapped(res, cfg.limits.result_bytes + 64 * 1024);\n parsed = text ? JSON.parse(text) : null;\n } catch (err) {\n if (op !== \"query\") state.indeterminate = true;\n if (err.code === \"ACTION_RESULT_TOO_LARGE\") throw err;\n throw handleError(\"ACTION_DB_UNAVAILABLE\", \"the database returned an unreadable response\");\n }\n if (!res.ok) {\n const env = parsed?.error;\n if (typeof env?.code !== \"string\") {\n if (op !== \"query\") state.indeterminate = true;\n throw handleError(`HTTP_${res.status}`, `database call failed (${res.status})`);\n }\n const message = typeof env.message === \"string\" ? env.message : `database call failed (${res.status})`;\n throw handleError(env.code, message);\n }\n trackDataSeq(state, parsed);\n return parsed;\n }\n async function call(op, payload) {\n if (state.revoked)\n throw handleError(\"ACTION_HANDLE_REVOKED\", \"this database handle is no longer valid\");\n if (now() >= cfg.deadlineMs)\n throw handleError(\"ACTION_DEADLINE\", \"the action ran past its deadline\");\n if (cfg.kind === \"read\" && op !== \"query\") {\n throw handleError(\"ACTION_READ_ONLY\", \"a read action can only query\");\n }\n state.calls++;\n if (state.calls > cfg.limits.db_calls) {\n state.limitHit = true;\n throw handleError(\n \"ACTION_LIMIT_EXCEEDED\",\n `an action may make at most ${cfg.limits.db_calls} database calls`\n );\n }\n const body = requestBody(op, payload, cfg.limits);\n const pending = send(op, body);\n state.inflight.add(pending);\n try {\n return await pending;\n } finally {\n state.inflight.delete(pending);\n }\n }\n return { state, call };\n}\nfunction settleCall(caller, op, payload) {\n return settleWith(\n () => caller.call(op, payload),\n \"ACTION_DB_UNAVAILABLE\",\n \"the database call failed\"\n );\n}\nasync function settleWith(run, fallbackCode, fallbackMessage) {\n try {\n return { ok: true, value: await run() };\n } catch (err) {\n const { code, message } = err ?? {};\n return {\n ok: false,\n error: {\n code: typeof code === \"string\" ? code : fallbackCode,\n message: typeof message === \"string\" ? message : fallbackMessage\n }\n };\n }\n}\nasync function settle(caller, deadlineMs, now = Date.now) {\n caller.state.revoked = true;\n const inflight = [...caller.state.inflight];\n if (inflight.length === 0) return true;\n const remaining = deadlineMs - now();\n if (remaining > 0) {\n let timer = null;\n await Promise.race([\n Promise.allSettled(inflight),\n new Promise((r) => {\n timer = setTimeout(r, remaining);\n })\n ]);\n if (timer !== null) clearTimeout(timer);\n }\n return caller.state.inflight.size === 0;\n}\n\n// ../actions-worker/src/clip-caller.ts\nvar ENVELOPE_BYTES = 64 * 1024;\nvar MAX_FIELD_BYTES = 256;\nvar encoder2 = new TextEncoder();\nfunction unknownOutcome() {\n return handleError(\n \"OUTCOME_UNKNOWN\",\n \"the Clip call\\u2019s answer was lost \\u2014 it may or may not have run; do not retry it blindly\"\n );\n}\nfunction field(v, required) {\n if (v === void 0 || v === null) return required ? null : void 0;\n if (typeof v !== \"string\" || encoder2.encode(v).byteLength > MAX_FIELD_BYTES) return null;\n if (required && v.trim() === \"\") return null;\n return v;\n}\nfunction requestBody2(req, seq, maxBytes) {\n const r = typeof req === \"object\" && req !== null ? req : {};\n const clip = field(r.clip, true);\n const command = field(r.command, true);\n const connection = field(r.connection, false);\n const profile = field(r.profile, false);\n const timeout = r.timeout_ms;\n if (clip === null || command === null || connection === null || profile === null) {\n throw handleError(\n \"ACTION_INVALID_CALL\",\n \"clip.exec needs a Clip name or id, a command, and string connection and profile options of at most 256 bytes\"\n );\n }\n if (timeout !== void 0 && (typeof timeout !== \"number\" || !Number.isInteger(timeout) || timeout <= 0 || timeout > 12e4)) {\n throw handleError(\n \"ACTION_INVALID_CALL\",\n \"timeoutMs must be a whole number of milliseconds from 1 to 120000\"\n );\n }\n let body;\n try {\n body = JSON.stringify({\n seq,\n clip,\n command,\n args: r.args,\n connection: connection ?? \"\",\n profile,\n timeout_ms: timeout\n });\n } catch {\n throw handleError(\"ACTION_INVALID_CALL\", \"the Clip arguments cannot be sent as JSON\");\n }\n if (encoder2.encode(body).byteLength > maxBytes) {\n throw handleError(\n \"ACTION_LIMIT_EXCEEDED\",\n `a Clip call's arguments may be at most ${maxBytes} bytes`\n );\n }\n return body;\n}\nfunction createClipCaller(cfg, state) {\n const fetchImpl = cfg.fetchImpl ?? fetch;\n const now = cfg.now ?? Date.now;\n const url = `${cfg.callbackOrigin.replace(/\\/+$/, \"\")}/api/v1/mini-app-actions/clip/exec`;\n async function send(body) {\n const headers = {\n \"Content-Type\": \"application/json\",\n \"User-Agent\": USER_AGENT,\n [TICKET_HEADER]: cfg.ticket,\n [INVOCATION_HEADER]: cfg.invocationId\n };\n if (cfg.instance !== \"default\") headers[SWIMLANE_HEADER] = cfg.instance;\n let res;\n try {\n res = await fetchImpl(url, {\n method: \"POST\",\n headers,\n body,\n signal: AbortSignal.timeout(Math.max(1, cfg.deadlineMs - now()))\n });\n } catch {\n throw unknownOutcome();\n }\n let parsed;\n try {\n const text = await readCapped(res, cfg.maxBytes + ENVELOPE_BYTES);\n parsed = text ? JSON.parse(text) : null;\n } catch {\n throw unknownOutcome();\n }\n if (res.ok) {\n const a = parsed;\n if (a?.ok === true) return a.value ?? null;\n if (a?.ok === false && typeof a.error?.code === \"string\") {\n throw handleError(\n a.error.code,\n typeof a.error.message === \"string\" ? a.error.message : a.error.code\n );\n }\n throw unknownOutcome();\n }\n const env = parsed?.error;\n if (typeof env?.code !== \"string\") throw unknownOutcome();\n throw handleError(\n env.code,\n typeof env.message === \"string\" ? env.message : `Clip call refused (${res.status})`\n );\n }\n async function call(req) {\n if (state.revoked) throw handleError(\"ACTION_HANDLE_REVOKED\", \"this handle is no longer valid\");\n if (!cfg.enabled) {\n throw handleError(\n \"CLIP_NOT_DECLARED\",\n \"this action does not declare clip, so it cannot call Clip\"\n );\n }\n if (now() >= cfg.deadlineMs)\n throw handleError(\"ACTION_DEADLINE\", \"the action ran past its deadline\");\n if (state.clipCalls >= cfg.maxCalls) {\n state.clipLimitHit = true;\n throw handleError(\n \"ACTION_LIMIT_EXCEEDED\",\n `an action may make at most ${cfg.maxCalls} Clip calls`\n );\n }\n const body = requestBody2(req, state.clipCalls + 1, cfg.maxBytes);\n state.clipCalls++;\n const pending = send(body);\n state.inflight.add(pending);\n try {\n return await pending;\n } finally {\n state.inflight.delete(pending);\n }\n }\n return { call };\n}\n\n// ../actions-worker/src/handle.ts\nimport { RpcTarget } from \"cloudflare:workers\";\nvar ActionHandle = class extends RpcTarget {\n #caller;\n #clip;\n #net;\n constructor(caller, clip, net) {\n super();\n this.#caller = caller;\n this.#clip = clip;\n this.#net = net;\n }\n query(sql, params) {\n return settleCall(this.#caller, \"query\", { sql, params });\n }\n exec(sql, params) {\n return settleCall(this.#caller, \"exec\", { sql, params });\n }\n batch(statements) {\n return settleCall(this.#caller, \"batch\", { statements });\n }\n clip(req) {\n return settleWith(() => this.#clip.call(req), \"CLIP_UNAVAILABLE\", \"the Clip call failed\");\n }\n request(req) {\n return settleWith(() => this.#net.request(req), \"NET_FAILED\", \"the request failed\");\n }\n};\nfunction makeHandle(caller, clip, net) {\n return new ActionHandle(caller, clip, net);\n}\n\n// ../actions-worker/src/net-begin.ts\nvar BEGIN_TIMEOUT_MS = 1e4;\nvar BEGIN_ANSWER_MAX_BYTES = 64 * 1024;\nvar ERROR_CODE = /^[A-Z][A-Z0-9_]{0,63}$/;\nfunction notRegistered() {\n return handleError(\n \"NET_UNAVAILABLE\",\n \"the request could not be registered with the platform, so it was not sent\"\n );\n}\nasync function begin(target, seq, fields, timeoutMs) {\n const headers = {\n \"Content-Type\": \"application/json\",\n \"User-Agent\": USER_AGENT,\n [TICKET_HEADER]: target.ticket,\n [INVOCATION_HEADER]: target.invocationId\n };\n if (target.instance !== \"default\") headers[SWIMLANE_HEADER] = target.instance;\n const url = `${target.callbackOrigin.replace(/\\/+$/, \"\")}/api/v1/mini-app-actions/net/begin`;\n const fetchImpl = target.fetchImpl;\n let res;\n try {\n res = await fetchImpl(url, {\n method: \"POST\",\n headers,\n body: JSON.stringify({ seq, method: fields.method, host: fields.host, path: fields.path }),\n signal: AbortSignal.timeout(timeoutMs)\n });\n } catch {\n throw notRegistered();\n }\n let parsed;\n try {\n const text = await readCapped(res, BEGIN_ANSWER_MAX_BYTES);\n parsed = text ? JSON.parse(text) : null;\n } catch {\n throw notRegistered();\n }\n const answer = parsed;\n if (res.status === 200 && answer?.ok === true) return;\n const error = res.ok ? answer?.ok === false ? answer.error : void 0 : answer?.error;\n if (typeof error?.code === \"string\" && ERROR_CODE.test(error.code)) {\n throw handleError(\n error.code,\n typeof error.message === \"string\" ? error.message : \"the platform refused the request\"\n );\n }\n throw notRegistered();\n}\n\n// ../actions-worker/src/net-request.ts\nvar NET_URL_MAX_BYTES = 8 * 1024;\nvar NET_HEADERS_MAX = 64;\nvar NET_HEADER_BYTES_MAX = 32 * 1024;\nvar NET_BODY_MAX_BYTES = 1024 * 1024;\nvar NET_TIMEOUT_MAX_MS = 12e4;\nvar FORBIDDEN_HEADERS = /* @__PURE__ */ new Set([\n \"host\",\n \"connection\",\n \"upgrade\",\n \"keep-alive\",\n \"te\",\n \"trailer\",\n \"transfer-encoding\"\n]);\nvar FORBIDDEN_HEADER_PREFIXES = [\"proxy-\", \"x-prll-\", \"cf-\"];\nvar DROPPED_HEADERS = /* @__PURE__ */ new Set([\"content-length\"]);\nvar METHOD = /^[!#$%&'*+.^_`|~0-9A-Za-z-]{1,16}$/;\nvar FORBIDDEN_METHODS = /* @__PURE__ */ new Set([\"CONNECT\", \"TRACE\", \"TRACK\"]);\nvar NORMALIZED_METHODS = /* @__PURE__ */ new Set([\"DELETE\", \"GET\", \"HEAD\", \"OPTIONS\", \"PATCH\", \"POST\", \"PUT\"]);\nvar HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;\nvar encoder3 = new TextEncoder();\nfunction isObject(v) {\n return typeof v === \"object\" && v !== null;\n}\nfunction normalizeMethod(method) {\n const upper = method.toUpperCase();\n return NORMALIZED_METHODS.has(upper) ? upper : method;\n}\nvar RECORD_HOST_MAX_BYTES = 300;\nfunction printableAscii(s) {\n return /^[\\x21-\\x7e]+$/.test(s);\n}\nfunction recordableHost(host) {\n return host.length <= RECORD_HOST_MAX_BYTES && printableAscii(host) && !/[/?#@\\\\]/.test(host);\n}\nfunction recordablePath(path) {\n return path.startsWith(\"/\") && path.length <= NET_URL_MAX_BYTES && printableAscii(path);\n}\nfunction describeRequest(raw) {\n const r = isObject(raw) ? raw : {};\n const fields = { method: \"\", host: \"\", path: \"\" };\n const method = r.method === void 0 ? \"GET\" : r.method;\n if (typeof method === \"string\" && METHOD.test(method)) fields.method = normalizeMethod(method);\n if (typeof r.url === \"string\" && r.url.length <= 4 * NET_URL_MAX_BYTES) {\n try {\n const url = new URL(r.url);\n const host = normalizeHost(url.hostname) + (url.port === \"\" ? \"\" : `:${url.port}`);\n if (recordableHost(host)) fields.host = host;\n if (recordablePath(url.pathname)) fields.path = url.pathname;\n } catch {\n }\n }\n return fields;\n}\nfunction readUrl(raw, policy) {\n if (typeof raw !== \"string\" || raw === \"\") {\n throw handleError(\"ACTION_INVALID_CALL\", \"a request needs an absolute http(s) URL\");\n }\n if (raw.length > 4 * NET_URL_MAX_BYTES) {\n throw handleError(\"ACTION_LIMIT_EXCEEDED\", `a URL may be at most ${NET_URL_MAX_BYTES} bytes`);\n }\n let parsed;\n try {\n parsed = new URL(raw);\n } catch {\n throw handleError(\"ACTION_INVALID_CALL\", \"a request needs an absolute http(s) URL\");\n }\n const verdict = checkAddress(parsed, policy);\n if (!verdict.ok) throw handleError(\"NET_ADDRESS_BLOCKED\", verdict.reason);\n if (encoder3.encode(verdict.url.href).byteLength > NET_URL_MAX_BYTES) {\n throw handleError(\"ACTION_LIMIT_EXCEEDED\", `a URL may be at most ${NET_URL_MAX_BYTES} bytes`);\n }\n return { url: verdict.url, host: verdict.host };\n}\nfunction readMethod(raw) {\n if (raw === void 0) return \"GET\";\n if (typeof raw !== \"string\" || !METHOD.test(raw)) {\n throw handleError(\"ACTION_INVALID_CALL\", \"the method must be an HTTP method name\");\n }\n const method = normalizeMethod(raw);\n if (FORBIDDEN_METHODS.has(method.toUpperCase())) {\n throw handleError(\"ACTION_INVALID_CALL\", `${method} requests cannot be made`);\n }\n return method;\n}\nfunction headerPairs(raw) {\n if (raw === void 0 || raw === null) return [];\n if (Array.isArray(raw)) {\n return raw.map(\n (pair) => Array.isArray(pair) && pair.length === 2 ? [pair[0], pair[1]] : [null, null]\n );\n }\n if (isObject(raw)) return Object.entries(raw);\n throw handleError(\"ACTION_INVALID_CALL\", \"headers must be [name, value] pairs or an object\");\n}\nfunction readHeaders(raw) {\n const pairs = headerPairs(raw);\n if (pairs.length > NET_HEADERS_MAX) {\n throw handleError(\n \"ACTION_LIMIT_EXCEEDED\",\n `a request may have at most ${NET_HEADERS_MAX} headers`\n );\n }\n let bytes = 0;\n const out = [];\n for (const [name, value] of pairs) {\n if (typeof name !== \"string\" || typeof value !== \"string\" || !HEADER_NAME.test(name)) {\n throw handleError(\"ACTION_INVALID_CALL\", \"each header needs a valid name and a string value\");\n }\n bytes += encoder3.encode(name).byteLength + encoder3.encode(value).byteLength;\n const lower = name.toLowerCase();\n if (FORBIDDEN_HEADERS.has(lower) || FORBIDDEN_HEADER_PREFIXES.some((prefix) => lower.startsWith(prefix))) {\n throw handleError(\"ACTION_INVALID_CALL\", `the ${name} header cannot be set`);\n }\n if (!DROPPED_HEADERS.has(lower)) out.push([name, value]);\n }\n if (bytes > NET_HEADER_BYTES_MAX) {\n throw handleError(\n \"ACTION_LIMIT_EXCEEDED\",\n `a request's headers may be at most ${NET_HEADER_BYTES_MAX} bytes in all`\n );\n }\n return out;\n}\nfunction readBody(raw, method) {\n if (raw === void 0 || raw === null) return null;\n let body;\n if (typeof raw === \"string\") body = encoder3.encode(raw);\n else if (raw instanceof ArrayBuffer) body = new Uint8Array(raw);\n else if (ArrayBuffer.isView(raw))\n body = new Uint8Array(raw.buffer, raw.byteOffset, raw.byteLength);\n else throw handleError(\"ACTION_INVALID_CALL\", \"the body must be a string or bytes\");\n if (body.byteLength > NET_BODY_MAX_BYTES) {\n throw handleError(\n \"ACTION_LIMIT_EXCEEDED\",\n `a request body may be at most ${NET_BODY_MAX_BYTES} bytes`\n );\n }\n if (method === \"GET\" || method === \"HEAD\") {\n throw handleError(\"ACTION_INVALID_CALL\", `a ${method} request cannot have a body`);\n }\n return body;\n}\nfunction readTimeout(raw) {\n if (raw === void 0 || raw === null) return null;\n if (typeof raw !== \"number\" || !Number.isInteger(raw) || raw <= 0 || raw > NET_TIMEOUT_MAX_MS) {\n throw handleError(\n \"ACTION_INVALID_CALL\",\n `timeoutMs must be a whole number of milliseconds from 1 to ${NET_TIMEOUT_MAX_MS}`\n );\n }\n return raw;\n}\nfunction parseOutgoing(raw, policy) {\n if (!isObject(raw) || Array.isArray(raw)) {\n throw handleError(\"ACTION_INVALID_CALL\", \"a request needs { url, method, headers, body }\");\n }\n const { url, host } = readUrl(raw.url, policy);\n const method = readMethod(raw.method);\n const headers = readHeaders(raw.headers);\n const body = readBody(raw.body, method);\n const timeoutMs = readTimeout(raw.timeout_ms);\n if (!recordableHost(host) || !recordablePath(url.pathname)) {\n throw handleError(\"ACTION_INVALID_CALL\", \"the request cannot be recorded, so it is not sent\");\n }\n return { url: url.href, method, host, path: url.pathname, headers, body, timeoutMs };\n}\n\n// ../actions-worker/src/net-caller.ts\nvar NET_RESPONSE_MAX_BYTES = 1024 * 1024;\nvar NET_DEFAULT_TIMEOUT_MS = 3e4;\nvar NET_DEADLINE_MARGIN_MS = 3e3;\nvar NET_MIN_TIME_MS = 1e3;\nvar LOADER_BODY_BUDGET = { limit: 32 * 1024 * 1024, used: 0 };\nfunction codeOf(err) {\n const code = err?.code;\n return typeof code === \"string\" ? code : void 0;\n}\nvar Ended = class extends Error {\n code;\n result;\n constructor(code, message, result) {\n super(message);\n this.name = \"Ended\";\n this.code = code;\n this.result = result;\n }\n};\nvar BODYLESS_STATUS = /* @__PURE__ */ new Set([204, 205, 304]);\nasync function readAnswer(res, method, max, counted) {\n const bodyless = method === \"HEAD\" || BODYLESS_STATUS.has(res.status);\n const declared = Number(res.headers.get(\"Content-Length\") ?? \"\");\n if (!bodyless && Number.isFinite(declared) && declared > max) {\n await res.body?.cancel().catch(() => {\n });\n throw handleError(\"NET_RESPONSE_TOO_LARGE\", `an answer may be at most ${max} bytes`);\n }\n if (!res.body) return new ArrayBuffer(0);\n const reader = res.body.getReader();\n const chunks = [];\n let total = 0;\n for (; ; ) {\n const { done, value } = await reader.read();\n if (done) break;\n total += value.byteLength;\n counted(total);\n if (total > max) {\n await reader.cancel().catch(() => {\n });\n throw handleError(\"NET_RESPONSE_TOO_LARGE\", `an answer may be at most ${max} bytes`);\n }\n chunks.push(value);\n }\n const out = new Uint8Array(total);\n let off = 0;\n for (const c of chunks) {\n out.set(c, off);\n off += c.byteLength;\n }\n return out.buffer;\n}\nfunction createNetCaller(cfg, state) {\n const fetchImpl = cfg.fetchImpl ?? fetch;\n const beginFetch = cfg.beginFetch ?? fetch;\n const now = cfg.now ?? Date.now;\n const budget = cfg.budget ?? LOADER_BODY_BUDGET;\n const beginTarget = {\n ticket: cfg.ticket,\n invocationId: cfg.invocationId,\n instance: cfg.instance,\n callbackOrigin: cfg.callbackOrigin,\n fetchImpl: beginFetch\n };\n function record(result) {\n if (cfg.mode === \"record\") state.netCalls.push(result);\n }\n function timeLeft() {\n return cfg.deadlineMs - NET_DEADLINE_MARGIN_MS - now();\n }\n async function send(seq, out, outbound, controller, started) {\n const base2 = {\n seq,\n method: out.method,\n host: out.host,\n path: out.path,\n request_bytes: out.body?.byteLength ?? 0\n };\n if (cfg.mode === \"record\") {\n try {\n await begin(beginTarget, seq, out, Math.max(1, Math.min(BEGIN_TIMEOUT_MS, timeLeft())));\n } catch (err) {\n throw new Ended(codeOf(err) ?? \"NET_UNAVAILABLE\", err.message, {\n ...base2,\n status: \"refused\"\n });\n }\n }\n const left = timeLeft();\n if (left < NET_MIN_TIME_MS) {\n throw new Ended(\"ACTION_DEADLINE\", \"too little time is left before the action deadline\", {\n ...base2,\n status: \"refused\"\n });\n }\n const timer = setTimeout(\n () => controller.abort(),\n Math.min(out.timeoutMs ?? NET_DEFAULT_TIMEOUT_MS, left)\n );\n let res = null;\n let received = 0;\n try {\n res = await fetchImpl(outbound);\n if (res.status < 200 || res.status > 599) {\n await res.body?.cancel().catch(() => {\n });\n throw handleError(\"NET_FAILED\", \"the server answered with a status code outside 200\\u2013599\");\n }\n const body = await readAnswer(res, out.method, NET_RESPONSE_MAX_BYTES, (n) => {\n received = n;\n });\n const answer = {\n status: res.status,\n status_text: res.statusText,\n headers: [...res.headers],\n body,\n url: out.url\n };\n record({\n ...base2,\n status: \"ok\",\n http_status: res.status,\n response_bytes: body.byteLength,\n duration_ms: now() - started\n });\n return answer;\n } catch (err) {\n const timedOut = controller.signal.aborted;\n const code = timedOut ? \"NET_TIMEOUT\" : codeOf(err) ?? \"NET_FAILED\";\n const message = timedOut ? \"the request timed out; it may have reached the server\" : code === \"NET_FAILED\" && !codeOf(err) ? \"the request failed (connection, DNS or TLS); it may have reached the server\" : err.message;\n const answered = res !== null && res.status >= 200 && res.status <= 599;\n throw new Ended(code, message, {\n ...base2,\n status: \"failed\",\n ...answered ? { http_status: res?.status } : {},\n ...received > 0 ? { response_bytes: received } : {}\n });\n } finally {\n clearTimeout(timer);\n }\n }\n async function take(raw) {\n if (state.revoked) throw handleError(\"ACTION_HANDLE_REVOKED\", \"this handle is no longer valid\");\n if (cfg.maxRequests <= 0 || cfg.policy === null) {\n throw handleError(\n \"NET_UNAVAILABLE\",\n \"actions cannot make outbound requests on this deployment yet\"\n );\n }\n const started = now();\n const seq = ++state.netRequests;\n let fields = describeRequest(raw);\n const refuse = (code, message) => {\n record({ seq, status: \"refused\", ...fields, error_code: code, duration_ms: now() - started });\n return handleError(code, message);\n };\n const overLimit = `an action may make at most ${cfg.maxRequests} outbound requests`;\n if (seq > cfg.maxRequests) {\n state.netLimitHit = true;\n if (seq === cfg.maxRequests + 1) throw refuse(\"ACTION_LIMIT_EXCEEDED\", overLimit);\n throw handleError(\"ACTION_LIMIT_EXCEEDED\", overLimit);\n }\n if (timeLeft() < NET_MIN_TIME_MS) {\n throw refuse(\"ACTION_DEADLINE\", \"too little time is left before the action deadline\");\n }\n let out;\n try {\n out = parseOutgoing(raw, cfg.policy);\n } catch (err) {\n throw refuse(codeOf(err) ?? \"ACTION_INVALID_CALL\", err.message);\n }\n fields = { method: out.method, host: out.host, path: out.path };\n if (state.netInFlight >= cfg.maxInFlight) {\n throw refuse(\n \"ACTION_LIMIT_EXCEEDED\",\n `at most ${cfg.maxInFlight} requests may be in flight at once; wait for one to finish`\n );\n }\n const controller = new AbortController();\n let outbound;\n try {\n outbound = new Request(out.url, {\n method: out.method,\n headers: out.headers,\n body: out.body,\n redirect: \"manual\",\n cache: \"no-store\",\n signal: controller.signal\n });\n } catch {\n throw refuse(\"ACTION_INVALID_CALL\", \"the request's method, headers or body are not valid\");\n }\n const reserved = (out.body?.byteLength ?? 0) + NET_RESPONSE_MAX_BYTES;\n if (budget.used + reserved > budget.limit) {\n throw refuse(\n \"NET_BUSY\",\n \"the platform has too many requests in flight right now; nothing was sent, try again shortly\"\n );\n }\n budget.used += reserved;\n state.netInFlight++;\n const pending = send(seq, out, outbound, controller, started);\n state.inflight.add(pending);\n try {\n return await pending;\n } catch (err) {\n if (err instanceof Ended) {\n record({\n seq,\n status: \"failed\",\n method: out.method,\n host: out.host,\n path: out.path,\n ...err.result,\n error_code: err.code,\n duration_ms: now() - started\n });\n throw handleError(err.code, err.message);\n }\n throw err;\n } finally {\n state.inflight.delete(pending);\n state.netInFlight--;\n budget.used -= reserved;\n }\n }\n return {\n async request(raw) {\n try {\n return await take(raw);\n } catch (err) {\n if (codeOf(err)) throw err;\n throw handleError(\"NET_FAILED\", \"the request failed\");\n }\n }\n };\n}\n\n// ../actions-worker/src/outcome.ts\nvar encoder4 = new TextEncoder();\nfunction truncateBytes(s, maxBytes) {\n const bytes = encoder4.encode(s);\n if (bytes.byteLength <= maxBytes) return s;\n return new TextDecoder().decode(bytes.subarray(0, maxBytes)).replace(/�+$/u, \"\");\n}\nfunction base(state) {\n return {\n db_calls: state.calls,\n data_seq: state.dataSeq,\n clip_calls: state.clipCalls,\n // In seq order; each was added as it ended.\n net_calls: [...state.netCalls].sort((a, b) => a.seq - b.seq)\n };\n}\nfunction limitMessage(state) {\n if (state.limitHit) return \"the action made more database calls than allowed\";\n if (state.clipLimitHit) return \"the action made more Clip calls than allowed\";\n if (state.netLimitHit) return \"the action made more outbound requests than allowed\";\n return null;\n}\nfunction failed(state, error) {\n const limit = limitMessage(state);\n if (limit) {\n return { status: \"limit_exceeded\", error: { kind: \"limit\", message: limit }, ...base(state) };\n }\n return { status: \"failed\", error, ...base(state) };\n}\nfunction asString(v) {\n return typeof v === \"string\" ? v : \"\";\n}\nfunction outcomeFromResult(raw, limits, state) {\n if (typeof raw === \"object\" && raw !== null && !Array.isArray(raw)) {\n const r = raw;\n if (r.ok === true && typeof r.json === \"string\") {\n if (encoder4.encode(r.json).byteLength > limits.result_bytes) {\n return failed(state, {\n kind: \"unexpected\",\n message: `the action result is larger than ${limits.result_bytes} bytes`\n });\n }\n return { status: \"ok\", result_json: r.json, ...base(state) };\n }\n if (r.ok === false && typeof r.error === \"object\" && r.error !== null) {\n const e = r.error;\n if (e.kind === \"action_error\") {\n return failed(state, {\n kind: \"action_error\",\n message: truncateBytes(asString(e.message), limits.message_bytes)\n });\n }\n return failed(state, {\n kind: \"unexpected\",\n message: truncateBytes(asString(e.message), limits.message_bytes),\n stack: truncateBytes(asString(e.stack), limits.stack_bytes)\n });\n }\n }\n return failed(state, {\n kind: \"unexpected\",\n message: \"the action returned a result in an unknown shape\"\n });\n}\nvar CPU_LIMIT = /exceeded (its )?cpu|cpu time limit|exceeded resource limits/i;\nfunction isCpuLimitError(err) {\n const message = err instanceof Error ? err.message : String(err);\n return CPU_LIMIT.test(message);\n}\nfunction outcomeFromThrown(err, limits, state) {\n if (isCpuLimitError(err)) {\n return {\n status: \"limit_exceeded\",\n error: { kind: \"limit\", message: \"the action ran past its CPU time limit\" },\n ...base(state)\n };\n }\n const message = err instanceof Error ? `${err.name}: ${err.message}` : String(err);\n return failed(state, {\n kind: \"unexpected\",\n message: truncateBytes(message, limits.message_bytes)\n });\n}\nfunction timeoutOutcome(state) {\n return {\n status: \"timeout\",\n error: {\n kind: \"timeout\",\n message: \"the action ran past its deadline or lost a database answer; writes it started may have committed\"\n },\n ...base(state)\n };\n}\n\n// ../actions-worker/src/sandbox.ts\nvar COMPATIBILITY_DATE = \"2026-04-01\";\nvar COMPATIBILITY_FLAGS = [];\nvar ENTRYPOINT = \"ActionRunner\";\nvar PRELUDE = `// Runs before the author module (see actions-worker src/sandbox.ts).\nfor (const name of ['caches', 'WebSocket']) {\n try {\n delete globalThis[name];\n } catch {}\n if (name in globalThis) {\n Object.defineProperty(globalThis, name, { value: undefined, writable: false, configurable: false });\n }\n}\n`;\nvar ENTRY = `import './prelude.js';\nexport * from './author.js';\n`;\nfunction workerCode(authorSource) {\n return {\n compatibilityDate: COMPATIBILITY_DATE,\n compatibilityFlags: COMPATIBILITY_FLAGS,\n mainModule: \"entry.js\",\n modules: { \"entry.js\": ENTRY, \"prelude.js\": PRELUDE, \"author.js\": authorSource },\n env: {},\n globalOutbound: null\n };\n}\nvar runtimeVersion = null;\nfunction runtimeVersionOf() {\n if (!runtimeVersion) {\n const material = JSON.stringify([\n COMPATIBILITY_DATE,\n COMPATIBILITY_FLAGS,\n ENTRYPOINT,\n PRELUDE,\n ENTRY,\n \"env:{}\",\n \"outbound:null\"\n ]);\n runtimeVersion = crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(material)).then(\n (d) => Array.from(new Uint8Array(d).slice(0, 8), (b) => b.toString(16).padStart(2, \"0\")).join(\"\")\n );\n }\n return runtimeVersion;\n}\nfunction isolateId(instance, appId, sha256, runtime) {\n return `${instance}:${appId}:${sha256}:${runtime}`;\n}\n\n// ../actions-worker/src/run.ts\nvar DEADLINE_MARGIN_MS = 250;\nasync function runWithDeadline(call, budgetMs) {\n if (budgetMs <= 0) return { kind: \"timeout\" };\n let timer = null;\n const timedOut = new Promise((resolve) => {\n timer = setTimeout(() => resolve({ kind: \"timeout\" }), budgetMs);\n });\n try {\n return await Promise.race([\n call().then(\n (value) => ({ kind: \"result\", value }),\n (error) => ({ kind: \"thrown\", error })\n ),\n timedOut\n ]);\n } finally {\n if (timer !== null) clearTimeout(timer);\n }\n}\nasync function runInvocation(worker, req, opts) {\n const { callbackOrigin, loadFailure = () => null } = opts;\n const effectiveDeadline = req.deadline_ms - DEADLINE_MARGIN_MS;\n const caller = createDbCaller({\n kind: req.kind,\n ticket: req.ticket,\n invocationId: req.invocation_id,\n instance: req.instance,\n callbackOrigin,\n deadlineMs: effectiveDeadline,\n limits: req.limits\n });\n const clip = createClipCaller(\n {\n enabled: req.clip,\n ticket: req.ticket,\n invocationId: req.invocation_id,\n instance: req.instance,\n callbackOrigin,\n deadlineMs: effectiveDeadline,\n maxCalls: req.limits.clip_calls,\n maxBytes: req.limits.result_bytes\n },\n caller.state\n );\n const net = netLimits(req.limits);\n const netCaller = createNetCaller(\n {\n mode: opts.netMode,\n ticket: req.ticket,\n invocationId: req.invocation_id,\n instance: req.instance,\n callbackOrigin,\n deadlineMs: effectiveDeadline,\n maxRequests: net.requests,\n maxInFlight: net.inFlight,\n policy: opts.netPolicy\n },\n caller.state\n );\n const handle = makeHandle(caller, clip, netCaller);\n const entry = worker.getEntrypoint(ENTRYPOINT, { limits: { cpuMs: req.limits.cpu_ms } });\n const settled = await runWithDeadline(\n () => entry.run(\n {\n action: req.action,\n params: req.params,\n viewer: req.viewer,\n app: req.app,\n invocation_id: req.invocation_id,\n // The app's secrets, as ctx.env (mini-app-network-design.md §7.4):\n // per call, never in the isolate's own env.\n env: req.env ?? {},\n // How many requests the SDK lets run at once; it queues the rest.\n net_in_flight: net.inFlight\n },\n handle\n ),\n effectiveDeadline - Date.now()\n );\n const drained = await settle(caller, effectiveDeadline);\n if (settled.kind === \"timeout\" || !drained || caller.state.indeterminate) {\n return timeoutOutcome(caller.state);\n }\n if (settled.kind === \"thrown\") {\n return loadFailure() ?? outcomeFromThrown(settled.error, req.limits, caller.state);\n }\n return outcomeFromResult(settled.value, req.limits, caller.state);\n}\n\n// ../actions-worker/src/local.ts\nvar local_default = {\n async fetch(request, env) {\n let body;\n try {\n body = await request.json();\n } catch {\n return Response.json({ error: \"body is not JSON\" }, { status: 400 });\n }\n const req = parseInvokeRequest(body?.request, { unpublished: true });\n if (typeof req === \"string\") return Response.json({ error: `invalid ${req}` }, { status: 400 });\n if (typeof body.source !== \"string\" || typeof body.callback_origin !== \"string\") {\n return Response.json({ error: \"source and callback_origin are required\" }, { status: 400 });\n }\n const runtime = await runtimeVersionOf();\n const worker = env.LOADER.get(\n isolateId(req.instance, req.app.id, req.module.sha256, runtime),\n async () => workerCode(body.source)\n );\n return Response.json(\n await runInvocation(worker, req, {\n callbackOrigin: body.callback_origin,\n netPolicy: policyFrom(\n env.NET_BLOCKED_HOSTS,\n env.NET_TEST_ALLOW_LOOPBACK,\n body.callback_origin\n ),\n netMode: \"direct\"\n })\n );\n }\n};\nexport {\n local_default as default\n};\n";
5
+ export const LOCAL_RUNNER_SOURCE = "// ../actions-worker/src/contract.ts\nvar DEFAULT_NET_IN_FLIGHT = 4;\nvar INSTANCE = /^(default|pr-\\d{1,6})$/;\nvar APP_ID = /^app_[0-9a-z]{21}$/;\nvar SHA256 = /^[0-9a-f]{64}$/;\nvar ACTION_NAME = /^[a-zA-Z][a-zA-Z0-9_]{0,63}$/;\nvar INVOCATION_ID = /^[0-9A-Za-z_-]{1,64}$/;\nvar LIMIT_CEILINGS = {\n cpu_ms: 3e4,\n db_calls: 1e3,\n batch_statements: 1e3,\n batch_bytes: 8 * 1024 * 1024,\n result_bytes: 8 * 1024 * 1024,\n message_bytes: 64 * 1024,\n stack_bytes: 256 * 1024\n};\nvar CLIP_CALLS_CEILING = 100;\nvar NET_REQUESTS_CEILING = 100;\nvar NET_IN_FLIGHT_CEILING = 6;\nvar PARALL_READS_CEILING = 100;\nvar ENV_NAME = /^[A-Z_][A-Z0-9_]{0,127}$/;\nvar ENV_CEILING_BYTES = 256 * 1024;\nfunction isRecord(v) {\n return typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\nfunction positiveInt(v, max) {\n return typeof v === \"number\" && Number.isInteger(v) && v > 0 && v <= max;\n}\nfunction intInRange(v, min, max) {\n return typeof v === \"number\" && Number.isInteger(v) && v >= min && v <= max;\n}\nvar envEncoder = new TextEncoder();\nfunction validEnv(v) {\n if (!isRecord(v)) return false;\n let total = 0;\n for (const [name, value] of Object.entries(v)) {\n if (!ENV_NAME.test(name) || typeof value !== \"string\") return false;\n total += envEncoder.encode(name).byteLength + envEncoder.encode(value).byteLength;\n if (total > ENV_CEILING_BYTES) return false;\n }\n return true;\n}\nfunction parseInvokeRequest(raw, opts = {}) {\n if (!isRecord(raw)) return \"body is not an object\";\n const {\n invocation_id,\n instance,\n app,\n module,\n action,\n kind,\n clip,\n viewer,\n ticket,\n deadline_ms,\n limits\n } = raw;\n if (typeof invocation_id !== \"string\" || !INVOCATION_ID.test(invocation_id))\n return \"invocation_id\";\n if (typeof instance !== \"string\" || !INSTANCE.test(instance)) return \"instance\";\n if (!isRecord(app) || typeof app.id !== \"string\" || !APP_ID.test(app.id)) return \"app.id\";\n if (!(opts.unpublished && app.version_seq === 0) && !positiveInt(app.version_seq, 2 ** 31))\n return \"app.version_seq\";\n if (!isRecord(module) || typeof module.sha256 !== \"string\" || !SHA256.test(module.sha256))\n return \"module.sha256\";\n if (typeof action !== \"string\" || !ACTION_NAME.test(action)) return \"action\";\n if (kind !== \"read\" && kind !== \"write\") return \"kind\";\n if (clip !== void 0 && clip !== false && !(clip === true && kind === \"write\")) return \"clip\";\n if (!(\"params\" in raw)) return \"params\";\n if (!isRecord(viewer) || typeof viewer.id !== \"string\" || typeof viewer.display_name !== \"string\" || typeof viewer.is_agent !== \"boolean\" || typeof viewer.role !== \"string\") {\n return \"viewer\";\n }\n if (typeof ticket !== \"string\" || ticket.length === 0 || ticket.length > 4096) return \"ticket\";\n if (typeof deadline_ms !== \"number\" || !Number.isFinite(deadline_ms)) return \"deadline_ms\";\n if (!isRecord(limits)) return \"limits\";\n for (const key of Object.keys(LIMIT_CEILINGS)) {\n if (!positiveInt(limits[key], LIMIT_CEILINGS[key])) return `limits.${key}`;\n }\n const clipCalls = limits.clip_calls ?? 0;\n if (clipCalls !== 0 && !positiveInt(clipCalls, CLIP_CALLS_CEILING)) return \"limits.clip_calls\";\n const netRequests = limits.net_requests ?? 0;\n if (!intInRange(netRequests, 0, NET_REQUESTS_CEILING)) return \"limits.net_requests\";\n const netInFlight = limits.net_in_flight ?? DEFAULT_NET_IN_FLIGHT;\n if (!intInRange(netInFlight, 0, NET_IN_FLIGHT_CEILING) || netRequests > 0 && netInFlight === 0) {\n return \"limits.net_in_flight\";\n }\n if (!intInRange(limits.parall_reads ?? 0, 0, PARALL_READS_CEILING)) return \"limits.parall_reads\";\n if (raw.env !== void 0 && raw.env !== null && !validEnv(raw.env)) return \"env\";\n return {\n invocation_id,\n instance,\n app: { id: app.id, version_seq: app.version_seq },\n module: { sha256: module.sha256 },\n action,\n kind,\n clip: clip === true,\n params: raw.params,\n viewer: {\n id: viewer.id,\n display_name: viewer.display_name,\n is_agent: viewer.is_agent,\n role: viewer.role\n },\n ticket,\n deadline_ms,\n limits: { ...limits, clip_calls: clipCalls },\n ...raw.env === null ? { env: null } : {},\n ...isRecord(raw.env) ? { env: { ...raw.env } } : {}\n };\n}\nfunction parallReads(limits) {\n return limits.parall_reads ?? 0;\n}\nfunction netLimits(limits) {\n return {\n requests: limits.net_requests ?? 0,\n inFlight: limits.net_in_flight ?? DEFAULT_NET_IN_FLIGHT\n };\n}\n\n// ../actions-worker/src/net-address.ts\nvar BAD_PORTS = /* @__PURE__ */ new Set([\n 0,\n 1,\n 7,\n 9,\n 11,\n 13,\n 15,\n 17,\n 19,\n 20,\n 21,\n 22,\n 23,\n 25,\n 37,\n 42,\n 43,\n 53,\n 69,\n 77,\n 79,\n 87,\n 95,\n 101,\n 102,\n 103,\n 104,\n 109,\n 110,\n 111,\n 113,\n 115,\n 117,\n 119,\n 123,\n 135,\n 137,\n 139,\n 143,\n 161,\n 179,\n 389,\n 427,\n 465,\n 512,\n 513,\n 514,\n 515,\n 526,\n 530,\n 531,\n 532,\n 540,\n 548,\n 554,\n 556,\n 563,\n 587,\n 601,\n 636,\n 989,\n 990,\n 993,\n 995,\n 1719,\n 1720,\n 1723,\n 2049,\n 3659,\n 4045,\n 4190,\n 5060,\n 5061,\n 6e3,\n 6566,\n 6665,\n 6666,\n 6667,\n 6668,\n 6669,\n 6679,\n 6697,\n 10080\n]);\nvar NUMERIC_LABEL = /^(?:0x[0-9a-f]*|\\d+)$/i;\nvar HOST_NAME = /^[a-z0-9_-]+(?:\\.[a-z0-9_-]+)*$/;\nvar HOST_NAME_MAX_BYTES = 253;\nvar HOST_LABEL_MAX_BYTES = 63;\nfunction normalizeHost(host) {\n return host.toLowerCase().replace(/\\.+$/, \"\");\n}\nfunction isIpLiteral(host) {\n if (host.startsWith(\"[\") || host.includes(\":\")) return true;\n const labels = host.split(\".\");\n return NUMERIC_LABEL.test(labels[labels.length - 1] ?? \"\");\n}\nfunction isLoopbackName(host) {\n return host === \"localhost\" || host.endsWith(\".localhost\");\n}\nfunction isHostName(host) {\n return host.length <= HOST_NAME_MAX_BYTES && HOST_NAME.test(host) && host.split(\".\").every((label) => label.length <= HOST_LABEL_MAX_BYTES);\n}\nfunction isBlockedHost(host, blocked) {\n return blocked.some((name) => host === name || host.endsWith(`.${name}`));\n}\nfunction checkAddress(input, policy) {\n if (input.protocol !== \"https:\" && input.protocol !== \"http:\") {\n return { ok: false, reason: \"only https: and http: URLs can be requested\" };\n }\n if (input.username !== \"\" || input.password !== \"\") {\n return { ok: false, reason: \"a URL with credentials in it (user:pass@) cannot be requested\" };\n }\n const host = normalizeHost(input.hostname);\n if (host === \"\") return { ok: false, reason: \"the URL has no host\" };\n if (isIpLiteral(host)) {\n return { ok: false, reason: \"requests go to host names, not IP addresses\" };\n }\n if (!isHostName(host)) {\n return {\n ok: false,\n reason: `the URL host is not a host name (at most ${HOST_NAME_MAX_BYTES} bytes, ${HOST_LABEL_MAX_BYTES} per label)`\n };\n }\n if (input.port !== \"\" && BAD_PORTS.has(Number(input.port))) {\n return { ok: false, reason: `port ${input.port} cannot be requested` };\n }\n if (isLoopbackName(host) && !policy.allowLoopback) {\n return { ok: false, reason: \"loopback hosts cannot be requested\" };\n }\n if (isBlockedHost(host, policy.blockedHosts)) {\n return { ok: false, reason: \"the platform's own hosts cannot be requested\" };\n }\n const url = new URL(input.href);\n url.hostname = host;\n url.hash = \"\";\n return { ok: true, url, host: input.port === \"\" ? host : `${host}:${input.port}` };\n}\nfunction parseBlockedHosts(raw) {\n if (typeof raw !== \"string\") return null;\n const names = raw.split(\",\").map((s) => normalizeHost(s.trim())).filter((s) => s !== \"\");\n if (names.length === 0) return null;\n for (const name of names) {\n if (!isHostName(name) || isIpLiteral(name)) return null;\n }\n return names;\n}\nvar LOOPBACK_ORIGIN_HOSTS = /* @__PURE__ */ new Set([\"127.0.0.1\", \"localhost\", \"[::1]\"]);\nfunction loopbackAllowed(flag, callbackOrigin) {\n if (flag !== \"1\" && flag !== \"true\") return false;\n try {\n return LOOPBACK_ORIGIN_HOSTS.has(new URL(callbackOrigin).hostname);\n } catch {\n return false;\n }\n}\nfunction policyFrom(blockedHosts, loopbackFlag, callbackOrigin) {\n const blocked = parseBlockedHosts(blockedHosts);\n if (!blocked) return null;\n return { blockedHosts: blocked, allowLoopback: loopbackAllowed(loopbackFlag, callbackOrigin) };\n}\n\n// ../actions-worker/src/db-caller.ts\nvar USER_AGENT = \"parall-actions-worker/1\";\nvar TICKET_HEADER = \"X-Prll-Action-Ticket\";\nvar INVOCATION_HEADER = \"X-Prll-Action-Invocation\";\nvar SWIMLANE_HEADER = \"X-Prll-Swimlane\";\nvar MAX_SQL_BYTES = 256 * 1024;\nvar encoder = new TextEncoder();\nfunction handleError(code, message) {\n const err = new Error(message);\n err.name = \"ActionDbError\";\n err.code = code;\n return err;\n}\nfunction statementOf(v) {\n if (typeof v !== \"object\" || v === null) return null;\n const { sql, params } = v;\n if (typeof sql !== \"string\" || sql.length === 0 || encoder.encode(sql).byteLength > MAX_SQL_BYTES)\n return null;\n if (params !== void 0 && !Array.isArray(params)) return null;\n return { sql, params: params ?? [] };\n}\nfunction requestBody(op, payload, limits) {\n if (op === \"batch\") {\n const statements = payload?.statements;\n if (!Array.isArray(statements) || statements.length === 0) {\n throw handleError(\"ACTION_INVALID_CALL\", \"batch needs a non-empty array of { sql, params }\");\n }\n if (statements.length > limits.batch_statements) {\n throw handleError(\n \"ACTION_LIMIT_EXCEEDED\",\n `a batch may hold at most ${limits.batch_statements} statements`\n );\n }\n const parsed = statements.map(statementOf);\n if (parsed.some((s) => s === null)) {\n throw handleError(\n \"ACTION_INVALID_CALL\",\n \"every batch entry needs a non-empty sql string and a params array\"\n );\n }\n const body = JSON.stringify({ statements: parsed });\n if (encoder.encode(body).byteLength > limits.batch_bytes) {\n throw handleError(\n \"ACTION_LIMIT_EXCEEDED\",\n `a batch may be at most ${limits.batch_bytes} bytes`\n );\n }\n return body;\n }\n const statement = statementOf(payload);\n if (!statement)\n throw handleError(\n \"ACTION_INVALID_CALL\",\n `${op} needs a non-empty sql string and a params array`\n );\n return JSON.stringify(statement);\n}\nfunction trackDataSeq(state, result) {\n const seq = result?.data_seq;\n if (typeof seq !== \"number\" || !Number.isInteger(seq)) return;\n state.dataSeq = state.dataSeq ? { from: Math.min(state.dataSeq.from, seq), to: Math.max(state.dataSeq.to, seq) } : { from: seq, to: seq };\n}\nasync function readCapped(res, maxBytes) {\n if (!res.body) return \"\";\n const reader = res.body.getReader();\n const chunks = [];\n let total = 0;\n for (; ; ) {\n const { done, value } = await reader.read();\n if (done) break;\n total += value.byteLength;\n if (total > maxBytes) {\n await reader.cancel();\n throw handleError(\n \"ACTION_RESULT_TOO_LARGE\",\n `a database result may be at most ${maxBytes} bytes`\n );\n }\n chunks.push(value);\n }\n const out = new Uint8Array(total);\n let off = 0;\n for (const c of chunks) {\n out.set(c, off);\n off += c.byteLength;\n }\n return new TextDecoder().decode(out);\n}\nfunction createDbCaller(cfg) {\n const fetchImpl = cfg.fetchImpl ?? fetch;\n const now = cfg.now ?? Date.now;\n const state = {\n revoked: false,\n calls: 0,\n limitHit: false,\n inflight: /* @__PURE__ */ new Set(),\n dataSeq: null,\n indeterminate: false,\n clipCalls: 0,\n clipLimitHit: false,\n netRequests: 0,\n netLimitHit: false,\n netInFlight: 0,\n netCalls: [],\n parallReads: 0,\n parallLimitHit: false\n };\n const origin = cfg.callbackOrigin.replace(/\\/+$/, \"\");\n async function send(op, body) {\n const headers = {\n \"Content-Type\": \"application/json\",\n \"User-Agent\": USER_AGENT,\n [TICKET_HEADER]: cfg.ticket,\n [INVOCATION_HEADER]: cfg.invocationId\n };\n if (cfg.instance !== \"default\") headers[SWIMLANE_HEADER] = cfg.instance;\n const remaining = Math.max(1, cfg.deadlineMs - now());\n let res;\n try {\n res = await fetchImpl(`${origin}/api/v1/mini-app-actions/db/${op}`, {\n method: \"POST\",\n headers,\n body,\n signal: AbortSignal.timeout(remaining)\n });\n } catch {\n if (op !== \"query\") state.indeterminate = true;\n throw handleError(\"ACTION_DB_UNAVAILABLE\", \"the database could not be reached\");\n }\n let parsed;\n try {\n const text = await readCapped(res, cfg.limits.result_bytes + 64 * 1024);\n parsed = text ? JSON.parse(text) : null;\n } catch (err) {\n if (op !== \"query\") state.indeterminate = true;\n if (err.code === \"ACTION_RESULT_TOO_LARGE\") throw err;\n throw handleError(\"ACTION_DB_UNAVAILABLE\", \"the database returned an unreadable response\");\n }\n if (!res.ok) {\n const env = parsed?.error;\n if (typeof env?.code !== \"string\") {\n if (op !== \"query\") state.indeterminate = true;\n throw handleError(`HTTP_${res.status}`, `database call failed (${res.status})`);\n }\n const message = typeof env.message === \"string\" ? env.message : `database call failed (${res.status})`;\n throw handleError(env.code, message);\n }\n trackDataSeq(state, parsed);\n return parsed;\n }\n async function call(op, payload) {\n if (state.revoked)\n throw handleError(\"ACTION_HANDLE_REVOKED\", \"this database handle is no longer valid\");\n if (now() >= cfg.deadlineMs)\n throw handleError(\"ACTION_DEADLINE\", \"the action ran past its deadline\");\n if (cfg.kind === \"read\" && op !== \"query\") {\n throw handleError(\"ACTION_READ_ONLY\", \"a read action can only query\");\n }\n state.calls++;\n if (state.calls > cfg.limits.db_calls) {\n state.limitHit = true;\n throw handleError(\n \"ACTION_LIMIT_EXCEEDED\",\n `an action may make at most ${cfg.limits.db_calls} database calls`\n );\n }\n const body = requestBody(op, payload, cfg.limits);\n const pending = send(op, body);\n state.inflight.add(pending);\n try {\n return await pending;\n } finally {\n state.inflight.delete(pending);\n }\n }\n return { state, call };\n}\nfunction settleCall(caller, op, payload) {\n return settleWith(\n () => caller.call(op, payload),\n \"ACTION_DB_UNAVAILABLE\",\n \"the database call failed\"\n );\n}\nasync function settleWith(run, fallbackCode, fallbackMessage) {\n try {\n return { ok: true, value: await run() };\n } catch (err) {\n const { code, message } = err ?? {};\n return {\n ok: false,\n error: {\n code: typeof code === \"string\" ? code : fallbackCode,\n message: typeof message === \"string\" ? message : fallbackMessage\n }\n };\n }\n}\nasync function settle(caller, deadlineMs, now = Date.now) {\n caller.state.revoked = true;\n const inflight = [...caller.state.inflight];\n if (inflight.length === 0) return true;\n const remaining = deadlineMs - now();\n if (remaining > 0) {\n let timer = null;\n await Promise.race([\n Promise.allSettled(inflight),\n new Promise((r) => {\n timer = setTimeout(r, remaining);\n })\n ]);\n if (timer !== null) clearTimeout(timer);\n }\n return caller.state.inflight.size === 0;\n}\n\n// ../actions-worker/src/clip-caller.ts\nvar ENVELOPE_BYTES = 64 * 1024;\nvar MAX_FIELD_BYTES = 256;\nvar encoder2 = new TextEncoder();\nfunction unknownOutcome() {\n return handleError(\n \"OUTCOME_UNKNOWN\",\n \"the Clip call\\u2019s answer was lost \\u2014 it may or may not have run; do not retry it blindly\"\n );\n}\nfunction field(v, required) {\n if (v === void 0 || v === null) return required ? null : void 0;\n if (typeof v !== \"string\" || encoder2.encode(v).byteLength > MAX_FIELD_BYTES) return null;\n if (required && v.trim() === \"\") return null;\n return v;\n}\nfunction requestBody2(req, seq, maxBytes) {\n const r = typeof req === \"object\" && req !== null ? req : {};\n const clip = field(r.clip, true);\n const command = field(r.command, true);\n const connection = field(r.connection, false);\n const profile = field(r.profile, false);\n const timeout = r.timeout_ms;\n if (clip === null || command === null || connection === null || profile === null) {\n throw handleError(\n \"ACTION_INVALID_CALL\",\n \"clip.exec needs a Clip name or id, a command, and string connection and profile options of at most 256 bytes\"\n );\n }\n if (timeout !== void 0 && (typeof timeout !== \"number\" || !Number.isInteger(timeout) || timeout <= 0 || timeout > 12e4)) {\n throw handleError(\n \"ACTION_INVALID_CALL\",\n \"timeoutMs must be a whole number of milliseconds from 1 to 120000\"\n );\n }\n let body;\n try {\n body = JSON.stringify({\n seq,\n clip,\n command,\n args: r.args,\n connection: connection ?? \"\",\n profile,\n timeout_ms: timeout\n });\n } catch {\n throw handleError(\"ACTION_INVALID_CALL\", \"the Clip arguments cannot be sent as JSON\");\n }\n if (encoder2.encode(body).byteLength > maxBytes) {\n throw handleError(\n \"ACTION_LIMIT_EXCEEDED\",\n `a Clip call's arguments may be at most ${maxBytes} bytes`\n );\n }\n return body;\n}\nfunction createClipCaller(cfg, state) {\n const fetchImpl = cfg.fetchImpl ?? fetch;\n const now = cfg.now ?? Date.now;\n const url = `${cfg.callbackOrigin.replace(/\\/+$/, \"\")}/api/v1/mini-app-actions/clip/exec`;\n async function send(body) {\n const headers = {\n \"Content-Type\": \"application/json\",\n \"User-Agent\": USER_AGENT,\n [TICKET_HEADER]: cfg.ticket,\n [INVOCATION_HEADER]: cfg.invocationId\n };\n if (cfg.instance !== \"default\") headers[SWIMLANE_HEADER] = cfg.instance;\n let res;\n try {\n res = await fetchImpl(url, {\n method: \"POST\",\n headers,\n body,\n signal: AbortSignal.timeout(Math.max(1, cfg.deadlineMs - now()))\n });\n } catch {\n throw unknownOutcome();\n }\n let parsed;\n try {\n const text = await readCapped(res, cfg.maxBytes + ENVELOPE_BYTES);\n parsed = text ? JSON.parse(text) : null;\n } catch {\n throw unknownOutcome();\n }\n if (res.ok) {\n const a = parsed;\n if (a?.ok === true) return a.value ?? null;\n if (a?.ok === false && typeof a.error?.code === \"string\") {\n throw handleError(\n a.error.code,\n typeof a.error.message === \"string\" ? a.error.message : a.error.code\n );\n }\n throw unknownOutcome();\n }\n const env = parsed?.error;\n if (typeof env?.code !== \"string\") throw unknownOutcome();\n throw handleError(\n env.code,\n typeof env.message === \"string\" ? env.message : `Clip call refused (${res.status})`\n );\n }\n async function call(req) {\n if (state.revoked) throw handleError(\"ACTION_HANDLE_REVOKED\", \"this handle is no longer valid\");\n if (!cfg.enabled) {\n throw handleError(\n \"CLIP_NOT_DECLARED\",\n \"this action does not declare clip, so it cannot call Clip\"\n );\n }\n if (now() >= cfg.deadlineMs)\n throw handleError(\"ACTION_DEADLINE\", \"the action ran past its deadline\");\n if (state.clipCalls >= cfg.maxCalls) {\n state.clipLimitHit = true;\n throw handleError(\n \"ACTION_LIMIT_EXCEEDED\",\n `an action may make at most ${cfg.maxCalls} Clip calls`\n );\n }\n const body = requestBody2(req, state.clipCalls + 1, cfg.maxBytes);\n state.clipCalls++;\n const pending = send(body);\n state.inflight.add(pending);\n try {\n return await pending;\n } finally {\n state.inflight.delete(pending);\n }\n }\n return { call };\n}\n\n// ../actions-worker/src/handle.ts\nimport { RpcTarget } from \"cloudflare:workers\";\nvar ActionHandle = class extends RpcTarget {\n #caller;\n #clip;\n #net;\n #parall;\n constructor(caller, clip, net, parall) {\n super();\n this.#caller = caller;\n this.#clip = clip;\n this.#net = net;\n this.#parall = parall;\n }\n query(sql, params) {\n return settleCall(this.#caller, \"query\", { sql, params });\n }\n exec(sql, params) {\n return settleCall(this.#caller, \"exec\", { sql, params });\n }\n batch(statements) {\n return settleCall(this.#caller, \"batch\", { statements });\n }\n clip(req) {\n return settleWith(() => this.#clip.call(req), \"CLIP_UNAVAILABLE\", \"the Clip call failed\");\n }\n request(req) {\n return settleWith(() => this.#net.request(req), \"NET_FAILED\", \"the request failed\");\n }\n parall(req) {\n return settleWith(\n () => this.#parall.get(req),\n \"PARALL_READ_UNAVAILABLE\",\n \"Parall data could not be read\"\n );\n }\n};\nfunction makeHandle(caller, clip, net, parall) {\n return new ActionHandle(caller, clip, net, parall);\n}\n\n// ../actions-worker/src/net-begin.ts\nvar BEGIN_TIMEOUT_MS = 1e4;\nvar BEGIN_ANSWER_MAX_BYTES = 64 * 1024;\nvar ERROR_CODE = /^[A-Z][A-Z0-9_]{0,63}$/;\nfunction notRegistered() {\n return handleError(\n \"NET_UNAVAILABLE\",\n \"the request could not be registered with the platform, so it was not sent\"\n );\n}\nasync function begin(target, seq, fields, timeoutMs) {\n const headers = {\n \"Content-Type\": \"application/json\",\n \"User-Agent\": USER_AGENT,\n [TICKET_HEADER]: target.ticket,\n [INVOCATION_HEADER]: target.invocationId\n };\n if (target.instance !== \"default\") headers[SWIMLANE_HEADER] = target.instance;\n const url = `${target.callbackOrigin.replace(/\\/+$/, \"\")}/api/v1/mini-app-actions/net/begin`;\n const fetchImpl = target.fetchImpl;\n let res;\n try {\n res = await fetchImpl(url, {\n method: \"POST\",\n headers,\n body: JSON.stringify({ seq, method: fields.method, host: fields.host, path: fields.path }),\n signal: AbortSignal.timeout(timeoutMs)\n });\n } catch {\n throw notRegistered();\n }\n let parsed;\n try {\n const text = await readCapped(res, BEGIN_ANSWER_MAX_BYTES);\n parsed = text ? JSON.parse(text) : null;\n } catch {\n throw notRegistered();\n }\n const answer = parsed;\n if (res.status === 200 && answer?.ok === true) return;\n const error = res.ok ? answer?.ok === false ? answer.error : void 0 : answer?.error;\n if (typeof error?.code === \"string\" && ERROR_CODE.test(error.code)) {\n throw handleError(\n error.code,\n typeof error.message === \"string\" ? error.message : \"the platform refused the request\"\n );\n }\n throw notRegistered();\n}\n\n// ../actions-worker/src/net-request.ts\nvar NET_URL_MAX_BYTES = 8 * 1024;\nvar NET_HEADERS_MAX = 64;\nvar NET_HEADER_BYTES_MAX = 32 * 1024;\nvar NET_BODY_MAX_BYTES = 1024 * 1024;\nvar NET_TIMEOUT_MAX_MS = 12e4;\nvar FORBIDDEN_HEADERS = /* @__PURE__ */ new Set([\n \"host\",\n \"connection\",\n \"upgrade\",\n \"keep-alive\",\n \"te\",\n \"trailer\",\n \"transfer-encoding\"\n]);\nvar FORBIDDEN_HEADER_PREFIXES = [\"proxy-\", \"x-prll-\", \"cf-\"];\nvar DROPPED_HEADERS = /* @__PURE__ */ new Set([\"content-length\"]);\nvar METHOD = /^[!#$%&'*+.^_`|~0-9A-Za-z-]{1,16}$/;\nvar FORBIDDEN_METHODS = /* @__PURE__ */ new Set([\"CONNECT\", \"TRACE\", \"TRACK\"]);\nvar NORMALIZED_METHODS = /* @__PURE__ */ new Set([\"DELETE\", \"GET\", \"HEAD\", \"OPTIONS\", \"PATCH\", \"POST\", \"PUT\"]);\nvar HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;\nvar encoder3 = new TextEncoder();\nfunction isObject(v) {\n return typeof v === \"object\" && v !== null;\n}\nfunction normalizeMethod(method) {\n const upper = method.toUpperCase();\n return NORMALIZED_METHODS.has(upper) ? upper : method;\n}\nvar RECORD_HOST_MAX_BYTES = 300;\nfunction printableAscii(s) {\n return /^[\\x21-\\x7e]+$/.test(s);\n}\nfunction recordableHost(host) {\n return host.length <= RECORD_HOST_MAX_BYTES && printableAscii(host) && !/[/?#@\\\\]/.test(host);\n}\nfunction recordablePath(path) {\n return path.startsWith(\"/\") && path.length <= NET_URL_MAX_BYTES && printableAscii(path);\n}\nfunction describeRequest(raw) {\n const r = isObject(raw) ? raw : {};\n const fields = { method: \"\", host: \"\", path: \"\" };\n const method = r.method === void 0 ? \"GET\" : r.method;\n if (typeof method === \"string\" && METHOD.test(method)) fields.method = normalizeMethod(method);\n if (typeof r.url === \"string\" && r.url.length <= 4 * NET_URL_MAX_BYTES) {\n try {\n const url = new URL(r.url);\n const host = normalizeHost(url.hostname) + (url.port === \"\" ? \"\" : `:${url.port}`);\n if (recordableHost(host)) fields.host = host;\n if (recordablePath(url.pathname)) fields.path = url.pathname;\n } catch {\n }\n }\n return fields;\n}\nfunction readUrl(raw, policy) {\n if (typeof raw !== \"string\" || raw === \"\") {\n throw handleError(\"ACTION_INVALID_CALL\", \"a request needs an absolute http(s) URL\");\n }\n if (raw.length > 4 * NET_URL_MAX_BYTES) {\n throw handleError(\"ACTION_LIMIT_EXCEEDED\", `a URL may be at most ${NET_URL_MAX_BYTES} bytes`);\n }\n let parsed;\n try {\n parsed = new URL(raw);\n } catch {\n throw handleError(\"ACTION_INVALID_CALL\", \"a request needs an absolute http(s) URL\");\n }\n const verdict = checkAddress(parsed, policy);\n if (!verdict.ok) throw handleError(\"NET_ADDRESS_BLOCKED\", verdict.reason);\n if (encoder3.encode(verdict.url.href).byteLength > NET_URL_MAX_BYTES) {\n throw handleError(\"ACTION_LIMIT_EXCEEDED\", `a URL may be at most ${NET_URL_MAX_BYTES} bytes`);\n }\n return { url: verdict.url, host: verdict.host };\n}\nfunction readMethod(raw) {\n if (raw === void 0) return \"GET\";\n if (typeof raw !== \"string\" || !METHOD.test(raw)) {\n throw handleError(\"ACTION_INVALID_CALL\", \"the method must be an HTTP method name\");\n }\n const method = normalizeMethod(raw);\n if (FORBIDDEN_METHODS.has(method.toUpperCase())) {\n throw handleError(\"ACTION_INVALID_CALL\", `${method} requests cannot be made`);\n }\n return method;\n}\nfunction headerPairs(raw) {\n if (raw === void 0 || raw === null) return [];\n if (Array.isArray(raw)) {\n return raw.map(\n (pair) => Array.isArray(pair) && pair.length === 2 ? [pair[0], pair[1]] : [null, null]\n );\n }\n if (isObject(raw)) return Object.entries(raw);\n throw handleError(\"ACTION_INVALID_CALL\", \"headers must be [name, value] pairs or an object\");\n}\nfunction readHeaders(raw) {\n const pairs = headerPairs(raw);\n if (pairs.length > NET_HEADERS_MAX) {\n throw handleError(\n \"ACTION_LIMIT_EXCEEDED\",\n `a request may have at most ${NET_HEADERS_MAX} headers`\n );\n }\n let bytes = 0;\n const out = [];\n for (const [name, value] of pairs) {\n if (typeof name !== \"string\" || typeof value !== \"string\" || !HEADER_NAME.test(name)) {\n throw handleError(\"ACTION_INVALID_CALL\", \"each header needs a valid name and a string value\");\n }\n bytes += encoder3.encode(name).byteLength + encoder3.encode(value).byteLength;\n const lower = name.toLowerCase();\n if (FORBIDDEN_HEADERS.has(lower) || FORBIDDEN_HEADER_PREFIXES.some((prefix) => lower.startsWith(prefix))) {\n throw handleError(\"ACTION_INVALID_CALL\", `the ${name} header cannot be set`);\n }\n if (!DROPPED_HEADERS.has(lower)) out.push([name, value]);\n }\n if (bytes > NET_HEADER_BYTES_MAX) {\n throw handleError(\n \"ACTION_LIMIT_EXCEEDED\",\n `a request's headers may be at most ${NET_HEADER_BYTES_MAX} bytes in all`\n );\n }\n return out;\n}\nfunction readBody(raw, method) {\n if (raw === void 0 || raw === null) return null;\n let body;\n if (typeof raw === \"string\") body = encoder3.encode(raw);\n else if (raw instanceof ArrayBuffer) body = new Uint8Array(raw);\n else if (ArrayBuffer.isView(raw))\n body = new Uint8Array(raw.buffer, raw.byteOffset, raw.byteLength);\n else throw handleError(\"ACTION_INVALID_CALL\", \"the body must be a string or bytes\");\n if (body.byteLength > NET_BODY_MAX_BYTES) {\n throw handleError(\n \"ACTION_LIMIT_EXCEEDED\",\n `a request body may be at most ${NET_BODY_MAX_BYTES} bytes`\n );\n }\n if (method === \"GET\" || method === \"HEAD\") {\n throw handleError(\"ACTION_INVALID_CALL\", `a ${method} request cannot have a body`);\n }\n return body;\n}\nfunction readTimeout(raw) {\n if (raw === void 0 || raw === null) return null;\n if (typeof raw !== \"number\" || !Number.isInteger(raw) || raw <= 0 || raw > NET_TIMEOUT_MAX_MS) {\n throw handleError(\n \"ACTION_INVALID_CALL\",\n `timeoutMs must be a whole number of milliseconds from 1 to ${NET_TIMEOUT_MAX_MS}`\n );\n }\n return raw;\n}\nfunction parseOutgoing(raw, policy) {\n if (!isObject(raw) || Array.isArray(raw)) {\n throw handleError(\"ACTION_INVALID_CALL\", \"a request needs { url, method, headers, body }\");\n }\n const { url, host } = readUrl(raw.url, policy);\n const method = readMethod(raw.method);\n const headers = readHeaders(raw.headers);\n const body = readBody(raw.body, method);\n const timeoutMs = readTimeout(raw.timeout_ms);\n if (!recordableHost(host) || !recordablePath(url.pathname)) {\n throw handleError(\"ACTION_INVALID_CALL\", \"the request cannot be recorded, so it is not sent\");\n }\n return { url: url.href, method, host, path: url.pathname, headers, body, timeoutMs };\n}\n\n// ../actions-worker/src/net-caller.ts\nvar NET_RESPONSE_MAX_BYTES = 1024 * 1024;\nvar NET_DEFAULT_TIMEOUT_MS = 3e4;\nvar NET_DEADLINE_MARGIN_MS = 3e3;\nvar NET_MIN_TIME_MS = 1e3;\nvar LOADER_BODY_BUDGET = { limit: 32 * 1024 * 1024, used: 0 };\nfunction codeOf(err) {\n const code = err?.code;\n return typeof code === \"string\" ? code : void 0;\n}\nvar Ended = class extends Error {\n code;\n result;\n constructor(code, message, result) {\n super(message);\n this.name = \"Ended\";\n this.code = code;\n this.result = result;\n }\n};\nvar BODYLESS_STATUS = /* @__PURE__ */ new Set([204, 205, 304]);\nasync function readAnswer(res, method, max, counted) {\n const bodyless = method === \"HEAD\" || BODYLESS_STATUS.has(res.status);\n const declared = Number(res.headers.get(\"Content-Length\") ?? \"\");\n if (!bodyless && Number.isFinite(declared) && declared > max) {\n await res.body?.cancel().catch(() => {\n });\n throw handleError(\"NET_RESPONSE_TOO_LARGE\", `an answer may be at most ${max} bytes`);\n }\n if (!res.body) return new ArrayBuffer(0);\n const reader = res.body.getReader();\n const chunks = [];\n let total = 0;\n for (; ; ) {\n const { done, value } = await reader.read();\n if (done) break;\n total += value.byteLength;\n counted(total);\n if (total > max) {\n await reader.cancel().catch(() => {\n });\n throw handleError(\"NET_RESPONSE_TOO_LARGE\", `an answer may be at most ${max} bytes`);\n }\n chunks.push(value);\n }\n const out = new Uint8Array(total);\n let off = 0;\n for (const c of chunks) {\n out.set(c, off);\n off += c.byteLength;\n }\n return out.buffer;\n}\nfunction createNetCaller(cfg, state) {\n const fetchImpl = cfg.fetchImpl ?? fetch;\n const beginFetch = cfg.beginFetch ?? fetch;\n const now = cfg.now ?? Date.now;\n const budget = cfg.budget ?? LOADER_BODY_BUDGET;\n const beginTarget = {\n ticket: cfg.ticket,\n invocationId: cfg.invocationId,\n instance: cfg.instance,\n callbackOrigin: cfg.callbackOrigin,\n fetchImpl: beginFetch\n };\n function record(result) {\n if (cfg.mode === \"record\") state.netCalls.push(result);\n }\n function timeLeft() {\n return cfg.deadlineMs - NET_DEADLINE_MARGIN_MS - now();\n }\n async function send(seq, out, outbound, controller, started) {\n const base2 = {\n seq,\n method: out.method,\n host: out.host,\n path: out.path,\n request_bytes: out.body?.byteLength ?? 0\n };\n if (cfg.mode === \"record\") {\n try {\n await begin(beginTarget, seq, out, Math.max(1, Math.min(BEGIN_TIMEOUT_MS, timeLeft())));\n } catch (err) {\n throw new Ended(codeOf(err) ?? \"NET_UNAVAILABLE\", err.message, {\n ...base2,\n status: \"refused\"\n });\n }\n }\n const left = timeLeft();\n if (left < NET_MIN_TIME_MS) {\n throw new Ended(\"ACTION_DEADLINE\", \"too little time is left before the action deadline\", {\n ...base2,\n status: \"refused\"\n });\n }\n const timer = setTimeout(\n () => controller.abort(),\n Math.min(out.timeoutMs ?? NET_DEFAULT_TIMEOUT_MS, left)\n );\n let res = null;\n let received = 0;\n try {\n res = await fetchImpl(outbound);\n if (res.status < 200 || res.status > 599) {\n await res.body?.cancel().catch(() => {\n });\n throw handleError(\"NET_FAILED\", \"the server answered with a status code outside 200\\u2013599\");\n }\n const body = await readAnswer(res, out.method, NET_RESPONSE_MAX_BYTES, (n) => {\n received = n;\n });\n const answer = {\n status: res.status,\n status_text: res.statusText,\n headers: [...res.headers],\n body,\n url: out.url\n };\n record({\n ...base2,\n status: \"ok\",\n http_status: res.status,\n response_bytes: body.byteLength,\n duration_ms: now() - started\n });\n return answer;\n } catch (err) {\n const timedOut = controller.signal.aborted;\n const code = timedOut ? \"NET_TIMEOUT\" : codeOf(err) ?? \"NET_FAILED\";\n const message = timedOut ? \"the request timed out; it may have reached the server\" : code === \"NET_FAILED\" && !codeOf(err) ? \"the request failed (connection, DNS or TLS); it may have reached the server\" : err.message;\n const answered = res !== null && res.status >= 200 && res.status <= 599;\n throw new Ended(code, message, {\n ...base2,\n status: \"failed\",\n ...answered ? { http_status: res?.status } : {},\n ...received > 0 ? { response_bytes: received } : {}\n });\n } finally {\n clearTimeout(timer);\n }\n }\n async function take(raw) {\n if (state.revoked) throw handleError(\"ACTION_HANDLE_REVOKED\", \"this handle is no longer valid\");\n if (cfg.maxRequests <= 0 || cfg.policy === null) {\n throw handleError(\n \"NET_UNAVAILABLE\",\n \"actions cannot make outbound requests on this deployment yet\"\n );\n }\n const started = now();\n const seq = ++state.netRequests;\n let fields = describeRequest(raw);\n const refuse = (code, message) => {\n record({ seq, status: \"refused\", ...fields, error_code: code, duration_ms: now() - started });\n return handleError(code, message);\n };\n const overLimit = `an action may make at most ${cfg.maxRequests} outbound requests`;\n if (seq > cfg.maxRequests) {\n state.netLimitHit = true;\n if (seq === cfg.maxRequests + 1) throw refuse(\"ACTION_LIMIT_EXCEEDED\", overLimit);\n throw handleError(\"ACTION_LIMIT_EXCEEDED\", overLimit);\n }\n if (timeLeft() < NET_MIN_TIME_MS) {\n throw refuse(\"ACTION_DEADLINE\", \"too little time is left before the action deadline\");\n }\n let out;\n try {\n out = parseOutgoing(raw, cfg.policy);\n } catch (err) {\n throw refuse(codeOf(err) ?? \"ACTION_INVALID_CALL\", err.message);\n }\n fields = { method: out.method, host: out.host, path: out.path };\n if (state.netInFlight >= cfg.maxInFlight) {\n throw refuse(\n \"ACTION_LIMIT_EXCEEDED\",\n `at most ${cfg.maxInFlight} requests may be in flight at once; wait for one to finish`\n );\n }\n const controller = new AbortController();\n let outbound;\n try {\n outbound = new Request(out.url, {\n method: out.method,\n headers: out.headers,\n body: out.body,\n redirect: \"manual\",\n cache: \"no-store\",\n signal: controller.signal\n });\n } catch {\n throw refuse(\"ACTION_INVALID_CALL\", \"the request's method, headers or body are not valid\");\n }\n const reserved = (out.body?.byteLength ?? 0) + NET_RESPONSE_MAX_BYTES;\n if (budget.used + reserved > budget.limit) {\n throw refuse(\n \"NET_BUSY\",\n \"the platform has too many requests in flight right now; nothing was sent, try again shortly\"\n );\n }\n budget.used += reserved;\n state.netInFlight++;\n const pending = send(seq, out, outbound, controller, started);\n state.inflight.add(pending);\n try {\n return await pending;\n } catch (err) {\n if (err instanceof Ended) {\n record({\n seq,\n status: \"failed\",\n method: out.method,\n host: out.host,\n path: out.path,\n ...err.result,\n error_code: err.code,\n duration_ms: now() - started\n });\n throw handleError(err.code, err.message);\n }\n throw err;\n } finally {\n state.inflight.delete(pending);\n state.netInFlight--;\n budget.used -= reserved;\n }\n }\n return {\n async request(raw) {\n try {\n return await take(raw);\n } catch (err) {\n if (codeOf(err)) throw err;\n throw handleError(\"NET_FAILED\", \"the request failed\");\n }\n }\n };\n}\n\n// ../actions-worker/src/outcome.ts\nvar encoder4 = new TextEncoder();\nfunction truncateBytes(s, maxBytes) {\n const bytes = encoder4.encode(s);\n if (bytes.byteLength <= maxBytes) return s;\n return new TextDecoder().decode(bytes.subarray(0, maxBytes)).replace(/�+$/u, \"\");\n}\nfunction base(state) {\n return {\n db_calls: state.calls,\n data_seq: state.dataSeq,\n clip_calls: state.clipCalls,\n // In seq order; each was added as it ended.\n net_calls: [...state.netCalls].sort((a, b) => a.seq - b.seq)\n };\n}\nfunction limitMessage(state) {\n if (state.limitHit) return \"the action made more database calls than allowed\";\n if (state.clipLimitHit) return \"the action made more connector calls than allowed\";\n if (state.netLimitHit) return \"the action made more outbound requests than allowed\";\n if (state.parallLimitHit) return \"the action read Parall data more times than allowed\";\n return null;\n}\nfunction failed(state, error) {\n const limit = limitMessage(state);\n if (limit) {\n return { status: \"limit_exceeded\", error: { kind: \"limit\", message: limit }, ...base(state) };\n }\n return { status: \"failed\", error, ...base(state) };\n}\nfunction asString(v) {\n return typeof v === \"string\" ? v : \"\";\n}\nfunction outcomeFromResult(raw, limits, state) {\n if (typeof raw === \"object\" && raw !== null && !Array.isArray(raw)) {\n const r = raw;\n if (r.ok === true && typeof r.json === \"string\") {\n if (encoder4.encode(r.json).byteLength > limits.result_bytes) {\n return failed(state, {\n kind: \"unexpected\",\n message: `the action result is larger than ${limits.result_bytes} bytes`\n });\n }\n return { status: \"ok\", result_json: r.json, ...base(state) };\n }\n if (r.ok === false && typeof r.error === \"object\" && r.error !== null) {\n const e = r.error;\n if (e.kind === \"action_error\") {\n return failed(state, {\n kind: \"action_error\",\n message: truncateBytes(asString(e.message), limits.message_bytes)\n });\n }\n return failed(state, {\n kind: \"unexpected\",\n message: truncateBytes(asString(e.message), limits.message_bytes),\n stack: truncateBytes(asString(e.stack), limits.stack_bytes)\n });\n }\n }\n return failed(state, {\n kind: \"unexpected\",\n message: \"the action returned a result in an unknown shape\"\n });\n}\nvar CPU_LIMIT = /exceeded (its )?cpu|cpu time limit|exceeded resource limits/i;\nfunction isCpuLimitError(err) {\n const message = err instanceof Error ? err.message : String(err);\n return CPU_LIMIT.test(message);\n}\nfunction outcomeFromThrown(err, limits, state) {\n if (isCpuLimitError(err)) {\n return {\n status: \"limit_exceeded\",\n error: { kind: \"limit\", message: \"the action ran past its CPU time limit\" },\n ...base(state)\n };\n }\n const message = err instanceof Error ? `${err.name}: ${err.message}` : String(err);\n return failed(state, {\n kind: \"unexpected\",\n message: truncateBytes(message, limits.message_bytes)\n });\n}\nfunction timeoutOutcome(state) {\n return {\n status: \"timeout\",\n error: {\n kind: \"timeout\",\n message: \"the action ran past its deadline or lost a database answer; writes it started may have committed\"\n },\n ...base(state)\n };\n}\n\n// ../actions-worker/src/parall-caller.ts\nvar PARALL_MAX_REFS = 100;\nvar PARALL_GET_TIMEOUT_MS = 12e3;\nvar ENVELOPE_BYTES2 = 64 * 1024;\nvar encoder5 = new TextEncoder();\nfunction unavailable() {\n return handleError(\n \"PARALL_READ_UNAVAILABLE\",\n \"Parall data could not be read just now; nothing changed, so the get can be retried\"\n );\n}\nfunction refsOf(req) {\n const refs = typeof req === \"object\" && req !== null ? req.refs : null;\n if (!Array.isArray(refs) || refs.length === 0 || refs.length > PARALL_MAX_REFS || !refs.every((ref) => typeof ref === \"string\")) {\n throw handleError(\n \"ACTION_INVALID_CALL\",\n `get takes a list of 1 to ${PARALL_MAX_REFS} references (strings)`\n );\n }\n return refs;\n}\nfunction isItem(v) {\n if (typeof v !== \"object\" || v === null) return false;\n const i = v;\n if (i.ok === true)\n return typeof i.type === \"string\" && typeof i.item === \"object\" && i.item !== null;\n return i.ok === false && typeof i.code === \"string\";\n}\nfunction createParallCaller(cfg, state) {\n const fetchImpl = cfg.fetchImpl ?? fetch;\n const now = cfg.now ?? Date.now;\n const url = `${cfg.callbackOrigin.replace(/\\/+$/, \"\")}/api/v1/mini-app-actions/parall/get`;\n async function send(body, count) {\n const headers = {\n \"Content-Type\": \"application/json\",\n \"User-Agent\": USER_AGENT,\n [TICKET_HEADER]: cfg.ticket,\n [INVOCATION_HEADER]: cfg.invocationId\n };\n if (cfg.instance !== \"default\") headers[SWIMLANE_HEADER] = cfg.instance;\n let res;\n try {\n res = await fetchImpl(url, {\n method: \"POST\",\n headers,\n body,\n signal: AbortSignal.timeout(\n Math.max(1, Math.min(PARALL_GET_TIMEOUT_MS, cfg.deadlineMs - now()))\n )\n });\n } catch {\n if (now() >= cfg.deadlineMs) {\n throw handleError(\"ACTION_DEADLINE\", \"the action ran past its deadline\");\n }\n throw unavailable();\n }\n let parsed;\n try {\n const text = await readCapped(res, cfg.maxBytes + ENVELOPE_BYTES2);\n parsed = text ? JSON.parse(text) : null;\n } catch {\n throw unavailable();\n }\n if (res.ok) {\n const a = parsed;\n if (a?.ok === true && Array.isArray(a.value) && a.value.length === count && a.value.every(isItem)) {\n return a.value;\n }\n throw unavailable();\n }\n const env = parsed?.error;\n if (typeof env?.code !== \"string\") throw unavailable();\n throw handleError(\n env.code,\n typeof env.message === \"string\" ? env.message : `the get was refused (${res.status})`\n );\n }\n async function get(req) {\n if (state.revoked) throw handleError(\"ACTION_HANDLE_REVOKED\", \"this handle is no longer valid\");\n if (cfg.maxReads <= 0) {\n throw handleError(\n \"PARALL_READ_UNAVAILABLE\",\n \"actions cannot read Parall data on this deployment\"\n );\n }\n if (now() >= cfg.deadlineMs)\n throw handleError(\"ACTION_DEADLINE\", \"the action ran past its deadline\");\n const refs = refsOf(req);\n if (state.parallReads >= cfg.maxReads) {\n state.parallLimitHit = true;\n throw handleError(\n \"ACTION_LIMIT_EXCEEDED\",\n `an action may read Parall data at most ${cfg.maxReads} times`\n );\n }\n const body = JSON.stringify({ refs });\n if (encoder5.encode(body).byteLength > cfg.maxBytes) {\n throw handleError(\n \"ACTION_INVALID_CALL\",\n `a get's references may be at most ${cfg.maxBytes} bytes in all`\n );\n }\n state.parallReads++;\n const pending = send(body, refs.length);\n state.inflight.add(pending);\n try {\n return await pending;\n } finally {\n state.inflight.delete(pending);\n }\n }\n return { get };\n}\n\n// ../actions-worker/src/sandbox.ts\nvar COMPATIBILITY_DATE = \"2026-04-01\";\nvar COMPATIBILITY_FLAGS = [];\nvar ENTRYPOINT = \"ActionRunner\";\nvar PRELUDE = `// Runs before the author module (see actions-worker src/sandbox.ts).\nfor (const name of ['caches', 'WebSocket']) {\n try {\n delete globalThis[name];\n } catch {}\n if (name in globalThis) {\n Object.defineProperty(globalThis, name, { value: undefined, writable: false, configurable: false });\n }\n}\n`;\nvar ENTRY = `import './prelude.js';\nexport * from './author.js';\n`;\nfunction workerCode(authorSource) {\n return {\n compatibilityDate: COMPATIBILITY_DATE,\n compatibilityFlags: COMPATIBILITY_FLAGS,\n mainModule: \"entry.js\",\n modules: { \"entry.js\": ENTRY, \"prelude.js\": PRELUDE, \"author.js\": authorSource },\n env: {},\n globalOutbound: null\n };\n}\nvar runtimeVersion = null;\nfunction runtimeVersionOf() {\n if (!runtimeVersion) {\n const material = JSON.stringify([\n COMPATIBILITY_DATE,\n COMPATIBILITY_FLAGS,\n ENTRYPOINT,\n PRELUDE,\n ENTRY,\n \"env:{}\",\n \"outbound:null\"\n ]);\n runtimeVersion = crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(material)).then(\n (d) => Array.from(new Uint8Array(d).slice(0, 8), (b) => b.toString(16).padStart(2, \"0\")).join(\"\")\n );\n }\n return runtimeVersion;\n}\nfunction isolateId(instance, appId, sha256, runtime) {\n return `${instance}:${appId}:${sha256}:${runtime}`;\n}\n\n// ../actions-worker/src/run.ts\nvar DEADLINE_MARGIN_MS = 250;\nasync function runWithDeadline(call, budgetMs) {\n if (budgetMs <= 0) return { kind: \"timeout\" };\n let timer = null;\n const timedOut = new Promise((resolve) => {\n timer = setTimeout(() => resolve({ kind: \"timeout\" }), budgetMs);\n });\n try {\n return await Promise.race([\n call().then(\n (value) => ({ kind: \"result\", value }),\n (error) => ({ kind: \"thrown\", error })\n ),\n timedOut\n ]);\n } finally {\n if (timer !== null) clearTimeout(timer);\n }\n}\nasync function runInvocation(worker, req, opts) {\n const { callbackOrigin, loadFailure = () => null } = opts;\n const effectiveDeadline = req.deadline_ms - DEADLINE_MARGIN_MS;\n const caller = createDbCaller({\n kind: req.kind,\n ticket: req.ticket,\n invocationId: req.invocation_id,\n instance: req.instance,\n callbackOrigin,\n deadlineMs: effectiveDeadline,\n limits: req.limits\n });\n const clip = createClipCaller(\n {\n enabled: req.clip,\n ticket: req.ticket,\n invocationId: req.invocation_id,\n instance: req.instance,\n callbackOrigin,\n deadlineMs: effectiveDeadline,\n maxCalls: req.limits.clip_calls,\n maxBytes: req.limits.result_bytes\n },\n caller.state\n );\n const net = netLimits(req.limits);\n const netCaller = createNetCaller(\n {\n mode: opts.netMode,\n ticket: req.ticket,\n invocationId: req.invocation_id,\n instance: req.instance,\n callbackOrigin,\n deadlineMs: effectiveDeadline,\n maxRequests: net.requests,\n maxInFlight: net.inFlight,\n policy: opts.netPolicy\n },\n caller.state\n );\n const parall = createParallCaller(\n {\n ticket: req.ticket,\n invocationId: req.invocation_id,\n instance: req.instance,\n callbackOrigin,\n deadlineMs: effectiveDeadline,\n maxReads: parallReads(req.limits),\n maxBytes: req.limits.result_bytes\n },\n caller.state\n );\n const handle = makeHandle(caller, clip, netCaller, parall);\n const entry = worker.getEntrypoint(ENTRYPOINT, { limits: { cpuMs: req.limits.cpu_ms } });\n const settled = await runWithDeadline(\n () => entry.run(\n {\n action: req.action,\n params: req.params,\n viewer: req.viewer,\n app: req.app,\n invocation_id: req.invocation_id,\n // The app's secrets, as ctx.env (mini-app-network-design.md §7.4):\n // per call, never in the isolate's own env.\n env: req.env ?? {},\n // How many requests the SDK lets run at once; it queues the rest.\n net_in_flight: net.inFlight\n },\n handle\n ),\n effectiveDeadline - Date.now()\n );\n const drained = await settle(caller, effectiveDeadline);\n if (settled.kind === \"timeout\" || !drained || caller.state.indeterminate) {\n return timeoutOutcome(caller.state);\n }\n if (settled.kind === \"thrown\") {\n return loadFailure() ?? outcomeFromThrown(settled.error, req.limits, caller.state);\n }\n return outcomeFromResult(settled.value, req.limits, caller.state);\n}\n\n// ../actions-worker/src/local.ts\nvar local_default = {\n async fetch(request, env) {\n let body;\n try {\n body = await request.json();\n } catch {\n return Response.json({ error: \"body is not JSON\" }, { status: 400 });\n }\n const req = parseInvokeRequest(body?.request, { unpublished: true });\n if (typeof req === \"string\") return Response.json({ error: `invalid ${req}` }, { status: 400 });\n if (typeof body.source !== \"string\" || typeof body.callback_origin !== \"string\") {\n return Response.json({ error: \"source and callback_origin are required\" }, { status: 400 });\n }\n const runtime = await runtimeVersionOf();\n const worker = env.LOADER.get(\n isolateId(req.instance, req.app.id, req.module.sha256, runtime),\n async () => workerCode(body.source)\n );\n return Response.json(\n await runInvocation(worker, req, {\n callbackOrigin: body.callback_origin,\n netPolicy: policyFrom(\n env.NET_BLOCKED_HOSTS,\n env.NET_TEST_ALLOW_LOOPBACK,\n body.callback_origin\n ),\n netMode: \"direct\"\n })\n );\n }\n};\nexport {\n local_default as default\n};\n";
@@ -3,7 +3,7 @@ export const APP_TEMPLATES = [
3
3
  "id": "pipeline",
4
4
  "intro": {
5
5
  "id": "pipeline",
6
- "cli": "1.79.0",
6
+ "cli": "1.80.0",
7
7
  "name": {
8
8
  "en": "Customer / partner pipeline",
9
9
  "zh": "客户 / 合作管线"
@@ -196,14 +196,14 @@ export const APP_TEMPLATES = [
196
196
  }
197
197
  ]
198
198
  },
199
- "skill": "# 应用模板:客户 / 合作管线(pipeline)\n\n有人要一个跟进客户、品牌商单或达人合作的 app 时,照这份 skill 做:先和发起的人对清楚、讲明要读哪些数据,对方同意后用模板源码和组织里的真数据建好 app,配好叫醒,之后每次被叫醒照「平时」一节做。建 app 的通用做法、PostgreSQL 写法和订阅数据变化的写法在能力说明和脚手架的 `AGENTS.md` 里,这里只写这个模板特有的。\n\n用对方的语言和对方说话;app 里的阶段名和文案也用对方团队的说法。\n\n## 1. 对齐\n\n在私信里一条消息问完下面几件事,每件带上默认值;对方没答的按默认:\n\n1. 跟进的是什么(客户、品牌商单、达人合作……),阶段怎么叫。默认:模板自带的 询价 → 报价 → 签约 → 执行 → 结款。\n2. 这些信息现在记在哪:表格、某个频道、邮件、任务还是 Wiki。默认:只用对方在私信里发给你的内容。\n3. 谁负责跟进,要不要按人分开看。默认:发起人自己负责,看板上可以按负责人筛选。\n4. 金额要不要录进来(录了能打开这个 app 的人都看得到)。默认:不录。\n5. 每天几点巡检一遍,用哪个时区。默认:每天 9:00,发起人所在的时区。\n\n## 2. 讲明数据\n\n同一条消息里,在读任何数据之前讲明:\n\n- 要读哪些:具体到哪个频道、哪些任务、哪几篇 Wiki、组织层的哪个连接,读多久以前的。\n- 读到的什么会写进 app:合作方、联系人、阶段、金额(如果录)、下一步和往来摘要。\n- 写进 app 后默认组织里所有人都能看到;要只给少数人看,把 app 的「组织里的其他人」设成不可读,再单独加人。写类调用的参数记在调用记录里,能打开这个 app 的人都能查。\n- 你读不到的:请对方把你拉进频道,或者按审批卡申请连接,不绕路。\n\n对方同意之前,不读这些数据,也不建 app。\n\n要读的内容里,发起人自己看不到的(发起人不在的频道——公开频道也一样,非成员读不到消息;发起人没有权限的任务或 Wiki;别人的个人连接),先在私信里问你的负责人,没有负责人就问 org admin:说清是谁要建什么、要读哪些内容、写进 app 后谁能看到(默认组织里所有人)。他同意了才读这部分;不同意,就只用发起人看得到的。拿不准发起人看不看得到,按看不到处理。频道看成员名单:`parall chats members list <chat>`。\n\n## 3. 建\n\n1. `parall app create --name \"<名字>\"`,记下 `app_…`。对方要只给少数人看的,建的时候加 `--members none`(先建开放的再改,名字已经出现在别人的列表里),建好后用 `parall app access add <app_…> <usr_…> --level read` 逐个加人,要能改的用 `--level write`。\n2. `parall app init <dir> --template pipeline --app <app_…>`:写出模板源码和这份 skill(项目根目录的 `SKILL.md`)。这个 app 的 Database 在 TiDB 上时它会拒绝:照它的说明告诉对方,不要自己改写成 MySQL。\n3. 按回答改:阶段在 `shared/pipeline.ts` 的 `STAGES`(改名就改 `en` / `zh`,`id` 是存进数据的值),不录金额就把 `AMOUNTS` 改成 `false`,币种是 `CURRENCY`;文案在 `src/pages/*/messages.ts`;要多记的字段,在 `db/schema.sql` 加列(`ALTER TABLE … ADD COLUMN IF NOT EXISTS`),再改 `actions/` 和页面。\n4. 建表:`parall app db exec --app <app_…> --file db/schema.sql`。\n5. 导入真数据,只从对方同意的来源:合作方进 `partners`(同名按 `lower(name)` 去重),每个合作进 `deals`,往来进 `activities`(`source` 写来源,比如 `#商务合作`、`Gmail`;你整理的写 `by_agent = true`)。负责人写成员的 `usr_…` 和名字。读不到的字段留空:不猜金额、日期或联系方式,不编合作方或往来。一次 exec 最多 256 KiB,大的分几次。\n6. `pnpm install && pnpm build` → `parall app check dist` → `parall app publish dist --app <app_…> --source .`。\n\n## 4. 叫醒\n\n- 订阅这个 app 的数据变化,只盯 `deals` 与 `activities`:`parall triggers create --source-kind platform_event --event-types app.data.changed --name \"<app 名>有写入\" --target-ids <你的 usr_…> --filter '…' --template '…'`。过滤条件写这个 app(`\"<app_…>\" in entity.app_ids`)和这两张表(`entity.tables != null && (\"deals\" in entity.tables || \"activities\" in entity.tables)`;过滤条件不支持 `exists` 这类循环宏)。`--template` 是叫醒你时发来的话(Liquid),写明是哪个 app、怎么处理,比如 `「<app 名>」prll://<app_…> 有新写入:表 {{ entity.tables | json }},写入的人 {{ entity.actor_ids | json }}。照 <dir>/SKILL.md 的「平时」处理。`\n- 再建一个每天一次的定时任务,时间按对方说的:`parall schedules create --name \"…\" --description \"…\" --target-ids <你的 usr_…> --cron-expr \"0 9 * * *\" --timezone <对方的时区>`;`--description` 写清这是哪个 app 的巡检、照 `SKILL.md` 的「平时」做。\n- 你自己写入不会叫醒你。平时读数据用 `parall app db query`:用 `parall app db exec` 跑查询也算一次写入,而且表名记为未知,按表过滤就失效了。\n\n## 5. 交付\n\n在私信里回 app 链接(`prll://app_…`),说明导入了什么(几个合作方、几个合作、几条往来,各来自哪里)、什么时候会被叫醒(有人在 app 里改阶段或加记录时,以及每天几点),问要不要发到频道。\n\n## 6. 平时\n\n- 每天的巡检:读进行中的合作(`parall app db query`)。下一步今天到期或已经逾期的,写清为什么要跟进,再替负责人起草一条跟进消息:`parall app action run <app_…> followups_draft --params '{\"id\": \"<deal id>\", \"reason\": \"…\", \"draft\": \"…\"}'`,页面「今天该跟进」就会列出来。在一个阶段停了太久(默认 14 天没有变化)的,私信提醒负责人。\n- 有人在 app 里写入时:看改了什么。下一步空了的,按往来记录补上下一步和日期;拿不准就问负责人。\n- 只读对方同意过的来源。要读新的来源,先按「讲明数据」再问一次。\n- 改 app 前,本地没有项目就先 `parall app pull <app_…> --out <dir>` 取回当前版本的源码。\n- 要人拍板的事去问,不替人决定:改金额、改负责人、把合作标为完成或未成、删除合作方或合作。\n",
199
+ "skill": "# 应用模板:客户 / 合作管线(pipeline)\n\n有人要一个跟进客户、品牌商单或达人合作的 app 时,照这份 skill 做:先和发起的人对清楚、讲明要读哪些数据,对方同意后用模板源码和组织里的真数据建好 app,配好叫醒,之后每次被叫醒照「平时」一节做。建 app 的通用做法、PostgreSQL 写法和订阅数据变化的写法在能力说明和脚手架的 `AGENTS.md` 里,这里只写这个模板特有的。\n\n用对方的语言和对方说话;app 里的阶段名和文案也用对方团队的说法。\n\n## 1. 对齐\n\n在私信里一条消息问完下面几件事,每件带上默认值;对方没答的按默认:\n\n1. 跟进的是什么(客户、品牌商单、达人合作……),阶段怎么叫。默认:模板自带的 询价 → 报价 → 签约 → 执行 → 结款。\n2. 这些信息现在记在哪:表格、某个频道、邮件、任务还是 Wiki。默认:只用对方在私信里发给你的内容。\n3. 谁负责跟进,要不要按人分开看。默认:发起人自己负责,看板上可以按负责人筛选。\n4. 金额要不要录进来(录了能打开这个 app 的人都看得到)。默认:不录。\n5. 每天几点巡检一遍,用哪个时区。默认:每天 9:00,发起人所在的时区。\n\n## 2. 讲明数据\n\n同一条消息里,在读任何数据之前讲明:\n\n- 要读哪些:具体到哪个频道、哪些任务、哪几篇 Wiki、组织层的哪个连接,读多久以前的。\n- 读到的什么会写进 app:合作方、联系人、阶段、金额(如果录)、下一步和往来摘要。\n- 写进 app 后默认组织里所有人都能看到;要只给少数人看,把 app 的「组织里的其他人」设成不可读,再单独加人。写类调用的参数记在调用记录里,只有作者、组织 owner / admin 和调用者本人看得到。\n- 你读不到的:请对方把你拉进频道,或者按审批卡申请连接,不绕路。\n\n对方同意之前,不读这些数据,也不建 app。\n\n要读的内容里,发起人自己看不到的(发起人不在的频道——公开频道也一样,非成员读不到消息;发起人没有权限的任务或 Wiki;别人的个人连接),先在私信里问你的负责人,没有负责人就问 org admin:说清是谁要建什么、要读哪些内容、写进 app 后谁能看到(默认组织里所有人)。他同意了才读这部分;不同意,就只用发起人看得到的。拿不准发起人看不看得到,按看不到处理。频道看成员名单:`parall chats members list <chat>`。\n\n## 3. 建\n\n1. `parall app create --name \"<名字>\"`,记下 `app_…`。对方要只给少数人看的,建的时候加 `--members none`(先建开放的再改,名字已经出现在别人的列表里),建好后用 `parall app access add <app_…> <usr_…> --level read` 逐个加人,要能改的用 `--level write`。\n2. `parall app init <dir> --template pipeline --app <app_…>`:写出模板源码和这份 skill(项目根目录的 `SKILL.md`)。这个 app 的 Database 在 TiDB 上时它会拒绝:照它的说明告诉对方,不要自己改写成 MySQL。\n3. 按回答改:阶段在 `shared/pipeline.ts` 的 `STAGES`(改名就改 `en` / `zh`,`id` 是存进数据的值),不录金额就把 `AMOUNTS` 改成 `false`,币种是 `CURRENCY`;文案在 `src/pages/*/messages.ts`;要多记的字段,在 `db/schema.sql` 加列(`ALTER TABLE … ADD COLUMN IF NOT EXISTS`),再改 `actions/` 和页面。\n4. 建表:`parall app db exec --app <app_…> --file db/schema.sql`。\n5. 导入真数据,只从对方同意的来源:合作方进 `partners`(同名按 `lower(name)` 去重),每个合作进 `deals`,往来进 `activities`(`source` 写来源,比如 `#商务合作`、`Gmail`;你整理的写 `by_agent = true`)。负责人写成员的 `usr_…` 和名字。读不到的字段留空:不猜金额、日期或联系方式,不编合作方或往来。一次 exec 最多 256 KiB,大的分几次。\n6. `pnpm install && pnpm build` → `parall app check dist` → `parall app publish dist --app <app_…> --source .`。\n\n## 4. 叫醒\n\n- 订阅这个 app 的数据变化,只盯 `deals` 与 `activities`:`parall triggers create --source-kind platform_event --event-types app.data.changed --name \"<app 名>有写入\" --target-ids <你的 usr_…> --filter '…' --template '…'`。过滤条件写这个 app(`\"<app_…>\" in entity.app_ids`)和这两张表(`entity.tables != null && (\"deals\" in entity.tables || \"activities\" in entity.tables)`;过滤条件不支持 `exists` 这类循环宏)。`--template` 是叫醒你时发来的话(Liquid),写明是哪个 app、怎么处理,比如 `「<app 名>」prll://<app_…> 有新写入:表 {{ entity.tables | json }},写入的人 {{ entity.actor_ids | json }}。照 <dir>/SKILL.md 的「平时」处理。`\n- 再建一个每天一次的定时任务,时间按对方说的:`parall schedules create --name \"…\" --description \"…\" --target-ids <你的 usr_…> --cron-expr \"0 9 * * *\" --timezone <对方的时区>`;`--description` 写清这是哪个 app 的巡检、照 `SKILL.md` 的「平时」做。\n- 你自己写入不会叫醒你。平时读数据用 `parall app db query`:用 `parall app db exec` 跑查询也算一次写入,而且表名记为未知,按表过滤就失效了。\n\n## 5. 交付\n\n在私信里回 app 链接(`prll://app_…`),说明导入了什么(几个合作方、几个合作、几条往来,各来自哪里)、什么时候会被叫醒(有人在 app 里改阶段或加记录时,以及每天几点),问要不要发到频道。\n\n## 6. 平时\n\n- 每天的巡检:读进行中的合作(`parall app db query`)。下一步今天到期或已经逾期的,写清为什么要跟进,再替负责人起草一条跟进消息:`parall app action run <app_…> followups_draft --params '{\"id\": \"<deal id>\", \"reason\": \"…\", \"draft\": \"…\"}'`,页面「今天该跟进」就会列出来。在一个阶段停了太久(默认 14 天没有变化)的,私信提醒负责人。\n- 有人在 app 里写入时:看改了什么。下一步空了的,按往来记录补上下一步和日期;拿不准就问负责人。\n- 只读对方同意过的来源。要读新的来源,先按「讲明数据」再问一次。\n- 改 app 前,本地没有项目就先 `parall app pull <app_…> --out <dir>` 取回当前版本的源码。\n- 要人拍板的事去问,不替人决定:改金额、改负责人、把合作标为完成或未成、删除合作方或合作。\n",
200
200
  "overlay": {
201
201
  "_overlay.json": "{\n \"remove\": [\"public/manifest.json\", \"src/pages/items\", \"actions/items.ts\", \"shared/items.ts\"],\n \"blocks\": []\n}\n",
202
202
  "actions/checks.ts": "import { STAGES } from '@shared/pipeline';\nimport { ActionError } from './parall-actions';\n\n// Checks the pipeline's actions share. The platform has already checked the\n// params against public/manifest.json; these are the rules a JSON Schema\n// cannot say. Messages reach the caller as they are (ActionError).\n\nconst UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\nconst DATE = /^\\d{4}-\\d{2}-\\d{2}$/;\n\n/** An id of a row; anything else cannot exist. */\nexport function uuid(id: unknown, what: string): string {\n if (typeof id !== 'string' || !UUID.test(id)) {\n throw new ActionError(`This ${what} does not exist.`);\n }\n return id;\n}\n\n/** A YYYY-MM-DD that is a real day; '' or nothing is null. */\nexport function optionalDate(value: string | undefined, field: string): string | null {\n if (!value) return null;\n const day = new Date(`${value}T00:00:00Z`);\n if (!DATE.test(value) || Number.isNaN(day.getTime()) || !day.toISOString().startsWith(value)) {\n throw new ActionError(`${field} is not a date (YYYY-MM-DD).`);\n }\n return value;\n}\n\n/** Trimmed text, required. */\nexport function required(value: string | undefined, field: string): string {\n const text = (value ?? '').trim();\n if (!text) throw new ActionError(`${field} is required.`);\n return text;\n}\n\n/** A stage of shared/pipeline.ts. */\nexport function stage(id: string): string {\n if (!STAGES.some((s) => s.id === id)) {\n throw new ActionError(\n `Unknown stage ${JSON.stringify(id)}; the stages are ${STAGES.map((s) => s.id).join(', ')}.`,\n );\n }\n return id;\n}\n\n/** An amount of money: a finite number, not negative; nothing is null. */\nexport function amount(value: number | undefined): number | null {\n if (value === undefined) return null;\n if (!Number.isFinite(value) || value < 0) throw new ActionError('The amount is not valid.');\n return Math.round(value * 100) / 100;\n}\n",
203
203
  "actions/deals.ts": "import type {\n Deal,\n DealInput,\n DealMoveInput,\n FollowupDoneInput,\n FollowupDraftInput,\n FollowupSnoozeInput,\n} from '@shared/pipeline';\nimport { DEAL_STATUSES } from '@shared/pipeline';\nimport { amount, optionalDate, required, stage, uuid } from './checks';\nimport { type ActionContext, ActionError } from './parall-actions';\nimport { rememberViewer } from './people';\n\n// Deals and the follow-ups on them (src/pages/board, src/pages/followups).\n// Everyone who can open the app (by default, the whole organization) reads\n// every deal, and those who can change it create, edit and move deals and\n// mark follow-ups done; a deal is deleted by its creator or an org\n// owner/admin. Tighten these here: past the app's access setting, the\n// actions are the only gate.\n\nconst DEAL_COLUMNS = `d.id, d.partner_id, p.name AS partner_name, d.title, d.stage, d.status,\n d.amount, d.owner_id, d.owner_name, d.next_step,\n to_char(d.next_step_due, 'YYYY-MM-DD') AS next_step_due,\n d.followup_reason, d.followup_draft, d.followup_by_name, d.created_by, d.updated_at`;\n// $1 = ctx.viewer.id, $2 = ctx.viewer.role\nconst CAN_DELETE = `(d.created_by = $1 OR $2 IN ('owner', 'admin'))`;\n\nexport async function readDeals(ctx: ActionContext, where: string, params: unknown[]) {\n const { rows } = await ctx.db.query(\n `SELECT ${DEAL_COLUMNS}, ${CAN_DELETE} AS can_delete\n FROM deals d JOIN partners p ON p.id = d.partner_id\n WHERE ${where}\n ORDER BY d.next_step_due NULLS LAST, d.updated_at DESC\n LIMIT 2000`,\n [ctx.viewer.id, ctx.viewer.role, ...params],\n );\n return rows as unknown as Deal[];\n}\n\nasync function readDeal(ctx: ActionContext, id: string): Promise<Deal> {\n const [deal] = await readDeals(ctx, 'd.id = $3', [id]);\n if (!deal) throw new ActionError('This deal does not exist.');\n return deal;\n}\n\n/** The deal's partner: partner_id, or the partner of that name (created\n * when there is none). */\nasync function partnerFor(ctx: ActionContext, input: DealInput): Promise<string> {\n if (input.partner_id) {\n const id = uuid(input.partner_id, 'partner');\n const { rows } = await ctx.db.query(`SELECT id FROM partners WHERE id = $1`, [id]);\n if (!rows[0]) throw new ActionError('This partner does not exist.');\n return id;\n }\n const name = required(input.partner_name, 'The partner');\n // The no-op update makes RETURNING give the existing partner's id.\n const { rows } = await ctx.db.exec(\n `INSERT INTO partners (name, owner_id, owner_name, created_by, created_by_name)\n VALUES ($1, $2, $3, $4, $5)\n ON CONFLICT ((lower(name))) DO UPDATE SET name = partners.name\n RETURNING id`,\n [\n name,\n input.owner_id || null,\n input.owner_id ? (input.owner_name ?? null) : null,\n ctx.viewer.id,\n ctx.viewer.display_name,\n ],\n );\n return rows[0]?.id as string;\n}\n\nexport const dealActions = {\n /** read: the open deals — the board and the follow-ups page. */\n async pipeline_board(ctx: ActionContext): Promise<Deal[]> {\n return readDeals(ctx, `d.status = 'open'`, []);\n },\n\n /** write: creates a deal (no id) or rewrites one; see DealInput. */\n async deals_save(ctx: ActionContext, input: DealInput): Promise<Deal> {\n const id = input.id === undefined ? null : uuid(input.id, 'deal');\n const title = required(input.title, 'A title');\n const stageId = stage(input.stage);\n const value = amount(input.amount);\n const due = optionalDate(input.next_step_due, 'next_step_due');\n const ownerId = input.owner_id || null;\n const ownerName = ownerId ? (input.owner_name ?? '').trim() || null : null;\n const nextStep = (input.next_step ?? '').trim();\n if (id !== null) {\n // Before partnerFor: an edit of a deal that is gone must not leave a new partner behind.\n const { rows } = await ctx.db.query(`SELECT 1 FROM deals WHERE id = $1`, [id]);\n if (!rows[0]) throw new ActionError('This deal does not exist.');\n }\n const partnerId = await partnerFor(ctx, input);\n\n if (id === null) {\n const { results } = await ctx.db.batch([\n rememberViewer(ctx),\n {\n sql: `INSERT INTO deals (partner_id, title, stage, amount, owner_id, owner_name,\n next_step, next_step_due, created_by, created_by_name)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)\n RETURNING id`,\n params: [\n partnerId,\n title,\n stageId,\n value,\n ownerId,\n ownerName,\n nextStep,\n due,\n ctx.viewer.id,\n ctx.viewer.display_name,\n ],\n },\n ]);\n return readDeal(ctx, results[1]?.rows[0]?.id as string);\n }\n\n const { results } = await ctx.db.batch([\n rememberViewer(ctx),\n {\n sql: `UPDATE deals\n SET partner_id = $1, title = $2, stage = $3, amount = $4, owner_id = $5,\n owner_name = $6, next_step = $7, next_step_due = $8, updated_at = now()\n WHERE id = $9`,\n params: [partnerId, title, stageId, value, ownerId, ownerName, nextStep, due, id],\n },\n ]);\n if (!results[1]?.rows_affected) throw new ActionError('This deal does not exist.');\n return readDeal(ctx, id);\n },\n\n /** write: moves a deal to another stage and/or closes or reopens it. */\n async deals_move(ctx: ActionContext, input: DealMoveInput): Promise<Deal> {\n const id = uuid(input.id, 'deal');\n if (input.stage === undefined && input.status === undefined) {\n throw new ActionError('Give a stage or a status.');\n }\n const stageId = input.stage === undefined ? null : stage(input.stage);\n if (input.status !== undefined && !DEAL_STATUSES.includes(input.status)) {\n throw new ActionError(`Unknown status ${input.status}.`);\n }\n const { results } = await ctx.db.batch([\n rememberViewer(ctx),\n {\n sql: `UPDATE deals\n SET stage = COALESCE($1, stage), status = COALESCE($2, status), updated_at = now()\n WHERE id = $3`,\n params: [stageId, input.status ?? null, id],\n },\n ]);\n if (!results[1]?.rows_affected) throw new ActionError('This deal does not exist.');\n return readDeal(ctx, id);\n },\n\n /** write: deletes a deal; its history stays with the partner. */\n async deals_delete(ctx: ActionContext, params: { id: string }): Promise<{ id: string }> {\n const id = uuid(params.id, 'deal');\n const { rows_affected } = await ctx.db.exec(\n `DELETE FROM deals d WHERE d.id = $3 AND ${CAN_DELETE}`,\n [ctx.viewer.id, ctx.viewer.role, id],\n );\n if (rows_affected === 0) {\n throw new ActionError('Only its creator or an org admin can delete this deal.');\n }\n return { id };\n },\n\n /** write: the owner followed up. The note goes into the partner's\n * history and the next step is cleared, for the agent (or a person) to\n * set the following one. */\n async followups_done(ctx: ActionContext, input: FollowupDoneInput): Promise<Deal> {\n const id = uuid(input.id, 'deal');\n const note = required(input.note, 'A note');\n const { results } = await ctx.db.batch([\n rememberViewer(ctx),\n {\n sql: `INSERT INTO activities (partner_id, deal_id, kind, body, actor_name, created_by,\n created_by_name, by_agent)\n SELECT partner_id, id, 'note', $2::text, $3::text, $4::text, $3::text, $5::boolean\n FROM deals WHERE id = $1 AND status = 'open'`,\n params: [id, note, ctx.viewer.display_name, ctx.viewer.id, ctx.viewer.is_agent],\n },\n {\n sql: `UPDATE deals\n SET next_step = '', next_step_due = NULL, followup_reason = '',\n followup_draft = '', followup_by_name = '', updated_at = now()\n WHERE id = $1 AND status = 'open'`,\n params: [id],\n },\n ]);\n if (!results[2]?.rows_affected) throw new ActionError('This deal is closed or was deleted.');\n return readDeal(ctx, id);\n },\n\n /** write: moves the deal's next step to another day. */\n async followups_snooze(ctx: ActionContext, input: FollowupSnoozeInput): Promise<Deal> {\n const id = uuid(input.id, 'deal');\n const until = optionalDate(input.until, 'until');\n if (!until) throw new ActionError('Give the day to move the follow-up to.');\n const { results } = await ctx.db.batch([\n rememberViewer(ctx),\n {\n sql: `UPDATE deals SET next_step_due = $1, updated_at = now()\n WHERE id = $2 AND status = 'open'`,\n params: [until, id],\n },\n ]);\n if (!results[1]?.rows_affected) throw new ActionError('This deal is closed or was deleted.');\n return readDeal(ctx, id);\n },\n\n /** write (the agent's daily run): why to follow up the deal and the\n * message drafted for its owner; due also sets the next step's day. */\n async followups_draft(ctx: ActionContext, input: FollowupDraftInput): Promise<Deal> {\n const id = uuid(input.id, 'deal');\n const due = optionalDate(input.due, 'due');\n const { results } = await ctx.db.batch([\n rememberViewer(ctx),\n {\n sql: `UPDATE deals\n SET followup_reason = $1, followup_draft = $2, followup_by_name = $3,\n next_step_due = COALESCE($4::date, next_step_due), updated_at = now()\n WHERE id = $5 AND status = 'open'`,\n params: [input.reason.trim(), input.draft.trim(), ctx.viewer.display_name, due, id],\n },\n ]);\n if (!results[1]?.rows_affected) throw new ActionError('This deal is closed or was deleted.');\n return readDeal(ctx, id);\n },\n};\n",
204
204
  "actions/index.ts": "import { dealActions } from './deals';\nimport { defineActions } from './parall-actions';\nimport { partnerActions } from './partners';\nimport { peopleActions } from './people';\n// parall:action-imports — `parall app add` puts block imports above this line.\n\n// Every action is declared in public/manifest.json under actions.functions\n// (kind read | write, params as a JSON Schema) and implemented here;\n// `parall app check dist` compares the two, and publish runs it too. The\n// loader looks the module up by the export name ActionRunner.\nexport const ActionRunner = defineActions({\n ...peopleActions,\n ...dealActions,\n ...partnerActions,\n // parall:actions — `parall app add` puts block actions above this line.\n});\n",
205
205
  "actions/partners.ts": "import type {\n Activity,\n ActivityInput,\n Partner,\n PartnerDetail,\n PartnerInput,\n PartnerSummary,\n} from '@shared/pipeline';\nimport { ACTIVITY_KINDS } from '@shared/pipeline';\nimport { required, uuid } from './checks';\nimport { readDeals } from './deals';\nimport { type ActionContext, ActionError } from './parall-actions';\nimport { rememberViewer } from './people';\n\n// Partners and their history (src/pages/partners). Everyone who can open\n// the app (by default, the whole organization) reads every partner, and those\n// who can change it edit partners and add to their history.\n\nconst PARTNER_COLUMNS = `p.id, p.name, p.kind, p.contact_name, p.contact_phone, p.contact_email,\n p.owner_id, p.owner_name, p.notes, p.updated_at`;\nconst ACTIVITY_COLUMNS = `a.id, a.partner_id, a.deal_id, a.kind, a.body, a.happened_at,\n a.actor_name, a.source, a.by_agent`;\n\nasync function readPartner(ctx: ActionContext, id: string): Promise<Partner> {\n const { rows } = await ctx.db.query(`SELECT ${PARTNER_COLUMNS} FROM partners p WHERE p.id = $1`, [\n id,\n ]);\n if (!rows[0]) throw new ActionError('This partner does not exist.');\n return rows[0] as unknown as Partner;\n}\n\n/** Another partner already has this name, whatever the case. */\nasync function nameTaken(ctx: ActionContext, name: string, id: string | null): Promise<boolean> {\n const { rows } = await ctx.db.query(\n `SELECT 1 FROM partners WHERE lower(name) = lower($1) AND id IS DISTINCT FROM $2::uuid`,\n [name, id],\n );\n return rows.length > 0;\n}\n\nexport const partnerActions = {\n /** read: every partner with its open deals, the amounts of its deals and\n * when it was last in touch. */\n async partners_list(ctx: ActionContext): Promise<PartnerSummary[]> {\n const { rows } = await ctx.db.query(\n `SELECT ${PARTNER_COLUMNS},\n (SELECT count(*) FROM deals d\n WHERE d.partner_id = p.id AND d.status = 'open')::int AS open_deals,\n (SELECT sum(d.amount) FROM deals d\n WHERE d.partner_id = p.id AND d.status <> 'lost') AS total_amount,\n (SELECT max(a.happened_at) FROM activities a\n WHERE a.partner_id = p.id) AS last_activity_at\n FROM partners p\n ORDER BY last_activity_at DESC NULLS LAST, p.name\n LIMIT 1000`,\n );\n return rows as unknown as PartnerSummary[];\n },\n\n /** read: one partner, all its deals and its history, newest first. */\n async partner_get(ctx: ActionContext, params: { id: string }): Promise<PartnerDetail> {\n const id = uuid(params.id, 'partner');\n const partner = await readPartner(ctx, id);\n const deals = await readDeals(ctx, 'd.partner_id = $3', [id]);\n const { rows } = await ctx.db.query(\n `SELECT ${ACTIVITY_COLUMNS} FROM activities a\n WHERE a.partner_id = $1\n ORDER BY a.happened_at DESC\n LIMIT 500`,\n [id],\n );\n return { partner, deals, activities: rows as unknown as Activity[] };\n },\n\n /** write: creates a partner (no id) or rewrites one; '' clears a field. */\n async partners_save(ctx: ActionContext, input: PartnerInput): Promise<Partner> {\n const name = required(input.name, 'A name');\n const id = input.id === undefined ? null : uuid(input.id, 'partner');\n if (await nameTaken(ctx, name, id)) {\n throw new ActionError(`There is already a partner named ${name}.`);\n }\n const ownerId = input.owner_id || null;\n const fields = [\n name,\n (input.kind ?? '').trim(),\n (input.contact_name ?? '').trim(),\n (input.contact_phone ?? '').trim(),\n (input.contact_email ?? '').trim(),\n ownerId,\n ownerId ? (input.owner_name ?? '').trim() || null : null,\n (input.notes ?? '').trim(),\n ];\n if (id === null) {\n const { results } = await ctx.db.batch([\n rememberViewer(ctx),\n {\n sql: `INSERT INTO partners (name, kind, contact_name, contact_phone, contact_email,\n owner_id, owner_name, notes, created_by, created_by_name)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)\n RETURNING id`,\n params: [...fields, ctx.viewer.id, ctx.viewer.display_name],\n },\n ]);\n return readPartner(ctx, results[1]?.rows[0]?.id as string);\n }\n const { results } = await ctx.db.batch([\n rememberViewer(ctx),\n {\n sql: `UPDATE partners\n SET name = $1, kind = $2, contact_name = $3, contact_phone = $4,\n contact_email = $5, owner_id = $6, owner_name = $7, notes = $8,\n updated_at = now()\n WHERE id = $9`,\n params: [...fields, id],\n },\n ]);\n if (!results[1]?.rows_affected) throw new ActionError('This partner does not exist.');\n return readPartner(ctx, id);\n },\n\n /** write: adds an entry to a partner's history, by the caller. */\n async activities_add(ctx: ActionContext, input: ActivityInput): Promise<Activity> {\n const partnerId = uuid(input.partner_id, 'partner');\n const dealId = input.deal_id ? uuid(input.deal_id, 'deal') : null;\n if (!ACTIVITY_KINDS.includes(input.kind)) throw new ActionError(`Unknown kind ${input.kind}.`);\n const body = required(input.body, 'The text');\n const at = input.happened_at ? new Date(input.happened_at) : new Date();\n if (Number.isNaN(at.getTime())) throw new ActionError('happened_at is not a time.');\n const { results } = await ctx.db.batch([\n rememberViewer(ctx),\n {\n sql: `INSERT INTO activities (partner_id, deal_id, kind, body, happened_at, actor_name,\n created_by, created_by_name, by_agent)\n SELECT p.id, $2::uuid, $3::text, $4::text, $5::timestamptz, $6::text, $7::text,\n $6::text, $8::boolean\n FROM partners p\n WHERE p.id = $1\n AND ($2::uuid IS NULL\n OR EXISTS (SELECT 1 FROM deals d WHERE d.id = $2::uuid AND d.partner_id = p.id))\n RETURNING id, partner_id, deal_id, kind, body, happened_at, actor_name, source,\n by_agent`,\n params: [\n partnerId,\n dealId,\n input.kind,\n body,\n at.toISOString(),\n ctx.viewer.display_name,\n ctx.viewer.id,\n ctx.viewer.is_agent,\n ],\n },\n ]);\n const row = results[1]?.rows[0];\n if (!row) throw new ActionError('This partner or deal does not exist.');\n return row as unknown as Activity;\n },\n};\n",
206
- "db/schema.sql": "-- The pipeline's tables. The Database is PostgreSQL (not SQLite): uuid,\n-- timestamptz, numeric, ILIKE, ON CONFLICT and gen_random_uuid() all work.\n--\n-- Apply (safe to run again — everything is IF NOT EXISTS):\n-- parall app db exec --app <app_…> --file db/schema.sql\n--\n-- The template brings no rows: what goes in is the team's own data, read\n-- from the sources the person agreed to (SKILL.md). Add a column the team\n-- needs with ALTER TABLE … ADD COLUMN IF NOT EXISTS …; an agent cannot DROP\n-- or TRUNCATE a table or drop a column.\n\n-- People who used the app. Write actions remember the caller here\n-- (actions/people.ts rememberViewer), so pages can offer them as owners.\n-- ctx.viewer is the only trustworthy identity.\nCREATE TABLE IF NOT EXISTS app_people (\n user_id text PRIMARY KEY,\n display_name text NOT NULL,\n is_agent boolean NOT NULL DEFAULT false,\n last_seen_at timestamptz NOT NULL DEFAULT now()\n);\n\n-- The customers, brands or creators the team works with. owner_id is the\n-- teammate (usr_…) who looks after the partner.\nCREATE TABLE IF NOT EXISTS partners (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(),\n name text NOT NULL CHECK (length(name) BETWEEN 1 AND 200),\n kind text NOT NULL DEFAULT '',\n contact_name text NOT NULL DEFAULT '',\n contact_phone text NOT NULL DEFAULT '',\n contact_email text NOT NULL DEFAULT '',\n owner_id text,\n owner_name text,\n notes text NOT NULL DEFAULT '',\n created_by text NOT NULL,\n created_by_name text NOT NULL,\n created_at timestamptz NOT NULL DEFAULT now(),\n updated_at timestamptz NOT NULL DEFAULT now()\n);\n-- One partner per name, whatever the case: imports and the new-deal form\n-- reuse it (ON CONFLICT ((lower(name))) …).\nCREATE UNIQUE INDEX IF NOT EXISTS partners_name_key ON partners (lower(name));\n\n-- One piece of business with a partner. stage is an id of STAGES in\n-- shared/pipeline.ts (the action checks it, so renaming stages needs no\n-- schema change); status open shows it on the board, won and lost close it.\n-- followup_* are what the agent writes each day for the follow-ups page.\nCREATE TABLE IF NOT EXISTS deals (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(),\n partner_id uuid NOT NULL REFERENCES partners (id),\n title text NOT NULL CHECK (length(title) BETWEEN 1 AND 200),\n stage text NOT NULL CHECK (length(stage) BETWEEN 1 AND 64),\n status text NOT NULL DEFAULT 'open' CHECK (status IN ('open', 'won', 'lost')),\n amount numeric(14, 2) CHECK (amount >= 0),\n owner_id text,\n owner_name text,\n next_step text NOT NULL DEFAULT '',\n next_step_due date,\n followup_reason text NOT NULL DEFAULT '',\n followup_draft text NOT NULL DEFAULT '',\n followup_by_name text NOT NULL DEFAULT '',\n created_by text NOT NULL,\n created_by_name text NOT NULL,\n created_at timestamptz NOT NULL DEFAULT now(),\n updated_at timestamptz NOT NULL DEFAULT now()\n);\nCREATE INDEX IF NOT EXISTS deals_partner_idx ON deals (partner_id);\nCREATE INDEX IF NOT EXISTS deals_open_idx ON deals (status, next_step_due);\n\n-- A partner's history: emails, calls, meetings, messages and notes, from\n-- the app or imported (source names where: a mailbox, a channel). A deleted\n-- deal leaves its history on the partner.\nCREATE TABLE IF NOT EXISTS activities (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(),\n partner_id uuid NOT NULL REFERENCES partners (id),\n deal_id uuid REFERENCES deals (id) ON DELETE SET NULL,\n kind text NOT NULL DEFAULT 'note'\n CHECK (kind IN ('email', 'call', 'meeting', 'message', 'note')),\n body text NOT NULL CHECK (length(body) BETWEEN 1 AND 5000),\n happened_at timestamptz NOT NULL DEFAULT now(),\n actor_name text NOT NULL,\n source text NOT NULL DEFAULT '',\n created_by text NOT NULL,\n created_by_name text NOT NULL,\n by_agent boolean NOT NULL DEFAULT false,\n created_at timestamptz NOT NULL DEFAULT now()\n);\nCREATE INDEX IF NOT EXISTS activities_partner_idx ON activities (partner_id, happened_at DESC);\n\n-- Who may open the app, and who may also call its write actions, is the\n-- app's access setting (parall app access); within that, who may change\n-- what is decided in the actions, from ctx.viewer. Here everyone who can\n-- open the app reads and edits partners, deals and history (a team's shared\n-- pipeline); a deal is deleted by its creator or an org owner/admin\n-- (actions/deals.ts). Amounts, phone numbers and emails are visible to\n-- everyone who can open the app — by default the whole organization; to keep\n-- them to a few people, set everyone else in the organization to not\n-- readable and add those people one by one — and what a write action is\n-- passed is kept in the app's call log, which everyone who can open the app\n-- can read.\n",
206
+ "db/schema.sql": "-- The pipeline's tables. The Database is PostgreSQL (not SQLite): uuid,\n-- timestamptz, numeric, ILIKE, ON CONFLICT and gen_random_uuid() all work.\n--\n-- Apply (safe to run again — everything is IF NOT EXISTS):\n-- parall app db exec --app <app_…> --file db/schema.sql\n--\n-- The template brings no rows: what goes in is the team's own data, read\n-- from the sources the person agreed to (SKILL.md). Add a column the team\n-- needs with ALTER TABLE … ADD COLUMN IF NOT EXISTS …; an agent cannot DROP\n-- or TRUNCATE a table or drop a column.\n\n-- People who used the app. Write actions remember the caller here\n-- (actions/people.ts rememberViewer), so pages can offer them as owners.\n-- ctx.viewer is the only trustworthy identity.\nCREATE TABLE IF NOT EXISTS app_people (\n user_id text PRIMARY KEY,\n display_name text NOT NULL,\n is_agent boolean NOT NULL DEFAULT false,\n last_seen_at timestamptz NOT NULL DEFAULT now()\n);\n\n-- The customers, brands or creators the team works with. owner_id is the\n-- teammate (usr_…) who looks after the partner.\nCREATE TABLE IF NOT EXISTS partners (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(),\n name text NOT NULL CHECK (length(name) BETWEEN 1 AND 200),\n kind text NOT NULL DEFAULT '',\n contact_name text NOT NULL DEFAULT '',\n contact_phone text NOT NULL DEFAULT '',\n contact_email text NOT NULL DEFAULT '',\n owner_id text,\n owner_name text,\n notes text NOT NULL DEFAULT '',\n created_by text NOT NULL,\n created_by_name text NOT NULL,\n created_at timestamptz NOT NULL DEFAULT now(),\n updated_at timestamptz NOT NULL DEFAULT now()\n);\n-- One partner per name, whatever the case: imports and the new-deal form\n-- reuse it (ON CONFLICT ((lower(name))) …).\nCREATE UNIQUE INDEX IF NOT EXISTS partners_name_key ON partners (lower(name));\n\n-- One piece of business with a partner. stage is an id of STAGES in\n-- shared/pipeline.ts (the action checks it, so renaming stages needs no\n-- schema change); status open shows it on the board, won and lost close it.\n-- followup_* are what the agent writes each day for the follow-ups page.\nCREATE TABLE IF NOT EXISTS deals (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(),\n partner_id uuid NOT NULL REFERENCES partners (id),\n title text NOT NULL CHECK (length(title) BETWEEN 1 AND 200),\n stage text NOT NULL CHECK (length(stage) BETWEEN 1 AND 64),\n status text NOT NULL DEFAULT 'open' CHECK (status IN ('open', 'won', 'lost')),\n amount numeric(14, 2) CHECK (amount >= 0),\n owner_id text,\n owner_name text,\n next_step text NOT NULL DEFAULT '',\n next_step_due date,\n followup_reason text NOT NULL DEFAULT '',\n followup_draft text NOT NULL DEFAULT '',\n followup_by_name text NOT NULL DEFAULT '',\n created_by text NOT NULL,\n created_by_name text NOT NULL,\n created_at timestamptz NOT NULL DEFAULT now(),\n updated_at timestamptz NOT NULL DEFAULT now()\n);\nCREATE INDEX IF NOT EXISTS deals_partner_idx ON deals (partner_id);\nCREATE INDEX IF NOT EXISTS deals_open_idx ON deals (status, next_step_due);\n\n-- A partner's history: emails, calls, meetings, messages and notes, from\n-- the app or imported (source names where: a mailbox, a channel). A deleted\n-- deal leaves its history on the partner.\nCREATE TABLE IF NOT EXISTS activities (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(),\n partner_id uuid NOT NULL REFERENCES partners (id),\n deal_id uuid REFERENCES deals (id) ON DELETE SET NULL,\n kind text NOT NULL DEFAULT 'note'\n CHECK (kind IN ('email', 'call', 'meeting', 'message', 'note')),\n body text NOT NULL CHECK (length(body) BETWEEN 1 AND 5000),\n happened_at timestamptz NOT NULL DEFAULT now(),\n actor_name text NOT NULL,\n source text NOT NULL DEFAULT '',\n created_by text NOT NULL,\n created_by_name text NOT NULL,\n by_agent boolean NOT NULL DEFAULT false,\n created_at timestamptz NOT NULL DEFAULT now()\n);\nCREATE INDEX IF NOT EXISTS activities_partner_idx ON activities (partner_id, happened_at DESC);\n\n-- Who may open the app, and who may also call its write actions, is the\n-- app's access setting (parall app access); within that, who may change\n-- what is decided in the actions, from ctx.viewer. Here everyone who can\n-- open the app reads and edits partners, deals and history (a team's shared\n-- pipeline); a deal is deleted by its creator or an org owner/admin\n-- (actions/deals.ts). Amounts, phone numbers and emails are visible to\n-- everyone who can open the app — by default the whole organization; to keep\n-- them to a few people, set everyone else in the organization to not\n-- readable and add those people one by one — and what a write action is\n-- passed is kept in the app's call log, which only the app's authors, org\n-- owners/admins and the caller can read.\n",
207
207
  "public/manifest.json": "{\n \"entry\": \"index.html\",\n \"sdk_version\": \"0.1.0\",\n \"capabilities\": [],\n \"actions\": {\n \"entry\": \"_actions/index.js\",\n \"functions\": {\n \"people_list\": { \"kind\": \"read\" },\n \"pipeline_board\": { \"kind\": \"read\" },\n \"deals_save\": {\n \"kind\": \"write\",\n \"params\": {\n \"type\": \"object\",\n \"properties\": {\n \"id\": { \"type\": \"string\", \"maxLength\": 64 },\n \"partner_id\": { \"type\": \"string\", \"maxLength\": 64 },\n \"partner_name\": { \"type\": \"string\", \"maxLength\": 200 },\n \"title\": { \"type\": \"string\", \"minLength\": 1, \"maxLength\": 200 },\n \"stage\": { \"type\": \"string\", \"minLength\": 1, \"maxLength\": 64 },\n \"amount\": { \"type\": \"number\", \"minimum\": 0, \"maximum\": 999999999999 },\n \"owner_id\": { \"type\": \"string\", \"maxLength\": 64 },\n \"owner_name\": { \"type\": \"string\", \"maxLength\": 200 },\n \"next_step\": { \"type\": \"string\", \"maxLength\": 500 },\n \"next_step_due\": { \"type\": \"string\", \"maxLength\": 10 }\n },\n \"required\": [\"title\", \"stage\"]\n }\n },\n \"deals_move\": {\n \"kind\": \"write\",\n \"params\": {\n \"type\": \"object\",\n \"properties\": {\n \"id\": { \"type\": \"string\", \"maxLength\": 64 },\n \"stage\": { \"type\": \"string\", \"minLength\": 1, \"maxLength\": 64 },\n \"status\": { \"type\": \"string\", \"enum\": [\"open\", \"won\", \"lost\"] }\n },\n \"required\": [\"id\"]\n }\n },\n \"deals_delete\": {\n \"kind\": \"write\",\n \"params\": {\n \"type\": \"object\",\n \"properties\": { \"id\": { \"type\": \"string\", \"maxLength\": 64 } },\n \"required\": [\"id\"]\n }\n },\n \"followups_done\": {\n \"kind\": \"write\",\n \"params\": {\n \"type\": \"object\",\n \"properties\": {\n \"id\": { \"type\": \"string\", \"maxLength\": 64 },\n \"note\": { \"type\": \"string\", \"minLength\": 1, \"maxLength\": 5000 }\n },\n \"required\": [\"id\", \"note\"]\n }\n },\n \"followups_snooze\": {\n \"kind\": \"write\",\n \"params\": {\n \"type\": \"object\",\n \"properties\": {\n \"id\": { \"type\": \"string\", \"maxLength\": 64 },\n \"until\": { \"type\": \"string\", \"format\": \"date\" }\n },\n \"required\": [\"id\", \"until\"]\n }\n },\n \"followups_draft\": {\n \"kind\": \"write\",\n \"params\": {\n \"type\": \"object\",\n \"properties\": {\n \"id\": { \"type\": \"string\", \"maxLength\": 64 },\n \"reason\": { \"type\": \"string\", \"maxLength\": 1000 },\n \"draft\": { \"type\": \"string\", \"maxLength\": 5000 },\n \"due\": { \"type\": \"string\", \"format\": \"date\" }\n },\n \"required\": [\"id\", \"reason\", \"draft\"]\n }\n },\n \"partners_list\": { \"kind\": \"read\" },\n \"partner_get\": {\n \"kind\": \"read\",\n \"params\": {\n \"type\": \"object\",\n \"properties\": { \"id\": { \"type\": \"string\", \"maxLength\": 64 } },\n \"required\": [\"id\"]\n }\n },\n \"partners_save\": {\n \"kind\": \"write\",\n \"params\": {\n \"type\": \"object\",\n \"properties\": {\n \"id\": { \"type\": \"string\", \"maxLength\": 64 },\n \"name\": { \"type\": \"string\", \"minLength\": 1, \"maxLength\": 200 },\n \"kind\": { \"type\": \"string\", \"maxLength\": 200 },\n \"contact_name\": { \"type\": \"string\", \"maxLength\": 200 },\n \"contact_phone\": { \"type\": \"string\", \"maxLength\": 100 },\n \"contact_email\": { \"type\": \"string\", \"maxLength\": 200 },\n \"owner_id\": { \"type\": \"string\", \"maxLength\": 64 },\n \"owner_name\": { \"type\": \"string\", \"maxLength\": 200 },\n \"notes\": { \"type\": \"string\", \"maxLength\": 5000 }\n },\n \"required\": [\"name\"]\n }\n },\n \"activities_add\": {\n \"kind\": \"write\",\n \"params\": {\n \"type\": \"object\",\n \"properties\": {\n \"partner_id\": { \"type\": \"string\", \"maxLength\": 64 },\n \"deal_id\": { \"type\": \"string\", \"maxLength\": 64 },\n \"kind\": { \"type\": \"string\", \"enum\": [\"email\", \"call\", \"meeting\", \"message\", \"note\"] },\n \"body\": { \"type\": \"string\", \"minLength\": 1, \"maxLength\": 5000 },\n \"happened_at\": { \"type\": \"string\", \"format\": \"date-time\" }\n },\n \"required\": [\"partner_id\", \"kind\", \"body\"]\n }\n }\n }\n }\n}\n",
208
208
  "shared/pipeline.ts": "// Types shared by the pipeline's actions (actions/deals.ts, actions/partners.ts)\n// and its pages (src/pages/board, followups, partners): the actions return\n// rows of these shapes.\n\nexport type StageColor = 'gray' | 'blue' | 'violet' | 'amber' | 'rose' | 'green';\n\nexport interface Stage {\n /** What deals.stage stores. Keep an id once deals use it; to retire one,\n * move its deals to another stage in SQL first. */\n id: string;\n /** The stage's name, as the team says it. */\n en: string;\n zh: string;\n color: StageColor;\n}\n\n/** The stages a deal moves through, in board order. They are the team's own\n * words: rename, add or drop them to match what the team calls them. */\nexport const STAGES: Stage[] = [\n { id: 'inquiry', en: 'Inquiry', zh: '询价', color: 'gray' },\n { id: 'quote', en: 'Quote', zh: '报价', color: 'blue' },\n { id: 'contract', en: 'Contract', zh: '签约', color: 'violet' },\n { id: 'delivery', en: 'Delivery', zh: '执行', color: 'amber' },\n { id: 'payment', en: 'Payment', zh: '结款', color: 'green' },\n];\n\n/** Whether the team records amounts. false hides them on every page (the\n * column stays, empty). */\nexport const AMOUNTS: boolean = true;\n\n/** The ISO 4217 currency amounts are kept in. */\nexport const CURRENCY = 'CNY';\n\n/** open: on the board; won: done and paid; lost: did not happen. */\nexport type DealStatus = 'open' | 'won' | 'lost';\nexport const DEAL_STATUSES: DealStatus[] = ['open', 'won', 'lost'];\n\n/** One piece of business with a partner. */\nexport interface Deal {\n id: string;\n partner_id: string;\n partner_name: string;\n title: string;\n /** A Stage id. */\n stage: string;\n status: DealStatus;\n /** Null when no amount is recorded (not quoted yet, or the team keeps\n * amounts out of the app). */\n amount: number | null;\n owner_id: string | null;\n owner_name: string | null;\n /** What happens next, and by when (YYYY-MM-DD). */\n next_step: string;\n next_step_due: string | null;\n /** Why to follow up and the message drafted for the owner, written by the\n * agent for the follow-ups page (followups_draft); '' when there is none. */\n followup_reason: string;\n followup_draft: string;\n /** Who drafted it. */\n followup_by_name: string;\n created_by: string;\n updated_at: string;\n /** Whether the caller may delete it: its creator or an org owner/admin. */\n can_delete: boolean;\n}\n\n/** deals_save params: no id creates a deal. The partner is partner_id, or a\n * name: the partner of that name (any case) is reused, else created. Every\n * field is written as given; '' clears owner_id and next_step_due, and a\n * missing amount clears it. */\nexport interface DealInput {\n id?: string;\n partner_id?: string;\n partner_name?: string;\n title: string;\n stage: string;\n amount?: number;\n owner_id?: string;\n owner_name?: string;\n next_step?: string;\n next_step_due?: string;\n}\n\n/** deals_move params: a new stage, a new status, or both. */\nexport interface DealMoveInput {\n id: string;\n stage?: string;\n status?: DealStatus;\n}\n\n/** followups_done params: the note goes into the partner's history. */\nexport interface FollowupDoneInput {\n id: string;\n note: string;\n}\n\n/** followups_snooze params: the deal's next step moves to this day. */\nexport interface FollowupSnoozeInput {\n id: string;\n until: string;\n}\n\n/** followups_draft params (the agent's daily run): why to follow up and the\n * message drafted for the owner; due sets the next step's date too. */\nexport interface FollowupDraftInput {\n id: string;\n reason: string;\n draft: string;\n due?: string;\n}\n\n/** A customer, brand or creator the team works with. */\nexport interface Partner {\n id: string;\n name: string;\n /** What kind of partner, in the team's words (industry, category…). */\n kind: string;\n contact_name: string;\n contact_phone: string;\n contact_email: string;\n owner_id: string | null;\n owner_name: string | null;\n notes: string;\n updated_at: string;\n}\n\n/** partners_list rows: the partner with its deals summed up. */\nexport interface PartnerSummary extends Partner {\n open_deals: number;\n /** The amounts of every deal that did not fall through; null when none\n * has an amount. */\n total_amount: number | null;\n last_activity_at: string | null;\n}\n\n/** partners_save params: no id creates a partner; '' clears a field. */\nexport interface PartnerInput {\n id?: string;\n name: string;\n kind?: string;\n contact_name?: string;\n contact_phone?: string;\n contact_email?: string;\n owner_id?: string;\n owner_name?: string;\n notes?: string;\n}\n\nexport type ActivityKind = 'email' | 'call' | 'meeting' | 'message' | 'note';\nexport const ACTIVITY_KINDS: ActivityKind[] = ['email', 'call', 'meeting', 'message', 'note'];\n\n/** One entry of a partner's history: an email, a call, a message, a note. */\nexport interface Activity {\n id: string;\n partner_id: string;\n deal_id: string | null;\n kind: ActivityKind;\n body: string;\n /** When it happened (ISO timestamp). */\n happened_at: string;\n /** Who did it: a teammate, someone at the partner, or the agent. */\n actor_name: string;\n /** Where it was recorded from (a mailbox, a channel); '' when typed in\n * the app. */\n source: string;\n /** Written by an agent. */\n by_agent: boolean;\n}\n\n/** activities_add params. */\nexport interface ActivityInput {\n partner_id: string;\n deal_id?: string;\n kind: ActivityKind;\n body: string;\n /** ISO timestamp; now when absent. */\n happened_at?: string;\n}\n\n/** partner_get: one partner with all its deals and its history. */\nexport interface PartnerDetail {\n partner: Partner;\n deals: Deal[];\n activities: Activity[];\n}\n",
209
209
  "src/components/owner-filter.tsx": "import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';\nimport { t } from '@/lib/pipeline';\nimport { cn } from '@/lib/utils';\n\nexport const ALL_OWNERS = '__all__';\n\n/** \"All\" or one owner, as a row of toggles; with counts when given. */\nexport function OwnerFilter({\n owners,\n value,\n onChange,\n counts,\n total,\n className,\n}: {\n owners: Array<{ id: string; name: string }>;\n value: string;\n onChange: (value: string) => void;\n counts?: Record<string, number>;\n total?: number;\n className?: string;\n}) {\n if (owners.length === 0) return null;\n return (\n <ToggleGroup\n type=\"single\"\n variant=\"outline\"\n size=\"sm\"\n value={value}\n onValueChange={(next) => next && onChange(next)}\n className={cn('no-scrollbar max-w-full overflow-x-auto', className)}\n >\n <ToggleGroupItem value={ALL_OWNERS} className=\"shrink-0 gap-1.5 px-3\">\n {t('everyone')}\n {total !== undefined ? (\n <span className=\"text-muted-foreground text-xs tabular-nums\">{total}</span>\n ) : null}\n </ToggleGroupItem>\n {owners.map((owner) => (\n <ToggleGroupItem key={owner.id} value={owner.id} className=\"shrink-0 gap-1.5 px-3\">\n {owner.name}\n {counts ? (\n <span className=\"text-muted-foreground text-xs tabular-nums\">\n {counts[owner.id] ?? 0}\n </span>\n ) : null}\n </ToggleGroupItem>\n ))}\n </ToggleGroup>\n );\n}\n",