@johnhenry/sitefile 0.0.1 → 0.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +480 -3
- package/README.md +70 -21
- package/lib/src/archive-writers.d.ts +12 -2
- package/lib/src/archive-writers.js +53 -10
- package/lib/src/canonical.d.ts +16 -0
- package/lib/src/canonical.js +46 -0
- package/lib/src/car.d.ts +34 -0
- package/lib/src/car.js +203 -0
- package/lib/src/checklinks.js +8 -2
- package/lib/src/cli/bake.js +4 -3
- package/lib/src/cli/build-image.d.ts +1 -0
- package/lib/src/cli/build-image.js +1 -0
- package/lib/src/cli/common.js +4 -1
- package/lib/src/cli/hosts.d.ts +5 -0
- package/lib/src/cli/hosts.js +78 -0
- package/lib/src/cli/images.js +23 -5
- package/lib/src/cli/import-config.d.ts +2 -0
- package/lib/src/cli/import-config.js +56 -0
- package/lib/src/cli/index.d.ts +3 -1
- package/lib/src/cli/index.js +31 -2
- package/lib/src/cli/integrity.d.ts +2 -0
- package/lib/src/cli/integrity.js +77 -0
- package/lib/src/cli/network.d.ts +7 -0
- package/lib/src/cli/network.js +14 -3
- package/lib/src/cli/serve-keys.d.ts +39 -0
- package/lib/src/cli/serve-keys.js +106 -0
- package/lib/src/cli/serve-worker.js +46 -8
- package/lib/src/cli/servers.d.ts +124 -1
- package/lib/src/cli/servers.js +705 -62
- package/lib/src/cli/up.d.ts +2 -0
- package/lib/src/cli/up.js +193 -0
- package/lib/src/cli/watch.d.ts +14 -1
- package/lib/src/cli/watch.js +20 -3
- package/lib/src/cli.js +138 -18
- package/lib/src/csp.d.ts +17 -0
- package/lib/src/csp.js +52 -0
- package/lib/src/dictionary.d.ts +16 -0
- package/lib/src/dictionary.js +89 -0
- package/lib/src/epub.d.ts +5 -0
- package/lib/src/epub.js +113 -0
- package/lib/src/errors.d.ts +22 -9
- package/lib/src/errors.js +20 -1
- package/lib/src/executor.d.ts +31 -1
- package/lib/src/executor.js +192 -22
- package/lib/src/explain.js +33 -3
- package/lib/src/export-for.d.ts +42 -0
- package/lib/src/export-for.js +466 -0
- package/lib/src/export-formats.d.ts +2 -2
- package/lib/src/export-formats.js +52 -2
- package/lib/src/fingerprint.d.ts +3 -1
- package/lib/src/fingerprint.js +32 -5
- package/lib/src/host-config.d.ts +34 -0
- package/lib/src/host-config.js +645 -0
- package/lib/src/hosts.d.ts +47 -0
- package/lib/src/hosts.js +106 -0
- package/lib/src/index.d.ts +1 -1
- package/lib/src/index.js +1 -1
- package/lib/src/integrity.d.ts +115 -0
- package/lib/src/integrity.js +273 -0
- package/lib/src/language/ast.d.ts +116 -3
- package/lib/src/language/ast.js +7 -1
- package/lib/src/language/parser.js +176 -7
- package/lib/src/language/validate.js +21 -0
- package/lib/src/links.d.ts +33 -0
- package/lib/src/links.js +271 -3
- package/lib/src/lint.d.ts +1 -1
- package/lib/src/lint.js +26 -1
- package/lib/src/mime-data.d.ts +2 -0
- package/lib/src/mime-data.js +92 -0
- package/lib/src/oci.d.ts +20 -2
- package/lib/src/oci.js +70 -28
- package/lib/src/outdated.d.ts +3 -0
- package/lib/src/outdated.js +4 -4
- package/lib/src/planner.d.ts +69 -2
- package/lib/src/planner.js +150 -8
- package/lib/src/plugins/cache.d.ts +11 -0
- package/lib/src/plugins/cache.js +29 -0
- package/lib/src/plugins/host.d.ts +51 -2
- package/lib/src/plugins/host.js +144 -18
- package/lib/src/plugins/wasm.js +1 -3
- package/lib/src/portable.d.ts +8 -0
- package/lib/src/portable.js +47 -0
- package/lib/src/precache.d.ts +33 -0
- package/lib/src/precache.js +75 -0
- package/lib/src/precompress.d.ts +19 -0
- package/lib/src/precompress.js +35 -0
- package/lib/src/qr.d.ts +18 -0
- package/lib/src/qr.js +372 -0
- package/lib/src/registry-ops.js +4 -2
- package/lib/src/reload-client.d.ts +2 -0
- package/lib/src/reload-client.js +304 -0
- package/lib/src/resources/archive.d.ts +36 -0
- package/lib/src/resources/archive.js +338 -67
- package/lib/src/resources/convert.js +3 -1
- package/lib/src/resources/https.d.ts +9 -1
- package/lib/src/resources/https.js +36 -0
- package/lib/src/resources/network.d.ts +25 -3
- package/lib/src/resources/network.js +77 -6
- package/lib/src/secrets.d.ts +12 -3
- package/lib/src/secrets.js +18 -5
- package/lib/src/serve-auth.d.ts +32 -0
- package/lib/src/serve-auth.js +112 -0
- package/lib/src/serve-rules.d.ts +83 -7
- package/lib/src/serve-rules.js +264 -53
- package/lib/src/server.d.ts +437 -10
- package/lib/src/server.js +1236 -52
- package/lib/src/servers-file.d.ts +36 -0
- package/lib/src/servers-file.js +101 -0
- package/lib/src/servers.d.ts +109 -7
- package/lib/src/servers.js +151 -29
- package/lib/src/single-file.d.ts +12 -0
- package/lib/src/single-file.js +147 -0
- package/lib/src/site.d.ts +54 -0
- package/lib/src/site.js +204 -6
- package/lib/src/store.js +9 -5
- package/lib/src/swbn.d.ts +10 -0
- package/lib/src/swbn.js +86 -0
- package/lib/src/toml.d.ts +17 -0
- package/lib/src/toml.js +323 -0
- package/lib/src/wacz.d.ts +6 -0
- package/lib/src/wacz.js +96 -0
- package/lib/src/warc.d.ts +28 -0
- package/lib/src/warc.js +252 -0
- package/lib/src/watch.d.ts +12 -1
- package/lib/src/watch.js +67 -1
- package/lib/src/wbn.d.ts +9 -1
- package/lib/src/wbn.js +23 -33
- package/lib/src/zstd.d.ts +4 -0
- package/lib/src/zstd.js +328 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
#
|
|
1
|
+
# sitefile
|
|
2
2
|
|
|
3
3
|
[](https://www.npmjs.com/package/@johnhenry/sitefile)
|
|
4
4
|
[](https://github.com/johnhenry/sitefile/actions/workflows/ci.yml)
|
|
@@ -82,12 +82,18 @@ no runtime dependencies.
|
|
|
82
82
|
| `PLUGIN name FROM ./plugins/x.mjs\|x.wasm [INTEGRITY sha256:…]` | yes; a custom renderer: a sandboxed JS module (runs only with `--allow-plugin name`) or an import-free WebAssembly module (no flag needed; see [docs/PLUGINS.md](docs/PLUGINS.md), `examples/wasm/`) |
|
|
83
83
|
| `TRANSFORM [--include/--exclude=<pattern>] [<source>] WITH name TO <dest> [OPTIONS k=v …] [FOR item IN list]` | yes; e.g. text → animated SVG (`examples/motion/`), responsive images (`examples/image/`); a directory source runs once per file (`TO /img/thumbs/*.png`) |
|
|
84
84
|
| `TOOL name` + `TRANSFORM … WITH name TO <dest> [OPTIONS …] [FOR …] ARGS …` | yes; run an external program (e.g. `ffmpeg`) you allow with `--allow-exec name`: argv only, no shell, temp files, scrubbed environment (see [docs/PLUGINS.md](docs/PLUGINS.md)) |
|
|
85
|
-
| `SITEMAP BASE <url> [TO <dest>]` | yes; a sitemaps.org `/sitemap.xml` of the `.html` pages so far |
|
|
85
|
+
| `SITEMAP BASE <url> [TO <dest>]` | yes; a sitemaps.org `/sitemap.xml` of the `.html` pages so far (a sitemap index and parts above 50,000 URLs or 50 MiB) |
|
|
86
|
+
| `CANONICAL BASE <url> [PRETTY]` | yes; a `<link rel="canonical">` in every page that has none |
|
|
86
87
|
| `FEED <import> BASE <url> LINK <path> [TO <dest>] [TITLE <text>]` | yes; an Atom `/feed.xml` from Markdown posts (`title` and `date` required) |
|
|
88
|
+
| `ROBOTS [ALLOW\|DISALLOW <path>]… [SITEMAP] [TO <dest>]`, `SECURITY_TXT CONTACT <uri>… EXPIRES <date> [ENCRYPTION <uri>]… [POLICY <uri>]…` | yes; `/robots.txt` (with the SITEMAP URLs) and an RFC 9116 `/.well-known/security.txt` (Expires required; warns when near) |
|
|
87
89
|
| `REDIRECT <from> <to> [STATUS 301\|302\|303\|307\|308]`, `HEADER <pattern> <Name>: <value>` | yes; `/_redirects` and `/_headers` for Netlify / Cloudflare Pages (and `sitefile serve`); a `wbn` export also bakes HEADER values into each response and exact-path REDIRECTs into 3xx responses (splats stay in `/_redirects`) |
|
|
90
|
+
| `CSP [POLICY <policy>] [META]` | yes; a strict Content-Security-Policy per page in `/_headers` (or a `<meta>`), with the SHA-256 of each inline script and style instead of `'unsafe-inline'` |
|
|
91
|
+
| `MIME <.ext> <type/subtype>` | yes; a custom Content-Type (`.usdz`, `.ts` as MPEG-TS) as a `/_headers` rule, which also types the files in a Web Bundle export |
|
|
88
92
|
| `CHECKLINKS [--warn] [--external]` | yes; fails (or warns) on links to files that do not exist, with file and line; `--external` requests http(s) links under the network policy |
|
|
89
|
-
| `FINGERPRINT [--overwrite] <pattern>… [MANIFEST <dest>]` | yes; renames assets to `name.<hash>.ext` and rewrites the HTML and CSS that reference them, plus a JSON manifest |
|
|
90
|
-
| `
|
|
93
|
+
| `FINGERPRINT [--overwrite] [--no-cache-headers] <pattern>… [MANIFEST <dest>] [INTEGRITY]` | yes; renames assets to `name.<hash>.ext` and rewrites the HTML and CSS that reference them, plus a JSON manifest, `Cache-Control` lines in `/_headers` and (INTEGRITY) SRI attributes |
|
|
94
|
+
| `PRECOMPRESS [--overwrite] [gzip] <pattern>… [MIN <bytes>]` | yes; deterministic `.gz` sidecars of text files for hosts that serve them in place of the file (nginx `gzip_static`, Caddy `precompressed`); `br` and `zstd` are not supported yet |
|
|
95
|
+
| `PRECACHE [--overwrite] <pattern>… [TO <dest>] [INTO <service-worker>]` | yes; a Workbox-style `[{url, revision}]` precache manifest (fingerprinted files get `revision: null`), or injected at `self.__WB_MANIFEST` |
|
|
96
|
+
| `EXPORT <path> [AS directory\|zip\|tar\|tgz\|wbn\|oci\|car\|html\|mhtml\|warc\|swbn\|wacz\|epub] [BASE <https-url>] [AT <root>] [COMPRESSION gzip\|none] [KEY <secret-id>] [FOR <host>]` | yes; `FOR netlify\|cloudflare\|vercel\|firebase\|azure\|github-pages\|s3` writes REDIRECT and HEADER as that host reads them (a rule it cannot express is an error, a warning with `--lossy`); archives are deterministic, `wbn` is an unsigned Web Bundle (needs `BASE` or `--base-url`; `COMPRESSION gzip` gzips it, default `none`), `oci` is a single-layer OCI image of the files (under `AT`, default `/srv/www`; `COMPRESSION` sets its layer, default `gzip`), `car` is an IPFS CARv1 file whose root CID matches kubo's `ipfs add -r --cid-version=1`, `html` is `index.html` with its assets inlined as `data:` URIs, `mhtml` the same page and assets as one MHTML file, `warc` a WARC/1.1 web archive of every file at `BASE` (also imported and served), `swbn` a Signed Web Bundle for an Isolated Web App, signed with the Ed25519 key in `--secret` `KEY`, `wacz` that WARC as a WACZ package for ReplayWeb.page, `epub` an EPUB 3 book of the XHTML pages |
|
|
91
97
|
|
|
92
98
|
Templates can also live in the Sitefile itself (see `examples/inline/`):
|
|
93
99
|
|
|
@@ -174,6 +180,8 @@ sitefile graph [context] [--json | --dot] # dependency graph of imports, st
|
|
|
174
180
|
sitefile why <path> [context] [--json] # which instructions wrote an exported file, and what overwrote it
|
|
175
181
|
sitefile vendor [context] [--vendor-dir vendor/sitefile] # download remote inputs for offline builds
|
|
176
182
|
sitefile outdated [context] [--json] # compare remote imports and BASE images with their pins (read-only)
|
|
183
|
+
sitefile import-config netlify.toml # a host's config (Netlify, Vercel, Firebase, Azure, wrangler, .htaccess) as _redirects/_headers
|
|
184
|
+
sitefile hosts [context] [--json] # the hosts a build would contact and whether they are allowed (no fetch)
|
|
177
185
|
sitefile bake [targets...] [-f sitefile.bake.yaml] [--print [--json]] [-j n] # build several variants
|
|
178
186
|
|
|
179
187
|
# images and servers (see below and docs/CLI.md)
|
|
@@ -184,6 +192,7 @@ sitefile cache du # cache sizes; SITEFILE_
|
|
|
184
192
|
sitefile serve [-d] [--name n] [-p [host:]port] [--spa] <image|./dir|site.zip>
|
|
185
193
|
sitefile serve --watch [-p [host:]port] [--spa] [context] # build in memory, serve, live reload
|
|
186
194
|
sitefile servers [-a] | server stop|rm [-f]|restart|logs [-f] <name>
|
|
195
|
+
sitefile up | down | ps [-f sitefile.servers.yaml] # several servers from one file, like docker compose
|
|
187
196
|
```
|
|
188
197
|
|
|
189
198
|
`--target <stage>` (like `docker build --target`) stops after a named stage and exports that stage's whole
|
|
@@ -325,7 +334,7 @@ stopgap in VS Code.
|
|
|
325
334
|
- [docs/RUST.md](docs/RUST.md) — the Rust port: layout, parity checks, known differences
|
|
326
335
|
- [docs/LSP.md](docs/LSP.md) — the language server for editors (`sitefile lsp`, Rust binary)
|
|
327
336
|
- [docs/PLUGINS.md](docs/PLUGINS.md) — writing renderer plugins, and the sandbox
|
|
328
|
-
- [docs/DOCKER.md](docs/DOCKER.md) —
|
|
337
|
+
- [docs/DOCKER.md](docs/DOCKER.md) — sitefile next to Docker: site images Docker runs, Dockerfile stages, shared registries
|
|
329
338
|
- [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) — invariants and module layout
|
|
330
339
|
- [docs/MILESTONES.md](docs/MILESTONES.md), [docs/TASKS.md](docs/TASKS.md)
|
|
331
340
|
- [AGENTS.md](AGENTS.md) — the verification loop and rules for anyone (human or agent) changing this repo
|
|
@@ -380,7 +389,7 @@ stage), so building one is treated as running untrusted input. Templates,
|
|
|
380
389
|
imports and WebAssembly plugins are data; JavaScript plugins and external
|
|
381
390
|
tools are code, and run only when you name them on the command line.
|
|
382
391
|
|
|
383
|
-
**What
|
|
392
|
+
**What sitefile guarantees:**
|
|
384
393
|
|
|
385
394
|
- **Local reads stay inside the build context.** No `..`, absolute paths or
|
|
386
395
|
symlinks out; hard-linked files are refused (`E_HARDLINK`) unless
|
|
@@ -395,6 +404,14 @@ tools are code, and run only when you name them on the command line.
|
|
|
395
404
|
checks the target itself before handing it to the proxy. `--allow-hosts` and
|
|
396
405
|
`--deny-hosts` narrow it further, on every hop
|
|
397
406
|
([docs/CLI.md](docs/CLI.md#network-proxy-host-rules-and-timeouts)).
|
|
407
|
+
- **Strict network mode is opt-in.** With `--network strict` (or
|
|
408
|
+
`SITEFILE_NETWORK=strict`) a build contacts only hosts you list with
|
|
409
|
+
`--allow-hosts`, none when you list none. A refused host fails with
|
|
410
|
+
`E_HOST_BLOCKED` naming the flag to add, also as `needs` in the library
|
|
411
|
+
error and in `--json` output, so a tool can ask before allowing it.
|
|
412
|
+
`sitefile hosts` lists the hosts a build needs before any is contacted. A
|
|
413
|
+
vendored build with pinned, stored images contacts nothing
|
|
414
|
+
([docs/CLI.md](docs/CLI.md#strict-network-mode)).
|
|
398
415
|
- **Pins are enforced.** Unpinned URLs are recorded in `Sitefile.lock` and must
|
|
399
416
|
match on later builds; `--strict-pins` refuses any remote import or BASE image
|
|
400
417
|
that is not pinned (`INTEGRITY`, `@sha256:` or a lockfile entry).
|
|
@@ -405,15 +422,35 @@ tools are code, and run only when you name them on the command line.
|
|
|
405
422
|
- **Secrets go only where they are sent.** `--secret id=token,env=API_TOKEN` with
|
|
406
423
|
`IMPORT … SECRET token AS BEARER` (or `AS HEADER X-Api-Key`) sends the secret
|
|
407
424
|
only to that import's own origin, and never into the output, caches,
|
|
408
|
-
`Sitefile.lock`, vendor files, provenance, traces or messages.
|
|
425
|
+
`Sitefile.lock`, vendor files, provenance, traces or messages. In strict mode a
|
|
426
|
+
secret is sent only to a host that `--allow-secret-host <id>=<host>` names.
|
|
409
427
|
- **Nothing executes unless you allow it by name.** A JavaScript `PLUGIN` runs
|
|
410
428
|
only with `--allow-plugin <name>`, in its own Node process under Node's
|
|
411
429
|
permission model (read access to its own folder only, no writes, network,
|
|
412
|
-
processes or environment)
|
|
430
|
+
processes or environment) with a heap limit (`--plugin-memory`, default
|
|
431
|
+
1 GiB), on a Node you can name with `--node` (checked to be at least Node 26
|
|
432
|
+
and printed); a `TOOL` runs only with `--allow-exec <name>`, argv
|
|
413
433
|
only, no shell, scrubbed environment. The Sitefile cannot allow itself. A
|
|
414
|
-
|
|
434
|
+
JavaScript plugin's `INTEGRITY` pins its whole folder (everything it can
|
|
435
|
+
read), a wasm plugin's its module. A WebAssembly plugin must import nothing (checked before the build starts) and
|
|
415
436
|
runs with a time and memory limit, so it needs no flag
|
|
416
437
|
([docs/PLUGINS.md](docs/PLUGINS.md#trust-model---allow-plugin)).
|
|
438
|
+
- **`serve` answers only local names.** A request whose `Host` is not
|
|
439
|
+
`localhost`, `*.localhost` or an IP address is refused (`403`), so a web page
|
|
440
|
+
that DNS-rebinds its name to `127.0.0.1` cannot read a local server;
|
|
441
|
+
`--allowed-host` adds names ([docs/CLI.md](docs/CLI.md#site-servers)).
|
|
442
|
+
- **Caches are trusted.** A TRANSFORM cache hit (local, or from
|
|
443
|
+
`--cache-from <registry>`) is used as if the plugin had returned it, and the
|
|
444
|
+
Rust build loads compiled wasm modules from `$SITEFILE_HOME/cache/wasm` as
|
|
445
|
+
native code (kept `0700`/`0600`). Only pull caches from registries you
|
|
446
|
+
trust; `--no-cache` skips them
|
|
447
|
+
([docs/PLUGINS.md](docs/PLUGINS.md#what-sitefile-trusts-as-is)). JavaScript
|
|
448
|
+
plugins say whether they are deterministic with `export const cache =
|
|
449
|
+
true|false`; one that says neither is cached with a warning.
|
|
450
|
+
- **Sharing a server with `--auth`** keeps people who lack the password out
|
|
451
|
+
(basic authentication on every request, passwords stored only as PBKDF2
|
|
452
|
+
verifiers). It does not hide the traffic: over plain HTTP on a LAN the
|
|
453
|
+
password and the pages travel in the clear, so use it on networks you trust.
|
|
417
454
|
- **No silent overwrites.** Writing different content to an existing path fails
|
|
418
455
|
unless `--overwrite` is given. Two output paths that differ only in case
|
|
419
456
|
(`/A.html`, `/a.html`) always fail (`E_PATH_COLLISION`), and every path is
|
|
@@ -431,6 +468,11 @@ tools are code, and run only when you name them on the command line.
|
|
|
431
468
|
([docs/LANGUAGE.md](docs/LANGUAGE.md#vendoring-sitefile-vendor)).
|
|
432
469
|
- **`sitefile serve` listens on `127.0.0.1`**, GET/HEAD only, no directory
|
|
433
470
|
listings, unless `-p` names another address.
|
|
471
|
+
- **`serve` proxies only where you allow it.** A `_redirects` proxy rule (200
|
|
472
|
+
to a URL) in a site you serve reaches only hosts in `--allow-hosts`; others
|
|
473
|
+
get a `502` naming the flag. `--proxy /api=url` is allowed by being written.
|
|
474
|
+
Both follow the build fetch policy above and never forward cookies or
|
|
475
|
+
`Authorization` ([docs/CLI.md](docs/CLI.md#site-servers)).
|
|
434
476
|
|
|
435
477
|
**What is still yours:**
|
|
436
478
|
|
|
@@ -447,14 +489,21 @@ tools are code, and run only when you name them on the command line.
|
|
|
447
489
|
`INTEGRITY`, `@sha256:` and `--strict-pins` for builds that must be
|
|
448
490
|
reproducible.
|
|
449
491
|
- **Web Bundles are unsigned.** `EXPORT … AS wbn` writes an unsigned b2 bundle;
|
|
450
|
-
signing (for example for an Isolated Web App) happens outside
|
|
492
|
+
signing (for example for an Isolated Web App) happens outside sitefile.
|
|
493
|
+
- **Which hosts an open build contacts.** The default network mode is `open`:
|
|
494
|
+
a Sitefile you did not write may make the build contact any public HTTPS
|
|
495
|
+
host its author chose (telling it your IP address and when you build),
|
|
496
|
+
clone Git repositories and pull registry images, and send a `--secret` you
|
|
497
|
+
supplied to the host its `IMPORT … SECRET` names. Use `--network strict`
|
|
498
|
+
with `--allow-hosts` (and `--allow-secret-host`) for builds you did not
|
|
499
|
+
write.
|
|
451
500
|
- **Widening flags are yours to justify.** `--allow-http`,
|
|
452
501
|
`--allow-private-network`, `--allow-hardlinks`, `--force` and `serve -p
|
|
453
502
|
0.0.0.0:…` each turn off one of the guarantees above for that build.
|
|
454
503
|
|
|
455
504
|
## Family
|
|
456
505
|
|
|
457
|
-
|
|
506
|
+
sitefile is the build orchestrator of the @johnhenry family's static tools. It
|
|
458
507
|
runs the pipeline (pinned imports, stages, templates, sandboxed plugins, checks,
|
|
459
508
|
exports); its siblings write file trees in code and serve the result. It has no
|
|
460
509
|
runtime dependency on either: they meet at file formats, a directory, a zip or
|
|
@@ -462,7 +511,7 @@ a `.wbn` Web Bundle.
|
|
|
462
511
|
|
|
463
512
|
- **[`@johnhenry/fileable`](https://github.com/johnhenry/fileable)** -- writes
|
|
464
513
|
file trees in JSX (`Dir`, `File`, `Rm`), for scaffolding and codegen. A
|
|
465
|
-
fileable build's output is an ordinary
|
|
514
|
+
fileable build's output is an ordinary sitefile input. Neither package
|
|
466
515
|
depends on the other.
|
|
467
516
|
- **[`@johnhenry/packfile`](https://github.com/johnhenry/packfile)** -- the
|
|
468
517
|
family's Web Bundle reader and in-memory server. It reads what `EXPORT … AS
|
|
@@ -479,14 +528,14 @@ not published: the npm versions still behave as the rest of that row says.
|
|
|
479
528
|
|
|
480
529
|
| From | To | How | Status |
|
|
481
530
|
| --- | --- | --- | --- |
|
|
482
|
-
| fileable, loose output |
|
|
483
|
-
| fileable, `encode="zip"` |
|
|
484
|
-
| fileable, `encode="wbn"` |
|
|
531
|
+
| fileable, loose output | sitefile | `COPY ./generated/ /` | Works |
|
|
532
|
+
| fileable, `encode="zip"` | sitefile | `IMPORT gen FROM ./site.zip AS tree`, then `COPY gen:/ /` | Works (same output as loose) |
|
|
533
|
+
| fileable, `encode="wbn"` | sitefile | `IMPORT … AS tree` | **Not yet:** it's gzip around a Web Bundle, and `AS tree` reads only plain bundles ([#141](https://github.com/johnhenry/sitefile/issues/141)) |
|
|
485
534
|
| fileable tree, rendered during a build | Sitefile | a JavaScript `TRANSFORM` plugin calling fileable's in-memory `toFiles()` | An example on main, not part of the npm package: [`examples/fileable/`](examples/fileable/) ([#145](https://github.com/johnhenry/sitefile/issues/145)). fileable is vendored into the plugin folder; `cmd`, local `src=` and `env://` fail with `E_PLUGIN` |
|
|
486
|
-
|
|
|
487
|
-
|
|
|
488
|
-
|
|
|
489
|
-
| packfile `toArchive()` |
|
|
535
|
+
| sitefile, `EXPORT / AS wbn BASE <url>` | packfile | `fromWebBundle(buffer, { baseURL })` from `@johnhenry/packfile/web-bundle`, then `createRouter(files)` | Works; tested here (`test/packfile-interop.test.ts`), and packfile's own tests read a bundle written by sitefile 0.0.0 |
|
|
536
|
+
| sitefile `.wbn` | packfile `fromArchive()` | with 0.0.0 / 0.2.0: gzip it, and export with `BASE https://packfile.invalid/` | Works with that workaround. **Fixed on main, in the next release:** `EXPORT … AS wbn COMPRESSION gzip` (or `-o site.wbn.gz`) writes the gzip ([#143](https://github.com/johnhenry/sitefile/issues/143)), and `fromArchive()` takes a `baseURL` or the origin of the bundle's primary URL, so any `BASE` reads back ([packfile#18](https://github.com/johnhenry/packfile/issues/18)) |
|
|
537
|
+
| sitefile `HEADER` / `REDIRECT` | packfile `createWebBundleRouter()` | -- | **Not applied in 0.0.0:** only the `/_headers` and `/_redirects` files are in the bundle. **Fixed on main, in the next release:** each response carries its HEADER values, and exact-path 301/302/303/307/308 REDIRECTs are 3xx responses with `location` ([#144](https://github.com/johnhenry/sitefile/issues/144)). Splats, `200` rewrites and `404` rules stay in `/_redirects` only |
|
|
538
|
+
| packfile `toArchive()` | sitefile | `IMPORT … AS tree` | **Not yet** (same as fileable's `.wbn`, [#141](https://github.com/johnhenry/sitefile/issues/141)) |
|
|
490
539
|
|
|
491
540
|
Gotchas when serving a Sitefile bundle with packfile:
|
|
492
541
|
|
|
@@ -494,14 +543,14 @@ Gotchas when serving a Sitefile bundle with packfile:
|
|
|
494
543
|
for `/docs/ünï/page.html` returns 404 because the pathname isn't
|
|
495
544
|
percent-decoded; the string `"/docs/ünï/page.html"` works
|
|
496
545
|
([packfile#20](https://github.com/johnhenry/packfile/issues/20)).
|
|
497
|
-
- **`fromWebBundle` skips the bundle's entry at the bare base URL.**
|
|
546
|
+
- **`fromWebBundle` skips the bundle's entry at the bare base URL.** sitefile
|
|
498
547
|
stores the index page there as well as at `/index.html`; you get it from
|
|
499
548
|
`index.html`.
|
|
500
549
|
- **The `baseURL` you pass to `fromWebBundle` must be the `BASE` you exported
|
|
501
550
|
with.** Entries under any other origin are skipped, so the wrong base reads
|
|
502
551
|
back as an empty map, without an error. packfile's `fromArchive()` on its
|
|
503
552
|
main branch (next release) defaults to the origin of the primary URL, which
|
|
504
|
-
|
|
553
|
+
sitefile writes only when the site has `/index.html`; with a `BASE` that has
|
|
505
554
|
a path (`https://site.example/blog/`), the keys start with `blog/` unless you
|
|
506
555
|
pass that `baseURL`.
|
|
507
556
|
- **HEADER and REDIRECT need `createWebBundleRouter()`** (on main, next
|
|
@@ -21,8 +21,18 @@ export interface WriterOptions {
|
|
|
21
21
|
/** Read `SOURCE_DATE_EPOCH`; undefined if unset, E_USAGE if malformed. */
|
|
22
22
|
export declare function sourceDateEpoch(env?: NodeJS.ProcessEnv): number | undefined;
|
|
23
23
|
export { crc32 };
|
|
24
|
-
/**
|
|
25
|
-
export declare
|
|
24
|
+
/** File extensions (ASCII, lowercase) whose content is already compressed; zip stores them without deflating. */
|
|
25
|
+
export declare const COMPRESSED_MEDIA: string[];
|
|
26
|
+
/** Whether a zip entry name ends in an already-compressed media extension ({@link COMPRESSED_MEDIA}), ASCII case-insensitively. */
|
|
27
|
+
export declare function isCompressedMedia(name: string): boolean;
|
|
28
|
+
/**
|
|
29
|
+
* Zip (no zip64). Deflate when it shrinks the data, otherwise stored.
|
|
30
|
+
*
|
|
31
|
+
* `first` (tree paths, e.g. `['/mimetype']` for EPUB): these entries come first, in that order, stored
|
|
32
|
+
* and without an extra field (the EPUB container requires its `mimetype` entry that way); the rest
|
|
33
|
+
* follow in path order as usual.
|
|
34
|
+
*/
|
|
35
|
+
export declare function writeZip(tree: Tree, options?: WriterOptions, first?: readonly string[]): Uint8Array;
|
|
26
36
|
/** POSIX ustar; long names use the prefix field, then a pax `path` extended header. */
|
|
27
37
|
export declare function writeTar(tree: Tree, options?: WriterOptions): Uint8Array;
|
|
28
38
|
/** gzip of the tar, header mtime 0 and no filename, so the stream is reproducible. */
|
|
@@ -34,21 +34,63 @@ function dosDateTime(epoch) {
|
|
|
34
34
|
date: ((year - 1980) << 9) | ((d.getUTCMonth() + 1) << 5) | d.getUTCDate(),
|
|
35
35
|
};
|
|
36
36
|
}
|
|
37
|
-
/**
|
|
38
|
-
export
|
|
39
|
-
|
|
37
|
+
/** File extensions (ASCII, lowercase) whose content is already compressed; zip stores them without deflating. */
|
|
38
|
+
export const COMPRESSED_MEDIA = [
|
|
39
|
+
'png', 'jpg', 'jpeg', 'gif', 'webp', 'avif', 'heic', 'jxl',
|
|
40
|
+
'woff', 'woff2',
|
|
41
|
+
'mp3', 'm4a', 'aac', 'ogg', 'oga', 'opus', 'flac',
|
|
42
|
+
'mp4', 'm4v', 'webm', 'mov', 'mkv',
|
|
43
|
+
'zip', 'gz', 'tgz', 'br', 'zst', 'xz', 'bz2', '7z', 'rar', 'wbn',
|
|
44
|
+
];
|
|
45
|
+
const COMPRESSED = new Set(COMPRESSED_MEDIA);
|
|
46
|
+
/** Whether a zip entry name ends in an already-compressed media extension ({@link COMPRESSED_MEDIA}), ASCII case-insensitively. */
|
|
47
|
+
export function isCompressedMedia(name) {
|
|
48
|
+
const base = name.slice(name.lastIndexOf('/') + 1);
|
|
49
|
+
const dot = base.lastIndexOf('.');
|
|
50
|
+
return dot > 0 && COMPRESSED.has(base.slice(dot + 1).replace(/[A-Z]/g, (c) => c.toLowerCase()));
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* The extended-timestamp extra field (0x5455 "UT", APPNOTE 4.4.6, Info-ZIP extrafld.txt) with the
|
|
54
|
+
* modification time only: unlike the DOS time, which unzippers read as local time, it is UTC
|
|
55
|
+
* seconds, so SOURCE_DATE_EPOCH survives extraction in any time zone. The same 9 bytes go in the
|
|
56
|
+
* local and the central header. Without an epoch it says 1980-01-01, as the DOS time does.
|
|
57
|
+
*/
|
|
58
|
+
function extendedTimestamp(epoch) {
|
|
59
|
+
const ut = Buffer.alloc(9);
|
|
60
|
+
ut.writeUInt16LE(0x5455, 0);
|
|
61
|
+
ut.writeUInt16LE(5, 2);
|
|
62
|
+
ut[4] = 1; // mtime present
|
|
63
|
+
ut.writeUInt32LE(Math.min(Math.max(epoch ?? 315532800, 0), 0xffffffff), 5);
|
|
64
|
+
return ut;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Zip (no zip64). Deflate when it shrinks the data, otherwise stored.
|
|
68
|
+
*
|
|
69
|
+
* `first` (tree paths, e.g. `['/mimetype']` for EPUB): these entries come first, in that order, stored
|
|
70
|
+
* and without an extra field (the EPUB container requires its `mimetype` entry that way); the rest
|
|
71
|
+
* follow in path order as usual.
|
|
72
|
+
*/
|
|
73
|
+
export function writeZip(tree, options = {}, first = []) {
|
|
74
|
+
const all = entriesOf(tree);
|
|
75
|
+
const firstNames = first.map((p) => p.slice(1));
|
|
76
|
+
const plain = new Set(firstNames);
|
|
77
|
+
const entries = [...firstNames.flatMap((n) => all.filter((e) => e.name === n)), ...all.filter((e) => !plain.has(e.name))];
|
|
40
78
|
if (entries.length > ZIP_MAX_ENTRIES) {
|
|
41
79
|
throw new SitefileError('E_EXPORT', `zip export supports at most ${ZIP_MAX_ENTRIES} entries (zip64 is not implemented); got ${entries.length}`);
|
|
42
80
|
}
|
|
43
81
|
const { time, date } = dosDateTime(options.epoch);
|
|
82
|
+
const ut = extendedTimestamp(options.epoch);
|
|
44
83
|
const chunks = [];
|
|
45
84
|
const central = [];
|
|
46
85
|
let offset = 0;
|
|
47
86
|
for (const e of entries) {
|
|
48
87
|
if (e.nameBytes.length > 0xffff)
|
|
49
88
|
throw new SitefileError('E_EXPORT', `zip entry name is too long (${e.nameBytes.length} bytes): '${e.name.slice(0, 60)}…'`);
|
|
50
|
-
const
|
|
51
|
-
|
|
89
|
+
const isPlain = plain.has(e.name);
|
|
90
|
+
// Already-compressed media is stored as is: deflate would only spend time to gain nothing (#203).
|
|
91
|
+
const deflated = isPlain || isCompressedMedia(e.name) ? undefined : deflateRaw(e.bytes);
|
|
92
|
+
const stored = deflated === undefined || deflated.length >= e.bytes.length;
|
|
93
|
+
const extra = isPlain ? Buffer.alloc(0) : ut;
|
|
52
94
|
const data = stored ? e.bytes : deflated;
|
|
53
95
|
if (e.bytes.length > ZIP_MAX || data.length > ZIP_MAX) {
|
|
54
96
|
throw new SitefileError('E_EXPORT', `zip export does not support files of 4 GiB or more (zip64 is not implemented): '/${e.name}'`);
|
|
@@ -68,7 +110,7 @@ export function writeZip(tree, options = {}) {
|
|
|
68
110
|
lh.writeUInt32LE(data.length, 18);
|
|
69
111
|
lh.writeUInt32LE(e.bytes.length, 22);
|
|
70
112
|
lh.writeUInt16LE(e.nameBytes.length, 26);
|
|
71
|
-
lh.writeUInt16LE(
|
|
113
|
+
lh.writeUInt16LE(extra.length, 28);
|
|
72
114
|
const ch = Buffer.alloc(46);
|
|
73
115
|
ch.writeUInt32LE(0x02014b50, 0);
|
|
74
116
|
ch.writeUInt16LE((3 << 8) | 20, 4); // made by: Unix, spec 2.0
|
|
@@ -81,12 +123,13 @@ export function writeZip(tree, options = {}) {
|
|
|
81
123
|
ch.writeUInt32LE(data.length, 20);
|
|
82
124
|
ch.writeUInt32LE(e.bytes.length, 24);
|
|
83
125
|
ch.writeUInt16LE(e.nameBytes.length, 28);
|
|
84
|
-
|
|
126
|
+
ch.writeUInt16LE(extra.length, 30);
|
|
127
|
+
// comment, disk number, internal attrs = 0
|
|
85
128
|
ch.writeUInt32LE(((0o100000 | e.mode) << 16) >>> 0, 38);
|
|
86
129
|
ch.writeUInt32LE(offset, 42);
|
|
87
|
-
chunks.push(lh, e.nameBytes, data);
|
|
88
|
-
central.push(ch, e.nameBytes);
|
|
89
|
-
offset += 30 + e.nameBytes.length + data.length;
|
|
130
|
+
chunks.push(lh, e.nameBytes, extra, data);
|
|
131
|
+
central.push(ch, e.nameBytes, extra);
|
|
132
|
+
offset += 30 + e.nameBytes.length + extra.length + data.length;
|
|
90
133
|
}
|
|
91
134
|
const cdSize = central.reduce((n, c) => n + c.length, 0);
|
|
92
135
|
if (offset + cdSize > ZIP_MAX)
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { SourceSpan } from './errors.js';
|
|
2
|
+
import { type Tree } from './tree.js';
|
|
3
|
+
export interface CanonicalOp {
|
|
4
|
+
readonly base: string;
|
|
5
|
+
readonly pretty: boolean;
|
|
6
|
+
readonly root: string;
|
|
7
|
+
readonly span: SourceSpan;
|
|
8
|
+
}
|
|
9
|
+
/** A page's canonical URL: `<base><url path>`, `…/index.html` as its directory, and with `pretty` no `.html`. */
|
|
10
|
+
export declare function canonicalUrl(base: string, url: string, pretty: boolean): string;
|
|
11
|
+
/**
|
|
12
|
+
* The tree with `<link rel="canonical" href="…">` inserted before `</head>` of every `.html`/`.htm` page
|
|
13
|
+
* below `root` (except `/404.html` there) that is valid UTF-8 and has no canonical link yet. Pages without
|
|
14
|
+
* a `</head>` are left as they are, and named in one warning.
|
|
15
|
+
*/
|
|
16
|
+
export declare function canonical(tree: Tree, op: CanonicalOp, origin: string, warn: (m: string) => void): Tree;
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { canonicalSlot, referenceKind } from './links.js';
|
|
2
|
+
import { pageUrl, xmlEscape } from './site.js';
|
|
3
|
+
import { makeFile } from './tree.js';
|
|
4
|
+
const UTF8 = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
|
|
5
|
+
/** A page's canonical URL: `<base><url path>`, `…/index.html` as its directory, and with `pretty` no `.html`. */
|
|
6
|
+
export function canonicalUrl(base, url, pretty) {
|
|
7
|
+
const u = pretty && url.endsWith('.html') && !url.endsWith('/index.html') ? url.slice(0, -'.html'.length) : url;
|
|
8
|
+
return pageUrl(base, u);
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* The tree with `<link rel="canonical" href="…">` inserted before `</head>` of every `.html`/`.htm` page
|
|
12
|
+
* below `root` (except `/404.html` there) that is valid UTF-8 and has no canonical link yet. Pages without
|
|
13
|
+
* a `</head>` are left as they are, and named in one warning.
|
|
14
|
+
*/
|
|
15
|
+
export function canonical(tree, op, origin, warn) {
|
|
16
|
+
const files = [];
|
|
17
|
+
const headless = [];
|
|
18
|
+
for (const [p, node] of tree.entries()) {
|
|
19
|
+
if (referenceKind(p) !== 'html')
|
|
20
|
+
continue;
|
|
21
|
+
const url = op.root === '/' ? p : p.startsWith(op.root + '/') ? p.slice(op.root.length) : undefined;
|
|
22
|
+
if (url === undefined || url === '/404.html')
|
|
23
|
+
continue;
|
|
24
|
+
let text;
|
|
25
|
+
try {
|
|
26
|
+
text = UTF8.decode(node.bytes);
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
continue;
|
|
30
|
+
}
|
|
31
|
+
const at = canonicalSlot(text);
|
|
32
|
+
if (at === 'has')
|
|
33
|
+
continue;
|
|
34
|
+
if (at === undefined) {
|
|
35
|
+
headless.push(p);
|
|
36
|
+
continue;
|
|
37
|
+
}
|
|
38
|
+
const link = `<link rel="canonical" href="${xmlEscape(canonicalUrl(op.base, url, op.pretty))}">`;
|
|
39
|
+
files.push([p, makeFile(new TextEncoder().encode(text.slice(0, at) + link + text.slice(at)), origin, node.mode)]);
|
|
40
|
+
}
|
|
41
|
+
if (headless.length > 0) {
|
|
42
|
+
warn(`${origin}: ${headless.length === 1 ? '1 page has' : `${headless.length} pages have`} no </head>, so no canonical link was added: ${headless.join(', ')}`);
|
|
43
|
+
}
|
|
44
|
+
return files.length ? tree.withFiles(files, 'overwrite', op.span) : tree;
|
|
45
|
+
}
|
|
46
|
+
//# sourceMappingURL=canonical.js.map
|
package/lib/src/car.d.ts
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { Tree } from './tree.js';
|
|
2
|
+
/**
|
|
3
|
+
* `EXPORT … AS car` (issue #208): the tree as a UnixFS DAG in a CARv1 file, the way
|
|
4
|
+
* `ipfs add -r --hidden --cid-version=1` (kubo) builds it, so the root CID is the one kubo
|
|
5
|
+
* prints for the same directory:
|
|
6
|
+
*
|
|
7
|
+
* - files are cut into 262144-byte chunks (kubo's default `size-262144` chunker); each chunk
|
|
8
|
+
* is a raw block (CIDv1, codec raw 0x55); a one-chunk file is that block;
|
|
9
|
+
* - longer files are a balanced tree of dag-pb UnixFS File nodes of at most 174 links;
|
|
10
|
+
* - directories are dag-pb UnixFS Directory nodes, links sorted by name (no HAMT sharding:
|
|
11
|
+
* a directory large enough for kubo to shard is refused);
|
|
12
|
+
* - every CID is v1 with a SHA-256 multihash; the root is the tree's `/` directory.
|
|
13
|
+
*
|
|
14
|
+
* The CAR holds every block once, root first, then depth first in link order. No
|
|
15
|
+
* timestamps or modes are recorded (kubo stores neither by default), so the output
|
|
16
|
+
* depends only on paths and contents.
|
|
17
|
+
*/
|
|
18
|
+
export declare const CHUNK_SIZE = 262144;
|
|
19
|
+
export declare const MAX_LINKS = 174;
|
|
20
|
+
/** kubo shards a directory (HAMT) when the names and CIDs of its links exceed this many bytes. */
|
|
21
|
+
export declare const HAMT_THRESHOLD = 262144;
|
|
22
|
+
/** A CID as text: multibase base32 (lower case, no padding) with the `b` prefix. */
|
|
23
|
+
export declare function cidString(cid: Uint8Array): string;
|
|
24
|
+
/** The root CID of `tree` as `EXPORT … AS car` writes it. */
|
|
25
|
+
export declare function carRoot(tree: Tree): string;
|
|
26
|
+
/** CARv1: a dag-cbor header `{roots: [root], version: 1}`, then each block as varint(len) CID data. */
|
|
27
|
+
export declare function writeCar(tree: Tree): Uint8Array;
|
|
28
|
+
/** {@link writeCar} and the root CID. */
|
|
29
|
+
export declare function encodeCar(tree: Tree): {
|
|
30
|
+
bytes: Uint8Array;
|
|
31
|
+
root: string;
|
|
32
|
+
};
|
|
33
|
+
/** The CID of one file's UnixFS DAG (a raw block for a file of one chunk). */
|
|
34
|
+
export declare function fileCid(bytes: Uint8Array): string;
|
package/lib/src/car.js
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { SitefileError } from './errors.js';
|
|
3
|
+
/**
|
|
4
|
+
* `EXPORT … AS car` (issue #208): the tree as a UnixFS DAG in a CARv1 file, the way
|
|
5
|
+
* `ipfs add -r --hidden --cid-version=1` (kubo) builds it, so the root CID is the one kubo
|
|
6
|
+
* prints for the same directory:
|
|
7
|
+
*
|
|
8
|
+
* - files are cut into 262144-byte chunks (kubo's default `size-262144` chunker); each chunk
|
|
9
|
+
* is a raw block (CIDv1, codec raw 0x55); a one-chunk file is that block;
|
|
10
|
+
* - longer files are a balanced tree of dag-pb UnixFS File nodes of at most 174 links;
|
|
11
|
+
* - directories are dag-pb UnixFS Directory nodes, links sorted by name (no HAMT sharding:
|
|
12
|
+
* a directory large enough for kubo to shard is refused);
|
|
13
|
+
* - every CID is v1 with a SHA-256 multihash; the root is the tree's `/` directory.
|
|
14
|
+
*
|
|
15
|
+
* The CAR holds every block once, root first, then depth first in link order. No
|
|
16
|
+
* timestamps or modes are recorded (kubo stores neither by default), so the output
|
|
17
|
+
* depends only on paths and contents.
|
|
18
|
+
*/
|
|
19
|
+
export const CHUNK_SIZE = 262144;
|
|
20
|
+
export const MAX_LINKS = 174;
|
|
21
|
+
/** kubo shards a directory (HAMT) when the names and CIDs of its links exceed this many bytes. */
|
|
22
|
+
export const HAMT_THRESHOLD = 262144;
|
|
23
|
+
const RAW = 0x55;
|
|
24
|
+
const DAG_PB = 0x70;
|
|
25
|
+
function varint(n) {
|
|
26
|
+
const out = [];
|
|
27
|
+
let v = n;
|
|
28
|
+
while (v >= 0x80) {
|
|
29
|
+
out.push((v % 0x80) | 0x80);
|
|
30
|
+
v = Math.floor(v / 0x80);
|
|
31
|
+
}
|
|
32
|
+
out.push(v);
|
|
33
|
+
return out;
|
|
34
|
+
}
|
|
35
|
+
function concat(parts) {
|
|
36
|
+
let n = 0;
|
|
37
|
+
for (const p of parts)
|
|
38
|
+
n += p.byteLength;
|
|
39
|
+
const out = new Uint8Array(n);
|
|
40
|
+
let o = 0;
|
|
41
|
+
for (const p of parts) {
|
|
42
|
+
out.set(p, o);
|
|
43
|
+
o += p.byteLength;
|
|
44
|
+
}
|
|
45
|
+
return out;
|
|
46
|
+
}
|
|
47
|
+
/** CIDv1 bytes: version, codec, sha2-256 multihash. */
|
|
48
|
+
function cidOf(codec, block) {
|
|
49
|
+
const digest = createHash('sha256').update(block).digest();
|
|
50
|
+
return new Uint8Array([1, codec, 0x12, 0x20, ...digest]);
|
|
51
|
+
}
|
|
52
|
+
const B32 = 'abcdefghijklmnopqrstuvwxyz234567';
|
|
53
|
+
/** A CID as text: multibase base32 (lower case, no padding) with the `b` prefix. */
|
|
54
|
+
export function cidString(cid) {
|
|
55
|
+
let out = 'b';
|
|
56
|
+
let bits = 0;
|
|
57
|
+
let value = 0;
|
|
58
|
+
for (const byte of cid) {
|
|
59
|
+
value = (value << 8) | byte;
|
|
60
|
+
bits += 8;
|
|
61
|
+
while (bits >= 5) {
|
|
62
|
+
out += B32[(value >>> (bits - 5)) & 31];
|
|
63
|
+
bits -= 5;
|
|
64
|
+
}
|
|
65
|
+
value &= (1 << bits) - 1;
|
|
66
|
+
}
|
|
67
|
+
if (bits > 0)
|
|
68
|
+
out += B32[(value << (5 - bits)) & 31];
|
|
69
|
+
return out;
|
|
70
|
+
}
|
|
71
|
+
// --- protobuf (only what dag-pb and UnixFS need) ------------------------------
|
|
72
|
+
const field = (num, wire) => varint(num * 8 + wire);
|
|
73
|
+
const pbVarint = (num, v) => [...field(num, 0), ...varint(v)];
|
|
74
|
+
const pbBytes = (num, b) => concat([new Uint8Array([...field(num, 2), ...varint(b.byteLength)]), b]);
|
|
75
|
+
/** UnixFS `Data` message: Type, filesize, blocksizes (Data and the rest omitted). */
|
|
76
|
+
function unixfs(type, filesize, blocksizes = []) {
|
|
77
|
+
return new Uint8Array([...pbVarint(1, type), ...(filesize !== undefined ? pbVarint(3, filesize) : []), ...blocksizes.flatMap((s) => pbVarint(4, s))]);
|
|
78
|
+
}
|
|
79
|
+
/** A dag-pb node: links first (field 2), then data (field 1), as the dag-pb spec's canonical form has it. */
|
|
80
|
+
function dagPb(links, data) {
|
|
81
|
+
const enc = new TextEncoder();
|
|
82
|
+
const parts = links.map((l) => pbBytes(2, concat([pbBytes(1, l.cid), pbBytes(2, enc.encode(l.name)), new Uint8Array(pbVarint(3, l.tsize))])));
|
|
83
|
+
return concat([...parts, pbBytes(1, data)]);
|
|
84
|
+
}
|
|
85
|
+
class Dag {
|
|
86
|
+
/** Blocks by CID (hex), in creation order, and their children for the CAR walk. */
|
|
87
|
+
blocks = new Map();
|
|
88
|
+
put(codec, data, children) {
|
|
89
|
+
const cid = cidOf(codec, data);
|
|
90
|
+
const key = Buffer.from(cid).toString('hex');
|
|
91
|
+
if (!this.blocks.has(key))
|
|
92
|
+
this.blocks.set(key, { cid, data, children });
|
|
93
|
+
return cid;
|
|
94
|
+
}
|
|
95
|
+
file(bytes) {
|
|
96
|
+
const leaves = [];
|
|
97
|
+
for (let o = 0; o < bytes.byteLength || (o === 0 && leaves.length === 0); o += CHUNK_SIZE) {
|
|
98
|
+
const chunk = bytes.subarray(o, Math.min(o + CHUNK_SIZE, bytes.byteLength));
|
|
99
|
+
leaves.push({ cid: this.put(RAW, chunk, []), tsize: chunk.byteLength, fileSize: chunk.byteLength });
|
|
100
|
+
if (bytes.byteLength === 0)
|
|
101
|
+
break;
|
|
102
|
+
}
|
|
103
|
+
if (leaves.length === 1)
|
|
104
|
+
return leaves[0];
|
|
105
|
+
let depth = 1;
|
|
106
|
+
let span = MAX_LINKS;
|
|
107
|
+
while (span < leaves.length) {
|
|
108
|
+
depth++;
|
|
109
|
+
span *= MAX_LINKS;
|
|
110
|
+
}
|
|
111
|
+
return this.fileNode(leaves, depth);
|
|
112
|
+
}
|
|
113
|
+
/** kubo's balanced layout: every subtree but the last is full. */
|
|
114
|
+
fileNode(leaves, depth) {
|
|
115
|
+
let children;
|
|
116
|
+
if (depth === 1)
|
|
117
|
+
children = [...leaves];
|
|
118
|
+
else {
|
|
119
|
+
const per = MAX_LINKS ** (depth - 1);
|
|
120
|
+
children = [];
|
|
121
|
+
for (let i = 0; i < leaves.length; i += per)
|
|
122
|
+
children.push(this.fileNode(leaves.slice(i, i + per), depth - 1));
|
|
123
|
+
}
|
|
124
|
+
const fileSize = children.reduce((n, c) => n + c.fileSize, 0);
|
|
125
|
+
const block = dagPb(children.map((c) => ({ cid: c.cid, name: '', tsize: c.tsize })), unixfs(2, fileSize, children.map((c) => c.fileSize)));
|
|
126
|
+
const cid = this.put(DAG_PB, block, children.map((c) => c.cid));
|
|
127
|
+
return { cid, tsize: block.byteLength + children.reduce((n, c) => n + c.tsize, 0), fileSize };
|
|
128
|
+
}
|
|
129
|
+
dir(path, entries) {
|
|
130
|
+
const enc = new TextEncoder();
|
|
131
|
+
// dag-pb sorts links by name bytes.
|
|
132
|
+
const sorted = [...entries].sort(([a], [b]) => Buffer.compare(enc.encode(a), enc.encode(b)));
|
|
133
|
+
const estimate = sorted.reduce((n, [name, c]) => n + enc.encode(name).byteLength + c.cid.byteLength, 0);
|
|
134
|
+
if (estimate > HAMT_THRESHOLD) {
|
|
135
|
+
throw new SitefileError('E_EXPORT', `car export: directory '${path}' has too many entries for a plain UnixFS directory (IPFS would shard it; HAMT directories are not supported)`);
|
|
136
|
+
}
|
|
137
|
+
const block = dagPb(sorted.map(([name, c]) => ({ cid: c.cid, name, tsize: c.tsize })), unixfs(1));
|
|
138
|
+
const cid = this.put(DAG_PB, block, sorted.map(([, c]) => c.cid));
|
|
139
|
+
return { cid, tsize: block.byteLength + sorted.reduce((n, [, c]) => n + c.tsize, 0), fileSize: 0 };
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
function buildDag(tree) {
|
|
143
|
+
const top = { files: new Map(), dirs: new Map() };
|
|
144
|
+
for (const [p, n] of tree.entries()) {
|
|
145
|
+
const segs = p.slice(1).split('/');
|
|
146
|
+
let d = top;
|
|
147
|
+
for (const s of segs.slice(0, -1)) {
|
|
148
|
+
let next = d.dirs.get(s);
|
|
149
|
+
if (!next)
|
|
150
|
+
d.dirs.set(s, (next = { files: new Map(), dirs: new Map() }));
|
|
151
|
+
d = next;
|
|
152
|
+
}
|
|
153
|
+
d.files.set(segs[segs.length - 1], n.bytes);
|
|
154
|
+
}
|
|
155
|
+
const dag = new Dag();
|
|
156
|
+
const walk = (d, path) => {
|
|
157
|
+
const entries = [];
|
|
158
|
+
for (const [name, sub] of d.dirs)
|
|
159
|
+
entries.push([name, walk(sub, path === '/' ? `/${name}` : `${path}/${name}`)]);
|
|
160
|
+
for (const [name, bytes] of d.files)
|
|
161
|
+
entries.push([name, dag.file(bytes)]);
|
|
162
|
+
return dag.dir(path, entries);
|
|
163
|
+
};
|
|
164
|
+
return { dag, root: walk(top, '/').cid };
|
|
165
|
+
}
|
|
166
|
+
/** The root CID of `tree` as `EXPORT … AS car` writes it. */
|
|
167
|
+
export function carRoot(tree) {
|
|
168
|
+
return cidString(buildDag(tree).root);
|
|
169
|
+
}
|
|
170
|
+
/** CARv1: a dag-cbor header `{roots: [root], version: 1}`, then each block as varint(len) CID data. */
|
|
171
|
+
export function writeCar(tree) {
|
|
172
|
+
return encodeCar(tree).bytes;
|
|
173
|
+
}
|
|
174
|
+
/** {@link writeCar} and the root CID. */
|
|
175
|
+
export function encodeCar(tree) {
|
|
176
|
+
const { dag, root } = buildDag(tree);
|
|
177
|
+
const enc = new TextEncoder();
|
|
178
|
+
// dag-cbor: map(2) "roots" -> [tag 42 bytes(0x00 ‖ cid)], "version" -> 1 (keys by length, then bytes).
|
|
179
|
+
const cidBytes = [0x00, ...root];
|
|
180
|
+
const header = new Uint8Array([0xa2, 0x65, ...enc.encode('roots'), 0x81, 0xd8, 0x2a, 0x58, cidBytes.length, ...cidBytes, 0x67, ...enc.encode('version'), 0x01]);
|
|
181
|
+
const parts = [new Uint8Array(varint(header.byteLength)), header];
|
|
182
|
+
const seen = new Set();
|
|
183
|
+
const stack = [root];
|
|
184
|
+
while (stack.length) {
|
|
185
|
+
const cid = stack.pop();
|
|
186
|
+
const key = Buffer.from(cid).toString('hex');
|
|
187
|
+
if (seen.has(key))
|
|
188
|
+
continue;
|
|
189
|
+
seen.add(key);
|
|
190
|
+
const b = dag.blocks.get(key);
|
|
191
|
+
if (!b)
|
|
192
|
+
throw new Error('car: missing block');
|
|
193
|
+
parts.push(new Uint8Array(varint(cid.byteLength + b.data.byteLength)), cid, b.data);
|
|
194
|
+
for (let i = b.children.length - 1; i >= 0; i--)
|
|
195
|
+
stack.push(b.children[i]);
|
|
196
|
+
}
|
|
197
|
+
return { bytes: concat(parts), root: cidString(root) };
|
|
198
|
+
}
|
|
199
|
+
/** The CID of one file's UnixFS DAG (a raw block for a file of one chunk). */
|
|
200
|
+
export function fileCid(bytes) {
|
|
201
|
+
return cidString(new Dag().file(bytes).cid);
|
|
202
|
+
}
|
|
203
|
+
//# sourceMappingURL=car.js.map
|