@parall/cli 1.78.0 → 1.80.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/commands/apps-access.d.ts +8 -0
- package/dist/commands/apps-access.d.ts.map +1 -0
- package/dist/commands/apps-access.js +151 -0
- package/dist/commands/apps-actions-sdk.generated.d.ts +1 -1
- package/dist/commands/apps-actions-sdk.generated.d.ts.map +1 -1
- package/dist/commands/apps-actions-sdk.generated.js +1 -1
- package/dist/commands/apps-actions.d.ts +5 -3
- package/dist/commands/apps-actions.d.ts.map +1 -1
- package/dist/commands/apps-actions.js +11 -4
- package/dist/commands/apps-add.js +1 -1
- package/dist/commands/apps-blocks.d.ts.map +1 -1
- package/dist/commands/apps-blocks.js +8 -0
- package/dist/commands/apps-dev-page.d.ts +2 -0
- package/dist/commands/apps-dev-page.d.ts.map +1 -1
- package/dist/commands/apps-dev-page.js +3 -3
- package/dist/commands/apps-dev-server.d.ts +10 -1
- package/dist/commands/apps-dev-server.d.ts.map +1 -1
- package/dist/commands/apps-dev-server.js +26 -3
- package/dist/commands/apps-dev.d.ts +12 -1
- package/dist/commands/apps-dev.d.ts.map +1 -1
- package/dist/commands/apps-dev.js +25 -10
- package/dist/commands/apps-page-sdk.generated.d.ts +1 -1
- package/dist/commands/apps-page-sdk.generated.d.ts.map +1 -1
- package/dist/commands/apps-page-sdk.generated.js +1 -1
- package/dist/commands/apps-placement.d.ts +13 -0
- package/dist/commands/apps-placement.d.ts.map +1 -0
- package/dist/commands/apps-placement.js +20 -0
- package/dist/commands/apps-scaffold.d.ts +7 -1
- package/dist/commands/apps-scaffold.d.ts.map +1 -1
- package/dist/commands/apps-scaffold.js +88 -30
- package/dist/commands/apps-template-catalog.d.ts +85 -0
- package/dist/commands/apps-template-catalog.d.ts.map +1 -0
- package/dist/commands/apps-template-catalog.gen.d.ts +3 -0
- package/dist/commands/apps-template-catalog.gen.d.ts.map +1 -0
- package/dist/commands/apps-template-catalog.gen.js +228 -0
- package/dist/commands/apps-template-catalog.js +49 -0
- package/dist/commands/apps-template-init.d.ts +39 -0
- package/dist/commands/apps-template-init.d.ts.map +1 -0
- package/dist/commands/apps-template-init.js +118 -0
- package/dist/commands/apps-template.d.ts +11 -0
- package/dist/commands/apps-template.d.ts.map +1 -1
- package/dist/commands/apps-template.js +18 -7
- package/dist/commands/apps-templates.gen.d.ts +1 -0
- package/dist/commands/apps-templates.gen.d.ts.map +1 -1
- package/dist/commands/apps-templates.gen.js +27 -18
- package/dist/commands/apps.d.ts +3 -2
- package/dist/commands/apps.d.ts.map +1 -1
- package/dist/commands/apps.js +15 -4
- package/dist/commands/chat-connections.d.ts +11 -0
- package/dist/commands/chat-connections.d.ts.map +1 -0
- package/dist/commands/chat-connections.js +162 -0
- package/dist/commands/chats.d.ts.map +1 -1
- package/dist/commands/chats.js +6 -1
- package/dist/commands/db-plane.d.ts.map +1 -1
- package/dist/commands/db-plane.js +10 -6
- package/dist/commands/dbs.d.ts +3 -2
- package/dist/commands/dbs.d.ts.map +1 -1
- package/dist/commands/dbs.js +10 -5
- package/dist/commands/search.d.ts.map +1 -1
- package/dist/commands/search.js +1 -1
- package/dist/lib/output.d.ts +11 -0
- package/dist/lib/output.d.ts.map +1 -1
- package/dist/lib/output.js +32 -5
- package/package.json +5 -5
|
@@ -9,6 +9,15 @@ import { type MiniAppActionKind } from '@parall/sdk';
|
|
|
9
9
|
* loopback Host (so DNS rebinding cannot reach it); JSON bodies only. The
|
|
10
10
|
* page and the host page are on two ports — two origins — like the app
|
|
11
11
|
* origin and the Parall origin. */
|
|
12
|
+
/** The viewer's level on the app the dev host reports (viewer.access). */
|
|
13
|
+
export type DevAccess = 'read' | 'write';
|
|
14
|
+
/** What the page gets for a write action when the dev host shows it to
|
|
15
|
+
* someone who can only view the app: the code Parall answers with, and a
|
|
16
|
+
* message that says the refusal is the dev host's. */
|
|
17
|
+
export declare const DEV_VIEW_ONLY_REFUSAL: {
|
|
18
|
+
readonly code: "PERMISSION_DENIED";
|
|
19
|
+
readonly message: "You can only view this app, so its write actions are refused (parall app dev --access read: nothing ran)";
|
|
20
|
+
};
|
|
12
21
|
/** One call as the host page shows it and answers the page. */
|
|
13
22
|
export interface DevCallAnswer {
|
|
14
23
|
ok: boolean;
|
|
@@ -32,7 +41,7 @@ export interface DevCallAnswer {
|
|
|
32
41
|
/** Printed when `parall app dev` starts: it is a server, and an agent that
|
|
33
42
|
* waits for it to return waits until its tool gives up. */
|
|
34
43
|
export declare const DEV_LONG_RUNNING_HINT = " This keeps running until stopped: from a script or an agent, start it in the background (parall app dev \u2026 > dev.log 2>&1 &). To check one action, parall app action run <app> <name> --local runs it and returns.";
|
|
35
|
-
export declare function serveAppDev(dist: string, port: number, appId: string): Promise<void>;
|
|
44
|
+
export declare function serveAppDev(dist: string, port: number, appId: string, accessOverride?: DevAccess): Promise<void>;
|
|
36
45
|
/** The deployment's files-worker origin, the one outside source the
|
|
37
46
|
* apps-worker lets a page load images from (attachment images the platform
|
|
38
47
|
* serves). Deployments name it after the API host — `api.X` serves files from
|
|
@@ -1 +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;2DAC2D;AAC3D,eAAO,MAAM,qBAAqB,6NACqL,CAAC;AAExN,wBAAsB,WAAW,
|
|
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,0EAA0E;AAC1E,MAAM,MAAM,SAAS,GAAG,MAAM,GAAG,OAAO,CAAC;AAEzC;;sDAEsD;AACtD,eAAO,MAAM,qBAAqB;;;CAIxB,CAAC;AAEX,+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;2DAC2D;AAC3D,eAAO,MAAM,qBAAqB,6NACqL,CAAC;AAExN,wBAAsB,WAAW,CAC/B,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,MAAM,EACZ,KAAK,EAAE,MAAM,EACb,cAAc,CAAC,EAAE,SAAS,GACzB,OAAO,CAAC,IAAI,CAAC,CAqGf;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"}
|
|
@@ -6,12 +6,19 @@ import { ApiError } from '@parall/sdk';
|
|
|
6
6
|
import { resolveCredentials } from '../lib/client.js';
|
|
7
7
|
import { readLocalAction, runLocalAction } from './apps-action-local.js';
|
|
8
8
|
import { devAppHostPage } from './apps-dev-page.js';
|
|
9
|
+
/** What the page gets for a write action when the dev host shows it to
|
|
10
|
+
* someone who can only view the app: the code Parall answers with, and a
|
|
11
|
+
* message that says the refusal is the dev host's. */
|
|
12
|
+
export const DEV_VIEW_ONLY_REFUSAL = {
|
|
13
|
+
code: 'PERMISSION_DENIED',
|
|
14
|
+
message: 'You can only view this app, so its write actions are refused (parall app dev --access read: nothing ran)',
|
|
15
|
+
};
|
|
9
16
|
const MAX_BODY_BYTES = 1 << 20;
|
|
10
17
|
const MAX_CONSOLE_CHARS = 8000;
|
|
11
18
|
/** Printed when `parall app dev` starts: it is a server, and an agent that
|
|
12
19
|
* waits for it to return waits until its tool gives up. */
|
|
13
20
|
export const DEV_LONG_RUNNING_HINT = ' This keeps running until stopped: from a script or an agent, start it in the background (parall app dev … > dev.log 2>&1 &). To check one action, parall app action run <app> <name> --local runs it and returns.';
|
|
14
|
-
export async function serveAppDev(dist, port, appId) {
|
|
21
|
+
export async function serveAppDev(dist, port, appId, accessOverride) {
|
|
15
22
|
const { client, orgId } = resolveCredentials();
|
|
16
23
|
const apiUrl = process.env.PRLL_API_URL ?? '';
|
|
17
24
|
const [me, app, members] = await Promise.all([
|
|
@@ -20,6 +27,9 @@ export async function serveAppDev(dist, port, appId) {
|
|
|
20
27
|
client.getOrgMembers(orgId),
|
|
21
28
|
]);
|
|
22
29
|
const role = members.find((m) => m.user_id === me.id)?.role ?? 'member';
|
|
30
|
+
// Who runs this is almost always an author (they hold the app outright);
|
|
31
|
+
// --access read shows the page as someone who can only view it.
|
|
32
|
+
const access = accessOverride ?? app.viewer_access ?? 'write';
|
|
23
33
|
const appPort = port + 1;
|
|
24
34
|
const filesOrigin = filesOriginFor(apiUrl);
|
|
25
35
|
const token = randomBytes(24).toString('base64url');
|
|
@@ -38,6 +48,11 @@ export async function serveAppDev(dist, port, appId) {
|
|
|
38
48
|
// Read on every call, so a rebuild takes effect without a restart.
|
|
39
49
|
const local = await readLocalAction(dist, name);
|
|
40
50
|
kind = local.kind;
|
|
51
|
+
if (access === 'read' && kind === 'write') {
|
|
52
|
+
// As Parall answers someone who can only view the app: refused
|
|
53
|
+
// before anything runs.
|
|
54
|
+
return done({ ok: false, kind, error: { ...DEV_VIEW_ONLY_REFUSAL } });
|
|
55
|
+
}
|
|
41
56
|
const out = await runLocalAction(client, orgId, app.id, apiUrl, dist, name, local, params, {
|
|
42
57
|
console: (text) => {
|
|
43
58
|
printed = (printed + text).slice(-MAX_CONSOLE_CHARS);
|
|
@@ -71,7 +86,13 @@ export async function serveAppDev(dist, port, appId) {
|
|
|
71
86
|
const page = {
|
|
72
87
|
appOrigin: `http://127.0.0.1:${appPort}`,
|
|
73
88
|
app: { id: app.id, name: app.name, database_id: app.database_id },
|
|
74
|
-
viewer: {
|
|
89
|
+
viewer: {
|
|
90
|
+
id: me.id,
|
|
91
|
+
display_name: me.display_name,
|
|
92
|
+
is_agent: me.type === 'agent',
|
|
93
|
+
role,
|
|
94
|
+
access,
|
|
95
|
+
},
|
|
75
96
|
};
|
|
76
97
|
const host = createServer((req, res) => {
|
|
77
98
|
handleHostRequest(req, res, { port, token, page, run }).catch(() => failRequest(res));
|
|
@@ -89,7 +110,9 @@ export async function serveAppDev(dist, port, appId) {
|
|
|
89
110
|
}
|
|
90
111
|
console.error(`Mini App dev host: http://127.0.0.1:${port}/?t=${token}`);
|
|
91
112
|
console.error(` ${app.name} (${app.id}) from ${dist}, page on http://127.0.0.1:${appPort}`);
|
|
92
|
-
console.error(
|
|
113
|
+
console.error(access === 'read'
|
|
114
|
+
? " As someone who can only view the app: its write actions are refused without running; read actions run on this machine against the app's real Database. Ctrl-C to stop."
|
|
115
|
+
: " Actions run on this machine against the app's real Database: writes are real. Ctrl-C to stop.");
|
|
93
116
|
console.error(DEV_LONG_RUNNING_HINT);
|
|
94
117
|
}
|
|
95
118
|
/** The deployment's files-worker origin, the one outside source the
|
|
@@ -1,8 +1,19 @@
|
|
|
1
1
|
import type { Command } from 'commander';
|
|
2
|
+
import { type DevAccess } from './apps-dev-server.js';
|
|
2
3
|
/** `parall app dev`: a local host page speaking the same bridge as the
|
|
3
4
|
* Parall hosts, for an author (often an agent with a headless browser) to
|
|
4
5
|
* look at the built page before publishing. With --app the page also calls
|
|
5
6
|
* 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
|
+
* (apps-dev-server.ts); without it the host is static and offline.
|
|
8
|
+
* `--access read` shows the page to someone who can only view the app
|
|
9
|
+
* (mini-app-access-design.md §5.2): the viewer says so, and with --app its
|
|
10
|
+
* write actions are refused here, as Parall refuses them, without running. */
|
|
7
11
|
export declare function registerAppDevCommand(app: Command): void;
|
|
12
|
+
/** The viewer's level the host reports, as --access gives it; undefined
|
|
13
|
+
* when --access is not given. */
|
|
14
|
+
export declare function devAccess(raw: string | undefined): DevAccess | undefined;
|
|
15
|
+
/** The local host page: the host side of the bridge shell — answers ready
|
|
16
|
+
* with a dev viewer at `access`, relays resize, logs everything else. The
|
|
17
|
+
* same request/response protocol the real hosts speak (§6.3, shell subset). */
|
|
18
|
+
export declare function devHostPage(access: DevAccess): string;
|
|
8
19
|
//# sourceMappingURL=apps-dev.d.ts.map
|
|
@@ -1 +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;
|
|
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;AAEzC,OAAO,EAAyB,KAAK,SAAS,EAAe,MAAM,sBAAsB,CAAC;AAE1F;;;;;;;8EAO8E;AAC9E,wBAAgB,qBAAqB,CAAC,GAAG,EAAE,OAAO,QA+CjD;AAgBD;iCACiC;AACjC,wBAAgB,SAAS,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,GAAG,SAAS,GAAG,SAAS,CAKxE;AAmCD;;+EAE+E;AAC/E,wBAAgB,WAAW,CAAC,MAAM,EAAE,SAAS,GAAG,MAAM,CAiCrD"}
|
|
@@ -7,7 +7,10 @@ import { DEV_LONG_RUNNING_HINT, serveAppDev } from './apps-dev-server.js';
|
|
|
7
7
|
* Parall hosts, for an author (often an agent with a headless browser) to
|
|
8
8
|
* look at the built page before publishing. With --app the page also calls
|
|
9
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.
|
|
10
|
+
* (apps-dev-server.ts); without it the host is static and offline.
|
|
11
|
+
* `--access read` shows the page to someone who can only view the app
|
|
12
|
+
* (mini-app-access-design.md §5.2): the viewer says so, and with --app its
|
|
13
|
+
* write actions are refused here, as Parall refuses them, without running. */
|
|
11
14
|
export function registerAppDevCommand(app) {
|
|
12
15
|
app
|
|
13
16
|
.command('dev')
|
|
@@ -15,17 +18,19 @@ export function registerAppDevCommand(app) {
|
|
|
15
18
|
.option('--dist <dir>', 'The built bundle directory', 'dist')
|
|
16
19
|
.option('--port <n>', 'Port to listen on (with --app, the page uses the next one)', '5180')
|
|
17
20
|
.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)")
|
|
21
|
+
.option('--access <level>', 'Show the page as someone who can only view the app: read (with --app its write actions are refused without running), or write. Default: your own level on --app, else write')
|
|
18
22
|
.action(async (opts) => {
|
|
19
23
|
try {
|
|
24
|
+
const access = devAccess(opts.access);
|
|
20
25
|
const dist = resolve(opts.dist);
|
|
21
26
|
await fs.access(join(dist, 'index.html'));
|
|
22
27
|
const port = Number(opts.port);
|
|
23
28
|
if (opts.app) {
|
|
24
|
-
await serveAppDev(dist, port, stripPrllScheme(opts.app));
|
|
29
|
+
await serveAppDev(dist, port, stripPrllScheme(opts.app), access);
|
|
25
30
|
return;
|
|
26
31
|
}
|
|
27
32
|
const server = createServer((req, res) => {
|
|
28
|
-
void handleDevRequest(dist, req.url ?? '/', res);
|
|
33
|
+
void handleDevRequest(dist, req.url ?? '/', res, access ?? 'write');
|
|
29
34
|
});
|
|
30
35
|
// Loopback only: this serves the app's build directory and must not
|
|
31
36
|
// be reachable from the local network. A bind failure (port in use)
|
|
@@ -39,7 +44,7 @@ export function registerAppDevCommand(app) {
|
|
|
39
44
|
});
|
|
40
45
|
});
|
|
41
46
|
console.error(`Mini App dev host: http://127.0.0.1:${port}/ (serving ${dist})`);
|
|
42
|
-
console.error(
|
|
47
|
+
console.error(`The host page answers parall.ready() with a local dev viewer who can ${access === 'read' ? 'only view the app' : 'change the app'}; Ctrl-C to stop.`);
|
|
43
48
|
console.error(DEV_LONG_RUNNING_HINT);
|
|
44
49
|
}
|
|
45
50
|
catch (err) {
|
|
@@ -60,12 +65,22 @@ const devContentTypes = {
|
|
|
60
65
|
'.map': 'application/json',
|
|
61
66
|
'.woff2': 'font/woff2',
|
|
62
67
|
};
|
|
63
|
-
|
|
68
|
+
/** The viewer's level the host reports, as --access gives it; undefined
|
|
69
|
+
* when --access is not given. */
|
|
70
|
+
export function devAccess(raw) {
|
|
71
|
+
if (raw === undefined)
|
|
72
|
+
return undefined;
|
|
73
|
+
const level = raw.trim();
|
|
74
|
+
if (level === 'read' || level === 'write')
|
|
75
|
+
return level;
|
|
76
|
+
throw new Error('--access must be read or write');
|
|
77
|
+
}
|
|
78
|
+
async function handleDevRequest(dist, url, res, access) {
|
|
64
79
|
try {
|
|
65
80
|
const pathname = decodeURIComponent(new URL(url, 'http://localhost').pathname);
|
|
66
81
|
if (pathname === '/' || pathname === '/index.html') {
|
|
67
82
|
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
|
|
68
|
-
res.end(devHostPage());
|
|
83
|
+
res.end(devHostPage(access));
|
|
69
84
|
return;
|
|
70
85
|
}
|
|
71
86
|
if (pathname.startsWith('/app/')) {
|
|
@@ -89,9 +104,9 @@ async function handleDevRequest(dist, url, res) {
|
|
|
89
104
|
}
|
|
90
105
|
}
|
|
91
106
|
/** The local host page: the host side of the bridge shell — answers ready
|
|
92
|
-
* with a dev viewer
|
|
93
|
-
* request/response protocol the real hosts speak (§6.3, shell subset). */
|
|
94
|
-
function devHostPage() {
|
|
107
|
+
* with a dev viewer at `access`, relays resize, logs everything else. The
|
|
108
|
+
* same request/response protocol the real hosts speak (§6.3, shell subset). */
|
|
109
|
+
export function devHostPage(access) {
|
|
95
110
|
return `<!doctype html>
|
|
96
111
|
<html>
|
|
97
112
|
<head><meta charset="utf-8"><title>Mini App dev host</title>
|
|
@@ -108,7 +123,7 @@ function devHostPage() {
|
|
|
108
123
|
if (!msg || msg.parall !== 'v1' || typeof msg.id !== 'number') return;
|
|
109
124
|
if (msg.method === 'ready') {
|
|
110
125
|
frame.contentWindow.postMessage({ parall: 'v1', id: msg.id, result: {
|
|
111
|
-
viewer: { id: 'usr_dev', display_name: 'Dev Viewer', is_agent: false },
|
|
126
|
+
viewer: { id: 'usr_dev', display_name: 'Dev Viewer', is_agent: false, access: ${JSON.stringify(access)} },
|
|
112
127
|
app: { id: 'app_dev', name: 'local dev', version_seq: 0 },
|
|
113
128
|
route: location.hash.slice(1) || '',
|
|
114
129
|
}}, '*');
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export declare const PAGE_SDK_SOURCE = "/**\n * @parall/miniapp-sdk \u2014 the page side of the Mini App bridge (design \u00A77.1):\n * host handshake, host\u2192page events, resize, and `action`, the page's only\n * data method: it calls one of the app's server-side actions through the\n * host, which adds the viewer's session and the version the page loaded\n * (Mini App Action design \u00A73.1). No db, files, clip or chat methods exist\n * on this surface. The transport is postMessage to window.parent; the host\n * validates our origin, we validate that messages come from our parent\n * and, after the first answer, pin the parent's origin.\n *\n * Protocol (request/response + events):\n * page \u2192 host {parall: 'v1', id, method: 'ready' | 'resize' | 'action' | 'report', params}\n * host \u2192 page {parall: 'v1', id, result} | {parall: 'v1', id, error: {code, message, details?}}\n * host \u2192 page {parall: 'v1', event: 'route.changed' | 'viewer.changed' | 'data.changed', data}\n */\n\nexport interface ViewerSummary {\n id: string;\n display_name: string;\n is_agent: boolean;\n /** The viewer's organization role (owner / admin / member) \u2014 the same\n * value an action sees as ctx.viewer.role. */\n role?: string;\n}\n\nexport interface AppSummary {\n id: string;\n name: string;\n version_seq: number;\n}\n\nexport interface ReadyResult {\n viewer: ViewerSummary;\n app: AppSummary;\n route: string;\n}\n\n/** A Database the app reads was written. It carries no data: read again. */\nexport interface DataChanged {\n database_id: string;\n data_seq: number;\n /** Sent once after the host's connection came back: writes in between\n * may have been missed, so read again whatever data_seq says. */\n catch_up?: boolean;\n}\n\nexport type HostEvent =\n | { event: 'route.changed'; data: { route: string } }\n | { event: 'viewer.changed'; data: { viewer: ViewerSummary } }\n | { event: 'data.changed'; data: DataChanged };\n\n/** A refusal or failure from the host, in the error-contract envelope. An\n * action's failure keeps the server's code and details (invocation_id,\n * error_kind, field, current_version_seq\u2026); APP_VERSION_CHANGED means the\n * app was updated and the host offers the viewer a reload. */\nexport interface BridgeError extends Error {\n code: string;\n details?: Record<string, unknown>;\n}\n\ninterface WireError {\n code: string;\n message: string;\n details?: Record<string, unknown>;\n}\n\ntype Pending = {\n resolve: (v: unknown) => void;\n reject: (e: Error) => void;\n timer: ReturnType<typeof setTimeout>;\n};\n\nconst PROTOCOL = 'v1';\n\n// How long the page waits for the host. An action waits longer than the\n// host's request timeout, which waits longer than the server takes to\n// answer at worst \u2014 an action that calls Clip may run 100 s \u2014 so the page\n// always gets the server's answer rather than a timeout of its own (Mini\n// App Action design \u00A73.1, \u00A715; Clip design \u00A74.2).\nconst HOST_TIMEOUT_MS = 10_000;\nconst ACTION_TIMEOUT_MS = 120_000;\n\n// Marks the errors the bridge itself rejects with: what the host or the\n// server answered, never the page's own bug.\nconst FROM_BRIDGE = Symbol.for('parall.bridge-error');\n\nfunction bridgeError(\n code: string,\n message: string,\n details?: Record<string, unknown>,\n): BridgeError {\n const err = Object.assign(new Error(message), { code, details }) as BridgeError;\n Object.defineProperty(err, FROM_BRIDGE, { value: true });\n return err;\n}\n\n/**\n * What a page reports when something goes wrong (Mini App design \u00A79): an\n * error thrown on the page, a promise rejected without a handler, and an\n * action call that failed unexpectedly, timed out or ran over its limits.\n * Never console.error, and never an ActionError \u2014 that is the author's own\n * message to the caller. The host adds the version the page loaded and\n * reports it in the viewer's name; the app's authors are told.\n */\ntype ErrorReport = {\n kind: 'exception' | 'rejection' | 'action';\n name?: string;\n message?: string;\n stack?: string;\n action?: string;\n code?: string;\n invocation_id?: string;\n};\n\n// Each kind of error once per page load, and only so many: a page stuck in\n// a loop must not flood its authors (the server keeps its own budgets).\nconst REPORTS_PER_LOAD = 10;\nconst REPORTED_ACTION_CODES = new Set(['ACTION_TIMEOUT', 'ACTION_LIMIT_EXCEEDED']);\n\nfunction clip(s: string | undefined, max: number): string | undefined {\n return s && s.length > max ? s.slice(0, max) : s;\n}\n\n// A stack line that names a place in the code (file:line[:col]).\nconst FRAME = /:\\d+(?::\\d+)?\\)?$/;\n\n/** What makes two reports the same error \u2014 the way the server groups them:\n * an action failure by its action and code; anything else by its kind, its\n * name and the places its stack names, or by its message when the stack\n * names none. One throw site with a changing message is one error. */\nfunction reportKey(r: ErrorReport): string {\n if (r.kind === 'action') return `action\\u0000${r.action}\\u0000${r.code}`;\n const frames = (r.stack ?? '')\n .split('\\n')\n .map((line) => line.trim())\n .filter((line) => line !== '' && FRAME.test(line));\n return frames.length > 0\n ? `${r.kind}\\u0000${r.name}\\u0000${frames.join('\\n')}`\n : `${r.kind}\\u0000${r.name}\\u0000message\\u0000${r.message}`;\n}\n\nfunction describe(value: unknown): string {\n if (typeof value === 'string') return value;\n try {\n return JSON.stringify(value) ?? String(value);\n } catch {\n return String(value);\n }\n}\n\nclass MiniAppBridge {\n private nextId = 1;\n private pending = new Map<number, Pending>();\n private listeners = new Set<(e: HostEvent) => void>();\n private hostOrigin: string | null = null;\n private started = false;\n private reported = new Set<string>();\n\n constructor() {\n if (typeof window === 'undefined' || typeof window.addEventListener !== 'function') return;\n window.addEventListener('error', (event: ErrorEvent) => {\n const err: unknown = event.error;\n if (err instanceof Error) {\n this.report({ kind: 'exception', name: err.name, message: err.message, stack: err.stack });\n } else {\n const where = event.filename\n ? ` at ${event.filename}:${event.lineno}:${event.colno}`\n : '';\n this.report({\n kind: 'exception',\n name: 'Error',\n message: String(event.message || 'Script error.'),\n stack: where,\n });\n }\n });\n window.addEventListener('unhandledrejection', (event: PromiseRejectionEvent) => {\n const reason: unknown = event.reason;\n // The bridge's own rejections are the host's or the server's answers:\n // a failed action is reported where it failed, by its own rules.\n if (reason !== null && typeof reason === 'object' && FROM_BRIDGE in reason) return;\n if (reason instanceof Error) {\n this.report({\n kind: 'rejection',\n name: reason.name,\n message: reason.message,\n stack: reason.stack,\n });\n } else {\n this.report({ kind: 'rejection', name: '', message: describe(reason) });\n }\n });\n }\n\n /** Sends one error report to the host; drops repeats, anything past the\n * page's share, and every failure of the report itself (an older host\n * answers NOT_GRANTED). */\n private report(r: ErrorReport): void {\n // Cut to what the host may send: the server takes at most 16 KiB.\n const params: ErrorReport = {\n ...r,\n name: clip(r.name, 100),\n message: clip(r.message, 500),\n stack: clip(r.stack, 3000),\n };\n const key = reportKey(params);\n if (this.reported.has(key) || this.reported.size >= REPORTS_PER_LOAD) return;\n this.reported.add(key);\n void this.call('report', params).catch(() => {});\n }\n\n private start(): void {\n if (this.started) return;\n this.started = true;\n window.addEventListener('message', (event: MessageEvent) => {\n // Only our embedding host: same source as window.parent, and once\n // the handshake pinned an origin, exactly that origin.\n if (event.source !== window.parent) return;\n if (this.hostOrigin !== null && event.origin !== this.hostOrigin) return;\n const msg = event.data as Record<string, unknown> | null;\n if (!msg || msg.parall !== PROTOCOL) return;\n if (typeof msg.id === 'number') {\n const pending = this.pending.get(msg.id);\n if (!pending) return;\n this.pending.delete(msg.id);\n clearTimeout(pending.timer);\n if (this.hostOrigin === null) this.hostOrigin = event.origin;\n if (msg.error) {\n const err = msg.error as WireError;\n pending.reject(bridgeError(err.code, err.message, err.details));\n } else {\n pending.resolve(msg.result);\n }\n return;\n }\n if (typeof msg.event === 'string') {\n for (const fn of this.listeners) fn(msg as unknown as HostEvent);\n }\n });\n }\n\n private call<T>(method: string, params?: unknown, timeoutMs = HOST_TIMEOUT_MS): Promise<T> {\n this.start();\n const id = this.nextId++;\n return new Promise<T>((resolve, reject) => {\n const timer = setTimeout(() => {\n if (this.pending.delete(id)) {\n reject(bridgeError('HOST_TIMEOUT', `${method} timed out waiting for the host`));\n }\n }, timeoutMs);\n this.pending.set(id, { resolve: resolve as (v: unknown) => void, reject, timer });\n window.parent.postMessage({ parall: PROTOCOL, id, method, params }, '*');\n });\n }\n\n /** Handshake with the host; resolves with the viewer, app and initial route. */\n ready(): Promise<ReadyResult> {\n return this.call<ReadyResult>('ready');\n }\n\n /** Ask the host to grow/shrink the iframe (fire-and-forget semantics). */\n resize(height: number): void {\n void this.call('resize', { height }).catch(() => {});\n }\n\n /**\n * Call one of the app's actions with the viewer's identity and resolve\n * with what the action returned. A failure rejects with a BridgeError\n * whose code is the server's (ACTION_FAILED, ACTION_TIMEOUT,\n * INVALID_ACTION_PARAMS, APP_VERSION_CHANGED\u2026); its message is the\n * action's ActionError message when it threw one. HOST_TIMEOUT and\n * HOST_UNAVAILABLE mean no answer came back: whether the action ran is\n * not known, so read again before retrying a write.\n */\n async action<T = unknown>(name: string, params?: Record<string, unknown>): Promise<T> {\n let answer: { invocation_id: string; result: T };\n try {\n answer = await this.call<{ invocation_id: string; result: T }>(\n 'action',\n { name, params: params ?? {} },\n ACTION_TIMEOUT_MS,\n );\n } catch (err) {\n // The app's authors hear of an action that failed unexpectedly, timed\n // out or ran over its limits \u2014 caught by the page or not. An\n // ActionError (error_kind \"action\") is the author's own answer.\n const e = err as BridgeError;\n const unexpected = e.code === 'ACTION_FAILED' && e.details?.error_kind === 'unexpected';\n if (unexpected || REPORTED_ACTION_CODES.has(e.code)) {\n const invocation = e.details?.invocation_id;\n this.report({\n kind: 'action',\n action: name,\n code: e.code,\n invocation_id: typeof invocation === 'string' ? invocation : undefined,\n });\n }\n throw err;\n }\n return answer.result;\n }\n\n /** Subscribe to host events; returns the unsubscribe function. */\n onEvent(fn: (e: HostEvent) => void): () => void {\n this.start();\n this.listeners.add(fn);\n return () => this.listeners.delete(fn);\n }\n\n /**\n * Call fn when a Database the app reads has new writes: once per new\n * (database_id, data_seq) \u2014 repeats and older ones are dropped \u2014 and\n * always on a catch-up after the host reconnected. Read again in fn.\n */\n onDataChanged(fn: (change: DataChanged) => void): () => void {\n const seen = new Map<string, number>();\n return this.onEvent((e) => {\n if (e.event !== 'data.changed') return;\n const { database_id, data_seq, catch_up } = e.data;\n const last = seen.get(database_id);\n if (!catch_up && last !== undefined && data_seq <= last) return;\n if (last === undefined || data_seq > last) seen.set(database_id, data_seq);\n fn(e.data);\n });\n }\n}\n\nexport const parall = new MiniAppBridge();\n";
|
|
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 /** How far the viewer reaches into this app: 'write' \u2014 they may call\n * every action \u2014 or 'read' \u2014 they may only call read actions, and the\n * platform refuses their write actions. A hint for hiding edit controls,\n * never the gate. Absent from hosts that predate it: read it as 'write'.\n * An action's ctx.viewer does not carry it. */\n access?: 'read' | 'write';\n}\n\nexport interface AppSummary {\n id: string;\n name: string;\n version_seq: number;\n}\n\nexport interface ReadyResult {\n viewer: ViewerSummary;\n app: AppSummary;\n route: string;\n}\n\n/** A Database the app reads was written. It carries no data: read again. */\nexport interface DataChanged {\n database_id: string;\n data_seq: number;\n /** Sent once after the host's connection came back: writes in between\n * may have been missed, so read again whatever data_seq says. */\n catch_up?: boolean;\n}\n\nexport type HostEvent =\n | { event: 'route.changed'; data: { route: string } }\n | { event: 'viewer.changed'; data: { viewer: ViewerSummary } }\n | { event: 'data.changed'; data: DataChanged };\n\n/** A refusal or failure from the host, in the error-contract envelope. An\n * action's failure keeps the server's code and details (invocation_id,\n * error_kind, field, current_version_seq\u2026); APP_VERSION_CHANGED means the\n * app was updated and the host offers the viewer a reload. */\nexport interface BridgeError extends Error {\n code: string;\n details?: Record<string, unknown>;\n}\n\ninterface WireError {\n code: string;\n message: string;\n details?: Record<string, unknown>;\n}\n\ntype Pending = {\n resolve: (v: unknown) => void;\n reject: (e: Error) => void;\n timer: ReturnType<typeof setTimeout>;\n};\n\nconst PROTOCOL = 'v1';\n\n// How long the page waits for the host. An action waits longer than the\n// host's request timeout, which waits longer than the server takes to\n// answer at worst \u2014 an action that calls Clip may run 100 s \u2014 so the page\n// always gets the server's answer rather than a timeout of its own (Mini\n// App Action design \u00A73.1, \u00A715; Clip design \u00A74.2).\nconst HOST_TIMEOUT_MS = 10_000;\nconst ACTION_TIMEOUT_MS = 120_000;\n\n// Marks the errors the bridge itself rejects with: what the host or the\n// server answered, never the page's own bug.\nconst FROM_BRIDGE = Symbol.for('parall.bridge-error');\n\nfunction bridgeError(\n code: string,\n message: string,\n details?: Record<string, unknown>,\n): BridgeError {\n const err = Object.assign(new Error(message), { code, details }) as BridgeError;\n Object.defineProperty(err, FROM_BRIDGE, { value: true });\n return err;\n}\n\n/**\n * What a page reports when something goes wrong (Mini App design \u00A79): an\n * error thrown on the page, a promise rejected without a handler, and an\n * action call that failed unexpectedly, timed out or ran over its limits.\n * Never console.error, and never an ActionError \u2014 that is the author's own\n * message to the caller. The host adds the version the page loaded and\n * reports it in the viewer's name; the app's authors are told.\n */\ntype ErrorReport = {\n kind: 'exception' | 'rejection' | 'action';\n name?: string;\n message?: string;\n stack?: string;\n action?: string;\n code?: string;\n invocation_id?: string;\n};\n\n// Each kind of error once per page load, and only so many: a page stuck in\n// a loop must not flood its authors (the server keeps its own budgets).\nconst REPORTS_PER_LOAD = 10;\nconst REPORTED_ACTION_CODES = new Set(['ACTION_TIMEOUT', 'ACTION_LIMIT_EXCEEDED']);\n\nfunction clip(s: string | undefined, max: number): string | undefined {\n return s && s.length > max ? s.slice(0, max) : s;\n}\n\n// A stack line that names a place in the code (file:line[:col]).\nconst FRAME = /:\\d+(?::\\d+)?\\)?$/;\n\n/** What makes two reports the same error \u2014 the way the server groups them:\n * an action failure by its action and code; anything else by its kind, its\n * name and the places its stack names, or by its message when the stack\n * names none. One throw site with a changing message is one error. */\nfunction reportKey(r: ErrorReport): string {\n if (r.kind === 'action') return `action\\u0000${r.action}\\u0000${r.code}`;\n const frames = (r.stack ?? '')\n .split('\\n')\n .map((line) => line.trim())\n .filter((line) => line !== '' && FRAME.test(line));\n return frames.length > 0\n ? `${r.kind}\\u0000${r.name}\\u0000${frames.join('\\n')}`\n : `${r.kind}\\u0000${r.name}\\u0000message\\u0000${r.message}`;\n}\n\nfunction describe(value: unknown): string {\n if (typeof value === 'string') return value;\n try {\n return JSON.stringify(value) ?? String(value);\n } catch {\n return String(value);\n }\n}\n\nclass MiniAppBridge {\n private nextId = 1;\n private pending = new Map<number, Pending>();\n private listeners = new Set<(e: HostEvent) => void>();\n private hostOrigin: string | null = null;\n private started = false;\n private reported = new Set<string>();\n\n constructor() {\n if (typeof window === 'undefined' || typeof window.addEventListener !== 'function') return;\n window.addEventListener('error', (event: ErrorEvent) => {\n const err: unknown = event.error;\n if (err instanceof Error) {\n this.report({ kind: 'exception', name: err.name, message: err.message, stack: err.stack });\n } else {\n const where = event.filename\n ? ` at ${event.filename}:${event.lineno}:${event.colno}`\n : '';\n this.report({\n kind: 'exception',\n name: 'Error',\n message: String(event.message || 'Script error.'),\n stack: where,\n });\n }\n });\n window.addEventListener('unhandledrejection', (event: PromiseRejectionEvent) => {\n const reason: unknown = event.reason;\n // The bridge's own rejections are the host's or the server's answers:\n // a failed action is reported where it failed, by its own rules.\n if (reason !== null && typeof reason === 'object' && FROM_BRIDGE in reason) return;\n if (reason instanceof Error) {\n this.report({\n kind: 'rejection',\n name: reason.name,\n message: reason.message,\n stack: reason.stack,\n });\n } else {\n this.report({ kind: 'rejection', name: '', message: describe(reason) });\n }\n });\n }\n\n /** Sends one error report to the host; drops repeats, anything past the\n * page's share, and every failure of the report itself (an older host\n * answers NOT_GRANTED). */\n private report(r: ErrorReport): void {\n // Cut to what the host may send: the server takes at most 16 KiB.\n const params: ErrorReport = {\n ...r,\n name: clip(r.name, 100),\n message: clip(r.message, 500),\n stack: clip(r.stack, 3000),\n };\n const key = reportKey(params);\n if (this.reported.has(key) || this.reported.size >= REPORTS_PER_LOAD) return;\n this.reported.add(key);\n void this.call('report', params).catch(() => {});\n }\n\n private start(): void {\n if (this.started) return;\n this.started = true;\n window.addEventListener('message', (event: MessageEvent) => {\n // Only our embedding host: same source as window.parent, and once\n // the handshake pinned an origin, exactly that origin.\n if (event.source !== window.parent) return;\n if (this.hostOrigin !== null && event.origin !== this.hostOrigin) return;\n const msg = event.data as Record<string, unknown> | null;\n if (!msg || msg.parall !== PROTOCOL) return;\n if (typeof msg.id === 'number') {\n const pending = this.pending.get(msg.id);\n if (!pending) return;\n this.pending.delete(msg.id);\n clearTimeout(pending.timer);\n if (this.hostOrigin === null) this.hostOrigin = event.origin;\n if (msg.error) {\n const err = msg.error as WireError;\n pending.reject(bridgeError(err.code, err.message, err.details));\n } else {\n pending.resolve(msg.result);\n }\n return;\n }\n if (typeof msg.event === 'string') {\n for (const fn of this.listeners) fn(msg as unknown as HostEvent);\n }\n });\n }\n\n private call<T>(method: string, params?: unknown, timeoutMs = HOST_TIMEOUT_MS): Promise<T> {\n this.start();\n const id = this.nextId++;\n return new Promise<T>((resolve, reject) => {\n const timer = setTimeout(() => {\n if (this.pending.delete(id)) {\n reject(bridgeError('HOST_TIMEOUT', `${method} timed out waiting for the host`));\n }\n }, timeoutMs);\n this.pending.set(id, { resolve: resolve as (v: unknown) => void, reject, timer });\n window.parent.postMessage({ parall: PROTOCOL, id, method, params }, '*');\n });\n }\n\n /** Handshake with the host; resolves with the viewer, app and initial route. */\n ready(): Promise<ReadyResult> {\n return this.call<ReadyResult>('ready');\n }\n\n /** Ask the host to grow/shrink the iframe (fire-and-forget semantics). */\n resize(height: number): void {\n void this.call('resize', { height }).catch(() => {});\n }\n\n /**\n * Call one of the app's actions with the viewer's identity and resolve\n * with what the action returned. A failure rejects with a BridgeError\n * whose code is the server's (ACTION_FAILED, ACTION_TIMEOUT,\n * INVALID_ACTION_PARAMS, APP_VERSION_CHANGED\u2026); its message is the\n * action's ActionError message when it threw one. HOST_TIMEOUT and\n * HOST_UNAVAILABLE mean no answer came back: whether the action ran is\n * not known, so read again before retrying a write.\n */\n async action<T = unknown>(name: string, params?: Record<string, unknown>): Promise<T> {\n let answer: { invocation_id: string; result: T };\n try {\n answer = await this.call<{ invocation_id: string; result: T }>(\n 'action',\n { name, params: params ?? {} },\n ACTION_TIMEOUT_MS,\n );\n } catch (err) {\n // The app's authors hear of an action that failed unexpectedly, timed\n // out or ran over its limits \u2014 caught by the page or not. An\n // ActionError (error_kind \"action\") is the author's own answer.\n const e = err as BridgeError;\n const unexpected = e.code === 'ACTION_FAILED' && e.details?.error_kind === 'unexpected';\n if (unexpected || REPORTED_ACTION_CODES.has(e.code)) {\n const invocation = e.details?.invocation_id;\n this.report({\n kind: 'action',\n action: name,\n code: e.code,\n invocation_id: typeof invocation === 'string' ? invocation : undefined,\n });\n }\n throw err;\n }\n return answer.result;\n }\n\n /** Subscribe to host events; returns the unsubscribe function. */\n onEvent(fn: (e: HostEvent) => void): () => void {\n this.start();\n this.listeners.add(fn);\n return () => this.listeners.delete(fn);\n }\n\n /**\n * Call fn when a Database the app reads has new writes: once per new\n * (database_id, data_seq) \u2014 repeats and older ones are dropped \u2014 and\n * always on a catch-up after the host reconnected. Read again in fn.\n */\n onDataChanged(fn: (change: DataChanged) => void): () => void {\n const seen = new Map<string, number>();\n return this.onEvent((e) => {\n if (e.event !== 'data.changed') return;\n const { database_id, data_seq, catch_up } = e.data;\n const last = seen.get(database_id);\n if (!catch_up && last !== undefined && data_seq <= last) return;\n if (last === undefined || data_seq > last) seen.set(database_id, data_seq);\n fn(e.data);\n });\n }\n}\n\nexport const parall = new MiniAppBridge();\n";
|
|
2
2
|
//# sourceMappingURL=apps-page-sdk.generated.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"apps-page-sdk.generated.d.ts","sourceRoot":"","sources":["../../src/commands/apps-page-sdk.generated.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,eAAe,
|
|
1
|
+
{"version":3,"file":"apps-page-sdk.generated.d.ts","sourceRoot":"","sources":["../../src/commands/apps-page-sdk.generated.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,eAAe,8xZAAsqZ,CAAC"}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// Generated from ts/miniapp-sdk/src/index.ts by scripts/generate-miniapp-sdk.mjs. Do not edit.
|
|
2
2
|
// biome-ignore format: generated copy
|
|
3
|
-
export const PAGE_SDK_SOURCE = "/**\n * @parall/miniapp-sdk — the page side of the Mini App bridge (design §7.1):\n * host handshake, host→page events, resize, and `action`, the page's only\n * data method: it calls one of the app's server-side actions through the\n * host, which adds the viewer's session and the version the page loaded\n * (Mini App Action design §3.1). No db, files, clip or chat methods exist\n * on this surface. The transport is postMessage to window.parent; the host\n * validates our origin, we validate that messages come from our parent\n * and, after the first answer, pin the parent's origin.\n *\n * Protocol (request/response + events):\n * page → host {parall: 'v1', id, method: 'ready' | 'resize' | 'action' | 'report', params}\n * host → page {parall: 'v1', id, result} | {parall: 'v1', id, error: {code, message, details?}}\n * host → page {parall: 'v1', event: 'route.changed' | 'viewer.changed' | 'data.changed', data}\n */\n\nexport interface ViewerSummary {\n id: string;\n display_name: string;\n is_agent: boolean;\n /** The viewer's organization role (owner / admin / member) — the same\n * value an action sees as ctx.viewer.role. */\n role?: string;\n}\n\nexport interface AppSummary {\n id: string;\n name: string;\n version_seq: number;\n}\n\nexport interface ReadyResult {\n viewer: ViewerSummary;\n app: AppSummary;\n route: string;\n}\n\n/** A Database the app reads was written. It carries no data: read again. */\nexport interface DataChanged {\n database_id: string;\n data_seq: number;\n /** Sent once after the host's connection came back: writes in between\n * may have been missed, so read again whatever data_seq says. */\n catch_up?: boolean;\n}\n\nexport type HostEvent =\n | { event: 'route.changed'; data: { route: string } }\n | { event: 'viewer.changed'; data: { viewer: ViewerSummary } }\n | { event: 'data.changed'; data: DataChanged };\n\n/** A refusal or failure from the host, in the error-contract envelope. An\n * action's failure keeps the server's code and details (invocation_id,\n * error_kind, field, current_version_seq…); APP_VERSION_CHANGED means the\n * app was updated and the host offers the viewer a reload. */\nexport interface BridgeError extends Error {\n code: string;\n details?: Record<string, unknown>;\n}\n\ninterface WireError {\n code: string;\n message: string;\n details?: Record<string, unknown>;\n}\n\ntype Pending = {\n resolve: (v: unknown) => void;\n reject: (e: Error) => void;\n timer: ReturnType<typeof setTimeout>;\n};\n\nconst PROTOCOL = 'v1';\n\n// How long the page waits for the host. An action waits longer than the\n// host's request timeout, which waits longer than the server takes to\n// answer at worst — an action that calls Clip may run 100 s — so the page\n// always gets the server's answer rather than a timeout of its own (Mini\n// App Action design §3.1, §15; Clip design §4.2).\nconst HOST_TIMEOUT_MS = 10_000;\nconst ACTION_TIMEOUT_MS = 120_000;\n\n// Marks the errors the bridge itself rejects with: what the host or the\n// server answered, never the page's own bug.\nconst FROM_BRIDGE = Symbol.for('parall.bridge-error');\n\nfunction bridgeError(\n code: string,\n message: string,\n details?: Record<string, unknown>,\n): BridgeError {\n const err = Object.assign(new Error(message), { code, details }) as BridgeError;\n Object.defineProperty(err, FROM_BRIDGE, { value: true });\n return err;\n}\n\n/**\n * What a page reports when something goes wrong (Mini App design §9): an\n * error thrown on the page, a promise rejected without a handler, and an\n * action call that failed unexpectedly, timed out or ran over its limits.\n * Never console.error, and never an ActionError — that is the author's own\n * message to the caller. The host adds the version the page loaded and\n * reports it in the viewer's name; the app's authors are told.\n */\ntype ErrorReport = {\n kind: 'exception' | 'rejection' | 'action';\n name?: string;\n message?: string;\n stack?: string;\n action?: string;\n code?: string;\n invocation_id?: string;\n};\n\n// Each kind of error once per page load, and only so many: a page stuck in\n// a loop must not flood its authors (the server keeps its own budgets).\nconst REPORTS_PER_LOAD = 10;\nconst REPORTED_ACTION_CODES = new Set(['ACTION_TIMEOUT', 'ACTION_LIMIT_EXCEEDED']);\n\nfunction clip(s: string | undefined, max: number): string | undefined {\n return s && s.length > max ? s.slice(0, max) : s;\n}\n\n// A stack line that names a place in the code (file:line[:col]).\nconst FRAME = /:\\d+(?::\\d+)?\\)?$/;\n\n/** What makes two reports the same error — the way the server groups them:\n * an action failure by its action and code; anything else by its kind, its\n * name and the places its stack names, or by its message when the stack\n * names none. One throw site with a changing message is one error. */\nfunction reportKey(r: ErrorReport): string {\n if (r.kind === 'action') return `action\\u0000${r.action}\\u0000${r.code}`;\n const frames = (r.stack ?? '')\n .split('\\n')\n .map((line) => line.trim())\n .filter((line) => line !== '' && FRAME.test(line));\n return frames.length > 0\n ? `${r.kind}\\u0000${r.name}\\u0000${frames.join('\\n')}`\n : `${r.kind}\\u0000${r.name}\\u0000message\\u0000${r.message}`;\n}\n\nfunction describe(value: unknown): string {\n if (typeof value === 'string') return value;\n try {\n return JSON.stringify(value) ?? String(value);\n } catch {\n return String(value);\n }\n}\n\nclass MiniAppBridge {\n private nextId = 1;\n private pending = new Map<number, Pending>();\n private listeners = new Set<(e: HostEvent) => void>();\n private hostOrigin: string | null = null;\n private started = false;\n private reported = new Set<string>();\n\n constructor() {\n if (typeof window === 'undefined' || typeof window.addEventListener !== 'function') return;\n window.addEventListener('error', (event: ErrorEvent) => {\n const err: unknown = event.error;\n if (err instanceof Error) {\n this.report({ kind: 'exception', name: err.name, message: err.message, stack: err.stack });\n } else {\n const where = event.filename\n ? ` at ${event.filename}:${event.lineno}:${event.colno}`\n : '';\n this.report({\n kind: 'exception',\n name: 'Error',\n message: String(event.message || 'Script error.'),\n stack: where,\n });\n }\n });\n window.addEventListener('unhandledrejection', (event: PromiseRejectionEvent) => {\n const reason: unknown = event.reason;\n // The bridge's own rejections are the host's or the server's answers:\n // a failed action is reported where it failed, by its own rules.\n if (reason !== null && typeof reason === 'object' && FROM_BRIDGE in reason) return;\n if (reason instanceof Error) {\n this.report({\n kind: 'rejection',\n name: reason.name,\n message: reason.message,\n stack: reason.stack,\n });\n } else {\n this.report({ kind: 'rejection', name: '', message: describe(reason) });\n }\n });\n }\n\n /** Sends one error report to the host; drops repeats, anything past the\n * page's share, and every failure of the report itself (an older host\n * answers NOT_GRANTED). */\n private report(r: ErrorReport): void {\n // Cut to what the host may send: the server takes at most 16 KiB.\n const params: ErrorReport = {\n ...r,\n name: clip(r.name, 100),\n message: clip(r.message, 500),\n stack: clip(r.stack, 3000),\n };\n const key = reportKey(params);\n if (this.reported.has(key) || this.reported.size >= REPORTS_PER_LOAD) return;\n this.reported.add(key);\n void this.call('report', params).catch(() => {});\n }\n\n private start(): void {\n if (this.started) return;\n this.started = true;\n window.addEventListener('message', (event: MessageEvent) => {\n // Only our embedding host: same source as window.parent, and once\n // the handshake pinned an origin, exactly that origin.\n if (event.source !== window.parent) return;\n if (this.hostOrigin !== null && event.origin !== this.hostOrigin) return;\n const msg = event.data as Record<string, unknown> | null;\n if (!msg || msg.parall !== PROTOCOL) return;\n if (typeof msg.id === 'number') {\n const pending = this.pending.get(msg.id);\n if (!pending) return;\n this.pending.delete(msg.id);\n clearTimeout(pending.timer);\n if (this.hostOrigin === null) this.hostOrigin = event.origin;\n if (msg.error) {\n const err = msg.error as WireError;\n pending.reject(bridgeError(err.code, err.message, err.details));\n } else {\n pending.resolve(msg.result);\n }\n return;\n }\n if (typeof msg.event === 'string') {\n for (const fn of this.listeners) fn(msg as unknown as HostEvent);\n }\n });\n }\n\n private call<T>(method: string, params?: unknown, timeoutMs = HOST_TIMEOUT_MS): Promise<T> {\n this.start();\n const id = this.nextId++;\n return new Promise<T>((resolve, reject) => {\n const timer = setTimeout(() => {\n if (this.pending.delete(id)) {\n reject(bridgeError('HOST_TIMEOUT', `${method} timed out waiting for the host`));\n }\n }, timeoutMs);\n this.pending.set(id, { resolve: resolve as (v: unknown) => void, reject, timer });\n window.parent.postMessage({ parall: PROTOCOL, id, method, params }, '*');\n });\n }\n\n /** Handshake with the host; resolves with the viewer, app and initial route. */\n ready(): Promise<ReadyResult> {\n return this.call<ReadyResult>('ready');\n }\n\n /** Ask the host to grow/shrink the iframe (fire-and-forget semantics). */\n resize(height: number): void {\n void this.call('resize', { height }).catch(() => {});\n }\n\n /**\n * Call one of the app's actions with the viewer's identity and resolve\n * with what the action returned. A failure rejects with a BridgeError\n * whose code is the server's (ACTION_FAILED, ACTION_TIMEOUT,\n * INVALID_ACTION_PARAMS, APP_VERSION_CHANGED…); its message is the\n * action's ActionError message when it threw one. HOST_TIMEOUT and\n * HOST_UNAVAILABLE mean no answer came back: whether the action ran is\n * not known, so read again before retrying a write.\n */\n async action<T = unknown>(name: string, params?: Record<string, unknown>): Promise<T> {\n let answer: { invocation_id: string; result: T };\n try {\n answer = await this.call<{ invocation_id: string; result: T }>(\n 'action',\n { name, params: params ?? {} },\n ACTION_TIMEOUT_MS,\n );\n } catch (err) {\n // The app's authors hear of an action that failed unexpectedly, timed\n // out or ran over its limits — caught by the page or not. An\n // ActionError (error_kind \"action\") is the author's own answer.\n const e = err as BridgeError;\n const unexpected = e.code === 'ACTION_FAILED' && e.details?.error_kind === 'unexpected';\n if (unexpected || REPORTED_ACTION_CODES.has(e.code)) {\n const invocation = e.details?.invocation_id;\n this.report({\n kind: 'action',\n action: name,\n code: e.code,\n invocation_id: typeof invocation === 'string' ? invocation : undefined,\n });\n }\n throw err;\n }\n return answer.result;\n }\n\n /** Subscribe to host events; returns the unsubscribe function. */\n onEvent(fn: (e: HostEvent) => void): () => void {\n this.start();\n this.listeners.add(fn);\n return () => this.listeners.delete(fn);\n }\n\n /**\n * Call fn when a Database the app reads has new writes: once per new\n * (database_id, data_seq) — repeats and older ones are dropped — and\n * always on a catch-up after the host reconnected. Read again in fn.\n */\n onDataChanged(fn: (change: DataChanged) => void): () => void {\n const seen = new Map<string, number>();\n return this.onEvent((e) => {\n if (e.event !== 'data.changed') return;\n const { database_id, data_seq, catch_up } = e.data;\n const last = seen.get(database_id);\n if (!catch_up && last !== undefined && data_seq <= last) return;\n if (last === undefined || data_seq > last) seen.set(database_id, data_seq);\n fn(e.data);\n });\n }\n}\n\nexport const parall = new MiniAppBridge();\n";
|
|
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 /** How far the viewer reaches into this app: 'write' — they may call\n * every action — or 'read' — they may only call read actions, and the\n * platform refuses their write actions. A hint for hiding edit controls,\n * never the gate. Absent from hosts that predate it: read it as 'write'.\n * An action's ctx.viewer does not carry it. */\n access?: 'read' | 'write';\n}\n\nexport interface AppSummary {\n id: string;\n name: string;\n version_seq: number;\n}\n\nexport interface ReadyResult {\n viewer: ViewerSummary;\n app: AppSummary;\n route: string;\n}\n\n/** A Database the app reads was written. It carries no data: read again. */\nexport interface DataChanged {\n database_id: string;\n data_seq: number;\n /** Sent once after the host's connection came back: writes in between\n * may have been missed, so read again whatever data_seq says. */\n catch_up?: boolean;\n}\n\nexport type HostEvent =\n | { event: 'route.changed'; data: { route: string } }\n | { event: 'viewer.changed'; data: { viewer: ViewerSummary } }\n | { event: 'data.changed'; data: DataChanged };\n\n/** A refusal or failure from the host, in the error-contract envelope. An\n * action's failure keeps the server's code and details (invocation_id,\n * error_kind, field, current_version_seq…); APP_VERSION_CHANGED means the\n * app was updated and the host offers the viewer a reload. */\nexport interface BridgeError extends Error {\n code: string;\n details?: Record<string, unknown>;\n}\n\ninterface WireError {\n code: string;\n message: string;\n details?: Record<string, unknown>;\n}\n\ntype Pending = {\n resolve: (v: unknown) => void;\n reject: (e: Error) => void;\n timer: ReturnType<typeof setTimeout>;\n};\n\nconst PROTOCOL = 'v1';\n\n// How long the page waits for the host. An action waits longer than the\n// host's request timeout, which waits longer than the server takes to\n// answer at worst — an action that calls Clip may run 100 s — so the page\n// always gets the server's answer rather than a timeout of its own (Mini\n// App Action design §3.1, §15; Clip design §4.2).\nconst HOST_TIMEOUT_MS = 10_000;\nconst ACTION_TIMEOUT_MS = 120_000;\n\n// Marks the errors the bridge itself rejects with: what the host or the\n// server answered, never the page's own bug.\nconst FROM_BRIDGE = Symbol.for('parall.bridge-error');\n\nfunction bridgeError(\n code: string,\n message: string,\n details?: Record<string, unknown>,\n): BridgeError {\n const err = Object.assign(new Error(message), { code, details }) as BridgeError;\n Object.defineProperty(err, FROM_BRIDGE, { value: true });\n return err;\n}\n\n/**\n * What a page reports when something goes wrong (Mini App design §9): an\n * error thrown on the page, a promise rejected without a handler, and an\n * action call that failed unexpectedly, timed out or ran over its limits.\n * Never console.error, and never an ActionError — that is the author's own\n * message to the caller. The host adds the version the page loaded and\n * reports it in the viewer's name; the app's authors are told.\n */\ntype ErrorReport = {\n kind: 'exception' | 'rejection' | 'action';\n name?: string;\n message?: string;\n stack?: string;\n action?: string;\n code?: string;\n invocation_id?: string;\n};\n\n// Each kind of error once per page load, and only so many: a page stuck in\n// a loop must not flood its authors (the server keeps its own budgets).\nconst REPORTS_PER_LOAD = 10;\nconst REPORTED_ACTION_CODES = new Set(['ACTION_TIMEOUT', 'ACTION_LIMIT_EXCEEDED']);\n\nfunction clip(s: string | undefined, max: number): string | undefined {\n return s && s.length > max ? s.slice(0, max) : s;\n}\n\n// A stack line that names a place in the code (file:line[:col]).\nconst FRAME = /:\\d+(?::\\d+)?\\)?$/;\n\n/** What makes two reports the same error — the way the server groups them:\n * an action failure by its action and code; anything else by its kind, its\n * name and the places its stack names, or by its message when the stack\n * names none. One throw site with a changing message is one error. */\nfunction reportKey(r: ErrorReport): string {\n if (r.kind === 'action') return `action\\u0000${r.action}\\u0000${r.code}`;\n const frames = (r.stack ?? '')\n .split('\\n')\n .map((line) => line.trim())\n .filter((line) => line !== '' && FRAME.test(line));\n return frames.length > 0\n ? `${r.kind}\\u0000${r.name}\\u0000${frames.join('\\n')}`\n : `${r.kind}\\u0000${r.name}\\u0000message\\u0000${r.message}`;\n}\n\nfunction describe(value: unknown): string {\n if (typeof value === 'string') return value;\n try {\n return JSON.stringify(value) ?? String(value);\n } catch {\n return String(value);\n }\n}\n\nclass MiniAppBridge {\n private nextId = 1;\n private pending = new Map<number, Pending>();\n private listeners = new Set<(e: HostEvent) => void>();\n private hostOrigin: string | null = null;\n private started = false;\n private reported = new Set<string>();\n\n constructor() {\n if (typeof window === 'undefined' || typeof window.addEventListener !== 'function') return;\n window.addEventListener('error', (event: ErrorEvent) => {\n const err: unknown = event.error;\n if (err instanceof Error) {\n this.report({ kind: 'exception', name: err.name, message: err.message, stack: err.stack });\n } else {\n const where = event.filename\n ? ` at ${event.filename}:${event.lineno}:${event.colno}`\n : '';\n this.report({\n kind: 'exception',\n name: 'Error',\n message: String(event.message || 'Script error.'),\n stack: where,\n });\n }\n });\n window.addEventListener('unhandledrejection', (event: PromiseRejectionEvent) => {\n const reason: unknown = event.reason;\n // The bridge's own rejections are the host's or the server's answers:\n // a failed action is reported where it failed, by its own rules.\n if (reason !== null && typeof reason === 'object' && FROM_BRIDGE in reason) return;\n if (reason instanceof Error) {\n this.report({\n kind: 'rejection',\n name: reason.name,\n message: reason.message,\n stack: reason.stack,\n });\n } else {\n this.report({ kind: 'rejection', name: '', message: describe(reason) });\n }\n });\n }\n\n /** Sends one error report to the host; drops repeats, anything past the\n * page's share, and every failure of the report itself (an older host\n * answers NOT_GRANTED). */\n private report(r: ErrorReport): void {\n // Cut to what the host may send: the server takes at most 16 KiB.\n const params: ErrorReport = {\n ...r,\n name: clip(r.name, 100),\n message: clip(r.message, 500),\n stack: clip(r.stack, 3000),\n };\n const key = reportKey(params);\n if (this.reported.has(key) || this.reported.size >= REPORTS_PER_LOAD) return;\n this.reported.add(key);\n void this.call('report', params).catch(() => {});\n }\n\n private start(): void {\n if (this.started) return;\n this.started = true;\n window.addEventListener('message', (event: MessageEvent) => {\n // Only our embedding host: same source as window.parent, and once\n // the handshake pinned an origin, exactly that origin.\n if (event.source !== window.parent) return;\n if (this.hostOrigin !== null && event.origin !== this.hostOrigin) return;\n const msg = event.data as Record<string, unknown> | null;\n if (!msg || msg.parall !== PROTOCOL) return;\n if (typeof msg.id === 'number') {\n const pending = this.pending.get(msg.id);\n if (!pending) return;\n this.pending.delete(msg.id);\n clearTimeout(pending.timer);\n if (this.hostOrigin === null) this.hostOrigin = event.origin;\n if (msg.error) {\n const err = msg.error as WireError;\n pending.reject(bridgeError(err.code, err.message, err.details));\n } else {\n pending.resolve(msg.result);\n }\n return;\n }\n if (typeof msg.event === 'string') {\n for (const fn of this.listeners) fn(msg as unknown as HostEvent);\n }\n });\n }\n\n private call<T>(method: string, params?: unknown, timeoutMs = HOST_TIMEOUT_MS): Promise<T> {\n this.start();\n const id = this.nextId++;\n return new Promise<T>((resolve, reject) => {\n const timer = setTimeout(() => {\n if (this.pending.delete(id)) {\n reject(bridgeError('HOST_TIMEOUT', `${method} timed out waiting for the host`));\n }\n }, timeoutMs);\n this.pending.set(id, { resolve: resolve as (v: unknown) => void, reject, timer });\n window.parent.postMessage({ parall: PROTOCOL, id, method, params }, '*');\n });\n }\n\n /** Handshake with the host; resolves with the viewer, app and initial route. */\n ready(): Promise<ReadyResult> {\n return this.call<ReadyResult>('ready');\n }\n\n /** Ask the host to grow/shrink the iframe (fire-and-forget semantics). */\n resize(height: number): void {\n void this.call('resize', { height }).catch(() => {});\n }\n\n /**\n * Call one of the app's actions with the viewer's identity and resolve\n * with what the action returned. A failure rejects with a BridgeError\n * whose code is the server's (ACTION_FAILED, ACTION_TIMEOUT,\n * INVALID_ACTION_PARAMS, APP_VERSION_CHANGED…); its message is the\n * action's ActionError message when it threw one. HOST_TIMEOUT and\n * HOST_UNAVAILABLE mean no answer came back: whether the action ran is\n * not known, so read again before retrying a write.\n */\n async action<T = unknown>(name: string, params?: Record<string, unknown>): Promise<T> {\n let answer: { invocation_id: string; result: T };\n try {\n answer = await this.call<{ invocation_id: string; result: T }>(\n 'action',\n { name, params: params ?? {} },\n ACTION_TIMEOUT_MS,\n );\n } catch (err) {\n // The app's authors hear of an action that failed unexpectedly, timed\n // out or ran over its limits — caught by the page or not. An\n // ActionError (error_kind \"action\") is the author's own answer.\n const e = err as BridgeError;\n const unexpected = e.code === 'ACTION_FAILED' && e.details?.error_kind === 'unexpected';\n if (unexpected || REPORTED_ACTION_CODES.has(e.code)) {\n const invocation = e.details?.invocation_id;\n this.report({\n kind: 'action',\n action: name,\n code: e.code,\n invocation_id: typeof invocation === 'string' ? invocation : undefined,\n });\n }\n throw err;\n }\n return answer.result;\n }\n\n /** Subscribe to host events; returns the unsubscribe function. */\n onEvent(fn: (e: HostEvent) => void): () => void {\n this.start();\n this.listeners.add(fn);\n return () => this.listeners.delete(fn);\n }\n\n /**\n * Call fn when a Database the app reads has new writes: once per new\n * (database_id, data_seq) — repeats and older ones are dropped — and\n * always on a catch-up after the host reconnected. Read again in fn.\n */\n onDataChanged(fn: (change: DataChanged) => void): () => void {\n const seen = new Map<string, number>();\n return this.onEvent((e) => {\n if (e.event !== 'data.changed') return;\n const { database_id, data_seq, catch_up } = e.data;\n const last = seen.get(database_id);\n if (!catch_up && last !== undefined && data_seq <= last) return;\n if (last === undefined || data_seq > last) seen.set(database_id, data_seq);\n fn(e.data);\n });\n }\n}\n\nexport const parall = new MiniAppBridge();\n";
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { MiniAppPlacement } from '@parall/sdk';
|
|
2
|
+
import type { SqlDialect } from './apps-template.js';
|
|
3
|
+
/** Where a Database keeps its data decides the SQL it speaks
|
|
4
|
+
* (mini-app-tidb-placement-design.md §5.1, §6.7): `apps` is its
|
|
5
|
+
* organization's PostgreSQL database, `tidb` the TiDB cluster, which speaks
|
|
6
|
+
* MySQL. A server older than placements sends none: that is `apps`. */
|
|
7
|
+
export declare function dialectOf(placement: MiniAppPlacement | undefined): SqlDialect;
|
|
8
|
+
/** The line `app create`, `db create` and `db get` print on stderr next to
|
|
9
|
+
* their JSON: the Database's placement and the SQL it speaks — for a
|
|
10
|
+
* Database on TiDB with how MySQL differs and, when the Database came with
|
|
11
|
+
* an app, how to scaffold for it. */
|
|
12
|
+
export declare function placementHint(databaseId: string, placement: MiniAppPlacement | undefined, appId?: string): string;
|
|
13
|
+
//# sourceMappingURL=apps-placement.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"apps-placement.d.ts","sourceRoot":"","sources":["../../src/commands/apps-placement.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AACpD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAErD;;;uEAGuE;AACvE,wBAAgB,SAAS,CAAC,SAAS,EAAE,gBAAgB,GAAG,SAAS,GAAG,UAAU,CAE7E;AAED;;;qCAGqC;AACrC,wBAAgB,aAAa,CAC3B,UAAU,EAAE,MAAM,EAClB,SAAS,EAAE,gBAAgB,GAAG,SAAS,EACvC,KAAK,CAAC,EAAE,MAAM,GACb,MAAM,CAQR"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/** Where a Database keeps its data decides the SQL it speaks
|
|
2
|
+
* (mini-app-tidb-placement-design.md §5.1, §6.7): `apps` is its
|
|
3
|
+
* organization's PostgreSQL database, `tidb` the TiDB cluster, which speaks
|
|
4
|
+
* MySQL. A server older than placements sends none: that is `apps`. */
|
|
5
|
+
export function dialectOf(placement) {
|
|
6
|
+
return placement === 'tidb' ? 'mysql' : 'postgres';
|
|
7
|
+
}
|
|
8
|
+
/** The line `app create`, `db create` and `db get` print on stderr next to
|
|
9
|
+
* their JSON: the Database's placement and the SQL it speaks — for a
|
|
10
|
+
* Database on TiDB with how MySQL differs and, when the Database came with
|
|
11
|
+
* an app, how to scaffold for it. */
|
|
12
|
+
export function placementHint(databaseId, placement, appId) {
|
|
13
|
+
if (dialectOf(placement) === 'postgres') {
|
|
14
|
+
return `Database ${databaseId}: placement apps — PostgreSQL`;
|
|
15
|
+
}
|
|
16
|
+
const scaffold = appId
|
|
17
|
+
? ` Scaffold for it with parall app init <dir> --actions --app ${appId}.`
|
|
18
|
+
: '';
|
|
19
|
+
return `Database ${databaseId}: placement tidb — TiDB, MySQL: ? parameters (one value each), no RETURNING, one schema change per exec and no dry run for it.${scaffold}`;
|
|
20
|
+
}
|
|
@@ -2,7 +2,13 @@ import type { Command } from 'commander';
|
|
|
2
2
|
/** `parall app init`: the scaffold of design §7.4 — Vite + React + TS +
|
|
3
3
|
* Tailwind + shadcn/ui with the host bridge wired (apps-template.ts);
|
|
4
4
|
* `--actions` adds the server-side actions, the schema and an example list
|
|
5
|
-
* that reads and writes through them.
|
|
5
|
+
* that reads and writes through them. `--app` names the app the project is
|
|
6
|
+
* for: the scaffold's SQL is written in the dialect of that app's Database
|
|
7
|
+
* (MySQL on TiDB, PostgreSQL otherwise; mini-app-tidb-placement-design.md
|
|
8
|
+
* §6.7) and the next steps name the app. Without it the SQL is PostgreSQL,
|
|
9
|
+
* as before. `--template` starts from an app template instead of the
|
|
10
|
+
* example (apps-template-init.ts), listed by `parall app templates`
|
|
11
|
+
* (apps-template-catalog.ts). Blocks go on top with `parall app add`
|
|
6
12
|
* (apps-add.ts). */
|
|
7
13
|
export declare function registerAppScaffoldCommands(app: Command): void;
|
|
8
14
|
//# sourceMappingURL=apps-scaffold.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"apps-scaffold.d.ts","sourceRoot":"","sources":["../../src/commands/apps-scaffold.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;
|
|
1
|
+
{"version":3,"file":"apps-scaffold.d.ts","sourceRoot":"","sources":["../../src/commands/apps-scaffold.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAoBzC;;;;;;;;;;oBAUoB;AACpB,wBAAgB,2BAA2B,CAAC,GAAG,EAAE,OAAO,QA0DvD"}
|
|
@@ -1,59 +1,117 @@
|
|
|
1
1
|
import { promises as fs } from 'node:fs';
|
|
2
2
|
import { join, resolve, sep } from 'node:path';
|
|
3
3
|
import { printError } from '../lib/output.js';
|
|
4
|
+
import { dialectOf } from './apps-placement.js';
|
|
4
5
|
import { scaffoldProject } from './apps-template.js';
|
|
6
|
+
import { cliVersion, findAppTemplate, registerAppTemplatesCommand, unknownTemplateError, } from './apps-template-catalog.js';
|
|
7
|
+
import { resolveInitTarget, templateBlocks, templateNextSteps, templateProject, templateRefusal, writeTemplateProject, } from './apps-template-init.js';
|
|
5
8
|
/** `parall app init`: the scaffold of design §7.4 — Vite + React + TS +
|
|
6
9
|
* Tailwind + shadcn/ui with the host bridge wired (apps-template.ts);
|
|
7
10
|
* `--actions` adds the server-side actions, the schema and an example list
|
|
8
|
-
* that reads and writes through them.
|
|
11
|
+
* that reads and writes through them. `--app` names the app the project is
|
|
12
|
+
* for: the scaffold's SQL is written in the dialect of that app's Database
|
|
13
|
+
* (MySQL on TiDB, PostgreSQL otherwise; mini-app-tidb-placement-design.md
|
|
14
|
+
* §6.7) and the next steps name the app. Without it the SQL is PostgreSQL,
|
|
15
|
+
* as before. `--template` starts from an app template instead of the
|
|
16
|
+
* example (apps-template-init.ts), listed by `parall app templates`
|
|
17
|
+
* (apps-template-catalog.ts). Blocks go on top with `parall app add`
|
|
9
18
|
* (apps-add.ts). */
|
|
10
19
|
export function registerAppScaffoldCommands(app) {
|
|
20
|
+
registerAppTemplatesCommand(app);
|
|
11
21
|
app
|
|
12
22
|
.command('init')
|
|
13
23
|
.description('Scaffold a new Mini App project (Vite + React + TS + Tailwind + shadcn/ui, bridge wired)')
|
|
14
24
|
.argument('<dir>', 'Directory to create (must be empty or absent)')
|
|
15
25
|
.option('--actions', 'Also scaffold server-side actions, the schema and an example list wired to them (actions/ → dist/_actions/index.js)')
|
|
16
|
-
.
|
|
26
|
+
.option('--template <id>', 'Start from an app template (parall app templates) instead of the example: its pages, actions and schema over the --actions scaffold, and its skill as SKILL.md. Needs --app; read the skill first (parall app templates show <id>)')
|
|
27
|
+
.option('--app <appId>', "The app the project is for (app_… or prll://app_…; create it first with parall app create): the SQL is written for its Database — MySQL when the Database's placement is tidb, PostgreSQL otherwise — the next steps name the app, and --template checks its Database")
|
|
28
|
+
.action(async (dir, opts, command) => {
|
|
17
29
|
try {
|
|
18
30
|
const out = resolve(dir);
|
|
19
|
-
await fs.
|
|
20
|
-
|
|
31
|
+
const entries = await fs.readdir(out).catch((err) => {
|
|
32
|
+
if (err.code === 'ENOENT')
|
|
33
|
+
return [];
|
|
34
|
+
throw err;
|
|
35
|
+
});
|
|
36
|
+
if (entries.length > 0)
|
|
21
37
|
throw new Error(`${out} is not empty`);
|
|
22
|
-
}
|
|
23
38
|
const name = out.split(sep).pop() ?? 'mini-app';
|
|
24
|
-
|
|
39
|
+
if (opts.template !== undefined) {
|
|
40
|
+
await initFromTemplate({ dir, out, name, id: opts.template, app: opts.app, command });
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
// Before anything is written: an app that cannot be read leaves no
|
|
44
|
+
// half-made project behind.
|
|
45
|
+
const forApp = opts.app === undefined ? undefined : await resolveInitTarget(opts.app);
|
|
46
|
+
await fs.mkdir(out, { recursive: true });
|
|
47
|
+
const actions = Boolean(opts.actions);
|
|
48
|
+
const files = scaffoldProject({ name, actions, dialect: dialectOf(forApp?.placement) });
|
|
25
49
|
for (const [rel, content] of files) {
|
|
26
50
|
const target = join(out, rel);
|
|
27
51
|
await fs.mkdir(resolve(target, '..'), { recursive: true });
|
|
28
52
|
await fs.writeFile(target, content);
|
|
29
53
|
}
|
|
30
|
-
console.error(
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
' parall app db exec --app <app_…> --file db/schema.sql # create the tables',
|
|
39
|
-
' parall app check dist # manifest ↔ actions/',
|
|
40
|
-
]
|
|
41
|
-
: []),
|
|
42
|
-
` parall app publish dist --app <app_…> --source .`,
|
|
43
|
-
// `app dev` runs until stopped: an agent starts it in the background.
|
|
44
|
-
opts.actions
|
|
45
|
-
? ` parall app dev --dist dist --app <app_…> > dev.log 2>&1 & # runs until stopped; actions run on this machine`
|
|
46
|
-
: ` parall app dev --dist dist > dev.log 2>&1 & # runs until stopped; look at it locally first`,
|
|
47
|
-
...(opts.actions
|
|
48
|
-
? [` parall app action run <app_…> <name> --local # one action, then returns`]
|
|
49
|
-
: []),
|
|
50
|
-
...(opts.actions
|
|
51
|
-
? ['', 'Ready-made pages (calendar, kanban, …): parall app add --list']
|
|
52
|
-
: []),
|
|
53
|
-
].join('\n'));
|
|
54
|
+
console.error(nextSteps({
|
|
55
|
+
name,
|
|
56
|
+
dir,
|
|
57
|
+
out,
|
|
58
|
+
actions,
|
|
59
|
+
target: forApp,
|
|
60
|
+
schemaFiles: files.map(([rel]) => rel).filter((rel) => rel.startsWith('db/')),
|
|
61
|
+
}));
|
|
54
62
|
}
|
|
55
63
|
catch (err) {
|
|
56
64
|
printError(err);
|
|
57
65
|
}
|
|
58
66
|
});
|
|
59
67
|
}
|
|
68
|
+
/** init --template: refused before anything is written when the id is
|
|
69
|
+
* unknown, --app is missing or the app's Database cannot take the template. */
|
|
70
|
+
async function initFromTemplate(p) {
|
|
71
|
+
const template = findAppTemplate(p.id);
|
|
72
|
+
if (!template)
|
|
73
|
+
throw unknownTemplateError(p.id, cliVersion(p.command));
|
|
74
|
+
if (p.app === undefined) {
|
|
75
|
+
throw new Error(`--template needs --app: create the app first (parall app create --name "<name>"), then parall app init ${p.dir} --template ${template.id} --app <app_…>`);
|
|
76
|
+
}
|
|
77
|
+
const target = await resolveInitTarget(p.app);
|
|
78
|
+
const refusal = templateRefusal(template, target);
|
|
79
|
+
if (refusal)
|
|
80
|
+
throw new Error(refusal);
|
|
81
|
+
await writeTemplateProject(p.out, templateProject(p.name, template), templateBlocks(template));
|
|
82
|
+
console.error(templateNextSteps({ ...p, template, target }));
|
|
83
|
+
}
|
|
84
|
+
function nextSteps(p) {
|
|
85
|
+
const app = p.target?.appId ?? '<app_…>';
|
|
86
|
+
const mysql = dialectOf(p.target?.placement) === 'mysql';
|
|
87
|
+
const header = p.target
|
|
88
|
+
? `Scaffolded ${p.name} in ${p.out} for ${p.target.appId}: its Database ${p.target.databaseId} has placement ${p.target.placement}, so the SQL here is ${mysql ? 'MySQL (TiDB)' : 'PostgreSQL'}`
|
|
89
|
+
: `Scaffolded ${p.name} in ${p.out}`;
|
|
90
|
+
const tables = !p.actions
|
|
91
|
+
? []
|
|
92
|
+
: mysql
|
|
93
|
+
? p.schemaFiles.map((file, i) => ` parall app db exec --app ${app} --file ${file}${i === 0 ? ' # create the tables: one schema change per exec on TiDB, in order' : ''}`)
|
|
94
|
+
: [` parall app db exec --app ${app} --file db/schema.sql # create the tables`];
|
|
95
|
+
return [
|
|
96
|
+
header,
|
|
97
|
+
'',
|
|
98
|
+
'Next steps:',
|
|
99
|
+
` cd ${p.dir} && pnpm install && pnpm build`,
|
|
100
|
+
...(p.target ? [] : [` parall app create --name "${p.name}"`]),
|
|
101
|
+
...tables,
|
|
102
|
+
...(p.actions ? [' parall app check dist # manifest ↔ actions/'] : []),
|
|
103
|
+
` parall app publish dist --app ${app} --source .`,
|
|
104
|
+
// `app dev` runs until stopped: an agent starts it in the background.
|
|
105
|
+
p.actions
|
|
106
|
+
? ` parall app dev --dist dist --app ${app} > dev.log 2>&1 & # runs until stopped; actions run on this machine`
|
|
107
|
+
: ` parall app dev --dist dist > dev.log 2>&1 & # runs until stopped; look at it locally first`,
|
|
108
|
+
...(p.actions
|
|
109
|
+
? [` parall app action run ${app} <name> --local # one action, then returns`]
|
|
110
|
+
: []),
|
|
111
|
+
// The blocks are written for PostgreSQL (apps-add.ts refuses a MySQL
|
|
112
|
+
// project).
|
|
113
|
+
...(p.actions && !mysql
|
|
114
|
+
? ['', 'Ready-made pages (calendar, kanban, …): parall app add --list']
|
|
115
|
+
: []),
|
|
116
|
+
].join('\n');
|
|
117
|
+
}
|