blast-studio 0.0.0-stage → 0.1.1

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 (256) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +138 -2
  3. package/bin/bstudio.mjs +13 -0
  4. package/dist/agent-env.js +177 -0
  5. package/dist/brief.js +53 -0
  6. package/dist/budget/ledger.js +153 -0
  7. package/dist/campaign-zip.js +93 -0
  8. package/dist/cli.js +118 -0
  9. package/dist/commands/accept.js +64 -0
  10. package/dist/commands/auth.js +77 -0
  11. package/dist/commands/brief.js +117 -0
  12. package/dist/commands/budget.js +22 -0
  13. package/dist/commands/dashboard.js +9 -0
  14. package/dist/commands/doctor.js +57 -0
  15. package/dist/commands/export.js +42 -0
  16. package/dist/commands/init.js +24 -0
  17. package/dist/commands/install-skills.js +52 -0
  18. package/dist/commands/library.js +12 -0
  19. package/dist/commands/make.js +71 -0
  20. package/dist/commands/mark.js +44 -0
  21. package/dist/commands/new.js +25 -0
  22. package/dist/commands/plan.js +57 -0
  23. package/dist/commands/render-preview.js +43 -0
  24. package/dist/commands/render.js +243 -0
  25. package/dist/commands/review.js +119 -0
  26. package/dist/commands/revise.js +73 -0
  27. package/dist/commands/sources.js +33 -0
  28. package/dist/commands/status.js +34 -0
  29. package/dist/config.js +141 -0
  30. package/dist/dashboard/server.js +171 -0
  31. package/dist/dashboard/static/app.css +1 -0
  32. package/dist/dashboard/static/app.js +52 -0
  33. package/dist/dashboard/static/index.html +8 -0
  34. package/dist/env.js +47 -0
  35. package/dist/export.js +110 -0
  36. package/dist/fetch-text.js +64 -0
  37. package/dist/io.js +1 -0
  38. package/dist/keychain.js +41 -0
  39. package/dist/library.js +49 -0
  40. package/dist/packs.js +91 -0
  41. package/dist/plan.js +75 -0
  42. package/dist/posts.js +40 -0
  43. package/dist/providers/images.js +116 -0
  44. package/dist/providers/voice.js +55 -0
  45. package/dist/render/bins.js +21 -0
  46. package/dist/render/ffmpeg.js +102 -0
  47. package/dist/render/metrics.js +109 -0
  48. package/dist/render/stills.js +175 -0
  49. package/dist/render/template.js +20 -0
  50. package/dist/render/video.js +175 -0
  51. package/dist/review/gates.js +201 -0
  52. package/dist/review/reviewer.js +79 -0
  53. package/dist/review/score.js +21 -0
  54. package/dist/review/slop.js +17 -0
  55. package/dist/review-hash.js +21 -0
  56. package/dist/types.js +29 -0
  57. package/dist/updater/check.js +140 -0
  58. package/dist/updater/propose.js +144 -0
  59. package/dist/workspace.js +142 -0
  60. package/package.json +45 -4
  61. package/platforms/bluesky/guide.md +94 -0
  62. package/platforms/bluesky/pack.yml +150 -0
  63. package/platforms/dailydev/guide.md +82 -0
  64. package/platforms/dailydev/pack.yml +152 -0
  65. package/platforms/devto/guide.md +93 -0
  66. package/platforms/devto/pack.yml +119 -0
  67. package/platforms/gist/guide.md +92 -0
  68. package/platforms/gist/pack.yml +119 -0
  69. package/platforms/github-discussion/guide.md +92 -0
  70. package/platforms/github-discussion/pack.yml +122 -0
  71. package/platforms/hashnode/guide.md +93 -0
  72. package/platforms/hashnode/pack.yml +124 -0
  73. package/platforms/hn/guide.md +48 -0
  74. package/platforms/hn/pack.yml +59 -0
  75. package/platforms/instagram/guide.md +95 -0
  76. package/platforms/instagram/pack.yml +136 -0
  77. package/platforms/lemmy/guide.md +88 -0
  78. package/platforms/lemmy/pack.yml +141 -0
  79. package/platforms/linkedin/guide.md +93 -0
  80. package/platforms/linkedin/pack.yml +145 -0
  81. package/platforms/mastodon/guide.md +92 -0
  82. package/platforms/mastodon/pack.yml +138 -0
  83. package/platforms/medium/guide.md +92 -0
  84. package/platforms/medium/pack.yml +119 -0
  85. package/platforms/newsletter/guide.md +94 -0
  86. package/platforms/newsletter/pack.yml +144 -0
  87. package/platforms/producthunt/guide.md +92 -0
  88. package/platforms/producthunt/pack.yml +166 -0
  89. package/platforms/reddit/guide.md +92 -0
  90. package/platforms/reddit/pack.yml +151 -0
  91. package/platforms/snapshots/.gitkeep +0 -0
  92. package/platforms/snapshots/bluesky-10.sha256 +1 -0
  93. package/platforms/snapshots/bluesky-10.txt +1 -0
  94. package/platforms/snapshots/bluesky-11.sha256 +1 -0
  95. package/platforms/snapshots/bluesky-11.txt +1 -0
  96. package/platforms/snapshots/bluesky-12.sha256 +1 -0
  97. package/platforms/snapshots/bluesky-12.txt +1 -0
  98. package/platforms/snapshots/bluesky-13.sha256 +1 -0
  99. package/platforms/snapshots/bluesky-13.txt +1 -0
  100. package/platforms/snapshots/bluesky-14.sha256 +1 -0
  101. package/platforms/snapshots/bluesky-14.txt +1 -0
  102. package/platforms/snapshots/cross-platform-63.sha256 +1 -0
  103. package/platforms/snapshots/cross-platform-63.txt +1 -0
  104. package/platforms/snapshots/cross-platform-64.sha256 +1 -0
  105. package/platforms/snapshots/cross-platform-64.txt +1 -0
  106. package/platforms/snapshots/dailydev-55.sha256 +1 -0
  107. package/platforms/snapshots/dailydev-55.txt +1 -0
  108. package/platforms/snapshots/dailydev-56.sha256 +1 -0
  109. package/platforms/snapshots/dailydev-56.txt +1 -0
  110. package/platforms/snapshots/dailydev-57.sha256 +1 -0
  111. package/platforms/snapshots/dailydev-57.txt +1 -0
  112. package/platforms/snapshots/devto-26.sha256 +1 -0
  113. package/platforms/snapshots/devto-26.txt +1 -0
  114. package/platforms/snapshots/devto-27.sha256 +1 -0
  115. package/platforms/snapshots/devto-27.txt +1 -0
  116. package/platforms/snapshots/devto-28.sha256 +1 -0
  117. package/platforms/snapshots/devto-28.txt +1 -0
  118. package/platforms/snapshots/devto-29.sha256 +1 -0
  119. package/platforms/snapshots/devto-29.txt +1 -0
  120. package/platforms/snapshots/gist-52.sha256 +1 -0
  121. package/platforms/snapshots/gist-52.txt +1 -0
  122. package/platforms/snapshots/gist-53.sha256 +1 -0
  123. package/platforms/snapshots/gist-53.txt +1 -0
  124. package/platforms/snapshots/gist-54.sha256 +1 -0
  125. package/platforms/snapshots/gist-54.txt +1 -0
  126. package/platforms/snapshots/github-discussion-policy.sha256 +1 -0
  127. package/platforms/snapshots/github-discussion-policy.txt +1 -0
  128. package/platforms/snapshots/hashnode-30.sha256 +1 -0
  129. package/platforms/snapshots/hashnode-30.txt +1 -0
  130. package/platforms/snapshots/hashnode-31.sha256 +1 -0
  131. package/platforms/snapshots/hashnode-31.txt +1 -0
  132. package/platforms/snapshots/hashnode-32.sha256 +1 -0
  133. package/platforms/snapshots/hashnode-32.txt +1 -0
  134. package/platforms/snapshots/hn-23.sha256 +1 -0
  135. package/platforms/snapshots/hn-23.txt +1 -0
  136. package/platforms/snapshots/hn-24.sha256 +1 -0
  137. package/platforms/snapshots/hn-24.txt +1 -0
  138. package/platforms/snapshots/hn-25.sha256 +1 -0
  139. package/platforms/snapshots/hn-25.txt +1 -0
  140. package/platforms/snapshots/hyperframes-releases.sha256 +1 -0
  141. package/platforms/snapshots/hyperframes-releases.txt +1 -0
  142. package/platforms/snapshots/instagram-43.sha256 +1 -0
  143. package/platforms/snapshots/instagram-43.txt +1 -0
  144. package/platforms/snapshots/instagram-47.sha256 +1 -0
  145. package/platforms/snapshots/instagram-47.txt +1 -0
  146. package/platforms/snapshots/lemmy-policy.sha256 +1 -0
  147. package/platforms/snapshots/lemmy-policy.txt +1 -0
  148. package/platforms/snapshots/linkedin-1.sha256 +1 -0
  149. package/platforms/snapshots/linkedin-1.txt +1 -0
  150. package/platforms/snapshots/linkedin-2.sha256 +1 -0
  151. package/platforms/snapshots/linkedin-2.txt +1 -0
  152. package/platforms/snapshots/linkedin-3.sha256 +1 -0
  153. package/platforms/snapshots/linkedin-3.txt +1 -0
  154. package/platforms/snapshots/linkedin-4.sha256 +1 -0
  155. package/platforms/snapshots/linkedin-4.txt +1 -0
  156. package/platforms/snapshots/mastodon-15.sha256 +1 -0
  157. package/platforms/snapshots/mastodon-15.txt +1 -0
  158. package/platforms/snapshots/mastodon-16.sha256 +1 -0
  159. package/platforms/snapshots/mastodon-16.txt +1 -0
  160. package/platforms/snapshots/mastodon-17.sha256 +1 -0
  161. package/platforms/snapshots/mastodon-17.txt +1 -0
  162. package/platforms/snapshots/medium-34.sha256 +1 -0
  163. package/platforms/snapshots/medium-34.txt +1 -0
  164. package/platforms/snapshots/medium-35.sha256 +1 -0
  165. package/platforms/snapshots/medium-35.txt +1 -0
  166. package/platforms/snapshots/medium-36.sha256 +1 -0
  167. package/platforms/snapshots/medium-36.txt +1 -0
  168. package/platforms/snapshots/newsletter-58.sha256 +1 -0
  169. package/platforms/snapshots/newsletter-58.txt +1 -0
  170. package/platforms/snapshots/newsletter-59.sha256 +1 -0
  171. package/platforms/snapshots/newsletter-59.txt +1 -0
  172. package/platforms/snapshots/newsletter-60.sha256 +1 -0
  173. package/platforms/snapshots/newsletter-60.txt +1 -0
  174. package/platforms/snapshots/newsletter-61.sha256 +1 -0
  175. package/platforms/snapshots/newsletter-61.txt +1 -0
  176. package/platforms/snapshots/newsletter-62.sha256 +1 -0
  177. package/platforms/snapshots/newsletter-62.txt +1 -0
  178. package/platforms/snapshots/openai-image-pricing.sha256 +1 -0
  179. package/platforms/snapshots/openai-image-pricing.txt +1 -0
  180. package/platforms/snapshots/playwright-releases.sha256 +1 -0
  181. package/platforms/snapshots/playwright-releases.txt +1 -0
  182. package/platforms/snapshots/producthunt-37.sha256 +1 -0
  183. package/platforms/snapshots/producthunt-37.txt +1 -0
  184. package/platforms/snapshots/producthunt-38.sha256 +1 -0
  185. package/platforms/snapshots/producthunt-38.txt +1 -0
  186. package/platforms/snapshots/producthunt-39.sha256 +1 -0
  187. package/platforms/snapshots/producthunt-39.txt +1 -0
  188. package/platforms/snapshots/reddit-20.sha256 +1 -0
  189. package/platforms/snapshots/reddit-20.txt +1 -0
  190. package/platforms/snapshots/reddit-21.sha256 +1 -0
  191. package/platforms/snapshots/reddit-21.txt +1 -0
  192. package/platforms/snapshots/reddit-22.sha256 +1 -0
  193. package/platforms/snapshots/reddit-22.txt +1 -0
  194. package/platforms/snapshots/substack-policy.sha256 +1 -0
  195. package/platforms/snapshots/substack-policy.txt +1 -0
  196. package/platforms/snapshots/threads-18.sha256 +1 -0
  197. package/platforms/snapshots/threads-18.txt +1 -0
  198. package/platforms/snapshots/threads-19.sha256 +1 -0
  199. package/platforms/snapshots/threads-19.txt +1 -0
  200. package/platforms/snapshots/tiktok-50.sha256 +1 -0
  201. package/platforms/snapshots/tiktok-50.txt +1 -0
  202. package/platforms/snapshots/tiktok-51.sha256 +1 -0
  203. package/platforms/snapshots/tiktok-51.txt +1 -0
  204. package/platforms/snapshots/x-5.sha256 +1 -0
  205. package/platforms/snapshots/x-5.txt +1 -0
  206. package/platforms/snapshots/x-6.sha256 +1 -0
  207. package/platforms/snapshots/x-6.txt +1 -0
  208. package/platforms/snapshots/x-7.sha256 +1 -0
  209. package/platforms/snapshots/x-7.txt +1 -0
  210. package/platforms/snapshots/x-8.sha256 +1 -0
  211. package/platforms/snapshots/x-8.txt +1 -0
  212. package/platforms/snapshots/x-9.sha256 +1 -0
  213. package/platforms/snapshots/x-9.txt +1 -0
  214. package/platforms/snapshots/youtube-shorts-40.sha256 +1 -0
  215. package/platforms/snapshots/youtube-shorts-40.txt +1 -0
  216. package/platforms/snapshots/youtube-shorts-41.sha256 +1 -0
  217. package/platforms/snapshots/youtube-shorts-41.txt +1 -0
  218. package/platforms/snapshots/youtube-shorts-42.sha256 +1 -0
  219. package/platforms/snapshots/youtube-shorts-42.txt +1 -0
  220. package/platforms/sources.yml +947 -0
  221. package/platforms/substack/guide.md +94 -0
  222. package/platforms/substack/pack.yml +116 -0
  223. package/platforms/threads/guide.md +93 -0
  224. package/platforms/threads/pack.yml +148 -0
  225. package/platforms/tiktok/guide.md +92 -0
  226. package/platforms/tiktok/pack.yml +129 -0
  227. package/platforms/x/guide.md +94 -0
  228. package/platforms/x/pack.yml +130 -0
  229. package/platforms/youtube-shorts/guide.md +92 -0
  230. package/platforms/youtube-shorts/pack.yml +138 -0
  231. package/providers/prices.yml +31 -0
  232. package/schemas/campaign.v2.json +26 -0
  233. package/schemas/manifest.v1.json +37 -0
  234. package/schemas/pack.schema.json +601 -0
  235. package/schemas/review.schema.json +31 -0
  236. package/skills/studio-reviewer/SKILL.md +13 -0
  237. package/skills/studio-updater/SKILL.md +8 -0
  238. package/skills/studio-video/SKILL.md +20 -0
  239. package/skills/studio-visual/SKILL.md +12 -0
  240. package/skills/studio-writer/SKILL.md +14 -0
  241. package/templates/README.md +7 -0
  242. package/templates/card.html +1 -0
  243. package/templates/carousel-closing.html +1 -0
  244. package/templates/carousel-content.html +1 -0
  245. package/templates/carousel-title.html +1 -0
  246. package/templates/code.html +1 -0
  247. package/templates/fonts/IBM-Plex-OFL.txt +93 -0
  248. package/templates/fonts/IBMPlexMono.woff2 +0 -0
  249. package/templates/fonts/IBMPlexSans.woff2 +0 -0
  250. package/templates/fonts/Space-Grotesk-OFL.txt +93 -0
  251. package/templates/fonts/SpaceGrotesk.woff2 +0 -0
  252. package/templates/poster.html +1 -0
  253. package/templates/quote.html +1 -0
  254. package/templates/thumbnail.html +1 -0
  255. package/test/fixtures/reviews/calibration.json +22 -0
  256. package/test/fixtures/reviews/grounding/cases.json +17 -0
package/dist/packs.js ADDED
@@ -0,0 +1,91 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { fileURLToPath } from "node:url";
3
+ import { join } from "node:path";
4
+ import { Ajv } from "ajv";
5
+ import { parse } from "yaml";
6
+ import { PLATFORM_IDS, UserError } from "./types.js";
7
+ const root = fileURLToPath(new URL("../", import.meta.url));
8
+ const platformDir = join(root, "platforms");
9
+ function readYaml(path) {
10
+ try {
11
+ return parse(readFileSync(path, "utf8"));
12
+ }
13
+ catch (error) {
14
+ throw new UserError(`${path}: ${error instanceof Error ? error.message : String(error)}`);
15
+ }
16
+ }
17
+ export function loadSources() {
18
+ const file = join(platformDir, "sources.yml");
19
+ const rows = readYaml(file);
20
+ if (!Array.isArray(rows))
21
+ throw new UserError(`${file}: / must be an array`);
22
+ const ids = new Set();
23
+ for (const [index, row] of rows.entries()) {
24
+ const validPlatform = [...PLATFORM_IDS, "cross-platform", "provider", "tool"].includes(row?.platform);
25
+ const detector = row?.detector;
26
+ const validDetector = detector && (detector.kind === "manual" ||
27
+ (detector.kind === "page-hash" && (detector.selector === undefined || typeof detector.selector === "string")) ||
28
+ (detector.kind === "git-path" && typeof detector.repo === "string" && typeof detector.path === "string" && (detector.branch === undefined || typeof detector.branch === "string")));
29
+ if (!row || typeof row.id !== "string" || !row.id || ids.has(row.id) || !validPlatform ||
30
+ typeof row.url !== "string" || typeof row.scope !== "string" || !validDetector ||
31
+ !Array.isArray(row.governs) || !row.governs.every((value) => typeof value === "string")) {
32
+ throw new UserError(`${file}: /${index} invalid source row`);
33
+ }
34
+ ids.add(row.id);
35
+ }
36
+ return rows;
37
+ }
38
+ export function loadPacks() {
39
+ const schemaFile = join(root, "schemas", "pack.schema.json");
40
+ let schema;
41
+ try {
42
+ schema = JSON.parse(readFileSync(schemaFile, "utf8"));
43
+ }
44
+ catch (error) {
45
+ throw new UserError(`${schemaFile}: ${error instanceof Error ? error.message : String(error)}`);
46
+ }
47
+ const validate = new Ajv({ allErrors: true }).compile(schema);
48
+ const sourceIds = new Set(loadSources().map((source) => source.id));
49
+ const packs = new Map();
50
+ for (const id of PLATFORM_IDS) {
51
+ const file = join(platformDir, id, "pack.yml");
52
+ const data = readYaml(file);
53
+ if (!validate(data)) {
54
+ const error = validate.errors?.[0];
55
+ throw new UserError(`${file}: ${error?.instancePath || "/"} ${error?.message ?? "invalid pack"}`);
56
+ }
57
+ const pack = data;
58
+ if (pack.id !== id)
59
+ throw new UserError(`${file}: /id must match directory ${id}`);
60
+ for (const [index, source] of pack.sources.entries()) {
61
+ if (!sourceIds.has(source))
62
+ throw new UserError(`${file}: /sources/${index} unknown source ${source}`);
63
+ }
64
+ const checkSources = (value, path) => {
65
+ if (!value || typeof value !== "object")
66
+ return;
67
+ if (Array.isArray(value)) {
68
+ value.forEach((item, index) => checkSources(item, `${path}/${index}`));
69
+ return;
70
+ }
71
+ for (const [key, item] of Object.entries(value)) {
72
+ if (key === "source" && typeof item === "string" && (!sourceIds.has(item) || !pack.sources.includes(item))) {
73
+ throw new UserError(`${file}: ${path}/source unknown or unlisted source ${item}`);
74
+ }
75
+ checkSources(item, `${path}/${key}`);
76
+ }
77
+ };
78
+ checkSources(pack, "");
79
+ packs.set(id, pack);
80
+ }
81
+ return packs;
82
+ }
83
+ export function loadPack(id) {
84
+ const pack = loadPacks().get(id);
85
+ if (!pack)
86
+ throw new UserError(`Unknown platform: ${id}`);
87
+ return pack;
88
+ }
89
+ export function knownValue(value) {
90
+ return value === undefined || value === "unknown" ? undefined : value.value;
91
+ }
package/dist/plan.js ADDED
@@ -0,0 +1,75 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { parse } from 'yaml';
4
+ import { PLATFORM_IDS, UserError } from "./types.js";
5
+ export function readPlan(projectDir) {
6
+ const path = join(projectDir, 'plan.yml');
7
+ let value;
8
+ try {
9
+ value = parse(readFileSync(path, 'utf8'));
10
+ }
11
+ catch (e) {
12
+ throw new UserError(`plan.yml: ${String(e)}`);
13
+ }
14
+ if (!Array.isArray(value))
15
+ throw new UserError(`plan.yml: expected an array, got ${JSON.stringify(value)}`);
16
+ const errors = [], seen = new Set();
17
+ const assets = new Map();
18
+ const types = ['text', 'thread', 'article', 'image', 'carousel', 'diagram', 'poster', 'logo', 'video', 'terminal-demo'];
19
+ const kinds = ['card', 'poster', 'carousel', 'logo', 'diagram', 'video', 'terminal-demo', 'illustration', 'voiceover'];
20
+ for (const [index, p] of value.entries()) {
21
+ const name = typeof p?.platform === 'string' ? p.platform : `plan[${index}]`;
22
+ const problem = (field, actual, expectation) => errors.push(`${name}.${field} ${JSON.stringify(actual) ?? 'undefined'} ${expectation}`);
23
+ if (!p || typeof p !== 'object' || Array.isArray(p)) {
24
+ errors.push(`${name} ${JSON.stringify(p)} must be an object`);
25
+ continue;
26
+ }
27
+ if (!PLATFORM_IDS.includes(p.platform))
28
+ problem('platform', p.platform, `is not one of ${PLATFORM_IDS.join(', ')}`);
29
+ if (seen.has(p.platform))
30
+ problem('platform', p.platform, 'is duplicated');
31
+ seen.add(p.platform);
32
+ if (!types.includes(p.type))
33
+ problem('type', p.type, `is not one of ${types.join(', ')}`);
34
+ if (typeof p.angle !== 'string' || !p.angle.trim())
35
+ problem('angle', p.angle, 'must be a nonempty string');
36
+ if (!Array.isArray(p.hooks) || p.hooks.length !== 3)
37
+ problem('hooks', p.hooks, 'must contain exactly three hooks');
38
+ else
39
+ p.hooks.forEach((hook, i) => { if (typeof hook !== 'string' || !hook.trim())
40
+ problem(`hooks[${i}]`, hook, 'must be a nonempty string'); });
41
+ if (!Array.isArray(p.assets)) {
42
+ problem('assets', p.assets, 'must be an array');
43
+ continue;
44
+ }
45
+ for (const [i, a] of p.assets.entries()) {
46
+ const field = `assets[${i}]`;
47
+ if (!a || typeof a !== 'object' || Array.isArray(a)) {
48
+ problem(field, a, 'must be an object');
49
+ continue;
50
+ }
51
+ if (typeof a.id !== 'string' || !/^[a-z0-9][a-z0-9-]*$/.test(a.id))
52
+ problem(`${field}.id`, a.id, 'must be a lowercase asset id');
53
+ if (!kinds.includes(a.kind))
54
+ problem(`${field}.kind`, a.kind, `is not one of ${kinds.join(', ')}`);
55
+ if (typeof a.brief !== 'string' || !a.brief.trim())
56
+ problem(`${field}.brief`, a.brief, 'must be a nonempty string');
57
+ if (a.aspect !== undefined && (typeof a.aspect !== 'string' || !a.aspect.trim()))
58
+ problem(`${field}.aspect`, a.aspect, 'must be a nonempty string');
59
+ if (typeof a.id === 'string') {
60
+ const prior = assets.get(a.id);
61
+ if (prior && prior.kind !== a.kind)
62
+ problem(`${field}.kind`, a.kind, `conflicts with shared asset ${a.id} kind ${JSON.stringify(prior.kind)}`);
63
+ if (prior && prior.aspect !== undefined && a.aspect !== undefined && prior.aspect !== a.aspect)
64
+ problem(`${field}.aspect`, a.aspect, `conflicts with shared asset ${a.id} aspect ${JSON.stringify(prior.aspect)}`);
65
+ if (!prior)
66
+ assets.set(a.id, { kind: a.kind, aspect: a.aspect });
67
+ else if (prior.aspect === undefined)
68
+ prior.aspect = a.aspect;
69
+ }
70
+ }
71
+ }
72
+ if (errors.length)
73
+ throw new UserError(errors.join('\n'));
74
+ return value;
75
+ }
package/dist/posts.js ADDED
@@ -0,0 +1,40 @@
1
+ import { existsSync, readdirSync, readFileSync } from 'node:fs';
2
+ import { basename, join } from 'node:path';
3
+ import { parse, stringify } from 'yaml';
4
+ import { PLATFORM_IDS, UserError } from "./types.js";
5
+ export function parsePost(path, text) {
6
+ const match = text.match(/^---\s*\r?\n([\s\S]*?)\r?\n---\s*(?:\r?\n|$)([\s\S]*)$/);
7
+ if (!match)
8
+ throw new UserError(`${path}: expected YAML frontmatter`);
9
+ let data;
10
+ try {
11
+ data = parse(match[1]);
12
+ }
13
+ catch {
14
+ throw new UserError(`${path}: invalid frontmatter`);
15
+ }
16
+ const platform = data?.platform ?? basename(path, '.md');
17
+ if (!PLATFORM_IDS.includes(platform) || !Array.isArray(data.evidence) || !data.evidence.every(v => typeof v === 'string') || !Array.isArray(data.media) || !data.media.every(v => v && typeof v === 'object' && typeof v.asset === 'string' && typeof v.file === 'string' && typeof v.alt === 'string' && ['image', 'video', 'document', 'gif'].includes(v.kind)) || (data.thread !== undefined && (!Array.isArray(data.thread) || !data.thread.every(v => typeof v === 'string'))) || (data.title !== undefined && typeof data.title !== 'string') || (data.disclosure !== undefined && (!data.disclosure || typeof data.disclosure !== 'object' || Array.isArray(data.disclosure))))
18
+ throw new UserError(`${path}: invalid post frontmatter`);
19
+ if (data.sponsored !== undefined && typeof data.sponsored !== 'boolean')
20
+ throw new UserError(`${path}: sponsored must be boolean`);
21
+ if (data.tags !== undefined && (!Array.isArray(data.tags) || !data.tags.every(v => typeof v === 'string')))
22
+ throw new UserError(`${path}: tags must be an array of strings`);
23
+ return { ...data, platform, body: match[2].trim(), path };
24
+ }
25
+ export function loadPosts(projectDir) {
26
+ const dir = join(projectDir, 'posts'), posts = new Map();
27
+ if (!existsSync(dir))
28
+ return posts;
29
+ for (const file of readdirSync(dir).filter(f => f.endsWith('.md')).sort()) {
30
+ const path = join(dir, file), post = parsePost(path, readFileSync(path, 'utf8'));
31
+ if (file !== `${post.platform}.md` || posts.has(post.platform))
32
+ throw new UserError(`${path}: platform does not match filename`);
33
+ posts.set(post.platform, post);
34
+ }
35
+ return posts;
36
+ }
37
+ export function serializePost(post) {
38
+ const { path: _path, body, ...frontmatter } = post;
39
+ return `---\n${stringify(frontmatter)}---\n\n${body.trim()}\n`;
40
+ }
@@ -0,0 +1,116 @@
1
+ import { createHash } from "node:crypto";
2
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
+ import { dirname, join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { parse } from "yaml";
6
+ import { loadEnv } from "../env.js";
7
+ import { UserError } from "../types.js";
8
+ import { recordAgentRun, reserve, settle } from "../budget/ledger.js";
9
+ export function price(model, provider, kind) {
10
+ const table = parse(readFileSync(fileURLToPath(new URL("../../providers/prices.yml", import.meta.url)), "utf8"));
11
+ const entry = table.models[model];
12
+ if (!entry || entry.provider !== provider || entry.kind !== kind)
13
+ throw new UserError(`No price for ${provider} ${model}`);
14
+ return entry;
15
+ }
16
+ export async function generateImage(opts) {
17
+ const { config, io, projectSlug, prompt, size, out, regen } = opts;
18
+ const provider = config.images.provider;
19
+ if (opts.referenceImages?.length) {
20
+ if (!config.providers.allowUpload)
21
+ throw new UserError("Reference image uploads are disabled");
22
+ throw new UserError("Reference image uploads are not supported by this adapter");
23
+ }
24
+ if (provider === "none")
25
+ throw new UserError("Set images.provider before generating images");
26
+ if (provider === "omp" && (!io.isTTY || !!io.env.CI))
27
+ throw new UserError("omp image generation requires an interactive terminal outside CI");
28
+ const dimensions = /^(\d+)x(\d+)$/.exec(size);
29
+ if (!dimensions || Number(dimensions[1]) < 1 || Number(dimensions[2]) < 1)
30
+ throw new UserError("Image size must be WIDTHxHEIGHT");
31
+ const width = Number(dimensions[1]), height = Number(dimensions[2]);
32
+ const aspect = width === height ? "1:1" : width > height ? "3:2" : "2:3";
33
+ const apiSize = aspect === "1:1" ? "1024x1024" : aspect === "3:2" ? "1536x1024" : "1024x1536";
34
+ if (prompt.length > 4000)
35
+ throw new UserError("Image prompt exceeds 4000 characters");
36
+ const model = config.images.model ?? (provider === "gemini" ? "gemini-nano-banana-2.1" : provider === "openai" ? "gpt-image-2" : "omp");
37
+ const promptHash = createHash("sha256").update(JSON.stringify({ prompt, size, provider, model })).digest("hex");
38
+ const cacheDir = join(config.root, "cache", "images"), cache = join(cacheDir, `${promptHash}.png`), meta = `${cache}.json`;
39
+ const license = provider === "gemini" ? "https://ai.google.dev/gemini-api/terms" : provider === "openai" ? "https://openai.com/policies/business-terms/" : "omp subscription terms";
40
+ mkdirSync(dirname(out), { recursive: true });
41
+ if (!regen && existsSync(cache) && existsSync(meta)) {
42
+ copyFileSync(cache, out);
43
+ const saved = JSON.parse(readFileSync(meta, "utf8"));
44
+ return { file: out, costUsd: saved.costUsd, provider, aiGenerated: true, model, promptHash, license };
45
+ }
46
+ let bytes, costUsd = null;
47
+ if (provider === "omp") {
48
+ io.out(`Generate an image interactively with omp for this prompt:\n${prompt}`);
49
+ const path = (await io.prompt("Path to the generated PNG: ")).trim();
50
+ bytes = readFileSync(path);
51
+ await recordAgentRun(config, { model, ms: 0, usd: null, projectSlug, provider: "omp", usage: { images: 1 } });
52
+ }
53
+ else {
54
+ const amount = price(model, provider, "image").upperUsd;
55
+ if (!amount || !Number.isFinite(amount))
56
+ throw new UserError(`Invalid price for ${model}`);
57
+ const env = loadEnv(config.root, io.env, io.keychain), key = env[provider === "gemini" ? "GEMINI_API_KEY" : "OPENAI_API_KEY"];
58
+ if (!key)
59
+ throw new UserError(`Missing ${provider === "gemini" ? "GEMINI_API_KEY" : "OPENAI_API_KEY"}`);
60
+ const id = await reserve(config, amount, { projectSlug, provider, model });
61
+ const gemini = provider === "gemini";
62
+ let response;
63
+ try {
64
+ response = await io.fetch(gemini ? `https://generativelanguage.googleapis.com/v1beta/models/${encodeURIComponent(model)}:generateContent` : "https://api.openai.com/v1/images/generations", {
65
+ method: "POST", headers: { "content-type": "application/json", ...(gemini ? { "x-goog-api-key": key } : { authorization: `Bearer ${key}` }) },
66
+ body: JSON.stringify(gemini ? { contents: [{ parts: [{ text: prompt }] }], generationConfig: { responseModalities: ["IMAGE"], imageConfig: { aspectRatio: aspect } } } : { model, prompt, size: apiSize, quality: "medium", output_format: "png", n: 1 }), signal: AbortSignal.timeout(120000),
67
+ });
68
+ }
69
+ catch (error) {
70
+ io.out(`Warning: image request may have been billed; retaining $${amount} reservation`);
71
+ await settle(config.root, id, amount);
72
+ throw error;
73
+ }
74
+ if (!response.ok) {
75
+ const rejected = response.status >= 400 && response.status < 500;
76
+ if (!rejected)
77
+ io.out(`Warning: image request may have been billed; retaining $${amount} reservation`);
78
+ await settle(config.root, id, rejected ? 0 : amount);
79
+ throw new UserError(`${provider} image request failed (${response.status})`);
80
+ }
81
+ let usage;
82
+ try {
83
+ const json = await response.json();
84
+ const object = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
85
+ const root = object(json);
86
+ const candidates = Array.isArray(root.candidates) ? root.candidates : [];
87
+ const first = Array.isArray(root.data) ? object(root.data[0]) : {};
88
+ const parts = candidates.flatMap((candidate) => {
89
+ const value = object(object(candidate).content).parts;
90
+ return Array.isArray(value) ? value : [];
91
+ });
92
+ const encoded = gemini ? parts.map((part) => object(object(part).inlineData).data).find((data) => typeof data === "string" && data.length > 0) : first.b64_json;
93
+ if (typeof encoded !== "string" || !encoded)
94
+ throw new UserError("Provider returned no image");
95
+ bytes = Buffer.from(encoded, "base64");
96
+ if (!bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])))
97
+ throw new UserError("Provider returned a non-PNG image");
98
+ // The API does not provide a reliable dollar total; retain the priced upper bound.
99
+ costUsd = amount;
100
+ usage = root.usageMetadata ?? root.usage;
101
+ }
102
+ catch (error) {
103
+ io.out(`Warning: image response could not be used; retaining $${amount} reservation`);
104
+ await settle(config.root, id, amount);
105
+ throw error;
106
+ }
107
+ await settle(config.root, id, amount, usage);
108
+ }
109
+ if (!bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])))
110
+ throw new UserError("Provider returned a non-PNG image");
111
+ mkdirSync(cacheDir, { recursive: true, mode: 0o700 });
112
+ writeFileSync(cache, bytes, { mode: 0o600 });
113
+ writeFileSync(meta, JSON.stringify({ provider, model, promptHash, costUsd, aiGenerated: true, license }), { mode: 0o600 });
114
+ writeFileSync(out, bytes, { mode: 0o600 });
115
+ return { file: out, costUsd, provider, aiGenerated: true, model, promptHash, license };
116
+ }
@@ -0,0 +1,55 @@
1
+ import { createHash } from "node:crypto";
2
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
+ import { dirname, join } from "node:path";
4
+ import { loadEnv } from "../env.js";
5
+ import { UserError } from "../types.js";
6
+ import { reserve, settle } from "../budget/ledger.js";
7
+ import { price } from "./images.js";
8
+ export async function generateVoice(opts) {
9
+ const { config, io, projectSlug, text, out } = opts;
10
+ if (config.voice.provider !== "openai")
11
+ throw new UserError("Set voice.provider to openai to generate speech");
12
+ if (!text || text.length > 4096)
13
+ throw new UserError("Voice text must contain 1–4096 characters");
14
+ const model = config.voice.model ?? "tts-1", rate = price(model, "openai", "voice").usdPerCharacter;
15
+ if (!rate || !Number.isFinite(rate))
16
+ throw new UserError(`Invalid price for ${model}`);
17
+ const voice = config.voice.voice ?? "alloy";
18
+ const promptHash = createHash("sha256").update(JSON.stringify({ text, model, voice })).digest("hex");
19
+ const cacheDir = join(config.root, "cache", "voice"), cache = join(cacheDir, `${promptHash}.wav`), meta = `${cache}.json`;
20
+ const license = "https://openai.com/policies/business-terms/";
21
+ if (!opts.regen && existsSync(cache) && existsSync(meta)) {
22
+ const saved = JSON.parse(readFileSync(meta, "utf8"));
23
+ mkdirSync(dirname(out), { recursive: true });
24
+ copyFileSync(cache, out);
25
+ return { file: out, costUsd: saved.costUsd, provider: "openai", model, promptHash, license, aiGenerated: true };
26
+ }
27
+ const key = loadEnv(config.root, io.env, io.keychain).OPENAI_API_KEY;
28
+ if (!key)
29
+ throw new UserError("Missing OPENAI_API_KEY");
30
+ const costUsd = Array.from(text).length * rate;
31
+ const id = await reserve(config, costUsd, { projectSlug, provider: "openai", model });
32
+ let bytes, rejected = false;
33
+ try {
34
+ const response = await io.fetch("https://api.openai.com/v1/audio/speech", { method: "POST", headers: { authorization: `Bearer ${key}`, "content-type": "application/json" }, body: JSON.stringify({ model, input: text, voice, response_format: "wav" }), signal: AbortSignal.timeout(120000) });
35
+ rejected = response.status >= 400 && response.status < 500;
36
+ if (!response.ok)
37
+ throw new UserError(`OpenAI speech request failed (${response.status})`);
38
+ bytes = Buffer.from(await response.arrayBuffer());
39
+ if (bytes.length < 12 || bytes.toString("ascii", 0, 4) !== "RIFF" || bytes.toString("ascii", 8, 12) !== "WAVE")
40
+ throw new UserError("Provider returned invalid WAV audio");
41
+ }
42
+ catch (error) {
43
+ if (!rejected)
44
+ io.out(`Warning: speech request may have been billed; retaining $${costUsd} reservation`);
45
+ await settle(config.root, id, rejected ? 0 : costUsd);
46
+ throw error;
47
+ }
48
+ await settle(config.root, id, costUsd, { characters: Array.from(text).length });
49
+ mkdirSync(cacheDir, { recursive: true, mode: 0o700 });
50
+ writeFileSync(cache, bytes, { mode: 0o600 });
51
+ writeFileSync(meta, JSON.stringify({ costUsd, provider: "openai", model, promptHash, license, aiGenerated: true }), { mode: 0o600 });
52
+ mkdirSync(dirname(out), { recursive: true });
53
+ writeFileSync(out, bytes, { mode: 0o600 });
54
+ return { file: out, costUsd, provider: "openai", model, promptHash, license, aiGenerated: true };
55
+ }
@@ -0,0 +1,21 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ /**
5
+ * Path to an npm dependency's bin script, found the way Node resolves packages: the nearest
6
+ * `node_modules/<pkg>` walking up from this file. npm may nest the dependency inside blast-studio
7
+ * (source checkout, global install) or hoist it into the consumer's node_modules (local install).
8
+ * Reads package.json from disk because some packages (mermaid-cli) don't export it.
9
+ */
10
+ export function packageBin(pkg, bin) {
11
+ for (let dir = dirname(fileURLToPath(import.meta.url));; dir = dirname(dir)) {
12
+ const manifest = join(dir, "node_modules", pkg, "package.json");
13
+ if (existsSync(manifest)) {
14
+ const field = JSON.parse(readFileSync(manifest, "utf8")).bin;
15
+ const relative = typeof field === "string" ? field : field?.[bin];
16
+ return relative ? join(dirname(manifest), relative) : null;
17
+ }
18
+ if (dir === dirname(dir))
19
+ return null;
20
+ }
21
+ }
@@ -0,0 +1,102 @@
1
+ import { existsSync, mkdirSync, mkdtempSync, rmSync, statSync, symlinkSync } from "node:fs";
2
+ import { homedir, tmpdir } from "node:os";
3
+ import { join, resolve } from "node:path";
4
+ import { agentEnv, sandboxCommand } from "../agent-env.js";
5
+ import { UserError } from "../types.js";
6
+ const guidance = {
7
+ ffmpeg: "brew install ffmpeg (or your OS package manager)",
8
+ ffprobe: "brew install ffmpeg (or your OS package manager)",
9
+ vhs: "brew install vhs",
10
+ hyperframes: "npm install (HyperFrames is an optional dependency)",
11
+ };
12
+ export async function runTool(io, name, command, args, cwd, sandbox) {
13
+ const temp = mkdtempSync(join(tmpdir(), "bstudio-tool-"));
14
+ try {
15
+ const configured = Number(io.env.BSTUDIO_RENDER_TIMEOUT_MS);
16
+ const timeoutMs = Number.isFinite(configured) && configured > 0 ? configured : (name === "vhs" || name === "hyperframes" ? 1_800_000 : 120_000);
17
+ const env = agentEnv(io, { temp, home: temp, minimal: true });
18
+ const readDirs = [], writeDirs = [];
19
+ let managedCache;
20
+ if (name === "hyperframes") {
21
+ const home = io.env.HOME ?? homedir();
22
+ const managed = resolve(io.cwd, io.env.HYPERFRAMES_CACHE_DIR || join(home, ".cache/hyperframes"));
23
+ const puppeteer = join(home, ".cache/puppeteer");
24
+ if (existsSync(home)) {
25
+ mkdirSync(managed, { recursive: true, mode: 0o700 });
26
+ managedCache = managed;
27
+ env.HYPERFRAMES_CACHE_DIR = managed;
28
+ readDirs.push(managed);
29
+ if (sandbox?.config.agent.sandbox === "on") {
30
+ const locks = join(managed, "locks");
31
+ mkdirSync(locks, { recursive: true, mode: 0o700 });
32
+ writeDirs.push(locks);
33
+ }
34
+ }
35
+ if (existsSync(puppeteer)) {
36
+ mkdirSync(join(temp, ".cache"));
37
+ symlinkSync(puppeteer, join(temp, ".cache/puppeteer"), "dir");
38
+ readDirs.push(puppeteer);
39
+ }
40
+ }
41
+ const privateCache = process.platform === "linux" && managedCache ? { source: managedCache, target: "/.bstudio-hyperframes-cache" } : undefined;
42
+ const wrapped = sandbox ? sandboxCommand(io, sandbox.config, sandbox.workspace, temp, command, args, { render: true, loopback: name === "vhs" || name === "hyperframes", pty: name === "vhs", readDirs, writeDirs, privateCache }) : { command, args };
43
+ // The synthetic root prevents unmapped host-root owners from invalidating the pinned cache.
44
+ if (privateCache && wrapped.command !== command)
45
+ env.HYPERFRAMES_CACHE_DIR = privateCache.target;
46
+ if (name === "hyperframes" && wrapped.command !== command)
47
+ env.HYPERFRAMES_CHROME_SANDBOX = "0";
48
+ if (name === "vhs" && wrapped.command !== command)
49
+ env.VHS_NO_SANDBOX = "1";
50
+ return await io.run(wrapped.command, wrapped.args, { cwd, env, timeoutMs });
51
+ }
52
+ catch (error) {
53
+ throw new UserError(`${name} failed or is unavailable; run bstudio doctor; install: ${guidance[name]}. ${String(error)}`);
54
+ }
55
+ finally {
56
+ rmSync(temp, { recursive: true, force: true });
57
+ }
58
+ }
59
+ export async function probeMedia(file, io) {
60
+ const text = await runTool(io, "ffprobe", "ffprobe", ["-v", "error", "-show_entries", "stream=width,height:format=duration", "-of", "json", file]);
61
+ const data = JSON.parse(text);
62
+ const video = data.streams?.find(s => s.width && s.height);
63
+ const seconds = Number(data.format?.duration);
64
+ if (!video?.width || !video.height || !Number.isFinite(seconds) || seconds <= 0)
65
+ throw new UserError(`ffprobe could not determine video dimensions and duration: ${file}`);
66
+ return { width: video.width, height: video.height, seconds, bytes: statSync(file).size };
67
+ }
68
+ /** FFmpeg's filter parser has its own escaping, independent of shell quoting. */
69
+ function filterPath(path) {
70
+ return path.replace(/\\/g, "\\\\").replace(/'/g, "'\\''").replace(/:/g, "\\:").replace(/,/g, "\\,").replace(/\[/g, "\\[").replace(/\]/g, "\\]");
71
+ }
72
+ export async function encodeVideo(input, output, io, options = {}) {
73
+ const args = ["-y", "-i", input];
74
+ if (options.voiceover) {
75
+ const streams = await runTool(io, "ffprobe", "ffprobe", ["-v", "error", "-select_streams", "a", "-show_entries", "stream=index", "-of", "json", input]);
76
+ const hasAudio = (JSON.parse(streams).streams ?? []).length > 0;
77
+ args.push("-i", options.voiceover, "-map", "0:v:0");
78
+ if (hasAudio)
79
+ args.push("-filter_complex", "[1:a]apad[voice];[0:a][voice]amix=inputs=2:duration=first:normalize=0[audio]", "-map", "[audio]");
80
+ else
81
+ args.push("-map", "1:a:0", "-af", "apad", "-shortest");
82
+ }
83
+ if (options.captions)
84
+ args.push("-vf", `subtitles=filename='${filterPath(options.captions)}'`);
85
+ args.push("-c:v", options.captions ? "libx264" : "copy", ...(options.captions ? ["-pix_fmt", "yuv420p"] : []), "-movflags", "+faststart", "-c:a", "aac", output);
86
+ try {
87
+ await runTool(io, "ffmpeg", "ffmpeg", args);
88
+ }
89
+ catch (error) {
90
+ if (options.captions && /No such filter: '?subtitles'?|filter not found/i.test(String(error))) {
91
+ throw new UserError("FFmpeg lacks the subtitles filter (libass); install a libass-enabled FFmpeg, e.g. brew install ffmpeg-full, and run bstudio doctor");
92
+ }
93
+ throw error;
94
+ }
95
+ }
96
+ export async function extractFrames(input, files, seconds, io) {
97
+ for (let i = 0; i < files.length; i++) {
98
+ const at = seconds * (i + 1) / (files.length + 1);
99
+ // GIF duration includes the last frame's display delay, which may extend past its last timestamp.
100
+ await runTool(io, "ffmpeg", "ffmpeg", ["-y", "-i", input, "-vf", `tpad=stop_mode=clone:stop_duration=${seconds}`, "-ss", String(at), "-frames:v", "1", "-update", "1", files[i]]);
101
+ }
102
+ }
@@ -0,0 +1,109 @@
1
+ export const defaultZone = { top: .05, bottom: .05, left: .05, right: .05 };
2
+ /** Combine the independently required insets of all destinations sharing an output. */
3
+ export function combinedZone(packs, kind, vertical = true) {
4
+ const zone = { top: 0, bottom: 0, left: 0, right: 0 };
5
+ const descriptions = new Set();
6
+ for (const pack of packs) {
7
+ const sourced = vertical || kind === "image" ? pack?.safeZones?.[kind] : undefined;
8
+ const value = sourced && sourced !== "unknown" ? sourced.value : defaultZone;
9
+ descriptions.add(sourced && sourced !== "unknown" ? `${pack.name} zone (${sourced.source})` : `${pack?.name ?? "Unknown platform"} default 5% margin`);
10
+ for (const side of ["top", "bottom", "left", "right"])
11
+ zone[side] = Math.max(zone[side], value[side]);
12
+ }
13
+ if (!packs.length)
14
+ return { zone: { ...defaultZone }, description: "default 5% margin" };
15
+ return { zone, description: [...descriptions].join(", ") };
16
+ }
17
+ /** Measure actual rendered text, not bounding boxes of its containers. */
18
+ export async function measureText(page, inset = defaultZone) {
19
+ const results = await Promise.all(page.frames().map(frame => frame.evaluate((safeInset) => {
20
+ const parse = (value) => {
21
+ const m = value.match(/^rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)(?:\s*[,/]\s*([\d.]+%?))?\s*\)$/);
22
+ if (!m)
23
+ return null;
24
+ return [+m[1], +m[2], +m[3], m[4] ? (m[4].endsWith('%') ? parseFloat(m[4]) / 100 : +m[4]) : 1];
25
+ };
26
+ const over = (a, b) => {
27
+ const alpha = a[3] + b[3] * (1 - a[3]);
28
+ return alpha ? [0, 1, 2].map(i => (a[i] * a[3] + b[i] * b[3] * (1 - a[3])) / alpha).concat(alpha) : [0, 0, 0, 0];
29
+ };
30
+ const luminance = (c) => [0, 1, 2].map(i => { const v = c[i] / 255; return v <= .04045 ? v / 12.92 : ((v + .055) / 1.055) ** 2.4; }).reduce((s, v, i) => s + v * [0.2126, 0.7152, 0.0722][i], 0);
31
+ const nodes = [];
32
+ const unmeasurable = [];
33
+ for (const el of document.querySelectorAll('canvas, img')) {
34
+ const style = getComputedStyle(el), rect = el.getBoundingClientRect();
35
+ if (style.display === 'none' || style.visibility !== 'visible' || +style.opacity === 0 || !rect.width || !rect.height)
36
+ continue;
37
+ if (el.tagName === 'CANVAS')
38
+ unmeasurable.push('canvas');
39
+ else if (el instanceof HTMLImageElement && (/\.svg(?:[?#]|$)/i.test(el.currentSrc) || /^data:image\/svg\+xml[;,]/i.test(el.currentSrc)))
40
+ unmeasurable.push('SVG image');
41
+ }
42
+ const entries = [];
43
+ const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
44
+ while (walker.nextNode()) {
45
+ const node = walker.currentNode, text = node.textContent?.trim(), el = node.parentElement;
46
+ if (!text || !el)
47
+ continue;
48
+ const range = document.createRange();
49
+ range.selectNodeContents(node);
50
+ entries.push({ text, el, style: getComputedStyle(el), rects: [...range.getClientRects()] });
51
+ }
52
+ for (const el of document.querySelectorAll('*'))
53
+ for (const pseudo of ['::before', '::after']) {
54
+ const style = getComputedStyle(el, pseudo), content = style.content;
55
+ if (!content || content === 'none' || content === 'normal')
56
+ continue;
57
+ const text = [...content.matchAll(/"((?:\\.|[^"\\])*)"/g)].map(m => m[1].replace(/\\(["\\])/g, '$1')).join('');
58
+ if (text.trim())
59
+ entries.push({ text: text.trim(), el, style, rects: [el.getBoundingClientRect()] });
60
+ }
61
+ for (const { text, el, style, rects: allRects } of entries) {
62
+ if (style.display === 'none' || style.visibility !== 'visible' || +style.opacity === 0)
63
+ continue;
64
+ const rects = allRects.filter(r => r.width > 0 && r.height > 0);
65
+ if (!rects.length)
66
+ continue;
67
+ let bg = [0, 0, 0, 0];
68
+ let unknown = false;
69
+ for (let p = el; p; p = p.parentElement) {
70
+ const s = getComputedStyle(p);
71
+ if (s.backgroundImage !== 'none') {
72
+ unknown = true;
73
+ break;
74
+ }
75
+ const c = parse(s.backgroundColor);
76
+ if (!c) {
77
+ unknown = true;
78
+ break;
79
+ }
80
+ bg = over(bg, c);
81
+ if (bg[3] >= .999)
82
+ break;
83
+ }
84
+ bg = over(bg, [255, 255, 255, 1]);
85
+ const fg = parse(style.color);
86
+ let contrast = null;
87
+ if (!unknown && fg) {
88
+ const a = luminance(over(fg, bg));
89
+ const b = luminance(bg);
90
+ contrast = (Math.max(a, b) + .05) / (Math.min(a, b) + .05);
91
+ }
92
+ const slide = el.closest('.slide');
93
+ const bounds = slide?.getBoundingClientRect() ?? { left: 0, top: 0, width: innerWidth, height: innerHeight };
94
+ const outside = (r, box, inset) => r.left < box.left + box.width * inset.left - .5 || r.right > box.left + box.width * (1 - inset.right) + .5 || r.top < box.top + box.height * inset.top - .5 || r.bottom > box.top + box.height * (1 - inset.bottom) + .5;
95
+ let clipped = false;
96
+ for (let p = el; p && p !== document.body && !clipped; p = p.parentElement) {
97
+ const s = getComputedStyle(p);
98
+ if (s.overflowX !== 'visible' || s.overflowY !== 'visible')
99
+ clipped = rects.some(r => outside(r, p.getBoundingClientRect(), { top: 0, bottom: 0, left: 0, right: 0 }));
100
+ }
101
+ const overflow = clipped || rects.some(r => outside(r, bounds, { top: 0, bottom: 0, left: 0, right: 0 }));
102
+ const edge = !overflow && rects.some(r => outside(r, bounds, safeInset));
103
+ nodes.push({ text, fontPx: parseFloat(style.fontSize), bold: Number(style.fontWeight) >= 700 || style.fontWeight === 'bold', contrast, overflow, edge });
104
+ }
105
+ return { nodes, unmeasurable };
106
+ }, inset)));
107
+ const nodes = results.flatMap(result => result.nodes);
108
+ return { minFontPx: nodes.length ? Math.min(...nodes.map(n => n.fontPx)) : null, minContrast: nodes.some(n => n.contrast === null) ? null : nodes.length ? Math.min(...nodes.map(n => n.contrast)) : null, overflow: nodes.some(n => n.overflow), edge: nodes.some(n => n.edge), nodes, unmeasurable: [...new Set(results.flatMap(result => result.unmeasurable))] };
109
+ }