pi-pocket 0.25.0 → 0.26.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/AGENTS.md +2 -0
- package/README.md +5 -3
- package/docs/architecture.md +21 -0
- package/docs/design/design-mode.md +108 -0
- package/docs/design/notes-a.md +106 -0
- package/docs/design/notes-b.md +123 -0
- package/docs/design/notes-c.md +92 -0
- package/docs/design/notes-d.md +78 -0
- package/docs/design/release-notes-design.md +46 -0
- package/docs/extensions/browser-modules.md +2 -0
- package/docs/extensions/policies/api-stability.md +2 -0
- package/docs/extensions/reference/api-versions.md +1 -0
- package/docs/extensions/reference/host.md +1 -1
- package/docs/extensions/reference/limits.md +4 -0
- package/docs/extensions/reference/names.md +2 -2
- package/docs/extensions/reference/pocket.md +38 -0
- package/docs/features.md +19 -5
- package/docs/map.md +75 -54
- package/docs/release-notes.md +1 -1
- package/docs/self-editing.md +1 -1
- package/docs/systemd.md +1 -1
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/src/launcher/main.ts +20 -9
- package/src/server/app.ts +113 -4
- package/src/server/background.ts +3 -3
- package/src/server/cache-keeper.ts +605 -0
- package/src/server/compaction.ts +68 -15
- package/src/server/design/bundle.ts +65 -0
- package/src/server/design/export.ts +118 -0
- package/src/server/design/files.ts +49 -0
- package/src/server/design/guide.ts +56 -0
- package/src/server/design/index.ts +232 -0
- package/src/server/design/pptx.ts +304 -0
- package/src/server/design/render.ts +593 -0
- package/src/server/design/system.ts +248 -0
- package/src/server/docs.ts +55 -0
- package/src/server/extensions/artifacts.ts +202 -18
- package/src/server/extensions/design/canvas.js +304 -0
- package/src/server/extensions/design/comments.js +15 -0
- package/src/server/extensions/design/data.js +263 -0
- package/src/server/extensions/design/devices.js +70 -0
- package/src/server/extensions/design/docks.js +647 -0
- package/src/server/extensions/design/edits.js +37 -0
- package/src/server/extensions/design/index.js +326 -0
- package/src/server/extensions/design/messages.js +92 -0
- package/src/server/extensions/design/parts.js +160 -0
- package/src/server/extensions/design/state.js +146 -0
- package/src/server/extensions/design/style.css +1332 -0
- package/src/server/extensions/design/tweaks.js +161 -0
- package/src/server/extensions/design/views.js +375 -0
- package/src/server/extensions/design/workspace.js +723 -0
- package/src/server/extensions/design.ts +620 -0
- package/src/server/extensions/plan.ts +11 -9
- package/src/server/extensions/prompt.ts +11 -3
- package/src/server/extensions/subagents.ts +7 -1
- package/src/server/extensions/updates/index.js +16 -6
- package/src/server/extensions/updates.ts +2 -2
- package/src/server/http/artifact-assets.ts +216 -0
- package/src/server/http/artifact-inspect.ts +1281 -0
- package/src/server/http/artifacts.ts +89 -14
- package/src/server/http/conversation-routes.ts +46 -1
- package/src/server/http.ts +12 -4
- package/src/server/main.ts +4 -0
- package/src/server/npm-install.ts +82 -0
- package/src/server/npm-update.ts +100 -0
- package/src/server/reload.ts +5 -0
- package/src/server/room.ts +2 -0
- package/src/server/spend.ts +73 -9
- package/src/server/update-state.ts +257 -8
- package/src/server/updates.ts +268 -33
- package/src/server/zip.ts +163 -0
- package/types/pocket.d.ts +32 -0
- package/web/activity-fold.js +28 -0
- package/web/artifact-bridge.js +506 -82
- package/web/extension-ui.js +21 -1
- package/web/pip.js +46 -9
- package/web/sessions.js +1 -1
- package/web/sheets/appearance.js +10 -0
- package/web/sheets/viewers.js +26 -1
- package/web/style.css +11 -0
- package/web/taps.js +26 -0
- package/web/theme.js +6 -0
- package/web/transcript.js +19 -10
- package/src/server/http/public.ts +0 -30
|
@@ -0,0 +1,593 @@
|
|
|
1
|
+
/** Private, short-lived Chromium renders. No shared page, profile, or sign-in cookie reaches a design. */
|
|
2
|
+
import { randomBytes } from "node:crypto";
|
|
3
|
+
import { mkdtemp, rm } from "node:fs/promises";
|
|
4
|
+
import { createServer } from "node:http";
|
|
5
|
+
import { tmpdir } from "node:os";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
import { Chromium, type Json } from "../browser/cdp.ts";
|
|
8
|
+
import { findBrowser, profileFolder } from "../browser/discovery.ts";
|
|
9
|
+
import type { PocketHost } from "../host.ts";
|
|
10
|
+
import type { DesignBundle } from "./bundle.ts";
|
|
11
|
+
|
|
12
|
+
export const VIEWPORTS = {
|
|
13
|
+
mobile: { width: 390, height: 844 },
|
|
14
|
+
tablet: { width: 820, height: 1180 },
|
|
15
|
+
desktop: { width: 1280, height: 800 },
|
|
16
|
+
} as const;
|
|
17
|
+
|
|
18
|
+
export type ViewportName = keyof typeof VIEWPORTS;
|
|
19
|
+
export type DesignViewport = { width: number; height: number };
|
|
20
|
+
const LIMIT_MS = 90_000;
|
|
21
|
+
// Keep the /a/ page policy and add a separate, stricter render-only policy. CSP policies intersect.
|
|
22
|
+
const ARTIFACT_CSP =
|
|
23
|
+
"sandbox allow-scripts allow-forms allow-modals allow-popups allow-popups-to-escape-sandbox allow-pointer-lock allow-downloads; frame-ancestors 'self'";
|
|
24
|
+
const RENDER_CSP =
|
|
25
|
+
"sandbox allow-scripts allow-modals; frame-src 'none'; worker-src 'none'; object-src 'none'; connect-src http: https:;";
|
|
26
|
+
let active = 0;
|
|
27
|
+
|
|
28
|
+
/** The default slide size of a deck, as the canvas lays slides out. */
|
|
29
|
+
export const SLIDE_SIZE: DesignViewport = { width: 1920, height: 1080 };
|
|
30
|
+
|
|
31
|
+
/** A `pocket-slide-size` value (`WxH`, each 320 to 3840), or the default for anything else. */
|
|
32
|
+
export function parseSlideSize(value: string): DesignViewport {
|
|
33
|
+
const match = /^\s*(\d{3,4})\s*[x×]\s*(\d{3,4})\s*$/i.exec(value);
|
|
34
|
+
|
|
35
|
+
if (match === null) {
|
|
36
|
+
return SLIDE_SIZE;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const width = Number(match[1]);
|
|
40
|
+
const height = Number(match[2]);
|
|
41
|
+
|
|
42
|
+
if (width < 320 || height < 320 || width > 3840 || height > 3840) {
|
|
43
|
+
return SLIDE_SIZE;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
return { width, height };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function viewportOf(value: string | DesignViewport = "desktop"): DesignViewport {
|
|
50
|
+
if (typeof value === "string") {
|
|
51
|
+
if (Object.hasOwn(VIEWPORTS, value)) {
|
|
52
|
+
return VIEWPORTS[value as ViewportName];
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const match = /^(\d{3,4})x(\d{3,4})$/.exec(value);
|
|
56
|
+
|
|
57
|
+
if (match === null) {
|
|
58
|
+
throw new Error("Viewport must be mobile, tablet, desktop, or WIDTHxHEIGHT.");
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
value = { width: Number(match[1]), height: Number(match[2]) };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
if (
|
|
65
|
+
!Number.isInteger(value.width) ||
|
|
66
|
+
!Number.isInteger(value.height) ||
|
|
67
|
+
value.width < 320 ||
|
|
68
|
+
value.width > 2560 ||
|
|
69
|
+
value.height < 240 ||
|
|
70
|
+
value.height > 2560
|
|
71
|
+
) {
|
|
72
|
+
throw new Error("Viewport must be 320–2560 pixels wide and 240–2560 pixels tall.");
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
return { ...value };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Only this bundle is available. A random bearer path expires when the render ends. */
|
|
79
|
+
export async function serveBundle(bundle: DesignBundle) {
|
|
80
|
+
const token = randomBytes(32).toString("hex");
|
|
81
|
+
const prefix = `/${token}/a/`;
|
|
82
|
+
const assets = new Map(bundle.assets.map((asset) => [asset.name, asset]));
|
|
83
|
+
const server = createServer((request, response) => {
|
|
84
|
+
let url: URL;
|
|
85
|
+
let name: string;
|
|
86
|
+
|
|
87
|
+
try {
|
|
88
|
+
url = new URL(request.url ?? "/", "http://127.0.0.1");
|
|
89
|
+
name = decodeURIComponent(url.pathname.slice(prefix.length));
|
|
90
|
+
} catch {
|
|
91
|
+
response.writeHead(400).end();
|
|
92
|
+
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
if (
|
|
97
|
+
!url.pathname.startsWith(prefix) ||
|
|
98
|
+
(request.method !== "GET" && request.method !== "HEAD")
|
|
99
|
+
) {
|
|
100
|
+
response.writeHead(404).end();
|
|
101
|
+
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const asset = assets.get(name);
|
|
106
|
+
|
|
107
|
+
if (name !== "" && asset === undefined) {
|
|
108
|
+
response.writeHead(404).end();
|
|
109
|
+
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
response.writeHead(200, {
|
|
114
|
+
"content-type": asset?.type ?? "text/html; charset=utf-8",
|
|
115
|
+
"cache-control": "no-store",
|
|
116
|
+
"referrer-policy": "no-referrer",
|
|
117
|
+
"access-control-allow-origin": "*",
|
|
118
|
+
"x-content-type-options": "nosniff",
|
|
119
|
+
// No popups, workers, frames, or sockets can bypass the page's request interception.
|
|
120
|
+
"content-security-policy": `${ARTIFACT_CSP}, ${RENDER_CSP}`,
|
|
121
|
+
});
|
|
122
|
+
response.end(request.method === "HEAD" ? undefined : (asset?.bytes ?? bundle.content));
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
await new Promise<void>((resolve, reject) => {
|
|
126
|
+
server.once("error", reject);
|
|
127
|
+
server.listen(0, "127.0.0.1", resolve);
|
|
128
|
+
});
|
|
129
|
+
const address = server.address();
|
|
130
|
+
|
|
131
|
+
if (address === null || typeof address === "string") {
|
|
132
|
+
server.close();
|
|
133
|
+
|
|
134
|
+
throw new Error("The private render server did not start.");
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
return {
|
|
138
|
+
url: `http://127.0.0.1:${address.port}${prefix}`,
|
|
139
|
+
close: async () => {
|
|
140
|
+
server.closeAllConnections();
|
|
141
|
+
await new Promise<void>((resolve) => server.close(() => resolve()));
|
|
142
|
+
},
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export class DesignPage {
|
|
147
|
+
readonly errors: string[] = [];
|
|
148
|
+
readonly failedRequests: string[] = [];
|
|
149
|
+
readonly #browser: Chromium;
|
|
150
|
+
readonly #session: string;
|
|
151
|
+
readonly #url: string;
|
|
152
|
+
readonly #host: PocketHost;
|
|
153
|
+
readonly #signal: AbortSignal;
|
|
154
|
+
#requests = 0;
|
|
155
|
+
#pending = 0;
|
|
156
|
+
#networkBytes = 0;
|
|
157
|
+
#slideDisplays: string[] | undefined;
|
|
158
|
+
|
|
159
|
+
constructor(
|
|
160
|
+
browser: Chromium,
|
|
161
|
+
session: string,
|
|
162
|
+
url: string,
|
|
163
|
+
host: PocketHost,
|
|
164
|
+
signal: AbortSignal,
|
|
165
|
+
) {
|
|
166
|
+
this.#browser = browser;
|
|
167
|
+
this.#session = session;
|
|
168
|
+
this.#url = url;
|
|
169
|
+
this.#host = host;
|
|
170
|
+
this.#signal = signal;
|
|
171
|
+
browser.connection.listen(session, (method, params) => this.#event(method, params));
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
#record(list: string[], text: string): void {
|
|
175
|
+
if (list.length < 100) {
|
|
176
|
+
list.push(text.slice(0, 2000));
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
#event(method: string, params: Json): void {
|
|
181
|
+
if (method === "Fetch.requestPaused") {
|
|
182
|
+
void this.#request(params).catch(() => {});
|
|
183
|
+
} else if (method === "Runtime.exceptionThrown") {
|
|
184
|
+
const error = params.exceptionDetails;
|
|
185
|
+
|
|
186
|
+
this.#record(this.errors, String(error?.exception?.description ?? error?.text));
|
|
187
|
+
} else if (method === "Runtime.consoleAPICalled" && params.type === "error") {
|
|
188
|
+
this.#record(
|
|
189
|
+
this.errors,
|
|
190
|
+
(params.args ?? [])
|
|
191
|
+
.map((arg: Json) => String(arg.value ?? arg.description ?? arg.type))
|
|
192
|
+
.join(" "),
|
|
193
|
+
);
|
|
194
|
+
} else if (method === "Network.loadingFailed") {
|
|
195
|
+
this.#record(this.failedRequests, String(params.errorText));
|
|
196
|
+
} else if (method === "Network.responseReceived" && params.response?.status >= 400) {
|
|
197
|
+
this.#record(this.failedRequests, `${params.response.status} ${params.response.url}`);
|
|
198
|
+
} else if (method === "Page.javascriptDialogOpening") {
|
|
199
|
+
void this.send("Page.handleJavaScriptDialog", { accept: false }).catch(() => {});
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
async #request(params: Json): Promise<void> {
|
|
204
|
+
const url = String(params.request.url);
|
|
205
|
+
const id = params.requestId;
|
|
206
|
+
let external = false;
|
|
207
|
+
|
|
208
|
+
try {
|
|
209
|
+
if (++this.#requests > 400) {
|
|
210
|
+
throw new Error("The design exceeded 400 requests.");
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
if (url === new URL("/favicon.ico", this.#url).href) {
|
|
214
|
+
await this.send("Fetch.fulfillRequest", { requestId: id, responseCode: 204 });
|
|
215
|
+
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// Only the token-scoped bundle bypasses the public-network guard. Redirects go through Fetch again.
|
|
220
|
+
if (url.startsWith(this.#url) && /^(GET|HEAD)$/.test(params.request.method)) {
|
|
221
|
+
await this.send("Fetch.continueRequest", { requestId: id });
|
|
222
|
+
|
|
223
|
+
return;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
if (params.resourceType === "Document") {
|
|
227
|
+
throw new Error(
|
|
228
|
+
"External document navigation is disabled during design rendering.",
|
|
229
|
+
);
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
if (new URL(url).protocol !== "https:") {
|
|
233
|
+
throw new Error("External design resources must use public HTTPS addresses.");
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
if (!/^(GET|HEAD)$/.test(params.request.method)) {
|
|
237
|
+
throw new Error("Preview requests must use GET or HEAD.");
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
if (this.#pending >= 20 || this.#networkBytes >= 50_000_000) {
|
|
241
|
+
throw new Error("The design exceeded its external request budget.");
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
this.#pending++;
|
|
245
|
+
external = true;
|
|
246
|
+
// Fetch on the server pins DNS and rejects private addresses at every connection and redirect.
|
|
247
|
+
// No browser cookies, credentials, or authorization headers are forwarded.
|
|
248
|
+
const response = await this.#host.fetchPublic(url, {
|
|
249
|
+
method: params.request.method,
|
|
250
|
+
signal: this.#signal,
|
|
251
|
+
redirect: "manual",
|
|
252
|
+
maxBytes: 5_000_000,
|
|
253
|
+
timeoutMs: 10_000,
|
|
254
|
+
});
|
|
255
|
+
const bytes = Buffer.from(await response.arrayBuffer());
|
|
256
|
+
|
|
257
|
+
this.#networkBytes += bytes.length;
|
|
258
|
+
|
|
259
|
+
if (this.#networkBytes > 50_000_000) {
|
|
260
|
+
throw new Error("The design exceeded 50 MB of external resources.");
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
const headers = [...response.headers]
|
|
264
|
+
.filter(
|
|
265
|
+
([name]) =>
|
|
266
|
+
!["set-cookie", "content-encoding", "content-length"].includes(name),
|
|
267
|
+
)
|
|
268
|
+
.map(([name, value]) => ({ name, value }));
|
|
269
|
+
|
|
270
|
+
await this.send("Fetch.fulfillRequest", {
|
|
271
|
+
requestId: id,
|
|
272
|
+
responseCode: response.status,
|
|
273
|
+
responseHeaders: headers,
|
|
274
|
+
body: bytes.toString("base64"),
|
|
275
|
+
});
|
|
276
|
+
} catch (error) {
|
|
277
|
+
this.#record(this.failedRequests, `${url}: ${String(error)}`);
|
|
278
|
+
await this.send("Fetch.failRequest", { requestId: id, errorReason: "BlockedByClient" });
|
|
279
|
+
} finally {
|
|
280
|
+
if (external) {
|
|
281
|
+
this.#pending--;
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
send(method: string, params: Record<string, unknown> = {}): Promise<Json> {
|
|
287
|
+
this.#signal.throwIfAborted();
|
|
288
|
+
|
|
289
|
+
return this.#browser.connection.send(method, params, this.#session, 15_000);
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
async evaluate(expression: string): Promise<Json> {
|
|
293
|
+
const result = await this.send("Runtime.evaluate", {
|
|
294
|
+
expression,
|
|
295
|
+
returnByValue: true,
|
|
296
|
+
awaitPromise: true,
|
|
297
|
+
timeout: 10_000,
|
|
298
|
+
});
|
|
299
|
+
|
|
300
|
+
if (result.exceptionDetails !== undefined) {
|
|
301
|
+
throw new Error(
|
|
302
|
+
String(result.exceptionDetails.exception?.description ?? "Render script failed."),
|
|
303
|
+
);
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
return result.result?.value;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
async load(viewport: DesignViewport): Promise<void> {
|
|
310
|
+
this.#slideDisplays = undefined;
|
|
311
|
+
await this.send("Emulation.setDeviceMetricsOverride", {
|
|
312
|
+
...viewport,
|
|
313
|
+
deviceScaleFactor: 1,
|
|
314
|
+
mobile: viewport.width < 500,
|
|
315
|
+
});
|
|
316
|
+
const result = await this.send("Page.navigate", { url: this.#url });
|
|
317
|
+
|
|
318
|
+
if (result.errorText) {
|
|
319
|
+
throw new Error(String(result.errorText));
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
// Readiness is bounded even when an image, font, or page request never finishes.
|
|
323
|
+
for (let attempt = 0; attempt < 50; attempt++) {
|
|
324
|
+
if ((await this.evaluate("document.readyState")) === "complete") {
|
|
325
|
+
break;
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
await this.evaluate(`Promise.race([
|
|
332
|
+
Promise.all([document.fonts.ready, ...Array.from(document.images, image => image.decode().catch(() => {}))]),
|
|
333
|
+
new Promise(resolve => setTimeout(resolve, 3000))
|
|
334
|
+
]).then(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))))`);
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
async init(): Promise<void> {
|
|
338
|
+
// Network APIs outside Fetch interception must be unavailable before any untrusted script runs.
|
|
339
|
+
await this.send("Page.addScriptToEvaluateOnNewDocument", {
|
|
340
|
+
source: `(() => {
|
|
341
|
+
for (const name of Object.getOwnPropertyNames(globalThis)) {
|
|
342
|
+
if (/^(RTC|webkitRTC)/.test(name) || name === 'WebTransport') {
|
|
343
|
+
Object.defineProperty(globalThis, name, { value: undefined, writable: false, configurable: false });
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
})();`,
|
|
347
|
+
});
|
|
348
|
+
await this.send("DOM.enable");
|
|
349
|
+
await this.send("CSS.enable");
|
|
350
|
+
await Promise.all([
|
|
351
|
+
this.send("Page.enable"),
|
|
352
|
+
this.send("Runtime.enable"),
|
|
353
|
+
this.send("Network.enable"),
|
|
354
|
+
this.send("Fetch.enable", { patterns: [{ urlPattern: "*" }] }),
|
|
355
|
+
this.send("Browser.setDownloadBehavior", { behavior: "deny" }),
|
|
356
|
+
]);
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
async screenshot(viewport: DesignViewport, fullPage = false, preview = false): Promise<string> {
|
|
360
|
+
const metrics = fullPage ? await this.send("Page.getLayoutMetrics") : undefined;
|
|
361
|
+
const content = metrics?.cssContentSize;
|
|
362
|
+
// A full page is cut at a bound; a viewport (a slide up to 3840 a side) is taken whole.
|
|
363
|
+
const width =
|
|
364
|
+
content === undefined ? viewport.width : Math.min(2560, Math.ceil(content.width));
|
|
365
|
+
const height =
|
|
366
|
+
content === undefined ? viewport.height : Math.min(16000, Math.ceil(content.height));
|
|
367
|
+
const scale = preview ? Math.min(1, 2000 / Math.max(width, height)) : 1;
|
|
368
|
+
const result = await this.send("Page.captureScreenshot", {
|
|
369
|
+
format: "png",
|
|
370
|
+
captureBeyondViewport: true,
|
|
371
|
+
clip: { x: 0, y: 0, width, height, scale },
|
|
372
|
+
});
|
|
373
|
+
|
|
374
|
+
return String(result.data);
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
async isDeck(): Promise<boolean> {
|
|
378
|
+
return (
|
|
379
|
+
(await this.evaluate(
|
|
380
|
+
`document.querySelector('meta[name="pocket-kind"]')?.content === 'deck'`,
|
|
381
|
+
)) === true
|
|
382
|
+
);
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
/**
|
|
386
|
+
* The size a deck's slides are written at, as the canvas lays them out (`artifact-inspect.ts`): 1920×1080, or the
|
|
387
|
+
* page's `<meta name="pocket-slide-size" content="WxH">`.
|
|
388
|
+
*/
|
|
389
|
+
async slideSize(): Promise<DesignViewport> {
|
|
390
|
+
const value = await this.evaluate(
|
|
391
|
+
`document.querySelector('meta[name="pocket-slide-size"]')?.content ?? ''`,
|
|
392
|
+
);
|
|
393
|
+
|
|
394
|
+
return parseSlideSize(typeof value === "string" ? value : "");
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
async pdf(): Promise<string> {
|
|
398
|
+
if (await this.isDeck()) {
|
|
399
|
+
await this.slides();
|
|
400
|
+
const displays = await this.#displays();
|
|
401
|
+
const { width, height } = await this.slideSize();
|
|
402
|
+
|
|
403
|
+
await this.evaluate(`(() => {
|
|
404
|
+
document.getElementById('pocket-render-slide')?.remove();
|
|
405
|
+
const slides = Array.from(document.querySelectorAll('section.slide'));
|
|
406
|
+
const displays = ${JSON.stringify(displays)};
|
|
407
|
+
document.body.replaceChildren(...slides);
|
|
408
|
+
slides.forEach((slide, index) => {
|
|
409
|
+
slide.hidden = false;
|
|
410
|
+
slide.style.setProperty('display', displays[index] === 'none' ? 'block' : displays[index], 'important');
|
|
411
|
+
});
|
|
412
|
+
const style = document.createElement('style');
|
|
413
|
+
style.textContent = '@page{size:${width}px ${height}px;margin:0}html,body{margin:0!important;padding:0!important;width:${width}px!important;height:auto!important;overflow:visible!important}section.slide{position:relative!important;inset:auto!important;width:${width}px!important;height:${height}px!important;min-width:0!important;max-width:none!important;min-height:0!important;max-height:none!important;margin:0!important;overflow:hidden!important;box-sizing:border-box!important;transform:none!important;scale:1!important;break-after:page!important;break-inside:avoid!important}section.slide:last-child{break-after:auto!important}';
|
|
414
|
+
document.head.append(style);
|
|
415
|
+
})()`);
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
const result = await this.send("Page.printToPDF", {
|
|
419
|
+
printBackground: true,
|
|
420
|
+
preferCSSPageSize: true,
|
|
421
|
+
transferMode: "ReturnAsBase64",
|
|
422
|
+
});
|
|
423
|
+
|
|
424
|
+
return String(result.data);
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
async slides(): Promise<string[]> {
|
|
428
|
+
const result = await this.evaluate(`(() => {
|
|
429
|
+
if (document.querySelector('meta[name="pocket-kind"]')?.content !== 'deck') return null;
|
|
430
|
+
return Array.from(document.querySelectorAll('section.slide'), slide => (slide.textContent ?? '').slice(0, 20000));
|
|
431
|
+
})()`);
|
|
432
|
+
|
|
433
|
+
if (!Array.isArray(result) || result.length === 0 || result.length > 100) {
|
|
434
|
+
throw new Error("A deck needs pocket-kind=deck and 1–100 section.slide elements.");
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
return result.map(String);
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
/** DevTools exposes matched rules even for cross-origin stylesheets and inactive slides. */
|
|
441
|
+
async #displays(): Promise<string[]> {
|
|
442
|
+
if (this.#slideDisplays !== undefined) {
|
|
443
|
+
return this.#slideDisplays;
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
const computed = await this.evaluate(
|
|
447
|
+
`Array.from(document.querySelectorAll('section.slide'), slide => getComputedStyle(slide).display)`,
|
|
448
|
+
);
|
|
449
|
+
const document = await this.send("DOM.getDocument");
|
|
450
|
+
const nodes = await this.send("DOM.querySelectorAll", {
|
|
451
|
+
nodeId: document.root.nodeId,
|
|
452
|
+
selector: "section.slide",
|
|
453
|
+
});
|
|
454
|
+
const displays: string[] = [];
|
|
455
|
+
|
|
456
|
+
for (const [index, nodeId] of nodes.nodeIds.entries()) {
|
|
457
|
+
if (computed[index] !== "none") {
|
|
458
|
+
displays.push(String(computed[index]));
|
|
459
|
+
continue;
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
const matched = await this.send("CSS.getMatchedStylesForNode", { nodeId });
|
|
463
|
+
const declarations = [
|
|
464
|
+
...matched.matchedCSSRules.flatMap((match: Json) => match.rule.style.cssProperties),
|
|
465
|
+
...(matched.inlineStyle?.cssProperties ?? []),
|
|
466
|
+
].filter(
|
|
467
|
+
(property: Json) =>
|
|
468
|
+
property.name === "display" &&
|
|
469
|
+
property.value !== "none" &&
|
|
470
|
+
property.disabled !== true &&
|
|
471
|
+
property.parsedOk !== false,
|
|
472
|
+
);
|
|
473
|
+
const chosen =
|
|
474
|
+
declarations.filter((property: Json) => property.important).at(-1) ??
|
|
475
|
+
declarations.at(-1);
|
|
476
|
+
|
|
477
|
+
displays.push(String(chosen?.value ?? "block"));
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
this.#slideDisplays = displays;
|
|
481
|
+
|
|
482
|
+
return displays;
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
/** Show one slide (from 1), laid out at the deck's slide size and scaled to fit `viewport` (default: that size). */
|
|
486
|
+
async showSlide(slide: number, viewport?: DesignViewport): Promise<void> {
|
|
487
|
+
const slides = await this.slides();
|
|
488
|
+
const size = await this.slideSize();
|
|
489
|
+
|
|
490
|
+
viewport ??= size;
|
|
491
|
+
|
|
492
|
+
if (!Number.isInteger(slide) || slide < 1 || slide > slides.length) {
|
|
493
|
+
throw new Error(`Slide must be between 1 and ${slides.length}.`);
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
const displays = await this.#displays();
|
|
497
|
+
const scale = Math.min(viewport.width / size.width, viewport.height / size.height);
|
|
498
|
+
const left = (viewport.width - size.width * scale) / 2;
|
|
499
|
+
const top = (viewport.height - size.height * scale) / 2;
|
|
500
|
+
|
|
501
|
+
await this.evaluate(`(() => {
|
|
502
|
+
document.getElementById('pocket-render-slide')?.remove();
|
|
503
|
+
const visibleDisplay = ${JSON.stringify(displays[slide - 1])};
|
|
504
|
+
const style = document.createElement('style');
|
|
505
|
+
style.id = 'pocket-render-slide';
|
|
506
|
+
style.textContent = 'html,body{margin:0!important;padding:0!important;width:${viewport.width}px!important;height:${viewport.height}px!important;overflow:hidden!important}section.slide{display:none!important}section.slide[data-pocket-export]{display:' + visibleDisplay + '!important;position:fixed!important;inset:auto!important;left:${left}px!important;top:${top}px!important;width:${size.width}px!important;height:${size.height}px!important;min-width:0!important;max-width:none!important;min-height:0!important;max-height:none!important;margin:0!important;overflow:hidden!important;box-sizing:border-box!important;transform:scale(${scale})!important;transform-origin:top left!important;scale:1!important}';
|
|
507
|
+
document.head.append(style);
|
|
508
|
+
const slides = Array.from(document.querySelectorAll('section.slide'));
|
|
509
|
+
slides.forEach((item, index) => item.toggleAttribute('data-pocket-export', index === ${slide - 1}));
|
|
510
|
+
})()`);
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
export async function withRender<T>(
|
|
515
|
+
bundle: DesignBundle,
|
|
516
|
+
host: PocketHost,
|
|
517
|
+
signal: AbortSignal | undefined,
|
|
518
|
+
run: (page: DesignPage) => Promise<T>,
|
|
519
|
+
): Promise<T> {
|
|
520
|
+
if (active >= 2) {
|
|
521
|
+
throw new Error("2 design renders are already running. Try again when one finishes.");
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
const executable = findBrowser();
|
|
525
|
+
|
|
526
|
+
if (executable === undefined) {
|
|
527
|
+
throw new Error("Install Chromium or set PI_POCKET_BROWSER to render designs.");
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
active++;
|
|
531
|
+
const controller = new AbortController();
|
|
532
|
+
const abort = () => controller.abort(new Error("The design render stopped."));
|
|
533
|
+
const timer = setTimeout(abort, LIMIT_MS);
|
|
534
|
+
let browser: Chromium | undefined;
|
|
535
|
+
let profile: string | undefined;
|
|
536
|
+
let folder: string | undefined;
|
|
537
|
+
let server: Awaited<ReturnType<typeof serveBundle>> | undefined;
|
|
538
|
+
|
|
539
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
540
|
+
controller.signal.addEventListener("abort", () => browser?.kill(), { once: true });
|
|
541
|
+
|
|
542
|
+
try {
|
|
543
|
+
signal?.throwIfAborted();
|
|
544
|
+
folder = await mkdtemp(join(tmpdir(), "pocket-design-"));
|
|
545
|
+
|
|
546
|
+
profile = profileFolder(executable, folder);
|
|
547
|
+
server = await serveBundle(bundle);
|
|
548
|
+
browser = await Chromium.launch(executable, profile, [
|
|
549
|
+
"--force-webrtc-ip-handling-policy=disable_non_proxied_udp",
|
|
550
|
+
]);
|
|
551
|
+
controller.signal.throwIfAborted();
|
|
552
|
+
const context = await browser.connection.send("Target.createBrowserContext");
|
|
553
|
+
const target = await browser.connection.send("Target.createTarget", {
|
|
554
|
+
url: "about:blank",
|
|
555
|
+
browserContextId: context.browserContextId,
|
|
556
|
+
});
|
|
557
|
+
const attached = await browser.connection.send("Target.attachToTarget", {
|
|
558
|
+
targetId: target.targetId,
|
|
559
|
+
flatten: true,
|
|
560
|
+
});
|
|
561
|
+
const page = new DesignPage(
|
|
562
|
+
browser,
|
|
563
|
+
attached.sessionId,
|
|
564
|
+
server.url,
|
|
565
|
+
host,
|
|
566
|
+
controller.signal,
|
|
567
|
+
);
|
|
568
|
+
|
|
569
|
+
await page.init();
|
|
570
|
+
|
|
571
|
+
return await run(page);
|
|
572
|
+
} finally {
|
|
573
|
+
clearTimeout(timer);
|
|
574
|
+
signal?.removeEventListener("abort", abort);
|
|
575
|
+
controller.abort();
|
|
576
|
+
|
|
577
|
+
try {
|
|
578
|
+
browser?.kill();
|
|
579
|
+
await browser?.exited;
|
|
580
|
+
await server?.close();
|
|
581
|
+
|
|
582
|
+
if (profile !== undefined) {
|
|
583
|
+
await rm(profile, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
if (folder !== undefined) {
|
|
587
|
+
await rm(folder, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
|
|
588
|
+
}
|
|
589
|
+
} finally {
|
|
590
|
+
active--;
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
}
|