@open-take/compositor 0.5.2 → 0.6.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 (439) hide show
  1. package/dist/cdp-CzT5BKNY.js +3 -0
  2. package/dist/cdp-QXbQfXna.js +373 -0
  3. package/dist/cdp-QXbQfXna.js.map +1 -0
  4. package/dist/index.d.ts +4327 -195
  5. package/dist/index.d.ts.map +1 -1
  6. package/dist/index.js +26282 -160
  7. package/dist/index.js.map +1 -1
  8. package/dist/server-841PMF2H.js +163 -0
  9. package/dist/server-841PMF2H.js.map +1 -0
  10. package/dist/server-C2aVv4-t.js +3 -0
  11. package/kit/audio.mjs +2366 -0
  12. package/kit/camera.js +587 -0
  13. package/kit/cursor.js +264 -0
  14. package/kit/cut.js +427 -0
  15. package/kit/draw.js +346 -0
  16. package/kit/look.js +589 -0
  17. package/kit/map.js +170 -0
  18. package/kit/media.js +3568 -0
  19. package/kit/motion.js +1115 -0
  20. package/kit/seams.js +1006 -0
  21. package/kit/stage.js +923 -0
  22. package/kit/time.js +812 -0
  23. package/kit/world.js +1072 -0
  24. package/package.json +7 -3
  25. package/src/ffmpeg.ts +63 -0
  26. package/src/film/beats.ts +1285 -0
  27. package/src/film/carry.ts +221 -0
  28. package/src/film/changes.ts +330 -0
  29. package/src/film/check.ts +996 -0
  30. package/src/film/clock.ts +2530 -0
  31. package/src/film/components-probe.ts +809 -0
  32. package/src/film/components.ts +1566 -0
  33. package/src/film/frames.ts +389 -0
  34. package/src/film/gallery.ts +3276 -0
  35. package/src/film/kit.ts +515 -0
  36. package/src/film/layout.ts +701 -0
  37. package/src/film/listen.ts +1979 -0
  38. package/src/film/look.ts +3829 -0
  39. package/src/film/materials.ts +976 -0
  40. package/src/film/moving.ts +248 -0
  41. package/src/film/part-files.ts +729 -0
  42. package/src/film/picture.ts +74 -0
  43. package/src/film/probe-text.ts +843 -0
  44. package/src/film/probe.ts +3456 -0
  45. package/src/film/provenance.ts +596 -0
  46. package/src/film/render.ts +2447 -0
  47. package/src/film/report.ts +1631 -0
  48. package/src/film/sheet.ts +156 -0
  49. package/src/film/study-declared.ts +123 -0
  50. package/src/film/study-picture.ts +791 -0
  51. package/src/film/study-sound.ts +416 -0
  52. package/src/film/study.ts +864 -0
  53. package/src/film/tuning.ts +155 -0
  54. package/src/film/viewer.ts +174 -0
  55. package/src/html/cdp.ts +575 -0
  56. package/src/html/server.ts +208 -0
  57. package/src/index.ts +202 -0
  58. package/src/launch-render.ts +3 -2
  59. package/src/math.ts +3 -3
  60. package/src/mjpeg-matroska.ts +228 -0
  61. package/src/render.ts +6 -4
  62. package/src/state-diff.ts +215 -0
  63. package/src/state-index.ts +99 -0
  64. package/src/types.ts +59 -1
  65. package/starter/PLAN.md +84 -0
  66. package/starter/START.md +460 -0
  67. package/starter/lib/anim.js +760 -0
  68. package/starter/lib/devices.js +1402 -0
  69. package/starter/lib/handoff.js +421 -0
  70. package/starter/lib/hud.js +1879 -0
  71. package/starter/lib/measure.mjs +154 -0
  72. package/starter/lib/moves.js +1095 -0
  73. package/starter/lib/palette.mjs +803 -0
  74. package/starter/lib/physics-seeds.mjs +198 -0
  75. package/starter/lib/physics.js +738 -0
  76. package/starter/lib/sampler.mjs +242 -0
  77. package/starter/lib/solid.js +727 -0
  78. package/starter/lib/space.js +1227 -0
  79. package/starter/lib/swarm.js +1398 -0
  80. package/starter/reference/motion.md +276 -0
  81. package/starter/reference/structure.md +466 -0
  82. package/starter/reference/travel/motion.md +433 -0
  83. package/starter/reference/travel/sound.md +241 -0
  84. package/starter/reference/travel/structure.md +518 -0
  85. package/starter/samples/NOTICE.txt +55 -0
  86. package/starter/samples/celli/celli_24_1.opus +0 -0
  87. package/starter/samples/celli/celli_24_3.opus +0 -0
  88. package/starter/samples/celli/celli_28_1.opus +0 -0
  89. package/starter/samples/celli/celli_28_3.opus +0 -0
  90. package/starter/samples/celli/celli_31_1.opus +0 -0
  91. package/starter/samples/celli/celli_31_3.opus +0 -0
  92. package/starter/samples/celli/celli_35_1.opus +0 -0
  93. package/starter/samples/celli/celli_35_3.opus +0 -0
  94. package/starter/samples/celli/celli_38_1.opus +0 -0
  95. package/starter/samples/celli/celli_38_3.opus +0 -0
  96. package/starter/samples/celli/celli_41_1.opus +0 -0
  97. package/starter/samples/celli/celli_41_3.opus +0 -0
  98. package/starter/samples/celli/celli_45_1.opus +0 -0
  99. package/starter/samples/celli/celli_45_3.opus +0 -0
  100. package/starter/samples/celli/celli_48_1.opus +0 -0
  101. package/starter/samples/celli/celli_48_3.opus +0 -0
  102. package/starter/samples/celli/celli_52_1.opus +0 -0
  103. package/starter/samples/celli/celli_52_3.opus +0 -0
  104. package/starter/samples/celli/celli_55_1.opus +0 -0
  105. package/starter/samples/celli/celli_55_3.opus +0 -0
  106. package/starter/samples/celli/celli_59_1.opus +0 -0
  107. package/starter/samples/celli/celli_59_3.opus +0 -0
  108. package/starter/samples/celli/celli_62_1.opus +0 -0
  109. package/starter/samples/celli/celli_62_3.opus +0 -0
  110. package/starter/samples/celli/celli_65_1.opus +0 -0
  111. package/starter/samples/celli/celli_65_3.opus +0 -0
  112. package/starter/samples/crash/crash_f_1.flac +0 -0
  113. package/starter/samples/crash/crash_fff_1.flac +0 -0
  114. package/starter/samples/ebass/ebass_0_x.flac +0 -0
  115. package/starter/samples/ebass/ebass_10_x.flac +0 -0
  116. package/starter/samples/ebass/ebass_11_x.flac +0 -0
  117. package/starter/samples/ebass/ebass_1_x.flac +0 -0
  118. package/starter/samples/ebass/ebass_2_x.flac +0 -0
  119. package/starter/samples/ebass/ebass_3_x.flac +0 -0
  120. package/starter/samples/ebass/ebass_4_x.flac +0 -0
  121. package/starter/samples/ebass/ebass_5_x.flac +0 -0
  122. package/starter/samples/ebass/ebass_6_x.flac +0 -0
  123. package/starter/samples/ebass/ebass_7_x.flac +0 -0
  124. package/starter/samples/ebass/ebass_8_x.flac +0 -0
  125. package/starter/samples/ebass/ebass_9_x.flac +0 -0
  126. package/starter/samples/ek_clap/ek_clap_1_1.flac +0 -0
  127. package/starter/samples/ek_hat/ek_hat_1_1.flac +0 -0
  128. package/starter/samples/ek_hat/ek_hat_1_2.flac +0 -0
  129. package/starter/samples/ek_kick/ek_kick_1_1.flac +0 -0
  130. package/starter/samples/ek_kick/ek_kick_1_2.flac +0 -0
  131. package/starter/samples/glock/glock_67_x.flac +0 -0
  132. package/starter/samples/glock/glock_72_x.flac +0 -0
  133. package/starter/samples/glock/glock_79_x.flac +0 -0
  134. package/starter/samples/glock/glock_84_x.flac +0 -0
  135. package/starter/samples/glock/glock_91_x.flac +0 -0
  136. package/starter/samples/glock/glock_96_x.flac +0 -0
  137. package/starter/samples/harp/harp_101_f.opus +0 -0
  138. package/starter/samples/harp/harp_28_f.opus +0 -0
  139. package/starter/samples/harp/harp_31_mp.opus +0 -0
  140. package/starter/samples/harp/harp_35_mf.opus +0 -0
  141. package/starter/samples/harp/harp_38_mf.opus +0 -0
  142. package/starter/samples/harp/harp_41_mf.opus +0 -0
  143. package/starter/samples/harp/harp_45_mf.opus +0 -0
  144. package/starter/samples/harp/harp_48_mf.opus +0 -0
  145. package/starter/samples/harp/harp_52_mf.opus +0 -0
  146. package/starter/samples/harp/harp_55_mf.opus +0 -0
  147. package/starter/samples/harp/harp_59_mf.opus +0 -0
  148. package/starter/samples/harp/harp_62_mf.opus +0 -0
  149. package/starter/samples/harp/harp_65_mf.opus +0 -0
  150. package/starter/samples/harp/harp_69_mf.opus +0 -0
  151. package/starter/samples/harp/harp_72_mf.opus +0 -0
  152. package/starter/samples/harp/harp_76_mf.opus +0 -0
  153. package/starter/samples/harp/harp_79_mf.opus +0 -0
  154. package/starter/samples/harp/harp_83_mf.opus +0 -0
  155. package/starter/samples/harp/harp_86_mf.opus +0 -0
  156. package/starter/samples/harp/harp_89_mf.opus +0 -0
  157. package/starter/samples/harp/harp_93_mf.opus +0 -0
  158. package/starter/samples/harp/harp_95_mf.opus +0 -0
  159. package/starter/samples/harp/harp_98_f.opus +0 -0
  160. package/starter/samples/manifest.json +2951 -0
  161. package/starter/samples/marimba/marimba_29_x.flac +0 -0
  162. package/starter/samples/marimba/marimba_36_x.flac +0 -0
  163. package/starter/samples/marimba/marimba_43_x.flac +0 -0
  164. package/starter/samples/marimba/marimba_47_x.flac +0 -0
  165. package/starter/samples/marimba/marimba_53_x.flac +0 -0
  166. package/starter/samples/marimba/marimba_60_x.flac +0 -0
  167. package/starter/samples/marimba/marimba_67_x.flac +0 -0
  168. package/starter/samples/marimba/marimba_71_x.flac +0 -0
  169. package/starter/samples/marimba/marimba_77_x.flac +0 -0
  170. package/starter/samples/marimba/marimba_84_x.flac +0 -0
  171. package/starter/samples/piano/piano_102_12.opus +0 -0
  172. package/starter/samples/piano/piano_102_16.opus +0 -0
  173. package/starter/samples/piano/piano_102_4.opus +0 -0
  174. package/starter/samples/piano/piano_102_8.opus +0 -0
  175. package/starter/samples/piano/piano_105_12.opus +0 -0
  176. package/starter/samples/piano/piano_105_16.opus +0 -0
  177. package/starter/samples/piano/piano_105_4.opus +0 -0
  178. package/starter/samples/piano/piano_105_8.opus +0 -0
  179. package/starter/samples/piano/piano_108_12.opus +0 -0
  180. package/starter/samples/piano/piano_108_16.opus +0 -0
  181. package/starter/samples/piano/piano_108_4.opus +0 -0
  182. package/starter/samples/piano/piano_108_8.opus +0 -0
  183. package/starter/samples/piano/piano_21_12.opus +0 -0
  184. package/starter/samples/piano/piano_21_16.opus +0 -0
  185. package/starter/samples/piano/piano_21_4.opus +0 -0
  186. package/starter/samples/piano/piano_21_8.opus +0 -0
  187. package/starter/samples/piano/piano_24_12.opus +0 -0
  188. package/starter/samples/piano/piano_24_16.opus +0 -0
  189. package/starter/samples/piano/piano_24_4.opus +0 -0
  190. package/starter/samples/piano/piano_24_8.opus +0 -0
  191. package/starter/samples/piano/piano_27_12.opus +0 -0
  192. package/starter/samples/piano/piano_27_16.opus +0 -0
  193. package/starter/samples/piano/piano_27_4.opus +0 -0
  194. package/starter/samples/piano/piano_27_8.opus +0 -0
  195. package/starter/samples/piano/piano_30_12.opus +0 -0
  196. package/starter/samples/piano/piano_30_16.opus +0 -0
  197. package/starter/samples/piano/piano_30_4.opus +0 -0
  198. package/starter/samples/piano/piano_30_8.opus +0 -0
  199. package/starter/samples/piano/piano_33_12.opus +0 -0
  200. package/starter/samples/piano/piano_33_16.opus +0 -0
  201. package/starter/samples/piano/piano_33_4.opus +0 -0
  202. package/starter/samples/piano/piano_33_8.opus +0 -0
  203. package/starter/samples/piano/piano_36_12.opus +0 -0
  204. package/starter/samples/piano/piano_36_16.opus +0 -0
  205. package/starter/samples/piano/piano_36_4.opus +0 -0
  206. package/starter/samples/piano/piano_36_8.opus +0 -0
  207. package/starter/samples/piano/piano_39_12.opus +0 -0
  208. package/starter/samples/piano/piano_39_16.opus +0 -0
  209. package/starter/samples/piano/piano_39_4.opus +0 -0
  210. package/starter/samples/piano/piano_39_8.opus +0 -0
  211. package/starter/samples/piano/piano_42_12.opus +0 -0
  212. package/starter/samples/piano/piano_42_16.opus +0 -0
  213. package/starter/samples/piano/piano_42_4.opus +0 -0
  214. package/starter/samples/piano/piano_42_8.opus +0 -0
  215. package/starter/samples/piano/piano_45_12.opus +0 -0
  216. package/starter/samples/piano/piano_45_16.opus +0 -0
  217. package/starter/samples/piano/piano_45_4.opus +0 -0
  218. package/starter/samples/piano/piano_45_8.opus +0 -0
  219. package/starter/samples/piano/piano_48_12.opus +0 -0
  220. package/starter/samples/piano/piano_48_16.opus +0 -0
  221. package/starter/samples/piano/piano_48_4.opus +0 -0
  222. package/starter/samples/piano/piano_48_8.opus +0 -0
  223. package/starter/samples/piano/piano_51_12.opus +0 -0
  224. package/starter/samples/piano/piano_51_16.opus +0 -0
  225. package/starter/samples/piano/piano_51_4.opus +0 -0
  226. package/starter/samples/piano/piano_51_8.opus +0 -0
  227. package/starter/samples/piano/piano_54_12.opus +0 -0
  228. package/starter/samples/piano/piano_54_16.opus +0 -0
  229. package/starter/samples/piano/piano_54_4.opus +0 -0
  230. package/starter/samples/piano/piano_54_8.opus +0 -0
  231. package/starter/samples/piano/piano_57_12.opus +0 -0
  232. package/starter/samples/piano/piano_57_16.opus +0 -0
  233. package/starter/samples/piano/piano_57_4.opus +0 -0
  234. package/starter/samples/piano/piano_57_8.opus +0 -0
  235. package/starter/samples/piano/piano_60_12.opus +0 -0
  236. package/starter/samples/piano/piano_60_16.opus +0 -0
  237. package/starter/samples/piano/piano_60_4.opus +0 -0
  238. package/starter/samples/piano/piano_60_8.opus +0 -0
  239. package/starter/samples/piano/piano_63_12.opus +0 -0
  240. package/starter/samples/piano/piano_63_16.opus +0 -0
  241. package/starter/samples/piano/piano_63_4.opus +0 -0
  242. package/starter/samples/piano/piano_63_8.opus +0 -0
  243. package/starter/samples/piano/piano_66_12.opus +0 -0
  244. package/starter/samples/piano/piano_66_16.opus +0 -0
  245. package/starter/samples/piano/piano_66_4.opus +0 -0
  246. package/starter/samples/piano/piano_66_8.opus +0 -0
  247. package/starter/samples/piano/piano_69_12.opus +0 -0
  248. package/starter/samples/piano/piano_69_16.opus +0 -0
  249. package/starter/samples/piano/piano_69_4.opus +0 -0
  250. package/starter/samples/piano/piano_69_8.opus +0 -0
  251. package/starter/samples/piano/piano_72_12.opus +0 -0
  252. package/starter/samples/piano/piano_72_16.opus +0 -0
  253. package/starter/samples/piano/piano_72_4.opus +0 -0
  254. package/starter/samples/piano/piano_72_8.opus +0 -0
  255. package/starter/samples/piano/piano_75_12.opus +0 -0
  256. package/starter/samples/piano/piano_75_16.opus +0 -0
  257. package/starter/samples/piano/piano_75_4.opus +0 -0
  258. package/starter/samples/piano/piano_75_8.opus +0 -0
  259. package/starter/samples/piano/piano_78_12.opus +0 -0
  260. package/starter/samples/piano/piano_78_16.opus +0 -0
  261. package/starter/samples/piano/piano_78_4.opus +0 -0
  262. package/starter/samples/piano/piano_78_8.opus +0 -0
  263. package/starter/samples/piano/piano_81_12.opus +0 -0
  264. package/starter/samples/piano/piano_81_16.opus +0 -0
  265. package/starter/samples/piano/piano_81_4.opus +0 -0
  266. package/starter/samples/piano/piano_81_8.opus +0 -0
  267. package/starter/samples/piano/piano_84_12.opus +0 -0
  268. package/starter/samples/piano/piano_84_16.opus +0 -0
  269. package/starter/samples/piano/piano_84_4.opus +0 -0
  270. package/starter/samples/piano/piano_84_8.opus +0 -0
  271. package/starter/samples/piano/piano_87_12.opus +0 -0
  272. package/starter/samples/piano/piano_87_16.opus +0 -0
  273. package/starter/samples/piano/piano_87_4.opus +0 -0
  274. package/starter/samples/piano/piano_87_8.opus +0 -0
  275. package/starter/samples/piano/piano_90_12.opus +0 -0
  276. package/starter/samples/piano/piano_90_16.opus +0 -0
  277. package/starter/samples/piano/piano_90_4.opus +0 -0
  278. package/starter/samples/piano/piano_90_8.opus +0 -0
  279. package/starter/samples/piano/piano_93_12.opus +0 -0
  280. package/starter/samples/piano/piano_93_16.opus +0 -0
  281. package/starter/samples/piano/piano_93_4.opus +0 -0
  282. package/starter/samples/piano/piano_93_8.opus +0 -0
  283. package/starter/samples/piano/piano_96_12.opus +0 -0
  284. package/starter/samples/piano/piano_96_16.opus +0 -0
  285. package/starter/samples/piano/piano_96_4.opus +0 -0
  286. package/starter/samples/piano/piano_96_8.opus +0 -0
  287. package/starter/samples/piano/piano_99_12.opus +0 -0
  288. package/starter/samples/piano/piano_99_16.opus +0 -0
  289. package/starter/samples/piano/piano_99_4.opus +0 -0
  290. package/starter/samples/piano/piano_99_8.opus +0 -0
  291. package/starter/samples/piano/piano_rel_102_x.opus +0 -0
  292. package/starter/samples/piano/piano_rel_105_x.opus +0 -0
  293. package/starter/samples/piano/piano_rel_108_x.opus +0 -0
  294. package/starter/samples/piano/piano_rel_21_x.opus +0 -0
  295. package/starter/samples/piano/piano_rel_24_x.opus +0 -0
  296. package/starter/samples/piano/piano_rel_27_x.opus +0 -0
  297. package/starter/samples/piano/piano_rel_30_x.opus +0 -0
  298. package/starter/samples/piano/piano_rel_33_x.opus +0 -0
  299. package/starter/samples/piano/piano_rel_36_x.opus +0 -0
  300. package/starter/samples/piano/piano_rel_39_x.opus +0 -0
  301. package/starter/samples/piano/piano_rel_42_x.opus +0 -0
  302. package/starter/samples/piano/piano_rel_45_x.opus +0 -0
  303. package/starter/samples/piano/piano_rel_48_x.opus +0 -0
  304. package/starter/samples/piano/piano_rel_51_x.opus +0 -0
  305. package/starter/samples/piano/piano_rel_54_x.opus +0 -0
  306. package/starter/samples/piano/piano_rel_57_x.opus +0 -0
  307. package/starter/samples/piano/piano_rel_60_x.opus +0 -0
  308. package/starter/samples/piano/piano_rel_63_x.opus +0 -0
  309. package/starter/samples/piano/piano_rel_66_x.opus +0 -0
  310. package/starter/samples/piano/piano_rel_69_x.opus +0 -0
  311. package/starter/samples/piano/piano_rel_72_x.opus +0 -0
  312. package/starter/samples/piano/piano_rel_75_x.opus +0 -0
  313. package/starter/samples/piano/piano_rel_78_x.opus +0 -0
  314. package/starter/samples/piano/piano_rel_81_x.opus +0 -0
  315. package/starter/samples/piano/piano_rel_84_x.opus +0 -0
  316. package/starter/samples/piano/piano_rel_87_x.opus +0 -0
  317. package/starter/samples/piano/piano_rel_90_x.opus +0 -0
  318. package/starter/samples/piano/piano_rel_93_x.opus +0 -0
  319. package/starter/samples/piano/piano_rel_96_x.opus +0 -0
  320. package/starter/samples/piano/piano_rel_99_x.opus +0 -0
  321. package/starter/samples/pizz/pizz_24_2.flac +0 -0
  322. package/starter/samples/pizz/pizz_28_2.flac +0 -0
  323. package/starter/samples/pizz/pizz_31_2.flac +0 -0
  324. package/starter/samples/pizz/pizz_35_2.flac +0 -0
  325. package/starter/samples/pizz/pizz_38_2.flac +0 -0
  326. package/starter/samples/pizz/pizz_41_2.flac +0 -0
  327. package/starter/samples/pizz/pizz_45_2.flac +0 -0
  328. package/starter/samples/pizz/pizz_48_2.flac +0 -0
  329. package/starter/samples/pizz/pizz_52_2.flac +0 -0
  330. package/starter/samples/pizz/pizz_57_2.flac +0 -0
  331. package/starter/samples/pizz/pizz_60_2.flac +0 -0
  332. package/starter/samples/pizz/pizz_64_2.flac +0 -0
  333. package/starter/samples/pizz/pizz_67_2.flac +0 -0
  334. package/starter/samples/pizz/pizz_71_2.flac +0 -0
  335. package/starter/samples/pizz/pizz_74_2.flac +0 -0
  336. package/starter/samples/pk_hat/pk_hat_2_1.flac +0 -0
  337. package/starter/samples/pk_hat/pk_hat_2_2.flac +0 -0
  338. package/starter/samples/pk_hat/pk_hat_6_1.flac +0 -0
  339. package/starter/samples/pk_hat/pk_hat_6_2.flac +0 -0
  340. package/starter/samples/pk_kick/pk_kick_3_1.flac +0 -0
  341. package/starter/samples/pk_kick/pk_kick_3_2.flac +0 -0
  342. package/starter/samples/pk_kick/pk_kick_7_1.flac +0 -0
  343. package/starter/samples/pk_kick/pk_kick_7_2.flac +0 -0
  344. package/starter/samples/pk_ohat/pk_ohat_3_1.flac +0 -0
  345. package/starter/samples/pk_ohat/pk_ohat_3_2.flac +0 -0
  346. package/starter/samples/pk_ohat/pk_ohat_6_1.flac +0 -0
  347. package/starter/samples/pk_ohat/pk_ohat_6_2.flac +0 -0
  348. package/starter/samples/pk_rim/pk_rim_2_1.flac +0 -0
  349. package/starter/samples/pk_rim/pk_rim_2_2.flac +0 -0
  350. package/starter/samples/pk_rim/pk_rim_5_1.flac +0 -0
  351. package/starter/samples/pk_rim/pk_rim_5_2.flac +0 -0
  352. package/starter/samples/pk_snare/pk_snare_3_1.flac +0 -0
  353. package/starter/samples/pk_snare/pk_snare_3_2.flac +0 -0
  354. package/starter/samples/pk_snare/pk_snare_7_1.flac +0 -0
  355. package/starter/samples/pk_snare/pk_snare_7_2.flac +0 -0
  356. package/starter/samples/shaker/shaker_1_1.flac +0 -0
  357. package/starter/samples/shaker/shaker_2_1.flac +0 -0
  358. package/starter/samples/snap/snap_r_1.flac +0 -0
  359. package/starter/samples/snap/snap_r_2.flac +0 -0
  360. package/starter/samples/snap/snap_r_3.flac +0 -0
  361. package/starter/samples/snap/snap_r_4.flac +0 -0
  362. package/starter/samples/snap/snap_r_5.flac +0 -0
  363. package/starter/samples/snap/snap_r_6.flac +0 -0
  364. package/starter/samples/tom/tom_3_1.flac +0 -0
  365. package/starter/samples/tom/tom_3_2.flac +0 -0
  366. package/starter/samples/tom/tom_4_1.flac +0 -0
  367. package/starter/samples/tom/tom_4_2.flac +0 -0
  368. package/starter/samples/vibes/vibes_41_1.opus +0 -0
  369. package/starter/samples/vibes/vibes_41_2.opus +0 -0
  370. package/starter/samples/vibes/vibes_45_1.opus +0 -0
  371. package/starter/samples/vibes/vibes_45_2.opus +0 -0
  372. package/starter/samples/vibes/vibes_48_1.opus +0 -0
  373. package/starter/samples/vibes/vibes_48_2.opus +0 -0
  374. package/starter/samples/vibes/vibes_52_1.opus +0 -0
  375. package/starter/samples/vibes/vibes_52_2.opus +0 -0
  376. package/starter/samples/vibes/vibes_55_1.opus +0 -0
  377. package/starter/samples/vibes/vibes_55_2.opus +0 -0
  378. package/starter/samples/vibes/vibes_59_1.opus +0 -0
  379. package/starter/samples/vibes/vibes_59_2.opus +0 -0
  380. package/starter/samples/vibes/vibes_62_1.opus +0 -0
  381. package/starter/samples/vibes/vibes_62_2.opus +0 -0
  382. package/starter/samples/vibes/vibes_65_1.opus +0 -0
  383. package/starter/samples/vibes/vibes_65_2.opus +0 -0
  384. package/starter/samples/vibes/vibes_69_1.opus +0 -0
  385. package/starter/samples/vibes/vibes_69_2.opus +0 -0
  386. package/starter/samples/vibes/vibes_72_1.opus +0 -0
  387. package/starter/samples/vibes/vibes_72_2.opus +0 -0
  388. package/starter/samples/vibes/vibes_76_1.opus +0 -0
  389. package/starter/samples/vibes/vibes_76_2.opus +0 -0
  390. package/starter/samples/violas/violas_36_1.opus +0 -0
  391. package/starter/samples/violas/violas_36_2.opus +0 -0
  392. package/starter/samples/violas/violas_38_1.opus +0 -0
  393. package/starter/samples/violas/violas_38_2.opus +0 -0
  394. package/starter/samples/violas/violas_40_1.opus +0 -0
  395. package/starter/samples/violas/violas_40_2.opus +0 -0
  396. package/starter/samples/violas/violas_43_1.opus +0 -0
  397. package/starter/samples/violas/violas_43_2.opus +0 -0
  398. package/starter/samples/violas/violas_47_1.opus +0 -0
  399. package/starter/samples/violas/violas_47_2.opus +0 -0
  400. package/starter/samples/violas/violas_50_1.opus +0 -0
  401. package/starter/samples/violas/violas_50_2.opus +0 -0
  402. package/starter/samples/violas/violas_53_1.opus +0 -0
  403. package/starter/samples/violas/violas_53_2.opus +0 -0
  404. package/starter/samples/violas/violas_57_1.opus +0 -0
  405. package/starter/samples/violas/violas_57_2.opus +0 -0
  406. package/starter/samples/violas/violas_60_1.opus +0 -0
  407. package/starter/samples/violas/violas_60_2.opus +0 -0
  408. package/starter/samples/violas/violas_64_1.opus +0 -0
  409. package/starter/samples/violas/violas_64_2.opus +0 -0
  410. package/starter/samples/violas/violas_67_1.opus +0 -0
  411. package/starter/samples/violas/violas_67_2.opus +0 -0
  412. package/starter/samples/violas/violas_71_1.opus +0 -0
  413. package/starter/samples/violas/violas_71_2.opus +0 -0
  414. package/starter/samples/violas/violas_74_1.opus +0 -0
  415. package/starter/samples/violas/violas_74_2.opus +0 -0
  416. package/starter/samples/violins/violins_43_1.opus +0 -0
  417. package/starter/samples/violins/violins_43_2.opus +0 -0
  418. package/starter/samples/violins/violins_45_1.opus +0 -0
  419. package/starter/samples/violins/violins_45_2.opus +0 -0
  420. package/starter/samples/violins/violins_47_1.opus +0 -0
  421. package/starter/samples/violins/violins_47_2.opus +0 -0
  422. package/starter/samples/violins/violins_50_1.opus +0 -0
  423. package/starter/samples/violins/violins_50_2.opus +0 -0
  424. package/starter/samples/violins/violins_54_1.opus +0 -0
  425. package/starter/samples/violins/violins_54_2.opus +0 -0
  426. package/starter/samples/violins/violins_57_1.opus +0 -0
  427. package/starter/samples/violins/violins_57_2.opus +0 -0
  428. package/starter/samples/violins/violins_60_1.opus +0 -0
  429. package/starter/samples/violins/violins_60_2.opus +0 -0
  430. package/starter/samples/violins/violins_64_1.opus +0 -0
  431. package/starter/samples/violins/violins_64_2.opus +0 -0
  432. package/starter/samples/violins/violins_67_1.opus +0 -0
  433. package/starter/samples/violins/violins_67_2.opus +0 -0
  434. package/starter/samples/violins/violins_71_1.opus +0 -0
  435. package/starter/samples/violins/violins_71_2.opus +0 -0
  436. package/starter/samples/violins/violins_74_1.opus +0 -0
  437. package/starter/samples/violins/violins_74_2.opus +0 -0
  438. package/starter/samples/woodblock/woodblock_f_1.flac +0 -0
  439. package/starter/samples/woodblock/woodblock_f_2.flac +0 -0
@@ -0,0 +1,3829 @@
1
+ // `open-take film look`: a product's look, read off its real interface, with
2
+ // where each part was found — for a film page to execute at film scale. No
3
+ // named looks and no defaults: the colours, fonts, radii, shadows and motion
4
+ // timings are the product's own, each with its source and how much of the
5
+ // screen it covers, labelled measured / estimated / not detected.
6
+ //
7
+ // colours every colour the screen paints (backgrounds by sampled area, text
8
+ // by characters and the ground it sits on, borders by edge length,
9
+ // the custom properties that hold it) and an estimate of the roles
10
+ // (bg, surfaces, text, muted, accent, on-accent, border)
11
+ // fonts each family the visible text is set in — weights, sizes, the
12
+ // text itself — and the actual font files: saved with the screen
13
+ // (`make --states` keeps them) or downloaded from the live page
14
+ // shape corner radii and shadows, with examples
15
+ // motion transition / animation durations and easings declared in the
16
+ // product's CSS: one possible source for the film's timing, read
17
+ // as declared, never as what the film should use
18
+ //
19
+ // It writes look.json, look.png (a swatch and type specimen drawn in the
20
+ // product's own fonts with the product's own words, at a 1920×1080 frame) and
21
+ // fonts/ beside them. Given the film's text (--text, or --page: the film's
22
+ // own page, read statically) it checks every character against the font files
23
+ // — CJK included — reports what no file covers, and with --fonts writes the
24
+ // files the film needs, cut down to its characters, plus a fonts.css.
25
+ //
26
+ // The font code reads TrueType/OpenType, WOFF and WOFF2 (Brotli, with the
27
+ // transformed glyf/loca/hmtx rebuilt) in plain Node, and cuts a TrueType-
28
+ // outline font down by keeping every glyph id and emptying the glyphs no kept
29
+ // character reaches (through the cmap, composite glyphs, GSUB and COLR) — the
30
+ // tables that index glyphs stay valid untouched. CFF-outline and bitmap fonts
31
+ // are copied whole, and say so.
32
+
33
+ import { brotliDecompressSync, deflateSync, inflateSync } from "node:zlib";
34
+
35
+ // --- bytes ----------------------------------------------------------------
36
+
37
+ const u8 = (b: Buffer, o: number) => b.readUInt8(o);
38
+ const u16 = (b: Buffer, o: number) => b.readUInt16BE(o);
39
+ const i16 = (b: Buffer, o: number) => b.readInt16BE(o);
40
+ const u32 = (b: Buffer, o: number) => b.readUInt32BE(o);
41
+ const tagAt = (b: Buffer, o: number) => b.toString("latin1", o, o + 4);
42
+ const pad4 = (n: number) => (n + 3) & ~3;
43
+
44
+ /** A reader over one stream of bytes, failing with what it was reading. */
45
+ class Stream {
46
+ pos = 0;
47
+ constructor(
48
+ readonly buf: Buffer,
49
+ readonly what: string,
50
+ ) {}
51
+ need(n: number) {
52
+ if (this.pos + n > this.buf.length) throw new Error(`font: ${this.what} ends early`);
53
+ }
54
+ u8() {
55
+ this.need(1);
56
+ return this.buf[this.pos++]!;
57
+ }
58
+ u16() {
59
+ this.need(2);
60
+ const v = this.buf.readUInt16BE(this.pos);
61
+ this.pos += 2;
62
+ return v;
63
+ }
64
+ i16() {
65
+ this.need(2);
66
+ const v = this.buf.readInt16BE(this.pos);
67
+ this.pos += 2;
68
+ return v;
69
+ }
70
+ u32() {
71
+ this.need(4);
72
+ const v = this.buf.readUInt32BE(this.pos);
73
+ this.pos += 4;
74
+ return v;
75
+ }
76
+ bytes(n: number) {
77
+ this.need(n);
78
+ const v = this.buf.subarray(this.pos, this.pos + n);
79
+ this.pos += n;
80
+ return v;
81
+ }
82
+ /** WOFF2 UIntBase128 */
83
+ base128() {
84
+ let v = 0;
85
+ for (let i = 0; i < 5; i++) {
86
+ const b = this.u8();
87
+ if (i === 0 && b === 0x80) throw new Error(`font: ${this.what} has a malformed number`);
88
+ if (v & 0xfe000000) throw new Error(`font: ${this.what} has a number out of range`);
89
+ v = (v << 7) | (b & 0x7f);
90
+ if (!(b & 0x80)) return v >>> 0;
91
+ }
92
+ throw new Error(`font: ${this.what} has a number out of range`);
93
+ }
94
+ /** WOFF2 255UInt16 */
95
+ u255() {
96
+ const code = this.u8();
97
+ if (code === 253) return this.u16();
98
+ if (code === 255) return this.u8() + 253;
99
+ if (code === 254) return this.u8() + 506;
100
+ return code;
101
+ }
102
+ }
103
+
104
+ // --- fonts: reading the container -----------------------------------------
105
+
106
+ export type FontFormat = "ttf" | "otf" | "woff" | "woff2";
107
+ type Tables = Map<string, Buffer>;
108
+ type Sfnt = { format: FontFormat; flavor: number; tables: Tables };
109
+
110
+ const WOFF2_TAGS = [
111
+ "cmap",
112
+ "head",
113
+ "hhea",
114
+ "hmtx",
115
+ "maxp",
116
+ "name",
117
+ "OS/2",
118
+ "post",
119
+ "cvt ",
120
+ "fpgm",
121
+ "glyf",
122
+ "loca",
123
+ "prep",
124
+ "CFF ",
125
+ "VORG",
126
+ "EBDT",
127
+ "EBLC",
128
+ "gasp",
129
+ "hdmx",
130
+ "kern",
131
+ "LTSH",
132
+ "PCLT",
133
+ "VDMX",
134
+ "vhea",
135
+ "vmtx",
136
+ "BASE",
137
+ "GDEF",
138
+ "GPOS",
139
+ "GSUB",
140
+ "EBSC",
141
+ "JSTF",
142
+ "MATH",
143
+ "CBDT",
144
+ "CBLC",
145
+ "COLR",
146
+ "CPAL",
147
+ "SVG ",
148
+ "sbix",
149
+ "acnt",
150
+ "avar",
151
+ "bdat",
152
+ "bloc",
153
+ "bsln",
154
+ "cvar",
155
+ "fdsc",
156
+ "feat",
157
+ "fmtx",
158
+ "fvar",
159
+ "gvar",
160
+ "hsty",
161
+ "just",
162
+ "lcar",
163
+ "mort",
164
+ "morx",
165
+ "opbd",
166
+ "prop",
167
+ "trak",
168
+ "Zapf",
169
+ "Silf",
170
+ "Glat",
171
+ "Gloc",
172
+ "Feat",
173
+ "Sill",
174
+ ]; // prettier-ignore
175
+
176
+ /** The font's tables, whatever it came in: TrueType/OpenType (a collection's
177
+ * `index`-th face), WOFF or WOFF2. WOFF2's transformed glyf/loca/hmtx come
178
+ * back as the plain tables (loca long, head saying so). */
179
+ export function readSfnt(buf: Buffer, index = 0): Sfnt {
180
+ if (buf.length < 12) throw new Error("font: too short to be a font file");
181
+ const sig = tagAt(buf, 0);
182
+ if (sig === "wOFF") return readWoff(buf);
183
+ if (sig === "wOF2") return readWoff2(buf);
184
+ let base = 0;
185
+ if (sig === "ttcf") {
186
+ const n = u32(buf, 8);
187
+ if (index >= n) throw new Error(`font: the collection has ${n} faces, not ${index + 1}`);
188
+ base = u32(buf, 12 + 4 * index);
189
+ }
190
+ const flavor = u32(buf, base);
191
+ if (flavor !== 0x00010000 && flavor !== 0x4f54544f && flavor !== 0x74727565)
192
+ throw new Error("font: not a TrueType, OpenType, WOFF or WOFF2 file");
193
+ const n = u16(buf, base + 4);
194
+ const tables: Tables = new Map();
195
+ for (let i = 0; i < n; i++) {
196
+ const e = base + 12 + 16 * i;
197
+ const off = u32(buf, e + 8);
198
+ const len = u32(buf, e + 12);
199
+ if (off + len > buf.length) throw new Error(`font: table ${tagAt(buf, e)} runs past the file`);
200
+ tables.set(tagAt(buf, e), buf.subarray(off, off + len));
201
+ }
202
+ return { format: flavor === 0x4f54544f ? "otf" : "ttf", flavor, tables };
203
+ }
204
+
205
+ function readWoff(buf: Buffer): Sfnt {
206
+ const flavor = u32(buf, 4);
207
+ const n = u16(buf, 12);
208
+ const tables: Tables = new Map();
209
+ for (let i = 0; i < n; i++) {
210
+ const e = 44 + 20 * i;
211
+ const tag = tagAt(buf, e);
212
+ const off = u32(buf, e + 4);
213
+ const comp = u32(buf, e + 8);
214
+ const orig = u32(buf, e + 12);
215
+ if (off + comp > buf.length) throw new Error(`font: WOFF table ${tag} runs past the file`);
216
+ const raw = buf.subarray(off, off + comp);
217
+ const data = comp < orig ? inflateSync(raw) : raw;
218
+ if (data.length !== orig) throw new Error(`font: WOFF table ${tag} has the wrong length`);
219
+ tables.set(tag, data);
220
+ }
221
+ return { format: "woff", flavor, tables };
222
+ }
223
+
224
+ function readWoff2(buf: Buffer): Sfnt {
225
+ const flavor = u32(buf, 4);
226
+ if (flavor === 0x74746366) throw new Error("font: WOFF2 collections are not read");
227
+ const n = u16(buf, 12);
228
+ const compressed = u32(buf, 20);
229
+ const dir = new Stream(buf, "WOFF2 table directory");
230
+ dir.pos = 48;
231
+ const entries: { tag: string; orig: number; length: number; transformed: boolean }[] = [];
232
+ for (let i = 0; i < n; i++) {
233
+ const flags = dir.u8();
234
+ const tag = (flags & 0x3f) === 63 ? dir.bytes(4).toString("latin1") : WOFF2_TAGS[flags & 0x3f]!;
235
+ const version = flags >> 6;
236
+ const orig = dir.base128();
237
+ // glyf/loca: version 0 is the transform, 3 is none; every other table the reverse
238
+ const transformed = tag === "glyf" || tag === "loca" ? version === 0 : version !== 0;
239
+ const length = transformed ? dir.base128() : orig;
240
+ entries.push({ tag, orig, length, transformed });
241
+ }
242
+ const data = brotliDecompressSync(buf.subarray(dir.pos, dir.pos + compressed));
243
+ const raw: Tables = new Map();
244
+ let at = 0;
245
+ for (const e of entries) {
246
+ if (at + e.length > data.length)
247
+ throw new Error(`font: WOFF2 table ${e.tag} runs past the data`);
248
+ raw.set(e.tag, data.subarray(at, at + e.length));
249
+ at += e.length;
250
+ }
251
+ const tables: Tables = new Map();
252
+ for (const e of entries) if (!e.transformed) tables.set(e.tag, raw.get(e.tag)!);
253
+ const glyfEntry = entries.find((e) => e.tag === "glyf");
254
+ if (glyfEntry?.transformed) {
255
+ const { glyf, loca, xMins } = rebuildGlyf(raw.get("glyf")!);
256
+ tables.set("glyf", glyf);
257
+ tables.set("loca", loca);
258
+ const head = Buffer.from(tables.get("head")!);
259
+ head.writeInt16BE(1, 50); // loca is long now
260
+ tables.set("head", head);
261
+ const hmtxEntry = entries.find((e) => e.tag === "hmtx");
262
+ if (hmtxEntry?.transformed)
263
+ tables.set("hmtx", rebuildHmtx(raw.get("hmtx")!, tables.get("hhea")!, xMins));
264
+ } else if (entries.find((e) => e.tag === "hmtx")?.transformed)
265
+ throw new Error("font: WOFF2 hmtx is transformed but glyf is not");
266
+ return { format: "woff2", flavor, tables };
267
+ }
268
+
269
+ /** The WOFF2 glyf transform undone: every glyph back to TrueType bytes. */
270
+ function rebuildGlyf(t: Buffer): { glyf: Buffer; loca: Buffer; xMins: number[] } {
271
+ const h = new Stream(t, "WOFF2 glyf");
272
+ h.u16(); // reserved
273
+ const options = h.u16();
274
+ const numGlyphs = h.u16();
275
+ h.u16(); // indexFormat — the rebuilt loca is long either way
276
+ const sizes = [h.u32(), h.u32(), h.u32(), h.u32(), h.u32(), h.u32(), h.u32()];
277
+ const streams: Stream[] = [];
278
+ let at = h.pos;
279
+ const names = ["contours", "points", "flags", "glyphs", "composites", "bboxes", "instructions"];
280
+ for (let i = 0; i < 7; i++) {
281
+ if (at + sizes[i]! > t.length) throw new Error(`font: WOFF2 glyf ${names[i]} stream runs past`);
282
+ streams.push(new Stream(t.subarray(at, at + sizes[i]!), `WOFF2 glyf ${names[i]}`));
283
+ at += sizes[i]!;
284
+ }
285
+ const [nContour, nPoints, flagS, glyphS, compS, bboxS, instrS] = streams as [
286
+ Stream,
287
+ Stream,
288
+ Stream,
289
+ Stream,
290
+ Stream,
291
+ Stream,
292
+ Stream,
293
+ ]; // prettier-ignore
294
+ const bitmapLen = 4 * Math.floor((numGlyphs + 31) / 32);
295
+ const bboxBitmap = bboxS.bytes(bitmapLen);
296
+ const hasBbox = (i: number) => (bboxBitmap[i >> 3]! & (0x80 >> (i & 7))) !== 0;
297
+ const overlap = options & 1 ? t.subarray(at, at + ((numGlyphs + 7) >> 3)) : null;
298
+ const glyphs: Buffer[] = [];
299
+ const xMins: number[] = [];
300
+ for (let g = 0; g < numGlyphs; g++) {
301
+ const nc = nContour.i16();
302
+ if (nc === 0) {
303
+ if (hasBbox(g)) throw new Error(`font: WOFF2 empty glyph ${g} has a bbox`);
304
+ glyphs.push(Buffer.alloc(0));
305
+ xMins.push(0);
306
+ continue;
307
+ }
308
+ if (nc < 0) {
309
+ // composite: its component records verbatim, the bbox explicit
310
+ if (!hasBbox(g)) throw new Error(`font: WOFF2 composite glyph ${g} has no bbox`);
311
+ const bbox = bboxS.bytes(8);
312
+ const start = compS.pos;
313
+ let flags = 0;
314
+ let instructions = false;
315
+ do {
316
+ flags = compS.u16();
317
+ compS.u16();
318
+ compS.bytes(compositeArgBytes(flags));
319
+ if (flags & 0x0100) instructions = true;
320
+ } while (flags & 0x0020);
321
+ const comps = compS.buf.subarray(start, compS.pos);
322
+ const parts = [Buffer.from([0xff, 0xff]), bbox, comps];
323
+ if (instructions) {
324
+ const n = glyphS.u255();
325
+ const len = Buffer.alloc(2);
326
+ len.writeUInt16BE(n);
327
+ parts.push(len, instrS.bytes(n));
328
+ }
329
+ glyphs.push(Buffer.concat(parts));
330
+ xMins.push(bbox.readInt16BE(0));
331
+ continue;
332
+ }
333
+ const ends: number[] = [];
334
+ let total = 0;
335
+ for (let c = 0; c < nc; c++) {
336
+ total += nPoints.u255();
337
+ ends.push(total - 1);
338
+ }
339
+ const xs: number[] = [];
340
+ const ys: number[] = [];
341
+ const on: boolean[] = [];
342
+ let x = 0;
343
+ let y = 0;
344
+ for (let p = 0; p < total; p++) {
345
+ const flag = flagS.u8();
346
+ const [dx, dy] = triplet(flag & 0x7f, glyphS);
347
+ x += dx;
348
+ y += dy;
349
+ xs.push(x);
350
+ ys.push(y);
351
+ on.push(!(flag & 0x80));
352
+ }
353
+ const nInstr = glyphS.u255();
354
+ const instr = instrS.bytes(nInstr);
355
+ let box: [number, number, number, number];
356
+ if (hasBbox(g)) {
357
+ const b = bboxS.bytes(8);
358
+ box = [b.readInt16BE(0), b.readInt16BE(2), b.readInt16BE(4), b.readInt16BE(6)];
359
+ } else
360
+ box = total
361
+ ? [Math.min(...xs), Math.min(...ys), Math.max(...xs), Math.max(...ys)]
362
+ : [0, 0, 0, 0];
363
+ const overlapping = overlap ? (overlap[g >> 3]! & (0x80 >> (g & 7))) !== 0 : false;
364
+ glyphs.push(encodeSimpleGlyph(ends, xs, ys, on, instr, box, overlapping));
365
+ xMins.push(box[0]);
366
+ }
367
+ const { glyf, loca } = joinGlyphs(glyphs);
368
+ return { glyf, loca, xMins };
369
+ }
370
+
371
+ /** bytes of a composite component after its flags and glyph index */
372
+ function compositeArgBytes(flags: number): number {
373
+ let n = flags & 0x0001 ? 4 : 2;
374
+ if (flags & 0x0008) n += 2;
375
+ else if (flags & 0x0040) n += 4;
376
+ else if (flags & 0x0080) n += 8;
377
+ return n;
378
+ }
379
+
380
+ const withSign = (flag: number, v: number) => (flag & 1 ? v : -v);
381
+
382
+ /** one WOFF2 coordinate triplet: (dx, dy) from the flag's low 7 bits */
383
+ function triplet(f: number, s: Stream): [number, number] {
384
+ if (f < 10) return [0, withSign(f, ((f & 14) << 7) + s.u8())];
385
+ if (f < 20) return [withSign(f, (((f - 10) & 14) << 7) + s.u8()), 0];
386
+ if (f < 84) {
387
+ const b0 = f - 20;
388
+ const b1 = s.u8();
389
+ return [
390
+ withSign(f, 1 + (b0 & 0x30) + (b1 >> 4)),
391
+ withSign(f >> 1, 1 + ((b0 & 0x0c) << 2) + (b1 & 0x0f)),
392
+ ];
393
+ }
394
+ if (f < 120) {
395
+ const b0 = f - 84;
396
+ const a = s.u8();
397
+ const b = s.u8();
398
+ return [
399
+ withSign(f, 1 + (Math.floor(b0 / 12) << 8) + a),
400
+ withSign(f >> 1, 1 + (((b0 % 12) >> 2) << 8) + b),
401
+ ];
402
+ }
403
+ if (f < 124) {
404
+ const a = s.u8();
405
+ const b = s.u8();
406
+ const c = s.u8();
407
+ return [withSign(f, (a << 4) + (b >> 4)), withSign(f >> 1, ((b & 0x0f) << 8) + c)];
408
+ }
409
+ const a = s.u16();
410
+ const b = s.u16();
411
+ return [withSign(f, a), withSign(f >> 1, b)];
412
+ }
413
+
414
+ function encodeSimpleGlyph(
415
+ ends: number[],
416
+ xs: number[],
417
+ ys: number[],
418
+ on: boolean[],
419
+ instr: Buffer,
420
+ box: [number, number, number, number],
421
+ overlapping: boolean,
422
+ ): Buffer {
423
+ const head = Buffer.alloc(10 + 2 * ends.length + 2);
424
+ head.writeInt16BE(ends.length, 0);
425
+ for (const [i, v] of box.entries()) head.writeInt16BE(v, 2 + 2 * i);
426
+ for (const [i, v] of ends.entries()) head.writeUInt16BE(v, 10 + 2 * i);
427
+ head.writeUInt16BE(instr.length, 10 + 2 * ends.length);
428
+ const flags: number[] = [];
429
+ const xb: number[] = [];
430
+ const yb: number[] = [];
431
+ let px = 0;
432
+ let py = 0;
433
+ for (let i = 0; i < xs.length; i++) {
434
+ let f = on[i] ? 0x01 : 0;
435
+ if (i === 0 && overlapping) f |= 0x40;
436
+ const dx = xs[i]! - px;
437
+ const dy = ys[i]! - py;
438
+ px = xs[i]!;
439
+ py = ys[i]!;
440
+ if (dx === 0) f |= 0x10;
441
+ else if (Math.abs(dx) < 256) {
442
+ f |= 0x02 | (dx > 0 ? 0x10 : 0);
443
+ xb.push(Math.abs(dx));
444
+ } else xb.push((dx >> 8) & 0xff, dx & 0xff);
445
+ if (dy === 0) f |= 0x20;
446
+ else if (Math.abs(dy) < 256) {
447
+ f |= 0x04 | (dy > 0 ? 0x20 : 0);
448
+ yb.push(Math.abs(dy));
449
+ } else yb.push((dy >> 8) & 0xff, dy & 0xff);
450
+ flags.push(f);
451
+ }
452
+ return Buffer.concat([head, instr, Buffer.from(flags), Buffer.from(xb), Buffer.from(yb)]);
453
+ }
454
+
455
+ /** glyphs → a glyf table (each padded to 4 bytes) and a long loca */
456
+ function joinGlyphs(glyphs: Buffer[]): { glyf: Buffer; loca: Buffer } {
457
+ const loca = Buffer.alloc(4 * (glyphs.length + 1));
458
+ const parts: Buffer[] = [];
459
+ let off = 0;
460
+ glyphs.forEach((g, i) => {
461
+ loca.writeUInt32BE(off, 4 * i);
462
+ if (!g.length) return;
463
+ const padded = pad4(g.length);
464
+ parts.push(g, Buffer.alloc(padded - g.length));
465
+ off += padded;
466
+ });
467
+ loca.writeUInt32BE(off, 4 * glyphs.length);
468
+ return { glyf: Buffer.concat(parts), loca };
469
+ }
470
+
471
+ function rebuildHmtx(t: Buffer, hhea: Buffer, xMins: number[]): Buffer {
472
+ const s = new Stream(t, "WOFF2 hmtx");
473
+ const flags = s.u8();
474
+ const numGlyphs = xMins.length;
475
+ const nh = u16(hhea, 34);
476
+ const adv: number[] = [];
477
+ for (let i = 0; i < nh; i++) adv.push(s.u16());
478
+ const lsb: number[] = [];
479
+ for (let i = 0; i < nh; i++) lsb.push(flags & 1 ? xMins[i]! : s.i16());
480
+ for (let i = nh; i < numGlyphs; i++) lsb.push(flags & 2 ? xMins[i]! : s.i16());
481
+ const out = Buffer.alloc(4 * nh + 2 * (numGlyphs - nh));
482
+ for (let i = 0; i < nh; i++) {
483
+ out.writeUInt16BE(adv[i]!, 4 * i);
484
+ out.writeInt16BE(lsb[i]!, 4 * i + 2);
485
+ }
486
+ for (let i = nh; i < numGlyphs; i++) out.writeInt16BE(lsb[i]!, 4 * nh + 2 * (i - nh));
487
+ return out;
488
+ }
489
+
490
+ /** each glyph's bytes from glyf + loca */
491
+ function splitGlyphs(tables: Tables): Buffer[] {
492
+ const glyf = tables.get("glyf");
493
+ const loca = tables.get("loca");
494
+ const head = tables.get("head");
495
+ const maxp = tables.get("maxp");
496
+ if (!glyf || !loca || !head || !maxp) return [];
497
+ const n = u16(maxp, 4);
498
+ const long = i16(head, 50) === 1;
499
+ const at = (i: number) => (long ? u32(loca, 4 * i) : 2 * u16(loca, 2 * i));
500
+ const out: Buffer[] = [];
501
+ for (let i = 0; i < n; i++) {
502
+ const a = at(i);
503
+ const b = at(i + 1);
504
+ out.push(b > a && b <= glyf.length ? glyf.subarray(a, b) : Buffer.alloc(0));
505
+ }
506
+ return out;
507
+ }
508
+
509
+ // --- fonts: what is in one --------------------------------------------------
510
+
511
+ export type FontInfo = {
512
+ format: FontFormat;
513
+ /** "truetype" (glyf) / "cff" / "bitmap" — which outlines it carries */
514
+ outlines: "truetype" | "cff" | "bitmap";
515
+ family: string;
516
+ subfamily: string;
517
+ fullName: string;
518
+ postscriptName: string;
519
+ /** OS/2 usWeightClass (400 regular, 700 bold) */
520
+ weight: number;
521
+ italic: boolean;
522
+ /** variation axes, when it is a variable font */
523
+ axes: { tag: string; min: number; default: number; max: number }[];
524
+ glyphs: number;
525
+ unitsPerEm: number;
526
+ /** in font units: ascender/descender/lineGap (hhea), cap and x height (OS/2, 0 when absent) */
527
+ ascender: number;
528
+ descender: number;
529
+ lineGap: number;
530
+ capHeight: number;
531
+ xHeight: number;
532
+ /** code point → glyph id */
533
+ cmap: Map<number, number>;
534
+ /** advance widths by glyph id (font units) */
535
+ advances: number[];
536
+ };
537
+
538
+ function nameTable(b: Buffer | undefined): Map<number, string> {
539
+ const out = new Map<number, string>();
540
+ if (!b || b.length < 6) return out;
541
+ const count = u16(b, 2);
542
+ const strings = u16(b, 4);
543
+ const best = new Map<number, number>(); // nameID → score of the record kept
544
+ for (let i = 0; i < count; i++) {
545
+ const r = 6 + 12 * i;
546
+ if (r + 12 > b.length) break;
547
+ const platform = u16(b, r);
548
+ const encoding = u16(b, r + 2);
549
+ const lang = u16(b, r + 4);
550
+ const id = u16(b, r + 6);
551
+ const len = u16(b, r + 8);
552
+ const off = strings + u16(b, r + 10);
553
+ if (off + len > b.length) continue;
554
+ const raw = b.subarray(off, off + len);
555
+ let text: string;
556
+ let score: number;
557
+ if (platform === 3 || platform === 0) {
558
+ text = Buffer.from(raw).swap16().toString("utf16le");
559
+ score = platform === 3 && lang === 0x409 ? 3 : platform === 3 ? 2 : 1;
560
+ } else if (platform === 1 && encoding === 0) {
561
+ text = raw.toString("latin1");
562
+ score = 0;
563
+ } else continue;
564
+ if ((best.get(id) ?? -1) < score) {
565
+ best.set(id, score);
566
+ out.set(id, text);
567
+ }
568
+ }
569
+ return out;
570
+ }
571
+
572
+ function parseCmap(b: Buffer | undefined): Map<number, number> {
573
+ const map = new Map<number, number>();
574
+ if (!b) return map;
575
+ const n = u16(b, 2);
576
+ const subs: { off: number; format: number }[] = [];
577
+ for (let i = 0; i < n; i++) {
578
+ const r = 4 + 8 * i;
579
+ const platform = u16(b, r);
580
+ const encoding = u16(b, r + 2);
581
+ const off = u32(b, r + 4);
582
+ const unicode =
583
+ platform === 0 || (platform === 3 && (encoding === 1 || encoding === 10 || encoding === 0));
584
+ if (!unicode || off + 2 > b.length) continue;
585
+ subs.push({ off, format: u16(b, off) });
586
+ }
587
+ // the full-repertoire tables first, so a BMP table never overrides them
588
+ subs.sort((a, c) => (c.format === 12 ? 1 : 0) - (a.format === 12 ? 1 : 0));
589
+ const put = (cp: number, g: number) => {
590
+ if (g && !map.has(cp)) map.set(cp, g);
591
+ };
592
+ for (const { off, format } of subs) {
593
+ if (format === 12) {
594
+ const groups = u32(b, off + 12);
595
+ for (let i = 0; i < groups; i++) {
596
+ const r = off + 16 + 12 * i;
597
+ const start = u32(b, r);
598
+ const end = u32(b, r + 4);
599
+ const g0 = u32(b, r + 8);
600
+ for (let c = start; c <= end && c <= 0x10ffff; c++) put(c, g0 + (c - start));
601
+ }
602
+ } else if (format === 4) {
603
+ const seg = u16(b, off + 6) / 2;
604
+ const ends = off + 14;
605
+ const starts = ends + 2 * seg + 2;
606
+ const deltas = starts + 2 * seg;
607
+ const ranges = deltas + 2 * seg;
608
+ for (let s = 0; s < seg; s++) {
609
+ const end = u16(b, ends + 2 * s);
610
+ const start = u16(b, starts + 2 * s);
611
+ const delta = u16(b, deltas + 2 * s);
612
+ const ro = u16(b, ranges + 2 * s);
613
+ for (let c = start; c <= end && c !== 0xffff; c++) {
614
+ if (ro === 0) put(c, (c + delta) & 0xffff);
615
+ else {
616
+ const a = ranges + 2 * s + ro + 2 * (c - start);
617
+ if (a + 2 > b.length) continue;
618
+ const g = u16(b, a);
619
+ if (g) put(c, (g + delta) & 0xffff);
620
+ }
621
+ }
622
+ }
623
+ } else if (format === 6) {
624
+ const first = u16(b, off + 6);
625
+ const count = u16(b, off + 8);
626
+ for (let i = 0; i < count; i++) put(first + i, u16(b, off + 10 + 2 * i));
627
+ } else if (format === 0) {
628
+ for (let c = 0; c < 256; c++) put(c, u8(b, off + 6 + c));
629
+ }
630
+ }
631
+ return map;
632
+ }
633
+
634
+ /** What a font file is: names, weight, axes, metrics, the characters it maps. */
635
+ export function parseFont(buf: Buffer, opts: { index?: number } = {}): FontInfo {
636
+ const sfnt = readSfnt(buf, opts.index ?? 0);
637
+ return fontInfo(sfnt);
638
+ }
639
+
640
+ function fontInfo(sfnt: Sfnt): FontInfo {
641
+ const t = sfnt.tables;
642
+ const head = t.get("head");
643
+ const hhea = t.get("hhea");
644
+ const maxp = t.get("maxp");
645
+ if (!head || !maxp) throw new Error("font: head or maxp table missing");
646
+ const names = nameTable(t.get("name"));
647
+ const os2 = t.get("OS/2");
648
+ const axes: FontInfo["axes"] = [];
649
+ const fvar = t.get("fvar");
650
+ if (fvar && fvar.length >= 16) {
651
+ const axesAt = u16(fvar, 4);
652
+ const count = u16(fvar, 8);
653
+ const size = u16(fvar, 10);
654
+ const fixed = (o: number) => fvar.readInt32BE(o) / 65536;
655
+ for (let i = 0; i < count; i++) {
656
+ const r = axesAt + size * i;
657
+ if (r + 20 > fvar.length) break;
658
+ axes.push({
659
+ tag: tagAt(fvar, r),
660
+ min: fixed(r + 4),
661
+ default: fixed(r + 8),
662
+ max: fixed(r + 12),
663
+ });
664
+ }
665
+ }
666
+ const glyphs = u16(maxp, 4);
667
+ const advances: number[] = [];
668
+ const hmtx = t.get("hmtx");
669
+ if (hhea && hmtx) {
670
+ const nh = u16(hhea, 34);
671
+ for (let i = 0; i < nh && 4 * i + 2 <= hmtx.length; i++) advances.push(u16(hmtx, 4 * i));
672
+ }
673
+ const fsSelection = os2 && os2.length >= 64 ? u16(os2, 62) : 0;
674
+ const os2v = os2 && os2.length >= 2 ? u16(os2, 0) : 0;
675
+ return {
676
+ format: sfnt.format,
677
+ outlines: t.has("glyf") ? "truetype" : t.has("CFF ") || t.has("CFF2") ? "cff" : "bitmap",
678
+ family: names.get(16) ?? names.get(1) ?? "",
679
+ subfamily: names.get(17) ?? names.get(2) ?? "",
680
+ fullName: names.get(4) ?? "",
681
+ postscriptName: names.get(6) ?? "",
682
+ weight: os2 && os2.length >= 6 ? u16(os2, 4) : u16(head, 44) & 1 ? 700 : 400,
683
+ italic: (fsSelection & 1) !== 0 || (u16(head, 44) & 2) !== 0,
684
+ axes,
685
+ glyphs,
686
+ unitsPerEm: u16(head, 18),
687
+ ascender: hhea ? i16(hhea, 4) : 0,
688
+ descender: hhea ? i16(hhea, 6) : 0,
689
+ lineGap: hhea ? i16(hhea, 8) : 0,
690
+ capHeight: os2 && os2v >= 2 && os2.length >= 90 ? i16(os2, 88) : 0,
691
+ xHeight: os2 && os2v >= 2 && os2.length >= 88 ? i16(os2, 86) : 0,
692
+ cmap: parseCmap(t.get("cmap")),
693
+ advances,
694
+ };
695
+ }
696
+
697
+ /** Characters that need no glyph of their own: spaces, controls, joiners,
698
+ * variation selectors. */
699
+ export function needsGlyph(cp: number): boolean {
700
+ if (cp < 0x20 || (cp >= 0x7f && cp < 0xa0)) return false;
701
+ if (cp === 0x20 || cp === 0xa0 || cp === 0x3000 || cp === 0xfeff) return false;
702
+ if ((cp >= 0x2000 && cp <= 0x200f) || (cp >= 0x2028 && cp <= 0x202f)) return false;
703
+ if (cp >= 0x205f && cp <= 0x206f) return false;
704
+ if ((cp >= 0xfe00 && cp <= 0xfe0f) || (cp >= 0xe0100 && cp <= 0xe01ef)) return false;
705
+ return true;
706
+ }
707
+
708
+ /** the distinct characters of `text` that need a glyph, in code point order */
709
+ export function glyphChars(text: string): number[] {
710
+ const set = new Set<number>();
711
+ for (const ch of text) {
712
+ const cp = ch.codePointAt(0)!;
713
+ if (needsGlyph(cp)) set.add(cp);
714
+ }
715
+ return [...set].sort((a, b) => a - b);
716
+ }
717
+
718
+ /** Width of `text` set in `font` at `sizePx`, from the advance widths alone —
719
+ * no kerning, no shaping, the default instance of a variable font: an
720
+ * estimate, close for most Latin and CJK text. Unmapped characters count as
721
+ * the font's .notdef. */
722
+ export function textWidth(font: FontInfo, text: string, sizePx: number): number {
723
+ const last = font.advances[font.advances.length - 1] ?? 0;
724
+ let units = 0;
725
+ for (const ch of text) {
726
+ const g = font.cmap.get(ch.codePointAt(0)!) ?? 0;
727
+ units += font.advances[g] ?? last;
728
+ }
729
+ return (units * sizePx) / (font.unitsPerEm || 1000);
730
+ }
731
+
732
+ /** The font size (px) at which `font`'s capitals stand `px` tall (its em box
733
+ * when the font gives no cap height): the way back from a height measured in
734
+ * a frame to the size Latin text was set at. CJK fonts give a cap height too
735
+ * (for their Latin); their ideographs stand near the whole em instead, so a
736
+ * Han character's measured height is close to the size itself. */
737
+ export function sizeForCapHeight(font: FontInfo, px: number): number {
738
+ const cap = font.capHeight > 0 ? font.capHeight : font.unitsPerEm;
739
+ return (px * font.unitsPerEm) / cap;
740
+ }
741
+
742
+ export type GlyphCoverage = {
743
+ /** distinct characters checked (those needing a glyph) */
744
+ chars: number;
745
+ /** characters no font covers, with their code points */
746
+ missing: { char: string; code: string }[];
747
+ /** per font: how many of the characters it has, and which it lacks */
748
+ byFont: { name: string; covered: number; lacks: string }[];
749
+ };
750
+
751
+ /** Which of `text`'s characters each font has, and which none of them has. */
752
+ export function glyphCoverage(
753
+ fonts: readonly { name: string; font: Pick<FontInfo, "cmap"> }[],
754
+ text: string,
755
+ ): GlyphCoverage {
756
+ const cps = glyphChars(text);
757
+ const missing = cps
758
+ .filter((cp) => !fonts.some((f) => f.font.cmap.has(cp)))
759
+ .map((cp) => ({ char: String.fromCodePoint(cp), code: codeLabel(cp) }));
760
+ return {
761
+ chars: cps.length,
762
+ missing,
763
+ byFont: fonts.map((f) => {
764
+ const lacks = cps.filter((cp) => !f.font.cmap.has(cp));
765
+ return {
766
+ name: f.name,
767
+ covered: cps.length - lacks.length,
768
+ lacks: lacks.map((cp) => String.fromCodePoint(cp)).join(""),
769
+ };
770
+ }),
771
+ };
772
+ }
773
+
774
+ const codeLabel = (cp: number) => `U+${cp.toString(16).toUpperCase().padStart(4, "0")}`;
775
+
776
+ // --- fonts: cutting one down ----------------------------------------------
777
+
778
+ type Coverage = [number, number][]; // [glyph, coverage index]
779
+
780
+ function coverage(b: Buffer, off: number): Coverage {
781
+ const out: Coverage = [];
782
+ if (off + 4 > b.length) return out;
783
+ const format = u16(b, off);
784
+ if (format === 1) {
785
+ const n = u16(b, off + 2);
786
+ for (let i = 0; i < n; i++) out.push([u16(b, off + 4 + 2 * i), i]);
787
+ } else if (format === 2) {
788
+ const n = u16(b, off + 2);
789
+ for (let i = 0; i < n; i++) {
790
+ const r = off + 4 + 6 * i;
791
+ const start = u16(b, r);
792
+ const end = u16(b, r + 2);
793
+ const idx = u16(b, r + 4);
794
+ for (let g = start; g <= end; g++) out.push([g, idx + g - start]);
795
+ }
796
+ }
797
+ return out;
798
+ }
799
+
800
+ /** Every glyph a GSUB lookup could produce from glyphs in `keep` (contexts
801
+ * ignored — a lookup that could fire is assumed to), added to `keep`.
802
+ * Returns whether anything was added. */
803
+ function gsubClosure(gsub: Buffer, keep: Set<number>): boolean {
804
+ let grew = false;
805
+ const add = (g: number) => {
806
+ if (!keep.has(g)) {
807
+ keep.add(g);
808
+ grew = true;
809
+ }
810
+ };
811
+ const lookups = u16(gsub, 8);
812
+ const count = u16(gsub, lookups);
813
+ for (let l = 0; l < count; l++) {
814
+ const lo = lookups + u16(gsub, lookups + 2 + 2 * l);
815
+ const type = u16(gsub, lo);
816
+ const subCount = u16(gsub, lo + 4);
817
+ for (let s = 0; s < subCount; s++) {
818
+ let st = lo + u16(gsub, lo + 6 + 2 * s);
819
+ let t = type;
820
+ if (t === 7) {
821
+ t = u16(gsub, st + 2);
822
+ st = st + u32(gsub, st + 4);
823
+ }
824
+ if (st + 2 > gsub.length) continue;
825
+ const format = u16(gsub, st);
826
+ const cov = () => coverage(gsub, st + u16(gsub, st + 2));
827
+ if (t === 1) {
828
+ if (format === 1) {
829
+ const delta = u16(gsub, st + 4);
830
+ for (const [g] of cov()) if (keep.has(g)) add((g + delta) & 0xffff);
831
+ } else if (format === 2) {
832
+ for (const [g, i] of cov()) if (keep.has(g)) add(u16(gsub, st + 6 + 2 * i));
833
+ }
834
+ } else if (t === 2 || t === 3) {
835
+ for (const [g, i] of cov()) {
836
+ if (!keep.has(g)) continue;
837
+ const seq = st + u16(gsub, st + 6 + 2 * i);
838
+ const n = u16(gsub, seq);
839
+ for (let k = 0; k < n; k++) add(u16(gsub, seq + 2 + 2 * k));
840
+ }
841
+ } else if (t === 4) {
842
+ for (const [g, i] of cov()) {
843
+ if (!keep.has(g)) continue;
844
+ const set = st + u16(gsub, st + 6 + 2 * i);
845
+ const n = u16(gsub, set);
846
+ for (let k = 0; k < n; k++) {
847
+ const lig = set + u16(gsub, set + 2 + 2 * k);
848
+ const comps = u16(gsub, lig + 2);
849
+ let all = true;
850
+ for (let c = 0; c < comps - 1; c++)
851
+ if (!keep.has(u16(gsub, lig + 4 + 2 * c))) all = false;
852
+ if (all) add(u16(gsub, lig));
853
+ }
854
+ }
855
+ } else if (t === 8) {
856
+ const back = u16(gsub, st + 4);
857
+ const ahead = u16(gsub, st + 6 + 2 * back);
858
+ const subs = st + 10 + 2 * back + 2 * ahead; // after the glyph count
859
+ for (const [g, i] of cov()) if (keep.has(g)) add(u16(gsub, subs + 2 * i));
860
+ }
861
+ }
862
+ }
863
+ return grew;
864
+ }
865
+
866
+ /** the glyphs a composite glyph is built from */
867
+ function components(glyph: Buffer): number[] {
868
+ if (glyph.length < 10 || glyph.readInt16BE(0) >= 0) return [];
869
+ const out: number[] = [];
870
+ let at = 10;
871
+ for (;;) {
872
+ if (at + 4 > glyph.length) break;
873
+ const flags = u16(glyph, at);
874
+ out.push(u16(glyph, at + 2));
875
+ at += 4 + compositeArgBytes(flags);
876
+ if (!(flags & 0x0020)) break;
877
+ }
878
+ return out;
879
+ }
880
+
881
+ /** COLR version 0: a base glyph's layers */
882
+ function colrClosure(colr: Buffer, keep: Set<number>): boolean {
883
+ if (u16(colr, 0) !== 0) return false;
884
+ let grew = false;
885
+ const nBase = u16(colr, 2);
886
+ const baseAt = u32(colr, 4);
887
+ const layerAt = u32(colr, 8);
888
+ for (let i = 0; i < nBase; i++) {
889
+ const r = baseAt + 6 * i;
890
+ if (!keep.has(u16(colr, r))) continue;
891
+ const first = u16(colr, r + 2);
892
+ const n = u16(colr, r + 4);
893
+ for (let k = 0; k < n; k++) {
894
+ const g = u16(colr, layerAt + 4 * (first + k));
895
+ if (!keep.has(g)) {
896
+ keep.add(g);
897
+ grew = true;
898
+ }
899
+ }
900
+ }
901
+ return grew;
902
+ }
903
+
904
+ function buildCmap(pairs: [number, number][]): Buffer {
905
+ pairs.sort((a, b) => a[0] - b[0]);
906
+ const runs = (list: [number, number][], max: number) => {
907
+ const out: [number, number, number][] = []; // start, end, first glyph
908
+ for (const [cp, g] of list) {
909
+ if (cp > max) break;
910
+ const last = out[out.length - 1];
911
+ if (last && cp === last[1] + 1 && g === last[2] + (cp - last[0])) last[1] = cp;
912
+ else out.push([cp, cp, g]);
913
+ }
914
+ return out;
915
+ };
916
+ const bmp = runs(
917
+ pairs.filter(([cp]) => cp < 0xffff),
918
+ 0xfffe,
919
+ );
920
+ bmp.push([0xffff, 0xffff, 0]);
921
+ const seg = bmp.length;
922
+ const f4Len = 16 + 8 * seg;
923
+ const subtables: { platform: number; encoding: number; data: Buffer }[] = [];
924
+ if (f4Len <= 0xffff) {
925
+ const f4 = Buffer.alloc(f4Len);
926
+ const lg = Math.floor(Math.log2(seg));
927
+ f4.writeUInt16BE(4, 0);
928
+ f4.writeUInt16BE(f4Len, 2);
929
+ f4.writeUInt16BE(seg * 2, 6);
930
+ f4.writeUInt16BE(2 * 2 ** lg, 8);
931
+ f4.writeUInt16BE(lg, 10);
932
+ f4.writeUInt16BE(seg * 2 - 2 * 2 ** lg, 12);
933
+ bmp.forEach(([start, end, g], i) => {
934
+ f4.writeUInt16BE(end, 14 + 2 * i);
935
+ f4.writeUInt16BE(start, 16 + 2 * seg + 2 * i);
936
+ f4.writeUInt16BE(end === 0xffff ? 1 : (g - start) & 0xffff, 16 + 4 * seg + 2 * i);
937
+ // idRangeOffset stays 0
938
+ });
939
+ subtables.push({ platform: 3, encoding: 1, data: f4 });
940
+ }
941
+ if (pairs.some(([cp]) => cp > 0xffff) || f4Len > 0xffff) {
942
+ const groups = runs(pairs, 0x10ffff);
943
+ const f12 = Buffer.alloc(16 + 12 * groups.length);
944
+ f12.writeUInt16BE(12, 0);
945
+ f12.writeUInt32BE(f12.length, 4);
946
+ f12.writeUInt32BE(groups.length, 12);
947
+ groups.forEach(([start, end, g], i) => {
948
+ f12.writeUInt32BE(start, 16 + 12 * i);
949
+ f12.writeUInt32BE(end, 20 + 12 * i);
950
+ f12.writeUInt32BE(g, 24 + 12 * i);
951
+ });
952
+ subtables.push({ platform: 3, encoding: 10, data: f12 });
953
+ }
954
+ const header = Buffer.alloc(4 + 8 * subtables.length);
955
+ header.writeUInt16BE(subtables.length, 2);
956
+ let off = header.length;
957
+ subtables.forEach((s, i) => {
958
+ header.writeUInt16BE(s.platform, 4 + 8 * i);
959
+ header.writeUInt16BE(s.encoding, 6 + 8 * i);
960
+ header.writeUInt32BE(off, 8 + 8 * i);
961
+ off += s.data.length;
962
+ });
963
+ return Buffer.concat([header, ...subtables.map((s) => s.data)]);
964
+ }
965
+
966
+ /** gvar with the variation data of every glyph not kept dropped */
967
+ function subsetGvar(gvar: Buffer, keep: Set<number>): Buffer {
968
+ const axisCount = u16(gvar, 4);
969
+ const sharedCount = u16(gvar, 6);
970
+ const sharedAt = u32(gvar, 8);
971
+ const n = u16(gvar, 12);
972
+ const long = (u16(gvar, 14) & 1) === 1;
973
+ const dataAt = u32(gvar, 16);
974
+ const at = (i: number) => dataAt + (long ? u32(gvar, 20 + 4 * i) : 2 * u16(gvar, 20 + 2 * i));
975
+ const shared = gvar.subarray(sharedAt, sharedAt + 2 * axisCount * sharedCount);
976
+ const header = Buffer.alloc(20 + 4 * (n + 1));
977
+ gvar.copy(header, 0, 0, 8);
978
+ header.writeUInt16BE(n, 12);
979
+ header.writeUInt16BE(u16(gvar, 14) | 1, 14);
980
+ const newShared = header.length;
981
+ const newData = newShared + shared.length;
982
+ header.writeUInt32BE(newShared, 8);
983
+ header.writeUInt32BE(newData, 16);
984
+ const parts: Buffer[] = [];
985
+ let off = 0;
986
+ for (let i = 0; i < n; i++) {
987
+ header.writeUInt32BE(off, 20 + 4 * i);
988
+ if (!keep.has(i)) continue;
989
+ const d = gvar.subarray(at(i), at(i + 1));
990
+ parts.push(d);
991
+ off += d.length;
992
+ }
993
+ header.writeUInt32BE(off, 20 + 4 * n);
994
+ return Buffer.concat([header, shared, ...parts]);
995
+ }
996
+
997
+ function checksum(b: Buffer): number {
998
+ let sum = 0;
999
+ const n = b.length & ~3;
1000
+ for (let i = 0; i < n; i += 4) sum = (sum + b.readUInt32BE(i)) >>> 0;
1001
+ if (n < b.length) {
1002
+ const tail = Buffer.alloc(4);
1003
+ b.copy(tail, 0, n);
1004
+ sum = (sum + tail.readUInt32BE(0)) >>> 0;
1005
+ }
1006
+ return sum;
1007
+ }
1008
+
1009
+ /** tables → a TrueType file, head's checkSumAdjustment set */
1010
+ function writeSfnt(flavor: number, tables: Tables): Buffer {
1011
+ const tags = [...tables.keys()].sort();
1012
+ const n = tags.length;
1013
+ const lg = Math.floor(Math.log2(n));
1014
+ const header = Buffer.alloc(12 + 16 * n);
1015
+ header.writeUInt32BE(flavor, 0);
1016
+ header.writeUInt16BE(n, 4);
1017
+ header.writeUInt16BE(16 * 2 ** lg, 6);
1018
+ header.writeUInt16BE(lg, 8);
1019
+ header.writeUInt16BE(16 * n - 16 * 2 ** lg, 10);
1020
+ const head = tables.get("head");
1021
+ if (head) {
1022
+ const h = Buffer.from(head);
1023
+ h.writeUInt32BE(0, 8);
1024
+ tables.set("head", h);
1025
+ }
1026
+ const parts: Buffer[] = [header];
1027
+ let off = header.length;
1028
+ tags.forEach((tag, i) => {
1029
+ const data = tables.get(tag)!;
1030
+ const e = 12 + 16 * i;
1031
+ header.write(tag, e, "latin1");
1032
+ header.writeUInt32BE(checksum(data), e + 4);
1033
+ header.writeUInt32BE(off, e + 8);
1034
+ header.writeUInt32BE(data.length, e + 12);
1035
+ parts.push(data, Buffer.alloc(pad4(data.length) - data.length));
1036
+ off += pad4(data.length);
1037
+ });
1038
+ const font = Buffer.concat(parts);
1039
+ if (head) {
1040
+ const headOff = header.readUInt32BE(12 + 16 * tags.indexOf("head") + 8);
1041
+ font.writeUInt32BE((0xb1b0afba - checksum(font)) >>> 0, headOff + 8);
1042
+ }
1043
+ return font;
1044
+ }
1045
+
1046
+ /** a TrueType file → WOFF 1.0 (each table zlib'd when that is smaller) */
1047
+ function toWoff(ttf: Buffer): Buffer {
1048
+ const sfnt = readSfnt(ttf);
1049
+ const tags = [...sfnt.tables.keys()].sort();
1050
+ const header = Buffer.alloc(44 + 20 * tags.length);
1051
+ header.write("wOFF", 0, "latin1");
1052
+ header.writeUInt32BE(sfnt.flavor, 4);
1053
+ header.writeUInt16BE(tags.length, 12);
1054
+ header.writeUInt32BE(ttf.length, 16);
1055
+ header.writeUInt16BE(1, 20);
1056
+ const parts: Buffer[] = [header];
1057
+ let off = header.length;
1058
+ tags.forEach((tag, i) => {
1059
+ const data = sfnt.tables.get(tag)!;
1060
+ const z = deflateSync(data);
1061
+ const stored = z.length < data.length ? z : data;
1062
+ const e = 44 + 20 * i;
1063
+ header.write(tag, e, "latin1");
1064
+ header.writeUInt32BE(off, e + 4);
1065
+ header.writeUInt32BE(stored.length, e + 8);
1066
+ header.writeUInt32BE(data.length, e + 12);
1067
+ header.writeUInt32BE(ttf.readUInt32BE(12 + 16 * i + 4), e + 16); // the sfnt's own checksum
1068
+ parts.push(stored, Buffer.alloc(pad4(stored.length) - stored.length));
1069
+ off += pad4(stored.length);
1070
+ });
1071
+ header.writeUInt32BE(off, 8);
1072
+ return Buffer.concat(parts);
1073
+ }
1074
+
1075
+ export type FontSubset = {
1076
+ /** the cut-down font (WOFF unless `format: "ttf"`), or the original bytes when copied */
1077
+ data: Buffer;
1078
+ how: "subset" | "copied";
1079
+ /** why it was copied whole */
1080
+ why?: string;
1081
+ /** the requested characters the font has (the ones it keeps) */
1082
+ kept: number;
1083
+ /** glyphs left with outlines, of all */
1084
+ glyphs: { kept: number; of: number };
1085
+ };
1086
+
1087
+ /** The font cut down to `chars` (a string, or code points): every glyph id
1088
+ * kept, the glyphs no kept character can reach emptied, the cmap holding
1089
+ * only the kept characters. TrueType outlines only — CFF and bitmap fonts
1090
+ * come back whole, saying so. */
1091
+ export function subsetFont(
1092
+ buf: Buffer,
1093
+ chars: string | Iterable<number>,
1094
+ opts: { format?: "woff" | "ttf"; index?: number } = {},
1095
+ ): FontSubset {
1096
+ const sfnt = readSfnt(buf, opts.index ?? 0);
1097
+ const info = fontInfo(sfnt);
1098
+ const cps = typeof chars === "string" ? [...chars].map((c) => c.codePointAt(0)!) : [...chars];
1099
+ const pairs: [number, number][] = [];
1100
+ const seen = new Set<number>();
1101
+ for (const cp of cps) {
1102
+ const g = info.cmap.get(cp);
1103
+ if (g === undefined || seen.has(cp)) continue;
1104
+ seen.add(cp);
1105
+ pairs.push([cp, g]);
1106
+ }
1107
+ const copied = (why: string): FontSubset => ({
1108
+ data: buf,
1109
+ how: "copied",
1110
+ why,
1111
+ kept: pairs.length,
1112
+ glyphs: { kept: info.glyphs, of: info.glyphs },
1113
+ });
1114
+ if (info.outlines !== "truetype")
1115
+ return copied(`${info.outlines} outlines are not cut down here — the whole file is kept`);
1116
+ const colr = sfnt.tables.get("COLR");
1117
+ if (colr && u16(colr, 0) !== 0)
1118
+ return copied("COLR version 1 colour glyphs — the whole file is kept");
1119
+ const glyphs = splitGlyphs(sfnt.tables);
1120
+ const keep = new Set<number>([0, ...pairs.map(([, g]) => g)]);
1121
+ const gsub = sfnt.tables.get("GSUB");
1122
+ for (let round = 0; round < 16; round++) {
1123
+ let grew = false;
1124
+ if (gsub && gsub.length >= 10) grew = gsubClosure(gsub, keep) || grew;
1125
+ if (colr) grew = colrClosure(colr, keep) || grew;
1126
+ for (const g of [...keep])
1127
+ for (const c of components(glyphs[g] ?? Buffer.alloc(0)))
1128
+ if (!keep.has(c) && c < glyphs.length) {
1129
+ keep.add(c);
1130
+ grew = true;
1131
+ }
1132
+ if (!grew) break;
1133
+ }
1134
+ const { glyf, loca } = joinGlyphs(glyphs.map((g, i) => (keep.has(i) ? g : Buffer.alloc(0))));
1135
+ const tables: Tables = new Map(sfnt.tables);
1136
+ tables.delete("DSIG");
1137
+ tables.set("glyf", glyf);
1138
+ tables.set("loca", loca);
1139
+ const head = Buffer.from(tables.get("head")!);
1140
+ head.writeInt16BE(1, 50);
1141
+ tables.set("head", head);
1142
+ tables.set("cmap", buildCmap(pairs));
1143
+ const gvar = tables.get("gvar");
1144
+ if (gvar) tables.set("gvar", subsetGvar(gvar, keep));
1145
+ const ttf = writeSfnt(sfnt.flavor === 0x74727565 ? 0x00010000 : sfnt.flavor, tables);
1146
+ return {
1147
+ data: opts.format === "ttf" ? ttf : toWoff(ttf),
1148
+ how: "subset",
1149
+ kept: pairs.length,
1150
+ glyphs: {
1151
+ kept: [...keep].filter((g) => g < glyphs.length && glyphs[g]!.length).length,
1152
+ of: glyphs.length,
1153
+ },
1154
+ };
1155
+ }
1156
+
1157
+ // --- colour -----------------------------------------------------------------
1158
+
1159
+ /** sRGB 0..255 channels, alpha 0..1 */
1160
+ export type Rgba = { r: number; g: number; b: number; a: number };
1161
+
1162
+ const NAMED: Record<string, string> = {
1163
+ black: "#000000",
1164
+ white: "#ffffff",
1165
+ red: "#ff0000",
1166
+ green: "#008000",
1167
+ blue: "#0000ff",
1168
+ gray: "#808080",
1169
+ grey: "#808080",
1170
+ silver: "#c0c0c0",
1171
+ yellow: "#ffff00",
1172
+ orange: "#ffa500",
1173
+ purple: "#800080",
1174
+ navy: "#000080",
1175
+ teal: "#008080",
1176
+ };
1177
+
1178
+ /** A CSS colour in hex, rgb()/rgba() (comma or space syntax), hsl()/hsla(),
1179
+ * `transparent` or a few common names; null for anything else. */
1180
+ export function parseCssColor(input: string): Rgba | null {
1181
+ const s = input.trim().toLowerCase();
1182
+ if (s === "transparent") return { r: 0, g: 0, b: 0, a: 0 };
1183
+ if (NAMED[s]) return parseCssColor(NAMED[s]!);
1184
+ const hex = /^#([0-9a-f]{3,8})$/.exec(s);
1185
+ if (hex) {
1186
+ let h = hex[1]!;
1187
+ if (h.length === 3 || h.length === 4) h = [...h].map((c) => c + c).join("");
1188
+ if (h.length !== 6 && h.length !== 8) return null;
1189
+ const n = (i: number) => parseInt(h.slice(i, i + 2), 16);
1190
+ return { r: n(0), g: n(2), b: n(4), a: h.length === 8 ? n(6) / 255 : 1 };
1191
+ }
1192
+ const fn = /^(rgba?|hsla?)\(([^)]*)\)$/.exec(s);
1193
+ if (!fn) return null;
1194
+ const parts = fn[2]!
1195
+ .replace(/\s*\/\s*/, " / ")
1196
+ .split(/[\s,]+/)
1197
+ .filter((p) => p && p !== "/");
1198
+ if (parts.length < 3) return null;
1199
+ const num = (p: string, scale: number) =>
1200
+ p.endsWith("%") ? (Number.parseFloat(p) / 100) * scale : Number.parseFloat(p);
1201
+ const alpha = parts[3] != null ? num(parts[3], 1) : 1;
1202
+ if (fn[1]!.startsWith("rgb")) {
1203
+ const [r, g, b] = parts.slice(0, 3).map((p) => num(p, 255)) as [number, number, number];
1204
+ if (![r, g, b, alpha].every(Number.isFinite)) return null;
1205
+ const c = (v: number) => Math.max(0, Math.min(255, Math.round(v)));
1206
+ return { r: c(r), g: c(g), b: c(b), a: Math.max(0, Math.min(1, alpha)) };
1207
+ }
1208
+ const h = (((Number.parseFloat(parts[0]!) % 360) + 360) % 360) / 360;
1209
+ const sat = Number.parseFloat(parts[1]!) / 100;
1210
+ const l = Number.parseFloat(parts[2]!) / 100;
1211
+ if (![h, sat, l, alpha].every(Number.isFinite)) return null;
1212
+ const q = l < 0.5 ? l * (1 + sat) : l + sat - l * sat;
1213
+ const p = 2 * l - q;
1214
+ const ch = (t: number) => {
1215
+ const u = t < 0 ? t + 1 : t > 1 ? t - 1 : t;
1216
+ const v =
1217
+ u < 1 / 6
1218
+ ? p + (q - p) * 6 * u
1219
+ : u < 1 / 2
1220
+ ? q
1221
+ : u < 2 / 3
1222
+ ? p + (q - p) * (2 / 3 - u) * 6
1223
+ : p;
1224
+ return Math.round(v * 255);
1225
+ };
1226
+ return { r: ch(h + 1 / 3), g: ch(h), b: ch(h - 1 / 3), a: Math.max(0, Math.min(1, alpha)) };
1227
+ }
1228
+
1229
+ const hex2 = (v: number) => Math.round(v).toString(16).padStart(2, "0");
1230
+ /** #rrggbb, or #rrggbbaa when not opaque */
1231
+ export const toHex = (c: Rgba): string =>
1232
+ `#${hex2(c.r)}${hex2(c.g)}${hex2(c.b)}${c.a < 1 ? hex2(c.a * 255) : ""}`;
1233
+
1234
+ /** `fg` laid over `bg` (alpha compositing; bg taken as opaque) */
1235
+ export function over(fg: Rgba, bg: Rgba): Rgba {
1236
+ const a = fg.a;
1237
+ return {
1238
+ r: fg.r * a + bg.r * (1 - a),
1239
+ g: fg.g * a + bg.g * (1 - a),
1240
+ b: fg.b * a + bg.b * (1 - a),
1241
+ a: 1,
1242
+ };
1243
+ }
1244
+
1245
+ const lin = (v: number) => {
1246
+ const c = v / 255;
1247
+ return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
1248
+ };
1249
+
1250
+ /** WCAG relative luminance, 0 (black) .. 1 (white) */
1251
+ export const relativeLuminance = (c: Rgba): number =>
1252
+ 0.2126 * lin(c.r) + 0.7152 * lin(c.g) + 0.0722 * lin(c.b);
1253
+
1254
+ /** WCAG contrast ratio of `fg` on `bg` (1..21); a translucent fg is laid over bg first */
1255
+ export function contrastRatio(fg: Rgba | string, bg: Rgba | string): number {
1256
+ const b = typeof bg === "string" ? parseCssColor(bg) : bg;
1257
+ const f = typeof fg === "string" ? parseCssColor(fg) : fg;
1258
+ if (!b || !f) return Number.NaN;
1259
+ const bb = b.a < 1 ? over(b, { r: 255, g: 255, b: 255, a: 1 }) : b;
1260
+ const l1 = relativeLuminance(over(f, bb));
1261
+ const l2 = relativeLuminance(bb);
1262
+ return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
1263
+ }
1264
+
1265
+ /** OKLCH: lightness 0..1, chroma (≈0..0.37), hue in degrees */
1266
+ export function oklch(c: Rgba): [number, number, number] {
1267
+ const r = lin(c.r);
1268
+ const g = lin(c.g);
1269
+ const b = lin(c.b);
1270
+ const l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b);
1271
+ const m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b);
1272
+ const s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b);
1273
+ const L = 0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s;
1274
+ const A = 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s;
1275
+ const B = 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s;
1276
+ const C = Math.hypot(A, B);
1277
+ const H = C < 1e-4 ? 0 : ((Math.atan2(B, A) * 180) / Math.PI + 360) % 360;
1278
+ return [L, C, H];
1279
+ }
1280
+
1281
+ /** distance in OKLab (0 same .. ~1 black–white) */
1282
+ function okDistance(a: Rgba, b: Rgba): number {
1283
+ const [l1, c1, h1] = oklch(a);
1284
+ const [l2, c2, h2] = oklch(b);
1285
+ const x1 = c1 * Math.cos((h1 * Math.PI) / 180);
1286
+ const y1 = c1 * Math.sin((h1 * Math.PI) / 180);
1287
+ const x2 = c2 * Math.cos((h2 * Math.PI) / 180);
1288
+ const y2 = c2 * Math.sin((h2 * Math.PI) / 180);
1289
+ return Math.hypot(l1 - l2, x1 - x2, y1 - y2);
1290
+ }
1291
+
1292
+ // --- text at film scale -------------------------------------------------------
1293
+
1294
+ export type ScreenSize = { name: string; widthPx: number; mmPerPx?: number };
1295
+
1296
+ /** Where a film is watched, as the CSS px width the frame is shown across.
1297
+ * The phone's millimetres assume a 6.1-inch phone (393 px across 65 mm). */
1298
+ export const SCREENS: readonly ScreenSize[] = [
1299
+ { name: "phone, upright, film across the screen", widthPx: 393, mmPerPx: 65.1 / 393 },
1300
+ { name: "phone, sideways, full screen", widthPx: 852, mmPerPx: 141.2 / 852 },
1301
+ { name: "desktop timeline (about 600 px wide)", widthPx: 600 },
1302
+ { name: "laptop, full screen", widthPx: 1440 },
1303
+ ];
1304
+
1305
+ export type Readable = {
1306
+ filmPx: number;
1307
+ filmWidth: number;
1308
+ on: { screen: string; px: number; mm?: number }[];
1309
+ /** what those sizes compare with: Apple's default text sizes (px = pt) */
1310
+ reference: string;
1311
+ };
1312
+
1313
+ /** How big text set at `sizePx` in a `filmWidth`-wide film shows on the
1314
+ * screens it is watched on — information, not a rule. */
1315
+ export function readableSize(
1316
+ sizePx: number,
1317
+ opts: { filmWidth?: number; screens?: readonly ScreenSize[] } = {},
1318
+ ): Readable {
1319
+ const filmWidth = opts.filmWidth ?? 1920;
1320
+ return {
1321
+ filmPx: sizePx,
1322
+ filmWidth,
1323
+ on: (opts.screens ?? SCREENS).map((s) => {
1324
+ const px = Math.round(((sizePx * s.widthPx) / filmWidth) * 10) / 10;
1325
+ return {
1326
+ screen: s.name,
1327
+ px,
1328
+ ...(s.mmPerPx ? { mm: Math.round(px * s.mmPerPx * 10) / 10 } : {}),
1329
+ };
1330
+ }),
1331
+ reference: "iOS default text: body 17 px, footnote 13 px, caption 12 px, the smallest 11 px",
1332
+ };
1333
+ }
1334
+
1335
+ // --- CSS ------------------------------------------------------------------------
1336
+
1337
+ export type CssDecl = {
1338
+ selector: string;
1339
+ property: string;
1340
+ value: string;
1341
+ /** which block it sits in: declarations of one rule share it */
1342
+ block: number;
1343
+ };
1344
+
1345
+ /** Every declaration in a stylesheet with the selector (or at-rule) it sits
1346
+ * under — nested blocks flattened, comments dropped. Tolerant: it never
1347
+ * throws on broken CSS, it just reads what it can. */
1348
+ export function cssDeclarations(css: string): CssDecl[] {
1349
+ const text = css.replace(/\/\*[\s\S]*?\*\//g, "");
1350
+ const out: CssDecl[] = [];
1351
+ const stack: { selector: string; block: number }[] = [];
1352
+ let blocks = 0;
1353
+ let buf = "";
1354
+ let quote = "";
1355
+ let paren = 0;
1356
+ const flush = () => {
1357
+ const d = buf.trim();
1358
+ buf = "";
1359
+ const colon = d.indexOf(":");
1360
+ const top = stack[stack.length - 1];
1361
+ if (colon <= 0 || !top) return;
1362
+ const property = d.slice(0, colon).trim();
1363
+ if (!/^(--)?[a-zA-Z-][\w-]*$/.test(property)) return;
1364
+ out.push({
1365
+ selector: top.selector,
1366
+ property: property.startsWith("--") ? property : property.toLowerCase(),
1367
+ value: d.slice(colon + 1).trim(),
1368
+ block: top.block,
1369
+ });
1370
+ };
1371
+ for (let i = 0; i < text.length; i++) {
1372
+ const ch = text[i]!;
1373
+ if (quote) {
1374
+ buf += ch;
1375
+ if (ch === "\\") buf += text[++i] ?? "";
1376
+ else if (ch === quote) quote = "";
1377
+ continue;
1378
+ }
1379
+ if (ch === '"' || ch === "'") {
1380
+ quote = ch;
1381
+ buf += ch;
1382
+ } else if (ch === "(") {
1383
+ paren++;
1384
+ buf += ch;
1385
+ } else if (ch === ")") {
1386
+ paren = Math.max(0, paren - 1);
1387
+ buf += ch;
1388
+ } else if (paren) buf += ch;
1389
+ else if (ch === "{") {
1390
+ stack.push({ selector: buf.trim().replace(/\s+/g, " "), block: blocks++ });
1391
+ buf = "";
1392
+ } else if (ch === "}") {
1393
+ flush();
1394
+ stack.pop();
1395
+ } else if (ch === ";") flush();
1396
+ else buf += ch;
1397
+ }
1398
+ return out;
1399
+ }
1400
+
1401
+ /** "U+0-7F, U+4??, U+20AC" → [start, end] ranges */
1402
+ export function parseUnicodeRange(s: string): [number, number][] {
1403
+ const out: [number, number][] = [];
1404
+ for (const part of s.split(",")) {
1405
+ const m = /^\s*u\+([0-9a-f?]{1,6})(?:-([0-9a-f]{1,6}))?\s*$/i.exec(part);
1406
+ if (!m) continue;
1407
+ if (m[1]!.includes("?"))
1408
+ out.push([parseInt(m[1]!.replace(/\?/g, "0"), 16), parseInt(m[1]!.replace(/\?/g, "f"), 16)]);
1409
+ else out.push([parseInt(m[1]!, 16), parseInt(m[2] ?? m[1]!, 16)]);
1410
+ }
1411
+ return out;
1412
+ }
1413
+
1414
+ /** code points → the shortest "U+…" list */
1415
+ export function unicodeRangeOf(cps: Iterable<number>): string {
1416
+ const sorted = [...new Set(cps)].sort((a, b) => a - b);
1417
+ const parts: string[] = [];
1418
+ for (let i = 0; i < sorted.length; ) {
1419
+ let j = i;
1420
+ while (j + 1 < sorted.length && sorted[j + 1] === sorted[j]! + 1) j++;
1421
+ const a = sorted[i]!.toString(16).toUpperCase();
1422
+ parts.push(i === j ? `U+${a}` : `U+${a}-${sorted[j]!.toString(16).toUpperCase()}`);
1423
+ i = j + 1;
1424
+ }
1425
+ return parts.join(", ");
1426
+ }
1427
+
1428
+ const inRanges = (cp: number, ranges: readonly [number, number][]) =>
1429
+ !ranges.length || ranges.some(([a, b]) => cp >= a && cp <= b);
1430
+
1431
+ export type CssFontFace = {
1432
+ family: string;
1433
+ /** as declared: "400", "100 900" */
1434
+ weight: string;
1435
+ style: string;
1436
+ unicodeRange: string;
1437
+ /** the first url() source, resolved against the stylesheet; null when none
1438
+ * (local() only) — "about:blank" is a source a saved screen never loaded */
1439
+ src: string | null;
1440
+ format: string | null;
1441
+ };
1442
+
1443
+ const unquote = (s: string) => s.trim().replace(/^(['"])(.*)\1$/, "$2");
1444
+
1445
+ /** The @font-face rules of a stylesheet, their url()s resolved against `base`. */
1446
+ export function parseFontFaces(css: string, base?: string): CssFontFace[] {
1447
+ const blocks = new Map<number, Record<string, string>>();
1448
+ for (const d of cssDeclarations(css)) {
1449
+ if (d.selector.toLowerCase() !== "@font-face") continue;
1450
+ const b = blocks.get(d.block) ?? {};
1451
+ b[d.property] = d.value;
1452
+ blocks.set(d.block, b);
1453
+ }
1454
+ const faces: CssFontFace[] = [];
1455
+ for (const cur of blocks.values()) {
1456
+ if (!cur["font-family"]) continue;
1457
+ const m = /url\(\s*(['"]?)([^'")]+)\1\s*\)(?:\s*format\(\s*['"]?([^'")]+)['"]?\s*\))?/.exec(
1458
+ cur.src ?? "",
1459
+ );
1460
+ let url: string | null = null;
1461
+ if (m) {
1462
+ try {
1463
+ url = base ? new URL(m[2]!, base).href : m[2]!;
1464
+ } catch {
1465
+ url = m[2]!;
1466
+ }
1467
+ }
1468
+ faces.push({
1469
+ family: unquote(cur["font-family"]),
1470
+ weight: (cur["font-weight"] ?? "400").replace(/\s+/g, " "),
1471
+ style: cur["font-style"] ?? "normal",
1472
+ unicodeRange: cur["unicode-range"] ?? "",
1473
+ src: url,
1474
+ format: m?.[3] ?? null,
1475
+ });
1476
+ }
1477
+ return faces;
1478
+ }
1479
+
1480
+ const DURATION = /(-?\d*\.?\d+)(ms|s)\b/g;
1481
+ const EASING =
1482
+ /cubic-bezier\([^)]*\)|steps\([^)]*\)|linear\([^)]*\)|\b(?:ease-in-out|ease-in|ease-out|ease|linear|step-start|step-end)\b/g;
1483
+
1484
+ export type CssMotion = {
1485
+ durations: { ms: number; count: number; where: string[] }[];
1486
+ easings: { value: string; count: number; where: string[] }[];
1487
+ keyframes: string[];
1488
+ };
1489
+
1490
+ /** Transition and animation timings declared in stylesheets. Declared is not
1491
+ * played: a utility class can sit in the CSS unused. */
1492
+ export function cssMotion(sheets: readonly string[]): CssMotion {
1493
+ const durations = new Map<number, { count: number; where: Set<string> }>();
1494
+ const easings = new Map<string, { count: number; where: Set<string> }>();
1495
+ const keyframes = new Set<string>();
1496
+ const note = <K>(m: Map<K, { count: number; where: Set<string> }>, k: K, where: string) => {
1497
+ const e = m.get(k) ?? { count: 0, where: new Set<string>() };
1498
+ e.count++;
1499
+ if (e.where.size < 4) e.where.add(where);
1500
+ m.set(k, e);
1501
+ };
1502
+ for (const css of sheets) {
1503
+ for (const m of css
1504
+ .replace(/\/\*[\s\S]*?\*\//g, "")
1505
+ .matchAll(/@(?:-webkit-)?keyframes\s+([\w-]+)/g))
1506
+ keyframes.add(m[1]!);
1507
+ for (const d of cssDeclarations(css)) {
1508
+ if (!/^(-webkit-)?(transition|animation)(-duration|-timing-function)?$/.test(d.property))
1509
+ continue;
1510
+ if (/^(none|initial|inherit|unset)$/.test(d.value)) continue;
1511
+ const where = `${d.selector.slice(0, 60)} { ${d.property} }`;
1512
+ if (!d.property.endsWith("timing-function"))
1513
+ for (const m of d.value.replace(EASING, " ").matchAll(DURATION)) {
1514
+ const ms = Math.round(Number.parseFloat(m[1]!) * (m[2] === "s" ? 1000 : 1));
1515
+ // a transition's second time is its delay; both are listed as found
1516
+ if (ms > 0) note(durations, ms, where);
1517
+ }
1518
+ if (!d.property.endsWith("-duration"))
1519
+ for (const m of d.value.matchAll(EASING)) note(easings, m[0]!.replace(/\s+/g, ""), where);
1520
+ }
1521
+ }
1522
+ const list = <K>(m: Map<K, { count: number; where: Set<string> }>) =>
1523
+ [...m]
1524
+ .sort((a, b) => b[1].count - a[1].count)
1525
+ .map(([k, v]) => ({ k, count: v.count, where: [...v.where] }));
1526
+ return {
1527
+ durations: list(durations).map(({ k, ...r }) => ({ ms: k, ...r })),
1528
+ easings: list(easings).map(({ k, ...r }) => ({ value: k, ...r })),
1529
+ keyframes: [...keyframes],
1530
+ };
1531
+ }
1532
+
1533
+ // --- the film's own words ---------------------------------------------------------
1534
+
1535
+ /** String literals in a script — template literal text included, `${…}`
1536
+ * read for the strings inside it; comments and regular expressions skipped. */
1537
+ export function scriptStrings(js: string): string[] {
1538
+ const out: string[] = [];
1539
+ let i = 0;
1540
+ let last = ""; // the last significant character outside strings and comments
1541
+ const regexCanStart = () => !last || /[(,=:[!&|?{};+\-*%<>~^]/.test(last);
1542
+ const walk = (stopAtBrace: boolean): void => {
1543
+ let depth = 0;
1544
+ while (i < js.length) {
1545
+ const ch = js[i]!;
1546
+ const next = js[i + 1];
1547
+ if (ch === "/" && next === "/") {
1548
+ while (i < js.length && js[i] !== "\n") i++;
1549
+ continue;
1550
+ }
1551
+ if (ch === "/" && next === "*") {
1552
+ const e = js.indexOf("*/", i + 2);
1553
+ i = e < 0 ? js.length : e + 2;
1554
+ continue;
1555
+ }
1556
+ if (ch === '"' || ch === "'") {
1557
+ let s = "";
1558
+ i++;
1559
+ while (i < js.length && js[i] !== ch && js[i] !== "\n") {
1560
+ if (js[i] === "\\") {
1561
+ s += unescapeJs(js, i);
1562
+ i += escapeLength(js, i);
1563
+ } else s += js[i++];
1564
+ }
1565
+ i++;
1566
+ out.push(s);
1567
+ last = "a";
1568
+ continue;
1569
+ }
1570
+ if (ch === "`") {
1571
+ i++;
1572
+ let s = "";
1573
+ while (i < js.length && js[i] !== "`") {
1574
+ if (js[i] === "\\") {
1575
+ s += unescapeJs(js, i);
1576
+ i += escapeLength(js, i);
1577
+ } else if (js[i] === "$" && js[i + 1] === "{") {
1578
+ out.push(s);
1579
+ s = "";
1580
+ i += 2;
1581
+ walk(true);
1582
+ } else s += js[i++];
1583
+ }
1584
+ i++;
1585
+ out.push(s);
1586
+ last = "a";
1587
+ continue;
1588
+ }
1589
+ if (ch === "/" && regexCanStart()) {
1590
+ // a regular expression literal: skip to its unescaped closing slash
1591
+ i++;
1592
+ let cls = false;
1593
+ while (i < js.length && js[i] !== "\n") {
1594
+ if (js[i] === "\\") i += 2;
1595
+ else if (js[i] === "[") {
1596
+ cls = true;
1597
+ i++;
1598
+ } else if (js[i] === "]") {
1599
+ cls = false;
1600
+ i++;
1601
+ } else if (js[i] === "/" && !cls) break;
1602
+ else i++;
1603
+ }
1604
+ i++;
1605
+ last = "a";
1606
+ continue;
1607
+ }
1608
+ if (stopAtBrace) {
1609
+ if (ch === "{") depth++;
1610
+ if (ch === "}") {
1611
+ if (depth === 0) {
1612
+ i++;
1613
+ return;
1614
+ }
1615
+ depth--;
1616
+ }
1617
+ }
1618
+ if (!/\s/.test(ch)) {
1619
+ // a keyword before a slash still starts a regex
1620
+ if (/[\w$]/.test(ch)) {
1621
+ let w = "";
1622
+ while (i < js.length && /[\w$]/.test(js[i]!)) w += js[i++];
1623
+ last = /^(return|typeof|case|do|else|in|of|void|yield|await)$/.test(w) ? "(" : "a";
1624
+ continue;
1625
+ }
1626
+ last = ch;
1627
+ }
1628
+ i++;
1629
+ }
1630
+ };
1631
+ walk(false);
1632
+ return out.filter((s) => s.trim());
1633
+ }
1634
+
1635
+ function escapeLength(js: string, i: number): number {
1636
+ const c = js[i + 1];
1637
+ if (c === "u") return js[i + 2] === "{" ? js.indexOf("}", i) - i + 1 : 6;
1638
+ if (c === "x") return 4;
1639
+ return 2;
1640
+ }
1641
+
1642
+ function unescapeJs(js: string, i: number): string {
1643
+ const c = js[i + 1] ?? "";
1644
+ if (c === "u") {
1645
+ const code = js[i + 2] === "{" ? js.slice(i + 3, js.indexOf("}", i)) : js.slice(i + 2, i + 6);
1646
+ const n = parseInt(code, 16);
1647
+ return Number.isFinite(n) ? String.fromCodePoint(n) : "";
1648
+ }
1649
+ if (c === "x") return String.fromCharCode(parseInt(js.slice(i + 2, i + 4), 16) || 0);
1650
+ return (
1651
+ ({ n: "\n", t: "\t", r: "", b: "", f: "", v: "", "0": "" } as Record<string, string>)[c] ?? c
1652
+ );
1653
+ }
1654
+
1655
+ const ENTITIES: Record<string, string> = {
1656
+ amp: "&",
1657
+ lt: "<",
1658
+ gt: ">",
1659
+ quot: '"',
1660
+ apos: "'",
1661
+ nbsp: " ",
1662
+ };
1663
+ const decodeHtml = (s: string) =>
1664
+ s.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (m, e: string) => {
1665
+ if (e[0] === "#") {
1666
+ const n = e[1] === "x" || e[1] === "X" ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10);
1667
+ return Number.isFinite(n) ? String.fromCodePoint(n) : m;
1668
+ }
1669
+ return ENTITIES[e.toLowerCase()] ?? m;
1670
+ });
1671
+
1672
+ /** markup and CSS-looking strings dropped from a string literal, what a viewer could read kept */
1673
+ function readableText(s: string): string {
1674
+ const t = s.replace(/<[^>]*>/g, " ");
1675
+ return decodeHtml(t);
1676
+ }
1677
+
1678
+ const GENERIC_FAMILIES = new Set([
1679
+ "serif",
1680
+ "sans-serif",
1681
+ "monospace",
1682
+ "cursive",
1683
+ "fantasy",
1684
+ "system-ui",
1685
+ "ui-sans-serif",
1686
+ "ui-serif",
1687
+ "ui-monospace",
1688
+ "ui-rounded",
1689
+ "math",
1690
+ "emoji",
1691
+ "fangsong",
1692
+ "-apple-system",
1693
+ "blinkmacsystemfont",
1694
+ ]); // prettier-ignore
1695
+
1696
+ /** The words a film page could show, read statically: its markup's text and
1697
+ * every string literal in its own scripts (inline, and the .js/.mjs/.json
1698
+ * files it loads from its folder — kit/ left out), markup inside strings
1699
+ * stripped. An estimate: text a page builds or fetches at run time is not
1700
+ * seen, and a string that never reaches the screen is counted. */
1701
+ export async function filmText(page: string): Promise<{ text: string; files: string[] }> {
1702
+ const { existsSync, statSync } = await import("node:fs");
1703
+ const { readFile } = await import("node:fs/promises");
1704
+ const { dirname, join, resolve, relative, sep } = await import("node:path");
1705
+ let file = resolve(page);
1706
+ if (existsSync(file) && statSync(file).isDirectory()) file = join(file, "index.html");
1707
+ if (!existsSync(file)) throw new Error(`film look: no film page at ${page}`);
1708
+ const root = dirname(file);
1709
+ const parts: string[] = [];
1710
+ const files: string[] = [];
1711
+ const seen = new Set<string>();
1712
+ const local = (from: string, spec: string): string | null => {
1713
+ if (/^[a-z]+:|^\/\//i.test(spec) || spec.startsWith("data:")) return null;
1714
+ const p = resolve(dirname(from), spec.split(/[?#]/)[0]!);
1715
+ const rel = relative(root, p);
1716
+ if (rel.startsWith("..") || rel.split(sep)[0] === "kit" || rel.includes("node_modules"))
1717
+ return null;
1718
+ return existsSync(p) && statSync(p).isFile() ? p : null;
1719
+ };
1720
+ const readScript = async (path: string): Promise<void> => {
1721
+ if (seen.has(path)) return;
1722
+ seen.add(path);
1723
+ files.push(path);
1724
+ const src = await readFile(path, "utf8");
1725
+ if (path.endsWith(".json")) {
1726
+ const walk = (v: unknown) => {
1727
+ if (typeof v === "string") parts.push(readableText(v));
1728
+ else if (Array.isArray(v)) v.forEach(walk);
1729
+ else if (v && typeof v === "object") Object.values(v).forEach(walk);
1730
+ };
1731
+ try {
1732
+ walk(JSON.parse(src));
1733
+ } catch {
1734
+ /* not JSON after all */
1735
+ }
1736
+ return;
1737
+ }
1738
+ await readJs(path, src);
1739
+ };
1740
+ const readJs = async (from: string, src: string): Promise<void> => {
1741
+ for (const s of scriptStrings(src)) parts.push(readableText(s));
1742
+ const specs = [
1743
+ ...src.matchAll(/\bimport\s*(?:[\w*{}\s,$]+from\s*)?["']([^"']+)["']/g),
1744
+ ...src.matchAll(/\bimport\(\s*["']([^"']+)["']\s*\)/g),
1745
+ ...src.matchAll(/\bfetch\(\s*["']([^"']+\.json)["']/g),
1746
+ ].map((m) => m[1]!);
1747
+ for (const spec of specs) {
1748
+ const p = local(from, spec);
1749
+ if (p && /\.(m?js|json)$/.test(p)) await readScript(p);
1750
+ }
1751
+ };
1752
+ const html = await readFile(file, "utf8");
1753
+ files.push(file);
1754
+ for (const m of html.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)) {
1755
+ const src = /\bsrc\s*=\s*["']([^"']+)["']/i.exec(m[1]!)?.[1];
1756
+ if (src) {
1757
+ const p = local(file, src);
1758
+ if (p) await readScript(p);
1759
+ } else await readJs(file, m[2]!);
1760
+ }
1761
+ const body = html
1762
+ .replace(/<script\b[\s\S]*?<\/script>/gi, " ")
1763
+ .replace(/<style\b[\s\S]*?<\/style>/gi, " ")
1764
+ .replace(/<!--[\s\S]*?-->/g, " ");
1765
+ parts.push(decodeHtml(body.replace(/<[^>]*>/g, " ")));
1766
+ for (const m of body.matchAll(/\b(?:alt|title|aria-label|placeholder|value)\s*=\s*"([^"]*)"/gi))
1767
+ parts.push(decodeHtml(m[1]!));
1768
+ return { text: parts.join("\n"), files };
1769
+ }
1770
+
1771
+ // --- reading a page -----------------------------------------------------------
1772
+
1773
+ /** What the page reader returns for one screen (all px are CSS px). */
1774
+ type PageRead = {
1775
+ url: string;
1776
+ title: string;
1777
+ ua: string;
1778
+ width: number;
1779
+ height: number;
1780
+ frozen: boolean;
1781
+ samples: number;
1782
+ images: number;
1783
+ backgrounds: { hex: string; n: number; interactive: number; where: [string, number][] }[];
1784
+ gradients: { value: string; n: number; where: [string, number][] }[];
1785
+ texts: {
1786
+ hex: string;
1787
+ chars: number;
1788
+ area: number;
1789
+ interactive: number;
1790
+ grounds: [string, number][];
1791
+ where: [string, number][];
1792
+ }[];
1793
+ borders: { hex: string; length: number; where: [string, number][] }[];
1794
+ fills: { hex: string; area: number; where: [string, number][] }[];
1795
+ families: {
1796
+ family: string;
1797
+ webfont: boolean;
1798
+ chars: number;
1799
+ weights: [string, number][];
1800
+ sizes: [number, number][];
1801
+ stacks: string[];
1802
+ }[];
1803
+ type: {
1804
+ family: string;
1805
+ weight: string;
1806
+ size: number;
1807
+ chars: number;
1808
+ sample: string;
1809
+ where: string;
1810
+ }[];
1811
+ samples_: {
1812
+ text: string;
1813
+ family: string;
1814
+ weight: string;
1815
+ size: number;
1816
+ area: number;
1817
+ hex: string;
1818
+ }[];
1819
+ radii: { value: string; px: number; n: number; where: [string, number][] }[];
1820
+ shadows: { value: string; n: number; where: [string, number][] }[];
1821
+ transitions: { value: string; n: number; where: [string, number][] }[];
1822
+ faces: { family: string; weight: string; style: string; unicodeRange: string; status: string }[];
1823
+ sheets: { href?: string; text?: string }[];
1824
+ };
1825
+
1826
+ // The reader runs inside the page. Backgrounds are sampled on a grid with
1827
+ // elementsFromPoint, compositing translucent layers down to the first opaque
1828
+ // one (white under all); text is read node by node with its rendered boxes,
1829
+ // each character attributed to the first family in its stack whose declared
1830
+ // faces cover it; borders, SVG fills, radii and shadows come from every
1831
+ // element on screen. Colours are normalised by painting one canvas pixel.
1832
+ const PAGE_READ_JS = String.raw`async () => {
1833
+ try { await Promise.race([document.fonts.ready, new Promise((r) => setTimeout(r, 8000))]); } catch (e) {}
1834
+ const W = innerWidth, H = innerHeight;
1835
+ const cv = document.createElement("canvas"); cv.width = cv.height = 1;
1836
+ const cx = cv.getContext("2d", { willReadFrequently: true });
1837
+ const colours = new Map();
1838
+ const rgba = (s) => {
1839
+ if (!s || s === "none") return null;
1840
+ if (colours.has(s)) return colours.get(s);
1841
+ let v = null;
1842
+ const m = /^rgba?\(([^)]+)\)$/.exec(s);
1843
+ if (m) {
1844
+ const p = m[1].split(/[\s,\/]+/).filter(Boolean).map((x) => x.endsWith("%") ? parseFloat(x) / 100 : Number(x));
1845
+ v = [p[0], p[1], p[2], p.length > 3 ? p[3] : 1];
1846
+ } else {
1847
+ cx.clearRect(0, 0, 1, 1); cx.fillStyle = "rgba(0,0,0,0)"; cx.fillStyle = s; cx.fillRect(0, 0, 1, 1);
1848
+ const d = cx.getImageData(0, 0, 1, 1).data; v = [d[0], d[1], d[2], d[3] / 255];
1849
+ }
1850
+ colours.set(s, v);
1851
+ return v;
1852
+ };
1853
+ const h2 = (n) => Math.max(0, Math.min(255, Math.round(n))).toString(16).padStart(2, "0");
1854
+ const hex = (c) => "#" + h2(c[0]) + h2(c[1]) + h2(c[2]) + (c[3] < 0.995 ? h2(c[3] * 255) : "");
1855
+ const styles = new Map();
1856
+ const cs = (el) => { let s = styles.get(el); if (!s) { s = getComputedStyle(el); styles.set(el, s); } return s; };
1857
+ const descs = new Map();
1858
+ const desc = (el) => {
1859
+ if (!el) return "page";
1860
+ if (descs.has(el)) return descs.get(el);
1861
+ let d = el.tagName.toLowerCase();
1862
+ if (el.id && el.id.length < 24 && !/\d{4}/.test(el.id)) d += "#" + el.id;
1863
+ else {
1864
+ const c = (el.getAttribute("class") || "").split(/\s+/).find((c) => c && c.length < 28 && !c.includes(":") && !/[0-9a-f]{5,}|__|--[a-z0-9]{5}/i.test(c));
1865
+ if (c) d += "." + c;
1866
+ }
1867
+ const r = el.getBoundingClientRect();
1868
+ if (r.width * r.height < W * H * 0.2) {
1869
+ const t = (el.getAttribute("aria-label") || el.innerText || el.getAttribute("alt") || "").trim().replace(/\s+/g, " ").slice(0, 24);
1870
+ if (t) d += ' "' + t + '"';
1871
+ }
1872
+ descs.set(el, d);
1873
+ return d;
1874
+ };
1875
+ const INTERACTIVE = "a,button,[role=button],[role=link],[role=tab],input,select,textarea,summary";
1876
+ const interactive = (el) => !!(el && el.closest && el.closest(INTERACTIVE));
1877
+ const bump = (map, key, el, add, inter) => {
1878
+ let e = map.get(key);
1879
+ if (!e) { e = { n: 0, interactive: 0, where: new Map() }; map.set(key, e); }
1880
+ e.n += add;
1881
+ if (inter) e.interactive += add;
1882
+ const d = desc(el);
1883
+ e.where.set(d, (e.where.get(d) || 0) + add);
1884
+ return e;
1885
+ };
1886
+ const top3 = (m) => [...m].sort((a, b) => b[1] - a[1]).slice(0, 4).map(([k, v]) => [k, Math.round(v * 100) / 100]);
1887
+ const IMAGE = new Set(["IMG", "VIDEO", "CANVAS", "PICTURE", "IFRAME", "OBJECT", "EMBED"]);
1888
+ // the canvas under everything: the root's background, or the body's when
1889
+ // the root has none (CSS propagates it, and the body then paints none)
1890
+ const html = document.documentElement, body = document.body;
1891
+ const rootBg = rgba(cs(html).backgroundColor);
1892
+ const fromBody = !(rootBg && rootBg[3] > 0) && cs(html).backgroundImage === "none" && body;
1893
+ const canvasBg = (() => {
1894
+ const c = fromBody ? rgba(cs(body).backgroundColor) : rootBg;
1895
+ if (!c || c[3] === 0) return [255, 255, 255];
1896
+ const k = 1 - c[3];
1897
+ return [c[0] * c[3] + 255 * k, c[1] * c[3] + 255 * k, c[2] * c[3] + 255 * k];
1898
+ })();
1899
+ const canvasEl = fromBody ? body : html;
1900
+ const ground = (x, y) => {
1901
+ let r = 0, g = 0, b = 0, a = 0, top = null;
1902
+ for (const el of document.elementsFromPoint(x, y)) {
1903
+ if (el === html || (fromBody && el === body)) break;
1904
+ if (IMAGE.has(el.tagName) || el.tagName.toLowerCase() === "svg") {
1905
+ if (el.tagName.toLowerCase() === "svg") continue;
1906
+ return { kind: "image", top: top || el };
1907
+ }
1908
+ if (el instanceof SVGElement) continue;
1909
+ const s = cs(el);
1910
+ const bi = s.backgroundImage;
1911
+ if (bi && bi !== "none" && a < 0.5) return { kind: bi.includes("url(") ? "image" : "gradient", value: bi, top: top || el };
1912
+ const c = rgba(s.backgroundColor);
1913
+ if (c && c[3] > 0) {
1914
+ const k = (1 - a) * c[3];
1915
+ r += k * c[0]; g += k * c[1]; b += k * c[2]; a += k;
1916
+ if (!top) top = el;
1917
+ }
1918
+ if (a >= 0.995) break;
1919
+ }
1920
+ const k = 1 - a;
1921
+ return { kind: "colour", colour: [r + k * canvasBg[0], g + k * canvasBg[1], b + k * canvasBg[2], 1], top: top || canvasEl };
1922
+ };
1923
+ const step = Math.max(8, Math.round(Math.max(W, H) / 160));
1924
+ const bgs = new Map(), grads = new Map();
1925
+ let samples = 0, images = 0;
1926
+ for (let y = step / 2; y < H; y += step)
1927
+ for (let x = step / 2; x < W; x += step) {
1928
+ samples++;
1929
+ const p = ground(x, y);
1930
+ if (p.kind === "image") images++;
1931
+ else if (p.kind === "gradient") bump(grads, p.value.slice(0, 300), p.top, 1, false);
1932
+ else bump(bgs, hex(p.colour), p.top, 1, interactive(p.top));
1933
+ }
1934
+ // faces, by family, for attributing characters
1935
+ const faces = [...document.fonts].map((f) => ({ family: f.family.replace(/^["']|["']$/g, ""), weight: String(f.weight), style: f.style, unicodeRange: f.unicodeRange, status: f.status }));
1936
+ const parseRange = (s) => (s || "").split(",").map((p) => {
1937
+ const m = /u\+([0-9a-f?]+)(?:-([0-9a-f]+))?/i.exec(p.trim());
1938
+ if (!m) return null;
1939
+ if (m[1].includes("?")) return [parseInt(m[1].replace(/\?/g, "0"), 16), parseInt(m[1].replace(/\?/g, "f"), 16)];
1940
+ return [parseInt(m[1], 16), parseInt(m[2] || m[1], 16)];
1941
+ }).filter(Boolean);
1942
+ const byFamily = new Map();
1943
+ for (const f of faces) {
1944
+ const k = f.family.toLowerCase();
1945
+ if (!byFamily.has(k)) byFamily.set(k, []);
1946
+ byFamily.get(k).push(parseRange(f.unicodeRange));
1947
+ }
1948
+ const covers = (k, cp) => byFamily.get(k).some((rs) => !rs.length || rs.some((r) => cp >= r[0] && cp <= r[1]));
1949
+ // families whose every readable @font-face is local() only (a metric
1950
+ // fallback like "X Fallback": src: local(Arial)) are checked glyph by glyph,
1951
+ // like fonts of the machine, instead of by their (absent) unicode-range
1952
+ const localOnly = new Map();
1953
+ const scanRules = (rules) => {
1954
+ for (const r of rules) {
1955
+ if (r instanceof CSSFontFaceRule) {
1956
+ const fam = (r.style.getPropertyValue("font-family") || "").trim().replace(/^["']|["']$/g, "").toLowerCase();
1957
+ const url = /url\(/.test(r.style.getPropertyValue("src") || "");
1958
+ localOnly.set(fam, (localOnly.has(fam) ? localOnly.get(fam) : true) && !url);
1959
+ } else if (r.cssRules) scanRules(r.cssRules);
1960
+ }
1961
+ };
1962
+ for (const ss of [...document.styleSheets, ...(document.adoptedStyleSheets || [])]) { try { scanRules(ss.cssRules); } catch (e) {} }
1963
+ const glyphs_ = new Map();
1964
+ const hasGlyph = (fam, weight, ch) => {
1965
+ const k = fam + "|" + weight + "|" + ch;
1966
+ if (glyphs_.has(k)) return glyphs_.get(k);
1967
+ const width = (f) => { cx.font = weight + " 64px " + f; return cx.measureText(ch).width; };
1968
+ const q = JSON.stringify(fam);
1969
+ const v = width(q + ",monospace") !== width("monospace") || width(q + ",serif") !== width("serif");
1970
+ glyphs_.set(k, v);
1971
+ return v;
1972
+ };
1973
+ const stacks = new Map();
1974
+ const stackOf = (s) => {
1975
+ if (!stacks.has(s)) stacks.set(s, s.split(",").map((x) => x.trim().replace(/^["']|["']$/g, "")).filter(Boolean));
1976
+ return stacks.get(s);
1977
+ };
1978
+ const familyFor = (stack, cp, weight, ch) => {
1979
+ for (const fam of stack) {
1980
+ const k = fam.toLowerCase();
1981
+ if (byFamily.has(k) && !localOnly.get(k)) { if (covers(k, cp)) return [fam, true]; continue; }
1982
+ if (GENERIC.has(k)) return [fam, false];
1983
+ if (hasGlyph(fam, weight, ch)) return [fam, false];
1984
+ }
1985
+ return ["(browser default)", false];
1986
+ };
1987
+ const GENERIC = new Set(${JSON.stringify([...GENERIC_FAMILIES])});
1988
+ const opacities = new Map();
1989
+ const opacity = (el) => {
1990
+ if (!el || el.nodeType !== 1) return 1;
1991
+ if (opacities.has(el)) return opacities.get(el);
1992
+ const v = parseFloat(cs(el).opacity || "1") * opacity(el.parentElement);
1993
+ opacities.set(el, v);
1994
+ return v;
1995
+ };
1996
+ const texts = new Map(), fams = new Map(), type = new Map(), said = [];
1997
+ const range = document.createRange();
1998
+ const walker = document.createTreeWalker(document.body || document.documentElement, NodeFilter.SHOW_TEXT);
1999
+ const SKIP = new Set(["SCRIPT", "STYLE", "NOSCRIPT", "TEMPLATE", "TITLE", "OPTION"]);
2000
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {
2001
+ const raw = node.nodeValue;
2002
+ if (!raw || !raw.trim()) continue;
2003
+ const el = node.parentElement;
2004
+ if (!el || SKIP.has(el.tagName)) continue;
2005
+ const s = cs(el);
2006
+ if (s.visibility !== "visible" || opacity(el) < 0.05) continue;
2007
+ range.selectNodeContents(node);
2008
+ let area = 0, all = 0, first = null;
2009
+ for (const rc of range.getClientRects()) {
2010
+ all += rc.width * rc.height;
2011
+ const w = Math.min(rc.right, W) - Math.max(rc.left, 0), h = Math.min(rc.bottom, H) - Math.max(rc.top, 0);
2012
+ if (w > 0 && h > 0) { area += w * h; if (!first) first = rc; }
2013
+ }
2014
+ if (!area) continue;
2015
+ const frac = all ? area / all : 1;
2016
+ let text = raw.replace(/\s+/g, " ").trim();
2017
+ if (s.textTransform === "uppercase") text = text.toUpperCase();
2018
+ else if (s.textTransform === "lowercase") text = text.toLowerCase();
2019
+ const glyphs = [...text.replace(/\s/g, "")];
2020
+ const chars = glyphs.length * frac;
2021
+ let fill = rgba(s.webkitTextFillColor) || rgba(s.color);
2022
+ const clipText = (s.webkitBackgroundClip || s.backgroundClip) === "text";
2023
+ const fg = clipText && fill && fill[3] === 0 ? "gradient text" : fill ? hex([fill[0], fill[1], fill[2], fill[3] * opacity(el)]) : "unknown";
2024
+ const gx = Math.max(0, Math.min(W - 1, first.left + first.width / 2)), gy = Math.max(0, Math.min(H - 1, first.top + first.height / 2));
2025
+ const gp = ground(gx, gy);
2026
+ const g = gp.kind === "colour" ? hex(gp.colour) : gp.kind;
2027
+ const e = bump(texts, fg, el, chars, interactive(el));
2028
+ e.area = (e.area || 0) + area;
2029
+ e.grounds = e.grounds || new Map();
2030
+ e.grounds.set(g, (e.grounds.get(g) || 0) + chars);
2031
+ const stack = stackOf(s.fontFamily);
2032
+ const size = Math.round(parseFloat(s.fontSize) * 10) / 10;
2033
+ const weight = s.fontWeight;
2034
+ const count = new Map();
2035
+ for (const ch of glyphs) {
2036
+ const [fam, web] = familyFor(stack, ch.codePointAt(0), weight, ch);
2037
+ let f = fams.get(fam);
2038
+ if (!f) { f = { family: fam, webfont: web, chars: 0, weights: new Map(), sizes: new Map(), stacks: new Set() }; fams.set(fam, f); }
2039
+ f.chars += frac; f.weights.set(weight, (f.weights.get(weight) || 0) + frac); f.sizes.set(size, (f.sizes.get(size) || 0) + frac); f.stacks.add(s.fontFamily);
2040
+ count.set(fam, (count.get(fam) || 0) + 1);
2041
+ }
2042
+ const main = [...count].sort((a, b) => b[1] - a[1])[0];
2043
+ if (!main) continue;
2044
+ const tk = main[0] + "|" + weight + "|" + size;
2045
+ let t = type.get(tk);
2046
+ if (!t) { t = { family: main[0], weight, size, chars: 0, sample: text.slice(0, 60), where: desc(el) }; type.set(tk, t); }
2047
+ t.chars += chars;
2048
+ said.push({ text: text.slice(0, 120), family: main[0], weight, size, area, hex: fg });
2049
+ }
2050
+ const borders = new Map(), fills = new Map(), radii = new Map(), shadows = new Map(), trans = new Map();
2051
+ const px = (v, base) => v.endsWith("%") ? parseFloat(v) / 100 * base : parseFloat(v) || 0;
2052
+ for (const el of document.querySelectorAll("body *")) {
2053
+ const r = el.getBoundingClientRect();
2054
+ if (r.width < 1 || r.height < 1 || r.right <= 0 || r.bottom <= 0 || r.left >= W || r.top >= H) continue;
2055
+ const s = cs(el);
2056
+ if (s.visibility !== "visible" || opacity(el) < 0.05) continue;
2057
+ const cw = Math.min(r.right, W) - Math.max(r.left, 0), ch = Math.min(r.bottom, H) - Math.max(r.top, 0);
2058
+ if (el instanceof SVGElement) {
2059
+ const tag = el.tagName.toLowerCase();
2060
+ if (tag === "svg" || tag === "g" || tag === "defs" || tag === "symbol") continue;
2061
+ const f = rgba(s.fill);
2062
+ if (f && f[3] > 0.05 && s.fill !== "none") bump(fills, hex(f), el.closest("svg") || el, cw * ch / (W * H), false);
2063
+ const st = rgba(s.stroke);
2064
+ if (st && st[3] > 0.05 && s.stroke !== "none") bump(fills, hex(st), el.closest("svg") || el, (cw + ch) * 2 * (parseFloat(s.strokeWidth) || 1) / (W * H), false);
2065
+ continue;
2066
+ }
2067
+ let bordered = false;
2068
+ for (const side of ["Top", "Right", "Bottom", "Left"]) {
2069
+ const w = parseFloat(s["border" + side + "Width"]);
2070
+ const style = s["border" + side + "Style"];
2071
+ if (!(w > 0) || style === "none" || style === "hidden") continue;
2072
+ const c = rgba(s["border" + side + "Color"]);
2073
+ if (!c || c[3] < 0.05) continue;
2074
+ bordered = true;
2075
+ bump(borders, hex(c), el, side === "Top" || side === "Bottom" ? cw : ch, false);
2076
+ }
2077
+ const bg = rgba(s.backgroundColor);
2078
+ const visual = (bg && bg[3] > 0.05) || bordered || s.boxShadow !== "none" || s.backgroundImage !== "none" || IMAGE.has(el.tagName);
2079
+ if (visual) {
2080
+ const rad = Math.max(px(s.borderTopLeftRadius, r.width), px(s.borderTopRightRadius, r.width), px(s.borderBottomLeftRadius, r.width), px(s.borderBottomRightRadius, r.width));
2081
+ if (rad >= 0.5) {
2082
+ const pill = rad >= Math.min(r.width, r.height) / 2 - 0.5;
2083
+ const key = pill ? (Math.abs(r.width - r.height) < 2 ? "circle" : "pill") : Math.round(rad) + "px";
2084
+ const e = bump(radii, key, el, 1, false);
2085
+ e.px = pill ? Math.min(r.width, r.height) / 2 : Math.round(rad);
2086
+ }
2087
+ }
2088
+ if (s.boxShadow && s.boxShadow !== "none") {
2089
+ // the layers that draw something (a utility framework stacks empty ones)
2090
+ const layers = s.boxShadow.split(/,(?![^(]*\))/).map((x) => x.trim()).filter((x) => {
2091
+ const c = /rgba?\([^)]*\)|#[0-9a-f]+|[a-z]+\([^)]*\)/i.exec(x);
2092
+ const col = c ? rgba(c[0]) : [0, 0, 0, 1];
2093
+ const nums = x.replace(c ? c[0] : "", "").match(/-?[\d.]+px/g) || [];
2094
+ return col && col[3] > 0.01 && nums.some((n) => parseFloat(n) !== 0);
2095
+ });
2096
+ if (layers.length) bump(shadows, layers.join(", "), el, 1, false);
2097
+ }
2098
+ if (s.transitionDuration && s.transitionDuration.split(",").some((d) => parseFloat(d) > 0))
2099
+ bump(trans, s.transitionProperty + " " + s.transitionDuration + " " + s.transitionTimingFunction, el, 1, false);
2100
+ if (s.animationName && s.animationName !== "none")
2101
+ bump(trans, "animation " + s.animationName + " " + s.animationDuration + " " + s.animationTimingFunction, el, 1, false);
2102
+ }
2103
+ const sheets = [];
2104
+ for (const ss of [...document.styleSheets, ...(document.adoptedStyleSheets || [])]) {
2105
+ if (ss.href) { sheets.push({ href: ss.href }); continue; }
2106
+ let text = ss.ownerNode && ss.ownerNode.textContent;
2107
+ if (!text) { try { text = [...ss.cssRules].map((r) => r.cssText).join("\n"); } catch (e) {} }
2108
+ if (text) sheets.push({ text });
2109
+ }
2110
+ const list = (m, f) => [...m].map(([k, e]) => f(k, e));
2111
+ return {
2112
+ url: location.href, title: document.title, ua: navigator.userAgent, width: W, height: H,
2113
+ frozen: !!document.querySelector("style[data-ot-freeze]"), samples, images,
2114
+ backgrounds: list(bgs, (k, e) => ({ hex: k, n: e.n, interactive: e.interactive, where: top3(e.where) })),
2115
+ gradients: list(grads, (k, e) => ({ value: k, n: e.n, where: top3(e.where) })),
2116
+ texts: list(texts, (k, e) => ({ hex: k, chars: e.n, area: e.area, interactive: e.interactive, grounds: top3(e.grounds), where: top3(e.where) })),
2117
+ borders: list(borders, (k, e) => ({ hex: k, length: e.n, where: top3(e.where) })),
2118
+ fills: list(fills, (k, e) => ({ hex: k, area: e.n, where: top3(e.where) })),
2119
+ families: [...fams.values()].map((f) => ({ family: f.family, webfont: f.webfont, chars: f.chars, weights: [...f.weights], sizes: [...f.sizes], stacks: [...f.stacks].slice(0, 4) })),
2120
+ type: [...type.values()],
2121
+ samples_: said.sort((a, b) => b.size - a.size || b.area - a.area).slice(0, 80),
2122
+ radii: list(radii, (k, e) => ({ value: k, px: e.px, n: e.n, where: top3(e.where) })),
2123
+ shadows: list(shadows, (k, e) => ({ value: k, n: e.n, where: top3(e.where) })),
2124
+ transitions: list(trans, (k, e) => ({ value: k, n: e.n, where: top3(e.where) })),
2125
+ faces, sheets,
2126
+ };
2127
+ }`;
2128
+
2129
+ /** resolves custom properties (names found in the CSS) at the root, colours normalised */
2130
+ const VARS_JS = `(names) => {
2131
+ const root = getComputedStyle(document.documentElement);
2132
+ const body = document.body ? getComputedStyle(document.body) : root;
2133
+ const cv = document.createElement("canvas"); cv.width = cv.height = 1;
2134
+ const cx = cv.getContext("2d", { willReadFrequently: true });
2135
+ const h2 = (n) => Math.round(n).toString(16).padStart(2, "0");
2136
+ return names.map((n) => {
2137
+ const v = (root.getPropertyValue(n) || body.getPropertyValue(n) || "").trim();
2138
+ if (!v || !CSS.supports("color", v) || /^(inherit|initial|unset|currentcolor)$/i.test(v)) return [n, v, null];
2139
+ cx.clearRect(0, 0, 1, 1); cx.fillStyle = "rgba(0,0,0,0)"; cx.fillStyle = v; cx.fillRect(0, 0, 1, 1);
2140
+ const d = cx.getImageData(0, 0, 1, 1).data;
2141
+ return [n, v, "#" + h2(d[0]) + h2(d[1]) + h2(d[2]) + (d[3] < 254 ? h2(d[3]) : "")];
2142
+ });
2143
+ }`;
2144
+
2145
+ /** Cancels the page's uncaught errors and rejections, so a live site's own
2146
+ * failures (an analytics script, a blocked request) leave the read alone. */
2147
+ const QUIET_ERRORS_JS =
2148
+ "addEventListener('error',function(e){e.preventDefault()},true);addEventListener('unhandledrejection',function(e){e.preventDefault()},true);";
2149
+
2150
+ // --- the look -----------------------------------------------------------------
2151
+
2152
+ export type How = "measured" | "estimated" | "not detected";
2153
+
2154
+ export type LookColour = {
2155
+ hex: string;
2156
+ /** share of the sampled screen it paints as a background (0..1) */
2157
+ background: number;
2158
+ /** characters set in it */
2159
+ text: number;
2160
+ /** px of border edge drawn in it */
2161
+ border: number;
2162
+ /** share of the screen its SVG fills and strokes cover */
2163
+ fill: number;
2164
+ /** share of its background and text use that is on links, buttons, inputs */
2165
+ interactive: number;
2166
+ /** the grounds its text sits on, with the contrast ratio there */
2167
+ on: { ground: string; chars: number; contrast: number | null }[];
2168
+ /** elements it was found on, most first */
2169
+ where: string[];
2170
+ /** custom properties that resolve to it */
2171
+ vars: string[];
2172
+ /** OKLCH lightness, chroma, hue */
2173
+ oklch: [number, number, number];
2174
+ };
2175
+
2176
+ export type LookRole = {
2177
+ hex: string | null;
2178
+ how: How;
2179
+ why: string;
2180
+ where: string[];
2181
+ vars: string[];
2182
+ /** the next candidates, for a different reading */
2183
+ alternatives?: { hex: string; why: string }[];
2184
+ };
2185
+
2186
+ export type RoleName = "bg" | "surface" | "text" | "muted" | "accent" | "onAccent" | "border";
2187
+
2188
+ export type LookFontFile = {
2189
+ /** relative to look.json, when the file is in fonts/ */
2190
+ file: string | null;
2191
+ /** where it came from (the product's URL, or the saved screen's asset) */
2192
+ source: string | null;
2193
+ weight: string;
2194
+ style: string;
2195
+ unicodeRange: string;
2196
+ status: "saved" | "downloaded" | "not saved" | "not downloaded" | string;
2197
+ bytes?: number;
2198
+ /** from the file itself */
2199
+ name?: string;
2200
+ glyphs?: number;
2201
+ chars?: number;
2202
+ outlines?: FontInfo["outlines"];
2203
+ axes?: FontInfo["axes"];
2204
+ /** font units per em, cap and x height — for sizing type by its letters */
2205
+ metrics?: {
2206
+ unitsPerEm: number;
2207
+ capHeight: number;
2208
+ xHeight: number;
2209
+ ascender: number;
2210
+ descender: number;
2211
+ };
2212
+ };
2213
+
2214
+ export type LookFont = {
2215
+ family: string;
2216
+ /** a web font the page loads (else a font of the machine that read it, or generic) */
2217
+ webfont: boolean;
2218
+ chars: number;
2219
+ share: number;
2220
+ weights: { weight: string; chars: number }[];
2221
+ sizes: { px: number; chars: number }[];
2222
+ stacks: string[];
2223
+ /** the product's own words in it, biggest first */
2224
+ samples: string[];
2225
+ files: LookFontFile[];
2226
+ /** @font-face rules declaring the family, and how many have no file here */
2227
+ declared: number;
2228
+ missingFiles: number;
2229
+ };
2230
+
2231
+ export type LookGlyphs = {
2232
+ how: How;
2233
+ /** what was checked: "--text", the page's files */
2234
+ source: string[];
2235
+ chars: number;
2236
+ missing: { char: string; code: string }[];
2237
+ /** per face: family, weight and style (a weight lacking a character falls
2238
+ * back to the next family, whatever another weight has) */
2239
+ byFamily: { family: string; weight: string; style: string; covered: number; lacks: string }[];
2240
+ /** faces the product declares for missing characters that are not here —
2241
+ * missing from every file, or from the files of that face's weight */
2242
+ declaredElsewhere: {
2243
+ family: string;
2244
+ weight: string;
2245
+ style: string;
2246
+ src: string | null;
2247
+ chars: string;
2248
+ }[];
2249
+ };
2250
+
2251
+ export type LookPackage = {
2252
+ dir: string;
2253
+ css: string;
2254
+ files: {
2255
+ file: string;
2256
+ family: string;
2257
+ weight: string;
2258
+ style: string;
2259
+ /** the film's characters it serves (the spaces it keeps besides are not counted) */
2260
+ chars: number;
2261
+ bytes: number;
2262
+ from: string;
2263
+ fromBytes: number;
2264
+ how: FontSubset["how"];
2265
+ why?: string;
2266
+ }[];
2267
+ };
2268
+
2269
+ export type FilmLook = {
2270
+ version: 1;
2271
+ source: {
2272
+ kind: "take" | "states" | "state" | "url" | "look";
2273
+ input: string;
2274
+ url: string | null;
2275
+ title: string | null;
2276
+ /** the saved screens read (ids), or the page */
2277
+ screens: string[];
2278
+ skipped: string[];
2279
+ viewport: { width: number; height: number } | null;
2280
+ };
2281
+ roles: Record<RoleName, LookRole>;
2282
+ colours: LookColour[];
2283
+ gradients: { value: string; share: number; where: string[] }[];
2284
+ /** share of the sampled screen that is an image, video or canvas */
2285
+ imageShare: number;
2286
+ vars: { name: string; value: string; hex: string | null }[];
2287
+ fonts: LookFont[];
2288
+ /** families with @font-face rules that no visible text is set in */
2289
+ declaredFamilies: string[];
2290
+ type: {
2291
+ family: string;
2292
+ weight: string;
2293
+ sizePx: number;
2294
+ chars: number;
2295
+ sample: string;
2296
+ where: string;
2297
+ }[];
2298
+ radii: { value: string; px: number; count: number; where: string[] }[];
2299
+ shadows: { value: string; count: number; where: string[] }[];
2300
+ motion: {
2301
+ declared: CssMotion;
2302
+ used: { value: string; count: number; where: string[] }[];
2303
+ usedHow: How;
2304
+ };
2305
+ glyphs?: LookGlyphs;
2306
+ packaged?: LookPackage;
2307
+ labels: Record<string, How>;
2308
+ notes: string[];
2309
+ };
2310
+
2311
+ export type FilmLookOptions = {
2312
+ /** a take (…/x.take, or a folder holding states/), a states/ folder, one
2313
+ * saved screen (its folder or state.html), an http(s) URL, or a look.json
2314
+ * written before (then only the font work is done) */
2315
+ source: string;
2316
+ /** the folder look.json, look.png and fonts/ go in (default ./look; for a
2317
+ * look.json source, its own folder) */
2318
+ out?: string;
2319
+ /** needed unless the source is a look.json */
2320
+ chromePath?: string;
2321
+ /** only these saved screens (ids: s0, s3) */
2322
+ states?: string[];
2323
+ /** the film's words, checked against the fonts */
2324
+ text?: string;
2325
+ /** the film's page (or folder): its words read statically */
2326
+ page?: string;
2327
+ /** write the fonts the film's words need here, cut down, with fonts.css */
2328
+ fonts?: string;
2329
+ /** more font files the film uses (checked and packaged with the product's) */
2330
+ fontFiles?: string[];
2331
+ /** the page's CSS px for a URL (default 1920×1080) */
2332
+ width?: number;
2333
+ height?: number;
2334
+ /** skip look.png */
2335
+ noPicture?: boolean;
2336
+ onConsole?: (level: string, text: string) => void;
2337
+ };
2338
+
2339
+ export type FilmLookResult = {
2340
+ look: FilmLook;
2341
+ json: string;
2342
+ png: string | null;
2343
+ css: string | null;
2344
+ };
2345
+
2346
+ type Screen = { id: string; rel: string };
2347
+ type Source =
2348
+ | { kind: "take" | "states" | "state"; root: string; screens: Screen[]; skipped: string[] }
2349
+ | { kind: "url"; url: string }
2350
+ | { kind: "look"; file: string };
2351
+
2352
+ const MAX_SCREENS = 12;
2353
+
2354
+ async function resolveSource(input: string, only?: string[]): Promise<Source> {
2355
+ const { existsSync, statSync, readdirSync, readFileSync } = await import("node:fs");
2356
+ const { basename, dirname, join, resolve } = await import("node:path");
2357
+ if (/^https?:\/\//i.test(input)) return { kind: "url", url: input };
2358
+ let p = resolve(input);
2359
+ if (!existsSync(p)) throw new Error(`film look: nothing at ${input}`);
2360
+ if (statSync(p).isFile()) {
2361
+ if (p.endsWith(".json")) return { kind: "look", file: p };
2362
+ if (/\.(mp4|mov|webm)$/i.test(p)) p = p.replace(/\.[^./]+$/, ".take");
2363
+ else if (basename(p) === "state.html") p = dirname(p);
2364
+ else throw new Error(`film look: ${input} is not a take, a saved screen, a URL or a look.json`);
2365
+ }
2366
+ if (
2367
+ existsSync(join(p, "look.json")) &&
2368
+ !existsSync(join(p, "states")) &&
2369
+ !existsSync(join(p, "state.html"))
2370
+ )
2371
+ return { kind: "look", file: join(p, "look.json") };
2372
+ const isScreen = (d: string) =>
2373
+ existsSync(join(d, "index.json")) && existsSync(join(d, "state.html"));
2374
+ if (isScreen(p))
2375
+ return {
2376
+ kind: "state",
2377
+ root: dirname(p),
2378
+ screens: [{ id: basename(p), rel: `${basename(p)}/state.html` }],
2379
+ skipped: [],
2380
+ };
2381
+ const kind = existsSync(join(p, "states")) ? "take" : "states";
2382
+ const statesDir = kind === "take" ? join(p, "states") : p;
2383
+ const found: { id: string; tMs: number; ok: boolean }[] = [];
2384
+ for (const id of existsSync(statesDir) ? readdirSync(statesDir) : []) {
2385
+ const d = join(statesDir, id);
2386
+ if (!isScreen(d)) continue;
2387
+ let tMs = 0;
2388
+ let ok = true;
2389
+ try {
2390
+ const index = JSON.parse(readFileSync(join(d, "index.json"), "utf8"));
2391
+ tMs = Number(index.tMs) || 0;
2392
+ ok = index.fidelity?.ok !== false;
2393
+ } catch {
2394
+ /* unreadable index: read it anyway */
2395
+ }
2396
+ found.push({ id, tMs, ok });
2397
+ }
2398
+ if (!found.length)
2399
+ throw new Error(
2400
+ `film look: no saved screens in ${input} (record the take with --states, or give a URL)`,
2401
+ );
2402
+ found.sort((a, b) => a.tMs - b.tMs);
2403
+ const skipped: string[] = [];
2404
+ let use = found.filter((f) => {
2405
+ if (only?.length) return only.includes(f.id);
2406
+ if (!f.ok) skipped.push(`${f.id} (its saved screen did not match the recording)`);
2407
+ return f.ok;
2408
+ });
2409
+ if (only?.length) {
2410
+ const missing = only.filter((id) => !found.some((f) => f.id === id));
2411
+ if (missing.length)
2412
+ throw new Error(`film look: no saved screen ${missing.join(", ")} in ${input}`);
2413
+ }
2414
+ if (use.length > MAX_SCREENS) {
2415
+ const step = use.length / MAX_SCREENS;
2416
+ const keep = new Set(
2417
+ Array.from({ length: MAX_SCREENS }, (_, i) => use[Math.floor(i * step)]!.id),
2418
+ );
2419
+ for (const f of use)
2420
+ if (!keep.has(f.id))
2421
+ skipped.push(`${f.id} (${MAX_SCREENS} screens are read at most, spread over the take)`);
2422
+ use = use.filter((f) => keep.has(f.id));
2423
+ }
2424
+ if (!use.length)
2425
+ throw new Error(`film look: every saved screen in ${input} was skipped: ${skipped.join("; ")}`);
2426
+ return {
2427
+ kind,
2428
+ root: statesDir,
2429
+ screens: use.map((f) => ({ id: f.id, rel: `${f.id}/state.html` })),
2430
+ skipped,
2431
+ };
2432
+ }
2433
+
2434
+ const sleepMs = (ms: number) => new Promise((r) => setTimeout(r, ms));
2435
+
2436
+ /** go to `url` in the page and wait for it (and a saved screen's restore) to finish */
2437
+ async function navigate(browser: import("../html/cdp").HtmlBrowser, url: string): Promise<void> {
2438
+ await browser.evaluate(`setTimeout(() => { location.href = ${JSON.stringify(url)} }, 0), true`);
2439
+ const deadline = Date.now() + 30_000;
2440
+ for (;;) {
2441
+ await sleepMs(100);
2442
+ try {
2443
+ const done = await browser.evaluate<boolean>(
2444
+ `location.href === ${JSON.stringify(url)} && document.readyState === "complete"`,
2445
+ { timeoutMs: 5000 },
2446
+ );
2447
+ if (done) return;
2448
+ } catch (e) {
2449
+ if (!/context|navigat|destroyed|Cannot find/i.test((e as Error).message)) throw e;
2450
+ }
2451
+ if (Date.now() > deadline) throw new Error(`film look: ${url} never finished loading`);
2452
+ }
2453
+ }
2454
+
2455
+ const STATE_READY_JS = `new Promise((ok) => {
2456
+ const t0 = Date.now();
2457
+ const tick = () => document.documentElement.dataset.otReady === "1" || Date.now() - t0 > 10000 ? setTimeout(ok, 80) : setTimeout(tick, 50);
2458
+ tick();
2459
+ })`;
2460
+
2461
+ type Fetched = { bytes: Buffer; type: string };
2462
+
2463
+ async function fetchBytes(url: string, ua: string): Promise<Fetched | string> {
2464
+ try {
2465
+ const r = await fetch(url, {
2466
+ headers: { "user-agent": ua },
2467
+ signal: AbortSignal.timeout(20_000),
2468
+ });
2469
+ if (!r.ok) return `HTTP ${r.status}`;
2470
+ return { bytes: Buffer.from(await r.arrayBuffer()), type: r.headers.get("content-type") ?? "" };
2471
+ } catch (e) {
2472
+ return (e as Error).message;
2473
+ }
2474
+ }
2475
+
2476
+ /** the families a page's text is set in, and its stylesheets, read in Chrome */
2477
+ async function readSource(
2478
+ src: Exclude<Source, { kind: "look" }>,
2479
+ opts: FilmLookOptions,
2480
+ ): Promise<{
2481
+ reads: PageRead[];
2482
+ sheets: { text: string; base: string }[];
2483
+ vars: FilmLook["vars"];
2484
+ fetch: (url: string) => Promise<Fetched | string>;
2485
+ }> {
2486
+ if (!opts.chromePath) throw new Error("film look: a Chrome is needed to read the page");
2487
+ const { launchHtmlBrowser } = await import("../html/cdp");
2488
+ const { serveDirectory } = await import("../html/server");
2489
+ const { readFile } = await import("node:fs/promises");
2490
+ const { join } = await import("node:path");
2491
+ let width = opts.width ?? 1920;
2492
+ let height = opts.height ?? 1080;
2493
+ let server: Awaited<ReturnType<typeof serveDirectory>> | null = null;
2494
+ const urls: string[] = [];
2495
+ if (src.kind === "url") urls.push(src.url);
2496
+ else {
2497
+ server = await serveDirectory(src.root);
2498
+ for (const s of src.screens)
2499
+ urls.push(`${server.url}/${s.rel.split("/").map(encodeURIComponent).join("/")}`);
2500
+ try {
2501
+ const index = JSON.parse(
2502
+ await readFile(join(src.root, src.screens[0]!.id, "index.json"), "utf8"),
2503
+ );
2504
+ if (index?.viewport?.w && index?.viewport?.h) ({ w: width, h: height } = index.viewport);
2505
+ } catch {
2506
+ /* a screen without an index reads at the default size */
2507
+ }
2508
+ }
2509
+ let browser: import("../html/cdp").HtmlBrowser | null = null;
2510
+ try {
2511
+ browser = await launchHtmlBrowser({
2512
+ chromePath: opts.chromePath,
2513
+ url: urls[0]!,
2514
+ width: Math.round(width),
2515
+ height: Math.round(height),
2516
+ profilePrefix: "open-take-look-",
2517
+ ...(src.kind === "url" ? { initScript: QUIET_ERRORS_JS } : {}),
2518
+ onConsole: opts.onConsole,
2519
+ });
2520
+ const reads: PageRead[] = [];
2521
+ for (let i = 0; i < urls.length; i++) {
2522
+ if (i > 0) await navigate(browser, urls[i]!);
2523
+ await browser.evaluate(
2524
+ src.kind === "url" ? "new Promise((ok) => setTimeout(ok, 1500))" : STATE_READY_JS,
2525
+ {
2526
+ timeoutMs: 20_000,
2527
+ },
2528
+ );
2529
+ reads.push(await browser.evaluate<PageRead>(`(${PAGE_READ_JS})()`, { timeoutMs: 180_000 }));
2530
+ }
2531
+ const ua = reads[0]?.ua ?? "Mozilla/5.0";
2532
+ const fetchUrl = (url: string) => fetchBytes(url, ua);
2533
+ const sheets: { text: string; base: string }[] = [];
2534
+ const seen = new Set<string>();
2535
+ for (const r of reads)
2536
+ for (const s of r.sheets) {
2537
+ if (s.text != null) {
2538
+ if (!seen.has(s.text)) sheets.push({ text: s.text, base: r.url });
2539
+ seen.add(s.text);
2540
+ } else if (s.href && !seen.has(s.href) && /^https?:/.test(s.href)) {
2541
+ seen.add(s.href);
2542
+ const got = await fetchUrl(s.href);
2543
+ if (typeof got !== "string")
2544
+ sheets.push({ text: got.bytes.toString("utf8"), base: s.href });
2545
+ }
2546
+ }
2547
+ const names = new Set<string>();
2548
+ for (const s of sheets)
2549
+ for (const d of cssDeclarations(s.text))
2550
+ if (d.property.startsWith("--") && names.size < 600) names.add(d.property);
2551
+ const resolved = names.size
2552
+ ? await browser.evaluate<[string, string, string | null][]>(
2553
+ `(${VARS_JS})(${JSON.stringify([...names])})`,
2554
+ )
2555
+ : [];
2556
+ const vars = resolved.filter(([, v]) => v).map(([name, value, hex]) => ({ name, value, hex }));
2557
+ // a saved screen's fonts are fetched while its server still runs
2558
+ const cache = new Map<string, Fetched | string>();
2559
+ const all = sheets.flatMap((s) => parseFontFaces(s.text, s.base));
2560
+ if (server)
2561
+ for (const f of all)
2562
+ if (f.src?.startsWith(server.url) && !cache.has(f.src))
2563
+ cache.set(f.src, await fetchUrl(f.src));
2564
+ return {
2565
+ reads,
2566
+ sheets,
2567
+ vars,
2568
+ fetch: async (url) => {
2569
+ if (!cache.has(url))
2570
+ cache.set(url, /^https?:/.test(url) && !server ? await fetchUrl(url) : "not saved");
2571
+ return cache.get(url)!;
2572
+ },
2573
+ };
2574
+ } finally {
2575
+ await browser?.close();
2576
+ await server?.close();
2577
+ }
2578
+ }
2579
+
2580
+ type Where = [string, number][];
2581
+ const mergeWhere = (into: Map<string, number>, w: Where) => {
2582
+ for (const [k, n] of w) into.set(k, (into.get(k) ?? 0) + n);
2583
+ };
2584
+ const topWhere = (m: Map<string, number>, n = 4) =>
2585
+ [...m]
2586
+ .sort((a, b) => b[1] - a[1])
2587
+ .slice(0, n)
2588
+ .map(([k]) => k);
2589
+ const round = (v: number, d = 3) => Math.round(v * 10 ** d) / 10 ** d;
2590
+ const pctText = (v: number) => `${(v * 100).toFixed(v < 0.1 ? 1 : 0)} %`;
2591
+ const sameHex = (a: string, b: string) =>
2592
+ a.toLowerCase().replace(/^(#[0-9a-f]{6})ff$/, "$1") ===
2593
+ b.toLowerCase().replace(/^(#[0-9a-f]{6})ff$/, "$1");
2594
+
2595
+ /** Everything the reads saw, merged over the screens, as colours with uses. */
2596
+ function mergeReads(reads: PageRead[], vars: FilmLook["vars"]) {
2597
+ const samples = reads.reduce((s, r) => s + r.samples, 0) || 1;
2598
+ type Acc = {
2599
+ bg: number;
2600
+ bgInter: number;
2601
+ text: number;
2602
+ textInter: number;
2603
+ border: number;
2604
+ fill: number;
2605
+ grounds: Map<string, number>;
2606
+ where: Map<string, number>;
2607
+ };
2608
+ const acc = new Map<string, Acc>();
2609
+ const get = (hex: string): Acc => {
2610
+ let a = acc.get(hex);
2611
+ if (!a) {
2612
+ a = {
2613
+ bg: 0,
2614
+ bgInter: 0,
2615
+ text: 0,
2616
+ textInter: 0,
2617
+ border: 0,
2618
+ fill: 0,
2619
+ grounds: new Map(),
2620
+ where: new Map(),
2621
+ };
2622
+ acc.set(hex, a);
2623
+ }
2624
+ return a;
2625
+ };
2626
+ const gradients = new Map<string, { n: number; where: Map<string, number> }>();
2627
+ let images = 0;
2628
+ let gradientText = 0;
2629
+ for (const r of reads) {
2630
+ images += r.images;
2631
+ for (const b of r.backgrounds) {
2632
+ const a = get(b.hex);
2633
+ a.bg += b.n;
2634
+ a.bgInter += b.interactive;
2635
+ mergeWhere(a.where, b.where);
2636
+ }
2637
+ for (const t of r.texts) {
2638
+ if (!t.hex.startsWith("#")) {
2639
+ gradientText += t.chars;
2640
+ continue;
2641
+ }
2642
+ const a = get(t.hex);
2643
+ a.text += t.chars;
2644
+ a.textInter += t.interactive;
2645
+ mergeWhere(a.grounds, t.grounds);
2646
+ mergeWhere(a.where, t.where);
2647
+ }
2648
+ for (const b of r.borders) {
2649
+ const a = get(b.hex);
2650
+ a.border += b.length;
2651
+ mergeWhere(a.where, b.where);
2652
+ }
2653
+ for (const f of r.fills) {
2654
+ const a = get(f.hex);
2655
+ a.fill += f.area / reads.length;
2656
+ mergeWhere(a.where, f.where);
2657
+ }
2658
+ for (const g of r.gradients) {
2659
+ const e = gradients.get(g.value) ?? { n: 0, where: new Map() };
2660
+ e.n += g.n;
2661
+ mergeWhere(e.where, g.where);
2662
+ gradients.set(g.value, e);
2663
+ }
2664
+ }
2665
+ const totalChars = [...acc.values()].reduce((s, a) => s + a.text, 0) || 1;
2666
+ const colours: LookColour[] = [];
2667
+ for (const [hex, a] of acc) {
2668
+ const c = parseCssColor(hex)!;
2669
+ const uses = a.bg + a.text;
2670
+ colours.push({
2671
+ hex,
2672
+ background: round(a.bg / samples, 4),
2673
+ text: Math.round(a.text),
2674
+ border: Math.round(a.border),
2675
+ fill: round(a.fill, 4),
2676
+ interactive: uses ? round((a.bgInter + a.textInter) / uses, 2) : 0,
2677
+ on: [...a.grounds]
2678
+ .sort((x, y) => y[1] - x[1])
2679
+ .slice(0, 4)
2680
+ .map(([ground, chars]) => ({
2681
+ ground,
2682
+ chars: Math.round(chars),
2683
+ contrast: ground.startsWith("#") ? round(contrastRatio(hex, ground), 2) : null,
2684
+ })),
2685
+ where: topWhere(a.where),
2686
+ // a framework's internal variables after the product's own names
2687
+ vars: vars
2688
+ .filter((v) => v.hex && sameHex(v.hex, hex))
2689
+ .map((v) => v.name)
2690
+ .sort(
2691
+ (a, b) =>
2692
+ Number(a.startsWith("--tw-")) - Number(b.startsWith("--tw-")) || a.length - b.length,
2693
+ )
2694
+ .slice(0, 6),
2695
+ oklch: oklch(c).map((v, i) => round(v, i === 2 ? 1 : 3)) as [number, number, number],
2696
+ });
2697
+ }
2698
+ const weightOf = (c: LookColour) =>
2699
+ c.background * 100 + (c.text / totalChars) * 30 + c.border / 2000 + c.fill * 100;
2700
+ colours.sort((a, b) => weightOf(b) - weightOf(a));
2701
+ return {
2702
+ colours,
2703
+ totalChars,
2704
+ gradientText,
2705
+ imageShare: round(images / samples, 4),
2706
+ gradients: [...gradients]
2707
+ .sort((a, b) => b[1].n - a[1].n)
2708
+ .slice(0, 8)
2709
+ .map(([value, e]) => ({ value, share: round(e.n / samples, 4), where: topWhere(e.where) })),
2710
+ };
2711
+ }
2712
+
2713
+ /** An estimate of which colour plays which part, from where and how much each is used. */
2714
+ export function estimateRoles(
2715
+ colours: readonly LookColour[],
2716
+ totalChars: number,
2717
+ ): Record<RoleName, LookRole> {
2718
+ const none = (why: string): LookRole => ({
2719
+ hex: null,
2720
+ how: "not detected",
2721
+ why,
2722
+ where: [],
2723
+ vars: [],
2724
+ });
2725
+ const role = (c: LookColour, why: string, alternatives?: LookRole["alternatives"]): LookRole => ({
2726
+ hex: c.hex,
2727
+ how: "estimated",
2728
+ why,
2729
+ where: c.where,
2730
+ vars: c.vars,
2731
+ ...(alternatives?.length ? { alternatives } : {}),
2732
+ });
2733
+ const rgb = (c: LookColour) => parseCssColor(c.hex)!;
2734
+ const far = (a: LookColour, b: LookColour | undefined) => !b || okDistance(rgb(a), rgb(b)) > 0.02;
2735
+ const byBg = colours.filter((c) => c.background > 0).sort((a, b) => b.background - a.background);
2736
+ const bg = byBg[0];
2737
+ const surfaces = byBg.filter((c) => c !== bg && c.background >= 0.01 && far(c, bg));
2738
+ const byText = colours.filter((c) => c.text > 0).sort((a, b) => b.text - a.text);
2739
+ const contrastOf = (c: LookColour) => c.on[0]?.contrast ?? 0;
2740
+ // of the colours most text is set in (at least half the most-used one's
2741
+ // characters), the one standing out most from its ground
2742
+ const text = byText
2743
+ .filter((c) => c.text >= 0.5 * (byText[0]?.text ?? 0))
2744
+ .sort((a, b) => contrastOf(b) - contrastOf(a))[0];
2745
+ const mainGround = text?.on[0]?.ground;
2746
+ const textContrast = text ? contrastOf(text) : 21;
2747
+ const muted = byText.find(
2748
+ (c) =>
2749
+ c !== text &&
2750
+ c.text >= 0.02 * totalChars &&
2751
+ c.oklch[1] < 0.06 &&
2752
+ c.on[0]?.ground === mainGround &&
2753
+ contrastOf(c) < textContrast &&
2754
+ far(c, text),
2755
+ );
2756
+ const accentScore = (c: LookColour) => {
2757
+ const chroma = c.oklch[1];
2758
+ if (chroma < 0.06) return 0;
2759
+ const use =
2760
+ c.background * 1000 + c.fill * 1000 + (c.text / (totalChars || 1)) * 100 + c.border / 500;
2761
+ return chroma * chroma * (1 + 4 * c.interactive) * Math.log1p(use);
2762
+ };
2763
+ const accents = colours
2764
+ .filter((c) => c !== bg && accentScore(c) > 0)
2765
+ .sort((a, b) => accentScore(b) - accentScore(a));
2766
+ const accent = accents[0];
2767
+ const onAccent =
2768
+ accent &&
2769
+ colours
2770
+ .filter((c) => c.on.some((o) => o.ground === accent.hex))
2771
+ .sort(
2772
+ (a, b) =>
2773
+ (b.on.find((o) => o.ground === accent.hex)?.chars ?? 0) -
2774
+ (a.on.find((o) => o.ground === accent.hex)?.chars ?? 0),
2775
+ )[0];
2776
+ const border = colours.filter((c) => c.border > 0).sort((a, b) => b.border - a.border)[0];
2777
+ const useText = (c: LookColour) => {
2778
+ const parts: string[] = [];
2779
+ if (c.background) parts.push(`background on ${pctText(c.background)} of the screen`);
2780
+ if (c.text) parts.push(`${c.text} characters`);
2781
+ if (c.fill) parts.push(`icons/shapes on ${pctText(c.fill)}`);
2782
+ if (c.border) parts.push(`${c.border} px of border`);
2783
+ if (c.interactive) parts.push(`${pctText(c.interactive)} of it on links/buttons/inputs`);
2784
+ return parts.join(", ");
2785
+ };
2786
+ return {
2787
+ bg: bg
2788
+ ? role(bg, `the background covering the most sampled area (${pctText(bg.background)})`)
2789
+ : none("no painted background found"),
2790
+ surface: surfaces[0]
2791
+ ? role(
2792
+ surfaces[0],
2793
+ `the next background by area (${pctText(surfaces[0].background)}), unlike bg`,
2794
+ surfaces.slice(1, 4).map((c) => ({ hex: c.hex, why: useText(c) })),
2795
+ )
2796
+ : none("no second background covering ≥ 1 % of the screen"),
2797
+ text: text
2798
+ ? role(
2799
+ text,
2800
+ `of the colours most text is set in, the one with the most contrast on its ground (${text.text} of ${Math.round(totalChars)} characters, ${textContrast}:1 on ${mainGround})`,
2801
+ )
2802
+ : none("no visible text"),
2803
+ muted: muted
2804
+ ? role(
2805
+ muted,
2806
+ `a near-neutral text colour on the same ground with less contrast (${contrastOf(muted)}:1), ${muted.text} characters`,
2807
+ )
2808
+ : none("no second near-neutral text colour on the main text's ground with less contrast"),
2809
+ accent: accent
2810
+ ? role(
2811
+ accent,
2812
+ `the most chromatic colour weighed by use, links and buttons counting more: ${useText(accent)}`,
2813
+ accents.slice(1, 4).map((c) => ({ hex: c.hex, why: useText(c) })),
2814
+ )
2815
+ : none("no chromatic colour (OKLCH chroma ≥ 0.06) in use"),
2816
+ onAccent:
2817
+ accent && onAccent
2818
+ ? role(
2819
+ onAccent,
2820
+ `the text set most on the accent (${onAccent.on.find((o) => o.ground === accent.hex)?.chars} characters)`,
2821
+ )
2822
+ : none(accent ? "no text sits on the accent" : "no accent"),
2823
+ border: border
2824
+ ? role(border, `the border colour drawn longest (${border.border} px)`)
2825
+ : none("no visible borders"),
2826
+ };
2827
+ }
2828
+
2829
+ const slug = (s: string) =>
2830
+ s
2831
+ .toLowerCase()
2832
+ .replace(/[^a-z0-9]+/g, "-")
2833
+ .replace(/^-|-$/g, "") || "font";
2834
+
2835
+ function sniffExt(bytes: Buffer, fallback: string | null): string {
2836
+ const sig = bytes.toString("latin1", 0, 4);
2837
+ if (sig === "wOF2") return "woff2";
2838
+ if (sig === "wOFF") return "woff";
2839
+ if (sig === "OTTO") return "otf";
2840
+ if (sig === "ttcf") return "ttc";
2841
+ if (bytes.length >= 4 && bytes.readUInt32BE(0) === 0x00010000) return "ttf";
2842
+ return fallback ?? "bin";
2843
+ }
2844
+
2845
+ /** one face as the CSS declares it and as document.fonts reports it: the
2846
+ * same key (weights by number, the whole of Unicode when no range is given) */
2847
+ const facesKey = (f: { family: string; weight: string; style: string; unicodeRange: string }) => {
2848
+ const weight = normWeight(f.weight);
2849
+ const ranges = parseUnicodeRange(f.unicodeRange || "U+0-10FFFF");
2850
+ const cps = ranges.flatMap(([a, b]) =>
2851
+ b - a > 4096 ? [a, b] : Array.from({ length: b - a + 1 }, (_, i) => a + i),
2852
+ );
2853
+ return `${f.family.toLowerCase()}|${weight}|${f.style.trim() || "normal"}|${unicodeRangeOf(cps)}`;
2854
+ };
2855
+
2856
+ const normWeight = (w: string) =>
2857
+ w
2858
+ .trim()
2859
+ .replace(/\s+/g, " ")
2860
+ .replace(/\bnormal\b/g, "400")
2861
+ .replace(/\bbold\b/g, "700");
2862
+ /** one face of a family as a key: its files together serve its characters */
2863
+ const faceGroup = (family: string, weight: string, style: string) =>
2864
+ `${family.toLowerCase()}|${normWeight(weight)}|${style.trim() || "normal"}`;
2865
+
2866
+ /** cps the face is used for: its file's cmap within its unicode-range */
2867
+ function faceChars(info: FontInfo, unicodeRange: string): Set<number> {
2868
+ const ranges = parseUnicodeRange(unicodeRange);
2869
+ const out = new Set<number>();
2870
+ for (const cp of info.cmap.keys()) if (inRanges(cp, ranges)) out.add(cp);
2871
+ return out;
2872
+ }
2873
+
2874
+ export async function filmLook(opts: FilmLookOptions): Promise<FilmLookResult> {
2875
+ const { mkdir, readFile, writeFile, rm } = await import("node:fs/promises");
2876
+ const { existsSync } = await import("node:fs");
2877
+ const { createHash } = await import("node:crypto");
2878
+ const { basename, dirname, join, relative, resolve } = await import("node:path");
2879
+ const src = await resolveSource(opts.source, opts.states);
2880
+ const outDir = resolve(opts.out ?? (src.kind === "look" ? dirname(src.file) : "look"));
2881
+ await mkdir(join(outDir, "fonts"), { recursive: true });
2882
+ const notes: string[] = [];
2883
+ let look: FilmLook;
2884
+ /** every font file in reach, by family: parsed, with the face it serves */
2885
+ const files: {
2886
+ family: string;
2887
+ face: LookFontFile;
2888
+ info: FontInfo | null;
2889
+ path: string | null;
2890
+ }[] = [];
2891
+ /** declared faces with no file here (for missing characters) */
2892
+ let unfetched: (CssFontFace & { fetchable: boolean })[] = [];
2893
+ let fetchFont: ((url: string) => Promise<Fetched | string>) | null = null;
2894
+
2895
+ const savedAs = new Map<string, string>(); // content hash → file name: one copy of a file serving several faces
2896
+ const keepFile = async (
2897
+ family: string,
2898
+ face: LookFontFile,
2899
+ bytes: Buffer,
2900
+ ext: string | null,
2901
+ ) => {
2902
+ const sha = createHash("sha1").update(bytes).digest("hex").slice(0, 8);
2903
+ const name =
2904
+ savedAs.get(sha) ??
2905
+ `${slug(family)}-${slug(face.weight)}${face.style !== "normal" ? `-${slug(face.style)}` : ""}-${sha}.${sniffExt(bytes, ext)}`;
2906
+ savedAs.set(sha, name);
2907
+ const path = join(outDir, "fonts", name);
2908
+ if (!existsSync(path)) await writeFile(path, bytes);
2909
+ face.file = `fonts/${name}`;
2910
+ face.bytes = bytes.length;
2911
+ let info: FontInfo | null = null;
2912
+ try {
2913
+ info = parseFont(bytes);
2914
+ face.name = info.fullName || info.family;
2915
+ face.glyphs = info.glyphs;
2916
+ face.chars = faceChars(info, face.unicodeRange).size;
2917
+ face.outlines = info.outlines;
2918
+ if (info.axes.length) face.axes = info.axes;
2919
+ face.metrics = {
2920
+ unitsPerEm: info.unitsPerEm,
2921
+ capHeight: info.capHeight,
2922
+ xHeight: info.xHeight,
2923
+ ascender: info.ascender,
2924
+ descender: info.descender,
2925
+ };
2926
+ } catch (e) {
2927
+ face.status = `unreadable: ${(e as Error).message}`;
2928
+ }
2929
+ files.push({ family, face, info, path });
2930
+ };
2931
+
2932
+ if (src.kind === "look") {
2933
+ look = JSON.parse(await readFile(src.file, "utf8")) as FilmLook;
2934
+ if (look?.version !== 1) throw new Error(`film look: ${src.file} is not a look.json`);
2935
+ for (const f of look.fonts)
2936
+ for (const face of f.files) {
2937
+ if (!face.file) continue;
2938
+ const path = join(dirname(src.file), face.file);
2939
+ if (!existsSync(path)) continue;
2940
+ let info: FontInfo | null = null;
2941
+ try {
2942
+ info = parseFont(await readFile(path));
2943
+ } catch {
2944
+ /* listed but unreadable: left out of the check */
2945
+ }
2946
+ files.push({ family: f.family, face, info, path });
2947
+ }
2948
+ } else {
2949
+ const read = await readSource(src, opts);
2950
+ fetchFont = read.fetch;
2951
+ const { reads, sheets, vars } = read;
2952
+ const merged = mergeReads(reads, vars);
2953
+ const first = reads[0]!;
2954
+ // fonts: the families text is set in, merged over the screens
2955
+ type FamAcc = {
2956
+ webfont: boolean;
2957
+ chars: number;
2958
+ weights: Map<string, number>;
2959
+ sizes: Map<number, number>;
2960
+ stacks: Set<string>;
2961
+ };
2962
+ const fams = new Map<string, FamAcc>();
2963
+ for (const r of reads)
2964
+ for (const f of r.families) {
2965
+ const a = fams.get(f.family) ?? {
2966
+ webfont: f.webfont,
2967
+ chars: 0,
2968
+ weights: new Map(),
2969
+ sizes: new Map(),
2970
+ stacks: new Set(),
2971
+ };
2972
+ a.chars += f.chars;
2973
+ for (const [w, n] of f.weights) a.weights.set(w, (a.weights.get(w) ?? 0) + n);
2974
+ for (const [s, n] of f.sizes) a.sizes.set(s, (a.sizes.get(s) ?? 0) + n);
2975
+ for (const s of f.stacks) a.stacks.add(s);
2976
+ fams.set(f.family, a);
2977
+ }
2978
+ const totalFamChars = [...fams.values()].reduce((s, a) => s + a.chars, 0) || 1;
2979
+ const cssFaces = sheets.flatMap((s) => parseFontFaces(s.text, s.base));
2980
+ const loaded = new Set(
2981
+ reads.flatMap((r) => r.faces.filter((f) => f.status === "loaded").map(facesKey)),
2982
+ );
2983
+ const samples = reads.flatMap((r) => r.samples_);
2984
+ const fonts: LookFont[] = [];
2985
+ for (const [family, a] of [...fams].sort((x, y) => y[1].chars - x[1].chars)) {
2986
+ const declared = cssFaces.filter((f) => f.family.toLowerCase() === family.toLowerCase());
2987
+ const lf: LookFont = {
2988
+ family,
2989
+ webfont: a.webfont,
2990
+ chars: Math.round(a.chars),
2991
+ share: round(a.chars / totalFamChars, 3),
2992
+ weights: [...a.weights]
2993
+ .sort((x, y) => y[1] - x[1])
2994
+ .map(([weight, n]) => ({ weight, chars: Math.round(n) })),
2995
+ sizes: [...a.sizes]
2996
+ .sort((x, y) => y[1] - x[1])
2997
+ .slice(0, 12)
2998
+ .map(([px, n]) => ({ px, chars: Math.round(n) })),
2999
+ stacks: [...a.stacks].slice(0, 4),
3000
+ samples: [...new Set(samples.filter((s) => s.family === family).map((s) => s.text))].slice(
3001
+ 0,
3002
+ 8,
3003
+ ),
3004
+ files: [],
3005
+ declared: declared.length,
3006
+ missingFiles: 0,
3007
+ };
3008
+ const seenFace = new Set<string>();
3009
+ for (const f of declared) {
3010
+ const key = facesKey(f);
3011
+ if (seenFace.has(key)) continue;
3012
+ seenFace.add(key);
3013
+ const face: LookFontFile = {
3014
+ file: null,
3015
+ source: f.src,
3016
+ weight: f.weight,
3017
+ style: f.style,
3018
+ unicodeRange: f.unicodeRange,
3019
+ status: "not saved",
3020
+ };
3021
+ const want = src.kind === "url" ? loaded.has(key) : !!f.src && f.src !== "about:blank";
3022
+ if (want && f.src && f.src !== "about:blank") {
3023
+ const got = await read.fetch(f.src);
3024
+ if (typeof got !== "string") {
3025
+ face.status = src.kind === "url" ? "downloaded" : "saved";
3026
+ await keepFile(
3027
+ family,
3028
+ face,
3029
+ got.bytes,
3030
+ f.format?.replace(/^truetype$/, "ttf").replace(/^opentype$/, "otf") ?? null,
3031
+ );
3032
+ lf.files.push(face);
3033
+ continue;
3034
+ }
3035
+ face.status = `${src.kind === "url" ? "not downloaded" : "not saved"}: ${got}`;
3036
+ } else if (src.kind === "url") face.status = "not downloaded";
3037
+ unfetched.push({
3038
+ ...f,
3039
+ fetchable: src.kind === "url" && !!f.src && /^https?:/.test(f.src),
3040
+ });
3041
+ lf.missingFiles++;
3042
+ }
3043
+ fonts.push(lf);
3044
+ }
3045
+ const usedFamilies = new Set(fonts.map((f) => f.family.toLowerCase()));
3046
+ const declaredFamilies = [...new Set(cssFaces.map((f) => f.family))].filter(
3047
+ (f) => !usedFamilies.has(f.toLowerCase()),
3048
+ );
3049
+ // type scale
3050
+ const type = new Map<string, FilmLook["type"][number]>();
3051
+ for (const r of reads)
3052
+ for (const t of r.type) {
3053
+ const k = `${t.family}|${t.weight}|${t.size}`;
3054
+ const e = type.get(k) ?? {
3055
+ family: t.family,
3056
+ weight: t.weight,
3057
+ sizePx: t.size,
3058
+ chars: 0,
3059
+ sample: t.sample,
3060
+ where: t.where,
3061
+ };
3062
+ e.chars += t.chars;
3063
+ type.set(k, e);
3064
+ }
3065
+ const radii = new Map<string, { px: number; count: number; where: Map<string, number> }>();
3066
+ const shadows = new Map<string, { count: number; where: Map<string, number> }>();
3067
+ const used = new Map<string, { count: number; where: Map<string, number> }>();
3068
+ for (const r of reads) {
3069
+ for (const x of r.radii) {
3070
+ const e = radii.get(x.value) ?? { px: x.px, count: 0, where: new Map() };
3071
+ e.count += x.n;
3072
+ mergeWhere(e.where, x.where);
3073
+ radii.set(x.value, e);
3074
+ }
3075
+ for (const [list, map] of [
3076
+ [r.shadows, shadows],
3077
+ [r.transitions, used],
3078
+ ] as const)
3079
+ for (const x of list) {
3080
+ const e = map.get(x.value) ?? { count: 0, where: new Map() };
3081
+ e.count += x.n;
3082
+ mergeWhere(e.where, x.where);
3083
+ map.set(x.value, e);
3084
+ }
3085
+ }
3086
+ const frozen = reads.every((r) => r.frozen);
3087
+ const roles = estimateRoles(merged.colours, merged.totalChars);
3088
+ if (merged.gradientText)
3089
+ notes.push(
3090
+ `${Math.round(merged.gradientText)} characters are set in gradient-filled text (background-clip: text) — see gradients`,
3091
+ );
3092
+ if (merged.imageShare > 0.25)
3093
+ notes.push(
3094
+ `${pctText(merged.imageShare)} of the sampled screen is images, video or canvas — their colours are not read`,
3095
+ );
3096
+ const declared = cssMotion(sheets.map((s) => s.text));
3097
+ look = {
3098
+ version: 1,
3099
+ source: {
3100
+ kind: src.kind,
3101
+ input: opts.source,
3102
+ url:
3103
+ src.kind === "url"
3104
+ ? src.url
3105
+ : ((await readIndexUrl(src.root, src.screens[0]!.id)) ?? null),
3106
+ title: first.title || null,
3107
+ screens: src.kind === "url" ? [src.url] : src.screens.map((s) => s.id),
3108
+ skipped: src.kind === "url" ? [] : src.skipped,
3109
+ viewport: { width: first.width, height: first.height },
3110
+ },
3111
+ roles,
3112
+ colours: merged.colours.slice(0, 48),
3113
+ gradients: merged.gradients,
3114
+ imageShare: merged.imageShare,
3115
+ vars: vars.slice(0, 200),
3116
+ fonts,
3117
+ declaredFamilies,
3118
+ type: [...type.values()]
3119
+ .map((t) => ({ ...t, chars: Math.round(t.chars) }))
3120
+ .sort((a, b) => b.sizePx - a.sizePx || b.chars - a.chars)
3121
+ .slice(0, 24),
3122
+ radii: [...radii]
3123
+ .sort((a, b) => b[1].count - a[1].count)
3124
+ .slice(0, 12)
3125
+ .map(([value, e]) => ({
3126
+ value,
3127
+ px: round(e.px, 1),
3128
+ count: e.count,
3129
+ where: topWhere(e.where, 3),
3130
+ })),
3131
+ shadows: [...shadows]
3132
+ .sort((a, b) => b[1].count - a[1].count)
3133
+ .slice(0, 8)
3134
+ .map(([value, e]) => ({ value, count: e.count, where: topWhere(e.where, 3) })),
3135
+ motion: {
3136
+ declared: {
3137
+ durations: declared.durations.slice(0, 16),
3138
+ easings: declared.easings.slice(0, 12),
3139
+ keyframes: declared.keyframes.slice(0, 24),
3140
+ },
3141
+ used: frozen
3142
+ ? []
3143
+ : [...used]
3144
+ .sort((a, b) => b[1].count - a[1].count)
3145
+ .slice(0, 16)
3146
+ .map(([value, e]) => ({ value, count: e.count, where: topWhere(e.where, 3) })),
3147
+ usedHow: frozen ? "not detected" : used.size ? "measured" : "not detected",
3148
+ },
3149
+ labels: {
3150
+ colours: merged.colours.length ? "measured" : "not detected",
3151
+ roles: "estimated",
3152
+ fonts: fonts.length ? "measured" : "not detected",
3153
+ type: type.size ? "measured" : "not detected",
3154
+ radii: radii.size ? "measured" : "not detected",
3155
+ shadows: shadows.size ? "measured" : "not detected",
3156
+ motion: declared.durations.length || declared.easings.length ? "measured" : "not detected",
3157
+ },
3158
+ notes,
3159
+ };
3160
+ if (frozen)
3161
+ notes.push(
3162
+ "a saved screen holds its motion still, so no transition is read as playing on it — motion.declared is what the CSS says; read a URL for what plays",
3163
+ );
3164
+ notes.push(
3165
+ "motion timings are the product interface's own, as its CSS declares them: one possible source for the film's motion, nothing more",
3166
+ );
3167
+ }
3168
+
3169
+ // --- the film's words against the fonts ---
3170
+ const extra: string[] = [];
3171
+ for (const f of opts.fontFiles ?? []) {
3172
+ const path = resolve(f);
3173
+ const bytes = await readFile(path).catch(() => null);
3174
+ if (!bytes) throw new Error(`film look: no font file at ${f}`);
3175
+ let info: FontInfo;
3176
+ try {
3177
+ info = parseFont(bytes);
3178
+ } catch (e) {
3179
+ throw new Error(`film look: ${f}: ${(e as Error).message}`);
3180
+ }
3181
+ // a variable font serves its whole weight axis, under its family name
3182
+ // without the default instance's weight ("Noto Sans TC Thin" when the
3183
+ // file gives no typographic family)
3184
+ const wght = info.axes.find((a) => a.tag === "wght");
3185
+ const family = (wght ? info.family.replace(WEIGHT_WORD, "") : info.family) || basename(path);
3186
+ files.push({
3187
+ family,
3188
+ face: {
3189
+ file: null,
3190
+ source: path,
3191
+ weight: wght ? `${wght.min} ${wght.max}` : String(info.weight),
3192
+ style: info.italic ? "italic" : "normal",
3193
+ unicodeRange: "",
3194
+ status: "given",
3195
+ },
3196
+ info,
3197
+ path,
3198
+ });
3199
+ extra.push(family);
3200
+ }
3201
+ let filmWords = opts.text ?? "";
3202
+ const sourcesChecked: string[] = [];
3203
+ if (opts.text) sourcesChecked.push("--text");
3204
+ if (opts.page) {
3205
+ const t = await filmText(opts.page);
3206
+ filmWords += `\n${t.text}`;
3207
+ sourcesChecked.push(
3208
+ ...t.files.map((f) => {
3209
+ const rel = relative(process.cwd(), f);
3210
+ return rel && !rel.startsWith("..") ? rel : f;
3211
+ }),
3212
+ );
3213
+ }
3214
+ if (opts.fonts && !filmWords.trim())
3215
+ throw new Error(
3216
+ "film look: --fonts packs the fonts for the film's words — give --text or --page",
3217
+ );
3218
+ let css: string | null = null;
3219
+ if (filmWords.trim()) {
3220
+ const cps = glyphChars(filmWords);
3221
+ // coverage per face (family, weight, style): a browser setting a weight
3222
+ // whose files lack a character falls back to the next family in the
3223
+ // stack, not to another weight of the same family that has it
3224
+ const coverageOf = () => {
3225
+ const byFace = new Map<
3226
+ string,
3227
+ { family: string; weight: string; style: string; set: Set<number> }
3228
+ >();
3229
+ for (const f of files) {
3230
+ if (!f.info) continue;
3231
+ const k = faceGroup(f.family, f.face.weight, f.face.style);
3232
+ const e = byFace.get(k) ?? {
3233
+ family: f.family,
3234
+ weight: normWeight(f.face.weight),
3235
+ style: f.face.style.trim() || "normal",
3236
+ set: new Set<number>(),
3237
+ };
3238
+ for (const cp of faceChars(f.info, f.face.unicodeRange)) e.set.add(cp);
3239
+ byFace.set(k, e);
3240
+ }
3241
+ return byFace;
3242
+ };
3243
+ let byFace = coverageOf();
3244
+ const covered = (cp: number) => [...byFace.values()].some((e) => e.set.has(cp));
3245
+ /** the film's characters a declared face would serve that no file here does —
3246
+ * none at all, or not at the weight and style of a face that has files */
3247
+ const gapsOf = (f: CssFontFace) => {
3248
+ const ranges = parseUnicodeRange(f.unicodeRange);
3249
+ const own = byFace.get(faceGroup(f.family, f.weight, f.style))?.set;
3250
+ return cps.filter((cp) => inRanges(cp, ranges) && (!covered(cp) || (own && !own.has(cp))));
3251
+ };
3252
+ // a live product's faces for the missing characters are fetched now —
3253
+ // again while a face fetched gives its weight characters to check
3254
+ for (let pass = 0; pass < 4 && fetchFont; pass++) {
3255
+ let added = false;
3256
+ for (const f of unfetched) {
3257
+ if (!f.fetchable || !f.src) continue;
3258
+ if (!gapsOf(f).length) continue;
3259
+ f.fetchable = false;
3260
+ const got = await fetchFont(f.src);
3261
+ if (typeof got === "string") continue;
3262
+ const lf = look.fonts.find((x) => x.family.toLowerCase() === f.family.toLowerCase());
3263
+ if (!lf) continue;
3264
+ const face: LookFontFile = {
3265
+ file: null,
3266
+ source: f.src,
3267
+ weight: f.weight,
3268
+ style: f.style,
3269
+ unicodeRange: f.unicodeRange,
3270
+ status: "downloaded (for the film's words)",
3271
+ };
3272
+ await keepFile(lf.family, face, got.bytes, null);
3273
+ lf.files.push(face);
3274
+ lf.missingFiles = Math.max(0, lf.missingFiles - 1);
3275
+ byFace = coverageOf();
3276
+ added = true;
3277
+ }
3278
+ if (!added) break;
3279
+ }
3280
+ unfetched = unfetched.filter(
3281
+ (f) => f.fetchable || !f.src || !files.some((x) => x.face.source === f.src),
3282
+ );
3283
+ const missing = cps.filter((cp) => !covered(cp));
3284
+ const elsewhere = new Map<
3285
+ string,
3286
+ { family: string; weight: string; style: string; src: string | null; chars: Set<number> }
3287
+ >();
3288
+ for (const f of unfetched) {
3289
+ const hit = gapsOf(f);
3290
+ if (!hit.length) continue;
3291
+ const k = `${f.family}|${f.weight}|${f.style}`;
3292
+ const e = elsewhere.get(k) ?? {
3293
+ family: f.family,
3294
+ weight: f.weight,
3295
+ style: f.style,
3296
+ src: f.src,
3297
+ chars: new Set<number>(),
3298
+ };
3299
+ for (const cp of hit) e.chars.add(cp);
3300
+ elsewhere.set(k, e);
3301
+ }
3302
+ look.glyphs = {
3303
+ how: "measured",
3304
+ source: sourcesChecked,
3305
+ chars: cps.length,
3306
+ missing: missing.map((cp) => ({ char: String.fromCodePoint(cp), code: codeLabel(cp) })),
3307
+ byFamily: [...byFace.values()].map(({ family, weight, style, set }) => {
3308
+ const lacks = cps.filter((cp) => !set.has(cp));
3309
+ return {
3310
+ family,
3311
+ weight,
3312
+ style,
3313
+ covered: cps.length - lacks.length,
3314
+ lacks: lacks.map((cp) => String.fromCodePoint(cp)).join(""),
3315
+ };
3316
+ }),
3317
+ declaredElsewhere: [...elsewhere.values()].map((e) => ({
3318
+ family: e.family,
3319
+ weight: e.weight,
3320
+ style: e.style,
3321
+ src: e.src,
3322
+ chars: [...e.chars].map((cp) => String.fromCodePoint(cp)).join(""),
3323
+ })),
3324
+ };
3325
+ look.labels.glyphs = "measured";
3326
+ if (opts.fonts) {
3327
+ const pack = await packageFonts({
3328
+ dir: resolve(opts.fonts),
3329
+ chars: cps,
3330
+ files: files
3331
+ .filter((f) => f.info && f.path)
3332
+ .map((f) => ({
3333
+ family: f.family,
3334
+ weight: f.face.weight,
3335
+ style: f.face.style,
3336
+ unicodeRange: f.face.unicodeRange,
3337
+ path: f.path!,
3338
+ })),
3339
+ });
3340
+ look.packaged = pack;
3341
+ css = pack.css;
3342
+ }
3343
+ }
3344
+
3345
+ const json = join(outDir, "look.json");
3346
+ await writeFile(json, `${JSON.stringify(look, null, 2)}\n`);
3347
+ await writeFile(join(outDir, "look.css"), lookCss(look));
3348
+ let png: string | null = null;
3349
+ if (!opts.noPicture && opts.chromePath) {
3350
+ png = join(outDir, "look.png");
3351
+ await drawSpecimen(look, outDir, png, opts.chromePath, filmWords);
3352
+ }
3353
+ if (src.kind !== "look" && !look.fonts.some((f) => f.files.length))
3354
+ await rm(join(outDir, "fonts"), { recursive: true, force: true }).catch(() => {});
3355
+ return { look, json, png, css };
3356
+ }
3357
+
3358
+ const WEIGHT_WORD =
3359
+ /\s+(?:Thin|Hairline|(?:Extra|Ultra)[ -]?Light|Light|Regular|Book|Medium|(?:Semi|Demi)[ -]?Bold|(?:Extra|Ultra)[ -]?Bold|Bold|Black|Heavy)$/i;
3360
+
3361
+ async function readIndexUrl(root: string, id: string): Promise<string | null> {
3362
+ const { readFile } = await import("node:fs/promises");
3363
+ const { join } = await import("node:path");
3364
+ try {
3365
+ return (JSON.parse(await readFile(join(root, id, "index.json"), "utf8")).url as string) ?? null;
3366
+ } catch {
3367
+ return null;
3368
+ }
3369
+ }
3370
+
3371
+ const SPACES = [0x20, 0xa0, 0x2002, 0x2003, 0x2009, 0x200a, 0x202f, 0x3000];
3372
+
3373
+ /** Font files cut down to the characters each serves of `chars`, written to
3374
+ * `dir` with a fonts.css of @font-face rules (each unicode-range the
3375
+ * characters the file kept). A file serving none of them is left out. */
3376
+ export async function packageFonts(opts: {
3377
+ dir: string;
3378
+ chars: Iterable<number>;
3379
+ files: { family: string; weight: string; style: string; unicodeRange?: string; path: string }[];
3380
+ }): Promise<LookPackage> {
3381
+ const { mkdir, readFile, writeFile } = await import("node:fs/promises");
3382
+ const { join } = await import("node:path");
3383
+ const { createHash } = await import("node:crypto");
3384
+ await mkdir(opts.dir, { recursive: true });
3385
+ const want = new Set(opts.chars);
3386
+ const rules: string[] = [];
3387
+ const out: LookPackage["files"] = [];
3388
+ // a file serving several faces (a variable font declared per weight) is cut once
3389
+ const written = new Map<string, string>();
3390
+ for (const f of opts.files) {
3391
+ const bytes = await readFile(f.path);
3392
+ const info = parseFont(bytes);
3393
+ const served = faceChars(info, f.unicodeRange ?? "");
3394
+ const cps = [...served].filter((cp) => want.has(cp));
3395
+ if (!cps.length) continue;
3396
+ const asked = cps.length;
3397
+ // the spaces it has go along: a space from another font would set the
3398
+ // words at another width
3399
+ for (const sp of SPACES) if (served.has(sp) && !want.has(sp)) cps.push(sp);
3400
+ const sub = subsetFont(bytes, cps);
3401
+ const ext = sub.how === "subset" ? "woff" : sniffExt(bytes, "bin");
3402
+ const sha = createHash("sha1").update(sub.data).digest("hex").slice(0, 8);
3403
+ const name =
3404
+ written.get(sha) ??
3405
+ `${slug(f.family)}-${slug(f.weight)}${f.style !== "normal" ? `-${slug(f.style)}` : ""}-${sha}.${ext}`;
3406
+ if (!written.has(sha)) await writeFile(join(opts.dir, name), sub.data);
3407
+ written.set(sha, name);
3408
+ const format = { woff: "woff", woff2: "woff2", ttf: "truetype", otf: "opentype" }[ext] ?? ext;
3409
+ rules.push(
3410
+ `@font-face {\n font-family: ${JSON.stringify(f.family)};\n font-weight: ${f.weight};\n font-style: ${f.style};\n font-display: block;\n src: url(${JSON.stringify(name)}) format(${JSON.stringify(format)});\n unicode-range: ${unicodeRangeOf(cps)};\n}`,
3411
+ );
3412
+ out.push({
3413
+ file: name,
3414
+ family: f.family,
3415
+ weight: f.weight,
3416
+ style: f.style,
3417
+ chars: asked,
3418
+ bytes: sub.data.length,
3419
+ from: f.path,
3420
+ fromBytes: bytes.length,
3421
+ how: sub.how,
3422
+ ...(sub.why ? { why: sub.why } : {}),
3423
+ });
3424
+ }
3425
+ const css = join(opts.dir, "fonts.css");
3426
+ await writeFile(
3427
+ css,
3428
+ `/* the film's fonts, cut down to its words by \`open-take film look\` — link this file and use the families by name */\n${rules.join("\n")}\n`,
3429
+ );
3430
+ return { dir: opts.dir, css, files: out };
3431
+ }
3432
+
3433
+ /** @font-face rules for every font file in the look, and the roles as custom properties */
3434
+ function lookCss(look: FilmLook): string {
3435
+ const L: string[] = [
3436
+ "/* the product's look, read by `open-take film look` — its own fonts and colours; use any of it or none */",
3437
+ ];
3438
+ for (const f of look.fonts)
3439
+ for (const face of f.files) {
3440
+ if (!face.file) continue;
3441
+ const ext = face.file.split(".").pop()!;
3442
+ const format = { woff: "woff", woff2: "woff2", ttf: "truetype", otf: "opentype" }[ext] ?? ext;
3443
+ L.push(
3444
+ `@font-face { font-family: ${JSON.stringify(f.family)}; font-weight: ${face.weight}; font-style: ${face.style}; src: url(${JSON.stringify(face.file)}) format(${JSON.stringify(format)});${face.unicodeRange ? ` unicode-range: ${face.unicodeRange};` : ""} }`,
3445
+ );
3446
+ }
3447
+ L.push(":root {");
3448
+ for (const [name, r] of Object.entries(look.roles))
3449
+ if (r.hex)
3450
+ L.push(
3451
+ ` --look-${name.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`)}: ${r.hex}; /* ${r.how}: ${r.why.replace(/\*\//g, "")} */`,
3452
+ );
3453
+ const fam = (f: LookFont) => `${JSON.stringify(f.family)}`;
3454
+ const webfonts = look.fonts.filter((f) => f.webfont);
3455
+ if (webfonts.length) L.push(` --look-font: ${webfonts.map(fam).join(", ")};`);
3456
+ L.push("}");
3457
+ return `${L.join("\n")}\n`;
3458
+ }
3459
+
3460
+ // --- the specimen -------------------------------------------------------------
3461
+
3462
+ const esc = (s: string) =>
3463
+ s.replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c]!);
3464
+
3465
+ /** black or white, whichever reads better on `hex` */
3466
+ const inkOn = (hex: string) =>
3467
+ contrastRatio("#000000", hex) >= contrastRatio("#ffffff", hex) ? "#000" : "#fff";
3468
+
3469
+ /** the film's own lines worth trying in the product's fonts: distinct, longest first */
3470
+ function filmLines(words: string): string[] {
3471
+ const lines = words
3472
+ .split(/\n+/)
3473
+ .map((l) => l.replace(/\s+/g, " ").trim())
3474
+ .filter(
3475
+ (l) =>
3476
+ l.length >= 2 &&
3477
+ l.length <= 48 &&
3478
+ /[\p{L}\p{N}]/u.test(l) &&
3479
+ !/^[\w.-]+\.(js|css|png|mp4|wav|json|html)$/i.test(l),
3480
+ );
3481
+ return [...new Set(lines)].sort((a, b) => b.length - a.length).slice(0, 3);
3482
+ }
3483
+
3484
+ /** look.png: the colours as swatches, each family set at film sizes with the
3485
+ * product's own words (and the film's, when given), radii, shadows, easings —
3486
+ * on a 1920×1080 frame, in the product's own font files. */
3487
+ async function drawSpecimen(
3488
+ look: FilmLook,
3489
+ outDir: string,
3490
+ png: string,
3491
+ chromePath: string,
3492
+ words: string,
3493
+ ) {
3494
+ const { writeFile, rm } = await import("node:fs/promises");
3495
+ const { join } = await import("node:path");
3496
+ const { launchHtmlBrowser } = await import("../html/cdp");
3497
+ const { serveDirectory } = await import("../html/server");
3498
+ const bg = look.roles.bg.hex ?? "#ffffff";
3499
+ const ink = look.roles.text.hex ?? inkOn(bg);
3500
+ const note = look.roles.muted.hex ?? ink;
3501
+ const faces = look.fonts
3502
+ .flatMap((f) =>
3503
+ f.files
3504
+ .filter((x) => x.file)
3505
+ .map(
3506
+ (x) =>
3507
+ `@font-face{font-family:${JSON.stringify(f.family)};font-weight:${x.weight};font-style:${x.style};src:url(${JSON.stringify(x.file)});${x.unicodeRange ? `unicode-range:${x.unicodeRange};` : ""}}`,
3508
+ ),
3509
+ )
3510
+ .join("\n");
3511
+ const roleTiles = (Object.entries(look.roles) as [RoleName, LookRole][])
3512
+ .map(([name, r]) =>
3513
+ r.hex
3514
+ ? `<div class="tile" style="background:${r.hex};color:${inkOn(r.hex)}"><b>${name}</b> ${esc(r.hex)}<small>${esc(r.vars[0] ?? r.where[0] ?? "")}</small></div>`
3515
+ : `<div class="tile none"><b>${name}</b> not detected</div>`,
3516
+ )
3517
+ .join("");
3518
+ const chips = look.colours
3519
+ .slice(0, 24)
3520
+ .map((c) => `<span class="chip" style="background:${c.hex}" title="${esc(c.hex)}"></span>`)
3521
+ .join("");
3522
+ const fams = look.fonts.filter((f) => f.files.length || !f.webfont).slice(0, 3);
3523
+ const lines = filmLines(words);
3524
+ const typeRows = fams
3525
+ .map((f, i) => {
3526
+ const heavy = f.weights.map((w) => Number(w.weight)).filter(Number.isFinite);
3527
+ const big = look.type.find((t) => t.family === f.family);
3528
+ const sample = esc((big?.sample ?? f.samples[0] ?? f.family).slice(0, 28));
3529
+ const second = esc((f.samples.find((s) => s !== big?.sample) ?? "").slice(0, 40));
3530
+ const sizes = f.sizes.map((s) => s.px);
3531
+ const meta = `${esc(f.family)} · ${f.chars} chars (${pctText(f.share)}) · weights ${[...new Set(heavy)].sort((a, b) => a - b).join(" ")} · ${sizes.length ? `${Math.min(...sizes)}–${Math.max(...sizes)} px on the page` : ""} · ${f.webfont ? `${new Set(f.files.map((x) => x.file)).size} file(s) here${f.missingFiles ? `, ${f.missingFiles} declared face(s) without a file` : ""}` : "not a web font"}`;
3532
+ const fam = `${JSON.stringify(f.family).replace(/"/g, "&quot;")}, sans-serif`;
3533
+ return `<div class="fam"><div class="meta">${meta}</div>
3534
+ <div style="font-family:${fam};font-weight:${big?.weight ?? 700};font-size:${i === 0 ? 92 : 64}px;line-height:1.15" class="line">${sample}</div>
3535
+ ${second ? `<div style="font-family:${fam};font-weight:${f.weights[0]?.weight ?? 400};font-size:36px" class="line">${second}</div>` : ""}
3536
+ ${i === 0 && lines.length ? `<div class="meta">the film's words</div>${lines.map((l) => `<div style="font-family:${fam};font-weight:${big?.weight ?? 700};font-size:56px" class="line">${esc(l)}</div>`).join("")}` : ""}</div>`;
3537
+ })
3538
+ .join("");
3539
+ const surface = look.roles.surface.hex ?? look.roles.accent.hex ?? "#888";
3540
+ const border = look.roles.border.hex ?? "transparent";
3541
+ const radii = look.radii
3542
+ .slice(0, 6)
3543
+ .map(
3544
+ (r) =>
3545
+ `<div class="rad"><div style="background:${surface};border:1px solid ${border};border-radius:${r.value === "circle" ? "50%" : r.value === "pill" ? "999px" : r.value};${r.value === "circle" ? "width:72px;" : ""}"></div><small>${esc(r.value)} ×${r.count}</small></div>`,
3546
+ )
3547
+ .join("");
3548
+ const shadows = look.shadows
3549
+ .slice(0, 4)
3550
+ .map(
3551
+ (s) =>
3552
+ `<div class="shadow" style="box-shadow:${esc(s.value)};background:${bg}"><small>×${s.count}</small></div>`,
3553
+ )
3554
+ .join("");
3555
+ const curves = look.motion.declared.easings
3556
+ .filter((e) => /^cubic-bezier|^ease|^linear$/.test(e.value))
3557
+ .slice(0, 4)
3558
+ .map((e) => {
3559
+ const named: Record<string, number[]> = {
3560
+ ease: [0.25, 0.1, 0.25, 1],
3561
+ "ease-in": [0.42, 0, 1, 1],
3562
+ "ease-out": [0, 0, 0.58, 1],
3563
+ "ease-in-out": [0.42, 0, 0.58, 1],
3564
+ linear: [0, 0, 1, 1],
3565
+ };
3566
+ const p =
3567
+ named[e.value] ??
3568
+ (/cubic-bezier\(([^)]*)\)/.exec(e.value)?.[1] ?? "").split(",").map(Number);
3569
+ if (p.length !== 4 || !p.every(Number.isFinite)) return "";
3570
+ const [x1, y1, x2, y2] = p as [number, number, number, number];
3571
+ return `<div class="ease"><svg viewBox="-0.1 -0.4 1.2 1.8" width="64" height="80"><path d="M0 1 C${x1} ${1 - y1} ${x2} ${1 - y2} 1 0" fill="none" stroke="${look.roles.accent.hex ?? ink}" stroke-width="0.04"/><rect x="0" y="0" width="1" height="1" fill="none" stroke="${note}" stroke-width="0.01"/></svg><small>${esc(e.value)} ×${e.count}</small></div>`;
3572
+ })
3573
+ .join("");
3574
+ const durs = look.motion.declared.durations
3575
+ .slice(0, 6)
3576
+ .map((d) => `${d.ms} ms ×${d.count}`)
3577
+ .join(" · ");
3578
+ const html = `<!doctype html><html><head><meta charset="utf-8"><style>
3579
+ ${faces}
3580
+ html,body{margin:0;width:1920px;height:1080px;overflow:hidden;background:${bg};color:${ink}}
3581
+ body{font:15px/1.35 system-ui,-apple-system,"Segoe UI",sans-serif;display:grid;grid-template-columns:760px minmax(0,1fr);gap:40px;padding:44px 56px;box-sizing:border-box}
3582
+ body>div{min-width:0}
3583
+ h2{font:600 13px system-ui,sans-serif;letter-spacing:.08em;text-transform:uppercase;color:${note};margin:0 0 12px}
3584
+ .tiles{display:grid;grid-template-columns:1fr 1fr;gap:10px}
3585
+ .tile{height:74px;border-radius:10px;padding:10px 14px;box-sizing:border-box;font:16px system-ui,sans-serif;box-shadow:inset 0 0 0 1px rgba(127,127,127,.25)}
3586
+ .tile b{display:block;font-size:13px;letter-spacing:.06em;text-transform:uppercase;opacity:.8}
3587
+ .tile small{display:block;opacity:.7;font-size:12px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
3588
+ .tile.none{border:1px dashed ${note};box-shadow:none;color:${note}}
3589
+ .chips{display:flex;flex-wrap:wrap;gap:6px;margin:0 0 22px}.chip{width:36px;height:36px;border-radius:6px;box-shadow:inset 0 0 0 1px rgba(127,127,127,.3)}
3590
+ .row{display:flex;gap:16px;align-items:flex-end;margin-bottom:20px;flex-wrap:nowrap;overflow:hidden}
3591
+ .rad div{width:96px;height:56px}.rad small,.ease small,.shadow small{display:block;margin-top:6px;color:${note};font-size:12px;max-width:150px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
3592
+ .shadow{width:130px;height:64px;border-radius:10px;padding:8px;box-sizing:border-box;margin:0 6px}
3593
+ .fam{margin-bottom:26px}.meta{color:${note};font-size:14px;margin:6px 0}.line{white-space:nowrap;overflow:hidden;text-overflow:clip}
3594
+ .src{position:absolute;right:56px;bottom:16px;color:${note};font-size:12px;max-width:1000px;text-align:right;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
3595
+ </style></head><body>
3596
+ <div><h2>colour roles (estimated)</h2><div class="tiles">${roleTiles}</div>
3597
+ <h2 style="margin-top:18px">every colour, most used first</h2><div class="chips">${chips}</div>
3598
+ ${radii ? `<h2>radii, most used first</h2><div class="row">${radii}</div>` : ""}
3599
+ ${shadows ? `<h2>shadows</h2><div class="row" style="overflow:visible">${shadows}</div>` : ""}
3600
+ ${curves || durs ? `<h2>motion declared in its CSS</h2><div class="row">${curves}</div><div class="meta">${esc(durs)}</div>` : ""}
3601
+ </div>
3602
+ <div><h2>type — the product's own words in its own files, at film size</h2>${typeRows || '<div class="meta">no text read</div>'}</div>
3603
+ <script>for (const el of document.querySelectorAll(".line")) { let s = parseFloat(getComputedStyle(el).fontSize); while (el.scrollWidth > el.clientWidth + 1 && s > 16) { s -= 2; el.style.fontSize = s + "px"; } }</script>
3604
+ <div class="src">${esc(look.source.title ?? "")} — ${esc(look.source.url ?? look.source.input)} · ${esc(look.source.screens.join(" "))}</div>
3605
+ </body></html>`;
3606
+ const page = join(outDir, `.look-specimen-${process.pid}.html`);
3607
+ await writeFile(page, html);
3608
+ const server = await serveDirectory(outDir);
3609
+ let browser: import("../html/cdp").HtmlBrowser | null = null;
3610
+ try {
3611
+ browser = await launchHtmlBrowser({
3612
+ chromePath,
3613
+ url: `${server.url}/${encodeURIComponent(`.look-specimen-${process.pid}.html`)}`,
3614
+ width: 1920,
3615
+ height: 1080,
3616
+ profilePrefix: "open-take-look-",
3617
+ });
3618
+ // the lines are fitted once the fonts are in, then drawn
3619
+ await browser.evaluate(
3620
+ `document.fonts.ready.then(() => { for (const el of document.querySelectorAll(".line")) { let s = parseFloat(getComputedStyle(el).fontSize); while (el.scrollWidth > el.clientWidth + 1 && s > 16) { s -= 2; el.style.fontSize = s + "px"; } } return new Promise((ok) => setTimeout(ok, 100)); })`,
3621
+ );
3622
+ await writeFile(png, await browser.screenshot());
3623
+ } finally {
3624
+ await browser?.close();
3625
+ await server.close();
3626
+ await rm(page, { force: true });
3627
+ }
3628
+ }
3629
+
3630
+ // --- the report -----------------------------------------------------------------
3631
+
3632
+ export function formatFilmLook(look: FilmLook): string {
3633
+ const L: string[] = [];
3634
+ const s = look.source;
3635
+ L.push(`# film look — ${s.title ?? s.input}`);
3636
+ L.push("");
3637
+ L.push(
3638
+ `${s.url ?? s.input}; ${s.screens.length} screen(s) read${s.viewport ? ` at ${s.viewport.width}×${s.viewport.height}` : ""}${s.skipped.length ? `; skipped ${s.skipped.join(", ")}` : ""}. Each line says how it was found: measured, estimated, not detected. These are the product's own values — what to use is the film's choice.`,
3639
+ );
3640
+ L.push("");
3641
+ L.push("## Colour roles");
3642
+ L.push("[estimated] from where and how much each colour is used:");
3643
+ for (const [name, r] of Object.entries(look.roles) as [RoleName, LookRole][]) {
3644
+ L.push(
3645
+ r.hex
3646
+ ? ` ${name.padEnd(9)} ${r.hex.padEnd(10)} ${r.why}${r.vars.length ? `; var ${r.vars.join(", ")}` : ""}${r.where.length ? `; on ${r.where.slice(0, 2).join(", ")}` : ""}`
3647
+ : ` ${name.padEnd(9)} [not detected] ${r.why}`,
3648
+ );
3649
+ for (const a of r.alternatives ?? []) L.push(` ${"".padEnd(9)} or ${a.hex}: ${a.why}`);
3650
+ }
3651
+ L.push("");
3652
+ L.push(`## Colours (${look.colours.length})`);
3653
+ if (!look.colours.length) L.push("[not detected] no painted colour");
3654
+ else
3655
+ L.push(
3656
+ "[measured] background = share of the sampled screen; text = characters (on ground, contrast); border = px of edge",
3657
+ );
3658
+ for (const c of look.colours.slice(0, 14)) {
3659
+ const parts: string[] = [];
3660
+ if (c.background) parts.push(`background ${pctText(c.background)}`);
3661
+ if (c.text)
3662
+ parts.push(
3663
+ `text ${c.text}${c.on[0] ? ` (on ${c.on[0].ground}${c.on[0].contrast != null ? `, ${c.on[0].contrast}:1` : ""})` : ""}`,
3664
+ );
3665
+ if (c.fill) parts.push(`icons ${pctText(c.fill)}`);
3666
+ if (c.border) parts.push(`border ${c.border} px`);
3667
+ L.push(
3668
+ ` ${c.hex.padEnd(10)} ${parts.join(", ")}${c.vars.length ? ` — ${c.vars.slice(0, 2).join(", ")}` : ""} — ${c.where.slice(0, 2).join(", ")}`,
3669
+ );
3670
+ }
3671
+ if (look.gradients.length)
3672
+ L.push(
3673
+ `[measured] gradients: ${look.gradients
3674
+ .slice(0, 3)
3675
+ .map((g) => `${pctText(g.share)} ${g.value.slice(0, 80)}`)
3676
+ .join(" | ")}`,
3677
+ );
3678
+ if (look.imageShare)
3679
+ L.push(
3680
+ `[measured] images, video, canvas: ${pctText(look.imageShare)} of the sampled screen (not read for colour)`,
3681
+ );
3682
+ L.push("");
3683
+ L.push("## Fonts");
3684
+ if (!look.fonts.length) L.push("[not detected] no visible text");
3685
+ for (const f of look.fonts) {
3686
+ L.push(
3687
+ `[measured] ${f.family}${f.webfont ? "" : " (not a web font: the reading machine's own, or generic)"} — ${f.chars} chars (${pctText(f.share)}), weights ${f.weights.map((w) => `${w.weight}×${w.chars}`).join(" ")}, sizes ${f.sizes
3688
+ .slice(0, 6)
3689
+ .map((z) => `${z.px}px`)
3690
+ .join(" ")}`,
3691
+ );
3692
+ if (f.webfont) {
3693
+ // one line per file, however many faces it serves
3694
+ const files = [
3695
+ ...new Map(
3696
+ f.files.map((x) => [
3697
+ x.file,
3698
+ `${x.file}${x.axes?.length ? ` ${x.axes.map((a) => `${a.tag} ${a.min}–${a.max}`).join(" ")}` : ""}`,
3699
+ ]),
3700
+ ).values(),
3701
+ ];
3702
+ const none = f.missingFiles
3703
+ ? `; ${f.missingFiles} declared face(s) have no file (${look.source.kind === "url" ? "not loaded by the page" : "the screen never loaded them"})`
3704
+ : "";
3705
+ L.push(
3706
+ ` files: ${files.length} here (${files.slice(0, 3).join(", ")}${files.length > 3 ? ", …" : ""})${none}`,
3707
+ );
3708
+ }
3709
+ }
3710
+ if (look.declaredFamilies.length)
3711
+ L.push(`declared but not seen on screen: ${look.declaredFamilies.join(", ")}`);
3712
+ if (look.type.length) {
3713
+ L.push("[measured] type on the page (family weight size: characters — sample):");
3714
+ for (const t of look.type.slice(0, 8))
3715
+ L.push(` ${t.family} ${t.weight} ${t.sizePx}px: ${t.chars} — ${t.sample.slice(0, 40)}`);
3716
+ }
3717
+ L.push("");
3718
+ L.push("## Shape");
3719
+ L.push(
3720
+ look.radii.length
3721
+ ? `[measured] radii: ${look.radii.map((r) => `${r.value}×${r.count}`).join(" ")}`
3722
+ : "[not detected] no rounded corners",
3723
+ );
3724
+ L.push(
3725
+ look.shadows.length
3726
+ ? `[measured] shadows: ${look.shadows
3727
+ .slice(0, 3)
3728
+ .map((x) => `${x.value} ×${x.count}`)
3729
+ .join(" | ")}`
3730
+ : "[not detected] no shadows",
3731
+ );
3732
+ L.push("");
3733
+ L.push("## Motion in its CSS");
3734
+ const m = look.motion;
3735
+ L.push(
3736
+ m.declared.durations.length || m.declared.easings.length
3737
+ ? `[measured] declared (not necessarily played): durations ${m.declared.durations
3738
+ .slice(0, 8)
3739
+ .map((d) => `${d.ms}ms×${d.count}`)
3740
+ .join(" ")}; easings ${m.declared.easings
3741
+ .slice(0, 5)
3742
+ .map((e) => `${e.value}×${e.count}`)
3743
+ .join(
3744
+ " ",
3745
+ )}${m.declared.keyframes.length ? `; keyframes ${m.declared.keyframes.slice(0, 6).join(" ")}` : ""}`
3746
+ : "[not detected] no transition or animation timing in its CSS",
3747
+ );
3748
+ L.push(
3749
+ m.used.length
3750
+ ? `[measured] on elements on screen: ${m.used
3751
+ .slice(0, 4)
3752
+ .map((u) => `${u.value} ×${u.count}`)
3753
+ .join(" | ")}`
3754
+ : `[not detected] no transition set on an element on screen${look.source.kind === "url" ? "" : " (a saved screen holds motion still)"}`,
3755
+ );
3756
+ if (look.glyphs) {
3757
+ const g = look.glyphs;
3758
+ L.push("");
3759
+ L.push("## The film's words in these fonts");
3760
+ L.push(
3761
+ `[measured] ${g.chars} distinct characters from ${g.source.slice(0, 4).join(", ")}${g.source.length > 4 ? ", …" : ""}`,
3762
+ );
3763
+ L.push(
3764
+ g.missing.length
3765
+ ? `[measured] in no font file here (${g.missing.length}): ${g.missing
3766
+ .slice(0, 60)
3767
+ .map((x) => x.char)
3768
+ .join(
3769
+ "",
3770
+ )}${g.missing.length > 60 ? "…" : ""} — they would fall back to whatever font the rendering machine has`
3771
+ : "[measured] every character is in a font file here",
3772
+ );
3773
+ // a family's weight named when it has several: each weight is checked on its own
3774
+ const faces = new Map<string, number>();
3775
+ for (const f of g.byFamily) faces.set(f.family, (faces.get(f.family) ?? 0) + 1);
3776
+ // weights of a family lacking the same characters share a line
3777
+ const same = new Map<string, { f: (typeof g.byFamily)[number]; weights: string[] }>();
3778
+ for (const f of g.byFamily) {
3779
+ const k = `${f.family}|${f.lacks}`;
3780
+ const e = same.get(k) ?? { f, weights: [] };
3781
+ e.weights.push(`${f.weight}${f.style !== "normal" ? ` ${f.style}` : ""}`);
3782
+ same.set(k, e);
3783
+ }
3784
+ for (const { f, weights } of same.values())
3785
+ L.push(
3786
+ ` ${f.family}${(faces.get(f.family) ?? 0) > 1 ? ` ${weights.join(", ")}` : ""}: ${f.covered}/${g.chars}${f.lacks ? ` — lacks ${[...f.lacks].slice(0, 40).join("")}${[...f.lacks].length > 40 ? "…" : ""}` : ""}`,
3787
+ );
3788
+ const thin = g.byFamily.filter(
3789
+ (f) =>
3790
+ (faces.get(f.family) ?? 0) > 1 &&
3791
+ g.byFamily.some(
3792
+ (o) => o !== f && o.family === f.family && [...f.lacks].some((c) => !o.lacks.includes(c)),
3793
+ ),
3794
+ );
3795
+ if (thin.length)
3796
+ L.push(
3797
+ ` (set at a weight whose files lack a character, the browser falls back to the next family in the stack — another weight of ${[...new Set(thin.map((f) => f.family))].join(", ")} having it does not help)`,
3798
+ );
3799
+ // one line per family and characters, its weights together
3800
+ const grouped = new Map<
3801
+ string,
3802
+ { family: string; chars: string; weights: string[]; online: boolean }
3803
+ >();
3804
+ for (const e of g.declaredElsewhere) {
3805
+ const k = `${e.family}|${e.chars}`;
3806
+ const x = grouped.get(k) ?? { family: e.family, chars: e.chars, weights: [], online: false };
3807
+ x.weights.push(`${e.weight}${e.style !== "normal" ? ` ${e.style}` : ""}`);
3808
+ x.online ||= !!e.src && /^https?:/.test(e.src);
3809
+ grouped.set(k, x);
3810
+ }
3811
+ for (const e of grouped.values())
3812
+ L.push(
3813
+ ` the product declares ${e.family} (${e.weights.join(", ")}) for ${[...e.chars].slice(0, 30).join("")} — ${e.online ? "its file was not fetched" : "in a file not saved with the screen; reading the product's URL fetches it"}`,
3814
+ );
3815
+ }
3816
+ if (look.packaged) {
3817
+ L.push("");
3818
+ L.push(`## Packed for the film: ${look.packaged.css}`);
3819
+ for (const f of look.packaged.files)
3820
+ L.push(
3821
+ ` ${f.file}: ${f.family} ${f.weight}, ${f.chars} chars, ${f.bytes} bytes (from ${f.fromBytes})${f.how === "copied" ? ` — ${f.why}` : ""}`,
3822
+ );
3823
+ }
3824
+ if (look.notes.length) {
3825
+ L.push("");
3826
+ for (const n of look.notes) L.push(`note: ${n}`);
3827
+ }
3828
+ return L.join("\n");
3829
+ }