@preventive/archive 1.4.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/compression.d.ts CHANGED
@@ -1,39 +1,59 @@
1
- // The typed contract for archive/compression.js, hand-written: keep it
2
- // name for name with compression.js, and change it in the same commit as
3
- // the signature.
1
+ /**
2
+ * Bytes through the platform's `CompressionStream` and `DecompressionStream`, whole
3
+ *
4
+ * ```js
5
+ * import { compress, decompress, supports } from '@preventive/archive/compression.js'
6
+ * ```
7
+ *
8
+ * @module @preventive/archive/compression.js
9
+ */
4
10
 
5
- // A format is what the platform's streams take: 'gzip', 'deflate' and
6
- // 'deflate-raw' everywhere, 'brotli' where it was added. `supports` says
7
- // whether this runtime has one both ways.
8
- export function supports(format: string): boolean
11
+ import { ArchiveError } from './src/error.js';
12
+
13
+ export { ArchiveError };
14
+
15
+ /**
16
+ * Whether this runtime has a format both ways
17
+ *
18
+ * @param format - `'gzip'`, `'deflate'` and `'deflate-raw'` are everywhere, `'brotli'` only where added
19
+ */
20
+ export function supports(format: string): boolean;
9
21
 
10
- // `limit` bounds the output in bytes; past it the call rejects with
11
- // `limited` set rather than going on.
12
22
  export interface Options {
13
- limit?: number
23
+ /** Most bytes of output; past it, rejects with `limited` set (default: no limit) */
24
+ limit?: number;
14
25
  }
15
26
 
16
- // The whole input through one stream, the whole output back. gzip is
17
- // decompressed past zero bytes after its last member, as gzip(1) and zlib
18
- // take them for padding, where the platform's stream refuses them; nothing
19
- // else after the end is passed over.
20
- export function compress(bytes: Uint8Array, format: string, options?: Options): Promise<Uint8Array>
21
- export function decompress(bytes: Uint8Array, format: string, options?: Options): Promise<Uint8Array>
27
+ /**
28
+ * Compress bytes
29
+ *
30
+ * @param bytes - The input
31
+ * @param format - A `CompressionStream` format; one the runtime lacks rejects with the platform's error
32
+ * @param options - The output bound
33
+ * @returns The output
34
+ */
35
+ export function compress(bytes: Uint8Array, format: string, options?: Options): Promise<Uint8Array>;
22
36
 
23
- // `offset` is where in the archive the reader gave up; unset here.
24
- // `limited` is true where a bound the caller set stopped it.
25
- export class ArchiveError extends Error {
26
- constructor(detail: string, offset?: number, options?: { limited?: boolean })
27
- offset: number | undefined
28
- limited: boolean
29
- }
37
+ /**
38
+ * Decompress bytes
39
+ *
40
+ * gzip is read past zero bytes after its last member, as gzip(1) and zlib take them for padding and the
41
+ * platform does not; nothing else after the end is passed over.
42
+ *
43
+ * @param bytes - The input
44
+ * @param format - A `DecompressionStream` format; one the runtime lacks rejects with the platform's error
45
+ * @param options - The output bound
46
+ * @returns The output
47
+ */
48
+ export function decompress(bytes: Uint8Array, format: string, options?: Options): Promise<Uint8Array>;
30
49
 
31
- // What a stream refused: `bytes` is what it had put out by then, kept for a
32
- // caller that wants it as gzip does; `limited` is true when the output
33
- // bound stopped it rather than the data; `cause` is the platform's error.
50
+ /**
51
+ * What a stream refused
52
+ */
34
53
  export class CompressionError extends ArchiveError {
35
- constructor(detail: string, options: { bytes: Uint8Array; limited?: boolean; cause?: unknown })
36
- bytes: Uint8Array
37
- limited: boolean
38
- cause: unknown
54
+ constructor(detail: string, options: { bytes: Uint8Array; limited?: boolean; cause?: unknown });
55
+ /** The output made before the failure, for a caller that keeps it as gzip(1) does */
56
+ bytes: Uint8Array;
57
+ /** The platform's error */
58
+ cause: unknown;
39
59
  }
package/compression.js CHANGED
@@ -1,7 +1,2 @@
1
- // The compression front door of @preventive/archive, reached as
2
- // `@preventive/archive/compression.js`: bytes through the platform's
3
- // CompressionStream and DecompressionStream, whole, with an output bound,
4
- // gzip's zero padding passed over, and with what came out before a failure
5
- // kept on the error. The zip half deflates through the same code.
6
1
  export { CompressionError, compress, decompress, supports } from './src/compression.js'
7
2
  export { ArchiveError } from './src/error.js'
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@preventive/archive",
3
- "version": "1.4.0",
3
+ "version": "1.5.0",
4
4
  "description": "Strict in-memory tar and zip on browser APIs",
5
5
  "type": "module",
6
6
  "exports": {
@@ -25,6 +25,7 @@
25
25
  "src/bytes.js",
26
26
  "src/compression.js",
27
27
  "src/entry.js",
28
+ "src/error.d.ts",
28
29
  "src/error.js",
29
30
  "src/names.js",
30
31
  "src/tar/header.js",
package/src/bytes.js CHANGED
@@ -1,5 +1,3 @@
1
- // Byte helpers both halves use.
2
-
3
1
  export const EMPTY = new Uint8Array(0)
4
2
 
5
3
  export const isAscii = (raw) => raw.every((byte) => byte < 0x80)
@@ -1,8 +1,3 @@
1
- // Bytes through the platform's compression streams, both ways: the zip
2
- // half's deflate, and a front door of its own for anything else with bytes
3
- // to compress. What came out before a stream failed travels with the
4
- // error, for a caller that keeps it as gzip does.
5
-
6
1
  import { concat } from './bytes.js'
7
2
  import { ArchiveError } from './error.js'
8
3
 
@@ -15,137 +10,85 @@ export class CompressionError extends ArchiveError {
15
10
  }
16
11
  }
17
12
 
18
- // Whether this runtime's streams know a format both ways: gzip is
19
- // everywhere they are, brotli only where it was added.
20
13
  export function supports(format) {
21
14
  try {
22
- return [new CompressionStream(format), new DecompressionStream(format)].every(Boolean)
15
+ return [CompressionStream, DecompressionStream].every((Stream) => new Stream(format))
23
16
  } catch {
24
17
  return false
25
18
  }
26
19
  }
27
20
 
28
- // A stream's chunks: the stream itself where the platform iterates streams,
29
- // and a reader's where it does not. Either cancels the stream when the loop
30
- // reading it is left before its end.
31
- async function* readerChunks(stream) {
32
- const reader = stream.getReader()
33
- try {
34
- for (let next = await reader.read(); !next.done; next = await reader.read()) yield next.value
35
- } finally {
36
- reader.cancel().catch(() => {})
37
- }
21
+ function checkBytes(bytes) {
22
+ if (!(bytes instanceof Uint8Array)) throw new ArchiveError('the data is not a Uint8Array')
38
23
  }
39
- const chunksOf = (stream) => (Symbol.asyncIterator in stream ? stream : readerChunks(stream))
40
24
 
41
- // The stream is made here, so a format the runtime lacks rejects with the
42
- // platform's own error, as a bad argument rather than bad data. The bytes
43
- // go in as one write, which the stream takes in as it can, rather than in
44
- // a Blob's pieces, each a turn of its own. Output is gathered in the pieces
45
- // the stream makes and joined at the end, or, given `into`, copied into it
46
- // as each piece comes and the piece let go: joining holds the output twice
47
- // at the end, which a caller who knows how much is coming need not pay.
48
- // Given `expected` bytes instead, the first that many are copied into one
49
- // array of that size as they come, and any past it gathered in pieces.
50
- // Output past `limit` is refused where it is, not after it has all been
51
- // made: leaving the loop cancels the stream. A bound that is no number
52
- // (NaN) refuses everything, not nothing.
53
- async function through(bytes, Stream, format, limit, verb, into, expected = 0) {
54
- if (!(bytes instanceof Uint8Array)) throw new ArchiveError('the data is not a Uint8Array')
55
- const transform = new Stream(format)
56
- const chunks = []
57
- let length = 0
58
- // Where the output is copied as it comes, and how much of it is filled.
59
- let target = into ?? (expected > 0 ? new Uint8Array(expected) : undefined)
60
- let filled = 0
61
- // What has come out so far, as one array: handed back at the end, and
62
- // with the error if the stream fails first.
63
- const made = () => {
64
- if (into !== undefined) return into.subarray(0, length)
65
- if (target !== undefined) return filled === target.length ? target : target.subarray(0, filled)
66
- return chunks.length === 1 ? chunks[0] : concat(chunks)
67
- }
68
- // The stream's own failure is read from its output; the writes fail with it.
25
+ // Output past `limit` is refused as it comes (NaN refuses all). Given `target`, output is written
26
+ // into it while it fits, rather than gathered in pieces and joined, which holds it twice.
27
+ async function through(bytes, Stream, format, limit, verb, target) {
28
+ const transform = new Stream(format) // a format the runtime lacks rejects with the platform's error
69
29
  const writer = transform.writable.getWriter()
70
- writer.write(bytes).catch(() => {})
30
+ writer.write(bytes).catch(() => {}) // the stream's failure is read from its output
71
31
  writer.close().catch(() => {})
32
+ const reader = transform.readable.getReader() // not async iteration, which not every platform has
33
+ const chunks = []
34
+ let length = 0
35
+ const made = () => (target ? target.subarray(0, length) : chunks.length === 1 ? chunks[0] : concat(chunks))
72
36
  try {
73
- for await (const chunk of chunksOf(transform.readable)) {
37
+ for (let next = await reader.read(); !next.done; next = await reader.read()) {
38
+ const chunk = next.value
74
39
  if (!(length + chunk.length <= limit)) throw new RangeError(`output past ${limit} bytes`)
75
- if (target !== undefined && filled + chunk.length > target.length && into === undefined) {
76
- // More than was expected: what is filled is the first piece.
77
- chunks.push(target.subarray(0, filled))
40
+ if (target && length + chunk.length > target.length) {
41
+ chunks.push(target.subarray(0, length))
78
42
  target = undefined
79
43
  }
80
- if (target === undefined) {
81
- chunks.push(chunk)
82
- } else {
83
- target.set(chunk, filled)
84
- filled += chunk.length
85
- }
44
+ if (target) target.set(chunk, length)
45
+ else chunks.push(chunk)
86
46
  length += chunk.length
87
47
  }
88
48
  } catch (cause) {
49
+ reader.cancel().catch(() => {})
89
50
  const limited = cause instanceof RangeError
90
51
  throw new CompressionError(limited ? `the data ${verb}es past ${limit} bytes` : `the data does not ${verb}`, { bytes: made(), limited, cause })
91
52
  }
92
53
  return made()
93
54
  }
94
55
 
95
- export const compress = (bytes, format, { limit = Infinity } = {}) => through(bytes, CompressionStream, format, limit, 'compress')
56
+ export async function compress(bytes, format, { limit = Infinity } = {}) {
57
+ checkBytes(bytes)
58
+ return await through(bytes, CompressionStream, format, limit, 'compress')
59
+ }
96
60
 
97
- // What gzip says it decompresses to: its last member's trailer ends with the
98
- // length of that member's data, mod 2^32, which is all of it where the data
99
- // is one member and no more than 4 GiB. It is the data's own word, so it is
100
- // taken only where `limit` lets that much through and it is no more than
101
- // RATIO times the data: tarballs come to 2 to 13 times theirs, so one that
102
- // says more is gathered in pieces as before, and a trailer that lies costs
103
- // no more than that. Else, as when the data ends in padding, none is
104
- // expected. Where it says less than comes, the rest is gathered as any
105
- // output is; where it says more, the stream fails on it, as zlib holds the
106
- // trailer to what it made.
61
+ // gzip's last 4 bytes are its last member's size mod 2^32. Trusted only within `limit` and RATIO times
62
+ // the input (tarballs come to 2 to 13), so a lying trailer costs no more than that.
107
63
  const RATIO = 16
108
- function expectedOf(bytes, limit) {
64
+ function trailerSize(bytes, limit) {
109
65
  if (bytes.length < 18) return 0
110
66
  const said = new DataView(bytes.buffer, bytes.byteOffset + bytes.length - 4, 4).getUint32(0, true)
111
67
  return said <= limit && said <= bytes.length * RATIO ? said : 0
112
68
  }
113
69
 
114
- // With `sized`, the output made into one array as big as the trailer says
115
- // (expectedOf), which only the data as given has: a place that padding is
116
- // tried ending at has the member's checksum or none where a trailer would be.
117
- const inflate = (bytes, format, limit, sized) => through(bytes, DecompressionStream, format, limit, 'decompress', undefined, sized && format === 'gzip' ? expectedOf(bytes, limit) : 0)
70
+ const inflate = (bytes, format, limit, size = 0) => through(bytes, DecompressionStream, format, limit, 'decompress', size ? new Uint8Array(size) : undefined)
118
71
 
119
- // gzip(1) and zlib take zero bytes after the last member as padding, as old
120
- // tarballs run on in zeros to a whole 10240-byte record, the way npm 1.0
121
- // packed them through the system's tar; the platform's stream refuses
122
- // anything there. So gzip that ends in a zero and does not decompress is
123
- // tried again ending sooner, at the one place it decompresses whole: its
124
- // last member's last four bytes are the length it inflates to, mod 2^32,
125
- // so where that is not 0 it ends within three zeros past the last byte that
126
- // is not; where the member is empty, as zlib writes one, `03 00` and eight
127
- // zeros, within nine. Only zeros are passed over, where zlib passes over
128
- // whatever follows one; and each place tried inflates it all again, which
129
- // only padded data pays for.
72
+ // gzip(1) and zlib take zeros after the last member as padding, which the platform refuses. A member ends
73
+ // in its size, so within 3 zeros past the last nonzero byte, or 9 for an empty one: each end is tried.
130
74
  export async function decompress(bytes, format, { limit = Infinity } = {}) {
75
+ checkBytes(bytes)
76
+ const gzip = format === 'gzip'
131
77
  try {
132
- return await inflate(bytes, format, limit, true)
78
+ return await inflate(bytes, format, limit, gzip ? trailerSize(bytes, limit) : 0)
133
79
  } catch (error) {
134
- if (format !== 'gzip' || !(error instanceof CompressionError) || error.limited || bytes.at(-1) !== 0) throw error
80
+ if (!gzip || !(error instanceof CompressionError) || error.limited || bytes.at(-1) !== 0) throw error
135
81
  const last = bytes.findLastIndex((byte) => byte !== 0)
136
82
  for (let end = last + 1; end <= Math.min(last + 10, bytes.length - 1); end++) {
137
83
  try {
138
- return await inflate(bytes.subarray(0, end), format, limit, false)
84
+ return await inflate(bytes.subarray(0, end), format, limit)
139
85
  } catch (retry) {
140
- // Output past the bound before the end is past it wherever the end is.
141
- if (!(retry instanceof CompressionError) || retry.limited) throw retry
86
+ if (!(retry instanceof CompressionError) || retry.limited) throw retry // past the bound at any end
142
87
  }
143
88
  }
144
89
  throw error
145
90
  }
146
91
  }
147
92
 
148
- // Into `into`, which bounds the output, and handed back as much of it as
149
- // was filled. Not in the front door: the zip half's, whose entries each
150
- // declare their size.
93
+ // Bounded by and made into `into`, for zip's entries, which declare their size
151
94
  export const decompressInto = (bytes, format, into) => through(bytes, DecompressionStream, format, into.length, 'decompress', into)
package/src/entry.js CHANGED
@@ -1,25 +1,19 @@
1
- // What an entry to write is in either format: checked here, and each
2
- // format adds the fields it stores.
3
-
4
1
  import { EMPTY } from './bytes.js'
5
2
  import { ArchiveError } from './error.js'
6
3
  import { checkString, quote } from './text.js'
7
4
 
8
5
  export const DEFAULT_MODE = { file: 0o644, directory: 0o755, symlink: 0o777 }
9
6
 
10
- // A contiguous file is a file for every purpose here.
11
7
  export const isFile = (type) => type === 'file' || type === 'contiguous-file'
12
8
 
13
- // The name as the archive stores it, a directory's with its slash.
9
+ // The name as stored: a directory's with its slash
14
10
  export const wireName = (entry) => (entry.type === 'directory' ? `${entry.name}/` : entry.name)
15
11
 
16
- // `types` holds what the format writes; `data` is for a file and a link
17
- // target for a link, whatever the format allows.
12
+ // The fields both formats share, checked; `types` has a key for each type the format writes
18
13
  export function checkEntry(entry, types) {
19
14
  if (entry === null || typeof entry !== 'object') throw new ArchiveError('an entry is not an object')
20
15
  const type = entry.type ?? 'file'
21
- // A key lookup would take anything that stringifies to a type this package
22
- // writes, and everything after compares `type` as the string it is not.
16
+ // Before Object.hasOwn, which would take anything that stringifies to a type
23
17
  if (typeof type !== 'string') throw new ArchiveError('entry type is not a string')
24
18
  if (!Object.hasOwn(types, type)) throw new ArchiveError(`entry type ${quote(type)} is not one this package writes`)
25
19
  const { name } = entry
package/src/error.d.ts ADDED
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Thrown on anything refused, by a reader or a writer
3
+ */
4
+ export class ArchiveError extends Error {
5
+ constructor(detail: string, offset?: number, options?: { limited?: boolean });
6
+ /** Byte offset in the archive where a reader gave up; unset from a writer */
7
+ offset: number | undefined;
8
+ /** Whether a bound the caller set stopped it, rather than anything wrong with the input */
9
+ limited: boolean;
10
+ }
package/src/error.js CHANGED
@@ -1,18 +1,14 @@
1
- // `offset` is where in the archive the reader gave up, in bytes; the
2
- // writer leaves it unset. `limited` is true where a bound the caller set
3
- // stopped it, rather than anything wrong with the archive.
4
1
  export class ArchiveError extends Error {
5
2
  constructor(detail, offset, { limited = false } = {}) {
6
3
  super(offset === undefined ? detail : `${detail} at byte ${offset}`)
7
4
  this.name = 'ArchiveError'
8
- this.offset = offset
9
- this.limited = limited
5
+ this.offset = offset // where a reader gave up, unset from a writer
6
+ this.limited = limited // a bound the caller set, not bad input
10
7
  }
11
8
  }
12
9
 
13
- // The same error, placed: for a check that does not know where in the
14
- // archive it is running. Anything but such a refusal -- a bug above all --
15
- // goes on as it was, rather than dressed up as bad input.
10
+ // Places a refusal from a check that does not know where in the archive it runs.
11
+ // Anything else, a bug above all, is rethrown as is rather than dressed up as bad input.
16
12
  export function located(fn, at) {
17
13
  try {
18
14
  return fn()