@supa-media/tex-contract 0.0.0-stage → 0.2.7

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 (212) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +11 -2
  3. package/package.json +16 -4
  4. package/texContract/aboutLines.cjs +117 -0
  5. package/texContract/aboutLines.d.cts +14 -0
  6. package/texContract/aboutNoteLimits.cjs +41 -0
  7. package/texContract/aboutNoteLimits.d.cts +5 -0
  8. package/texContract/actionManual.cjs +104 -0
  9. package/texContract/activityHint.cjs +40 -0
  10. package/texContract/activityHint.d.cts +4 -0
  11. package/texContract/asks.cjs +16 -0
  12. package/texContract/asks.d.cts +6 -0
  13. package/texContract/asksToFile.cjs +20 -0
  14. package/texContract/asksToFile.d.cts +2 -0
  15. package/texContract/attention.cjs +138 -0
  16. package/texContract/attention.d.cts +20 -0
  17. package/texContract/browserHandback.cjs +13 -0
  18. package/texContract/browserHandback.d.cts +3 -0
  19. package/texContract/browserOwner.cjs +31 -0
  20. package/texContract/browserOwner.d.cts +2 -0
  21. package/texContract/bytes.cjs +12 -0
  22. package/texContract/chatHistoryPath.cjs +38 -0
  23. package/texContract/chatHistoryPath.d.cts +5 -0
  24. package/texContract/chatLedger.cjs +91 -0
  25. package/texContract/chatLedger.d.cts +21 -0
  26. package/texContract/computerTool.cjs +102 -0
  27. package/texContract/computerTool.d.cts +16 -0
  28. package/texContract/consentYes.cjs +22 -0
  29. package/texContract/consentYes.d.cts +5 -0
  30. package/texContract/contextGateway.cjs +52 -0
  31. package/texContract/contextGateway.d.cts +19 -0
  32. package/texContract/deskEligible.cjs +20 -0
  33. package/texContract/deskEligible.d.cts +3 -0
  34. package/texContract/downloads.cjs +129 -0
  35. package/texContract/downloads.d.cts +15 -0
  36. package/texContract/egressLedger.cjs +114 -0
  37. package/texContract/egressLedger.d.cts +14 -0
  38. package/texContract/emailRead.cjs +38 -0
  39. package/texContract/emailRead.d.cts +5 -0
  40. package/texContract/eventWords.cjs +35 -0
  41. package/texContract/eventWords.d.cts +4 -0
  42. package/texContract/fileParts.cjs +43 -0
  43. package/texContract/fileParts.d.cts +6 -0
  44. package/texContract/fileTables.cjs +243 -0
  45. package/texContract/fileWords.cjs +169 -0
  46. package/texContract/folded.cjs +16 -0
  47. package/texContract/folded.d.cts +3 -0
  48. package/texContract/googleAiAccess.cjs +12 -0
  49. package/texContract/googleAiAccess.d.cts +2 -0
  50. package/texContract/graphWires.cjs +18 -0
  51. package/texContract/graphWires.d.cts +5 -0
  52. package/texContract/groupSession.cjs +28 -0
  53. package/texContract/groupSession.d.cts +7 -0
  54. package/texContract/guestNames.cjs +136 -0
  55. package/texContract/guestNames.d.cts +35 -0
  56. package/texContract/heard.cjs +19 -0
  57. package/texContract/heard.d.cts +4 -0
  58. package/texContract/heldOffer.cjs +57 -0
  59. package/texContract/heldOffer.d.cts +8 -0
  60. package/texContract/helperCallers.cjs +29 -0
  61. package/texContract/helperCallers.d.cts +4 -0
  62. package/texContract/identity.cjs +179 -0
  63. package/texContract/identity.d.cts +8 -0
  64. package/texContract/jobLogEntries.cjs +93 -0
  65. package/texContract/jobLogEntries.d.cts +12 -0
  66. package/texContract/judgedActions.cjs +20 -0
  67. package/texContract/judgedActions.d.cts +4 -0
  68. package/texContract/labSandboxGate.cjs +63 -0
  69. package/texContract/labSandboxGate.d.cts +9 -0
  70. package/texContract/ledgerReadChars.cjs +4 -0
  71. package/texContract/ledgerReadChars.d.cts +3 -0
  72. package/texContract/mailCheck.cjs +90 -0
  73. package/texContract/mailCheck.d.cts +12 -0
  74. package/texContract/mailEntries.cjs +64 -0
  75. package/texContract/mailEntries.d.cts +13 -0
  76. package/texContract/mailHealth.cjs +60 -0
  77. package/texContract/mailHealth.d.cts +10 -0
  78. package/texContract/notePath.cjs +99 -0
  79. package/texContract/notePath.d.cts +4 -0
  80. package/texContract/noteRunFacts.cjs +136 -0
  81. package/texContract/noteRunFacts.d.cts +32 -0
  82. package/texContract/objectEtag.cjs +84 -0
  83. package/texContract/objectEtag.d.cts +4 -0
  84. package/texContract/objectPlace.cjs +32 -0
  85. package/texContract/objectPlace.d.cts +5 -0
  86. package/texContract/pageJobs.cjs +226 -0
  87. package/texContract/pageJobs.d.cts +13 -0
  88. package/texContract/pdfLinks.cjs +135 -0
  89. package/texContract/pdfLinks.d.cts +4 -0
  90. package/texContract/personHub.cjs +38 -0
  91. package/texContract/personHub.d.cts +5 -0
  92. package/texContract/personNameText.cjs +18 -0
  93. package/texContract/personNameText.d.cts +3 -0
  94. package/texContract/pinnedContext.cjs +12 -0
  95. package/texContract/pinnedContext.d.cts +3 -0
  96. package/texContract/quietHoursWindow.cjs +36 -0
  97. package/texContract/quietHoursWindow.d.cts +3 -0
  98. package/texContract/scopeClamp.cjs +117 -0
  99. package/texContract/scopeClamp.d.cts +5 -0
  100. package/texContract/scopes.cjs +29 -0
  101. package/texContract/scopes.d.cts +7 -0
  102. package/texContract/searchSettings.cjs +54 -0
  103. package/texContract/searchSettings.d.cts +6 -0
  104. package/texContract/settingHabits.cjs +87 -0
  105. package/texContract/settingHabits.d.cts +20 -0
  106. package/texContract/settingsNotes.cjs +217 -0
  107. package/texContract/settingsNotes.d.cts +26 -0
  108. package/texContract/shownEmail.cjs +181 -0
  109. package/texContract/texClients.cjs +53 -0
  110. package/texContract/texClients.d.cts +12 -0
  111. package/texContract/texGraph.cjs +593 -0
  112. package/texContract/texGraph.d.cts +55 -0
  113. package/texContract/texKeys.cjs +100 -0
  114. package/texContract/texKeys.d.cts +13 -0
  115. package/texContract/texOwnSources.cjs +9 -0
  116. package/texContract/texOwnSources.d.cts +3 -0
  117. package/texContract/texStoreNames.cjs +26 -0
  118. package/texContract/texStoreNames.d.cts +12 -0
  119. package/texContract/texStoreWire.cjs +306 -0
  120. package/texContract/texStoreWire.d.cts +32 -0
  121. package/texContract/threadsFold.cjs +75 -0
  122. package/texContract/threadsFold.d.cts +22 -0
  123. package/texContract/toolActions.cjs +253 -0
  124. package/texContract/toolCatalog.cjs +49 -0
  125. package/texContract/toolCatalog.generated.json +90 -0
  126. package/texContract/toolContract.cjs +52 -0
  127. package/texContract/toolContract.d.cts +12 -0
  128. package/texContract/toolShapes.cjs +14 -0
  129. package/texContract/transcription.cjs +101 -0
  130. package/texContract/transcription.d.cts +3 -0
  131. package/texContract/treeJobs.cjs +31 -0
  132. package/texContract/treeJobs.d.cts +3 -0
  133. package/texContract/turnSession.cjs +90 -0
  134. package/texContract/turnSession.d.cts +19 -0
  135. package/texContract/turnWords.cjs +90 -0
  136. package/texContract/turnWords.d.cts +9 -0
  137. package/texContract/uploadImages.cjs +131 -0
  138. package/texContract/uploadImages.d.cts +13 -0
  139. package/texContract/v2Names.cjs +41 -0
  140. package/texContract/v2SearchFetch.cjs +316 -0
  141. package/texContract/v2Translate.cjs +123 -0
  142. package/texContract/vaultTools.cjs +112 -0
  143. package/texContract/vaultTools.d.cts +15 -0
  144. package/texContract/yesWords.cjs +91 -0
  145. package/texShared/argumentCoercion.cjs +93 -0
  146. package/texShared/cellComments.cjs +122 -0
  147. package/texShared/cellComments.d.cts +21 -0
  148. package/texShared/comments.cjs +586 -0
  149. package/texShared/comments.d.cts +115 -0
  150. package/texShared/contentTypes.cjs +85 -0
  151. package/texShared/fileKinds.cjs +123 -0
  152. package/texShared/flags.cjs +124 -0
  153. package/texShared/flags.d.cts +21 -0
  154. package/texShared/folderJobInfo.cjs +301 -0
  155. package/texShared/folderJobInfo.d.cts +40 -0
  156. package/texShared/folderRoles.cjs +512 -0
  157. package/texShared/folderRoles.d.cts +73 -0
  158. package/texShared/githubOidc.ts +98 -0
  159. package/texShared/groupRunQuestions.cjs +98 -0
  160. package/texShared/groupRunQuestions.d.cts +4 -0
  161. package/texShared/inboxFolders.cjs +49 -0
  162. package/texShared/inboxFolders.d.cts +5 -0
  163. package/texShared/ink/drawing.cjs +474 -0
  164. package/texShared/ink/texFigure.cjs +252 -0
  165. package/texShared/ink/texFigure.d.cts +36 -0
  166. package/texShared/ink/texPoses.cjs +180 -0
  167. package/texShared/ink/texPoses.d.cts +20 -0
  168. package/texShared/jobPartEnd.cjs +133 -0
  169. package/texShared/jobPartEnd.d.cts +13 -0
  170. package/texShared/jobResume.cjs +31 -0
  171. package/texShared/jobResume.d.cts +5 -0
  172. package/texShared/jobSplit.cjs +90 -0
  173. package/texShared/jobSplit.d.cts +6 -0
  174. package/texShared/jobStart.cjs +56 -0
  175. package/texShared/jobStart.d.cts +9 -0
  176. package/texShared/mail.cjs +400 -0
  177. package/texShared/mail.d.cts +56 -0
  178. package/texShared/messageAnchors.cjs +38 -0
  179. package/texShared/models/aiKeys.cjs +137 -0
  180. package/texShared/models/aiKeys.d.cts +42 -0
  181. package/texShared/models/aiKeys.json +56 -0
  182. package/texShared/models/creditRest.cjs +269 -0
  183. package/texShared/models/promptBudget.cjs +295 -0
  184. package/texShared/models/promptSections.cjs +29 -0
  185. package/texShared/noteAppLink.cjs +23 -0
  186. package/texShared/notePreview.cjs +219 -0
  187. package/texShared/notePreview.d.cts +21 -0
  188. package/texShared/pages/blocks.cjs +215 -0
  189. package/texShared/pages/cover.cjs +164 -0
  190. package/texShared/pages/css.cjs +181 -0
  191. package/texShared/pages/cssBlocks.cjs +264 -0
  192. package/texShared/pages/draw.cjs +212 -0
  193. package/texShared/pages/drawRich.cjs +232 -0
  194. package/texShared/pages/html.cjs +168 -0
  195. package/texShared/pages/inline.cjs +251 -0
  196. package/texShared/pages/layout.cjs +76 -0
  197. package/texShared/pages/parse.cjs +418 -0
  198. package/texShared/pages/render.cjs +200 -0
  199. package/texShared/pages/skill.cjs +147 -0
  200. package/texShared/pages/skill.d.cts +5 -0
  201. package/texShared/pages/templates.cjs +336 -0
  202. package/texShared/r2Store.cjs +163 -0
  203. package/texShared/remoteImage.cjs +177 -0
  204. package/texShared/routines.cjs +656 -0
  205. package/texShared/routines.d.cts +86 -0
  206. package/texShared/servedListing.cjs +250 -0
  207. package/texShared/servedListing.d.cts +17 -0
  208. package/texShared/sheetCsv.cjs +566 -0
  209. package/texShared/sheetCsv.d.cts +91 -0
  210. package/texShared/storageLayout.cjs +88 -0
  211. package/texShared/storeKeys.cjs +144 -0
  212. package/texShared/toolArguments.cjs +323 -0
@@ -0,0 +1,98 @@
1
+ /**
2
+ * WHAT A GROUP CHAT'S ROUTINE AND CHECK-IN TURNS ARE ASKED (the owner, 2026-10-27;
3
+ * `docs/decisions/texting-assistant/chat-routines.md`).
4
+ *
5
+ * The texting Worker queues a due chat routine or a chat's own check-in as a turn of the chat itself, its writer's tag
6
+ * in these words (`packages/tex/worker/groupRoutines.ts` `chatRoutineMessage`). They live here, plain JS, so the bench asks
7
+ * a Dev test's group routine or check-in in exactly the words production does (`apps/mcp/bench/setsFd.mjs`).
8
+ *
9
+ * Silence is the `say_nothing` call, never a word (2026-11-17: these words asked for "exactly SKIP", and a check-in
10
+ * with nothing new posted its reasoning and the word into a WhatsApp group; `packages/tex/gateway/agent/scheduledQuiet.js`).
11
+ */
12
+ "use strict";
13
+
14
+ /** The path the control plane hands a chat's own check-in under (`textGroupLooks.ts`): no note. */
15
+ const CHAT_LOOK_PATH = "(check-in)";
16
+
17
+ /** When a run last went, in the routine's own time zone, or null when it never did or the zone is unknown. */
18
+ function lastRanWords(since, timeZone) {
19
+ if (since === undefined) return null;
20
+ try {
21
+ return new Intl.DateTimeFormat("en-US", {
22
+ timeZone: timeZone ?? "UTC",
23
+ month: "short",
24
+ day: "numeric",
25
+ hour: "numeric",
26
+ minute: "2-digit",
27
+ timeZoneName: "short",
28
+ }).format(new Date(since));
29
+ } catch {
30
+ return null;
31
+ }
32
+ }
33
+
34
+ /** Whether a routine is kept in its chat's home, `tex/groups/<words>/routines/` in `@context-lc` (the owner, 2026-11-02). */
35
+ const inChatHome = (path) => /^tex\/groups\/[a-z][a-z0-9-]*\/routines\//i.test(path);
36
+
37
+ /** What a chat routine's turn is asked: its writer's tag, in words only the Worker writes. */
38
+ function chatRoutineQuestion(path, lastRan = null) {
39
+ return (
40
+ `(It's time for this chat's routine, ${path}${inChatHome(path) ? ` (context: "@context-lc")` : ""}. Read that note and do what it says now, for everyone here, ` +
41
+ "as if it had just been asked. " +
42
+ (lastRan === null ? "" : `It last ran ${lastRan}: anything "new" means since then. `) +
43
+ "If it only wants a word when there is something to say and there isn't, call send with action say_nothing: nothing is posted, " +
44
+ "and never write why you are quiet as your answer, since an answer is posted to everyone here.)"
45
+ );
46
+ }
47
+
48
+ /**
49
+ * What a chat's own check-in is asked (the owner, 2026-10-27: "heartbeats and
50
+ * stuff just as dm Tex would do ... it should just work, and know when an
51
+ * email needs to go to the group vs me personally"). Mail that needs only the
52
+ * mailbox's own person is theirs: their own check-ins text them about it.
53
+ * Calendars shared with the chat are looked at too, and held against what the chat said (Dev2, 2026-11-19: a member's
54
+ * calendar had the wedding on Saturday while the chat planned around Sunday, and the check-in stayed quiet). Since
55
+ * 2026-11-27 a check-in reads a shared calendar only as free or busy, and a possible clash goes to the calendar's own
56
+ * person alone (Dev2 chose "the check-in reads the full calendar, but details go only to the calendar's owner": their
57
+ * own Tex reads it whole), never to the room.
58
+ * Mail shared with the chat is named only when some is (`mail` from `textGroupLooks.ts`; Dev2, 2026-11-25: Tex Devs had
59
+ * none, its check-ins searched mail anyway with a tool they are never given, and one told the chat its "lookups keep
60
+ * timing out"). `mail` undefined (an older control plane) keeps the line.
61
+ * `replies` (up to five, from the control plane's due chat look run; Tex request for Seyi, 2026-11-29) are replies that
62
+ * arrived on notes this chat's Tex sent note mail on. A reply reaches the chat only through here: people are not pulled
63
+ * into every AI thread by default. The rule below, "Post here only what someone in this chat needs to act on or know
64
+ * now", decides whether it is posted; a reply is read, never posted as it is.
65
+ */
66
+ const PLACE_WORDS = { 3: "three", 4: "four", 5: "five" };
67
+
68
+ function chatLookQuestion(since, lastRan, { mail, replies } = {}) {
69
+ const after = since === undefined ? "" : ` (search it with after:${Math.floor(since / 1000)})`;
70
+ const shared = mail === false ? "" : `mail shared with this chat${after}, `;
71
+ const reply = Array.isArray(replies) && replies.length > 0 ? replies : null;
72
+ const places = 3 + (mail === false ? 0 : 1) + (reply === null ? 0 : 1);
73
+ const replied =
74
+ reply === null
75
+ ? ""
76
+ : "replies to mail this chat sent (read each note's mail with fetch and args { mail: true }: " +
77
+ `${reply.map((entry) => `${entry.path} (context: "${entry.context}")`).join("; ")}), `;
78
+ return (
79
+ `(Time for this chat's check-in: look on your own at what is new${lastRan === null ? "" : ` since ${lastRan}`}, ` +
80
+ `in ${PLACE_WORDS[places]} places only: ${shared}mail sent to this chat's own address (the notes in its folder's email/ that arrived since), ` +
81
+ "calendars shared with this chat (read_calendar from today for the next 7 days, one account at a time; none shared, skip it), " +
82
+ replied +
83
+ "and what was asked of you in this chat that you said you would follow up on. " +
84
+ "Hold what you find against what people here said or planned: when an email disagrees with the chat " +
85
+ "(a different day, time or place), that is worth one short question to the person it's about, asking which is right; never guess which one is. " +
86
+ "A shared calendar reads here only as free or busy: when a busy time may clash with what the chat plans, ask its own person alone " +
87
+ "(send action text_privately, to: their handle), never here. " +
88
+ "Never post about the workspace's other activity, notes or other agents' work: nobody here asked. " +
89
+ "Post here only what someone in this chat needs to act on or know now, in one short line: " +
90
+ "what happened and who should handle it. " +
91
+ "Leave out mail that concerns only the mailbox's owner personally: their own check-ins text them about it. " +
92
+ "Never post just to say hello or to summarize; newsletters, receipts and automated notices are not worth a message, " +
93
+ "and neither is anything you already posted here. If nothing needs the chat, call send with action say_nothing: nothing is posted, " +
94
+ "and never write why you are quiet as your answer, since an answer is posted to everyone here.)"
95
+ );
96
+ }
97
+
98
+ module.exports = { CHAT_LOOK_PATH, chatLookQuestion, chatRoutineQuestion, lastRanWords };
@@ -0,0 +1,4 @@
1
+ export declare const CHAT_LOOK_PATH: "(check-in)";
2
+ export declare function lastRanWords(since: number | undefined, timeZone: string | undefined): string | null;
3
+ export declare function chatRoutineQuestion(path: string, lastRan?: string | null): string;
4
+ export declare function chatLookQuestion(since: number | undefined, lastRan: string | null, options?: { mail?: boolean; replies?: ReadonlyArray<{ context: string; path: string }> }): string;
@@ -0,0 +1,49 @@
1
+ "use strict";
2
+ /**
3
+ * Where a workspace's Inbox and its contact pages are, as Context's communications contract and Tex both read
4
+ * them. `packages/communications/src/protocol.js` re-exports these; see `docs/decisions/communications.md`.
5
+ */
6
+
7
+ /**
8
+ * Where unfiled things arrive: the Inbox, under its plain name since the
9
+ * numbers in front of the built-in folders were dropped (owner, 2026-10-21;
10
+ * see the decision). In a workspace whose Inbox is named otherwise (`0-inbox`
11
+ * where the rename was skipped, `Capture` where somebody renamed it), a note
12
+ * written here lands in the folder doing the Inbox's job: the control plane
13
+ * carries a built-in folder's default name to that folder (`jobPath`).
14
+ */
15
+ const INBOX_FOLDER = "inbox";
16
+
17
+ /**
18
+ * The Inbox's name before the numbers were dropped. A workspace the rename
19
+ * skipped still has it, so a reader that cannot ask which folder does the
20
+ * Inbox's job lists both names.
21
+ */
22
+ const LEGACY_INBOX_FOLDER = "0-inbox";
23
+
24
+ /** How a key's first segment can spell the Inbox: its word, with a sort number in front or not. */
25
+ const INBOX_NAME = /^(?:\d+-)?inbox$/i;
26
+
27
+ /**
28
+ * `key` with its Inbox spelled `INBOX_FOLDER`, so a reader recognises what
29
+ * this package wrote whatever the Inbox is called: `0-inbox/email/a.md` (a
30
+ * workspace the rename skipped) and, given `inbox` (the folder doing the job,
31
+ * when the caller knows it), `Capture/email/a.md` are `inbox/email/a.md`. Only
32
+ * the first segment is read; every other key is returned as it is.
33
+ *
34
+ * @param {string} key
35
+ * @param {string|null} [inbox] The path of the folder doing the Inbox's job.
36
+ */
37
+ function asInboxKey(key, inbox) {
38
+ if (typeof key !== "string") return key;
39
+ const home = typeof inbox === "string" ? inbox.replace(/\/+$/, "") : "";
40
+ if (home !== "" && (key === home || key.startsWith(`${home}/`))) return `${INBOX_FOLDER}${key.slice(home.length)}`;
41
+ const slash = key.indexOf("/");
42
+ const first = slash < 0 ? key : key.slice(0, slash);
43
+ return INBOX_NAME.test(first) ? `${INBOX_FOLDER}${key.slice(first.length)}` : key;
44
+ }
45
+
46
+ /** One stable page per canonical person or organization. */
47
+ const CONTACTS_FOLDER = `${INBOX_FOLDER}/contacts`;
48
+
49
+ module.exports = { INBOX_FOLDER, LEGACY_INBOX_FOLDER, CONTACTS_FOLDER, asInboxKey };
@@ -0,0 +1,5 @@
1
+ /** Types for `inboxFolders.cjs`. */
2
+ export declare const INBOX_FOLDER: "inbox";
3
+ export declare const LEGACY_INBOX_FOLDER: "0-inbox";
4
+ export declare const CONTACTS_FOLDER: "inbox/contacts";
5
+ export declare function asInboxKey<T>(key: T, inbox?: string | null): T;
@@ -0,0 +1,474 @@
1
+ /**
2
+ * A page's drawing: the picture Tex draws for a page that has none, in its own
3
+ * ink (owner, 2026-11-03: "whenever Tex makes pages, ... generate an image
4
+ * representing the page if there is no image already in the page, it should
5
+ * be in tex style"; then "Tex draws it in ink", and "use the more calm
6
+ * version of tex ... most people won't be generating images involving Tex").
7
+ *
8
+ * The model draws the page's topic as a small SVG scene, on a 1200 x 900
9
+ * canvas, with plain shapes. Nothing it writes reaches the picture as it
10
+ * wrote it: `readScene` reads the markup into shapes and numbers, refusing
11
+ * anything it does not know, and `drawingSvg` writes a new picture from them.
12
+ * So no address, script, style or unknown attribute can ride along into the
13
+ * page the screenshot Worker draws. What makes it Tex's is added here, never
14
+ * left to the model:
15
+ *
16
+ * - **One ink**: every stroke is Tex blue on the page's own paper (the
17
+ * page's background, so the drawing sits on the page with no panel),
18
+ * periwinkle on the dark page, through the app's brush (`#rough`, the
19
+ * filter `apps/mobile/features/chaos/RoughInk.web.tsx` draws Tex with).
20
+ * - **One hatch**: a fill is `none`, `ink`, `paper` or `hatch`, and every
21
+ * hatch is the same lines at the same spacing. A light colour the model
22
+ * names (white, `#fff`, a high luminance) is paper. A filled shape that
23
+ * covers most of the canvas is left out: the paper is already there, and
24
+ * an ink fill that size would bury the drawing, which is refused with why.
25
+ * - **The calm Tex**, the # with googly eyes, legs and a wave, from the app's
26
+ * own geometry (`./texFigure.cjs`), wherever the scene puts a `<tex>`, or
27
+ * at its foot when it names none.
28
+ *
29
+ * The drawing is a 1200 x 1000 picture: the scene scaled into a safe area that
30
+ * keeps clear of the phone's round buttons and the crop of a cover.
31
+ * Decision: `docs/decisions/app-and-console/page-drawings.md`.
32
+ */
33
+
34
+ const { figureParts, CX } = require("./texFigure.cjs");
35
+
36
+ /** The canvas the model draws on. */
37
+ const SCENE_WIDTH = 1200;
38
+ const SCENE_HEIGHT = 900;
39
+ /** The picture it becomes. */
40
+ const DRAWING_WIDTH = 1200;
41
+ const DRAWING_HEIGHT = 1000;
42
+ /** Where the scene sits in the picture: scaled, with margins every crop keeps. */
43
+ const SAFE = { x: 120, y: 150, scale: 0.8 };
44
+
45
+ /** Most a scene may be, before it is read. */
46
+ const MAX_SCENE_CHARS = 30_000;
47
+ const MAX_SHAPES = 400;
48
+ const MAX_DEPTH = 6;
49
+ const MAX_TEXT_CHARS = 40;
50
+ const MAX_POINTS = 400;
51
+ const MAX_PATH_CHARS = 6_000;
52
+
53
+ /** The page's paper and Tex's ink, light and dark (`../pages/css.cjs`, `texColors`). */
54
+ const INKS = {
55
+ light: { paper: "#FFFDF9", ink: "#2A45CF", eye: "#FBF7EE", grain: "0 0 0 0 0.35 0 0 0 0 0.28 0 0 0 0 0.18 0 0 0 0.035 0" },
56
+ dark: { paper: "#191715", ink: "#8A9BF2", eye: "#F4F0E8", grain: "0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0.02 0" },
57
+ };
58
+
59
+ /** Calm: the # with its eyes. Its limbs are drawn in a drawing, where the app's calm Tex has let them fade. */
60
+ const CALM = 6;
61
+ /** Tex's height in the scene, when it does not say. */
62
+ const TEX_SIZE = 240;
63
+ /** Where Tex stands when the scene names no `<tex>`: at its foot, on the right. */
64
+ const TEX_DEFAULT = { x: 1060, y: 860, size: TEX_SIZE, flip: true };
65
+
66
+ /** The elements a scene may use, and the attributes each reads. */
67
+ const COMMON = ["transform", "fill", "stroke", "stroke-width", "opacity", "stroke-dasharray"];
68
+ const SHAPES = {
69
+ g: [],
70
+ path: ["d"],
71
+ line: ["x1", "y1", "x2", "y2"],
72
+ polyline: ["points"],
73
+ polygon: ["points"],
74
+ rect: ["x", "y", "width", "height", "rx"],
75
+ circle: ["cx", "cy", "r"],
76
+ ellipse: ["cx", "cy", "rx", "ry"],
77
+ text: ["x", "y", "font-size", "text-anchor", "font-weight"],
78
+ tex: ["x", "y", "size", "flip"],
79
+ };
80
+ const NUMBER_ATTRS = new Set(["x", "y", "x1", "y1", "x2", "y2", "width", "height", "rx", "ry", "cx", "cy", "r", "size", "stroke-width", "opacity", "font-size"]);
81
+ const FILLS = new Set(["none", "ink", "paper", "hatch"]);
82
+ /** A fill this light is paper, not ink: a white background the model drew would otherwise become a slab of ink. */
83
+ const LIGHT_LUMINANCE = 0.7;
84
+ /** A filled shape covering this much of the canvas is a background. The paper is already there. */
85
+ const COVER_SHARE = 0.8;
86
+ /** Named colours light enough to be paper. A hex, rgb or hsl colour is judged by its luminance instead. */
87
+ const LIGHT_NAMES = new Set(["white", "snow", "ivory", "floralwhite", "ghostwhite", "whitesmoke", "seashell", "linen", "oldlace", "beige", "cornsilk", "papayawhip", "blanchedalmond", "antiquewhite", "bisque", "azure", "mintcream", "honeydew", "aliceblue", "lavenderblush", "lightyellow", "lightcyan", "lightgoldenrodyellow"]);
88
+ const COVER_INK = "A filled shape covers most of the canvas, so it would bury the drawing in ink. Leave the background out: the paper is already there.";
89
+
90
+ const NUMBER = /^-?(?:\d+\.?\d*|\.\d+)(?:e-?\d+)?$/i;
91
+ const PATH_DATA = /^[MmLlHhVvCcSsQqTtAaZz0-9eE.,\s+-]+$/;
92
+ const TRANSFORM = /^\s*(?:(?:translate|rotate|scale)\(\s*-?[\d.]+(?:[\s,]+-?[\d.]+){0,2}\s*\)\s*)+$/;
93
+ const TAG = /<\s*(\/?)\s*([A-Za-z][\w-]*)((?:\s+[A-Za-z_:][\w:.-]*\s*=\s*(?:"[^"<>]*"|'[^'<>]*'))*)\s*(\/?)\s*>/y;
94
+ const ATTR = /([A-Za-z_:][\w:.-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;
95
+
96
+ const fail = (error) => ({ shapes: null, tex: null, error });
97
+ const num = (value) => (NUMBER.test(value) ? Number(value) : NaN);
98
+
99
+ /** sRGB channel to linear light, for the luminance of a colour the model named. */
100
+ function linear(channel) {
101
+ const c = channel / 255;
102
+ return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
103
+ }
104
+
105
+ /** Relative luminance of an sRGB triple, 0 to 1. */
106
+ function luminance(r, g, b) {
107
+ return 0.2126 * linear(r) + 0.7152 * linear(g) + 0.0722 * linear(b);
108
+ }
109
+
110
+ /** hsl (0-360, 0-1, 0-1) as an sRGB triple. */
111
+ function hslToRgb(h, s, l) {
112
+ const a = s * Math.min(l, 1 - l);
113
+ const f = (n) => {
114
+ const k = (n + h / 30) % 12;
115
+ return l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);
116
+ };
117
+ return [f(0), f(8), f(4)].map((c) => Math.round(Math.min(1, Math.max(0, c)) * 255));
118
+ }
119
+
120
+ /** A colour as `[r, g, b]`, or null when it is not a hex, rgb or hsl colour. */
121
+ function rgbOf(value) {
122
+ const hex3 = /^#([0-9a-f]{3})$/.exec(value);
123
+ const hex6 = /^#([0-9a-f]{6})(?:[0-9a-f]{2})?$/.exec(value);
124
+ const hex = hex3 ? hex3[1].split("").map((c) => c + c).join("") : hex6 ? hex6[1] : null;
125
+ if (hex) return [parseInt(hex.slice(0, 2), 16), parseInt(hex.slice(2, 4), 16), parseInt(hex.slice(4, 6), 16)];
126
+ const rgb = /^rgba?\(\s*([\d.]+%?)\s*,\s*([\d.]+%?)\s*,\s*([\d.]+%?)/.exec(value);
127
+ if (rgb) {
128
+ const channel = (part) => (part.endsWith("%") ? (Number(part.slice(0, -1)) / 100) * 255 : Number(part));
129
+ return [channel(rgb[1]), channel(rgb[2]), channel(rgb[3])].map((n) => Math.min(255, Math.max(0, n)));
130
+ }
131
+ const hsl = /^hsla?\(\s*([\d.]+)\s*,\s*([\d.]+)%\s*,\s*([\d.]+)%/.exec(value);
132
+ if (hsl) return hslToRgb(Number(hsl[1]), Number(hsl[2]) / 100, Number(hsl[3]) / 100);
133
+ return null;
134
+ }
135
+
136
+ /**
137
+ * A colour the model named, as the fill the drawing can use: `paper` when it
138
+ * is light, `none` when it is transparent, `ink` when it is a dark colour we
139
+ * can read, or null when it is not a colour (a named ink like `blue` stays
140
+ * for the caller).
141
+ */
142
+ function toneOf(value) {
143
+ const v = value.trim().toLowerCase();
144
+ if (v === "transparent") return "none";
145
+ if (LIGHT_NAMES.has(v)) return "paper";
146
+ const rgb = rgbOf(v);
147
+ if (!rgb) return null;
148
+ return luminance(...rgb) >= LIGHT_LUMINANCE ? "paper" : "ink";
149
+ }
150
+
151
+ /** A shape's box on the canvas, before any transform, or null when it has none we can measure. */
152
+ function shapeBox(node) {
153
+ const a = node.attrs;
154
+ if (node.tag === "rect") {
155
+ if (!(a.width > 0) || !(a.height > 0)) return null;
156
+ return { x: a.x ?? 0, y: a.y ?? 0, w: a.width, h: a.height };
157
+ }
158
+ if (node.tag === "circle") {
159
+ if (!(a.r > 0)) return null;
160
+ return { x: (a.cx ?? 0) - a.r, y: (a.cy ?? 0) - a.r, w: a.r * 2, h: a.r * 2 };
161
+ }
162
+ if (node.tag === "ellipse") {
163
+ if (!(a.rx > 0) || !(a.ry > 0)) return null;
164
+ return { x: (a.cx ?? 0) - a.rx, y: (a.cy ?? 0) - a.ry, w: a.rx * 2, h: a.ry * 2 };
165
+ }
166
+ if ((node.tag === "polygon" || node.tag === "polyline") && Array.isArray(a.points) && a.points.length >= 4) {
167
+ let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
168
+ for (let i = 0; i < a.points.length; i += 2) {
169
+ minX = Math.min(minX, a.points[i]);
170
+ maxX = Math.max(maxX, a.points[i]);
171
+ minY = Math.min(minY, a.points[i + 1]);
172
+ maxY = Math.max(maxY, a.points[i + 1]);
173
+ }
174
+ return { x: minX, y: minY, w: maxX - minX, h: maxY - minY };
175
+ }
176
+ return null;
177
+ }
178
+
179
+ /** How far a transform slides a shape, and whether a scale or rotation means we should not guess its size. */
180
+ function slideOf(transform) {
181
+ if (typeof transform !== "string" || transform === "") return { x: 0, y: 0, plain: true };
182
+ if (/rotate\s*\(|scale\s*\(/i.test(transform)) return { x: 0, y: 0, plain: false };
183
+ let x = 0, y = 0;
184
+ for (const m of transform.matchAll(/translate\(\s*(-?[\d.]+)(?:[\s,]+(-?[\d.]+))?\s*\)/gi)) {
185
+ x += Number(m[1]);
186
+ y += m[2] === undefined ? 0 : Number(m[2]);
187
+ }
188
+ return { x, y, plain: true };
189
+ }
190
+
191
+ /** Whether a box covers most of the canvas, counting only the part that sits on it. */
192
+ function coversCanvas(box) {
193
+ const x0 = Math.max(0, box.x);
194
+ const y0 = Math.max(0, box.y);
195
+ const x1 = Math.min(SCENE_WIDTH, box.x + box.w);
196
+ const y1 = Math.min(SCENE_HEIGHT, box.y + box.h);
197
+ if (!(x1 > x0) || !(y1 > y0)) return false;
198
+ return (x1 - x0) * (y1 - y0) >= COVER_SHARE * SCENE_WIDTH * SCENE_HEIGHT;
199
+ }
200
+
201
+ /**
202
+ * Filled shapes that cover most of the canvas, taken out. The paper is
203
+ * already there, so a paper or hatch background is dropped. An ink one would
204
+ * bury the drawing: `buried` says so, and the scene is refused with why.
205
+ * A scale or rotation is left alone: its size is no longer the numbers written.
206
+ */
207
+ function dropCoveringFills(nodes, shift = { x: 0, y: 0 }, plain = true) {
208
+ const shapes = [];
209
+ let buried = false;
210
+ for (const node of nodes) {
211
+ if (node.tag === "g") {
212
+ const moved = slideOf(node.attrs.transform);
213
+ const inner = dropCoveringFills(
214
+ node.children,
215
+ { x: shift.x + (moved.plain ? moved.x : 0), y: shift.y + (moved.plain ? moved.y : 0) },
216
+ plain && moved.plain,
217
+ );
218
+ buried = buried || inner.buried;
219
+ if (inner.shapes.length > 0) shapes.push({ ...node, children: inner.shapes });
220
+ continue;
221
+ }
222
+ const own = slideOf(node.attrs.transform);
223
+ const box = plain && own.plain ? shapeBox(node) : null;
224
+ const fill = node.attrs.fill;
225
+ if (box && fill && fill !== "none" && coversCanvas({ x: box.x + shift.x + own.x, y: box.y + shift.y + own.y, w: box.w, h: box.h })) {
226
+ if (fill === "ink") buried = true;
227
+ continue;
228
+ }
229
+ shapes.push(node);
230
+ }
231
+ return { shapes, buried };
232
+ }
233
+
234
+ /** Shapes a picture would actually draw: an empty group is not one. */
235
+ function drawable(nodes) {
236
+ let n = 0;
237
+ for (const node of nodes) n += node.tag === "g" ? drawable(node.children) : 1;
238
+ return n;
239
+ }
240
+ const fmt = (n) => String(Math.round(n * 100) / 100);
241
+ const esc = (text) => String(text).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
242
+ const unesc = (text) => String(text).replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&amp;/g, "&");
243
+
244
+ /** One attribute's value as the drawing may use it, or `undefined` to drop it, or an Error for one that cannot be read. */
245
+ function readAttr(tag, name, raw) {
246
+ const value = unesc(raw).trim();
247
+ if (NUMBER_ATTRS.has(name)) {
248
+ const n = num(value.replace(/px$/i, ""));
249
+ if (!Number.isFinite(n) || Math.abs(n) > 5000) return new Error(`<${tag} ${name}="${value.slice(0, 20)}">: a number, please`);
250
+ if (name === "stroke-width") return Math.min(40, Math.max(0.5, n));
251
+ if (name === "opacity") return Math.min(1, Math.max(0, n));
252
+ if (name === "font-size") return Math.min(140, Math.max(10, n));
253
+ if (name === "size") return Math.min(600, Math.max(80, n));
254
+ return n;
255
+ }
256
+ switch (name) {
257
+ case "d":
258
+ if (value.length > MAX_PATH_CHARS || !PATH_DATA.test(value)) return new Error(`<path d>: only path commands and numbers, at most ${MAX_PATH_CHARS} characters`);
259
+ return value.replace(/\s+/g, " ");
260
+ case "points": {
261
+ const list = value.split(/[\s,]+/).filter(Boolean).map(num);
262
+ if (list.length < 4 || list.length % 2 === 1 || list.length > MAX_POINTS * 2 || list.some((n) => !Number.isFinite(n) || Math.abs(n) > 5000)) return new Error(`<${tag} points>: pairs of numbers`);
263
+ return list;
264
+ }
265
+ case "transform":
266
+ if (!TRANSFORM.test(value)) return new Error(`<${tag} transform>: translate, rotate or scale only`);
267
+ return value.replace(/\s+/g, " ").trim();
268
+ case "fill": {
269
+ // A light colour is paper. Anything darker the model names is ink: the drawing has one colour.
270
+ if (FILLS.has(value)) return value;
271
+ if (value === "") return undefined;
272
+ const tone = toneOf(value);
273
+ if (tone) return tone;
274
+ return /^(?:#|rgb|hsl|[a-z]+$)/i.test(value) ? "ink" : undefined;
275
+ }
276
+ case "stroke":
277
+ return value === "none" ? "none" : "ink";
278
+ case "stroke-dasharray": {
279
+ const list = value.split(/[\s,]+/).filter(Boolean).map(num);
280
+ if (list.length === 0 || list.length > 6 || list.some((n) => !Number.isFinite(n) || n < 0 || n > 200)) return undefined;
281
+ return list;
282
+ }
283
+ case "text-anchor":
284
+ return ["start", "middle", "end"].includes(value) ? value : undefined;
285
+ case "font-weight":
286
+ return ["400", "500", "600", "700", "bold", "normal"].includes(value) ? (value === "bold" ? "700" : value === "normal" ? "400" : value) : undefined;
287
+ case "flip":
288
+ return value === "true" || value === "1" || value === "yes";
289
+ default:
290
+ return undefined;
291
+ }
292
+ }
293
+
294
+ /**
295
+ * The model's scene, read into shapes, or `{ error }` naming what to fix.
296
+ * An outer `<svg>` is let through and ignored; comments are dropped; every
297
+ * other element must be one of `SHAPES`, and only the attributes each reads
298
+ * survive. Text only inside `<text>`, at most `MAX_TEXT_CHARS`.
299
+ */
300
+ function readScene(markup) {
301
+ if (typeof markup !== "string" || markup.trim() === "") return fail("Draw the scene as SVG shapes on a 1200 x 900 canvas.");
302
+ if (markup.length > MAX_SCENE_CHARS) return fail(`A scene is at most ${MAX_SCENE_CHARS} characters: draw fewer, simpler shapes.`);
303
+ const source = markup.replace(/<!--[\s\S]*?-->/g, "").replace(/<\?xml[\s\S]*?\?>/g, "");
304
+ const root = { tag: "g", attrs: {}, children: [] };
305
+ const stack = [root];
306
+ let tex = null;
307
+ let count = 0;
308
+ let at = 0;
309
+ while (at < source.length) {
310
+ const lt = source.indexOf("<", at);
311
+ const textEnd = lt === -1 ? source.length : lt;
312
+ const between = source.slice(at, textEnd);
313
+ if (between.trim() !== "") {
314
+ const top = stack[stack.length - 1];
315
+ if (top.tag !== "text") return fail(`Words go inside <text>: "${between.trim().slice(0, 30)}"`);
316
+ top.text = (top.text ?? "") + unesc(between).replace(/\s+/g, " ");
317
+ if (top.text.trim().length > MAX_TEXT_CHARS) return fail(`A <text> is at most ${MAX_TEXT_CHARS} characters: a word or a number, not a sentence.`);
318
+ }
319
+ if (lt === -1) break;
320
+ TAG.lastIndex = lt;
321
+ const m = TAG.exec(source);
322
+ if (!m) return fail(`Could not read the scene near: ${source.slice(lt, lt + 40)}`);
323
+ at = TAG.lastIndex;
324
+ const [, closing, rawTag, rawAttrs, selfClosing] = m;
325
+ const tag = rawTag.toLowerCase();
326
+ if (tag === "svg") continue;
327
+ if (!Object.hasOwn(SHAPES, tag)) return fail(`<${rawTag}> is not drawn: use ${Object.keys(SHAPES).join(", ")}.`);
328
+ if (closing) {
329
+ const top = stack[stack.length - 1];
330
+ if (top.tag !== tag || stack.length === 1) return fail(`</${rawTag}> closes nothing open.`);
331
+ stack.pop();
332
+ continue;
333
+ }
334
+ const attrs = {};
335
+ for (const [, name, double, single] of rawAttrs.matchAll(ATTR)) {
336
+ const key = name.toLowerCase();
337
+ if (![...COMMON, ...SHAPES[tag]].includes(key)) continue;
338
+ const value = readAttr(tag, key, double ?? single ?? "");
339
+ if (value instanceof Error) return fail(value.message);
340
+ if (value !== undefined) attrs[key] = value;
341
+ }
342
+ if (tag === "tex") {
343
+ if (tex !== null) return fail("One <tex> per scene.");
344
+ tex = { x: attrs.x ?? TEX_DEFAULT.x, y: attrs.y ?? TEX_DEFAULT.y, size: attrs.size ?? TEX_SIZE, flip: attrs.flip === true, transform: stack.length > 1 ? stack.slice(1).map((node) => node.attrs.transform).filter(Boolean).join(" ") : "" };
345
+ if (!selfClosing) stack.push({ tag: "tex", attrs: {}, children: [], skip: true });
346
+ continue;
347
+ }
348
+ count += 1;
349
+ if (count > MAX_SHAPES) return fail(`A scene is at most ${MAX_SHAPES} shapes: draw fewer, bigger ones.`);
350
+ const node = { tag, attrs, children: [] };
351
+ const parent = stack[stack.length - 1];
352
+ if (parent.skip || parent.tag === "text") return fail(`<${rawTag}> cannot go inside <${parent.tag}>.`);
353
+ parent.children.push(node);
354
+ if (!selfClosing) {
355
+ if (stack.length > MAX_DEPTH) return fail(`Groups nest at most ${MAX_DEPTH} deep.`);
356
+ stack.push(node);
357
+ }
358
+ }
359
+ if (stack.length > 1) return fail(`<${stack[stack.length - 1].tag}> is never closed.`);
360
+ const dropped = dropCoveringFills(root.children);
361
+ if (dropped.buried) return fail(COVER_INK);
362
+ if (count === 0 || drawable(dropped.shapes) === 0) return fail("The scene has no shapes: draw what the page is about.");
363
+ return { shapes: dropped.shapes, tex, error: null };
364
+ }
365
+
366
+ /** One shape, written again from what was read. */
367
+ function shapeSvg(node, colors) {
368
+ const a = node.attrs;
369
+ const parts = [];
370
+ const put = (name, value) => value !== undefined && parts.push(`${name}="${value}"`);
371
+ for (const name of SHAPES[node.tag]) {
372
+ const value = a[name];
373
+ if (value === undefined || name === "flip") continue;
374
+ if (name === "points") put("points", value.map(fmt).join(" "));
375
+ else if (typeof value === "number") put(name, fmt(value));
376
+ else put(name, esc(value));
377
+ }
378
+ if (a.transform) put("transform", esc(a.transform));
379
+ if (a["stroke-width"] !== undefined) put("stroke-width", fmt(a["stroke-width"]));
380
+ if (a.opacity !== undefined) put("opacity", fmt(a.opacity));
381
+ if (a["stroke-dasharray"]) put("stroke-dasharray", a["stroke-dasharray"].map(fmt).join(" "));
382
+ if (node.tag === "text") {
383
+ // Words are ink, set in the page's own face, never stroked.
384
+ put("fill", colors.ink);
385
+ put("stroke", "none");
386
+ put("font-family", "Instrument Sans, sans-serif");
387
+ if (a["font-size"] === undefined) put("font-size", "44");
388
+ return `<text ${parts.join(" ")}>${esc((node.text ?? "").trim())}</text>`;
389
+ }
390
+ if (a.fill !== undefined) put("fill", a.fill === "ink" ? colors.ink : a.fill === "paper" ? colors.paper : a.fill === "hatch" ? "url(#ink-hatch)" : "none");
391
+ if (a.stroke === "none") put("stroke", "none");
392
+ if (node.tag === "g") return `<g ${parts.join(" ")}>${node.children.map((child) => shapeSvg(child, colors)).join("")}</g>`;
393
+ return `<${node.tag} ${parts.join(" ")}/>`;
394
+ }
395
+
396
+ /** The calm Tex, feet at (x, y), `size` tall, from the app's own geometry. */
397
+ function texSvg({ x, y, size, flip, transform }, colors) {
398
+ // The board's figure stands 640 tall; its feet are at CY + 285.
399
+ const s = size / 640;
400
+ const parts = figureParts(CALM, { small: false, minStroke: 11 / s });
401
+ const strands = parts.strands
402
+ .map((st) => `<path d="${st.d}" stroke-width="${fmt(st.width)}"/><path d="${st.dry}" stroke-width="${fmt(st.width * 0.45)}" opacity=".7"/>`)
403
+ .join("");
404
+ const limbs = parts.limbs.map((limb) => `<path d="${limb.d}" stroke-width="${fmt(limb.width)}"/>`).join("");
405
+ const g = parts.googly;
406
+ // The eyes are drawn unmirrored about the figure's centre, so a flipped Tex still looks the same way.
407
+ const eyes =
408
+ `<g transform="translate(${g.x} ${g.y}) scale(${fmt(g.scale)})">` +
409
+ g.whites.map((w) => `<ellipse cx="${w.cx}" cy="${w.cy}" rx="${w.rx}" ry="${w.ry}" fill="${colors.eye}" stroke-width="${fmt(g.outline)}"/>`).join("") +
410
+ g.pupils.map((p) => `<circle cx="${fmt(p.cx)}" cy="${fmt(p.cy)}" r="${p.r}" fill="${colors.ink}" stroke="none"/>`).join("") +
411
+ `</g>`;
412
+ const body = `<g transform="translate(${fmt(x)} ${fmt(y)}) scale(${fmt(flip ? -s : s)} ${fmt(s)}) translate(-${CX} -665)">${strands}${limbs}</g>`;
413
+ const face = `<g transform="translate(${fmt(x)} ${fmt(y)}) scale(${fmt(s)}) translate(-${CX} -665)">${eyes}</g>`;
414
+ const outer = transform ? ` transform="${esc(transform)}"` : "";
415
+ return `<g${outer} data-tex="calm">${body}${face}</g>`;
416
+ }
417
+
418
+ /** Ink speckles on the paper, seeded from the scene so the same scene is the same picture. */
419
+ function speckles(seedText, colors) {
420
+ let s = 0;
421
+ for (let i = 0; i < seedText.length; i++) s = (s * 31 + seedText.charCodeAt(i)) % 2147483647;
422
+ s = s || 99;
423
+ const rnd = () => (s = (s * 16807) % 2147483647) / 2147483647;
424
+ let out = "";
425
+ for (let i = 0; i < 30; i++) {
426
+ out += `<circle cx="${Math.round(rnd() * DRAWING_WIDTH)}" cy="${Math.round(rnd() * DRAWING_HEIGHT)}" r="${fmt(1 + rnd() * 2.4)}" fill="${colors.ink}" opacity="${fmt(0.1 + rnd() * 0.22)}"/>`;
427
+ }
428
+ return out;
429
+ }
430
+
431
+ /**
432
+ * The drawing as one SVG document, `dark` for the dark page. `scene` is
433
+ * `readScene`'s answer; every value in it was read as a number, a keyword or
434
+ * escaped text, so nothing here is the model's markup.
435
+ */
436
+ function drawingSvg(scene, { dark = false, seed = "" } = {}) {
437
+ const colors = dark ? INKS.dark : INKS.light;
438
+ const tex = texSvg(scene.tex ?? TEX_DEFAULT, colors);
439
+ const shapes = scene.shapes.map((node) => shapeSvg(node, colors)).join("");
440
+ return (
441
+ `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${DRAWING_WIDTH} ${DRAWING_HEIGHT}" width="${DRAWING_WIDTH}" height="${DRAWING_HEIGHT}">` +
442
+ `<defs>` +
443
+ // The app's brush (`RoughInk.web.tsx`): the edge moved by low noise, then pitted where the brush ran dry.
444
+ `<filter id="ink-rough" x="-5%" y="-5%" width="110%" height="110%">` +
445
+ `<feTurbulence type="fractalNoise" baseFrequency="0.035" numOctaves="2" seed="4" result="n"/>` +
446
+ `<feDisplacementMap in="SourceGraphic" in2="n" scale="7" xChannelSelector="R" yChannelSelector="G" result="d"/>` +
447
+ `<feTurbulence type="fractalNoise" baseFrequency="0.9" numOctaves="1" seed="9" result="grain"/>` +
448
+ `<feColorMatrix in="grain" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -1.5 1.95" result="holes"/>` +
449
+ `<feComposite in="d" in2="holes" operator="in"/>` +
450
+ `</filter>` +
451
+ `<filter id="ink-paper"><feTurbulence type="fractalNoise" baseFrequency="0.8" numOctaves="3" seed="2"/><feColorMatrix type="matrix" values="${colors.grain}"/></filter>` +
452
+ `<pattern id="ink-hatch" width="22" height="22" patternUnits="userSpaceOnUse" patternTransform="rotate(-41)"><line x1="0" y1="0" x2="0" y2="22" stroke="${colors.ink}" stroke-width="6"/></pattern>` +
453
+ `</defs>` +
454
+ `<rect width="${DRAWING_WIDTH}" height="${DRAWING_HEIGHT}" fill="${colors.paper}"/>` +
455
+ `<rect width="${DRAWING_WIDTH}" height="${DRAWING_HEIGHT}" filter="url(#ink-paper)"/>` +
456
+ speckles(seed, colors) +
457
+ `<g transform="translate(${SAFE.x} ${SAFE.y}) scale(${SAFE.scale})">` +
458
+ `<g filter="url(#ink-rough)" stroke="${colors.ink}" fill="none" stroke-width="8" stroke-linecap="round" stroke-linejoin="round">${shapes}${tex}</g>` +
459
+ `</g></svg>`
460
+ );
461
+ }
462
+
463
+ /** The page the screenshot Worker photographs: the drawing, and the page's face for its words. */
464
+ function drawingHtml(scene, options = {}) {
465
+ const colors = options.dark ? INKS.dark : INKS.light;
466
+ return (
467
+ `<!doctype html><html><head><meta charset="utf-8">` +
468
+ `<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Instrument+Sans:wght@400;500;600;700&amp;display=block">` +
469
+ `<style>html,body{margin:0;padding:0;background:${colors.paper}}svg{display:block}</style></head>` +
470
+ `<body>${drawingSvg(scene, options)}</body></html>`
471
+ );
472
+ }
473
+
474
+ module.exports = { readScene, drawingSvg, drawingHtml, SCENE_WIDTH, SCENE_HEIGHT, DRAWING_WIDTH, DRAWING_HEIGHT, MAX_SCENE_CHARS };