@format.dev/zip 0.0.0 → 0.1.1

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/README.md CHANGED
@@ -1,32 +1,15 @@
1
1
  # @format.dev/zip
2
2
 
3
- **This is a bootstrap placeholder. It reserves the package name and does nothing else.**
3
+ Bundles the assets a Format document references. The scanners find asset references in HTML and CSS, the resolvers read their bytes, and `zip()` packs the archive that travels to the Format API alongside the document.
4
4
 
5
- Format is not released yet. Version `0.0.0` is not a usable version of this
6
- package: it contains no implementation, and installing it gets you an empty
7
- module.
5
+ ## Entry points
8
6
 
9
- ## Why it exists
7
+ - `.` is the Node entry: `zip()`, `zipDir`, the scanners, the resolvers (`dirResolver`, `urlResolver`), and the error types.
8
+ - `./web` runs in browsers, workers, and edge runtimes. It is fully self-contained, because compiled document wrappers import it from bundled code that cannot resolve its dependencies.
9
+ - `./scan` is the slim scanner entry: `scanAssetRefs` and `scanRemoteRefs` only, for compiled documents that never build a ZIP at runtime.
10
10
 
11
- npm binds a package’s trusted publisher, and its staged-publishing flow, to a
12
- package that already exists. Creating these names ahead of the first release is
13
- what lets every real release go out through a reviewed, credential-free
14
- workflow rather than through a token somebody holds.
11
+ Remote asset references are not fetched unless `remoteAssets` is enabled in `ZipOptions`. Fetching per render makes the network a render-time failure mode, so prefer local files.
15
12
 
16
- This version is published deliberately and deprecated immediately.
13
+ ## Node support
17
14
 
18
- ## Why a bare install resolves it
19
-
20
- npm creates a `latest` tag on a package’s first publish and will not remove it,
21
- so `latest` points at this placeholder until Format reaches general
22
- availability. That is why the deprecation warning is there.
23
-
24
- - Beta releases go out under the `beta` tag.
25
- - General availability is when `latest` moves to a real release.
26
-
27
- ## Format
28
-
29
- - https://format.dev
30
- - https://github.com/format-hq/format-js
31
-
32
- Licensed under MIT. The full text ships beside this file.
15
+ Node 22.13 or later. The package ships ES modules only. CommonJS consumers load them through Node's `require()` support for ES modules, which every version from the floor upward provides.
@@ -0,0 +1,279 @@
1
+ import { RemoteAssetFetcher, ZipOptions } from "@format.dev/types";
2
+
3
+ //#region src/types.d.ts
4
+ /** Header forms accepted for remote asset requests. Mirrors the standard `HeadersInit`. */
5
+ type RequestHeaders = Headers | Record<string, string> | [string, string][];
6
+ /** The response headers a server offers for asking later whether an asset changed. */
7
+ interface RemoteValidators {
8
+ etag?: string;
9
+ lastModified?: string;
10
+ }
11
+ interface RemoteAsset {
12
+ bytes: Uint8Array;
13
+ mimeType?: string;
14
+ validators: RemoteValidators;
15
+ }
16
+ /** A remote asset already inside an archive, as `readRemoteAssets` returns it. */
17
+ interface StoredRemoteAsset {
18
+ url: string;
19
+ bytes: Uint8Array;
20
+ }
21
+ /**
22
+ * Resolves a referenced asset path to its bytes. Returns `null` when there is
23
+ * no asset for that path. `zip()` treats this as missing (and throws, unless
24
+ * `skipMissing` is set).
25
+ *
26
+ * A resolver is the single seam through which `zip()` reaches the filesystem,
27
+ * a URL map, or any other store, which is what keeps the package portable
28
+ * across Node, workers, and browsers. `dirResolver` (Node) and `urlResolver`
29
+ * (web) are the built-ins; pass your own for anything else.
30
+ */
31
+ type AssetResolver = (relPath: string) => Promise<Uint8Array | null>;
32
+ //#endregion
33
+ //#region src/zip.d.ts
34
+
35
+ /** Entry names of an existing archive. A static-mode zip's entries are the document's known-asset set. */
36
+ declare function listZipEntries(bytes: Uint8Array): string[];
37
+ /**
38
+ * The remote assets an archive already holds, from the manifest
39
+ * {@link mergeRemoteAssets} writes, sorted by URL. Empty when the archive has
40
+ * no manifest. Lets a caller compare what was bundled with what the server
41
+ * serves now.
42
+ */
43
+ declare function readRemoteAssets(bytes: Uint8Array): StoredRemoteAsset[];
44
+ interface MergeRemoteAssetsArgs {
45
+ html: string;
46
+ /** Existing archive to merge into, or undefined to start fresh. */
47
+ zip?: Uint8Array;
48
+ options?: ZipOptions;
49
+ }
50
+ /**
51
+ * Fetch every remote (http/https) asset `html` references and merge it into an
52
+ * existing archive, alongside a manifest mapping each URL to its zip entry.
53
+ * Remote stylesheets are walked too, so a remote CSS file's fonts and images
54
+ * come along with it. Local CSS already inside the archive is also walked for
55
+ * remote references.
56
+ *
57
+ * URLs already present in the archive's manifest are not fetched again, so
58
+ * calling this repeatedly over the same archive is idempotent and cheap.
59
+ *
60
+ * @returns the merged archive bytes; the input `zip` unchanged when `html`
61
+ * references nothing remote that isn't already bundled; or `undefined` when
62
+ * there is no input archive and nothing remote to fetch.
63
+ * @throws {RemoteAssetFetchError} when the network itself is unreachable.
64
+ */
65
+ declare function mergeRemoteAssets(args: MergeRemoteAssetsArgs): Promise<Uint8Array | undefined>;
66
+ //#endregion
67
+ //#region src/zip-dir.d.ts
68
+ /**
69
+ * Zip the entire contents of a directory, preserving relative paths as entry
70
+ * names ('/'-separated). No HTML scanning — this is the static-asset-mode
71
+ * builder: every known asset ships, so any render works. Only OS-generated
72
+ * junk (`.DS_Store`, `Thumbs.db`, and friends) is skipped.
73
+ *
74
+ * Node-only (reads the filesystem).
75
+ *
76
+ * @returns the archive bytes, or `undefined` when the directory is missing or
77
+ * empty — callers write no zip at all for asset-less documents.
78
+ */
79
+ declare function zipDir(dir: string, options?: ZipOptions): Promise<Uint8Array | undefined>;
80
+ //#endregion
81
+ //#region src/junk-files.d.ts
82
+ /**
83
+ * True when `name` (a single path segment, not a full path) is OS-generated
84
+ * junk rather than a real file. Used to keep these out of asset listings,
85
+ * archives, and cache hashes.
86
+ */
87
+ declare function isSystemJunkFile(name: string): boolean;
88
+ //#endregion
89
+ //#region src/dir-resolver.d.ts
90
+ /**
91
+ * Node-only resolver that reads asset paths from a filesystem directory.
92
+ * Returns `null` for any path that does not resolve to a readable file, or that
93
+ * resolves outside the directory (path-traversal guard).
94
+ *
95
+ * This is what the Node `zip(html, dir)` overload uses under the hood, and the
96
+ * compile-time resolver. It pulls in `node:fs`, so it lives in its own module
97
+ * and is never reachable from the `@format.dev/zip/web` entry.
98
+ */
99
+ declare function dirResolver(dir: string): AssetResolver;
100
+ //#endregion
101
+ //#region src/url-resolver.d.ts
102
+ /**
103
+ * Web-standard resolver that maps asset paths to URLs and fetches them. This is
104
+ * the dynamic-mode runtime resolver: the compiled wrapper bakes in the
105
+ * `{ relPath: url }` map and fetches only the bytes a given render references.
106
+ * Returns `null` for unmapped paths. Portable — uses only `fetch`.
107
+ */
108
+ declare function urlResolver(urlMap: Record<string, string>): AssetResolver;
109
+ //#endregion
110
+ //#region src/helpers.d.ts
111
+ interface RemoteRequestParams {
112
+ url: string;
113
+ headers?: RequestHeaders;
114
+ timeoutMs?: number;
115
+ }
116
+ interface ConditionalRemoteRequestParams extends RemoteRequestParams {
117
+ validators: RemoteValidators;
118
+ }
119
+ /**
120
+ * Fetch a remote asset and return its bytes, parsed MIME type, and the
121
+ * validators the server sent, so a caller holding the bytes can later ask
122
+ * whether they changed with {@link fetchRemoteIfChanged}.
123
+ *
124
+ * Uses `fetch` + `arrayBuffer()` rather than a Node stream so the remote path
125
+ * stays portable across Node, workers, and browsers.
126
+ *
127
+ * @throws {RemoteAssetFetchError} when the network itself fails (offline, DNS,
128
+ * blocked egress, timeout). HTTP error statuses throw a plain Error — the
129
+ * server was reachable, so it's a different problem.
130
+ */
131
+ declare function fetchRemote(params: RemoteRequestParams): Promise<RemoteAsset>;
132
+ /**
133
+ * Ask the server whether a remote asset changed since `validators` were
134
+ * issued. Returns `null` on `304 Not Modified`, otherwise the full asset. A
135
+ * server that sent no validators gets an ordinary request, so this always
136
+ * downloads there.
137
+ *
138
+ * @throws {RemoteAssetFetchError} and plain HTTP errors, as {@link fetchRemote}.
139
+ */
140
+ declare function fetchRemoteIfChanged(params: ConditionalRemoteRequestParams): Promise<RemoteAsset | null>;
141
+ /**
142
+ * Probe each remote URL and return the ones that can't be loaded — a failed
143
+ * request or a non-OK status, the same "broken" definition `fetchRemote` uses.
144
+ * Collects every failure rather than stopping at the first, so callers can report
145
+ * the full set. Runs the probes concurrently.
146
+ */
147
+ declare function findBrokenRemoteAssets(params: {
148
+ urls: string[];
149
+ headers?: RequestHeaders;
150
+ timeoutMs?: number;
151
+ fetch?: RemoteAssetFetcher;
152
+ }): Promise<string[]>;
153
+ //#endregion
154
+ //#region src/scan-lite.d.ts
155
+ /**
156
+ * Scan an HTML string for the local asset references it carries, returning each
157
+ * as a bundle-root relative path. Dependency-free implementation for browser,
158
+ * worker, and edge bundles — same contract as scan.ts's `scanAssetRefs`.
159
+ */
160
+ declare const scanAssetRefs: (html: string) => string[];
161
+ //#endregion
162
+ //#region src/scan-remote.d.ts
163
+ /**
164
+ * Every remote (http/https) asset reference in an HTML string: `<img src>`,
165
+ * inline-SVG `<image>`/`<use>` hrefs, `<link rel=stylesheet>` hrefs, and
166
+ * `url()`/`@import` targets in `<style>` blocks and style attributes.
167
+ *
168
+ * Parser-backed (node-html-parser) counterpart to scan-lite's regex
169
+ * `scanRemoteRefs`; both are built from `makeScanRemoteRefs`, so they stay in
170
+ * step. Pure and IO-free — it does not fetch anything. PDF rendering never
171
+ * fetches remote references, so anything this returns will be missing from the
172
+ * output unless it's bundled (see `mergeRemoteAssets`) or removed.
173
+ */
174
+ declare const scanRemoteRefs: (html: string) => string[];
175
+ //#endregion
176
+ //#region src/errors.d.ts
177
+ /**
178
+ * Every error thrown by `@format.dev/zip` (and by compiled documents while building
179
+ * their assets zip) extends this class. The umbrella check lets callers branch
180
+ * once on "this is a zip-side failure", then narrow further by `code`.
181
+ *
182
+ * Mirrors `FormatError` from `@format.dev/client`: a single class to catch, a
183
+ * `code` field to dispatch on.
184
+ */
185
+ type FormatZipErrorCode = 'MISSING_ASSET' | 'UNRESOLVABLE_REF' | 'ASSET_MISMATCH' | 'INVALID_EXTENSION' | 'REMOTE_ASSETS_DISABLED' | 'REMOTE_ASSET_FETCH';
186
+ declare class FormatZipError extends Error {
187
+ readonly code: FormatZipErrorCode;
188
+ constructor(code: FormatZipErrorCode, message: string, options?: ErrorOptions);
189
+ }
190
+ declare class MissingAssetError extends FormatZipError {
191
+ relPath: string;
192
+ constructor(relPath: string);
193
+ }
194
+ /**
195
+ * Thrown by `zip()` when the HTML references a local asset that resolves to no
196
+ * file: an empty `src`/`href`/`url("")`, or one like `/`, `.`, or `..` that
197
+ * points at the bundle root (a directory) rather than a file. A same-document
198
+ * fragment (`url(#gradient)`) is not this: it names an element already in the
199
+ * document and is skipped silently. Reported with a warning instead of thrown
200
+ * when `skipMissing` is set.
201
+ */
202
+ declare class UnresolvableRefError extends FormatZipError {
203
+ ref: string;
204
+ constructor(ref: string);
205
+ }
206
+ interface AssetMismatchDetail {
207
+ documentName: string;
208
+ mode: 'static' | 'dynamic';
209
+ missing: string[];
210
+ known: string[];
211
+ /**
212
+ * Remote (http/https) URLs the HTML references. The render-time check attaches
213
+ * these so a later step can find broken remotes even when local assets are
214
+ * already missing — they are referenced, not yet known to be unreachable.
215
+ */
216
+ remoteRefs?: string[];
217
+ /** Remote URLs that could not be loaded, filled in once they have been probed. */
218
+ brokenRemote?: string[];
219
+ }
220
+ /**
221
+ * Thrown by a compiled document wrapper when rendered HTML references assets
222
+ * the bundle cannot supply: local files not in its known-asset set, or remote
223
+ * URLs that could not be loaded. Carries enough context for the consumer to fix
224
+ * the source: add the file to the shared assets folder or the document's
225
+ * `./assets/` folder, switch asset mode, or make the remote URL reachable.
226
+ */
227
+ declare class AssetMismatchError extends FormatZipError {
228
+ documentName: string;
229
+ mode: 'static' | 'dynamic';
230
+ missing: string[];
231
+ known: string[];
232
+ remoteRefs: string[];
233
+ brokenRemote: string[];
234
+ constructor(detail: AssetMismatchDetail);
235
+ }
236
+ declare class InvalidExtensionError extends FormatZipError {
237
+ url: string;
238
+ mimeType?: string | undefined;
239
+ constructor(url: string, mimeType?: string | undefined);
240
+ }
241
+ /**
242
+ * Thrown by `zip()` when the HTML references remote (http/https) assets and
243
+ * `remoteAssets` is not enabled. PDF generation never fetches remote
244
+ * references at render time, so a zip built without them produces a broken
245
+ * PDF — failing loudly here makes the gap visible at the source.
246
+ */
247
+ declare class RemoteAssetsDisabledError extends FormatZipError {
248
+ urls: string[];
249
+ constructor(urls: string[]);
250
+ }
251
+ /**
252
+ * Thrown when a remote asset cannot be fetched because the network itself
253
+ * failed (offline machine, DNS failure, blocked egress, timeout) — as opposed
254
+ * to the server answering with an error status. The message is written for the
255
+ * common trap: a CI runner with no outbound network access.
256
+ */
257
+ declare class RemoteAssetFetchError extends FormatZipError {
258
+ url: string;
259
+ constructor(url: string, cause?: unknown);
260
+ }
261
+ //#endregion
262
+ //#region src/index.d.ts
263
+ /**
264
+ * Build a ZIP of every asset `html` references.
265
+ *
266
+ * `source` is either a directory path (read from disk via {@link dirResolver})
267
+ * or a custom {@link AssetResolver}. For browser, worker, and edge runtimes,
268
+ * import from `@format.dev/zip/web` instead — that entry takes a resolver only and
269
+ * carries no `node:*` dependencies.
270
+ *
271
+ * @param html - The rendered Format HTML to scan for asset references.
272
+ * @param source - A directory path (Node) or an {@link AssetResolver} returning the bytes for each referenced path.
273
+ * @param options - {@link ZipOptions}: remote-asset fetching, compression level, and missing-asset handling.
274
+ * @returns the archive bytes, or `undefined` when `html` references no assets.
275
+ */
276
+ declare function zip(html: string, source: string | AssetResolver, options?: ZipOptions): Promise<Uint8Array | undefined>;
277
+ //#endregion
278
+ export { type AssetMismatchDetail, AssetMismatchError, type AssetResolver, FormatZipError, type FormatZipErrorCode, InvalidExtensionError, MissingAssetError, type RemoteAsset, RemoteAssetFetchError, type RemoteAssetFetcher, RemoteAssetsDisabledError, type RemoteValidators, type StoredRemoteAsset, UnresolvableRefError, type ZipOptions, dirResolver, fetchRemote, fetchRemoteIfChanged, findBrokenRemoteAssets, isSystemJunkFile, listZipEntries, mergeRemoteAssets, readRemoteAssets, scanAssetRefs, scanRemoteRefs, urlResolver, zip, zipDir };
279
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/types.ts","../src/zip.ts","../src/zip-dir.ts","../src/junk-files.ts","../src/dir-resolver.ts","../src/url-resolver.ts","../src/helpers.ts","../src/scan-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