bagit-node 0.0.0-stage → 1.0.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 +21 -0
- package/NOTICE +6 -0
- package/README.md +228 -2
- package/dist/cjs/bag.d.ts +59 -0
- package/dist/cjs/bag.d.ts.map +1 -0
- package/dist/cjs/bag.js +329 -0
- package/dist/cjs/bag.js.map +1 -0
- package/dist/cjs/errors.d.ts +32 -0
- package/dist/cjs/errors.d.ts.map +1 -0
- package/dist/cjs/errors.js +60 -0
- package/dist/cjs/errors.js.map +1 -0
- package/dist/cjs/index.d.ts +6 -0
- package/dist/cjs/index.d.ts.map +1 -0
- package/dist/cjs/index.js +39 -0
- package/dist/cjs/index.js.map +1 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/types.d.ts +29 -0
- package/dist/cjs/types.d.ts.map +1 -0
- package/dist/cjs/types.js +3 -0
- package/dist/cjs/types.js.map +1 -0
- package/dist/cjs/util.d.ts +39 -0
- package/dist/cjs/util.d.ts.map +1 -0
- package/dist/cjs/util.js +355 -0
- package/dist/cjs/util.js.map +1 -0
- package/dist/cjs/zip.d.ts +47 -0
- package/dist/cjs/zip.d.ts.map +1 -0
- package/dist/cjs/zip.js +336 -0
- package/dist/cjs/zip.js.map +1 -0
- package/dist/esm/bag.d.ts +59 -0
- package/dist/esm/bag.d.ts.map +1 -0
- package/dist/esm/bag.js +322 -0
- package/dist/esm/bag.js.map +1 -0
- package/dist/esm/errors.d.ts +32 -0
- package/dist/esm/errors.d.ts.map +1 -0
- package/dist/esm/errors.js +50 -0
- package/dist/esm/errors.js.map +1 -0
- package/dist/esm/index.d.ts +6 -0
- package/dist/esm/index.d.ts.map +1 -0
- package/dist/esm/index.js +5 -0
- package/dist/esm/index.js.map +1 -0
- package/dist/esm/types.d.ts +29 -0
- package/dist/esm/types.d.ts.map +1 -0
- package/dist/esm/types.js +2 -0
- package/dist/esm/types.js.map +1 -0
- package/dist/esm/util.d.ts +39 -0
- package/dist/esm/util.d.ts.map +1 -0
- package/dist/esm/util.js +326 -0
- package/dist/esm/util.js.map +1 -0
- package/dist/esm/zip.d.ts +47 -0
- package/dist/esm/zip.d.ts.map +1 -0
- package/dist/esm/zip.js +330 -0
- package/dist/esm/zip.js.map +1 -0
- package/package.json +46 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 dcbeck
|
|
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.
|
package/NOTICE
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
BagIt behavior and compatibility tests are based on LibraryOfCongress/bagit-python:
|
|
2
|
+
https://github.com/LibraryOfCongress/bagit-python
|
|
3
|
+
Reference commit: 4bd2713cedbe1f8e634567c20ef0dded9622011d
|
|
4
|
+
Upstream identifies its Python code as public domain.
|
|
5
|
+
The test/vendor directory contains unmodified reference material for testing only
|
|
6
|
+
and is excluded from npm releases. See test/vendor/bagit-python/README.md.
|
package/README.md
CHANGED
|
@@ -1,3 +1,229 @@
|
|
|
1
|
-
#
|
|
1
|
+
# bagit-node
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A TypeScript implementation of the [Library of Congress BagIt Python library](https://github.com/LibraryOfCongress/bagit-python), with ESM and CommonJS APIs. Uses Node's standard libraries for BagIt and [yazl](https://github.com/thejoshwolfe/yazl) for ZIP output: one direct runtime dependency, with its small `buffer-crc32` dependency. Requires Node.js 20.19 or newer. Python is needed only for the optional compatibility tests.
|
|
4
|
+
|
|
5
|
+
Creates and validates [RFC 8493 BagIt 1.0](https://www.rfc-editor.org/rfc/rfc8493.html) bags, reads older bags from version 0.93, and streams folders or application-provided sources into ZIP64 archives.
|
|
6
|
+
|
|
7
|
+
## Build and import
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
npm install
|
|
11
|
+
npm run build
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
```ts
|
|
15
|
+
// ESM / TypeScript
|
|
16
|
+
import { Bag, makeBag, folderToBagZip, createBagZipStream } from 'bagit-node';
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
```js
|
|
20
|
+
// CommonJS
|
|
21
|
+
const { Bag, makeBag, folderToBagZip, createBagZipStream } = require('bagit-node');
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
Both formats include TypeScript declarations. Development dependencies are TypeScript and type definitions. There is no CLI.
|
|
25
|
+
|
|
26
|
+
## Create a bag in place
|
|
27
|
+
|
|
28
|
+
```ts
|
|
29
|
+
const bag = await makeBag('/exports/my-folder', {
|
|
30
|
+
bagInfo: {
|
|
31
|
+
'Source-Organization': 'My archive',
|
|
32
|
+
'Contact-Name': ['Alice', 'Bob'],
|
|
33
|
+
'External-Identifier': 'collection-123',
|
|
34
|
+
},
|
|
35
|
+
checksums: ['sha256', 'sha512'], // defaults
|
|
36
|
+
concurrency: 4, // default: 1 simultaneous file read
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
await bag.validate();
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
This moves the folder's existing contents into `data/`, preserves directory permissions, and writes `bagit.txt`, `bag-info.txt`, payload manifests, and tag manifests. An existing `data/` becomes `data/data/`, matching Python. Empty payloads receive empty manifests and remain valid. The function never changes the process working directory.
|
|
43
|
+
|
|
44
|
+
`Bagging-Date` defaults to the local calendar date. `Bag-Software-Agent` defaults to `bagit-node v1.0.0`. Both may be overridden. `Payload-Oxum` is always calculated from the payload. New bags use UTF-8.
|
|
45
|
+
|
|
46
|
+
## Open, inspect, validate, and save
|
|
47
|
+
|
|
48
|
+
```ts
|
|
49
|
+
const bag = new Bag('/exports/existing-bag');
|
|
50
|
+
// Opening reads declaration, metadata, and manifests synchronously.
|
|
51
|
+
// Hashing, validation, and saving are asynchronous.
|
|
52
|
+
|
|
53
|
+
console.log(bag.info, bag.algorithms, bag.versionInfo);
|
|
54
|
+
console.log([...bag.payloadFiles()]);
|
|
55
|
+
console.log(bag.payloadEntries()); // { 'data/file.txt': { sha256: '...', ... } }
|
|
56
|
+
|
|
57
|
+
await bag.validate(); // structure, oxum, completeness, hashes
|
|
58
|
+
await bag.validate({ fast: true }); // structure and oxum; requires Payload-Oxum
|
|
59
|
+
await bag.validate({ completenessOnly: true }); // structure, oxum, filenames; no hashes
|
|
60
|
+
console.log(await bag.isValid()); // boolean for BagError failures
|
|
61
|
+
|
|
62
|
+
bag.info['Contact-Name'] = 'New contact';
|
|
63
|
+
await bag.save(); // preserves payload manifests, regenerates tag manifests
|
|
64
|
+
|
|
65
|
+
// After deliberately adding, removing or updating payload files:
|
|
66
|
+
await bag.save({ manifests: true }); // also regenerates payload manifests and oxum
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
`validate`, `isValid`, and `save` accept `concurrency` and `signal`. Cancellation and programming errors propagate; `isValid` catches only bag errors. An open `Bag` retains its loaded manifest entries, like Python; construct a new instance to reload external manifest changes.
|
|
70
|
+
|
|
71
|
+
| API | Result |
|
|
72
|
+
| --- | --- |
|
|
73
|
+
| `bag.manifestFiles()` / `bag.tagmanifestFiles()` | Iterators of absolute manifest paths |
|
|
74
|
+
| `bag.payloadFiles()` | Iterator of payload paths relative to the bag |
|
|
75
|
+
| `bag.payloadEntries()` / `bag.tagfileEntries()` | Filename → algorithm → checksum objects |
|
|
76
|
+
| `bag.compareManifestsWithFs()` | `[missingFiles, unexpectedFiles]` |
|
|
77
|
+
| `bag.missingOptionalTagfiles()` | Iterator of missing tag files listed in manifests |
|
|
78
|
+
| `bag.fetchEntries()` | Iterator of `[url, sizeString, filename]` tuples |
|
|
79
|
+
| `bag.filesToBeFetched()` | Iterator of paths listed in `fetch.txt` |
|
|
80
|
+
| `bag.compareFetchWithFs()` | Fetch paths not present in the payload |
|
|
81
|
+
| `bag.validateFetch()` | Checks fetch URLs and safe paths; does not download files |
|
|
82
|
+
| `bag.hasOxum()` | Whether metadata contains `Payload-Oxum` |
|
|
83
|
+
|
|
84
|
+
Python-style method aliases such as `payload_files`, `is_valid`, and `fetch_entries` are available. The exported `make_bag` alias takes the same **options object** as `makeBag`; Python positional argument conventions are not used in the Node API.
|
|
85
|
+
|
|
86
|
+
Validation errors are structured:
|
|
87
|
+
|
|
88
|
+
```ts
|
|
89
|
+
import { BagValidationError, ChecksumMismatch } from 'bagit-node';
|
|
90
|
+
|
|
91
|
+
try {
|
|
92
|
+
await bag.validate();
|
|
93
|
+
} catch (error) {
|
|
94
|
+
if (error instanceof BagValidationError) {
|
|
95
|
+
for (const detail of error.details) {
|
|
96
|
+
console.error(detail.path, detail.message);
|
|
97
|
+
if (detail instanceof ChecksumMismatch) {
|
|
98
|
+
console.error(detail.algorithm, detail.expected, detail.found);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
Exported error classes: `BagError`, `BagValidationError`, `ManifestErrorDetail`, `ChecksumMismatch`, `FileMissing`, `UnexpectedFile`, and `FileNormalizationConflict`.
|
|
106
|
+
|
|
107
|
+
Lower-level helpers include `makeManifests(bagRoot, options)`, `makeTagManifests(bagRoot, algorithms)`, `generateManifestLines(filename, algorithms)`, `loadTagFile`, `parseTagFile`, `serializeTagFile`, `encodeFilename`, `decodeFilename`, `normalizeUnicode`, `buildUnicodeNormalizedLookupDict`, and `getHashers`. `generateManifestLines` reads a file once and returns `[algorithm, digest, filename, byteCount]` tuples, with byte counts as `bigint`. Constants include `VERSION`, `DEFAULT_CHECKSUMS`, `CHECKSUM_ALGOS`, `HASH_BLOCK_SIZE`, and `STANDARD_BAG_INFO_HEADERS`.
|
|
108
|
+
|
|
109
|
+
## Stream a folder to a BagIt ZIP
|
|
110
|
+
|
|
111
|
+
```ts
|
|
112
|
+
const result = await folderToBagZip('/exports/source', '/exports/source.bag.zip', {
|
|
113
|
+
bagName: 'my-bag', // optional containing directory; default: archive root
|
|
114
|
+
bagInfo: { 'External-Identifier': 'collection-123' },
|
|
115
|
+
checksums: ['sha256', 'sha512'],
|
|
116
|
+
compressionLevel: 6, // 0–9
|
|
117
|
+
onProgress({ path, totalFiles, totalBytes }) {
|
|
118
|
+
console.log(path, totalFiles, totalBytes);
|
|
119
|
+
},
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
console.log(result.payloadFiles, result.payloadBytes, result.bytesWritten);
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
The source directory remains intact. The output path must be outside it. File output is written to a temporary sibling and renamed after successful completion, preserving an existing destination if generation fails. A writable stream is also accepted and is ended by the method:
|
|
126
|
+
|
|
127
|
+
```ts
|
|
128
|
+
import { createWriteStream } from 'node:fs';
|
|
129
|
+
|
|
130
|
+
await folderToBagZip('/exports/source', createWriteStream('/exports/source.bag.zip'));
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
`folderToBagitZip` is an alias for `folderToBagZip`.
|
|
134
|
+
|
|
135
|
+
Each source file is opened once. Its bytes pass through incremental hashing, ZIP deflate compression, and the output stream with backpressure. SHA checksums cover the original bytes before compression. Payload manifests are appended after payload entries, then bag metadata, then tag manifests. ZIP64 supports files and offsets above 4 GiB and more than 65,535 entries.
|
|
136
|
+
|
|
137
|
+
Payloads and the complete ZIP are never buffered or staged by the streaming APIs. Manifests are spooled to temporary files, removed on completion, cancellation, or failure. Memory holds stream buffers, ZIP central directory metadata, and filenames for duplicate/path checks; it grows with the number of entries, not their byte sizes. `tempDirectory` selects the spool location and must be outside a folder source. Directory exports preserve empty directories, ZIP timestamps, and Unix modes. `mtime` sets a fixed ZIP timestamp for reproducible exports. Yazl automatically uses ZIP64 when needed, so small archives remain compatible with ordinary ZIP readers.
|
|
138
|
+
|
|
139
|
+
Source changes detected while a file is read cause export to fail. Keep sources stable during export: this is not a filesystem snapshot. Symlinks resolving outside the source are rejected, and folder export rejects directory symlinks. Custom source iterables must honor cancellation during their own pending I/O.
|
|
140
|
+
|
|
141
|
+
## Pipe directly to Ceph / S3 multipart upload
|
|
142
|
+
|
|
143
|
+
`createBagZipStream` returns a standard Node `Readable`, suitable for your existing multipart uploader. For example, if your application already uses the AWS SDK:
|
|
144
|
+
|
|
145
|
+
```ts
|
|
146
|
+
import { createBagZipStream } from 'bagit-node';
|
|
147
|
+
import { Upload } from '@aws-sdk/lib-storage'; // application dependency, not a bagit-node dependency
|
|
148
|
+
|
|
149
|
+
const controller = new AbortController();
|
|
150
|
+
const body = createBagZipStream('/exports/source', {
|
|
151
|
+
signal: controller.signal,
|
|
152
|
+
checksums: ['sha256', 'sha512'],
|
|
153
|
+
});
|
|
154
|
+
|
|
155
|
+
const upload = new Upload({
|
|
156
|
+
client: s3Client, // configured by your application for S3 or Ceph
|
|
157
|
+
params: {
|
|
158
|
+
Bucket: 'archive',
|
|
159
|
+
Key: 'collection-123.bag.zip',
|
|
160
|
+
Body: body,
|
|
161
|
+
ContentType: 'application/zip',
|
|
162
|
+
},
|
|
163
|
+
queueSize: 4,
|
|
164
|
+
partSize: 8 * 1024 * 1024,
|
|
165
|
+
});
|
|
166
|
+
|
|
167
|
+
try {
|
|
168
|
+
await upload.done();
|
|
169
|
+
} catch (error) {
|
|
170
|
+
controller.abort(error);
|
|
171
|
+
await upload.abort().catch(() => {});
|
|
172
|
+
throw error;
|
|
173
|
+
}
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
The uploader's queue adds its own multipart buffers. A content length is not known before streaming. The stream emits source, compression, and filesystem errors; use an error-aware consumer such as `pipeline` or your multipart uploader. A consumed stream cannot be replayed. To retry or generate a temporary ZIP fallback, call `createBagZipStream` or `folderToBagZip` again, reading the sources again.
|
|
177
|
+
|
|
178
|
+
## Build a ZIP directly from application sources
|
|
179
|
+
|
|
180
|
+
`createBagZipStreamFromEntries` accepts an iterable or async iterable of lazy sources. This lets exporters produce bytes without writing ordinary payload files to a staging folder.
|
|
181
|
+
|
|
182
|
+
```ts
|
|
183
|
+
import { Readable } from 'node:stream';
|
|
184
|
+
import { createBagZipStreamFromEntries } from 'bagit-node';
|
|
185
|
+
|
|
186
|
+
async function* entries() {
|
|
187
|
+
yield {
|
|
188
|
+
path: 'record.json', // relative to data/; do not include the data/ prefix
|
|
189
|
+
open: () => Readable.from([Buffer.from(JSON.stringify({ id: 123 }))]),
|
|
190
|
+
};
|
|
191
|
+
yield {
|
|
192
|
+
path: 'images/original.tif',
|
|
193
|
+
open: async () => openOriginalImageStream(), // supplied by your application
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
const body = createBagZipStreamFromEntries(entries(), {
|
|
198
|
+
bagInfo: { 'External-Identifier': 'collection-123' },
|
|
199
|
+
});
|
|
200
|
+
// Pass body to your multipart uploader or pipeline(body, destination).
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
`open()` is called lazily, once per entry, and returns a `Readable`, iterable, or async iterable of `Uint8Array`/`Buffer` chunks, or a promise for one. Only one payload is read at a time. Source lengths need not be known. Entries may set `mtime`, `mode`, and `directory: true` (with `open: () => []`) for empty directories. Progress callbacks are awaited after each completed payload.
|
|
204
|
+
|
|
205
|
+
Archive paths must be relative POSIX paths. Absolute paths, traversal, backslashes, duplicate paths, Unicode normalization collisions, and file/directory conflicts are rejected. CR/LF filenames are encoded in manifests. Literal `%0A`/`%0D` in names and trailing whitespace that cannot round-trip through Python's manifest parser are rejected by ZIP export.
|
|
206
|
+
|
|
207
|
+
## Compatibility and verification
|
|
208
|
+
|
|
209
|
+
The reference is pinned at [`4bd2713`](https://github.com/LibraryOfCongress/bagit-python/tree/4bd2713cedbe1f8e634567c20ef0dded9622011d). Test-only upstream files and fixtures are included under `test/vendor/` and excluded from npm packages.
|
|
210
|
+
|
|
211
|
+
```sh
|
|
212
|
+
npm test # Node API, ESM/CommonJS, validation and streaming failure tests
|
|
213
|
+
npm run test:upstream # 96 unchanged upstream library cases through a Python → Node transport
|
|
214
|
+
npm run test:interop # independent Python validation and byte comparisons; stdlib ZIP extraction
|
|
215
|
+
npm run test:stress # actual >4 GiB file and >65,535 archive entries
|
|
216
|
+
npm run test:all # all of the above
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
Compatibility/stress tests require Python 3; no Python packages need installing. Permission tests should run as a regular user, as in the upstream suite. The Python adapter only translates calls, options, and errors; creation, parsing, hashing, and validation execute in Node. Upstream CLI tests are omitted because this package deliberately has no CLI. Three Python multiprocessing implementation tests are inapplicable; Node uses bounded asynchronous file I/O and has separate cancellation/failure tests.
|
|
220
|
+
|
|
221
|
+
Supported checksum names are `md5`, `sha1`, `sha224`, `sha256`, `sha384`, `sha512`, `sha3_224`, `sha3_256`, `sha3_384`, `sha3_512`, `blake2b`, and `blake2s`, subject to the Node OpenSSL build. Unsupported requested names are skipped if another supported algorithm remains. SHAKE algorithms require a digest length and are not supported by upstream's fixed-length BagIt manifest generation either.
|
|
222
|
+
|
|
223
|
+
The implementation preserves Python's metadata formatting, manifest syntax, default SHA-256/SHA-512 algorithms, repeated tags, folded tags, mixed-case checksum acceptance, optional tags, fetch validation, Unicode-normalized filename lookup, validation modes, and error details. It intentionally identifies itself in `Bag-Software-Agent`, creates valid empty manifests for empty bags, rejects additional unsafe or ambiguous archive paths, and does not reproduce Python's process-management internals or CLI. Tag-manifest entry ordering is deterministic here; Python's ordering depends on filesystem enumeration. Supply identical metadata when comparing generated bag bytes.
|
|
224
|
+
|
|
225
|
+
Reading existing tag encodings uses Node's built-in `TextDecoder`, with strict UTF-8, ASCII and ISO-8859-1 handling. Saving supports UTF-8, UTF-16 and representable single-byte encodings. Python-specific codecs and legacy multibyte encoding output are not provided; new bags always use UTF-8.
|
|
226
|
+
|
|
227
|
+
## License
|
|
228
|
+
|
|
229
|
+
MIT. See [LICENSE](LICENSE) and [NOTICE](NOTICE). The reference Python project declares its code public domain.
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import type { BagInfo, Entries, FetchEntry, MakeBagOptions, SaveOptions, ValidationOptions } from './types.js';
|
|
2
|
+
export declare class Bag {
|
|
3
|
+
readonly path: string;
|
|
4
|
+
tags: BagInfo;
|
|
5
|
+
info: BagInfo;
|
|
6
|
+
entries: Entries;
|
|
7
|
+
algorithms: string[];
|
|
8
|
+
versionInfo: readonly [number, number];
|
|
9
|
+
version: string;
|
|
10
|
+
encoding: string;
|
|
11
|
+
tagFileName: string;
|
|
12
|
+
normalizedFilesystemNames: Record<string, string>;
|
|
13
|
+
normalizedManifestNames: Record<string, string>;
|
|
14
|
+
/** Reads declaration, metadata and manifests synchronously; file hashing is asynchronous. */
|
|
15
|
+
constructor(path: string);
|
|
16
|
+
toString(): string;
|
|
17
|
+
get algs(): string[];
|
|
18
|
+
get version_info(): readonly [number, number];
|
|
19
|
+
get tag_file_name(): string;
|
|
20
|
+
private get verifiesTagFiles();
|
|
21
|
+
manifestFiles(): Generator<string>;
|
|
22
|
+
tagmanifestFiles(): Generator<string>;
|
|
23
|
+
private loadManifests;
|
|
24
|
+
payloadFiles(): Generator<string>;
|
|
25
|
+
payloadEntries(): Entries;
|
|
26
|
+
tagfileEntries(): Entries;
|
|
27
|
+
missingOptionalTagfiles(): Generator<string>;
|
|
28
|
+
compareManifestsWithFs(): [string[], string[]];
|
|
29
|
+
fetchEntries(): Generator<FetchEntry>;
|
|
30
|
+
filesToBeFetched(): Generator<string>;
|
|
31
|
+
compareFetchWithFs(): string[];
|
|
32
|
+
validateFetch(): void;
|
|
33
|
+
hasOxum(): boolean;
|
|
34
|
+
validate(options?: ValidationOptions): Promise<true>;
|
|
35
|
+
private validateOxum;
|
|
36
|
+
isValid(options?: ValidationOptions): Promise<boolean>;
|
|
37
|
+
save(options?: SaveOptions): Promise<void>;
|
|
38
|
+
manifest_files: () => Generator<string>;
|
|
39
|
+
tagmanifest_files: () => Generator<string>;
|
|
40
|
+
payload_files: () => Generator<string>;
|
|
41
|
+
payload_entries: () => Entries;
|
|
42
|
+
tagfile_entries: () => Entries;
|
|
43
|
+
missing_optional_tagfiles: () => Generator<string>;
|
|
44
|
+
compare_manifests_with_fs: () => [string[], string[]];
|
|
45
|
+
compare_fetch_with_fs: () => string[];
|
|
46
|
+
fetch_entries: () => Generator<FetchEntry>;
|
|
47
|
+
files_to_be_fetched: () => Generator<string>;
|
|
48
|
+
validate_fetch: () => void;
|
|
49
|
+
has_oxum: () => boolean;
|
|
50
|
+
is_valid: (options?: ValidationOptions) => Promise<boolean>;
|
|
51
|
+
}
|
|
52
|
+
/** Convert a directory in place. Existing contents, including an existing data/, become payload. */
|
|
53
|
+
export declare function makeBag(directory: string, options?: MakeBagOptions): Promise<Bag>;
|
|
54
|
+
export declare function makeManifests(root: string, options?: Pick<MakeBagOptions, 'checksums' | 'concurrency' | 'signal'>, encoding?: string): Promise<{
|
|
55
|
+
bytes: bigint;
|
|
56
|
+
files: number;
|
|
57
|
+
}>;
|
|
58
|
+
export declare function makeTagManifests(root: string, algorithms?: readonly string[], encoding?: string, signal?: AbortSignal): Promise<void>;
|
|
59
|
+
//# sourceMappingURL=bag.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bag.d.ts","sourceRoot":"","sources":["../../src/bag.ts"],"names":[],"mappings":"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"}
|
package/dist/cjs/bag.js
ADDED
|
@@ -0,0 +1,329 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.Bag = void 0;
|
|
4
|
+
exports.makeBag = makeBag;
|
|
5
|
+
exports.makeManifests = makeManifests;
|
|
6
|
+
exports.makeTagManifests = makeTagManifests;
|
|
7
|
+
const node_fs_1 = require("node:fs");
|
|
8
|
+
const promises_1 = require("node:fs/promises");
|
|
9
|
+
const node_path_1 = require("node:path");
|
|
10
|
+
const errors_js_1 = require("./errors.js");
|
|
11
|
+
const util_js_1 = require("./util.js");
|
|
12
|
+
class Bag {
|
|
13
|
+
path;
|
|
14
|
+
tags = Object.create(null);
|
|
15
|
+
info = Object.create(null);
|
|
16
|
+
entries = Object.create(null);
|
|
17
|
+
algorithms = [];
|
|
18
|
+
versionInfo;
|
|
19
|
+
version;
|
|
20
|
+
encoding;
|
|
21
|
+
tagFileName;
|
|
22
|
+
normalizedFilesystemNames = Object.create(null);
|
|
23
|
+
normalizedManifestNames = Object.create(null);
|
|
24
|
+
/** Reads declaration, metadata and manifests synchronously; file hashing is asynchronous. */
|
|
25
|
+
constructor(path) {
|
|
26
|
+
this.path = (0, node_path_1.resolve)(path);
|
|
27
|
+
const declaration = (0, node_path_1.join)(this.path, 'bagit.txt');
|
|
28
|
+
if (!(0, util_js_1.isFile)(declaration))
|
|
29
|
+
throw new errors_js_1.BagError(`Expected bagit.txt does not exist: ${declaration}`);
|
|
30
|
+
this.tags = (0, util_js_1.parseTagFile)((0, util_js_1.decodeText)((0, node_fs_1.readFileSync)(declaration)), 'bagit.txt');
|
|
31
|
+
const missing = ['BagIt-Version', 'Tag-File-Character-Encoding'].filter(k => !(k in this.tags));
|
|
32
|
+
if (missing.length)
|
|
33
|
+
throw new errors_js_1.BagError(`Missing required tag in bagit.txt: ${missing.join(', ')}`);
|
|
34
|
+
const version = this.tags['BagIt-Version'];
|
|
35
|
+
if (typeof version !== 'string' || !/^\d+\.\d+$/.test(version)) {
|
|
36
|
+
throw new errors_js_1.BagError(`Bag version numbers must be MAJOR.MINOR numbers, not ${String(version)}`);
|
|
37
|
+
}
|
|
38
|
+
this.version = version;
|
|
39
|
+
const [major, minor] = version.split('.').map(Number);
|
|
40
|
+
this.versionInfo = [major, minor];
|
|
41
|
+
if (major === 0 && minor >= 93 && minor <= 95)
|
|
42
|
+
this.tagFileName = 'package-info.txt';
|
|
43
|
+
else if ((major === 0 && minor >= 96) || major === 1)
|
|
44
|
+
this.tagFileName = 'bag-info.txt';
|
|
45
|
+
else
|
|
46
|
+
throw new errors_js_1.BagError(`Unsupported bag version: ${version}`);
|
|
47
|
+
const encoding = this.tags['Tag-File-Character-Encoding'];
|
|
48
|
+
if (typeof encoding !== 'string')
|
|
49
|
+
throw new errors_js_1.BagValidationError('Tag-File-Character-Encoding must occur once');
|
|
50
|
+
this.encoding = encoding;
|
|
51
|
+
(0, util_js_1.checkEncoding)(encoding);
|
|
52
|
+
const infoPath = (0, node_path_1.join)(this.path, this.tagFileName);
|
|
53
|
+
if ((0, util_js_1.isFile)(infoPath))
|
|
54
|
+
this.info = (0, util_js_1.parseTagFile)((0, util_js_1.decodeText)((0, node_fs_1.readFileSync)(infoPath), encoding), this.tagFileName);
|
|
55
|
+
this.loadManifests();
|
|
56
|
+
}
|
|
57
|
+
toString() { return this.path; }
|
|
58
|
+
get algs() { return this.algorithms; }
|
|
59
|
+
get version_info() { return this.versionInfo; }
|
|
60
|
+
get tag_file_name() { return this.tagFileName; }
|
|
61
|
+
get verifiesTagFiles() { return this.versionInfo[0] >= 1 || this.versionInfo[1] >= 97; }
|
|
62
|
+
*manifestFiles() {
|
|
63
|
+
for (const a of util_js_1.CHECKSUM_ALGOS)
|
|
64
|
+
if ((0, util_js_1.isFile)((0, node_path_1.join)(this.path, `manifest-${a}.txt`)))
|
|
65
|
+
yield (0, node_path_1.join)(this.path, `manifest-${a}.txt`);
|
|
66
|
+
}
|
|
67
|
+
*tagmanifestFiles() {
|
|
68
|
+
for (const a of util_js_1.CHECKSUM_ALGOS)
|
|
69
|
+
if ((0, util_js_1.isFile)((0, node_path_1.join)(this.path, `tagmanifest-${a}.txt`)))
|
|
70
|
+
yield (0, node_path_1.join)(this.path, `tagmanifest-${a}.txt`);
|
|
71
|
+
}
|
|
72
|
+
loadManifests() {
|
|
73
|
+
this.entries = Object.create(null);
|
|
74
|
+
this.algorithms = [];
|
|
75
|
+
const manifests = [...this.manifestFiles(), ...(this.verifiesTagFiles ? this.tagmanifestFiles() : [])];
|
|
76
|
+
for (const manifest of manifests) {
|
|
77
|
+
const algorithm = (0, node_path_1.basename)(manifest).replace(/^(?:tag)?manifest-/, '').replace(/\.txt$/, '');
|
|
78
|
+
if (!this.algorithms.includes(algorithm))
|
|
79
|
+
this.algorithms.push(algorithm);
|
|
80
|
+
const text = (0, util_js_1.decodeText)((0, node_fs_1.readFileSync)(manifest), this.encoding);
|
|
81
|
+
for (const raw of text.split(/\r\n|\n|\r/)) {
|
|
82
|
+
const line = raw.trim();
|
|
83
|
+
if (!line || line.startsWith('#'))
|
|
84
|
+
continue;
|
|
85
|
+
const entry = /^(\S+)\s+(.+)$/.exec(line);
|
|
86
|
+
if (!entry)
|
|
87
|
+
continue; // Python logs and skips malformed lines.
|
|
88
|
+
const digest = entry[1];
|
|
89
|
+
const filename = (0, util_js_1.decodeFilename)(node_path_1.posix.normalize(entry[2].replace(/^\*+/, '')));
|
|
90
|
+
(0, util_js_1.assertSafePath)(this.path, filename, `manifest "${manifest}"`);
|
|
91
|
+
const hashes = this.entries[filename] ??= Object.create(null);
|
|
92
|
+
if (Object.hasOwn(hashes, algorithm)) {
|
|
93
|
+
const same = hashes[algorithm] === digest;
|
|
94
|
+
if (!same || this.versionInfo[0] >= 1) {
|
|
95
|
+
throw new errors_js_1.BagError(`${this.path}: ${algorithm} manifest lists ${filename} multiple times with ${same ? 'the same value' : 'conflicting values'}`);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
hashes[algorithm] = digest;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
this.normalizedManifestNames = (0, util_js_1.buildUnicodeNormalizedLookupDict)(Object.keys(this.entries));
|
|
102
|
+
}
|
|
103
|
+
*payloadFiles() {
|
|
104
|
+
this.normalizedFilesystemNames = Object.create(null);
|
|
105
|
+
for (const filename of (0, util_js_1.walkFiles)((0, node_path_1.join)(this.path, 'data'), 'data/')) {
|
|
106
|
+
this.normalizedFilesystemNames[(0, util_js_1.normalizeUnicode)(filename)] = filename;
|
|
107
|
+
yield filename;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
payloadEntries() { return Object.fromEntries(Object.entries(this.entries).filter(([p]) => p.startsWith('data/'))); }
|
|
111
|
+
tagfileEntries() { return Object.fromEntries(Object.entries(this.entries).filter(([p]) => !p.startsWith('data/'))); }
|
|
112
|
+
*missingOptionalTagfiles() {
|
|
113
|
+
for (const filename of Object.keys(this.tagfileEntries()))
|
|
114
|
+
if (!(0, util_js_1.isFile)((0, node_path_1.join)(this.path, filename)))
|
|
115
|
+
yield filename;
|
|
116
|
+
}
|
|
117
|
+
compareManifestsWithFs() {
|
|
118
|
+
const files = [...this.payloadFiles()];
|
|
119
|
+
this.normalizedFilesystemNames = (0, util_js_1.buildUnicodeNormalizedLookupDict)(files);
|
|
120
|
+
const onFs = new Set(files.map(util_js_1.normalizeUnicode));
|
|
121
|
+
const inManifest = new Set(Object.keys(this.payloadEntries()).map(util_js_1.normalizeUnicode));
|
|
122
|
+
if (this.verifiesTagFiles)
|
|
123
|
+
for (const f of this.missingOptionalTagfiles())
|
|
124
|
+
inManifest.add((0, util_js_1.normalizeUnicode)(f));
|
|
125
|
+
return [
|
|
126
|
+
[...inManifest].filter(p => !onFs.has(p)).map(p => this.normalizedManifestNames[p]),
|
|
127
|
+
[...onFs].filter(p => !inManifest.has(p)).map(p => this.normalizedFilesystemNames[p]),
|
|
128
|
+
];
|
|
129
|
+
}
|
|
130
|
+
*fetchEntries() {
|
|
131
|
+
const path = (0, node_path_1.join)(this.path, 'fetch.txt');
|
|
132
|
+
if (!(0, util_js_1.isFile)(path))
|
|
133
|
+
return;
|
|
134
|
+
for (const line of (0, util_js_1.decodeText)((0, node_fs_1.readFileSync)(path), this.encoding).split(/\r\n|\n|\r/)) {
|
|
135
|
+
if (!line.trim())
|
|
136
|
+
continue;
|
|
137
|
+
const parts = /^(\S+)\s+(\S+)\s+(.+)$/.exec(line.trim());
|
|
138
|
+
if (!parts)
|
|
139
|
+
throw new errors_js_1.BagError(`Malformed entry in fetch.txt: ${line}`);
|
|
140
|
+
const filename = parts[3];
|
|
141
|
+
(0, util_js_1.assertSafePath)(this.path, filename, `"${path}"`);
|
|
142
|
+
yield [parts[1], parts[2], filename];
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
*filesToBeFetched() { for (const [, , filename] of this.fetchEntries())
|
|
146
|
+
yield filename; }
|
|
147
|
+
compareFetchWithFs() {
|
|
148
|
+
const files = new Set(this.payloadFiles());
|
|
149
|
+
return [...new Set(this.filesToBeFetched())].filter(f => !files.has(f));
|
|
150
|
+
}
|
|
151
|
+
validateFetch() {
|
|
152
|
+
for (const [url] of this.fetchEntries()) {
|
|
153
|
+
// Like urllib.urlparse: permit any scheme with an authority, or file: URLs.
|
|
154
|
+
if (!/^file:/i.test(url) && !/^[a-z][a-z\d+.-]*:\/\/[^/\s?#]+/i.test(url))
|
|
155
|
+
throw new errors_js_1.BagError(`Malformed URL in fetch.txt: ${url}`);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
hasOxum() { return Object.hasOwn(this.info, 'Payload-Oxum'); }
|
|
159
|
+
async validate(options = {}) {
|
|
160
|
+
const concurrency = (0, util_js_1.checkConcurrency)(options.concurrency);
|
|
161
|
+
options.signal?.throwIfAborted();
|
|
162
|
+
if (!(0, util_js_1.isDirectory)((0, node_path_1.join)(this.path, 'data')))
|
|
163
|
+
throw new errors_js_1.BagValidationError(`Expected data directory ${(0, node_path_1.join)(this.path, 'data')} does not exist`);
|
|
164
|
+
if (![...this.manifestFiles()].length)
|
|
165
|
+
throw new errors_js_1.BagValidationError('No manifest files found');
|
|
166
|
+
const declaration = (0, node_path_1.join)(this.path, 'bagit.txt');
|
|
167
|
+
if (!(0, util_js_1.isFile)(declaration))
|
|
168
|
+
throw new errors_js_1.BagValidationError(`Expected ${this.path} to contain "bagit.txt"`);
|
|
169
|
+
if ((0, node_fs_1.readFileSync)(declaration).subarray(0, 3).equals(Buffer.from([0xef, 0xbb, 0xbf])))
|
|
170
|
+
throw new errors_js_1.BagValidationError('bagit.txt must not contain a byte-order mark');
|
|
171
|
+
this.validateFetch();
|
|
172
|
+
if (options.fast && !this.hasOxum())
|
|
173
|
+
throw new errors_js_1.BagValidationError('Fast validation requires bag-info.txt to include Payload-Oxum');
|
|
174
|
+
this.validateOxum();
|
|
175
|
+
if (options.fast)
|
|
176
|
+
return true;
|
|
177
|
+
const [missing, unexpected] = this.compareManifestsWithFs();
|
|
178
|
+
const errors = [...missing.map(p => new errors_js_1.FileMissing(p)), ...unexpected.map(p => new errors_js_1.UnexpectedFile(p))];
|
|
179
|
+
if (errors.length)
|
|
180
|
+
throw new errors_js_1.BagValidationError('Bag is incomplete', errors);
|
|
181
|
+
if (options.completenessOnly || options.completeness_only)
|
|
182
|
+
return true;
|
|
183
|
+
const results = await (0, util_js_1.mapConcurrent)(Object.entries(this.entries), concurrency, async ([filename, expected]) => {
|
|
184
|
+
options.signal?.throwIfAborted();
|
|
185
|
+
const actualName = this.normalizedFilesystemNames[(0, util_js_1.normalizeUnicode)(filename)] ?? filename;
|
|
186
|
+
(0, util_js_1.assertSafePath)(this.path, actualName);
|
|
187
|
+
let hashes;
|
|
188
|
+
try {
|
|
189
|
+
({ hashes } = await (0, util_js_1.hashFile)((0, node_path_1.join)(this.path, actualName), Object.keys(expected), options.signal));
|
|
190
|
+
}
|
|
191
|
+
catch (error) {
|
|
192
|
+
if (!(error instanceof errors_js_1.BagValidationError))
|
|
193
|
+
throw error;
|
|
194
|
+
hashes = Object.fromEntries(Object.keys(expected).map(a => [a, error.message]));
|
|
195
|
+
}
|
|
196
|
+
return Object.entries(expected).filter(([a, h]) => h.toLowerCase() !== hashes[a]).map(([a, h]) => new errors_js_1.ChecksumMismatch(filename, a, h.toLowerCase(), hashes[a]));
|
|
197
|
+
});
|
|
198
|
+
errors.push(...results.flat());
|
|
199
|
+
if (errors.length)
|
|
200
|
+
throw new errors_js_1.BagValidationError('Bag validation failed', errors);
|
|
201
|
+
return true;
|
|
202
|
+
}
|
|
203
|
+
validateOxum() {
|
|
204
|
+
let oxum = this.info['Payload-Oxum'];
|
|
205
|
+
if (oxum === undefined)
|
|
206
|
+
return;
|
|
207
|
+
if (Array.isArray(oxum))
|
|
208
|
+
oxum = oxum[0];
|
|
209
|
+
if (!/^\d+\.\d+$/.test(oxum))
|
|
210
|
+
throw new errors_js_1.BagError(`Malformed Payload-Oxum value: ${oxum}`);
|
|
211
|
+
const [expectedBytes, expectedFiles] = oxum.split('.').map(BigInt);
|
|
212
|
+
const files = [...this.payloadFiles()];
|
|
213
|
+
let bytes = 0n;
|
|
214
|
+
for (const f of files) {
|
|
215
|
+
(0, util_js_1.assertSafePath)(this.path, f);
|
|
216
|
+
bytes += (0, node_fs_1.statSync)((0, node_path_1.join)(this.path, f), { bigint: true }).size;
|
|
217
|
+
}
|
|
218
|
+
if (bytes !== expectedBytes || BigInt(files.length) !== expectedFiles) {
|
|
219
|
+
throw new errors_js_1.BagValidationError(`Payload-Oxum validation failed. Expected ${expectedFiles} files and ${expectedBytes} bytes but found ${files.length} files and ${bytes} bytes`);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
async isValid(options = {}) {
|
|
223
|
+
try {
|
|
224
|
+
await this.validate(options);
|
|
225
|
+
return true;
|
|
226
|
+
}
|
|
227
|
+
catch (error) {
|
|
228
|
+
if (error instanceof errors_js_1.BagError)
|
|
229
|
+
return false;
|
|
230
|
+
throw error;
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
async save(options = {}) {
|
|
234
|
+
(0, util_js_1.checkConcurrency)(options.concurrency);
|
|
235
|
+
options.signal?.throwIfAborted();
|
|
236
|
+
(0, util_js_1.checkPermissions)(this.path, true);
|
|
237
|
+
if (options.manifests) {
|
|
238
|
+
const { bytes, files } = await makeManifests(this.path, { checksums: this.algorithms, concurrency: options.concurrency, signal: options.signal }, this.encoding);
|
|
239
|
+
this.info['Payload-Oxum'] = `${bytes}.${files}`;
|
|
240
|
+
}
|
|
241
|
+
await (0, promises_1.writeFile)((0, node_path_1.join)(this.path, this.tagFileName), (0, util_js_1.encodeText)((0, util_js_1.serializeTagFile)(this.info), this.encoding));
|
|
242
|
+
await makeTagManifests(this.path, this.algorithms, this.encoding, options.signal);
|
|
243
|
+
this.loadManifests();
|
|
244
|
+
}
|
|
245
|
+
// Python-style method aliases ease migration while the primary API uses Node naming conventions.
|
|
246
|
+
manifest_files = this.manifestFiles;
|
|
247
|
+
tagmanifest_files = this.tagmanifestFiles;
|
|
248
|
+
payload_files = this.payloadFiles;
|
|
249
|
+
payload_entries = this.payloadEntries;
|
|
250
|
+
tagfile_entries = this.tagfileEntries;
|
|
251
|
+
missing_optional_tagfiles = this.missingOptionalTagfiles;
|
|
252
|
+
compare_manifests_with_fs = this.compareManifestsWithFs;
|
|
253
|
+
compare_fetch_with_fs = this.compareFetchWithFs;
|
|
254
|
+
fetch_entries = this.fetchEntries;
|
|
255
|
+
files_to_be_fetched = this.filesToBeFetched;
|
|
256
|
+
validate_fetch = this.validateFetch;
|
|
257
|
+
has_oxum = this.hasOxum;
|
|
258
|
+
is_valid = this.isValid;
|
|
259
|
+
}
|
|
260
|
+
exports.Bag = Bag;
|
|
261
|
+
/** Convert a directory in place. Existing contents, including an existing data/, become payload. */
|
|
262
|
+
async function makeBag(directory, options = {}) {
|
|
263
|
+
const root = (0, node_path_1.resolve)(directory);
|
|
264
|
+
const algorithms = (0, util_js_1.algorithmsFor)(options.checksums);
|
|
265
|
+
(0, util_js_1.checkConcurrency)(options.concurrency);
|
|
266
|
+
if (options.encoding && options.encoding.toLowerCase() !== 'utf-8')
|
|
267
|
+
throw new errors_js_1.BagError('New bags must use UTF-8');
|
|
268
|
+
options.signal?.throwIfAborted();
|
|
269
|
+
if (!(0, util_js_1.isDirectory)(root))
|
|
270
|
+
throw new errors_js_1.BagError(`Bag directory ${root} does not exist`);
|
|
271
|
+
const cwdRelative = (0, node_path_1.relative)(root, process.cwd());
|
|
272
|
+
if (cwdRelative && !cwdRelative.startsWith(`..${node_path_1.sep}`) && cwdRelative !== '..' && !(0, node_path_1.isAbsolute)(cwdRelative)) {
|
|
273
|
+
throw new errors_js_1.BagError('Bagging a parent of the current directory is not supported');
|
|
274
|
+
}
|
|
275
|
+
(0, util_js_1.checkPermissions)(root);
|
|
276
|
+
const sourceFiles = [...(0, util_js_1.walkFiles)(root)];
|
|
277
|
+
(0, util_js_1.buildUnicodeNormalizedLookupDict)(sourceFiles);
|
|
278
|
+
for (const f of sourceFiles)
|
|
279
|
+
(0, util_js_1.assertSafePath)(root, f, 'source directory');
|
|
280
|
+
const originalMode = (await (0, promises_1.stat)(root)).mode;
|
|
281
|
+
const children = await (0, promises_1.readdir)(root);
|
|
282
|
+
const staging = await (0, promises_1.mkdtemp)((0, node_path_1.join)(root, '.bagit-'));
|
|
283
|
+
const moved = [];
|
|
284
|
+
try {
|
|
285
|
+
for (const name of children) {
|
|
286
|
+
await (0, promises_1.rename)((0, node_path_1.join)(root, name), (0, node_path_1.join)(staging, name));
|
|
287
|
+
moved.push(name);
|
|
288
|
+
}
|
|
289
|
+
await (0, promises_1.rename)(staging, (0, node_path_1.join)(root, 'data'));
|
|
290
|
+
}
|
|
291
|
+
catch (error) {
|
|
292
|
+
for (const name of moved.reverse())
|
|
293
|
+
await (0, promises_1.rename)((0, node_path_1.join)(staging, name), (0, node_path_1.join)(root, name));
|
|
294
|
+
await (0, promises_1.rm)(staging, { recursive: true, force: true });
|
|
295
|
+
throw error;
|
|
296
|
+
}
|
|
297
|
+
await (0, promises_1.chmod)((0, node_path_1.join)(root, 'data'), originalMode);
|
|
298
|
+
const { bytes, files } = await makeManifests(root, { ...options, checksums: algorithms });
|
|
299
|
+
await (0, promises_1.writeFile)((0, node_path_1.join)(root, 'bagit.txt'), util_js_1.BAG_DECLARATION);
|
|
300
|
+
await (0, promises_1.writeFile)((0, node_path_1.join)(root, 'bag-info.txt'), (0, util_js_1.serializeTagFile)((0, util_js_1.makeBagInfo)(options.bagInfo, bytes, files)));
|
|
301
|
+
await makeTagManifests(root, algorithms, 'utf-8', options.signal);
|
|
302
|
+
return new Bag(root);
|
|
303
|
+
}
|
|
304
|
+
async function makeManifests(root, options = {}, encoding = 'utf-8') {
|
|
305
|
+
const algorithms = (0, util_js_1.algorithmsFor)(options.checksums);
|
|
306
|
+
const filenames = [...(0, util_js_1.walkFiles)((0, node_path_1.join)(root, 'data'), 'data/')];
|
|
307
|
+
(0, util_js_1.buildUnicodeNormalizedLookupDict)(filenames);
|
|
308
|
+
const records = await (0, util_js_1.mapConcurrent)(filenames, options.concurrency ?? 1, async (filename) => {
|
|
309
|
+
(0, util_js_1.assertSafePath)(root, filename);
|
|
310
|
+
return { filename, ...await (0, util_js_1.hashFile)((0, node_path_1.join)(root, filename), algorithms, options.signal) };
|
|
311
|
+
});
|
|
312
|
+
for (const a of algorithms) {
|
|
313
|
+
const text = records.map(r => `${r.hashes[a]} ${(0, util_js_1.encodeFilename)(r.filename)}\n`).join('');
|
|
314
|
+
await (0, promises_1.writeFile)((0, node_path_1.join)(root, `manifest-${a}.txt`), (0, util_js_1.encodeText)(text, encoding));
|
|
315
|
+
}
|
|
316
|
+
return { bytes: records.reduce((sum, r) => sum + r.bytes, 0n), files: records.length };
|
|
317
|
+
}
|
|
318
|
+
async function makeTagManifests(root, algorithms = util_js_1.DEFAULT_CHECKSUMS, encoding = 'utf-8', signal) {
|
|
319
|
+
const tagFiles = [...(0, util_js_1.walkFiles)(root)].filter(f => !f.startsWith('data/') && !(0, node_path_1.basename)(f).startsWith('tagmanifest-'));
|
|
320
|
+
const records = [];
|
|
321
|
+
for (const filename of tagFiles) {
|
|
322
|
+
(0, util_js_1.assertSafePath)(root, filename);
|
|
323
|
+
records.push({ filename, ...await (0, util_js_1.hashFile)((0, node_path_1.join)(root, filename), algorithms, signal) });
|
|
324
|
+
}
|
|
325
|
+
for (const a of (0, util_js_1.algorithmsFor)(algorithms)) {
|
|
326
|
+
await (0, promises_1.writeFile)((0, node_path_1.join)(root, `tagmanifest-${a}.txt`), (0, util_js_1.encodeText)(records.map(r => `${r.hashes[a]} ${(0, util_js_1.encodeFilename)(r.filename)}\n`).join(''), encoding));
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
//# sourceMappingURL=bag.js.map
|