@tryghost/mg-context 0.11.8 → 0.11.10-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.
Files changed (73) hide show
  1. package/README.md +73 -832
  2. package/build/index.d.ts +10 -4
  3. package/build/index.js +5 -2
  4. package/build/index.js.map +1 -1
  5. package/build/lib/AuthorContext.d.ts +3 -3
  6. package/build/lib/AuthorContext.js +32 -34
  7. package/build/lib/AuthorContext.js.map +1 -1
  8. package/build/lib/MigrateBase.js +2 -2
  9. package/build/lib/MigrateBase.js.map +1 -1
  10. package/build/lib/MigrateContext.d.ts +139 -36
  11. package/build/lib/MigrateContext.js +606 -324
  12. package/build/lib/MigrateContext.js.map +1 -1
  13. package/build/lib/PostContext.d.ts +72 -16
  14. package/build/lib/PostContext.js +191 -123
  15. package/build/lib/PostContext.js.map +1 -1
  16. package/build/lib/SourceRecords.d.ts +80 -0
  17. package/build/lib/SourceRecords.js +385 -0
  18. package/build/lib/SourceRecords.js.map +1 -0
  19. package/build/lib/TagContext.d.ts +1 -1
  20. package/build/lib/TagContext.js +35 -37
  21. package/build/lib/TagContext.js.map +1 -1
  22. package/build/lib/database.d.ts +47 -11
  23. package/build/lib/database.js +189 -24
  24. package/build/lib/database.js.map +1 -1
  25. package/build/lib/db-helpers.d.ts +1 -5
  26. package/build/lib/db-helpers.js +7 -37
  27. package/build/lib/db-helpers.js.map +1 -1
  28. package/build/lib/export-filename.d.ts +1 -0
  29. package/build/lib/export-filename.js +11 -0
  30. package/build/lib/export-filename.js.map +1 -0
  31. package/build/lib/ghost-csv.d.ts +10 -0
  32. package/build/lib/ghost-csv.js +55 -0
  33. package/build/lib/ghost-csv.js.map +1 -0
  34. package/build/lib/ghost-json.d.ts +4 -0
  35. package/build/lib/ghost-json.js +108 -0
  36. package/build/lib/ghost-json.js.map +1 -0
  37. package/build/lib/ghost-schema.d.ts +58 -0
  38. package/build/lib/ghost-schema.js +61 -0
  39. package/build/lib/ghost-schema.js.map +1 -0
  40. package/build/lib/json.d.ts +8 -0
  41. package/build/lib/json.js +40 -0
  42. package/build/lib/json.js.map +1 -0
  43. package/build/lib/migration-report.d.ts +3 -0
  44. package/build/lib/migration-report.js +41 -0
  45. package/build/lib/migration-report.js.map +1 -0
  46. package/build/lib/source-schema.d.ts +1 -0
  47. package/build/lib/source-schema.js +44 -0
  48. package/build/lib/source-schema.js.map +1 -0
  49. package/build/test/fixtures/mg-context-v2.d.ts +5 -0
  50. package/build/test/fixtures/mg-context-v2.js +58 -0
  51. package/build/test/fixtures/mg-context-v2.js.map +1 -0
  52. package/build/test/ghost-csv.test.d.ts +1 -0
  53. package/build/test/ghost-csv.test.js +333 -0
  54. package/build/test/ghost-csv.test.js.map +1 -0
  55. package/build/test/ghost-schema.test.d.ts +1 -0
  56. package/build/test/ghost-schema.test.js +38 -0
  57. package/build/test/ghost-schema.test.js.map +1 -0
  58. package/build/test/migrate-base.test.js +0 -6
  59. package/build/test/migrate-base.test.js.map +1 -1
  60. package/build/test/migrate-context.test.js +1094 -250
  61. package/build/test/migrate-context.test.js.map +1 -1
  62. package/build/test/package-exports.test.d.ts +1 -0
  63. package/build/test/package-exports.test.js +50 -0
  64. package/build/test/package-exports.test.js.map +1 -0
  65. package/build/test/post-context.test.js +36 -151
  66. package/build/test/post-context.test.js.map +1 -1
  67. package/build/test/source-records.test.d.ts +1 -0
  68. package/build/test/source-records.test.js +625 -0
  69. package/build/test/source-records.test.js.map +1 -0
  70. package/build/test/stream-export.test.d.ts +1 -0
  71. package/build/test/stream-export.test.js +401 -0
  72. package/build/test/stream-export.test.js.map +1 -0
  73. package/package.json +13 -10
@@ -2,10 +2,12 @@ import assert from 'node:assert/strict';
2
2
  import { describe, it, before, after, mock } from 'node:test';
3
3
  import { tmpdir } from 'node:os';
4
4
  import { join } from 'node:path';
5
- import { readFile, unlink, rm } from 'node:fs/promises';
5
+ import { DatabaseSync } from 'node:sqlite';
6
+ import { mkdir, readFile, readdir, stat, unlink, rm, writeFile } from 'node:fs/promises';
6
7
  import errors from '@tryghost/errors';
7
- import { MigrateContext, PostContext, TagContext, AuthorContext } from '../index.js';
8
- import { withTransaction, findPostsByIds } from '../lib/db-helpers.js';
8
+ import { MigrateContext, PostContext, TagContext, AuthorContext, MIGRATE_CONTEXT_SCHEMA_VERSION } from '../index.js';
9
+ import { withTransaction } from '../lib/db-helpers.js';
10
+ import { MG_CONTEXT_V2_SCHEMA } from './fixtures/mg-context-v2.js';
9
11
  describe('MigrateContext', () => {
10
12
  it('Is instance of', () => {
11
13
  const instance = new MigrateContext();
@@ -24,11 +26,243 @@ describe('MigrateContext', () => {
24
26
  assert.ok(instance.db);
25
27
  await instance.close();
26
28
  });
29
+ describe('database lifecycle', () => {
30
+ it('Uses a managed temporary on-disk database by default and removes it on close', async () => {
31
+ const instance = new MigrateContext();
32
+ await instance.init();
33
+ const databasePath = instance.databasePath;
34
+ assert.notEqual(databasePath, ':memory:');
35
+ assert.ok((await stat(databasePath)).isFile());
36
+ await instance.close();
37
+ await assert.rejects(stat(databasePath), { code: 'ENOENT' });
38
+ });
39
+ it('Uses memory only when explicitly requested', async () => {
40
+ const instance = new MigrateContext({ storage: 'memory' });
41
+ await instance.init();
42
+ assert.equal(instance.databasePath, ':memory:');
43
+ await instance.close();
44
+ });
45
+ it('Retains ephemeral as a one-release memory compatibility shim', async () => {
46
+ const instance = new MigrateContext({ ephemeral: true });
47
+ await instance.init();
48
+ assert.equal(instance.databasePath, ':memory:');
49
+ await instance.close();
50
+ });
51
+ it('Rejects conflicting storage options', () => {
52
+ assert.throws(() => new MigrateContext({ dbPath: 'migration.sqlite', storage: 'memory' }), {
53
+ name: 'BadRequestError',
54
+ message: 'Pass either dbPath or storage, not both.'
55
+ });
56
+ });
57
+ it('Validates the content reset option', () => {
58
+ assert.throws(() => new MigrateContext({ resetContent: 'yes' }), {
59
+ name: 'BadRequestError',
60
+ message: 'resetContent must be a boolean.'
61
+ });
62
+ assert.throws(() => new MigrateContext({ rereadSource: true }), {
63
+ name: 'BadRequestError',
64
+ message: 'Use resetContent instead of rereadSource.'
65
+ });
66
+ });
67
+ it('Does not let an invalid path bypass persistent resume validation', () => {
68
+ assert.throws(() => new MigrateContext({ dbPath: '' }), {
69
+ name: 'BadRequestError',
70
+ message: 'dbPath must be a non-empty path.'
71
+ });
72
+ assert.throws(() => new MigrateContext({ dbPath: 3 }), {
73
+ name: 'BadRequestError',
74
+ message: 'dbPath must be a non-empty path.'
75
+ });
76
+ assert.throws(() => new MigrateContext({ mode: 'refresh' }), {
77
+ name: 'BadRequestError',
78
+ message: 'Use resetContent: true instead of the removed mode option.'
79
+ });
80
+ });
81
+ it('Reports the schema version and whether migration content exists', async () => {
82
+ const instance = new MigrateContext();
83
+ await instance.init();
84
+ assert.equal(instance.schemaVersion, MIGRATE_CONTEXT_SCHEMA_VERSION);
85
+ assert.equal(instance.hasContent(), false);
86
+ instance.addLink('example.com/existing/', '/existing/');
87
+ assert.deepEqual(instance.hasContent(), {
88
+ posts: 0,
89
+ pages: 0,
90
+ users: 0,
91
+ tags: 0,
92
+ userAssociations: 0,
93
+ tagAssociations: 0,
94
+ links: 1
95
+ });
96
+ instance.reset();
97
+ assert.equal(instance.hasContent(), false);
98
+ await instance.close();
99
+ });
100
+ it('Clears run-specific reports when the same context is reinitialized', async () => {
101
+ const instance = new MigrateContext();
102
+ await instance.init();
103
+ for (const title of ['First', 'Second']) {
104
+ const post = await instance.addPost();
105
+ post.set('title', title);
106
+ post.set('slug', 'duplicate');
107
+ post.set('created_at', new Date('2023-11-23T12:00:00.000Z'));
108
+ await post.save(instance.db);
109
+ }
110
+ assert.equal((await instance.deduplicateSlugs()).length, 2);
111
+ await instance.close();
112
+ await instance.init();
113
+ assert.deepEqual(instance.duplicateSlugs, []);
114
+ assert.deepEqual(await instance.deduplicateSlugs(), []);
115
+ await instance.close();
116
+ });
117
+ it('Resets all managed content, sequences, and in-memory state', async () => {
118
+ const instance = new MigrateContext();
119
+ await instance.init();
120
+ instance.db.stmts.setFingerprint.run('source', 'source-v1');
121
+ const first = await instance.addPost();
122
+ first.set('title', 'x'.repeat(300));
123
+ first.set('slug', 'reset-post');
124
+ first.set('created_at', new Date('2023-11-23T12:00:00.000Z'));
125
+ first.addTag({ name: 'Reset Tag', slug: 'reset-tag' });
126
+ first.addAuthor({ name: 'Reset Author', slug: 'reset-author', email: 'reset@example.com' });
127
+ await first.save(instance.db);
128
+ const duplicate = await instance.addPost();
129
+ duplicate.set('title', 'Duplicate');
130
+ duplicate.set('slug', 'reset-post');
131
+ duplicate.set('type', 'page');
132
+ duplicate.set('created_at', new Date('2023-11-24T12:00:00.000Z'));
133
+ await duplicate.save(instance.db);
134
+ instance.addLink('example.com/reset-post/', '/reset-post/');
135
+ assert.deepEqual(instance.hasContent(), {
136
+ posts: 1,
137
+ pages: 1,
138
+ users: 1,
139
+ tags: 1,
140
+ userAssociations: 1,
141
+ tagAssociations: 1,
142
+ links: 1
143
+ });
144
+ assert.equal((await instance.deduplicateSlugs()).length, 2);
145
+ assert.ok(instance.db.slugRenames.length > 0);
146
+ assert.ok(instance.sanitizedFields.length > 0);
147
+ instance.reset();
148
+ assert.equal(instance.hasContent(), false);
149
+ assert.equal(instance.db.stmts.getFingerprint.get('source'), undefined);
150
+ assert.equal(instance.db.slugRenames.length, 0);
151
+ assert.equal(instance.sanitizedFields.length, 0);
152
+ assert.deepEqual(instance.duplicateSlugs, []);
153
+ for (const table of ['Posts', 'Tags', 'Authors', 'PostTags', 'PostAuthors', 'Links']) {
154
+ const row = instance.db.db.prepare(`SELECT COUNT(*) AS count FROM ${table}`).get();
155
+ assert.equal(row.count, 0);
156
+ }
157
+ const replacement = await instance.addPost();
158
+ replacement.set('title', 'Replacement');
159
+ replacement.set('slug', 'reset-post');
160
+ replacement.set('created_at', new Date('2023-11-25T12:00:00.000Z'));
161
+ replacement.addTag({ name: 'Reset Tag', slug: 'reset-tag' });
162
+ replacement.addAuthor({ name: 'Reset Author', slug: 'reset-author', email: 'reset@example.com' });
163
+ await replacement.save(instance.db);
164
+ const secondDuplicate = await instance.addPost();
165
+ secondDuplicate.set('title', 'Replacement Duplicate');
166
+ secondDuplicate.set('slug', 'reset-post');
167
+ secondDuplicate.set('created_at', new Date('2023-11-26T12:00:00.000Z'));
168
+ await secondDuplicate.save(instance.db);
169
+ assert.equal(replacement.dbId, 1);
170
+ assert.equal(replacement.data.tags[0].dbId, 1);
171
+ assert.equal(replacement.data.authors[0].dbId, 1);
172
+ assert.equal((await instance.deduplicateSlugs()).length, 2);
173
+ await instance.close();
174
+ });
175
+ it('Reuses complete mapped posts without remapping on resume', async () => {
176
+ const filePath = join(tmpdir(), `mg-context-stored-resume-${Date.now()}.sqlite`);
177
+ const first = new MigrateContext({ dbPath: filePath });
178
+ await first.init();
179
+ const post = await first.addPost({
180
+ lookupKey: 'raw-1'
181
+ });
182
+ post.set('title', 'Original title');
183
+ post.set('slug', 'original');
184
+ post.set('html', '<p>Original HTML</p>');
185
+ post.set('created_at', new Date('2026-01-01T00:00:00.000Z'));
186
+ post.addTag(new TagContext({ initialData: { name: 'Original Tag', slug: 'original-tag' } }));
187
+ post.addAuthor(new AuthorContext({
188
+ initialData: { name: 'Original Author', slug: 'original-author', email: 'author@example.com' }
189
+ }));
190
+ post.save(first.db);
191
+ const databaseId = post.dbId;
192
+ const ghostId = post.ghostId;
193
+ await first.close();
194
+ const resumed = new MigrateContext({ dbPath: filePath });
195
+ const replacements = [];
196
+ resumed.on('post:replaced', event => replacements.push(event));
197
+ await resumed.init();
198
+ const [stored] = await resumed.getAllPosts();
199
+ assert.equal(stored.dbId, databaseId);
200
+ assert.equal(stored.ghostId, ghostId);
201
+ assert.equal(stored.data.title, 'Original title');
202
+ assert.equal(stored.data.html, '<p>Original HTML</p>');
203
+ assert.deepEqual(stored.data.tags.map((tag) => tag.data.slug), ['original-tag']);
204
+ assert.deepEqual(stored.data.authors.map((author) => author.data.slug), ['original-author']);
205
+ assert.deepEqual(replacements, []);
206
+ await resumed.close();
207
+ await rm(filePath, { force: true });
208
+ });
209
+ it('Rejects databases older than the HTML-only compatibility baseline', async () => {
210
+ const filePath = join(tmpdir(), `mg-context-v1-schema-test-${Date.now()}.sqlite`);
211
+ const oldDb = new DatabaseSync(filePath);
212
+ oldDb.exec('CREATE TABLE Posts (id INTEGER PRIMARY KEY);');
213
+ oldDb.exec('PRAGMA user_version = 1;');
214
+ oldDb.close();
215
+ const instance = new MigrateContext({ dbPath: filePath });
216
+ await assert.rejects(() => instance.init(), {
217
+ name: 'InternalServerError',
218
+ message: `Incompatible database schema version 1; rebuild the database from source (requires ${MIGRATE_CONTEXT_SCHEMA_VERSION}).`
219
+ });
220
+ await rm(filePath, { force: true });
221
+ });
222
+ it('Rejects unversioned databases that already contain a migration schema', async () => {
223
+ const filePath = join(tmpdir(), `mg-context-unversioned-schema-test-${Date.now()}.sqlite`);
224
+ const oldDb = new DatabaseSync(filePath);
225
+ oldDb.exec('CREATE TABLE Posts (id INTEGER PRIMARY KEY);');
226
+ oldDb.close();
227
+ const instance = new MigrateContext({ dbPath: filePath });
228
+ await assert.rejects(() => instance.init(), {
229
+ name: 'InternalServerError',
230
+ message: `Incompatible database schema version 0; rebuild the database from source (requires ${MIGRATE_CONTEXT_SCHEMA_VERSION}).`
231
+ });
232
+ await rm(filePath, { force: true });
233
+ });
234
+ it('Rejects the frozen version-two schema without changing its original payloads', async () => {
235
+ const filePath = join(tmpdir(), `mg-context-v2-schema-test-${Date.now()}.sqlite`);
236
+ const oldDb = new DatabaseSync(filePath);
237
+ oldDb.exec(MG_CONTEXT_V2_SCHEMA);
238
+ oldDb.exec("INSERT INTO Posts(data, source) VALUES ('{}', '{\"original\":true}');");
239
+ oldDb.close();
240
+ const instance = new MigrateContext({ dbPath: filePath });
241
+ await assert.rejects(() => instance.init(), /Incompatible database schema version 2; rebuild/);
242
+ const verified = new DatabaseSync(filePath);
243
+ assert.equal(verified.prepare('SELECT source FROM Posts').get().source, '{"original":true}');
244
+ assert.equal(verified.prepare('PRAGMA user_version').get().user_version, 2);
245
+ verified.close();
246
+ await rm(filePath, { force: true });
247
+ });
248
+ it('Rejects a database created by a newer mg-context schema', async () => {
249
+ const filePath = join(tmpdir(), `mg-context-newer-schema-test-${Date.now()}.sqlite`);
250
+ const db = new DatabaseSync(filePath);
251
+ db.exec(`PRAGMA user_version = ${MIGRATE_CONTEXT_SCHEMA_VERSION + 1};`);
252
+ db.close();
253
+ const instance = new MigrateContext({ dbPath: filePath });
254
+ await assert.rejects(() => instance.init(), {
255
+ name: 'InternalServerError',
256
+ message: `Incompatible database schema version ${MIGRATE_CONTEXT_SCHEMA_VERSION + 1}; rebuild the database from source (requires ${MIGRATE_CONTEXT_SCHEMA_VERSION}).`
257
+ });
258
+ await rm(filePath, { force: true });
259
+ });
260
+ });
27
261
  it('Can use file-based DB with dbPath', async () => {
28
262
  const filePath = join(tmpdir(), `mg-context-db-test-${Date.now()}.sqlite`);
29
263
  const instance = new MigrateContext({ dbPath: filePath });
30
264
  await instance.init();
31
- const post = await instance.addPost();
265
+ const post = await instance.addPost({ lookupKey: 'file-db-post' });
32
266
  post.set('title', 'File DB Post');
33
267
  post.set('slug', 'file-db-post');
34
268
  post.set('created_at', new Date('2023-11-23T12:00:00.000Z'));
@@ -62,6 +296,91 @@ describe('MigrateContext', () => {
62
296
  assert.equal(allPosts[1].data.title, 'Another Post');
63
297
  await instance.close();
64
298
  });
299
+ describe('updatePostData', () => {
300
+ it('Patches scalar data and scraper output without touching relationships', async () => {
301
+ const instance = new MigrateContext();
302
+ await instance.init();
303
+ const post = await instance.addPost();
304
+ post.set('title', 'Original title');
305
+ post.set('slug', 'original-title');
306
+ post.set('html', '<p>Original HTML</p>');
307
+ post.set('created_at', new Date('2023-11-23T12:00:00.000Z'));
308
+ post.set('published_at', new Date('2023-11-24T12:00:00.000Z'));
309
+ post.addTag(new TagContext({ name: 'First tag', slug: 'first-tag' }));
310
+ post.addTag(new TagContext({ name: 'Second tag', slug: 'second-tag' }));
311
+ post.addAuthor(new AuthorContext({ name: 'First author', slug: 'first-author', email: 'first@example.com' }));
312
+ post.addAuthor(new AuthorContext({ name: 'Second author', slug: 'second-author', email: 'second@example.com' }));
313
+ post.save(instance.db);
314
+ assert.ok(post.dbId);
315
+ const postTagsBefore = instance.db.stmts.findPostTagsByPostId.all(post.dbId);
316
+ const postAuthorsBefore = instance.db.stmts.findPostAuthorsByPostId.all(post.dbId);
317
+ const tagRead = mock.method(instance.db.stmts.findPostTagsByPostId, 'all');
318
+ const authorRead = mock.method(instance.db.stmts.findPostAuthorsByPostId, 'all');
319
+ instance.updatePostData(post.dbId, {
320
+ title: ' Updated title ',
321
+ html: '<p>Enriched HTML</p>',
322
+ feature_image: `https://example.com/${'x'.repeat(2000)}`,
323
+ updated_at: new Date('2023-11-25T12:00:00.000Z'),
324
+ published_at: null
325
+ }, { webscrapeData: { featureImage: 'downloaded.jpg' } });
326
+ assert.equal(tagRead.mock.callCount(), 0);
327
+ assert.equal(authorRead.mock.callCount(), 0);
328
+ tagRead.mock.restore();
329
+ authorRead.mock.restore();
330
+ const row = instance.db.stmts.findPostById.get(post.dbId);
331
+ const data = JSON.parse(row.data);
332
+ assert.equal(data.title, 'Updated title');
333
+ assert.equal(data.html, '<p>Enriched HTML</p>');
334
+ assert.equal(data.feature_image, null);
335
+ assert.equal(row.created_at, '2023-11-23T12:00:00.000Z');
336
+ assert.equal(row.updated_at, '2023-11-25T12:00:00.000Z');
337
+ assert.equal(row.published_at, null);
338
+ assert.deepEqual(JSON.parse(row.webscrape_data), { featureImage: 'downloaded.jpg' });
339
+ assert.deepEqual(instance.db.stmts.findPostTagsByPostId.all(post.dbId), postTagsBefore);
340
+ assert.deepEqual(instance.db.stmts.findPostAuthorsByPostId.all(post.dbId), postAuthorsBefore);
341
+ const [reloaded] = await instance.getAllPosts();
342
+ assert.deepEqual(reloaded.data.tags.map((tag) => tag.data.slug), ['first-tag', 'second-tag']);
343
+ assert.deepEqual(reloaded.data.authors.map((author) => author.data.slug), ['first-author', 'second-author']);
344
+ assert.deepEqual(instance.sanitizedFields.map(field => [field.field, field.reason]), [
345
+ ['title', 'trimmed'],
346
+ ['feature_image', 'replaced']
347
+ ]);
348
+ instance.updatePostData(post.dbId, { status: 'published' });
349
+ const rowWithoutScraperUpdate = instance.db.stmts.findPostById.get(post.dbId);
350
+ assert.deepEqual(JSON.parse(rowWithoutScraperUpdate.webscrape_data), {
351
+ featureImage: 'downloaded.jpg'
352
+ });
353
+ instance.updatePostData(post.dbId, {}, { webscrapeData: undefined });
354
+ const rowWithClearedScraperData = instance.db.stmts.findPostById.get(post.dbId);
355
+ assert.equal(rowWithClearedScraperData.webscrape_data, null);
356
+ await instance.close();
357
+ });
358
+ it('Rejects invalid patches, relationship fields, slugs, and unknown posts', async () => {
359
+ const instance = new MigrateContext();
360
+ await instance.init();
361
+ assert.throws(() => instance.updatePostData(1, null), {
362
+ name: 'BadRequestError',
363
+ message: 'Post data patch must be an object.'
364
+ });
365
+ assert.throws(() => instance.updatePostData(1, []), {
366
+ name: 'BadRequestError',
367
+ message: 'Post data patch must be an object.'
368
+ });
369
+ assert.throws(() => instance.updatePostData(1, { tags: [] }), {
370
+ name: 'BadRequestError',
371
+ message: 'Post data patch cannot update "tags". Use PostContext.save() instead.'
372
+ });
373
+ assert.throws(() => instance.updatePostData(1, { slug: 'replacement' }), {
374
+ name: 'BadRequestError',
375
+ message: 'Post data patch cannot update "slug". Use PostContext.save() instead.'
376
+ });
377
+ assert.throws(() => instance.updatePostData(999, { title: 'Missing' }), {
378
+ name: 'NotFoundError',
379
+ message: 'Post with database ID 999 was not found.'
380
+ });
381
+ await instance.close();
382
+ });
383
+ });
65
384
  it('Can add existing PostContext to list of posts', async () => {
66
385
  const instance = new MigrateContext();
67
386
  await instance.init();
@@ -125,7 +444,7 @@ describe('MigrateContext', () => {
125
444
  post2.set('created_at', new Date('2023-11-24T12:00:00.000Z'));
126
445
  await post2.save(instance.db);
127
446
  const progressCalls = [];
128
- instance.on('progress', (_event, processed, total) => {
447
+ instance.on('progress', ({ processed, total }) => {
129
448
  progressCalls.push([processed, total]);
130
449
  });
131
450
  await instance.forEachPost(async (post) => {
@@ -140,16 +459,46 @@ describe('MigrateContext', () => {
140
459
  ]);
141
460
  await instance.close();
142
461
  });
462
+ it('Bounds unfiltered post iteration to the rows present when it starts', async () => {
463
+ const instance = new MigrateContext();
464
+ await instance.init();
465
+ for (let i = 1; i <= 3; i += 1) {
466
+ const post = await instance.addPost();
467
+ post.set('title', `Original ${i}`);
468
+ post.set('slug', `original-${i}`);
469
+ await post.save(instance.db);
470
+ }
471
+ const titles = [];
472
+ const progressCalls = [];
473
+ instance.on('progress', ({ operation, processed, total }) => {
474
+ if (operation === 'forEachPost') {
475
+ progressCalls.push([processed, total]);
476
+ }
477
+ });
478
+ await instance.forEachPost(async (post) => {
479
+ titles.push(post.data.title);
480
+ if (titles.length === 1) {
481
+ const added = await instance.addPost();
482
+ added.set('title', 'Added during iteration');
483
+ added.set('slug', 'added-during-iteration');
484
+ await added.save(instance.db);
485
+ }
486
+ }, { batchSize: 1 });
487
+ assert.deepEqual(titles, ['Original 1', 'Original 2', 'Original 3']);
488
+ assert.deepEqual(progressCalls, [
489
+ [1, 3],
490
+ [2, 3],
491
+ [3, 3]
492
+ ]);
493
+ assert.equal((await instance.getAllPosts()).length, 4);
494
+ await instance.close();
495
+ });
143
496
  describe('findPosts', () => {
144
497
  let reusedInstance;
145
498
  before(async () => {
146
499
  reusedInstance = new MigrateContext();
147
500
  await reusedInstance.init();
148
- const reusedPost1 = await reusedInstance.addPost({
149
- source: {
150
- url: 'https://example.com/blog/2023/11/26/test-post/'
151
- }
152
- });
501
+ const reusedPost1 = await reusedInstance.addPost({});
153
502
  reusedPost1.set('title', 'Test Post');
154
503
  reusedPost1.set('slug', 'test-post');
155
504
  reusedPost1.set('created_at', new Date('2023-11-23T12:00:00.000Z'));
@@ -160,11 +509,7 @@ describe('MigrateContext', () => {
160
509
  reusedPost1.addAuthor({ name: 'Test Author', slug: 'test-author', email: 'test@example.com' });
161
510
  reusedPost1.addAuthor({ name: 'First Author', slug: 'first-author', email: 'first@example.com' });
162
511
  await reusedPost1.save(reusedInstance.db);
163
- const reusedPost2 = await reusedInstance.addPost({
164
- source: {
165
- url: 'https://example.com/blog/2023/11/26/another-post/'
166
- }
167
- });
512
+ const reusedPost2 = await reusedInstance.addPost({});
168
513
  reusedPost2.set('title', 'Another Post');
169
514
  reusedPost2.set('slug', 'another-post');
170
515
  reusedPost2.set('created_at', new Date('2023-11-24T12:00:00.000Z'));
@@ -193,16 +538,6 @@ describe('MigrateContext', () => {
193
538
  assert.equal(foundPosts.length, 1);
194
539
  assert.equal(foundPosts[0].data.title, 'Another Post');
195
540
  });
196
- it('Can find posts by source', async () => {
197
- const foundPosts = await reusedInstance.findPosts({
198
- sourceAttr: {
199
- key: 'url',
200
- value: 'https://example.com/blog/2023/11/26/test-post/'
201
- }
202
- });
203
- assert.equal(foundPosts.length, 1);
204
- assert.equal(foundPosts[0].data.title, 'Test Post');
205
- });
206
541
  it('Can find posts by tag slug', async () => {
207
542
  const foundPosts = await reusedInstance.findPosts({
208
543
  tagSlug: 'second-tag'
@@ -312,7 +647,7 @@ describe('MigrateContext', () => {
312
647
  await instance.forEachTag(async (tag) => {
313
648
  slugs.push(tag.data.slug);
314
649
  tag.set('description', `Desc for ${tag.data.slug}`);
315
- });
650
+ }, { batchSize: 1 });
316
651
  assert.deepEqual(slugs, ['alpha', 'beta']);
317
652
  // Verify saves persisted
318
653
  const tags = await instance.findTags({ slug: 'alpha' });
@@ -329,13 +664,14 @@ describe('MigrateContext', () => {
329
664
  post.set('slug', 'post');
330
665
  post.set('created_at', new Date('2023-01-01T00:00:00.000Z'));
331
666
  post.addAuthor({ name: 'Alice', slug: 'alice', email: 'alice@example.com' });
667
+ post.addAuthor({ name: 'Bob', slug: 'bob', email: 'bob@example.com' });
332
668
  await post.save(instance.db);
333
669
  const slugs = [];
334
670
  await instance.forEachAuthor(async (author) => {
335
671
  slugs.push(author.data.slug);
336
672
  author.set('bio', 'Updated bio');
337
- });
338
- assert.deepEqual(slugs, ['alice']);
673
+ }, { batchSize: 1 });
674
+ assert.deepEqual(slugs, ['alice', 'bob']);
339
675
  // Verify saves persisted
340
676
  const authors = await instance.findAuthors({ slug: 'alice' });
341
677
  assert.equal(authors[0].data.bio, 'Updated bio');
@@ -391,6 +727,74 @@ describe('MigrateContext', () => {
391
727
  assert.equal(foundTags, null);
392
728
  });
393
729
  });
730
+ describe('tag and author scope', () => {
731
+ it('Uses referenced by default and applies all consistently across find, iterate, stream, and export', async () => {
732
+ const instance = new MigrateContext({ storage: 'memory' });
733
+ await instance.init();
734
+ const post = await instance.addPost();
735
+ post.set('title', 'Scoped post');
736
+ post.set('slug', 'scoped-post');
737
+ post.set('created_at', new Date('2026-01-01T00:00:00.000Z'));
738
+ post.addTag({ name: 'Used tag', slug: 'used-tag' });
739
+ post.addAuthor({ name: 'Used author', slug: 'used-author', email: 'used@example.com' });
740
+ post.save(instance.db);
741
+ new TagContext({ name: 'Orphan tag', slug: 'orphan-tag' }).save(instance.db);
742
+ new AuthorContext({
743
+ name: 'Orphan author',
744
+ slug: 'orphan-author',
745
+ email: 'orphan@example.com'
746
+ }).save(instance.db);
747
+ assert.deepEqual(await instance.findTags({ slug: 'orphan-tag' }), []);
748
+ assert.equal((await instance.findTags({ slug: 'orphan-tag', scope: 'all' }))[0].data.name, 'Orphan tag');
749
+ assert.deepEqual(await instance.findAuthors({ slug: 'orphan-author' }), []);
750
+ assert.equal((await instance.findAuthors({ slug: 'orphan-author', scope: 'all' }))[0].data.name, 'Orphan author');
751
+ const referencedTags = [];
752
+ await instance.forEachTag(async (tag) => {
753
+ referencedTags.push(tag.data.slug);
754
+ });
755
+ assert.deepEqual(referencedTags, ['used-tag']);
756
+ const allTags = [];
757
+ await instance.forEachTag(async (tag) => {
758
+ allTags.push(tag.data.slug);
759
+ }, { scope: 'all' });
760
+ assert.deepEqual(allTags, ['used-tag', 'orphan-tag']);
761
+ const allStreamedTags = [];
762
+ for await (const tag of instance.streamTags({ scope: 'all' })) {
763
+ allStreamedTags.push(tag.data.slug);
764
+ }
765
+ assert.deepEqual(allStreamedTags, ['used-tag', 'orphan-tag']);
766
+ const referencedAuthors = [];
767
+ for await (const author of instance.streamAuthors()) {
768
+ referencedAuthors.push(author.data.slug);
769
+ }
770
+ assert.deepEqual(referencedAuthors, ['used-author']);
771
+ const allAuthors = [];
772
+ for await (const author of instance.streamAuthors({ scope: 'all' })) {
773
+ allAuthors.push(author.data.slug);
774
+ }
775
+ assert.deepEqual(allAuthors, ['used-author', 'orphan-author']);
776
+ const allIteratedAuthors = [];
777
+ await instance.forEachAuthor(async (author) => {
778
+ allIteratedAuthors.push(author.data.slug);
779
+ }, { scope: 'all' });
780
+ assert.deepEqual(allIteratedAuthors, ['used-author', 'orphan-author']);
781
+ const directory = join(tmpdir(), `mg-context-scope-${Date.now()}`);
782
+ const referencedTagFile = await instance.writeGhostTagsJson(directory, { filename: 'referenced-tags' });
783
+ const referencedTagsJson = JSON.parse(await readFile(referencedTagFile.path, 'utf8'));
784
+ const allTagFile = await instance.writeGhostTagsJson(directory, { filename: 'all-tags', scope: 'all' });
785
+ const referencedUserFile = await instance.writeGhostUsersJson(directory, { filename: 'referenced-users' });
786
+ const referencedUsersJson = JSON.parse(await readFile(referencedUserFile.path, 'utf8'));
787
+ const allUserFile = await instance.writeGhostUsersJson(directory, { filename: 'all-users', scope: 'all' });
788
+ assert.equal(referencedTagsJson.data.tags.length, 1);
789
+ assert.equal(JSON.parse(await readFile(allTagFile.path, 'utf8')).data.tags.length, 2);
790
+ assert.equal(referencedUsersJson.data.users.length, 1);
791
+ assert.equal(JSON.parse(await readFile(allUserFile.path, 'utf8')).data.users.length, 2);
792
+ await readFile(referencedTagFile.path);
793
+ await readFile(referencedUserFile.path);
794
+ await rm(directory, { recursive: true, force: true });
795
+ await instance.close();
796
+ });
797
+ });
394
798
  describe('addLink / findLink', () => {
395
799
  it('Stores and retrieves links', async () => {
396
800
  const instance = new MigrateContext();
@@ -478,7 +882,7 @@ describe('MigrateContext', () => {
478
882
  await post.save(instance.db);
479
883
  }
480
884
  const progressCalls = [];
481
- instance.on('progress', (_event, processed, total) => {
885
+ instance.on('progress', ({ processed, total }) => {
482
886
  progressCalls.push([processed, total]);
483
887
  });
484
888
  await instance.forEachGhostPost(async () => { }, { batchSize: 2 });
@@ -507,9 +911,7 @@ describe('MigrateContext', () => {
507
911
  it('Can return Ghost JSON', async () => {
508
912
  const instance = new MigrateContext();
509
913
  await instance.init();
510
- const post1 = await instance.addPost({
511
- source: { url: 'https://example.com/blog/2023/11/26/test-post/' }
512
- });
914
+ const post1 = await instance.addPost({});
513
915
  post1.set('title', 'Test Post');
514
916
  post1.set('slug', 'test-post');
515
917
  post1.set('created_at', new Date('2023-11-23T12:00:00.000Z'));
@@ -519,9 +921,7 @@ describe('MigrateContext', () => {
519
921
  post1.addTag({ name: 'Test Tag', slug: 'test-tag' });
520
922
  post1.addAuthor({ name: 'Test Author', slug: 'test-author', email: 'test@example.com' });
521
923
  await post1.save(instance.db);
522
- const post2 = await instance.addPost({
523
- source: { url: 'https://example.com/blog/2023/11/26/another-post/' }
524
- });
924
+ const post2 = await instance.addPost({});
525
925
  post2.set('title', 'Another Post');
526
926
  post2.set('slug', 'another-post');
527
927
  post2.set('created_at', new Date('2023-11-24T12:00:00.000Z'));
@@ -624,6 +1024,22 @@ describe('MigrateContext', () => {
624
1024
  await unlink(writtenFiles[0].path);
625
1025
  await instance.close();
626
1026
  });
1027
+ it('Emits export:file-written after each completed file', async () => {
1028
+ const instance = new MigrateContext({ storage: 'memory' });
1029
+ await instance.init();
1030
+ const post = await instance.addPost();
1031
+ post.set('title', 'Event export');
1032
+ post.set('slug', 'event-export');
1033
+ post.set('created_at', new Date('2026-01-01T00:00:00.000Z'));
1034
+ post.save(instance.db);
1035
+ const events = [];
1036
+ instance.on('export:file-written', event => events.push(event));
1037
+ const directory = join(tmpdir(), `mg-context-export-event-${Date.now()}`);
1038
+ const files = await instance.writeGhostJson(directory);
1039
+ assert.deepEqual(events, files);
1040
+ await rm(directory, { recursive: true, force: true });
1041
+ await instance.close();
1042
+ });
627
1043
  it('Can write batched Ghost JSON files', async () => {
628
1044
  const instance = new MigrateContext();
629
1045
  await instance.init();
@@ -669,6 +1085,107 @@ describe('MigrateContext', () => {
669
1085
  }
670
1086
  await instance.close();
671
1087
  });
1088
+ it('Leaves previous chunks and renamed exports for the consumer to remove', async () => {
1089
+ const instance = new MigrateContext({ storage: 'memory' });
1090
+ await instance.init();
1091
+ for (let i = 1; i <= 4; i += 1) {
1092
+ const post = await instance.addPost();
1093
+ post.set('title', `Post ${i}`);
1094
+ post.set('slug', `post-${i}`);
1095
+ post.set('created_at', new Date('2026-01-01T00:00:00Z'));
1096
+ post.save(instance.db);
1097
+ }
1098
+ const directory = join(tmpdir(), `mg-context-consumer-output-${Date.now()}`);
1099
+ try {
1100
+ const first = await instance.writeGhostJson(directory, { batchSize: 1 });
1101
+ const previous = await readFile(first[3].path, 'utf8');
1102
+ await instance.writeGhostJson(directory, { batchSize: 2 });
1103
+ assert.equal(await readFile(first[3].path, 'utf8'), previous);
1104
+ const [single] = await instance.writeGhostJson(directory);
1105
+ const singleContent = await readFile(single.path, 'utf8');
1106
+ await instance.writeGhostJson(directory, { filename: 'renamed' });
1107
+ assert.equal(await readFile(single.path, 'utf8'), singleContent);
1108
+ for (const file of first) {
1109
+ await readFile(file.path);
1110
+ }
1111
+ assert.equal((await readdir(directory)).some(name => name.startsWith('.mg-context-')), false);
1112
+ }
1113
+ finally {
1114
+ await rm(directory, { recursive: true, force: true });
1115
+ await instance.close();
1116
+ }
1117
+ });
1118
+ it('Keeps the previous output set when generation is interrupted', async () => {
1119
+ const instance = new MigrateContext({ storage: 'memory' });
1120
+ await instance.init();
1121
+ for (let i = 1; i <= 2; i += 1) {
1122
+ const post = await instance.addPost();
1123
+ post.set('title', `Interrupted Post ${i}`);
1124
+ post.set('slug', `interrupted-post-${i}`);
1125
+ post.set('created_at', new Date('2026-01-01T00:00:00.000Z'));
1126
+ post.save(instance.db);
1127
+ }
1128
+ const directory = join(tmpdir(), `mg-context-interrupted-export-${Date.now()}`);
1129
+ const previous = await instance.writeGhostJson(directory, { batchSize: 1, filename: 'previous' });
1130
+ const previousContents = await Promise.all(previous.map(file => readFile(file.path, 'utf8')));
1131
+ const originalToGhostPost = PostContext.toGhostPost;
1132
+ let calls = 0;
1133
+ const converter = mock.method(PostContext, 'toGhostPost', (row) => {
1134
+ calls += 1;
1135
+ if (calls === 2) {
1136
+ throw new Error('interrupted export');
1137
+ }
1138
+ return originalToGhostPost(row);
1139
+ });
1140
+ await assert.rejects(() => instance.writeGhostJson(directory, { batchSize: 1, filename: 'interrupted' }), {
1141
+ message: 'interrupted export'
1142
+ });
1143
+ converter.mock.restore();
1144
+ assert.deepEqual(await Promise.all(previous.map(file => readFile(file.path, 'utf8'))), previousContents);
1145
+ await readFile(previous[0].path);
1146
+ await readFile(previous[1].path);
1147
+ await assert.rejects(readFile(join(directory, 'interrupted-1.json')), { code: 'ENOENT' });
1148
+ await assert.rejects(readFile(join(directory, 'interrupted-2.json')), { code: 'ENOENT' });
1149
+ await rm(directory, { recursive: true, force: true });
1150
+ await instance.close();
1151
+ });
1152
+ it('Rejects invalid export filenames', async () => {
1153
+ const instance = new MigrateContext();
1154
+ await instance.init();
1155
+ for (const filename of ['.json', 'nested/export', 'nested\\export']) {
1156
+ await assert.rejects(() => instance.writeGhostJson(tmpdir(), { filename }), {
1157
+ name: 'BadRequestError',
1158
+ message: 'Ghost JSON filename must be a non-empty base filename without path separators.'
1159
+ });
1160
+ await assert.rejects(() => instance.writeGhostTagsJson(tmpdir(), { filename }), {
1161
+ name: 'BadRequestError',
1162
+ message: 'Ghost JSON filename must be a non-empty base filename without path separators.'
1163
+ });
1164
+ await assert.rejects(() => instance.writeGhostUsersJson(tmpdir(), { filename }), {
1165
+ name: 'BadRequestError',
1166
+ message: 'Ghost JSON filename must be a non-empty base filename without path separators.'
1167
+ });
1168
+ }
1169
+ await instance.close();
1170
+ });
1171
+ it('Ignores legacy ownership metadata in the consumer output folder', async () => {
1172
+ const instance = new MigrateContext({ storage: 'memory' });
1173
+ await instance.init();
1174
+ const directory = join(tmpdir(), `mg-context-legacy-output-${Date.now()}`);
1175
+ await mkdir(directory, { recursive: true });
1176
+ try {
1177
+ const manifest = join(directory, '.mg-context-export-manifest.json');
1178
+ await writeFile(manifest, 'consumer-owned metadata');
1179
+ await writeFile(join(directory, 'previous.json'), 'previous export');
1180
+ await instance.writeGhostJson(directory);
1181
+ assert.equal(await readFile(manifest, 'utf8'), 'consumer-owned metadata');
1182
+ assert.equal(await readFile(join(directory, 'previous.json'), 'utf8'), 'previous export');
1183
+ }
1184
+ finally {
1185
+ await rm(directory, { recursive: true, force: true });
1186
+ await instance.close();
1187
+ }
1188
+ });
672
1189
  it('Strips .json extension from filename option', async () => {
673
1190
  const instance = new MigrateContext();
674
1191
  await instance.init();
@@ -703,9 +1220,9 @@ describe('MigrateContext', () => {
703
1220
  await unlink(writtenFiles[0].path);
704
1221
  await instance.close();
705
1222
  });
706
- describe('Ghost JSON content formats', () => {
707
- it('Can export with HTML only', async () => {
708
- const instance = new MigrateContext({ contentFormat: 'html' });
1223
+ describe('Ghost JSON content', () => {
1224
+ it('Exports HTML only', async () => {
1225
+ const instance = new MigrateContext();
709
1226
  await instance.init();
710
1227
  const post = await instance.addPost();
711
1228
  post.set('title', 'HTML Only Post');
@@ -718,30 +1235,6 @@ describe('MigrateContext', () => {
718
1235
  const ghostJSON = JSON.parse(await readFile(writtenFiles[0].path, 'utf-8'));
719
1236
  assert.equal(ghostJSON.data.posts.length, 1);
720
1237
  assert.equal(ghostJSON.data.posts[0].html, '<p>Hello world</p>');
721
- assert.equal(ghostJSON.data.posts[0].mobiledoc, null);
722
- assert.equal(ghostJSON.data.posts[0].lexical, null);
723
- await unlink(writtenFiles[0].path);
724
- await instance.close();
725
- });
726
- it('Can export with Lexical only', async () => {
727
- const instance = new MigrateContext({ contentFormat: 'lexical' });
728
- await instance.init();
729
- const post = await instance.addPost();
730
- post.set('title', 'Lexical Only Post');
731
- post.set('slug', 'lexical-only-post');
732
- post.set('created_at', new Date('2023-11-23T12:00:00.000Z'));
733
- post.set('html', '<p>Hello world</p>');
734
- post.addAuthor({ name: 'Test Author', slug: 'test-author', email: 'test@example.com' });
735
- await post.save(instance.db);
736
- await instance.prepareForExport();
737
- const writtenFiles = await instance.writeGhostJson(tmpdir(), { filename: 'lexical-test' });
738
- const ghostJSON = JSON.parse(await readFile(writtenFiles[0].path, 'utf-8'));
739
- assert.equal(ghostJSON.data.posts.length, 1);
740
- assert.equal(ghostJSON.data.posts[0].html, null);
741
- assert.ok(ghostJSON.data.posts[0].lexical);
742
- assert.equal(typeof ghostJSON.data.posts[0].lexical, 'string');
743
- assert.ok(JSON.parse(ghostJSON.data.posts[0].lexical).root);
744
- assert.equal(ghostJSON.data.posts[0].mobiledoc, null);
745
1238
  await unlink(writtenFiles[0].path);
746
1239
  await instance.close();
747
1240
  });
@@ -820,6 +1313,201 @@ describe('MigrateContext', () => {
820
1313
  assert.equal(post2.dbId, post1.dbId);
821
1314
  await instance.close();
822
1315
  });
1316
+ it('Replaces transformed content from an earlier run when onDuplicate is replace', async () => {
1317
+ const filePath = join(tmpdir(), `mg-context-lookup-replace-${Date.now()}.sqlite`);
1318
+ const firstRun = new MigrateContext({ dbPath: filePath });
1319
+ await firstRun.init();
1320
+ const original = await firstRun.addPost({
1321
+ lookupKey: 'https://example.com/refresh-me'
1322
+ });
1323
+ original.set('title', 'Old title');
1324
+ original.set('slug', 'old-slug');
1325
+ original.set('html', '<p>Old shortcode output</p>');
1326
+ original.set('created_at', new Date('2023-11-23T12:00:00.000Z'));
1327
+ original.addTag({ name: 'Old Tag', slug: 'old-tag' });
1328
+ original.addAuthor({ name: 'Old Author', slug: 'old-author', email: 'old@example.com' });
1329
+ await original.save(firstRun.db);
1330
+ await firstRun.prepareForExport();
1331
+ const originalDbId = original.dbId;
1332
+ const originalGhostId = original.ghostId;
1333
+ await firstRun.close();
1334
+ const secondRun = new MigrateContext({
1335
+ dbPath: filePath,
1336
+ onDuplicate: 'replace'
1337
+ });
1338
+ await secondRun.init();
1339
+ const replacement = await secondRun.addPost({
1340
+ lookupKey: 'https://example.com/refresh-me'
1341
+ });
1342
+ replacement.set('title', 'New title');
1343
+ replacement.set('slug', 'new-slug');
1344
+ replacement.set('html', '<p>Fresh transformed content</p>');
1345
+ replacement.set('created_at', new Date('2023-11-24T12:00:00.000Z'));
1346
+ replacement.addTag({ name: 'New Tag', slug: 'new-tag' });
1347
+ replacement.addAuthor({ name: 'New Author', slug: 'new-author', email: 'new@example.com' });
1348
+ await replacement.save(secondRun.db);
1349
+ await secondRun.prepareForExport();
1350
+ const allPosts = await secondRun.getAllPosts();
1351
+ assert.equal(allPosts.length, 1);
1352
+ assert.equal(replacement.dbId, originalDbId);
1353
+ assert.equal(replacement.ghostId, originalGhostId);
1354
+ assert.equal(allPosts[0].data.title, 'New title');
1355
+ assert.equal(allPosts[0].data.slug, 'new-slug');
1356
+ assert.equal(allPosts[0].data.html, '<p>Fresh transformed content</p>');
1357
+ assert.deepEqual(allPosts[0].data.tags.map((tag) => tag.data.slug), ['new-tag']);
1358
+ assert.deepEqual(allPosts[0].data.authors.map((author) => author.data.slug), ['new-author']);
1359
+ await secondRun.close();
1360
+ await unlink(filePath);
1361
+ });
1362
+ it('Allows a per-post replace policy to override the context default', async () => {
1363
+ const instance = new MigrateContext();
1364
+ await instance.init();
1365
+ const original = await instance.addPost({ lookupKey: 'https://example.com/per-post-replace' });
1366
+ original.set('title', 'Old title');
1367
+ original.set('slug', 'old-slug');
1368
+ original.set('created_at', new Date('2023-11-23T12:00:00.000Z'));
1369
+ await original.save(instance.db);
1370
+ const replacement = await instance.addPost({
1371
+ lookupKey: 'https://example.com/per-post-replace',
1372
+ onDuplicate: 'replace'
1373
+ });
1374
+ replacement.set('title', 'New title');
1375
+ replacement.set('slug', 'new-slug');
1376
+ replacement.set('created_at', new Date('2023-11-24T12:00:00.000Z'));
1377
+ await replacement.save(instance.db);
1378
+ const allPosts = await instance.getAllPosts();
1379
+ assert.equal(allPosts.length, 1);
1380
+ assert.equal(allPosts[0].data.title, 'New title');
1381
+ await instance.close();
1382
+ });
1383
+ it('Uses a duplicate resolver to keep the most recently updated source revision', async () => {
1384
+ const decisions = [];
1385
+ const instance = new MigrateContext({
1386
+ onDuplicate: (existing, incoming) => {
1387
+ decisions.push(`${existing.get('title')} -> ${incoming.get('title')}`);
1388
+ const existingUpdatedAt = existing.get('updated_at');
1389
+ const incomingUpdatedAt = incoming.get('updated_at');
1390
+ if (incomingUpdatedAt && (!existingUpdatedAt || incomingUpdatedAt > existingUpdatedAt)) {
1391
+ return 'replace';
1392
+ }
1393
+ return 'skip';
1394
+ }
1395
+ });
1396
+ await instance.init();
1397
+ const first = await instance.addPost({ lookupKey: 'wordpress-post-900' });
1398
+ first.set('title', 'Middle revision');
1399
+ first.set('slug', 'post-900');
1400
+ first.set('created_at', new Date('2026-10-02T10:00:00.000Z'));
1401
+ first.set('updated_at', new Date('2026-10-04T10:00:00.000Z'));
1402
+ await first.save(instance.db);
1403
+ const older = await instance.addPost({ lookupKey: 'wordpress-post-900' });
1404
+ older.set('title', 'Older revision');
1405
+ older.set('slug', 'post-900');
1406
+ older.set('created_at', new Date('2026-10-02T10:00:00.000Z'));
1407
+ older.set('updated_at', new Date('2026-10-03T09:00:00.000Z'));
1408
+ await older.save(instance.db);
1409
+ let posts = await instance.getAllPosts();
1410
+ assert.equal(posts.length, 1);
1411
+ assert.equal(posts[0].data.title, 'Middle revision');
1412
+ const newest = await instance.addPost({ lookupKey: 'wordpress-post-900' });
1413
+ newest.set('title', 'Newest revision');
1414
+ newest.set('slug', 'post-900');
1415
+ newest.set('created_at', new Date('2026-10-02T10:00:00.000Z'));
1416
+ newest.set('updated_at', new Date('2026-10-05T12:30:00.000Z'));
1417
+ await newest.save(instance.db);
1418
+ posts = await instance.getAllPosts();
1419
+ assert.equal(posts.length, 1);
1420
+ assert.equal(posts[0].data.title, 'Newest revision');
1421
+ assert.deepEqual(posts[0].data.updated_at, new Date('2026-10-05T12:30:00.000Z'));
1422
+ assert.equal(older.dbId, first.dbId);
1423
+ assert.equal(newest.dbId, first.dbId);
1424
+ assert.deepEqual(decisions, ['Middle revision -> Older revision', 'Middle revision -> Newest revision']);
1425
+ await instance.close();
1426
+ });
1427
+ it('Rejects an invalid duplicate resolver result', async () => {
1428
+ const instance = new MigrateContext({
1429
+ onDuplicate: (() => 'merge')
1430
+ });
1431
+ await instance.init();
1432
+ const original = await instance.addPost({ lookupKey: 'invalid-resolver-result' });
1433
+ original.set('title', 'Original');
1434
+ original.set('slug', 'original');
1435
+ original.set('created_at', new Date('2026-10-02T10:00:00.000Z'));
1436
+ await original.save(instance.db);
1437
+ const duplicate = await instance.addPost({ lookupKey: 'invalid-resolver-result' });
1438
+ duplicate.set('title', 'Duplicate');
1439
+ duplicate.set('slug', 'duplicate');
1440
+ duplicate.set('created_at', new Date('2026-10-03T10:00:00.000Z'));
1441
+ assert.throws(() => duplicate.save(instance.db), {
1442
+ name: 'InternalServerError',
1443
+ message: 'Duplicate post resolver must return "skip" or "replace".'
1444
+ });
1445
+ assert.equal(duplicate.dbId, null);
1446
+ assert.equal(duplicate.ghostId, null);
1447
+ const posts = await instance.getAllPosts();
1448
+ assert.equal(posts.length, 1);
1449
+ assert.equal(posts[0].data.title, 'Original');
1450
+ await instance.close();
1451
+ });
1452
+ it('Deduplicates a replacement slug owned by another post', async () => {
1453
+ const instance = new MigrateContext();
1454
+ await instance.init();
1455
+ const original = await instance.addPost({ lookupKey: 'https://example.com/replaced-post' });
1456
+ original.set('title', 'Original');
1457
+ original.set('slug', 'original-slug');
1458
+ original.set('created_at', new Date('2023-11-23T12:00:00.000Z'));
1459
+ await original.save(instance.db);
1460
+ const retained = await instance.addPost({ lookupKey: 'https://example.com/retained-post' });
1461
+ retained.set('title', 'Retained');
1462
+ retained.set('slug', 'refreshed-slug');
1463
+ retained.set('created_at', new Date('2023-11-24T12:00:00.000Z'));
1464
+ await retained.save(instance.db);
1465
+ const replacement = await instance.addPost({
1466
+ lookupKey: 'https://example.com/replaced-post',
1467
+ onDuplicate: 'replace'
1468
+ });
1469
+ replacement.set('title', 'Replacement');
1470
+ replacement.set('slug', 'refreshed-slug');
1471
+ replacement.set('created_at', new Date('2023-11-25T12:00:00.000Z'));
1472
+ await replacement.save(instance.db);
1473
+ assert.equal(replacement.data.slug, 'refreshed-slug-2');
1474
+ assert.deepEqual(instance.db.slugRenames, [
1475
+ {
1476
+ oldSlug: 'refreshed-slug',
1477
+ newSlug: 'refreshed-slug-2',
1478
+ url: ''
1479
+ }
1480
+ ]);
1481
+ const row = instance.db.db
1482
+ .prepare('SELECT slug, original_slug FROM Posts WHERE id = ?')
1483
+ .get(replacement.dbId);
1484
+ assert.equal(row.slug, 'refreshed-slug-2');
1485
+ assert.equal(row.original_slug, 'refreshed-slug');
1486
+ const duplicates = await instance.deduplicateSlugs();
1487
+ assert.deepEqual(duplicates, [
1488
+ { oldSlug: 'refreshed-slug', newSlug: 'refreshed-slug', url: '' },
1489
+ { oldSlug: 'refreshed-slug', newSlug: 'refreshed-slug-2', url: '' }
1490
+ ]);
1491
+ await instance.close();
1492
+ });
1493
+ it('Applies the context duplicate policy to a pre-built PostContext', async () => {
1494
+ const instance = new MigrateContext({ onDuplicate: 'replace' });
1495
+ await instance.init();
1496
+ const original = await instance.addPost({ lookupKey: 'https://example.com/pre-built-replace' });
1497
+ original.set('title', 'Old title');
1498
+ original.set('slug', 'old-slug');
1499
+ original.set('created_at', new Date('2023-11-23T12:00:00.000Z'));
1500
+ await original.save(instance.db);
1501
+ const replacement = new PostContext({ lookupKey: 'https://example.com/pre-built-replace' });
1502
+ replacement.set('title', 'New title');
1503
+ replacement.set('slug', 'new-slug');
1504
+ replacement.set('created_at', new Date('2023-11-24T12:00:00.000Z'));
1505
+ await instance.addPost(replacement);
1506
+ const allPosts = await instance.getAllPosts();
1507
+ assert.equal(allPosts.length, 1);
1508
+ assert.equal(allPosts[0].data.title, 'New title');
1509
+ await instance.close();
1510
+ });
823
1511
  it('Does not record a slug rename for a post skipped by lookup_key', async () => {
824
1512
  const instance = new MigrateContext();
825
1513
  await instance.init();
@@ -893,12 +1581,15 @@ describe('MigrateContext', () => {
893
1581
  assert.notEqual(post1.dbId, post2.dbId);
894
1582
  await instance.close();
895
1583
  });
896
- it('Can get and set lookupKey and warnOnLookupKeyDuplicate on PostContext', () => {
1584
+ it('Can get and set lookupKey, onDuplicate and warnOnLookupKeyDuplicate on PostContext', () => {
897
1585
  const post = new PostContext({ lookupKey: 'https://example.com/initial' });
898
1586
  assert.equal(post.lookupKey, 'https://example.com/initial');
1587
+ assert.equal(post.onDuplicate, 'skip');
899
1588
  assert.equal(post.warnOnLookupKeyDuplicate, false);
900
1589
  post.lookupKey = 'https://example.com/updated';
901
1590
  assert.equal(post.lookupKey, 'https://example.com/updated');
1591
+ post.onDuplicate = 'replace';
1592
+ assert.equal(post.onDuplicate, 'replace');
902
1593
  post.warnOnLookupKeyDuplicate = true;
903
1594
  assert.equal(post.warnOnLookupKeyDuplicate, true);
904
1595
  });
@@ -933,7 +1624,7 @@ describe('MigrateContext', () => {
933
1624
  warnMock.mock.restore();
934
1625
  await instance.close();
935
1626
  });
936
- it('Warning logged when warnOnLookupKeyDuplicate is true', async () => {
1627
+ it('Deprecated warning option does not log and the skip is reported', async () => {
937
1628
  const warnMock = mock.method(console, 'warn', () => { });
938
1629
  const instance = new MigrateContext({ warnOnLookupKeyDuplicate: true });
939
1630
  await instance.init();
@@ -947,8 +1638,8 @@ describe('MigrateContext', () => {
947
1638
  post2.set('slug', 'duplicate');
948
1639
  post2.set('created_at', new Date('2023-11-24T12:00:00.000Z'));
949
1640
  await post2.save(instance.db);
950
- assert.equal(warnMock.mock.calls.length, 1);
951
- assert.ok(warnMock.mock.calls[0].arguments[0].includes('https://example.com/warn-me'));
1641
+ assert.equal(warnMock.mock.calls.length, 0);
1642
+ assert.equal(instance.getMigrationReport().summary['post:skipped'], 1);
952
1643
  warnMock.mock.restore();
953
1644
  await instance.close();
954
1645
  });
@@ -1041,7 +1732,7 @@ describe('MigrateContext', () => {
1041
1732
  await post.save(instance.db);
1042
1733
  assert.throws(() => {
1043
1734
  withTransaction(instance.db, () => {
1044
- instance.db.stmts.updatePost.run(JSON.stringify({ title: 'Rolled Back', slug: 'before-rollback' }), '{}', '{}', 'lexical', null, post.ghostId, '2023-11-23T00:00:00.000Z', null, null, 'before-rollback', null, post.dbId);
1735
+ instance.db.stmts.updatePost.run(JSON.stringify({ title: 'Rolled Back', slug: 'before-rollback' }), null, post.ghostId, '2023-11-23T00:00:00.000Z', null, null, 'before-rollback', null, post.dbId);
1045
1736
  throw new errors.InternalServerError({ message: 'sync rollback' });
1046
1737
  });
1047
1738
  }, { message: 'sync rollback' });
@@ -1060,7 +1751,7 @@ describe('MigrateContext', () => {
1060
1751
  // Outer transaction via ctx.transaction, inner via withTransaction
1061
1752
  await instance.transaction(async () => {
1062
1753
  withTransaction(instance.db, () => {
1063
- instance.db.stmts.updatePost.run(JSON.stringify({ title: 'Updated In Nested', slug: 'nested-tx' }), '{}', '{}', 'lexical', null, post.ghostId, '2023-11-23T00:00:00.000Z', null, null, 'nested-tx', null, post.dbId);
1754
+ instance.db.stmts.updatePost.run(JSON.stringify({ title: 'Updated In Nested', slug: 'nested-tx' }), null, post.ghostId, '2023-11-23T00:00:00.000Z', null, null, 'nested-tx', null, post.dbId);
1064
1755
  });
1065
1756
  });
1066
1757
  const allPosts = await instance.getAllPosts();
@@ -1090,15 +1781,6 @@ describe('MigrateContext', () => {
1090
1781
  await instance.close();
1091
1782
  });
1092
1783
  });
1093
- describe('findPostsByIds', () => {
1094
- it('Returns empty array for empty ID list', async () => {
1095
- const instance = new MigrateContext();
1096
- await instance.init();
1097
- const result = findPostsByIds(instance.db, []);
1098
- assert.deepEqual(result, []);
1099
- await instance.close();
1100
- });
1101
- });
1102
1784
  describe('init guard', () => {
1103
1785
  it('Throws when init() is called twice without close()', async () => {
1104
1786
  const instance = new MigrateContext();
@@ -1109,25 +1791,25 @@ describe('MigrateContext', () => {
1109
1791
  await instance.close();
1110
1792
  });
1111
1793
  });
1112
- describe('Cache bypass paths', () => {
1113
- it('Tag existing.update branch when slug exists in DB but not cache', async () => {
1794
+ describe('Database entity reuse', () => {
1795
+ it('Reuses tags inserted directly into the database', async () => {
1114
1796
  const instance = new MigrateContext();
1115
1797
  await instance.init();
1116
- // Insert tag directly into DB, bypassing the cache
1798
+ // Insert a tag directly into the database
1117
1799
  instance.db.stmts.insertTag.run(JSON.stringify({ name: 'Pre-existing', slug: 'pre-tag' }), 'pre-tag', 'Pre-existing', null);
1118
1800
  // Save a TagContext with the same slug — should hit the existing.update branch
1119
- const tag = new TagContext({ name: 'Updated Pre-existing', slug: 'pre-tag' });
1801
+ const tag = new TagContext({ name: 'Pre-existing', slug: 'pre-tag' });
1120
1802
  await tag.save(instance.db);
1121
1803
  assert.ok(tag.dbId);
1122
- const found = await instance.findTags({ slug: 'pre-tag' });
1804
+ const found = await instance.findTags({ slug: 'pre-tag', scope: 'all' });
1123
1805
  assert.equal(found.length, 1);
1124
- assert.equal(found[0].data.name, 'Updated Pre-existing');
1806
+ assert.equal(found[0].data.name, 'Pre-existing');
1125
1807
  await instance.close();
1126
1808
  });
1127
- it('Author existing.update branch when slug exists in DB but not cache', async () => {
1809
+ it('Reuses authors inserted directly into the database', async () => {
1128
1810
  const instance = new MigrateContext();
1129
1811
  await instance.init();
1130
- // Insert author directly into DB, bypassing the cache
1812
+ // Insert an author directly into the database
1131
1813
  instance.db.stmts.insertAuthor.run(JSON.stringify({ name: 'Pre-existing', slug: 'pre-author', email: 'pre@example.com' }), 'pre-author', 'Pre-existing', 'pre@example.com', null);
1132
1814
  // Save an AuthorContext with the same slug — should hit the existing.update branch
1133
1815
  const author = new AuthorContext({
@@ -1137,9 +1819,9 @@ describe('MigrateContext', () => {
1137
1819
  });
1138
1820
  await author.save(instance.db);
1139
1821
  assert.ok(author.dbId);
1140
- const found = await instance.findAuthors({ slug: 'pre-author' });
1822
+ const found = await instance.findAuthors({ slug: 'pre-author', scope: 'all' });
1141
1823
  assert.equal(found.length, 1);
1142
- assert.equal(found[0].data.name, 'Updated Pre-existing');
1824
+ assert.equal(found[0].data.name, 'Pre-existing');
1143
1825
  await instance.close();
1144
1826
  });
1145
1827
  });
@@ -1268,165 +1950,76 @@ describe('MigrateContext', () => {
1268
1950
  await instance.close();
1269
1951
  });
1270
1952
  });
1271
- describe('Conversion caching', () => {
1272
- it('prepareForExport converts and caches content in DB', async () => {
1273
- const instance = new MigrateContext();
1274
- await instance.init();
1275
- const post = await instance.addPost();
1276
- post.set('title', 'Cache Test');
1277
- post.set('slug', 'cache-test');
1278
- post.set('created_at', new Date('2023-01-01T00:00:00.000Z'));
1279
- post.set('html', '<p>Hello</p>');
1280
- await post.save(instance.db);
1281
- // Before: no cached lexical
1282
- const rowBefore = instance.db.stmts.findPostById.get(post.dbId);
1283
- assert.equal(JSON.parse(rowBefore.data).lexical, null);
1284
- await instance.prepareForExport();
1285
- // After: lexical cached in DB
1286
- const rowAfter = instance.db.stmts.findPostById.get(post.dbId);
1287
- const stored = JSON.parse(rowAfter.data);
1288
- assert.ok(stored.lexical, 'lexical should be cached after prepareForExport');
1289
- assert.ok(JSON.parse(stored.lexical).root);
1290
- assert.equal(stored.html, '<p>Hello</p>', 'html should be preserved');
1291
- await instance.close();
1292
- });
1293
- it('Skips posts that already have converted content', async () => {
1294
- const instance = new MigrateContext();
1295
- await instance.init();
1296
- const post = await instance.addPost();
1297
- post.set('title', 'Skip Test');
1298
- post.set('slug', 'skip-test');
1299
- post.set('created_at', new Date('2023-01-01T00:00:00.000Z'));
1300
- post.set('html', '<p>Hello</p>');
1301
- await post.save(instance.db);
1302
- const dir = join(tmpdir(), `mg-skip-${Date.now()}`);
1303
- await instance.prepareForExport();
1304
- await instance.writeGhostJson(dir);
1305
- const file1 = JSON.parse(await readFile(join(dir, 'posts.json'), 'utf-8'));
1306
- // Second prepare + write: uses cached content (same output)
1307
- await instance.prepareForExport();
1308
- await instance.writeGhostJson(dir);
1309
- const file2 = JSON.parse(await readFile(join(dir, 'posts.json'), 'utf-8'));
1310
- assert.equal(file1.data.posts[0].lexical, file2.data.posts[0].lexical);
1311
- await rm(dir, { recursive: true, force: true });
1312
- await instance.close();
1313
- });
1314
- it('Re-converts after HTML changes via forEachPost', async () => {
1315
- const instance = new MigrateContext();
1953
+ describe('Export preparation', () => {
1954
+ it('Runs automatically before writing Ghost JSON', async () => {
1955
+ const instance = new MigrateContext({ storage: 'memory' });
1316
1956
  await instance.init();
1317
1957
  const post = await instance.addPost();
1318
- post.set('title', 'Invalidate Test');
1319
- post.set('slug', 'invalidate-test');
1320
- post.set('created_at', new Date('2023-01-01T00:00:00.000Z'));
1321
- post.set('html', '<p>Original</p>');
1322
- await post.save(instance.db);
1323
- // First prepare: converts and caches
1324
- await instance.prepareForExport();
1325
- const row1 = instance.db.stmts.findPostById.get(post.dbId);
1326
- const lexical1 = JSON.parse(row1.data).lexical;
1327
- assert.ok(lexical1);
1328
- // Modify HTML → clears cached lexical
1329
- await instance.forEachPost(async (p) => {
1330
- p.set('html', '<p>Updated</p>');
1331
- });
1332
- const rowAfterUpdate = instance.db.stmts.findPostById.get(post.dbId);
1333
- assert.equal(JSON.parse(rowAfterUpdate.data).lexical, null, 'lexical should be cleared after HTML change');
1334
- // Second prepare: re-converts with new HTML
1335
- await instance.prepareForExport();
1336
- const row2 = instance.db.stmts.findPostById.get(post.dbId);
1337
- const lexical2 = JSON.parse(row2.data).lexical;
1338
- assert.ok(lexical2);
1339
- assert.notEqual(lexical1, lexical2);
1340
- await instance.close();
1341
- });
1342
- it('set html invalidates cached conversion', async () => {
1343
- const instance = new MigrateContext();
1344
- await instance.init();
1345
- const post = await instance.addPost();
1346
- post.set('title', 'Invalidate Test');
1347
- post.set('slug', 'invalidate-test');
1348
- post.set('created_at', new Date('2023-01-01T00:00:00.000Z'));
1349
- post.set('html', '<p>Original</p>');
1350
- post.convertContent();
1351
- assert.ok(post.data.lexical);
1352
- // Setting HTML should clear cached lexical
1353
- post.set('html', '<p>New HTML</p>');
1354
- assert.equal(post.data.lexical, null);
1355
- assert.equal(post.htmlDirty, true);
1356
- await instance.close();
1357
- });
1358
- it('Lexical conversion is cached by prepareForExport', async () => {
1359
- const instance = new MigrateContext();
1360
- await instance.init();
1361
- const post = await instance.addPost();
1362
- post.set('title', 'Lexical Test');
1363
- post.set('slug', 'lexical-test');
1364
- post.set('created_at', new Date('2023-01-01T00:00:00.000Z'));
1365
- post.set('html', '<p>Lexical</p>');
1366
- await post.save(instance.db);
1367
- await instance.prepareForExport();
1958
+ post.set('title', 'Original');
1959
+ post.set('slug', 'automatic-preparation');
1960
+ post.set('created_at', new Date('2026-01-01T00:00:00.000Z'));
1961
+ post.save(instance.db);
1368
1962
  const row = instance.db.stmts.findPostById.get(post.dbId);
1369
- const stored = JSON.parse(row.data);
1370
- assert.ok(stored.lexical);
1371
- assert.ok(JSON.parse(stored.lexical).root);
1372
- assert.equal(stored.mobiledoc, null);
1963
+ const data = JSON.parse(row.data);
1964
+ data.title = ' ';
1965
+ instance.db.stmts.updatePostData.run(JSON.stringify(data), post.dbId);
1966
+ const directory = join(tmpdir(), `mg-context-automatic-preparation-${Date.now()}`);
1967
+ const files = await instance.writeGhostJson(directory);
1968
+ const output = JSON.parse(await readFile(files[0].path, 'utf8'));
1969
+ assert.equal(output.data.posts[0].title, '(Untitled)');
1970
+ assert.equal(instance.getMigrationReport().summary['field:sanitized'], 1);
1971
+ await rm(directory, { recursive: true, force: true });
1373
1972
  await instance.close();
1374
1973
  });
1375
- it('Clears stale mobiledoc during prepareForExport', async () => {
1974
+ it('Backfills blank titles already stored in SQLite', async () => {
1376
1975
  const instance = new MigrateContext();
1377
1976
  await instance.init();
1378
1977
  const post = await instance.addPost();
1379
- post.set('title', 'Stale Mobiledoc');
1380
- post.set('slug', 'stale-mobiledoc');
1978
+ post.set('title', 'Original');
1979
+ post.set('slug', 'untitled');
1381
1980
  post.set('created_at', new Date('2023-01-01T00:00:00.000Z'));
1382
- post.set('html', '<p>Hello</p>');
1383
1981
  await post.save(instance.db);
1384
1982
  const row = instance.db.stmts.findPostById.get(post.dbId);
1385
1983
  const data = JSON.parse(row.data);
1386
- data.mobiledoc = '{"version":"0.3.1","atoms":[],"cards":[]}';
1984
+ data.title = ' ';
1387
1985
  instance.db.stmts.updatePostData.run(JSON.stringify(data), post.dbId);
1388
1986
  await instance.prepareForExport();
1389
- const updatedRow = instance.db.stmts.findPostById.get(post.dbId);
1390
- const stored = JSON.parse(updatedRow.data);
1391
- assert.ok(stored.lexical);
1392
- assert.equal(stored.mobiledoc, null);
1987
+ const updated = instance.db.stmts.findPostById.get(post.dbId);
1988
+ assert.equal(JSON.parse(updated.data).title, '(Untitled)');
1393
1989
  await instance.close();
1394
1990
  });
1395
- it('Skips html-format posts', async () => {
1396
- const instance = new MigrateContext({ contentFormat: 'html' });
1991
+ it('Reports an empty slug when preparing a legacy malformed row', async () => {
1992
+ const instance = new MigrateContext({ storage: 'memory' });
1397
1993
  await instance.init();
1398
1994
  const post = await instance.addPost();
1399
- post.set('title', 'HTML Only');
1400
- post.set('slug', 'html-only');
1401
- post.set('created_at', new Date('2023-01-01T00:00:00.000Z'));
1402
- post.set('html', '<p>Hello</p>');
1403
- await post.save(instance.db);
1404
- await instance.prepareForExport();
1995
+ post.set('title', 'Original');
1996
+ post.set('slug', 'legacy-malformed');
1997
+ post.set('created_at', new Date('2026-01-01T00:00:00.000Z'));
1998
+ post.save(instance.db);
1405
1999
  const row = instance.db.stmts.findPostById.get(post.dbId);
1406
- const stored = JSON.parse(row.data);
1407
- assert.equal(stored.html, '<p>Hello</p>');
1408
- assert.equal(stored.lexical, null);
1409
- assert.equal(stored.mobiledoc, null);
2000
+ const data = JSON.parse(row.data);
2001
+ data.title = '';
2002
+ delete data.slug;
2003
+ instance.db.stmts.updatePostData.run(JSON.stringify(data), post.dbId);
2004
+ await instance.prepareForExport();
2005
+ assert.equal(instance.sanitizedFields.at(-1).slug, '');
1410
2006
  await instance.close();
1411
2007
  });
1412
- it('convertContent can be called manually', async () => {
1413
- const instance = new MigrateContext();
2008
+ it('Rolls back preparation and clears queued events when a stored row is invalid', async () => {
2009
+ const instance = new MigrateContext({ storage: 'memory' });
1414
2010
  await instance.init();
1415
2011
  const post = await instance.addPost();
1416
- post.set('title', 'Manual Test');
1417
- post.set('slug', 'manual-test');
1418
- post.set('created_at', new Date('2023-01-01T00:00:00.000Z'));
1419
- post.set('html', '<p>Manual</p>');
1420
- post.convertContent();
1421
- assert.ok(post.data.lexical);
1422
- assert.equal(post.htmlDirty, false);
1423
- await post.save(instance.db);
1424
- const row = instance.db.stmts.findPostById.get(post.dbId);
1425
- const stored = JSON.parse(row.data);
1426
- assert.ok(stored.lexical);
2012
+ post.set('title', 'Invalid row');
2013
+ post.set('slug', 'invalid-row');
2014
+ post.set('created_at', new Date('2026-01-01T00:00:00.000Z'));
2015
+ post.save(instance.db);
2016
+ instance.db.stmts.updatePostData.run('{not json', post.dbId);
2017
+ await assert.rejects(() => instance.prepareForExport(), SyntaxError);
2018
+ assert.equal(instance.db.inTransaction, false);
2019
+ assert.equal(instance.db.db.prepare('SELECT COUNT(*) AS n FROM PendingEvents').get().n, 0);
1427
2020
  await instance.close();
1428
2021
  });
1429
- it('Reports progress during conversion', async () => {
2022
+ it('Reports progress during preparation', async () => {
1430
2023
  const instance = new MigrateContext();
1431
2024
  await instance.init();
1432
2025
  for (let i = 0; i < 3; i += 1) {
@@ -1438,7 +2031,7 @@ describe('MigrateContext', () => {
1438
2031
  await post.save(instance.db);
1439
2032
  }
1440
2033
  const calls = [];
1441
- instance.on('progress', (_event, processed, total) => {
2034
+ instance.on('progress', ({ processed, total }) => {
1442
2035
  calls.push([processed, total]);
1443
2036
  });
1444
2037
  await instance.prepareForExport();
@@ -1458,7 +2051,7 @@ describe('MigrateContext', () => {
1458
2051
  post.set('html', '<p>Hello</p>');
1459
2052
  await post.save(instance.db);
1460
2053
  const calls = [];
1461
- const listener = (_event, processed) => {
2054
+ const listener = ({ processed }) => {
1462
2055
  calls.push(processed);
1463
2056
  };
1464
2057
  instance.on('progress', listener);
@@ -1578,6 +2171,27 @@ describe('MigrateContext', () => {
1578
2171
  const titles = await collectTitles({});
1579
2172
  assert.equal(titles.length, 5);
1580
2173
  });
2174
+ it('Snapshots matches before callbacks mutate the filtered field', async () => {
2175
+ const filtered = new MigrateContext();
2176
+ await filtered.init();
2177
+ for (let i = 1; i <= 2; i += 1) {
2178
+ const post = await filtered.addPost();
2179
+ post.set('title', `Filtered ${i}`);
2180
+ post.set('slug', `filtered-${i}`);
2181
+ post.set('created_at', new Date(`2023-01-0${i}T00:00:00.000Z`));
2182
+ await post.save(filtered.db);
2183
+ }
2184
+ const titles = [];
2185
+ await filtered.forEachPost(async (post) => {
2186
+ titles.push(post.data.title);
2187
+ post.set('created_at', new Date('2025-01-01T00:00:00.000Z'));
2188
+ }, {
2189
+ batchSize: 1,
2190
+ filter: { createdAt: { before: new Date('2024-01-01T00:00:00.000Z') } }
2191
+ });
2192
+ assert.deepEqual(titles, ['Filtered 1', 'Filtered 2']);
2193
+ await filtered.close();
2194
+ });
1581
2195
  it('Tag slug filter returns matching posts', async () => {
1582
2196
  const titles = await collectTitles({ tag: { slug: 'news' } });
1583
2197
  assert.deepEqual(titles, ['Post A', 'Post B']);
@@ -1665,7 +2279,7 @@ describe('MigrateContext', () => {
1665
2279
  });
1666
2280
  it('Progress reports correct filtered total', async () => {
1667
2281
  const progressCalls = [];
1668
- ctx.on('progress', (_event, processed, total) => {
2282
+ ctx.on('progress', ({ processed, total }) => {
1669
2283
  progressCalls.push([processed, total]);
1670
2284
  });
1671
2285
  // eslint-disable-next-line no-unused-vars
@@ -1691,11 +2305,33 @@ describe('MigrateContext', () => {
1691
2305
  describe('streamPosts', () => {
1692
2306
  it('yields all posts as PostContext objects', async () => {
1693
2307
  const titles = [];
1694
- for await (const post of ctx.streamPosts()) {
2308
+ for await (const post of ctx.streamPosts({ batchSize: 1 })) {
1695
2309
  titles.push(post.data.title);
1696
2310
  }
1697
2311
  assert.equal(titles.length, 5);
1698
2312
  });
2313
+ it('does not yield posts added after unfiltered streaming starts', async () => {
2314
+ const streamed = new MigrateContext();
2315
+ await streamed.init();
2316
+ for (let i = 1; i <= 2; i += 1) {
2317
+ const post = await streamed.addPost();
2318
+ post.set('title', `Streamed ${i}`);
2319
+ post.set('slug', `streamed-${i}`);
2320
+ await post.save(streamed.db);
2321
+ }
2322
+ const titles = [];
2323
+ for await (const post of streamed.streamPosts({ batchSize: 1 })) {
2324
+ titles.push(post.data.title);
2325
+ if (titles.length === 1) {
2326
+ const added = await streamed.addPost();
2327
+ added.set('title', 'Added during stream');
2328
+ added.set('slug', 'added-during-stream');
2329
+ await added.save(streamed.db);
2330
+ }
2331
+ }
2332
+ assert.deepEqual(titles, ['Streamed 1', 'Streamed 2']);
2333
+ await streamed.close();
2334
+ });
1699
2335
  it('supports filter option', async () => {
1700
2336
  const titles = [];
1701
2337
  for await (const post of ctx.streamPosts({ filter: { tag: { slug: 'news' } } })) {
@@ -1703,6 +2339,28 @@ describe('MigrateContext', () => {
1703
2339
  }
1704
2340
  assert.deepEqual(titles, ['Post A', 'Post B']);
1705
2341
  });
2342
+ it('snapshots matches before consumers persist filtered-field changes', async () => {
2343
+ const filtered = new MigrateContext();
2344
+ await filtered.init();
2345
+ for (let i = 1; i <= 2; i += 1) {
2346
+ const post = await filtered.addPost();
2347
+ post.set('title', `Stream filter ${i}`);
2348
+ post.set('slug', `stream-filter-${i}`);
2349
+ post.set('created_at', new Date(`2023-02-0${i}T00:00:00.000Z`));
2350
+ await post.save(filtered.db);
2351
+ }
2352
+ const titles = [];
2353
+ for await (const post of filtered.streamPosts({
2354
+ batchSize: 1,
2355
+ filter: { createdAt: { before: new Date('2024-01-01T00:00:00.000Z') } }
2356
+ })) {
2357
+ titles.push(post.data.title);
2358
+ post.set('created_at', new Date('2025-01-01T00:00:00.000Z'));
2359
+ await post.save(filtered.db);
2360
+ }
2361
+ assert.deepEqual(titles, ['Stream filter 1', 'Stream filter 2']);
2362
+ await filtered.close();
2363
+ });
1706
2364
  it('yields zero posts on empty context', async () => {
1707
2365
  const empty = new MigrateContext();
1708
2366
  await empty.init();
@@ -1718,7 +2376,7 @@ describe('MigrateContext', () => {
1718
2376
  describe('streamTags', () => {
1719
2377
  it('yields all used tags', async () => {
1720
2378
  const slugs = [];
1721
- for await (const tag of ctx.streamTags()) {
2379
+ for await (const tag of ctx.streamTags({ batchSize: 1 })) {
1722
2380
  slugs.push(tag.data.slug);
1723
2381
  }
1724
2382
  assert.ok(slugs.includes('news'));
@@ -1728,7 +2386,7 @@ describe('MigrateContext', () => {
1728
2386
  describe('streamAuthors', () => {
1729
2387
  it('yields all used authors', async () => {
1730
2388
  const slugs = [];
1731
- for await (const author of ctx.streamAuthors()) {
2389
+ for await (const author of ctx.streamAuthors({ batchSize: 1 })) {
1732
2390
  slugs.push(author.data.slug);
1733
2391
  }
1734
2392
  assert.ok(slugs.includes('alice'));
@@ -1746,7 +2404,7 @@ describe('MigrateContext', () => {
1746
2404
  });
1747
2405
  it('Tag filter with progress reports correct total', async () => {
1748
2406
  const progressCalls = [];
1749
- ctx.on('progress', (_event, processed, total) => {
2407
+ ctx.on('progress', ({ processed, total }) => {
1750
2408
  progressCalls.push([processed, total]);
1751
2409
  });
1752
2410
  // eslint-disable-next-line no-unused-vars
@@ -2085,6 +2743,174 @@ describe('MigrateContext', () => {
2085
2743
  await ctx.close();
2086
2744
  });
2087
2745
  });
2746
+ describe('typed change events and durable reports', () => {
2747
+ it('Emits sanitization and slug changes with before/after values after commit', async () => {
2748
+ const instance = new MigrateContext({ storage: 'memory' });
2749
+ await instance.init();
2750
+ const sanitized = [];
2751
+ const renamed = [];
2752
+ instance.on('field:sanitized', event => sanitized.push(event));
2753
+ instance.on('slug:renamed', event => {
2754
+ assert.ok(instance.db.stmts.findPostById.get(event.postId));
2755
+ renamed.push(event);
2756
+ });
2757
+ const first = await instance.addPost({ lookupKey: 'first' });
2758
+ first.set('title', 'First');
2759
+ first.set('slug', 'same-slug');
2760
+ first.set('created_at', new Date('2026-01-01T00:00:00.000Z'));
2761
+ first.save(instance.db);
2762
+ const second = await instance.addPost({ lookupKey: 'second' });
2763
+ second.set('title', 'x'.repeat(300));
2764
+ second.set('slug', 'same-slug');
2765
+ second.set('created_at', new Date('2026-01-02T00:00:00.000Z'));
2766
+ second.save(instance.db);
2767
+ assert.equal(sanitized.at(-1).oldValue, 'x'.repeat(300));
2768
+ assert.equal(sanitized.at(-1).newValue, 'x'.repeat(255));
2769
+ assert.deepEqual(renamed, [
2770
+ {
2771
+ postId: second.dbId,
2772
+ lookupKey: 'second',
2773
+ oldSlug: 'same-slug',
2774
+ newSlug: 'same-slug-2',
2775
+ url: ''
2776
+ }
2777
+ ]);
2778
+ const report = instance.getMigrationReport();
2779
+ assert.equal(report.summary['post:inserted'], 2);
2780
+ assert.equal(report.summary['field:sanitized'], 1);
2781
+ assert.equal(report.summary['slug:renamed'], 1);
2782
+ assert.equal(report.events.find(event => event.type === 'slug:renamed').details.newSlug, 'same-slug-2');
2783
+ await instance.close();
2784
+ });
2785
+ it('Persists duplicate skips for later runs and emits their identity', async () => {
2786
+ const filePath = join(tmpdir(), `mg-context-report-${Date.now()}.sqlite`);
2787
+ const firstRun = new MigrateContext({ dbPath: filePath });
2788
+ await firstRun.init();
2789
+ const skipped = [];
2790
+ firstRun.on('post:skipped', event => skipped.push(event));
2791
+ const original = await firstRun.addPost({ lookupKey: 'same-source-id' });
2792
+ original.set('title', 'Original');
2793
+ original.set('slug', 'original');
2794
+ original.set('created_at', new Date('2026-01-01T00:00:00.000Z'));
2795
+ original.save(firstRun.db);
2796
+ const duplicate = await firstRun.addPost({ lookupKey: 'same-source-id' });
2797
+ duplicate.set('title', 'Duplicate');
2798
+ duplicate.set('slug', 'duplicate');
2799
+ duplicate.set('created_at', new Date('2026-01-02T00:00:00.000Z'));
2800
+ duplicate.save(firstRun.db);
2801
+ assert.deepEqual(skipped, [{ lookupKey: 'same-source-id', existingPostId: original.dbId }]);
2802
+ await firstRun.close();
2803
+ const secondRun = new MigrateContext({ dbPath: filePath });
2804
+ await secondRun.init();
2805
+ const report = secondRun.getMigrationReport();
2806
+ assert.equal(report.summary['post:skipped'], 1);
2807
+ assert.deepEqual(report.events.find(event => event.type === 'post:skipped').details, {
2808
+ existingPostId: original.dbId
2809
+ });
2810
+ await secondRun.close();
2811
+ await rm(filePath, { force: true });
2812
+ });
2813
+ it('Emits complete detached snapshots for replacements', async () => {
2814
+ const instance = new MigrateContext({ storage: 'memory', onDuplicate: 'replace' });
2815
+ await instance.init();
2816
+ const original = await instance.addPost({
2817
+ lookupKey: 'replace-me'
2818
+ });
2819
+ original.set('title', 'Old title');
2820
+ original.set('slug', 'replace-me');
2821
+ original.set('html', '<p>Old</p>');
2822
+ original.set('created_at', new Date('2026-01-01T00:00:00.000Z'));
2823
+ original.webscrapeData = { old: true };
2824
+ original.addTag({ name: 'Old tag', slug: 'old-tag' });
2825
+ original.addAuthor({ name: 'Old author', slug: 'old-author', email: 'old@example.com' });
2826
+ original.save(instance.db);
2827
+ let replacementEvent;
2828
+ instance.on('post:replaced', event => {
2829
+ const stored = instance.db.stmts.findPostById.get(event.postId);
2830
+ assert.equal(JSON.parse(stored.data).title, 'New title');
2831
+ replacementEvent = event;
2832
+ });
2833
+ const replacement = await instance.addPost({
2834
+ lookupKey: 'replace-me'
2835
+ });
2836
+ replacement.set('title', 'New title');
2837
+ replacement.set('slug', 'replace-me');
2838
+ replacement.set('html', '<p>New</p>');
2839
+ replacement.set('created_at', new Date('2026-02-01T00:00:00.000Z'));
2840
+ replacement.webscrapeData = { new: true };
2841
+ replacement.addTag({ name: 'New tag', slug: 'new-tag' });
2842
+ replacement.addAuthor({ name: 'New author', slug: 'new-author', email: 'new@example.com' });
2843
+ replacement.save(instance.db);
2844
+ assert.equal(replacementEvent.previous.data.title, 'Old title');
2845
+ assert.equal(replacementEvent.previous.data.tags[0].name, 'Old tag');
2846
+ assert.equal(replacementEvent.previous.data.authors[0].name, 'Old author');
2847
+ assert.deepEqual(replacementEvent.previous.webscrapeData, { old: true });
2848
+ assert.equal(replacementEvent.current.data.title, 'New title');
2849
+ assert.equal(replacementEvent.current.data.html, '<p>New</p>');
2850
+ assert.equal(replacementEvent.current.data.tags[0].name, 'New tag');
2851
+ assert.equal(replacementEvent.current.data.authors[0].name, 'New author');
2852
+ replacementEvent.current.data.title = 'Listener mutation';
2853
+ replacementEvent.current.data.tags[0].name = 'Listener tag mutation';
2854
+ const stored = (await instance.findPosts({ slug: 'replace-me' }))[0];
2855
+ assert.equal(stored.data.title, 'New title');
2856
+ assert.equal(stored.data.tags[0].data.name, 'New tag');
2857
+ const replaced = instance.getMigrationReport().events.find(event => event.type === 'post:replaced');
2858
+ assert.ok(replaced.details.changedFields.includes('html'));
2859
+ assert.ok(replaced.details.changedFields.includes('tags'));
2860
+ await instance.close();
2861
+ });
2862
+ it('Leaves a committed replacement intact when its listener throws', async () => {
2863
+ const instance = new MigrateContext({ storage: 'memory', onDuplicate: 'replace' });
2864
+ await instance.init();
2865
+ const original = await instance.addPost({ lookupKey: 'listener-error' });
2866
+ original.set('title', 'Before');
2867
+ original.set('slug', 'listener-error');
2868
+ original.set('created_at', new Date('2026-01-01T00:00:00.000Z'));
2869
+ original.save(instance.db);
2870
+ instance.on('post:replaced', () => {
2871
+ throw new Error('listener failed');
2872
+ });
2873
+ const replacement = await instance.addPost({ lookupKey: 'listener-error' });
2874
+ replacement.set('title', 'After');
2875
+ replacement.set('slug', 'listener-error');
2876
+ replacement.set('created_at', new Date('2026-02-01T00:00:00.000Z'));
2877
+ assert.throws(() => replacement.save(instance.db), { message: 'listener failed' });
2878
+ assert.equal((await instance.findPosts({ slug: 'listener-error' }))[0].data.title, 'After');
2879
+ assert.equal(instance.getMigrationReport().summary['post:replaced'], 1);
2880
+ await instance.close();
2881
+ });
2882
+ it('Does not emit or persist rolled-back outcomes', async () => {
2883
+ const instance = new MigrateContext({ storage: 'memory' });
2884
+ await instance.init();
2885
+ const sanitized = [];
2886
+ instance.on('field:sanitized', event => sanitized.push(event));
2887
+ await assert.rejects(instance.transaction(async () => {
2888
+ const post = await instance.addPost({ lookupKey: 'rolled-back' });
2889
+ post.set('title', 'x'.repeat(300));
2890
+ post.set('slug', 'rolled-back');
2891
+ post.set('created_at', new Date('2026-01-01T00:00:00.000Z'));
2892
+ post.save(instance.db);
2893
+ throw new Error('rollback');
2894
+ }), { message: 'rollback' });
2895
+ assert.deepEqual(sanitized, []);
2896
+ assert.equal(instance.hasContent(), false);
2897
+ assert.equal(instance.getMigrationReport().events.length, 0);
2898
+ await instance.close();
2899
+ });
2900
+ it('Emits standalone entity sanitization after the save completes', async () => {
2901
+ const instance = new MigrateContext({ storage: 'memory' });
2902
+ await instance.init();
2903
+ const events = [];
2904
+ instance.on('field:sanitized', event => events.push(event));
2905
+ const tag = new TagContext({ name: ',Standalone', slug: 'standalone' });
2906
+ tag.save(instance.db);
2907
+ assert.equal(events.length, 1);
2908
+ assert.equal(events[0].oldValue, ',Standalone');
2909
+ assert.equal(events[0].newValue, 'Standalone');
2910
+ assert.ok(instance.db.stmts.findTagById.get(tag.dbId));
2911
+ await instance.close();
2912
+ });
2913
+ });
2088
2914
  describe('deduplicateSlugs', () => {
2089
2915
  it('Stores the pre-deduplication slug in original_slug', async () => {
2090
2916
  const instance = new MigrateContext();
@@ -2133,30 +2959,33 @@ describe('MigrateContext', () => {
2133
2959
  const filePath = join(tmpdir(), `mg-context-dedup-resume-${Date.now()}.sqlite`);
2134
2960
  const firstRun = new MigrateContext({ dbPath: filePath });
2135
2961
  await firstRun.init();
2136
- const post1 = await firstRun.addPost({ source: { url: 'https://example.com/blog/my-post' } });
2962
+ const post1 = await firstRun.addPost({
2963
+ lookupKey: 'blog/my-post'
2964
+ });
2137
2965
  post1.set('title', 'First');
2138
2966
  post1.set('slug', 'my-post');
2139
2967
  post1.set('created_at', new Date('2023-01-01T00:00:00.000Z'));
2140
2968
  await post1.save(firstRun.db);
2141
- const post2 = await firstRun.addPost({ source: { url: 'https://example.com/news/my-post' } });
2969
+ const post2 = await firstRun.addPost({
2970
+ lookupKey: 'news/my-post'
2971
+ });
2142
2972
  post2.set('title', 'Second');
2143
2973
  post2.set('slug', 'my-post');
2144
2974
  post2.set('created_at', new Date('2023-06-01T00:00:00.000Z'));
2145
2975
  await post2.save(firstRun.db);
2146
2976
  await firstRun.close();
2147
- // Resume against the same database — nothing is inserted this run, so the
2148
- // in-memory renames are empty, but the group is still reported from the DB
2977
+ // Resume keeps the stored slugs; the duplicate report is rebuilt from SQLite.
2149
2978
  const secondRun = new MigrateContext({ dbPath: filePath });
2150
2979
  await secondRun.init();
2151
- assert.equal(secondRun.db.slugRenames.length, 0);
2980
+ assert.equal(secondRun.db.slugRenames.length, 1);
2152
2981
  const duplicates = await secondRun.deduplicateSlugs();
2153
2982
  assert.equal(duplicates.length, 2);
2154
2983
  assert.equal(duplicates[0].oldSlug, 'my-post');
2155
2984
  assert.equal(duplicates[0].newSlug, 'my-post');
2156
- assert.equal(duplicates[0].url, 'https://example.com/blog/my-post');
2985
+ assert.equal(duplicates[0].url, '');
2157
2986
  assert.equal(duplicates[1].oldSlug, 'my-post');
2158
2987
  assert.equal(duplicates[1].newSlug, 'my-post-2');
2159
- assert.equal(duplicates[1].url, 'https://example.com/news/my-post');
2988
+ assert.equal(duplicates[1].url, '');
2160
2989
  await secondRun.close();
2161
2990
  await unlink(filePath);
2162
2991
  });
@@ -2196,13 +3025,13 @@ describe('MigrateContext', () => {
2196
3025
  it('Deduplicates 2 posts with the same slug, oldest keeps original', async () => {
2197
3026
  const instance = new MigrateContext();
2198
3027
  await instance.init();
2199
- const post1 = await instance.addPost({ source: { url: 'https://example.com/blog/my-post' } });
3028
+ const post1 = await instance.addPost({});
2200
3029
  post1.set('title', 'Older Post');
2201
3030
  post1.set('slug', 'my-post');
2202
3031
  post1.set('created_at', new Date('2023-01-01T00:00:00.000Z'));
2203
3032
  post1.set('published_at', new Date('2023-01-01T00:00:00.000Z'));
2204
3033
  await post1.save(instance.db);
2205
- const post2 = await instance.addPost({ source: { url: 'https://example.com/news/my-post' } });
3034
+ const post2 = await instance.addPost({});
2206
3035
  post2.set('title', 'Newer Post');
2207
3036
  post2.set('slug', 'my-post');
2208
3037
  post2.set('created_at', new Date('2023-06-01T00:00:00.000Z'));
@@ -2213,10 +3042,10 @@ describe('MigrateContext', () => {
2213
3042
  assert.equal(duplicates.length, 2);
2214
3043
  assert.equal(duplicates[0].oldSlug, 'my-post');
2215
3044
  assert.equal(duplicates[0].newSlug, 'my-post');
2216
- assert.equal(duplicates[0].url, 'https://example.com/blog/my-post');
3045
+ assert.equal(duplicates[0].url, '');
2217
3046
  assert.equal(duplicates[1].oldSlug, 'my-post');
2218
3047
  assert.equal(duplicates[1].newSlug, 'my-post-2');
2219
- assert.equal(duplicates[1].url, 'https://example.com/news/my-post');
3048
+ assert.equal(duplicates[1].url, '');
2220
3049
  // Verify DB was updated
2221
3050
  const posts = await instance.findPosts({ slug: 'my-post' });
2222
3051
  assert.equal(posts.length, 1);
@@ -2291,16 +3120,16 @@ describe('MigrateContext', () => {
2291
3120
  assert.equal(existingPosts[0].data.title, 'Existing -2');
2292
3121
  await instance.close();
2293
3122
  });
2294
- it('Includes source URL for both retained and renamed entries', async () => {
3123
+ it('Does not invent URLs for posts without canonical URLs', async () => {
2295
3124
  const instance = new MigrateContext();
2296
3125
  await instance.init();
2297
- const post1 = await instance.addPost({ source: { url: 'https://example.com/blog/my-post' } });
3126
+ const post1 = await instance.addPost({});
2298
3127
  post1.set('title', 'First');
2299
3128
  post1.set('slug', 'my-post');
2300
3129
  post1.set('created_at', new Date('2023-01-01T00:00:00.000Z'));
2301
3130
  post1.set('published_at', new Date('2023-01-01T00:00:00.000Z'));
2302
3131
  await post1.save(instance.db);
2303
- const post2 = await instance.addPost({ source: { url: 'https://example.com/news/my-post' } });
3132
+ const post2 = await instance.addPost({});
2304
3133
  post2.set('title', 'Second');
2305
3134
  post2.set('slug', 'my-post');
2306
3135
  post2.set('created_at', new Date('2023-06-01T00:00:00.000Z'));
@@ -2308,11 +3137,11 @@ describe('MigrateContext', () => {
2308
3137
  await post2.save(instance.db);
2309
3138
  const duplicates = await instance.deduplicateSlugs();
2310
3139
  assert.equal(duplicates.length, 2);
2311
- assert.equal(duplicates[0].url, 'https://example.com/blog/my-post');
2312
- assert.equal(duplicates[1].url, 'https://example.com/news/my-post');
3140
+ assert.equal(duplicates[0].url, '');
3141
+ assert.equal(duplicates[1].url, '');
2313
3142
  await instance.close();
2314
3143
  });
2315
- it('Falls back to canonical_url when source.url is absent', async () => {
3144
+ it('Includes canonical URLs in slug reports', async () => {
2316
3145
  const instance = new MigrateContext();
2317
3146
  await instance.init();
2318
3147
  const post1 = await instance.addPost();
@@ -2399,13 +3228,13 @@ describe('MigrateContext', () => {
2399
3228
  it('prepareForExport deduplicates and results are used by writeGhostJson', async () => {
2400
3229
  const instance = new MigrateContext();
2401
3230
  await instance.init();
2402
- const post1 = await instance.addPost({ source: { url: 'https://example.com/first' } });
3231
+ const post1 = await instance.addPost({});
2403
3232
  post1.set('title', 'First');
2404
3233
  post1.set('slug', 'dupe');
2405
3234
  post1.set('created_at', new Date('2023-01-01T00:00:00.000Z'));
2406
3235
  post1.set('published_at', new Date('2023-01-01T00:00:00.000Z'));
2407
3236
  await post1.save(instance.db);
2408
- const post2 = await instance.addPost({ source: { url: 'https://example.com/second' } });
3237
+ const post2 = await instance.addPost({});
2409
3238
  post2.set('title', 'Second');
2410
3239
  post2.set('slug', 'dupe');
2411
3240
  post2.set('created_at', new Date('2023-06-01T00:00:00.000Z'));
@@ -2422,9 +3251,9 @@ describe('MigrateContext', () => {
2422
3251
  assert.equal(instance.duplicateSlugs.length, 2);
2423
3252
  assert.equal(instance.duplicateSlugs[0].oldSlug, 'dupe');
2424
3253
  assert.equal(instance.duplicateSlugs[0].newSlug, 'dupe');
2425
- assert.equal(instance.duplicateSlugs[0].url, 'https://example.com/first');
3254
+ assert.equal(instance.duplicateSlugs[0].url, '');
2426
3255
  assert.equal(instance.duplicateSlugs[1].newSlug, 'dupe-2');
2427
- assert.equal(instance.duplicateSlugs[1].url, 'https://example.com/second');
3256
+ assert.equal(instance.duplicateSlugs[1].url, '');
2428
3257
  await unlink(files[0].path);
2429
3258
  await instance.close();
2430
3259
  });
@@ -2445,7 +3274,7 @@ describe('MigrateContext', () => {
2445
3274
  await post2.save(instance.db);
2446
3275
  const first = await instance.deduplicateSlugs();
2447
3276
  assert.equal(first.length, 2);
2448
- // Second call returns cached result without modifying anything
3277
+ // Repeated calls read the same persisted result without modifying anything
2449
3278
  const second = await instance.deduplicateSlugs();
2450
3279
  assert.equal(second.length, 2);
2451
3280
  assert.deepEqual(first, second);
@@ -2456,6 +3285,21 @@ describe('MigrateContext', () => {
2456
3285
  });
2457
3286
  });
2458
3287
  describe('sanitizedFields', () => {
3288
+ it('Stores a fallback when a post title is missing', async () => {
3289
+ const instance = new MigrateContext();
3290
+ await instance.init();
3291
+ const post = await instance.addPost();
3292
+ post.set('slug', 'untitled');
3293
+ post.set('created_at', new Date('2023-01-01T00:00:00.000Z'));
3294
+ await post.save(instance.db);
3295
+ const stored = await instance.findPosts({ slug: 'untitled' });
3296
+ assert.equal(stored[0].data.title, '(Untitled)');
3297
+ const titleChange = instance.sanitizedFields.find((entry) => entry.field === 'title');
3298
+ assert.equal(titleChange.reason, 'replaced');
3299
+ assert.equal(titleChange.oldValue, null);
3300
+ assert.equal(titleChange.newValue, '(Untitled)');
3301
+ await instance.close();
3302
+ });
2459
3303
  it('Reports values trimmed on the way into the database', async () => {
2460
3304
  const instance = new MigrateContext();
2461
3305
  await instance.init();