oxedyne/daimond/src/wasm/typst.rs
104 KiB, 1 run
created by r2519314175:997, which is this file's identity for as long as the history lasts, whatever it is later renamed to
download · who wrote it · its history
| 1 | //! The Typst compiler edge — thin bindings to the JS driver `window.DaimondTypst`. |
| 2 | //! |
| 3 | //! The compiler itself is a 30 MB wasm module vendored under `www/vendor/typst` |
| 4 | //! and driven from `www/js/typst.js`. It is reached the same way the Web panel |
| 5 | //! is: one object on `window`, one method, and a `Promise` awaited here. |
| 6 | //! |
| 7 | //! The division of labour matters. This side does BYTES ONLY: the source text |
| 8 | //! goes out, PDF bytes come back, and every file touch -- reading the `.typ`, |
| 9 | //! writing the `.pdf` -- happens in Rust through [`crate::wasm::opfs`], so the |
| 10 | //! path jail, the per-account namespace and the real-folder override all apply. |
| 11 | //! The driver never learns a path. |
| 12 | //! |
| 13 | //! A driver that cannot load the compiler resolves with `{ error }` rather than |
| 14 | //! rejecting, so the wording the page already owns (`typst.load_failed`, |
| 15 | //! `typst.no_pdf`, `typst.compile_error`) reaches the model verbatim as the |
| 16 | //! reason the compile failed. |
| 17 | //! |
| 18 | //! # A book is not a file |
| 19 | //! |
| 20 | //! Until this module grew a gatherer, exactly one string went to the compiler and |
| 21 | //! the shadow filesystem was wiped before every compile, so `#import "template.typ"` |
| 22 | //! on line one of a real book could never resolve. What came back was typst's |
| 23 | //! dummy-access-model message -- *cannot read file outside of project root, you can |
| 24 | //! adjust the project root with the --root argument* -- which is what that model |
| 25 | //! says about ANY path it cannot reach. It reads like a settings problem with an |
| 26 | //! obvious fix, and in a real session it sent a daimon hunting for out-of-bounds |
| 27 | //! images that were never the problem. A wrong message bought a wrong diagnosis. |
| 28 | //! |
| 29 | //! So [`gather`] builds the project here, in Rust, and hands the driver CONTENTS. |
| 30 | //! The paths that cross the boundary are virtual: they are positions inside the |
| 31 | //! compiler's in-memory shadow filesystem, rooted at `/`, and there is nothing at |
| 32 | //! the far end that could read one even if it wanted to. Every byte the compiler |
| 33 | //! sees was read on this side, through [`crate::wasm::opfs`], under the same jail |
| 34 | //! as every other file the app touches. |
| 35 | //! |
| 36 | //! # The root is not the search path |
| 37 | //! |
| 38 | //! Landing the gatherer was not enough, because it made ONE directory do three |
| 39 | //! jobs. The compiler's project root has to sit high enough that |
| 40 | //! `#import "../style/glossary_index.typ"` resolves, which for the author's book |
| 41 | //! means the folder ABOVE it; fonts and root-relative pictures live inside the |
| 42 | //! book, one level DOWN from there. Tying the font search to the root therefore |
| 43 | //! meant that the arrangement which made the imports work was the arrangement |
| 44 | //! which lost every font -- and the refusal, correctly, said the book asked for a |
| 45 | //! family it could not load. Two right answers to two questions that were never |
| 46 | //! the same question. |
| 47 | //! |
| 48 | //! They are separated here. The root is inferred from the import closure and |
| 49 | //! nothing else. Assets and fonts are searched from the MAIN FILE'S OWN FOLDER |
| 50 | //! outward, at every ancestor up to the folder the user marked in, and a |
| 51 | //! root-relative reference is placed in the shadow filesystem at the path the |
| 52 | //! source names it by -- so `"/assets/svg/mark.svg"` is satisfied by |
| 53 | //! `<book>/assets/svg/mark.svg` whether the root came out at the book or three |
| 54 | //! levels above it, and a font beside the book is found whether the root reaches |
| 55 | //! it or not. |
| 56 | //! |
| 57 | //! Nothing asks the user where the root is. Marking a folder into the workspace |
| 58 | //! is already a permission grant; asking for a second folder that satisfies an |
| 59 | //! import graph nobody can see is a configuration question wearing a permission's |
| 60 | //! hat, and it has no feedback until it fails. |
| 61 | //! |
| 62 | //! # The rule, so it cannot be re-coupled by accident |
| 63 | //! |
| 64 | //! **The ROOT says how the compiler ADDRESSES a file. The MARK says what may be |
| 65 | //! READ. They are different questions.** |
| 66 | //! |
| 67 | //! Two variables that look interchangeable, and joining them back together is a |
| 68 | //! two-character change that passes every test but one. It was made once here |
| 69 | //! already, in the first version of this rewrite: the asset and font search was |
| 70 | //! capped at the inferred root, and a fixture that lost one import shrank the root |
| 71 | //! from `books` to `books/proj`, which put `books/assets/fonts` outside it. The |
| 72 | //! compile was then refused for a missing font family -- while the actual fault was |
| 73 | //! a missing import, three inches up the same file. A wrong message buying a wrong |
| 74 | //! diagnosis is the entire reason this module was rewritten, and it had grown back |
| 75 | //! in a smaller costume. |
| 76 | //! |
| 77 | //! So the search ceiling is the FLOOR -- the folder marked into the workspace, or |
| 78 | //! the compartment a turn works in -- and never the root. Two consequences that |
| 79 | //! look like bugs to a reader who does not know why: |
| 80 | //! |
| 81 | //! - A file may be READ from above the inferred root. That is not a hole: the |
| 82 | //! mark is the permission, and the root is a conclusion drawn from the imports |
| 83 | //! after the fact. Nothing above the mark is ever reached, and `MAX_UP` bounds |
| 84 | //! the climb whatever the mark is. |
| 85 | //! - A root-relative reference found above the root is still ADDRESSABLE, because |
| 86 | //! it is placed in the shadow filesystem at the position the source named it by |
| 87 | //! -- `"/assets/x.svg"` goes to `/assets/x.svg` -- and not at where it was found. |
| 88 | //! The shadow filesystem is ours to lay out; it owes nothing to the disk. |
| 89 | //! |
| 90 | //! # A package is not a download |
| 91 | //! |
| 92 | //! `#import "@preview/cetz:0.3.4"` names a package in Typst Universe. The |
| 93 | //! command-line compiler fetches it over the network and caches it; this one has no |
| 94 | //! network, so for a long time every document with a live cetz diagram was refused |
| 95 | //! outright -- including the author's own 281-page book, whose template opens with |
| 96 | //! that exact line. It was the largest single thing standing between this compiler |
| 97 | //! and real work. |
| 98 | //! |
| 99 | //! Five packages now travel INSIDE the bundle, as sealed files under |
| 100 | //! `www/assets/typst/packs/`, and [`packages`] hands their sources to the compiler |
| 101 | //! the same way the project's own sources are handed over: as contents, at positions |
| 102 | //! in the shadow filesystem. Nothing is fetched from a registry, so "this compiler |
| 103 | //! runs inside the page with no network at all" stays literally true, and what |
| 104 | //! compiled the book is inside `www/manifest.json` and the transparency chain -- |
| 105 | //! provably what shipped. `www/assets/typst/VENDORED.md` is the whole account. |
| 106 | //! |
| 107 | //! ## The closure, and why it is walked rather than listed |
| 108 | //! |
| 109 | //! cetz 0.3.4's `src/deps.typ` is one line: `#import "@preview/oxifmt:0.2.1"`. Ship |
| 110 | //! cetz without oxifmt and the import resolves and then fails -- and **a package that |
| 111 | //! resolves while its dependency does not is indistinguishable from one that never |
| 112 | //! resolved**. That is not a hypothetical: it stopped the first run of |
| 113 | //! `dev/probe_typstpkg.mjs` dead. |
| 114 | //! |
| 115 | //! So the set in `refresh.sh` is a WISH LIST, and the closure is derived here, from |
| 116 | //! the package sources themselves: every pack that arrives is read for the `@…` |
| 117 | //! imports it names, and each of those is followed in turn. Nothing consults a |
| 118 | //! hand-written list of dependencies, so a dependency cannot be quietly absent, and |
| 119 | //! one that is missing gets its own refusal saying the document is not at fault. |
| 120 | //! |
| 121 | //! cetz-plot is why this matters in practice: it imports `@preview/cetz:0.3.2`, not |
| 122 | //! the 0.3.4 the book uses, so cetz is vendored twice. Nothing about the package's |
| 123 | //! name or version would have told anybody that. |
| 124 | //! |
| 125 | //! ## The import is re-pointed, and the registry hook is not used |
| 126 | //! |
| 127 | //! `TypstCompilerBuilder` does expose `set_package_registry`, and a probe proved it |
| 128 | //! works. It is deliberately not what this does, because it only works alongside |
| 129 | //! `set_access_model` -- which would replace the DUMMY access model the driver |
| 130 | //! installs, and the dummy model's wording (`failed to load file (access denied)`) is |
| 131 | //! what `www/js/typst.js` matches on to compose the careful message about a file that |
| 132 | //! was never gathered. Buying packages at the price of that message would be trading |
| 133 | //! one wrong diagnosis for another, which is the fault this whole module exists to |
| 134 | //! answer. |
| 135 | //! |
| 136 | //! Instead the package becomes ORDINARY FILES. Its contents go into the shadow |
| 137 | //! filesystem under `/_pkg/<namespace>/<name>/<version>/pkg/`, a one-line module is |
| 138 | //! placed beside them at `…/<name>.typ`, and the literal in the import is re-pointed |
| 139 | //! at that module. The binding is unchanged -- a path import takes its name from the |
| 140 | //! file stem, and the stem is the package's own name -- so `#import "@preview/cetz:0.3.4"` |
| 141 | //! still binds `cetz`, and every other form of the statement (`: *`, an item list, |
| 142 | //! `as`) survives untouched because only the quoted string is replaced. |
| 143 | //! |
| 144 | //! Two consequences, stated because they are real: |
| 145 | //! |
| 146 | //! - Columns AFTER the import on that one line shift by the difference in length. |
| 147 | //! Line numbers do not move, and no other line is touched. |
| 148 | //! - Inside a package, a leading `/` means the PACKAGE root, not the project's, so |
| 149 | //! those references are re-pointed too -- but only when they name a file the pack |
| 150 | //! actually holds, so a string of prose beginning with a slash is left alone. |
| 151 | //! cetz-plot's `src/lib.typ` is the case that proves this is not optional. |
| 152 | |
| 153 | use crate::tools::{FileRoot, ToolContext}; |
| 154 | use crate::wasm::{js_str, opfs}; |
| 155 | |
| 156 | use oxedyne_fe2o3_core::prelude::*; |
| 157 | |
| 158 | use std::cell::RefCell; |
| 159 | use std::rc::Rc; |
| 160 | |
| 161 | use wasm_bindgen::prelude::wasm_bindgen; |
| 162 | use wasm_bindgen::{JsCast, JsValue}; |
| 163 | use wasm_bindgen_futures::JsFuture; |
| 164 | |
| 165 | |
| 166 | #[wasm_bindgen] |
| 167 | extern "C" { |
| 168 | |
| 169 | /// The driver object `www/js/typst.js` installs at `window.DaimondTypst`. |
| 170 | #[wasm_bindgen(js_name = DaimondTypst)] |
| 171 | type Driver; |
| 172 | |
| 173 | /// Compile a Typst source string, resolving `{ pdf }` or `{ error }`. |
| 174 | #[wasm_bindgen(method)] |
| 175 | fn compile(this: &Driver, source: &str) -> js_sys::Promise; |
| 176 | |
| 177 | /// Compile a gathered project, resolving `{ pdf }` or `{ error }`. |
| 178 | #[wasm_bindgen(method, js_name = compileProject)] |
| 179 | fn compile_project(this: &Driver, project: &JsValue) -> js_sys::Promise; |
| 180 | |
| 181 | /// Lay a gathered project out without writing it out, resolving |
| 182 | /// `{ vector }` or `{ error }`. What the live view draws. |
| 183 | #[wasm_bindgen(method, js_name = compileProjectVector)] |
| 184 | fn compile_project_vector(this: &Driver, project: &JsValue) -> js_sys::Promise; |
| 185 | |
| 186 | /// The watcher object `www/js/typstwatch.js` installs at |
| 187 | /// `window.DaimondTypstWatch`, absent on a page that has no live view. |
| 188 | #[wasm_bindgen(js_name = DaimondTypstWatch)] |
| 189 | type Watcher; |
| 190 | |
| 191 | /// Tell the watcher a document has just been compiled from the page, so it |
| 192 | /// can follow the file from here on. |
| 193 | #[wasm_bindgen(method)] |
| 194 | fn began(this: &Watcher, path: &str, watch: &JsValue); |
| 195 | } |
| 196 | |
| 197 | |
| 198 | // ── Bounds ────────────────────────────────────────────────────────────────── |
| 199 | // |
| 200 | // A walk that follows whatever it finds is how a turn hung today. Every limit |
| 201 | // below is a REFUSAL, not a truncation: a project gathered up to a cap and then |
| 202 | // compiled would produce a PDF missing a chapter, and the author would proofread |
| 203 | // it without ever being told. Silence is the failure mode worth engineering |
| 204 | // against, so hitting any of these stops the compile and says which one it was. |
| 205 | |
| 206 | /// The most files -- sources and assets together -- one project may gather. |
| 207 | const MAX_FILES: usize = 500; |
| 208 | |
| 209 | /// The most bytes those files may come to, in total. |
| 210 | const MAX_BYTES: usize = 48 * 1024 * 1024; |
| 211 | |
| 212 | /// The most font files one project may load. |
| 213 | const MAX_FONTS: usize = 48; |
| 214 | |
| 215 | /// The most bytes those fonts may come to. |
| 216 | const MAX_FONT_BYTES: usize = 24 * 1024 * 1024; |
| 217 | |
| 218 | /// How far above a file's own directory a reference may be searched for. |
| 219 | /// |
| 220 | /// The author's book sits one level down and reaches one level up, so the true |
| 221 | /// root is the parent; four levels is room for a deeper tree without turning a |
| 222 | /// stray `"/usr/share/x.png"` in prose into a walk of the whole workspace. |
| 223 | const MAX_UP: usize = 4; |
| 224 | |
| 225 | /// How deep a font directory is searched. |
| 226 | const MAX_FONT_DEPTH: usize = 3; |
| 227 | |
| 228 | /// How many directories a font search may open. |
| 229 | const MAX_FONT_DIRS: usize = 64; |
| 230 | |
| 231 | /// Extensions the compiler can be handed as bytes and a source can name. |
| 232 | /// |
| 233 | /// `.pdf` is deliberately absent: typst cannot place one, and a book directory |
| 234 | /// usually holds the last build, which would be the largest thing gathered and |
| 235 | /// the least use. |
| 236 | const ASSET_EXTS: &[&str] = &[ |
| 237 | "svg", "png", "jpg", "jpeg", "gif", "webp", |
| 238 | "bib", "csv", "json", "yaml", "yml", "toml", "xml", "txt", |
| 239 | ]; |
| 240 | |
| 241 | /// Extensions a font file carries. |
| 242 | const FONT_EXTS: &[&str] = &["ttf", "otf", "ttc", "otc"]; |
| 243 | |
| 244 | /// Directories searched for fonts, relative to each folder on the search path, |
| 245 | /// mirroring what `typst --font-path` is usually pointed at. |
| 246 | const FONT_DIRS: &[&str] = &["assets/fonts", "fonts"]; |
| 247 | |
| 248 | /// Typst's own project manifest, which a self-declaring project puts at its root. |
| 249 | const MANIFEST: &str = "typst.toml"; |
| 250 | |
| 251 | /// Where a vendored package's files are placed in the shadow filesystem. |
| 252 | /// |
| 253 | /// One directory that no real project would name, because the shadow filesystem is |
| 254 | /// shared with the project's own files and a book with a `_pkg` folder of its own |
| 255 | /// would otherwise collide with a package. |
| 256 | const PKG_ROOT: &str = "/_pkg"; |
| 257 | |
| 258 | /// What this build carries, as `www/assets/typst/refresh.sh` wrote it. |
| 259 | /// |
| 260 | /// Compiled in rather than fetched, deliberately. The sentence "this build carries |
| 261 | /// cetz 0.3.4 and four others" has to be true of THIS build, and a build that reads |
| 262 | /// its own inventory over the network can be handed a stale one by a cache. The |
| 263 | /// packs themselves are fetched; the list of them is not. |
| 264 | const PKG_INDEX: &str = include_str!("../../www/assets/typst/packs/INDEX"); |
| 265 | |
| 266 | /// Where a pack is served from, relative to the page. |
| 267 | /// |
| 268 | /// Relative, so it resolves against the document's base and a deployment under a |
| 269 | /// sub-path needs no setting. Under `assets/`, NOT under `vendor/`: `vendor/` is |
| 270 | /// gitignored, excluded from the public mirror by `dev/publish.mjs` and excluded |
| 271 | /// from the bundle fingerprint by `verify/lib.mjs`, so a package shipped there would |
| 272 | /// be outside the seal and, worse, would not be deployed at all. |
| 273 | const PKG_URL: &str = "assets/typst/packs"; |
| 274 | |
| 275 | /// The most files the vendored packages may come to. |
| 276 | /// |
| 277 | /// A tripwire rather than a limit: the closure is bounded by what the bundle carries, |
| 278 | /// which is 119 files today. It exists so that a future vendor set that grew by |
| 279 | /// accident is refused loudly rather than pushed through the boundary a page at a time. |
| 280 | const MAX_PKG_FILES: usize = 400; |
| 281 | |
| 282 | /// The most bytes they may come to. |
| 283 | const MAX_PKG_BYTES: usize = 8 * 1024 * 1024; |
| 284 | |
| 285 | |
| 286 | // ── Fonts do not change between rebuilds ──────────────────────────────────── |
| 287 | // |
| 288 | // The gather re-read 63 sources AND ELEVEN MEGABYTES OF FONTS ACROSS 24 FILES on |
| 289 | // every compile -- about 150 ms of a 430 ms rebuild, or a third of a watch loop, |
| 290 | // spent reading bytes that were byte-for-byte the ones read a second earlier. |
| 291 | // |
| 292 | // Sources have to be re-read: they are what changed. Fonts do not. So the font |
| 293 | // directories are still WALKED every time -- a listing is cheap and a font really |
| 294 | // can be dropped in mid-session -- but the bytes are only re-read when the walk |
| 295 | // produces a different answer. "Different" is `lastModified` WITH `size`, per |
| 296 | // file, which is the same test `www/js/cloud.js` uses for cloud sync and the same |
| 297 | // one [`opfs::stamp`] exists to serve; a font edited in place to the same length |
| 298 | // within the same millisecond is the case it misses, and it is the case every |
| 299 | // mtime-based cache in the world misses. |
| 300 | // |
| 301 | // A stale font here would be worse than a slow one, which is why the key is per |
| 302 | // file and not a count: this module refuses to compile a book in a substitute |
| 303 | // font at all, on the grounds that the line breaks and the page count of what |
| 304 | // came back would not be the ones that print. A cache that quietly served the |
| 305 | // wrong face would be the same lie by a different route. |
| 306 | |
| 307 | /// Font bytes kept from the last gather, with the walk that justified them. |
| 308 | struct FontCache { |
| 309 | /// One line per font file: path, size and modification time. Any difference |
| 310 | /// at all re-reads the whole set. |
| 311 | key: String, |
| 312 | /// The bytes themselves, as `(workspace path, contents)`. |
| 313 | fonts: Vec<(String, Vec<u8>)>, |
| 314 | } |
| 315 | |
| 316 | thread_local! { |
| 317 | /// The fonts of the last project gathered, so a rebuild does not re-read them. |
| 318 | /// |
| 319 | /// One slot, not a map: a watch loop compiles ONE project over and over, and a |
| 320 | /// map keyed on project would hold every book of a long session in memory for |
| 321 | /// the sake of a rebuild nobody is waiting on. |
| 322 | static FONTS: RefCell<Option<FontCache>> = const { RefCell::new(None) }; |
| 323 | } |
| 324 | |
| 325 | /// Forget the cached fonts, so the next gather re-reads them. |
| 326 | /// |
| 327 | /// Nothing calls this in the ordinary course; it exists so a caller that has just |
| 328 | /// written a font file can say so, and so the cache is not the only thing standing |
| 329 | /// between a changed font and a compile. |
| 330 | pub fn forget_fonts() { |
| 331 | FONTS.with(|c| { *c.borrow_mut() = None; }); |
| 332 | } |
| 333 | |
| 334 | |
| 335 | // ── Paths ─────────────────────────────────────────────────────────────────── |
| 336 | |
| 337 | /// Collapse `.` and `..` in a slash path. |
| 338 | /// |
| 339 | /// `None` when the path climbs above the top, which for a workspace path means |
| 340 | /// out of the folder the user attached -- a condition worth a sentence of its |
| 341 | /// own rather than a silent clamp to the root. |
| 342 | fn norm(path: &str) -> Option<String> { |
| 343 | let mut out: Vec<&str> = Vec::new(); |
| 344 | for seg in path.split('/') { |
| 345 | match seg { |
| 346 | "" | "." => {}, |
| 347 | ".." => { if out.pop().is_none() { return None; } }, |
| 348 | s => out.push(s), |
| 349 | } |
| 350 | } |
| 351 | Some(out.join("/")) |
| 352 | } |
| 353 | |
| 354 | /// The directory part of a slash path, or the empty string at the top. |
| 355 | fn parent(path: &str) -> String { |
| 356 | match path.rfind('/') { |
| 357 | Some(i) => path[..i].to_string(), |
| 358 | None => String::new(), |
| 359 | } |
| 360 | } |
| 361 | |
| 362 | /// Resolve `rel` against directory `dir`, both workspace-relative. |
| 363 | fn join(dir: &str, rel: &str) -> Option<String> { |
| 364 | if dir.is_empty() { norm(rel) } else { norm(&fmt!("{}/{}", dir, rel)) } |
| 365 | } |
| 366 | |
| 367 | /// The lower-case extension of a path, without the dot. |
| 368 | fn ext(path: &str) -> String { |
| 369 | let name = match path.rfind('/') { |
| 370 | Some(i) => &path[i + 1..], |
| 371 | None => path, |
| 372 | }; |
| 373 | match name.rfind('.') { |
| 374 | Some(i) => name[i + 1..].to_ascii_lowercase(), |
| 375 | None => String::new(), |
| 376 | } |
| 377 | } |
| 378 | |
| 379 | /// The file name of a slash path, lower-cased. |
| 380 | fn leaf(path: &str) -> String { |
| 381 | match path.rfind('/') { |
| 382 | Some(i) => path[i + 1..].to_ascii_lowercase(), |
| 383 | None => path.to_ascii_lowercase(), |
| 384 | } |
| 385 | } |
| 386 | |
| 387 | /// How many segments deep a directory is. |
| 388 | fn depth(dir: &str) -> usize { |
| 389 | if dir.is_empty() { 0 } else { dir.split('/').count() } |
| 390 | } |
| 391 | |
| 392 | /// The deepest directory that contains both directories `a` and `b`. |
| 393 | fn common_of(a: &str, b: &str) -> String { |
| 394 | let sa: Vec<&str> = if a.is_empty() { Vec::new() } else { a.split('/').collect() }; |
| 395 | let sb: Vec<&str> = if b.is_empty() { Vec::new() } else { b.split('/').collect() }; |
| 396 | let n = sa.iter().zip(sb.iter()).take_while(|(x, y)| x == y).count(); |
| 397 | sa[..n].join("/") |
| 398 | } |
| 399 | |
| 400 | /// The deepest directory that contains every path in `paths`. |
| 401 | fn common_dir(paths: &[String]) -> String { |
| 402 | let mut common: Option<String> = None; |
| 403 | for p in paths { |
| 404 | let dir = parent(p); |
| 405 | common = Some(match common { |
| 406 | None => dir, |
| 407 | Some(c) => common_of(&c, &dir), |
| 408 | }); |
| 409 | } |
| 410 | common.unwrap_or_default() |
| 411 | } |
| 412 | |
| 413 | /// Express `path` relative to `root`, as the compiler's shadow filesystem wants |
| 414 | /// it: rooted at `/`, because that is where this build puts the project root. |
| 415 | /// |
| 416 | /// `None` when `path` is not inside `root`, which is also how containment is |
| 417 | /// asked here -- whole segments, so `alpha2` is not inside `alpha`. |
| 418 | fn under_root(root: &str, path: &str) -> Option<String> { |
| 419 | if root.is_empty() { |
| 420 | return Some(fmt!("/{}", path)); |
| 421 | } |
| 422 | if path == root { |
| 423 | return Some("/".to_string()); |
| 424 | } |
| 425 | let pre = fmt!("{}/", root); |
| 426 | path.strip_prefix(&pre).map(|r| fmt!("/{}", r)) |
| 427 | } |
| 428 | |
| 429 | /// `dir` and its ancestors, nearest first, stopping at `top` and never climbing |
| 430 | /// more than `up` levels. |
| 431 | fn chain(dir: &str, top: &str, up: usize) -> Vec<String> { |
| 432 | let mut out: Vec<String> = Vec::new(); |
| 433 | let mut cur = dir.to_string(); |
| 434 | loop { |
| 435 | if !out.contains(&cur) { out.push(cur.clone()); } |
| 436 | if cur == top || cur.is_empty() || out.len() > up { break; } |
| 437 | cur = parent(&cur); |
| 438 | } |
| 439 | out |
| 440 | } |
| 441 | |
| 442 | /// Where a reference that its own directory does not satisfy is looked for. |
| 443 | /// |
| 444 | /// The main file's folder comes first, because that is the book; then the folder |
| 445 | /// of whichever source named the reference; then upward from both, never above |
| 446 | /// the root. This is the whole of the root/search-path separation: the root can |
| 447 | /// sit as high as the imports need it to, and `"/assets/fonts"` still means the |
| 448 | /// one inside the book. |
| 449 | fn search_dirs(main_dir: &str, from_dir: &str, root: &str) -> Vec<String> { |
| 450 | let mut out = chain(main_dir, root, MAX_UP); |
| 451 | for d in chain(from_dir, root, MAX_UP) { |
| 452 | if !out.contains(&d) { out.push(d); } |
| 453 | } |
| 454 | out |
| 455 | } |
| 456 | |
| 457 | /// A shadow path for a root-relative reference: the literal itself, cleaned. |
| 458 | fn abs_shadow(lit: &str) -> Option<String> { |
| 459 | norm(lit).map(|p| fmt!("/{}", p)) |
| 460 | } |
| 461 | |
| 462 | /// Resolve `rel` against the shadow position of the file that names it. |
| 463 | /// |
| 464 | /// `None` when it climbs above the shadow root, which this compiler cannot |
| 465 | /// address -- and neither can the command-line one, for the same reason. |
| 466 | fn shadow_join(from_shadow: &str, rel: &str) -> Option<String> { |
| 467 | let dir = parent(from_shadow); |
| 468 | join(dir.trim_start_matches('/'), rel).map(|p| fmt!("/{}", p)) |
| 469 | } |
| 470 | |
| 471 | |
| 472 | // ── Reading a source for what it names ────────────────────────────────────── |
| 473 | |
| 474 | /// Every double-quoted literal in `src`, as `(start, end, raw text)` byte spans. |
| 475 | /// |
| 476 | /// `start` is the opening quote and `end` is one past the closing one, so a caller |
| 477 | /// that means to REPLACE a literal has the whole of it. The text is raw: escapes |
| 478 | /// are left as written, because the only caller that cares decodes them itself. |
| 479 | /// |
| 480 | /// Typst strings are double-quoted with backslash escapes, and a line comment or a |
| 481 | /// raw block may hold something that looks like one. Over-reading is safe here: a |
| 482 | /// literal that names nothing resolves to no file and is dropped, and the only cost |
| 483 | /// of a false one is a lookup that finds nothing. |
| 484 | fn quoted(src: &str) -> Vec<(usize, usize, &str)> { |
| 485 | let b = src.as_bytes(); |
| 486 | let mut out = Vec::new(); |
| 487 | let mut i = 0usize; |
| 488 | while i < b.len() { |
| 489 | if b[i] != b'"' { i += 1; continue; } |
| 490 | let start = i; |
| 491 | i += 1; |
| 492 | let from = i; |
| 493 | let mut closed = false; |
| 494 | while i < b.len() { |
| 495 | if b[i] == b'"' { closed = true; break; } |
| 496 | if b[i] == b'\\' && i + 1 < b.len() { i += 2; continue; } |
| 497 | if b[i] == b'\n' { break; } |
| 498 | i += 1; |
| 499 | } |
| 500 | if closed { |
| 501 | out.push((start, i + 1, &src[from..i])); |
| 502 | i += 1; |
| 503 | } else { |
| 504 | i = start + 1; |
| 505 | } |
| 506 | } |
| 507 | out |
| 508 | } |
| 509 | |
| 510 | /// A quoted literal's text, with backslash escapes taken literally. |
| 511 | /// |
| 512 | /// Only the separator matters for a path, so an escape is passed through rather |
| 513 | /// than decoded. |
| 514 | fn unescape(raw: &str) -> String { |
| 515 | let b = raw.as_bytes(); |
| 516 | let mut out = String::new(); |
| 517 | let mut i = 0usize; |
| 518 | while i < b.len() { |
| 519 | if b[i] == b'\\' && i + 1 < b.len() { |
| 520 | out.push(b[i + 1] as char); |
| 521 | i += 2; |
| 522 | continue; |
| 523 | } |
| 524 | out.push(b[i] as char); |
| 525 | i += 1; |
| 526 | } |
| 527 | out |
| 528 | } |
| 529 | |
| 530 | /// Every double-quoted literal in `src`, with the byte offset it begins at. |
| 531 | fn literals(src: &str) -> Vec<(usize, String)> { |
| 532 | quoted(src).into_iter().map(|(start, _, raw)| (start, unescape(raw))).collect() |
| 533 | } |
| 534 | |
| 535 | /// Every raw block and raw span in `src`, as byte spans. |
| 536 | /// |
| 537 | /// A run of N backticks opens a raw region that the next run of exactly N closes, |
| 538 | /// which is typst's own rule and the whole of what is needed here. A run with no |
| 539 | /// matching close opens nothing: a stray backtick in a comment must not make the |
| 540 | /// rest of the file invisible, and typst refuses an unterminated raw in any case. |
| 541 | fn raw_spans(src: &str) -> Vec<(usize, usize)> { |
| 542 | let b = src.as_bytes(); |
| 543 | let mut out = Vec::new(); |
| 544 | let mut i = 0usize; |
| 545 | while i < b.len() { |
| 546 | if b[i] != b'`' { i += 1; continue; } |
| 547 | let open = i; |
| 548 | let mut n = 0usize; |
| 549 | while i < b.len() && b[i] == b'`' { n += 1; i += 1; } |
| 550 | let mut j = i; |
| 551 | let mut end = None; |
| 552 | while j < b.len() { |
| 553 | if b[j] != b'`' { j += 1; continue; } |
| 554 | let mut m = 0usize; |
| 555 | while j < b.len() && b[j] == b'`' { m += 1; j += 1; } |
| 556 | if m == n { end = Some(j); break; } |
| 557 | } |
| 558 | match end { |
| 559 | Some(e) => { out.push((open, e)); i = e; }, |
| 560 | None => break, |
| 561 | } |
| 562 | } |
| 563 | out |
| 564 | } |
| 565 | |
| 566 | /// Whether byte `at` falls inside one of `spans`. |
| 567 | fn within(spans: &[(usize, usize)], at: usize) -> bool { |
| 568 | spans.iter().any(|(a, b)| at >= *a && at < *b) |
| 569 | } |
| 570 | |
| 571 | /// Whether the literal beginning at byte `at` is what an `#import` or `#include` |
| 572 | /// is being given. |
| 573 | /// |
| 574 | /// A book about Typst may quote `"@preview/cetz:0.3.4"` in its prose, and a |
| 575 | /// quotation must not become an import. The token immediately before the literal |
| 576 | /// is the whole of the syntax that decides it. |
| 577 | fn is_import_operand(src: &str, at: usize) -> bool { |
| 578 | let b = src.as_bytes(); |
| 579 | let mut i = at; |
| 580 | while i > 0 && (b[i - 1] as char).is_ascii_whitespace() { i -= 1; } |
| 581 | for kw in ["import", "include"] { |
| 582 | let n = kw.len(); |
| 583 | if i < n || &b[i - n..i] != kw.as_bytes() { continue; } |
| 584 | if i == n { return true; } |
| 585 | // A longer identifier that merely ENDS in "import" is not the keyword. |
| 586 | let p = b[i - n - 1]; |
| 587 | if !(p as char).is_ascii_alphanumeric() && p != b'_' && p != b'-' { return true; } |
| 588 | } |
| 589 | false |
| 590 | } |
| 591 | |
| 592 | |
| 593 | // ── Packages are carried, not fetched ─────────────────────────────────────── |
| 594 | // |
| 595 | // The module header sets out why the packages travel inside the bundle and why the |
| 596 | // import is re-pointed rather than resolved through the registry hook. What follows |
| 597 | // is the machinery: read the spec, find it in the compiled-in inventory, fetch the |
| 598 | // pack from this origin, and follow what IT imports. |
| 599 | // |
| 600 | // Nothing here consults `Reach`. A pack is part of the application, like the five |
| 601 | // bundled fonts, and is no more the user's file than the compiler wasm is -- so a |
| 602 | // turn confined to one folder can still draw a diagram, and the path jail is not |
| 603 | // asked a question about a file that was never on disk. |
| 604 | |
| 605 | /// A package as a source names it: `@preview/cetz:0.3.4`. |
| 606 | #[derive(Clone, PartialEq, Eq)] |
| 607 | struct Spec { |
| 608 | /// The registry namespace, which for everything carried here is `preview`. |
| 609 | ns: String, |
| 610 | /// The package name. |
| 611 | name: String, |
| 612 | /// The exact version. Typst has no version ranges: 0.3.2 and 0.3.4 are |
| 613 | /// different packages as far as an import is concerned. |
| 614 | version: String, |
| 615 | } |
| 616 | |
| 617 | impl Spec { |
| 618 | |
| 619 | /// Read a spec from a quoted literal, or `None` when it is not one. |
| 620 | fn parse(lit: &str) -> Option<Self> { |
| 621 | if !lit.starts_with('@') { return None; } |
| 622 | let rest = &lit[1..]; |
| 623 | let slash = match rest.find('/') { Some(i) => i, None => return None }; |
| 624 | let (ns, tail) = (&rest[..slash], &rest[slash + 1..]); |
| 625 | let colon = match tail.find(':') { Some(i) => i, None => return None }; |
| 626 | let (name, version) = (&tail[..colon], &tail[colon + 1..]); |
| 627 | if !Self::word(ns) || !Self::word(name) || !Self::semver(version) { return None; } |
| 628 | Some(Self { |
| 629 | ns: ns.to_string(), |
| 630 | name: name.to_string(), |
| 631 | version: version.to_string(), |
| 632 | }) |
| 633 | } |
| 634 | |
| 635 | /// Whether `s` is a namespace or a package name. |
| 636 | fn word(s: &str) -> bool { |
| 637 | !s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') |
| 638 | } |
| 639 | |
| 640 | /// Whether `s` is a `major.minor.patch` version. |
| 641 | fn semver(s: &str) -> bool { |
| 642 | let parts: Vec<&str> = s.split('.').collect(); |
| 643 | parts.len() == 3 |
| 644 | && parts.iter().all(|p| !p.is_empty() && p.chars().all(|c| c.is_ascii_digit())) |
| 645 | } |
| 646 | |
| 647 | /// The spec as a source spells it. |
| 648 | fn text(&self) -> String { |
| 649 | fmt!("@{}/{}:{}", self.ns, self.name, self.version) |
| 650 | } |
| 651 | |
| 652 | /// The spec as a person reads it. |
| 653 | fn plain(&self) -> String { |
| 654 | fmt!("{} {}", self.name, self.version) |
| 655 | } |
| 656 | |
| 657 | /// The shadow directory this package occupies. |
| 658 | fn dir(&self) -> String { |
| 659 | fmt!("{}/{}/{}/{}", PKG_ROOT, self.ns, self.name, self.version) |
| 660 | } |
| 661 | |
| 662 | /// The one-line module an import of this package is re-pointed at. |
| 663 | /// |
| 664 | /// Named for the PACKAGE, because a path import takes its binding from the file |
| 665 | /// stem -- so `#import "@preview/cetz:0.3.4"` goes on binding `cetz`, which is |
| 666 | /// what the document then writes. It sits beside the package rather than in it, |
| 667 | /// so it can never collide with a file the package itself ships. |
| 668 | fn shim(&self) -> String { |
| 669 | fmt!("{}/{}.typ", self.dir(), self.name) |
| 670 | } |
| 671 | } |
| 672 | |
| 673 | /// One line of the compiled-in inventory: a pack this build carries. |
| 674 | struct Vendored { |
| 675 | /// Which package, exactly. |
| 676 | spec: Spec, |
| 677 | /// How many files the pack holds. |
| 678 | files: usize, |
| 679 | /// How many bytes the pack itself is. |
| 680 | bytes: usize, |
| 681 | } |
| 682 | |
| 683 | /// Every package this build carries, in the order the inventory lists them. |
| 684 | fn vendored() -> Vec<Vendored> { |
| 685 | let mut out = Vec::new(); |
| 686 | for line in PKG_INDEX.lines() { |
| 687 | let f: Vec<&str> = line.split_whitespace().collect(); |
| 688 | if f.len() != 6 || f[0] != "pack" { continue; } |
| 689 | let files = match f[4].parse::<usize>() { Ok(n) => n, Err(_) => continue }; |
| 690 | let bytes = match f[5].parse::<usize>() { Ok(n) => n, Err(_) => continue }; |
| 691 | out.push(Vendored { |
| 692 | spec: Spec { |
| 693 | ns: f[1].to_string(), |
| 694 | name: f[2].to_string(), |
| 695 | version: f[3].to_string(), |
| 696 | }, |
| 697 | files, |
| 698 | bytes, |
| 699 | }); |
| 700 | } |
| 701 | out |
| 702 | } |
| 703 | |
| 704 | /// What this build carries, as a refusal reads it out. |
| 705 | fn carried() -> String { |
| 706 | let all = vendored(); |
| 707 | if all.is_empty() { return "no packages at all".to_string(); } |
| 708 | all.iter().map(|v| v.spec.plain()).collect::<Vec<String>>().join(", ") |
| 709 | } |
| 710 | |
| 711 | /// Which versions of `name` this build carries, in inventory order. |
| 712 | fn versions_of(name: &str) -> Vec<String> { |
| 713 | vendored().into_iter() |
| 714 | .filter(|v| v.spec.name == name) |
| 715 | .map(|v| v.spec.version) |
| 716 | .collect() |
| 717 | } |
| 718 | |
| 719 | /// Every package `src` imports, with the byte offset of the literal naming each. |
| 720 | /// |
| 721 | /// **The one place a source is read for packages**, so the walk that gathers them, |
| 722 | /// the scan that follows a package's own dependencies, and the rewrite that |
| 723 | /// re-points the import cannot disagree about what an import is. Three scanners |
| 724 | /// agreeing today would be three scanners disagreeing later -- and disagreeing here |
| 725 | /// means a package gathered and not re-pointed, or re-pointed and not gathered. |
| 726 | /// |
| 727 | /// A literal inside a raw block or a raw span is not an import. A document that |
| 728 | /// SHOWS `#import "@preview/cetz:0.3.4"` in a code example is describing one, not |
| 729 | /// making one, and refusing to compile a book because it quotes an import would be |
| 730 | /// the wrong message buying the wrong diagnosis all over again. |
| 731 | fn imports(src: &str) -> Vec<(usize, Spec)> { |
| 732 | if !src.contains('@') { return Vec::new(); } |
| 733 | let raws = raw_spans(src); |
| 734 | let mut out = Vec::new(); |
| 735 | for (start, _, raw) in quoted(src) { |
| 736 | let spec = match Spec::parse(raw) { Some(s) => s, None => continue }; |
| 737 | if !is_import_operand(src, start) { continue; } |
| 738 | if within(&raws, start) { continue; } |
| 739 | out.push((start, spec)); |
| 740 | } |
| 741 | out |
| 742 | } |
| 743 | |
| 744 | /// A pack as it arrives off the wire. |
| 745 | struct Pack { |
| 746 | /// The file the package declares as its entry, package-relative. |
| 747 | entry: String, |
| 748 | /// Every file it holds, as `(package-relative path, bytes)`. |
| 749 | files: Vec<(String, Vec<u8>)>, |
| 750 | } |
| 751 | |
| 752 | /// A package, laid out for the compiler and read for what it imports in turn. |
| 753 | struct Ready { |
| 754 | /// Shadow sources: the package's `.typ` files, re-pointed, plus the one-line |
| 755 | /// module that carries the binding. |
| 756 | sources: Vec<(String, String)>, |
| 757 | /// Shadow files that are not sources -- the manifest, the licence, and anything |
| 758 | /// a package might `read`. |
| 759 | assets: Vec<(String, Vec<u8>)>, |
| 760 | /// What this package imports, with the file of its own that names each. THE |
| 761 | /// CLOSURE COMES FROM HERE and from nowhere else. |
| 762 | deps: Vec<(Spec, String)>, |
| 763 | } |
| 764 | |
| 765 | thread_local! { |
| 766 | /// The packages read in this page so far. |
| 767 | /// |
| 768 | /// A pack is a sealed file of the build and cannot change under a running page, |
| 769 | /// so this is a cache with no invalidation and needs none. It matters for the |
| 770 | /// watch loop: without it every rebuild would re-fetch and re-scan 900 KB of |
| 771 | /// package source that is byte-for-byte what it was a second earlier. |
| 772 | static PACKS: RefCell<Vec<(Spec, Rc<Ready>)>> = const { RefCell::new(Vec::new()) }; |
| 773 | } |
| 774 | |
| 775 | // ── Why these three answer in a String and not an `Outcome` ───────────────── |
| 776 | // |
| 777 | // Everything that can go wrong reading a pack ends up in the middle of a sentence a |
| 778 | // PERSON reads -- "…but its files could not be read from this device: <this bit>". |
| 779 | // A fe2o3 error rendered with `fmt!("{}", e)` is `LocalErr{[Invalid Data] "…"}`, ANSI |
| 780 | // colour codes and the source position of the Rust line that raised it and all, and |
| 781 | // dropping that into a sentence is precisely the failure `driver_error` further down |
| 782 | // this file was written to stop: a message about the machinery in place of a message |
| 783 | // about the problem. So the reason travels as the clause it is going to become. |
| 784 | |
| 785 | /// Fetch a pack from this origin, or say why it could not be. |
| 786 | /// |
| 787 | /// The URL is built from the compiled-in inventory and never from the document, so |
| 788 | /// there is no literal a source could write that would make this reach anywhere |
| 789 | /// else; and it is relative, so it resolves against the page's own base. |
| 790 | async fn fetch_pack(v: &Vendored) -> Result<Vec<u8>, String> { |
| 791 | use web_sys::{Request, RequestInit, RequestMode, Response}; |
| 792 | |
| 793 | let url = fmt!("{}/{}/{}/{}.pack", PKG_URL, v.spec.ns, v.spec.name, v.spec.version); |
| 794 | let opts = RequestInit::new(); |
| 795 | opts.set_method("GET"); |
| 796 | opts.set_mode(RequestMode::SameOrigin); |
| 797 | let req = match Request::new_with_str_and_init(&url, &opts) { |
| 798 | Ok(r) => r, |
| 799 | Err(e) => return Err(fmt!("asking for {} failed, {}", url, js_str(&e))), |
| 800 | }; |
| 801 | let win = match web_sys::window() { |
| 802 | Some(w) => w, |
| 803 | None => return Err("there is no browser window to read it with".to_string()), |
| 804 | }; |
| 805 | let val = match JsFuture::from(win.fetch_with_request(&req)).await { |
| 806 | Ok(v) => v, |
| 807 | Err(e) => return Err(fmt!("{} could not be reached, {}", url, js_str(&e))), |
| 808 | }; |
| 809 | let resp: Response = match val.dyn_into() { |
| 810 | Ok(r) => r, |
| 811 | Err(_) => return Err(fmt!("asking for {} did not answer with a response", url)), |
| 812 | }; |
| 813 | if !resp.ok() { |
| 814 | return Err(fmt!("{} answered {}", url, resp.status())); |
| 815 | } |
| 816 | let promise = match resp.array_buffer() { |
| 817 | Ok(p) => p, |
| 818 | Err(e) => return Err(fmt!("reading {} failed, {}", url, js_str(&e))), |
| 819 | }; |
| 820 | match JsFuture::from(promise).await { |
| 821 | Ok(b) => Ok(js_sys::Uint8Array::new(&b).to_vec()), |
| 822 | Err(e) => Err(fmt!("reading {} failed, {}", url, js_str(&e))), |
| 823 | } |
| 824 | } |
| 825 | |
| 826 | /// Read a pack: an ASCII header, one blank line, then the file bodies concatenated |
| 827 | /// in the order the header lists them. |
| 828 | /// |
| 829 | /// Everything is checked against the inventory line that asked for it -- the name, |
| 830 | /// the version, the file count and the byte length -- because a pack that does not |
| 831 | /// match the build's own record of it is a broken deployment, and that is a |
| 832 | /// different thing from a package nobody vendored. |
| 833 | /// |
| 834 | /// # Arguments |
| 835 | /// * `bytes` - The pack as fetched. |
| 836 | /// * `v` - The inventory line this was fetched for. |
| 837 | fn parse_pack(bytes: &[u8], v: &Vendored) -> Result<Pack, String> { |
| 838 | if bytes.len() != v.bytes { |
| 839 | return Err(fmt!( |
| 840 | "it is {} bytes and this build was sealed with {}", bytes.len(), v.bytes)); |
| 841 | } |
| 842 | let mut split = None; |
| 843 | for i in 0..bytes.len().saturating_sub(1) { |
| 844 | if bytes[i] == b'\n' && bytes[i + 1] == b'\n' { split = Some(i); break; } |
| 845 | } |
| 846 | let split = match split { Some(i) => i, None => return Err("it has no header".to_string()) }; |
| 847 | let head = String::from_utf8_lossy(&bytes[..split]).to_string(); |
| 848 | let mut lines = head.lines(); |
| 849 | match lines.next() { |
| 850 | Some("DAIMOND TYPST PACK 1") => {}, |
| 851 | _ => return Err("it is not a pack this build knows how to read".to_string()), |
| 852 | } |
| 853 | let mut entry = String::new(); |
| 854 | let mut names: Vec<(String, usize)> = Vec::new(); |
| 855 | let mut got = Spec { ns: String::new(), name: String::new(), version: String::new() }; |
| 856 | for line in lines { |
| 857 | let (key, rest) = match line.find(' ') { |
| 858 | Some(i) => (&line[..i], line[i + 1..].trim()), |
| 859 | None => continue, |
| 860 | }; |
| 861 | match key { |
| 862 | "namespace" => got.ns = rest.to_string(), |
| 863 | "name" => got.name = rest.to_string(), |
| 864 | "version" => got.version = rest.to_string(), |
| 865 | "entrypoint" => entry = rest.trim_start_matches('/').to_string(), |
| 866 | "file" => { |
| 867 | let (len, path) = match rest.find(' ') { |
| 868 | Some(i) => (&rest[..i], rest[i + 1..].to_string()), |
| 869 | None => continue, |
| 870 | }; |
| 871 | let len = match len.parse::<usize>() { Ok(n) => n, Err(_) => continue }; |
| 872 | names.push((path, len)); |
| 873 | }, |
| 874 | _ => {}, |
| 875 | } |
| 876 | } |
| 877 | if got != v.spec { |
| 878 | return Err(fmt!( |
| 879 | "it holds {} and this build asked for {}", got.plain(), v.spec.plain())); |
| 880 | } |
| 881 | if entry.is_empty() { |
| 882 | return Err("it names no entrypoint".to_string()); |
| 883 | } |
| 884 | if names.len() != v.files { |
| 885 | return Err(fmt!( |
| 886 | "it holds {} files and this build was sealed with {}", names.len(), v.files)); |
| 887 | } |
| 888 | let body = &bytes[split + 2..]; |
| 889 | let total: usize = names.iter().map(|(_, n)| *n).sum(); |
| 890 | if total != body.len() { |
| 891 | return Err(fmt!( |
| 892 | "its header accounts for {} bytes and it carries {}", total, body.len())); |
| 893 | } |
| 894 | let mut files = Vec::with_capacity(names.len()); |
| 895 | let mut at = 0usize; |
| 896 | for (path, len) in names.into_iter() { |
| 897 | files.push((path, body[at..at + len].to_vec())); |
| 898 | at += len; |
| 899 | } |
| 900 | if !files.iter().any(|(p, _)| *p == entry) { |
| 901 | return Err(fmt!("its entrypoint {} is not among its files", entry)); |
| 902 | } |
| 903 | Ok(Pack { entry, files }) |
| 904 | } |
| 905 | |
| 906 | /// Re-point every package and package-root reference in `text`. |
| 907 | /// |
| 908 | /// # Arguments |
| 909 | /// * `text` - The source as it was written. |
| 910 | /// * `inside` - When this source is a package's own file: the shadow directory that |
| 911 | /// package sits at, and every path it holds. `None` for a project's own source. |
| 912 | fn repoint(text: &str, inside: Option<(&str, &[String])>) -> String { |
| 913 | // The imports come from the one scanner, so what is re-pointed here is exactly |
| 914 | // what was gathered; the raw spans are re-taken for the second rule below. |
| 915 | let imps = imports(text); |
| 916 | let raws = raw_spans(text); |
| 917 | let mut out = String::new(); |
| 918 | let mut last = 0usize; |
| 919 | for (start, end, raw) in quoted(text) { |
| 920 | // Re-pointed whether or not the package turned out to be carried, because a |
| 921 | // gather that found one missing refuses before anything is compiled. |
| 922 | let rep = match imps.iter().find(|(o, _)| *o == start) { |
| 923 | Some((_, spec)) => Some(spec.shim()), |
| 924 | None => match inside { |
| 925 | // Inside a package a leading "/" means the PACKAGE root, not the |
| 926 | // project's. Re-pointed only when it really names a file the pack |
| 927 | // holds, so a string of prose beginning with a slash is left alone -- |
| 928 | // fletcher's `"/"` is a mark name, not a path. |
| 929 | Some((dir, names)) if raw.starts_with('/') && !within(&raws, start) => { |
| 930 | match norm(raw) { |
| 931 | Some(p) if names.iter().any(|n| *n == p) => { |
| 932 | Some(fmt!("{}/pkg/{}", dir, p)) |
| 933 | }, |
| 934 | _ => None, |
| 935 | } |
| 936 | }, |
| 937 | _ => None, |
| 938 | }, |
| 939 | }; |
| 940 | if let Some(r) = rep { |
| 941 | out.push_str(&text[last..start]); |
| 942 | out.push('"'); |
| 943 | out.push_str(&r); |
| 944 | out.push('"'); |
| 945 | last = end; |
| 946 | } |
| 947 | } |
| 948 | out.push_str(&text[last..]); |
| 949 | out |
| 950 | } |
| 951 | |
| 952 | /// Lay a pack out for the compiler and read it for what it imports in turn. |
| 953 | fn prepare(spec: &Spec, pack: &Pack) -> Ready { |
| 954 | let dir = spec.dir(); |
| 955 | let names: Vec<String> = pack.files.iter().map(|(p, _)| p.clone()).collect(); |
| 956 | let mut sources: Vec<(String, String)> = Vec::new(); |
| 957 | let mut assets: Vec<(String, Vec<u8>)> = Vec::new(); |
| 958 | let mut deps: Vec<(Spec, String)> = Vec::new(); |
| 959 | for (rel, data) in pack.files.iter() { |
| 960 | let shadow = fmt!("{}/pkg/{}", dir, rel); |
| 961 | if ext(rel) != "typ" { |
| 962 | assets.push((shadow, data.clone())); |
| 963 | continue; |
| 964 | } |
| 965 | let text = String::from_utf8_lossy(data).to_string(); |
| 966 | for (_, dep) in imports(&text) { |
| 967 | if dep == *spec || deps.iter().any(|(d, _)| *d == dep) { continue; } |
| 968 | deps.push((dep, rel.clone())); |
| 969 | } |
| 970 | sources.push((shadow, repoint(&text, Some((dir.as_str(), names.as_slice()))))); |
| 971 | } |
| 972 | // The binding, and the only file here that was not written by the package's |
| 973 | // authors. A star import re-exports: the shim's own scope becomes whatever the |
| 974 | // entrypoint exports, which is what the document then reaches through. |
| 975 | sources.push((spec.shim(), fmt!("#import \"pkg/{}\": *\n", pack.entry))); |
| 976 | Ready { sources, assets, deps } |
| 977 | } |
| 978 | |
| 979 | /// The package `v` names, fetched and laid out, or the clause saying why not. |
| 980 | async fn package(v: &Vendored) -> Result<Rc<Ready>, String> { |
| 981 | let hit = PACKS.with(|c| c.borrow().iter() |
| 982 | .find(|(s, _)| *s == v.spec) |
| 983 | .map(|(_, r)| r.clone())); |
| 984 | if let Some(r) = hit { return Ok(r); } |
| 985 | let bytes = ok!(fetch_pack(v).await); |
| 986 | let pack = ok!(parse_pack(&bytes, v)); |
| 987 | let ready = Rc::new(prepare(&v.spec, &pack)); |
| 988 | PACKS.with(|c| c.borrow_mut().push((v.spec.clone(), ready.clone()))); |
| 989 | Ok(ready) |
| 990 | } |
| 991 | |
| 992 | /// Why a package the document reaches for is not available, said differently |
| 993 | /// depending on WHOSE gap it is. |
| 994 | /// |
| 995 | /// Three cases, and keeping them apart is the whole point of this function. A |
| 996 | /// document asking for something nobody vendored is the author's decision to work |
| 997 | /// around; a document asking for a version next to one that IS here is a one-word |
| 998 | /// edit; and a package that was found, loaded, and then wanted something else is not |
| 999 | /// the author's fault at all -- and looks identical to the first case unless it is |
| 1000 | /// said not to be. |
| 1001 | /// |
| 1002 | /// # Arguments |
| 1003 | /// * `spec` - What could not be supplied. |
| 1004 | /// * `via` - The packages between the document and `spec`, nearest the DOCUMENT first, |
| 1005 | /// each with the file of its own that names the next link. Empty when the document |
| 1006 | /// asked for `spec` itself. |
| 1007 | /// * `from` - The workspace file the whole chain started in. |
| 1008 | fn unavailable(spec: &Spec, via: &[(Spec, String)], from: &str) -> String { |
| 1009 | if let Some((first, _)) = via.first() { |
| 1010 | // Read the chain out link by link, because "cetz is here but its dependency |
| 1011 | // is not" is only convincing if the reader can see which dependency of what. |
| 1012 | let mut chain = String::new(); |
| 1013 | for (i, (pkg, file)) in via.iter().enumerate() { |
| 1014 | let next = match via.get(i + 1) { |
| 1015 | Some((n, _)) => n.plain(), |
| 1016 | None => spec.plain(), |
| 1017 | }; |
| 1018 | if i == 0 { |
| 1019 | chain.push_str(&fmt!("{}'s {} imports {}", pkg.plain(), file, next)); |
| 1020 | } else { |
| 1021 | chain.push_str(&fmt!(", whose {} imports {}", file, next)); |
| 1022 | } |
| 1023 | } |
| 1024 | let head = match via.last() { Some((p, _)) => p.plain(), None => first.plain() }; |
| 1025 | // The near miss inside a near miss: the right package at the wrong version, |
| 1026 | // reached through another package. cetz is carried twice for exactly this |
| 1027 | // reason, and saying only "not carried" would send somebody looking for a |
| 1028 | // package that is sitting right there under a different number. |
| 1029 | let others = versions_of(&spec.name); |
| 1030 | let near = if others.is_empty() { |
| 1031 | String::new() |
| 1032 | } else { |
| 1033 | fmt!(" This build does carry {} at {} -- a different package, as far as an import is \ |
| 1034 | concerned, and not one {} would accept.", |
| 1035 | spec.name, others.join(" and "), head) |
| 1036 | }; |
| 1037 | return fmt!( |
| 1038 | "'{}' imports {}, and this build carries it. {} -- and {} is NOT carried, so {} \ |
| 1039 | cannot be loaded either. Nothing was compiled.\n\n\ |
| 1040 | THIS IS NOT A PROBLEM WITH YOUR DOCUMENT. {} was found and read; what is missing is \ |
| 1041 | the package IT names in turn. A package that resolves while its own dependency does \ |
| 1042 | not looks exactly like a package that was never there, which is why this is said in \ |
| 1043 | different words: there is nothing to change in your source, no folder to attach and \ |
| 1044 | no path to correct.{} This build carries {}. The fix is to vendor {} beside {} -- see \ |
| 1045 | www/assets/typst/refresh.sh -- or to compile this document with the command-line \ |
| 1046 | typst, which can fetch it.", |
| 1047 | from, first.plain(), chain, spec.plain(), head, |
| 1048 | head, near, carried(), spec.plain(), head); |
| 1049 | } |
| 1050 | let others = versions_of(&spec.name); |
| 1051 | if !others.is_empty() { |
| 1052 | return fmt!( |
| 1053 | "'{}' imports '{}'. This build carries {} at {}, but not at {}. Nothing was compiled.\n\n\ |
| 1054 | A Typst package version is exact -- {} and {} are different packages as far as an \ |
| 1055 | import is concerned -- so this is not a near miss that would have worked anyway. \ |
| 1056 | Either import a version carried here, or compile this document with the command-line \ |
| 1057 | typst, which can fetch the one you asked for. Daimond carries {}.", |
| 1058 | from, spec.text(), spec.name, others.join(" and "), spec.version, |
| 1059 | others[0], spec.version, carried()); |
| 1060 | } |
| 1061 | fmt!( |
| 1062 | "'{}' imports '{}'. Names beginning '@' come from Typst Universe, a registry the \ |
| 1063 | command-line compiler downloads from and caches; this compiler runs inside the page with \ |
| 1064 | no network at all, so the only packages it has are the ones Daimond carries in its own \ |
| 1065 | bundle. This build carries {}, and {} is not among them. Nothing was compiled.\n\n\ |
| 1066 | So this is not a missing file, not a path problem and not a root problem, and no amount \ |
| 1067 | of moving files or attaching folders will fix it: do not go looking, and do not rewrite \ |
| 1068 | the source to work around it. Compile this document with the command-line typst, which \ |
| 1069 | can fetch the package -- or copy what it provides into the project as ordinary files and \ |
| 1070 | import it by path. Vendoring it into Daimond is the third way: \ |
| 1071 | www/assets/typst/refresh.sh says how.", |
| 1072 | from, spec.text(), carried(), spec.name) |
| 1073 | } |
| 1074 | |
| 1075 | /// A package this build does carry, whose files could not be read from this device. |
| 1076 | /// |
| 1077 | /// Its own sentence, because it is the only one of these that is nobody's decision: |
| 1078 | /// the bundle says the package is here and the bundle is wrong about itself. |
| 1079 | /// |
| 1080 | /// # Arguments |
| 1081 | /// * `spec` - The package whose pack would not read. |
| 1082 | /// * `via` - The packages between the document and `spec`, as [`unavailable`] takes them. |
| 1083 | /// * `from` - The workspace file the chain started in. |
| 1084 | /// * `why` - What went wrong reading it, in the words the read itself used. |
| 1085 | fn pack_broken(spec: &Spec, via: &[(Spec, String)], from: &str, why: &str) -> String { |
| 1086 | let reached = match via.first() { |
| 1087 | Some((f, _)) => fmt!("imports {}, which needs '{}'", f.plain(), spec.text()), |
| 1088 | None => fmt!("imports '{}'", spec.text()), |
| 1089 | }; |
| 1090 | fmt!( |
| 1091 | "'{}' {} -- and this build does carry it, but its files could not be read from this \ |
| 1092 | device: {}. Nothing was compiled.\n\n\ |
| 1093 | That is a broken installation rather than anything about the document. The packages ship \ |
| 1094 | as sealed files under assets/typst/packs/ and are covered by the bundle manifest, so \ |
| 1095 | /verify.html will have more to say about it. Reload the page; if it happens again, the \ |
| 1096 | deployment is missing files it was sealed with.", |
| 1097 | from, reached, why) |
| 1098 | } |
| 1099 | |
| 1100 | /// What a project's packages came to, once the closure was walked. |
| 1101 | struct Packages { |
| 1102 | /// Shadow sources to hand over alongside the project's own. |
| 1103 | sources: Vec<(String, String)>, |
| 1104 | /// Shadow files that are not sources. |
| 1105 | assets: Vec<(String, Vec<u8>)>, |
| 1106 | } |
| 1107 | |
| 1108 | /// What the package walk produced. |
| 1109 | enum Closure { |
| 1110 | /// The closure, gathered whole. |
| 1111 | Ready(Packages), |
| 1112 | /// Nothing was gathered, and this is why. |
| 1113 | Refused(String), |
| 1114 | } |
| 1115 | |
| 1116 | /// Gather the transitive closure of the packages `srcs` import. |
| 1117 | /// |
| 1118 | /// The document's own imports are taken in the order it makes them, and each pack |
| 1119 | /// that arrives is read for the imports IT makes, which go on the end of the same |
| 1120 | /// queue. So the first thing a refusal is about is the first thing the document |
| 1121 | /// asked for, and a dependency is never assumed from a list somebody wrote down. |
| 1122 | /// |
| 1123 | /// **Nothing is partial.** The first package that cannot be supplied stops the walk |
| 1124 | /// and returns a refusal, because a closure gathered up to a hole and then compiled |
| 1125 | /// would fail somewhere else entirely, with a message about whatever the hole made |
| 1126 | /// undefined. |
| 1127 | /// |
| 1128 | /// # Arguments |
| 1129 | /// * `srcs` - The project's own sources, already gathered. |
| 1130 | async fn packages(srcs: &[Src]) -> Closure { |
| 1131 | // `want` is the queue AND the record of what has been queued, so a package |
| 1132 | // reached twice by two routes is read once and keeps the route it was first |
| 1133 | // reached by -- which is the shorter one, and the one a refusal should describe. |
| 1134 | let mut want: Vec<(Spec, Vec<(Spec, String)>, String)> = Vec::new(); |
| 1135 | for s in srcs.iter() { |
| 1136 | for (_, spec) in imports(&s.text) { |
| 1137 | if want.iter().any(|(sp, _, _)| *sp == spec) { continue; } |
| 1138 | want.push((spec, Vec::new(), s.real.clone())); |
| 1139 | } |
| 1140 | } |
| 1141 | if want.is_empty() { |
| 1142 | return Closure::Ready(Packages { sources: Vec::new(), assets: Vec::new() }); |
| 1143 | } |
| 1144 | let inventory = vendored(); |
| 1145 | let mut sources: Vec<(String, String)> = Vec::new(); |
| 1146 | let mut assets: Vec<(String, Vec<u8>)> = Vec::new(); |
| 1147 | let mut bytes = 0usize; |
| 1148 | let mut at = 0usize; |
| 1149 | while at < want.len() { |
| 1150 | let (spec, via, from) = want[at].clone(); |
| 1151 | at += 1; |
| 1152 | let v = match inventory.iter().find(|v| v.spec == spec) { |
| 1153 | Some(v) => v, |
| 1154 | None => return Closure::Refused(unavailable(&spec, &via, &from)), |
| 1155 | }; |
| 1156 | let ready = match package(v).await { |
| 1157 | Ok(r) => r, |
| 1158 | Err(w) => return Closure::Refused(pack_broken(&spec, &via, &from, &w)), |
| 1159 | }; |
| 1160 | for (dep, named_by) in ready.deps.iter() { |
| 1161 | if want.iter().any(|(sp, _, _)| *sp == *dep) { continue; } |
| 1162 | let mut chain = via.clone(); |
| 1163 | chain.push((spec.clone(), named_by.clone())); |
| 1164 | want.push((dep.clone(), chain, from.clone())); |
| 1165 | } |
| 1166 | for (path, text) in ready.sources.iter() { |
| 1167 | bytes += text.len(); |
| 1168 | sources.push((path.clone(), text.clone())); |
| 1169 | } |
| 1170 | for (path, data) in ready.assets.iter() { |
| 1171 | bytes += data.len(); |
| 1172 | assets.push((path.clone(), data.clone())); |
| 1173 | } |
| 1174 | if sources.len() + assets.len() > MAX_PKG_FILES || bytes > MAX_PKG_BYTES { |
| 1175 | return Closure::Refused(fmt!( |
| 1176 | "The packages this document imports come to more than {} files or more than {} MB, \ |
| 1177 | which is past what this compiler carries. Nothing was compiled. That is a limit on \ |
| 1178 | DAIMOND'S OWN bundle rather than on the document, so it means the vendored set has \ |
| 1179 | grown past what was intended -- see www/assets/typst/refresh.sh.", |
| 1180 | MAX_PKG_FILES, MAX_PKG_BYTES / (1024 * 1024))); |
| 1181 | } |
| 1182 | } |
| 1183 | Closure::Ready(Packages { sources, assets }) |
| 1184 | } |
| 1185 | |
| 1186 | |
| 1187 | // ── How far a gather may reach ────────────────────────────────────────────── |
| 1188 | |
| 1189 | /// How far a gather may reach, since it follows paths the call never named. |
| 1190 | /// |
| 1191 | /// The tool guard can only check the paths a call NAMES, and a project is a |
| 1192 | /// closure: one path goes in and a hundred files are read. `file_search` and |
| 1193 | /// `file_glob` have exactly this shape and answer it by re-asking the turn about |
| 1194 | /// every entry they reach, so this re-asks too rather than inventing a second |
| 1195 | /// convention. Dispatching the model's `typst_compile` at the gatherer without |
| 1196 | /// this would have widened one named read into a walk that could climb out of a |
| 1197 | /// chat's folder by writing `#import "../../elsewhere.typ"` in a source. |
| 1198 | pub enum Reach<'a> { |
| 1199 | /// Anywhere in the workspace: the page's own Compile button, which is the |
| 1200 | /// user opening a file they marked in themselves. |
| 1201 | Workspace, |
| 1202 | /// Only what this turn may read, and never above its compartment. |
| 1203 | Turn(&'a ToolContext), |
| 1204 | } |
| 1205 | |
| 1206 | impl<'a> Reach<'a> { |
| 1207 | |
| 1208 | /// The deepest directory this gather may not climb above. |
| 1209 | fn floor(&self) -> String { |
| 1210 | match self { |
| 1211 | Self::Workspace => String::new(), |
| 1212 | Self::Turn(ctx) => norm(&ctx.path_prefix).unwrap_or_default(), |
| 1213 | } |
| 1214 | } |
| 1215 | |
| 1216 | /// Whether `path`, workspace-relative and normalised, may be read. |
| 1217 | fn allows(&self, path: &str) -> bool { |
| 1218 | match self { |
| 1219 | Self::Workspace => true, |
| 1220 | Self::Turn(ctx) => { |
| 1221 | let floor = self.floor(); |
| 1222 | // A compartment and an allow-list are two ways of saying where a turn |
| 1223 | // lives, and a path is measured against one of them and never both -- |
| 1224 | // `Tool::scoped` records why at length. |
| 1225 | if floor.is_empty() { |
| 1226 | ctx.may_read(path) |
| 1227 | } else { |
| 1228 | under_root(&floor, path).is_some() |
| 1229 | } |
| 1230 | }, |
| 1231 | } |
| 1232 | } |
| 1233 | } |
| 1234 | |
| 1235 | |
| 1236 | // ── The gathered project ──────────────────────────────────────────────────── |
| 1237 | |
| 1238 | /// Where a gathered source sits in the compiler's shadow filesystem. |
| 1239 | /// |
| 1240 | /// Two anchors rather than one, because a root-relative import names its own |
| 1241 | /// position: `#import "/style/x.typ"` must be readable at `/style/x.typ` however |
| 1242 | /// the root came out, while an ordinary import is placed where it really sits, |
| 1243 | /// re-based on the root. A file's relative imports are resolved against its own |
| 1244 | /// anchor, so the two kinds nest without either one knowing about the other. |
| 1245 | #[derive(Clone)] |
| 1246 | enum Anchor { |
| 1247 | /// Under the project root: the shadow path is the workspace path, re-based. |
| 1248 | Root, |
| 1249 | /// At a position a root-relative reference named. |
| 1250 | Fixed(String), |
| 1251 | } |
| 1252 | |
| 1253 | /// One source, as read on this side. |
| 1254 | struct Src { |
| 1255 | /// Workspace path the bytes came from. |
| 1256 | real: String, |
| 1257 | /// Where the compiler will see it. |
| 1258 | anchor: Anchor, |
| 1259 | /// The text itself. |
| 1260 | text: String, |
| 1261 | } |
| 1262 | |
| 1263 | /// A project, read on this side and ready to hand across as contents. |
| 1264 | struct Project { |
| 1265 | /// Workspace-relative directory that becomes the compiler's project root. |
| 1266 | root: String, |
| 1267 | /// The file to compile, as a shadow path under that root. |
| 1268 | main: String, |
| 1269 | /// `.typ` files, as (shadow path, text). The project's own first, then the |
| 1270 | /// vendored packages it imports, which the compiler cannot tell apart from any |
| 1271 | /// other source and has no reason to. |
| 1272 | sources: Vec<(String, String)>, |
| 1273 | /// Everything else the sources name, as (shadow path, bytes), plus the non-source |
| 1274 | /// files of those packages. |
| 1275 | assets: Vec<(String, Vec<u8>)>, |
| 1276 | /// Font files, as (workspace path, bytes). Fonts live in the compiler's |
| 1277 | /// font book, not its filesystem, so they carry no shadow path. |
| 1278 | fonts: Vec<(String, Vec<u8>)>, |
| 1279 | /// Where fonts were looked for, so a refusal can say where to put one. |
| 1280 | font_dirs: Vec<String>, |
| 1281 | /// Which folders a root-relative reference was searched in, so a refusal can |
| 1282 | /// say where it looked rather than only that it failed. |
| 1283 | searched: Vec<String>, |
| 1284 | /// Every REAL workspace path this compile read, so a watcher knows what to poll. |
| 1285 | /// |
| 1286 | /// The rest of this struct carries shadow paths, which address nothing on disk |
| 1287 | /// -- deliberately, and the module header says why at length. A watch loop |
| 1288 | /// needs the other kind: the file the user is editing, spelled the way the |
| 1289 | /// workspace spells it. It is the gatherer's answer because the gatherer is |
| 1290 | /// the only thing that knows which files a document actually reaches; a |
| 1291 | /// watcher that guessed from the directory would poll a build output and a |
| 1292 | /// backup and miss an import three folders up. |
| 1293 | watch: Vec<String>, |
| 1294 | } |
| 1295 | |
| 1296 | /// What the client should DO about a refusal, beside being told about it. |
| 1297 | /// |
| 1298 | /// Prose is not an action. The refusal that prompted this said, correctly, to |
| 1299 | /// open the folder above the one attached; the daimon reading it concluded the |
| 1300 | /// compiler "can only handle self-contained single files" and told the user to |
| 1301 | /// attach a folder that was already in the workspace and named in the same |
| 1302 | /// sentence. The translation from advice to action is where it went wrong, so |
| 1303 | /// the action is carried alongside the words instead of being left to be |
| 1304 | /// inferred from them. |
| 1305 | enum Remedy { |
| 1306 | /// Mark in the folder ABOVE the one the workspace holds, because the project |
| 1307 | /// reaches past it. Carries the file that reaches and what it reaches for. |
| 1308 | MarkAbove { |
| 1309 | /// The source that climbs out, workspace-relative. |
| 1310 | from: String, |
| 1311 | /// What it names. |
| 1312 | what: String, |
| 1313 | }, |
| 1314 | } |
| 1315 | |
| 1316 | impl Remedy { |
| 1317 | |
| 1318 | /// The stable action word a client dispatches on. |
| 1319 | fn action(&self) -> &'static str { |
| 1320 | match self { |
| 1321 | Self::MarkAbove { .. } => "mark-above", |
| 1322 | } |
| 1323 | } |
| 1324 | |
| 1325 | /// The path the action is about. |
| 1326 | fn subject(&self) -> String { |
| 1327 | match self { |
| 1328 | Self::MarkAbove { from, .. } => parent(from), |
| 1329 | } |
| 1330 | } |
| 1331 | |
| 1332 | /// One line a model can act on without parsing English. |
| 1333 | /// |
| 1334 | /// Deliberately the LAST line and deliberately dull: a model that reads only |
| 1335 | /// the prose loses nothing, and one that looks for an action finds it in the |
| 1336 | /// same shape every time. |
| 1337 | fn line(&self) -> String { |
| 1338 | match self { |
| 1339 | Self::MarkAbove { from, what } => { |
| 1340 | let folder = self.subject(); |
| 1341 | let folder = if folder.is_empty() { ".".to_string() } else { folder }; |
| 1342 | fmt!("REMEDY mark-above folder={} because={} needs={}", folder, from, what) |
| 1343 | }, |
| 1344 | } |
| 1345 | } |
| 1346 | } |
| 1347 | |
| 1348 | /// What a gather produced. |
| 1349 | /// |
| 1350 | /// A refusal is a first-class result rather than an error, because most of them |
| 1351 | /// are answers to the user -- the wrong folder is marked in, a font is not there |
| 1352 | /// -- and one of them carries an action the client can offer. Squeezing that |
| 1353 | /// through a formatted error string would mean parsing back what was just |
| 1354 | /// written. |
| 1355 | enum Gathered { |
| 1356 | /// A project ready to compile. |
| 1357 | Ready(Project), |
| 1358 | /// Nothing was gathered, and this is why. |
| 1359 | Refused { |
| 1360 | /// The reason, in the language the model and the user both read. |
| 1361 | why: String, |
| 1362 | /// What to do about it, when there is something to do. |
| 1363 | remedy: Option<Remedy>, |
| 1364 | }, |
| 1365 | } |
| 1366 | |
| 1367 | /// Refuse, with no action to offer. |
| 1368 | fn refuse(why: String) -> Gathered { |
| 1369 | Gathered::Refused { why, remedy: None } |
| 1370 | } |
| 1371 | |
| 1372 | /// Read a file as text, or `None` when it is not there. |
| 1373 | async fn read_text(root: FileRoot, path: &str) -> Option<String> { |
| 1374 | match opfs::read_file(root, path).await { |
| 1375 | Ok(b) => Some(String::from_utf8_lossy(&b).to_string()), |
| 1376 | Err(_) => None, |
| 1377 | } |
| 1378 | } |
| 1379 | |
| 1380 | /// Gather the project `main_rel` belongs to. |
| 1381 | /// |
| 1382 | /// Four phases, in this order because each needs the one before it: |
| 1383 | /// |
| 1384 | /// 1. The source closure. A relative import is resolved against the importing |
| 1385 | /// file; a root-relative one is searched for from the main file's folder |
| 1386 | /// outward and then pinned at the position it named. |
| 1387 | /// 2. The root, inferred and never asked for: the deepest directory holding |
| 1388 | /// every ordinarily-imported source, raised if a picture sits above it, and |
| 1389 | /// overridden by a `typst.toml` that declares one. |
| 1390 | /// 3. The assets, now that a shadow position exists for everything. |
| 1391 | /// 4. The fonts, searched from the main file's folder up to the root. |
| 1392 | /// |
| 1393 | /// # Arguments |
| 1394 | /// * `reach` - How far this caller may follow the closure. |
| 1395 | /// * `root` - Which filesystem root the workspace path is under. |
| 1396 | /// * `main_rel` - Workspace-relative path of the `.typ` file to compile. |
| 1397 | async fn gather(reach: &Reach<'_>, root: FileRoot, main_rel: &str) -> Outcome<Gathered> { |
| 1398 | let floor = reach.floor(); |
| 1399 | let main = match norm(main_rel) { |
| 1400 | Some(m) => m, |
| 1401 | None => return Ok(refuse(fmt!( |
| 1402 | "'{}' climbs above the workspace, so there is no file there to compile.", main_rel))), |
| 1403 | }; |
| 1404 | if !reach.allows(&main) { |
| 1405 | return Ok(refuse(fmt!( |
| 1406 | "'{}' is outside what this turn may read, so nothing was compiled.", main))); |
| 1407 | } |
| 1408 | let main_text = match read_text(root, &main).await { |
| 1409 | Some(t) => t, |
| 1410 | None => return Ok(refuse(fmt!("There is no file at '{}' to compile.", main))), |
| 1411 | }; |
| 1412 | let main_dir = parent(&main); |
| 1413 | |
| 1414 | // ── Phase 1: the source closure ────────────────────────────────────── |
| 1415 | let mut srcs: Vec<Src> = vec![Src { |
| 1416 | real: main.clone(), anchor: Anchor::Root, text: main_text }]; |
| 1417 | let mut queue: Vec<usize> = vec![0]; |
| 1418 | let mut escaped: Vec<(String, String)> = Vec::new(); |
| 1419 | let mut outside: Vec<(String, String)> = Vec::new(); |
| 1420 | let mut above: Vec<(String, String)> = Vec::new(); |
| 1421 | let mut bytes: usize = srcs[0].text.len(); |
| 1422 | while let Some(idx) = queue.pop() { |
| 1423 | let from = srcs[idx].real.clone(); |
| 1424 | let from_anchor = srcs[idx].anchor.clone(); |
| 1425 | let text = srcs[idx].text.clone(); |
| 1426 | let dir = parent(&from); |
| 1427 | for (_, lit) in literals(&text) { |
| 1428 | // A package import (`@preview/cetz:0.3.4`) names nothing on disk, so it is |
| 1429 | // not part of THIS walk. It is answered in phase 1b, out of the packages |
| 1430 | // the bundle carries, once the sources that name them are all in hand. |
| 1431 | if lit.starts_with('@') { continue; } |
| 1432 | if ext(&lit) != "typ" { continue; } |
| 1433 | let (path, anchor) = if lit.starts_with('/') { |
| 1434 | // Root-relative, and the root here is inferred rather than given, so the |
| 1435 | // file is looked for beside the main file first and upward from there. |
| 1436 | // Wherever it is found it is PLACED where the source named it, which is |
| 1437 | // what makes the position independent of where the root came out. |
| 1438 | let shadow = match abs_shadow(&lit) { Some(s) => s, None => continue }; |
| 1439 | let mut hit: Option<String> = None; |
| 1440 | for base in search_dirs(&main_dir, &dir, &floor) { |
| 1441 | let cand = match join(&base, lit.trim_start_matches('/')) { |
| 1442 | Some(c) => c, |
| 1443 | None => continue, |
| 1444 | }; |
| 1445 | if !reach.allows(&cand) { continue; } |
| 1446 | if opfs::exists(root, &cand).await.unwrap_or(false) { |
| 1447 | hit = Some(cand); |
| 1448 | break; |
| 1449 | } |
| 1450 | } |
| 1451 | match hit { |
| 1452 | Some(p) => (p, Anchor::Fixed(shadow)), |
| 1453 | // Nothing of that name anywhere on the search path. Left for the |
| 1454 | // compiler to fail on, because a literal that merely looks like a |
| 1455 | // path -- a filename quoted in prose -- must not stop a compile. |
| 1456 | None => continue, |
| 1457 | } |
| 1458 | } else { |
| 1459 | let path = match join(&dir, &lit) { |
| 1460 | Some(p) => p, |
| 1461 | None => { |
| 1462 | // A climb out of the marked folder, which is the shape of |
| 1463 | // "the folder marked in was one level too deep". |
| 1464 | if !escaped.iter().any(|(_, r)| *r == lit) { |
| 1465 | escaped.push((from.clone(), lit.clone())); |
| 1466 | } |
| 1467 | continue; |
| 1468 | }, |
| 1469 | }; |
| 1470 | if !reach.allows(&path) { |
| 1471 | if !outside.iter().any(|(_, r)| *r == lit) { |
| 1472 | outside.push((from.clone(), lit.clone())); |
| 1473 | } |
| 1474 | continue; |
| 1475 | } |
| 1476 | let anchor = match &from_anchor { |
| 1477 | Anchor::Root => Anchor::Root, |
| 1478 | Anchor::Fixed(f) => match shadow_join(f, &lit) { |
| 1479 | Some(s) => Anchor::Fixed(s), |
| 1480 | None => { |
| 1481 | // A file reached by a root-relative import, itself importing |
| 1482 | // its way above the root. A different fault from the one below |
| 1483 | // -- the folder marked in is not the problem, the source is -- |
| 1484 | // and the command-line compiler refuses it too. |
| 1485 | if !above.iter().any(|(_, r)| *r == lit) { |
| 1486 | above.push((from.clone(), lit.clone())); |
| 1487 | } |
| 1488 | continue; |
| 1489 | }, |
| 1490 | }, |
| 1491 | }; |
| 1492 | (path, anchor) |
| 1493 | }; |
| 1494 | let key = match &anchor { |
| 1495 | Anchor::Root => String::new(), |
| 1496 | Anchor::Fixed(f) => f.clone(), |
| 1497 | }; |
| 1498 | if srcs.iter().any(|s| s.real == path && match &s.anchor { |
| 1499 | Anchor::Root => key.is_empty(), |
| 1500 | Anchor::Fixed(f) => *f == key, |
| 1501 | }) { continue; } |
| 1502 | let text = match read_text(root, &path).await { Some(t) => t, None => continue }; |
| 1503 | bytes += text.len(); |
| 1504 | if bytes > MAX_BYTES { |
| 1505 | return Ok(refuse(fmt!( |
| 1506 | "This project's source files come to more than {} MB, which is past the \ |
| 1507 | limit this compiler gathers. Nothing was compiled rather than something \ |
| 1508 | incomplete.", MAX_BYTES / (1024 * 1024)))); |
| 1509 | } |
| 1510 | srcs.push(Src { real: path, anchor, text }); |
| 1511 | if srcs.len() > MAX_FILES { |
| 1512 | return Ok(refuse(fmt!( |
| 1513 | "This project reaches more than {} source files, which is past the limit \ |
| 1514 | this compiler gathers. Nothing was compiled -- a project cut off at a limit \ |
| 1515 | would have produced a PDF missing whatever fell outside it, and said nothing. \ |
| 1516 | Compile a smaller part of it, or mark in a narrower folder.", MAX_FILES))); |
| 1517 | } |
| 1518 | queue.push(srcs.len() - 1); |
| 1519 | } |
| 1520 | } |
| 1521 | if !escaped.is_empty() { |
| 1522 | let (from, lit) = escaped[0].clone(); |
| 1523 | let here = parent(&from); |
| 1524 | let here = if here.is_empty() { "the marked folder".to_string() } else { here }; |
| 1525 | return Ok(Gathered::Refused { |
| 1526 | why: fmt!( |
| 1527 | "'{}' imports '{}', which is above the folder the workspace holds. The compiler \ |
| 1528 | is given the files of one project, and nothing above the marked folder exists as \ |
| 1529 | far as this page is concerned -- not because of a setting, but because that mark \ |
| 1530 | is the whole of the permission it has. Mark in the folder ABOVE '{}' -- the one \ |
| 1531 | that holds both it and what it reaches for -- and compile the same file from \ |
| 1532 | there. Nothing else needs changing: the root is worked out from the imports \ |
| 1533 | themselves, and pictures and fonts are still found inside the book.", |
| 1534 | from, lit, here), |
| 1535 | remedy: Some(Remedy::MarkAbove { from, what: lit }), |
| 1536 | }); |
| 1537 | } |
| 1538 | if !outside.is_empty() { |
| 1539 | let (from, lit) = outside[0].clone(); |
| 1540 | return Ok(refuse(fmt!( |
| 1541 | "'{}' imports '{}', which is outside the folder this turn works in. Nothing was \ |
| 1542 | compiled. A compile gathers every file its source reaches, so it is held to the same \ |
| 1543 | bounds as a read: what the turn may not read, it may not typeset either.", from, lit))); |
| 1544 | } |
| 1545 | if !above.is_empty() { |
| 1546 | let (from, lit) = above[0].clone(); |
| 1547 | return Ok(refuse(fmt!( |
| 1548 | "'{}' was reached by a path beginning with '/', which places it at the top of the \ |
| 1549 | project, and it imports '{}' -- above the top. Nothing was compiled. This is the \ |
| 1550 | source's own arithmetic rather than anything about the folder marked in: the \ |
| 1551 | command-line compiler refuses the same import for the same reason. Import it by a \ |
| 1552 | path that stays inside the project.", from, lit))); |
| 1553 | } |
| 1554 | |
| 1555 | // ── Phase 1b: the packages those sources name ──────────────────────── |
| 1556 | // |
| 1557 | // Before the root, the assets and the fonts, because a document that asks for a |
| 1558 | // package this build does not carry is refused whatever else is true of it -- and |
| 1559 | // refusing here means not first pulling eleven megabytes of fonts through the edge |
| 1560 | // to find out. A document that imports no package pays nothing: the scan stops at |
| 1561 | // the first source with no '@' in it. |
| 1562 | let pkgs = match packages(&srcs).await { |
| 1563 | Closure::Ready(p) => p, |
| 1564 | Closure::Refused(w) => return Ok(refuse(w)), |
| 1565 | }; |
| 1566 | |
| 1567 | // ── Phase 2: the root, inferred ────────────────────────────────────── |
| 1568 | // |
| 1569 | // The deepest directory holding every ordinarily-imported source, which is |
| 1570 | // exactly what `typst --root` is passed on the command line and exactly what |
| 1571 | // the author's own build script passes (`typst compile --root .. book.typ`). |
| 1572 | // A file pinned by a root-relative import does not constrain it: that one |
| 1573 | // sits where it named itself. |
| 1574 | let anchored: Vec<String> = srcs.iter() |
| 1575 | .filter(|s| matches!(s.anchor, Anchor::Root)) |
| 1576 | .map(|s| s.real.clone()) |
| 1577 | .collect(); |
| 1578 | let base_root = common_dir(&anchored); |
| 1579 | let mut proj_root = base_root.clone(); |
| 1580 | // A picture beside the book rather than inside it raises the root, so long as |
| 1581 | // it really is there. Probed rather than assumed, because a quoted filename in |
| 1582 | // prose must not move the root of a project that has nothing to do with it. |
| 1583 | for s in srcs.iter() { |
| 1584 | if !matches!(s.anchor, Anchor::Root) { continue; } |
| 1585 | let dir = parent(&s.real); |
| 1586 | for (_, lit) in literals(&s.text) { |
| 1587 | if lit.starts_with('/') || lit.starts_with('@') { continue; } |
| 1588 | if !ASSET_EXTS.contains(&ext(&lit).as_str()) { continue; } |
| 1589 | let path = match join(&dir, &lit) { Some(p) => p, None => continue }; |
| 1590 | if under_root(&proj_root, &path).is_some() { continue; } |
| 1591 | if !reach.allows(&path) { continue; } |
| 1592 | if !opfs::exists(root, &path).await.unwrap_or(false) { continue; } |
| 1593 | let want = common_of(&proj_root, &parent(&path)); |
| 1594 | if depth(&base_root).saturating_sub(depth(&want)) <= MAX_UP |
| 1595 | && under_root(&floor, &want).is_some() |
| 1596 | { |
| 1597 | proj_root = want; |
| 1598 | } |
| 1599 | } |
| 1600 | } |
| 1601 | // Typst's own manifest declares a root, so a project that says where it is |
| 1602 | // gets taken at its word -- but only when the closure actually fits inside |
| 1603 | // it, since a manifest left behind by a package would otherwise cut the |
| 1604 | // book in half. |
| 1605 | for cand in chain(&main_dir, &floor, MAX_UP) { |
| 1606 | let manifest = if cand.is_empty() { MANIFEST.to_string() } else { fmt!("{}/{}", cand, MANIFEST) }; |
| 1607 | if !opfs::exists(root, &manifest).await.unwrap_or(false) { continue; } |
| 1608 | if anchored.iter().all(|p| under_root(&cand, p).is_some()) { |
| 1609 | proj_root = cand; |
| 1610 | } |
| 1611 | break; |
| 1612 | } |
| 1613 | let main_shadow = match under_root(&proj_root, &main) { |
| 1614 | Some(s) => s, |
| 1615 | None => return Ok(refuse(fmt!( |
| 1616 | "The project root worked out as '{}', which does not contain '{}'.", proj_root, main))), |
| 1617 | }; |
| 1618 | |
| 1619 | // Every source's position, settled now that the root is. |
| 1620 | let mut shadows: Vec<String> = Vec::new(); |
| 1621 | for s in srcs.iter() { |
| 1622 | let shadow = match &s.anchor { |
| 1623 | Anchor::Fixed(f) => f.clone(), |
| 1624 | Anchor::Root => match under_root(&proj_root, &s.real) { |
| 1625 | Some(sh) => sh, |
| 1626 | None => return Ok(refuse(fmt!( |
| 1627 | "'{}' is outside the project root '{}' this compile worked out.", |
| 1628 | s.real, proj_root))), |
| 1629 | }, |
| 1630 | }; |
| 1631 | shadows.push(shadow); |
| 1632 | } |
| 1633 | |
| 1634 | // ── Phase 3: assets ────────────────────────────────────────────────── |
| 1635 | // |
| 1636 | // The search runs from the main file's folder up to the FLOOR -- the folder |
| 1637 | // marked into the workspace, or the compartment a turn works in -- and not up |
| 1638 | // to the root. The root is where the imports put it and says how the compiler |
| 1639 | // ADDRESSES a file; the mark is the permission and says what may be READ. A |
| 1640 | // book whose fonts sit beside it rather than inside it has them above the |
| 1641 | // inferred root, and capping the search at the root would lose them exactly as |
| 1642 | // hanging it off the root did. Nothing above the mark is ever reached, and a |
| 1643 | // root-relative reference found above the root is still addressable, because it |
| 1644 | // is placed at the position the source named rather than where it was found. |
| 1645 | let searched = search_dirs(&main_dir, &main_dir, &floor); |
| 1646 | let mut assets: Vec<(String, Vec<u8>)> = Vec::new(); |
| 1647 | // The real paths behind those assets, which the shadow positions deliberately |
| 1648 | // do not carry. A picture is as much a reason to rebuild as a chapter is. |
| 1649 | let mut asset_reals: Vec<String> = Vec::new(); |
| 1650 | for (i, s) in srcs.iter().enumerate() { |
| 1651 | let dir = parent(&s.real); |
| 1652 | for (_, lit) in literals(&s.text) { |
| 1653 | if lit.starts_with('@') { continue; } |
| 1654 | if !ASSET_EXTS.contains(&ext(&lit).as_str()) { continue; } |
| 1655 | let (shadow, path) = if lit.starts_with('/') { |
| 1656 | // Placed where the source names it, found wherever it lives on the |
| 1657 | // search path. This is what lets `"/assets/svg/mark.svg"` mean the one |
| 1658 | // inside the book while the root sits above the book. |
| 1659 | let shadow = match abs_shadow(&lit) { Some(s) => s, None => continue }; |
| 1660 | let mut hit: Option<String> = None; |
| 1661 | for base in search_dirs(&main_dir, &dir, &floor) { |
| 1662 | let cand = match join(&base, lit.trim_start_matches('/')) { |
| 1663 | Some(c) => c, |
| 1664 | None => continue, |
| 1665 | }; |
| 1666 | if !reach.allows(&cand) { continue; } |
| 1667 | if opfs::exists(root, &cand).await.unwrap_or(false) { |
| 1668 | hit = Some(cand); |
| 1669 | break; |
| 1670 | } |
| 1671 | } |
| 1672 | match hit { Some(p) => (shadow, p), None => continue } |
| 1673 | } else { |
| 1674 | let path = match join(&dir, &lit) { Some(p) => p, None => continue }; |
| 1675 | if !reach.allows(&path) { continue; } |
| 1676 | let shadow = match shadow_join(&shadows[i], &lit) { Some(s) => s, None => continue }; |
| 1677 | (shadow, path) |
| 1678 | }; |
| 1679 | if assets.iter().any(|(p, _)| *p == shadow) { continue; } |
| 1680 | let data = match opfs::read_file(root, &path).await { Ok(d) => d, Err(_) => continue }; |
| 1681 | bytes += data.len(); |
| 1682 | if bytes > MAX_BYTES { |
| 1683 | return Ok(refuse(fmt!( |
| 1684 | "This project's files come to more than {} MB, which is past the limit this \ |
| 1685 | compiler gathers. Nothing was compiled, because a project cut short would \ |
| 1686 | have produced a PDF with pictures missing and no warning that they were.", |
| 1687 | MAX_BYTES / (1024 * 1024)))); |
| 1688 | } |
| 1689 | assets.push((shadow, data)); |
| 1690 | asset_reals.push(path); |
| 1691 | if srcs.len() + assets.len() > MAX_FILES { |
| 1692 | return Ok(refuse(fmt!( |
| 1693 | "This project reaches more than {} files, which is past the limit this \ |
| 1694 | compiler gathers. Nothing was compiled rather than something incomplete.", |
| 1695 | MAX_FILES))); |
| 1696 | } |
| 1697 | } |
| 1698 | } |
| 1699 | |
| 1700 | // ── Phase 4: fonts ─────────────────────────────────────────────────── |
| 1701 | // |
| 1702 | // The command line passes `--font-path ./assets/fonts`; this looks in the |
| 1703 | // same two places at every folder from the book outward to the root, and |
| 1704 | // reports where it looked whether it found anything or not, so a refusal can |
| 1705 | // name a directory to put a font in. |
| 1706 | // |
| 1707 | // Outward rather than at the root alone, because the root is where the |
| 1708 | // IMPORTS put it and the fonts are where the BOOK is. Tying the two together |
| 1709 | // is what made the author's book compile without a single one of its fonts. |
| 1710 | // |
| 1711 | // The walk finds the files and stamps them; the BYTES are only read when the |
| 1712 | // stamps differ from the last gather's (see `FontCache` above). The caps are |
| 1713 | // therefore checked against the stamped sizes, before anything is read, which |
| 1714 | // also means a project that is over the limit is refused without first pulling |
| 1715 | // twenty-four megabytes through the edge to find out. |
| 1716 | let mut font_dirs: Vec<String> = Vec::new(); |
| 1717 | let mut found: Vec<(String, f64, f64)> = Vec::new(); // path, mtime, size |
| 1718 | let mut font_bytes: f64 = 0.0; |
| 1719 | let mut have: Vec<String> = Vec::new(); |
| 1720 | for base in searched.iter() { |
| 1721 | for suffix in FONT_DIRS.iter() { |
| 1722 | let start = if base.is_empty() { suffix.to_string() } else { fmt!("{}/{}", base, suffix) }; |
| 1723 | if !reach.allows(&start) { continue; } |
| 1724 | if !opfs::exists(root, &start).await.unwrap_or(false) { continue; } |
| 1725 | font_dirs.push(start.clone()); |
| 1726 | let mut open: Vec<(String, usize)> = vec![(start, 0)]; |
| 1727 | let mut opened = 0usize; |
| 1728 | while let Some((dir, depth)) = open.pop() { |
| 1729 | opened += 1; |
| 1730 | if opened > MAX_FONT_DIRS { break; } |
| 1731 | let entries = match opfs::list_dir(root, &dir).await { Ok(e) => e, Err(_) => continue }; |
| 1732 | for (name, is_dir, _) in entries { |
| 1733 | let path = fmt!("{}/{}", dir, name); |
| 1734 | if is_dir { |
| 1735 | if depth + 1 <= MAX_FONT_DEPTH { open.push((path, depth + 1)); } |
| 1736 | continue; |
| 1737 | } |
| 1738 | if !FONT_EXTS.contains(&ext(&name).as_str()) { continue; } |
| 1739 | // The same face reached twice -- a book folder whose `assets` is a |
| 1740 | // link to the shared one, say -- is one font, not two, and loading it |
| 1741 | // twice would spend the cap below on duplicates. |
| 1742 | if have.contains(&leaf(&name)) { continue; } |
| 1743 | let (mtime, size) = match opfs::stamp(root, &path).await { |
| 1744 | Ok(Some(s)) => s, |
| 1745 | _ => continue, |
| 1746 | }; |
| 1747 | font_bytes += size; |
| 1748 | if found.len() >= MAX_FONTS || font_bytes > MAX_FONT_BYTES as f64 { |
| 1749 | return Ok(refuse(fmt!( |
| 1750 | "This project's font directories hold more than {} fonts or more than \ |
| 1751 | {} MB of them. Nothing was compiled: loading only some of them would \ |
| 1752 | typeset the book in whichever ones happened to be loaded first, and the \ |
| 1753 | line breaks and page count would be wrong in a way nothing would show.", |
| 1754 | MAX_FONTS, MAX_FONT_BYTES / (1024 * 1024)))); |
| 1755 | } |
| 1756 | have.push(leaf(&name)); |
| 1757 | found.push((path, mtime, size)); |
| 1758 | } |
| 1759 | } |
| 1760 | } |
| 1761 | } |
| 1762 | // One line per file, in walk order, so any difference at all -- a font added, a |
| 1763 | // font removed, a font rewritten -- produces a different key and re-reads the set. |
| 1764 | let font_key = found.iter() |
| 1765 | .map(|(p, m, s)| fmt!("{}\u{1}{}\u{1}{}", p, m, s)) |
| 1766 | .collect::<Vec<String>>() |
| 1767 | .join("\n"); |
| 1768 | let cached = FONTS.with(|c| { |
| 1769 | let c = c.borrow(); |
| 1770 | match c.as_ref() { |
| 1771 | Some(fc) if fc.key == font_key => Some(fc.fonts.clone()), |
| 1772 | _ => None, |
| 1773 | } |
| 1774 | }); |
| 1775 | let fonts: Vec<(String, Vec<u8>)> = match cached { |
| 1776 | Some(f) => f, |
| 1777 | None => { |
| 1778 | let mut read: Vec<(String, Vec<u8>)> = Vec::new(); |
| 1779 | for (path, _, _) in found.iter() { |
| 1780 | let data = match opfs::read_file(root, path).await { Ok(d) => d, Err(_) => continue }; |
| 1781 | read.push((path.clone(), data)); |
| 1782 | } |
| 1783 | FONTS.with(|c| { |
| 1784 | *c.borrow_mut() = Some(FontCache { key: font_key.clone(), fonts: read.clone() }); |
| 1785 | }); |
| 1786 | read |
| 1787 | }, |
| 1788 | }; |
| 1789 | |
| 1790 | // The sources were followed in workspace paths, because that is the only way |
| 1791 | // a relative import can be resolved before the root is known. They cross the |
| 1792 | // boundary as shadow paths, so nothing on the far side ever holds a path that |
| 1793 | // addresses a real file. |
| 1794 | let mut shadow_srcs: Vec<(String, String)> = Vec::new(); |
| 1795 | let mut watch: Vec<String> = Vec::new(); |
| 1796 | for (i, s) in srcs.into_iter().enumerate() { |
| 1797 | if !watch.contains(&s.real) { watch.push(s.real); } |
| 1798 | // The package imports are re-pointed HERE, at the last moment, and not |
| 1799 | // earlier: phases 2 and 3 read these same literals to infer the root and find |
| 1800 | // the pictures, and a source already carrying `/_pkg/...` paths would have |
| 1801 | // sent both of them hunting for a directory that exists only inside the |
| 1802 | // compiler. The guard is the cheap one -- a source with no '@' in it cannot |
| 1803 | // name a package -- so a book that imports nothing pays one scan of a byte. |
| 1804 | let text = if s.text.contains('@') { repoint(&s.text, None) } else { s.text }; |
| 1805 | shadow_srcs.push((shadows[i].clone(), text)); |
| 1806 | } |
| 1807 | for p in asset_reals.into_iter() { |
| 1808 | if !watch.contains(&p) { watch.push(p); } |
| 1809 | } |
| 1810 | for (p, _, _) in found.iter() { |
| 1811 | if !watch.contains(p) { watch.push(p.clone()); } |
| 1812 | } |
| 1813 | // The packages go on the end, and NOT into `watch`: they are files of the build, |
| 1814 | // sealed and unchanging, so a watcher that polled them would poll something that |
| 1815 | // cannot move. They do count toward what the compiler was handed, which is why |
| 1816 | // they join the same two lists rather than travelling beside them. |
| 1817 | shadow_srcs.extend(pkgs.sources.into_iter()); |
| 1818 | assets.extend(pkgs.assets.into_iter()); |
| 1819 | |
| 1820 | Ok(Gathered::Ready(Project { |
| 1821 | root: proj_root, |
| 1822 | main: main_shadow, |
| 1823 | sources: shadow_srcs, |
| 1824 | assets, |
| 1825 | fonts, |
| 1826 | font_dirs, |
| 1827 | searched, |
| 1828 | watch, |
| 1829 | })) |
| 1830 | } |
| 1831 | |
| 1832 | /// Lay a gathered project out as the plain JS object the driver takes. |
| 1833 | /// |
| 1834 | /// Contents cross, not paths to contents: the `path` on each entry is a position |
| 1835 | /// in the compiler's shadow filesystem, which exists only inside the wasm module |
| 1836 | /// and has no filesystem behind it. |
| 1837 | fn to_js(p: &Project) -> Outcome<JsValue> { |
| 1838 | let obj = js_sys::Object::new(); |
| 1839 | let set = |k: &str, v: &JsValue| -> Outcome<()> { |
| 1840 | res!(js_sys::Reflect::set(&obj, &JsValue::from_str(k), v) |
| 1841 | .map_err(|e| err!("Building the project object failed: {}.", js_str(&e); System))); |
| 1842 | Ok(()) |
| 1843 | }; |
| 1844 | let sources = js_sys::Array::new(); |
| 1845 | for (path, text) in p.sources.iter() { |
| 1846 | let pair = js_sys::Array::new(); |
| 1847 | pair.push(&JsValue::from_str(path)); |
| 1848 | pair.push(&JsValue::from_str(text)); |
| 1849 | sources.push(&pair); |
| 1850 | } |
| 1851 | let assets = js_sys::Array::new(); |
| 1852 | for (path, data) in p.assets.iter() { |
| 1853 | let pair = js_sys::Array::new(); |
| 1854 | pair.push(&JsValue::from_str(path)); |
| 1855 | pair.push(&js_sys::Uint8Array::from(&data[..])); |
| 1856 | assets.push(&pair); |
| 1857 | } |
| 1858 | let fonts = js_sys::Array::new(); |
| 1859 | for (name, data) in p.fonts.iter() { |
| 1860 | let pair = js_sys::Array::new(); |
| 1861 | pair.push(&JsValue::from_str(name)); |
| 1862 | pair.push(&js_sys::Uint8Array::from(&data[..])); |
| 1863 | fonts.push(&pair); |
| 1864 | } |
| 1865 | let dirs = js_sys::Array::new(); |
| 1866 | for d in p.font_dirs.iter() { dirs.push(&JsValue::from_str(d)); } |
| 1867 | let looked = js_sys::Array::new(); |
| 1868 | for d in p.searched.iter() { |
| 1869 | looked.push(&JsValue::from_str(if d.is_empty() { "the workspace root" } else { d })); |
| 1870 | } |
| 1871 | // The one array here that names REAL files. It goes out because a watcher has to |
| 1872 | // know what to poll and only the gatherer knows; nothing on the far side reads a |
| 1873 | // file by it -- the poll comes back through `typst_watch_stamps`, on this side, |
| 1874 | // under the same jail as every other read. |
| 1875 | let watching = js_sys::Array::new(); |
| 1876 | for w in p.watch.iter() { watching.push(&JsValue::from_str(w)); } |
| 1877 | res!(set("root", &JsValue::from_str(if p.root.is_empty() { "the workspace root" } else { &p.root }))); |
| 1878 | res!(set("main", &JsValue::from_str(&p.main))); |
| 1879 | res!(set("sources", &sources)); |
| 1880 | res!(set("assets", &assets)); |
| 1881 | res!(set("fonts", &fonts)); |
| 1882 | res!(set("fontDirs", &dirs)); |
| 1883 | res!(set("searched", &looked)); |
| 1884 | res!(set("watch", &watching)); |
| 1885 | Ok(obj.into()) |
| 1886 | } |
| 1887 | |
| 1888 | |
| 1889 | // ── Reaching the driver ───────────────────────────────────────────────────── |
| 1890 | |
| 1891 | /// Reach the driver object on `window`, or refuse in the model's language. |
| 1892 | fn driver() -> Outcome<Driver> { |
| 1893 | let win = res!(web_sys::window() |
| 1894 | .ok_or_else(|| err!("The Typst tool needs a browser window."; System, Missing))); |
| 1895 | let obj = res!(js_sys::Reflect::get(&win, &JsValue::from_str("DaimondTypst")) |
| 1896 | .map_err(|e| err!("Reading window.DaimondTypst failed: {}.", js_str(&e); System, Missing))); |
| 1897 | if obj.is_undefined() || obj.is_null() { |
| 1898 | return Err(err!( |
| 1899 | "The Typst compiler is not loaded in this page, so nothing can be typeset. \ |
| 1900 | Tell the user, and carry on without it."; |
| 1901 | System, Missing)); |
| 1902 | } |
| 1903 | Ok(obj.unchecked_into::<Driver>()) |
| 1904 | } |
| 1905 | |
| 1906 | /// The `message` of a rejected JS `Error`, verbatim, falling back to the |
| 1907 | /// value's own rendering when it is not an `Error`. |
| 1908 | fn refusal(e: &JsValue) -> String { |
| 1909 | match js_sys::Reflect::get(e, &JsValue::from_str("message")) { |
| 1910 | Ok(m) => m.as_string().unwrap_or_else(|| js_str(e)), |
| 1911 | Err(_) => js_str(e), |
| 1912 | } |
| 1913 | } |
| 1914 | |
| 1915 | /// The driver's own `error` string, when it reported one. |
| 1916 | /// |
| 1917 | /// **A failed compile is an ANSWER, not a fault**, and this is the only shape it |
| 1918 | /// arrives in. `www/js/typst.js` composes it out of typst's diagnostics -- the |
| 1919 | /// file, the line, the literal the line names, and what the compiler was actually |
| 1920 | /// given -- and that is the whole of what a reader or a daimon can act on. |
| 1921 | /// |
| 1922 | /// It is read out separately, and BEFORE anything is turned into an |
| 1923 | /// [`Error`](oxedyne_fe2o3_core::error::Error), because turning it into one is how |
| 1924 | /// it gets destroyed. A fe2o3 error renders as `LocalErr{[Invalid Data] "…"}`, |
| 1925 | /// with ANSI colour codes and the source position of the Rust line that raised it, |
| 1926 | /// and every layer that touches it adds another. A person pressing ⚙ Compile with |
| 1927 | /// no Typst pack was shown exactly that -- escape codes included, unchanged by the |
| 1928 | /// locale -- in place of the sentence the refusal was written as. |
| 1929 | /// |
| 1930 | /// Which was the very failure this module was rewritten for: a message about the |
| 1931 | /// machinery in place of a message about the problem. It matters more now than it |
| 1932 | /// did, because the live view puts a failed build in front of the reader every time |
| 1933 | /// a brace is mistyped, rather than once when a button is pressed. |
| 1934 | fn driver_error(v: &JsValue) -> Option<String> { |
| 1935 | let msg = match js_sys::Reflect::get(v, &JsValue::from_str("error")) { |
| 1936 | Ok(m) => m, |
| 1937 | Err(_) => return None, |
| 1938 | }; |
| 1939 | match msg.as_string() { |
| 1940 | Some(t) if !t.trim().is_empty() => Some(t), |
| 1941 | _ => None, |
| 1942 | } |
| 1943 | } |
| 1944 | |
| 1945 | /// Read the resolved `{ pdf }` / `{ error }` object into PDF bytes. |
| 1946 | /// |
| 1947 | /// An `error` is passed through untouched: the page composed it from the |
| 1948 | /// compiler's own diagnostics, which name the failing line and, since the |
| 1949 | /// gatherer landed, the file that was asked for and not found. Rewording it |
| 1950 | /// would destroy the only thing the model can act on. |
| 1951 | /// |
| 1952 | /// # Arguments |
| 1953 | /// * `v` - What the driver's promise resolved with. |
| 1954 | /// * `field` - Which byte field to take: `"pdf"` or `"vector"`. |
| 1955 | fn bytes_of(v: &JsValue, field: &str) -> Outcome<Vec<u8>> { |
| 1956 | if v.is_undefined() || v.is_null() { |
| 1957 | return Err(err!( |
| 1958 | "The Typst compiler returned nothing at all."; Invalid, Data)); |
| 1959 | } |
| 1960 | if let Some(text) = driver_error(v) { |
| 1961 | return Err(err!("{}", text; Invalid, Data)); |
| 1962 | } |
| 1963 | let got = res!(js_sys::Reflect::get(v, &JsValue::from_str(field)) |
| 1964 | .map_err(|e| err!( |
| 1965 | "Reading the compiled document failed: {}.", refusal(&e); Invalid, Data))); |
| 1966 | if got.is_undefined() || got.is_null() { |
| 1967 | return Err(err!( |
| 1968 | "The Typst compiler reported neither a document nor an error."; Invalid, Data)); |
| 1969 | } |
| 1970 | let arr = res!(got.dyn_into::<js_sys::Uint8Array>() |
| 1971 | .map_err(|_| err!( |
| 1972 | "The Typst compiler returned a document that is not a byte array."; Invalid, Data))); |
| 1973 | let out = arr.to_vec(); |
| 1974 | if out.len() < 5 { |
| 1975 | return Err(err!( |
| 1976 | "The Typst compiler returned {} bytes, which is not a document.", out.len(); |
| 1977 | Invalid, Data)); |
| 1978 | } |
| 1979 | Ok(out) |
| 1980 | } |
| 1981 | |
| 1982 | /// Compile `source` to PDF bytes in the browser, as ONE self-contained file. |
| 1983 | /// |
| 1984 | /// Kept for a source that has no project behind it -- a string composed in the |
| 1985 | /// page rather than read off disk. Anything that imports, includes or names a |
| 1986 | /// picture wants [`compile_project`] instead; this one really can see nothing |
| 1987 | /// but the string it is given, and now says so when a source reaches further. |
| 1988 | /// |
| 1989 | /// **Not the door for a workspace file.** It was, until seq 117, and that is the |
| 1990 | /// whole reason the author's book failed: the model's `typst_compile` read one |
| 1991 | /// file and handed the string here, so a book's first `#import` failed with a |
| 1992 | /// refusal that was accurate, well written, and about a situation the caller had |
| 1993 | /// created for no reason. |
| 1994 | /// |
| 1995 | /// # Arguments |
| 1996 | /// * `source` - The whole Typst document, self-contained. |
| 1997 | pub async fn compile(source: &str) -> Outcome<Vec<u8>> { |
| 1998 | let d = res!(driver()); |
| 1999 | match JsFuture::from(d.compile(source)).await { |
| 2000 | Ok(v) => bytes_of(&v, "pdf"), |
| 2001 | Err(e) => Err(err!("{}", refusal(&e); Invalid, Data)), |
| 2002 | } |
| 2003 | } |
| 2004 | |
| 2005 | /// Compile the project that `main_rel` belongs to, in the browser. |
| 2006 | /// |
| 2007 | /// # Arguments |
| 2008 | /// * `reach` - How far the closure may be followed, which is the caller's bounds. |
| 2009 | /// * `root` - Which filesystem root the workspace path is under. |
| 2010 | /// * `main_rel` - Workspace-relative path of the `.typ` file to compile. |
| 2011 | pub async fn compile_project( |
| 2012 | reach: &Reach<'_>, |
| 2013 | root: FileRoot, |
| 2014 | main_rel: &str, |
| 2015 | ) |
| 2016 | -> Outcome<Vec<u8>> |
| 2017 | { |
| 2018 | let d = res!(driver()); |
| 2019 | let has = js_sys::Reflect::has(&d, &JsValue::from_str("compileProject")).unwrap_or(false); |
| 2020 | if !has { |
| 2021 | return Err(err!( |
| 2022 | "The Typst driver in this page is an older one that compiles a single file only. \ |
| 2023 | Reload the page to pick up the current one."; System, Missing)); |
| 2024 | } |
| 2025 | let project = match res!(gather(reach, root, main_rel).await) { |
| 2026 | Gathered::Ready(p) => p, |
| 2027 | Gathered::Refused { why, remedy } => { |
| 2028 | return Err(match remedy { |
| 2029 | Some(r) => err!("{}\n\n{}", why, r.line(); Invalid, Input), |
| 2030 | None => err!("{}", why; Invalid, Input), |
| 2031 | }); |
| 2032 | }, |
| 2033 | }; |
| 2034 | let arg = res!(to_js(&project)); |
| 2035 | match JsFuture::from(d.compile_project(&arg)).await { |
| 2036 | Ok(v) => bytes_of(&v, "pdf"), |
| 2037 | Err(e) => Err(err!("{}", refusal(&e); Invalid, Data)), |
| 2038 | } |
| 2039 | } |
| 2040 | |
| 2041 | |
| 2042 | // ── The page's door ───────────────────────────────────────────────────────── |
| 2043 | |
| 2044 | /// Compile the project a workspace `.typ` file belongs to, for the Doc panel's |
| 2045 | /// Compile button, resolving `{ pdf }` or `{ error, remedy }`. |
| 2046 | /// |
| 2047 | /// The button read the source in JavaScript and handed the driver a string, which |
| 2048 | /// is why it could only ever compile one file. It comes through here instead, so |
| 2049 | /// there is exactly ONE gatherer and the button and the model's `typst_compile` |
| 2050 | /// tool cannot disagree about what a project is -- and so the reading still |
| 2051 | /// happens on this side, under the path jail. |
| 2052 | /// |
| 2053 | /// `remedy`, when present, is `{ action, path, line }`: something the page can |
| 2054 | /// offer as a button rather than prose the reader has to turn into an action. |
| 2055 | /// `action` is a stable word -- `mark-above` is the only one so far -- and `path` |
| 2056 | /// is what it is about. |
| 2057 | /// |
| 2058 | /// # Arguments |
| 2059 | /// * `path` - Workspace-relative path of the `.typ` file to compile. |
| 2060 | #[wasm_bindgen] |
| 2061 | pub async fn typst_compile_project(path: String) -> js_sys::Object { |
| 2062 | page_compile(&path, Want::Pdf).await |
| 2063 | } |
| 2064 | |
| 2065 | /// Lay out the project a workspace `.typ` file belongs to, WITHOUT writing a PDF, |
| 2066 | /// resolving `{ vector, watch, pages }` or `{ error, remedy }`. |
| 2067 | /// |
| 2068 | /// The live view's door, and the whole reason it is affordable. Measured on the |
| 2069 | /// author's 281-page book, same compiler and same layout: writing the PDF is |
| 2070 | /// 1834-2069 ms and laying the pages out is 235-272 ms. A watch loop that produced |
| 2071 | /// a PDF on every save would spend seven eighths of its life writing a file nobody |
| 2072 | /// opens, because the reader is looking at the screen. |
| 2073 | /// |
| 2074 | /// `watch` is the list of REAL workspace paths this compile read -- what a watcher |
| 2075 | /// polls, and the only place real paths cross out of this module. See |
| 2076 | /// [`typst_watch_stamps`], which is how they come back. |
| 2077 | /// |
| 2078 | /// # Arguments |
| 2079 | /// * `path` - Workspace-relative path of the `.typ` file to lay out. |
| 2080 | #[wasm_bindgen] |
| 2081 | pub async fn typst_compile_project_vector(path: String) -> js_sys::Object { |
| 2082 | page_compile(&path, Want::Vector).await |
| 2083 | } |
| 2084 | |
| 2085 | /// Which artifact the page's door is being asked for. |
| 2086 | enum Want { |
| 2087 | /// The published document: real bytes, written to disk, opened by a reader. |
| 2088 | Pdf, |
| 2089 | /// The laid-out pages, for the live view. |
| 2090 | Vector, |
| 2091 | } |
| 2092 | |
| 2093 | impl Want { |
| 2094 | |
| 2095 | /// The field the driver answers in, which is also the field this answers in. |
| 2096 | fn field(&self) -> &'static str { |
| 2097 | match self { |
| 2098 | Self::Pdf => "pdf", |
| 2099 | Self::Vector => "vector", |
| 2100 | } |
| 2101 | } |
| 2102 | } |
| 2103 | |
| 2104 | /// Gather and compile for the PAGE -- the Compile button and the live view alike. |
| 2105 | /// |
| 2106 | /// One gatherer, one refusal vocabulary and one remedy, whichever artifact was |
| 2107 | /// asked for. Two copies of this would be two answers to "what is a project", and |
| 2108 | /// the live view would drift from the PDF it is supposed to be a preview of. |
| 2109 | /// |
| 2110 | /// # Arguments |
| 2111 | /// * `path` - Workspace-relative path of the `.typ` file. |
| 2112 | /// * `want` - Which artifact to ask the driver for. |
| 2113 | async fn page_compile(path: &str, want: Want) -> js_sys::Object { |
| 2114 | let obj = js_sys::Object::new(); |
| 2115 | let set = |k: &str, v: &JsValue| { |
| 2116 | let _ = js_sys::Reflect::set(&obj, &JsValue::from_str(k), v); |
| 2117 | }; |
| 2118 | // The page's own button is the user acting on a folder they marked in |
| 2119 | // themselves, so it carries the workspace's reach and not a turn's. |
| 2120 | let reach = Reach::Workspace; |
| 2121 | let gathered = match gather(&reach, FileRoot::Workspace, path).await { |
| 2122 | Ok(g) => g, |
| 2123 | Err(e) => { |
| 2124 | set("error", &JsValue::from_str(&fmt!("{}", e))); |
| 2125 | return obj; |
| 2126 | }, |
| 2127 | }; |
| 2128 | let project = match gathered { |
| 2129 | Gathered::Ready(p) => p, |
| 2130 | Gathered::Refused { why, remedy } => { |
| 2131 | set("error", &JsValue::from_str(&why)); |
| 2132 | if let Some(r) = remedy { |
| 2133 | let rem = js_sys::Object::new(); |
| 2134 | let _ = js_sys::Reflect::set( |
| 2135 | &rem, &JsValue::from_str("action"), &JsValue::from_str(r.action())); |
| 2136 | let _ = js_sys::Reflect::set( |
| 2137 | &rem, &JsValue::from_str("path"), &JsValue::from_str(&r.subject())); |
| 2138 | let _ = js_sys::Reflect::set( |
| 2139 | &rem, &JsValue::from_str("line"), &JsValue::from_str(&r.line())); |
| 2140 | set("remedy", &rem.into()); |
| 2141 | } |
| 2142 | return obj; |
| 2143 | }, |
| 2144 | }; |
| 2145 | // The watch list goes out even when the compile then FAILS, and that is the |
| 2146 | // point: a broken source is exactly when a watcher most needs to know which |
| 2147 | // files to keep an eye on, since the next save is the one that fixes it. |
| 2148 | let watching = js_sys::Array::new(); |
| 2149 | for w in project.watch.iter() { watching.push(&JsValue::from_str(w)); } |
| 2150 | set("watch", &watching); |
| 2151 | let arg = match to_js(&project) { |
| 2152 | Ok(a) => a, |
| 2153 | Err(e) => { |
| 2154 | set("error", &JsValue::from_str(&fmt!("{}", e))); |
| 2155 | return obj; |
| 2156 | }, |
| 2157 | }; |
| 2158 | let d = match driver() { |
| 2159 | Ok(d) => d, |
| 2160 | Err(e) => { |
| 2161 | set("error", &JsValue::from_str(&fmt!("{}", e))); |
| 2162 | return obj; |
| 2163 | }, |
| 2164 | }; |
| 2165 | let promise = match want { |
| 2166 | Want::Pdf => d.compile_project(&arg), |
| 2167 | Want::Vector => { |
| 2168 | let has = js_sys::Reflect::has(&d, &JsValue::from_str("compileProjectVector")) |
| 2169 | .unwrap_or(false); |
| 2170 | if !has { |
| 2171 | set("error", &JsValue::from_str( |
| 2172 | "The Typst driver in this page is an older one with no live view in it. \ |
| 2173 | Reload the page to pick up the current one.")); |
| 2174 | return obj; |
| 2175 | } |
| 2176 | d.compile_project_vector(&arg) |
| 2177 | }, |
| 2178 | }; |
| 2179 | // THE COMPILER'S OWN WORDS, VERBATIM, AND NOT A RUST ERROR RENDERED AS ONE. |
| 2180 | // |
| 2181 | // This arm used to hand the whole resolved value to `bytes_of`, which wraps a |
| 2182 | // reported `{error}` in `err!()` so it can be returned as an `Outcome` -- right |
| 2183 | // for the model's tool, which has to return one, and wrong here, where the string |
| 2184 | // goes straight to a person. `fmt!("{}", e)` on a fe2o3 error is |
| 2185 | // `LocalErr{[Invalid Data] "src/wasm/typst.rs:…: …"}`, ANSI escapes and all, and |
| 2186 | // that is what somebody pressing ⚙ Compile without the pack was shown: a Rust |
| 2187 | // debug dump, in English whatever their locale, in place of a sentence written |
| 2188 | // for them. The error is read out FIRST and passed through untouched, which is |
| 2189 | // what `bytes_of`'s own doc comment always said happened. |
| 2190 | match JsFuture::from(promise).await { |
| 2191 | Ok(v) => match driver_error(&v) { |
| 2192 | Some(text) => set("error", &JsValue::from_str(&text)), |
| 2193 | None => match bytes_of(&v, want.field()) { |
| 2194 | Ok(b) => { |
| 2195 | set(want.field(), &js_sys::Uint8Array::from(&b[..]).into()); |
| 2196 | // COMPILING IS WHAT STARTS THE WATCH, and this is where that is |
| 2197 | // said -- once, at the page's own door, after a compile that |
| 2198 | // WORKED. Not a toggle, not a setting, and nothing that starts a |
| 2199 | // compiler on its own: the user pressed Compile, so from here the |
| 2200 | // document follows the file. A vector compile does not re-arm it, |
| 2201 | // or every rebuild would arm the loop that produced it. |
| 2202 | if matches!(want, Want::Pdf) { |
| 2203 | if let Ok(w) = watcher() { |
| 2204 | w.began(path, &watching); |
| 2205 | } |
| 2206 | } |
| 2207 | }, |
| 2208 | // Everything reaching here is about the SHAPE of what came back -- |
| 2209 | // no bytes, the wrong type, a length that is not a document -- and |
| 2210 | // never the compiler's opinion of the source, which was taken above. |
| 2211 | // A fe2o3 error is the right carrier for a broken contract and the |
| 2212 | // wrong one for a diagnostic. |
| 2213 | Err(e) => set("error", &JsValue::from_str(&fmt!("{}", e))), |
| 2214 | }, |
| 2215 | }, |
| 2216 | Err(e) => set("error", &JsValue::from_str(&refusal(&e))), |
| 2217 | } |
| 2218 | obj |
| 2219 | } |
| 2220 | |
| 2221 | /// Reach the watcher object on `window`, or say there is none. |
| 2222 | /// |
| 2223 | /// Absent is ORDINARY, not an error: a build with no live view in it, or a page |
| 2224 | /// where the module has not been evaluated yet, simply compiles and shows a PDF |
| 2225 | /// exactly as it did before. Nothing above treats this as a failure. |
| 2226 | fn watcher() -> Outcome<Watcher> { |
| 2227 | let win = res!(web_sys::window() |
| 2228 | .ok_or_else(|| err!("No browser window."; System, Missing))); |
| 2229 | let obj = res!(js_sys::Reflect::get(&win, &JsValue::from_str("DaimondTypstWatch")) |
| 2230 | .map_err(|e| err!("Reading window.DaimondTypstWatch failed: {}.", js_str(&e); System, Missing))); |
| 2231 | if obj.is_undefined() || obj.is_null() { |
| 2232 | return Err(err!("There is no live view on this page."; System, Missing)); |
| 2233 | } |
| 2234 | Ok(obj.unchecked_into::<Watcher>()) |
| 2235 | } |
| 2236 | |
| 2237 | /// When each of `paths` was last written, and how long it is. |
| 2238 | /// |
| 2239 | /// The answer is one string per path, `"<lastModified>:<size>"`, in the order asked. |
| 2240 | /// A file that is not there answers `"0:-1"`, which is a change like any other: a |
| 2241 | /// chapter deleted under a watcher is a rebuild, not a silence. |
| 2242 | /// |
| 2243 | /// A string rather than a pair of numbers because the only question ever asked of it |
| 2244 | /// is whether it is the SAME as last time, and a string compares in one operation |
| 2245 | /// with no chance of a caller comparing the modification time and forgetting the |
| 2246 | /// size. Two answers to "has this changed" is how one caller decides a file is |
| 2247 | /// fresh while another decides it is stale. |
| 2248 | /// |
| 2249 | /// **Polling is the only mechanism there is.** The File System Access API has no |
| 2250 | /// change events for a real folder, so a watcher on the author's own directory has |
| 2251 | /// to ask. Asking is cheap: sixty-three files answered in thirteen milliseconds, |
| 2252 | /// three runs, measured in `dev/measure_typstbook.mjs`. The test itself -- |
| 2253 | /// `lastModified` WITH `size` -- is the one `www/js/cloud.js` already uses for cloud |
| 2254 | /// sync, deliberately, and [`opfs::stamp`] is the one place either is read. |
| 2255 | /// |
| 2256 | /// Every path goes through the same OPFS edge as every other read, so the jail, the |
| 2257 | /// per-account namespace and the real-folder override all apply. A watcher cannot |
| 2258 | /// use this to look at anything it could not already read. |
| 2259 | /// |
| 2260 | /// # Arguments |
| 2261 | /// * `paths` - Workspace-relative paths, as the project's `watch` handed them out. |
| 2262 | #[wasm_bindgen] |
| 2263 | pub async fn typst_watch_stamps(paths: Vec<String>) -> Vec<String> { |
| 2264 | let mut out: Vec<String> = Vec::with_capacity(paths.len()); |
| 2265 | for p in paths.iter() { |
| 2266 | let (m, s) = match opfs::stamp(FileRoot::Workspace, p).await { |
| 2267 | Ok(Some(v)) => v, |
| 2268 | _ => (0.0, -1.0), |
| 2269 | }; |
| 2270 | out.push(fmt!("{}:{}", m, s)); |
| 2271 | } |
| 2272 | out |
| 2273 | } |
| 2274 | |
| 2275 | |
| 2276 | // ── Where these are checked ───────────────────────────────────────────────── |
| 2277 | // |
| 2278 | // Not here. `src/wasm` is gated to `wasm32`, and nothing in this tree runs a |
| 2279 | // wasm test runner, so a `#[cfg(test)] mod tests` in this file would compile for |
| 2280 | // no target anybody builds and could never go red -- a check that cannot fail is |
| 2281 | // worse than none, because it reads as coverage. |
| 2282 | // |
| 2283 | // The path arithmetic above, the closure, the caps and the font refusal are all |
| 2284 | // proved in `dev/verify_typstproject.mjs`, which drives the real gatherer against |
| 2285 | // real files in a real OPFS workspace, and withholds each file in turn to see the |
| 2286 | // refusal it is supposed to produce. It drives them THROUGH THE MODEL'S TOOL, |
| 2287 | // because the first version of this module was proved by calling the gatherer |
| 2288 | // directly and passed 24 checks while production still compiled one string. |