@parall/cli 1.70.0 → 1.71.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 (58) 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 +9 -2
  42. package/dist/commands/db-plane.d.ts.map +1 -1
  43. package/dist/commands/db-plane.js +2 -0
  44. package/dist/commands/messages.d.ts.map +1 -1
  45. package/dist/commands/messages.js +6 -11
  46. package/dist/commands/msteams.d.ts +10 -0
  47. package/dist/commands/msteams.d.ts.map +1 -0
  48. package/dist/commands/msteams.js +41 -0
  49. package/dist/index.js +7 -5
  50. package/dist/lib/client.d.ts +2 -1
  51. package/dist/lib/client.d.ts.map +1 -1
  52. package/dist/lib/mini-app-discovery.d.ts +6 -0
  53. package/dist/lib/mini-app-discovery.d.ts.map +1 -0
  54. package/dist/lib/mini-app-discovery.js +32 -0
  55. package/dist/lib/output.d.ts +3 -1
  56. package/dist/lib/output.d.ts.map +1 -1
  57. package/dist/lib/output.js +5 -1
  58. package/package.json +5 -5
@@ -0,0 +1,34 @@
1
+ import type { Command } from 'commander';
2
+ /** `parall app check [dir]` (docs/engineering-design/mini-app-action-design.md
3
+ * §10.1): before publishing, confirm the built action module can be what
4
+ * the loader runs — one file whose only import is cloudflare:workers,
5
+ * exporting ActionRunner — and that it implements exactly the actions
6
+ * manifest.json declares. Params schemas are left to the server's
7
+ * acceptance at publish. */
8
+ export declare function registerAppCheckCommand(app: Command): void;
9
+ export interface ActionCheck {
10
+ /** The module's path in the bundle; absent when no actions are declared. */
11
+ module?: string;
12
+ sha256?: string;
13
+ /** The implemented (and declared) actions, sorted. */
14
+ actions: string[];
15
+ }
16
+ /** A built action module as the manifest declares it, read and checked
17
+ * without running it: the static half of `checkActions`, which is all a
18
+ * local run takes (`apps-action-local.ts` runs the module only in workerd). */
19
+ export interface ActionModule {
20
+ entry: string;
21
+ source: string;
22
+ sha256: string;
23
+ /** actions.functions as declared, by name. */
24
+ functions: Record<string, unknown>;
25
+ }
26
+ export declare function checkActions(dist: string): Promise<ActionCheck>;
27
+ /** The declared action module, or null when the manifest declares no
28
+ * actions. */
29
+ export declare function readActionModule(dist: string): Promise<ActionModule | null>;
30
+ /** The specifiers a module imports, found by a scan of its text: static
31
+ * imports and re-exports at the start of a line (where a bundler puts them)
32
+ * and import() of a string literal anywhere. */
33
+ export declare function moduleImports(source: string): string[];
34
+ //# sourceMappingURL=apps-check.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"apps-check.d.ts","sourceRoot":"","sources":["../../src/commands/apps-check.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAGzC;;;;;4BAK4B;AAC5B,wBAAgB,uBAAuB,CAAC,GAAG,EAAE,OAAO,QAYnD;AAED,MAAM,WAAW,WAAW;IAC1B,4EAA4E;IAC5E,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,sDAAsD;IACtD,OAAO,EAAE,MAAM,EAAE,CAAC;CACnB;AAWD;;+EAE+E;AAC/E,MAAM,WAAW,YAAY;IAC3B,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,8CAA8C;IAC9C,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACpC;AAED,wBAAsB,YAAY,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,CAAC,CAiBrE;AAED;cACc;AACd,wBAAsB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,YAAY,GAAG,IAAI,CAAC,CAkDjF;AAED;;gDAEgD;AAChD,wBAAgB,aAAa,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,CAWtD"}
@@ -0,0 +1,155 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { promises as fs } from 'node:fs';
3
+ import { tmpdir } from 'node:os';
4
+ import { join, posix, resolve } from 'node:path';
5
+ import { pathToFileURL } from 'node:url';
6
+ import { printError, printJson } from '../lib/output.js';
7
+ /** `parall app check [dir]` (docs/engineering-design/mini-app-action-design.md
8
+ * §10.1): before publishing, confirm the built action module can be what
9
+ * the loader runs — one file whose only import is cloudflare:workers,
10
+ * exporting ActionRunner — and that it implements exactly the actions
11
+ * manifest.json declares. Params schemas are left to the server's
12
+ * acceptance at publish. */
13
+ export function registerAppCheckCommand(app) {
14
+ app
15
+ .command('check')
16
+ .description("Check a built bundle's action module against its manifest")
17
+ .argument('[dir]', 'The built bundle directory', 'dist')
18
+ .action(async (dir) => {
19
+ try {
20
+ printJson({ ok: true, ...(await checkActions(resolve(dir))) });
21
+ }
22
+ catch (err) {
23
+ printError(err);
24
+ }
25
+ });
26
+ }
27
+ const MODULE_DIR = '_actions/';
28
+ // Mirrors the server's cap (miniappaction.ModuleMaxBytes).
29
+ const MODULE_MAX_BYTES = 5 * 1024 * 1024;
30
+ const RUNTIME_MODULE = 'cloudflare:workers';
31
+ // Enough of cloudflare:workers for a module to load outside the runtime.
32
+ const RUNTIME_STAND_IN = 'export class WorkerEntrypoint { constructor(ctx, env) { this.ctx = ctx; this.env = env; } }\n' +
33
+ 'export class RpcTarget {}\nexport class DurableObject {}\nexport const env = {};\n';
34
+ export async function checkActions(dist) {
35
+ const module = await readActionModule(dist);
36
+ if (!module)
37
+ return { actions: [] };
38
+ const implemented = await implementedActions(module.entry, module.source);
39
+ const names = Object.keys(module.functions).sort();
40
+ const missing = names.filter((n) => !implemented.includes(n));
41
+ const undeclared = implemented.filter((n) => !names.includes(n));
42
+ if (missing.length > 0 || undeclared.length > 0) {
43
+ const parts = [];
44
+ if (missing.length > 0)
45
+ parts.push(`declared but not implemented: ${missing.join(', ')}`);
46
+ if (undeclared.length > 0)
47
+ parts.push(`implemented but not declared in manifest.json: ${undeclared.join(', ')}`);
48
+ throw new Error(`action module ${module.entry} does not match the manifest — ${parts.join('; ')}`);
49
+ }
50
+ return { module: module.entry, sha256: module.sha256, actions: implemented };
51
+ }
52
+ /** The declared action module, or null when the manifest declares no
53
+ * actions. */
54
+ export async function readActionModule(dist) {
55
+ let manifest;
56
+ try {
57
+ manifest = JSON.parse(await fs.readFile(join(dist, 'manifest.json'), 'utf8'));
58
+ }
59
+ catch (err) {
60
+ throw new Error(`${dist}/manifest.json: ${err.message}`);
61
+ }
62
+ const declared = manifest.actions;
63
+ if (declared === undefined || declared === null) {
64
+ if (await hasFiles(join(dist, MODULE_DIR))) {
65
+ throw new Error(`${dist}/${MODULE_DIR} has files but manifest.json declares no actions; declare them under "actions" or remove the directory`);
66
+ }
67
+ return null;
68
+ }
69
+ const { entry, functions } = declared;
70
+ if (typeof entry !== 'string' || !entry.startsWith(MODULE_DIR) || !/\.m?js$/.test(entry)) {
71
+ throw new Error(`manifest actions.entry must be a .js / .mjs file under ${MODULE_DIR}`);
72
+ }
73
+ // As the server's acceptance (miniappaction checkEntry): a path that is
74
+ // not already clean could name a file outside the bundle.
75
+ if (posix.normalize(entry) !== entry || entry.includes('\\')) {
76
+ throw new Error(`manifest actions.entry ${JSON.stringify(entry)} is not a clean relative path`);
77
+ }
78
+ if (typeof functions !== 'object' || functions === null || Array.isArray(functions)) {
79
+ throw new Error('manifest actions.functions must be an object of action declarations');
80
+ }
81
+ let bytes;
82
+ try {
83
+ bytes = await fs.readFile(join(dist, entry));
84
+ }
85
+ catch {
86
+ throw new Error(`manifest actions.entry ${entry} is not in ${dist} — build the actions first`);
87
+ }
88
+ if (bytes.length > MODULE_MAX_BYTES) {
89
+ throw new Error(`action module ${entry} is ${bytes.length} bytes, over the 5 MiB cap`);
90
+ }
91
+ const source = bytes.toString('utf8');
92
+ const foreign = moduleImports(source).filter((s) => s !== RUNTIME_MODULE);
93
+ if (foreign.length > 0) {
94
+ throw new Error(`action module ${entry} imports ${[...new Set(foreign)].join(', ')}; it must be one bundled file whose only import is ${RUNTIME_MODULE}`);
95
+ }
96
+ return {
97
+ entry,
98
+ source,
99
+ sha256: createHash('sha256').update(bytes).digest('hex'),
100
+ functions: functions,
101
+ };
102
+ }
103
+ /** The specifiers a module imports, found by a scan of its text: static
104
+ * imports and re-exports at the start of a line (where a bundler puts them)
105
+ * and import() of a string literal anywhere. */
106
+ export function moduleImports(source) {
107
+ const found = [];
108
+ const patterns = [
109
+ /^[ \t]*import\s*(?:[\w$\s{},*]+?\s*from\s*)?(['"])([^'"\n]+)\1/gm,
110
+ /^[ \t]*export\s*(?:\*(?:\s*as\s+[\w$]+)?|\{[\w$\s,]*\})\s*from\s*(['"])([^'"\n]+)\1/gm,
111
+ /\bimport\s*\(\s*(['"])([^'"\n]+)\1\s*\)/g,
112
+ ];
113
+ for (const pattern of patterns) {
114
+ for (const m of source.matchAll(pattern))
115
+ found.push(m[2]);
116
+ }
117
+ return found;
118
+ }
119
+ /** Loads the module in Node with a stand-in for cloudflare:workers and reads
120
+ * the action list defineActions puts on ActionRunner. Loading runs the
121
+ * module's top-level code, as building it on this machine already did. */
122
+ async function implementedActions(entry, source) {
123
+ const standIn = `data:text/javascript,${encodeURIComponent(RUNTIME_STAND_IN)}`;
124
+ const rewritten = source.replace(/(['"])cloudflare:workers\1/g, JSON.stringify(standIn));
125
+ const dir = await fs.mkdtemp(join(tmpdir(), 'parall-app-check-'));
126
+ let mod;
127
+ try {
128
+ const file = join(dir, 'actions.mjs');
129
+ await fs.writeFile(file, rewritten);
130
+ mod = await import(pathToFileURL(file).href);
131
+ }
132
+ catch (err) {
133
+ throw new Error(`action module ${entry} failed to load: ${err?.message ?? err}`);
134
+ }
135
+ finally {
136
+ await fs.rm(dir, { recursive: true, force: true });
137
+ }
138
+ const runner = mod.ActionRunner;
139
+ if (typeof runner !== 'function') {
140
+ throw new Error(`action module ${entry} does not export ActionRunner — export the result of defineActions under that name`);
141
+ }
142
+ const list = runner.actions;
143
+ if (!Array.isArray(list) || !list.every((n) => typeof n === 'string')) {
144
+ throw new Error(`ActionRunner in ${entry} does not list its actions — build it with defineActions`);
145
+ }
146
+ return [...list].sort();
147
+ }
148
+ async function hasFiles(dir) {
149
+ try {
150
+ return (await fs.readdir(dir)).length > 0;
151
+ }
152
+ catch {
153
+ return false;
154
+ }
155
+ }
@@ -0,0 +1,26 @@
1
+ /** What the `app dev --app` host page needs to answer the page. */
2
+ export interface DevPageContext {
3
+ /** The page's own origin (the second loopback port). */
4
+ appOrigin: string;
5
+ app: {
6
+ id: string;
7
+ name: string;
8
+ database_id: string;
9
+ };
10
+ viewer: {
11
+ id: string;
12
+ display_name: string;
13
+ is_agent: boolean;
14
+ role: string;
15
+ };
16
+ }
17
+ /**
18
+ * The host page of `parall app dev --app` (design mockup D): the local build
19
+ * on the left, answered over the same bridge as in Parall — `ready` with the
20
+ * author's real identity and role, `action` run on this machine (its writes
21
+ * are real), `data.changed` after a write commits, `route.changed` from this
22
+ * page's #route — and every call on the right, with what the action printed.
23
+ * Light or dark with the system; Chinese or English with the browser.
24
+ */
25
+ export declare function devAppHostPage(ctx: DevPageContext, nonce: string): string;
26
+ //# sourceMappingURL=apps-dev-page.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"apps-dev-page.d.ts","sourceRoot":"","sources":["../../src/commands/apps-dev-page.ts"],"names":[],"mappings":"AAAA,mEAAmE;AACnE,MAAM,WAAW,cAAc;IAC7B,wDAAwD;IACxD,SAAS,EAAE,MAAM,CAAC;IAClB,GAAG,EAAE;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAC;QAAC,WAAW,EAAE,MAAM,CAAA;KAAE,CAAC;IACvD,MAAM,EAAE;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,YAAY,EAAE,MAAM,CAAC;QAAC,QAAQ,EAAE,OAAO,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC;CAC/E;AAYD;;;;;;;GAOG;AACH,wBAAgB,cAAc,CAAC,GAAG,EAAE,cAAc,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,CAiPzE"}
@@ -0,0 +1,259 @@
1
+ /** JSON inside a <script> element: nothing in it may close the element. */
2
+ function scriptJson(value) {
3
+ return JSON.stringify(value)
4
+ .replace(/</g, '\\u003c')
5
+ .replace(/>/g, '\\u003e')
6
+ .replace(/&/g, '\\u0026')
7
+ .replace(/\u2028/g, '\\u2028')
8
+ .replace(/\u2029/g, '\\u2029');
9
+ }
10
+ /**
11
+ * The host page of `parall app dev --app` (design mockup D): the local build
12
+ * on the left, answered over the same bridge as in Parall — `ready` with the
13
+ * author's real identity and role, `action` run on this machine (its writes
14
+ * are real), `data.changed` after a write commits, `route.changed` from this
15
+ * page's #route — and every call on the right, with what the action printed.
16
+ * Light or dark with the system; Chinese or English with the browser.
17
+ */
18
+ export function devAppHostPage(ctx, nonce) {
19
+ return `<!doctype html>
20
+ <html>
21
+ <head>
22
+ <meta charset="utf-8">
23
+ <meta name="color-scheme" content="light dark">
24
+ <title>parall app dev</title>
25
+ <style nonce="${nonce}">
26
+ :root{--bg:#fff;--fg:#111827;--muted:#6b7280;--line:#e5e7eb;--chip:#f3f4f6;--warn-bg:#fef3c7;--warn-fg:#92400e;--ok-bg:#ecfdf5;--ok-fg:#047857;--ok-line:#a7f3d0;--bad-bg:#fef2f2;--bad-fg:#b91c1c;--bad-line:#fecaca;--slow-bg:#fffbeb;--slow-fg:#b45309;--slow-line:#fde68a;--code:#f5f5f4}
27
+ @media (prefers-color-scheme:dark){:root{--bg:#141414;--fg:#f3f4f6;--muted:#9ca3af;--line:#2a2a2a;--chip:#232323;--warn-bg:#3a2a0a;--warn-fg:#fbbf24;--ok-bg:#0c2a20;--ok-fg:#34d399;--ok-line:#14532d;--bad-bg:#2a1010;--bad-fg:#f87171;--bad-line:#7f1d1d;--slow-bg:#2a2108;--slow-fg:#fbbf24;--slow-line:#713f12;--code:#1f1f1f}}
28
+ *{box-sizing:border-box}
29
+ html,body{height:100%;margin:0}
30
+ body{display:flex;flex-direction:column;background:var(--bg);color:var(--fg);font:14px/1.4 system-ui,-apple-system,"PingFang SC",sans-serif}
31
+ header{display:flex;align-items:center;gap:8px;padding:8px 12px;border-bottom:1px solid var(--line);flex-wrap:wrap}
32
+ .addr{font:12px ui-monospace,Menlo,monospace;color:var(--muted);background:var(--chip);border-radius:6px;padding:4px 8px}
33
+ .name{font-weight:600}
34
+ .chip{font-size:12px;border-radius:999px;padding:3px 10px;background:var(--chip);color:var(--muted)}
35
+ .warn{background:var(--warn-bg);color:var(--warn-fg)}
36
+ .spacer{flex:1}
37
+ button{font:inherit;font-size:13px;border:1px solid var(--line);background:var(--chip);color:var(--fg);border-radius:999px;padding:5px 12px;cursor:pointer}
38
+ .alert{padding:8px 12px;background:var(--bad-bg);color:var(--bad-fg);border-bottom:1px solid var(--bad-line);font-size:13px}
39
+ .hidden{display:none}
40
+ main{flex:1;display:flex;min-height:0}
41
+ iframe{flex:1;border:0;min-width:0;background:#fff}
42
+ aside{width:360px;border-left:1px solid var(--line);display:flex;flex-direction:column;min-height:0}
43
+ .head{display:flex;align-items:center;justify-content:space-between;padding:12px;border-bottom:1px solid var(--line);font-weight:600}
44
+ .count{font-size:12px;font-weight:500;background:var(--chip);color:var(--muted);border-radius:999px;padding:1px 8px}
45
+ ol{list-style:none;margin:0;padding:0;overflow-y:auto}
46
+ li{padding:10px 12px;border-bottom:1px solid var(--line)}
47
+ .row{display:flex;align-items:center;gap:6px}
48
+ .action{font:600 13px ui-monospace,Menlo,monospace}
49
+ .kind,.ms{font-size:12px;color:var(--muted)}
50
+ .pill{font-size:11px;border-radius:6px;padding:1px 6px;border:1px solid}
51
+ .pill.ok{background:var(--ok-bg);color:var(--ok-fg);border-color:var(--ok-line)}
52
+ .pill.failed{background:var(--bad-bg);color:var(--bad-fg);border-color:var(--bad-line)}
53
+ .pill.slow{background:var(--slow-bg);color:var(--slow-fg);border-color:var(--slow-line)}
54
+ .id{font:11px ui-monospace,Menlo,monospace;color:var(--muted);margin-top:2px;word-break:break-all}
55
+ .box{margin-top:6px;border-radius:6px;padding:6px 8px;font:12px/1.45 ui-monospace,Menlo,monospace;white-space:pre-wrap;word-break:break-word;max-height:9em;overflow:auto}
56
+ .box.error{background:var(--bad-bg);color:var(--bad-fg)}
57
+ .box.console{background:var(--code);color:var(--fg)}
58
+ .empty{padding:16px 12px;color:var(--muted);font-size:13px}
59
+ </style>
60
+ </head>
61
+ <body>
62
+ <header>
63
+ <span class="addr" id="addr"></span>
64
+ <span class="name" id="name"></span>
65
+ <span class="chip" id="local"></span>
66
+ <span class="chip warn" id="real"></span>
67
+ <span class="spacer"></span>
68
+ <span class="chip" id="viewer"></span>
69
+ <button type="button" id="reload"></button>
70
+ </header>
71
+ <div class="alert hidden" id="no-token"></div>
72
+ <main>
73
+ <iframe id="app" title="app" sandbox="allow-scripts allow-same-origin allow-downloads"></iframe>
74
+ <aside>
75
+ <div class="head"><span id="calls"></span><span class="count" id="count">0</span></div>
76
+ <ol id="log"></ol>
77
+ <p class="empty" id="empty"></p>
78
+ </aside>
79
+ </main>
80
+ <script type="application/json" id="ctx">${scriptJson(ctx)}</script>
81
+ <script nonce="${nonce}">
82
+ (() => {
83
+ const ctx = JSON.parse(document.getElementById('ctx').textContent);
84
+ const zh = (navigator.language || '').toLowerCase().startsWith('zh');
85
+ const T = zh
86
+ ? { local: '本地构建 · 未发布', real: '连的是真实 Database,写会生效', as: (n, r) => '以 ' + n + '(' + r + ')的身份', reload: '重新加载', calls: '调用记录', empty: '页面调用 action 后会显示在这里。', noToken: '地址里缺少令牌:请用终端里打印的完整地址打开,否则 action 调不通。', write: '写', read: '读', ok: '成功', failed: '失败', timeout: '超时', limit: '超限', gone: '本地联调服务没有回应', pageError: '页面报错', kinds: { exception: '页面异常', rejection: '未处理的 Promise', action: 'action 失败' } }
87
+ : { local: 'Local build · not published', real: 'Real Database: writes take effect', as: (n, r) => 'As ' + n + ' (' + r + ')', reload: 'Reload', calls: 'Calls', empty: 'Actions the page calls show up here.', noToken: 'The address has no token: open the full address the terminal printed, or actions cannot be called.', write: 'write', read: 'read', ok: 'ok', failed: 'failed', timeout: 'timed out', limit: 'over limit', gone: 'The local dev server did not answer', pageError: 'Page error', kinds: { exception: 'thrown', rejection: 'unhandled promise', action: 'action failed' } };
88
+ const $ = (id) => document.getElementById(id);
89
+ const token = new URLSearchParams(location.search).get('t') || '';
90
+ $('addr').textContent = location.host + '/?t=' + (token ? '••••••' : '');
91
+ $('name').textContent = ctx.app.name;
92
+ $('local').textContent = T.local;
93
+ $('real').textContent = T.real;
94
+ $('viewer').textContent = T.as(ctx.viewer.display_name, ctx.viewer.role);
95
+ $('reload').textContent = T.reload;
96
+ $('calls').textContent = T.calls;
97
+ $('empty').textContent = T.empty;
98
+ if (!token) {
99
+ $('no-token').textContent = T.noToken;
100
+ $('no-token').classList.remove('hidden');
101
+ }
102
+ const frame = $('app');
103
+ const pageUrl = () => ctx.appOrigin + '/index.html';
104
+ frame.src = pageUrl();
105
+ // Each load of the page is a generation, as in Parall's host: the answer to
106
+ // a request an earlier load made (one still running when Reload was
107
+ // clicked) is dropped, or it would land on the new page's request with the
108
+ // same id. data.changed still goes out: it is news about the Database.
109
+ let generation = 0;
110
+ $('reload').addEventListener('click', () => {
111
+ generation += 1;
112
+ frame.src = pageUrl() + '?reload=' + Date.now();
113
+ });
114
+ const send = (message) => frame.contentWindow && frame.contentWindow.postMessage(message, ctx.appOrigin);
115
+ window.addEventListener('hashchange', () => {
116
+ send({ parall: 'v1', event: 'route.changed', data: { route: location.hash.slice(1) } });
117
+ });
118
+
119
+ let count = 0;
120
+ function record(name, answer) {
121
+ count += 1;
122
+ $('count').textContent = String(count);
123
+ $('empty').classList.add('hidden');
124
+ const li = document.createElement('li');
125
+ li.dataset.testid = 'dev-call';
126
+ const row = document.createElement('div');
127
+ row.className = 'row';
128
+ const action = document.createElement('span');
129
+ action.className = 'action';
130
+ action.textContent = name;
131
+ const kind = document.createElement('span');
132
+ kind.className = 'kind';
133
+ kind.textContent = answer.kind === 'write' ? T.write : answer.kind === 'read' ? T.read : '';
134
+ const spacer = document.createElement('span');
135
+ spacer.className = 'spacer';
136
+ const code = answer.ok ? 'ok' : (answer.error && answer.error.code) || '';
137
+ const pill = document.createElement('span');
138
+ pill.className = 'pill ' + (answer.ok ? 'ok' : code === 'ACTION_TIMEOUT' || code === 'ACTION_LIMIT_EXCEEDED' ? 'slow' : 'failed');
139
+ pill.textContent = answer.ok ? T.ok : code === 'ACTION_TIMEOUT' ? T.timeout : code === 'ACTION_LIMIT_EXCEEDED' ? T.limit : T.failed;
140
+ const ms = document.createElement('span');
141
+ ms.className = 'ms';
142
+ ms.textContent = typeof answer.duration_ms === 'number' ? answer.duration_ms + ' ms' : '';
143
+ row.append(action, kind, spacer, pill, ms);
144
+ li.append(row);
145
+ if (answer.invocation_id) {
146
+ const id = document.createElement('div');
147
+ id.className = 'id';
148
+ id.textContent = answer.invocation_id;
149
+ li.append(id);
150
+ }
151
+ if (!answer.ok && answer.error) {
152
+ const box = document.createElement('div');
153
+ box.className = 'box error';
154
+ box.textContent = answer.error.code + ': ' + answer.error.message;
155
+ li.append(box);
156
+ }
157
+ if (answer.console) {
158
+ const box = document.createElement('div');
159
+ box.className = 'box console';
160
+ box.textContent = answer.console.trimEnd();
161
+ li.append(box);
162
+ }
163
+ $('log').prepend(li);
164
+ }
165
+
166
+ // A page error the page reported (Mini App design §9): listed here and in
167
+ // the terminal, never sent to Parall — this build is not published.
168
+ function recordReport(r) {
169
+ count += 1;
170
+ $('count').textContent = String(count);
171
+ $('empty').classList.add('hidden');
172
+ const li = document.createElement('li');
173
+ li.dataset.testid = 'dev-report';
174
+ const row = document.createElement('div');
175
+ row.className = 'row';
176
+ const label = document.createElement('span');
177
+ label.className = 'action';
178
+ label.textContent = r.kind === 'action' && r.action ? r.action : T.pageError;
179
+ const kind = document.createElement('span');
180
+ kind.className = 'kind';
181
+ kind.textContent = T.kinds[r.kind] || '';
182
+ const spacer = document.createElement('span');
183
+ spacer.className = 'spacer';
184
+ const pill = document.createElement('span');
185
+ pill.className = 'pill failed';
186
+ pill.textContent = T.pageError;
187
+ row.append(label, kind, spacer, pill);
188
+ li.append(row);
189
+ const box = document.createElement('div');
190
+ box.className = 'box error';
191
+ // The name and message, then the stack — unless the stack starts with
192
+ // them as whole lines (V8 does; Firefox and Safari do not).
193
+ const header = r.name && r.message ? r.name + ': ' + r.message : String(r.name || r.message || '');
194
+ const stack = r.stack ? String(r.stack).trim() : '';
195
+ box.textContent = r.kind === 'action'
196
+ ? (r.code || '') + (r.invocation_id ? ' ' + r.invocation_id : '')
197
+ : !stack ? header
198
+ : !header || stack === header || stack.startsWith(header + '\\n') ? stack
199
+ : header + '\\n' + stack;
200
+ li.append(box);
201
+ $('log').prepend(li);
202
+ }
203
+
204
+ window.addEventListener('message', async (event) => {
205
+ if (event.source !== frame.contentWindow || event.origin !== ctx.appOrigin) return;
206
+ const msg = event.data;
207
+ if (!msg || msg.parall !== 'v1' || typeof msg.id !== 'number') return;
208
+ const gen = generation;
209
+ const reply = (body) => {
210
+ if (gen === generation) send(Object.assign({ parall: 'v1', id: msg.id }, body));
211
+ };
212
+ if (msg.method === 'ready') {
213
+ reply({ result: { viewer: ctx.viewer, app: { id: ctx.app.id, name: ctx.app.name, version_seq: 0 }, route: location.hash.slice(1) } });
214
+ return;
215
+ }
216
+ if (msg.method === 'resize') {
217
+ reply({ result: {} });
218
+ return;
219
+ }
220
+ if (msg.method === 'report') {
221
+ reply({ result: {} });
222
+ const r = msg.params && typeof msg.params === 'object' ? msg.params : {};
223
+ recordReport(r);
224
+ fetch('/api/report', {
225
+ method: 'POST',
226
+ headers: { 'Content-Type': 'application/json', 'X-Parall-Dev-Token': token },
227
+ body: JSON.stringify(r),
228
+ }).catch(() => {});
229
+ return;
230
+ }
231
+ if (msg.method === 'action') {
232
+ const name = msg.params && typeof msg.params.name === 'string' ? msg.params.name : '';
233
+ const params = (msg.params && msg.params.params) || {};
234
+ let answer;
235
+ try {
236
+ const res = await fetch('/api/action', {
237
+ method: 'POST',
238
+ headers: { 'Content-Type': 'application/json', 'X-Parall-Dev-Token': token },
239
+ body: JSON.stringify({ name, params }),
240
+ });
241
+ answer = res.ok ? await res.json() : { ok: false, console: '', error: { code: 'HOST_UNAVAILABLE', message: res.status + ' ' + (await res.text()) } };
242
+ } catch (err) {
243
+ answer = { ok: false, console: '', error: { code: 'HOST_UNAVAILABLE', message: T.gone } };
244
+ }
245
+ record(name, answer);
246
+ if (answer.ok) reply({ result: { invocation_id: answer.invocation_id, result: answer.result } });
247
+ else reply({ error: answer.error });
248
+ if (answer.data_seq) {
249
+ send({ parall: 'v1', event: 'data.changed', data: { database_id: ctx.app.database_id, data_seq: answer.data_seq.to } });
250
+ }
251
+ return;
252
+ }
253
+ reply({ error: { code: 'NOT_GRANTED', message: msg.method + ' is not part of the bridge' } });
254
+ });
255
+ })();
256
+ </script>
257
+ </body>
258
+ </html>`;
259
+ }
@@ -0,0 +1,42 @@
1
+ import { type MiniAppActionKind } from '@parall/sdk';
2
+ /** `parall app dev --app <app>` (mini-app-action-design.md §10.2): the page
3
+ * of the local build, on its own origin, under a host page that answers the
4
+ * bridge as Parall's hosts do — and runs the actions it calls on this
5
+ * machine against the app's real Database, as `action run --local` does.
6
+ *
7
+ * Writes are real, so the local server answers its own page only: a random
8
+ * token per start, in the host page's address and on every API call; a
9
+ * loopback Host (so DNS rebinding cannot reach it); JSON bodies only. The
10
+ * page and the host page are on two ports — two origins — like the app
11
+ * origin and the Parall origin. */
12
+ /** One call as the host page shows it and answers the page. */
13
+ export interface DevCallAnswer {
14
+ ok: boolean;
15
+ kind?: MiniAppActionKind;
16
+ invocation_id?: string;
17
+ result?: unknown;
18
+ error?: {
19
+ code: string;
20
+ message: string;
21
+ details?: Record<string, unknown>;
22
+ };
23
+ /** What the action printed. */
24
+ console: string;
25
+ /** The data_seq range its writes committed under. */
26
+ data_seq?: {
27
+ from: number;
28
+ to: number;
29
+ };
30
+ duration_ms: number;
31
+ }
32
+ export declare function serveAppDev(dist: string, port: number, appId: string): Promise<void>;
33
+ /** The deployment's files-worker origin, the one outside source the
34
+ * apps-worker lets a page load images from (attachment images the platform
35
+ * serves). Deployments name it after the API host — `api.X` serves files from
36
+ * `files.X` — and nothing else is guessed: without it, those images are
37
+ * blocked locally, never allowed where Parall would block them. */
38
+ export declare function filesOriginFor(apiUrl: string): string;
39
+ /** The Host a loopback server answers: anything else (a DNS-rebound name)
40
+ * is refused before the request is looked at. */
41
+ export declare function isLoopbackHost(host: string | undefined, port: number): boolean;
42
+ //# sourceMappingURL=apps-dev-server.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"apps-dev-server.d.ts","sourceRoot":"","sources":["../../src/commands/apps-dev-server.ts"],"names":[],"mappings":"AAIA,OAAO,EAAY,KAAK,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAK/D;;;;;;;;;mCASmC;AAEnC,+DAA+D;AAC/D,MAAM,WAAW,aAAa;IAC5B,EAAE,EAAE,OAAO,CAAC;IACZ,IAAI,CAAC,EAAE,iBAAiB,CAAC;IACzB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB,KAAK,CAAC,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAC;QAAC,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;KAAE,CAAC;IAC7E,+BAA+B;IAC/B,OAAO,EAAE,MAAM,CAAC;IAChB,qDAAqD;IACrD,QAAQ,CAAC,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,EAAE,EAAE,MAAM,CAAA;KAAE,CAAC;IACxC,WAAW,EAAE,MAAM,CAAC;CACrB;AAKD,wBAAsB,WAAW,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAoF1F;AAED;;;;mEAImE;AACnE,wBAAgB,cAAc,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAQrD;AAcD;iDACiD;AACjD,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAE9E"}