@preventive/archive 1.0.0-beta.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Nikita Skovoroda
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,34 @@
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.
4
+
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
9
+
10
+ // `limit` bounds the output in bytes; past it the call rejects with
11
+ // `limited` set rather than going on.
12
+ export interface Options {
13
+ limit?: number
14
+ }
15
+
16
+ // The whole input through one stream, the whole output back.
17
+ export function compress(bytes: Uint8Array, format: string, options?: Options): Promise<Uint8Array>
18
+ export function decompress(bytes: Uint8Array, format: string, options?: Options): Promise<Uint8Array>
19
+
20
+ // `offset` is where in the archive the reader gave up; unset here.
21
+ export class ArchiveError extends Error {
22
+ constructor(detail: string, offset?: number)
23
+ offset: number | undefined
24
+ }
25
+
26
+ // What a stream refused: `bytes` is what it had put out by then, kept for a
27
+ // caller that wants it as gzip does; `limited` is true when the output
28
+ // bound stopped it rather than the data; `cause` is the platform's error.
29
+ export class CompressionError extends ArchiveError {
30
+ constructor(detail: string, options: { bytes: Uint8Array; limited?: boolean; cause?: unknown })
31
+ bytes: Uint8Array
32
+ limited: boolean
33
+ cause: unknown
34
+ }
package/compression.js ADDED
@@ -0,0 +1,7 @@
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
+ // and with what came out before a failure kept on the error. The zip half
5
+ // deflates through the same code.
6
+ export { CompressionError, compress, decompress, supports } from './src/compression.js'
7
+ export { ArchiveError } from './src/error.js'
package/package.json ADDED
@@ -0,0 +1,68 @@
1
+ {
2
+ "name": "@preventive/archive",
3
+ "version": "1.0.0-beta.0",
4
+ "description": "Strict in-memory tar and zip on browser APIs",
5
+ "type": "module",
6
+ "exports": {
7
+ "./tar.js": {
8
+ "types": "./tar.d.ts",
9
+ "default": "./tar.js"
10
+ },
11
+ "./compression.js": {
12
+ "types": "./compression.d.ts",
13
+ "default": "./compression.js"
14
+ },
15
+ "./zip.js": {
16
+ "types": "./zip.d.ts",
17
+ "default": "./zip.js"
18
+ }
19
+ },
20
+ "files": [
21
+ "compression.d.ts",
22
+ "compression.js",
23
+ "src/bytes.js",
24
+ "src/compression.js",
25
+ "src/entry.js",
26
+ "src/error.js",
27
+ "src/names.js",
28
+ "src/tar/header.js",
29
+ "src/tar/pack.js",
30
+ "src/tar/pax.js",
31
+ "src/tar/unpack.js",
32
+ "src/text.js",
33
+ "src/zip/format.js",
34
+ "src/zip/unzip.js",
35
+ "src/zip/zip.js",
36
+ "tar.d.ts",
37
+ "tar.js",
38
+ "zip.d.ts",
39
+ "zip.js"
40
+ ],
41
+ "engines": {
42
+ "node": ">=24.14.0"
43
+ },
44
+ "scripts": {
45
+ "test": "node --test ./tests/*.test.js ./tests/tar/*.test.js ./tests/zip/*.test.js"
46
+ },
47
+ "license": "MIT",
48
+ "author": {
49
+ "name": "Nikita Skovoroda",
50
+ "email": "chalkerx@gmail.com",
51
+ "url": "https://github.com/ChALkeR"
52
+ },
53
+ "repository": {
54
+ "type": "git",
55
+ "url": "https://github.com/PreventiveMeasures/libraries.git",
56
+ "directory": "archive"
57
+ },
58
+ "bugs": {
59
+ "url": "https://github.com/PreventiveMeasures/libraries/issues"
60
+ },
61
+ "homepage": "https://github.com/PreventiveMeasures/libraries/tree/main/archive",
62
+ "publishConfig": {
63
+ "access": "public"
64
+ },
65
+ "dependencies": {
66
+ "@exodus/bytes": "^1.16.0"
67
+ }
68
+ }
package/src/bytes.js ADDED
@@ -0,0 +1,16 @@
1
+ // Byte helpers both halves use.
2
+
3
+ export const EMPTY = new Uint8Array(0)
4
+
5
+ export const isAscii = (raw) => raw.every((byte) => byte < 0x80)
6
+ export const sameBytes = (a, b) => a.length === b.length && a.every((byte, i) => byte === b[i])
7
+
8
+ export function concat(chunks) {
9
+ const out = new Uint8Array(chunks.reduce((total, chunk) => total + chunk.length, 0))
10
+ let at = 0
11
+ for (const chunk of chunks) {
12
+ out.set(chunk, at)
13
+ at += chunk.length
14
+ }
15
+ return out
16
+ }
@@ -0,0 +1,87 @@
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
+ import { concat } from './bytes.js'
7
+ import { ArchiveError } from './error.js'
8
+
9
+ export class CompressionError extends ArchiveError {
10
+ constructor(detail, { bytes, limited = false, cause }) {
11
+ super(detail)
12
+ this.name = 'CompressionError'
13
+ this.bytes = bytes
14
+ this.limited = limited
15
+ this.cause = cause
16
+ }
17
+ }
18
+
19
+ // Whether this runtime's streams know a format both ways: gzip is
20
+ // everywhere they are, brotli only where it was added.
21
+ export function supports(format) {
22
+ try {
23
+ return [new CompressionStream(format), new DecompressionStream(format)].every(Boolean)
24
+ } catch {
25
+ return false
26
+ }
27
+ }
28
+
29
+ // A stream's chunks, through async iteration where the platform has it on
30
+ // streams, and a reader where it does not.
31
+ async function* chunksOf(stream) {
32
+ if (Symbol.asyncIterator in stream) return yield* stream
33
+ const reader = stream.getReader()
34
+ for (let next = await reader.read(); !next.done; next = await reader.read()) yield next.value
35
+ }
36
+
37
+ // Output past `limit` is refused where it is, not after it has all been
38
+ // made: erroring the bound cancels the stream behind it. A bound that is
39
+ // no number (NaN) refuses everything, not nothing.
40
+ function bounded(limit) {
41
+ let total = 0
42
+ return new TransformStream({
43
+ transform(chunk, controller) {
44
+ total += chunk.length
45
+ if (total <= limit) controller.enqueue(chunk)
46
+ else controller.error(new RangeError(`output past ${limit} bytes`))
47
+ },
48
+ })
49
+ }
50
+
51
+ // The stream is made here, so a format the runtime lacks rejects with the
52
+ // platform's own error, as a bad argument rather than bad data. Output is
53
+ // gathered in the pieces the stream makes and joined at the end, or, given
54
+ // `into`, copied into it as each piece comes and the piece let go: joining
55
+ // holds the output twice at the end, which a caller who knows how much is
56
+ // coming need not pay.
57
+ async function through(bytes, Stream, format, limit, verb, into) {
58
+ if (!(bytes instanceof Uint8Array)) throw new ArchiveError('the data is not a Uint8Array')
59
+ const transform = new Stream(format)
60
+ const chunks = []
61
+ let length = 0
62
+ // What has come out so far, as one array: handed back at the end, and
63
+ // with the error if the stream fails first.
64
+ const made = () => {
65
+ if (into !== undefined) return into.subarray(0, length)
66
+ return chunks.length === 1 ? chunks[0] : concat(chunks)
67
+ }
68
+ try {
69
+ for await (const chunk of chunksOf(new Blob([bytes]).stream().pipeThrough(transform).pipeThrough(bounded(limit)))) {
70
+ if (into === undefined) chunks.push(chunk)
71
+ else into.set(chunk, length)
72
+ length += chunk.length
73
+ }
74
+ } catch (cause) {
75
+ const limited = cause instanceof RangeError
76
+ throw new CompressionError(limited ? `the data ${verb}es past ${limit} bytes` : `the data does not ${verb}`, { bytes: made(), limited, cause })
77
+ }
78
+ return made()
79
+ }
80
+
81
+ export const compress = (bytes, format, { limit = Infinity } = {}) => through(bytes, CompressionStream, format, limit, 'compress')
82
+ export const decompress = (bytes, format, { limit = Infinity } = {}) => through(bytes, DecompressionStream, format, limit, 'decompress')
83
+
84
+ // Into `into`, which bounds the output, and handed back as much of it as
85
+ // was filled. Not in the front door: the zip half's, whose entries each
86
+ // declare their size.
87
+ export const decompressInto = (bytes, format, into) => through(bytes, DecompressionStream, format, into.length, 'decompress', into)
package/src/entry.js ADDED
@@ -0,0 +1,34 @@
1
+ // What an entry to write is in either format: checked here, and each
2
+ // format adds the fields it stores.
3
+
4
+ import { EMPTY } from './bytes.js'
5
+ import { ArchiveError } from './error.js'
6
+ import { checkString, quote } from './text.js'
7
+
8
+ export const DEFAULT_MODE = { file: 0o644, directory: 0o755, symlink: 0o777 }
9
+
10
+ // A contiguous file is a file for every purpose here.
11
+ export const isFile = (type) => type === 'file' || type === 'contiguous-file'
12
+
13
+ // The name as the archive stores it, a directory's with its slash.
14
+ export const wireName = (entry) => (entry.type === 'directory' ? `${entry.name}/` : entry.name)
15
+
16
+ // `types` holds what the format writes; `data` is for a file and a link
17
+ // target for a link, whatever the format allows.
18
+ export function checkEntry(entry, types) {
19
+ if (entry === null || typeof entry !== 'object') throw new ArchiveError('an entry is not an object')
20
+ 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.
23
+ if (typeof type !== 'string') throw new ArchiveError('entry type is not a string')
24
+ if (!Object.hasOwn(types, type)) throw new ArchiveError(`entry type ${quote(type)} is not one this package writes`)
25
+ const { name } = entry
26
+ checkString(name, 'entry name')
27
+ const data = entry.data ?? EMPTY
28
+ if (!(data instanceof Uint8Array)) throw new ArchiveError(`data of ${quote(name)} is not a Uint8Array`)
29
+ if (data.length !== 0 && !isFile(type)) throw new ArchiveError(`a ${type} cannot carry data (${quote(name)})`)
30
+ const linkname = entry.linkname ?? ''
31
+ checkString(linkname, `link target of ${quote(name)}`)
32
+ if (linkname !== '' && type !== 'link' && type !== 'symlink') throw new ArchiveError(`a ${type} cannot have a link target (${quote(name)})`)
33
+ return { name, type, data, linkname }
34
+ }
package/src/error.js ADDED
@@ -0,0 +1,21 @@
1
+ // `offset` is where in the archive the reader gave up, in bytes; the
2
+ // writer leaves it unset.
3
+ export class ArchiveError extends Error {
4
+ constructor(detail, offset) {
5
+ super(offset === undefined ? detail : `${detail} at byte ${offset}`)
6
+ this.name = 'ArchiveError'
7
+ this.offset = offset
8
+ }
9
+ }
10
+
11
+ // The same error, placed: for a check that does not know where in the
12
+ // archive it is running. Anything but such a refusal — a bug above all —
13
+ // goes on as it was, rather than dressed up as bad input.
14
+ export function located(fn, at) {
15
+ try {
16
+ return fn()
17
+ } catch (error) {
18
+ if (!(error instanceof ArchiveError) || error.offset !== undefined) throw error
19
+ throw new ArchiveError(error.message, at)
20
+ }
21
+ }
package/src/names.js ADDED
@@ -0,0 +1,219 @@
1
+ // Name safety, applied before writing an entry and before handing one out
2
+ // of an archive. A name is a relative path: `.` segments and a directory's
3
+ // trailing slash are dropped, and what is left has no empty or `..`
4
+ // segment, no control character and no backslash — a separator on
5
+ // Windows, where `..\` would get past the check on `..` — and does not
6
+ // start with a drive letter and colon, which Windows resolves from that
7
+ // drive rather than from the archive. A symlink target may use `..`, but
8
+ // is followed from where the link sits and refused if it climbs above the
9
+ // archive or passes through anything but a directory, which is how a
10
+ // chain of links would climb. A hard link to a symlink, directly or down a
11
+ // chain of hard links, is a second name for it, and is held to the same walk
12
+ // from where that name sits, since a target safe under `a/b/` need not be
13
+ // safe at the root. Lengths are bounded by what a filesystem takes at all:
14
+ // PATH_MAX for the whole, NAME_MAX for a segment, in bytes.
15
+ //
16
+ // A name may repeat only as the same entry again, field for field and byte
17
+ // for byte (some npm packagers write `d/f` and `d/./f` both): two different
18
+ // entries under one name would leave the winner to extraction order.
19
+ // Collisions a filesystem might add — case, Unicode normalisation — are
20
+ // the filesystem's, not the archive's, and are not looked for.
21
+
22
+ import { sameBytes } from './bytes.js'
23
+ import { ArchiveError } from './error.js'
24
+ import { checkString, hasUnsafe, quote, utf8Length } from './text.js'
25
+
26
+ const PATH_MAX = 4096
27
+ const NAME_MAX = 255
28
+
29
+ // The rules every path is held to, whatever it names; hands back its
30
+ // segments, split the once.
31
+ function checkText(path, what) {
32
+ checkString(path, what)
33
+ if (path === '') throw new ArchiveError(`${what} is empty`)
34
+ if (hasUnsafe(path, true)) throw new ArchiveError(`${what} ${quote(path)} holds a control or formatting character, or a backslash`)
35
+ if (path.startsWith('/')) throw new ArchiveError(`${what} ${quote(path)} is absolute`)
36
+ const segments = path.split('/')
37
+ // Once `.` segments are dropped, `./C:x` is `C:x`, so the first segment
38
+ // that is not one is what a drive letter is looked for on.
39
+ if (/^[a-zA-Z]:/u.test(segments.find((segment) => segment !== '.') ?? '')) throw new ArchiveError(`${what} ${quote(path)} starts with a drive letter`)
40
+ if (utf8Length(path) > PATH_MAX) throw new ArchiveError(`${what} ${quote(path)} is longer than ${PATH_MAX} bytes`)
41
+ for (const segment of segments) {
42
+ if (utf8Length(segment) > NAME_MAX) throw new ArchiveError(`${what} ${quote(path)} has a segment longer than ${NAME_MAX} bytes`)
43
+ }
44
+ return segments
45
+ }
46
+
47
+ // What is left of `.` or `./` is the archive root, which only a directory
48
+ // may name; it comes back as `.`.
49
+ export function cleanPath(path, what, directory = false) {
50
+ const segments = checkText(path, what)
51
+ if (segments.at(-1) === '') {
52
+ if (!directory) throw new ArchiveError(`${what} ${quote(path)} ends in a slash but is not a directory`)
53
+ segments.pop()
54
+ }
55
+ const kept = segments.filter((segment) => segment !== '.')
56
+ for (const segment of kept) {
57
+ if (segment === '') throw new ArchiveError(`${what} ${quote(path)} has an empty segment`)
58
+ if (segment === '..') throw new ArchiveError(`${what} ${quote(path)} has a .. segment`)
59
+ }
60
+ if (kept.length) return kept.join('/')
61
+ if (!directory) throw new ArchiveError(`${what} ${quote(path)} names the archive root but is not a directory`)
62
+ return '.'
63
+ }
64
+
65
+ // Checks the target, walked from the link's directory, never climbs above
66
+ // the archive, and returns its steps: each segment it goes into, or `..` to
67
+ // come back out of one. The walk is counted rather than spelled out, since
68
+ // spelling out the path at every step of a deep one costs its depth squared.
69
+ export function checkSymlinkTarget(name, target) {
70
+ const steps = checkText(target, `symlink target of ${quote(name)}`).filter((segment) => segment !== '' && segment !== '.')
71
+ let depth = name.split('/').length - 1
72
+ for (const step of steps) {
73
+ depth += step === '..' ? -1 : 1
74
+ if (depth < 0) throw new ArchiveError(`symlink ${quote(name)} points outside the archive, to ${quote(target)}`)
75
+ }
76
+ return steps
77
+ }
78
+
79
+ // The name and link target of an entry, cleaned and checked.
80
+ export function cleanNames(path, type, target) {
81
+ const name = cleanPath(path, 'entry name', type === 'directory')
82
+ let linkname = target
83
+ if (type === 'symlink') checkSymlinkTarget(name, target)
84
+ else if (type === 'link') linkname = cleanPath(target, `hard link target of ${quote(name)}`)
85
+ return { name, linkname }
86
+ }
87
+
88
+ const node = () => ({ kind: undefined, entry: undefined, symlink: undefined, first: undefined, firstNode: undefined, rest: undefined })
89
+
90
+ // A node's first child sits on the node itself, and only a second one
91
+ // brings a map for the rest: a deep path is a chain of directories holding
92
+ // one thing each, and a map at every link of it would cost more than the
93
+ // link. With `make` false, a missing child stays missing.
94
+ function child(parent, segment, make = true) {
95
+ if (parent.first === segment) return parent.firstNode
96
+ let next = parent.rest?.get(segment)
97
+ if (next !== undefined || !make) return next
98
+ next = node()
99
+ if (parent.first === undefined) {
100
+ parent.first = segment
101
+ parent.firstNode = next
102
+ } else {
103
+ parent.rest ??= new Map()
104
+ parent.rest.set(segment, next)
105
+ }
106
+ return next
107
+ }
108
+
109
+ const FIELDS = ['type', 'mode', 'uid', 'gid', 'mtime', 'uname', 'gname', 'linkname', 'devmajor', 'devminor']
110
+
111
+ // Each name seen is an entry, a directory entry, or a directory implied by
112
+ // an entry inside it or by a symlink target walking through it; an implied
113
+ // directory may still be named as one. An entry inside a non-directory is
114
+ // refused — that is the shape of a path through a symlink — and so is a
115
+ // symlink target that walks through one, in either order, so no chain of
116
+ // links leads out of the archive. Whether entries are kept with their data
117
+ // decides what a repeat can be compared with: the in-memory calls keep
118
+ // them, and a stream keeps the fields alone and refuses what it cannot
119
+ // compare.
120
+ //
121
+ // The names are a tree walked a segment at a time, so a lookup hashes one
122
+ // segment rather than a whole path, and a walk down a deep one costs its
123
+ // length rather than its depth squared; a path is spelled out only for a
124
+ // refusal. A node's `kind` is unset until its path is seen, which makes the
125
+ // tree hold exactly what a map from each path seen to its kind would.
126
+ export class Names {
127
+ #root = node()
128
+ #keep
129
+
130
+ constructor(keep = false) {
131
+ this.#keep = keep
132
+ }
133
+
134
+ // `entry` is cleaned, with its data.
135
+ add(entry) {
136
+ const { name, type } = entry
137
+ // The target of the symlink this entry is, if it is one: a symlink's
138
+ // own, or, for a hard link, that of the entry it links to.
139
+ let symlink = type === 'symlink' ? entry.linkname : undefined
140
+ if (type === 'link') {
141
+ const target = this.#find(entry.linkname)
142
+ if (target?.kind !== 'entry') throw new ArchiveError(`hard link ${quote(name)} targets ${quote(entry.linkname)}, which is not an earlier non-directory entry`)
143
+ // A hard link to a symlink is a second name for that symlink, and a
144
+ // relative target is followed from wherever it is reached: `../x` under
145
+ // `a/b/` stays inside, the same link at the root does not. So the
146
+ // target is walked again from here, as if the symlink sat at this name.
147
+ // A hard link to such a hard link is the same symlink again, so the
148
+ // target travels down a chain of them, rather than the chain being
149
+ // followed back, which would cost each new link the chain's length.
150
+ symlink = target.symlink
151
+ if (symlink !== undefined) this.#symlink(name, symlink, `hard link ${quote(name)} to symlink ${quote(entry.linkname)}`)
152
+ }
153
+ const segments = name.split('/')
154
+ const nodes = this.#walk(segments)
155
+ const seen = nodes.at(-1)
156
+ if (seen.kind !== undefined && seen.kind !== 'implied') {
157
+ const differs = FIELDS.find((field) => seen.entry[field] !== entry[field])
158
+ if (differs !== undefined) throw new ArchiveError(`duplicate entry ${quote(name)} differs in ${differs}`)
159
+ if (seen.entry.data === undefined) throw new ArchiveError(`duplicate entry ${quote(name)}, which only the in-memory call can compare with the earlier one`)
160
+ if (!sameBytes(seen.entry.data, entry.data)) throw new ArchiveError(`duplicate entry ${quote(name)} differs in data`)
161
+ return
162
+ }
163
+ const kind = type === 'directory' ? 'directory' : 'entry'
164
+ if (seen.kind !== undefined && kind !== 'directory') throw new ArchiveError(`${quote(name)} is already a directory, so it cannot be a ${type}`)
165
+ // Every parent, the outermost first; nodes[0] is the root, which no
166
+ // name has as a parent.
167
+ for (let i = 1; i < segments.length; i++) {
168
+ this.#directory(nodes[i], () => `${quote(name)} is inside ${quote(segments.slice(0, i).join('/'))}, which is not a directory`)
169
+ }
170
+ seen.kind = kind
171
+ seen.symlink = symlink
172
+ seen.entry = this.#keep ? entry : Object.fromEntries(FIELDS.map((field) => [field, entry[field]]))
173
+ if (type === 'symlink') this.#symlink(name, entry.linkname, `symlink ${quote(name)}`)
174
+ }
175
+
176
+ // A target followed from `at`: it has to stay inside the archive, and every
177
+ // path it walks through has to be a directory — each one it stands on short
178
+ // of the last step, the archive root aside. `what` names it in a refusal.
179
+ #symlink(at, target, what) {
180
+ const steps = checkSymlinkTarget(at, target)
181
+ const path = at.split('/').slice(0, -1)
182
+ const nodes = this.#walk(path)
183
+ for (const [i, step] of steps.entries()) {
184
+ if (step === '..') {
185
+ path.pop()
186
+ nodes.pop()
187
+ } else {
188
+ path.push(step)
189
+ nodes.push(child(nodes.at(-1), step))
190
+ }
191
+ if (i < steps.length - 1 && path.length) this.#directory(nodes.at(-1), () => `the target of ${what} passes through ${quote(path.join('/'))}, which is not a directory`)
192
+ }
193
+ }
194
+
195
+ // A path is a directory if named or implied as one so far, or implied now.
196
+ // `refusal` spells the path out, and only if it has to.
197
+ #directory(at, refusal) {
198
+ if (at.kind === 'entry') throw new ArchiveError(refusal())
199
+ at.kind ??= 'implied'
200
+ }
201
+
202
+ // The root and the node of each segment in turn, made where missing: a
203
+ // node made here is unseen until something sets its kind.
204
+ #walk(segments) {
205
+ const nodes = [this.#root]
206
+ for (const segment of segments) nodes.push(child(nodes.at(-1), segment))
207
+ return nodes
208
+ }
209
+
210
+ // A path's node where it has one, without making any.
211
+ #find(path) {
212
+ let at = this.#root
213
+ for (const segment of path.split('/')) {
214
+ at = child(at, segment, false)
215
+ if (at === undefined) return undefined
216
+ }
217
+ return at
218
+ }
219
+ }
@@ -0,0 +1,156 @@
1
+ // The 512-byte ustar header block, as GNU tar 1.35 writes and reads it.
2
+ // String fields come back as bytes cut at the first NUL, not text: GNU cuts
3
+ // a long name at 100 bytes wherever the real name went, and that is not
4
+ // always a whole character, so only the field that counts gets decoded.
5
+
6
+ import { EMPTY } from '../bytes.js'
7
+ import { ArchiveError } from '../error.js'
8
+
9
+ export const BLOCK = 512
10
+
11
+ export const isDevice = (type) => type === 'character-device' || type === 'block-device'
12
+
13
+ export const NAME_SIZE = 100
14
+ export const PREFIX_SIZE = 155
15
+ // 32 bytes, and GNU always ends them with a NUL, so 31 is the most.
16
+ export const OWNER_SIZE = 32
17
+
18
+ const NAME = 0
19
+ const MODE = 100
20
+ const UID = 108
21
+ const GID = 116
22
+ const SIZE = 124
23
+ const MTIME = 136
24
+ const CHKSUM = 148
25
+ const TYPEFLAG = 156
26
+ const LINKNAME = 157
27
+ const MAGIC = 257
28
+ const UNAME = 265
29
+ const GNAME = 297
30
+ const DEVMAJOR = 329
31
+ const DEVMINOR = 337
32
+ const PREFIX = 345
33
+ // Under the gnu magic: the old GNU sparse map, its isextended flag and the
34
+ // file's real size. libarchive reads them whatever the type flag says —
35
+ // taking the real size as the file's, and the map and any extension blocks
36
+ // after the header as its layout — where GNU tar and the rest read them for
37
+ // a sparse entry alone.
38
+ const OLD_SPARSE = 386
39
+ const OLD_SPARSE_END = 495
40
+
41
+ const USTAR_MAGIC = 'ustar\u000000' // "ustar", NUL, "00": ustar and pax
42
+ const GNU_MAGIC = 'ustar \0'
43
+
44
+ const latin1 = (text) => Uint8Array.from(text, (c) => c.codePointAt(0))
45
+ const ascii = (raw) => String.fromCodePoint(...raw)
46
+ // Throws (RangeError) rather than overwriting the next field.
47
+ const put = (block, offset, size, bytes) => block.subarray(offset, offset + size).set(bytes)
48
+
49
+ export const octalMax = (size) => 8 ** (size - 1) - 1
50
+ export const fitsOctal = (value, size) => value >= 0 && value <= octalMax(size)
51
+
52
+ // A number is size-1 octal digits and a NUL. GNU's format falls back to
53
+ // 0x80 (0xff when negative) and the value in base 256, big-endian, two's
54
+ // complement, over the rest of the field.
55
+ export function writeNumber(block, offset, size, value, gnu) {
56
+ if (fitsOctal(value, size)) {
57
+ put(block, offset, size, latin1(value.toString(8).padStart(size - 1, '0')))
58
+ return
59
+ }
60
+ if (!gnu) throw new ArchiveError(`${value} does not fit an octal field of ${size - 1} digits`)
61
+ block[offset] = value < 0 ? 0xff : 0x80
62
+ let v = BigInt.asUintN((size - 1) * 8, BigInt(value))
63
+ for (let i = offset + size - 1; i > offset; i--) {
64
+ block[i] = Number(v & 0xffn)
65
+ v >>= 8n
66
+ }
67
+ }
68
+
69
+ // Older tars wrote leading spaces, and either spaces or NULs after; a field
70
+ // left blank (npm's packer wrote uid and gid so for years) is 0, as GNU tar,
71
+ // libarchive and the rest read it. A NUL ends the number wherever it sits, so
72
+ // a field that opens with one is 0 however it goes on — GNU stops there, and
73
+ // reading the digits past it instead would give a size, and so an archive,
74
+ // that only this package sees. Only a time may be negative.
75
+ export function readNumber(block, offset, size, what, at, signed = false) {
76
+ const first = block[offset]
77
+ if (first === 0x80 || first === 0xff) {
78
+ let v = 0n
79
+ for (let i = offset + 1; i < offset + size; i++) v = (v << 8n) | BigInt(block[i])
80
+ if (first === 0xff) v = BigInt.asIntN((size - 1) * 8, v)
81
+ if (v < 0n && !signed) throw new ArchiveError(`the ${what} field is negative`, at)
82
+ if (v > BigInt(Number.MAX_SAFE_INTEGER) || v < -BigInt(Number.MAX_SAFE_INTEGER)) throw new ArchiveError(`the ${what} field is too large`, at)
83
+ return Number(v)
84
+ }
85
+ const match = /^ *([0-7]*) *$/u.exec(ascii(untilNul(block.subarray(offset, offset + size))))
86
+ if (!match) throw new ArchiveError(`the ${what} field is not an octal number`, at)
87
+ return match[1] === '' ? 0 : Number.parseInt(match[1], 8)
88
+ }
89
+
90
+ export function untilNul(raw) {
91
+ const end = raw.indexOf(0)
92
+ return end === -1 ? raw : raw.subarray(0, end)
93
+ }
94
+
95
+ const field = (block, offset, size) => untilNul(block.subarray(offset, offset + size))
96
+
97
+ // Every byte, with the checksum field itself counted as spaces.
98
+ function checksum(block) {
99
+ let sum = 8 * 0x20
100
+ for (let i = 0; i < CHKSUM; i++) sum += block[i]
101
+ for (let i = CHKSUM + 8; i < BLOCK; i++) sum += block[i]
102
+ return sum
103
+ }
104
+
105
+ export const isZeroBlock = (block) => block.every((byte) => byte === 0)
106
+
107
+ // String fields are bytes already cut to size; numbers already fit the
108
+ // format. `devmajor` and `devminor` are null except for a device, since
109
+ // GNU leaves those fields NUL for everything else.
110
+ export function encodeHeader(f) {
111
+ const block = new Uint8Array(BLOCK)
112
+ put(block, NAME, NAME_SIZE, f.name)
113
+ writeNumber(block, MODE, 8, f.mode, f.gnu)
114
+ writeNumber(block, UID, 8, f.uid, f.gnu)
115
+ writeNumber(block, GID, 8, f.gid, f.gnu)
116
+ writeNumber(block, SIZE, 12, f.size, f.gnu)
117
+ writeNumber(block, MTIME, 12, f.mtime, f.gnu)
118
+ block[TYPEFLAG] = f.typeflag
119
+ put(block, LINKNAME, NAME_SIZE, f.linkname)
120
+ put(block, MAGIC, 8, latin1(f.gnu ? GNU_MAGIC : USTAR_MAGIC))
121
+ put(block, UNAME, OWNER_SIZE - 1, f.uname)
122
+ put(block, GNAME, OWNER_SIZE - 1, f.gname)
123
+ if (f.devmajor !== null) writeNumber(block, DEVMAJOR, 8, f.devmajor, f.gnu)
124
+ if (f.devminor !== null) writeNumber(block, DEVMINOR, 8, f.devminor, f.gnu)
125
+ put(block, PREFIX, PREFIX_SIZE, f.prefix)
126
+ // The one field written as digits, NUL, space.
127
+ put(block, CHKSUM, 8, latin1(`${checksum(block).toString(8).padStart(6, '0')}\0 `))
128
+ return block
129
+ }
130
+
131
+ export function decodeHeader(block, at) {
132
+ if (checksum(block) !== readNumber(block, CHKSUM, 8, 'checksum', at)) throw new ArchiveError('header checksum does not match', at)
133
+ const magic = ascii(block.subarray(MAGIC, MAGIC + 8))
134
+ const gnu = magic === GNU_MAGIC
135
+ if (!gnu && magic !== USTAR_MAGIC) throw new ArchiveError('header is not in the ustar, pax or gnu format', at)
136
+ if (gnu && !isZeroBlock(block.subarray(OLD_SPARSE, OLD_SPARSE_END))) throw new ArchiveError('header carries an old GNU sparse map or real size', at)
137
+ const typeflag = block[TYPEFLAG]
138
+ const device = typeflag === 0x33 || typeflag === 0x34
139
+ return {
140
+ gnu,
141
+ typeflag,
142
+ name: field(block, NAME, NAME_SIZE),
143
+ // Under the gnu magic those bytes belong to the old GNU header instead.
144
+ prefix: gnu ? EMPTY : field(block, PREFIX, PREFIX_SIZE),
145
+ linkname: field(block, LINKNAME, NAME_SIZE),
146
+ uname: field(block, UNAME, OWNER_SIZE),
147
+ gname: field(block, GNAME, OWNER_SIZE),
148
+ mode: readNumber(block, MODE, 8, 'mode', at),
149
+ uid: readNumber(block, UID, 8, 'uid', at),
150
+ gid: readNumber(block, GID, 8, 'gid', at),
151
+ size: readNumber(block, SIZE, 12, 'size', at),
152
+ mtime: readNumber(block, MTIME, 12, 'mtime', at, true),
153
+ devmajor: device ? readNumber(block, DEVMAJOR, 8, 'devmajor', at) : 0,
154
+ devminor: device ? readNumber(block, DEVMINOR, 8, 'devminor', at) : 0,
155
+ }
156
+ }