transcript.md 0.1.0__py3-none-any.whl

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 (49) hide show
  1. transcript/__init__.py +35 -0
  2. transcript/_rule/__init__.py +0 -0
  3. transcript/_rule/archive.py +128 -0
  4. transcript/_rule/conda.py +52 -0
  5. transcript/_rule/container.py +290 -0
  6. transcript/_rule/core.py +524 -0
  7. transcript/_rule/lambdas.py +120 -0
  8. transcript/_rule/registry.py +54 -0
  9. transcript/_rule/serialize.py +26 -0
  10. transcript/_rule/snakefile.py +81 -0
  11. transcript/_rule/wildcards.py +110 -0
  12. transcript/cli.py +363 -0
  13. transcript/document.py +56 -0
  14. transcript/execute.py +240 -0
  15. transcript/html/__init__.py +17 -0
  16. transcript/html/_assets/.frontend.sha256 +1 -0
  17. transcript/html/_assets/__init__.py +21 -0
  18. transcript/html/_assets/style.min.css +1 -0
  19. transcript/html/_assets/transcript.min.js +21 -0
  20. transcript/html/_island.py +72 -0
  21. transcript/html/_navigate.py +198 -0
  22. transcript/html/_output.py +100 -0
  23. transcript/html/_resources.py +171 -0
  24. transcript/html/_review.py +34 -0
  25. transcript/html/markup.py +26 -0
  26. transcript/html/page.py +107 -0
  27. transcript/output.py +308 -0
  28. transcript/parse.py +256 -0
  29. transcript/renderers/__init__.py +126 -0
  30. transcript/renderers/bitmap.py +166 -0
  31. transcript/renderers/compose.py +174 -0
  32. transcript/renderers/compose_runtime.js +233 -0
  33. transcript/renderers/datavzrd.py +321 -0
  34. transcript/renderers/datavzrd_runtime.js +362 -0
  35. transcript/renderers/label.py +211 -0
  36. transcript/renderers/markdown.py +45 -0
  37. transcript/renderers/table.py +32 -0
  38. transcript/renderers/vegalite.py +250 -0
  39. transcript/review/__init__.py +13 -0
  40. transcript/review/_block.py +167 -0
  41. transcript/review/_migrate.py +212 -0
  42. transcript/review/_records.py +238 -0
  43. transcript/review/_span.py +287 -0
  44. transcript/review/load.py +64 -0
  45. transcript/tmd.py +159 -0
  46. transcript_md-0.1.0.dist-info/METADATA +17 -0
  47. transcript_md-0.1.0.dist-info/RECORD +49 -0
  48. transcript_md-0.1.0.dist-info/WHEEL +4 -0
  49. transcript_md-0.1.0.dist-info/entry_points.txt +2 -0
transcript/execute.py ADDED
@@ -0,0 +1,240 @@
1
+ """Execute a document statement by statement, capturing report output."""
2
+
3
+ import __future__ as future
4
+
5
+ import ast
6
+
7
+ # import builtins
8
+ import io
9
+ import sys
10
+ import types
11
+ from pathlib import Path
12
+ from typing import TYPE_CHECKING
13
+
14
+ from ._rule import registry
15
+ from .parse import ReportBlock, span
16
+ from .renderers.markdown import markdown
17
+
18
+ if TYPE_CHECKING:
19
+ from .document import AstDocument
20
+
21
+ _FUTURE_FLAGS = 0
22
+ for _name in future.all_feature_names:
23
+ _FUTURE_FLAGS |= getattr(future, _name).compiler_flag
24
+
25
+
26
+ def text(value: str):
27
+ """Normalize captured output to LF endings with a single trailing newline."""
28
+ return value.replace("\r\n", "\n").replace("\r", "\n").rstrip("\n") + "\n"
29
+
30
+
31
+ class ExecutionScope:
32
+ def __init__(self, path: Path, wildcards: dict[str, str] | None = None):
33
+ self.path = path
34
+ self.wildcards = dict(wildcards or {})
35
+
36
+ def __enter__(self):
37
+ filename = str(self.path)
38
+ self.registry_scope = registry.Execution(self.wildcards)
39
+ self.registry_scope.__enter__()
40
+ self.old_path, self.old_argv = sys.path, sys.argv
41
+ sys.path = [str(self.path.parent), *self.old_path]
42
+ sys.argv = [filename]
43
+ module = types.ModuleType("__main__")
44
+ self.old_main = sys.modules.get("__main__")
45
+ sys.modules["__main__"] = module
46
+ namespace = module.__dict__
47
+ namespace.update(__file__=filename, __package__=None)
48
+ return namespace
49
+
50
+ def __exit__(self, exc_type, exc, tb):
51
+ if self.old_main is not None:
52
+ sys.modules["__main__"] = self.old_main
53
+ else:
54
+ sys.modules.pop("__main__", None)
55
+ sys.path = self.old_path
56
+ sys.argv = self.old_argv
57
+ self.registry_scope.__exit__(exc_type, exc, tb)
58
+
59
+
60
+ md = markdown
61
+
62
+
63
+ def execute(self: AstDocument, path: Path, wildcards: dict[str, str] | None = None):
64
+ """Execute statements in order and capture dynamically identified reports."""
65
+
66
+ filename = str(path)
67
+ # collect future flags and send to each compile cell
68
+ future_flags = (
69
+ compile(self.tree, filename, "exec", dont_inherit=True).co_flags & _FUTURE_FLAGS
70
+ )
71
+ hack_name = "__transcript__name"
72
+ while hack_name in self.source:
73
+ hack_name += hack_name
74
+
75
+ def eval_expression(node: ast.expr):
76
+ return eval(
77
+ compile(
78
+ ast.Expression(node),
79
+ filename,
80
+ "eval",
81
+ flags=future_flags,
82
+ dont_inherit=True,
83
+ ),
84
+ namespace,
85
+ )
86
+
87
+ def exec_statement(node: ast.stmt):
88
+ return exec(
89
+ compile(
90
+ ast.Module(body=[node], type_ignores=[]),
91
+ filename,
92
+ "exec",
93
+ flags=future_flags,
94
+ dont_inherit=True,
95
+ ),
96
+ namespace,
97
+ )
98
+
99
+ def run_captured(node: ast.stmt):
100
+ stream = io.StringIO()
101
+ old = sys.stdout
102
+ sys.stdout = stream
103
+
104
+ # def displayhook(value):
105
+ # from .renderers.vegalite import is_altair_chart, vegalite
106
+
107
+ # if is_altair_chart(value):
108
+ # setattr(builtins, "_", value)
109
+ # print(repr(vegalite(value)))
110
+ # else:
111
+ # old_displayhook(value)
112
+
113
+ # old_displayhook = sys.displayhook
114
+ # sys.displayhook = displayhook
115
+ try:
116
+ exec(
117
+ compile(
118
+ ast.Interactive(body=[node]),
119
+ filename,
120
+ "single",
121
+ flags=future_flags,
122
+ dont_inherit=True,
123
+ ),
124
+ namespace,
125
+ )
126
+ except BaseException as exc:
127
+ failures.append(exc)
128
+ raise
129
+ finally:
130
+ sys.stdout = old
131
+ # sys.displayhook = old_displayhook
132
+ captured = stream.getvalue()
133
+ return text(captured) if captured else ""
134
+
135
+ def with_transcript(context, block: ReportBlock, optional_vars=None):
136
+ with context as entered:
137
+ if optional_vars is not None:
138
+ # bind the entered context manager to the `with ... as` target
139
+ namespace[hack_name] = entered
140
+ assignment = ast.Assign(
141
+ targets=[optional_vars],
142
+ value=ast.Name(id=hack_name, ctx=ast.Load()),
143
+ )
144
+ ast.fix_missing_locations(assignment)
145
+ exec_statement(assignment)
146
+ del namespace[hack_name]
147
+ return [run_captured(statement.node) for statement in block.statements]
148
+
149
+ def with_normal(context, node: ast.With):
150
+ namespace[hack_name] = context
151
+ rebuilt = ast.With(
152
+ items=[
153
+ ast.withitem(
154
+ context_expr=ast.Name(id=hack_name, ctx=ast.Load()),
155
+ optional_vars=node.items[0].optional_vars,
156
+ )
157
+ ],
158
+ body=node.body,
159
+ type_comment=node.type_comment,
160
+ )
161
+ ast.fix_missing_locations(rebuilt)
162
+ exec_statement(rebuilt)
163
+ del namespace[hack_name]
164
+
165
+ failures: list[BaseException] = []
166
+ outputs: list[list[str]] = []
167
+ blocks: list[ReportBlock] = []
168
+ rule_not_set = True
169
+
170
+ with ExecutionScope(path, wildcards) as namespace:
171
+ for i, node in enumerate(self.tree.body):
172
+ if i not in self.regions:
173
+ exec_statement(node)
174
+ if rule_not_set:
175
+ rule_not_set = check_namespace(self, node, namespace)
176
+ continue
177
+ if isinstance(node, ast.With):
178
+ context = eval_expression(node.items[0].context_expr)
179
+ if context is not md:
180
+ if context is registry.current():
181
+ if TYPE_CHECKING:
182
+ context = registry.current()
183
+ assert context is not None
184
+ context.set_lambdas(node)
185
+ with_normal(context, node)
186
+ job = registry.current()
187
+ if context is job and job is not None:
188
+ rule_s, rule_e = span(node.items[0].context_expr, self.position)
189
+ job.edit = span(node, self.position), self.source[rule_s:rule_e]
190
+ if not rule_not_set:
191
+ if not job.target:
192
+ raise NameError(
193
+ "Cannot trace the declared rule, please define "
194
+ "it as a global variable"
195
+ )
196
+ if namespace[job.target] is not job:
197
+ # old name lost, try to find the new one
198
+ rule_not_set = True
199
+ if rule_not_set:
200
+ optional_vars = node.items[0].optional_vars
201
+ if not isinstance(optional_vars, ast.Name):
202
+ raise NameError(
203
+ "transcript.rule() must be assigned `as` a name "
204
+ "in the `with` statement"
205
+ )
206
+ job.target = optional_vars.id
207
+ rule_not_set = False
208
+ continue
209
+ optional_vars = node.items[0].optional_vars
210
+ else:
211
+ context = md
212
+ optional_vars = None
213
+ blocks.append(self.regions[i].parse_block(self.source, self.position))
214
+ outputs.append(with_transcript(context, blocks[-1], optional_vars))
215
+ if rule_not_set:
216
+ rule_not_set = check_namespace(self, node, namespace)
217
+ job = registry.current()
218
+ if failures:
219
+ raise failures[0]
220
+ return blocks, outputs, job
221
+
222
+
223
+ def check_namespace(self: AstDocument, node: ast.stmt, namespace: dict):
224
+ """Find the variable bound to the rule and record its archive insertion.
225
+
226
+ Return whether the rule is still unset.
227
+ """
228
+ job = registry.current()
229
+ if job is None:
230
+ return True
231
+ for name, value in namespace.items():
232
+ if value is job:
233
+ _, end = span(node, self.position)
234
+ newline = self.source.find("\n", end)
235
+ if newline == -1:
236
+ newline = len(self.source)
237
+ job.target = name
238
+ job.edit = (newline, newline), None
239
+ return False
240
+ return False
@@ -0,0 +1,17 @@
1
+ """Render recorded documents as HTML without executing their Python code.
2
+
3
+ The implementation is split by responsibility:
4
+
5
+ - :mod:`~transcript.html._assets` packaged static CSS and JavaScript
6
+ - :mod:`~transcript.html._markup` online image/link recognition and rewriting
7
+ - :mod:`~transcript.html._output` statement code, outputs, and script blocks
8
+ - :mod:`~transcript.html._navigate` anchors and the document outline
9
+ - :mod:`~transcript.html._island` the embedded archive and its extraction
10
+ - :mod:`~transcript.html._resources` styles, report payload, scripts, and CSP
11
+ - :mod:`~transcript.html.page` assembles the final page
12
+ """
13
+
14
+ from ._island import extract, extract_parts
15
+ from .page import render
16
+
17
+ __all__ = ["extract", "extract_parts", "render"]
@@ -0,0 +1 @@
1
+ 65ec9170de76a1d3feb43c342e8588d95a9f434b5c9d79e7df543fdb68c14572
@@ -0,0 +1,21 @@
1
+ """Compiled CSS and JavaScript shipped with every exported page.
2
+
3
+ The authored TypeScript and CSS live in ``src/frontend``. The frontend build
4
+ writes the minified assets beside this module. This package only reads those
5
+ generated files back into the strings the exporter embeds.
6
+ """
7
+
8
+ from importlib.resources import files
9
+
10
+ __all__ = ["ASSET_SCRIPTS", "SCRIPT", "STYLE"]
11
+
12
+
13
+ def _asset(name: str):
14
+ """Read one compiled frontend asset packaged beside this module."""
15
+ return files(__package__).joinpath(name).read_text(encoding="utf-8")
16
+
17
+
18
+ STYLE = _asset("style.min.css")
19
+ SCRIPT = _asset("transcript.min.js")
20
+
21
+ ASSET_SCRIPTS = (SCRIPT,)
@@ -0,0 +1 @@
1
+ :root{color-scheme:light dark;--unit: 1.25rem;--body-max: 860px;--side: 15rem;--side-rail: 2.25rem;--radius: .4rem;--radius-sm: .25rem;--accent: #3984c6;--accent-dark: #2f6ea8;--accent-soft: #3984c622;--accent-faint: #3984c61a;--accent-mid: #3984c633;--accent-stroke: #3984c680;--border: #8885;--border-soft: #8881;--muted: #888;--surface: canvas;--ink: canvastext;--ink-soft: #172033cc;--shadow-soft: #0002;--shadow: #0003;--shadow-strong: #0004;--code-bg: #f1f5f9;--code-ink: #172033;--diff-ins-bg: #28a74526;--diff-ins-line: #2e7d32;--diff-del-bg: #c6282818;--diff-del-line: #c62828;--danger: #b42318;--danger-bg: #fff1f0;--locked: #b4531a;--locked-veil: #b4531a1a;--locked-stroke: #b4531a99;--locked-strong: #8f3f12}body{margin:0;font:17px/1.65 system-ui,sans-serif}.page{max-width:var(--body-max);margin:3rem auto;padding:0 1.25rem 0 3rem}h1,h2,h3{line-height:1.25}a{color:var(--accent)}code{font-family:ui-monospace,monospace;font-size:.9em}blockquote{margin-left:0;padding-left:1rem;border-left:3px solid var(--border)}table{border-collapse:collapse}th,td{border:1px solid var(--border);padding:.35rem .7rem}.page--navigate{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:var(--unit);margin:3rem auto;padding:0 var(--unit);max-width:calc(var(--body-max) + var(--side) + 3 * var(--unit))}.page--navigate>main{grid-area:1 / 1;max-width:var(--body-max)}.page--navigate>.navigate{grid-area:1 / 2}.navigate{position:sticky;top:3rem;align-self:start;z-index:20;width:var(--side);max-height:calc(100vh - 6rem);overflow-y:auto;box-sizing:border-box;padding-right:.75rem;border-right:1px solid var(--border);font-size:.9rem;transition:width .2s ease}.navigate-tabs{display:flex;gap:.25rem;margin-bottom:.5rem}.navigate-tab{display:flex;align-items:center;flex:1;min-width:0;border-bottom:2px solid transparent}.navigate-tab[data-active=true]{border-bottom-color:var(--accent)}.navigate-tab-body{flex:1;min-width:0;padding:.15rem .25rem;background:none;border:0;cursor:pointer;color:var(--muted);font:inherit;text-align:left;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.navigate-tab[data-active=true] .navigate-tab-body{color:inherit;font-weight:600}.navigate-tab-toggle{flex:none;width:1.4rem;height:1.4rem;display:grid;place-items:center;background:none;border:0;cursor:pointer;border-radius:var(--radius-sm);font:700 .9rem/1 ui-monospace,monospace}.navigate-tab-toggle[aria-pressed=true]{color:var(--accent)}.navigate-tab-toggle[aria-pressed=false]{color:var(--muted)}.navigate-eye{display:grid;width:1rem;height:1rem}.navigate-eye svg{grid-area:1 / 1;width:100%;height:100%;fill:none;stroke:currentColor;stroke-width:1.5;stroke-linecap:round;stroke-linejoin:round}.navigate-tab-toggle[aria-pressed=true] .navigate-eye-closed,.navigate-tab-toggle[aria-pressed=false] .navigate-eye-open{display:none}.navigate-tab-toggle:hover{background:var(--accent-soft)}.navigate-tab-body:focus-visible,.navigate-tab-toggle:focus-visible{outline:2px solid var(--accent);outline-offset:2px}.navigate[data-collapsed=true]{top:3rem;width:var(--side-rail);height:auto;max-height:calc(100vh - 6rem);padding:.4rem .2rem;border:1px solid var(--border);border-radius:var(--radius);background:var(--surface);box-shadow:none}.navigate[data-collapsed=true] .navigate-list{display:none}.navigate[data-collapsed=true] .navigate-tabs{flex-direction:column;gap:.3rem;margin-bottom:0}.navigate[data-collapsed=true] .navigate-tab{flex:none;border-bottom:0;border-left:2px solid transparent}.navigate[data-collapsed=true] .navigate-tab-toggle{display:none}.navigate[data-collapsed=true] .navigate-tab-body{flex:none;padding:.4rem .1rem;writing-mode:vertical-rl}.navigate ol{list-style:none;margin:0;padding:0}.navigate li{margin:.1rem 0}.navigate a{display:block;padding:.1rem .5rem;color:inherit;text-decoration:none;border-left:2px solid transparent}.navigate a:hover{color:var(--accent);border-left-color:var(--accent)}.navigate .toc-l1 a{font-weight:600}.navigate .toc-l2 a{padding-left:1.25rem}.navigate .toc-l3 a{padding-left:2rem}.navigate .toc-l4 a,.navigate .toc-l5 a,.navigate .toc-l6 a{padding-left:2.75rem}.navigate .toc-label a{padding-left:1.25rem}.navigate .toc-label a:before{content:"◆ ";color:var(--muted);font-size:.7em;vertical-align:.15em}.navigate .toc-review a{padding-left:1.25rem}.navigate .toc-review a:before{content:"✎ ";color:var(--muted);font-size:.7em;vertical-align:.15em}.script-code,.doctest-code{border:1px solid var(--border);border-radius:var(--radius)}.script-block{position:relative;margin:0;padding:0;border:0}.script-block[open]{display:flow-root}.script-block:not([open]){min-height:var(--unit)}.script-code{margin:0 0 1.5rem;padding:1rem;overflow-x:auto;line-height:1.5}.script-toggle{position:absolute;left:calc(-1 * var(--unit));top:0;width:var(--unit);height:var(--unit);display:grid;place-items:center;cursor:pointer;list-style:none;color:var(--accent);border-radius:var(--radius-sm);line-height:1;font:700 .6rem/1 ui-monospace,monospace}.script-toggle::-webkit-details-marker{display:none}.script-toggle:focus-visible{outline:2px solid var(--accent);outline-offset:2px}.script-toggle:hover,.script-block[open]>.script-toggle{background:var(--accent-soft)}.script-block[open]>.script-toggle{position:sticky;top:.5rem;left:auto;z-index:1;margin-left:calc(-1 * var(--unit));margin-bottom:calc(-1 * var(--unit))}.report-block{display:flow-root}.doctest-code{position:relative;margin:.3rem 0;overflow:hidden;border-left:3px solid var(--accent);--box-border-left: 3px;--box-border-top: 1px;font:.9em/1.5 ui-monospace,monospace}.doctest-code[data-boxed]{overflow:visible}.doctest-code[data-boxed=false]{margin:0;border:0;border-radius:0;--box-border-left: 0px;--box-border-top: 0px;min-height:calc(var(--unit) + .3rem)}.doctest-code[data-boxed=false]>.doc-text{display:none}.output-box-toggle{position:absolute;left:calc(-1 * var(--unit) - var(--box-border-left));top:calc(.3rem - var(--box-border-top));width:var(--unit);height:var(--unit);cursor:pointer;color:var(--accent);border:0;border-radius:var(--radius-sm);background:transparent;font:700 .6rem/1 ui-monospace,monospace}.output-box-toggle:hover{background:var(--accent-soft)}.output-box-toggle:focus-visible{outline:2px solid var(--accent);outline-offset:2px}.doc-text{margin:0;overflow-x:auto;font:inherit}.doc-code,.doc-out{display:block;padding:0 1rem;font:inherit}.doc-code{min-width:fit-content;padding-top:.65rem;background:var(--code-bg);color:var(--code-ink)}.doc-line{position:relative;display:block;padding-left:4ch}.doc-line:before{position:absolute;left:0;content:"... ";user-select:none;-webkit-user-select:none}.doc-line:first-child:before{content:">>> "}.doc-line.multiline-string:before{content:""}.tmd-render-error{margin:1rem 0;padding:.75rem 1rem;border:1px solid var(--danger);border-radius:var(--radius);color:var(--danger);background:var(--danger-bg)}.doc-out{padding-bottom:.65rem}.doc-code+.doc-out{padding-top:.35rem}.doc-code:only-child{padding-bottom:.65rem}.doc-out:only-child{padding-top:.65rem}.tmd-toolbar{position:fixed;right:var(--unit);bottom:var(--unit);z-index:30;display:flex;gap:.4rem}.tmd-toolbar button{padding:.3rem .7rem;cursor:pointer;color:var(--ink);background:var(--surface);border:1px solid var(--border);border-radius:var(--radius-sm);box-shadow:0 1px 4px var(--shadow);font:600 .8rem/1.4 system-ui,sans-serif}.tmd-toolbar button:hover{background:var(--accent-soft)}.doc-md{position:relative}.doctest-code:has(>.transcript-report[data-tmd-renderer=markdown]){font:inherit}.doctest-code:has(>.transcript-report[data-tmd-renderer=markdown])>.doc-text{font:.9em/1.5 ui-monospace,monospace}.tmd-md-popup[hidden],.tmd-md-rendered[hidden]{display:none}.tmd-md-source[hidden],.tmd-md-comment[hidden],.tmd-rec-list[hidden]{display:none!important}.tmd-md-popup{position:absolute;left:0;right:0;z-index:10;margin:0;padding:.65rem 1rem;display:flex;flex-direction:column;gap:.5rem;border:1px solid var(--border);border-radius:var(--radius);box-shadow:0 8px 24px var(--shadow);background:var(--code-bg);color:var(--code-ink)}.tmd-md-overlay{position:absolute;inset:0;width:100%;height:100%;overflow:visible;pointer-events:none;z-index:5}.tmd-md-box{fill:var(--accent-faint);stroke:var(--accent-stroke);stroke-width:3;filter:drop-shadow(0 1px 2px var(--shadow-soft))}.tmd-md-box-active{fill:var(--accent-mid);stroke:var(--accent)}.tmd-md-box.tmd-md-locked{fill:var(--locked-veil);stroke:var(--locked-stroke)}.tmd-md-wave{fill:none;stroke:var(--accent);stroke-width:1.6;stroke-linecap:round}.tmd-md-controls{position:absolute;inset:0;pointer-events:none;z-index:6}.tmd-md-controls>*{position:absolute;pointer-events:auto}.tmd-md-trigger{padding:.15rem .45rem;cursor:pointer;color:var(--accent);background:var(--surface);border:1px solid var(--border);border-radius:var(--radius-sm);box-shadow:0 1px 4px var(--shadow);font:600 .75rem/1.2 system-ui,sans-serif}.tmd-md-trigger:hover{background:var(--accent-soft)}.tmd-md-trigger:focus-visible,.tmd-md-badge:focus-visible{outline:2px solid var(--accent);outline-offset:2px}.tmd-md-badge{width:1.15rem;height:1.45rem;padding:0;border:0;background:var(--accent);color:#fff;cursor:pointer;clip-path:polygon(0 0,100% 0,100% 72%,50% 100%,0 72%);font:700 .7rem/1.45 system-ui,sans-serif;display:grid;place-items:center;box-shadow:0 1px 3px var(--shadow-strong)}.tmd-md-badge[hidden]{display:none}.tmd-md-badge:hover{background:var(--accent-dark)}.tmd-md-badge.tmd-md-locked{background:var(--locked)}.tmd-md-badge.tmd-md-locked:hover{background:var(--locked-strong)}.tmd-md-actions{display:flex;justify-content:flex-end;gap:.35rem}.tmd-md-actions button{padding:.15rem .55rem;cursor:pointer;color:var(--accent);background:var(--surface);border:1px solid var(--border);border-radius:var(--radius-sm);font:600 .75rem/1.2 system-ui,sans-serif}.tmd-md-actions button:hover{background:var(--accent-soft)}.tmd-md-actions button:focus-visible{outline:2px solid var(--accent);outline-offset:2px}.tmd-md-source{position:relative;max-height:40vh;overflow:hidden;border:1px solid var(--border);border-radius:var(--radius-sm)}.tmd-md-source:focus-within{border-color:var(--accent);box-shadow:0 0 0 2px var(--accent-soft)}.tmd-diff-fill{position:absolute;inset:0;margin:0;padding:.35rem .5rem;overflow:hidden;pointer-events:none;font:.9em/1.5 ui-monospace,monospace;white-space:pre-wrap;overflow-wrap:anywhere;color:var(--code-ink)}.tmd-diff-input{position:relative;z-index:1;display:block;box-sizing:border-box;width:100%;resize:none;border:0;padding:.35rem .5rem;margin:0;font:.9em/1.5 ui-monospace,monospace;white-space:pre-wrap;overflow-wrap:anywhere;background:transparent!important;color:transparent!important;-webkit-text-fill-color:transparent!important;caret-color:var(--accent)}.tmd-diff-input::selection{background:var(--accent-mid)}.tmd-diff-input:focus{outline:none}.tmd-diff-ins{background:var(--diff-ins-bg);border-radius:.15rem;text-decoration:overline;text-decoration-color:var(--diff-ins-line);text-decoration-thickness:.12em}.tmd-diff-del{background:var(--diff-del-bg);border-radius:.15rem;text-decoration:underline;text-decoration-color:var(--diff-del-line);text-decoration-thickness:.12em}.tmd-diff-anchor{position:relative;display:inline-block;width:0;height:0;color:var(--diff-del-line)}.tmd-diff-edit-del{position:absolute;left:-1px;top:-.8em;width:2px;height:1.1em;background:currentColor;border-radius:1px}.tmd-diff-range{background:var(--accent-faint);border-radius:.15rem}.tmd-diff-range .tmd-diff-anchor{color:var(--accent)}.tmd-diff-last-del,.tmd-diff-next-ins{position:absolute;left:0;width:.62rem;height:.34rem;background-color:currentColor;-webkit-mask-repeat:no-repeat;mask-repeat:no-repeat;-webkit-mask-position:center;mask-position:center;-webkit-mask-size:contain;mask-size:contain}.tmd-diff-last-del{top:-.8em;transform:translate(-50%,-100%);--tmd-chevron: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 10 6'%3E%3Cpolyline points='1,1 5,5 9,1' fill='none' stroke='black' stroke-width='1.6' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E");-webkit-mask-image:var(--tmd-chevron);mask-image:var(--tmd-chevron)}.tmd-diff-next-ins{top:.3em;transform:translate(-50%);--tmd-chevron: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 10 6'%3E%3Cpolyline points='1,5 5,1 9,5' fill='none' stroke='black' stroke-width='1.6' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E");-webkit-mask-image:var(--tmd-chevron);mask-image:var(--tmd-chevron)}.tmd-md-comment{display:block}.tmd-md-comment textarea{box-sizing:border-box;width:100%;resize:none;border:1px solid var(--border);border-radius:var(--radius-sm);padding:.35rem .5rem;font:.85em/1.5 system-ui,sans-serif;background:var(--surface);color:var(--ink);caret-color:var(--accent)}.tmd-md-comment textarea:focus{outline:none;border-color:var(--accent);box-shadow:0 0 0 2px var(--accent-soft)}.tmd-md-comment textarea[readonly]{background:var(--border-soft);caret-color:transparent}.tmd-rec-list{display:flex;flex-direction:column;gap:.45rem;max-height:50vh;overflow:auto}.tmd-rec{display:flex;flex-direction:column;gap:.2rem}.tmd-rec-code{margin:0;padding:.35rem .5rem;border:1px solid var(--border);border-radius:var(--radius-sm);font:.9em/1.5 ui-monospace,monospace;white-space:pre-wrap;overflow-wrap:anywhere;cursor:pointer}.tmd-rec-source .tmd-rec-code{border-left:3px solid var(--rec-color, var(--border));cursor:default}.tmd-rec-meta{display:flex;align-items:flex-start;gap:.3rem;padding:0 .1rem}.tmd-rec-time{padding:0 .35rem;border-radius:var(--radius-sm);background:color-mix(in srgb,var(--rec-color, var(--accent)) 18%,transparent);color:var(--ink-soft);font:600 .72rem/1.5 system-ui,sans-serif;font-variant-numeric:tabular-nums}.tmd-rec-comment{flex:1;min-width:0;font:.8em/1.4 system-ui,sans-serif;white-space:pre-wrap;color:var(--ink-soft)}.tmd-rec-comment .tmd-rec-time{margin-right:.4rem}.tmd-rec-sep{display:flex;align-items:center;gap:.5rem}.tmd-rec-sep-rule{flex:1;border-top:1px solid var(--border)}.tmd-rec-hl{border-radius:.15rem}.tmd-rec-actions{display:inline-flex;flex:none}.tmd-rec-actions button{padding:0 .35rem;cursor:pointer;color:var(--accent);background:var(--surface);border:1px solid var(--border);border-radius:0;font:600 .75rem/1.4 system-ui,sans-serif}.tmd-rec-actions button:first-child{border-radius:var(--radius-sm) 0 0 var(--radius-sm)}.tmd-rec-actions button:last-child{border-radius:0 var(--radius-sm) var(--radius-sm) 0}.tmd-rec-actions button:only-child{border-radius:var(--radius-sm)}.tmd-rec-actions button+button{border-left:0}.tmd-rec-actions button:hover{background:var(--accent-soft)}.tmd-rec-actions button:focus-visible{outline:2px solid var(--accent);outline-offset:2px}.tmd-rec .tmd-md-source,.tmd-rec .tmd-md-comment{width:100%}img{max-width:100%;height:auto}main img{display:block;margin:.35rem auto;max-height:50vh;object-fit:contain;cursor:zoom-in}main img.image-expanded{width:100%;max-height:none;cursor:zoom-out}main img:focus-visible{outline:2px solid var(--accent);outline-offset:2px}@media(prefers-color-scheme:dark){:root{--code-bg: #202b3b;--code-ink: #e5eaf1;--ink-soft: #e5eaf1cc;--diff-ins-bg: #28a7453d;--diff-del-bg: #c6282833}.tmd-md-popup textarea{background:var(--code-bg);color:var(--code-ink)}}@media(max-width:920px){.page--navigate{display:block}.page--navigate>main{margin:0 auto}.page--navigate:has(.navigate[data-collapsed=true])>main{margin-left:0;margin-right:calc(var(--side-rail) + var(--unit))}.navigate{position:fixed;top:3rem;right:var(--unit);left:auto;background:var(--surface);color:var(--ink);border:1px solid var(--border);border-radius:var(--radius);box-shadow:-2px 0 12px var(--shadow-soft)}}@media print{.page{max-width:none;margin:0;padding:0}.page--navigate{display:block}.navigate{display:none}.script-toggle{display:none!important}.script-block:not([open]){min-height:0}.tmd-toolbar,.tmd-md-controls,.tmd-md-overlay,.tmd-md-popup{display:none!important}.tmd-md-rendered{display:block!important}}
@@ -0,0 +1,21 @@
1
+ (()=>{document.querySelectorAll("main img").forEach(o=>{o.tabIndex=0,o.setAttribute("role","button"),o.setAttribute("aria-pressed","false"),o.title="Click to expand to text width";function t(){let e=o.classList.toggle("image-expanded");o.setAttribute("aria-pressed",String(e)),o.title=e?"Click to restore preview":"Click to expand to text width"}o.addEventListener("click",t),o.addEventListener("keydown",e=>{(e.key==="Enter"||e.key===" ")&&(e.preventDefault(),t())})});document.querySelectorAll(".doctest-code[data-boxed]").forEach(o=>{let t=o.querySelector(":scope > .output-box-toggle");if(!t)return;function e(n){o.dataset.boxed=String(n),t.setAttribute("aria-expanded",String(n)),t.title=n?"Hide code and frame":"Show code and frame"}t.addEventListener("click",()=>e(o.dataset.boxed!=="true")),e(o.dataset.boxed==="true")});(function(){function o(e){if(e.dataset.tmdWired==="true")return;e.dataset.tmdWired="true";let n=Array.from(e.querySelectorAll(".navigate-tab")),r=e.querySelector(".navigate-list");if(!r)return;let i=Array.from(r.querySelectorAll("[data-tmd-type]"));function s(){return(r.dataset.tmdShow||"").split(/\s+/).filter(Boolean)}function l(h){r.dataset.tmdShow=h.join(" "),i.forEach(g=>{g.hidden=!h.includes(g.dataset.tmdType)}),n.forEach(g=>{let x=h.includes(g.dataset.tmdType);g.dataset.active=String(x),g.querySelector(".navigate-tab-toggle")?.setAttribute("aria-pressed",String(x))}),e.dataset.collapsed=String(h.length===0)}if(n.forEach(h=>{let g=h.dataset.tmdType;h.querySelector(".navigate-tab-toggle")?.addEventListener("click",()=>{let x=s();l(x.includes(g)?x.filter(C=>C!==g):[...x,g])}),h.querySelector(".navigate-tab-body")?.addEventListener("click",()=>{l([g])})}),!n.length)return;let a=window.matchMedia("(max-width: 920px)"),c=n[0].dataset.tmdType;function d(h){l(h.matches?[]:[c])}d(a),a.addEventListener("change",d),document.addEventListener("click",h=>{a.matches&&h.target instanceof Node&&!e.contains(h.target)&&l([])})}function t(){document.querySelectorAll(".navigate").forEach(o)}window.transcriptInitNavigate=t,t()})();function ct(o,t,e){let n=new Blob([t],{type:e}),r=URL.createObjectURL(n),i=document.createElement("a");i.href=r,i.download=o,document.body.appendChild(i),i.click(),i.remove(),setTimeout(()=>URL.revokeObjectURL(r),0)}function Zt(){let o=document.documentElement.cloneNode(!0);o.querySelectorAll(".tmd-toolbar, .navigate, [data-tmd-library]").forEach(e=>e.remove());let t=window.transcriptReviewStore;if(t){let e=document.createElement("script");e.id="transcript-reviews",e.type="application/json",e.textContent=t.exportIsland();let n=o.querySelector("#transcript-reviews");n?n.replaceWith(e):o.querySelector("#transcript-source")?.after(e)}return`<!doctype html>
2
+ `+o.outerHTML}(function(){let o=document.getElementById("transcript-source");if(!o)return;let t;try{t=JSON.parse(o.textContent)}catch{return}if(typeof t!="string")return;let e=document.createElement("div");e.className="tmd-toolbar";let n=document.createElement("button");n.type="button",n.textContent="Export .tmd.py",n.addEventListener("click",()=>{let i=window.transcriptReviewStore,s=i?i.exportSource():t;ct(document.title+".tmd.py",s,"text/plain")});let r=document.createElement("button");r.type="button",r.textContent="Save .html",r.addEventListener("click",()=>{ct(document.title+".html",Zt(),"text/html")}),e.append(n,r),document.body.appendChild(e)})();var te=new TextEncoder;function ee(o){let t="";return o.forEach(e=>{t+=String.fromCharCode(e)}),btoa(t)}async function dt(o,t){let[e,n]=o.integrity.split("-",2);if(e!=="sha384"||!n)return!1;let r=await crypto.subtle.digest("SHA-384",te.encode(t));return ee(new Uint8Array(r))===n}async function ne(o,t){let e;if("caches"in window)try{e=await caches.open(t)}catch{e=null}if(e){let i=await e.match(o.url);if(i){let s=await i.text();if(await dt(o,s))return s;await e.delete(o.url)}}let n=await fetch(o.url,{mode:"cors",credentials:"omit"});if(!n.ok)throw new Error(`${o.url}: HTTP ${n.status}`);let r=await n.text();if(!await dt(o,r))throw new Error(`${o.url}: SHA-384 integrity check failed`);return e&&await e.put(o.url,new Response(r,{headers:{"Content-Type":o.type==="style"?"text/css; charset=utf-8":"text/javascript; charset=utf-8"}})),r}async function re(o,t){if(o.type==="style"){let e=document.createElement("style");return e.dataset.tmdLibrary=o.name,e.textContent=t,document.head.appendChild(e),Promise.resolve()}return new Promise((e,n)=>{let r=new Blob([t],{type:"text/javascript"}),i=URL.createObjectURL(r),s=document.createElement("script");s.src=i,s.dataset.tmdLibrary=o.name,s.onload=()=>{URL.revokeObjectURL(i),e()},s.onerror=()=>{URL.revokeObjectURL(i),n(new Error(`could not execute ${o.name}`))},document.head.appendChild(s)})}async function ut(o,t){for(let e of o)e.global&&window[e.global]||await re(e,await ne(e,t));if(typeof window.markdownit!="function"||!window.hljs)throw new Error("renderer libraries did not expose their browser globals")}function A(o,t,e){let n=o[o.length-1];n&&n.orig===n.mod==(t===e)?(n.orig+=t,n.mod+=e):o.push({orig:t,mod:e})}function ht(o,t){let e=o.length,n=t.length;if(e*n>1e6)return o===t?[{orig:o,mod:t}]:[{orig:o,mod:""},{orig:"",mod:t}];let r=Array.from({length:e+1},()=>new Uint32Array(n+1));for(let a=e-1;a>=0;a-=1)for(let c=n-1;c>=0;c-=1)r[a][c]=o[a]===t[c]?r[a+1][c+1]+1:Math.max(r[a+1][c],r[a][c+1]);let i=[],s=0,l=0;for(;s<e&&l<n;)o[s]===t[l]?(A(i,o[s],t[l]),s+=1,l+=1):r[s+1][l]>=r[s][l+1]?(A(i,o[s],""),s+=1):(A(i,"",t[l]),l+=1);for(;s<e;)A(i,o[s],""),s+=1;for(;l<n;)A(i,"",t[l]),l+=1;return i}var P={words:ht,chars:ht};function pt(o){o&&(P.words=(t,e)=>mt(ie(ft(o.diffWordsWithSpace(t,e)))),P.chars=(t,e)=>mt(ft(o.diffChars(t,e))))}function mt(o){let t=[];for(let e of o)A(t,e.orig,e.mod);return t}function ft(o){let t=[];for(let e of o)A(t,e.removed?"":e.value,e.added?"":e.value);return t}function k(o,t){return P.words(o,t)}function ie(o){let t=[],e=0;for(;e<o.length;){let n=o[e],r=o[e+1];r&&n.mod===""&&r.orig===""?(t.push(...P.chars(n.orig,r.mod)),e+=2):r&&n.orig===""&&r.mod===""?(t.push(...P.chars(r.orig,n.mod)),e+=2):(t.push(n),e+=1)}return t}function Z(o,t){let e=Math.min(o.length,t.length),n=0;for(;n<e&&o[n]===t[n];)n+=1;let r=o.length,i=t.length;for(;r>n&&i>n&&o[r-1]===t[i-1];)r-=1,i-=1;return{start:n,end:r,revised:t.slice(n,i)}}var H=class{constructor(t){this.record=t.record??null,this.chosen=t.chosen,this.original=t.original,this.edit=t.edit,this.comment=t.comment,this.modified=t.modified,this.selection=t.selection??null,this.bands=null,this.locked=t.locked??!1}};function oe(o){let t=o.replace(/\\/g,"\\\\").replace(/\r/g,"\\r").replace(/\t/g,"\\t");return t=t.replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g,e=>"\\x"+e.charCodeAt(0).toString(16).padStart(2,"0")),t.replace(/"{3,}|"+$/g,e=>e.replace(/"/g,'\\"'))}function gt(o,t,e){let n=o.replace(/\n+$/,"")+`
3
+ `;return t.length?n+`
4
+ `+tt(t,e)+`
5
+ `:n}function tt(o,t){let e=o.map(i=>JSON.stringify(i.data())),n=e.length?`[
6
+ `+e.map(i=>" "+i).join(`,
7
+ `)+`
8
+ ]`:"[]";return`if "${t?`transcript.review=${t}`:"transcript.review"}":
9
+ """${oe(n)}"""`}function wt(o,t){let e={records:o.map(n=>n.data()),hash:t};return JSON.stringify(e).replace(/</g,"\\u003c").replace(/>/g,"\\u003e")}function bt(o){let t=new Map,e=new Map;for(let n of o){if(n.type!=="source")continue;let r=n.at,i=n.before??null,s=t.get(i)??t.set(i,new Map).get(i);for(let l=r.lastLine();l>=r.start_line;l-=1)s.set(l,n);if(n.cover){let{span:l,time:a}=n.cover,c=e.get(a)??e.set(a,new Map).get(a);for(let d=l.start_line;d<=l.lastLine();d+=1)(c.get(d)??c.set(d,[]).get(d)).push(n)}}for(let n of e.values())n.forEach(r=>r.sort((i,s)=>{let l=i.cover.span.start_line-s.cover.span.start_line;return l!==0?l:i.cover.span.start_column-s.cover.span.start_column}));return{byVersion:t,successors:e}}function yt(o,t,e){let n=[...o].sort((i,s)=>i.start-s.start),r=t;for(let i of n){if(i.start>r)break;if(i.end>r&&(r=i.end),r>=e)return!0}return!1}function vt(o,t){let e=0,n=0;for(let r of o){let i=r.orig.length;if(t<e+i)return n+(i?Math.round((t-e)*r.mod.length/i):0);e+=i,n+=r.mod.length}return n}function xt(o,t){let e=0,n=0;for(let r of o){let i=r.mod.length;if(t<n+i)return e+(i?Math.round((t-n)*r.orig.length/i):0);e+=r.orig.length,n+=r.mod.length}return e}function Et(o,t){let e=null;for(let n of o){if(!n.cover)continue;let r=n.cover.span.contains(t);if(r===0)return n;(e===null||r<0)&&(e=n)}return e}function q(o){let t=o.trim();if(!t.startsWith("L"))throw new Error("invalid coordinate: "+o);let[e,n,r]=et(t.slice(1),"C");if(!/^\d+$/.test(e))throw new Error("invalid coordinate: "+o);if(n&&!/^\d+$/.test(r))throw new Error("invalid coordinate: "+o);return{line:Number(e),col:n?Number(r):null}}var R=class o{constructor(t,e,n,r){this.start_line=t,this.start_column=e,this.end_line=n,this.end_column=r}static fromPoints(t,e){return new o(t.line,t.column,e.line,e.column)}static parse(t){let e=t.trim();if(!e)throw new Error("empty coordinate");if(e.includes("+")){let[a,,c]=et(e,"+"),{line:d,col:h}=q(a);if(h===null||!/^\d+$/.test(c))throw new Error("invalid coordinate: "+t);return new o(d-1,h-1,d-1,h+Number(c)-1)}let[n,r,i]=et(e,"-");if(!r){let{line:a,col:c}=q(n);return c===null?new o(a-1,0,a,0):new o(a-1,c-1,a-1,c)}let s=q(n),l=q(i);return new o(s.line-1,s.col===null?0:s.col-1,l.col===null?l.line:l.line-1,l.col===null?0:l.col)}format(){let{start_line:t,start_column:e,end_line:n,end_column:r}=this,i=t+1;if(t===n)return`L${i}C${e+1}+${r-e}`;if(e===0&&r===0&&n===i)return`L${i}`;let s=e===0?`L${i}`:`L${i}C${e+1}`,l=r===0?`L${n}`:`L${n+1}C${r}`;return s+"-"+l}isEmpty(){return this.start_line===this.end_line&&this.start_column===this.end_column}lastLine(){return this.end_column===0?this.end_line-1:this.end_line}overlap(t){return this.start_line<=t.lastLine()&&t.start_line<=this.lastLine()}start(){return{line:this.start_line,column:this.start_column}}end(){return{line:this.end_line,column:this.end_column}}contains(t){return t.line<this.start_line||this.start_line===t.line&&t.column<this.start_column?-1:this.start_line<t.line&&t.line<this.lastLine()||t.line===this.lastLine()&&(this.end_column===0||t.column<this.end_column)?0:1}relativeTo(t=this.start()){let e=this.start_line===t.line?this.start_column-t.column:this.start_column,n=this.end_line===t.line?this.end_column-t.column:this.end_column;return new o(this.start_line-t.line,e,this.end_line-t.line,n)}offsetOf(t,e){let n=B(t),r=e.line-this.start_line,i=r===0?e.column-this.start_column:e.column;return Math.min(Math.max(n[r]+i,0),t.length)}pointAt(t,e){let n=B(t),r=n.length-1;for(;r>0&&n[r]>e;)r-=1;let i=(r===0?this.start_column:0)+(e-n[r]);return{line:this.start_line+r,column:i}}extract(t,e=B(t)){if(this.start_line<0||this.start_line>=e.length||this.end_line<0||this.end_line>=e.length)return null;let n=e[this.start_line]+this.start_column,r=e[this.end_line]+this.end_column;return n<0||n>r||r>t.length?null:t.slice(n,r)}},$=class o{constructor(t,e){this.span=t;this.time=e;if(!e||Number.isNaN(Date.parse(e)))throw new Error("at time must be a timestamp")}static parse(t){if(typeof t!="string")throw new Error("at must be a span@time string");let e=t.split("@");if(e.length!==2||!e[0]||!e[1])throw new Error("at must be a span@time string");return new o(R.parse(e[0]),e[1])}format(){return`${this.span.format()}@${this.time}`}};function B(o){let t=[0];for(let e=0;e<o.length;e+=1)o[e]===`
10
+ `&&t.push(e+1);return t}function _(o,t,e){let n=o.lastIndexOf(`
11
+ `,t-1),r=n===-1?0:n+1,i=o.indexOf(`
12
+ `,e);return{start:r,end:i===-1?o.length:i}}function nt(o,t,e){let n=e<t.length?t[e]:o.length,r=e+1<t.length?t[e+1]-1:o.length;return o.slice(n,r)}function et(o,t){let e=o.indexOf(t);return e===-1?[o,"",""]:[o.slice(0,e),t,o.slice(e+t.length)]}function j(o,t){let e=0,n=o.length-1;for(;e<n;){let r=e+n+1>>1;o[r]<=t?e=r:n=r-1}return{line:e,col:t-o[e]}}function Rt(o,t,e,n){let r=e<t.length?t[e]:o.length;return Math.min(r+n,o.length)}function W(o,t){return t>=o.map.length?o.rawEnd-o.rawStart:o.map[t]}function St(o,t){let e=0,n=o.length;for(;e<n;){let r=e+n>>1;o[r]<t?e=r+1:n=r}return e}function Lt(o,t,e,n,r){let i=e.rawStart+W(e,n),s=e.rawStart+W(e,Math.max(r-1,n)),l=j(t,i),a=j(t,s);return new R(l.line,l.col,a.line,a.col+1)}function Mt(o,t,e,n,r){let i=e.rawStart+W(e,n),s=e.rawStart+W(e,Math.max(r-1,n));return new R(j(t,i).line,0,j(t,s).line+1,0)}function Tt(o,t,e,n){if(n.isEmpty())return null;let r=Rt(o,t,n.start_line,n.start_column),i=Rt(o,t,n.end_line,n.end_column);if(i<=e.rawStart||r>=e.rawEnd)return null;let s=St(e.map,Math.max(r-e.rawStart,0)),l=St(e.map,Math.min(i-e.rawStart,e.rawEnd-e.rawStart));for(;l>s&&e.text[l-1]===`
13
+ `;)l-=1;return l<=s?null:{start:s,end:l}}var O=class{constructor(t){this.type="source";this.at=R.parse(t.at),this.cover=t.cover===void 0?null:$.parse(t.cover),this.source=t.source,this.before=t.before}parts(t){return this.diff===void 0&&(this.diff=t(this)),this.diff}data(){let t={type:"source",at:this.at.format()};return this.source!==void 0&&(t.source=this.source),this.cover&&(t.cover=this.cover.format()),this.before!==void 0&&(t.before=this.before),t}},V=class{constructor(t){this.type="review";if(this.at=R.parse(t.at),this.time=t.time,this.edit=t.edit,this.comment=t.comment,t.coveredAt!==void 0&&!Array.isArray(t.coveredAt))throw new Error("coveredAt must be an array");this.coveredAt=(t.coveredAt??[]).map(e=>$.parse(e))}versionOf(t){for(let{span:e,time:n}of this.coveredAt)if(e.start_line<=t&&t<=e.lastLine())return n;return null}data(){let t={type:"review",at:this.at.format(),time:this.time};return this.edit!==void 0&&(t.edit=this.edit),this.comment!==void 0&&(t.comment=this.comment),this.coveredAt.length&&(t.coveredAt=this.coveredAt.map(e=>e.format())),t}};function At(o){let t=[];for(let e of o)try{t.push(e.type==="source"?new O(e):new V(e))}catch{}return t}var U=class{constructor(t,e,n){this.regions=new Map;this.annotations=new Map;this.cache=null;this.source=t,this.records=Array.isArray(e)?At(e):[],this.hash=typeof n=="string"?n:"",this.lineStarts=B(t)}addRegion(t,e,n,r,i){this.regions.set(t,{rawStart:e,rawEnd:n,text:r,map:i});let s=[];return this.annotations.set(t,s),s}index(){return this.cache||(this.cache=bt(this.records)),this.cache}anchor(t,e){return this.index().byVersion.get(e.versionOf(t))?.get(t)??null}currentSpan(t){let e=t.at,n=this.forwardPoint(t,e.start());if(e.isEmpty())return R.fromPoints(n,n);let r;if(e.end_column!==0){let i=this.forwardPoint(t,{line:e.end_line,column:e.end_column-1});r={line:i.line,column:i.column+1}}else{let i=e.lastLine(),s=this.anchor(i,t),l=s?this.lineText(s,i).length:this.bodyLine(i).length,a=this.forwardPoint(t,{line:i,column:Math.max(l-1,0)});r={line:a.line,column:a.column+1},r.column>=this.bodyLine(r.line).length&&(r={line:r.line+1,column:0})}return n.line===e.start_line&&n.column===e.start_column&&r.line===e.end_line&&r.column===e.end_column?e:R.fromPoints(n,r)}forwardPoint(t,e){let n=this.anchor(e.line,t);if(!n)return e;let r=e;for(;n.before;){let i=this.index().successors.get(n.before)?.get(r.line)??[],s=Et(i,r);r=this.mapPoint(s,r),n=s}return r}getDiff(t){let e=t.cover;if(!e)return null;let n=this.coverText(e),r=t.source??t.at.extract(this.source,this.lineStarts)??"",i=t.parts(()=>k(n,r))??[];return{prevText:n,nextText:r,diff:i}}mapPoint(t,e){let n=this.getDiff(t);if(!n||!t.cover)return e;let r=t.cover.span.offsetOf(n.prevText,e);return t.at.pointAt(n.nextText,vt(n.diff,r))}backPoint(t,e){let n=this.getDiff(t);if(!n||!t.cover)return e;let r=t.at.offsetOf(n.nextText,e);return t.cover.span.pointAt(n.prevText,xt(n.diff,r))}coverText(t){let e=[];for(let i=t.span.start_line;i<=t.span.lastLine();i+=1){let s=this.index().byVersion.get(t.time)?.get(i);e.push((s?this.lineText(s,i):"")+`
14
+ `)}let n=e.join("");return t.span.relativeTo({line:t.span.start_line,column:0}).extract(n)??""}bodyLine(t){return nt(this.source,this.lineStarts,t)}lineText(t,e){let n=t.at,r=e-n.start_line;return typeof t.source=="string"?t.source.replace(/\n$/,"").split(`
15
+ `)[r]??"":this.bodyLine(e)}chainFor(t){let{byVersion:e}=this.index(),n=e.get(null)?.get(t)??null,r={line:t,column:0},i=[];for(;n&&(i.push({source:n,span:n.at,line:r.line}),!(!n.cover||n.cover.span.isEmpty()));){let s=this.backPoint(n,r),l=e.get(n.cover.time)?.get(s.line)??null;if(!l||l===n)break;n=l,r=s}return i.reverse(),i}buildAnnotations(){for(let t of this.records){if(t.type!=="review")continue;let e;try{e=this.currentSpan(t)}catch{continue}let n=typeof t.edit=="string",r=this.isLocked(t,e);for(let[i,s]of this.regions){let l=this.spanToDecoded(s,e);if(!l)continue;let a=_(s.text,l.start,l.end),c=s.text.slice(a.start,a.end);this.annotations.get(i).push(new H({record:t,chosen:l,original:c,edit:n?t.edit:c,comment:t.comment||"",modified:n,locked:r}))}}}isLocked(t,e){if(t.coveredAt.length)return!0;for(let n=e.start_line;n<=e.lastLine();n+=1)if(!this.hasLiveSource(n))return!0;return!1}visible(t){let e=(this.annotations.get(t)??[]).filter(l=>l.record),n=new Map(e.map((l,a)=>[l,a])),r=[...e].sort((l,a)=>{let c=l.record?.time??"",d=a.record?.time??"";return c!==d?c<d?1:-1:(n.get(a)??0)-(n.get(l)??0)}),i=[],s=[];for(let l of r)yt(i,l.chosen.start,l.chosen.end)||(s.push(l),i.push(l.chosen));return s}hasLiveSource(t){return this.index().byVersion.get(null)?.has(t)??!1}rawLine(t){return nt(this.source,this.lineStarts,t)}history(t,e){let n=this.regions.get(t);if(!n||!e.record)return null;let r=this.decodedSpan(n,e.chosen.start,e.chosen.end),i=r.start_line,s=r.lastLine(),l="";for(let u=i;u<=s;u+=1){let f=this.rawLine(u);if(f.trim()){l=(f.match(/^[ \t]*/)||[""])[0];break}}let a=u=>l&&u.startsWith(l)?u.slice(l.length):u,c=new Map;for(let u=i;u<=s;u+=1)c.set(u,this.chainFor(u));let d=(u,f)=>{let y=u.source.source;if(y==null)return null;let m=y.replace(/\n$/,"").split(`
16
+ `),b=u.span.lastLine()-u.span.start_line+1;return b===1||m.length===b?m[f-u.span.start_line]??m[m.length-1]??"":m.join(" ")},h=(u,f)=>{for(let y of c.get(u)??[]){let m=y.source,b=m.before??null,E=m.cover?m.cover.time:null,S=b===null||f!==null&&f<=b,N=E===null||f===null||f>E;if(S&&N)return y}return null},g=u=>{let f=[];for(let m=i;m<=s;m+=1){let b=c.get(m)??[],E,S;if(b.length===0)E=this.rawLine(m),S=m;else{let D=h(m,u);if(!D)continue;(D.source.before??null)===null?(E=this.rawLine(m),S=m):(E=d(D,D.line)??"",S=D.line)}let N=a(E);f.push({versionLine:S,text:N,start:0,shift:E.length-N.length})}let y=0;for(let m of f)m.start=y,y+=m.text.length+1;return{text:f.map(m=>m.text).join(`
17
+ `),slots:f}},x=new Set;for(let u of c.values())for(let f of u)f.source.before&&x.add(f.source.before);let C=[...x].sort(),p=[...C,null],w=p.map(u=>g(u)),v=w.map(u=>u.text),M=(u,f,y)=>{let m=u.slots.find(b=>b.versionLine===f);return m?m.start+Math.max(y-m.shift,0):null},I=(u,f)=>{if(f.isEmpty())return null;let y=M(u,f.start_line,f.start_column);if(y===null)return null;let m;if(f.end_column===0){let b=u.slots.find(S=>S.versionLine===f.end_line-1);if(!b)return null;let E=b.start+b.text.length;m=E<u.text.length?E+1:E}else{let b=M(u,f.end_line,f.end_column);if(b===null)return null;m=b}return m>y?{start:y,end:m}:null},z=v.map(()=>[]),Q=[];for(let u of this.annotations.get(t)??[]){if(!u.record)continue;let f=this.decodedSpan(n,u.chosen.start,u.chosen.end);if(f.lastLine()<i||f.start_line>s)continue;let y=u.record.time,m=0;for(let N of C)N<=y&&(m+=1);m>=v.length&&(m=v.length-1);let b=I(w[m],u.record.at),E=v[m],S={annotation:u,time:y,kind:u.modified?"edit":"highlight",text:u.modified?u.edit||"":u.comment||"",comment:u.comment||"",highlight:b?E.slice(b.start,b.end):null,highlightRange:b,hidden:!1};z[m].push(S),Q.push(S)}for(let u of z)u.sort((f,y)=>f.time<y.time?-1:1);for(let u of Q)for(let f of Q)if(!(f===u||f.time<=u.time)&&f.annotation.chosen.start<=u.annotation.chosen.start&&f.annotation.chosen.end>=u.annotation.chosen.end){u.hidden=!0;break}return{layers:v,before:p,entries:z}}save(t,e){let n=this.regions.get(t);if(!n||e.locked)return;let r=e.modified?this.decodedLineSpan(n,e.chosen.start,e.chosen.end):this.decodedSpan(n,e.chosen.start,e.chosen.end),i=r.format(),s=e.record??null;s||(s=new V({type:"review",time:new Date().toISOString(),at:i}),this.records.push(s),e.record=s,this.annotations.get(t)?.push(e)),s.at=r,e.modified?s.edit=e.edit:delete s.edit,e.comment?s.comment=e.comment:delete s.comment,this.ensureSource(r)}remove(t,e){if(!e.record)return;this.records=this.records.filter(r=>r!==e.record);let n=this.annotations.get(t);if(n){let r=n.indexOf(e);r!==-1&&n.splice(r,1)}}exportSource(){return gt(this.source,this.records,this.hash)}renderBlock(){return tt(this.records,this.hash)}exportIsland(){return wt(this.records,this.hash)}ensureSource(t){let e=new R(t.start_line,0,t.lastLine()+1,0);for(let n of this.records){if(n.type!=="source"||n.before)continue;let r=n.at;if(r.start_line<=e.start_line&&r.lastLine()>=e.lastLine())return}this.records.push(new O({type:"source",at:e.format()}))}decodedSpan(t,e,n){return Lt(this.source,this.lineStarts,t,e,n)}decodedLineSpan(t,e,n){return Mt(this.source,this.lineStarts,t,e,n)}spanToDecoded(t,e){return Tt(this.source,this.lineStarts,t,e)}};function kt(o,t){let e=[];for(let n of o){if(!n.width&&!n.height)continue;let r=n.top-t.top,i=n.bottom-t.top,s=n.left-t.left,l=n.right-t.left,a=(r+i)/2,c=e.find(d=>Math.abs(d.t-r)<1||Math.abs((d.t+d.b)/2-a)<Math.max(d.b-d.t,i-r)*.5);c?(c.l=Math.min(c.l,s),c.r=Math.max(c.r,l),c.b=Math.max(c.b,i)):e.push({l:s,r:l,t:r,b:i})}return e.sort((n,r)=>n.t-r.t),e}function Ct(o){if(!o.length)return"";let t=[],e=o[0];t.push([e.l,e.t],[e.r,e.t]);for(let r=1;r<o.length;r+=1){let i=o[r-1],s=o[r];t.push([i.r,s.t]),s.r!==i.r&&t.push([s.r,s.t])}let n=o[o.length-1];t.push([n.r,n.b],[n.l,n.b]);for(let r=o.length-2;r>=0;r-=1){let i=o[r+1],s=o[r];t.push([i.l,s.b]),s.l!==i.l&&t.push([s.l,s.b])}return"M"+t.map(r=>`${r[0].toFixed(1)} ${r[1].toFixed(1)}`).join("L")+"Z"}function Nt(o,t,e){if(t-o<=0)return"";let r=6,i=1.5,s=`M${o.toFixed(1)} ${e.toFixed(1)}`,l=o,a=!0;for(;l<t;){let c=Math.min(l+r,t),d=(l+c)/2;s+=`Q${d.toFixed(1)} ${(a?e-i:e+i).toFixed(1)} ${c.toFixed(1)} ${e.toFixed(1)}`,l=c,a=!a}return s}var Ht="http://www.w3.org/2000/svg";function _t(o,t){let e=o.slice(t.chosen.start,t.chosen.end),n=1;for(let r of e)r===`
18
+ `&&(n+=1);return n}function It(o,t){if(!t.modified)return t.chosen;let e=_(o,t.chosen.start,t.chosen.end),n=Z(t.original||"",t.edit||""),r=e.start+Math.max(n.start,0),i=e.start+n.end;if(i>r)return{start:r,end:i};let s=Math.min(Math.max(r,e.start),Math.max(e.end-1,e.start));return{start:s,end:s+1}}function Dt(o,t){if(!t||typeof t.getClientRects!="function")return null;let e=o.getBoundingClientRect(),n=kt(Array.from(t.getClientRects()),e);return n.length?n:null}function Pt(o,t,e){let n=document.createElementNS(Ht,"path");n.setAttribute("d",Ct(t)),n.setAttribute("class",e),o.appendChild(n);let r=t[t.length-1],i=document.createElementNS(Ht,"path");i.setAttribute("d",Nt(r.l,r.r,r.b)),i.setAttribute("class","tmd-md-wave"),o.appendChild(i)}function Bt(o,t){let e=new Map;for(let r of t){let i=r.bands[0],s=`${Math.round(i.t*2)/2}:${Math.round(i.r*2)/2}`,l=e.get(s);l?l.push(r):e.set(s,[r])}let n=new Set;for(let r of e.values()){let i=r[0];for(let s of r){let l=_t(o,s.annotation),a=_t(o,i.annotation),c=s.annotation.chosen.end-s.annotation.chosen.start,d=i.annotation.chosen.end-i.annotation.chosen.start;(l>a||l===a&&c>d)&&(i=s)}n.add(i.annotation)}return n}function $t(o,t,e,n){let r=e[0],i=document.createElement("button");i.type="button",i.className=t.locked?"tmd-md-badge tmd-md-locked":"tmd-md-badge",i.textContent="⋯";let s=t.modified?Z(t.original||"",t.edit||"").revised:"",l=t.locked?"[superseded: delete only] ":"";i.title=l+(t.comment||s||t.edit||"Mark Up"),i.tmdAnnotation=t,i.addEventListener("click",d=>{d.stopPropagation(),n(t)}),i.addEventListener("mouseenter",()=>rt(i)),i.addEventListener("mouseleave",()=>K(i)),o.appendChild(i);let a=i.offsetWidth,c=i.offsetHeight;i.style.left=`${Math.max(0,r.r-a)}px`,i.style.top=`${Math.max(0,r.t-c+2)}px`,i.hidden=!0}function rt(o){o.tmdHideTimer!==void 0&&(clearTimeout(o.tmdHideTimer),o.tmdHideTimer=void 0),o.hidden=!1}function K(o){o.tmdHideTimer===void 0&&(o.tmdHideTimer=window.setTimeout(()=>{o.tmdHideTimer=void 0,o.hidden=!0},220))}function se(o){let t=document.createElement("span");return t.className="tmd-diff-anchor",t.innerHTML=o,t}var le={v:"last-del","^":"next-ins","|":"edit-del"};function T(o,t){let e=se(`<i class="tmd-diff-${le[o]}"></i>`);return t&&(e.style.color=t),e}var it=["#0072B2","#D55E00","#009E73","#E69F00"];function ot(o,t){let e=new Array(t.length).fill(!1),n=[],r=0;for(let i of k(o,t))if(i.orig===i.mod)r+=i.mod.length;else if(i.mod!==""){for(let s=r;s<r+i.mod.length;s+=1)e[s]=!0;r+=i.mod.length}else n.push(r);return{ins:e,gaps:n}}function Ot(o,t){let e=new Array(o.length).fill(!1),n=[],r=0;for(let i of k(o,t))if(i.orig===i.mod)r+=i.orig.length;else if(i.orig!==""){for(let s=r;s<r+i.orig.length;s+=1)e[s]=!0;r+=i.orig.length}else n.push(r);return{del:e,gaps:n}}function Vt(o,t){let e=o.replace("#",""),n=parseInt(e.slice(0,2),16),r=parseInt(e.slice(2,4),16),i=parseInt(e.slice(4,6),16);return`rgba(${n},${r},${i},${t})`}function Ft(o,t,e,n,r){let i=document.createElement("pre");i.className="tmd-rec-code";for(let s=0;s<=o.length&&(t.gaps.includes(s)&&i.appendChild(T("v",n)),e.gaps.includes(s)&&i.appendChild(T("^",r)),s!==o.length);s+=1){let l=t.ins[s],a=e.del[s];if(!l&&!a){i.appendChild(document.createTextNode(o[s]));continue}let c=document.createElement("span");c.className=l?"tmd-diff-ins":"tmd-diff-del";let d=l?n:r;if(c.style.color=d,c.style.textDecorationColor=d,c.style.background=Vt(d,l?.14:.12),l&&a){let h=document.createElement("span");h.className="tmd-diff-del",h.style.background="transparent",h.style.textDecorationColor=r,h.textContent=o[s],c.appendChild(h)}else c.textContent=o[s];i.appendChild(c)}return i}function ae(o,t,e){let n=document.createElement("pre");n.className="tmd-rec-code";let r=t?Math.max(0,Math.min(t.start,o.length)):-1,i=t?Math.max(r,Math.min(t.end,o.length)):-1;return r<0||i<=r?(n.textContent=o,n):(n.append(document.createTextNode(o.slice(0,r)),ce(o.slice(r,i),e),document.createTextNode(o.slice(i))),n)}function ce(o,t){let e=document.createElement("span");return e.className="tmd-rec-hl",e.style.color=t,e.style.background=Vt(t,.18),e.textContent=o,e}function de(o,t,e,n){let r=e?Math.max(0,Math.min(e.start,t.length)):null,i=e?Math.max(0,Math.min(e.end,t.length)):null,s=r!==null&&i!==null&&i>=r?t.slice(0,r)+o+t.slice(i):o;return Ft(s,ot(t,s),Wt(s.length),n,n)}function qt(o,t,e,n){let r=document.createElement("div");return r.className=`tmd-rec tmd-rec-${o}`,r.style.setProperty("--rec-color",n),r.append(t),e&&r.appendChild(e),r}function jt(o){let t=document.createElement("time");return t.className="tmd-rec-time",t.textContent=o,t}function ue(o,t){let e=document.createElement("div");if(e.className="tmd-rec-actions",!o)return e;if(!o.locked){let r=document.createElement("button");r.type="button",r.textContent="✎",r.title="Edit",r.setAttribute("aria-label","Edit"),r.addEventListener("click",i=>{i.stopPropagation(),t.onEdit?.(o)}),e.appendChild(r)}let n=document.createElement("button");return n.type="button",n.textContent="×",n.title="Delete",n.setAttribute("aria-label","Delete"),n.addEventListener("click",r=>{r.stopPropagation(),t.onDelete?.(o)}),e.appendChild(n),e}var Wt=o=>({del:new Array(o).fill(!1),gaps:[]});function Ut(o,t,e={}){let n={rows:new Map,raws:new Map,comments:new Map};if(o.replaceChildren(),!t||!t.layers.length)return o.hidden=!0,n;o.hidden=!1;let r=t.layers.length,i=s=>it[(r-1-s)%it.length];for(let s=0;s<r;s+=1){let l=t.layers[s],a=s>0?ot(t.layers[s-1],l):{ins:new Array(l.length).fill(!1),gaps:[]},c=s<r-1?Ot(l,t.layers[s+1]):Wt(l.length);o.appendChild(qt("source",Ft(l,a,c,i(Math.max(s-1,0)),i(s)),null,i(s)));for(let h of t.entries[s]||[])o.appendChild(me(h,l,i(s),e,n));let d=t.before[s];d&&o.appendChild(he(d,i(s)))}return fe(o,n,e.focus),n}function he(o,t){let e=document.createElement("div");e.className="tmd-rec-sep",e.style.setProperty("--rec-color",t);let n=document.createElement("span");return n.className="tmd-rec-sep-rule",e.append(jt(o),n),e}function me(o,t,e,n,r){let i=o.annotation,s=o.kind==="edit"?de(o.text,t,o.highlightRange,e):ae(t,o.highlightRange,e),l=document.createElement("div");l.className="tmd-rec-meta";let a=document.createElement("div");if(a.className="tmd-rec-comment",a.appendChild(jt(o.time)),o.comment&&a.appendChild(document.createTextNode(o.comment)),l.appendChild(a),l.appendChild(ue(i,n)),n.onOpen){let d=h=>{h.target?.closest("textarea, button, .tmd-md-source, .tmd-md-comment")||n.onOpen?.(i)};s.addEventListener("click",d),a.addEventListener("click",d)}let c=qt(o.kind,s,l,e);return r.rows.set(i,c),r.raws.set(i,s),r.comments.set(i,a),c}function fe(o,t,e){if(!e)return;let n=t.rows.get(e);!n||e.record?.coveredAt.length||o.appendChild(n)}function pe(o){return o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ge(o,t,e){let n=t.trim();if(!n)return null;let r=n.split(/\s+/).map(pe).join("\\s+"),i=new RegExp(r,"g");i.lastIndex=e;let s=i.exec(o);return!s&&(e!==0&&(i.lastIndex=0,s=i.exec(o)),!s)?null:{start:s.index,end:s.index+s[0].length}}function we(o,t){let e=0;for(let n=0;n<t&&n<o.length;n+=1)/\s/.test(o[n])||(e+=1);return e}function be(o,t){let e=0,n=0;for(;n<o.length&&e<t;)/\s/.test(o[n])||(e+=1),n+=1;return n}function Kt(o,t,e){if(o.nodeType===Node.TEXT_NODE)return{node:o,offset:t};let n=o.childNodes[e?t-1:t];for(;n&&n.nodeType!==Node.TEXT_NODE;)n=e?n.lastChild:n.firstChild;return n?{node:n,offset:e?n.nodeValue.length:0}:null}var X=class{constructor(t){this.entries=[];this.literal=t}align(t){let e=[],n=document.createTreeWalker(t,NodeFilter.SHOW_TEXT),r=0,i;for(;i=n.nextNode();){let s=i.nodeValue;if(!s||!/\S/.test(s))continue;let l=ge(this.literal,s,r);if(!l)continue;let a=(s.match(/^\s*/)||[""])[0].length;e.push({node:i,start:l.start,end:l.end,lead:a}),r=l.end}this.entries=e}literalToDomOffset(t,e){let n=0;for(let s=t.start;s<e&&s<t.end;s+=1)/\s/.test(this.literal[s])||(n+=1);let r=t.node.nodeValue,i=t.lead+be(r.slice(t.lead),n);if(e<this.literal.length&&!/\s/.test(this.literal[e]))for(;i<r.length&&/\s/.test(r[i]);)i+=1;return i}domToLiteralOffset(t,e){let n=this.entries.find(l=>l.node===t);if(!n)return null;let r=we(t.nodeValue,e),i=n.start,s=0;for(;i<n.end&&s<r;)/\s/.test(this.literal[i])||(s+=1),i+=1;if(e<t.nodeValue.length&&!/\s/.test(t.nodeValue[e]))for(;i<n.end&&/\s/.test(this.literal[i]);)i+=1;return i}trimRange(t,e){for(;t<e&&/\s/.test(this.literal[t]);)t+=1;for(;e>t&&/\s/.test(this.literal[e-1]);)e-=1;return{start:t,end:e}}literalToRange(t,e){let n=this.entries.find(s=>s.end>t);if(!n)return null;let r=[...this.entries].reverse().find(s=>s.start<e);if(!r)return null;let i=document.createRange();return i.setStart(n.node,Math.min(this.literalToDomOffset(n,t),n.node.nodeValue.length)),i.setEnd(r.node,Math.min(this.literalToDomOffset(r,e),r.node.nodeValue.length)),i}selectionToLiteral(t,e){if(!e||e.isCollapsed||!e.rangeCount)return null;let n=e.getRangeAt(0);if(!t.contains(n.startContainer)||!t.contains(n.endContainer))return null;let r=Kt(n.startContainer,n.startOffset,!1),i=Kt(n.endContainer,n.endOffset,!0);if(!r||!i)return null;let s=this.domToLiteralOffset(r.node,r.offset),l=this.domToLiteralOffset(i.node,i.offset);if(s===null||l===null||l<=s)return null;let a=this.trimRange(s,l);return a.end>a.start?a:null}};var Y=class{constructor(t){this.annotation=t.annotation,this.chosen=t.chosen,this.chosenLocal=t.chosenLocal,this.lineStart=t.lineStart,this.baseline=t.baseline,this.original=t.original,this.text=t.text,this.body=t.committed,this.committed=t.committed,this.mode=t.mode}};var G=class{constructor(t,e,n){this.markers=null;this.drag=null;this.fill=t,this.input=e,this.session=n}render(){let t=this.session();if(!t)return;let e=this.input.value;if(this.fill.replaceChildren(),this.markers=null,t.text===t.original)this.appendDelimited(e,t.chosenLocal);else for(let n of k(t.original,e))if(n.orig===n.mod)this.fill.append(document.createTextNode(n.mod));else if(n.mod==="")this.fill.appendChild(T("|"));else{n.orig!==""&&this.fill.appendChild(T("|"));let r=document.createElement("span");r.className="tmd-diff-ins",r.textContent=n.mod,this.fill.appendChild(r)}this.fill.scrollTop=this.input.scrollTop,this.fill.scrollLeft=this.input.scrollLeft}appendDelimited(t,e){let n=e?Math.max(0,e.start):0,r=e?Math.min(t.length,e.end):0;if(n>=r){this.fill.append(document.createTextNode(t));return}let i=T("v"),s=T("^"),l=document.createElement("span");l.className="tmd-diff-range",l.append(i,document.createTextNode(t.slice(n,r)),s),this.fill.append(document.createTextNode(t.slice(0,n)),l,document.createTextNode(t.slice(r))),this.markers={left:i,right:s}}autosize(){this.input.style.height="auto";let t=Math.round(window.innerHeight*.4);this.input.style.height=`${Math.min(this.input.scrollHeight,t)}px`}clearMarkers(){this.markers=null,this.fill.querySelectorAll(".tmd-diff-anchor").forEach(t=>t.remove()),this.fill.querySelectorAll(".tmd-diff-range").forEach(t=>{t.replaceWith(...Array.from(t.childNodes))})}updateMarkers(){let t=this.session();if(t){if(t.text!==t.original){this.clearMarkers();return}this.render()}}rectsOfText(){let t=[],e=document.createTreeWalker(this.fill,NodeFilter.SHOW_TEXT),n;for(;n=e.nextNode();){let r=n.nodeValue||"";for(let i=0;i<r.length;i+=1){let s=document.createRange();s.setStart(n,i),s.setEnd(n,Math.min(i+1,r.length));let l=s.getBoundingClientRect();t.push({x:(l.left+l.right)/2,y:(l.top+l.bottom)/2})}}return t.length?t:null}localCharAt(t,e,n){let r=this.input,i=document,s=null;if(i.caretRangeFromPoint&&(s=i.caretRangeFromPoint(t,e)),!s&&i.caretPositionFromPoint){let c=i.caretPositionFromPoint(t,e);c&&(s={startContainer:c.offsetNode,startOffset:c.offset})}if(s&&s.startContainer===r)return Math.max(0,Math.min(s.startOffset,r.value.length));if(n||(n=this.rectsOfText()),!n)return null;let l=-1,a=1/0;for(let c=0;c<n.length;c+=1){let d=n[c];if(!d)continue;let h=Math.abs(d.y-e);if(h>14)continue;let g=Math.abs(d.x-t)+h*2;g<a&&(a=g,l=c)}return l}markerHitSide(t,e){if(!this.markers)return null;let n=5;for(let r of["left","right"]){let i=this.markers[r];if(!i)continue;if([i,...Array.from(i.children)].some(l=>{let a=l.getBoundingClientRect();return t>=a.left-n&&t<=a.right+n&&e>=a.top-6&&e<=a.bottom+6}))return r}return null}currentChosen(){let t=this.session();if(!t||!t.chosen)return null;if(!t.chosenLocal)return t.chosen;let e=t.lineStart+t.chosenLocal.start,n=t.lineStart+t.chosenLocal.end;return n<=e?t.chosen:{start:e,end:n}}setText(t){let e=this.session();e&&(e.text=t,this.input.value!==t&&(this.input.value=t),this.render(),this.autosize())}trackSelection(){let t=this.session();if(!t||this.drag||t.text!==t.original)return;let e=this.input.selectionStart,n=this.input.selectionEnd;if(n<=e){this.clearMarkers();return}t.chosenLocal&&e===t.chosenLocal.start&&n===t.chosenLocal.end||(t.chosenLocal={start:e,end:n},this.updateMarkers())}wire(){this.input.addEventListener("input",()=>this.setText(this.input.value)),this.input.addEventListener("scroll",()=>{this.fill.scrollTop=this.input.scrollTop,this.fill.scrollLeft=this.input.scrollLeft}),this.input.addEventListener("pointerdown",e=>this.pointerDown(e)),this.input.addEventListener("pointermove",e=>this.pointerMove(e));let t=()=>{this.drag=null};this.input.addEventListener("pointerup",t),this.input.addEventListener("pointercancel",t)}pointerDown(t){let e=this.session();if(!e||e.text!==e.original)return;let n=this.markerHitSide(t.clientX,t.clientY);if(n){t.preventDefault(),this.drag={side:n,rects:null};try{this.input.setPointerCapture(t.pointerId)}catch{}}}pointerMove(t){let e=this.session();if(this.drag){if(!e||!e.chosenLocal||e.text!==e.original)return;this.drag.rects||(this.drag.rects=this.rectsOfText());let r=this.localCharAt(t.clientX,t.clientY,this.drag.rects);if(r===null)return;let i=e.chosenLocal.start,s=e.chosenLocal.end;if(this.drag.side==="left"?i=Math.min(r,s-1):s=Math.max(r+1,i+1),i===e.chosenLocal.start&&s===e.chosenLocal.end)return;e.chosenLocal={start:i,end:s},this.input.setSelectionRange(i,s),this.updateMarkers();return}let n=e&&e.text===e.original?this.markerHitSide(t.clientX,t.clientY):null;this.input.style.cursor=n?"ew-resize":""}};function st(o){for(let t=0;t<o.length;t+=1){let e=o.charCodeAt(t);if(e!==32&&e!==9&&e!==13)return!0}return!1}function ye(o,t){if(!o)return{text:"",map:[]};let e=o.split(`
19
+ `),n=[],r=0;for(let c of e)n.push(r),r+=c.length+1;let i=0;for(;i<e.length&&!st(e[i]);)i+=1;if(i===e.length)return{text:"",map:[]};let s=e.length;for(;s>i&&!st(e[s-1]);)s-=1;let l=[],a=[];for(let c=i;c<s;c+=1){c>i&&(l.push(`
20
+ `),a.push(t[n[c]-1]));let d=e[c];if(!st(d))continue;let h=d.startsWith(" ")?4:0;for(let g=h;g<d.length;g+=1)l.push(d[g]),a.push(t[n[c]+g])}return{text:l.join(""),map:a}}function ve(o){if(o.length!==2)return!1;for(let t=0;t<2;t+=1){let e=o.charCodeAt(t);if(!(e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102))return!1}return!0}function xe(o){let t=[],e=[],n=0;for(;n<o.length;){let r=o[n];if(r==="\\"&&n+1<o.length){let i=o[n+1],s=null,l=2;if(i==="\\"||i==='"'||i==="'"?s=i:i==="r"?s="\r":i==="t"?s=" ":i==="x"&&ve(o.slice(n+2,n+4))&&(s=String.fromCharCode(parseInt(o.slice(n+2,n+4),16)),l=4),s!==null){t.push(s),e.push(n),n+=l;continue}}t.push(r),e.push(n),n+=1}return{text:t.join(""),offsets:e}}function Xt(o){let{text:t,offsets:e}=xe(o);return ye(t,e)}var Ee="http://www.w3.org/2000/svg",Yt=new WeakMap,F=new Set;function L(o,t="",e={},...n){let r=document.createElement(o);return t&&(r.className=t),Object.assign(r,e),r.append(...n),r}function Re(o){let t=document.createElementNS(Ee,"svg");return t.setAttribute("class",o),t}function lt(o){return o.replace(/[ \t\r\n]+$/,"")}var J=class{constructor(t,e,n=0,r=0){this.annotations=[];this.view="rendered";this.selection=null;this.editing=null;this.session=null;this.node=t,this.store=window.transcriptReviewStore;let{text:i,map:s}=Xt(e);this.map=new X(i),this.annotations=this.store.addRegion(this,n,r,i,s),this.sourceFill=L("pre","tmd-diff-fill"),this.sourceInput=L("textarea","tmd-diff-input",{rows:1,spellcheck:!1}),Yt.set(this.sourceInput,this),this.source=L("div","tmd-md-source",{hidden:!0},this.sourceFill,this.sourceInput),this.sourceView=new G(this.sourceFill,this.sourceInput,()=>this.session),this.list=L("div","tmd-rec-list",{hidden:!0}),this.commentInput=L("textarea","",{placeholder:"comment (Ctrl+Enter to submit) . . .",rows:2}),this.comment=L("label","tmd-md-comment",{hidden:!0},this.commentInput),this.popup=L("form","tmd-md-popup",{hidden:!0,noValidate:!0},this.list,this.source,this.comment),this.popup.addEventListener("submit",l=>l.preventDefault()),this.rendered=L("div","tmd-md-rendered"),this.svg=Re("tmd-md-overlay"),this.controls=L("div","tmd-md-controls"),t.style.position="relative",t.replaceChildren(this.rendered,this.popup,this.svg,this.controls),t.dataset.tmdMdView="rendered"}get literal(){return this.map.literal}align(){this.map.align(this.rendered)}clearTransient(){this.controls.querySelectorAll(".tmd-md-trigger").forEach(t=>t.remove())}showRendered(){this.view="rendered",F.delete(this),this.node.dataset.tmdMdView="rendered",this.rendered.hidden=!1,this.popup.hidden=!0,this.selection=null,this.editing=null,this.session=null,this.controls.replaceChildren(),this.svg.replaceChildren();let t=new Set(this.store.visible(this)),e=[];this.annotations.filter(r=>t.has(r)).forEach(r=>{let i=It(this.literal,r),s=this.map.literalToRange(i.start,i.end),l=Dt(this.node,s);l&&e.push({annotation:r,bands:l})});let n=Bt(this.literal,e);for(let{annotation:r,bands:i}of e)r.bands=i,Pt(this.svg,i,r.locked?"tmd-md-box tmd-md-locked":"tmd-md-box"),n.has(r)&&$t(this.controls,r,i,s=>this.openAnnotation(s))}openAnnotation(t){this.editing=t,this.view="list",F.add(this),this.node.dataset.tmdMdView="source",this.popup.hidden=!1,this.selection={start:t.chosen.start,end:t.chosen.end},this.controls.replaceChildren(),this.svg.replaceChildren(),this.session=null,this.renderList(),this.placePopup(this.anchorTopForRange(t.chosen.start,t.chosen.end))}beginEdit(t){let e=t||this.editing;!e||e.locked||(this.editing=e,this.openSource(e.chosen.start,e.chosen.end,this.anchorTopForRange(e.chosen.start,e.chosen.end),"edit"))}renderList(){this.view="list",this.list.hidden=!1,this.source.hidden=!0,this.comment.hidden=!0;let t=this.editing?this.store.history(this,this.editing):null,e=Ut(this.list,t,{focus:this.editing,onOpen:r=>this.openAnnotation(r),onEdit:r=>this.beginEdit(r),onDelete:r=>this.deleteAnnotation(r)}),n=this.session&&this.session.mode==="edit"&&this.session.annotation?this.session.annotation:null;if(n){let r=e.raws.get(n),i=e.comments.get(n);r&&r.replaceChildren(this.source),i&&i.replaceChildren(this.comment),this.source.hidden=!1,this.comment.hidden=!1}}deleteAnnotation(t){if(this.store.remove(this,t),t===this.editing){this.showRendered();return}this.renderList()}deleteEditing(){this.editing&&this.deleteAnnotation(this.editing)}anchorTopForRange(t,e){let n=this.map.literalToRange(t,e);if(!n||typeof n.getClientRects!="function")return 0;let r=Array.from(n.getClientRects());if(!r.length)return 0;let i=this.node.getBoundingClientRect();return r[0].top-i.top}placePopup(t){let e=this.node.getBoundingClientRect(),n=Number.isFinite(t)?t:0,r=this.popup.offsetHeight,i=8,s=n-r-6;e.top+s<i&&(s=n+6),e.top+s+r>window.innerHeight-i&&(s=Math.max(i,window.innerHeight-i-r)-e.top),this.popup.style.top=`${s}px`}openSource(t,e,n,r="edit"){this.view="source",F.add(this),this.node.dataset.tmdMdView="source",this.popup.hidden=!1,this.selection={start:t,end:e},this.controls.replaceChildren(),this.svg.replaceChildren(),this.list.hidden=!0,this.source.isConnected||this.popup.appendChild(this.source),this.comment.isConnected||this.popup.appendChild(this.comment),this.initSession(t,e,r),this.session&&this.session.mode==="edit"&&this.session.annotation?this.renderList():(this.source.hidden=!1,this.comment.hidden=!1),this.placePopup(n),this.session&&this.session.mode==="edit"&&this.sourceInput.focus({preventScroll:!0})}initSession(t,e,n){let r=this.editing,i={start:t,end:e},s=_(this.literal,i.start,i.end),l=r?typeof r.original=="string"?r.original:"":this.literal.slice(s.start,s.end),a={start:i.start-s.start,end:i.end-s.start},c=r&&typeof r.comment=="string"?r.comment:"",d={start:s.start,end:s.start+l.length};this.session=new Y({annotation:r,chosen:i,chosenLocal:a,lineStart:s.start,baseline:d,original:l,text:r&&typeof r.edit=="string"?r.edit:l,committed:c,mode:n||"edit"}),this.sourceInput.value=this.session.text,this.commentInput.value=this.session.body,this.modVisibility(),this.sourceView.render(),this.sourceView.autosize(),this.session.text===this.session.original&&a.start<a.end&&a.end<=this.session.text.length&&this.sourceInput.setSelectionRange(a.start,a.end)}modVisibility(){let t=this.session;if(!t)return;let e=!!(t.annotation&&t.annotation.locked);this.source.hidden=!1,this.comment.hidden=!1,this.commentInput.readOnly=e}isEmptyAnnotation(){let t=this.session;return!t||t.annotation?!1:!t.committed&&this.sourceInput.value===t.original}saveAnnotation(t){let e=this.session;if(!e)return;let n=t?lt(this.sourceInput.value):this.sourceInput.value,r=e.committed||"",i=n!==e.original,s=this.sourceView.currentChosen();if(!s||s.end<=s.start)return;i&&(s=e.baseline);let l=e.annotation;l?(l.chosen=s,l.original=e.original,l.edit=n,l.comment=r,l.modified=i):(r||i)&&(l=new H({selection:this.selection,chosen:s,original:e.original,edit:n,comment:r,modified:i}),e.annotation=l),l&&this.store.save(this,l)}sessionDirty(){let t=this.session;if(!t||this.isEmptyAnnotation())return!1;let e=this.sourceInput.value,n=t.committed||"";return t.annotation?e!==(t.annotation.edit||t.original)||n!==(t.annotation.comment||""):e!==t.original||n!==""}confirmAnnotation(){let t=this.session;t&&(t.committed=lt(this.commentInput.value)),this.saveAnnotation(!0),window.getSelection()?.removeAllRanges(),this.showRendered()}dismissPopup(){this.sessionDirty()&&this.saveAnnotation(!1),window.getSelection()?.removeAllRanges(),this.showRendered()}cancelSession(){window.getSelection()?.removeAllRanges(),this.showRendered()}showTrigger(t,e){this.clearTransient();let n=this.node.getBoundingClientRect(),r=document.createElement("button");r.type="button",r.className="tmd-md-trigger",r.textContent="✎",r.addEventListener("mousedown",g=>g.preventDefault()),r.addEventListener("click",()=>{this.openSource(e.start,e.end,this.anchorTopForRange(e.start,e.end))}),this.controls.appendChild(r);let i=r.offsetWidth,s=r.offsetHeight,l=this.node.clientWidth,a=t.x-n.left,c=t.y-n.top,d=a+10;d+i>l&&(d=a-i-10);let h=c-s-6;r.style.left=`${Math.max(0,d)}px`,r.style.top=`${Math.max(0,h)}px`}trackSelection(){this.sourceView.trackSelection()}wire(){this.node.addEventListener("mousemove",t=>{let e=this.node.getBoundingClientRect(),n=t.clientX-e.left,r=t.clientY-e.top;this.controls.querySelectorAll(".tmd-md-badge").forEach(i=>{let s=i.tmdAnnotation?.bands,l=!!s&&s.some(c=>n>=c.l-2&&n<=c.r+2&&r>=c.t-2&&r<=c.b+2),a=!i.hidden&&Se(i,n,r,e);l||a?rt(i):K(i)})}),this.node.addEventListener("mouseleave",()=>{this.controls.querySelectorAll(".tmd-md-badge").forEach(t=>K(t))}),this.rendered.addEventListener("mousedown",()=>{this.view!=="rendered"?this.dismissPopup():this.clearTransient()}),this.rendered.addEventListener("mouseup",t=>{let e=this.map.selectionToLiteral(this.rendered,window.getSelection());e&&this.showTrigger({x:t.clientX,y:t.clientY},e)}),this.sourceView.wire(),this.sourceInput.addEventListener("keydown",t=>{t.isComposing||!this.session||this.session.mode!=="edit"||(t.ctrlKey||t.metaKey)&&t.key==="Enter"&&(t.preventDefault(),this.confirmAnnotation())}),this.commentInput.addEventListener("input",()=>{this.session&&(this.session.body=this.commentInput.value)}),this.commentInput.addEventListener("keydown",t=>{t.isComposing||!this.session||this.session.mode!=="edit"||((t.ctrlKey||t.metaKey)&&t.key==="Enter"?(t.preventDefault(),this.confirmAnnotation()):t.key==="Enter"&&!t.shiftKey&&!t.altKey&&!t.ctrlKey&&!t.metaKey&&(this.session.committed=lt(this.commentInput.value)))})}};function Se(o,t,e,n){let r=o.getBoundingClientRect();return t>=r.left-n.left&&t<=r.right-n.left&&e>=r.top-n.top&&e<=r.bottom-n.top}document.addEventListener("keydown",o=>{if(o.key==="Escape")for(let t of[...F])t.cancelSession()});document.addEventListener("mousedown",o=>{let t=o.target;for(let e of[...F])e.node.contains(t)||e.dismissPopup()});document.addEventListener("selectionchange",()=>{let o=document.activeElement;o instanceof HTMLElement&&Yt.get(o)?.trackSelection()});function Le(o){let t=new Set;for(let e of(o||"").split(",")){if(!e)continue;let[n,r=n]=e.split("-").map(Number);for(let i=n;i<=r;i+=1)t.add(i)}return t}function at(o){let[t,e]=o.dataset.tmdSpan.split(",");return[Number(t),Number(e)]}function Me(o,t){let[e,n]=at(o),i=t.slice(e,n).split(`
21
+ `),s=(i.find(a=>a.trim())||"").match(/^[ \t]*/)[0],l=Le(o.dataset.tmdStringLines);return i.map((a,c)=>({interior:l.has(c+1),text:l.has(c+1)?a:a.startsWith(s)?a.slice(s.length):a}))}function Gt(o,t){let e=Me(o,t);o.replaceChildren(...e.map(n=>{let r=document.createElement("span");if(r.className="doc-line"+(n.interior?" multiline-string":""),n.interior){let i=document.createElement("span");i.className="hljs-string",i.textContent=n.text,r.appendChild(i)}else r.innerHTML=window.hljs.highlight(n.text,{language:"python"}).value;return r}))}function Te(o,t){let[e,n]=at(o);return t.slice(e,n).replace(/^[\r\n]+|[\r\n]+$/g,"")}function Jt(o,t){let e=Te(o,t);if(!e.replace(/[ \t\r\n\f;]/g,"")){o.remove();return}let n=document.createElement("summary");n.className="script-toggle",n.title="Show or hide script",n.setAttribute("aria-label","Toggle script block"),n.innerHTML='<span aria-hidden="true">&lt;/&gt;</span>';let r=document.createElement("pre");r.className="script-code";let i=document.createElement("code");i.className="language-python",i.innerHTML=window.hljs.highlight(e,{language:"python"}).value,r.appendChild(i),o.replaceChildren(n,r)}function Ae(o){o.querySelectorAll("a[href]").forEach(t=>{try{let e=new URL(t.getAttribute("href"),document.baseURI);(e.protocol==="http:"||e.protocol==="https:")&&(t.target="_blank",t.rel="noopener noreferrer")}catch{}})}function zt(o,t,e){let[n,r]=at(o),i=e.slice(n,r),s=new J(o,i,n,r);return s.rendered.innerHTML=t.render(s.literal),Ae(s.rendered),s.align(),s.wire(),s}function ke(o){return o.toLowerCase().replace(/[^\p{L}\p{N}_\- ]+/gu,"").replace(/[\s\-]+/g,"-").replace(/^-|-$/g,"")}function Qt(o){let t=o.querySelector("main");if(!t)return;let e=Array.from(t.querySelectorAll("figure.transcript-label[id]")),n=new Map(e.map(p=>[p.id,0])),r=[],i=0;t.querySelectorAll("h1,h2,h3,h4,h5,h6,figure.transcript-label[id]").forEach(p=>{if(p.matches("figure.transcript-label")){let M=p.querySelector(":scope > figcaption")?.textContent?.trim();r.push({type:"labels",level:Math.min(i+1,6),text:M||p.id,id:p.id});return}i=Number(p.tagName.slice(1));let w=p.textContent.trim(),v=p.id||ke(w)||`section-${r.length}`;if(n.has(v)){let M=v,I=n.get(M);do I+=1,v=`${M}-${I}`;while(n.has(v));n.set(M,I)}n.set(v,0),p.id=v,r.push({type:"contents",level:i,text:w,id:v})});let s=window.transcriptReviewStore;if(s){let p=0;for(let w of s.records)w.type==="review"&&(r.push({type:"reviews",level:0,text:w.comment||w.edit||"Review",id:`tmd-review-${p}`}),p+=1)}let l=t.parentElement;if(l.querySelector(":scope > .navigate")?.remove(),!r.length){l.className="page";return}let a=["contents","labels","reviews"].filter(p=>r.some(w=>w.type===p)),c=a[0],d=o.createElement("nav");d.className="navigate",d.setAttribute("aria-label","Document outline"),d.dataset.collapsed="false";let h=o.createElement("div");h.className="navigate-tabs";let g={contents:"Contents",labels:"Labels",reviews:"Reviews"};for(let p of a){let w=o.createElement("div");w.className="navigate-tab",w.dataset.tmdType=p,w.dataset.active=String(p===c),w.innerHTML=`<button class="navigate-tab-body" type="button">${g[p]}</button><button class="navigate-tab-toggle" type="button" aria-pressed="${p===c}" aria-label="Add or remove ${g[p]}"><span aria-hidden="true">◉</span></button>`,h.appendChild(w)}let x=o.createElement("ol");x.className="navigate-list",x.dataset.tmdShow=c;let C={contents:p=>`toc-heading toc-l${p.level}`,labels:()=>"toc-label",reviews:()=>"toc-review"};for(let p of r){let w=o.createElement("li");w.className=C[p.type](p),w.dataset.tmdType=p.type,w.hidden=p.type!==c;let v=o.createElement("a");v.href=`#${p.id}`,v.textContent=p.text,w.appendChild(v),x.appendChild(w)}d.append(h,x),l.className="page page--navigate",l.insertBefore(d,t),window.transcriptInitNavigate?.()}function Ce(o){let t=document.createElement("div");t.className="tmd-render-error",t.setAttribute("role","alert"),t.textContent=`Could not load browser renderers: ${o.message}`,document.querySelector("main")?.prepend(t)}(()=>{let o=document.getElementById("transcript-source"),t=document.getElementById("transcript-renderers");if(!o||!t)return;let e,n;try{if(e=JSON.parse(o.textContent),n=JSON.parse(t.textContent),typeof e!="string"||!Array.isArray(n.resources))return}catch{return}window.transcriptReviewStore=(i=>{let s={records:[],hash:""};if(i)try{let l=JSON.parse(i.textContent);l&&Array.isArray(l.records)&&(s=l)}catch{}return new U(e,s.records,s.hash)})(document.getElementById("transcript-reviews"));async function r(){try{await ut(n.resources,n.cache),pt(window.Diff);let i=window.markdownit("commonmark",{html:!1}).enable("table"),s=[];document.querySelectorAll('.doc-md[data-tmd-span], .transcript-report[data-tmd-renderer="markdown"][data-tmd-span]').forEach(l=>s.push(zt(l,i,e))),window.transcriptReviewStore?.buildAnnotations(),s.forEach(l=>l.showRendered()),document.querySelectorAll(".doc-code[data-tmd-span]").forEach(l=>Gt(l,e)),document.querySelectorAll(".script-block[data-tmd-span]").forEach(l=>Jt(l,e)),Qt(document),document.documentElement.dataset.tmdRendered="true",document.dispatchEvent(new CustomEvent("transcript-rendered"))}catch(i){Ce(i instanceof Error?i:new Error(String(i)))}}r()})();})();
@@ -0,0 +1,72 @@
1
+ """Embed the archive in the exported page and read it back out.
2
+
3
+ The page carries the archive *without* its trailing review block as a JSON
4
+ island, plus the review records in a second island. The browser runtime reads
5
+ the first for the report content and the second for annotations, so the page
6
+ stays self-contained and the archive (block re-rendered from the records) can
7
+ be recovered without executing the document.
8
+ """
9
+
10
+ import json
11
+ import re
12
+
13
+ _ISLAND = re.compile(
14
+ r'<script type="application/json" id="transcript-source">(?P<body>.*?)</script>',
15
+ re.DOTALL,
16
+ )
17
+ _REVIEWS = re.compile(
18
+ r'<script id="transcript-reviews" type="application/json">(?P<body>.*?)</script>',
19
+ re.DOTALL,
20
+ )
21
+
22
+
23
+ def source_island(source: str):
24
+ """Return the ``transcript-source`` island embedding *source*."""
25
+ encoded = json.dumps(source, ensure_ascii=False).replace("<", "\\u003c")
26
+ return f'<script type="application/json" id="transcript-source">{encoded}</script>'
27
+
28
+
29
+ def _reviews_island(page: str):
30
+ """Return the ``transcript-reviews`` records, or ``None``."""
31
+ from ..review._records import Record
32
+
33
+ match = _REVIEWS.search(page)
34
+ if match is None:
35
+ return None
36
+ payload = json.loads(match.group("body"))
37
+ if not isinstance(payload, dict) or not isinstance(payload.get("records"), list):
38
+ return None
39
+ return [Record.from_dict(item) for item in payload["records"]]
40
+
41
+
42
+ def extract_parts(page: str):
43
+ """Return ``(body, records)`` for an exported page.
44
+
45
+ *body* is the embedded archive *without* its review block; *records* are the
46
+ ``transcript-reviews`` records (or ``None`` when the page has no island).
47
+ """
48
+ match = _ISLAND.search(page)
49
+ if match is None:
50
+ raise ValueError("the HTML page has no transcript-source island")
51
+ payload = json.loads(match.group("body"))
52
+ if not isinstance(payload, str):
53
+ raise ValueError("the transcript-source island must be a JSON string")
54
+ return payload, _reviews_island(page)
55
+
56
+
57
+ def extract(page: str):
58
+ """Return the archive embedded in an exported page.
59
+
60
+ Raises ``ValueError`` when the page carries no island or the island is not
61
+ the expected JSON string. The review records kept in the ``reviews`` island
62
+ are rendered back into the archive's trailing review block, stamped with the
63
+ body hash.
64
+ """
65
+ from ..review._block import render_block
66
+ from ..tmd import body_hash
67
+
68
+ body, records = extract_parts(page)
69
+ if not records:
70
+ return body
71
+ body = body.rstrip("\n") + "\n"
72
+ return body + "\n" + render_block(records, hash=body_hash(body)) + "\n"