@parall/cli 1.70.0 → 1.72.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/dist/commands/apps-action-local.d.ts +44 -0
  2. package/dist/commands/apps-action-local.d.ts.map +1 -0
  3. package/dist/commands/apps-action-local.js +153 -0
  4. package/dist/commands/apps-action-stack.d.ts +14 -0
  5. package/dist/commands/apps-action-stack.d.ts.map +1 -0
  6. package/dist/commands/apps-action-stack.js +63 -0
  7. package/dist/commands/apps-actions-sdk.generated.d.ts +2 -0
  8. package/dist/commands/apps-actions-sdk.generated.d.ts.map +1 -0
  9. package/dist/commands/apps-actions-sdk.generated.js +3 -0
  10. package/dist/commands/apps-actions.d.ts +20 -0
  11. package/dist/commands/apps-actions.d.ts.map +1 -0
  12. package/dist/commands/apps-actions.js +266 -0
  13. package/dist/commands/apps-check.d.ts +34 -0
  14. package/dist/commands/apps-check.d.ts.map +1 -0
  15. package/dist/commands/apps-check.js +155 -0
  16. package/dist/commands/apps-dev-page.d.ts +26 -0
  17. package/dist/commands/apps-dev-page.d.ts.map +1 -0
  18. package/dist/commands/apps-dev-page.js +259 -0
  19. package/dist/commands/apps-dev-server.d.ts +42 -0
  20. package/dist/commands/apps-dev-server.d.ts.map +1 -0
  21. package/dist/commands/apps-dev-server.js +328 -0
  22. package/dist/commands/apps-dev.d.ts +8 -0
  23. package/dist/commands/apps-dev.d.ts.map +1 -0
  24. package/dist/commands/apps-dev.js +126 -0
  25. package/dist/commands/apps-local-runner.generated.d.ts +3 -0
  26. package/dist/commands/apps-local-runner.generated.d.ts.map +1 -0
  27. package/dist/commands/apps-local-runner.generated.js +4 -0
  28. package/dist/commands/apps-page-sdk.generated.d.ts +2 -0
  29. package/dist/commands/apps-page-sdk.generated.d.ts.map +1 -0
  30. package/dist/commands/apps-page-sdk.generated.js +3 -0
  31. package/dist/commands/apps-publish.d.ts.map +1 -1
  32. package/dist/commands/apps-publish.js +6 -0
  33. package/dist/commands/apps-scaffold-actions.d.ts +11 -0
  34. package/dist/commands/apps-scaffold-actions.d.ts.map +1 -0
  35. package/dist/commands/apps-scaffold-actions.js +163 -0
  36. package/dist/commands/apps-scaffold.d.ts +4 -6
  37. package/dist/commands/apps-scaffold.d.ts.map +1 -1
  38. package/dist/commands/apps-scaffold.js +22 -222
  39. package/dist/commands/apps.d.ts +3 -2
  40. package/dist/commands/apps.d.ts.map +1 -1
  41. package/dist/commands/apps.js +24 -2
  42. package/dist/commands/db-plane.d.ts +1 -2
  43. package/dist/commands/db-plane.d.ts.map +1 -1
  44. package/dist/commands/db-plane.js +3 -2
  45. package/dist/commands/dbs.d.ts.map +1 -1
  46. package/dist/commands/dbs.js +1 -15
  47. package/dist/commands/messages.d.ts.map +1 -1
  48. package/dist/commands/messages.js +6 -11
  49. package/dist/commands/msteams.d.ts +10 -0
  50. package/dist/commands/msteams.d.ts.map +1 -0
  51. package/dist/commands/msteams.js +41 -0
  52. package/dist/index.js +7 -5
  53. package/dist/lib/client.d.ts +2 -1
  54. package/dist/lib/client.d.ts.map +1 -1
  55. package/dist/lib/mini-app-discovery.d.ts +6 -0
  56. package/dist/lib/mini-app-discovery.d.ts.map +1 -0
  57. package/dist/lib/mini-app-discovery.js +32 -0
  58. package/dist/lib/output.d.ts +3 -1
  59. package/dist/lib/output.d.ts.map +1 -1
  60. package/dist/lib/output.js +5 -1
  61. package/package.json +5 -5
@@ -0,0 +1,328 @@
1
+ import { randomBytes, timingSafeEqual } from 'node:crypto';
2
+ import { promises as fs } from 'node:fs';
3
+ import { createServer } from 'node:http';
4
+ import { extname, join, normalize, sep } from 'node:path';
5
+ import { ApiError } from '@parall/sdk';
6
+ import { resolveCredentials } from '../lib/client.js';
7
+ import { readLocalAction, runLocalAction } from './apps-action-local.js';
8
+ import { devAppHostPage } from './apps-dev-page.js';
9
+ const MAX_BODY_BYTES = 1 << 20;
10
+ const MAX_CONSOLE_CHARS = 8000;
11
+ export async function serveAppDev(dist, port, appId) {
12
+ const { client, orgId } = resolveCredentials();
13
+ const apiUrl = process.env.PRLL_API_URL ?? '';
14
+ const [me, app, members] = await Promise.all([
15
+ client.getMe(),
16
+ client.getMiniApp(orgId, appId),
17
+ client.getOrgMembers(orgId),
18
+ ]);
19
+ const role = members.find((m) => m.user_id === me.id)?.role ?? 'member';
20
+ const appPort = port + 1;
21
+ const filesOrigin = filesOriginFor(apiUrl);
22
+ const token = randomBytes(24).toString('base64url');
23
+ const run = async (name, params) => {
24
+ const started = Date.now();
25
+ let printed = '';
26
+ let committed;
27
+ let kind;
28
+ const done = (answer) => ({
29
+ ...answer,
30
+ console: printed,
31
+ ...(committed ? { data_seq: committed } : {}),
32
+ duration_ms: Date.now() - started,
33
+ });
34
+ try {
35
+ // Read on every call, so a rebuild takes effect without a restart.
36
+ const local = await readLocalAction(dist, name);
37
+ kind = local.kind;
38
+ const out = await runLocalAction(client, orgId, app.id, apiUrl, dist, name, local, params, {
39
+ console: (text) => {
40
+ printed = (printed + text).slice(-MAX_CONSOLE_CHARS);
41
+ },
42
+ committed: (dataSeq) => {
43
+ committed = dataSeq;
44
+ },
45
+ });
46
+ return done({ ok: true, kind, invocation_id: out.invocation_id, result: out.result });
47
+ }
48
+ catch (err) {
49
+ if (err instanceof ApiError) {
50
+ const details = (err.extras?.details ?? undefined);
51
+ return done({
52
+ ok: false,
53
+ kind,
54
+ invocation_id: typeof details?.invocation_id === 'string' ? details.invocation_id : undefined,
55
+ error: { code: err.code ?? 'ACTION_FAILED', message: err.message, details },
56
+ });
57
+ }
58
+ return done({
59
+ ok: false,
60
+ kind,
61
+ error: {
62
+ code: 'DEV_HOST_FAILED',
63
+ message: err instanceof Error ? err.message : String(err),
64
+ },
65
+ });
66
+ }
67
+ };
68
+ const page = {
69
+ appOrigin: `http://127.0.0.1:${appPort}`,
70
+ app: { id: app.id, name: app.name, database_id: app.database_id },
71
+ viewer: { id: me.id, display_name: me.display_name, is_agent: me.type === 'agent', role },
72
+ };
73
+ const host = createServer((req, res) => {
74
+ handleHostRequest(req, res, { port, token, page, run }).catch(() => failRequest(res));
75
+ });
76
+ const appServer = createServer((req, res) => {
77
+ handleAppRequest(req, res, { appPort, hostPort: port, dist, filesOrigin }).catch(() => failRequest(res));
78
+ });
79
+ await listen(host, port);
80
+ try {
81
+ await listen(appServer, appPort);
82
+ }
83
+ catch (err) {
84
+ host.close();
85
+ throw err;
86
+ }
87
+ console.error(`Mini App dev host: http://127.0.0.1:${port}/?t=${token}`);
88
+ console.error(` ${app.name} (${app.id}) from ${dist}, page on http://127.0.0.1:${appPort}`);
89
+ console.error(" Actions run on this machine against the app's real Database: writes are real. Ctrl-C to stop.");
90
+ }
91
+ /** The deployment's files-worker origin, the one outside source the
92
+ * apps-worker lets a page load images from (attachment images the platform
93
+ * serves). Deployments name it after the API host — `api.X` serves files from
94
+ * `files.X` — and nothing else is guessed: without it, those images are
95
+ * blocked locally, never allowed where Parall would block them. */
96
+ export function filesOriginFor(apiUrl) {
97
+ try {
98
+ const url = new URL(apiUrl);
99
+ if (url.protocol !== 'https:' || !url.hostname.startsWith('api.'))
100
+ return '';
101
+ return `https://files.${url.hostname.slice('api.'.length)}`;
102
+ }
103
+ catch {
104
+ return '';
105
+ }
106
+ }
107
+ /** Loopback only: these serve the build and reach real data. A bind
108
+ * failure (port in use) arrives as an 'error' event, not a throw. */
109
+ function listen(server, port) {
110
+ return new Promise((resolveListen, rejectListen) => {
111
+ server.once('error', rejectListen);
112
+ server.listen(port, '127.0.0.1', () => {
113
+ server.off('error', rejectListen);
114
+ resolveListen();
115
+ });
116
+ });
117
+ }
118
+ /** The Host a loopback server answers: anything else (a DNS-rebound name)
119
+ * is refused before the request is looked at. */
120
+ export function isLoopbackHost(host, port) {
121
+ return host === `127.0.0.1:${port}` || host === `localhost:${port}`;
122
+ }
123
+ /** Whatever breaks one request ends that request, not the dev host. */
124
+ function failRequest(res) {
125
+ if (res.headersSent)
126
+ res.destroy();
127
+ else
128
+ res.writeHead(500, { 'Content-Type': 'text/plain' }).end('internal error');
129
+ }
130
+ const isObject = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
131
+ function sameToken(given, token) {
132
+ if (typeof given !== 'string')
133
+ return false;
134
+ const a = Buffer.from(given);
135
+ const b = Buffer.from(token);
136
+ return a.length === b.length && timingSafeEqual(a, b);
137
+ }
138
+ async function handleHostRequest(req, res, ctx) {
139
+ if (!isLoopbackHost(req.headers.host, ctx.port)) {
140
+ res.writeHead(403, { 'Content-Type': 'text/plain' }).end('host not allowed');
141
+ return;
142
+ }
143
+ let pathname;
144
+ try {
145
+ pathname = new URL(req.url ?? '/', 'http://localhost').pathname;
146
+ }
147
+ catch {
148
+ // A request line no URL parser takes (`GET //`, say).
149
+ res.writeHead(400, { 'Content-Type': 'text/plain' }).end('bad request');
150
+ return;
151
+ }
152
+ if (req.method === 'GET' && (pathname === '/' || pathname === '/index.html')) {
153
+ const nonce = randomBytes(16).toString('base64');
154
+ res.writeHead(200, {
155
+ 'Content-Type': 'text/html; charset=utf-8',
156
+ // The token rides in this page's address: no Referer may carry it, no
157
+ // other page may frame this one, nothing may cache it.
158
+ 'Content-Security-Policy': [
159
+ "default-src 'none'",
160
+ `script-src 'nonce-${nonce}'`,
161
+ `style-src 'nonce-${nonce}'`,
162
+ "connect-src 'self'",
163
+ `frame-src ${ctx.page.appOrigin}`,
164
+ "img-src 'self' data:",
165
+ "base-uri 'none'",
166
+ "form-action 'none'",
167
+ "frame-ancestors 'none'",
168
+ ].join('; '),
169
+ 'Referrer-Policy': 'no-referrer',
170
+ 'Cache-Control': 'no-store',
171
+ 'X-Content-Type-Options': 'nosniff',
172
+ });
173
+ res.end(devAppHostPage(ctx.page, nonce));
174
+ return;
175
+ }
176
+ if (pathname === '/api/report') {
177
+ // A page error the page reported: one terminal line, nothing sent on.
178
+ if (req.method !== 'POST') {
179
+ res.writeHead(405, { Allow: 'POST' }).end();
180
+ return;
181
+ }
182
+ if (!sameToken(req.headers['x-parall-dev-token'], ctx.token)) {
183
+ res.writeHead(403, { 'Content-Type': 'text/plain' }).end('token required');
184
+ return;
185
+ }
186
+ let report;
187
+ try {
188
+ report = JSON.parse(await readBody(req));
189
+ }
190
+ catch {
191
+ res.writeHead(400, { 'Content-Type': 'text/plain' }).end('not JSON');
192
+ return;
193
+ }
194
+ if (isObject(report))
195
+ logReport(report);
196
+ res.writeHead(204).end();
197
+ return;
198
+ }
199
+ if (pathname === '/api/action') {
200
+ if (req.method !== 'POST') {
201
+ res.writeHead(405, { Allow: 'POST' }).end();
202
+ return;
203
+ }
204
+ if (!sameToken(req.headers['x-parall-dev-token'], ctx.token)) {
205
+ res.writeHead(403, { 'Content-Type': 'text/plain' }).end('token required');
206
+ return;
207
+ }
208
+ if (!(req.headers['content-type'] ?? '').startsWith('application/json')) {
209
+ res.writeHead(415, { 'Content-Type': 'text/plain' }).end('JSON only');
210
+ return;
211
+ }
212
+ let body;
213
+ try {
214
+ body = JSON.parse(await readBody(req));
215
+ }
216
+ catch {
217
+ res.writeHead(400, { 'Content-Type': 'text/plain' }).end('not JSON');
218
+ return;
219
+ }
220
+ // `params` left out or null is an empty object, as the server takes it.
221
+ const params = isObject(body) ? (body.params ?? {}) : undefined;
222
+ if (!isObject(body) || typeof body.name !== 'string' || !isObject(params)) {
223
+ res.writeHead(400, { 'Content-Type': 'text/plain' }).end('{name, params} expected');
224
+ return;
225
+ }
226
+ const answer = await ctx.run(body.name, params);
227
+ logCall(body.name, answer);
228
+ res.writeHead(200, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
229
+ res.end(JSON.stringify(answer));
230
+ return;
231
+ }
232
+ res.writeHead(404).end('not found');
233
+ }
234
+ function readBody(req) {
235
+ return new Promise((resolveBody, rejectBody) => {
236
+ const chunks = [];
237
+ let size = 0;
238
+ req.on('data', (chunk) => {
239
+ size += chunk.length;
240
+ if (size > MAX_BODY_BYTES) {
241
+ rejectBody(new Error('body too large'));
242
+ req.destroy();
243
+ return;
244
+ }
245
+ chunks.push(chunk);
246
+ });
247
+ req.on('end', () => resolveBody(Buffer.concat(chunks).toString('utf8')));
248
+ req.on('error', rejectBody);
249
+ });
250
+ }
251
+ /** A page error, in one terminal line: what it was and where. */
252
+ function logReport(r) {
253
+ const text = (v) => (typeof v === 'string' ? v : '');
254
+ const firstLine = (v) => text(v).split('\n')[0]?.trim() ?? '';
255
+ const frame = text(r.stack)
256
+ .split('\n')
257
+ .map((line) => line.trim())
258
+ .find((line) => /:\d+(:\d+)?\)?$/.test(line));
259
+ const what = r.kind === 'action'
260
+ ? `${text(r.action)} ${text(r.code)} ${text(r.invocation_id)}`.trim()
261
+ : `${text(r.name) ? `${text(r.name)}: ` : ''}${firstLine(r.message)}${frame ? ` (${frame})` : ''}`;
262
+ console.error(`[app dev] page error ${text(r.kind)} — ${what}`);
263
+ }
264
+ /** The terminal gets every call too (the action's console went there already). */
265
+ function logCall(name, answer) {
266
+ const status = answer.ok ? 'ok' : (answer.error?.code ?? 'failed');
267
+ const id = answer.invocation_id ? ` ${answer.invocation_id}` : '';
268
+ const message = answer.ok ? '' : ` — ${answer.error?.message ?? ''}`;
269
+ console.error(`[app dev] ${name} ${answer.kind ?? ''} ${status} ${answer.duration_ms}ms${id}${message}`);
270
+ }
271
+ const contentTypes = {
272
+ '.html': 'text/html; charset=utf-8',
273
+ '.js': 'text/javascript; charset=utf-8',
274
+ '.mjs': 'text/javascript; charset=utf-8',
275
+ '.css': 'text/css; charset=utf-8',
276
+ '.json': 'application/json',
277
+ '.svg': 'image/svg+xml',
278
+ '.png': 'image/png',
279
+ '.jpg': 'image/jpeg',
280
+ '.ico': 'image/x-icon',
281
+ '.map': 'application/json',
282
+ '.woff2': 'font/woff2',
283
+ };
284
+ /** The page's origin: the build's files only, under the CSP the apps-worker
285
+ * sets in Parall (ts/apps-worker/src/headers.ts), framed by the host page. */
286
+ async function handleAppRequest(req, res, ctx) {
287
+ if (!isLoopbackHost(req.headers.host, ctx.appPort)) {
288
+ res.writeHead(403, { 'Content-Type': 'text/plain' }).end('host not allowed');
289
+ return;
290
+ }
291
+ if (req.method !== 'GET') {
292
+ res.writeHead(405, { Allow: 'GET' }).end();
293
+ return;
294
+ }
295
+ try {
296
+ const pathname = decodeURIComponent(new URL(req.url ?? '/', 'http://localhost').pathname);
297
+ const rel = normalize(pathname.replace(/^\/+/, ''));
298
+ if (rel.startsWith('..') || rel.includes(`..${sep}`)) {
299
+ res.writeHead(404).end();
300
+ return;
301
+ }
302
+ const file = join(ctx.dist, rel === '' || rel === '.' ? 'index.html' : rel);
303
+ const body = await fs.readFile(file);
304
+ res.writeHead(200, {
305
+ 'Content-Type': contentTypes[extname(file).toLowerCase()] ?? 'application/octet-stream',
306
+ 'Content-Security-Policy': [
307
+ "default-src 'none'",
308
+ "script-src 'self'",
309
+ "style-src 'self' 'unsafe-inline'",
310
+ `img-src 'self' data: blob:${ctx.filesOrigin ? ` ${ctx.filesOrigin}` : ''}`,
311
+ "media-src 'self' blob:",
312
+ "font-src 'self'",
313
+ "connect-src 'none'",
314
+ "form-action 'none'",
315
+ "base-uri 'none'",
316
+ `frame-ancestors http://127.0.0.1:${ctx.hostPort} http://localhost:${ctx.hostPort}`,
317
+ ].join('; '),
318
+ 'X-Content-Type-Options': 'nosniff',
319
+ 'Referrer-Policy': 'no-referrer',
320
+ 'Cross-Origin-Opener-Policy': 'same-origin',
321
+ 'Cache-Control': 'no-store',
322
+ });
323
+ res.end(body);
324
+ }
325
+ catch {
326
+ res.writeHead(404).end('not found');
327
+ }
328
+ }
@@ -0,0 +1,8 @@
1
+ import type { Command } from 'commander';
2
+ /** `parall app dev`: a local host page speaking the same bridge as the
3
+ * Parall hosts, for an author (often an agent with a headless browser) to
4
+ * look at the built page before publishing. With --app the page also calls
5
+ * the local build's actions against the app's real Database
6
+ * (apps-dev-server.ts); without it the host is static and offline. */
7
+ export declare function registerAppDevCommand(app: Command): void;
8
+ //# sourceMappingURL=apps-dev.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"apps-dev.d.ts","sourceRoot":"","sources":["../../src/commands/apps-dev.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAIzC;;;;sEAIsE;AACtE,wBAAgB,qBAAqB,CAAC,GAAG,EAAE,OAAO,QAyCjD"}
@@ -0,0 +1,126 @@
1
+ import { promises as fs } from 'node:fs';
2
+ import { createServer } from 'node:http';
3
+ import { extname, join, normalize, resolve, sep } from 'node:path';
4
+ import { printError, stripPrllScheme } from '../lib/output.js';
5
+ import { serveAppDev } from './apps-dev-server.js';
6
+ /** `parall app dev`: a local host page speaking the same bridge as the
7
+ * Parall hosts, for an author (often an agent with a headless browser) to
8
+ * look at the built page before publishing. With --app the page also calls
9
+ * the local build's actions against the app's real Database
10
+ * (apps-dev-server.ts); without it the host is static and offline. */
11
+ export function registerAppDevCommand(app) {
12
+ app
13
+ .command('dev')
14
+ .description('Serve a built bundle under a local host page that speaks the bridge')
15
+ .option('--dist <dir>', 'The built bundle directory', 'dist')
16
+ .option('--port <n>', 'Port to listen on (with --app, the page uses the next one)', '5180')
17
+ .option('--app <app>', "Connect the page to this app: the actions it calls run on this machine against the app's real Database (writes are real; needs miniflare in the project)")
18
+ .action(async (opts) => {
19
+ try {
20
+ const dist = resolve(opts.dist);
21
+ await fs.access(join(dist, 'index.html'));
22
+ const port = Number(opts.port);
23
+ if (opts.app) {
24
+ await serveAppDev(dist, port, stripPrllScheme(opts.app));
25
+ return;
26
+ }
27
+ const server = createServer((req, res) => {
28
+ void handleDevRequest(dist, req.url ?? '/', res);
29
+ });
30
+ // Loopback only: this serves the app's build directory and must not
31
+ // be reachable from the local network. A bind failure (port in use)
32
+ // arrives as an 'error' event, not a throw — it has to reach the
33
+ // catch below instead of crashing the CLI.
34
+ await new Promise((resolveListen, rejectListen) => {
35
+ server.once('error', rejectListen);
36
+ server.listen(port, '127.0.0.1', () => {
37
+ server.off('error', rejectListen);
38
+ resolveListen();
39
+ });
40
+ });
41
+ console.error(`Mini App dev host: http://127.0.0.1:${port}/ (serving ${dist})`);
42
+ console.error('The host page answers parall.ready() with a local dev viewer; Ctrl-C to stop.');
43
+ }
44
+ catch (err) {
45
+ printError(err);
46
+ }
47
+ });
48
+ }
49
+ const devContentTypes = {
50
+ '.html': 'text/html; charset=utf-8',
51
+ '.js': 'text/javascript; charset=utf-8',
52
+ '.mjs': 'text/javascript; charset=utf-8',
53
+ '.css': 'text/css; charset=utf-8',
54
+ '.json': 'application/json',
55
+ '.svg': 'image/svg+xml',
56
+ '.png': 'image/png',
57
+ '.jpg': 'image/jpeg',
58
+ '.ico': 'image/x-icon',
59
+ '.map': 'application/json',
60
+ '.woff2': 'font/woff2',
61
+ };
62
+ async function handleDevRequest(dist, url, res) {
63
+ try {
64
+ const pathname = decodeURIComponent(new URL(url, 'http://localhost').pathname);
65
+ if (pathname === '/' || pathname === '/index.html') {
66
+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
67
+ res.end(devHostPage());
68
+ return;
69
+ }
70
+ if (pathname.startsWith('/app/')) {
71
+ const rel = normalize(pathname.slice('/app/'.length));
72
+ if (rel.startsWith('..') || rel.includes(`..${sep}`)) {
73
+ res.writeHead(404).end();
74
+ return;
75
+ }
76
+ const file = join(dist, rel === '' || rel === '.' ? 'index.html' : rel);
77
+ const body = await fs.readFile(file);
78
+ res.writeHead(200, {
79
+ 'Content-Type': devContentTypes[extname(file).toLowerCase()] ?? 'application/octet-stream',
80
+ });
81
+ res.end(body);
82
+ return;
83
+ }
84
+ res.writeHead(404).end('not found');
85
+ }
86
+ catch {
87
+ res.writeHead(404).end('not found');
88
+ }
89
+ }
90
+ /** The local host page: the host side of the bridge shell — answers ready
91
+ * with a dev viewer, relays resize, logs everything else. The same
92
+ * request/response protocol the real hosts speak (§6.3, shell subset). */
93
+ function devHostPage() {
94
+ return `<!doctype html>
95
+ <html>
96
+ <head><meta charset="utf-8"><title>Mini App dev host</title>
97
+ <style>body{margin:0;font-family:system-ui}header{padding:8px 12px;background:#111;color:#eee;font-size:13px}iframe{border:0;width:100%;height:calc(100vh - 37px)}</style>
98
+ </head>
99
+ <body>
100
+ <header>parall app dev — local host (bridge shell: ready / resize / route.changed)</header>
101
+ <iframe id="app" sandbox="allow-scripts allow-same-origin allow-downloads" src="/app/index.html"></iframe>
102
+ <script>
103
+ const frame = document.getElementById('app');
104
+ window.addEventListener('message', (event) => {
105
+ if (event.source !== frame.contentWindow) return;
106
+ const msg = event.data;
107
+ if (!msg || msg.parall !== 'v1' || typeof msg.id !== 'number') return;
108
+ if (msg.method === 'ready') {
109
+ frame.contentWindow.postMessage({ parall: 'v1', id: msg.id, result: {
110
+ viewer: { id: 'usr_dev', display_name: 'Dev Viewer', is_agent: false },
111
+ app: { id: 'app_dev', name: 'local dev', version_seq: 0 },
112
+ route: location.hash.slice(1) || '',
113
+ }}, '*');
114
+ } else if (msg.method === 'resize') {
115
+ frame.contentWindow.postMessage({ parall: 'v1', id: msg.id, result: {} }, '*');
116
+ } else {
117
+ const message = msg.method === 'action'
118
+ ? 'parall app dev serves the page only: start it with --app <app> to run its actions on this machine, or run one with parall app action run --local'
119
+ : msg.method + ' is not part of the bridge';
120
+ frame.contentWindow.postMessage({ parall: 'v1', id: msg.id, error: { code: 'NOT_GRANTED', message } }, '*');
121
+ }
122
+ });
123
+ </script>
124
+ </body>
125
+ </html>`;
126
+ }
@@ -0,0 +1,3 @@
1
+ export declare const LOCAL_RUNNER_COMPATIBILITY_DATE = "2026-04-01";
2
+ export declare const LOCAL_RUNNER_SOURCE = "// ../actions-worker/src/contract.ts\nvar INSTANCE = /^(default|pr-\\d{1,6})$/;\nvar APP_ID = /^app_[0-9a-z]{21}$/;\nvar SHA256 = /^[0-9a-f]{64}$/;\nvar ACTION_NAME = /^[a-zA-Z][a-zA-Z0-9_]{0,63}$/;\nvar INVOCATION_ID = /^[0-9A-Za-z_-]{1,64}$/;\nvar LIMIT_CEILINGS = {\n cpu_ms: 3e4,\n db_calls: 1e3,\n batch_statements: 1e3,\n batch_bytes: 8 * 1024 * 1024,\n result_bytes: 8 * 1024 * 1024,\n message_bytes: 64 * 1024,\n stack_bytes: 256 * 1024\n};\nfunction isRecord(v) {\n return typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\nfunction positiveInt(v, max) {\n return typeof v === \"number\" && Number.isInteger(v) && v > 0 && v <= max;\n}\nfunction parseInvokeRequest(raw, opts = {}) {\n if (!isRecord(raw)) return \"body is not an object\";\n const {\n invocation_id,\n instance,\n app,\n module,\n action,\n kind,\n viewer,\n ticket,\n deadline_ms,\n limits\n } = raw;\n if (typeof invocation_id !== \"string\" || !INVOCATION_ID.test(invocation_id))\n return \"invocation_id\";\n if (typeof instance !== \"string\" || !INSTANCE.test(instance)) return \"instance\";\n if (!isRecord(app) || typeof app.id !== \"string\" || !APP_ID.test(app.id)) return \"app.id\";\n if (!(opts.unpublished && app.version_seq === 0) && !positiveInt(app.version_seq, 2 ** 31))\n return \"app.version_seq\";\n if (!isRecord(module) || typeof module.sha256 !== \"string\" || !SHA256.test(module.sha256))\n return \"module.sha256\";\n if (typeof action !== \"string\" || !ACTION_NAME.test(action)) return \"action\";\n if (kind !== \"read\" && kind !== \"write\") return \"kind\";\n if (!(\"params\" in raw)) return \"params\";\n if (!isRecord(viewer) || typeof viewer.id !== \"string\" || typeof viewer.display_name !== \"string\" || typeof viewer.is_agent !== \"boolean\" || typeof viewer.role !== \"string\") {\n return \"viewer\";\n }\n if (typeof ticket !== \"string\" || ticket.length === 0 || ticket.length > 4096) return \"ticket\";\n if (typeof deadline_ms !== \"number\" || !Number.isFinite(deadline_ms)) return \"deadline_ms\";\n if (!isRecord(limits)) return \"limits\";\n for (const key of Object.keys(LIMIT_CEILINGS)) {\n if (!positiveInt(limits[key], LIMIT_CEILINGS[key])) return `limits.${key}`;\n }\n return {\n invocation_id,\n instance,\n app: { id: app.id, version_seq: app.version_seq },\n module: { sha256: module.sha256 },\n action,\n kind,\n params: raw.params,\n viewer: {\n id: viewer.id,\n display_name: viewer.display_name,\n is_agent: viewer.is_agent,\n role: viewer.role\n },\n ticket,\n deadline_ms,\n limits\n };\n}\n\n// ../actions-worker/src/db-caller.ts\nvar USER_AGENT = \"parall-actions-worker/1\";\nvar TICKET_HEADER = \"X-Prll-Action-Ticket\";\nvar INVOCATION_HEADER = \"X-Prll-Action-Invocation\";\nvar SWIMLANE_HEADER = \"X-Prll-Swimlane\";\nvar MAX_SQL_BYTES = 256 * 1024;\nvar encoder = new TextEncoder();\nfunction handleError(code, message) {\n const err = new Error(message);\n err.name = \"ActionDbError\";\n err.code = code;\n return err;\n}\nfunction statementOf(v) {\n if (typeof v !== \"object\" || v === null) return null;\n const { sql, params } = v;\n if (typeof sql !== \"string\" || sql.length === 0 || encoder.encode(sql).byteLength > MAX_SQL_BYTES)\n return null;\n if (params !== void 0 && !Array.isArray(params)) return null;\n return { sql, params: params ?? [] };\n}\nfunction requestBody(op, payload, limits) {\n if (op === \"batch\") {\n const statements = payload?.statements;\n if (!Array.isArray(statements) || statements.length === 0) {\n throw handleError(\"ACTION_INVALID_CALL\", \"batch needs a non-empty array of { sql, params }\");\n }\n if (statements.length > limits.batch_statements) {\n throw handleError(\n \"ACTION_LIMIT_EXCEEDED\",\n `a batch may hold at most ${limits.batch_statements} statements`\n );\n }\n const parsed = statements.map(statementOf);\n if (parsed.some((s) => s === null)) {\n throw handleError(\n \"ACTION_INVALID_CALL\",\n \"every batch entry needs a non-empty sql string and a params array\"\n );\n }\n const body = JSON.stringify({ statements: parsed });\n if (encoder.encode(body).byteLength > limits.batch_bytes) {\n throw handleError(\n \"ACTION_LIMIT_EXCEEDED\",\n `a batch may be at most ${limits.batch_bytes} bytes`\n );\n }\n return body;\n }\n const statement = statementOf(payload);\n if (!statement)\n throw handleError(\n \"ACTION_INVALID_CALL\",\n `${op} needs a non-empty sql string and a params array`\n );\n return JSON.stringify(statement);\n}\nfunction trackDataSeq(state, result) {\n const seq = result?.data_seq;\n if (typeof seq !== \"number\" || !Number.isInteger(seq)) return;\n state.dataSeq = state.dataSeq ? { from: Math.min(state.dataSeq.from, seq), to: Math.max(state.dataSeq.to, seq) } : { from: seq, to: seq };\n}\nasync function readCapped(res, maxBytes) {\n if (!res.body) return \"\";\n const reader = res.body.getReader();\n const chunks = [];\n let total = 0;\n for (; ; ) {\n const { done, value } = await reader.read();\n if (done) break;\n total += value.byteLength;\n if (total > maxBytes) {\n await reader.cancel();\n throw handleError(\n \"ACTION_RESULT_TOO_LARGE\",\n `a database result may be at most ${maxBytes} bytes`\n );\n }\n chunks.push(value);\n }\n const out = new Uint8Array(total);\n let off = 0;\n for (const c of chunks) {\n out.set(c, off);\n off += c.byteLength;\n }\n return new TextDecoder().decode(out);\n}\nfunction createDbCaller(cfg) {\n const fetchImpl = cfg.fetchImpl ?? fetch;\n const now = cfg.now ?? Date.now;\n const state = {\n revoked: false,\n calls: 0,\n limitHit: false,\n inflight: /* @__PURE__ */ new Set(),\n dataSeq: null,\n indeterminate: false\n };\n const origin = cfg.callbackOrigin.replace(/\\/+$/, \"\");\n async function send(op, body) {\n const headers = {\n \"Content-Type\": \"application/json\",\n \"User-Agent\": USER_AGENT,\n [TICKET_HEADER]: cfg.ticket,\n [INVOCATION_HEADER]: cfg.invocationId\n };\n if (cfg.instance !== \"default\") headers[SWIMLANE_HEADER] = cfg.instance;\n const remaining = Math.max(1, cfg.deadlineMs - now());\n let res;\n try {\n res = await fetchImpl(`${origin}/api/v1/mini-app-actions/db/${op}`, {\n method: \"POST\",\n headers,\n body,\n signal: AbortSignal.timeout(remaining)\n });\n } catch {\n if (op !== \"query\") state.indeterminate = true;\n throw handleError(\"ACTION_DB_UNAVAILABLE\", \"the database could not be reached\");\n }\n let parsed;\n try {\n const text = await readCapped(res, cfg.limits.result_bytes + 64 * 1024);\n parsed = text ? JSON.parse(text) : null;\n } catch (err) {\n if (op !== \"query\") state.indeterminate = true;\n if (err.code === \"ACTION_RESULT_TOO_LARGE\") throw err;\n throw handleError(\"ACTION_DB_UNAVAILABLE\", \"the database returned an unreadable response\");\n }\n if (!res.ok) {\n const env = parsed?.error;\n if (typeof env?.code !== \"string\") {\n if (op !== \"query\") state.indeterminate = true;\n throw handleError(`HTTP_${res.status}`, `database call failed (${res.status})`);\n }\n const message = typeof env.message === \"string\" ? env.message : `database call failed (${res.status})`;\n throw handleError(env.code, message);\n }\n trackDataSeq(state, parsed);\n return parsed;\n }\n async function call(op, payload) {\n if (state.revoked)\n throw handleError(\"ACTION_HANDLE_REVOKED\", \"this database handle is no longer valid\");\n if (now() >= cfg.deadlineMs)\n throw handleError(\"ACTION_DEADLINE\", \"the action ran past its deadline\");\n if (cfg.kind === \"read\" && op !== \"query\") {\n throw handleError(\"ACTION_READ_ONLY\", \"a read action can only query\");\n }\n state.calls++;\n if (state.calls > cfg.limits.db_calls) {\n state.limitHit = true;\n throw handleError(\n \"ACTION_LIMIT_EXCEEDED\",\n `an action may make at most ${cfg.limits.db_calls} database calls`\n );\n }\n const body = requestBody(op, payload, cfg.limits);\n const pending = send(op, body);\n state.inflight.add(pending);\n try {\n return await pending;\n } finally {\n state.inflight.delete(pending);\n }\n }\n return { state, call };\n}\nasync function settleCall(caller, op, payload) {\n try {\n return { ok: true, value: await caller.call(op, payload) };\n } catch (err) {\n const { code, message } = err ?? {};\n return {\n ok: false,\n error: {\n code: typeof code === \"string\" ? code : \"ACTION_DB_UNAVAILABLE\",\n message: typeof message === \"string\" ? message : \"the database call failed\"\n }\n };\n }\n}\nasync function settle(caller, deadlineMs, now = Date.now) {\n caller.state.revoked = true;\n const inflight = [...caller.state.inflight];\n if (inflight.length === 0) return true;\n const remaining = deadlineMs - now();\n if (remaining > 0) {\n let timer = null;\n await Promise.race([\n Promise.allSettled(inflight),\n new Promise((r) => {\n timer = setTimeout(r, remaining);\n })\n ]);\n if (timer !== null) clearTimeout(timer);\n }\n return caller.state.inflight.size === 0;\n}\n\n// ../actions-worker/src/handle.ts\nimport { RpcTarget } from \"cloudflare:workers\";\nvar ActionDb = class extends RpcTarget {\n #caller;\n constructor(caller) {\n super();\n this.#caller = caller;\n }\n query(sql, params) {\n return settleCall(this.#caller, \"query\", { sql, params });\n }\n exec(sql, params) {\n return settleCall(this.#caller, \"exec\", { sql, params });\n }\n batch(statements) {\n return settleCall(this.#caller, \"batch\", { statements });\n }\n};\nfunction makeHandle(caller) {\n return new ActionDb(caller);\n}\n\n// ../actions-worker/src/outcome.ts\nvar encoder2 = new TextEncoder();\nfunction truncateBytes(s, maxBytes) {\n const bytes = encoder2.encode(s);\n if (bytes.byteLength <= maxBytes) return s;\n return new TextDecoder().decode(bytes.subarray(0, maxBytes)).replace(/\uFFFD+$/u, \"\");\n}\nfunction base(state) {\n return { db_calls: state.calls, data_seq: state.dataSeq };\n}\nfunction failed(state, error) {\n if (state.limitHit) {\n return {\n status: \"limit_exceeded\",\n error: { kind: \"limit\", message: \"the action made more database calls than allowed\" },\n ...base(state)\n };\n }\n return { status: \"failed\", error, ...base(state) };\n}\nfunction asString(v) {\n return typeof v === \"string\" ? v : \"\";\n}\nfunction outcomeFromResult(raw, limits, state) {\n if (typeof raw === \"object\" && raw !== null && !Array.isArray(raw)) {\n const r = raw;\n if (r.ok === true && typeof r.json === \"string\") {\n if (encoder2.encode(r.json).byteLength > limits.result_bytes) {\n return failed(state, {\n kind: \"unexpected\",\n message: `the action result is larger than ${limits.result_bytes} bytes`\n });\n }\n return { status: \"ok\", result_json: r.json, ...base(state) };\n }\n if (r.ok === false && typeof r.error === \"object\" && r.error !== null) {\n const e = r.error;\n if (e.kind === \"action_error\") {\n return failed(state, {\n kind: \"action_error\",\n message: truncateBytes(asString(e.message), limits.message_bytes)\n });\n }\n return failed(state, {\n kind: \"unexpected\",\n message: truncateBytes(asString(e.message), limits.message_bytes),\n stack: truncateBytes(asString(e.stack), limits.stack_bytes)\n });\n }\n }\n return failed(state, {\n kind: \"unexpected\",\n message: \"the action returned a result in an unknown shape\"\n });\n}\nvar CPU_LIMIT = /exceeded (its )?cpu|cpu time limit|exceeded resource limits/i;\nfunction isCpuLimitError(err) {\n const message = err instanceof Error ? err.message : String(err);\n return CPU_LIMIT.test(message);\n}\nfunction outcomeFromThrown(err, limits, state) {\n if (isCpuLimitError(err)) {\n return {\n status: \"limit_exceeded\",\n error: { kind: \"limit\", message: \"the action ran past its CPU time limit\" },\n ...base(state)\n };\n }\n const message = err instanceof Error ? `${err.name}: ${err.message}` : String(err);\n return failed(state, {\n kind: \"unexpected\",\n message: truncateBytes(message, limits.message_bytes)\n });\n}\nfunction timeoutOutcome(state) {\n return {\n status: \"timeout\",\n error: {\n kind: \"timeout\",\n message: \"the action ran past its deadline or lost a database answer; writes it started may have committed\"\n },\n ...base(state)\n };\n}\n\n// ../actions-worker/src/sandbox.ts\nvar COMPATIBILITY_DATE = \"2026-04-01\";\nvar COMPATIBILITY_FLAGS = [];\nvar ENTRYPOINT = \"ActionRunner\";\nvar PRELUDE = `// Runs before the author module (see actions-worker src/sandbox.ts).\nfor (const name of ['caches', 'WebSocket']) {\n try {\n delete globalThis[name];\n } catch {}\n if (name in globalThis) {\n Object.defineProperty(globalThis, name, { value: undefined, writable: false, configurable: false });\n }\n}\n`;\nvar ENTRY = `import './prelude.js';\nexport * from './author.js';\n`;\nfunction workerCode(authorSource) {\n return {\n compatibilityDate: COMPATIBILITY_DATE,\n compatibilityFlags: COMPATIBILITY_FLAGS,\n mainModule: \"entry.js\",\n modules: { \"entry.js\": ENTRY, \"prelude.js\": PRELUDE, \"author.js\": authorSource },\n env: {},\n globalOutbound: null\n };\n}\nvar runtimeVersion = null;\nfunction runtimeVersionOf() {\n if (!runtimeVersion) {\n const material = JSON.stringify([\n COMPATIBILITY_DATE,\n COMPATIBILITY_FLAGS,\n ENTRYPOINT,\n PRELUDE,\n ENTRY,\n \"env:{}\",\n \"outbound:null\"\n ]);\n runtimeVersion = crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(material)).then(\n (d) => Array.from(new Uint8Array(d).slice(0, 8), (b) => b.toString(16).padStart(2, \"0\")).join(\"\")\n );\n }\n return runtimeVersion;\n}\nfunction isolateId(instance, appId, sha256, runtime) {\n return `${instance}:${appId}:${sha256}:${runtime}`;\n}\n\n// ../actions-worker/src/run.ts\nvar DEADLINE_MARGIN_MS = 250;\nasync function runWithDeadline(call, budgetMs) {\n if (budgetMs <= 0) return { kind: \"timeout\" };\n let timer = null;\n const timedOut = new Promise((resolve) => {\n timer = setTimeout(() => resolve({ kind: \"timeout\" }), budgetMs);\n });\n try {\n return await Promise.race([\n call().then(\n (value) => ({ kind: \"result\", value }),\n (error) => ({ kind: \"thrown\", error })\n ),\n timedOut\n ]);\n } finally {\n if (timer !== null) clearTimeout(timer);\n }\n}\nasync function runInvocation(worker, req, callbackOrigin, loadFailure = () => null) {\n const effectiveDeadline = req.deadline_ms - DEADLINE_MARGIN_MS;\n const caller = createDbCaller({\n kind: req.kind,\n ticket: req.ticket,\n invocationId: req.invocation_id,\n instance: req.instance,\n callbackOrigin,\n deadlineMs: effectiveDeadline,\n limits: req.limits\n });\n const handle = makeHandle(caller);\n const entry = worker.getEntrypoint(ENTRYPOINT, { limits: { cpuMs: req.limits.cpu_ms } });\n const settled = await runWithDeadline(\n () => entry.run(\n {\n action: req.action,\n params: req.params,\n viewer: req.viewer,\n app: req.app,\n invocation_id: req.invocation_id\n },\n handle\n ),\n effectiveDeadline - Date.now()\n );\n const drained = await settle(caller, effectiveDeadline);\n if (settled.kind === \"timeout\" || !drained || caller.state.indeterminate) {\n return timeoutOutcome(caller.state);\n }\n if (settled.kind === \"thrown\") {\n return loadFailure() ?? outcomeFromThrown(settled.error, req.limits, caller.state);\n }\n return outcomeFromResult(settled.value, req.limits, caller.state);\n}\n\n// ../actions-worker/src/local.ts\nvar local_default = {\n async fetch(request, env) {\n let body;\n try {\n body = await request.json();\n } catch {\n return Response.json({ error: \"body is not JSON\" }, { status: 400 });\n }\n const req = parseInvokeRequest(body?.request, { unpublished: true });\n if (typeof req === \"string\") return Response.json({ error: `invalid ${req}` }, { status: 400 });\n if (typeof body.source !== \"string\" || typeof body.callback_origin !== \"string\") {\n return Response.json({ error: \"source and callback_origin are required\" }, { status: 400 });\n }\n const runtime = await runtimeVersionOf();\n const worker = env.LOADER.get(\n isolateId(req.instance, req.app.id, req.module.sha256, runtime),\n async () => workerCode(body.source)\n );\n return Response.json(await runInvocation(worker, req, body.callback_origin));\n }\n};\nexport {\n local_default as default\n};\n";
3
+ //# sourceMappingURL=apps-local-runner.generated.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"apps-local-runner.generated.d.ts","sourceRoot":"","sources":["../../src/commands/apps-local-runner.generated.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,+BAA+B,eAAe,CAAC;AAE5D,eAAO,MAAM,mBAAmB,47hBAAu7hB,CAAC"}
@@ -0,0 +1,4 @@
1
+ // Generated from ts/actions-worker/src/local.ts by scripts/generate-local-runner.mjs. Do not edit.
2
+ export const LOCAL_RUNNER_COMPATIBILITY_DATE = '2026-04-01';
3
+ // biome-ignore format: generated copy
4
+ export const LOCAL_RUNNER_SOURCE = "// ../actions-worker/src/contract.ts\nvar INSTANCE = /^(default|pr-\\d{1,6})$/;\nvar APP_ID = /^app_[0-9a-z]{21}$/;\nvar SHA256 = /^[0-9a-f]{64}$/;\nvar ACTION_NAME = /^[a-zA-Z][a-zA-Z0-9_]{0,63}$/;\nvar INVOCATION_ID = /^[0-9A-Za-z_-]{1,64}$/;\nvar LIMIT_CEILINGS = {\n cpu_ms: 3e4,\n db_calls: 1e3,\n batch_statements: 1e3,\n batch_bytes: 8 * 1024 * 1024,\n result_bytes: 8 * 1024 * 1024,\n message_bytes: 64 * 1024,\n stack_bytes: 256 * 1024\n};\nfunction isRecord(v) {\n return typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\nfunction positiveInt(v, max) {\n return typeof v === \"number\" && Number.isInteger(v) && v > 0 && v <= max;\n}\nfunction parseInvokeRequest(raw, opts = {}) {\n if (!isRecord(raw)) return \"body is not an object\";\n const {\n invocation_id,\n instance,\n app,\n module,\n action,\n kind,\n viewer,\n ticket,\n deadline_ms,\n limits\n } = raw;\n if (typeof invocation_id !== \"string\" || !INVOCATION_ID.test(invocation_id))\n return \"invocation_id\";\n if (typeof instance !== \"string\" || !INSTANCE.test(instance)) return \"instance\";\n if (!isRecord(app) || typeof app.id !== \"string\" || !APP_ID.test(app.id)) return \"app.id\";\n if (!(opts.unpublished && app.version_seq === 0) && !positiveInt(app.version_seq, 2 ** 31))\n return \"app.version_seq\";\n if (!isRecord(module) || typeof module.sha256 !== \"string\" || !SHA256.test(module.sha256))\n return \"module.sha256\";\n if (typeof action !== \"string\" || !ACTION_NAME.test(action)) return \"action\";\n if (kind !== \"read\" && kind !== \"write\") return \"kind\";\n if (!(\"params\" in raw)) return \"params\";\n if (!isRecord(viewer) || typeof viewer.id !== \"string\" || typeof viewer.display_name !== \"string\" || typeof viewer.is_agent !== \"boolean\" || typeof viewer.role !== \"string\") {\n return \"viewer\";\n }\n if (typeof ticket !== \"string\" || ticket.length === 0 || ticket.length > 4096) return \"ticket\";\n if (typeof deadline_ms !== \"number\" || !Number.isFinite(deadline_ms)) return \"deadline_ms\";\n if (!isRecord(limits)) return \"limits\";\n for (const key of Object.keys(LIMIT_CEILINGS)) {\n if (!positiveInt(limits[key], LIMIT_CEILINGS[key])) return `limits.${key}`;\n }\n return {\n invocation_id,\n instance,\n app: { id: app.id, version_seq: app.version_seq },\n module: { sha256: module.sha256 },\n action,\n kind,\n params: raw.params,\n viewer: {\n id: viewer.id,\n display_name: viewer.display_name,\n is_agent: viewer.is_agent,\n role: viewer.role\n },\n ticket,\n deadline_ms,\n limits\n };\n}\n\n// ../actions-worker/src/db-caller.ts\nvar USER_AGENT = \"parall-actions-worker/1\";\nvar TICKET_HEADER = \"X-Prll-Action-Ticket\";\nvar INVOCATION_HEADER = \"X-Prll-Action-Invocation\";\nvar SWIMLANE_HEADER = \"X-Prll-Swimlane\";\nvar MAX_SQL_BYTES = 256 * 1024;\nvar encoder = new TextEncoder();\nfunction handleError(code, message) {\n const err = new Error(message);\n err.name = \"ActionDbError\";\n err.code = code;\n return err;\n}\nfunction statementOf(v) {\n if (typeof v !== \"object\" || v === null) return null;\n const { sql, params } = v;\n if (typeof sql !== \"string\" || sql.length === 0 || encoder.encode(sql).byteLength > MAX_SQL_BYTES)\n return null;\n if (params !== void 0 && !Array.isArray(params)) return null;\n return { sql, params: params ?? [] };\n}\nfunction requestBody(op, payload, limits) {\n if (op === \"batch\") {\n const statements = payload?.statements;\n if (!Array.isArray(statements) || statements.length === 0) {\n throw handleError(\"ACTION_INVALID_CALL\", \"batch needs a non-empty array of { sql, params }\");\n }\n if (statements.length > limits.batch_statements) {\n throw handleError(\n \"ACTION_LIMIT_EXCEEDED\",\n `a batch may hold at most ${limits.batch_statements} statements`\n );\n }\n const parsed = statements.map(statementOf);\n if (parsed.some((s) => s === null)) {\n throw handleError(\n \"ACTION_INVALID_CALL\",\n \"every batch entry needs a non-empty sql string and a params array\"\n );\n }\n const body = JSON.stringify({ statements: parsed });\n if (encoder.encode(body).byteLength > limits.batch_bytes) {\n throw handleError(\n \"ACTION_LIMIT_EXCEEDED\",\n `a batch may be at most ${limits.batch_bytes} bytes`\n );\n }\n return body;\n }\n const statement = statementOf(payload);\n if (!statement)\n throw handleError(\n \"ACTION_INVALID_CALL\",\n `${op} needs a non-empty sql string and a params array`\n );\n return JSON.stringify(statement);\n}\nfunction trackDataSeq(state, result) {\n const seq = result?.data_seq;\n if (typeof seq !== \"number\" || !Number.isInteger(seq)) return;\n state.dataSeq = state.dataSeq ? { from: Math.min(state.dataSeq.from, seq), to: Math.max(state.dataSeq.to, seq) } : { from: seq, to: seq };\n}\nasync function readCapped(res, maxBytes) {\n if (!res.body) return \"\";\n const reader = res.body.getReader();\n const chunks = [];\n let total = 0;\n for (; ; ) {\n const { done, value } = await reader.read();\n if (done) break;\n total += value.byteLength;\n if (total > maxBytes) {\n await reader.cancel();\n throw handleError(\n \"ACTION_RESULT_TOO_LARGE\",\n `a database result may be at most ${maxBytes} bytes`\n );\n }\n chunks.push(value);\n }\n const out = new Uint8Array(total);\n let off = 0;\n for (const c of chunks) {\n out.set(c, off);\n off += c.byteLength;\n }\n return new TextDecoder().decode(out);\n}\nfunction createDbCaller(cfg) {\n const fetchImpl = cfg.fetchImpl ?? fetch;\n const now = cfg.now ?? Date.now;\n const state = {\n revoked: false,\n calls: 0,\n limitHit: false,\n inflight: /* @__PURE__ */ new Set(),\n dataSeq: null,\n indeterminate: false\n };\n const origin = cfg.callbackOrigin.replace(/\\/+$/, \"\");\n async function send(op, body) {\n const headers = {\n \"Content-Type\": \"application/json\",\n \"User-Agent\": USER_AGENT,\n [TICKET_HEADER]: cfg.ticket,\n [INVOCATION_HEADER]: cfg.invocationId\n };\n if (cfg.instance !== \"default\") headers[SWIMLANE_HEADER] = cfg.instance;\n const remaining = Math.max(1, cfg.deadlineMs - now());\n let res;\n try {\n res = await fetchImpl(`${origin}/api/v1/mini-app-actions/db/${op}`, {\n method: \"POST\",\n headers,\n body,\n signal: AbortSignal.timeout(remaining)\n });\n } catch {\n if (op !== \"query\") state.indeterminate = true;\n throw handleError(\"ACTION_DB_UNAVAILABLE\", \"the database could not be reached\");\n }\n let parsed;\n try {\n const text = await readCapped(res, cfg.limits.result_bytes + 64 * 1024);\n parsed = text ? JSON.parse(text) : null;\n } catch (err) {\n if (op !== \"query\") state.indeterminate = true;\n if (err.code === \"ACTION_RESULT_TOO_LARGE\") throw err;\n throw handleError(\"ACTION_DB_UNAVAILABLE\", \"the database returned an unreadable response\");\n }\n if (!res.ok) {\n const env = parsed?.error;\n if (typeof env?.code !== \"string\") {\n if (op !== \"query\") state.indeterminate = true;\n throw handleError(`HTTP_${res.status}`, `database call failed (${res.status})`);\n }\n const message = typeof env.message === \"string\" ? env.message : `database call failed (${res.status})`;\n throw handleError(env.code, message);\n }\n trackDataSeq(state, parsed);\n return parsed;\n }\n async function call(op, payload) {\n if (state.revoked)\n throw handleError(\"ACTION_HANDLE_REVOKED\", \"this database handle is no longer valid\");\n if (now() >= cfg.deadlineMs)\n throw handleError(\"ACTION_DEADLINE\", \"the action ran past its deadline\");\n if (cfg.kind === \"read\" && op !== \"query\") {\n throw handleError(\"ACTION_READ_ONLY\", \"a read action can only query\");\n }\n state.calls++;\n if (state.calls > cfg.limits.db_calls) {\n state.limitHit = true;\n throw handleError(\n \"ACTION_LIMIT_EXCEEDED\",\n `an action may make at most ${cfg.limits.db_calls} database calls`\n );\n }\n const body = requestBody(op, payload, cfg.limits);\n const pending = send(op, body);\n state.inflight.add(pending);\n try {\n return await pending;\n } finally {\n state.inflight.delete(pending);\n }\n }\n return { state, call };\n}\nasync function settleCall(caller, op, payload) {\n try {\n return { ok: true, value: await caller.call(op, payload) };\n } catch (err) {\n const { code, message } = err ?? {};\n return {\n ok: false,\n error: {\n code: typeof code === \"string\" ? code : \"ACTION_DB_UNAVAILABLE\",\n message: typeof message === \"string\" ? message : \"the database call failed\"\n }\n };\n }\n}\nasync function settle(caller, deadlineMs, now = Date.now) {\n caller.state.revoked = true;\n const inflight = [...caller.state.inflight];\n if (inflight.length === 0) return true;\n const remaining = deadlineMs - now();\n if (remaining > 0) {\n let timer = null;\n await Promise.race([\n Promise.allSettled(inflight),\n new Promise((r) => {\n timer = setTimeout(r, remaining);\n })\n ]);\n if (timer !== null) clearTimeout(timer);\n }\n return caller.state.inflight.size === 0;\n}\n\n// ../actions-worker/src/handle.ts\nimport { RpcTarget } from \"cloudflare:workers\";\nvar ActionDb = class extends RpcTarget {\n #caller;\n constructor(caller) {\n super();\n this.#caller = caller;\n }\n query(sql, params) {\n return settleCall(this.#caller, \"query\", { sql, params });\n }\n exec(sql, params) {\n return settleCall(this.#caller, \"exec\", { sql, params });\n }\n batch(statements) {\n return settleCall(this.#caller, \"batch\", { statements });\n }\n};\nfunction makeHandle(caller) {\n return new ActionDb(caller);\n}\n\n// ../actions-worker/src/outcome.ts\nvar encoder2 = new TextEncoder();\nfunction truncateBytes(s, maxBytes) {\n const bytes = encoder2.encode(s);\n if (bytes.byteLength <= maxBytes) return s;\n return new TextDecoder().decode(bytes.subarray(0, maxBytes)).replace(/�+$/u, \"\");\n}\nfunction base(state) {\n return { db_calls: state.calls, data_seq: state.dataSeq };\n}\nfunction failed(state, error) {\n if (state.limitHit) {\n return {\n status: \"limit_exceeded\",\n error: { kind: \"limit\", message: \"the action made more database calls than allowed\" },\n ...base(state)\n };\n }\n return { status: \"failed\", error, ...base(state) };\n}\nfunction asString(v) {\n return typeof v === \"string\" ? v : \"\";\n}\nfunction outcomeFromResult(raw, limits, state) {\n if (typeof raw === \"object\" && raw !== null && !Array.isArray(raw)) {\n const r = raw;\n if (r.ok === true && typeof r.json === \"string\") {\n if (encoder2.encode(r.json).byteLength > limits.result_bytes) {\n return failed(state, {\n kind: \"unexpected\",\n message: `the action result is larger than ${limits.result_bytes} bytes`\n });\n }\n return { status: \"ok\", result_json: r.json, ...base(state) };\n }\n if (r.ok === false && typeof r.error === \"object\" && r.error !== null) {\n const e = r.error;\n if (e.kind === \"action_error\") {\n return failed(state, {\n kind: \"action_error\",\n message: truncateBytes(asString(e.message), limits.message_bytes)\n });\n }\n return failed(state, {\n kind: \"unexpected\",\n message: truncateBytes(asString(e.message), limits.message_bytes),\n stack: truncateBytes(asString(e.stack), limits.stack_bytes)\n });\n }\n }\n return failed(state, {\n kind: \"unexpected\",\n message: \"the action returned a result in an unknown shape\"\n });\n}\nvar CPU_LIMIT = /exceeded (its )?cpu|cpu time limit|exceeded resource limits/i;\nfunction isCpuLimitError(err) {\n const message = err instanceof Error ? err.message : String(err);\n return CPU_LIMIT.test(message);\n}\nfunction outcomeFromThrown(err, limits, state) {\n if (isCpuLimitError(err)) {\n return {\n status: \"limit_exceeded\",\n error: { kind: \"limit\", message: \"the action ran past its CPU time limit\" },\n ...base(state)\n };\n }\n const message = err instanceof Error ? `${err.name}: ${err.message}` : String(err);\n return failed(state, {\n kind: \"unexpected\",\n message: truncateBytes(message, limits.message_bytes)\n });\n}\nfunction timeoutOutcome(state) {\n return {\n status: \"timeout\",\n error: {\n kind: \"timeout\",\n message: \"the action ran past its deadline or lost a database answer; writes it started may have committed\"\n },\n ...base(state)\n };\n}\n\n// ../actions-worker/src/sandbox.ts\nvar COMPATIBILITY_DATE = \"2026-04-01\";\nvar COMPATIBILITY_FLAGS = [];\nvar ENTRYPOINT = \"ActionRunner\";\nvar PRELUDE = `// Runs before the author module (see actions-worker src/sandbox.ts).\nfor (const name of ['caches', 'WebSocket']) {\n try {\n delete globalThis[name];\n } catch {}\n if (name in globalThis) {\n Object.defineProperty(globalThis, name, { value: undefined, writable: false, configurable: false });\n }\n}\n`;\nvar ENTRY = `import './prelude.js';\nexport * from './author.js';\n`;\nfunction workerCode(authorSource) {\n return {\n compatibilityDate: COMPATIBILITY_DATE,\n compatibilityFlags: COMPATIBILITY_FLAGS,\n mainModule: \"entry.js\",\n modules: { \"entry.js\": ENTRY, \"prelude.js\": PRELUDE, \"author.js\": authorSource },\n env: {},\n globalOutbound: null\n };\n}\nvar runtimeVersion = null;\nfunction runtimeVersionOf() {\n if (!runtimeVersion) {\n const material = JSON.stringify([\n COMPATIBILITY_DATE,\n COMPATIBILITY_FLAGS,\n ENTRYPOINT,\n PRELUDE,\n ENTRY,\n \"env:{}\",\n \"outbound:null\"\n ]);\n runtimeVersion = crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(material)).then(\n (d) => Array.from(new Uint8Array(d).slice(0, 8), (b) => b.toString(16).padStart(2, \"0\")).join(\"\")\n );\n }\n return runtimeVersion;\n}\nfunction isolateId(instance, appId, sha256, runtime) {\n return `${instance}:${appId}:${sha256}:${runtime}`;\n}\n\n// ../actions-worker/src/run.ts\nvar DEADLINE_MARGIN_MS = 250;\nasync function runWithDeadline(call, budgetMs) {\n if (budgetMs <= 0) return { kind: \"timeout\" };\n let timer = null;\n const timedOut = new Promise((resolve) => {\n timer = setTimeout(() => resolve({ kind: \"timeout\" }), budgetMs);\n });\n try {\n return await Promise.race([\n call().then(\n (value) => ({ kind: \"result\", value }),\n (error) => ({ kind: \"thrown\", error })\n ),\n timedOut\n ]);\n } finally {\n if (timer !== null) clearTimeout(timer);\n }\n}\nasync function runInvocation(worker, req, callbackOrigin, loadFailure = () => null) {\n const effectiveDeadline = req.deadline_ms - DEADLINE_MARGIN_MS;\n const caller = createDbCaller({\n kind: req.kind,\n ticket: req.ticket,\n invocationId: req.invocation_id,\n instance: req.instance,\n callbackOrigin,\n deadlineMs: effectiveDeadline,\n limits: req.limits\n });\n const handle = makeHandle(caller);\n const entry = worker.getEntrypoint(ENTRYPOINT, { limits: { cpuMs: req.limits.cpu_ms } });\n const settled = await runWithDeadline(\n () => entry.run(\n {\n action: req.action,\n params: req.params,\n viewer: req.viewer,\n app: req.app,\n invocation_id: req.invocation_id\n },\n handle\n ),\n effectiveDeadline - Date.now()\n );\n const drained = await settle(caller, effectiveDeadline);\n if (settled.kind === \"timeout\" || !drained || caller.state.indeterminate) {\n return timeoutOutcome(caller.state);\n }\n if (settled.kind === \"thrown\") {\n return loadFailure() ?? outcomeFromThrown(settled.error, req.limits, caller.state);\n }\n return outcomeFromResult(settled.value, req.limits, caller.state);\n}\n\n// ../actions-worker/src/local.ts\nvar local_default = {\n async fetch(request, env) {\n let body;\n try {\n body = await request.json();\n } catch {\n return Response.json({ error: \"body is not JSON\" }, { status: 400 });\n }\n const req = parseInvokeRequest(body?.request, { unpublished: true });\n if (typeof req === \"string\") return Response.json({ error: `invalid ${req}` }, { status: 400 });\n if (typeof body.source !== \"string\" || typeof body.callback_origin !== \"string\") {\n return Response.json({ error: \"source and callback_origin are required\" }, { status: 400 });\n }\n const runtime = await runtimeVersionOf();\n const worker = env.LOADER.get(\n isolateId(req.instance, req.app.id, req.module.sha256, runtime),\n async () => workerCode(body.source)\n );\n return Response.json(await runInvocation(worker, req, body.callback_origin));\n }\n};\nexport {\n local_default as default\n};\n";
@@ -0,0 +1,2 @@
1
+ export declare const PAGE_SDK_SOURCE = "/**\n * @parall/miniapp-sdk \u2014 the page side of the Mini App bridge (design \u00A77.1):\n * host handshake, host\u2192page events, resize, and `action`, the page's only\n * data method: it calls one of the app's server-side actions through the\n * host, which adds the viewer's session and the version the page loaded\n * (Mini App Action design \u00A73.1). No db, files, clip or chat methods exist\n * on this surface. The transport is postMessage to window.parent; the host\n * validates our origin, we validate that messages come from our parent\n * and, after the first answer, pin the parent's origin.\n *\n * Protocol (request/response + events):\n * page \u2192 host {parall: 'v1', id, method: 'ready' | 'resize' | 'action' | 'report', params}\n * host \u2192 page {parall: 'v1', id, result} | {parall: 'v1', id, error: {code, message, details?}}\n * host \u2192 page {parall: 'v1', event: 'route.changed' | 'viewer.changed' | 'data.changed', data}\n */\n\nexport interface ViewerSummary {\n id: string;\n display_name: string;\n is_agent: boolean;\n /** The viewer's organization role (owner / admin / member) \u2014 the same\n * value an action sees as ctx.viewer.role. */\n role?: string;\n}\n\nexport interface AppSummary {\n id: string;\n name: string;\n version_seq: number;\n}\n\nexport interface ReadyResult {\n viewer: ViewerSummary;\n app: AppSummary;\n route: string;\n}\n\n/** A Database the app reads was written. It carries no data: read again. */\nexport interface DataChanged {\n database_id: string;\n data_seq: number;\n /** Sent once after the host's connection came back: writes in between\n * may have been missed, so read again whatever data_seq says. */\n catch_up?: boolean;\n}\n\nexport type HostEvent =\n | { event: 'route.changed'; data: { route: string } }\n | { event: 'viewer.changed'; data: { viewer: ViewerSummary } }\n | { event: 'data.changed'; data: DataChanged };\n\n/** A refusal or failure from the host, in the error-contract envelope. An\n * action's failure keeps the server's code and details (invocation_id,\n * error_kind, field, current_version_seq\u2026); APP_VERSION_CHANGED means the\n * app was updated and the host offers the viewer a reload. */\nexport interface BridgeError extends Error {\n code: string;\n details?: Record<string, unknown>;\n}\n\ninterface WireError {\n code: string;\n message: string;\n details?: Record<string, unknown>;\n}\n\ntype Pending = {\n resolve: (v: unknown) => void;\n reject: (e: Error) => void;\n timer: ReturnType<typeof setTimeout>;\n};\n\nconst PROTOCOL = 'v1';\n\n// How long the page waits for the host. An action waits longer than the\n// host's request timeout, which waits longer than the server takes to\n// answer at worst, so the page always gets the server's answer rather than\n// a timeout of its own (Mini App Action design \u00A73.1, \u00A715).\nconst HOST_TIMEOUT_MS = 10_000;\nconst ACTION_TIMEOUT_MS = 30_000;\n\n// Marks the errors the bridge itself rejects with: what the host or the\n// server answered, never the page's own bug.\nconst FROM_BRIDGE = Symbol.for('parall.bridge-error');\n\nfunction bridgeError(\n code: string,\n message: string,\n details?: Record<string, unknown>,\n): BridgeError {\n const err = Object.assign(new Error(message), { code, details }) as BridgeError;\n Object.defineProperty(err, FROM_BRIDGE, { value: true });\n return err;\n}\n\n/**\n * What a page reports when something goes wrong (Mini App design \u00A79): an\n * error thrown on the page, a promise rejected without a handler, and an\n * action call that failed unexpectedly, timed out or ran over its limits.\n * Never console.error, and never an ActionError \u2014 that is the author's own\n * message to the caller. The host adds the version the page loaded and\n * reports it in the viewer's name; the app's authors are told.\n */\ntype ErrorReport = {\n kind: 'exception' | 'rejection' | 'action';\n name?: string;\n message?: string;\n stack?: string;\n action?: string;\n code?: string;\n invocation_id?: string;\n};\n\n// Each kind of error once per page load, and only so many: a page stuck in\n// a loop must not flood its authors (the server keeps its own budgets).\nconst REPORTS_PER_LOAD = 10;\nconst REPORTED_ACTION_CODES = new Set(['ACTION_TIMEOUT', 'ACTION_LIMIT_EXCEEDED']);\n\nfunction clip(s: string | undefined, max: number): string | undefined {\n return s && s.length > max ? s.slice(0, max) : s;\n}\n\n// A stack line that names a place in the code (file:line[:col]).\nconst FRAME = /:\\d+(?::\\d+)?\\)?$/;\n\n/** What makes two reports the same error \u2014 the way the server groups them:\n * an action failure by its action and code; anything else by its kind, its\n * name and the places its stack names, or by its message when the stack\n * names none. One throw site with a changing message is one error. */\nfunction reportKey(r: ErrorReport): string {\n if (r.kind === 'action') return `action\\u0000${r.action}\\u0000${r.code}`;\n const frames = (r.stack ?? '')\n .split('\\n')\n .map((line) => line.trim())\n .filter((line) => line !== '' && FRAME.test(line));\n return frames.length > 0\n ? `${r.kind}\\u0000${r.name}\\u0000${frames.join('\\n')}`\n : `${r.kind}\\u0000${r.name}\\u0000message\\u0000${r.message}`;\n}\n\nfunction describe(value: unknown): string {\n if (typeof value === 'string') return value;\n try {\n return JSON.stringify(value) ?? String(value);\n } catch {\n return String(value);\n }\n}\n\nclass MiniAppBridge {\n private nextId = 1;\n private pending = new Map<number, Pending>();\n private listeners = new Set<(e: HostEvent) => void>();\n private hostOrigin: string | null = null;\n private started = false;\n private reported = new Set<string>();\n\n constructor() {\n if (typeof window === 'undefined' || typeof window.addEventListener !== 'function') return;\n window.addEventListener('error', (event: ErrorEvent) => {\n const err: unknown = event.error;\n if (err instanceof Error) {\n this.report({ kind: 'exception', name: err.name, message: err.message, stack: err.stack });\n } else {\n const where = event.filename\n ? ` at ${event.filename}:${event.lineno}:${event.colno}`\n : '';\n this.report({\n kind: 'exception',\n name: 'Error',\n message: String(event.message || 'Script error.'),\n stack: where,\n });\n }\n });\n window.addEventListener('unhandledrejection', (event: PromiseRejectionEvent) => {\n const reason: unknown = event.reason;\n // The bridge's own rejections are the host's or the server's answers:\n // a failed action is reported where it failed, by its own rules.\n if (reason !== null && typeof reason === 'object' && FROM_BRIDGE in reason) return;\n if (reason instanceof Error) {\n this.report({\n kind: 'rejection',\n name: reason.name,\n message: reason.message,\n stack: reason.stack,\n });\n } else {\n this.report({ kind: 'rejection', name: '', message: describe(reason) });\n }\n });\n }\n\n /** Sends one error report to the host; drops repeats, anything past the\n * page's share, and every failure of the report itself (an older host\n * answers NOT_GRANTED). */\n private report(r: ErrorReport): void {\n // Cut to what the host may send: the server takes at most 16 KiB.\n const params: ErrorReport = {\n ...r,\n name: clip(r.name, 100),\n message: clip(r.message, 500),\n stack: clip(r.stack, 3000),\n };\n const key = reportKey(params);\n if (this.reported.has(key) || this.reported.size >= REPORTS_PER_LOAD) return;\n this.reported.add(key);\n void this.call('report', params).catch(() => {});\n }\n\n private start(): void {\n if (this.started) return;\n this.started = true;\n window.addEventListener('message', (event: MessageEvent) => {\n // Only our embedding host: same source as window.parent, and once\n // the handshake pinned an origin, exactly that origin.\n if (event.source !== window.parent) return;\n if (this.hostOrigin !== null && event.origin !== this.hostOrigin) return;\n const msg = event.data as Record<string, unknown> | null;\n if (!msg || msg.parall !== PROTOCOL) return;\n if (typeof msg.id === 'number') {\n const pending = this.pending.get(msg.id);\n if (!pending) return;\n this.pending.delete(msg.id);\n clearTimeout(pending.timer);\n if (this.hostOrigin === null) this.hostOrigin = event.origin;\n if (msg.error) {\n const err = msg.error as WireError;\n pending.reject(bridgeError(err.code, err.message, err.details));\n } else {\n pending.resolve(msg.result);\n }\n return;\n }\n if (typeof msg.event === 'string') {\n for (const fn of this.listeners) fn(msg as unknown as HostEvent);\n }\n });\n }\n\n private call<T>(method: string, params?: unknown, timeoutMs = HOST_TIMEOUT_MS): Promise<T> {\n this.start();\n const id = this.nextId++;\n return new Promise<T>((resolve, reject) => {\n const timer = setTimeout(() => {\n if (this.pending.delete(id)) {\n reject(bridgeError('HOST_TIMEOUT', `${method} timed out waiting for the host`));\n }\n }, timeoutMs);\n this.pending.set(id, { resolve: resolve as (v: unknown) => void, reject, timer });\n window.parent.postMessage({ parall: PROTOCOL, id, method, params }, '*');\n });\n }\n\n /** Handshake with the host; resolves with the viewer, app and initial route. */\n ready(): Promise<ReadyResult> {\n return this.call<ReadyResult>('ready');\n }\n\n /** Ask the host to grow/shrink the iframe (fire-and-forget semantics). */\n resize(height: number): void {\n void this.call('resize', { height }).catch(() => {});\n }\n\n /**\n * Call one of the app's actions with the viewer's identity and resolve\n * with what the action returned. A failure rejects with a BridgeError\n * whose code is the server's (ACTION_FAILED, ACTION_TIMEOUT,\n * INVALID_ACTION_PARAMS, APP_VERSION_CHANGED\u2026); its message is the\n * action's ActionError message when it threw one. HOST_TIMEOUT and\n * HOST_UNAVAILABLE mean no answer came back: whether the action ran is\n * not known, so read again before retrying a write.\n */\n async action<T = unknown>(name: string, params?: Record<string, unknown>): Promise<T> {\n let answer: { invocation_id: string; result: T };\n try {\n answer = await this.call<{ invocation_id: string; result: T }>(\n 'action',\n { name, params: params ?? {} },\n ACTION_TIMEOUT_MS,\n );\n } catch (err) {\n // The app's authors hear of an action that failed unexpectedly, timed\n // out or ran over its limits \u2014 caught by the page or not. An\n // ActionError (error_kind \"action\") is the author's own answer.\n const e = err as BridgeError;\n const unexpected = e.code === 'ACTION_FAILED' && e.details?.error_kind === 'unexpected';\n if (unexpected || REPORTED_ACTION_CODES.has(e.code)) {\n const invocation = e.details?.invocation_id;\n this.report({\n kind: 'action',\n action: name,\n code: e.code,\n invocation_id: typeof invocation === 'string' ? invocation : undefined,\n });\n }\n throw err;\n }\n return answer.result;\n }\n\n /** Subscribe to host events; returns the unsubscribe function. */\n onEvent(fn: (e: HostEvent) => void): () => void {\n this.start();\n this.listeners.add(fn);\n return () => this.listeners.delete(fn);\n }\n\n /**\n * Call fn when a Database the app reads has new writes: once per new\n * (database_id, data_seq) \u2014 repeats and older ones are dropped \u2014 and\n * always on a catch-up after the host reconnected. Read again in fn.\n */\n onDataChanged(fn: (change: DataChanged) => void): () => void {\n const seen = new Map<string, number>();\n return this.onEvent((e) => {\n if (e.event !== 'data.changed') return;\n const { database_id, data_seq, catch_up } = e.data;\n const last = seen.get(database_id);\n if (!catch_up && last !== undefined && data_seq <= last) return;\n if (last === undefined || data_seq > last) seen.set(database_id, data_seq);\n fn(e.data);\n });\n }\n}\n\nexport const parall = new MiniAppBridge();\n";
2
+ //# sourceMappingURL=apps-page-sdk.generated.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"apps-page-sdk.generated.d.ts","sourceRoot":"","sources":["../../src/commands/apps-page-sdk.generated.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,eAAe,4zYAAkuY,CAAC"}
@@ -0,0 +1,3 @@
1
+ // Generated from ts/miniapp-sdk/src/index.ts by scripts/generate-miniapp-sdk.mjs. Do not edit.
2
+ // biome-ignore format: generated copy
3
+ export const PAGE_SDK_SOURCE = "/**\n * @parall/miniapp-sdk — the page side of the Mini App bridge (design §7.1):\n * host handshake, host→page events, resize, and `action`, the page's only\n * data method: it calls one of the app's server-side actions through the\n * host, which adds the viewer's session and the version the page loaded\n * (Mini App Action design §3.1). No db, files, clip or chat methods exist\n * on this surface. The transport is postMessage to window.parent; the host\n * validates our origin, we validate that messages come from our parent\n * and, after the first answer, pin the parent's origin.\n *\n * Protocol (request/response + events):\n * page → host {parall: 'v1', id, method: 'ready' | 'resize' | 'action' | 'report', params}\n * host → page {parall: 'v1', id, result} | {parall: 'v1', id, error: {code, message, details?}}\n * host → page {parall: 'v1', event: 'route.changed' | 'viewer.changed' | 'data.changed', data}\n */\n\nexport interface ViewerSummary {\n id: string;\n display_name: string;\n is_agent: boolean;\n /** The viewer's organization role (owner / admin / member) — the same\n * value an action sees as ctx.viewer.role. */\n role?: string;\n}\n\nexport interface AppSummary {\n id: string;\n name: string;\n version_seq: number;\n}\n\nexport interface ReadyResult {\n viewer: ViewerSummary;\n app: AppSummary;\n route: string;\n}\n\n/** A Database the app reads was written. It carries no data: read again. */\nexport interface DataChanged {\n database_id: string;\n data_seq: number;\n /** Sent once after the host's connection came back: writes in between\n * may have been missed, so read again whatever data_seq says. */\n catch_up?: boolean;\n}\n\nexport type HostEvent =\n | { event: 'route.changed'; data: { route: string } }\n | { event: 'viewer.changed'; data: { viewer: ViewerSummary } }\n | { event: 'data.changed'; data: DataChanged };\n\n/** A refusal or failure from the host, in the error-contract envelope. An\n * action's failure keeps the server's code and details (invocation_id,\n * error_kind, field, current_version_seq…); APP_VERSION_CHANGED means the\n * app was updated and the host offers the viewer a reload. */\nexport interface BridgeError extends Error {\n code: string;\n details?: Record<string, unknown>;\n}\n\ninterface WireError {\n code: string;\n message: string;\n details?: Record<string, unknown>;\n}\n\ntype Pending = {\n resolve: (v: unknown) => void;\n reject: (e: Error) => void;\n timer: ReturnType<typeof setTimeout>;\n};\n\nconst PROTOCOL = 'v1';\n\n// How long the page waits for the host. An action waits longer than the\n// host's request timeout, which waits longer than the server takes to\n// answer at worst, so the page always gets the server's answer rather than\n// a timeout of its own (Mini App Action design §3.1, §15).\nconst HOST_TIMEOUT_MS = 10_000;\nconst ACTION_TIMEOUT_MS = 30_000;\n\n// Marks the errors the bridge itself rejects with: what the host or the\n// server answered, never the page's own bug.\nconst FROM_BRIDGE = Symbol.for('parall.bridge-error');\n\nfunction bridgeError(\n code: string,\n message: string,\n details?: Record<string, unknown>,\n): BridgeError {\n const err = Object.assign(new Error(message), { code, details }) as BridgeError;\n Object.defineProperty(err, FROM_BRIDGE, { value: true });\n return err;\n}\n\n/**\n * What a page reports when something goes wrong (Mini App design §9): an\n * error thrown on the page, a promise rejected without a handler, and an\n * action call that failed unexpectedly, timed out or ran over its limits.\n * Never console.error, and never an ActionError — that is the author's own\n * message to the caller. The host adds the version the page loaded and\n * reports it in the viewer's name; the app's authors are told.\n */\ntype ErrorReport = {\n kind: 'exception' | 'rejection' | 'action';\n name?: string;\n message?: string;\n stack?: string;\n action?: string;\n code?: string;\n invocation_id?: string;\n};\n\n// Each kind of error once per page load, and only so many: a page stuck in\n// a loop must not flood its authors (the server keeps its own budgets).\nconst REPORTS_PER_LOAD = 10;\nconst REPORTED_ACTION_CODES = new Set(['ACTION_TIMEOUT', 'ACTION_LIMIT_EXCEEDED']);\n\nfunction clip(s: string | undefined, max: number): string | undefined {\n return s && s.length > max ? s.slice(0, max) : s;\n}\n\n// A stack line that names a place in the code (file:line[:col]).\nconst FRAME = /:\\d+(?::\\d+)?\\)?$/;\n\n/** What makes two reports the same error — the way the server groups them:\n * an action failure by its action and code; anything else by its kind, its\n * name and the places its stack names, or by its message when the stack\n * names none. One throw site with a changing message is one error. */\nfunction reportKey(r: ErrorReport): string {\n if (r.kind === 'action') return `action\\u0000${r.action}\\u0000${r.code}`;\n const frames = (r.stack ?? '')\n .split('\\n')\n .map((line) => line.trim())\n .filter((line) => line !== '' && FRAME.test(line));\n return frames.length > 0\n ? `${r.kind}\\u0000${r.name}\\u0000${frames.join('\\n')}`\n : `${r.kind}\\u0000${r.name}\\u0000message\\u0000${r.message}`;\n}\n\nfunction describe(value: unknown): string {\n if (typeof value === 'string') return value;\n try {\n return JSON.stringify(value) ?? String(value);\n } catch {\n return String(value);\n }\n}\n\nclass MiniAppBridge {\n private nextId = 1;\n private pending = new Map<number, Pending>();\n private listeners = new Set<(e: HostEvent) => void>();\n private hostOrigin: string | null = null;\n private started = false;\n private reported = new Set<string>();\n\n constructor() {\n if (typeof window === 'undefined' || typeof window.addEventListener !== 'function') return;\n window.addEventListener('error', (event: ErrorEvent) => {\n const err: unknown = event.error;\n if (err instanceof Error) {\n this.report({ kind: 'exception', name: err.name, message: err.message, stack: err.stack });\n } else {\n const where = event.filename\n ? ` at ${event.filename}:${event.lineno}:${event.colno}`\n : '';\n this.report({\n kind: 'exception',\n name: 'Error',\n message: String(event.message || 'Script error.'),\n stack: where,\n });\n }\n });\n window.addEventListener('unhandledrejection', (event: PromiseRejectionEvent) => {\n const reason: unknown = event.reason;\n // The bridge's own rejections are the host's or the server's answers:\n // a failed action is reported where it failed, by its own rules.\n if (reason !== null && typeof reason === 'object' && FROM_BRIDGE in reason) return;\n if (reason instanceof Error) {\n this.report({\n kind: 'rejection',\n name: reason.name,\n message: reason.message,\n stack: reason.stack,\n });\n } else {\n this.report({ kind: 'rejection', name: '', message: describe(reason) });\n }\n });\n }\n\n /** Sends one error report to the host; drops repeats, anything past the\n * page's share, and every failure of the report itself (an older host\n * answers NOT_GRANTED). */\n private report(r: ErrorReport): void {\n // Cut to what the host may send: the server takes at most 16 KiB.\n const params: ErrorReport = {\n ...r,\n name: clip(r.name, 100),\n message: clip(r.message, 500),\n stack: clip(r.stack, 3000),\n };\n const key = reportKey(params);\n if (this.reported.has(key) || this.reported.size >= REPORTS_PER_LOAD) return;\n this.reported.add(key);\n void this.call('report', params).catch(() => {});\n }\n\n private start(): void {\n if (this.started) return;\n this.started = true;\n window.addEventListener('message', (event: MessageEvent) => {\n // Only our embedding host: same source as window.parent, and once\n // the handshake pinned an origin, exactly that origin.\n if (event.source !== window.parent) return;\n if (this.hostOrigin !== null && event.origin !== this.hostOrigin) return;\n const msg = event.data as Record<string, unknown> | null;\n if (!msg || msg.parall !== PROTOCOL) return;\n if (typeof msg.id === 'number') {\n const pending = this.pending.get(msg.id);\n if (!pending) return;\n this.pending.delete(msg.id);\n clearTimeout(pending.timer);\n if (this.hostOrigin === null) this.hostOrigin = event.origin;\n if (msg.error) {\n const err = msg.error as WireError;\n pending.reject(bridgeError(err.code, err.message, err.details));\n } else {\n pending.resolve(msg.result);\n }\n return;\n }\n if (typeof msg.event === 'string') {\n for (const fn of this.listeners) fn(msg as unknown as HostEvent);\n }\n });\n }\n\n private call<T>(method: string, params?: unknown, timeoutMs = HOST_TIMEOUT_MS): Promise<T> {\n this.start();\n const id = this.nextId++;\n return new Promise<T>((resolve, reject) => {\n const timer = setTimeout(() => {\n if (this.pending.delete(id)) {\n reject(bridgeError('HOST_TIMEOUT', `${method} timed out waiting for the host`));\n }\n }, timeoutMs);\n this.pending.set(id, { resolve: resolve as (v: unknown) => void, reject, timer });\n window.parent.postMessage({ parall: PROTOCOL, id, method, params }, '*');\n });\n }\n\n /** Handshake with the host; resolves with the viewer, app and initial route. */\n ready(): Promise<ReadyResult> {\n return this.call<ReadyResult>('ready');\n }\n\n /** Ask the host to grow/shrink the iframe (fire-and-forget semantics). */\n resize(height: number): void {\n void this.call('resize', { height }).catch(() => {});\n }\n\n /**\n * Call one of the app's actions with the viewer's identity and resolve\n * with what the action returned. A failure rejects with a BridgeError\n * whose code is the server's (ACTION_FAILED, ACTION_TIMEOUT,\n * INVALID_ACTION_PARAMS, APP_VERSION_CHANGED…); its message is the\n * action's ActionError message when it threw one. HOST_TIMEOUT and\n * HOST_UNAVAILABLE mean no answer came back: whether the action ran is\n * not known, so read again before retrying a write.\n */\n async action<T = unknown>(name: string, params?: Record<string, unknown>): Promise<T> {\n let answer: { invocation_id: string; result: T };\n try {\n answer = await this.call<{ invocation_id: string; result: T }>(\n 'action',\n { name, params: params ?? {} },\n ACTION_TIMEOUT_MS,\n );\n } catch (err) {\n // The app's authors hear of an action that failed unexpectedly, timed\n // out or ran over its limits — caught by the page or not. An\n // ActionError (error_kind \"action\") is the author's own answer.\n const e = err as BridgeError;\n const unexpected = e.code === 'ACTION_FAILED' && e.details?.error_kind === 'unexpected';\n if (unexpected || REPORTED_ACTION_CODES.has(e.code)) {\n const invocation = e.details?.invocation_id;\n this.report({\n kind: 'action',\n action: name,\n code: e.code,\n invocation_id: typeof invocation === 'string' ? invocation : undefined,\n });\n }\n throw err;\n }\n return answer.result;\n }\n\n /** Subscribe to host events; returns the unsubscribe function. */\n onEvent(fn: (e: HostEvent) => void): () => void {\n this.start();\n this.listeners.add(fn);\n return () => this.listeners.delete(fn);\n }\n\n /**\n * Call fn when a Database the app reads has new writes: once per new\n * (database_id, data_seq) — repeats and older ones are dropped — and\n * always on a catch-up after the host reconnected. Read again in fn.\n */\n onDataChanged(fn: (change: DataChanged) => void): () => void {\n const seen = new Map<string, number>();\n return this.onEvent((e) => {\n if (e.event !== 'data.changed') return;\n const { database_id, data_seq, catch_up } = e.data;\n const last = seen.get(database_id);\n if (!catch_up && last !== undefined && data_seq <= last) return;\n if (last === undefined || data_seq > last) seen.set(database_id, data_seq);\n fn(e.data);\n });\n }\n}\n\nexport const parall = new MiniAppBridge();\n";
@@ -1 +1 @@
1
- {"version":3,"file":"apps-publish.d.ts","sourceRoot":"","sources":["../../src/commands/apps-publish.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAKzC;;;;yBAIyB;AACzB,wBAAgB,0BAA0B,CAAC,GAAG,EAAE,OAAO,QA4ItD;AAgCD,UAAU,MAAM;IACd,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;IACf,yEAAyE;IACzE,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,MAAM,CAAC;CACnB;AAED;;yBAEyB;AACzB,iBAAe,aAAa,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE;IAAE,eAAe,EAAE,OAAO,CAAA;CAAE,GAAG,OAAO,CAAC,MAAM,CAAC,CA8D7F;AA4BD,iBAAe,YAAY,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAmCrE;AAGD,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,CAAC"}
1
+ {"version":3,"file":"apps-publish.d.ts","sourceRoot":"","sources":["../../src/commands/apps-publish.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAMzC;;;;yBAIyB;AACzB,wBAAgB,0BAA0B,CAAC,GAAG,EAAE,OAAO,QAiJtD;AAgCD,UAAU,MAAM;IACd,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;IACf,yEAAyE;IACzE,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,MAAM,CAAC;CACnB;AAED;;yBAEyB;AACzB,iBAAe,aAAa,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE;IAAE,eAAe,EAAE,OAAO,CAAA;CAAE,GAAG,OAAO,CAAC,MAAM,CAAC,CA8D7F;AA4BD,iBAAe,YAAY,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAmCrE;AAGD,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,CAAC"}