deictic 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (166) hide show
  1. package/API.md +303 -0
  2. package/README.md +56 -104
  3. package/dist/annotations/index.d.ts +1 -1
  4. package/dist/astro.d.ts +1 -1
  5. package/dist/bun.d.ts +1 -1
  6. package/dist/bun.js +2 -2
  7. package/dist/client/index.d.ts +4 -2
  8. package/dist/client/index.d.ts.map +1 -1
  9. package/dist/client/index.js +130 -16
  10. package/dist/client/index.js.map +1 -1
  11. package/dist/index.d.ts +21 -218
  12. package/dist/index.js.map +1 -1
  13. package/dist/loader.js +1 -1
  14. package/dist/logs/client.d.ts +4 -0
  15. package/dist/logs/client.d.ts.map +1 -0
  16. package/dist/logs/client.js +16 -0
  17. package/dist/logs/client.js.map +1 -0
  18. package/dist/logs/index.d.ts +18 -0
  19. package/dist/logs/index.d.ts.map +1 -0
  20. package/dist/logs/index.js +21 -0
  21. package/dist/logs/index.js.map +1 -0
  22. package/dist/network/client.d.ts +4 -0
  23. package/dist/network/client.d.ts.map +1 -0
  24. package/dist/network/client.js +29 -0
  25. package/dist/network/client.js.map +1 -0
  26. package/dist/network/index.d.ts +2 -0
  27. package/dist/network/index.js +39 -0
  28. package/dist/network/index.js.map +1 -0
  29. package/dist/next.d.ts +1 -1
  30. package/dist/next.js +2 -2
  31. package/dist/recommended/index.d.ts +15 -5
  32. package/dist/recommended/index.d.ts.map +1 -1
  33. package/dist/recommended/index.js +10 -3
  34. package/dist/recommended/index.js.map +1 -1
  35. package/dist/recordings/client.d.ts +1 -1
  36. package/dist/recordings/client.d.ts.map +1 -1
  37. package/dist/recordings/client.js +177 -48
  38. package/dist/recordings/client.js.map +1 -1
  39. package/dist/recordings/index.d.ts +2 -2
  40. package/dist/recordings/index.js +3 -3
  41. package/dist/screenshots/client.d.ts +7 -1
  42. package/dist/screenshots/client.d.ts.map +1 -1
  43. package/dist/screenshots/client.js +36 -4
  44. package/dist/screenshots/client.js.map +1 -1
  45. package/dist/screenshots/dom.d.ts +1 -1
  46. package/dist/screenshots/dom.d.ts.map +1 -1
  47. package/dist/screenshots/dom.js +1 -28
  48. package/dist/screenshots/dom.js.map +1 -1
  49. package/dist/screenshots/index.d.ts +1 -1
  50. package/dist/screenshots/index.js +2 -2
  51. package/dist/screenshots/index.js.map +1 -1
  52. package/dist/screenshots/rrweb.d.ts +2 -2
  53. package/dist/screenshots/rrweb.js +5 -1
  54. package/dist/screenshots/rrweb.js.map +1 -1
  55. package/dist/{endpoints.js → shared/endpoints.js} +1 -1
  56. package/dist/shared/endpoints.js.map +1 -0
  57. package/dist/shared/index.d.ts +238 -0
  58. package/dist/shared/index.d.ts.map +1 -0
  59. package/dist/{index3.d.ts → shared/index2.d.ts} +3 -1
  60. package/dist/shared/index2.d.ts.map +1 -0
  61. package/dist/shared/index3.d.ts +112 -0
  62. package/dist/shared/index3.d.ts.map +1 -0
  63. package/dist/shared/index4.d.ts +64 -0
  64. package/dist/shared/index4.d.ts.map +1 -0
  65. package/dist/shared/index5.d.ts +220 -0
  66. package/dist/shared/index5.d.ts.map +1 -0
  67. package/dist/{index5.d.ts → shared/index6.d.ts} +2 -2
  68. package/dist/shared/index6.d.ts.map +1 -0
  69. package/dist/{integration.d.ts → shared/integration.d.ts} +4 -3
  70. package/dist/shared/integration.d.ts.map +1 -0
  71. package/dist/{integration.js → shared/integration.js} +5 -3
  72. package/dist/shared/integration.js.map +1 -0
  73. package/dist/{kept.js → shared/kept.js} +2 -2
  74. package/dist/shared/kept.js.map +1 -0
  75. package/dist/{marks.js → shared/marks.js} +6 -1
  76. package/dist/shared/marks.js.map +1 -0
  77. package/dist/shared/mask.js +107 -0
  78. package/dist/shared/mask.js.map +1 -0
  79. package/dist/{playwright.js → shared/playwright.js} +19 -4
  80. package/dist/shared/playwright.js.map +1 -0
  81. package/dist/shared/recordings.js +437 -0
  82. package/dist/shared/recordings.js.map +1 -0
  83. package/dist/shared/shortcut.js.map +1 -0
  84. package/dist/shared/tasks.js +632 -0
  85. package/dist/shared/tasks.js.map +1 -0
  86. package/dist/shared/waveform.js.map +1 -0
  87. package/dist/tailwind/client.d.ts +1 -1
  88. package/dist/tailwind/index.d.ts +1 -1
  89. package/dist/tasks/client.d.ts +1 -1
  90. package/dist/tasks/client.d.ts.map +1 -1
  91. package/dist/tasks/client.js +272 -57
  92. package/dist/tasks/client.js.map +1 -1
  93. package/dist/tasks/index.d.ts +2 -159
  94. package/dist/tasks/index.js +1 -348
  95. package/dist/vite.d.ts +11 -12
  96. package/dist/vite.d.ts.map +1 -1
  97. package/dist/vite.js +21 -4
  98. package/dist/vite.js.map +1 -1
  99. package/dist/voice/client.d.ts.map +1 -1
  100. package/dist/voice/client.js +36 -15
  101. package/dist/voice/client.js.map +1 -1
  102. package/dist/voice/index.d.ts +6 -1
  103. package/dist/voice/index.d.ts.map +1 -1
  104. package/dist/voice/index.js +13 -3
  105. package/dist/voice/index.js.map +1 -1
  106. package/dist/webpack.d.ts +1 -1
  107. package/dist/webpack.js +2 -2
  108. package/package.json +41 -2
  109. package/skills/deictic/SKILL.md +20 -14
  110. package/skills/deictic/references/install.md +32 -10
  111. package/skills/deictic/references/recordings.md +29 -0
  112. package/skills/deictic/references/tasks.md +49 -21
  113. package/skills/deictic/references/watch.md +38 -11
  114. package/skills/deictic/scripts/lib.mjs +88 -4
  115. package/skills/deictic/scripts/recording.mjs +84 -4
  116. package/skills/deictic/scripts/task.mjs +36 -7
  117. package/skills/deictic/scripts/vb.mjs +12 -0
  118. package/skills/deictic/scripts/watch.mjs +74 -10
  119. package/src/client/away.ts +105 -0
  120. package/src/client/index.ts +60 -16
  121. package/src/client/style.ts +1 -0
  122. package/src/index.ts +21 -2
  123. package/src/plugins/logs/client.ts +18 -0
  124. package/src/plugins/logs/index.ts +55 -0
  125. package/src/plugins/network/client.ts +30 -0
  126. package/src/plugins/network/index.ts +69 -0
  127. package/src/plugins/network/mask.ts +133 -0
  128. package/src/plugins/recommended/index.ts +14 -1
  129. package/src/plugins/recordings/client.ts +220 -40
  130. package/src/plugins/recordings/index.ts +111 -25
  131. package/src/plugins/recordings/marks.ts +6 -0
  132. package/src/plugins/recordings/replay.ts +159 -10
  133. package/src/plugins/screenshots/client.ts +38 -2
  134. package/src/plugins/screenshots/dom.ts +1 -32
  135. package/src/plugins/screenshots/index.ts +2 -0
  136. package/src/plugins/screenshots/playwright.ts +15 -4
  137. package/src/plugins/screenshots/rrweb.ts +2 -1
  138. package/src/plugins/tasks/client.ts +273 -41
  139. package/src/plugins/tasks/index.ts +207 -47
  140. package/src/plugins/tasks/local.ts +170 -0
  141. package/src/plugins/tasks/watchers.ts +36 -0
  142. package/src/plugins/voice/client.ts +33 -10
  143. package/src/plugins/voice/index.ts +21 -4
  144. package/src/tools/integration.ts +5 -3
  145. package/src/tools/kept.ts +2 -2
  146. package/src/vite.ts +23 -4
  147. package/dist/endpoints.js.map +0 -1
  148. package/dist/index.d.ts.map +0 -1
  149. package/dist/index2.d.ts +0 -23
  150. package/dist/index3.d.ts.map +0 -1
  151. package/dist/index4.d.ts +0 -74
  152. package/dist/index4.d.ts.map +0 -1
  153. package/dist/index5.d.ts.map +0 -1
  154. package/dist/integration.d.ts.map +0 -1
  155. package/dist/integration.js.map +0 -1
  156. package/dist/kept.js.map +0 -1
  157. package/dist/marks.js.map +0 -1
  158. package/dist/playwright.js.map +0 -1
  159. package/dist/recordings.js +0 -235
  160. package/dist/recordings.js.map +0 -1
  161. package/dist/shortcut.js.map +0 -1
  162. package/dist/tasks/index.d.ts.map +0 -1
  163. package/dist/tasks/index.js.map +0 -1
  164. package/dist/waveform.js.map +0 -1
  165. /package/dist/{shortcut.js → shared/shortcut.js} +0 -0
  166. /package/dist/{waveform.js → shared/waveform.js} +0 -0
@@ -0,0 +1,107 @@
1
+ // src/plugins/network/mask.ts
2
+ /** What a blanked value reads as. */
3
+ const MASKED = "***";
4
+ /** What's kept of a body at most, in characters. */
5
+ const BODY = 1e4;
6
+ /** A name with one of these in it holds a secret, in any case: `access_token`, `X-Api-Key`, `Set-Cookie`. */
7
+ const PARTS = [
8
+ "token",
9
+ "secret",
10
+ "passw",
11
+ "pwd",
12
+ "auth",
13
+ "cookie",
14
+ "session",
15
+ "credential",
16
+ "signature",
17
+ "apikey",
18
+ "api-key",
19
+ "api_key",
20
+ "jwt",
21
+ "otp",
22
+ "cvv",
23
+ "cvc",
24
+ "ssn",
25
+ "cardnumber",
26
+ "card_number"
27
+ ];
28
+ /** And these whole names, too short to look for inside others: `code` is OAuth's, on its way back. */
29
+ const NAMES = /* @__PURE__ */ new Set([
30
+ "key",
31
+ "pass",
32
+ "code",
33
+ "pin",
34
+ "sig",
35
+ "sid"
36
+ ]);
37
+ /** deictic's own requests: a recording sends itself as it goes, which would be a request to record each second. */
38
+ const OURS = "/__deictic/";
39
+ const sensitive = (name, more = []) => {
40
+ const lower = name.toLowerCase();
41
+ return NAMES.has(lower) || PARTS.some((part) => lower.includes(part)) || more.some((part) => lower.includes(part.toLowerCase()));
42
+ };
43
+ function maskParams(params, more) {
44
+ let changed = false;
45
+ for (const name of new Set(params.keys())) {
46
+ if (!sensitive(name, more)) continue;
47
+ params.set(name, "***");
48
+ changed = true;
49
+ }
50
+ return changed;
51
+ }
52
+ /** The URL without a name and password before its host, and with its secrets blanked: the query's, and a fragment's that reads as one. */
53
+ function maskUrl(url, more = []) {
54
+ let parsed;
55
+ try {
56
+ parsed = new URL(url);
57
+ } catch {
58
+ return url;
59
+ }
60
+ let changed = parsed.username !== "" || parsed.password !== "";
61
+ parsed.username = parsed.password = "";
62
+ if (maskParams(parsed.searchParams, more)) changed = true;
63
+ if (parsed.hash.includes("=")) {
64
+ const fragment = new URLSearchParams(parsed.hash.slice(1));
65
+ if (maskParams(fragment, more)) {
66
+ parsed.hash = fragment.toString();
67
+ changed = true;
68
+ }
69
+ }
70
+ return changed ? parsed.href.replaceAll(encodeURIComponent("***"), "***") : url;
71
+ }
72
+ function maskHeaders(headers, more = []) {
73
+ return Object.fromEntries(Object.entries(headers).map(([name, value]) => [name, sensitive(name, more) ? "***" : value]));
74
+ }
75
+ function maskJson(value, more) {
76
+ if (Array.isArray(value)) return value.map((item) => maskJson(item, more));
77
+ if (typeof value !== "object" || value === null) return value;
78
+ return Object.fromEntries(Object.entries(value).map(([name, inner]) => [name, sensitive(name, more) ? "***" : maskJson(inner, more)]));
79
+ }
80
+ /** A body with its secrets blanked where it's JSON or a form's fields, cut where it's long: other text has no names to go by. */
81
+ function maskBody(body, more = []) {
82
+ const cut = (text) => text.length > BODY ? `${text.slice(0, BODY)}… (${text.length} characters)` : text;
83
+ const text = body.trim();
84
+ if (text.startsWith("{") || text.startsWith("[")) try {
85
+ return cut(JSON.stringify(maskJson(JSON.parse(text), more)));
86
+ } catch {}
87
+ if (/^[^\s=&]+=[^\s&]*(&[^\s=&]+=[^\s&]*)*$/.test(text)) {
88
+ const fields = new URLSearchParams(text);
89
+ if (maskParams(fields, more)) return cut(fields.toString().replaceAll(encodeURIComponent("***"), "***"));
90
+ }
91
+ return cut(body);
92
+ }
93
+ /** The request as it's kept, or nothing for one left out. */
94
+ function maskRequest(request, { mask, ignore }) {
95
+ if (request.name.includes(OURS) || ignore.some((part) => request.name.includes(part))) return void 0;
96
+ return {
97
+ ...request,
98
+ name: maskUrl(request.name, mask),
99
+ ...request.requestHeaders ? { requestHeaders: maskHeaders(request.requestHeaders, mask) } : {},
100
+ ...request.responseHeaders ? { responseHeaders: maskHeaders(request.responseHeaders, mask) } : {},
101
+ ...typeof request.requestBody === "string" ? { requestBody: maskBody(request.requestBody, mask) } : {},
102
+ ...typeof request.responseBody === "string" ? { responseBody: maskBody(request.responseBody, mask) } : {}
103
+ };
104
+ }
105
+ export { maskUrl as a, maskRequest as i, maskBody as n, sensitive as o, maskHeaders as r, MASKED as t };
106
+
107
+ //# sourceMappingURL=mask.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mask.js","names":[],"sources":["../../src/plugins/network/mask.ts"],"sourcesContent":["/**\n * What a request is kept as: with what it carries that's a secret blanked, wherever a name says so. The\n * names are all there is to go by, so a secret under a name that says nothing (a token in a path, a password in\n * prose) isn't found: bodies and headers are kept only where asked for, and `ignore` leaves a request out whole.\n */\n\n/** A request as rrweb's network plugin has it: all this reads of one, and changes. */\nexport interface Request {\n name: string;\n requestHeaders?: Record<string, string>;\n responseHeaders?: Record<string, string>;\n requestBody?: string | null;\n responseBody?: string | null;\n}\n\nexport interface Masking {\n /** More names whose values are blanked, as these are: a part of the name, in any case. */\n mask: string[];\n /** Requests left out: a part of the URL. */\n ignore: string[];\n}\n\n/** What a blanked value reads as. */\nexport const MASKED = '***';\n/** What's kept of a body at most, in characters. */\nconst BODY = 10_000;\n\n/** A name with one of these in it holds a secret, in any case: `access_token`, `X-Api-Key`, `Set-Cookie`. */\nconst PARTS = [\n 'token',\n 'secret',\n 'passw',\n 'pwd',\n 'auth',\n 'cookie',\n 'session',\n 'credential',\n 'signature',\n 'apikey',\n 'api-key',\n 'api_key',\n 'jwt',\n 'otp',\n 'cvv',\n 'cvc',\n 'ssn',\n 'cardnumber',\n 'card_number',\n];\n/** And these whole names, too short to look for inside others: `code` is OAuth's, on its way back. */\nconst NAMES = new Set(['key', 'pass', 'code', 'pin', 'sig', 'sid']);\n/** deictic's own requests: a recording sends itself as it goes, which would be a request to record each second. */\nconst OURS = '/__deictic/';\n\nexport const sensitive = (name: string, more: readonly string[] = []): boolean => {\n const lower = name.toLowerCase();\n return NAMES.has(lower) || PARTS.some((part) => lower.includes(part)) || more.some((part) => lower.includes(part.toLowerCase()));\n};\n\nfunction maskParams(params: URLSearchParams, more: readonly string[]): boolean {\n let changed = false;\n for (const name of new Set(params.keys())) {\n if (!sensitive(name, more)) continue;\n params.set(name, MASKED);\n changed = true;\n }\n return changed;\n}\n\n/** The URL without a name and password before its host, and with its secrets blanked: the query's, and a fragment's that reads as one. */\nexport function maskUrl(url: string, more: readonly string[] = []): string {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n // Not one this can read: kept as it is, as there's no telling its parts.\n return url;\n }\n let changed = parsed.username !== '' || parsed.password !== '';\n parsed.username = parsed.password = '';\n if (maskParams(parsed.searchParams, more)) changed = true;\n if (parsed.hash.includes('=')) {\n const fragment = new URLSearchParams(parsed.hash.slice(1));\n if (maskParams(fragment, more)) {\n parsed.hash = fragment.toString();\n changed = true;\n }\n }\n // As it was written where nothing changed: a parsed URL spells some things its own way.\n return changed ? parsed.href.replaceAll(encodeURIComponent(MASKED), MASKED) : url;\n}\n\nexport function maskHeaders(headers: Record<string, string>, more: readonly string[] = []): Record<string, string> {\n return Object.fromEntries(Object.entries(headers).map(([name, value]) => [name, sensitive(name, more) ? MASKED : value]));\n}\n\nfunction maskJson(value: unknown, more: readonly string[]): unknown {\n if (Array.isArray(value)) return value.map((item) => maskJson(item, more));\n if (typeof value !== 'object' || value === null) return value;\n return Object.fromEntries(Object.entries(value).map(([name, inner]) => [name, sensitive(name, more) ? MASKED : maskJson(inner, more)]));\n}\n\n/** A body with its secrets blanked where it's JSON or a form's fields, cut where it's long: other text has no names to go by. */\nexport function maskBody(body: string, more: readonly string[] = []): string {\n const cut = (text: string) => (text.length > BODY ? `${text.slice(0, BODY)}… (${text.length} characters)` : text);\n const text = body.trim();\n if (text.startsWith('{') || text.startsWith('[')) {\n try {\n return cut(JSON.stringify(maskJson(JSON.parse(text), more)));\n } catch {\n // Not JSON after all.\n }\n }\n // A form's fields: `name=value&…`, with nothing a sentence would have.\n if (/^[^\\s=&]+=[^\\s&]*(&[^\\s=&]+=[^\\s&]*)*$/.test(text)) {\n const fields = new URLSearchParams(text);\n if (maskParams(fields, more)) return cut(fields.toString().replaceAll(encodeURIComponent(MASKED), MASKED));\n }\n return cut(body);\n}\n\n/** The request as it's kept, or nothing for one left out. */\nexport function maskRequest<R extends Request>(request: R, { mask, ignore }: Masking): R | undefined {\n if (request.name.includes(OURS) || ignore.some((part) => request.name.includes(part))) return undefined;\n return {\n ...request,\n name: maskUrl(request.name, mask),\n ...(request.requestHeaders ? { requestHeaders: maskHeaders(request.requestHeaders, mask) } : {}),\n ...(request.responseHeaders ? { responseHeaders: maskHeaders(request.responseHeaders, mask) } : {}),\n ...(typeof request.requestBody === 'string' ? { requestBody: maskBody(request.requestBody, mask) } : {}),\n ...(typeof request.responseBody === 'string' ? { responseBody: maskBody(request.responseBody, mask) } : {}),\n };\n}\n"],"mappings":";;AAuBA,MAAa,SAAS;;AAEtB,MAAM,OAAO;;AAGb,MAAM,QAAQ;CACZ;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AAEA,MAAM,wBAAQ,IAAI,IAAI;CAAC;CAAO;CAAQ;CAAQ;CAAO;CAAO;AAAK,CAAC;;AAElE,MAAM,OAAO;AAEb,MAAa,aAAa,MAAc,OAA0B,CAAC,MAAe;CAChF,MAAM,QAAQ,KAAK,YAAY;CAC/B,OAAO,MAAM,IAAI,KAAK,KAAK,MAAM,MAAM,SAAS,MAAM,SAAS,IAAI,CAAC,KAAK,KAAK,MAAM,SAAS,MAAM,SAAS,KAAK,YAAY,CAAC,CAAC;AACjI;AAEA,SAAS,WAAW,QAAyB,MAAkC;CAC7E,IAAI,UAAU;CACd,KAAK,MAAM,QAAQ,IAAI,IAAI,OAAO,KAAK,CAAC,GAAG;EACzC,IAAI,CAAC,UAAU,MAAM,IAAI,GAAG;EAC5B,OAAO,IAAI,MAAA,KAAY;EACvB,UAAU;CACZ;CACA,OAAO;AACT;;AAGA,SAAgB,QAAQ,KAAa,OAA0B,CAAC,GAAW;CACzE,IAAI;CACJ,IAAI;EACF,SAAS,IAAI,IAAI,GAAG;CACtB,QAAQ;EAEN,OAAO;CACT;CACA,IAAI,UAAU,OAAO,aAAa,MAAM,OAAO,aAAa;CAC5D,OAAO,WAAW,OAAO,WAAW;CACpC,IAAI,WAAW,OAAO,cAAc,IAAI,GAAG,UAAU;CACrD,IAAI,OAAO,K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AAG,OAAO,IAAI,OAAO,SAAS,CAAC,CAAC,WAAW,mBAAA,KAAyB,GAAA,KAAS,CAAC;CAC3G;CACA,OAAO,IAAI,IAAI;AACjB;;AAGA,SAAgB,YAA+B,SAAY,EAAE,MAAM,UAAkC;CACnG,IAAI,QAAQ,KAAK,SAAS,IAAI,KAAK,OAAO,MAAM,SAAS,QAAQ,KAAK,SAAS,IAAI,CAAC,GAAG,OAAO,KAAA;CAC9F,OAAO;EACL,GAAG;EACH,MAAM,QAAQ,QAAQ,MAAM,IAAI;EAChC,GAAI,QAAQ,iBAAiB,EAAE,gBAAgB,YAAY,QAAQ,gBAAgB,IAAI,EAAE,IAAI,CAAC;EAC9F,GAAI,QAAQ,kBAAkB,EAAE,iBAAiB,YAAY,QAAQ,iBAAiB,IAAI,EAAE,IAAI,CAAC;EACjG,GAAI,OAAO,QAAQ,gBAAgB,WAAW,EAAE,aAAa,SAAS,QAAQ,aAAa,IAAI,EAAE,IAAI,CAAC;EACtG,GAAI,OAAO,QAAQ,iBAAiB,WAAW,EAAE,cAAc,SAAS,QAAQ,cAAc,IAAI,EAAE,IAAI,CAAC;CAC3G;AACF"}
@@ -8,6 +8,11 @@ import { createRequire } from "node:module";
8
8
  * The snapshot is rebuilt into a sandboxed iframe filling a blank page on the page's own origin, which
9
9
  * Playwright answers itself, so nothing asks the dev server for it: rrweb has made the snapshot's URLs
10
10
  * whole, and its stylesheets' fonts and images load from the dev server as the page's did.
11
+ *
12
+ * The browser is as big as the page's window, scrollbars and all, and shows its own: a media query asks the
13
+ * window's width, and the page is laid out in what the scrollbar leaves. At the width without it, a window
14
+ * right on a breakpoint (1024 wide, 1009 to lay out in) would render as the narrower layout. The shot is then
15
+ * cut to the part the page is in.
11
16
  */
12
17
  const HOST = "<!doctype html><html><body style=\"margin:0\"></body></html>";
13
18
  const browsers = /* @__PURE__ */ new Map();
@@ -21,13 +26,16 @@ function browserOf(options) {
21
26
  launched.catch(() => browsers.delete(key));
22
27
  return launched;
23
28
  }
29
+ /** Playwright hides a headless browser's scrollbars, and with them the room they take in the page. */
30
+ const SCROLLBARS = { ignoreDefaultArgs: ["--hide-scrollbars"] };
24
31
  async function launch({ executablePath, channel }) {
25
32
  const { chromium } = await import("playwright-core").catch((e) => {
26
33
  throw new Error("the rrweb() renderer needs playwright-core: add it to your devDependencies", { cause: e });
27
34
  });
28
35
  if (executablePath !== void 0 || channel !== void 0) return chromium.launch({
29
36
  executablePath,
30
- channel
37
+ channel,
38
+ ...SCROLLBARS
31
39
  });
32
40
  const tried = [];
33
41
  for (const attempt of [
@@ -35,7 +43,10 @@ async function launch({ executablePath, channel }) {
35
43
  { channel: "chrome" },
36
44
  { channel: "msedge" }
37
45
  ]) try {
38
- return await chromium.launch(attempt);
46
+ return await chromium.launch({
47
+ ...attempt,
48
+ ...SCROLLBARS
49
+ });
39
50
  } catch (e) {
40
51
  tried.push(`${"channel" in attempt ? attempt.channel : "Playwright's Chromium"}: ${(e instanceof Error ? e.message : String(e)).split("\n", 1)[0]}`);
41
52
  }
@@ -47,7 +58,7 @@ async function render(input, options) {
47
58
  const shot = input;
48
59
  if (typeof shot?.url !== "string" || typeof shot.snapshot !== "object" || typeof shot.viewport?.width !== "number") throw new Error("screenshots: that is not a snapshot the rrweb() renderer took");
49
60
  const context = await (await browserOf(options)).newContext({
50
- viewport: shot.viewport,
61
+ viewport: shot.window ?? shot.viewport,
51
62
  deviceScaleFactor: shot.scale
52
63
  });
53
64
  try {
@@ -78,7 +89,11 @@ async function render(input, options) {
78
89
  marks.innerHTML = overlay;
79
90
  document.body.append(marks);
80
91
  }, shot);
81
- const clip = shot.clip === void 0 ? void 0 : clamp(shot.clip, shot.viewport);
92
+ const clip = clamp(shot.clip ?? {
93
+ x: 0,
94
+ y: 0,
95
+ ...shot.viewport
96
+ }, shot.viewport);
82
97
  return new Uint8Array(await page.screenshot({
83
98
  type: "png",
84
99
  ...clip === void 0 ? {} : { clip }
@@ -0,0 +1 @@
1
+ {"version":3,"file":"playwright.js","names":[],"sources":["../../src/plugins/screenshots/playwright.ts"],"sourcesContent":["/**\n * The `rrweb()` renderer's server half: rebuilds a page's snapshot in a browser beside the dev server and\n * screenshots it at the page's viewport, scroll and pixel density, so text lays out as the page's does. The\n * browser is launched on the first shot and kept for the next; Playwright closes it with the process.\n *\n * The snapshot is rebuilt into a sandboxed iframe filling a blank page on the page's own origin, which\n * Playwright answers itself, so nothing asks the dev server for it: rrweb has made the snapshot's URLs\n * whole, and its stylesheets' fonts and images load from the dev server as the page's did.\n *\n * The browser is as big as the page's window, scrollbars and all, and shows its own: a media query asks the\n * window's width, and the page is laid out in what the scrollbar leaves. At the width without it, a window\n * right on a breakpoint (1024 wide, 1009 to lay out in) would render as the narrower layout. The shot is then\n * cut to the part the page is in.\n */\nimport { createRequire } from 'node:module';\n\nimport type { Browser } from 'playwright-core';\nimport type * as Rrweb from 'rrweb-snapshot';\n\nimport type { Box, BrowserOptions } from './index.ts';\n\n/** What the page sends: its snapshot and what's needed to show it as the page does. */\n/** A node of an rrweb snapshot, as `snapshot()` answers it. */\nexport type SnapshotNode = NonNullable<ReturnType<typeof Rrweb.snapshot>>;\n\nexport interface Snapshot {\n snapshot: SnapshotNode;\n url: string;\n viewport: { width: number; height: number };\n /** The window's size, scrollbars included, where it has any: what the page's media queries ask. */\n window?: { width: number; height: number };\n scroll: { x: number; y: number };\n scale: number;\n /** The part of the viewport to keep, for a shot of an element alone. */\n clip?: Box;\n /** An SVG the viewport's size, drawn over the page: the annotations, where there are any. */\n overlay?: string;\n}\n\nconst HOST = '<!doctype html><html><body style=\"margin:0\"></body></html>';\n\nconst browsers = new Map<string, Promise<Browser>>();\n\n/** A browser by the options, launched once: the one named, or Playwright's own Chromium, then Chrome, then Edge. */\nexport function browserOf(options: BrowserOptions): Promise<Browser> {\n const key = JSON.stringify(options);\n const known = browsers.get(key);\n if (known !== undefined) return known;\n const launched = launch(options);\n browsers.set(key, launched);\n // A launch that failed is tried again on the next shot, after the user installs what it said to.\n launched.catch(() => browsers.delete(key));\n return launched;\n}\n\n/** Playwright hides a headless browser's scrollbars, and with them the room they take in the page. */\nconst SCROLLBARS = { ignoreDefaultArgs: ['--hide-scrollbars'] };\n\nasync function launch({ executablePath, channel }: BrowserOptions): Promise<Browser> {\n const { chromium } = await import('playwright-core').catch((e: unknown) => {\n throw new Error('the rrweb() renderer needs playwright-core: add it to your devDependencies', { cause: e });\n });\n if (executablePath !== undefined || channel !== undefined) return chromium.launch({ executablePath, channel, ...SCROLLBARS });\n const tried: string[] = [];\n for (const attempt of [{}, { channel: 'chrome' }, { channel: 'msedge' }]) {\n try {\n return await chromium.launch({ ...attempt, ...SCROLLBARS });\n } catch (e) {\n tried.push(\n `${'channel' in attempt ? attempt.channel : \"Playwright's Chromium\"}: ${(e instanceof Error ? e.message : String(e)).split('\\n', 1)[0]}`,\n );\n }\n }\n throw new Error(\n `the rrweb() renderer found no browser to render in (${tried.join('; ')}): run \\`npx playwright install chromium\\`, or pass rrweb({ executablePath })`,\n );\n}\n\n/** The rrweb-snapshot bundle that defines `rrwebSnapshot` in a page: its CommonJS entry is that bundle. */\nconst bundle = () => createRequire(import.meta.url).resolve('rrweb-snapshot');\n\nexport async function render(input: unknown, options: BrowserOptions): Promise<Uint8Array> {\n const shot = input as Snapshot;\n if (typeof shot?.url !== 'string' || typeof shot.snapshot !== 'object' || typeof shot.viewport?.width !== 'number')\n throw new Error('screenshots: that is not a snapshot the rrweb() renderer took');\n const browser = await browserOf(options);\n const context = await browser.newContext({ viewport: shot.window ?? shot.viewport, deviceScaleFactor: shot.scale });\n try {\n const page = await context.newPage();\n const host = new URL('/__deictic/plugins/screenshots/host', shot.url).href;\n await page.route(host, (route) => route.fulfill({ contentType: 'text/html', body: HOST }));\n await page.goto(host);\n await page.addScriptTag({ path: bundle() });\n await page.evaluate(async ({ snapshot, scroll, overlay }) => {\n const { rebuildIntoSandboxedIframe, createCache, createMirror } = (globalThis as unknown as { rrwebSnapshot: typeof Rrweb })\n .rrwebSnapshot;\n const { iframe } = rebuildIntoSandboxedIframe(snapshot, {\n root: document.body,\n cache: createCache(),\n mirror: createMirror(),\n iframeAttributes: { style: 'border:0;position:fixed;inset:0;width:100vw;height:100vh' },\n });\n const doc = iframe.contentDocument;\n if (doc === null) throw new Error('screenshots: the snapshot was rebuilt where it cannot be read');\n await doc.fonts.ready;\n await Promise.all([...doc.images].map((img) => img.decode().catch(() => {})));\n iframe.contentWindow?.scrollTo(scroll.x, scroll.y);\n if (overlay === undefined) return;\n // Over the page and its scroll: the SVG is the viewport's, already where it scrolled to.\n const marks = document.createElement('div');\n marks.style.cssText = 'position:fixed;inset:0;z-index:1;pointer-events:none';\n marks.innerHTML = overlay;\n document.body.append(marks);\n }, shot);\n // Without the scrollbars: a shot is what the page is drawn in, which is what an element's box is from.\n const clip = clamp(shot.clip ?? { x: 0, y: 0, ...shot.viewport }, shot.viewport);\n return new Uint8Array(await page.screenshot({ type: 'png', ...(clip === undefined ? {} : { clip }) }));\n } finally {\n await context.close();\n }\n}\n\n/** A box kept within the viewport: an element partly scrolled out of it shows only the part that's in. */\nfunction clamp(box: Box, viewport: { width: number; height: number }): Box | undefined {\n const x = Math.max(0, box.x);\n const y = Math.max(0, box.y);\n const width = Math.min(viewport.width, box.x + box.width) - x;\n const height = Math.min(viewport.height, box.y + box.height) - y;\n return width > 0 && height > 0 ? { x, y, width, height } : undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAuCA,MAAM,OAAO;AAEb,MAAM,2BAAW,IAAI,IAA8B;;AAGnD,SAAgB,UAAU,SAA2C;CACnE,MAAM,MAAM,KAAK,UAAU,OAAO;CAClC,MAAM,QAAQ,SAAS,IAAI,GAAG;CAC9B,IAAI,UAAU,KAAA,GAAW,OAAO;CAChC,MAAM,WAAW,OAAO,OAAO;CAC/B,SAAS,IAAI,KAAK,QAAQ;CAE1B,SAAS,YAAY,SAAS,OAAO,GAAG,CAAC;CACzC,OAAO;AACT;;AAGA,MAAM,aAAa,EAAE,mBAAmB,CA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CAC3B,MAAM,QAAQ,KAAK,IAAI,SAAS,OAAO,IAAI,IAAI,IAAI,KAAK,IAAI;CAC5D,MAAM,SAAS,KAAK,IAAI,SAAS,QAAQ,IAAI,IAAI,IAAI,MAAM,IAAI;CAC/D,OAAO,QAAQ,KAAK,SAAS,IAAI;EAAE;EAAG;EAAG;EAAO;CAAO,IAAI,KAAA;AAC7D"}
@@ -0,0 +1,437 @@
1
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
2
+ import { createRequire } from "node:module";
3
+ import { dirname, join, resolve } from "node:path";
4
+ import { definePlugin } from "../index.js";
5
+ import { t as keptIn } from "./kept.js";
6
+ import { n as MARKS } from "./marks.js";
7
+ // src/plugins/recordings/replay.ts
8
+ /**
9
+ * The replay page, `replay/<id>`: rrweb's own player (`rrweb-player`), its timeline, speeds, skipping idle
10
+ * stretches and fullscreen, sized to the window, with what it doesn't do drawn over it:
11
+ *
12
+ * - The page shows in the colour scheme it was recorded in, whatever the viewer's: the replay's iframe
13
+ * answers `prefers-color-scheme` as the viewer's browser does, so the recorded CSS's queries are rewritten
14
+ * before it's replayed, the recorded scheme's to always match and the other's never.
15
+ * - The marks drawn while recording come as custom events, an SVG in page coordinates each; they're drawn
16
+ * over the replay in the player's own scaled wrapper, moved with its scroll, rather than into its document,
17
+ * which the replayer rebuilds. Each is a marker on the timeline.
18
+ * - The voice clips play in step, at the player's speed. A recording with voice starts paused, as a browser
19
+ * plays sound only after a click.
20
+ * - What the page logged and asked for (rrweb's console and network plugins' events, which its player doesn't
21
+ * show) is a list beside the replay, where the window has the room: the row the replay is at is lit, a click on
22
+ * one goes to its moment and shows the rest of it, and each error and failed request is a mark on the timeline.
23
+ * - A recorded canvas is replayed (`UNSAFE_replayCanvas`, which lets the replay's frame run rrweb's own script
24
+ * to draw it), for a recording that has one.
25
+ *
26
+ * `?t=<seconds>` opens it paused there, and `&bare` without the controls at the recorded size, 1:1, for a
27
+ * screenshot; `?embed` is it filling a frame, with no header of its own (the lightbox's); `body[data-ready]` says
28
+ * it's in place.
29
+ *
30
+ * The plugin's routes serve it, the player and what it plays. A page with no server behind it (a `standalone` build)
31
+ * publishes it as a file instead, `replayPage(sources)`: which recording is `?id=`, and a script of its own says
32
+ * where one is.
33
+ */
34
+ /** The replay page's HTML: the routes' as it is, or one for a page published as a file. */
35
+ const replayPage = ({ player = "..", source } = {}) => `<!doctype html>
36
+ <html lang="en">
37
+ <meta charset="utf-8">
38
+ <meta name="viewport" content="width=device-width, initial-scale=1">
39
+ <title>Recording · deictic</title>
40
+ <link rel="stylesheet" href="${player}/player.css">
41
+ <style>
42
+ :root { color-scheme: dark; --accent: #12b358; }
43
+ body { margin: 0; min-height: 100vh; display: flex; flex-direction: column; background: #18181b; color: #fafafa; font: 13px/1.4 system-ui, sans-serif; }
44
+ header { display: flex; gap: 10px; align-items: center; padding: 10px 16px; border-bottom: 1px solid #3f3f46; }
45
+ header a { color: #a1a1aa; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
46
+ #stage { flex: 1; display: flex; min-height: 0; }
47
+ main { flex: 1; min-width: 0; display: flex; justify-content: center; align-items: flex-start; padding: 16px; }
48
+ body.bare header { display: none; }
49
+ body.bare main { padding: 0; }
50
+ body.embed header { display: none; }
51
+ body.embed main { padding: 0; }
52
+ /* What the page logged and asked for, beside the replay: the window's height, its list scrolling in it. */
53
+ #log { display: none; flex: none; width: 340px; flex-direction: column; border-left: 1px solid #3f3f46; background: #1f1f23; }
54
+ body.logged { height: 100vh; }
55
+ body.logged #log { display: flex; }
56
+ @media (max-width: 899px) { body.logged #log { display: none; } }
57
+ #log .filters { display: flex; gap: 6px; padding: 8px; border-bottom: 1px solid #3f3f46; }
58
+ #log .filters button { padding: 3px 8px; border: 1px solid #3f3f46; border-radius: 6px; background: none; color: #a1a1aa; font: inherit; font-size: 12px; cursor: pointer; }
59
+ #log .filters button[aria-pressed='true'] { color: #fafafa; background: #3f3f46; }
60
+ #log ol { flex: 1; min-height: 0; overflow: auto; margin: 0; padding: 0; list-style: none; font: 12px/1.45 ui-monospace, monospace; }
61
+ #log li { border-bottom: 1px solid #2e2e33; border-left: 2px solid transparent; }
62
+ #log li.ahead { opacity: 0.45; }
63
+ #log li.now { border-left-color: var(--accent); background: #27272a; }
64
+ #log li.warn .label { color: #fbbf24; }
65
+ #log li.bad .label, #log li.bad .text { color: #f87171; }
66
+ #log li > button { display: flex; gap: 8px; align-items: baseline; width: 100%; padding: 5px 8px; border: 0; background: none; color: inherit; font: inherit; text-align: left; cursor: pointer; }
67
+ #log li > button:hover { background: #2e2e33; }
68
+ #log time { flex: none; color: #71717a; }
69
+ #log .label { flex: none; min-width: 4ch; color: #a1a1aa; }
70
+ #log .text { min-width: 0; overflow: hidden; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow-wrap: anywhere; }
71
+ #log li.open .text { display: block; white-space: pre-wrap; }
72
+ #log pre { margin: 0; padding: 2px 8px 8px calc(8px + 6ch + 8px); color: #a1a1aa; font: inherit; white-space: pre-wrap; overflow-wrap: anywhere; }
73
+ #log.no-console li.console, #log.no-network li.network, #log.only-bad li:not(.bad) { display: none; }
74
+ #main .rr-player .rr-progress .bad-mark { position: absolute; top: -3px; width: 3px; height: 10px; margin-left: -1px; border-radius: 1px; background: #f87171; pointer-events: none; }
75
+ body.embed #main .rr-player { box-shadow: none; border-radius: 0; }
76
+ #marks { position: absolute; left: 0; top: 0; pointer-events: none; z-index: 3; }
77
+ #marks svg { position: absolute; left: 0; top: 0; overflow: visible; }
78
+ .problem { color: #f87171; padding: 16px; }
79
+ /* rrweb-player, in the dark of the rest of deictic. Its rules repeat Svelte's scoping class, so these start
80
+ from #main, which outweighs any number of classes. */
81
+ #main .rr-player { background: #27272a; box-shadow: 0 12px 32px rgb(0 0 0 / 0.5); border-radius: 8px; overflow: hidden; }
82
+ body.bare #main .rr-player { box-shadow: none; border-radius: 0; }
83
+ #main .rr-player .rr-player__frame { background: #fff; }
84
+ #main .rr-player .rr-controller { background: #18181b; border-top: 1px solid #3f3f46; border-radius: 0; }
85
+ #main .rr-player .rr-timeline__time { color: #a1a1aa; font: 12px ui-monospace, monospace; }
86
+ #main .rr-player .rr-progress { background: #3f3f46; border-color: #18181b; }
87
+ #main .rr-player .rr-progress__step { background: color-mix(in srgb, var(--accent) 45%, transparent); }
88
+ #main .rr-player .rr-progress__handler { background: var(--accent); }
89
+ #main .rr-player .rr-controller__btns button { color: #e4e4e7; }
90
+ #main .rr-player .rr-controller__btns button:disabled { color: #52525b; }
91
+ #main .rr-player .rr-controller__btns button svg { fill: currentColor; }
92
+ #main .rr-player .rr-controller__btns button.active { color: #04130b; background: var(--accent); }
93
+ #main .rr-player .rr-controller__btns button:active { background: color-mix(in srgb, var(--accent) 60%, transparent); }
94
+ #main .rr-player .switch .label { color: #e4e4e7; }
95
+ #main .rr-player .switch.disabled .label { color: #52525b; }
96
+ #main .rr-player .switch label:before { background: #52525b; }
97
+ #main .rr-player .switch input:checked + label:before { background: var(--accent); }
98
+ </style>
99
+ <header>
100
+ <strong>Recording</strong>
101
+ <a id="page" target="_blank" rel="noreferrer"></a>
102
+ </header>
103
+ <div id="stage">
104
+ <main id="main"></main>
105
+ <aside id="log" aria-label="Console and network">
106
+ <div class="filters">
107
+ <button type="button" data-hides="no-console" aria-pressed="true">Console</button>
108
+ <button type="button" data-hides="no-network" aria-pressed="true">Network</button>
109
+ <button type="button" data-shows="only-bad" aria-pressed="false" title="Errors, and requests that failed">Problems</button>
110
+ </div>
111
+ <ol></ol>
112
+ </aside>
113
+ </div>
114
+ <script src="${player}/player.js"><\/script>${source === void 0 ? "" : `
115
+ <script src="${source}"><\/script>`}
116
+ <script>
117
+ const params = new URLSearchParams(location.search);
118
+ const bare = params.has('bare');
119
+ const embed = params.has('embed');
120
+ if (bare) document.body.classList.add('bare');
121
+ if (embed) document.body.classList.add('embed');
122
+ const id = params.get('id') ?? location.pathname.split('/').at(-1);
123
+ // The plugin's routes, unless the page was given a source of its own (\`replayPage\`).
124
+ const from = globalThis.deicticReplay ?? {
125
+ recording: (id) => fetch('../recording/' + id).then((r) => (r.ok ? r.json() : r.text().then((t) => Promise.reject(new Error(t))))),
126
+ clip: (id) => '../../voice/clip/' + id,
127
+ };
128
+ Promise.resolve(from.recording(id)).then(async (kept) => {
129
+ const scheme = kept.colorScheme ?? 'light';
130
+ const events = JSON.parse(
131
+ JSON.stringify(kept.events).replace(/\\(\\s*prefers-color-scheme\\s*:\\s*(light|dark)\\s*\\)/g, (_, s) =>
132
+ s === scheme ? '(min-width: 0px)' : '(max-width: 0px) and (min-width: 1px)',
133
+ ),
134
+ );
135
+ page.textContent = kept.page;
136
+ page.href = kept.page;
137
+
138
+ // What the page logged and asked for, where the recording has it (rrweb's console and network plugins' events):
139
+ // a row each, in their order, beside the replay. Not in a bare one, which is the page alone.
140
+ const t0 = events[0].timestamp;
141
+ const clock = (ms) => { const s = Math.max(0, ms) / 1000; return Math.floor(s / 60) + ':' + (s % 60).toFixed(1).padStart(4, '0'); };
142
+ // An argument is kept as JSON: a string reads better without its quotes.
143
+ const plain = (arg) => { try { const v = JSON.parse(arg); return typeof v === 'string' ? v : arg; } catch { return arg; } };
144
+ const origin = (() => { try { return new URL(kept.page).origin; } catch { return ''; } })();
145
+ const fields = (title, held) => (held && Object.keys(held).length > 0 ? [title, ...Object.entries(held).map(([k, v]) => ' ' + k + ': ' + v)] : []);
146
+ const rows = [];
147
+ for (const e of events) {
148
+ if (e.type !== 6 || bare) continue;
149
+ const at = e.timestamp - t0;
150
+ if (e.data.plugin === 'rrweb/console@1') {
151
+ const { level, payload = [], trace = [] } = e.data.payload;
152
+ rows.push({ at, kind: 'console', label: level, bad: level === 'error' || level === 'assert', warn: level === 'warn', text: payload.map(plain).join(' '), more: trace.map((l) => 'at ' + l) });
153
+ }
154
+ if (e.data.plugin === 'rrweb/network@1') {
155
+ for (const r of e.data.payload.requests ?? []) {
156
+ // The page's own origin goes without saying.
157
+ let name = r.name;
158
+ try { const u = new URL(r.name); if (u.origin === origin) name = u.pathname + u.search + u.hash; } catch {}
159
+ const more = [
160
+ r.name,
161
+ [r.initiatorType, Number.isFinite(r.duration) ? Math.round(r.duration) + ' ms' : '', e.data.payload.isInitial ? 'as the page loaded' : ''].filter(Boolean).join(' · '),
162
+ ...fields('Request headers', r.requestHeaders),
163
+ ...(r.requestBody ? ['Request body', ' ' + r.requestBody] : []),
164
+ ...fields('Response headers', r.responseHeaders),
165
+ ...(r.responseBody ? ['Response body', ' ' + r.responseBody] : []),
166
+ ];
167
+ // No status is one the browser won't say (another origin's), not one that failed.
168
+ rows.push({ at, kind: 'network', label: r.status ? String(r.status) : '···', bad: r.status >= 400, text: (r.method ? r.method + ' ' : '') + name, more });
169
+ }
170
+ }
171
+ }
172
+ const logged = rows.length > 0;
173
+ const log = document.getElementById('log');
174
+ if (logged) document.body.classList.add('logged');
175
+ // The panel's room, where the window is wide enough to show it (as the stylesheet has it).
176
+ const side = () => (logged && innerWidth >= 900 ? 340 : 0);
177
+
178
+ // A recording with the mic starts paused: a browser plays sound only after a click, which Play is.
179
+ const clips = await Promise.all((kept.voice ?? []).map(async (c) => ({ ...c, audio: Object.assign(new Audio(await from.clip(c.id)), { preload: 'auto' }) })));
180
+ const t = Number.parseFloat(params.get('t') ?? '');
181
+ // The player's frame, at most the window's room, the controls (80px) under it; 1:1 when bare.
182
+ const size = () => bare
183
+ ? { width: kept.viewport.width, height: kept.viewport.height }
184
+ : embed
185
+ ? { width: innerWidth - side(), height: innerHeight - 80 }
186
+ : { width: Math.min(kept.viewport.width, innerWidth - 32 - side()), height: Math.min(kept.viewport.height, innerHeight - 90 - 80 - 16) };
187
+ const Player = rrwebPlayer.default ?? rrwebPlayer.Player ?? rrwebPlayer;
188
+ const player = new Player({
189
+ target: main,
190
+ props: {
191
+ events,
192
+ ...size(),
193
+ autoPlay: !Number.isFinite(t) && clips.length === 0,
194
+ showController: !bare,
195
+ speedOption: [1, 2, 4, 8],
196
+ tags: { ${JSON.stringify(MARKS)}: '#12b358' },
197
+ inactiveColor: '#3f3f46',
198
+ mouseTail: false,
199
+ // A recorded canvas is drawn by rrweb's own script in the replay's frame, which then must run scripts
200
+ // (the page's own were never recorded): only for a recording that has one.
201
+ ...(events.some((e) => e.type === 3 && e.data.source === 9) ? { UNSAFE_replayCanvas: true } : {}),
202
+ },
203
+ });
204
+ addEventListener('resize', () => { player.$set(size()); player.triggerResize(); });
205
+ const replayer = player.getReplayer();
206
+ const total = player.getMetaData().totalTime;
207
+
208
+ // The marks as they were at this point: the latest custom event's, in the player's scaled wrapper, moved with the replay's scroll.
209
+ const marks = Object.assign(document.createElement('div'), { id: 'marks' });
210
+ replayer.wrapper.append(marks);
211
+ replayer.on('custom-event', (e) => { if (e.data.tag === ${JSON.stringify(MARKS)}) marks.innerHTML = e.data.payload.svg; });
212
+
213
+ let playing = false;
214
+ player.addEventListener('ui-update-player-state', (e) => { playing = e.payload === 'playing'; });
215
+
216
+ // The rows: a click goes to its moment, and shows the rest of it (where a line was logged from, a request's
217
+ // headers and bodies). All set as text: it's the recorded page's, not ours.
218
+ const list = log.querySelector('ol');
219
+ const bar = main.querySelector('.rr-progress');
220
+ for (const row of rows) {
221
+ const cell = (tag, name, text) => Object.assign(document.createElement(tag), { className: name, textContent: text });
222
+ const go = Object.assign(document.createElement('button'), { type: 'button' });
223
+ go.append(cell('time', '', clock(row.at)), cell('span', 'label', row.label), cell('span', 'text', row.text));
224
+ const more = Object.assign(cell('pre', '', row.more.join('\\n')), { hidden: true });
225
+ row.el = Object.assign(document.createElement('li'), { className: row.kind + (row.bad ? ' bad' : row.warn ? ' warn' : '') });
226
+ go.addEventListener('click', () => {
227
+ player.goto(Math.min(row.at, total), playing);
228
+ more.hidden = !more.hidden || row.more.length === 0;
229
+ row.el.classList.toggle('open', !more.hidden);
230
+ });
231
+ row.el.append(go, more);
232
+ list.append(row.el);
233
+ // An error, or a request that failed, is a mark on the timeline too.
234
+ if (row.bad && bar) bar.append(Object.assign(cell('i', 'bad-mark', ''), { title: row.text.slice(0, 200), style: 'left:' + (total > 0 ? (row.at / total) * 100 : 0) + '%' }));
235
+ }
236
+ for (const button of log.querySelectorAll('.filters button')) {
237
+ button.addEventListener('click', () => {
238
+ const on = button.getAttribute('aria-pressed') !== 'true';
239
+ button.setAttribute('aria-pressed', String(on));
240
+ if (button.dataset.hides) log.classList.toggle(button.dataset.hides, !on);
241
+ if (button.dataset.shows) log.classList.toggle(button.dataset.shows, on);
242
+ });
243
+ }
244
+ // The row the replay is at: the last whose moment has come, lit, the ones to come faint, kept in sight unless
245
+ // the list is being read.
246
+ let lit;
247
+ const light = (now) => {
248
+ let i = -1;
249
+ while (i + 1 < rows.length && rows[i + 1].at <= now) i++;
250
+ if (i === lit) return;
251
+ lit = i;
252
+ rows.forEach((row, k) => { row.el.classList.toggle('ahead', k > i); row.el.classList.toggle('now', k === i); });
253
+ if (i >= 0 && !log.matches(':hover')) rows[i].el.scrollIntoView({ block: 'nearest' });
254
+ };
255
+ const follow = () => {
256
+ const win = replayer.iframe.contentWindow;
257
+ if (win) marks.style.transform = 'translate(' + -win.scrollX + 'px,' + -win.scrollY + 'px)';
258
+ const now = Math.min(replayer.getCurrentTime(), total);
259
+ light(now);
260
+ const speed = replayer.config.speed ?? 1;
261
+ // Each clip plays while the replay is inside it, at its speed, kept within a few frames of the replay's time.
262
+ for (const c of clips) {
263
+ const into = now - c.at;
264
+ if (!playing || into < 0 || into >= c.duration) { if (!c.audio.paused) c.audio.pause(); continue; }
265
+ if (c.audio.playbackRate !== speed) c.audio.playbackRate = speed;
266
+ if (Math.abs(c.audio.currentTime * 1000 - into) > 250 * speed) c.audio.currentTime = into / 1000;
267
+ if (c.audio.paused) c.audio.play().catch(() => {});
268
+ }
269
+ requestAnimationFrame(follow);
270
+ };
271
+ follow();
272
+
273
+ if (Number.isFinite(t)) player.goto(Math.min(Math.max(0, t * 1000), total), false);
274
+ document.body.dataset.ready = '';
275
+ }).catch((e) => { document.querySelector('main').innerHTML = '<p class="problem"></p>'; document.querySelector('.problem').textContent = e.message; });
276
+ <\/script>
277
+ </html>
278
+ `;
279
+ // src/plugins/recordings/index.ts
280
+ /**
281
+ * `deictic/recordings`: records the page with rrweb, for other plugins to attach (tasks does). No tab of
282
+ * its own: `use('recordings').record()` shows a toolbar on the page (drag it to any edge) with annotate
283
+ * mode's tools, where that plugin is loaded, a mic where the voice plugin is, and Stop and Discard. What's drawn while recording is in the
284
+ * recording too, as custom events the replay draws.
285
+ *
286
+ * Recordings are kept under `.deictic/recordings`, the latest `keep`, as JSON: rrweb's
287
+ * events, with the page, its viewport and how long it ran. `replay/<id>` plays one back in the browser.
288
+ *
289
+ * The page sends one as it goes (`begin`, then `part/<id>` each second or so, then `end/<id>` or `discard/<id>`),
290
+ * not whole at the end, so it outlasts the page: after a reload, or a link to another page of the site, the next
291
+ * page carries on with the same recording, which then holds each page in turn.
292
+ */
293
+ const ID = /^[a-z0-9]+-[a-z0-9]+$/;
294
+ /** What one recording may weigh: minutes of a busy page are a few MB. */
295
+ const MAX = 52428800;
296
+ /** How long a recording nobody ended keeps its parts, in milliseconds. */
297
+ const STALE = 864e5;
298
+ /** rrweb's player (`rrweb-player`), served to the replay page: its build for a script tag, and its styles. */
299
+ const player = (file) => {
300
+ try {
301
+ return join(dirname(createRequire(import.meta.url).resolve("rrweb-player")), file);
302
+ } catch {
303
+ return "";
304
+ }
305
+ };
306
+ function recordings(options = {}) {
307
+ const keep = options.keep ?? 20;
308
+ let dir = "";
309
+ let taken = 0;
310
+ const pathOf = (id) => join(dir, `${id}.json`);
311
+ const read = (id) => {
312
+ if (!ID.test(id) || !existsSync(pathOf(id))) return void 0;
313
+ return {
314
+ data: new Uint8Array(readFileSync(pathOf(id))),
315
+ name: `recording-${id}.json`,
316
+ type: "application/json"
317
+ };
318
+ };
319
+ const partOf = (id) => join(dir, `${id}.part`);
320
+ /** The recording going on that a request names, as its last segment: its ID, or the answer that there's none. */
321
+ const going = (req) => {
322
+ const id = new URL(req.url).pathname.split("/").at(-1) ?? "";
323
+ if (ID.test(id) && existsSync(partOf(id))) return id;
324
+ return Response.json({ problem: `no recording ${id} is going any more: record again` }, { status: 404 });
325
+ };
326
+ const json = async (req) => {
327
+ try {
328
+ return await req.json();
329
+ } catch {
330
+ return;
331
+ }
332
+ };
333
+ /** A recording begun: its ID, and the file its parts are added to, which starts with what `Kept` says besides the events. */
334
+ const begin = (meta) => {
335
+ const id = `${Date.now().toString(36).padStart(9, "0")}${(taken++ % 1296).toString(36).padStart(2, "0")}-${crypto.randomUUID().slice(0, 8)}`;
336
+ mkdirSync(dir, { recursive: true });
337
+ for (const f of readdirSync(dir)) if (f.endsWith(".part") && Date.now() - statSync(join(dir, f)).mtimeMs > STALE) rmSync(join(dir, f));
338
+ writeFileSync(partOf(id), `${JSON.stringify(meta)}\n`);
339
+ return id;
340
+ };
341
+ /** The parts as one recording, in their order whatever order they came in: a page's last may overtake the one before. */
342
+ const end = (id, last) => {
343
+ const [meta, ...lines] = readFileSync(partOf(id), "utf8").trimEnd().split("\n");
344
+ const events = lines.map((line) => JSON.parse(line)).toSorted((a, b) => a.seq - b.seq).flatMap((part) => part.events);
345
+ rmSync(partOf(id));
346
+ if (events.length === 0) return false;
347
+ const kept = {
348
+ ...JSON.parse(meta),
349
+ ...last,
350
+ events
351
+ };
352
+ writeFileSync(pathOf(id), JSON.stringify(kept));
353
+ const all = readdirSync(dir).filter((f) => f.endsWith(".json")).toSorted();
354
+ for (const old of all.slice(0, Math.max(0, all.length - keep))) rmSync(join(dir, old));
355
+ return true;
356
+ };
357
+ const file = (path, type) => {
358
+ if (!existsSync(path)) return new Response("rrweb-player is missing: add it to your devDependencies", { status: 404 });
359
+ return new Response(readFileSync(path), { headers: { "content-type": type } });
360
+ };
361
+ return definePlugin({
362
+ name: "recordings",
363
+ client: "deictic/recordings/client",
364
+ clientOptions: {
365
+ masking: {
366
+ blockClass: options.blockClass ?? "rr-block",
367
+ blockSelector: options.blockSelector,
368
+ maskTextClass: options.maskTextClass ?? "rr-mask",
369
+ maskTextSelector: options.maskTextSelector,
370
+ maskAllInputs: options.maskAllInputs ?? false
371
+ },
372
+ canvas: options.canvas === false ? false : { fps: (options.canvas === true ? void 0 : options.canvas?.fps) ?? 2 }
373
+ },
374
+ setup: ({ root }) => {
375
+ dir = options.dir === void 0 ? keptIn(root, "recordings") : resolve(root, options.dir);
376
+ return { read };
377
+ },
378
+ routes: {
379
+ begin: async (req) => {
380
+ const meta = await json(req);
381
+ if (meta?.viewport === void 0 || typeof meta.page !== "string" || typeof meta.startedAt !== "number") return Response.json({ problem: "send the page, its viewport and when it started, as JSON" }, { status: 400 });
382
+ const { page, viewport, colorScheme, startedAt } = meta;
383
+ return Response.json({ id: begin({
384
+ page,
385
+ viewport,
386
+ ...colorScheme === void 0 ? {} : { colorScheme },
387
+ startedAt
388
+ }) });
389
+ },
390
+ part: async (req) => {
391
+ const id = going(req);
392
+ if (typeof id !== "string") return id;
393
+ const seq = Number(new URL(req.url).searchParams.get("seq") ?? "none");
394
+ const events = await json(req);
395
+ if (!Array.isArray(events) || !Number.isInteger(seq)) return Response.json({ problem: "send the events as a JSON array, and `seq`, their place" }, { status: 400 });
396
+ const line = `${JSON.stringify({
397
+ seq,
398
+ events
399
+ })}\n`;
400
+ if (statSync(partOf(id)).size + line.length > MAX) return Response.json({ problem: `a recording may weigh ${MAX / 1024 / 1024} MB at most: stop this one` }, { status: 413 });
401
+ appendFileSync(partOf(id), line);
402
+ return Response.json({ id });
403
+ },
404
+ end: async (req) => {
405
+ const id = going(req);
406
+ if (typeof id !== "string") return id;
407
+ const last = await json(req);
408
+ if (typeof last?.duration !== "number") return Response.json({ problem: "send how long it ran, as JSON" }, { status: 400 });
409
+ if (!end(id, {
410
+ duration: last.duration,
411
+ ...last.voice === void 0 ? {} : { voice: last.voice }
412
+ })) return Response.json({ problem: "the recording has no events: record for a moment longer" }, { status: 400 });
413
+ return Response.json({ id });
414
+ },
415
+ discard: (req) => {
416
+ const id = going(req);
417
+ if (typeof id !== "string") return id;
418
+ rmSync(partOf(id));
419
+ return Response.json({ id });
420
+ },
421
+ recording: (req) => {
422
+ const found = read(new URL(req.url).pathname.split("/").at(-1) ?? "");
423
+ if (found === void 0) return new Response("no such recording, or not kept any more", { status: 404 });
424
+ return new Response(found.data, { headers: {
425
+ "content-type": found.type,
426
+ "cache-control": "no-store"
427
+ } });
428
+ },
429
+ replay: () => new Response(replayPage(), { headers: { "content-type": "text/html; charset=utf-8" } }),
430
+ "player.js": () => file(player("rrweb-player.umd.min.cjs"), "text/javascript"),
431
+ "player.css": () => file(player("style.css"), "text/css")
432
+ }
433
+ });
434
+ }
435
+ export { replayPage as n, recordings as t };
436
+
437
+ //# sourceMappingURL=recordings.js.map