@stll/docx-core 0.39.1 → 0.40.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,114 @@
1
+ import { a as ZipCodec, i as InflateOutcome, n as ZipErrorReason, r as InflateExpectation, t as ZipError } from "../errors-Dm3jsb5q.js";
2
+ import { Result } from "better-result";
3
+ /** The compression an entry is written with. */
4
+ type ZipCompression = "store" | "deflate";
5
+ /** Whether `path` is a relative, forward-slash name with no `..` segment. */
6
+ export declare const isSafeZipPath: (path: string) => boolean;
7
+ /** Bounds a read enforces. Every byte limit counts inflated bytes. */
8
+ type ZipReadLimits = {
9
+ /** Records the central directory may hold, directories included. */
10
+ readonly maxEntries: number;
11
+ /** Inflated bytes one entry may declare. */
12
+ readonly maxEntryBytes: number;
13
+ /** Inflated bytes all entries together may declare. */
14
+ readonly maxTotalBytes: number;
15
+ /**
16
+ * Inflated bytes per compressed byte, for each entry and for the archive
17
+ * as a whole. Sizes under `compressionRatioGraceBytes` are exempt: a small
18
+ * part can compress extremely well without costing anything to hold.
19
+ */
20
+ readonly maxCompressionRatio: number;
21
+ readonly compressionRatioGraceBytes: number;
22
+ };
23
+ /**
24
+ * Defaults sized for office packages. A DEFLATE stream tops out near 1032:1;
25
+ * markup in real documents stays under 75:1.
26
+ */
27
+ export declare const ZIP_DEFAULT_READ_LIMITS: ZipReadLimits;
28
+ /** Entry content. Text is written as UTF-8. */
29
+ export type ZipEntryData = string | Uint8Array | ArrayBuffer;
30
+ /** How {@link ZipArchive.set} writes one entry. */
31
+ export type ZipEntryOptions = {
32
+ /** Overrides the archive-wide compression passed to `generate`. */
33
+ readonly compression?: ZipCompression;
34
+ /** Overrides the archive-wide DEFLATE level passed to `generate`. */
35
+ readonly level?: number;
36
+ /** Entry timestamp; defaults to 2000-01-01T00:00Z for reproducible output. */
37
+ readonly modified?: Date;
38
+ };
39
+ /** How {@link ZipArchive.read} bounds an archive. */
40
+ export type ZipReadOptions = {
41
+ /** Limits to apply; omitted fields take {@link ZIP_DEFAULT_READ_LIMITS}. */
42
+ readonly limits?: Partial<ZipReadLimits>;
43
+ /**
44
+ * Entries the per-entry compression-ratio cap skips, such as binary parts
45
+ * that legitimately compress like a run of one byte. They still count
46
+ * toward the archive-wide ratio and every byte limit.
47
+ */
48
+ readonly isCompressionRatioExempt?: (path: string) => boolean;
49
+ /** DEFLATE implementation; defaults to the platform's. */
50
+ readonly codec?: ZipCodec;
51
+ };
52
+ /** How {@link ZipArchive.generate} writes new and replaced entries. */
53
+ export type ZipGenerateOptions = {
54
+ /** Defaults to `"deflate"`. Entries passed through keep their compression. */
55
+ readonly compression?: ZipCompression;
56
+ /** DEFLATE level 0-9; defaults to 6. */
57
+ readonly level?: number;
58
+ /** Timestamp for every entry, replacing the ones read or set. */
59
+ readonly modified?: Date;
60
+ };
61
+ /** One entry of a {@link ZipArchive}. */
62
+ export type ZipEntry = {
63
+ /** Entry name, a relative forward-slash path. */
64
+ readonly path: string;
65
+ /** Inflated size in bytes. */
66
+ readonly size: number;
67
+ /** Entry timestamp, read as UTC with two seconds of resolution. */
68
+ readonly modified: Date;
69
+ /**
70
+ * The entry's bytes. A read entry inflates at most its declared size and
71
+ * must match its CRC-32; anything else rejects with a {@link ZipError}.
72
+ */
73
+ readonly bytes: () => Promise<Uint8Array<ArrayBuffer>>;
74
+ /** The entry decoded as UTF-8, keeping any byte-order mark. */
75
+ readonly text: () => Promise<string>;
76
+ /** The entry's bytes in an `ArrayBuffer` of exactly their length. */
77
+ readonly arrayBuffer: () => Promise<ArrayBuffer>;
78
+ };
79
+ /** An editable, bounded, in-memory ZIP archive. */
80
+ export declare class ZipArchive {
81
+ #private;
82
+ constructor(options?: {
83
+ readonly codec?: ZipCodec;
84
+ });
85
+ /**
86
+ * Read an archive. Rejects with a {@link ZipError} when the archive is
87
+ * malformed or exceeds a limit; entries inflate later, on demand. The
88
+ * archive keeps a reference to `input`, which must not change afterwards.
89
+ */
90
+ static read(input: Uint8Array | ArrayBuffer, options?: ZipReadOptions): Promise<ZipArchive>;
91
+ /** Entry names in archive order. */
92
+ paths(): string[];
93
+ /** Entries in archive order. */
94
+ entries(): ZipEntry[];
95
+ /** Whether an entry named `path` exists. */
96
+ has(path: string): boolean;
97
+ /** The entry named `path`, or `undefined`. */
98
+ entry(path: string): ZipEntry | undefined;
99
+ /**
100
+ * Add or replace one entry. A replaced entry keeps its position. No parent
101
+ * directory entries are created.
102
+ */
103
+ set(path: string, data: ZipEntryData, options?: ZipEntryOptions): void;
104
+ /**
105
+ * An independent copy: later edits to either archive leave the other
106
+ * unchanged. Entry content is shared, never copied, since it is immutable.
107
+ */
108
+ clone(): ZipArchive;
109
+ /** Remove an entry; returns whether it existed. */
110
+ delete(path: string): boolean;
111
+ /** Write the archive. Entries read and not replaced keep their bytes. */
112
+ generate({ compression, level, modified }?: ZipGenerateOptions): Promise<Uint8Array<ArrayBuffer>>;
113
+ }
114
+ export { type InflateExpectation, type InflateOutcome, type ZipCodec, type ZipCompression, ZipError, type ZipErrorReason, type ZipReadLimits };
@@ -0,0 +1,3 @@
1
+ import { _ as ZipError, h as isSafeZipPath } from "../format-DXPXB02u.js";
2
+ import { n as ZIP_DEFAULT_READ_LIMITS, t as ZipArchive } from "../archive-yBR7X-Qc.js";
3
+ export { ZIP_DEFAULT_READ_LIMITS, ZipArchive, ZipError, isSafeZipPath };
@@ -0,0 +1,30 @@
1
+ import { a as ZipCodec, n as ZipErrorReason, t as ZipError } from "../errors-Dm3jsb5q.js";
2
+ /** Content of one streamed entry. */
3
+ export type ZipStreamData = string | Uint8Array | AsyncIterable<Uint8Array> | Iterable<Uint8Array>;
4
+ /**
5
+ * One entry of a streamed archive. A path ending in `/` is a directory entry
6
+ * and takes no data.
7
+ */
8
+ export type ZipStreamEntry = {
9
+ readonly path: string;
10
+ readonly data?: ZipStreamData;
11
+ /** Entry timestamp; defaults to 2000-01-01T00:00Z. */
12
+ readonly modified?: Date;
13
+ };
14
+ /**
15
+ * The archive bytes for `entries`, produced as they are consumed. Entries
16
+ * are pulled one at a time, so a source that opens a download per entry
17
+ * opens it only when the archive reaches it.
18
+ */
19
+ export declare function zipStream(entries: AsyncIterable<ZipStreamEntry> | Iterable<ZipStreamEntry>, { codec }?: {
20
+ readonly codec?: ZipCodec;
21
+ }): AsyncGenerator<Uint8Array>;
22
+ /**
23
+ * {@link zipStream} as a `ReadableStream`. The stream pulls the next chunk
24
+ * only when its consumer asks, so a slow consumer slows the sources rather
25
+ * than buffering them.
26
+ */
27
+ export declare const createZipStream: (entries: AsyncIterable<ZipStreamEntry> | Iterable<ZipStreamEntry>, options?: {
28
+ readonly codec?: ZipCodec;
29
+ }) => ReadableStream<Uint8Array>;
30
+ export { ZipError, type ZipErrorReason };
@@ -0,0 +1,117 @@
1
+ import { _ as ZipError, d as encodeEndOfCentralDirectory, f as encodeEntryName, g as toDosDateTime, h as isSafeZipPath, l as encodeCentralHeader, p as encodeLocalHeader, r as FIXED_DOS_DATE_TIME, u as encodeDataDescriptor, y as platformZipCodec } from "../format-DXPXB02u.js";
2
+ import { encodeUtf8 } from "@stll/utf8-boundaries";
3
+ // src/zip/stream.ts
4
+ /**
5
+ * A streaming ZIP writer for archives too large to hold in memory.
6
+ *
7
+ * Entries are stored, not compressed, and their bytes flow straight from the
8
+ * input to the output: each entry's CRC-32 and size are counted as it passes
9
+ * and written in a data descriptor after it, and Zip64 records are used when
10
+ * a size, an offset or the entry count outgrows the classic fields. Memory
11
+ * holds one chunk at a time plus one small central-directory record per
12
+ * entry.
13
+ */
14
+ async function* entryChunks(data) {
15
+ if (data === void 0) return;
16
+ if (typeof data === "string") {
17
+ yield encodeUtf8(data);
18
+ return;
19
+ }
20
+ if (data instanceof Uint8Array) {
21
+ yield data;
22
+ return;
23
+ }
24
+ yield* data;
25
+ }
26
+ const invalidName = (path) => new ZipError({
27
+ message: "Archive entry name must be a relative path",
28
+ reason: "invalid-entry-name",
29
+ path
30
+ });
31
+ /**
32
+ * The archive bytes for `entries`, produced as they are consumed. Entries
33
+ * are pulled one at a time, so a source that opens a download per entry
34
+ * opens it only when the archive reaches it.
35
+ */
36
+ async function* zipStream(entries, { codec = platformZipCodec() } = {}) {
37
+ const centralHeaders = [];
38
+ const names = /* @__PURE__ */ new Set();
39
+ let offset = 0;
40
+ for await (const { path, data, modified } of entries) {
41
+ if (!isSafeZipPath(path)) throw invalidName(path);
42
+ if (names.has(path)) throw new ZipError({
43
+ message: "Archive names an entry twice",
44
+ reason: "duplicate-entry",
45
+ path
46
+ });
47
+ names.add(path);
48
+ const directory = path.endsWith("/");
49
+ if (directory && data !== void 0) throw invalidName(path);
50
+ const name = encodeEntryName(path);
51
+ const header = {
52
+ name: name.bytes,
53
+ flags: name.flags | 8,
54
+ method: 0,
55
+ dateTime: modified === void 0 ? FIXED_DOS_DATE_TIME : toDosDateTime(modified),
56
+ crc32: 0,
57
+ compressedSize: 0,
58
+ uncompressedSize: 0,
59
+ directory
60
+ };
61
+ const localOffset = offset;
62
+ const local = encodeLocalHeader(header);
63
+ yield local;
64
+ offset += local.byteLength;
65
+ let crc32 = 0;
66
+ let size = 0;
67
+ for await (const chunk of entryChunks(data)) {
68
+ if (chunk.byteLength === 0) continue;
69
+ crc32 = codec.crc32(chunk, crc32);
70
+ size += chunk.byteLength;
71
+ yield chunk;
72
+ }
73
+ offset += size;
74
+ const record = {
75
+ ...header,
76
+ crc32,
77
+ compressedSize: size,
78
+ uncompressedSize: size
79
+ };
80
+ const descriptor = encodeDataDescriptor(record);
81
+ yield descriptor;
82
+ offset += descriptor.byteLength;
83
+ centralHeaders.push(encodeCentralHeader(record, localOffset));
84
+ }
85
+ let directorySize = 0;
86
+ for (const header of centralHeaders) {
87
+ yield header;
88
+ directorySize += header.byteLength;
89
+ }
90
+ yield encodeEndOfCentralDirectory({
91
+ entryCount: centralHeaders.length,
92
+ offset,
93
+ size: directorySize
94
+ });
95
+ }
96
+ /**
97
+ * {@link zipStream} as a `ReadableStream`. The stream pulls the next chunk
98
+ * only when its consumer asks, so a slow consumer slows the sources rather
99
+ * than buffering them.
100
+ */
101
+ const createZipStream = (entries, options = {}) => {
102
+ const chunks = zipStream(entries, options);
103
+ return new ReadableStream({
104
+ pull: async (controller) => {
105
+ const { done, value } = await chunks.next();
106
+ if (done) {
107
+ controller.close();
108
+ return;
109
+ }
110
+ controller.enqueue(value);
111
+ },
112
+ cancel: async () => {
113
+ await chunks.return(void 0);
114
+ }
115
+ });
116
+ };
117
+ export { ZipError, createZipStream, zipStream };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stll/docx-core",
3
- "version": "0.39.1",
3
+ "version": "0.40.0",
4
4
  "description": "Typed OOXML/DOCX model, validation, serialization, legal-source compilation, and browser-native package projection.",
5
5
  "keywords": [
6
6
  "document-model",
@@ -58,9 +58,14 @@
58
58
  "default": "./dist/schema/sequenceChildren.js"
59
59
  },
60
60
  "./zip": {
61
- "types": "./dist/zip/writeZipPart.d.ts",
62
- "import": "./dist/zip/writeZipPart.js",
63
- "default": "./dist/zip/writeZipPart.js"
61
+ "types": "./dist/zip/archive.d.ts",
62
+ "import": "./dist/zip/archive.js",
63
+ "default": "./dist/zip/archive.js"
64
+ },
65
+ "./zip/stream": {
66
+ "types": "./dist/zip/stream.d.ts",
67
+ "import": "./dist/zip/stream.js",
68
+ "default": "./dist/zip/stream.js"
64
69
  }
65
70
  },
66
71
  "publishConfig": {
@@ -79,10 +84,9 @@
79
84
  "dependencies": {
80
85
  "@nodable/entities": "^3.0.0",
81
86
  "@stll/docx-utils": "^0.2.0",
82
- "@stll/utf8-boundaries": "0.1.2",
87
+ "@stll/utf8-boundaries": "0.2.0",
83
88
  "better-result": "3.0.1",
84
89
  "fast-xml-parser": "^5.11.2",
85
- "jszip": "3.10.2",
86
90
  "marked": "^18.1.1"
87
91
  },
88
92
  "devDependencies": {
@@ -1,12 +0,0 @@
1
- import JSZip from "jszip";
2
- //#region src/zip/writeZipPart.d.ts
3
- type WriteZipPartOptions = {
4
- zip: JSZip;
5
- path: string;
6
- data: Parameters<JSZip["loadAsync"]>[0];
7
- options?: Omit<JSZip.JSZipFileOptions, "createFolders">;
8
- };
9
- /** Write exactly one entry, without synthesizing parent directory entries. */
10
- export declare const writeZipPart: ({ zip, path, data, options }: WriteZipPartOptions) => void;
11
- //#endregion
12
- export {};
@@ -1,17 +0,0 @@
1
- import { writeZipEntry } from "@stll/utf8-boundaries";
2
- //#region src/zip/writeZipPart.ts
3
- const FIXED_ZIP_DATE_MS = Date.UTC(2e3, 0, 1);
4
- const UNIX_DIRECTORY_FLAG = 16384;
5
- const DOS_DIRECTORY_FLAG = 16;
6
- /** Write exactly one entry, without synthesizing parent directory entries. */
7
- const writeZipPart = ({ zip, path, data, options = {} }) => {
8
- const unixPermissions = typeof options.unixPermissions === "string" ? Number.parseInt(options.unixPermissions, 8) : options.unixPermissions ?? 0;
9
- if (options.dir === true || (unixPermissions & UNIX_DIRECTORY_FLAG) !== 0 || ((options.dosPermissions ?? 0) & DOS_DIRECTORY_FLAG) !== 0) data = /* @__PURE__ */ new Uint8Array();
10
- writeZipEntry(zip, path, data, {
11
- ...options,
12
- date: options.date ?? new Date(FIXED_ZIP_DATE_MS),
13
- createFolders: false
14
- });
15
- };
16
- //#endregion
17
- export { writeZipPart };