@aiquants/markdown-explorer 0.34.0 → 0.36.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +608 -0
- package/README.md +121 -41
- package/dist/EditSurface-B70iRFkG.cjs +6 -0
- package/dist/EditSurface-BCFJRyIM.js +990 -0
- package/dist/ExplorerSplit-BNrHrIus.cjs +2 -0
- package/dist/ExplorerSplit-Bgccz2nm.js +1589 -0
- package/dist/MultiLayout-Bo9LAXiY.cjs +1 -0
- package/dist/{MultiLayout-kcZyVnvK.js → MultiLayout-Dy5TIC2t.js} +249 -248
- package/dist/{NativeScrollBar-pUbA4Zq3.cjs → NativeScrollBar-Bj-LKej0.cjs} +1 -1
- package/dist/{NativeScrollBar-UNed10Na.js → NativeScrollBar-DpZMYhmf.js} +2 -2
- package/dist/TreeLayout-DsSKW_Qj.js +103 -0
- package/dist/TreeLayout-T8sc_wg7.cjs +1 -0
- package/dist/client/MarkdownExplorer.d.cts +14 -1
- package/dist/client/MarkdownExplorer.d.ts +14 -1
- package/dist/client/edit/lineEndings.d.cts +4 -0
- package/dist/client/edit/lineEndings.d.ts +4 -0
- package/dist/client/hostContract.d.cts +67 -0
- package/dist/client/hostContract.d.ts +67 -0
- package/dist/core/config.d.cts +13 -0
- package/dist/core/config.d.ts +13 -0
- package/dist/core/contracts.d.cts +31 -4
- package/dist/core/contracts.d.ts +31 -4
- package/dist/core/dataRoute.d.cts +5 -1
- package/dist/core/dataRoute.d.ts +5 -1
- package/dist/core/documentId.d.cts +6 -0
- package/dist/core/documentId.d.ts +6 -0
- package/dist/core/draftAnswer.d.cts +23 -0
- package/dist/core/draftAnswer.d.ts +23 -0
- package/dist/core/labels.d.cts +78 -0
- package/dist/core/labels.d.ts +78 -0
- package/dist/core/location.d.cts +22 -2
- package/dist/core/location.d.ts +22 -2
- package/dist/core/ownUrls.d.cts +15 -0
- package/dist/core/ownUrls.d.ts +15 -0
- package/dist/core/treeSettings.d.cts +3 -2
- package/dist/core/treeSettings.d.ts +3 -2
- package/dist/core/viewSettings.d.cts +3 -1
- package/dist/core/viewSettings.d.ts +3 -1
- package/dist/describeValue-CLlVRO8d.js +17 -0
- package/dist/describeValue-Ccvhbt36.cjs +1 -0
- package/dist/explorerCore-B3RGmMG6.js +1083 -0
- package/dist/explorerCore-CUkyKtm8.cjs +1 -0
- package/dist/index-D0l_BJqb.js +5980 -0
- package/dist/index-lpL7GltU.cjs +18 -0
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +8 -4
- package/dist/index.d.ts +8 -4
- package/dist/index.js +53 -43
- package/dist/licenses/@heroicons/react/LICENSE +21 -0
- package/dist/licenses/entities/LICENSE +11 -0
- package/dist/licenses/parse5/LICENSE +19 -0
- package/dist/location-Dh6K-y7w.js +761 -0
- package/dist/location-DrOP6t1F.cjs +1 -0
- package/dist/lru-DC8GBmkX.js +39 -0
- package/dist/lru-SGmUyBQU.cjs +1 -0
- package/dist/{merge-C1MWvhCS.js → merge-BwcqBd4c.js} +1 -1
- package/dist/{merge-BziXxZkE.cjs → merge-Dckw7r9T.cjs} +1 -1
- package/dist/nestingGuardWorker.js +5511 -0
- package/dist/ownUrls-BTPGNhBt.cjs +1 -0
- package/dist/ownUrls-DD0cSCsF.js +409 -0
- package/dist/sanitizeJob-BYqzjFJC.js +21 -0
- package/dist/sanitizeJob-CudE1RUP.cjs +1 -0
- package/dist/sanitizePolicy-C-ehd0J_.cjs +2 -0
- package/dist/sanitizePolicy-DAPnUUVm.js +139 -0
- package/dist/sanitizeWorker.cjs +1 -1
- package/dist/sanitizeWorker.js +134 -139
- package/dist/sanitizerService-B8v4ap9t.js +240 -0
- package/dist/sanitizerService-DomN7lwC.cjs +1 -0
- package/dist/server/assetResponse.d.cts +60 -0
- package/dist/server/assetResponse.d.ts +60 -0
- package/dist/server/browser/browserPlatform.d.cts +12 -0
- package/dist/server/browser/browserPlatform.d.ts +12 -0
- package/dist/server/createMarkdownExplorer.d.cts +0 -10
- package/dist/server/createMarkdownExplorer.d.ts +0 -10
- package/dist/server/errors.d.cts +1 -1
- package/dist/server/errors.d.ts +1 -1
- package/dist/server/explorerCore.d.cts +12 -0
- package/dist/server/explorerCore.d.ts +12 -0
- package/dist/server/fileSystemSource.d.cts +1 -0
- package/dist/server/fileSystemSource.d.ts +1 -0
- package/dist/server/inProcessFetch.d.cts +5 -0
- package/dist/server/inProcessFetch.d.ts +5 -0
- package/dist/server/platform.d.cts +18 -0
- package/dist/server/platform.d.ts +18 -0
- package/dist/server/ports.d.cts +55 -5
- package/dist/server/ports.d.ts +55 -5
- package/dist/server/sanitizeProtocol.d.cts +3 -0
- package/dist/server/sanitizeProtocol.d.ts +3 -0
- package/dist/server/sanitizer.d.cts +5 -40
- package/dist/server/sanitizer.d.ts +5 -40
- package/dist/server/sanitizerOptions.d.cts +24 -0
- package/dist/server/sanitizerOptions.d.ts +24 -0
- package/dist/server/sanitizerService.d.cts +41 -0
- package/dist/server/sanitizerService.d.ts +41 -0
- package/dist/server/{workerPool.d.cts → workerJobs.d.cts} +0 -16
- package/dist/server/{workerPool.d.ts → workerJobs.d.ts} +0 -16
- package/dist/server.cjs +1 -1
- package/dist/server.d.cts +3 -1
- package/dist/server.d.ts +3 -1
- package/dist/server.js +270 -1343
- package/dist/serverBrowser.cjs +1 -0
- package/dist/serverBrowser.d.cts +1 -0
- package/dist/serverBrowser.d.ts +1 -0
- package/dist/serverBrowser.js +120 -0
- package/dist/serverCore.cjs +1 -0
- package/dist/serverCore.d.cts +14 -0
- package/dist/serverCore.d.ts +14 -0
- package/dist/serverCore.js +46 -0
- package/dist/storage-BpYsprog.cjs +1 -0
- package/dist/{storage-CmGHg7OA.js → storage-D1uSw-xj.js} +19 -18
- package/dist/storage.cjs +1 -1
- package/dist/storage.js +1 -1
- package/dist/styles/markdown-explorer.css +1 -1
- package/dist/{tapScrollCircle-DigcJCsu.cjs → tapScrollCircle-DyLInGck.cjs} +1 -1
- package/dist/{tapScrollCircle-D_BpaLwY.js → tapScrollCircle-smKLgRa2.js} +1 -1
- package/dist/testing.cjs +1 -0
- package/dist/testing.d.cts +11 -0
- package/dist/testing.d.ts +11 -0
- package/dist/testing.js +82 -0
- package/dist/useSplitPersistence-BUa_KMsV.cjs +1 -0
- package/dist/useSplitPersistence-pnb21dsr.js +44 -0
- package/docs/behavior/dom-hooks.md +5 -1
- package/docs/behavior/hosting.md +123 -0
- package/docs/behavior/layout.md +5 -3
- package/docs/behavior/localization.md +25 -8
- package/docs/behavior/security.md +55 -15
- package/docs/behavior/url-contract.md +30 -3
- package/package.json +48 -10
- package/dist/EditSurface-CF82jZQg.cjs +0 -6
- package/dist/EditSurface-CqHk2R3k.js +0 -982
- package/dist/ExplorerSplit-D325YGEf.cjs +0 -1
- package/dist/ExplorerSplit-DGH9bckm.js +0 -1500
- package/dist/MultiLayout-CzR7yJ0m.cjs +0 -1
- package/dist/TreeLayout-BnIU87HX.js +0 -96
- package/dist/TreeLayout-DtvIpuOe.cjs +0 -1
- package/dist/dataRoute-D6KiSHIc.js +0 -298
- package/dist/dataRoute-DwYtgyt6.cjs +0 -1
- package/dist/index-BDCbvHDs.cjs +0 -15
- package/dist/index-DR31S_-4.js +0 -5012
- package/dist/location-C44b9H1S.js +0 -676
- package/dist/location-hGLhCCg4.cjs +0 -1
- package/dist/sanitizePolicy-CwvyPpp5.js +0 -98
- package/dist/sanitizePolicy-T5T-3vV5.cjs +0 -1
- package/dist/storage-DM0EvkVf.cjs +0 -1
- package/dist/useSplitPersistence-DCeYbJMx.js +0 -38
- package/dist/useSplitPersistence-QGcvyMAa.cjs +0 -1
|
@@ -10,6 +10,7 @@ The explorer renders documents that the reader did not write, from storage the r
|
|
|
10
10
|
- Deny rules (`deny`, default `DEFAULT_DENIED_PATH_SEGMENTS`) hide matching entries from every listing — by entry name and by path, so a denied folder is pruned with everything under it — and refuse every document or children request for a matching path with a `forbidden` failure before any source is called.
|
|
11
11
|
- A rule is matched against each path segment (or entry name) at every percent-decoding level up to three decodes, against each level whole and against its parts split again on `/` or `\` (a storage may read either character as part of one name, as a Linux file name, a Drive name or a GCS object name does, or as a separator), and after NFKC normalization and full case folding (upper-casing then lower-casing, which folds `ſ` to `s` and `ı` to `i`). Decoding is lenient: a malformed escape stays as written while the valid ones around it are decoded.
|
|
12
12
|
`%2Eenv`, `%252Eenv`, `.%65nv`, `docs%5C.env`, `SECRETS` and `ſecrets` are all denied like `.env` and `secrets`, whatever the storage backend decodes or folds before opening the path.
|
|
13
|
+
A segment that one more lenient decode would still change after those three is denied whatever the patterns; rules without a pattern (`deny: []`) deny nothing.
|
|
13
14
|
- Pattern syntax: a pattern matches one whole segment; `*` matches any run of characters inside it. `deny: false` turns the rules off; a custom array replaces the defaults (spread `DEFAULT_DENIED_PATH_SEGMENTS` to extend them).
|
|
14
15
|
- The defaults cover environment files (`.env*` — every name starting with `.env`, for example `.env~`, `.env-old`, `.envs/`, and also `.envelope.md` — and `*.env` with the names its backups and copies take:
|
|
15
16
|
`*.env.*`, `*.env~*`, `*.env-*`, `*.env_*` and `*.env#*`, for example `prod.env.bak`, `prod.env.production`, `prod.env.1`, `prod.env~`, `prod.env-old`, `prod.env_backup` and `#prod.env#`; rules have no exceptions, so a document named like `deploy.env.md` is denied too, while names in which `.env` is followed by a letter or digit, such as `prod.environment.md`, or has no dot before it, such as `environment.md` and `my-env.md`, are not),
|
|
@@ -17,7 +18,8 @@ The explorer renders documents that the reader did not write, from storage the r
|
|
|
17
18
|
keys and keystores (`id_rsa*`, `id_dsa*`, `id_ecdsa*`, `id_ed25519*`, `*.pem`, `*.key`, `*.p8`, `*.p12`, `*.pfx`, `*.ppk`, `*.jks`, `*.keystore`, `*.kdbx`), credential files (`*credentials*.json`, `service-account*.json`), Terraform state and variables (`*.tfstate`, `*.tfstate.*`, `*.tfvars`, `*.tfvars.json`) and shell histories (`.*_history`, `fish_history`).
|
|
18
19
|
- `createFileSystemSource` additionally checks lexical containment before any filesystem call and again after resolving the real path, refuses symbolic links, and never follows a path outside its root. It opens a file without following a link (where the platform has `O_NOFOLLOW`) and reads it only when the opened file is the one the checks saw (the same device and inode; a document read refuses another file as `forbidden`).
|
|
19
20
|
Its `asset` port also requires the size and modification time the checks saw, answers `not-found` when the file is another one or has changed since, and streams a whole file no further than the size the checks saw.
|
|
20
|
-
The walk leaves out every name it cannot carry — not in NFC, with a colon, ending in a dot or a space, holding a control character or a backslash, too long, a symbolic link or a special file — and every subdirectory it cannot read (a permission error, or one that vanished or became a file during the walk), and reports each once per path through `reportSkipped` (a `console.warn` by default); only an unreadable root fails the tree.
|
|
21
|
+
The walk leaves out every name it cannot carry — not in NFC, with a colon, ending in a dot or a space, holding a control character or a backslash, too long, a symbolic link or a special file — and every subdirectory it cannot read (a permission error, or one that vanished or became a file during the walk), and reports each once per path through `reportSkipped` (a `console.warn` by default); only an unreadable root fails the tree.
|
|
22
|
+
Only files with a known text extension or name are previewed as text; any other file that is not a Markdown document, an image, a medium or a table file is a `file` document, offered for download.
|
|
21
23
|
|
|
22
24
|
## Source boundaries
|
|
23
25
|
|
|
@@ -40,11 +42,17 @@ The explorer renders documents that the reader did not write, from storage the r
|
|
|
40
42
|
|
|
41
43
|
## HTML
|
|
42
44
|
|
|
43
|
-
Markdown HTML returned by a source is sanitized
|
|
45
|
+
Markdown HTML returned by a source is sanitized by the explorer's core with DOMPurify before it reaches the page loader's stream or the data route — on the Node entry in worker threads, on the browser runtime (`./server/browser`) on the page's main thread after a guard in a Web Worker (see below) — so the views never receive markup the allow-list rejects:
|
|
44
46
|
|
|
45
47
|
- removed elements: `script`, `style`, `noscript`, `template`, `form`, `button`, `textarea`, `select`, `option`, `object`, `embed`, `base`, `meta`, `link`, `frame`, `frameset`; `input` survives only as a disabled checkbox (task lists);
|
|
46
48
|
- removed attributes: every event handler (`on*`), `srcdoc`, `formaction`; `style` keeps only `text-align`;
|
|
47
49
|
- URLs keep only the `http:`, `https:`, `mailto:` and `tel:` schemes and relative references, and `data:` URLs are removed from every element;
|
|
50
|
+
- a URL of the app itself stays only where its use allows. The app's own are relative and path-absolute URLs, and absolute ones whose origin `config.appOrigins` lists or `config.mediaDataPath` names, or whose scheme is that of a listed origin with a scheme that is not special (such as `wails:`); any other absolute URL follows the scheme rule above alone.
|
|
51
|
+
A resource the page fetches (a `src`, `poster` or `background`, a `srcset` candidate, the `href` of SVG's `image`) stays only under `dataPath`; a link's `href` only under `basePath` or `dataPath`; the `src` of a `video`, `audio` or `source` also under `config.mediaDataPath`, as an absolute URL; and any other `href` inside SVG, which may name an element of the same document, under `dataPath` or as a fragment.
|
|
52
|
+
A path stays when, normalized as the URL parser normalizes it, it equals an allowed path or continues one after a `/` (the query and the fragment are not looked at). Of the relative URLs, a link stays without a `.` or `..` segment, a link the converter marked as one to a document always stays, and no resource stays.
|
|
53
|
+
A URL holding a backslash is removed, a scheme-relative one (`//host…`) is read under every scheme the page may have and stays only when every reading does, and a `srcset` loses the whole attribute when any of its candidates does not stay. Only the attribute is removed, never the element;
|
|
54
|
+
- the presentation attributes CSS may read a URL from (`clip-path`, `color-profile`, `cursor`, `fill`, `filter`, `marker-start`, `marker-mid`, `marker-end`, `mask`, `stroke`) keep only a value that refers to the same document alone: a `url()` of a fragment, no image function (`image-set()`, `image()`, `src()`, `element()`, `cross-fade()`, prefixed forms included) and no backslash;
|
|
55
|
+
- the `preload` of a `video` or an `audio` is `none` when it is written `none` (in any ASCII case) and `metadata` otherwise (missing, empty, `auto` or an unknown value);
|
|
48
56
|
- `iframe` survives only with an `https:` source without a user name, a password or an explicit port whose host is listed exactly in `config.iframeHosts` (a longer host such as `www.youtube.com.example.net`, or a protocol-relative source, is removed), judged on the `src` trimmed as DOMPurify trims it; this gate is `allowedFrameUrlOf` of `@aiquants/markdown/embeds`, the same function the viewer applies, and the viewer also never renders an iframe of the page's own origin;
|
|
49
57
|
- `allow`, `allowfullscreen`, `frameborder` and `referrerpolicy` survive only on iframes: `referrerpolicy` only as `no-referrer`, `origin`, `same-origin`, `strict-origin` or `strict-origin-when-cross-origin` (`EMBED_FRAME_REFERRER_POLICIES`), and `allow` reduced to `autoplay`, `clipboard-write`, `encrypted-media`, `fullscreen`, `picture-in-picture` and `web-share`, each without its allowlist (`reduceFrameFeatures`);
|
|
50
58
|
- `target` survives only on `a` and `area`, and a link with any `target` other than `_self` gets `rel="noopener noreferrer"`;
|
|
@@ -71,9 +79,10 @@ Every document the explorer shows is rendered by the viewer, on the server and i
|
|
|
71
79
|
The sanitized `htmlContent` of the page data and of the data route's answers still carries the classes and ids DOMPurify kept; a host that renders it outside the explorer reduces them itself (see [What the host must do](#what-the-host-must-do)).
|
|
72
80
|
|
|
73
81
|
A markdown document that lists more than 10,000 headings (`EXPLORER_MAX_HEADINGS`) is refused as `too-large` before it is sanitized: every listed heading travels with the document — copied by the server, sent in the data response, kept in the browser's document cache and rendered as an entry of the viewer's table of contents — and a parser can list headings its HTML never renders (`#` lines inside a math block), so none of the HTML's limits bounds the list. A host's own cache of parse results can rely on the same bound.
|
|
74
|
-
|
|
82
|
+
On the Node entry (`./server`), sanitizing never runs on the request thread. HTML larger than `sanitizer.maxHtmlBytes` (4 MiB by default) is refused as `too-large` at once; the rest goes to a pool of worker threads (`sanitizer.workers`, 2 by default), shared by every explorer of the process with the same pool settings, with a per-document deadline (`sanitizer.deadlineMs`, 30 s by default): a document that misses it is `too-large`, and its worker is replaced.
|
|
75
83
|
In the worker the nesting limit is enforced while the HTML is parsed, by the parser and in the mode DOMPurify's jsdom uses (parse5, the input as a whole document, scripting disabled), before DOMPurify runs and within the document's deadline.
|
|
76
|
-
The parse stops, and the document is `too-large` without being sanitized, as soon as an element is placed deeper than
|
|
84
|
+
The parse stops, and the document is `too-large` without being sanitized, as soon as an element is placed deeper than 256 levels (the children of `body` are at depth 1 and a `template`'s contents one level below it), or as soon as the parser has created more elements than the HTML has characters plus `html`, `head` and `body` (only formatting elements the parser reopens over and over can do that; an ordinary document stays far below).
|
|
85
|
+
The depth limit keeps a margin below the depth at which browsers' HTML parsers stop nesting elements (about 510 levels, by engine and by whether a document or a fragment is parsed), so no engine moves an element the sanitizer accepted to another parent for its depth, also inside a page that embeds the HTML.
|
|
77
86
|
Before DOMPurify runs, the guard also counts every element, attribute and comment the parser creates and refuses the document (`too-large`) once the count passes (`sanitizer.workerHeapMb` − 64 MiB − `sanitizer.maxHtmlBytes` × 32 bytes) ÷ 4 KiB, which is 81,920 nodes by default, or once it has seen more than 4,096 comments wherever they sit. jsdom inserts each comment the parser attaches to the document itself (before `<html>` or after `</html>`) in time that grows with those already there (4,000 took 0.37 s and 8,000 took 1.4 s in the worker, while 8,000 comments inside the body took 0.14 s),
|
|
78
87
|
so the cap keeps that worst case near 0.4 s. The constants are measured: the worker needs about 48 MiB of its own, a parsed node costs at most about 3.4 KB at the sanitizer's peak and a byte of HTML at most about 31 bytes, so a document the guard accepts fits in the worker's heap. The budget does not depend on the worker's heap limit and holds even where a process-wide `--max-old-space-size` overrides it.
|
|
79
88
|
Before parsing, a linear scan follows every `<` or `</` followed by a letter through the tokenizer's tag states, quotes included, and refuses the document once a tag could hold more than 1,024 attributes, duplicates included; it also reads text the tokenizer would treat as text, so it may refuse more, never less.
|
|
@@ -81,7 +90,7 @@ While parsing, `html` and `body` may receive at most 1,024 attributes through re
|
|
|
81
90
|
The guard also adds up the name and value characters of every attribute the parser creates, including the copies it gives a formatting element it reopens or the adoption agency recreates, and refuses the document once they exceed `sanitizer.maxHtmlBytes` (a document whose elements each appear once never does): Without the budget, 1 MiB of copied `title` makes the worker write 210 million characters; the budget refuses it in about 0.1 s.
|
|
82
91
|
Sanitized HTML longer than 4 × `sanitizer.maxHtmlBytes` UTF-16 code units (16,777,216 by default; ordinary HTML measured at most 2.05 characters per byte) is a cached `too-large`: the worker never posts it and the service refuses it should it arrive, so neither the cache (where the longest outcome weighs 32 MiB of the default 64 MiB) nor a caller ever holds more.
|
|
83
92
|
Every sanitizer worker starts with Node's `resourceLimits`: `workerHeapMb` MiB of old generation (512 by default) and 32 MiB of young generation. A worker whose heap runs out is ended with `ERR_WORKER_OUT_OF_MEMORY`, and its document is answered `too-large` and cached. The young generation is kept small on purpose: with Node's default for a worker (192 MiB), a worker at its limit could abort the whole process instead of ending alone, because one scavenge can promote more than the 16 MiB of leeway Node gives it.
|
|
84
|
-
An element counts at the depth where the parser first places it, so when the parser later moves misnested markup to a shallower place (the adoption agency for misnested formatting tags, a `frameset` replacing `body`), a document whose finished tree is at most
|
|
93
|
+
An element counts at the depth where the parser first places it, so when the parser later moves misnested markup to a shallower place (the adoption agency for misnested formatting tags, a `frameset` replacing `body`), a document whose finished tree is at most 256 levels deep can still be refused; a deeper one is never accepted. DOMPurify's own walk also stops at the first element deeper than 256 levels.
|
|
85
94
|
Each request names its reader's scope. The pool admits at most `sanitizer.jobsPerScope` documents per reader running or waiting and `sanitizer.maxQueuedJobs` waiting in all; a document beyond either is `failed`, logged without the principal and not remembered, so a later request tries again.
|
|
86
95
|
A page sends the document of every panel to the sanitizer at once for one reader, so the admission defaults follow the multi view: `jobsPerScope` defaults to `multiView.maxPanels` + max(1, `workers` − 1) + 3 — the panels, the previous page's documents still running after a reload (a running job is not stopped when its requests leave, and one reader runs at most max(1, `workers` − 1) at once), the two intent prefetches and one spare; 16 with the default 12 panels and two workers. `maxQueuedJobs` defaults to four times `jobsPerScope`, also when it is set.
|
|
87
96
|
Neither may be set below `multiView.maxPanels` (a `RangeError` naming both at startup). All anonymous readers share one scope and therefore one admission budget.
|
|
@@ -91,6 +100,11 @@ Every outcome that describes the HTML (a refusal for nesting, the node budget, t
|
|
|
91
100
|
A worker that fails before then (it cannot be started, is not ready within the deadline, or fails or exits while starting) never received the document: the document is answered `failed`, the cause is logged, and the outcome is not cached. A failure while a worker holds a document it was sent, such as an uncaught error or an unexpected exit, is that document's crash and stays a cached `failed`, whatever order Node delivers the worker's error and its messages in. Running out of heap and missing the deadline stay a cached `too-large`.
|
|
92
101
|
Creating the explorer fails when the worker file is missing next to the server module; where DOMPurify cannot run, it refuses instead of returning its input unchanged, and the document fails.
|
|
93
102
|
|
|
103
|
+
The browser runtime (`createBrowserExplorerPlatform` of `./server/browser`) keeps the same rules with one worker. The nesting guard above (the same parser, depth, node, comment and attribute budgets) runs in a module Web Worker started from the host's `nestingGuardWorkerUrl`, so its cost never blocks the page and HTML it stops never reaches the DOM; DOMPurify then sanitizes on the page's main thread, over the window the host gives, one document at a time and after yielding the main thread once.
|
|
104
|
+
Its limits are those above but for the worker fields: `sanitizer.workers` and `sanitizer.workerHeapMb` are refused (a `TypeError` when the explorer is created), the node budget is the one of Node's default worker heap (512 MiB, so 81,920 nodes with the default 4 MiB of HTML), and `sanitizer.maxHtmlBytes` may be at most 14,155,776, the most that leaves the budget 4,096 nodes (a `RangeError` above it).
|
|
105
|
+
The admission defaults are those of one worker (`jobsPerScope` defaults to `multiView.maxPanels` + 4, 16 with the default 12 panels). The deadline spans both steps: a guard that overruns it is ended and replaced, and DOMPurify, which keeps the main thread until it finishes, has its output discarded when it finishes after the deadline, so the document is `too-large` either way.
|
|
106
|
+
A guard worker that fails before it is ready leaves the document `failed` and not remembered, and one that fails while it holds a document makes that document a remembered `failed`; nothing here ends for a heap, since the guard's budgets bound what reaches DOMPurify.
|
|
107
|
+
|
|
94
108
|
Fixed or absolutely positioned markup in a document cannot cover the host or the explorer: the document region is its containing block and clips its painting (in a multi-view panel, the panel's frame clips it). Such markup can still cover the rest of its own document.
|
|
95
109
|
|
|
96
110
|
The rest of a source's output is validated before it is sent: image and media URLs must be `http:`, `https:` or relative, media types `video`, `audio` or `pdf`, notice links `http:`, `https:`, `mailto:` or relative, heading depths 1–6, and failure codes 1–64 lowercase letters, digits or hyphens. A violation is logged and the reader sees a generic failure (an empty notice list for notices).
|
|
@@ -102,16 +116,16 @@ In a tree or children listing, an entry with an empty name, or with a path the b
|
|
|
102
116
|
- The page loader's responses carry `Cache-Control: private, no-store` through the exported `headers`, to both the HTML document and the single-fetch data.
|
|
103
117
|
- The data route answers a React Router single-fetch request (`<dataPath>/<operation>.data`: its own URL path ends in `.data`, which React Router strips from the route's `url` argument and `params` but not from `request.url`) with a `not-found` failure (404) before authenticating or calling a source. React Router would run the route for it, read the whole response into memory and keep none of the headers above but `Set-Cookie`.
|
|
104
118
|
- Status codes: 200 for a tree, children, ancestors, reveal, document, text, refresh or editor (`edit`, `save`, `preview`, `revisions`, `revision`) answer (a refresh answers the reloaded tree, as a tree request does, failures included), 400 for a missing or malformed parameter or draft,
|
|
105
|
-
401 when the reader is signed out, 403 when the reader may not use the explorer (or a refresh, a document request marked as one's, a save
|
|
119
|
+
401 when the reader is signed out, 403 when the reader may not use the explorer (or a refresh, a document request marked as one's, a save, a preview or an ID's issue lacks its proof), 404 for an unknown operation or source for a children request to a source without `children()`, for an ancestors request to a source without `ancestors()`, for the editor's operations without `edit` ports and for the ID operations without `documentIds` ports, 405 (with `Allow`) for a wrong method, 413 for a draft longer than `editMaxBytes`.
|
|
106
120
|
When `authenticate`, `principalKey` or the route itself throws, the answer is the failure the exception maps to, with that failure's status: an `ExplorerError` keeps its reason (`too-large` is 413; `not-configured`, `unsupported` and `failed` are 500; the other reasons take the statuses above), and any other exception is logged and answered `failed` with 500.
|
|
107
|
-
A document or folder that cannot be shown — missing, denied, too large — is answered with status 200 and a failure in the JSON, so one inaccessible document does not break the multi-panel view.
|
|
121
|
+
A document or folder that cannot be shown — missing, denied, too large — is answered with status 200 and a failure in the JSON, so one inaccessible document does not break the multi-panel view. The ID operations (`issue-id`, `resolve-id`) answer a failure with its own status instead (see [Document IDs](#document-ids)).
|
|
108
122
|
- The tree refresh (`POST {dataPath}/refresh`) requires the custom request header `X-Markdown-Explorer: refresh` and passes the shared cross-origin check of server routes (`crossOriginRefusal` of `@aiquants/request-isolation`, serving no navigation from another origin).
|
|
109
123
|
That check refuses a request whose `Sec-Fetch-Site` is present and neither `same-origin` nor `none`, and a request without Fetch Metadata whose `Origin` is present and does not name the request's host (another host or port, `null`, or a value that is not a URL), so neither a cross-site form nor a page of a sibling subdomain can trigger it.
|
|
110
124
|
It reloads the tree from the source (the source receives `refresh: true`) and answers a tree whose walk began after the refresh arrived; refreshes arriving while a walk runs share one trailing walk, so repeated refreshes never run more than one walk of a tree at a time.
|
|
111
125
|
Once the reload settled and unless the request went away, `onTreeRefreshed` receives the tree's cache key, which a multi-process host relays to its other processes' `forgetTree`; the response does not wait for a promise it returns, and a throw or that promise's rejection is logged (operation `refresh`).
|
|
112
126
|
- A document GET carrying `X-Markdown-Explorer: refresh` marks a request a refresh triggered: the host's `document` (and the admitting source's `confirm`) receive `refresh: true` and skip their caches. Such a request must carry the header's exact value and pass the same cross-origin check as the refresh itself (as a `GET`, a request without Fetch Metadata passes whatever its `Origin`, since another origin's page cannot add the header without a CORS preflight), or it is answered 403 before any host call, so a cross-site page cannot make the host re-parse documents.
|
|
113
127
|
- The `text` operation (`GET {dataPath}/text?path=`) answers JSON like a document request: GET and HEAD only; a missing, repeated or unacceptable `path` is 400; signed out 401 and forbidden 403.
|
|
114
|
-
Everything else is status 200:
|
|
128
|
+
Everything else is status 200: the file read as text (`kind: "text"` with `name`, `text`, `truncated` and the file's asset `url` with its version, but no `lang`, since the operation reads any file a view shows as written), or a failure document — `forbidden` for a denied or unadmitted path, `unsupported` for a file whose decoded text holds NUL (U+0000;
|
|
115
129
|
the zero bytes of a UTF-16 file with a byte order mark are read as part of its characters, so only a U+0000 of its own is NUL, while a UTF-16 file without the mark is read as UTF-8 and its zero bytes are), the reason of an `ExplorerError` the host's `asset` port throws, and otherwise `failed`, logged with the operation `text` (a stream that ends before the size the port reported included).
|
|
116
130
|
It carries no refresh mark: the host's `asset` port receives `refresh: false`. The file is opened as the asset operation opens it — the first `textMaxBytes` bytes as a range when the port reports a longer size, the whole file otherwise, an empty file never — and the stream is cancelled once enough was read.
|
|
117
131
|
- The `asset` operation answers bytes instead of JSON (its failures stay JSON failures with the statuses above). GET and HEAD only; a request whose own URL path ends in `.data` is 404 before authentication; signed out 401 and forbidden 403 with no redirect; a missing, repeated or unacceptable `path` 400; a denied or unadmitted path 403.
|
|
@@ -137,7 +151,7 @@ In a tree or children listing, an entry with an empty name, or with a path the b
|
|
|
137
151
|
- `save` and `preview` are `POST` only, and need `X-Markdown-Explorer: edit` and the shared cross-origin check of a refresh (`crossOriginRefusal`), checked before the body is read (403). The body must be `text/markdown` with no charset or `utf-8` (else 400); a declared or actual length over `editMaxBytes` is refused (413) and the reading stops at the first byte past the limit; invalid UTF-8 and NUL are refused (400). All of this happens before any port is called.
|
|
138
152
|
- `base` (a save's version) and `revision` are tokens of 1 to 1024 characters (400 otherwise). A version, a revision id and a grant are copied from the ports' answers only in their contract's shape: a grant's `href` must be root-relative, an external editor's `href` an absolute `https:` URL; sources, conflict texts and revisions longer than `editMaxBytes`, and malformed revisions, are logged and answered `failed`.
|
|
139
153
|
- The preview's HTML goes through the same sanitizer, limits and reader share as a document's. The sanitizer keeps a converter's source lines only as `data-source-lines="<first>-<last>"` (positive line numbers, the first not after the last).
|
|
140
|
-
- With a draft converter (`draftConverter`), a draft is rendered in the browser and sanitized there before it is shown, by the same allow-list rules (`core/sanitizePolicy`, on a DOMPurify instance of the preview's own from `isomorphic-dompurify`'s browser build, so no hook another script adds to the page's shared DOMPurify takes part) and the same nesting limit (`too-large` deeper than
|
|
154
|
+
- With a draft converter (`draftConverter`), a draft is rendered in the browser and sanitized there before it is shown, by the same allow-list rules (`core/sanitizePolicy`, on a DOMPurify instance of the preview's own from `isomorphic-dompurify`'s browser build, so no hook another script adds to the page's shared DOMPurify takes part) and the same nesting limit (`too-large` deeper than 256 levels). The server's other resource limits do not apply there: the host's converter bounds the HTML (`maxHtmlBytes`), and the rendering never leaves the browser.
|
|
141
155
|
The only thing the browser takes from the server for it is the existence marks of images and linked documents, read from the HTML the server's `preview` operation answered (sanitized on the server) and written by the browser's sanitizer onto the elements naming the same document paths, exactly as the converter writes them; a draft the converter answers `unavailable` for is rendered by the server as before.
|
|
142
156
|
- What the host must do: decide per document and per reader whether a document is editable, and check it again in every port (a request names any admitted path); write with the reader's own credentials, never a service account's; write only when the document still has the draft's base version, and otherwise answer the current content without writing; keep revisions only where readers may see them.
|
|
143
157
|
|
|
@@ -148,17 +162,39 @@ In a tree or children listing, an entry with an empty name, or with a path the b
|
|
|
148
162
|
- **Fail closed.** A read-only authentication that carries any header (whatever its status; an empty `headers` holds none) is a broken contract: none of its headers is forwarded, the failure is logged once through `logger` with the operation `authenticate`, and the request is answered `failed` (500, `private, no-store`, no `Set-Cookie`).
|
|
149
163
|
A malformed authentication, or an `authenticate` that throws, is answered the same way; an `ExplorerError` answers its reason without a log, as on every operation, and an aborted request is not logged.
|
|
150
164
|
Nothing logged quotes a header value: `headers` that `Headers` cannot read are refused with a fixed message (on every request, the page loader included), and a `Response` that `authenticate` throws — React Router's `throw redirect(...)`, whose headers carry cookies — is logged by its status alone. `signed-out` and `forbidden` both mean no card: the handler answers its 401 with `no-store` before fetching anything.
|
|
151
|
-
- **SSRF guards live in `@aiquants/markdown
|
|
152
|
-
The handler refuses loopback, private, link-local, CGNAT and every other non-global IPv4 or IPv6 address in every form the URL parser normalizes, internal names (`localhost`, single-label names, `.local`, `.internal`, `.home.arpa`), names that resolve to such addresses (
|
|
153
|
-
|
|
165
|
+
- **SSRF guards live in `@aiquants/markdown`'s service.** The explorer creates `createLinkCardHandler` once, with `authorize` as its only option, and adds no option of its own: internal addresses never become cards in any environment.
|
|
166
|
+
The handler opens pages only through the markdown service (`MARKDOWN_SOCKET_PATH`, as `parseMarkdown`), and the service alone decides which hosts a card may reach: it refuses loopback, private, link-local, CGNAT and every other non-global IPv4 or IPv6 address in every form the URL parser normalizes, internal names (`localhost`, `*.localhost`, single-label names, `.local`, `.internal`, `.home.arpa`), names that resolve to such addresses (at every connection, against DNS rebinding) and every redirect hop to them, and it bounds time, redirects, headers and body.
|
|
167
|
+
Without the service the handler fetches nothing and answers its own `500` (`no-store`), which is passed through unchanged like its other answers.
|
|
168
|
+
Its answer for an internal link — `204 No Content` with `X-Link-Card-Skip: private-network` — is passed through unchanged, and `@aiquants/markdown`'s link card shows the link as a compact card and writes one `console.info` line; the explorer logs nothing of its own for cards.
|
|
154
169
|
- **Same origin.** The browser asks the page's own origin with its credentials and `redirect: "error"`, so no `connect-src` beyond `'self'` is needed and no cross-origin page can read an answer (the data route grants no CORS).
|
|
155
170
|
|
|
171
|
+
## Document IDs
|
|
172
|
+
|
|
173
|
+
- **An ID is not a permission.** The ID operations and ID URLs exist only with `documentIds` in the configuration and the server's `documentIds` ports (the host's registry, which binds each ID to one document path). Without the ports both operations answer as unknown operations (404) before the method is checked or the reader authenticated, and without the option the ID URLs' slug is an unknown view slug.
|
|
174
|
+
Opening an ID URL, or asking `resolve-id`, passes the same checks as the document's path URL — the reader's authentication, the deny rules, the sources' boundaries (with the admitting source's `confirm`) and the document's existence, confirmed through the host's `asset` port without opening its bytes — and an answer names the path only to a reader who can open it:
|
|
175
|
+
|
|
176
|
+
| Case | Answer | The path |
|
|
177
|
+
| --- | --- | --- |
|
|
178
|
+
| The ID is written wrong | 400 `invalid` | Not sent (the registry is not asked) |
|
|
179
|
+
| The registry does not know the ID (never issued, or forgotten when its document was erased) | 404 `not-found` | Not sent |
|
|
180
|
+
| The deny rules refuse the path, no source's boundary admits it, or the reader may not read it | 403 `forbidden` | Not sent |
|
|
181
|
+
| No document is at the path | 404 `not-found` | Not sent |
|
|
182
|
+
| The reader can open the document | A `302` to its path URL (the page loader), 200 `{ status: "ok", path, source }` (`resolve-id`) | Sent: the reader can open that path |
|
|
183
|
+
|
|
184
|
+
- A 403 tells that the ID exists. An ID carries about 55 random bits and cannot be guessed, so the 403 tells only a reader who was given the ID, for whom "it exists, but you may not read it" is a lead to ask for access.
|
|
185
|
+
- **`resolve-id`** (`GET` or `HEAD` `{dataPath}/resolve-id?id=`; 405 with `Allow: GET, HEAD` otherwise) takes an ID in its canonical form only (the lenient reading of lowercase, hyphens, `I`, `L` and `O` is the page URL's alone): a missing, repeated or other value is 400 before the registry is asked. The page loader answers an ID URL by the same resolution (see [URL contract](url-contract.md#document-ids)), and both send `Cache-Control: private, no-store`, so a redirect never outlives the binding it followed.
|
|
186
|
+
- **`issue-id`** (`POST {dataPath}/issue-id?path=`; 405 with `Allow: POST` otherwise) needs `X-Markdown-Explorer: document-id` and the shared cross-origin check of a refresh (`crossOriginRefusal`), checked before the reader is authenticated (403), so another site's page cannot make a reader issue IDs.
|
|
187
|
+
It issues only for a document the reader can open now: a missing, repeated or unacceptable `path`, or one ending in a slash (it has no URL), is 400; a path the deny rules refuse is 403 and logged with the operation, since the bar names only documents it shows; a path outside every source's boundary is 403 and a path where no document is 404 — all before the registry is called.
|
|
188
|
+
The explorer draws each candidate itself and hands the registry the path it shows, never a source's `readPath`; a `taken` candidate draws another, up to 4 candidates, and a fourth `taken` is logged and answered `failed` (500).
|
|
189
|
+
- **Answers are checked.** An `existing` ID that is not in its canonical form, a `bound` path that is not acceptable or has no URL, and any other shape break the contract: logged (a resolution's log names the operation and the error, not the path) and answered `failed` (500). An `ExplorerError` the registry throws answers its reason's status without a log, and any other exception is logged and answered `failed`.
|
|
190
|
+
|
|
156
191
|
## Caches and identity
|
|
157
192
|
|
|
158
193
|
- The server's tree cache is keyed by the reader's scope (derived from the principal's stable key) and the source. `cacheScope: "shared"` lets readers share one entry when the tree does not depend on who reads it; `createFileSystemSource` uses `"principal"` unless told otherwise, which a source wrapped to filter its tree per reader must keep. Entries expire after `treeCache.ttlMs`, and the cache holds at most `treeCache.maxEntries` trees and `treeCache.maxBytes` of their JSON.
|
|
159
194
|
It never keeps an empty or failed tree and never answers a tree past its time to live, counted from the moment its walk began: a page load or tree request after it waits for one new walk, which every concurrent request shares. At most one walk of a tree runs at a time per key; a walk a refresh or `forgetTree` superseded keeps running for the requests already waiting on it (they receive its tree, which is not kept) and is aborted once none waits, and the next walk starts once it settles (at once for a source that honours its signal).
|
|
160
195
|
Each process keeps its own cache: `forgetTree(key)` drops a key another process refreshed, without starting a walk.
|
|
161
|
-
- Each data response carries an opaque, pseudonymous scope (`X-Markdown-Explorer-Scope`): an HMAC of the principal's key under `scopeSecret`, which nobody without the secret can link to a principal
|
|
196
|
+
- Each data response carries an opaque, pseudonymous scope (`X-Markdown-Explorer-Scope`): on the Node entry an HMAC of the principal's key under `scopeSecret`, which nobody without the secret can link to a principal, and on the browser runtime the one scope the host gives with the page's one principal key.
|
|
197
|
+
When the browser sees a different scope — another reader signed in on the same browser — it drops every cached tree and document, clears the explorer's storage and reloads the page data (once per run of the loader, without cancelling a loader that is running). A 401 erases nothing and reloads the page data, whose loader answers a signed-out reader with `signedOutPage`.
|
|
162
198
|
- The page data carries the same scope, and the explorer records it in its storage namespace. On every page load, and whenever the page data names another reader, the recorded scope is compared during render — before any part of the explorer reads browser storage — and the namespace is erased unless it belongs to the page's reader (keys without a recorded scope are erased too).
|
|
163
199
|
A new scope also clears and reseeds both browser stores in a layout effect, before the browser paints, and rebuilds the explorer's components, so no document of the previous reader is drawn and no expansion state, selection or panel arrangement survives in memory either. Each reader also has a live-region announcer of their own: the rebuilt explorer's regions (the root's and the sheet's) start empty, and neither what the previous reader was last told (a folder or document name) nor a message their work posted just before the switch reaches it.
|
|
164
200
|
- The server keeps no failed tree and asks the source again for every document request (the sanitizer's cache only remembers what it made of a given HTML input). In the browser a failure is kept only until a pane has shown it: opening it again, or "Try again", asks the server again.
|
|
@@ -166,10 +202,13 @@ In a tree or children listing, an entry with an empty name, or with a path the b
|
|
|
166
202
|
## What the host must do
|
|
167
203
|
|
|
168
204
|
- Authenticate in `authenticate` and keep `principalKey` stable for one reader. Honour its `mode`: with `{ readOnly: true }` (the `link-card` operation) only read the session — never refresh a token, write no cookie and return no `headers`; the explorer refuses an authentication that does.
|
|
169
|
-
-
|
|
170
|
-
-
|
|
205
|
+
- On the Node entry, set `scopeSecret` from configuration, kept out of the source code and the browser: at least 32 characters, the same on every server instance.
|
|
206
|
+
- On the Node entry, keep the package external in your server bundle, so the sanitizer's worker file stays next to the server entry.
|
|
207
|
+
- On the browser runtime (`./server/browser`; [Hosting](hosting.md) gives the steps), create the runtime in a secure context (a window without `crypto.subtle` is refused), serve one principal per page (a request naming another principal key is a `TypeError`), and give `nestingGuardWorkerUrl` the URL your bundler emits for `@aiquants/markdown-explorer/server/browser/nesting-guard-worker`.
|
|
208
|
+
Answer the page's data requests with `createInProcessDataFetch` passed as `<MarkdownExplorer fetch>` (the page's router has no `basename`). The browser loads a document's images and media from their URLs, never through that fetch, so serve `{dataPath}/asset` (and `mediaDataPath`) over the page's own scheme, or show content without them.
|
|
171
209
|
- Implement the ports: `document` and `asset` (and `children` for lazy folders) read what the explorer admitted, with the `readPath` it hands them, and report the same `version` for the same file.
|
|
172
210
|
The explorer serves every file's bytes itself (see [What the explorer serves](#what-the-explorer-serves)), so the host writes no asset route (nor a route for a document's source, which the `text` operation reads through the same port); the `asset` port only finds the file and opens its bytes, through a handle it checked (for example by comparing the opened file's device, inode, size and modification time with those of the checked path, refusing a file that has changed since it was found) and aborting with the request's signal.
|
|
211
|
+
- With `documentIds`, give the server a registry (`documentIds` ports) whose bindings are unique both ways — one ID per path, one path per ID — and whose `issue` is atomic, so two readers pressing Copy permalink at once get one ID; bind the path the explorer passes (the document path, never a source's `readPath`), keep the ID in the canonical form it was given, and forget a document's ID when the document is erased, so an ID never comes to name another document. The ID grants nothing: keep authorizing every read by its path.
|
|
173
212
|
- Refuse React Router single-fetch requests in any code your data route module runs before it hands the request to `dataLoader` or `dataAction` (which refuse them themselves), and in every resource route of your own: answer 404 for a request whose own URL path (`new URL(request.url).pathname`) ends in `.data`, before authenticating or touching storage.
|
|
174
213
|
React Router strips that suffix from `params` and from the loader's `url` argument, runs the loader for such a request, reads the whole `Response` body into memory and drops every header but `Set-Cookie`.
|
|
175
214
|
- When a source addresses documents by ID rather than by name (a cloud drive, for example), the deny rules can only filter its listings by entry name; its `document` function must refuse denied names itself, since the request carries only the ID.
|
|
@@ -182,6 +221,7 @@ In a tree or children listing, an entry with an empty name, or with a path the b
|
|
|
182
221
|
- List only the iframe hosts you trust in `iframeHosts`, and list the host's own origin only when documents must frame it: every page of a listed host can be framed by a document, and a frame of your own origin is same-site, so it carries the reader's cookies (`SameSite=Lax` included) and the page's side effects happen in an invisible frame.
|
|
183
222
|
- Serve a content security policy for every page of the app — from the root route, the document handler or the edge — rather than on the explorer's route responses alone: a client-side navigation keeps the document it started in, and with it that document's policy, so a policy sent with the explorer's pages is missing when the reader arrives by a client-side navigation and stays on every page visited after them.
|
|
184
223
|
The explorer needs `frame-src`, `img-src` and `media-src` to allow `'self'`, the origin of its own asset URLs (PDF documents open in a frame from that URL), plus `frame-src https://<host>` for each `iframeHosts` entry, and works under `object-src 'none'` and `base-uri 'none'`.
|
|
224
|
+
With `mediaDataPath`, `media-src` and `frame-src` also allow its origin, which videos, audio and PDF documents then load from; on the browser runtime, `worker-src` (or the directive it falls back to) allows the nesting-guard worker's URL.
|
|
185
225
|
- Call `clearExplorerStorage(storageNamespace)` when a reader signs out of a shared browser. It throws a `RangeError` for a malformed namespace (empty, containing `:` or spaces, longer than 64 characters), so a typo cannot clear another namespace's keys or nothing at all.
|
|
186
226
|
|
|
187
227
|
## What the explorer serves
|
|
@@ -9,8 +9,10 @@ This page is part of the host-facing contract of `@aiquants/markdown-explorer`;
|
|
|
9
9
|
| Tree | `{basePath}/{views.tree}`, `{basePath}/{views.tree}/{document}` or `{basePath}/{views.tree}/{folder}/` | `source`, `style`, `align`, `maximized`, `markup` |
|
|
10
10
|
| Multi-panel | `{basePath}/{views.multi}` | `source`, `doc` (repeated, in panel order), `maximized`, `markup` (repeated, in the order of `doc`) |
|
|
11
11
|
| Single | `{basePath}/{views.single}/{document}` | `source`, `style`, `align`, `markup`, `showToc`, `showStyle`, `showAlign`, `padding`, `width`, `maxWidth` |
|
|
12
|
+
| Document ID (with `documentIds`) | `{basePath}/{documentIds.slug}/{ID}` (opens the document in the tree view) or `{basePath}/{documentIds.slug}/{ID}/{views.single}` (in the single view) | `style`, `align`; with `{views.single}` also `showToc`, `showStyle`, `showAlign`, `padding`, `width`, `maxWidth` |
|
|
12
13
|
|
|
13
14
|
- `basePath` and the view slugs come from `defineExplorerConfig` (`tree`, `multi` and `single` by default). The data route lives at `dataPath` and is not a page.
|
|
15
|
+
With `documentIds: { slug }` in the configuration, the URLs under that slug name a document by its ID instead of its path and are never a location of their own: they send the reader to the path URL of the document the ID names (see [Document IDs](#document-ids)). Without the option, the slug is an unknown view slug like any other.
|
|
14
16
|
- `source` names the source shown in the tree: one of the server's sources, whose ids come from `createMarkdownExplorer`'s `sources` in their order (the browser reads them from the page data's `sources`). The first is the default and is written by **omission**; it is never written explicitly. A source id is lowercase letters, digits and `-`, starting with a letter or digit (`isExplorerSourceId`).
|
|
15
17
|
- The tree view shows a document, a folder (its README, see [Folder segment](#folder-segment)) or neither: `ExplorerLocation`'s tree view has `doc` and `folder`, at most one of them not `null`.
|
|
16
18
|
- `markup` names the Markdown documents, SVG images and table files shown as written (their source — an SVG image's own SVG, a table file's CSV or TSV —, the document bar's Source toggle) instead of rendered (a table file as its table): in the tree and single views `markup=true` for the URL's document — in the tree view a folder's README too —, and in the multi-panel view one `markup` per open document shown that way, in the order of `doc` (a maximized document included).
|
|
@@ -57,6 +59,10 @@ Every URL resolves either to a location or to a redirect to its canonical form.
|
|
|
57
59
|
| Multi-panel `maximized` repeated, or not one of the open documents | Redirect without `maximized` |
|
|
58
60
|
| Multi-panel `markup` values that are not open documents, repeated, or out of the order of `doc` | Redirect with each open document shown as written once, in the order of `doc` |
|
|
59
61
|
| A path segment after the multi-panel slug | Redirect to the multi-panel view without it |
|
|
62
|
+
| An ID URL without an ID (`{basePath}/{documentIds.slug}` or `{basePath}/{documentIds.slug}/`) | Redirect to the tree view without a document, keeping a valid `source` |
|
|
63
|
+
| Anything after a well-written ID but `{views.single}` alone (a view slug, a trailing slash, more segments) | Redirect to the ID URL without it, keeping `style` and `align` (the embedding parameters are dropped) |
|
|
64
|
+
| An ID written in lowercase, with hyphens, or with `I`, `L` or `O` | Read as its canonical ID and not redirected (its resolution sends the reader to the path URL once) |
|
|
65
|
+
| An ID written wrong (not 12 symbols once the hyphens are dropped, a character outside the alphabet, a wrong check symbol) | Not redirected: the page shows the `invalid` failure (status 400 from the loader) |
|
|
60
66
|
| `style` naming no configured document style, `align` other than `left`, `center` or `right` | Ignored (the reader's own setting applies) |
|
|
61
67
|
| `padding` outside 0–256 or not written in decimal digits (signs, exponents, hexadecimal, surrounding spaces and `Infinity` are not numbers here), `width` / `maxWidth` not a CSS length in `px`, `rem`, `em`, `ch`, `vw` or `%` | Ignored (the default applies) |
|
|
62
68
|
| `showToc`, `showStyle`, `showAlign` other than `false` | Ignored (the control is shown) |
|
|
@@ -69,6 +75,26 @@ The page loader answers a non-canonical URL with a redirect, and the browser app
|
|
|
69
75
|
A redirect keeps the URL's fragment on a page load and on the explorer's own replacing navigation: the browser carries the fragment across the loader's HTTP redirect of a document request (whose `Location` has none), and the replacing navigation appends the current one to the canonical URL, so loading `/docs#%E6%A6%82%E8%A6%81` ends on the tree view's URL with `#%E6%A6%82%E8%A6%81`.
|
|
70
76
|
A client-side navigation from another route to a non-canonical URL loses its fragment: the loader runs and redirects, and React Router builds the redirected location from the redirect's `Location` alone. To keep a fragment, link to the canonical URL (`explorerHref`) with the fragment appended.
|
|
71
77
|
|
|
78
|
+
## Document IDs
|
|
79
|
+
|
|
80
|
+
With `documentIds: { slug }` in the configuration, a document can also be linked by an ID that stays with it when its path changes: the host's registry (the server's `documentIds` ports, see the README's [Document IDs](../../README.md#document-ids)) binds each ID to one document path, and an ID URL sends the reader to the path URL of the document its ID names. The ID is not a permission: an ID URL opens a document exactly when its path URL would, for the same reader (see [Security](security.md#document-ids)).
|
|
81
|
+
|
|
82
|
+
- **The ID.** 12 symbols of Crockford's Base32 (`DOCUMENT_ID_ALPHABET`: the digits and the capital letters without `I`, `L`, `O` and `U`; `DOCUMENT_ID_LENGTH`): 11 random symbols and a check symbol, the remainder of the 11 read as a base-32 number divided by 37.
|
|
83
|
+
The server draws each from Web Crypto and draws again when the remainder is 32 or more, so every check symbol is in the same alphabet and an ID carries about 55 random bits, never guessed.
|
|
84
|
+
`isCanonicalDocumentId(value)` tells whether a value is an ID in its canonical form; `parseDocumentId(written)` reads one as a reader writes it — hyphens dropped, lowercase raised, `I` and `L` read as `1` and `O` as `0` — into its canonical form, or `null` when it is no ID (a character outside ASCII is refused before any case is raised); `groupDocumentId(id)` groups an ID in its canonical form by four symbols for reading aloud and copying by hand (`7K3M-9QX2-AB4W`; any other value throws a `RangeError`). A URL carries the canonical form, ungrouped.
|
|
85
|
+
`documentIdVectors()` of `@aiquants/markdown-explorer/testing` lists the answers `parseDocumentId` owes, for a host's registry and for an implementation of the rule in another language.
|
|
86
|
+
- **Writing and reading.** `explorerHref(config, { view: "document-id", id, opens?, overrides?, embed? })` writes an ID URL: `opens: "single"` writes `{views.single}` after the ID and is the only form that takes `embed`; `overrides` (`style`, `align`) are written as in a path URL. It throws a `TypeError` with a configuration without `documentIds`, and a `RangeError` for an ID that is not canonical, an `opens` other than `"single"`, embedding options without `opens: "single"`, or a value the resolver would ignore.
|
|
87
|
+
`resolveExplorerLocation` answers an ID URL with `{ kind: "document-id", id, opens, location }`: the canonical ID (`null` when the URL's ID is written wrong), how its document opens (`ExplorerDocumentIdOpening`: the tree view with the overrides, or the single view with the overrides and the embedding options), and the location drawn meanwhile and on a failure — the default source's tree without a document. The URL's `source`, `doc`, `markup` and `maximized` are not read: the ID decides the document.
|
|
88
|
+
- **The page loader.** It authenticates first (a signed-out reader gets `signedOutPage` before the registry is asked), resolves the ID as the `resolve-id` operation does, and answers a document the reader can open with a `302` to its path URL — the view the ID URL asked for, under the source that admits the document (written by omission when it is the default), with the ID URL's overrides and embedding parameters — carrying `Cache-Control: private, no-store` and the authentication's headers.
|
|
89
|
+
Never `301` or `308`: a browser keeps a permanent redirect, and the path an ID names changes when its document moves.
|
|
90
|
+
Otherwise it answers the page with the location above, `documentId: { id, failure }` in the page data (never naming the path) and the failure's status: `invalid` 400 for an ID written wrong (the registry is not asked), `not-found` 404 for an ID the registry does not know or a path where no document is, `forbidden` 403 for a path the deny rules refuse, no source's boundary admits or the reader may not read, `failed` 500. Every other page carries `documentId: null`.
|
|
91
|
+
The browser keeps a fragment across the `302` on a page load; a client-side navigation from another route loses it, as for any redirect above.
|
|
92
|
+
- **In the browser.** A navigation inside the explorer to an ID URL (a document's link, Back and Forward) runs no loader: the explorer shows the document's skeleton in the location above, asks the data route's `resolve-id` operation, and moves with a replacing navigation to the path URL it writes with `explorerHref`, keeping the current fragment, so Back returns to the page the reader came from. A change of URL cancels the resolution in flight.
|
|
93
|
+
A failure is drawn in the document's place (`data-testid="markdown-explorer-document-id-failure"`, its reason in `data-aqmx-failure`) under its own title, with words of its own for `invalid`, `not-found` and `forbidden`, and with Try again for `failed` only; a failure the loader already answered for the same ID is drawn without asking again, and an answer that names a source the page does not know is drawn as `failed`.
|
|
94
|
+
- **Copy permalink.** The bar of a document that is not edited holds Copy permalink, from the server's render on; while the document loads or failed, the button is unavailable (`aria-disabled`) and ignores presses, so the bar's buttons keep their places whatever the document's state.
|
|
95
|
+
A press asks the data route's `issue-id` operation for the document's ID (issued on the first press, the same ID ever after) and copies its ID URL as an absolute URL with the router's basename, in the form of the current view: the single view's with its overrides and embedding parameters, the tree view's with its overrides, and a multi-view panel's as the tree view's without any.
|
|
96
|
+
The clipboard write starts inside the press, since Safari allows a write only during the reader's gesture: a `ClipboardItem` whose text the ID URL fulfils once the server answers. The outcome is announced and shown as the bar's other copies are, with the ID grouped, or with why nothing was copied: the failure's title when no ID could be issued, otherwise the browser's refusal — a browser without the asynchronous clipboard or without `ClipboardItem` included, never retried with `writeText()`, which would write outside the reader's gesture.
|
|
97
|
+
|
|
72
98
|
## Document links
|
|
73
99
|
|
|
74
100
|
A Markdown link that should open another document inside the explorer is resolved by the host's parser, which marks it on the `a` element:
|
|
@@ -153,12 +179,13 @@ A revalidation keeps the shown tree and documents on screen and replaces each on
|
|
|
153
179
|
|
|
154
180
|
## Display settings
|
|
155
181
|
|
|
156
|
-
The reader's display settings — the explorer width per view, whether the reader closed the explorer in each view, the document style and the
|
|
182
|
+
The reader's display settings — the explorer width per view, whether the reader closed the explorer in each view, the document style, the alignment, the column width and the colour pair — live in a cookie named by `settingsCookie`, so the server renders the first paint with them:
|
|
157
183
|
|
|
158
|
-
- the value is percent-encoded JSON with the keys `treeExplorer`, `treeExplorerHidden`, `multiExplorer`, `multiExplorerHidden`, `style` and `
|
|
184
|
+
- the value is percent-encoded JSON with the keys `treeExplorer`, `treeExplorerHidden`, `multiExplorer`, `multiExplorerHidden`, `style`, `align`, `measure` and `documentColors`, written in that order and only when set;
|
|
185
|
+
- `style` is one of the configuration's document styles, and `align`, `measure` and `documentColors` are one of `@aiquants/markdown`'s own alignments (`CONTENT_ALIGNS`), column widths (`CONTENT_MEASURES`) and colour pairs (`CONTENT_COLORS`);
|
|
159
186
|
- widths are percentages of the split, greater than 0 and at most 1/φ² (38.197 %), rounded to 0.01 %;
|
|
160
187
|
- a closed explorer is written as `true` and an open one not at all, and the explorer reads the flag as `=== true`, so `false` and a missing key mean the same (see [Layout](layout.md#closing-the-explorer));
|
|
161
188
|
- the cookie is written with `Path=/`, `Max-Age=31536000`, `SameSite=Lax`, and `Secure` on HTTPS;
|
|
162
189
|
- a malformed cookie, or a value outside these rules, is treated as absent (key by key).
|
|
163
190
|
|
|
164
|
-
The `style` and `align` query parameters override the cookie for one URL without changing it. Without either, a document takes the configuration's `defaultDocumentStyle` (`@aiquants/markdown`'s `DEFAULT_MARKDOWN_STYLE`, Zenn, unless the host names another of its styles) and `@aiquants/markdown`'s own default alignment, so the explorer and the viewer always agree.
|
|
191
|
+
The `style` and `align` query parameters override the cookie for one URL without changing it. Without either, a document takes the configuration's `defaultDocumentStyle` (`@aiquants/markdown`'s `DEFAULT_MARKDOWN_STYLE`, Zenn, unless the host names another of its styles) and `@aiquants/markdown`'s own default alignment, so the explorer and the viewer always agree. The column width and the colour pair have no query parameter: without a stored one, a document takes `@aiquants/markdown`'s own defaults (`DEFAULT_CONTENT_MEASURE`, `fill`, and `DEFAULT_CONTENT_COLORS`, `default`).
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aiquants/markdown-explorer",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.36.0",
|
|
4
4
|
"description": "Markdown document explorer for React Router 8 (framework mode): a source tree with a single-document view and a multi-panel reading view, storage-agnostic server ports, golden-ratio layout and an en / ja UI.",
|
|
5
5
|
"sideEffects": [
|
|
6
6
|
"**/*.css"
|
|
@@ -32,6 +32,29 @@
|
|
|
32
32
|
},
|
|
33
33
|
"default": "./dist/server.js"
|
|
34
34
|
},
|
|
35
|
+
"./server/core": {
|
|
36
|
+
"import": {
|
|
37
|
+
"types": "./dist/serverCore.d.ts",
|
|
38
|
+
"default": "./dist/serverCore.js"
|
|
39
|
+
},
|
|
40
|
+
"require": {
|
|
41
|
+
"types": "./dist/serverCore.d.cts",
|
|
42
|
+
"default": "./dist/serverCore.cjs"
|
|
43
|
+
},
|
|
44
|
+
"default": "./dist/serverCore.js"
|
|
45
|
+
},
|
|
46
|
+
"./server/browser": {
|
|
47
|
+
"import": {
|
|
48
|
+
"types": "./dist/serverBrowser.d.ts",
|
|
49
|
+
"default": "./dist/serverBrowser.js"
|
|
50
|
+
},
|
|
51
|
+
"require": {
|
|
52
|
+
"types": "./dist/serverBrowser.d.cts",
|
|
53
|
+
"default": "./dist/serverBrowser.cjs"
|
|
54
|
+
},
|
|
55
|
+
"default": "./dist/serverBrowser.js"
|
|
56
|
+
},
|
|
57
|
+
"./server/browser/nesting-guard-worker": "./dist/nestingGuardWorker.js",
|
|
35
58
|
"./storage": {
|
|
36
59
|
"import": {
|
|
37
60
|
"types": "./dist/storage.d.ts",
|
|
@@ -43,6 +66,17 @@
|
|
|
43
66
|
},
|
|
44
67
|
"default": "./dist/storage.js"
|
|
45
68
|
},
|
|
69
|
+
"./testing": {
|
|
70
|
+
"import": {
|
|
71
|
+
"types": "./dist/testing.d.ts",
|
|
72
|
+
"default": "./dist/testing.js"
|
|
73
|
+
},
|
|
74
|
+
"require": {
|
|
75
|
+
"types": "./dist/testing.d.cts",
|
|
76
|
+
"default": "./dist/testing.cjs"
|
|
77
|
+
},
|
|
78
|
+
"default": "./dist/testing.js"
|
|
79
|
+
},
|
|
46
80
|
"./styles/markdown-explorer.css": "./dist/styles/markdown-explorer.css",
|
|
47
81
|
"./package.json": "./package.json"
|
|
48
82
|
},
|
|
@@ -70,8 +104,8 @@
|
|
|
70
104
|
"peerDependencies": {
|
|
71
105
|
"@aiquants/directory-tree": "^6.1.1",
|
|
72
106
|
"@aiquants/drag-drop-panels": "^0.14.0",
|
|
73
|
-
"@aiquants/markdown": "^
|
|
74
|
-
"@aiquants/resize-panels": "^2.
|
|
107
|
+
"@aiquants/markdown": "^13.0.0",
|
|
108
|
+
"@aiquants/resize-panels": "^2.3.0",
|
|
75
109
|
"@aiquants/spreadsheet": "^0.20.0",
|
|
76
110
|
"@aiquants/virtualscroll": "^3.24.0",
|
|
77
111
|
"react": "^19.2.7",
|
|
@@ -79,10 +113,10 @@
|
|
|
79
113
|
"react-router": "^8.0.0"
|
|
80
114
|
},
|
|
81
115
|
"devDependencies": {
|
|
82
|
-
"@aiquants/directory-tree": "6.1.
|
|
83
|
-
"@aiquants/drag-drop-panels": "0.14.
|
|
84
|
-
"@aiquants/markdown": "
|
|
85
|
-
"@aiquants/resize-panels": "2.
|
|
116
|
+
"@aiquants/directory-tree": "6.1.3",
|
|
117
|
+
"@aiquants/drag-drop-panels": "0.14.1",
|
|
118
|
+
"@aiquants/markdown": "13.1.0",
|
|
119
|
+
"@aiquants/resize-panels": "2.3.0",
|
|
86
120
|
"@aiquants/spreadsheet": "0.20.0",
|
|
87
121
|
"@aiquants/virtualscroll": "3.24.0",
|
|
88
122
|
"@heroicons/react": "^2.2.0",
|
|
@@ -95,8 +129,11 @@
|
|
|
95
129
|
"@types/react": "^19.2.7",
|
|
96
130
|
"@types/react-dom": "^19.2.3",
|
|
97
131
|
"@vitejs/plugin-react": "^5.1.2",
|
|
132
|
+
"@vitest/browser": "4.1.10",
|
|
133
|
+
"@vitest/browser-playwright": "4.1.10",
|
|
98
134
|
"@vitest/coverage-v8": "^4.1.10",
|
|
99
135
|
"jsdom": "^27.4.0",
|
|
136
|
+
"playwright": "^1.64.1",
|
|
100
137
|
"react": "^19.2.7",
|
|
101
138
|
"react-dom": "^19.2.7",
|
|
102
139
|
"react-router": "^8.3.0",
|
|
@@ -131,7 +168,7 @@
|
|
|
131
168
|
"scripts": {
|
|
132
169
|
"build": "pnpm -w run workspace:build \"$PNPM_SCRIPT_SRC_DIR\"",
|
|
133
170
|
"prebuild:self": "pnpm -w run workspace:sync \"$PNPM_SCRIPT_SRC_DIR\"",
|
|
134
|
-
"build:self": "vite build && pnpm run build:css && node ../../.config/scripts/strip-dts-comments.mjs dist && node scripts/verify-dist.mjs",
|
|
171
|
+
"build:self": "vite build && vite build --mode nesting-guard-worker && pnpm run build:css && node ../../.config/scripts/strip-dts-comments.mjs dist && node scripts/verify-dist.mjs",
|
|
135
172
|
"build:css": "tailwindcss -i src/styles/markdown-explorer.css -o dist/styles/markdown-explorer.css --minify",
|
|
136
173
|
"dev": "vite build --watch",
|
|
137
174
|
"watch": "vite build --watch",
|
|
@@ -139,10 +176,11 @@
|
|
|
139
176
|
"demo:build": "cd demo && pnpm run build",
|
|
140
177
|
"demo:start": "cd demo && pnpm run start",
|
|
141
178
|
"typecheck": "tsc --noEmit && pnpm --dir demo run typecheck",
|
|
142
|
-
"test": "vitest run",
|
|
179
|
+
"test": "vitest run --project browser --project wiring --project server --project server-plan --project server-browser-chromium",
|
|
143
180
|
"test:run": "vitest run",
|
|
144
181
|
"test:watch": "vitest --watch",
|
|
145
|
-
"test:coverage": "vitest run --coverage",
|
|
182
|
+
"test:coverage": "vitest run --project browser --project wiring --project server --project server-plan --project server-browser-chromium --coverage",
|
|
183
|
+
"test:browser:webkit": "vitest run --project server-browser-webkit",
|
|
146
184
|
"test:e2e": "playwright test",
|
|
147
185
|
"test:e2e:ui": "playwright test --ui",
|
|
148
186
|
"lint": "biome check src tests",
|
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const q=require("react/jsx-runtime"),h=require("react"),x=require("./index-BDCbvHDs.cjs"),J=require("@aiquants/markdown/code-blocks"),K=require("@codemirror/commands"),pe=require("@codemirror/lang-markdown"),oe=require("@codemirror/language"),ge=require("@codemirror/search"),$=require("@codemirror/state"),P=require("@codemirror/view"),V=require("@lezer/highlight"),He=require("@aiquants/markdown"),ue=require("@aiquants/markdown/source-lines"),ee=require("./dataRoute-DwYtgyt6.cjs"),de=require("./sanitizePolicy-T5T-3vV5.cjs"),je=require("isomorphic-dompurify"),se=require("@aiquants/resize-panels"),X=require("./location-hGLhCCg4.cjs"),ze=require("./useSplitPersistence-QGcvyMAa.cjs"),Ce={history:K.historyField},Fe=oe.HighlightStyle.define([{tag:[V.tags.heading1,V.tags.heading2,V.tags.heading3,V.tags.heading4,V.tags.heading5,V.tags.heading6,V.tags.heading],color:"var(--aqmx-syntax-heading)",fontWeight:"700"},{tag:V.tags.strong,fontWeight:"700"},{tag:V.tags.emphasis,fontStyle:"italic"},{tag:V.tags.strikethrough,textDecoration:"line-through"},{tag:V.tags.link,color:"var(--aqmx-syntax-link)",textDecoration:"underline"},{tag:V.tags.url,color:"var(--aqmx-syntax-url)"},{tag:V.tags.monospace,color:"var(--aqmx-syntax-code)"},{tag:V.tags.quote,color:"var(--aqmx-syntax-quote)"},{tag:[V.tags.processingInstruction,V.tags.contentSeparator,V.tags.labelName,V.tags.meta],color:"var(--aqmx-syntax-mark)"}]),Ue=P.EditorView.theme({"&":{height:"100%",color:"var(--aqmx-text)",backgroundColor:"var(--aqmx-surface)",fontSize:"var(--aqmx-font-size-title)"},"&.cm-focused":{outline:"none"},".cm-scroller":{fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace',lineHeight:"var(--aqmx-line-height-prose)"},".cm-content":{caretColor:"var(--aqmx-text)",paddingBlock:"var(--aqmx-space-6)"},".cm-line":{paddingInline:"var(--aqmx-space-6)"},"&.cm-focused .cm-cursor":{borderLeftColor:"var(--aqmx-text)"},"&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection":{backgroundColor:"var(--aqmx-editor-selection)"},".cm-activeLine":{backgroundColor:"var(--aqmx-editor-active-line)"},".cm-gutters":{backgroundColor:"var(--aqmx-surface-raised)",color:"var(--aqmx-editor-gutter)",borderInlineEnd:"var(--aqmx-space-1) solid var(--aqmx-border)"},".cm-activeLineGutter":{backgroundColor:"var(--aqmx-editor-active-line)"},".cm-searchMatch":{outline:"var(--aqmx-space-1) solid var(--aqmx-border-strong)"},".cm-panels":{backgroundColor:"var(--aqmx-surface-raised)",color:"var(--aqmx-text)"}}),qe="data-aqmx-conflict-actions",Ge=P.Decoration.line({attributes:{"data-aqmx-conflict-line":"marker"}}),We=P.Decoration.line({attributes:{"data-aqmx-conflict-line":"ours"}}),Xe=P.Decoration.line({attributes:{"data-aqmx-conflict-line":"theirs"}});class $e extends P.WidgetType{constructor(t,n){super(),this.index=t,this.labels=n}index;labels;eq(t){return t.index===this.index&&t.labels===this.labels}toDOM(t){const n=document.createElement("div");n.setAttribute(qe,String(this.index));for(const[r,i]of[["ours",this.labels.useOurs],["theirs",this.labels.useTheirs],["both",this.labels.keepBoth]]){const o=document.createElement("button");o.type="button",o.textContent=i,o.setAttribute("data-aqmx-conflict-choice",r),o.addEventListener("mousedown",l=>l.preventDefault()),o.addEventListener("click",()=>{const l=re(t.state.doc)[this.index];l!==void 0&&(Me(t,l,r),t.focus())}),n.append(o)}return n}ignoreEvent(){return!0}}const re=e=>x.findConflictsInLines(e.iterLines()),ve=(e,t)=>{const n=new $.RangeSetBuilder;return re(e).forEach((r,i)=>{const o=e.line(r.start);n.add(o.from,o.from,P.Decoration.widget({widget:new $e(i,t),block:!0,side:-1}));for(let l=r.start;l<=r.end;l+=1){const s=e.line(l).from,d=l===r.start||l===r.separator||l===r.end?Ge:l<r.separator?We:Xe;n.add(s,s,d)}}),n.finish()},Ke=e=>$.StateField.define({create:t=>ve(t.doc,e),update:(t,n)=>n.docChanged?ve(n.state.doc,e):t,provide:t=>P.EditorView.decorations.from(t)}),Me=(e,t,n)=>{const{doc:r}=e.state,i=(k,c)=>{const E=[];for(let u=k;u<=c;u+=1)E.push(r.line(u).text);return E},o=i(t.start+1,t.separator-1),l=i(t.separator+1,t.end-1),s=n==="ours"?o:n==="theirs"?l:[...o,...l];let d=r.line(t.start).from,f=r.line(t.end).to;s.length===0&&(t.end<r.lines?f+=1:t.start>1&&(d-=1));const p=s.join(`
|
|
2
|
-
`);e.dispatch({changes:{from:d,to:f,insert:p},selection:$.EditorSelection.cursor(d),scrollIntoView:!0,userEvent:"input.resolve"})},we="input.preview",Ye=20,Je=P.ViewPlugin.fromClass(class{constructor(e){this.view=e,this.schedule()}view;cancel=null;update(e){e.docChanged&&this.schedule()}schedule(){if(this.cancel!==null||oe.syntaxTreeAvailable(this.view.state))return;const e=this.view.dom.ownerDocument.defaultView;if(e===null)return;const t=()=>{this.cancel=null,oe.ensureSyntaxTree(this.view.state,this.view.state.doc.length,Ye),this.schedule()};if(typeof e.requestIdleCallback=="function"){const n=e.requestIdleCallback(t);this.cancel=()=>e.cancelIdleCallback(n)}else{const n=e.setTimeout(t,0);this.cancel=()=>e.clearTimeout(n)}}destroy(){this.cancel?.(),this.cancel=null}}),Qe=/`{3,}|~{3,}/u,te=Object.freeze({kind:"absent"}),ce=Object.freeze({kind:"unreadable"}),Ze=(e,t,n)=>{const r=[];for(let d=t.parent;d!==null;d=d.parent)(d.name==="Blockquote"||d.name==="ListItem")&&r.unshift(d);const i=[],o=[],l=d=>{const f=o.indexOf(d);return f===-1?o.length:f};for(const d of r){const f=e.lineAt(d.from).number;if(d.name==="ListItem"){const p=J.listItemWidthOn(e.line(f).text,i,l(f));if(p===null)return null;i.push({kind:"listItem",width:p})}else i.push({kind:"quote"});o.push(f)}const s=J.openingFenceOn(n.text,i,l(n.number));return s===null?null:{containers:i,...s}},et=(e,t)=>{const{doc:n}=e;let r=n.lineAt(t).to;for(;;){const i=oe.ensureSyntaxTree(e,r,Number.POSITIVE_INFINITY);if(i===null)return null;const o=i.resolveInner(t,1),l=o.parent;if(o.name!=="CodeMark"||l===null||l.name!=="FencedCode"||l.from!==o.from)return null;if(l.to<r||r>=n.length)return l;r=Math.min(n.length,l.to+Math.max(l.to-t,1))}},Ee=(e,t)=>{const{doc:n}=e;if(!Number.isInteger(t)||t<1||t>n.lines)return te;const r=n.line(t),i=Qe.exec(r.text);if(i===null)return te;const o=et(e,r.from+i.index);if(o===null)return te;const l=o.getChild("CodeInfo");if(l===null)return te;const s=J.fencedCodeLanguageOf(n.sliceString(l.from,l.to));if(s===null)return ce;if(s!==J.SPREADSHEETS_LANGUAGE)return te;const d=Ze(n,o,r);if(d===null)return ce;const[,...f]=o.getChildren("CodeMark"),p=f.at(-1),k=p===void 0?n.lineAt(o.to).number:n.lineAt(p.from).number-1,c=[];let E="";for(let u=t+1;u<=k;u+=1){const m=n.line(u).text,v=J.readFencedLine(m,d);if(v===null)return ce;c.push(m),E+=u<n.lines?`${v.content}
|
|
3
|
-
`:v.content}return{kind:"found",firstLine:t+1,lines:c,layout:d,body:E}},tt=({parent:e,scroll:t,text:n,saved:r,labels:i,revisions:o,onChange:l,onGeometry:s,onSave:d})=>{let f=!1;const p=[P.EditorView.scrollHandler.of((u,m,v)=>(nt(u,m.head,v,t),!0)),P.lineNumbers(),P.highlightActiveLineGutter(),K.history(),P.drawSelection(),P.highlightActiveLine(),ge.highlightSelectionMatches(),P.EditorView.lineWrapping,pe.markdown({base:pe.markdownLanguage}),Je,oe.syntaxHighlighting(Fe),Ke(i),P.keymap.of([{key:"Mod-s",preventDefault:!0,run:()=>(d(),!0)},...ge.searchKeymap,...K.historyKeymap,...K.defaultKeymap]),P.EditorView.contentAttributes.of({"aria-label":i.editor,"aria-multiline":"true"}),P.EditorView.updateListener.of(u=>{for(const m of u.transactions)m.docChanged&&o.record(m.changes,m.newDoc);u.docChanged&&l(u.transactions.every(m=>!m.docChanged||m.isUserEvent(we))),(u.docChanged||u.heightChanged||u.geometryChanged)&&s(u.docChanged&&!f)}),Ue],k=st(r,p)??$.EditorState.create({doc:n,extensions:p}),c=new P.EditorView({state:k,parent:e});o.mount(c.state.doc);const E=u=>{f=!0;try{u()}finally{f=!1}};return{text:()=>c.state.doc.toString(),replaceText:u=>{const m=c.state.doc.toString();if(m===u)return;let v=0;const y=Math.min(m.length,u.length);for(;v<y&&m.charCodeAt(v)===u.charCodeAt(v);)v+=1;let g=0;for(;g<y-v&&m.charCodeAt(m.length-1-g)===u.charCodeAt(u.length-1-g);)g+=1;c.dispatch({changes:{from:v,to:m.length-g,insert:u.slice(v,u.length-g)},userEvent:"input.replace"})},replaceBody:(u,m,v,y)=>{const{doc:g}=c.state,L=o.lineOf(y,u);if(L===null)return"changed";const O=Ee(c.state,L);if(O.kind==="absent")return"changed";if(O.kind==="unreadable")return"unwritable";if(O.body!==J.fencedBodyAsRead(m,O.layout))return"changed";const A=J.planFencedBodyEdit(O.lines,O.layout,v);if(A.kind!=="edit")return A.kind;if(A.from===A.to&&A.lines.length===0)return"written";const D=j=>{const H=O.firstLine+j;return H<=g.lines?g.line(H).from:g.length},M=D(A.from),B=`${M===g.length&&g.sliceString(g.length-1)!==`
|
|
4
|
-
`?`
|
|
5
|
-
`:""}${A.lines.map(j=>`${j}
|
|
6
|
-
`).join("")}`;return E(()=>c.dispatch({changes:{from:M,to:D(A.to),insert:B},userEvent:we,annotations:K.isolateHistory.of("full")})),"written"},readBody:(u,m)=>{const v=o.lineOf(m,u);if(v===null)return null;const y=Ee(c.state,v);return y.kind==="found"?y.body:null},undo:()=>E(()=>K.undo(c)),redo:()=>E(()=>K.redo(c)),reveal:({line:u,column:m},v)=>{const{doc:y}=c.state,g=y.line(Math.min(Math.max(u,1),y.lines)),L=Math.min(g.from+m,g.to);c.dispatch({selection:$.EditorSelection.cursor(L),effects:be(c,L,v,t)})},showLine:u=>{const{doc:m}=c.state,v=m.line(Math.min(Math.max(u,1),m.lines)).from;c.dispatch({effects:be(c,v,null,t)})},topLine:()=>{const u=t.scrollerOf(c.scrollDOM),m=x.visibleTopOf(u,c.contentDOM),v=x.frameTopOf(u)+u.clientHeight,{documentTop:y}=c,{doc:g}=c.state;let L=c.lineBlockAtHeight(Math.max(m-y,0));for(;g.lineAt(L.from).text.trim()===""&&L.to<g.length;){const D=c.lineBlockAt(L.to+1);if(y+D.top>=v)break;L=D}const O=c.coordsAtPos(L.from),A=O===null?y+L.top:O.top;return{line:c.state.doc.lineAt(L.from).number,clientTop:A,offset:A-m}},lineSpans:u=>{const m=c.scrollDOM,v=m.scrollTop+c.documentTop-x.visibleTopOf(m,c.contentDOM),{doc:y}=c.state,g=L=>y.line(Math.min(Math.max(L,1),y.lines)).from;return u.map(({first:L,last:O})=>({top:v+c.lineBlockAt(g(L)).top,bottom:v+c.lineBlockAt(g(O)).bottom}))},scrollElement:c.scrollDOM,focus:()=>c.focus(),conflicts:()=>re(c.state.doc),resolveAtCursor:u=>{const m=re(c.state.doc),v=c.state.doc.lineAt(c.state.selection.main.head).number,y=m.find(g=>g.end>=v);return y===void 0?!1:(Me(c,y,u),!0)},nextConflict:()=>{const u=re(c.state.doc);if(u[0]===void 0)return!1;const v=c.state.doc.lineAt(c.state.selection.main.head).number,y=u.findIndex(A=>A.start>v),g=y<0?0:y,L=c.state.doc.line(u[g].start).from;c.dispatch({selection:$.EditorSelection.cursor(L),effects:P.EditorView.scrollIntoView(L,{y:"center"})});const O=c.contentDOM.querySelector(`[${qe}="${String(g)}"] button`);return O instanceof HTMLElement?O.focus({preventScroll:!0}):c.focus(),!0},save:()=>c.state.toJSON(Ce),destroy:()=>c.destroy()}},be=(e,t,n,r)=>{const i=r.scrollerOf(e.scrollDOM),o=(n===null?x.visibleTopOf(i,e.contentDOM):n)-x.frameTopOf(i);return P.EditorView.scrollIntoView(t,{y:"start",yMargin:o})},nt=(e,t,n,r)=>{const i=rt(e,t),o=r.scrollerOf(e.scrollDOM),l=x.frameTopOf(o),s=x.visibleTopOf(o,e.contentDOM),d=l+o.clientHeight;let f=0;switch(n.y){case"start":f=i.top-(l+n.yMargin);break;case"center":f=(i.top+i.bottom)/2-(s+d)/2;break;case"end":f=i.bottom-(d-n.yMargin);break;default:i.top<s+n.yMargin?f=i.top-(s+n.yMargin):i.bottom>d-n.yMargin&&(f=Math.min(i.bottom-(d-n.yMargin),i.top-(s+n.yMargin)))}if(f!==0&&(o.scrollTop+=f),n.y==="start")return;const p=ot(e,t);p!==null&&r.reveal(p)},rt=(e,t)=>{const{node:n,offset:r}=e.domAtPos(t);if(n.nodeType===Node.TEXT_NODE){const l=n.ownerDocument?.createRange();if(l!==void 0){l.setStart(n,r),l.setEnd(n,r);const[s]=l.getClientRects();if(s!==void 0&&s.height>0)return{top:s.top,bottom:s.bottom}}}const i=e.lineBlockAt(t),o=e.documentTop+i.top;return{top:o,bottom:o+i.height}},ot=(e,t)=>{const{node:n}=e.domAtPos(t);for(let r=n instanceof Element?n:n.parentElement;r!==null;r=r.parentElement)if(r.parentElement===e.contentDOM)return r;return null},st=(e,t)=>{if(e==null)return null;try{return $.EditorState.fromJSON(e,{extensions:t},Ce)}catch{return null}},it=610,lt=987,xe=Object.freeze({kind:"unavailable"}),ct="true",at="false",ut=e=>e===ct?!0:e===at?!1:null,dt=e=>{const t=new DOMParser().parseFromString(e,"text/html"),n=[];for(const r of t.querySelectorAll("img[data-asset-src], a[data-doc-path]")){const i=r.localName==="img",o=r.getAttribute(i?"data-asset-src":"data-doc-path");o!==null&&n.push({target:{kind:i?"asset":"doc",path:o},exists:ut(r.getAttribute(i?"data-asset-exists":"data-doc-exists"))})}return n},ft=({path:e,instant:t,preview:n,initial:r,onView:i})=>{const o=new AbortController,l={asset:new Map,doc:new Map};let s=r,d=null,f=!1,p=!1,k=null,c=null,E=[],u,m=!1,v,y=null;const g=w=>{w.parsed===s.parsed&&w.source===s.source&&w.failure===s.failure&&w.busy===s.busy&&w.tier===s.tier||(s=w,i(w))},L=(w,T)=>{f||(f=!0,console.error(`[markdown-explorer] ${w}`,...T===void 0?[]:[T]))},O=w=>{if(t!==null)for(const{target:T,exists:C}of t.marksOf(w))l[T.kind].set(T.path,C)},A=()=>{clearTimeout(v),v=void 0,y?.abort(),y=null},D=()=>{c=null,E=[],clearTimeout(u),u=void 0},M=(w,T)=>{g({...s,failure:w,busy:!1,tier:T})},F=()=>{clearTimeout(u),u=E.length===0?void 0:setTimeout(j,lt)},B=()=>{if(t===null||c===null)return;const w=c,T=[],C={asset:new Set,doc:new Set};let U;try{U=t.sanitize(w.html,S=>{const _=l[S.kind].get(S.path);return _===void 0&&!C[S.kind].has(S.path)&&(C[S.kind].add(S.path),T.push(S)),_??void 0})}catch(S){D(),S instanceof de.HtmlNestingLimitError?M(ee.failureOf("too-large"),"instant"):(L("the draft sanitizer failed",S),M(ee.failureOf("failed"),"instant"));return}E=T;const b=s.parsed!==null&&s.parsed.htmlContent===U&&s.parsed.headings===w.headings?s.parsed:{htmlContent:U,headings:w.headings};g({parsed:b,source:w.draft,failure:null,busy:!1,tier:"instant"}),F()},j=()=>{if(u=void 0,m||c===null||E.length===0)return;m=!0;const w=E;n(e,c.draft.text,o.signal).then(T=>{if(m=!1,!(o.signal.aborted||!("kind"in T))){T.kind==="preview"&&O(T.htmlContent);for(const C of w)l[C.kind].has(C.path)||l[C.kind].set(C.path,null);B()}})},H=w=>{A(),D(),g({...s,busy:!0,tier:"server"});const T=new AbortController;y=T,v=setTimeout(()=>{v=void 0,n(e,w.text,T.signal).then(C=>{if(!(T.signal.aborted||!("kind"in C))){if(y=null,C.kind==="failure"){M(C.failure,"server");return}O(C.htmlContent),g({parsed:{htmlContent:C.htmlContent,headings:C.headings},source:w,failure:null,busy:!1,tier:"server"})}})},it)},a=async(w,T)=>{let C;try{C=await w.convert({path:e,text:T},o.signal)}catch(b){return o.signal.aborted||L("the draft converter rejected a conversion, which its contract allows only once the signal aborted",b),xe}const U=ee.draftAnswerViolation(C);return U===null?C:(L(`the draft converter answered outside its contract: ${U}`),xe)},I=(w,T)=>{switch(T.kind){case"preview":if(A(),T.headings.length>ee.EXPLORER_MAX_HEADINGS){D(),M(ee.failureOf("too-large"),"instant");return}c={draft:w,html:T.htmlContent,headings:T.headings.map(({text:C,depth:U,id:b})=>({text:C,depth:U,id:b}))},B();return;case"failure":A(),D(),M(ee.failureOf(T.failure.reason,T.failure.code),"instant");return;case"unavailable":H(w);return}},R=async w=>{p=!0;try{for(;k!==null&&!o.signal.aborted;){const T=k;k=null;const C=await a(w,T.text);if(o.signal.aborted)return;I(T,C)}}finally{p=!1}};return t!==null&&t.seed!==null&&O(t.seed),{update:w=>{if(!(o.signal.aborted||w.text===d?.text)){if(d=w,clearTimeout(u),u=void 0,t===null){H(w);return}k=w,p||R(t.converter)}},dispose:()=>{o.abort(),k=null,clearTimeout(u),u=void 0,A()}}},mt=(e,t)=>de.createHtmlSanitizer(je(window),e,t,de.MAX_HTML_NESTING_DEPTH),ht=(e,t)=>e.flatMap((n,r)=>{const i=t[r];return i===void 0?[]:[{editor:i.top,preview:n.top},{editor:i.bottom,preview:n.bottom}]}),Y=(e,t)=>{const n=e[t];if(n===void 0)throw new RangeError(`[markdown-explorer] a scroll map index must be in 0..${String(e.length-1)}; got ${String(t)}`);return n},pt=e=>{const t=[];for(const r of e){let i=0,o=t.length;for(;i<o;){const l=i+o>>1;Y(t,l).pair.preview<=r.preview?i=l+1:o=l}t[i]={pair:r,before:i===0?void 0:Y(t,i-1)}}const n=[];for(let r=t.at(-1);r!==void 0;r=r.before)n.push(r.pair);return n.reverse()},gt=(e,t)=>{const n=Math.max(t.editorMax,0),r=Math.max(t.previewMax,0),i=n-t.editorViewport,o=r-t.previewViewport,l=e.filter(f=>f.editor>0&&f.editor<i&&f.preview>0&&f.preview<o).sort((f,p)=>f.editor-p.editor||f.preview-p.preview);let s={editor:0,preview:0};const d=[s];for(const f of pt(l))f.editor>s.editor&&f.preview>s.preview&&(d.push(f),s=f);return d.push({editor:n,preview:r}),{toPreview:f=>Se(d,"editor","preview",f),toEditor:f=>Se(d,"preview","editor",f)}},Se=(e,t,n,r)=>{const i=Y(e,0),o=Y(e,e.length-1);if(Number.isNaN(r)||r<=i[t])return i[n];if(r>=o[t])return o[n];let l=0,s=e.length-1;for(;s-l>1;){const p=l+s>>1;Y(e,p)[t]<=r?l=p:s=p}const d=Y(e,l),f=Y(e,s);return d[n]+(f[n]-d[n])*(r-d[t])/(f[t]-d[t])},vt=610,ye=89,Te=.5,wt=({editor:e,preview:t,previewBlocks:n,editorSpans:r,requestFrame:i,cancelFrame:o,now:l})=>{let s="editor",d=0,f=null,p=null,k=!1,c=null,E=null;const u={editor:0,preview:0},m={editor:null,preview:null};let v=null,y=()=>{};const g=a=>{f!==null&&a!==f||(s=a,d=l()+vt)},L=(a,I)=>{a!==s&&f===null&&l()>=d&&!O(a,I)&&(s=a),B()},O=(a,I)=>{const R=m[a];return l()<u[a]||R!==null&&Math.abs(I.position()-R)<Te},A=e.onScroll(()=>L("editor",e)),D=e.onIntent(()=>g("editor")),M=()=>{const a=t();return a!==v&&(y(),v=a,y=a===null?()=>{}:F(a)),a},F=a=>{const I=a.onScroll(()=>L("preview",a)),R=a.onIntent(()=>g("preview"));return()=>{I(),R()}},B=()=>{!k&&p===null&&(p=i(j))},j=()=>{p=null;const a=M();a!==null&&(c??=n(),E??=gt(ht(c,r(c)),{editorMax:e.max(),previewMax:a.max(),editorViewport:e.viewport(),previewViewport:a.viewport()}),s==="editor"?H(a,"preview",E.toPreview(e.position())):H(e,"editor",E.toEditor(a.position())))},H=(a,I,R)=>{if(Math.abs(a.position()-R)<Te){m[I]=a.position();return}u[I]=l()+ye,m[I]=a.scrollTo(R)};return B(),{editorChanged:a=>{E=null,a&&g("editor"),B()},previewChanged:()=>{c=null,E=null,u.preview=l()+ye,B()},showAlone:a=>{f=a,!(a===null||a===s)&&(s=a,d=0,B())},dispose:()=>{k=!0,p!==null&&o(p),p=null,A(),D(),y()}}},ke=Object.freeze(["wheel","pointerdown","keydown","focusin"]),_e=e=>({position:()=>e.scrollTop,max:()=>Math.max(e.scrollHeight-e.clientHeight,0),viewport:()=>e.clientHeight,scrollTo:t=>(e.scrollTo({top:t,behavior:"instant"}),e.scrollTop),onScroll:t=>(e.addEventListener("scroll",t,{passive:!0}),()=>e.removeEventListener("scroll",t)),onIntent:t=>{for(const n of ke)e.addEventListener(n,t,{capture:!0,passive:!0});return()=>{for(const n of ke)e.removeEventListener(n,t,{capture:!0})}}}),ne="[data-aqmd-scroll-container]",Et="[data-aqmd-content]",bt=`[${ue.SOURCE_LINES_ATTRIBUTE}]`,xt=Object.freeze(["p1","p2","p3","p4","p5","p6","p7","p8"]),Pe=(e,t)=>{const n=x.loadedOf(e.peek(t));return n!==null&&n.document.kind==="markdown"?{htmlContent:n.document.htmlContent,headings:n.document.headings}:null},St=(e,t,n,r,i)=>{if(n===void 0)return null;let o;try{o=mt(e,t)}catch(l){return console.error("[markdown-explorer] the draft sanitizer cannot run in this browser, so the server renders the preview",l),null}return{converter:n,sanitize:o,marksOf:dt,seed:Pe(r,i)?.htmlContent??null}},yt=e=>{const t=[];let n=null;for(const r of e.querySelectorAll(bt)){const i=ue.parseSourceLines(r.getAttribute(ue.SOURCE_LINES_ATTRIBUTE));if(i===null||r.getClientRects().length===0)continue;n??=e.scrollTop-x.visibleTopOf(e,r);const{top:o,bottom:l}=r.getBoundingClientRect();t.push({first:i.first,last:i.last,top:n+o,bottom:n+l})}return t},Tt=({path:e,readDraft:t,viewer:n,tables:r,concealed:i,onEditAt:o,onLayout:l,handleRef:s})=>{const{config:d,data:f,documents:p,draftConverter:k,labels:c}=x.useExplorer(),[E,u]=h.useState(()=>({parsed:Pe(p,e),source:null,failure:null,busy:!0,tier:k===void 0?"server":"instant"})),m=h.useRef(null),v=h.useRef(null),y=h.useRef(E);h.useLayoutEffect(()=>{y.current=E});const g=h.useEffectEvent(()=>t());h.useEffect(()=>{const a=St(d.iframeHosts,d.dataPath,k,p,e),I=g(),R=ft({path:e,instant:a,preview:f.preview,initial:y.current,onView:w=>h.startTransition(()=>u(w))});return v.current=R,R.update(I),()=>{R.dispose(),v.current=null}},[d,f,p,k,e]);const L=h.useEffectEvent(()=>l());h.useLayoutEffect(()=>{E.parsed!==null&&L()},[E.parsed]);const O=E.parsed!==null;h.useLayoutEffect(()=>{const a=O?m.current?.querySelector(ne):null;if(!(a instanceof HTMLElement))return;a.tabIndex=0;const I=new ResizeObserver(()=>L());I.observe(a);const R=a.querySelector(Et);return R!==null&&I.observe(R),()=>I.disconnect()},[O]);const A=h.useRef(null);h.useImperativeHandle(s,()=>({draft:a=>{v.current?.update(a)},scrollPort:()=>{const a=m.current?.querySelector(ne);return a instanceof HTMLElement?(A.current?.scroller!==a&&(A.current={scroller:a,port:_e(a)}),A.current.port):null},blocks:()=>{const a=m.current?.querySelector(ne);return a instanceof HTMLElement?yt(a):[]},focus:()=>{const a=m.current?.querySelector(ne);a instanceof HTMLElement&&a.focus({preventScroll:!0})},anchor:a=>{const I=m.current,R=I?.querySelector(ne);return I===null||!(R instanceof HTMLElement)?null:x.anchorOfView(I,a(R))},place:({line:a,clientTop:I},R)=>{const w=m.current,T=w===null?null:x.blockAtLine(w,a);T!==null&&(R(T).scrollTop+=x.lineTopIn(T,a)-I)}}),[]);const D=a=>{const I=m.current,{target:R}=a;if(o===void 0||I===null||!(R instanceof Element)||!x.isEditingDoubleClick(R))return;const w=x.anchorOfDoubleClick(R,I,I.ownerDocument.getSelection());w!==null&&o(w)},M=E.source===null?null:E.source.revision,F=h.useMemo(()=>M===null?void 0:{write:a=>r.write(M,a),read:a=>r.read(M,a),undo:r.undo,redo:r.redo,subscribe:r.subscribe},[r,M]),B=h.useMemo(()=>({...n.labels,spreadsheetReadOnly:c.previewTablePending}),[n.labels,c.previewTablePending]),j=h.useMemo(()=>({...n,labels:F===void 0?B:n.labels,showToc:!1,showStyle:!1,showAlign:!1,renderScrollBar:void 0,scrollBarGutter:void 0,scrollBarInlineSize:void 0,spreadsheetEditor:F}),[n,B,F]),H=h.useMemo(()=>E.parsed===null?null:q.jsx("div",{className:"aqmx-document-viewer",children:q.jsx(He.MarkdownViewer,{...j,parseResult:E.parsed,content:null})}),[j,E.parsed]);return q.jsxs("section",{ref:m,className:"aqmx-edit-preview","aria-label":c.previewRegion,"aria-busy":E.busy,inert:i!==null,hidden:i==="removed","data-aqmx-preview-tier":E.tier,"data-testid":"markdown-explorer-edit-preview",onDoubleClick:o===void 0?void 0:D,children:[E.failure===null?null:q.jsx("p",{className:"aqmx-callout aqmx-document-notice","data-aqmx-tone":"warning","data-testid":"markdown-explorer-edit-preview-failure",children:c.previewFailed(x.failureTitleOf(c,E.failure.reason))}),H??(E.failure===null?q.jsx("div",{className:"aqmx-skeleton","aria-hidden":"true","data-testid":"markdown-explorer-edit-preview-skeleton",children:xt.map(a=>q.jsx("span",{},a))}):null),E.busy?q.jsx("p",{className:"aqmx-sr-only",children:c.previewUpdating}):null]})},Le="data-aqmx-edit-split",ae="--aqmx-edit-share",Ie="--aqmx-edit-gutter",kt="data-aqmx-edit-split-probe",Lt="aqmx-edit-split",It="aqmx-edit-editor",At="aqmx-edit-preview",Ae={value:X.EDIT_SPLIT_MIN_PERCENT,unit:"percentage"},Oe={value:X.EDIT_SPLIT_MAX_PERCENT,unit:"percentage"},Re=e=>{if(e.length!==2)return null;const[t=0,n=0]=e,r=t+n;return r>0?t/r*100:null},ie=e=>{const t=e.current?.parentElement;if(t==null)throw new Error("[markdown-explorer] the edit split is not mounted in its surface");return t},Ot=(e,t,n)=>{const[r,i]=h.useState(null);return h.useLayoutEffect(()=>{const o=e.current,l=t.current;if(o===null||l===null)throw new Error("[markdown-explorer] the edit split is not mounted");const s={frame:o.getBoundingClientRect().width,measure:l.getBoundingClientRect().width},d=()=>{s.frame>0&&s.measure>0&&i(X.editSplitOrientation(s.frame,s.measure,n))};d();const f=new ResizeObserver(p=>{for(const k of p){const[c]=k.borderBoxSize;c!==void 0&&(k.target===o&&(s.frame=c.inlineSize),k.target===l&&(s.measure=c.inlineSize))}d()});return f.observe(o),f.observe(l),()=>f.disconnect()},[e,t,n]),r},Rt=({editorId:e})=>{const{edits:t,labels:n}=x.useExplorer(),r=h.useRef(null),i=h.useRef(null),o=x.useCoarsePointer()?X.COARSE_TARGET_PIXELS:X.FINE_TARGET_PIXELS,l=Ot(r,i,o),[s]=h.useState(()=>t.editorShare());h.useLayoutEffect(()=>{const p=ie(r);return p.style.setProperty(Ie,`${String(o)}px`),()=>{p.style.removeProperty(Ie)}},[o]),h.useLayoutEffect(()=>{const p=ie(r);return p.style.setProperty(ae,`${String(s)}%`),()=>{p.style.removeProperty(ae)}},[s]),h.useLayoutEffect(()=>{if(l===null)return;const p=ie(r);return p.setAttribute(Le,l),()=>p.removeAttribute(Le)},[l]);const d=ze.useSplitPersistence(h.useCallback(p=>{const k=Re(p);k!==null&&t.setEditorShare(k)},[t])),f=h.useCallback((p,k)=>{const c=Re(p);c!==null&&ie(r).style.setProperty(ae,`${String(c)}%`),d.layoutChanged(p,k)},[d]);return q.jsxs("div",{ref:r,className:"aqmx-edit-split","data-testid":"markdown-explorer-edit-split",children:[q.jsx("span",{ref:i,className:"aqmx-edit-split-probe","aria-hidden":"true",[kt]:""}),l===null?null:q.jsxs(se.PanelGroup,{id:Lt,direction:l==="beside"?"horizontal":"vertical",onLayout:f,className:"aqmx-edit-split-group",children:[q.jsx(se.Panel,{id:It,defaultSize:{value:s,unit:"percentage"},minSize:Ae,maxSize:Oe,contentOverflow:"hidden"}),q.jsx(se.PanelResizeHandle,{thickness:o,indicator:{visible:!0,thickness:X.SPLIT_HANDLE_PIXELS.gripThickness,length:X.SPLIT_HANDLE_PIXELS.gripLength,barThickness:X.SPLIT_HANDLE_PIXELS.barThickness,barLength:X.SPLIT_HANDLE_PIXELS.barLength},title:n.editViewSplitResize,"aria-label":n.editViewSplitResize,"aria-controls":e,onDragging:d.draggingChanged,className:"aqmx-split-handle aqmx-edit-split-handle"}),q.jsx(se.Panel,{id:At,defaultSize:{value:100-s,unit:"percentage"},minSize:Ae,maxSize:Oe,contentOverflow:"hidden"})]})]})},Ct=512,qt=()=>{const e=[];let t=0,n=null;const r=i=>{if(n===null||!Number.isInteger(i)||i<t)return null;if(i===t+e.length)return n;const o=e[i-t];return o===void 0?null:o.before};return{revision:()=>t+e.length,mount:i=>{if(n!==null&&(n===i||n.eq(i))){n=i;return}const o=t+e.length;e.length=0,t=n===null?o:o+1,n=i},record:(i,o)=>{if(n===null)throw new Error("[markdown-explorer] a change of the editor's text was recorded before an editor mounted");e.push({before:n,changes:i}),n=o,e.length>Ct&&(e.shift(),t+=1)},lineOf:(i,o)=>{const l=r(i);if(l===null||n===null||!Number.isInteger(o)||o<1||o>l.lines)return null;let s=l.line(o).from;for(const d of e.slice(i-t)){const f=d.changes.mapPos(s,1,$.MapMode.TrackAfter);if(f===null)return null;s=f}return n.lineAt(s).number}}},Ne=144,Mt=e=>{if(typeof e!="object"||e===null)return!1;const{generation:t,topLine:n}=e;return"state"in e&&typeof t=="number"&&typeof n=="number"},_t=e=>{e.stopPropagation()},Pt=e=>{const{path:t,name:n,session:r}=e,{edits:i,labels:o,announcer:l}=x.useExplorer(),{phase:s}=r,d=h.useCallback(()=>i.retry(t),[i,t]);switch(h.useEffect(()=>{s.kind==="failed"&&l.announce(o.documentFailed(n,x.failureTitleOf(o,s.failure.reason)))},[s,l,o,n]),s.kind){case"opening":return q.jsx(x.ContentSkeleton,{label:o.editLoading,testId:"markdown-explorer-edit-skeleton"});case"grant":return q.jsx("div",{className:"aqmx-edit-message",children:q.jsx(x.EditGrantNotice,{href:s.href,onRetry:d,testId:"markdown-explorer-edit-grant"})});case"failed":return q.jsx("div",{className:"aqmx-edit-message",children:q.jsx(x.FailureView,{failure:s.failure,alert:!1,onRetry:d,testId:"markdown-explorer-edit-failure"})});case"editing":return q.jsx(Nt,{...e})}},Nt=({path:e,name:t,session:n,layout:r,viewer:i,region:o,paneScroll:l})=>{const{edits:s,labels:d}=x.useExplorer(),f=h.useRef(null),p=h.useId(),k=h.useRef(null),[c]=h.useState(()=>new Set),[E]=h.useState(qt),u=h.useRef(null),m=h.useRef(null),v=r==="fill",y=x.useSideBySide(),g=x.editViewOf(n,y,v),L=g!=="editor"||n.previewPrepared,O=L&&v,A=h.useRef({layout:r,region:o,paneScroll:l});h.useLayoutEffect(()=>{A.current={layout:r,region:o,paneScroll:l}});const D=h.useRef(n.generation);h.useLayoutEffect(()=>{D.current=n.generation});const M=h.useRef({view:g,previewMounted:L});h.useLayoutEffect(()=>{M.current={view:g,previewMounted:L}});const F=h.useRef(null),B=h.useRef(null),j=h.useRef(!1),H=h.useMemo(()=>({editor:d.editorLabel(t),useOurs:d.conflictUseOurs,useTheirs:d.conflictUseTheirs,keepBoth:d.conflictKeepBoth}),[d,t]),a=h.useCallback(b=>{const{region:S,paneScroll:_}=A.current,z=S();return z===null?b:_.scrollerOf(z,b)},[]);h.useLayoutEffect(()=>{const b=f.current,S=s.draft(e);if(b===null||S===null)return;const _=s.editorState.get(e),z=Mt(_)&&_.generation===D.current?_:null;let W=null,Q=null;const le=()=>{W!==null&&clearTimeout(W),W=null,Q!==null&&s.setDraft(e,Q.text())},G=tt({parent:b,scroll:{scrollerOf:N=>{const{layout:Z,region:Ve,paneScroll:Be}=A.current,he=Ve();return Z==="fill"||he===null?N:Be.scrollerOf(he,N)},reveal:N=>A.current.paneScroll.reveal(N)},text:S,saved:z===null?void 0:z.state,labels:H,revisions:E,onGeometry:N=>m.current?.editorChanged(N),onChange:N=>{if(W??=setTimeout(le,Ne),!N)for(const Z of[...c])Z();M.current.previewMounted&&Q!==null&&u.current?.draft({text:Q.text(),revision:E.revision()})},onSave:()=>{s.save(e)}});Q=G,k.current=G;const fe=()=>{const N=G.topLine();return{line:N.line,clientTop:N.clientTop}},me=()=>u.current?.anchor(a)??null,De=s.bindEditor(e,{flush:le,adopt:N=>G.replaceText(N),returnPoint:()=>{const N=M.current.view==="preview"&&A.current.layout==="content"?me():null;return N===null?fe():{line:N.lines.first,clientTop:N.clientTop}},nextConflict:()=>M.current.view!=="preview"?G.nextConflict():G.conflicts().length===0?!1:(j.current=!0,s.setView(e,"editor"),!0),beforeView:N=>{if(A.current.layout==="fill")return;if(N==="preview"){F.current={to:"preview",point:fe()};return}const Z=me();F.current=Z===null?null:{to:"editor",anchor:Z}}});return z!==null&&G.showLine(z.topLine),()=>{le(),s.editorState.set(e,{state:G.save(),generation:D.current,topLine:G.topLine().line}),De(),G.destroy(),Q=null,k.current=null}},[s,e,H,a,c,E]);const{request:I}=n;h.useLayoutEffect(()=>{const b=k.current,S=s.draft(e);b===null||S===null||I===null||(I.anchor!==null&&b.reveal(x.positionInSource(S,I.anchor),I.anchor.clientTop),b.focus(),s.consumeRequest(e))},[s,e,I,H]),h.useLayoutEffect(()=>{g!=="editor"&&!n.previewPrepared&&s.preparePreview(e)},[s,e,g,n.previewPrepared]),h.useLayoutEffect(()=>{const b=F.current,S=B.current,_=j.current;F.current=null,B.current=null,j.current=!1;const z=k.current;if(b?.to==="preview")u.current?.place(b.point,a);else if(b?.to==="editor"&&z!==null){const W=s.draft(e);W!==null&&z.reveal(x.positionInSource(W,b.anchor),b.anchor.clientTop)}_?z?.nextConflict():S==="editor"?z?.focus():S==="preview"&&u.current?.focus()},[s,e,g,a]);const R=h.useMemo(()=>{const b=()=>{const S=k.current;if(S===null)throw new Error("[markdown-explorer] a table of the preview wrote back while no editor was mounted");return S};return{write:(S,{fenceLine:_,expected:z,text:W})=>b().replaceBody(_,z,W,S),read:(S,_)=>b().readBody(_,S),undo:()=>b().undo(),redo:()=>b().redo(),subscribe:S=>(c.add(S),()=>{c.delete(S)})}},[c]),w=h.useCallback(()=>{const b=k.current;if(b===null)throw new Error("[markdown-explorer] the preview read the draft before the editor was mounted");return{text:b.text(),revision:E.revision()}},[E]);h.useLayoutEffect(()=>{const b=k.current;if(!O||b===null)return;const S=wt({editor:_e(b.scrollElement),preview:()=>u.current?.scrollPort()??null,previewBlocks:()=>u.current?.blocks()??[],editorSpans:_=>b.lineSpans(_),requestFrame:_=>requestAnimationFrame(_),cancelFrame:_=>cancelAnimationFrame(_),now:()=>performance.now()});return S.showAlone(x.paneShownAlone(M.current.view)),m.current=S,()=>{S.dispose(),m.current=null}},[O,s,e,H]),h.useLayoutEffect(()=>{m.current?.showAlone(x.paneShownAlone(g))},[g]);const T=h.useCallback(()=>m.current?.previewChanged(),[]),C=h.useCallback(b=>s.start(e,b),[s,e]),U=b=>{if(x.isInFullscreenBlock(b.target))return;if(b.key==="Escape"){x.consumeKey(b);return}if(!x.isEditViewShortcut(b.nativeEvent,x.isApplePlatform(navigator.platform)))return;x.consumeKey(b);const S=x.toggledEditView(g);B.current=S,x.chooseEditView(s,e,S,v)};return q.jsxs("div",{className:"aqmx-edit","data-aqmx-edit-layout":r,"data-aqmx-edit-view":g,"data-testid":"markdown-explorer-edit",onKeyDown:U,onDoubleClick:_t,children:[q.jsx("div",{ref:f,id:p,className:"aqmx-edit-editor","data-testid":"markdown-explorer-editor",inert:g==="preview",hidden:g==="preview"&&!v,...x.ALLOW_KEY_REPEAT}),g==="split"?q.jsx(Rt,{editorId:p}):null,L?q.jsx(Tt,{path:e,readDraft:w,viewer:i,tables:R,concealed:g!=="editor"?null:v?"overlay":"removed",onEditAt:g==="preview"?C:void 0,onLayout:T,handleRef:u}):null]})};exports.DRAFT_WRITE_INTERVAL_MS=Ne;exports.default=Pt;
|