@tryghost/mg-fs-utils 0.26.7 → 0.27.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/README.md CHANGED
@@ -19,6 +19,48 @@ CACHE_PATH=/path/to/cache
19
19
  ```
20
20
 
21
21
 
22
+ ### Streaming readers
23
+
24
+ `zip.entries()`, `csv.streamRows()` and `json.streamArray()` read large exports one item at a time, so an archive, CSV or JSON file is never held in memory as a whole.
25
+
26
+ ```js
27
+ import fsUtils from '@tryghost/mg-fs-utils';
28
+
29
+ for await (const entry of fsUtils.zip.entries('/path/to/export.zip', {filter: entry => !entry.isDirectory})) {
30
+ if (entry.name === 'posts.csv') {
31
+ for await (const row of fsUtils.csv.streamRows(await entry.stream())) {
32
+ // One parsed row at a time
33
+ }
34
+ } else {
35
+ const contents = await entry.read(); // A Buffer of this entry only
36
+ }
37
+ }
38
+ ```
39
+
40
+ - `zip.entries(zipPath, {filter})` is an async generator of `{name, path, isDirectory, size, read(), stream()}`. Names are normalised much as `zip.read()` does: `__MACOSX` and `.DS_Store` entries are skipped, a top-level directory that holds every entry is removed from names, and a zip that holds only another zip is read as that inner zip. `path` is the unmodified name in the archive. `filter(entry)` returning false skips an entry. Call `read()` or `stream()` before the iteration finishes; the archive is closed when it does.
41
+ - `csv.streamRows(pathOrStream, options)` is an async generator of parsed rows from a file path or a readable stream. Options go to `csv-parse` and default to those of `csv.parseCSV()`. The input stream is destroyed if the caller stops early.
42
+
43
+ ```js
44
+ for await (const author of fsUtils.json.streamArray('/path/to/authors.json', {path: ['data', 'authors']})) {
45
+ // One parsed item of {"data": {"authors": [...]}} at a time
46
+ }
47
+ ```
48
+
49
+ - `json.streamArray(pathOrStream, {path})` is an async generator of the items of one array in a JSON file or readable stream, each parsed with `JSON.parse()`. `path` lists the keys leading to the array: the default `[]` reads a top-level array. Only the item being read is held; other values are skipped. The rest of the input is still read after the array, so malformed JSON anywhere rejects with a `SyntaxError` giving its position, as does a path that does not lead to an array. The first of repeated keys is used. The input stream is destroyed if the caller stops early.
50
+
51
+
52
+ ### Input files
53
+
54
+ `listInputFiles(path, globPattern)` resolves a source's input path to the files to read, for sources that accept either one file or a directory of them.
55
+
56
+ ```js
57
+ const files = await fsUtils.listInputFiles('/path/to/exports', '*.zip');
58
+ // [{path: '/path/to/exports/a.zip', name: 'a.zip'}, {path: '/path/to/exports/b.zip', name: 'b.zip'}]
59
+ ```
60
+
61
+ A file gives itself, named by its base name. A directory gives the files matching the [fast-glob](https://github.com/mrmlnc/fast-glob) pattern, sorted by path, named by their path relative to the directory with `/` separators. Hidden files are left out, a directory with no matches gives an empty list, and a missing path rejects with `ENOENT`.
62
+
63
+
22
64
  ## Develop
23
65
 
24
66
  This is a mono repository, managed with [Nx](https://nx.dev/) and pnpm workspaces.
package/index.js CHANGED
@@ -1,8 +1,10 @@
1
1
  import FileCache from './lib/FileCache.js';
2
2
  import zip from './lib/zip.js';
3
3
  import {readZipEntries} from './lib/read-zip.js';
4
+ import {listInputFiles} from './lib/input.js';
4
5
  import ghostJSON from './lib/ghost-json.js';
5
6
  import csv from './lib/csv.js';
7
+ import json from './lib/json.js';
6
8
  import * as utils from './lib/utils.js';
7
9
 
8
10
  export default {
@@ -10,6 +12,8 @@ export default {
10
12
  zip,
11
13
  ghostJSON,
12
14
  csv,
15
+ json,
13
16
  readZipEntries,
17
+ listInputFiles,
14
18
  utils
15
19
  };
package/lib/csv.js CHANGED
@@ -2,6 +2,7 @@ import {join} from 'path';
2
2
  import {parse} from 'csv-parse';
3
3
  import {parse as parseSync} from 'csv-parse/sync';
4
4
  import {createReadStream} from 'node:fs';
5
+ import {pipeline} from 'node:stream';
5
6
  import {outputFile, ensureDirSync} from 'fs-extra/esm';
6
7
  import errors from '@tryghost/errors';
7
8
 
@@ -49,6 +50,23 @@ const parseString = (
49
50
  return data;
50
51
  };
51
52
 
53
+ /**
54
+ * Parse a CSV file or readable stream one row at a time
55
+ * @param {String|import('node:stream').Readable} input - path to a CSV file, or a readable stream of CSV data
56
+ * @param {Object} options - optional options to pass to `csv-parse`
57
+ */
58
+ async function* streamRows(
59
+ input,
60
+ options = {skip_lines_with_error: true, columns: true, skip_empty_lines: true, trim: true}
61
+ ) {
62
+ const source = typeof input === 'string' ? createReadStream(input) : input;
63
+ // pipeline() destroys both streams when either fails or the caller stops early; errors surface while iterating.
64
+ const parser = pipeline(source, parse(options), () => {});
65
+ for await (const row of parser) {
66
+ yield row;
67
+ }
68
+ }
69
+
52
70
  /**
53
71
  * Convert a JSON file into a CSV format
54
72
  * @param {Array} data - the data to format
@@ -133,6 +151,7 @@ const hasKeys = async ({filePath, required = [], blocked = []}) => {
133
151
  export default {
134
152
  parseCSV,
135
153
  parseString,
154
+ streamRows,
136
155
  jsonToCSV,
137
156
  writeCSV,
138
157
  hasKeys
package/lib/input.js ADDED
@@ -0,0 +1,26 @@
1
+ import {stat} from 'node:fs/promises';
2
+ import {basename, relative, resolve} from 'node:path';
3
+ import fg from 'fast-glob';
4
+
5
+ /**
6
+ * Resolve an input path to the files a source reads: the file itself, or the files under a directory that match
7
+ * `globPattern`, sorted by path so every read sees them in the same order. Hidden files are left out.
8
+ *
9
+ * Each file is `{path, name}`: `path` is absolute, and `name` is the file's base name, or for a directory its path
10
+ * relative to that directory with `/` separators. A directory with no matching files gives an empty list.
11
+ *
12
+ * @param {String} input - path to a file or a directory
13
+ * @param {String} globPattern - fast-glob pattern for the files to read from a directory, such as `*.zip`
14
+ * @returns {Promise<Array<{path: String, name: String}>>}
15
+ */
16
+ const listInputFiles = async (input, globPattern) => {
17
+ const path = resolve(input);
18
+ if (!(await stat(path)).isDirectory()) {
19
+ return [{path, name: basename(path)}];
20
+ }
21
+ const paths = await fg(globPattern, {cwd: path, absolute: true, dot: false});
22
+ paths.sort();
23
+ return paths.map(file => ({path: file, name: relative(path, file).split('\\').join('/')}));
24
+ };
25
+
26
+ export {listInputFiles};
package/lib/json.js ADDED
@@ -0,0 +1,262 @@
1
+ import {createReadStream} from 'node:fs';
2
+ import {StringDecoder} from 'node:string_decoder';
3
+
4
+ // A byte order mark between tokens is skipped like whitespace.
5
+ const WHITESPACE = new Set([' ', '\t', '\n', '\r', '']);
6
+ const PRIMITIVE_END = new Set([',', ']', '}', ' ', '\t', '\n', '\r']);
7
+ const CLOSER = {'{': '}', '[': ']'};
8
+
9
+ /** Pulls decoded text from a stream and scans JSON values out of it, holding only the text not yet consumed. */
10
+ class Scanner {
11
+ #chunks;
12
+ #decoder = new StringDecoder('utf8');
13
+ // Characters dropped from the front of `text`, so errors can give positions in the whole input.
14
+ #dropped = 0;
15
+ text = '';
16
+ pos = 0;
17
+
18
+ constructor(source) {
19
+ this.#chunks = source[Symbol.asyncIterator]();
20
+ }
21
+
22
+ /** Append the next chunk to `text`. False once the input has ended. */
23
+ async #fill() {
24
+ const {value, done} = await this.#chunks.next();
25
+ if (done) {
26
+ return false;
27
+ }
28
+ this.text += typeof value === 'string' ? value : this.#decoder.write(value);
29
+ return true;
30
+ }
31
+
32
+ /** Drop the first `count` characters of `text`, which have been consumed. */
33
+ #drop(count) {
34
+ this.text = this.text.slice(count);
35
+ this.pos -= count;
36
+ this.#dropped += count;
37
+ }
38
+
39
+ error(message) {
40
+ return new SyntaxError(`${message} at position ${this.#dropped + this.pos}`);
41
+ }
42
+
43
+ unexpected(found) {
44
+ return this.error(found === null ? 'Unexpected end of JSON' : `Unexpected '${found}'`);
45
+ }
46
+
47
+ /** Skip whitespace and return the next character without consuming it, or null at the end of the input. */
48
+ async peek() {
49
+ for (;;) {
50
+ while (this.pos < this.text.length) {
51
+ if (!WHITESPACE.has(this.text[this.pos])) {
52
+ return this.text[this.pos];
53
+ }
54
+ this.pos += 1;
55
+ }
56
+ this.#drop(this.pos);
57
+ if (!(await this.#fill())) {
58
+ return null;
59
+ }
60
+ }
61
+ }
62
+
63
+ /** Consume `char`, which must be the next non-whitespace character. */
64
+ async expect(char) {
65
+ const found = await this.peek();
66
+ if (found !== char) {
67
+ throw this.unexpected(found);
68
+ }
69
+ this.pos += 1;
70
+ }
71
+
72
+ /**
73
+ * Consume the value starting at the next non-whitespace character. Returns its text when `keep` is true;
74
+ * otherwise the value is skipped without being held in memory. Strings, objects and arrays are scanned for their
75
+ * end, so their contents are checked when the caller parses the text; numbers, booleans and null are checked here.
76
+ */
77
+ async value(keep) {
78
+ const first = await this.peek();
79
+ if (first === null || first === ',' || first === ']' || first === '}') {
80
+ throw this.unexpected(first);
81
+ }
82
+ let start = this.pos;
83
+ let i = this.pos;
84
+ // Keep the value's text (or drop what has been scanned, when skipping) and read more input.
85
+ const refill = async retain => {
86
+ this.pos = i;
87
+ this.#drop(retain ? start : i);
88
+ i = this.pos;
89
+ start = 0;
90
+ return this.#fill();
91
+ };
92
+
93
+ if (first !== '{' && first !== '[' && first !== '"') {
94
+ // A number, true, false or null runs to the next delimiter or the end of the input. Its text is short, and
95
+ // is always kept so it can be checked whole.
96
+ for (;;) {
97
+ if (i === this.text.length) {
98
+ if (!(await refill(true))) {
99
+ break;
100
+ }
101
+ } else if (PRIMITIVE_END.has(this.text[i])) {
102
+ break;
103
+ } else {
104
+ i += 1;
105
+ }
106
+ }
107
+ const token = this.text.slice(start, i);
108
+ try {
109
+ JSON.parse(token);
110
+ } catch {
111
+ this.pos = start;
112
+ throw this.error(`Invalid JSON value '${token}'`);
113
+ }
114
+ this.pos = i;
115
+ return keep ? token : undefined;
116
+ }
117
+
118
+ const closers = [];
119
+ let inString = false;
120
+ let escaped = false;
121
+ for (;;) {
122
+ if (i === this.text.length) {
123
+ if (!(await refill(keep))) {
124
+ throw this.unexpected(null);
125
+ }
126
+ continue;
127
+ }
128
+ const char = this.text[i];
129
+ i += 1;
130
+ if (inString) {
131
+ if (escaped) {
132
+ escaped = false;
133
+ } else if (char === '\\') {
134
+ escaped = true;
135
+ } else if (char === '"') {
136
+ inString = false;
137
+ if (!closers.length) {
138
+ break;
139
+ }
140
+ }
141
+ } else if (char === '"') {
142
+ inString = true;
143
+ } else if (char === '{' || char === '[') {
144
+ closers.push(CLOSER[char]);
145
+ } else if (char === '}' || char === ']') {
146
+ if (closers.pop() !== char) {
147
+ this.pos = i - 1;
148
+ throw this.unexpected(char);
149
+ }
150
+ if (!closers.length) {
151
+ break;
152
+ }
153
+ }
154
+ }
155
+ this.pos = i;
156
+ return keep ? this.text.slice(start, i) : undefined;
157
+ }
158
+ }
159
+
160
+ const where = (path, depth) => (depth ? `"${path.slice(0, depth).join('.')}"` : 'the top level');
161
+
162
+ /** Yield the items of the array reached by following `path` from the current value. */
163
+ async function* arrayAt(scanner, path, depth) {
164
+ const found = await scanner.peek();
165
+ if (depth < path.length) {
166
+ if (found !== '{') {
167
+ throw scanner.error(`Expected an object at ${where(path, depth)}`);
168
+ }
169
+ scanner.pos += 1;
170
+ let matched = false;
171
+ let next = await scanner.peek();
172
+ while (next !== '}') {
173
+ if (next !== '"') {
174
+ throw scanner.unexpected(next);
175
+ }
176
+ const key = JSON.parse(await scanner.value(true));
177
+ await scanner.expect(':');
178
+ if (!matched && key === path[depth]) {
179
+ matched = true;
180
+ yield* arrayAt(scanner, path, depth + 1);
181
+ } else {
182
+ await scanner.value(false);
183
+ }
184
+ next = await scanner.peek();
185
+ if (next === ',') {
186
+ scanner.pos += 1;
187
+ next = await scanner.peek();
188
+ if (next === '}') {
189
+ throw scanner.unexpected(next);
190
+ }
191
+ } else if (next !== '}') {
192
+ throw scanner.unexpected(next);
193
+ }
194
+ }
195
+ scanner.pos += 1;
196
+ if (!matched) {
197
+ throw scanner.error(`No "${path[depth]}" key in the object at ${where(path, depth)}`);
198
+ }
199
+ return;
200
+ }
201
+
202
+ if (found !== '[') {
203
+ throw scanner.error(`Expected an array at ${where(path, depth)}`);
204
+ }
205
+ scanner.pos += 1;
206
+ if ((await scanner.peek()) === ']') {
207
+ scanner.pos += 1;
208
+ return;
209
+ }
210
+ for (let index = 0, next = ','; next === ','; index += 1) {
211
+ const text = await scanner.value(true);
212
+ let item;
213
+ try {
214
+ item = JSON.parse(text);
215
+ } catch (error) {
216
+ throw new SyntaxError(
217
+ `Invalid JSON in item ${index} of the array at ${where(path, depth)}: ${error.message}`,
218
+ {
219
+ cause: error
220
+ }
221
+ );
222
+ }
223
+ yield item;
224
+ next = await scanner.peek();
225
+ if (next !== ',' && next !== ']') {
226
+ throw scanner.unexpected(next);
227
+ }
228
+ scanner.pos += 1;
229
+ }
230
+ }
231
+
232
+ /**
233
+ * Read the items of one array in a JSON file or readable stream, one at a time, so a large export is never held in
234
+ * memory as a whole. Only the item being read is kept; each is parsed with `JSON.parse()`.
235
+ *
236
+ * `path` names the keys that lead from the top-level value to the array: `[]` (the default) reads a top-level array,
237
+ * and `['data', 'authors']` reads the array at `data.authors`. Other values are skipped without being held. The rest of
238
+ * the input is still read after the array, so malformed JSON anywhere in it rejects. The input is destroyed when the
239
+ * caller stops early or reading fails.
240
+ *
241
+ * @param {String|import('node:stream').Readable} input - path to a JSON file, or a readable stream of JSON text
242
+ * @param {Object} [options]
243
+ * @param {String[]} [options.path] - keys leading to the array; defaults to the top-level value
244
+ * @returns {AsyncGenerator<any>}
245
+ */
246
+ async function* streamArray(input, {path = []} = {}) {
247
+ const source = typeof input === 'string' ? createReadStream(input) : input;
248
+ try {
249
+ const scanner = new Scanner(source);
250
+ yield* arrayAt(scanner, path, 0);
251
+ const rest = await scanner.peek();
252
+ if (rest !== null) {
253
+ throw scanner.unexpected(rest);
254
+ }
255
+ } finally {
256
+ source.destroy();
257
+ }
258
+ }
259
+
260
+ export default {
261
+ streamArray
262
+ };
package/lib/zip.js CHANGED
@@ -1,5 +1,10 @@
1
1
  import {join} from 'node:path';
2
+ import {tmpdir} from 'node:os';
3
+ import {createWriteStream} from 'node:fs';
4
+ import {mkdtemp, rm} from 'node:fs/promises';
5
+ import {pipeline} from 'node:stream/promises';
2
6
  import AdmZip from 'adm-zip';
7
+ import yauzl from 'yauzl';
3
8
  import {ensureDirSync, remove, ensureFileSync} from 'fs-extra';
4
9
  import zip from '@tryghost/zip';
5
10
  import errors from '@tryghost/errors';
@@ -10,6 +15,114 @@ _private.openZipForRead = zipPath => {
10
15
  return AdmZip(zipPath);
11
16
  };
12
17
 
18
+ const isJunk = name => /^__MACOSX(?:\/|$)/.test(name) || /(?:^|\/)\.DS_Store$/.test(name);
19
+
20
+ const openZip = async zipPath => {
21
+ try {
22
+ return await yauzl.openPromise(zipPath, {autoClose: false});
23
+ } catch (error) {
24
+ throw new errors.InternalServerError({message: `Unable to read zip file ${zipPath}: ${error}`});
25
+ }
26
+ };
27
+
28
+ /**
29
+ * Scan the central directory (names only, no file data) for the layout `read()` normalises:
30
+ * a single top-level directory to strip, or a single nested zip to read instead.
31
+ */
32
+ const scanLayout = async (zipfile, unwrap) => {
33
+ let count = 0;
34
+ let only = null;
35
+ let prefix;
36
+ for await (const entry of zipfile.eachEntry()) {
37
+ const name = entry.fileName;
38
+ if (isJunk(name)) {
39
+ continue;
40
+ }
41
+ count += 1;
42
+ only = count === 1 ? entry : null;
43
+ const slash = name.indexOf('/');
44
+ const directory = slash > 0 ? name.slice(0, slash + 1) : null;
45
+ prefix = prefix === undefined || prefix === directory ? directory : null;
46
+ }
47
+ if (unwrap && only && /\.zip$/i.test(only.fileName)) {
48
+ return {nested: only};
49
+ }
50
+ return {prefix: prefix ?? ''};
51
+ };
52
+
53
+ async function* readEntries(zipPath, filter, unwrap) {
54
+ let layout;
55
+ const scan = await openZip(zipPath);
56
+ let nestedDir;
57
+ try {
58
+ layout = await scanLayout(scan, unwrap);
59
+ if (layout.nested) {
60
+ // A zip holding only another zip is read as that inner zip, extracted to a temporary file.
61
+ nestedDir = await mkdtemp(join(tmpdir(), 'mg-fs-utils-zip-'));
62
+ await pipeline(
63
+ await scan.openReadStreamPromise(layout.nested),
64
+ createWriteStream(join(nestedDir, 'nested.zip'))
65
+ );
66
+ }
67
+ } finally {
68
+ scan.close();
69
+ }
70
+ if (nestedDir) {
71
+ try {
72
+ yield* readEntries(join(nestedDir, 'nested.zip'), filter, false);
73
+ } finally {
74
+ await rm(nestedDir, {recursive: true, force: true});
75
+ }
76
+ return;
77
+ }
78
+
79
+ const zipfile = await openZip(zipPath);
80
+ try {
81
+ for await (const raw of zipfile.eachEntry()) {
82
+ const name = raw.fileName.slice(layout.prefix.length);
83
+ if (isJunk(raw.fileName) || !name) {
84
+ continue;
85
+ }
86
+ const stream = () => zipfile.openReadStreamPromise(raw);
87
+ const entry = {
88
+ name,
89
+ path: raw.fileName,
90
+ isDirectory: raw.fileName.endsWith('/'),
91
+ size: raw.uncompressedSize,
92
+ stream,
93
+ read: async () => {
94
+ const chunks = [];
95
+ for await (const chunk of await stream()) {
96
+ chunks.push(chunk);
97
+ }
98
+ return Buffer.concat(chunks);
99
+ }
100
+ };
101
+ if (!filter || filter(entry)) {
102
+ yield entry;
103
+ }
104
+ }
105
+ } finally {
106
+ zipfile.close();
107
+ }
108
+ }
109
+
110
+ /**
111
+ * Stream the entries of a zip one at a time, without expanding the archive in memory.
112
+ *
113
+ * Names are normalised much as `read()` does: `__MACOSX` and `.DS_Store` entries are skipped, a top-level
114
+ * directory that holds every entry is removed from names (whether or not the archive lists the directory itself),
115
+ * and a zip that holds only another zip is read as that inner zip.
116
+ * Each entry is `{name, path, isDirectory, size, read(), stream()}`, where `path` is the unmodified name in the
117
+ * archive, `read()` resolves to the entry's contents as a Buffer and `stream()` to a Readable of them. Call
118
+ * `read()` or `stream()` before the iteration finishes; the archive is closed when it does.
119
+ *
120
+ * @param {String} zipPath - path to the zip file
121
+ * @param {Object} [options]
122
+ * @param {Function} [options.filter] - called with each entry; return false to skip it
123
+ */
124
+ const entries = (zipPath, {filter} = {}) => readEntries(zipPath, filter, true);
125
+
13
126
  /**
14
127
  * Read a Zip File
15
128
  * - Flattens the structure if there's one top-level directory, so we only get the files inside
@@ -71,6 +184,7 @@ const deleteFile = async fileToDelete => {
71
184
 
72
185
  export default {
73
186
  read,
187
+ entries,
74
188
  write,
75
189
  _private,
76
190
  deleteFile
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tryghost/mg-fs-utils",
3
- "version": "0.26.7",
3
+ "version": "0.27.0-0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/TryGhost/migrate.git",
@@ -21,16 +21,18 @@
21
21
  "c8": "12.0.0"
22
22
  },
23
23
  "dependencies": {
24
- "@tryghost/errors": "3.4.2",
24
+ "@tryghost/errors": "3.4.6",
25
25
  "@tryghost/image-transform": "1.4.19",
26
- "@tryghost/string": "0.3.7",
27
- "@tryghost/zip": "3.5.16",
26
+ "@tryghost/string": "0.3.8",
27
+ "@tryghost/zip": "4.0.1",
28
28
  "adm-zip": "0.6.1",
29
29
  "csv-parse": "7.0.3",
30
- "dotenv": "18.0.6",
30
+ "dotenv": "18.0.9",
31
+ "fast-glob": "3.3.3",
31
32
  "fs-extra": "11.4.1",
32
33
  "sharp": "0.35.5",
33
- "transliteration": "2.6.1"
34
+ "transliteration": "2.7.0",
35
+ "yauzl": "3.4.0"
34
36
  },
35
37
  "scripts": {
36
38
  "dev": "echo \"Implement me!\"",