@tryghost/mg-context 0.11.9 → 0.12.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 +75 -832
- package/build/index.d.ts +13 -4
- package/build/index.js +7 -2
- package/build/index.js.map +1 -1
- package/build/lib/AuthorContext.d.ts +3 -3
- package/build/lib/AuthorContext.js +32 -34
- package/build/lib/AuthorContext.js.map +1 -1
- package/build/lib/MappingState.d.ts +30 -0
- package/build/lib/MappingState.js +81 -0
- package/build/lib/MappingState.js.map +1 -0
- package/build/lib/MigrateBase.js +2 -2
- package/build/lib/MigrateBase.js.map +1 -1
- package/build/lib/MigrateContext.d.ts +148 -36
- package/build/lib/MigrateContext.js +642 -324
- package/build/lib/MigrateContext.js.map +1 -1
- package/build/lib/PostContext.d.ts +72 -16
- package/build/lib/PostContext.js +191 -123
- package/build/lib/PostContext.js.map +1 -1
- package/build/lib/SourceRecords.d.ts +98 -0
- package/build/lib/SourceRecords.js +406 -0
- package/build/lib/SourceRecords.js.map +1 -0
- package/build/lib/TagContext.d.ts +1 -1
- package/build/lib/TagContext.js +35 -37
- package/build/lib/TagContext.js.map +1 -1
- package/build/lib/database.d.ts +47 -11
- package/build/lib/database.js +189 -24
- package/build/lib/database.js.map +1 -1
- package/build/lib/db-helpers.d.ts +1 -5
- package/build/lib/db-helpers.js +7 -37
- package/build/lib/db-helpers.js.map +1 -1
- package/build/lib/export-filename.d.ts +1 -0
- package/build/lib/export-filename.js +11 -0
- package/build/lib/export-filename.js.map +1 -0
- package/build/lib/ghost-csv.d.ts +10 -0
- package/build/lib/ghost-csv.js +55 -0
- package/build/lib/ghost-csv.js.map +1 -0
- package/build/lib/ghost-json.d.ts +4 -0
- package/build/lib/ghost-json.js +108 -0
- package/build/lib/ghost-json.js.map +1 -0
- package/build/lib/ghost-schema.d.ts +58 -0
- package/build/lib/ghost-schema.js +61 -0
- package/build/lib/ghost-schema.js.map +1 -0
- package/build/lib/json.d.ts +8 -0
- package/build/lib/json.js +40 -0
- package/build/lib/json.js.map +1 -0
- package/build/lib/mapping.d.ts +18 -0
- package/build/lib/mapping.js +23 -0
- package/build/lib/mapping.js.map +1 -0
- package/build/lib/migration-report.d.ts +3 -0
- package/build/lib/migration-report.js +41 -0
- package/build/lib/migration-report.js.map +1 -0
- package/build/lib/source-schema.d.ts +1 -0
- package/build/lib/source-schema.js +44 -0
- package/build/lib/source-schema.js.map +1 -0
- package/build/test/fixtures/mg-context-v2.d.ts +5 -0
- package/build/test/fixtures/mg-context-v2.js +58 -0
- package/build/test/fixtures/mg-context-v2.js.map +1 -0
- package/build/test/ghost-csv.test.d.ts +1 -0
- package/build/test/ghost-csv.test.js +333 -0
- package/build/test/ghost-csv.test.js.map +1 -0
- package/build/test/ghost-schema.test.d.ts +1 -0
- package/build/test/ghost-schema.test.js +38 -0
- package/build/test/ghost-schema.test.js.map +1 -0
- package/build/test/mapping.test.d.ts +1 -0
- package/build/test/mapping.test.js +231 -0
- package/build/test/mapping.test.js.map +1 -0
- package/build/test/migrate-base.test.js +0 -6
- package/build/test/migrate-base.test.js.map +1 -1
- package/build/test/migrate-context.test.js +1094 -250
- package/build/test/migrate-context.test.js.map +1 -1
- package/build/test/package-exports.test.d.ts +1 -0
- package/build/test/package-exports.test.js +50 -0
- package/build/test/package-exports.test.js.map +1 -0
- package/build/test/post-context.test.js +36 -151
- package/build/test/post-context.test.js.map +1 -1
- package/build/test/source-records.test.d.ts +1 -0
- package/build/test/source-records.test.js +625 -0
- package/build/test/source-records.test.js.map +1 -0
- package/build/test/stream-export.test.d.ts +1 -0
- package/build/test/stream-export.test.js +401 -0
- package/build/test/stream-export.test.js.map +1 -0
- package/package.json +13 -10
|
@@ -1,36 +1,102 @@
|
|
|
1
|
-
import { stat, mkdir,
|
|
2
|
-
import {
|
|
1
|
+
import { stat, mkdir, mkdtemp, rename, rm, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { createWriteStream } from 'node:fs';
|
|
3
|
+
import { randomUUID } from 'node:crypto';
|
|
4
|
+
import { tmpdir } from 'node:os';
|
|
5
|
+
import { dirname, join, resolve } from 'node:path';
|
|
3
6
|
import { EventEmitter } from 'node:events';
|
|
7
|
+
import { Readable } from 'node:stream';
|
|
8
|
+
import { pipeline } from 'node:stream/promises';
|
|
4
9
|
import errors from '@tryghost/errors';
|
|
5
|
-
import { htmlToLexical } from '@tryghost/mg-html-lexical';
|
|
6
10
|
import MigrateBase from './MigrateBase.js';
|
|
7
|
-
import
|
|
11
|
+
import SourceRecords from './SourceRecords.js';
|
|
12
|
+
import { RecordDataError, WARNING_EVENT_TYPES } from './mapping.js';
|
|
13
|
+
import { writeGhostJson } from './ghost-json.js';
|
|
14
|
+
import { writeMigrationReport } from './migration-report.js';
|
|
15
|
+
import { exportBaseFilename } from './export-filename.js';
|
|
16
|
+
import { serializeMetadata } from './json.js';
|
|
17
|
+
import PostContext, { normalizeTitle } from './PostContext.js';
|
|
8
18
|
import TagContext from './TagContext.js';
|
|
9
19
|
import AuthorContext from './AuthorContext.js';
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
20
|
+
import { GHOST_CSV_COLUMNS, csvLine, csvPostLine } from './ghost-csv.js';
|
|
21
|
+
import { createDatabase, assertMappedWrite, flushDatabaseEvents, recordSanitizedFields } from './database.js';
|
|
22
|
+
import { withTransaction, buildDateWhere, countWhere, findPostsWhere } from './db-helpers.js';
|
|
23
|
+
function hasPostFilter(filter) {
|
|
24
|
+
return Boolean(filter?.tag || filter?.author || filter?.createdAt || filter?.publishedAt);
|
|
25
|
+
}
|
|
26
|
+
export function buildPostWhere(filter) {
|
|
27
|
+
const dateWhere = buildDateWhere(filter);
|
|
28
|
+
const conditions = dateWhere.sql ? [dateWhere.sql] : [];
|
|
29
|
+
const params = [...dateWhere.params];
|
|
30
|
+
if (filter?.tag) {
|
|
31
|
+
const column = filter.tag.slug ? 'slug' : filter.tag.name ? 'name' : null;
|
|
32
|
+
if (column) {
|
|
33
|
+
conditions.push(`EXISTS (SELECT 1 FROM PostTags pt JOIN Tags t ON t.id = pt.tag_id WHERE pt.post_id = Posts.id AND t.${column} = ?)`);
|
|
34
|
+
params.push(filter.tag[column]);
|
|
35
|
+
}
|
|
36
|
+
else {
|
|
37
|
+
conditions.push('1 = 0');
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
if (filter?.author) {
|
|
41
|
+
const column = filter.author.slug ? 'slug' : filter.author.name ? 'name' : filter.author.email ? 'email' : null;
|
|
42
|
+
if (column) {
|
|
43
|
+
conditions.push(`EXISTS (SELECT 1 FROM PostAuthors pa JOIN Authors a ON a.id = pa.author_id WHERE pa.post_id = Posts.id AND a.${column} = ?)`);
|
|
44
|
+
params.push(filter.author[column]);
|
|
45
|
+
}
|
|
46
|
+
else {
|
|
47
|
+
conditions.push('1 = 0');
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
return { sql: conditions.length ? `WHERE ${conditions.join(' AND ')}` : '', params };
|
|
51
|
+
}
|
|
12
52
|
export default class MigrateContext extends MigrateBase {
|
|
13
|
-
#contentFormat;
|
|
14
53
|
#dbPath;
|
|
15
|
-
#
|
|
54
|
+
#storage;
|
|
55
|
+
#temporaryDirectory = null;
|
|
56
|
+
#sources = null;
|
|
57
|
+
#resetContent;
|
|
16
58
|
#emitEvents;
|
|
17
59
|
#warnOnLookupKeyDuplicate;
|
|
60
|
+
#onDuplicate;
|
|
18
61
|
#db = null;
|
|
19
|
-
#slugsDeduped = false;
|
|
20
|
-
#duplicateSlugs = [];
|
|
21
62
|
#emitter = new EventEmitter();
|
|
22
|
-
constructor({
|
|
63
|
+
constructor({ dbPath, storage, resetContent = false, ephemeral, emitEvents = true, warnOnLookupKeyDuplicate = false, onDuplicate, ...unsupportedOptions } = {}) {
|
|
23
64
|
super();
|
|
24
|
-
this.#contentFormat = normalizeContentFormat(contentFormat);
|
|
25
65
|
this.#emitEvents = emitEvents;
|
|
26
66
|
this.#warnOnLookupKeyDuplicate = warnOnLookupKeyDuplicate;
|
|
67
|
+
this.#onDuplicate = onDuplicate;
|
|
68
|
+
this.#resetContent = resetContent;
|
|
69
|
+
if (Object.hasOwn(unsupportedOptions, 'contentIdentity')) {
|
|
70
|
+
throw new errors.BadRequestError({
|
|
71
|
+
message: 'contentIdentity was removed; callers own ingestion and reuse policy.'
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
if (Object.hasOwn(unsupportedOptions, 'mode')) {
|
|
75
|
+
throw new errors.BadRequestError({ message: 'Use resetContent: true instead of the removed mode option.' });
|
|
76
|
+
}
|
|
77
|
+
if (Object.hasOwn(unsupportedOptions, 'rereadSource')) {
|
|
78
|
+
throw new errors.BadRequestError({ message: 'Use resetContent instead of rereadSource.' });
|
|
79
|
+
}
|
|
80
|
+
if (dbPath !== undefined && (typeof dbPath !== 'string' || !dbPath.trim())) {
|
|
81
|
+
throw new errors.BadRequestError({ message: 'dbPath must be a non-empty path.' });
|
|
82
|
+
}
|
|
83
|
+
if (typeof resetContent !== 'boolean') {
|
|
84
|
+
throw new errors.BadRequestError({ message: 'resetContent must be a boolean.' });
|
|
85
|
+
}
|
|
86
|
+
if (dbPath && storage) {
|
|
87
|
+
throw new errors.BadRequestError({ message: 'Pass either dbPath or storage, not both.' });
|
|
88
|
+
}
|
|
27
89
|
if (dbPath) {
|
|
28
90
|
this.#dbPath = dbPath;
|
|
29
|
-
this.#
|
|
91
|
+
this.#storage = 'persistent';
|
|
92
|
+
}
|
|
93
|
+
else if (storage === 'memory' || ephemeral === true) {
|
|
94
|
+
this.#dbPath = null;
|
|
95
|
+
this.#storage = 'memory';
|
|
30
96
|
}
|
|
31
97
|
else {
|
|
32
|
-
this.#dbPath =
|
|
33
|
-
this.#
|
|
98
|
+
this.#dbPath = null;
|
|
99
|
+
this.#storage = 'temporary';
|
|
34
100
|
}
|
|
35
101
|
}
|
|
36
102
|
get db() {
|
|
@@ -45,52 +111,292 @@ export default class MigrateContext extends MigrateBase {
|
|
|
45
111
|
message: 'MigrateContext is already initialized. Call close() before reinitializing.'
|
|
46
112
|
});
|
|
47
113
|
}
|
|
48
|
-
|
|
49
|
-
this.#
|
|
114
|
+
let databasePath;
|
|
115
|
+
if (this.#storage === 'memory') {
|
|
116
|
+
databasePath = ':memory:';
|
|
117
|
+
}
|
|
118
|
+
else if (this.#storage === 'persistent') {
|
|
119
|
+
databasePath = this.#dbPath;
|
|
120
|
+
await mkdir(dirname(databasePath), { recursive: true });
|
|
121
|
+
}
|
|
122
|
+
else {
|
|
123
|
+
this.#temporaryDirectory = await mkdtemp(join(tmpdir(), 'mg-context-'));
|
|
124
|
+
databasePath = join(this.#temporaryDirectory, 'mg-context.sqlite');
|
|
125
|
+
this.#dbPath = databasePath;
|
|
126
|
+
}
|
|
127
|
+
try {
|
|
128
|
+
this.#db = createDatabase(databasePath);
|
|
129
|
+
}
|
|
130
|
+
catch (error) {
|
|
131
|
+
/* c8 ignore next 4 -- defensive cleanup when SQLite initialization fails */
|
|
132
|
+
if (this.#temporaryDirectory) {
|
|
133
|
+
await rm(this.#temporaryDirectory, { recursive: true, force: true });
|
|
134
|
+
this.#temporaryDirectory = null;
|
|
135
|
+
}
|
|
136
|
+
throw error;
|
|
137
|
+
}
|
|
138
|
+
this.#sources = new SourceRecords(() => this.db, () => this.#clearMapped());
|
|
139
|
+
this.#db.hasListeners = type => this.#emitEvents && this.#emitter.listenerCount(type) > 0;
|
|
140
|
+
this.#db.emitEvent = (event) => {
|
|
141
|
+
if (this.#emitEvents) {
|
|
142
|
+
this.#emitter.emit(event.type, event.payload);
|
|
143
|
+
}
|
|
144
|
+
};
|
|
145
|
+
if (this.#resetContent) {
|
|
146
|
+
this.reset();
|
|
147
|
+
}
|
|
50
148
|
}
|
|
51
149
|
async close() {
|
|
52
|
-
|
|
53
|
-
this.#db
|
|
54
|
-
|
|
150
|
+
try {
|
|
151
|
+
if (this.#db) {
|
|
152
|
+
try {
|
|
153
|
+
this.#sources.close();
|
|
154
|
+
}
|
|
155
|
+
finally {
|
|
156
|
+
this.#sources = null;
|
|
157
|
+
try {
|
|
158
|
+
this.#db.db.close();
|
|
159
|
+
}
|
|
160
|
+
finally {
|
|
161
|
+
this.#db = null;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
finally {
|
|
167
|
+
if (this.#temporaryDirectory) {
|
|
168
|
+
const directory = this.#temporaryDirectory;
|
|
169
|
+
this.#temporaryDirectory = null;
|
|
170
|
+
await rm(directory, { recursive: true, force: true });
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
/** The SQLite path in use, or :memory: for explicit memory storage. */
|
|
175
|
+
get databasePath() {
|
|
176
|
+
return this.#storage === 'memory' ? ':memory:' : this.#dbPath;
|
|
177
|
+
}
|
|
178
|
+
/** The version of the mg-context schema stored in the open SQLite database. */
|
|
179
|
+
get schemaVersion() {
|
|
180
|
+
return this.db.schemaVersion;
|
|
181
|
+
}
|
|
182
|
+
/** Return content counts when populated, or false when the database is empty. */
|
|
183
|
+
hasContent() {
|
|
184
|
+
const row = this.db.stmts.contentStats.get();
|
|
185
|
+
const stats = {
|
|
186
|
+
posts: row.posts,
|
|
187
|
+
pages: row.pages,
|
|
188
|
+
users: row.users,
|
|
189
|
+
tags: row.tags,
|
|
190
|
+
userAssociations: row.post_user_associations,
|
|
191
|
+
tagAssociations: row.post_tag_associations,
|
|
192
|
+
links: row.links
|
|
193
|
+
};
|
|
194
|
+
return Object.values(stats).some(count => count > 0) ? stats : false;
|
|
195
|
+
}
|
|
196
|
+
get sources() {
|
|
197
|
+
if (!this.#sources) {
|
|
198
|
+
throw new errors.InternalServerError({ message: 'Database not initialized. Call init() first.' });
|
|
55
199
|
}
|
|
200
|
+
return this.#sources;
|
|
201
|
+
}
|
|
202
|
+
#clearMapped() {
|
|
203
|
+
const db = this.db;
|
|
204
|
+
withTransaction(db, () => {
|
|
205
|
+
db.db.exec(`DELETE FROM PostTags; DELETE FROM PostAuthors; DELETE FROM Posts;
|
|
206
|
+
DELETE FROM Tags; DELETE FROM Authors; DELETE FROM Links; DELETE FROM SourceEntityLinks;
|
|
207
|
+
DELETE FROM MigrationEvents WHERE phase = 'mapping';
|
|
208
|
+
DELETE FROM Fingerprints; DELETE FROM PendingEvents;`);
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
resetMappedContent() {
|
|
212
|
+
this.sources.assertIdle();
|
|
213
|
+
this.#clearMapped();
|
|
214
|
+
}
|
|
215
|
+
async rebuildMappedContent(callback) {
|
|
216
|
+
this.sources.assertIdle();
|
|
217
|
+
return this.savepoint(async () => {
|
|
218
|
+
this.#clearMapped();
|
|
219
|
+
return await callback();
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
reset() {
|
|
223
|
+
if (arguments.length > 0) {
|
|
224
|
+
throw new errors.BadRequestError({ message: 'reset() no longer accepts options.' });
|
|
225
|
+
}
|
|
226
|
+
this.sources.assertIdle();
|
|
227
|
+
withTransaction(this.db, () => {
|
|
228
|
+
this.#clearMapped();
|
|
229
|
+
this.db.db.exec(`DELETE FROM SourceRecords; DELETE FROM SourceIngestions; DELETE FROM MigrationEvents;
|
|
230
|
+
DELETE FROM sqlite_sequence WHERE name IN ('Posts', 'Tags', 'Authors', 'PostTags', 'PostAuthors', 'Links', 'MigrationEvents', 'SourceRecords', 'SourceIngestions', 'PendingEvents');`);
|
|
231
|
+
});
|
|
232
|
+
}
|
|
233
|
+
async savepoint(callback) {
|
|
234
|
+
if (!this.db.inTransaction) {
|
|
235
|
+
return this.transaction(callback);
|
|
236
|
+
}
|
|
237
|
+
const name = `record_${randomUUID().replaceAll('-', '')}`;
|
|
238
|
+
this.db.db.exec(`SAVEPOINT ${name}`);
|
|
239
|
+
try {
|
|
240
|
+
const result = await callback();
|
|
241
|
+
this.db.db.exec(`RELEASE ${name}`);
|
|
242
|
+
return result;
|
|
243
|
+
}
|
|
244
|
+
catch (error) {
|
|
245
|
+
this.db.db.exec(`ROLLBACK TO ${name}; RELEASE ${name}`);
|
|
246
|
+
throw error;
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
/**
|
|
250
|
+
* Map records one at a time, each inside its own savepoint. A `RecordDataError` rolls back that record's
|
|
251
|
+
* writes and records a `record:skipped` diagnostic; any other error fails the whole mapping. A mapper that
|
|
252
|
+
* returns `false` leaves the record unselected.
|
|
253
|
+
*/
|
|
254
|
+
async mapRecords(records, mapper) {
|
|
255
|
+
const summary = { selected: 0, imported: 0, skipped: 0 };
|
|
256
|
+
for await (const record of records) {
|
|
257
|
+
try {
|
|
258
|
+
if ((await this.savepoint(() => mapper(record))) === false) {
|
|
259
|
+
continue;
|
|
260
|
+
}
|
|
261
|
+
summary.imported++;
|
|
262
|
+
}
|
|
263
|
+
catch (error) {
|
|
264
|
+
if (!(error instanceof RecordDataError)) {
|
|
265
|
+
throw error;
|
|
266
|
+
}
|
|
267
|
+
summary.skipped++;
|
|
268
|
+
this.recordDiagnostic('record:skipped', { ...record.metadata, reason: error.message }, record.id);
|
|
269
|
+
}
|
|
270
|
+
summary.selected++;
|
|
271
|
+
}
|
|
272
|
+
return summary;
|
|
273
|
+
}
|
|
274
|
+
/** Count diagnostics of the `WARNING_EVENT_TYPES` from both ingestion and mapping. */
|
|
275
|
+
countWarnings() {
|
|
276
|
+
let count = 0;
|
|
277
|
+
for (const row of this.db.stmts.countMigrationEventsByType.all()) {
|
|
278
|
+
if (WARNING_EVENT_TYPES.includes(row.type)) {
|
|
279
|
+
count += row.count;
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
return count;
|
|
283
|
+
}
|
|
284
|
+
recordDiagnostic(type, details = {}, sourceRecordId) {
|
|
285
|
+
assertMappedWrite(this.db);
|
|
286
|
+
if (!type.trim() || (sourceRecordId !== undefined && !this.sources.getById(sourceRecordId))) {
|
|
287
|
+
throw new errors.BadRequestError({ message: 'Diagnostic requires a type and a completed source record.' });
|
|
288
|
+
}
|
|
289
|
+
this.db.db
|
|
290
|
+
.prepare("INSERT INTO MigrationEvents(type, details, created_at, phase, source_record_id) VALUES (?, ?, ?, 'mapping', ?)")
|
|
291
|
+
.run(type, serializeMetadata(details), new Date().toISOString(), sourceRecordId ?? null);
|
|
292
|
+
}
|
|
293
|
+
async *streamDiagnostics({ phase, ingestionId, batchSize = 25 } = {}) {
|
|
294
|
+
if (!Number.isSafeInteger(batchSize) || batchSize < 1) {
|
|
295
|
+
throw new RangeError('batchSize must be a positive safe integer.');
|
|
296
|
+
}
|
|
297
|
+
const conditions = ['id > ?'];
|
|
298
|
+
const params = [];
|
|
299
|
+
if (phase !== undefined) {
|
|
300
|
+
conditions.push('phase = ?');
|
|
301
|
+
params.push(phase);
|
|
302
|
+
}
|
|
303
|
+
if (ingestionId !== undefined) {
|
|
304
|
+
conditions.push('ingestion_id = ?');
|
|
305
|
+
params.push(ingestionId);
|
|
306
|
+
}
|
|
307
|
+
const query = this.db.db.prepare(`SELECT * FROM MigrationEvents WHERE ${conditions.join(' AND ')} ORDER BY id LIMIT ?`);
|
|
308
|
+
let after = 0;
|
|
309
|
+
while (true) {
|
|
310
|
+
const rows = query.all(after, ...params, batchSize);
|
|
311
|
+
if (!rows.length) {
|
|
312
|
+
break;
|
|
313
|
+
}
|
|
314
|
+
for (const row of rows) {
|
|
315
|
+
after = row.id;
|
|
316
|
+
yield {
|
|
317
|
+
id: row.id,
|
|
318
|
+
type: row.type,
|
|
319
|
+
postId: row.post_id,
|
|
320
|
+
lookupKey: row.lookup_key,
|
|
321
|
+
details: JSON.parse(row.details),
|
|
322
|
+
createdAt: row.created_at,
|
|
323
|
+
phase: row.phase,
|
|
324
|
+
ingestionId: row.ingestion_id,
|
|
325
|
+
sourceRecordId: row.source_record_id
|
|
326
|
+
};
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
writeGhostJsonStream(outputDir, options = {}) {
|
|
331
|
+
return writeGhostJson(this, outputDir, {
|
|
332
|
+
...options,
|
|
333
|
+
onWrite: file => {
|
|
334
|
+
options.onWrite?.(file);
|
|
335
|
+
if (this.#emitEvents) {
|
|
336
|
+
this.#emitter.emit('export:file-written', structuredClone(file));
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
});
|
|
340
|
+
}
|
|
341
|
+
writeMigrationReport(path, summary = {}) {
|
|
342
|
+
return writeMigrationReport(this, path, summary);
|
|
56
343
|
}
|
|
57
|
-
// eslint-disable-next-line no-unused-vars
|
|
58
344
|
on(event, listener) {
|
|
59
345
|
this.#emitter.on(event, listener);
|
|
60
346
|
return this;
|
|
61
347
|
}
|
|
62
|
-
// eslint-disable-next-line no-unused-vars
|
|
63
348
|
off(event, listener) {
|
|
64
349
|
this.#emitter.off(event, listener);
|
|
65
350
|
return this;
|
|
66
351
|
}
|
|
352
|
+
getMigrationReport() {
|
|
353
|
+
const summary = {
|
|
354
|
+
'post:inserted': 0,
|
|
355
|
+
'post:skipped': 0,
|
|
356
|
+
'post:replaced': 0,
|
|
357
|
+
'field:sanitized': 0,
|
|
358
|
+
'slug:renamed': 0
|
|
359
|
+
};
|
|
360
|
+
for (const row of this.db.stmts.countMigrationEventsByType.all()) {
|
|
361
|
+
summary[row.type] = row.count;
|
|
362
|
+
}
|
|
363
|
+
const events = this.db.stmts.findMigrationEvents.all().map(row => ({
|
|
364
|
+
id: row.id,
|
|
365
|
+
type: row.type,
|
|
366
|
+
postId: row.post_id ?? null,
|
|
367
|
+
lookupKey: row.lookup_key ?? null,
|
|
368
|
+
details: JSON.parse(row.details),
|
|
369
|
+
createdAt: row.created_at,
|
|
370
|
+
phase: row.phase,
|
|
371
|
+
ingestionId: row.ingestion_id,
|
|
372
|
+
sourceRecordId: row.source_record_id
|
|
373
|
+
}));
|
|
374
|
+
return { summary, events };
|
|
375
|
+
}
|
|
67
376
|
get duplicateSlugs() {
|
|
68
|
-
return this.#
|
|
377
|
+
return this.#collectDuplicateSlugs();
|
|
69
378
|
}
|
|
70
379
|
/**
|
|
71
|
-
*
|
|
72
|
-
*
|
|
380
|
+
* Materialize persisted sanitization diagnostics for the current mapped result.
|
|
381
|
+
* Use streamDiagnostics() when the full array would be too large.
|
|
73
382
|
*/
|
|
74
383
|
get sanitizedFields() {
|
|
75
384
|
return this.db.sanitizedFields;
|
|
76
385
|
}
|
|
77
386
|
#postUrl(row) {
|
|
78
|
-
const source = JSON.parse(row.source);
|
|
79
387
|
const data = JSON.parse(row.data);
|
|
80
|
-
return
|
|
388
|
+
return data.canonical_url || '';
|
|
81
389
|
}
|
|
82
390
|
async deduplicateSlugs() {
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
this.#slugsDeduped = true;
|
|
391
|
+
return this.#collectDuplicateSlugs();
|
|
392
|
+
}
|
|
393
|
+
#collectDuplicateSlugs() {
|
|
87
394
|
// Slug deduplication happens at insert time in PostContext.save(), which records the
|
|
88
395
|
// pre-deduplication slug in original_slug. The groups are rebuilt from the database
|
|
89
396
|
// rather than from the in-memory renames, so the result is still complete when
|
|
90
397
|
// resuming against an existing dbPath, where the renames happened on an earlier run.
|
|
91
398
|
const renamedRows = this.db.stmts.findRenamedPosts.all();
|
|
92
399
|
if (renamedRows.length === 0) {
|
|
93
|
-
this.#duplicateSlugs = [];
|
|
94
400
|
return [];
|
|
95
401
|
}
|
|
96
402
|
// Group the renamed posts by the slug they originally wanted. Map preserves
|
|
@@ -128,55 +434,51 @@ export default class MigrateContext extends MigrateBase {
|
|
|
128
434
|
});
|
|
129
435
|
}
|
|
130
436
|
}
|
|
131
|
-
this.#duplicateSlugs = result;
|
|
132
437
|
return result;
|
|
133
438
|
}
|
|
134
439
|
async prepareForExport({ batchSize = 200 } = {}) {
|
|
135
|
-
|
|
440
|
+
assertMappedWrite(this.db);
|
|
441
|
+
if (!Number.isSafeInteger(batchSize) || batchSize < 1) {
|
|
442
|
+
throw new RangeError('batchSize must be a positive safe integer.');
|
|
443
|
+
}
|
|
136
444
|
const total = this.db.stmts.countPosts.get().count;
|
|
137
445
|
let processed = 0;
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
446
|
+
let after = 0;
|
|
447
|
+
const query = this.db.db.prepare('SELECT id, data FROM Posts WHERE id > ? ORDER BY id LIMIT ?');
|
|
448
|
+
while (true) {
|
|
449
|
+
const rows = query.all(after, batchSize);
|
|
450
|
+
if (!rows.length) {
|
|
451
|
+
break;
|
|
452
|
+
}
|
|
453
|
+
withTransaction(this.db, () => {
|
|
142
454
|
for (const row of rows) {
|
|
143
|
-
const cf = normalizeContentFormat(row.content_format);
|
|
144
|
-
if (cf === 'html') {
|
|
145
|
-
continue;
|
|
146
|
-
}
|
|
147
455
|
const data = JSON.parse(row.data);
|
|
148
|
-
|
|
149
|
-
if (
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
456
|
+
const title = normalizeTitle(data.title);
|
|
457
|
+
if (data.title !== title) {
|
|
458
|
+
recordSanitizedFields(this.db, [
|
|
459
|
+
{
|
|
460
|
+
context: 'PostContext',
|
|
461
|
+
slug: data.slug ?? '',
|
|
462
|
+
field: 'title',
|
|
463
|
+
reason: 'replaced',
|
|
464
|
+
oldValue: data.title,
|
|
465
|
+
newValue: title
|
|
466
|
+
}
|
|
467
|
+
]);
|
|
468
|
+
data.title = title;
|
|
158
469
|
this.db.stmts.updatePostData.run(JSON.stringify(data), row.id);
|
|
159
470
|
}
|
|
471
|
+
after = row.id;
|
|
160
472
|
}
|
|
161
|
-
|
|
162
|
-
/* c8 ignore next 4 */
|
|
163
|
-
}
|
|
164
|
-
catch (err) {
|
|
165
|
-
this.db.db.exec('ROLLBACK');
|
|
166
|
-
throw err;
|
|
167
|
-
}
|
|
473
|
+
});
|
|
168
474
|
processed += rows.length;
|
|
169
475
|
if (this.#emitEvents) {
|
|
170
|
-
this.#emitter.emit('progress', 'prepareForExport', processed, total);
|
|
476
|
+
this.#emitter.emit('progress', { operation: 'prepareForExport', processed, total });
|
|
171
477
|
}
|
|
172
|
-
// Yield to the event loop between batches so V8 can garbage-collect
|
|
173
|
-
// the intermediate DOM/lexical trees created by the converter
|
|
174
|
-
await new Promise(r => {
|
|
175
|
-
setImmediate(r);
|
|
176
|
-
});
|
|
177
478
|
}
|
|
178
479
|
}
|
|
179
480
|
async transaction(callback) {
|
|
481
|
+
this.sources.assertIdle();
|
|
180
482
|
if (this.db.inTransaction) {
|
|
181
483
|
return await callback();
|
|
182
484
|
}
|
|
@@ -185,10 +487,14 @@ export default class MigrateContext extends MigrateBase {
|
|
|
185
487
|
try {
|
|
186
488
|
const result = await callback();
|
|
187
489
|
this.db.db.exec('COMMIT');
|
|
490
|
+
this.db.inTransaction = false;
|
|
491
|
+
flushDatabaseEvents(this.db);
|
|
188
492
|
return result;
|
|
189
493
|
}
|
|
190
494
|
catch (err) {
|
|
191
|
-
this.db.
|
|
495
|
+
if (this.db.inTransaction) {
|
|
496
|
+
this.db.db.exec('ROLLBACK');
|
|
497
|
+
}
|
|
192
498
|
throw err;
|
|
193
499
|
/* c8 ignore next */
|
|
194
500
|
}
|
|
@@ -196,130 +502,140 @@ export default class MigrateContext extends MigrateBase {
|
|
|
196
502
|
this.db.inTransaction = false;
|
|
197
503
|
}
|
|
198
504
|
}
|
|
199
|
-
#
|
|
200
|
-
|
|
201
|
-
|
|
505
|
+
#buildFilterWhere(filter) {
|
|
506
|
+
return buildPostWhere(filter);
|
|
507
|
+
}
|
|
508
|
+
async *#filteredRows(filter, batchSize, operation) {
|
|
509
|
+
if (!Number.isSafeInteger(batchSize) || batchSize < 1) {
|
|
510
|
+
throw new RangeError('batchSize must be a positive safe integer.');
|
|
202
511
|
}
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
512
|
+
const where = this.#buildFilterWhere(filter);
|
|
513
|
+
const iteration = randomUUID();
|
|
514
|
+
this.db.db
|
|
515
|
+
.prepare(`INSERT INTO IterationPosts SELECT ?, id FROM Posts ${where.sql}`)
|
|
516
|
+
.run(iteration, ...where.params);
|
|
517
|
+
try {
|
|
518
|
+
const total = this.db.db
|
|
519
|
+
.prepare('SELECT COUNT(*) AS count FROM IterationPosts WHERE iteration_id = ?')
|
|
520
|
+
.get(iteration).count;
|
|
521
|
+
const query = this.db.db.prepare('SELECT p.* FROM IterationPosts i JOIN Posts p ON p.id = i.post_id WHERE i.iteration_id = ? AND i.post_id > ? ORDER BY i.post_id LIMIT ?');
|
|
522
|
+
let after = 0;
|
|
523
|
+
let processed = 0;
|
|
524
|
+
while (true) {
|
|
525
|
+
const rows = query.all(iteration, after, batchSize);
|
|
526
|
+
if (!rows.length) {
|
|
527
|
+
break;
|
|
218
528
|
}
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
else if (filter.author.name) {
|
|
227
|
-
authors = this.db.stmts.findAuthorsByName.all(filter.author.name);
|
|
228
|
-
}
|
|
229
|
-
else if (filter.author.email) {
|
|
230
|
-
authors = this.db.stmts.findAuthorsByEmail.all(filter.author.email);
|
|
231
|
-
}
|
|
232
|
-
authorPostIds = new Set();
|
|
233
|
-
for (const author of authors) {
|
|
234
|
-
const postAuthors = this.db.stmts.findPostAuthorsByAuthorId.all(author.id);
|
|
235
|
-
for (const pa of postAuthors) {
|
|
236
|
-
authorPostIds.add(pa.post_id);
|
|
529
|
+
for (const row of rows) {
|
|
530
|
+
after = row.id;
|
|
531
|
+
yield row;
|
|
532
|
+
processed += 1;
|
|
533
|
+
}
|
|
534
|
+
if (this.#emitEvents) {
|
|
535
|
+
this.#emitter.emit('progress', { operation, processed, total });
|
|
237
536
|
}
|
|
238
537
|
}
|
|
239
538
|
}
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
ids = [...tagPostIds].filter(id => authorPostIds.has(id));
|
|
243
|
-
}
|
|
244
|
-
else if (tagPostIds) {
|
|
245
|
-
ids = [...tagPostIds];
|
|
246
|
-
}
|
|
247
|
-
else {
|
|
248
|
-
ids = [...authorPostIds];
|
|
539
|
+
finally {
|
|
540
|
+
this.db.db.prepare('DELETE FROM IterationPosts WHERE iteration_id = ?').run(iteration);
|
|
249
541
|
}
|
|
250
|
-
return ids.sort((a, b) => a - b);
|
|
251
|
-
}
|
|
252
|
-
#buildFilterWhere(filter) {
|
|
253
|
-
const postIds = this.#resolveFilterPostIds(filter);
|
|
254
|
-
const dateWhere = buildDateWhere(filter);
|
|
255
|
-
return buildFullWhere(dateWhere, postIds);
|
|
256
542
|
}
|
|
257
543
|
// eslint-disable-next-line no-unused-vars
|
|
258
544
|
async forEachPost(callback, { batchSize = 100, filter } = {}) {
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
const total = allIds.length;
|
|
264
|
-
let processed = 0;
|
|
265
|
-
for (let offset = 0; offset < total; offset += batchSize) {
|
|
266
|
-
const batchIds = allIds.slice(offset, offset + batchSize);
|
|
267
|
-
const rows = findPostsByIds(this.db, batchIds);
|
|
268
|
-
for (const row of rows) {
|
|
269
|
-
const post = PostContext.fromRow(row, this.db);
|
|
270
|
-
await callback(post);
|
|
545
|
+
if (!hasPostFilter(filter)) {
|
|
546
|
+
const total = this.db.stmts.countPosts.get().count;
|
|
547
|
+
const maxId = this.db.stmts.findMaxPostId.get().max_id;
|
|
548
|
+
await this.#forEachByKeyset(total, maxId, batchSize, 'forEachPost', (afterId, upperId, limit) => this.db.stmts.findPostsAfterId.all(afterId, upperId, limit), row => PostContext.fromRow(row, this.db), callback, post => {
|
|
271
549
|
withTransaction(this.db, () => {
|
|
272
550
|
post.save(this.db);
|
|
273
551
|
});
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
552
|
+
});
|
|
553
|
+
return;
|
|
554
|
+
}
|
|
555
|
+
for await (const row of this.#filteredRows(filter, batchSize, 'forEachPost')) {
|
|
556
|
+
const post = PostContext.fromRow(row, this.db);
|
|
557
|
+
await callback(post);
|
|
558
|
+
post.save(this.db);
|
|
279
559
|
}
|
|
280
560
|
}
|
|
281
561
|
async *streamPosts({ batchSize = 100, filter } = {}) {
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
562
|
+
if (!hasPostFilter(filter)) {
|
|
563
|
+
const total = this.db.stmts.countPosts.get().count;
|
|
564
|
+
const maxId = this.db.stmts.findMaxPostId.get().max_id;
|
|
565
|
+
yield* this.#streamByKeyset(total, maxId, batchSize, 'streamPosts', (afterId, upperId, limit) => this.db.stmts.findPostsAfterId.all(afterId, upperId, limit), row => PostContext.fromRow(row, this.db));
|
|
566
|
+
return;
|
|
567
|
+
}
|
|
568
|
+
for await (const row of this.#filteredRows(filter, batchSize, 'streamPosts')) {
|
|
569
|
+
yield PostContext.fromRow(row, this.db);
|
|
570
|
+
}
|
|
285
571
|
}
|
|
286
|
-
async *streamTags({ batchSize = 100 } = {}) {
|
|
287
|
-
const
|
|
288
|
-
|
|
572
|
+
async *streamTags({ batchSize = 100, scope = 'referenced' } = {}) {
|
|
573
|
+
const total = (scope === 'all' ? this.db.stmts.countAllTags : this.db.stmts.countUsedTags).get().count;
|
|
574
|
+
const maxId = (scope === 'all' ? this.db.stmts.findMaxTagId : this.db.stmts.findMaxUsedTagId).get().max_id;
|
|
575
|
+
yield* this.#streamByKeyset(total, maxId, batchSize, 'streamTags', (afterId, upperId, limit) => (scope === 'all' ? this.db.stmts.findTagsAfterId : this.db.stmts.findUsedTagsAfterId).all(afterId, upperId, limit), row => TagContext.fromRow(row));
|
|
289
576
|
}
|
|
290
|
-
async *streamAuthors({ batchSize = 100 } = {}) {
|
|
291
|
-
const
|
|
292
|
-
|
|
577
|
+
async *streamAuthors({ batchSize = 100, scope = 'referenced' } = {}) {
|
|
578
|
+
const total = (scope === 'all' ? this.db.stmts.countAllAuthors : this.db.stmts.countUsedAuthors).get().count;
|
|
579
|
+
const maxId = (scope === 'all' ? this.db.stmts.findMaxAuthorId : this.db.stmts.findMaxUsedAuthorId).get().max_id;
|
|
580
|
+
yield* this.#streamByKeyset(total, maxId, batchSize, 'streamAuthors', (afterId, upperId, limit) => (scope === 'all' ? this.db.stmts.findAuthorsAfterId : this.db.stmts.findUsedAuthorsAfterId).all(afterId, upperId, limit), row => AuthorContext.fromRow(row));
|
|
293
581
|
}
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
582
|
+
async #forEachByKeyset(total, maxId, batchSize, eventName, fetchBatch, toEntity, callback, save) {
|
|
583
|
+
if (maxId === null) {
|
|
584
|
+
return;
|
|
585
|
+
}
|
|
297
586
|
let processed = 0;
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
587
|
+
let lastId = 0;
|
|
588
|
+
let rows;
|
|
589
|
+
do {
|
|
590
|
+
rows = fetchBatch(lastId, maxId, batchSize);
|
|
301
591
|
for (const row of rows) {
|
|
302
|
-
|
|
592
|
+
lastId = row.id;
|
|
593
|
+
const entity = toEntity(row);
|
|
594
|
+
await callback(entity);
|
|
595
|
+
save(entity);
|
|
303
596
|
processed += 1;
|
|
304
597
|
}
|
|
305
598
|
if (this.#emitEvents) {
|
|
306
|
-
this.#emitter.emit('progress', eventName, processed, total);
|
|
599
|
+
this.#emitter.emit('progress', { operation: eventName, processed, total });
|
|
307
600
|
}
|
|
601
|
+
} while (rows.length === batchSize && lastId < maxId);
|
|
602
|
+
}
|
|
603
|
+
async *#streamByKeyset(total, maxId, batchSize, eventName, fetchBatch, toEntity) {
|
|
604
|
+
if (maxId === null) {
|
|
605
|
+
return;
|
|
308
606
|
}
|
|
607
|
+
let processed = 0;
|
|
608
|
+
let lastId = 0;
|
|
609
|
+
let rows;
|
|
610
|
+
do {
|
|
611
|
+
rows = fetchBatch(lastId, maxId, batchSize);
|
|
612
|
+
for (const row of rows) {
|
|
613
|
+
lastId = row.id;
|
|
614
|
+
yield toEntity(row);
|
|
615
|
+
processed += 1;
|
|
616
|
+
}
|
|
617
|
+
if (this.#emitEvents) {
|
|
618
|
+
this.#emitter.emit('progress', { operation: eventName, processed, total });
|
|
619
|
+
}
|
|
620
|
+
} while (rows.length === batchSize && lastId < maxId);
|
|
309
621
|
}
|
|
310
622
|
async addPost(post) {
|
|
311
623
|
let newPost;
|
|
312
624
|
if (post && post instanceof PostContext) {
|
|
313
625
|
newPost = post;
|
|
626
|
+
newPost.onDuplicate = this.#onDuplicate ?? newPost.onDuplicate;
|
|
314
627
|
newPost.warnOnLookupKeyDuplicate = this.#warnOnLookupKeyDuplicate;
|
|
315
628
|
newPost.save(this.db);
|
|
316
629
|
}
|
|
317
630
|
else if (post && typeof post === 'object') {
|
|
318
|
-
newPost = new PostContext({
|
|
631
|
+
newPost = new PostContext({
|
|
632
|
+
...post,
|
|
633
|
+
onDuplicate: post.onDuplicate ?? this.#onDuplicate
|
|
634
|
+
});
|
|
319
635
|
newPost.warnOnLookupKeyDuplicate = this.#warnOnLookupKeyDuplicate;
|
|
320
636
|
}
|
|
321
637
|
else {
|
|
322
|
-
newPost = new PostContext({
|
|
638
|
+
newPost = new PostContext({ onDuplicate: this.#onDuplicate });
|
|
323
639
|
newPost.warnOnLookupKeyDuplicate = this.#warnOnLookupKeyDuplicate;
|
|
324
640
|
}
|
|
325
641
|
return newPost;
|
|
@@ -328,7 +644,46 @@ export default class MigrateContext extends MigrateBase {
|
|
|
328
644
|
const rows = this.db.stmts.findAllPostsOrdered.all();
|
|
329
645
|
return rows.map((row) => PostContext.fromRow(row, this.db));
|
|
330
646
|
}
|
|
331
|
-
|
|
647
|
+
/**
|
|
648
|
+
* Patch scalar post data without hydrating or replacing tag/author relationships.
|
|
649
|
+
* Slugs stay on the full PostContext save path because they require deduplication
|
|
650
|
+
* and redirect tracking.
|
|
651
|
+
*/
|
|
652
|
+
updatePostData(dbId, patch, options = {}) {
|
|
653
|
+
assertMappedWrite(this.db);
|
|
654
|
+
if (!patch || typeof patch !== 'object' || Array.isArray(patch)) {
|
|
655
|
+
throw new errors.BadRequestError({ message: 'Post data patch must be an object.' });
|
|
656
|
+
}
|
|
657
|
+
const forbiddenField = ['slug', 'tags', 'authors'].find(field => Object.hasOwn(patch, field));
|
|
658
|
+
if (forbiddenField) {
|
|
659
|
+
throw new errors.BadRequestError({
|
|
660
|
+
message: `Post data patch cannot update "${forbiddenField}". Use PostContext.save() instead.`
|
|
661
|
+
});
|
|
662
|
+
}
|
|
663
|
+
const row = this.db.stmts.findPostById.get(dbId);
|
|
664
|
+
if (!row) {
|
|
665
|
+
throw new errors.NotFoundError({ message: `Post with database ID ${dbId} was not found.` });
|
|
666
|
+
}
|
|
667
|
+
const post = PostContext.fromRow(row, this.db, { hydrateRelationships: false });
|
|
668
|
+
for (const [key, value] of Object.entries(patch)) {
|
|
669
|
+
post.set(key, value);
|
|
670
|
+
}
|
|
671
|
+
const sanitized = [];
|
|
672
|
+
post.sanitize(sanitized);
|
|
673
|
+
post.checkRequired(post.data);
|
|
674
|
+
const postData = { ...post.data };
|
|
675
|
+
delete postData.tags;
|
|
676
|
+
delete postData.authors;
|
|
677
|
+
const toISOString = (value) => value?.toISOString() ?? null;
|
|
678
|
+
withTransaction(this.db, () => {
|
|
679
|
+
this.db.stmts.patchPostData.run(JSON.stringify(postData), toISOString(post.data.created_at), toISOString(post.data.updated_at), toISOString(post.data.published_at), dbId);
|
|
680
|
+
if (Object.hasOwn(options, 'webscrapeData')) {
|
|
681
|
+
this.db.stmts.updatePostWebscrapeData.run(JSON.stringify(options.webscrapeData) ?? null, dbId);
|
|
682
|
+
}
|
|
683
|
+
recordSanitizedFields(this.db, sanitized);
|
|
684
|
+
});
|
|
685
|
+
}
|
|
686
|
+
async findPosts({ slug, title, tagSlug, tagName, authorSlug, authorName, authorEmail } = {}) {
|
|
332
687
|
if (slug) {
|
|
333
688
|
const rows = this.db.stmts.findPostsBySlug.all(slug);
|
|
334
689
|
return rows.map((row) => PostContext.fromRow(row, this.db));
|
|
@@ -344,17 +699,6 @@ export default class MigrateContext extends MigrateBase {
|
|
|
344
699
|
}
|
|
345
700
|
return results;
|
|
346
701
|
}
|
|
347
|
-
else if (sourceAttr && sourceAttr.key && sourceAttr.value) {
|
|
348
|
-
const rows = this.db.stmts.findAllPostsOrdered.all();
|
|
349
|
-
const results = [];
|
|
350
|
-
for (const row of rows) {
|
|
351
|
-
const source = JSON.parse(row.source);
|
|
352
|
-
if (source[sourceAttr.key] === sourceAttr.value) {
|
|
353
|
-
results.push(PostContext.fromRow(row, this.db));
|
|
354
|
-
}
|
|
355
|
-
}
|
|
356
|
-
return results;
|
|
357
|
-
}
|
|
358
702
|
else if (tagSlug) {
|
|
359
703
|
const tag = this.db.stmts.findTagBySlug.get(tagSlug);
|
|
360
704
|
if (!tag) {
|
|
@@ -441,79 +785,59 @@ export default class MigrateContext extends MigrateBase {
|
|
|
441
785
|
}
|
|
442
786
|
}
|
|
443
787
|
addLink(oldUrl, newUrl) {
|
|
788
|
+
assertMappedWrite(this.db);
|
|
444
789
|
this.db.stmts.insertLink.run(oldUrl, newUrl);
|
|
445
790
|
}
|
|
446
791
|
findLink(oldUrl) {
|
|
447
792
|
const row = this.db.stmts.findLink.get(oldUrl);
|
|
448
793
|
return row ? row.new_url : null;
|
|
449
794
|
}
|
|
450
|
-
async findTags({ slug, name } = {}) {
|
|
795
|
+
async findTags({ slug, name, scope = 'referenced' } = {}) {
|
|
796
|
+
let rows;
|
|
451
797
|
if (slug) {
|
|
452
|
-
|
|
453
|
-
return rows.map((row) => TagContext.fromRow(row));
|
|
798
|
+
rows = this.db.stmts.findTagsBySlug.all(slug);
|
|
454
799
|
}
|
|
455
800
|
else if (name) {
|
|
456
|
-
|
|
457
|
-
return rows.map((row) => TagContext.fromRow(row));
|
|
801
|
+
rows = this.db.stmts.findTagsByName.all(name);
|
|
458
802
|
}
|
|
459
803
|
else {
|
|
460
804
|
return null;
|
|
461
805
|
}
|
|
806
|
+
if (scope === 'referenced') {
|
|
807
|
+
rows = rows.filter(row => this.db.stmts.tagIsUsed.get(row.id));
|
|
808
|
+
}
|
|
809
|
+
return rows.map((row) => TagContext.fromRow(row));
|
|
462
810
|
}
|
|
463
811
|
// eslint-disable-next-line no-unused-vars
|
|
464
|
-
async forEachTag(callback, { batchSize = 100 } = {}) {
|
|
465
|
-
const
|
|
466
|
-
const
|
|
467
|
-
|
|
468
|
-
for (let offset = 0; offset < total; offset += batchSize) {
|
|
469
|
-
const batchIds = allIds.slice(offset, offset + batchSize);
|
|
470
|
-
const rows = findByIds(this.db, 'Tags', batchIds);
|
|
471
|
-
for (const row of rows) {
|
|
472
|
-
const tag = TagContext.fromRow(row);
|
|
473
|
-
await callback(tag);
|
|
474
|
-
tag.save(this.db);
|
|
475
|
-
processed += 1;
|
|
476
|
-
}
|
|
477
|
-
if (this.#emitEvents) {
|
|
478
|
-
this.#emitter.emit('progress', 'forEachTag', processed, total);
|
|
479
|
-
}
|
|
480
|
-
}
|
|
812
|
+
async forEachTag(callback, { batchSize = 100, scope = 'referenced' } = {}) {
|
|
813
|
+
const total = (scope === 'all' ? this.db.stmts.countAllTags : this.db.stmts.countUsedTags).get().count;
|
|
814
|
+
const maxId = (scope === 'all' ? this.db.stmts.findMaxTagId : this.db.stmts.findMaxUsedTagId).get().max_id;
|
|
815
|
+
await this.#forEachByKeyset(total, maxId, batchSize, 'forEachTag', (afterId, upperId, limit) => (scope === 'all' ? this.db.stmts.findTagsAfterId : this.db.stmts.findUsedTagsAfterId).all(afterId, upperId, limit), row => TagContext.fromRow(row), callback, tag => tag.save(this.db));
|
|
481
816
|
}
|
|
482
817
|
// eslint-disable-next-line no-unused-vars
|
|
483
|
-
async forEachAuthor(callback, { batchSize = 100 } = {}) {
|
|
484
|
-
const
|
|
485
|
-
const
|
|
486
|
-
|
|
487
|
-
for (let offset = 0; offset < total; offset += batchSize) {
|
|
488
|
-
const batchIds = allIds.slice(offset, offset + batchSize);
|
|
489
|
-
const rows = findByIds(this.db, 'Authors', batchIds);
|
|
490
|
-
for (const row of rows) {
|
|
491
|
-
const author = AuthorContext.fromRow(row);
|
|
492
|
-
await callback(author);
|
|
493
|
-
author.save(this.db);
|
|
494
|
-
processed += 1;
|
|
495
|
-
}
|
|
496
|
-
if (this.#emitEvents) {
|
|
497
|
-
this.#emitter.emit('progress', 'forEachAuthor', processed, total);
|
|
498
|
-
}
|
|
499
|
-
}
|
|
818
|
+
async forEachAuthor(callback, { batchSize = 100, scope = 'referenced' } = {}) {
|
|
819
|
+
const total = (scope === 'all' ? this.db.stmts.countAllAuthors : this.db.stmts.countUsedAuthors).get().count;
|
|
820
|
+
const maxId = (scope === 'all' ? this.db.stmts.findMaxAuthorId : this.db.stmts.findMaxUsedAuthorId).get().max_id;
|
|
821
|
+
await this.#forEachByKeyset(total, maxId, batchSize, 'forEachAuthor', (afterId, upperId, limit) => (scope === 'all' ? this.db.stmts.findAuthorsAfterId : this.db.stmts.findUsedAuthorsAfterId).all(afterId, upperId, limit), row => AuthorContext.fromRow(row), callback, author => author.save(this.db));
|
|
500
822
|
}
|
|
501
|
-
async findAuthors({ slug, name, email } = {}) {
|
|
823
|
+
async findAuthors({ slug, name, email, scope = 'referenced' } = {}) {
|
|
824
|
+
let rows;
|
|
502
825
|
if (slug) {
|
|
503
|
-
|
|
504
|
-
return rows.map((row) => AuthorContext.fromRow(row));
|
|
826
|
+
rows = this.db.stmts.findAuthorsBySlug.all(slug);
|
|
505
827
|
}
|
|
506
828
|
else if (name) {
|
|
507
|
-
|
|
508
|
-
return rows.map((row) => AuthorContext.fromRow(row));
|
|
829
|
+
rows = this.db.stmts.findAuthorsByName.all(name);
|
|
509
830
|
}
|
|
510
831
|
else if (email) {
|
|
511
|
-
|
|
512
|
-
return rows.map((row) => AuthorContext.fromRow(row));
|
|
832
|
+
rows = this.db.stmts.findAuthorsByEmail.all(email);
|
|
513
833
|
}
|
|
514
834
|
else {
|
|
515
835
|
return null;
|
|
516
836
|
}
|
|
837
|
+
if (scope === 'referenced') {
|
|
838
|
+
rows = rows.filter(row => this.db.stmts.authorIsUsed.get(row.id));
|
|
839
|
+
}
|
|
840
|
+
return rows.map((row) => AuthorContext.fromRow(row));
|
|
517
841
|
}
|
|
518
842
|
// eslint-disable-next-line no-unused-vars
|
|
519
843
|
async forEachGhostPost(callback, { batchSize = 100, filter } = {}) {
|
|
@@ -532,139 +856,133 @@ export default class MigrateContext extends MigrateBase {
|
|
|
532
856
|
processed += 1;
|
|
533
857
|
}
|
|
534
858
|
if (this.#emitEvents) {
|
|
535
|
-
this.#emitter.emit('progress', 'forEachGhostPost', processed, total);
|
|
859
|
+
this.#emitter.emit('progress', { operation: 'forEachGhostPost', processed, total });
|
|
536
860
|
}
|
|
537
861
|
}
|
|
538
862
|
}
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
const
|
|
863
|
+
async writeGhostJson(outputDir, options = {}) {
|
|
864
|
+
const files = [];
|
|
865
|
+
for await (const file of this.writeGhostJsonStream(outputDir, options)) {
|
|
866
|
+
files.push(file);
|
|
867
|
+
}
|
|
868
|
+
return files;
|
|
869
|
+
}
|
|
870
|
+
async writeGhostCSV(outputDir, { filename: rawFilename = 'posts', filter } = {}) {
|
|
871
|
+
const name = `${exportBaseFilename(rawFilename, 'csv')}.csv`;
|
|
872
|
+
await this.prepareForExport();
|
|
542
873
|
await mkdir(outputDir, { recursive: true });
|
|
543
|
-
const where =
|
|
544
|
-
const
|
|
545
|
-
const
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
const
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
const
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
const postsTags = postTagRows.map((r) => ({
|
|
576
|
-
post_id: ghostIdMap.get(r.post_id),
|
|
577
|
-
tag_id: tagGhostIds.get(r.tag_id),
|
|
578
|
-
sort_order: r.sort_order
|
|
579
|
-
}));
|
|
580
|
-
const postsAuthors = postAuthorRows.map((r) => ({
|
|
581
|
-
post_id: ghostIdMap.get(r.post_id),
|
|
582
|
-
author_id: authorGhostIds.get(r.author_id),
|
|
583
|
-
sort_order: r.sort_order
|
|
584
|
-
}));
|
|
585
|
-
// Stream file: posts are loaded and written in sub-batches
|
|
586
|
-
const fileName = totalBatches === 1 ? `${filename}.json` : `${filename}-${batch + 1}.json`;
|
|
587
|
-
const outputPath = join(outputDir, fileName);
|
|
588
|
-
const fh = await open(outputPath, 'w');
|
|
589
|
-
const postsMeta = [];
|
|
590
|
-
let postCount = 0;
|
|
591
|
-
// Indent a JSON.stringify block so all lines after the first are at the given depth
|
|
592
|
-
const pretty = (obj, depth) => {
|
|
593
|
-
const pad = ' '.repeat(depth);
|
|
594
|
-
return JSON.stringify(obj, null, 2).replace(/\n/g, `\n${pad}`);
|
|
595
|
-
};
|
|
596
|
-
try {
|
|
597
|
-
await fh.write('{\n');
|
|
598
|
-
await fh.write(` "meta": ${pretty({ exported_on: Date.now(), version: '2.0.0' }, 2)},\n`);
|
|
599
|
-
await fh.write(' "data": {\n');
|
|
600
|
-
await fh.write(' "posts": [\n');
|
|
601
|
-
// Stream posts in sub-batches
|
|
602
|
-
for (let sub = 0; sub < batchLimit; sub += subBatchSize) {
|
|
603
|
-
const rows = findPostsWhere(this.db, where, Math.min(subBatchSize, batchLimit - sub), batchOffset + sub);
|
|
604
|
-
for (const row of rows) {
|
|
605
|
-
const { post, meta } = PostContext.toGhostPost(row);
|
|
606
|
-
if (postCount > 0) {
|
|
607
|
-
await fh.write(',\n');
|
|
608
|
-
}
|
|
609
|
-
await fh.write(` ${pretty(post, 6)}`);
|
|
610
|
-
if (meta) {
|
|
611
|
-
postsMeta.push(meta);
|
|
612
|
-
}
|
|
613
|
-
postCount += 1;
|
|
614
|
-
}
|
|
874
|
+
const where = buildPostWhere(filter);
|
|
875
|
+
const total = countWhere(this.db, where);
|
|
876
|
+
const { max_id: maxId } = this.db.db
|
|
877
|
+
.prepare(`SELECT MAX(id) AS max_id FROM Posts ${where.sql}`)
|
|
878
|
+
.get(...where.params);
|
|
879
|
+
const keysetWhere = where.sql
|
|
880
|
+
? `${where.sql} AND Posts.id > ? AND Posts.id <= ?`
|
|
881
|
+
: 'WHERE Posts.id > ? AND Posts.id <= ?';
|
|
882
|
+
const findBatch = this.db.db.prepare(`SELECT * FROM Posts ${keysetWhere} ORDER BY Posts.id ASC LIMIT ?`);
|
|
883
|
+
const outputPath = join(outputDir, name);
|
|
884
|
+
const temporaryPath = `${outputPath}.${randomUUID()}.tmp`;
|
|
885
|
+
let postCount = 0;
|
|
886
|
+
async function* lines(context) {
|
|
887
|
+
yield csvLine(GHOST_CSV_COLUMNS);
|
|
888
|
+
let afterId = 0;
|
|
889
|
+
while (maxId !== null) {
|
|
890
|
+
const rows = findBatch.all(...where.params, afterId, maxId, 200);
|
|
891
|
+
if (rows.length === 0) {
|
|
892
|
+
break;
|
|
893
|
+
}
|
|
894
|
+
const postIds = rows.map(row => row.id);
|
|
895
|
+
const placeholders = postIds.map(() => '?').join(',');
|
|
896
|
+
const tagRows = context.db.db
|
|
897
|
+
.prepare(`SELECT pt.post_id, t.data FROM PostTags pt JOIN Tags t ON t.id = pt.tag_id WHERE pt.post_id IN (${placeholders}) ORDER BY pt.post_id ASC, pt.sort_order ASC`)
|
|
898
|
+
.all(...postIds);
|
|
899
|
+
const authorRows = context.db.db
|
|
900
|
+
.prepare(`SELECT pa.post_id, a.data FROM PostAuthors pa JOIN Authors a ON a.id = pa.author_id WHERE pa.post_id IN (${placeholders}) ORDER BY pa.post_id ASC, pa.sort_order ASC`)
|
|
901
|
+
.all(...postIds);
|
|
902
|
+
const relations = new Map(postIds.map(id => [id, { authors: [], tags: [] }]));
|
|
903
|
+
for (const row of tagRows) {
|
|
904
|
+
const tag = JSON.parse(row.data);
|
|
905
|
+
relations.get(row.post_id).tags.push(tag.name);
|
|
615
906
|
}
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
};
|
|
634
|
-
|
|
635
|
-
if (
|
|
636
|
-
|
|
637
|
-
}
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
907
|
+
for (const row of authorRows) {
|
|
908
|
+
const author = JSON.parse(row.data);
|
|
909
|
+
relations.get(row.post_id).authors.push({ name: author.name, email: author.email });
|
|
910
|
+
}
|
|
911
|
+
for (const row of rows) {
|
|
912
|
+
yield csvPostLine(JSON.parse(row.data), relations.get(row.id));
|
|
913
|
+
postCount += 1;
|
|
914
|
+
}
|
|
915
|
+
afterId = rows[rows.length - 1].id;
|
|
916
|
+
if (context.#emitEvents) {
|
|
917
|
+
context.#emitter.emit('progress', { operation: 'writeGhostCSV', processed: postCount, total });
|
|
918
|
+
}
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
try {
|
|
922
|
+
await pipeline(Readable.from(lines(this)), createWriteStream(temporaryPath, { encoding: 'utf8' }));
|
|
923
|
+
const fileStats = await stat(temporaryPath);
|
|
924
|
+
const written = { path: resolve(outputPath), name, size: fileStats.size, posts: postCount };
|
|
925
|
+
await rename(temporaryPath, outputPath);
|
|
926
|
+
if (this.#emitEvents) {
|
|
927
|
+
this.#emitter.emit('export:file-written', structuredClone(written));
|
|
928
|
+
}
|
|
929
|
+
return written;
|
|
930
|
+
}
|
|
931
|
+
finally {
|
|
932
|
+
await rm(temporaryPath, { force: true });
|
|
933
|
+
}
|
|
934
|
+
}
|
|
935
|
+
async writeGhostTagsJson(outputDir, { filename = 'tags', scope = 'referenced' } = {}) {
|
|
936
|
+
const name = exportBaseFilename(filename) + '.json';
|
|
937
|
+
await this.prepareForExport();
|
|
643
938
|
await mkdir(outputDir, { recursive: true });
|
|
644
|
-
const rows = this.db.stmts.findUsedTags.all();
|
|
939
|
+
const rows = (scope === 'all' ? this.db.stmts.findAllTags : this.db.stmts.findUsedTags).all();
|
|
645
940
|
const tags = rows.map((r) => ({ id: r.ghost_id, ...JSON.parse(r.data) }));
|
|
646
941
|
const outputPath = join(outputDir, name);
|
|
942
|
+
const temporaryPath = `${outputPath}.${randomUUID()}.tmp`;
|
|
647
943
|
const content = JSON.stringify({
|
|
648
944
|
meta: { exported_on: Date.now(), version: '2.0.0' },
|
|
649
945
|
data: { tags }
|
|
650
946
|
}, null, 2);
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
947
|
+
try {
|
|
948
|
+
await writeFile(temporaryPath, content);
|
|
949
|
+
const fileStats = await stat(temporaryPath);
|
|
950
|
+
const written = { path: resolve(outputPath), name, size: fileStats.size, posts: 0 };
|
|
951
|
+
await rename(temporaryPath, outputPath);
|
|
952
|
+
if (this.#emitEvents) {
|
|
953
|
+
this.#emitter.emit('export:file-written', structuredClone(written));
|
|
954
|
+
}
|
|
955
|
+
return written;
|
|
956
|
+
}
|
|
957
|
+
finally {
|
|
958
|
+
await rm(temporaryPath, { force: true });
|
|
959
|
+
}
|
|
654
960
|
}
|
|
655
|
-
async writeGhostUsersJson(outputDir, { filename = 'users' } = {}) {
|
|
656
|
-
const name = filename
|
|
961
|
+
async writeGhostUsersJson(outputDir, { filename = 'users', scope = 'referenced' } = {}) {
|
|
962
|
+
const name = exportBaseFilename(filename) + '.json';
|
|
963
|
+
await this.prepareForExport();
|
|
657
964
|
await mkdir(outputDir, { recursive: true });
|
|
658
|
-
const rows = this.db.stmts.findUsedAuthors.all();
|
|
965
|
+
const rows = (scope === 'all' ? this.db.stmts.findAllAuthors : this.db.stmts.findUsedAuthors).all();
|
|
659
966
|
const users = rows.map((r) => ({ id: r.ghost_id, ...JSON.parse(r.data) }));
|
|
660
967
|
const outputPath = join(outputDir, name);
|
|
968
|
+
const temporaryPath = `${outputPath}.${randomUUID()}.tmp`;
|
|
661
969
|
const content = JSON.stringify({
|
|
662
970
|
meta: { exported_on: Date.now(), version: '2.0.0' },
|
|
663
971
|
data: { users }
|
|
664
972
|
}, null, 2);
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
973
|
+
try {
|
|
974
|
+
await writeFile(temporaryPath, content);
|
|
975
|
+
const fileStats = await stat(temporaryPath);
|
|
976
|
+
const written = { path: resolve(outputPath), name, size: fileStats.size, posts: 0 };
|
|
977
|
+
await rename(temporaryPath, outputPath);
|
|
978
|
+
if (this.#emitEvents) {
|
|
979
|
+
this.#emitter.emit('export:file-written', structuredClone(written));
|
|
980
|
+
}
|
|
981
|
+
return written;
|
|
982
|
+
}
|
|
983
|
+
finally {
|
|
984
|
+
await rm(temporaryPath, { force: true });
|
|
985
|
+
}
|
|
668
986
|
}
|
|
669
987
|
}
|
|
670
988
|
//# sourceMappingURL=MigrateContext.js.map
|