@tryghost/mg-context 0.1.27 → 0.2.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.
@@ -1,137 +1,199 @@
1
1
  import assert from 'node:assert/strict';
2
- import { describe, it } from 'node:test';
3
- import { MigrateContext, PostContext } from '../index.js';
4
- const reusedInstance = new MigrateContext();
5
- const reusedPost1 = reusedInstance.addPost({
6
- source: {
7
- url: 'https://example.com/blog/2023/11/26/test-post/'
8
- }
9
- });
10
- reusedPost1.set('title', 'Test Post');
11
- reusedPost1.set('slug', 'test-post');
12
- reusedPost1.set('created_at', new Date('2023-11-23T12:00:00.000Z'));
13
- reusedPost1.set('updated_at', new Date('2023-11-23T12:00:00.000Z'));
14
- reusedPost1.set('published_at', new Date('2023-11-23T12:00:00.000Z'));
15
- reusedPost1.addTag({ name: 'Test Tag', slug: 'test-tag' });
16
- reusedPost1.addTag({ name: 'First Tag', slug: 'first-tag' });
17
- reusedPost1.addAuthor({ name: 'Test Author', slug: 'test-author', email: 'test@example.com' });
18
- reusedPost1.addAuthor({ name: 'First Author', slug: 'first-author', email: 'first@example.com' });
19
- const reusedPost2 = reusedInstance.addPost({
20
- source: {
21
- url: 'https://example.com/blog/2023/11/26/another-post/'
22
- }
23
- });
24
- reusedPost2.set('title', 'Another Post');
25
- reusedPost2.set('slug', 'another-post');
26
- reusedPost2.set('created_at', new Date('2023-11-24T12:00:00.000Z'));
27
- reusedPost2.set('updated_at', new Date('2023-11-24T12:00:00.000Z'));
28
- reusedPost2.set('published_at', new Date('2023-11-24T12:00:00.000Z'));
29
- reusedPost2.addTag({ name: 'Test Tag', slug: 'test-tag' });
30
- reusedPost2.addTag({ name: 'Second Tag', slug: 'second-tag' });
31
- reusedPost2.addAuthor({ name: 'Test Author', slug: 'test-author', email: 'test@example.com' });
32
- reusedPost2.addAuthor({ name: 'Second Author', slug: 'second-author', email: 'second@example.com' });
2
+ import { describe, it, before, after, mock } from 'node:test';
3
+ import { tmpdir } from 'node:os';
4
+ import { join } from 'node:path';
5
+ import { readFile, unlink, rm } from 'node:fs/promises';
6
+ import errors from '@tryghost/errors';
7
+ import { MigrateContext, PostContext, TagContext, AuthorContext } from '../index.js';
8
+ import { withTransaction, findPostsByIds } from '../lib/db-helpers.js';
33
9
  describe('MigrateContext', () => {
34
10
  it('Is instance of', () => {
35
11
  const instance = new MigrateContext();
36
12
  assert.equal(instance instanceof MigrateContext, true);
37
13
  });
38
- it('Can add posts', () => {
14
+ it('Throws when accessing db before init', () => {
39
15
  const instance = new MigrateContext();
40
- const post1 = instance.addPost();
16
+ assert.throws(() => instance.db, {
17
+ name: 'InternalServerError',
18
+ message: 'Database not initialized. Call init() first.'
19
+ });
20
+ });
21
+ it('Can init and close', async () => {
22
+ const instance = new MigrateContext();
23
+ await instance.init();
24
+ assert.ok(instance.db);
25
+ await instance.close();
26
+ });
27
+ it('Can use file-based DB with dbPath', async () => {
28
+ const filePath = join(tmpdir(), `mg-context-db-test-${Date.now()}.sqlite`);
29
+ const instance = new MigrateContext({ dbPath: filePath });
30
+ await instance.init();
31
+ const post = await instance.addPost();
32
+ post.set('title', 'File DB Post');
33
+ post.set('slug', 'file-db-post');
34
+ post.set('created_at', new Date('2023-11-23T12:00:00.000Z'));
35
+ await post.save(instance.db);
36
+ const posts = await instance.getAllPosts();
37
+ assert.equal(posts.length, 1);
38
+ assert.equal(posts[0].data.title, 'File DB Post');
39
+ await instance.close();
40
+ await unlink(filePath);
41
+ });
42
+ it('Can add posts', async () => {
43
+ const instance = new MigrateContext();
44
+ await instance.init();
45
+ const post1 = await instance.addPost();
41
46
  post1.set('title', 'Test Post');
42
47
  post1.set('slug', 'test-post');
43
48
  post1.set('created_at', new Date('2023-11-23T12:00:00.000Z'));
44
49
  post1.set('updated_at', new Date('2023-11-23T12:00:00.000Z'));
45
50
  post1.set('published_at', new Date('2023-11-23T12:00:00.000Z'));
46
- const post2 = instance.addPost();
51
+ await post1.save(instance.db);
52
+ const post2 = await instance.addPost();
47
53
  post2.set('title', 'Another Post');
48
54
  post2.set('slug', 'another-post');
49
55
  post2.set('created_at', new Date('2023-11-24T12:00:00.000Z'));
50
56
  post2.set('updated_at', new Date('2023-11-24T12:00:00.000Z'));
51
57
  post2.set('published_at', new Date('2023-11-24T12:00:00.000Z'));
52
- assert.equal(instance.allPosts.length, 2);
53
- assert.equal(instance.allPosts[0].data.title, 'Test Post');
54
- assert.equal(instance.allPosts[1].data.title, 'Another Post');
58
+ await post2.save(instance.db);
59
+ const allPosts = await instance.getAllPosts();
60
+ assert.equal(allPosts.length, 2);
61
+ assert.equal(allPosts[0].data.title, 'Test Post');
62
+ assert.equal(allPosts[1].data.title, 'Another Post');
63
+ await instance.close();
55
64
  });
56
- it('Can add existing PostContext to list of posts', () => {
65
+ it('Can add existing PostContext to list of posts', async () => {
57
66
  const instance = new MigrateContext();
67
+ await instance.init();
58
68
  const post1 = new PostContext();
59
- instance.addPost(post1);
60
69
  post1.set('title', 'Test Post');
61
70
  post1.set('slug', 'test-post');
62
71
  post1.set('created_at', new Date('2023-11-23T12:00:00.000Z'));
63
72
  post1.set('updated_at', new Date('2023-11-23T12:00:00.000Z'));
64
73
  post1.set('published_at', new Date('2023-11-23T12:00:00.000Z'));
74
+ await instance.addPost(post1);
65
75
  const post2 = new PostContext();
66
- instance.addPost(post2);
67
76
  post2.set('title', 'Another Post');
68
77
  post2.set('slug', 'another-post');
69
78
  post2.set('created_at', new Date('2023-11-24T12:00:00.000Z'));
70
79
  post2.set('updated_at', new Date('2023-11-24T12:00:00.000Z'));
71
80
  post2.set('published_at', new Date('2023-11-24T12:00:00.000Z'));
72
- assert.equal(instance.allPosts.length, 2);
73
- assert.equal(instance.allPosts[0].data.title, 'Test Post');
74
- assert.equal(instance.allPosts[1].data.title, 'Another Post');
81
+ await instance.addPost(post2);
82
+ const allPosts = await instance.getAllPosts();
83
+ assert.equal(allPosts.length, 2);
84
+ assert.equal(allPosts[0].data.title, 'Test Post');
85
+ assert.equal(allPosts[1].data.title, 'Another Post');
86
+ await instance.close();
75
87
  });
76
88
  it('Can loop over posts async', async () => {
77
89
  const instance = new MigrateContext();
78
- const post1 = instance.addPost();
90
+ await instance.init();
91
+ const post1 = await instance.addPost();
79
92
  post1.set('title', 'Test Post');
80
93
  post1.set('slug', 'test-post');
81
94
  post1.set('created_at', new Date('2023-11-23T12:00:00.000Z'));
82
95
  post1.set('updated_at', new Date('2023-11-23T12:00:00.000Z'));
83
96
  post1.set('published_at', new Date('2023-11-23T12:00:00.000Z'));
84
- const post2 = instance.addPost();
97
+ await post1.save(instance.db);
98
+ const post2 = await instance.addPost();
85
99
  post2.set('title', 'Another Post');
86
100
  post2.set('slug', 'another-post');
87
101
  post2.set('created_at', new Date('2023-11-24T12:00:00.000Z'));
88
102
  post2.set('updated_at', new Date('2023-11-24T12:00:00.000Z'));
89
103
  post2.set('published_at', new Date('2023-11-24T12:00:00.000Z'));
90
- await instance.forEachPost((post) => {
104
+ await post2.save(instance.db);
105
+ await instance.forEachPost(async (post) => {
91
106
  post.set('status', 'published');
92
107
  });
93
- assert.equal(instance.allPosts.length, 2);
94
- assert.equal(instance.allPosts[0].data.status, 'published');
95
- assert.equal(instance.allPosts[1].data.status, 'published');
108
+ const allPosts = await instance.getAllPosts();
109
+ assert.equal(allPosts.length, 2);
110
+ assert.equal(allPosts[0].data.status, 'published');
111
+ assert.equal(allPosts[1].data.status, 'published');
112
+ await instance.close();
96
113
  });
97
- it('Can loop over posts sync', () => {
114
+ it('Can loop over posts with progress option', async () => {
98
115
  const instance = new MigrateContext();
99
- const post1 = instance.addPost();
100
- post1.set('title', 'Test Post');
101
- post1.set('slug', 'test-post');
116
+ await instance.init();
117
+ const post1 = await instance.addPost();
118
+ post1.set('title', 'Post A');
119
+ post1.set('slug', 'post-a');
102
120
  post1.set('created_at', new Date('2023-11-23T12:00:00.000Z'));
103
- post1.set('updated_at', new Date('2023-11-23T12:00:00.000Z'));
104
- post1.set('published_at', new Date('2023-11-23T12:00:00.000Z'));
105
- const post2 = instance.addPost();
106
- post2.set('title', 'Another Post');
107
- post2.set('slug', 'another-post');
121
+ await post1.save(instance.db);
122
+ const post2 = await instance.addPost();
123
+ post2.set('title', 'Post B');
124
+ post2.set('slug', 'post-b');
108
125
  post2.set('created_at', new Date('2023-11-24T12:00:00.000Z'));
109
- post2.set('updated_at', new Date('2023-11-24T12:00:00.000Z'));
110
- post2.set('published_at', new Date('2023-11-24T12:00:00.000Z'));
111
- instance.forEachPostSync((post) => {
126
+ await post2.save(instance.db);
127
+ const progressCalls = [];
128
+ await instance.forEachPost(async (post) => {
112
129
  post.set('status', 'published');
130
+ }, {
131
+ batchSize: 1,
132
+ progress(processed, total) {
133
+ progressCalls.push([processed, total]);
134
+ }
113
135
  });
114
- assert.equal(instance.allPosts.length, 2);
115
- assert.equal(instance.allPosts[0].data.status, 'published');
116
- assert.equal(instance.allPosts[1].data.status, 'published');
136
+ const allPosts = await instance.getAllPosts();
137
+ assert.equal(allPosts[0].data.status, 'published');
138
+ assert.equal(allPosts[1].data.status, 'published');
139
+ assert.deepEqual(progressCalls, [[1, 2], [2, 2]]);
140
+ await instance.close();
117
141
  });
118
142
  describe('findPosts', () => {
119
- it('Can find posts by slug', () => {
120
- const foundPosts = reusedInstance.findPosts({
143
+ let reusedInstance;
144
+ before(async () => {
145
+ reusedInstance = new MigrateContext();
146
+ await reusedInstance.init();
147
+ const reusedPost1 = await reusedInstance.addPost({
148
+ source: {
149
+ url: 'https://example.com/blog/2023/11/26/test-post/'
150
+ }
151
+ });
152
+ reusedPost1.set('title', 'Test Post');
153
+ reusedPost1.set('slug', 'test-post');
154
+ reusedPost1.set('created_at', new Date('2023-11-23T12:00:00.000Z'));
155
+ reusedPost1.set('updated_at', new Date('2023-11-23T12:00:00.000Z'));
156
+ reusedPost1.set('published_at', new Date('2023-11-23T12:00:00.000Z'));
157
+ reusedPost1.addTag({ name: 'Test Tag', slug: 'test-tag' });
158
+ reusedPost1.addTag({ name: 'First Tag', slug: 'first-tag' });
159
+ reusedPost1.addAuthor({ name: 'Test Author', slug: 'test-author', email: 'test@example.com' });
160
+ reusedPost1.addAuthor({ name: 'First Author', slug: 'first-author', email: 'first@example.com' });
161
+ await reusedPost1.save(reusedInstance.db);
162
+ const reusedPost2 = await reusedInstance.addPost({
163
+ source: {
164
+ url: 'https://example.com/blog/2023/11/26/another-post/'
165
+ }
166
+ });
167
+ reusedPost2.set('title', 'Another Post');
168
+ reusedPost2.set('slug', 'another-post');
169
+ reusedPost2.set('created_at', new Date('2023-11-24T12:00:00.000Z'));
170
+ reusedPost2.set('updated_at', new Date('2023-11-24T12:00:00.000Z'));
171
+ reusedPost2.set('published_at', new Date('2023-11-24T12:00:00.000Z'));
172
+ reusedPost2.addTag({ name: 'Test Tag', slug: 'test-tag' });
173
+ reusedPost2.addTag({ name: 'Second Tag', slug: 'second-tag' });
174
+ reusedPost2.addAuthor({ name: 'Test Author', slug: 'test-author', email: 'test@example.com' });
175
+ reusedPost2.addAuthor({ name: 'Second Author', slug: 'second-author', email: 'second@example.com' });
176
+ await reusedPost2.save(reusedInstance.db);
177
+ });
178
+ after(async () => {
179
+ await reusedInstance.close();
180
+ });
181
+ it('Can find posts by slug', async () => {
182
+ const foundPosts = await reusedInstance.findPosts({
121
183
  slug: 'another-post'
122
184
  });
123
185
  assert.equal(foundPosts.length, 1);
124
186
  assert.equal(foundPosts[0].data.title, 'Another Post');
125
187
  });
126
- it('Can find posts by title', () => {
127
- const foundPosts = reusedInstance.findPosts({
188
+ it('Can find posts by title', async () => {
189
+ const foundPosts = await reusedInstance.findPosts({
128
190
  title: 'Another Post'
129
191
  });
130
192
  assert.equal(foundPosts.length, 1);
131
193
  assert.equal(foundPosts[0].data.title, 'Another Post');
132
194
  });
133
- it('Can find posts by source', () => {
134
- const foundPosts = reusedInstance.findPosts({
195
+ it('Can find posts by source', async () => {
196
+ const foundPosts = await reusedInstance.findPosts({
135
197
  sourceAttr: {
136
198
  key: 'url',
137
199
  value: 'https://example.com/blog/2023/11/26/test-post/'
@@ -140,143 +202,1545 @@ describe('MigrateContext', () => {
140
202
  assert.equal(foundPosts.length, 1);
141
203
  assert.equal(foundPosts[0].data.title, 'Test Post');
142
204
  });
143
- it('Can find posts by tag slug', () => {
144
- const foundPosts = reusedInstance.findPosts({
205
+ it('Can find posts by tag slug', async () => {
206
+ const foundPosts = await reusedInstance.findPosts({
145
207
  tagSlug: 'second-tag'
146
208
  });
147
209
  assert.equal(foundPosts.length, 1);
148
210
  assert.equal(foundPosts[0].data.title, 'Another Post');
149
211
  });
150
- it('Can find posts by tag name', () => {
151
- const foundPosts = reusedInstance.findPosts({
212
+ it('Can find posts by tag name', async () => {
213
+ const foundPosts = await reusedInstance.findPosts({
152
214
  tagName: 'Second Tag'
153
215
  });
154
216
  assert.equal(foundPosts.length, 1);
155
217
  assert.equal(foundPosts[0].data.title, 'Another Post');
156
218
  });
157
- it('Can find posts by author slug', () => {
158
- const foundPosts = reusedInstance.findPosts({
219
+ it('Can find posts by author slug', async () => {
220
+ const foundPosts = await reusedInstance.findPosts({
159
221
  authorSlug: 'second-author'
160
222
  });
161
223
  assert.equal(foundPosts.length, 1);
162
224
  assert.equal(foundPosts[0].data.title, 'Another Post');
163
225
  });
164
- it('Can find posts by author name', () => {
165
- const foundPosts = reusedInstance.findPosts({
226
+ it('Can find posts by author name', async () => {
227
+ const foundPosts = await reusedInstance.findPosts({
166
228
  authorName: 'Second Author'
167
229
  });
168
230
  assert.equal(foundPosts.length, 1);
169
231
  assert.equal(foundPosts[0].data.title, 'Another Post');
170
232
  });
171
- it('Can find posts by author email', () => {
172
- const foundPosts = reusedInstance.findPosts({
233
+ it('Can find posts by author email', async () => {
234
+ const foundPosts = await reusedInstance.findPosts({
173
235
  authorEmail: 'second@example.com'
174
236
  });
175
237
  assert.equal(foundPosts.length, 1);
176
238
  assert.equal(foundPosts[0].data.title, 'Another Post');
177
239
  });
178
- it('Returns null if no filter provided', () => {
179
- const foundPosts = reusedInstance.findPosts({});
240
+ it('Returns null if no filter provided', async () => {
241
+ const foundPosts = await reusedInstance.findPosts({});
180
242
  assert.equal(foundPosts, null);
181
243
  });
244
+ it('Returns empty array for non-existent tag slug', async () => {
245
+ const found = await reusedInstance.findPosts({ tagSlug: 'nonexistent-tag' });
246
+ assert.deepEqual(found, []);
247
+ });
248
+ it('Returns empty array for non-existent author slug', async () => {
249
+ const found = await reusedInstance.findPosts({ authorSlug: 'nonexistent-author' });
250
+ assert.deepEqual(found, []);
251
+ });
252
+ it('Returns empty array for non-existent author email', async () => {
253
+ const found = await reusedInstance.findPosts({ authorEmail: 'nonexistent@example.com' });
254
+ assert.deepEqual(found, []);
255
+ });
182
256
  });
183
257
  describe('findTags', () => {
184
- it('Can find tags by slug', () => {
185
- const foundTags = reusedInstance.findTags({
258
+ let reusedInstance;
259
+ before(async () => {
260
+ reusedInstance = new MigrateContext();
261
+ await reusedInstance.init();
262
+ const post1 = await reusedInstance.addPost();
263
+ post1.set('title', 'Test Post');
264
+ post1.set('slug', 'test-post');
265
+ post1.set('created_at', new Date('2023-11-23T12:00:00.000Z'));
266
+ post1.addTag({ name: 'Test Tag', slug: 'test-tag' });
267
+ post1.addTag({ name: 'First Tag', slug: 'first-tag' });
268
+ await post1.save(reusedInstance.db);
269
+ const post2 = await reusedInstance.addPost();
270
+ post2.set('title', 'Another Post');
271
+ post2.set('slug', 'another-post');
272
+ post2.set('created_at', new Date('2023-11-24T12:00:00.000Z'));
273
+ post2.addTag({ name: 'Test Tag', slug: 'test-tag' });
274
+ post2.addTag({ name: 'Second Tag', slug: 'second-tag' });
275
+ await post2.save(reusedInstance.db);
276
+ });
277
+ after(async () => {
278
+ await reusedInstance.close();
279
+ });
280
+ it('Can find tags by slug', async () => {
281
+ const foundTags = await reusedInstance.findTags({
186
282
  slug: 'second-tag'
187
283
  });
188
284
  assert.equal(foundTags.length, 1);
189
285
  assert.equal(foundTags[0].data.name, 'Second Tag');
190
286
  });
191
- it('Can find tags by name', () => {
192
- const foundTags = reusedInstance.findTags({
287
+ it('Can find tags by name', async () => {
288
+ const foundTags = await reusedInstance.findTags({
193
289
  name: 'Second Tag'
194
290
  });
195
291
  assert.equal(foundTags.length, 1);
196
292
  assert.equal(foundTags[0].data.name, 'Second Tag');
197
293
  });
198
- it('Returns null if no filter provided', () => {
199
- const foundTags = reusedInstance.findTags({});
294
+ it('Returns null if no filter provided', async () => {
295
+ const foundTags = await reusedInstance.findTags({});
200
296
  assert.equal(foundTags, null);
201
297
  });
202
298
  });
203
299
  describe('findAuthors', () => {
204
- it('Can find authors by slug', () => {
205
- const foundAuthors = reusedInstance.findAuthors({
300
+ let reusedInstance;
301
+ before(async () => {
302
+ reusedInstance = new MigrateContext();
303
+ await reusedInstance.init();
304
+ const post1 = await reusedInstance.addPost();
305
+ post1.set('title', 'Test Post');
306
+ post1.set('slug', 'test-post');
307
+ post1.set('created_at', new Date('2023-11-23T12:00:00.000Z'));
308
+ post1.addAuthor({ name: 'Test Author', slug: 'test-author', email: 'test@example.com' });
309
+ post1.addAuthor({ name: 'First Author', slug: 'first-author', email: 'first@example.com' });
310
+ await post1.save(reusedInstance.db);
311
+ const post2 = await reusedInstance.addPost();
312
+ post2.set('title', 'Another Post');
313
+ post2.set('slug', 'another-post');
314
+ post2.set('created_at', new Date('2023-11-24T12:00:00.000Z'));
315
+ post2.addAuthor({ name: 'Test Author', slug: 'test-author', email: 'test@example.com' });
316
+ post2.addAuthor({ name: 'Second Author', slug: 'second-author', email: 'second@example.com' });
317
+ await post2.save(reusedInstance.db);
318
+ });
319
+ after(async () => {
320
+ await reusedInstance.close();
321
+ });
322
+ it('Can find authors by slug', async () => {
323
+ const foundAuthors = await reusedInstance.findAuthors({
206
324
  slug: 'second-author'
207
325
  });
208
326
  assert.equal(foundAuthors.length, 1);
209
327
  assert.equal(foundAuthors[0].data.name, 'Second Author');
210
328
  });
211
- it('Can find authors by name', () => {
212
- const foundAuthors = reusedInstance.findAuthors({
329
+ it('Can find authors by name', async () => {
330
+ const foundAuthors = await reusedInstance.findAuthors({
213
331
  name: 'Second Author'
214
332
  });
215
333
  assert.equal(foundAuthors.length, 1);
216
334
  assert.equal(foundAuthors[0].data.name, 'Second Author');
217
335
  });
218
- it('Can find authors by email', () => {
219
- const foundAuthors = reusedInstance.findAuthors({
336
+ it('Can find authors by email', async () => {
337
+ const foundAuthors = await reusedInstance.findAuthors({
220
338
  email: 'second@example.com'
221
339
  });
222
340
  assert.equal(foundAuthors.length, 1);
223
341
  assert.equal(foundAuthors[0].data.name, 'Second Author');
224
342
  });
225
- it('Returns null if no filter provided', () => {
226
- const foundTags = reusedInstance.findAuthors({});
343
+ it('Returns null if no filter provided', async () => {
344
+ const foundTags = await reusedInstance.findAuthors({});
227
345
  assert.equal(foundTags, null);
228
346
  });
229
347
  });
348
+ describe('forEachGhostPost', () => {
349
+ it('Iterates all posts with valid Ghost JSON', async () => {
350
+ const instance = new MigrateContext();
351
+ await instance.init();
352
+ const post1 = await instance.addPost();
353
+ post1.set('title', 'Ghost Post 1');
354
+ post1.set('slug', 'ghost-post-1');
355
+ post1.set('created_at', new Date('2023-11-23T12:00:00.000Z'));
356
+ post1.addTag({ name: 'Tag A', slug: 'tag-a' });
357
+ post1.addAuthor({ name: 'Author A', slug: 'author-a', email: 'a@example.com' });
358
+ await post1.save(instance.db);
359
+ const post2 = await instance.addPost();
360
+ post2.set('title', 'Ghost Post 2');
361
+ post2.set('slug', 'ghost-post-2');
362
+ post2.set('created_at', new Date('2023-11-24T12:00:00.000Z'));
363
+ post2.addTag({ name: 'Tag B', slug: 'tag-b' });
364
+ post2.addAuthor({ name: 'Author B', slug: 'author-b', email: 'b@example.com' });
365
+ await post2.save(instance.db);
366
+ const collected = [];
367
+ await instance.forEachGhostPost(async (json, post) => {
368
+ collected.push({ json, post });
369
+ });
370
+ assert.equal(collected.length, 2);
371
+ // Each call receives a flat post object with tags and authors inline
372
+ for (const { json } of collected) {
373
+ assert.ok(json.title);
374
+ assert.ok(json.slug);
375
+ assert.ok(Array.isArray(json.tags));
376
+ assert.ok(Array.isArray(json.authors));
377
+ }
378
+ // Correct post data
379
+ assert.equal(collected[0].json.title, 'Ghost Post 1');
380
+ assert.equal(collected[1].json.title, 'Ghost Post 2');
381
+ // Tags and authors are flat objects (no data wrapper)
382
+ assert.equal(collected[0].json.tags[0].slug, 'tag-a');
383
+ assert.equal(collected[0].json.authors[0].email, 'a@example.com');
384
+ // PostContext is also passed
385
+ assert.equal(collected[0].post.data.title, 'Ghost Post 1');
386
+ assert.equal(collected[1].post.data.title, 'Ghost Post 2');
387
+ await instance.close();
388
+ });
389
+ it('Fires progress callback', async () => {
390
+ const instance = new MigrateContext();
391
+ await instance.init();
392
+ for (let i = 1; i <= 3; i++) {
393
+ const post = await instance.addPost();
394
+ post.set('title', `Progress Post ${i}`);
395
+ post.set('slug', `progress-post-${i}`);
396
+ post.set('created_at', new Date('2023-11-23T12:00:00.000Z'));
397
+ await post.save(instance.db);
398
+ }
399
+ const progressCalls = [];
400
+ await instance.forEachGhostPost(async () => { }, {
401
+ batchSize: 2,
402
+ progress(processed, total) {
403
+ progressCalls.push([processed, total]);
404
+ }
405
+ });
406
+ assert.deepEqual(progressCalls, [[2, 3], [3, 3]]);
407
+ await instance.close();
408
+ });
409
+ it('Does not persist callback mutations', async () => {
410
+ const instance = new MigrateContext();
411
+ await instance.init();
412
+ const post = await instance.addPost();
413
+ post.set('title', 'Original Title');
414
+ post.set('slug', 'original-title');
415
+ post.set('created_at', new Date('2023-11-23T12:00:00.000Z'));
416
+ await post.save(instance.db);
417
+ await instance.forEachGhostPost(async (_json, p) => {
418
+ p.set('title', 'Mutated Title');
419
+ });
420
+ const allPosts = await instance.getAllPosts();
421
+ assert.equal(allPosts[0].data.title, 'Original Title');
422
+ await instance.close();
423
+ });
424
+ });
230
425
  it('Can return Ghost JSON', async () => {
231
- const ghostJSON = await reusedInstance.ghostJson;
426
+ const instance = new MigrateContext();
427
+ await instance.init();
428
+ const post1 = await instance.addPost({
429
+ source: { url: 'https://example.com/blog/2023/11/26/test-post/' }
430
+ });
431
+ post1.set('title', 'Test Post');
432
+ post1.set('slug', 'test-post');
433
+ post1.set('created_at', new Date('2023-11-23T12:00:00.000Z'));
434
+ post1.set('updated_at', new Date('2023-11-23T12:00:00.000Z'));
435
+ post1.set('published_at', new Date('2023-11-23T12:00:00.000Z'));
436
+ post1.set('meta_title', 'SEO Title');
437
+ post1.addTag({ name: 'Test Tag', slug: 'test-tag' });
438
+ post1.addAuthor({ name: 'Test Author', slug: 'test-author', email: 'test@example.com' });
439
+ await post1.save(instance.db);
440
+ const post2 = await instance.addPost({
441
+ source: { url: 'https://example.com/blog/2023/11/26/another-post/' }
442
+ });
443
+ post2.set('title', 'Another Post');
444
+ post2.set('slug', 'another-post');
445
+ post2.set('created_at', new Date('2023-11-24T12:00:00.000Z'));
446
+ post2.set('updated_at', new Date('2023-11-24T12:00:00.000Z'));
447
+ post2.set('published_at', new Date('2023-11-24T12:00:00.000Z'));
448
+ post2.addTag({ name: 'Test Tag', slug: 'test-tag' });
449
+ post2.addAuthor({ name: 'Test Author', slug: 'test-author', email: 'test@example.com' });
450
+ await post2.save(instance.db);
451
+ const writtenFiles = await instance.writeGhostJson(tmpdir());
452
+ assert.equal(writtenFiles.length, 1);
453
+ assert.equal(writtenFiles[0].posts, 2);
454
+ assert.ok(writtenFiles[0].size > 0);
455
+ assert.equal(writtenFiles[0].name, 'posts.json');
456
+ const ghostJSON = JSON.parse(await readFile(writtenFiles[0].path, 'utf-8'));
232
457
  assert.deepEqual(Object.keys(ghostJSON), ['meta', 'data']);
233
458
  assert.deepEqual(Object.keys(ghostJSON.data), ['posts', 'users', 'tags', 'posts_authors', 'posts_tags', 'posts_meta']);
234
459
  assert.deepEqual(ghostJSON.data.posts.length, 2);
460
+ assert.equal(ghostJSON.data.posts_meta.length, 1);
461
+ assert.equal(ghostJSON.data.posts_meta[0].meta_title, 'SEO Title');
462
+ await unlink(writtenFiles[0].path);
463
+ await instance.close();
464
+ });
465
+ it('Exports sort_order in posts_tags and posts_authors', async () => {
466
+ const instance = new MigrateContext();
467
+ await instance.init();
468
+ const post = await instance.addPost();
469
+ post.set('title', 'Sort Order Test');
470
+ post.set('slug', 'sort-order-test');
471
+ post.set('created_at', new Date('2023-11-23T12:00:00.000Z'));
472
+ post.addTag({ name: 'Tag A', slug: 'tag-a' });
473
+ post.addTag({ name: 'Tag B', slug: 'tag-b' });
474
+ post.addTag({ name: 'Tag C', slug: 'tag-c' });
475
+ post.addAuthor({ name: 'Author A', slug: 'author-a', email: 'a@example.com' });
476
+ post.addAuthor({ name: 'Author B', slug: 'author-b', email: 'b@example.com' });
477
+ await post.save(instance.db);
478
+ const writtenFiles = await instance.writeGhostJson(tmpdir(), { filename: 'sort-order-test' });
479
+ const ghostJSON = JSON.parse(await readFile(writtenFiles[0].path, 'utf-8'));
480
+ assert.equal(ghostJSON.data.posts_tags.length, 3);
481
+ assert.equal(ghostJSON.data.posts_tags[0].sort_order, 1);
482
+ assert.equal(ghostJSON.data.posts_tags[1].sort_order, 2);
483
+ assert.equal(ghostJSON.data.posts_tags[2].sort_order, 3);
484
+ assert.equal(ghostJSON.data.posts_authors.length, 2);
485
+ assert.equal(ghostJSON.data.posts_authors[0].sort_order, 1);
486
+ assert.equal(ghostJSON.data.posts_authors[1].sort_order, 2);
487
+ await unlink(writtenFiles[0].path);
488
+ await instance.close();
489
+ });
490
+ it('Preserves sort_order after reordering tags', async () => {
491
+ const instance = new MigrateContext();
492
+ await instance.init();
493
+ const post = await instance.addPost();
494
+ post.set('title', 'Reorder Test');
495
+ post.set('slug', 'reorder-test');
496
+ post.set('created_at', new Date('2023-11-23T12:00:00.000Z'));
497
+ post.addTag({ name: 'Alpha', slug: 'alpha' });
498
+ post.addTag({ name: 'Beta', slug: 'beta' });
499
+ post.addTag({ name: 'Gamma', slug: 'gamma' });
500
+ post.addAuthor({ name: 'Test Author', slug: 'test-author', email: 'test@example.com' });
501
+ await post.save(instance.db);
502
+ // Reload and reorder
503
+ const posts = await instance.getAllPosts();
504
+ const loaded = posts[0];
505
+ loaded.setPrimaryTag({ name: 'Gamma', slug: 'gamma' });
506
+ loaded.save(instance.db);
507
+ const writtenFiles = await instance.writeGhostJson(tmpdir(), { filename: 'reorder-test' });
508
+ const ghostJSON = JSON.parse(await readFile(writtenFiles[0].path, 'utf-8'));
509
+ // Gamma should now be sort_order 1 (primary)
510
+ const gammaTag = ghostJSON.data.tags.find((t) => t.slug === 'gamma');
511
+ const gammaJoin = ghostJSON.data.posts_tags.find((pt) => pt.tag_id === gammaTag.id);
512
+ assert.equal(gammaJoin.sort_order, 1);
513
+ // Alpha should now be sort_order 2
514
+ const alphaTag = ghostJSON.data.tags.find((t) => t.slug === 'alpha');
515
+ const alphaJoin = ghostJSON.data.posts_tags.find((pt) => pt.tag_id === alphaTag.id);
516
+ assert.equal(alphaJoin.sort_order, 2);
517
+ await unlink(writtenFiles[0].path);
518
+ await instance.close();
519
+ });
520
+ it('Can write Ghost JSON to file', async () => {
521
+ const instance = new MigrateContext();
522
+ await instance.init();
523
+ const post = await instance.addPost();
524
+ post.set('title', 'File Test Post');
525
+ post.set('slug', 'file-test-post');
526
+ post.set('created_at', new Date('2023-11-23T12:00:00.000Z'));
527
+ post.addAuthor({ name: 'Test Author', slug: 'test-author', email: 'test@example.com' });
528
+ await post.save(instance.db);
529
+ const writtenFiles = await instance.writeGhostJson(tmpdir(), { filename: 'file-test' });
530
+ assert.equal(writtenFiles.length, 1);
531
+ assert.equal(writtenFiles[0].name, 'file-test.json');
532
+ const fileContent = JSON.parse(await readFile(writtenFiles[0].path, 'utf-8'));
533
+ assert.deepEqual(Object.keys(fileContent), ['meta', 'data']);
534
+ assert.deepEqual(fileContent.data.posts.length, 1);
535
+ await unlink(writtenFiles[0].path);
536
+ await instance.close();
537
+ });
538
+ it('Can write batched Ghost JSON files', async () => {
539
+ const instance = new MigrateContext();
540
+ await instance.init();
541
+ // Create 3 posts with different tags/authors
542
+ for (let i = 1; i <= 3; i++) {
543
+ const post = await instance.addPost();
544
+ post.set('title', `Batch Post ${i}`);
545
+ post.set('slug', `batch-post-${i}`);
546
+ post.set('created_at', new Date('2023-11-23T12:00:00.000Z'));
547
+ post.addTag({ name: 'Shared Tag', slug: 'shared-tag' });
548
+ post.addTag({ name: `Tag ${i}`, slug: `tag-${i}` });
549
+ post.addAuthor({ name: 'Shared Author', slug: 'shared-author', email: 'shared@example.com' });
550
+ await post.save(instance.db);
551
+ }
552
+ const writtenFiles = await instance.writeGhostJson(tmpdir(), { batchSize: 2, filename: 'batch-test' });
553
+ assert.equal(writtenFiles.length, 2);
554
+ assert.equal(writtenFiles[0].name, 'batch-test-1.json');
555
+ assert.equal(writtenFiles[1].name, 'batch-test-2.json');
556
+ assert.equal(writtenFiles[0].posts, 2);
557
+ assert.equal(writtenFiles[1].posts, 1);
558
+ const batch1 = JSON.parse(await readFile(writtenFiles[0].path, 'utf-8'));
559
+ const batch2 = JSON.parse(await readFile(writtenFiles[1].path, 'utf-8'));
560
+ // Batch 1 has 2 posts, batch 2 has 1 post
561
+ assert.equal(batch1.data.posts.length, 2);
562
+ assert.equal(batch2.data.posts.length, 1);
563
+ // Each batch includes the tags for its posts
564
+ assert.ok(batch1.data.tags.length >= 2);
565
+ assert.ok(batch2.data.tags.length >= 1);
566
+ // Shared tag appears in both batches with the same ID
567
+ const batch1SharedTag = batch1.data.tags.find((t) => t.slug === 'shared-tag');
568
+ const batch2SharedTag = batch2.data.tags.find((t) => t.slug === 'shared-tag');
569
+ assert.ok(batch1SharedTag);
570
+ assert.ok(batch2SharedTag);
571
+ assert.equal(batch1SharedTag.id, batch2SharedTag.id);
572
+ // Shared author appears in both batches with the same ID
573
+ const batch1SharedAuthor = batch1.data.users.find((u) => u.slug === 'shared-author');
574
+ const batch2SharedAuthor = batch2.data.users.find((u) => u.slug === 'shared-author');
575
+ assert.ok(batch1SharedAuthor);
576
+ assert.ok(batch2SharedAuthor);
577
+ assert.equal(batch1SharedAuthor.id, batch2SharedAuthor.id);
578
+ for (const f of writtenFiles) {
579
+ await unlink(f.path);
580
+ }
581
+ await instance.close();
582
+ });
583
+ it('Strips .json extension from filename option', async () => {
584
+ const instance = new MigrateContext();
585
+ await instance.init();
586
+ const writtenFiles = await instance.writeGhostJson(tmpdir(), { filename: 'export.json' });
587
+ assert.equal(writtenFiles.length, 1);
588
+ assert.equal(writtenFiles[0].name, 'export.json');
589
+ assert.ok(!writtenFiles[0].name.includes('.json.json'));
590
+ await unlink(writtenFiles[0].path);
591
+ await instance.close();
592
+ });
593
+ it('Creates output directory if it does not exist', async () => {
594
+ const instance = new MigrateContext();
595
+ await instance.init();
596
+ const topDir = join(tmpdir(), `mg-context-mkdir-test-${Date.now()}`);
597
+ const nestedDir = join(topDir, 'sub', 'dir');
598
+ const writtenFiles = await instance.writeGhostJson(nestedDir);
599
+ assert.equal(writtenFiles.length, 1);
600
+ assert.ok(writtenFiles[0].path.startsWith(nestedDir));
601
+ await rm(topDir, { recursive: true });
602
+ await instance.close();
603
+ });
604
+ it('Can write Ghost JSON with empty context', async () => {
605
+ const instance = new MigrateContext();
606
+ await instance.init();
607
+ const writtenFiles = await instance.writeGhostJson(tmpdir(), { filename: 'empty-test' });
608
+ assert.equal(writtenFiles.length, 1);
609
+ assert.equal(writtenFiles[0].posts, 0);
610
+ assert.equal(writtenFiles[0].name, 'empty-test.json');
611
+ const content = JSON.parse(await readFile(writtenFiles[0].path, 'utf-8'));
612
+ assert.deepEqual(Object.keys(content), ['meta', 'data']);
613
+ assert.equal(content.data.posts.length, 0);
614
+ await unlink(writtenFiles[0].path);
615
+ await instance.close();
235
616
  });
236
617
  describe('Ghost JSON content formats', () => {
237
618
  it('Can export with HTML only', async () => {
238
- const instance = new MigrateContext();
239
- const post = instance.addPost();
619
+ const instance = new MigrateContext({ contentFormat: 'html' });
620
+ await instance.init();
621
+ const post = await instance.addPost();
240
622
  post.set('title', 'HTML Only Post');
241
623
  post.set('slug', 'html-only-post');
242
624
  post.set('created_at', new Date('2023-11-23T12:00:00.000Z'));
243
625
  post.set('html', '<p>Hello world</p>');
244
626
  post.addAuthor({ name: 'Test Author', slug: 'test-author', email: 'test@example.com' });
245
- const ghostJSON = await instance.ghostJson;
627
+ await post.save(instance.db);
628
+ const writtenFiles = await instance.writeGhostJson(tmpdir(), { filename: 'html-test' });
629
+ const ghostJSON = JSON.parse(await readFile(writtenFiles[0].path, 'utf-8'));
246
630
  assert.equal(ghostJSON.data.posts.length, 1);
247
631
  assert.equal(ghostJSON.data.posts[0].html, '<p>Hello world</p>');
248
632
  assert.equal(ghostJSON.data.posts[0].mobiledoc, null);
249
633
  assert.equal(ghostJSON.data.posts[0].lexical, null);
634
+ await unlink(writtenFiles[0].path);
635
+ await instance.close();
250
636
  });
251
637
  it('Can export with Lexical only', async () => {
252
638
  const instance = new MigrateContext({ contentFormat: 'lexical' });
253
- const post = instance.addPost();
639
+ await instance.init();
640
+ const post = await instance.addPost();
254
641
  post.set('title', 'Lexical Only Post');
255
642
  post.set('slug', 'lexical-only-post');
256
643
  post.set('created_at', new Date('2023-11-23T12:00:00.000Z'));
257
644
  post.set('html', '<p>Hello world</p>');
258
645
  post.addAuthor({ name: 'Test Author', slug: 'test-author', email: 'test@example.com' });
259
- const ghostJSON = await instance.ghostJson;
646
+ await post.save(instance.db);
647
+ const writtenFiles = await instance.writeGhostJson(tmpdir(), { filename: 'lexical-test' });
648
+ const ghostJSON = JSON.parse(await readFile(writtenFiles[0].path, 'utf-8'));
260
649
  assert.equal(ghostJSON.data.posts.length, 1);
261
650
  assert.equal(ghostJSON.data.posts[0].html, null);
262
651
  assert.ok(ghostJSON.data.posts[0].lexical);
263
- assert.equal(typeof ghostJSON.data.posts[0].lexical, 'object');
652
+ assert.equal(typeof ghostJSON.data.posts[0].lexical, 'string');
653
+ assert.ok(JSON.parse(ghostJSON.data.posts[0].lexical).root);
264
654
  assert.equal(ghostJSON.data.posts[0].mobiledoc, null);
655
+ await unlink(writtenFiles[0].path);
656
+ await instance.close();
265
657
  });
266
658
  it('Can export with Mobiledoc only', async () => {
267
659
  const instance = new MigrateContext({ contentFormat: 'mobiledoc' });
268
- const post = instance.addPost();
660
+ await instance.init();
661
+ const post = await instance.addPost();
269
662
  post.set('title', 'Mobiledoc Only Post');
270
663
  post.set('slug', 'mobiledoc-only-post');
271
664
  post.set('created_at', new Date('2023-11-23T12:00:00.000Z'));
272
665
  post.set('html', '<p>Hello world</p>');
273
666
  post.addAuthor({ name: 'Test Author', slug: 'test-author', email: 'test@example.com' });
274
- const ghostJSON = await instance.ghostJson;
667
+ await post.save(instance.db);
668
+ const writtenFiles = await instance.writeGhostJson(tmpdir(), { filename: 'mobiledoc-test' });
669
+ const ghostJSON = JSON.parse(await readFile(writtenFiles[0].path, 'utf-8'));
275
670
  assert.equal(ghostJSON.data.posts.length, 1);
276
671
  assert.equal(ghostJSON.data.posts[0].html, null);
277
672
  assert.ok(ghostJSON.data.posts[0].mobiledoc);
278
- assert.equal(typeof ghostJSON.data.posts[0].mobiledoc, 'object');
673
+ assert.equal(typeof ghostJSON.data.posts[0].mobiledoc, 'string');
674
+ assert.ok(JSON.parse(ghostJSON.data.posts[0].mobiledoc).version);
279
675
  assert.equal(ghostJSON.data.posts[0].lexical, null);
676
+ await unlink(writtenFiles[0].path);
677
+ await instance.close();
678
+ });
679
+ });
680
+ describe('Standalone save', () => {
681
+ it('Can update a tag with existing dbId', async () => {
682
+ const instance = new MigrateContext();
683
+ await instance.init();
684
+ const post = await instance.addPost();
685
+ post.set('title', 'Tag Update Test');
686
+ post.set('slug', 'tag-update-test');
687
+ post.set('created_at', new Date('2023-11-23T12:00:00.000Z'));
688
+ post.addTag({ name: 'Original Name', slug: 'update-tag' });
689
+ await post.save(instance.db);
690
+ // Load the tag from DB, modify it, and save again (covers dbId UPDATE branch)
691
+ const tags = await instance.findTags({ slug: 'update-tag' });
692
+ assert.equal(tags.length, 1);
693
+ tags[0].set('name', 'Updated Name');
694
+ await tags[0].save(instance.db);
695
+ const updatedTags = await instance.findTags({ slug: 'update-tag' });
696
+ assert.equal(updatedTags[0].data.name, 'Updated Name');
697
+ await instance.close();
698
+ });
699
+ it('Can update an author with existing dbId', async () => {
700
+ const instance = new MigrateContext();
701
+ await instance.init();
702
+ const post = await instance.addPost();
703
+ post.set('title', 'Author Update Test');
704
+ post.set('slug', 'author-update-test');
705
+ post.set('created_at', new Date('2023-11-23T12:00:00.000Z'));
706
+ post.addAuthor({ name: 'Original Author', slug: 'update-author', email: 'update@example.com' });
707
+ await post.save(instance.db);
708
+ // Load the author from DB, modify it, and save again (covers dbId UPDATE branch)
709
+ const authors = await instance.findAuthors({ slug: 'update-author' });
710
+ assert.equal(authors.length, 1);
711
+ authors[0].set('name', 'Updated Author');
712
+ await authors[0].save(instance.db);
713
+ const updatedAuthors = await instance.findAuthors({ slug: 'update-author' });
714
+ assert.equal(updatedAuthors[0].data.name, 'Updated Author');
715
+ await instance.close();
716
+ });
717
+ it('Can save a tag without a slug', async () => {
718
+ const instance = new MigrateContext();
719
+ await instance.init();
720
+ const tag = new TagContext({ name: 'No Slug Tag' });
721
+ await tag.save(instance.db);
722
+ assert.ok(tag.dbId);
723
+ await instance.close();
724
+ });
725
+ it('Can save an author without a slug', async () => {
726
+ const instance = new MigrateContext();
727
+ await instance.init();
728
+ const author = new AuthorContext({ name: 'No Slug Author' });
729
+ await author.save(instance.db);
730
+ assert.ok(author.dbId);
731
+ await instance.close();
732
+ });
733
+ });
734
+ describe('Post lookup_key deduplication', () => {
735
+ it('Silently skips insert when lookup_key already exists', async () => {
736
+ const instance = new MigrateContext();
737
+ await instance.init();
738
+ const post1 = await instance.addPost({ lookupKey: 'https://example.com/post-1' });
739
+ post1.set('title', 'First Post');
740
+ post1.set('slug', 'first-post');
741
+ post1.set('created_at', new Date('2023-11-23T12:00:00.000Z'));
742
+ await post1.save(instance.db);
743
+ const post2 = await instance.addPost({ lookupKey: 'https://example.com/post-1' });
744
+ post2.set('title', 'Duplicate Post');
745
+ post2.set('slug', 'duplicate-post');
746
+ post2.set('created_at', new Date('2023-11-24T12:00:00.000Z'));
747
+ await post2.save(instance.db);
748
+ const allPosts = await instance.getAllPosts();
749
+ assert.equal(allPosts.length, 1);
750
+ assert.equal(allPosts[0].data.title, 'First Post');
751
+ assert.equal(post2.dbId, post1.dbId);
752
+ await instance.close();
753
+ });
754
+ it('Posts without lookup_key always insert normally', async () => {
755
+ const instance = new MigrateContext();
756
+ await instance.init();
757
+ const post1 = await instance.addPost();
758
+ post1.set('title', 'Post A');
759
+ post1.set('slug', 'post-a');
760
+ post1.set('created_at', new Date('2023-11-23T12:00:00.000Z'));
761
+ await post1.save(instance.db);
762
+ const post2 = await instance.addPost();
763
+ post2.set('title', 'Post B');
764
+ post2.set('slug', 'post-b');
765
+ post2.set('created_at', new Date('2023-11-24T12:00:00.000Z'));
766
+ await post2.save(instance.db);
767
+ const allPosts = await instance.getAllPosts();
768
+ assert.equal(allPosts.length, 2);
769
+ await instance.close();
770
+ });
771
+ it('Different lookup_keys create separate posts', async () => {
772
+ const instance = new MigrateContext();
773
+ await instance.init();
774
+ const post1 = await instance.addPost({ lookupKey: 'https://example.com/post-1' });
775
+ post1.set('title', 'Post 1');
776
+ post1.set('slug', 'post-1');
777
+ post1.set('created_at', new Date('2023-11-23T12:00:00.000Z'));
778
+ await post1.save(instance.db);
779
+ const post2 = await instance.addPost({ lookupKey: 'https://example.com/post-2' });
780
+ post2.set('title', 'Post 2');
781
+ post2.set('slug', 'post-2');
782
+ post2.set('created_at', new Date('2023-11-24T12:00:00.000Z'));
783
+ await post2.save(instance.db);
784
+ const allPosts = await instance.getAllPosts();
785
+ assert.equal(allPosts.length, 2);
786
+ assert.notEqual(post1.dbId, post2.dbId);
787
+ await instance.close();
788
+ });
789
+ it('Can get and set lookupKey and warnOnLookupKeyDuplicate on PostContext', () => {
790
+ const post = new PostContext({ lookupKey: 'https://example.com/initial' });
791
+ assert.equal(post.lookupKey, 'https://example.com/initial');
792
+ assert.equal(post.warnOnLookupKeyDuplicate, false);
793
+ post.lookupKey = 'https://example.com/updated';
794
+ assert.equal(post.lookupKey, 'https://example.com/updated');
795
+ post.warnOnLookupKeyDuplicate = true;
796
+ assert.equal(post.warnOnLookupKeyDuplicate, true);
797
+ });
798
+ it('lookup_key round-trips through save/load', async () => {
799
+ const instance = new MigrateContext();
800
+ await instance.init();
801
+ const post = await instance.addPost({ lookupKey: 'https://example.com/round-trip' });
802
+ post.set('title', 'Round Trip Key');
803
+ post.set('slug', 'round-trip-key');
804
+ post.set('created_at', new Date('2023-11-23T12:00:00.000Z'));
805
+ await post.save(instance.db);
806
+ const loaded = await instance.getAllPosts();
807
+ assert.equal(loaded.length, 1);
808
+ assert.equal(loaded[0].lookupKey, 'https://example.com/round-trip');
809
+ await instance.close();
810
+ });
811
+ it('No warning logged when warnOnLookupKeyDuplicate is false', async () => {
812
+ const warnMock = mock.method(console, 'warn', () => { });
813
+ const instance = new MigrateContext();
814
+ await instance.init();
815
+ const post1 = await instance.addPost({ lookupKey: 'https://example.com/no-warn' });
816
+ post1.set('title', 'First');
817
+ post1.set('slug', 'first');
818
+ post1.set('created_at', new Date('2023-11-23T12:00:00.000Z'));
819
+ await post1.save(instance.db);
820
+ const post2 = await instance.addPost({ lookupKey: 'https://example.com/no-warn' });
821
+ post2.set('title', 'Duplicate');
822
+ post2.set('slug', 'duplicate');
823
+ post2.set('created_at', new Date('2023-11-24T12:00:00.000Z'));
824
+ await post2.save(instance.db);
825
+ assert.equal(warnMock.mock.calls.length, 0);
826
+ warnMock.mock.restore();
827
+ await instance.close();
828
+ });
829
+ it('Warning logged when warnOnLookupKeyDuplicate is true', async () => {
830
+ const warnMock = mock.method(console, 'warn', () => { });
831
+ const instance = new MigrateContext({ warnOnLookupKeyDuplicate: true });
832
+ await instance.init();
833
+ const post1 = await instance.addPost({ lookupKey: 'https://example.com/warn-me' });
834
+ post1.set('title', 'First');
835
+ post1.set('slug', 'first');
836
+ post1.set('created_at', new Date('2023-11-23T12:00:00.000Z'));
837
+ await post1.save(instance.db);
838
+ const post2 = await instance.addPost({ lookupKey: 'https://example.com/warn-me' });
839
+ post2.set('title', 'Duplicate');
840
+ post2.set('slug', 'duplicate');
841
+ post2.set('created_at', new Date('2023-11-24T12:00:00.000Z'));
842
+ await post2.save(instance.db);
843
+ assert.equal(warnMock.mock.calls.length, 1);
844
+ assert.ok(warnMock.mock.calls[0].arguments[0].includes('https://example.com/warn-me'));
845
+ warnMock.mock.restore();
846
+ await instance.close();
847
+ });
848
+ it('Duplicate skip does not modify existing post tags/authors', async () => {
849
+ const instance = new MigrateContext();
850
+ await instance.init();
851
+ const post1 = await instance.addPost({ lookupKey: 'https://example.com/tags-test' });
852
+ post1.set('title', 'Original');
853
+ post1.set('slug', 'original');
854
+ post1.set('created_at', new Date('2023-11-23T12:00:00.000Z'));
855
+ post1.addTag({ name: 'Original Tag', slug: 'original-tag' });
856
+ post1.addAuthor({ name: 'Original Author', slug: 'original-author', email: 'orig@example.com' });
857
+ await post1.save(instance.db);
858
+ const post2 = await instance.addPost({ lookupKey: 'https://example.com/tags-test' });
859
+ post2.set('title', 'Duplicate');
860
+ post2.set('slug', 'duplicate');
861
+ post2.set('created_at', new Date('2023-11-24T12:00:00.000Z'));
862
+ post2.addTag({ name: 'New Tag', slug: 'new-tag' });
863
+ post2.addAuthor({ name: 'New Author', slug: 'new-author', email: 'new@example.com' });
864
+ await post2.save(instance.db);
865
+ const allPosts = await instance.getAllPosts();
866
+ assert.equal(allPosts.length, 1);
867
+ assert.equal(allPosts[0].data.tags.length, 1);
868
+ assert.equal(allPosts[0].data.tags[0].data.slug, 'original-tag');
869
+ assert.equal(allPosts[0].data.authors.length, 1);
870
+ assert.equal(allPosts[0].data.authors[0].data.slug, 'original-author');
871
+ await instance.close();
872
+ });
873
+ it('lookup_key persists on update', async () => {
874
+ const instance = new MigrateContext();
875
+ await instance.init();
876
+ const post = await instance.addPost({ lookupKey: 'https://example.com/update-key' });
877
+ post.set('title', 'Before Update');
878
+ post.set('slug', 'update-key');
879
+ post.set('created_at', new Date('2023-11-23T12:00:00.000Z'));
880
+ await post.save(instance.db);
881
+ post.set('title', 'After Update');
882
+ await post.save(instance.db);
883
+ const loaded = await instance.getAllPosts();
884
+ assert.equal(loaded.length, 1);
885
+ assert.equal(loaded[0].data.title, 'After Update');
886
+ assert.equal(loaded[0].lookupKey, 'https://example.com/update-key');
887
+ await instance.close();
888
+ });
889
+ });
890
+ describe('transaction', () => {
891
+ it('Wraps operations in a single transaction', async () => {
892
+ const instance = new MigrateContext();
893
+ await instance.init();
894
+ await instance.transaction(async () => {
895
+ const post = await instance.addPost();
896
+ post.set('title', 'Transaction Post');
897
+ post.set('slug', 'txn-post');
898
+ post.set('created_at', new Date('2023-11-23T12:00:00.000Z'));
899
+ post.addTag({ name: 'Txn Tag', slug: 'txn-tag' });
900
+ post.addAuthor({ name: 'Txn Author', slug: 'txn-author', email: 'txn@example.com' });
901
+ await post.save(instance.db);
902
+ });
903
+ const allPosts = await instance.getAllPosts();
904
+ assert.equal(allPosts.length, 1);
905
+ assert.equal(allPosts[0].data.title, 'Transaction Post');
906
+ assert.equal(allPosts[0].data.tags.length, 1);
907
+ assert.equal(allPosts[0].data.authors.length, 1);
908
+ await instance.close();
909
+ });
910
+ it('Rolls back on error', async () => {
911
+ const instance = new MigrateContext();
912
+ await instance.init();
913
+ await assert.rejects(async () => {
914
+ await instance.transaction(async () => {
915
+ const post = await instance.addPost();
916
+ post.set('title', 'Will Rollback');
917
+ post.set('slug', 'will-rollback');
918
+ post.set('created_at', new Date('2023-11-23T12:00:00.000Z'));
919
+ await post.save(instance.db);
920
+ throw new errors.InternalServerError({ message: 'forced rollback' });
921
+ });
922
+ }, { message: 'forced rollback', name: 'InternalServerError' });
923
+ const allPosts = await instance.getAllPosts();
924
+ assert.equal(allPosts.length, 0);
925
+ await instance.close();
926
+ });
927
+ it('withTransaction rolls back on sync error', async () => {
928
+ const instance = new MigrateContext();
929
+ await instance.init();
930
+ const post = await instance.addPost();
931
+ post.set('title', 'Before Rollback');
932
+ post.set('slug', 'before-rollback');
933
+ post.set('created_at', new Date('2023-11-23T12:00:00.000Z'));
934
+ await post.save(instance.db);
935
+ assert.throws(() => {
936
+ withTransaction(instance.db, () => {
937
+ 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, post.dbId);
938
+ throw new errors.InternalServerError({ message: 'sync rollback' });
939
+ });
940
+ }, { message: 'sync rollback' });
941
+ const allPosts = await instance.getAllPosts();
942
+ assert.equal(allPosts[0].data.title, 'Before Rollback');
943
+ await instance.close();
944
+ });
945
+ it('withTransaction is a no-op wrapper when already in a transaction', async () => {
946
+ const instance = new MigrateContext();
947
+ await instance.init();
948
+ const post = await instance.addPost();
949
+ post.set('title', 'Nested TX');
950
+ post.set('slug', 'nested-tx');
951
+ post.set('created_at', new Date('2023-11-23T12:00:00.000Z'));
952
+ await post.save(instance.db);
953
+ // Outer transaction via ctx.transaction, inner via withTransaction
954
+ await instance.transaction(async () => {
955
+ withTransaction(instance.db, () => {
956
+ 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, post.dbId);
957
+ });
958
+ });
959
+ const allPosts = await instance.getAllPosts();
960
+ assert.equal(allPosts[0].data.title, 'Updated In Nested');
961
+ await instance.close();
962
+ });
963
+ });
964
+ describe('nested transaction', () => {
965
+ it('ctx.transaction() passes through when already in a transaction', async () => {
966
+ const instance = new MigrateContext();
967
+ await instance.init();
968
+ const post = await instance.addPost();
969
+ post.set('title', 'Outer TX');
970
+ post.set('slug', 'outer-tx');
971
+ post.set('created_at', new Date('2023-11-23T12:00:00.000Z'));
972
+ await post.save(instance.db);
973
+ await instance.transaction(async () => {
974
+ // Nested transaction should not issue BEGIN
975
+ await instance.transaction(async () => {
976
+ const posts = await instance.getAllPosts();
977
+ posts[0].set('title', 'Nested Update');
978
+ await posts[0].save(instance.db);
979
+ });
980
+ });
981
+ const allPosts = await instance.getAllPosts();
982
+ assert.equal(allPosts[0].data.title, 'Nested Update');
983
+ await instance.close();
984
+ });
985
+ });
986
+ describe('findPostsByIds', () => {
987
+ it('Returns empty array for empty ID list', async () => {
988
+ const instance = new MigrateContext();
989
+ await instance.init();
990
+ const result = findPostsByIds(instance.db, []);
991
+ assert.deepEqual(result, []);
992
+ await instance.close();
993
+ });
994
+ });
995
+ describe('init guard', () => {
996
+ it('Throws when init() is called twice without close()', async () => {
997
+ const instance = new MigrateContext();
998
+ await instance.init();
999
+ await assert.rejects(() => instance.init(), { message: 'MigrateContext is already initialized. Call close() before reinitializing.' });
1000
+ await instance.close();
1001
+ });
1002
+ });
1003
+ describe('Cache bypass paths', () => {
1004
+ it('Tag existing.update branch when slug exists in DB but not cache', async () => {
1005
+ const instance = new MigrateContext();
1006
+ await instance.init();
1007
+ // Insert tag directly into DB, bypassing the cache
1008
+ instance.db.stmts.insertTag.run(JSON.stringify({ name: 'Pre-existing', slug: 'pre-tag' }), 'pre-tag', 'Pre-existing', null);
1009
+ // Save a TagContext with the same slug — should hit the existing.update branch
1010
+ const tag = new TagContext({ name: 'Updated Pre-existing', slug: 'pre-tag' });
1011
+ await tag.save(instance.db);
1012
+ assert.ok(tag.dbId);
1013
+ const found = await instance.findTags({ slug: 'pre-tag' });
1014
+ assert.equal(found.length, 1);
1015
+ assert.equal(found[0].data.name, 'Updated Pre-existing');
1016
+ await instance.close();
1017
+ });
1018
+ it('Author existing.update branch when slug exists in DB but not cache', async () => {
1019
+ const instance = new MigrateContext();
1020
+ await instance.init();
1021
+ // Insert author directly into DB, bypassing the cache
1022
+ 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);
1023
+ // Save an AuthorContext with the same slug — should hit the existing.update branch
1024
+ const author = new AuthorContext({ name: 'Updated Pre-existing', slug: 'pre-author', email: 'pre@example.com' });
1025
+ await author.save(instance.db);
1026
+ assert.ok(author.dbId);
1027
+ const found = await instance.findAuthors({ slug: 'pre-author' });
1028
+ assert.equal(found.length, 1);
1029
+ assert.equal(found[0].data.name, 'Updated Pre-existing');
1030
+ await instance.close();
1031
+ });
1032
+ });
1033
+ describe('Duplicate skip guard', () => {
1034
+ it('Second save on a duplicate-skipped post is a no-op', async () => {
1035
+ const instance = new MigrateContext();
1036
+ await instance.init();
1037
+ const post1 = await instance.addPost({ lookupKey: 'https://example.com/dup-guard' });
1038
+ post1.set('title', 'Original');
1039
+ post1.set('slug', 'original');
1040
+ post1.set('created_at', new Date('2023-11-23T12:00:00.000Z'));
1041
+ await post1.save(instance.db);
1042
+ const post2 = await instance.addPost({ lookupKey: 'https://example.com/dup-guard' });
1043
+ post2.set('title', 'Duplicate');
1044
+ post2.set('slug', 'duplicate');
1045
+ post2.set('created_at', new Date('2023-11-24T12:00:00.000Z'));
1046
+ await post2.save(instance.db); // Sets duplicateSkipped = true
1047
+ // Call save again — should hit the #duplicateSkipped guard and return early
1048
+ await post2.save(instance.db);
1049
+ const allPosts = await instance.getAllPosts();
1050
+ assert.equal(allPosts.length, 1);
1051
+ assert.equal(allPosts[0].data.title, 'Original');
1052
+ await instance.close();
1053
+ });
1054
+ });
1055
+ describe('DB round-trip', () => {
1056
+ it('Preserves post data through save and load', async () => {
1057
+ const instance = new MigrateContext();
1058
+ await instance.init();
1059
+ const post = await instance.addPost();
1060
+ post.set('title', 'Round Trip');
1061
+ post.set('slug', 'round-trip');
1062
+ post.set('created_at', new Date('2023-11-23T12:00:00.000Z'));
1063
+ post.set('updated_at', new Date('2023-11-24T12:00:00.000Z'));
1064
+ post.set('published_at', new Date('2023-11-25T12:00:00.000Z'));
1065
+ post.set('status', 'published');
1066
+ post.set('featured', true);
1067
+ post.set('html', '<p>Content</p>');
1068
+ post.addTag({ name: 'Tag One', slug: 'tag-one' });
1069
+ post.addTag({ name: 'Tag Two', slug: 'tag-two' });
1070
+ post.addAuthor({ name: 'Author One', slug: 'author-one', email: 'one@example.com' });
1071
+ await post.save(instance.db);
1072
+ const loaded = await instance.getAllPosts();
1073
+ assert.equal(loaded.length, 1);
1074
+ const p = loaded[0];
1075
+ assert.equal(p.data.title, 'Round Trip');
1076
+ assert.equal(p.data.slug, 'round-trip');
1077
+ assert.equal(p.data.status, 'published');
1078
+ assert.equal(p.data.featured, true);
1079
+ assert.equal(p.data.html, '<p>Content</p>');
1080
+ assert.deepEqual(p.data.created_at, new Date('2023-11-23T12:00:00.000Z'));
1081
+ assert.deepEqual(p.data.updated_at, new Date('2023-11-24T12:00:00.000Z'));
1082
+ assert.deepEqual(p.data.published_at, new Date('2023-11-25T12:00:00.000Z'));
1083
+ assert.equal(p.data.tags.length, 2);
1084
+ assert.equal(p.data.tags[0].data.name, 'Tag One');
1085
+ assert.equal(p.data.tags[1].data.name, 'Tag Two');
1086
+ assert.equal(p.data.authors.length, 1);
1087
+ assert.equal(p.data.authors[0].data.name, 'Author One');
1088
+ await instance.close();
1089
+ });
1090
+ it('Tags are shared across posts', async () => {
1091
+ const instance = new MigrateContext();
1092
+ await instance.init();
1093
+ const post1 = await instance.addPost();
1094
+ post1.set('title', 'Post 1');
1095
+ post1.set('slug', 'post-1');
1096
+ post1.set('created_at', new Date('2023-11-23T12:00:00.000Z'));
1097
+ post1.addTag({ name: 'Shared Tag', slug: 'shared-tag' });
1098
+ await post1.save(instance.db);
1099
+ const post2 = await instance.addPost();
1100
+ post2.set('title', 'Post 2');
1101
+ post2.set('slug', 'post-2');
1102
+ post2.set('created_at', new Date('2023-11-24T12:00:00.000Z'));
1103
+ post2.addTag({ name: 'Shared Tag', slug: 'shared-tag' });
1104
+ await post2.save(instance.db);
1105
+ // Both posts should reference the same tag in the DB
1106
+ const tags = await instance.findTags({ slug: 'shared-tag' });
1107
+ assert.equal(tags.length, 1);
1108
+ await instance.close();
1109
+ });
1110
+ it('Mutable find results persist back to DB', async () => {
1111
+ const instance = new MigrateContext();
1112
+ await instance.init();
1113
+ const post = await instance.addPost();
1114
+ post.set('title', 'Original Title');
1115
+ post.set('slug', 'mutable-test');
1116
+ post.set('created_at', new Date('2023-11-23T12:00:00.000Z'));
1117
+ post.addTag({ name: 'News', slug: 'news' });
1118
+ await post.save(instance.db);
1119
+ const posts = await instance.findPosts({ tagSlug: 'news' });
1120
+ assert.equal(posts.length, 1);
1121
+ posts[0].addTag({ name: 'Breaking', slug: 'breaking' });
1122
+ await posts[0].save(instance.db);
1123
+ const updated = await instance.findPosts({ slug: 'mutable-test' });
1124
+ assert.equal(updated[0].data.tags.length, 2);
1125
+ assert.equal(updated[0].data.tags[1].data.slug, 'breaking');
1126
+ await instance.close();
1127
+ });
1128
+ });
1129
+ describe('Conversion caching', () => {
1130
+ it('writeGhostJson caches converted content back to DB', async () => {
1131
+ const instance = new MigrateContext();
1132
+ await instance.init();
1133
+ const post = await instance.addPost();
1134
+ post.set('title', 'Cache Test');
1135
+ post.set('slug', 'cache-test');
1136
+ post.set('created_at', new Date('2023-01-01T00:00:00.000Z'));
1137
+ post.set('html', '<p>Hello</p>');
1138
+ await post.save(instance.db);
1139
+ // Before write: no cached lexical
1140
+ const rowBefore = instance.db.stmts.findPostById.get(post.dbId);
1141
+ assert.equal(JSON.parse(rowBefore.data).lexical, null);
1142
+ // Write JSON — converts and caches
1143
+ const dir = join(tmpdir(), `mg-cache-${Date.now()}`);
1144
+ await instance.writeGhostJson(dir);
1145
+ // After write: lexical cached in DB
1146
+ const rowAfter = instance.db.stmts.findPostById.get(post.dbId);
1147
+ const stored = JSON.parse(rowAfter.data);
1148
+ assert.ok(stored.lexical, 'lexical should be cached after writeGhostJson');
1149
+ assert.ok(JSON.parse(stored.lexical).root);
1150
+ assert.equal(stored.html, '<p>Hello</p>', 'html should be preserved');
1151
+ await rm(dir, { recursive: true, force: true });
1152
+ await instance.close();
1153
+ });
1154
+ it('Second writeGhostJson skips conversion (uses cache)', async () => {
1155
+ const instance = new MigrateContext();
1156
+ await instance.init();
1157
+ const post = await instance.addPost();
1158
+ post.set('title', 'Skip Test');
1159
+ post.set('slug', 'skip-test');
1160
+ post.set('created_at', new Date('2023-01-01T00:00:00.000Z'));
1161
+ post.set('html', '<p>Hello</p>');
1162
+ await post.save(instance.db);
1163
+ const dir = join(tmpdir(), `mg-skip-${Date.now()}`);
1164
+ // First write: converts
1165
+ await instance.writeGhostJson(dir);
1166
+ const file1 = JSON.parse(await readFile(join(dir, 'posts.json'), 'utf-8'));
1167
+ // Second write: uses cached content (same output)
1168
+ await instance.writeGhostJson(dir);
1169
+ const file2 = JSON.parse(await readFile(join(dir, 'posts.json'), 'utf-8'));
1170
+ assert.equal(file1.data.posts[0].lexical, file2.data.posts[0].lexical);
1171
+ await rm(dir, { recursive: true, force: true });
1172
+ await instance.close();
1173
+ });
1174
+ it('Cache is invalidated when HTML changes via forEachPost', async () => {
1175
+ const instance = new MigrateContext();
1176
+ await instance.init();
1177
+ const post = await instance.addPost();
1178
+ post.set('title', 'Invalidate Test');
1179
+ post.set('slug', 'invalidate-test');
1180
+ post.set('created_at', new Date('2023-01-01T00:00:00.000Z'));
1181
+ post.set('html', '<p>Original</p>');
1182
+ await post.save(instance.db);
1183
+ const dir = join(tmpdir(), `mg-invalidate-${Date.now()}`);
1184
+ // First write: converts and caches
1185
+ await instance.writeGhostJson(dir);
1186
+ const row1 = instance.db.stmts.findPostById.get(post.dbId);
1187
+ const lexical1 = JSON.parse(row1.data).lexical;
1188
+ assert.ok(lexical1);
1189
+ // Modify HTML → clears cached lexical
1190
+ await instance.forEachPost(async (p) => {
1191
+ p.set('html', '<p>Updated</p>');
1192
+ });
1193
+ const rowAfterUpdate = instance.db.stmts.findPostById.get(post.dbId);
1194
+ assert.equal(JSON.parse(rowAfterUpdate.data).lexical, null, 'lexical should be cleared after HTML change');
1195
+ // Second write: re-converts with new HTML
1196
+ await instance.writeGhostJson(dir);
1197
+ const row2 = instance.db.stmts.findPostById.get(post.dbId);
1198
+ const lexical2 = JSON.parse(row2.data).lexical;
1199
+ assert.ok(lexical2);
1200
+ assert.notEqual(lexical1, lexical2);
1201
+ await rm(dir, { recursive: true, force: true });
1202
+ await instance.close();
1203
+ });
1204
+ it('set html invalidates cached conversion', async () => {
1205
+ const instance = new MigrateContext();
1206
+ await instance.init();
1207
+ const post = await instance.addPost();
1208
+ post.set('title', 'Invalidate Test');
1209
+ post.set('slug', 'invalidate-test');
1210
+ post.set('created_at', new Date('2023-01-01T00:00:00.000Z'));
1211
+ post.set('html', '<p>Original</p>');
1212
+ post.convertContent();
1213
+ assert.ok(post.data.lexical);
1214
+ // Setting HTML should clear cached lexical
1215
+ post.set('html', '<p>New HTML</p>');
1216
+ assert.equal(post.data.lexical, null);
1217
+ assert.equal(post.htmlDirty, true);
1218
+ await instance.close();
1219
+ });
1220
+ it('Mobiledoc conversion is cached', async () => {
1221
+ const instance = new MigrateContext({ contentFormat: 'mobiledoc' });
1222
+ await instance.init();
1223
+ const post = await instance.addPost();
1224
+ post.set('title', 'Mobiledoc Test');
1225
+ post.set('slug', 'mobiledoc-test');
1226
+ post.set('created_at', new Date('2023-01-01T00:00:00.000Z'));
1227
+ post.set('html', '<p>Mobiledoc</p>');
1228
+ await post.save(instance.db);
1229
+ const dir = join(tmpdir(), `mg-mobiledoc-cache-${Date.now()}`);
1230
+ await instance.writeGhostJson(dir);
1231
+ const row = instance.db.stmts.findPostById.get(post.dbId);
1232
+ const stored = JSON.parse(row.data);
1233
+ assert.ok(stored.mobiledoc);
1234
+ assert.ok(JSON.parse(stored.mobiledoc).version);
1235
+ assert.equal(stored.lexical, null);
1236
+ await rm(dir, { recursive: true, force: true });
1237
+ await instance.close();
1238
+ });
1239
+ it('convertContent can be called manually', async () => {
1240
+ const instance = new MigrateContext();
1241
+ await instance.init();
1242
+ const post = await instance.addPost();
1243
+ post.set('title', 'Manual Test');
1244
+ post.set('slug', 'manual-test');
1245
+ post.set('created_at', new Date('2023-01-01T00:00:00.000Z'));
1246
+ post.set('html', '<p>Manual</p>');
1247
+ post.convertContent();
1248
+ assert.ok(post.data.lexical);
1249
+ assert.equal(post.htmlDirty, false);
1250
+ await post.save(instance.db);
1251
+ const row = instance.db.stmts.findPostById.get(post.dbId);
1252
+ const stored = JSON.parse(row.data);
1253
+ assert.ok(stored.lexical);
1254
+ await instance.close();
1255
+ });
1256
+ });
1257
+ describe('PostFilter', () => {
1258
+ let ctx;
1259
+ // 5 posts:
1260
+ // A: tag=news, author=alice, created=2023-01-15, published=2023-02-01
1261
+ // B: tag=news, author=bob, created=2023-03-15, published=2023-04-01
1262
+ // C: tag=tech, author=alice, created=2023-06-15, published=2023-07-01
1263
+ // D: tag=tech, author=bob, created=2023-09-15, published=null (draft)
1264
+ // E: no tag, author=alice, created=2023-12-15, published=2023-12-20
1265
+ before(async () => {
1266
+ ctx = new MigrateContext();
1267
+ await ctx.init();
1268
+ const postA = await ctx.addPost();
1269
+ postA.set('title', 'Post A');
1270
+ postA.set('slug', 'post-a');
1271
+ postA.set('created_at', new Date('2023-01-15T00:00:00.000Z'));
1272
+ postA.set('published_at', new Date('2023-02-01T00:00:00.000Z'));
1273
+ postA.set('status', 'published');
1274
+ postA.addTag({ name: 'News', slug: 'news' });
1275
+ postA.addAuthor({ name: 'Alice', slug: 'alice', email: 'alice@example.com' });
1276
+ await postA.save(ctx.db);
1277
+ const postB = await ctx.addPost();
1278
+ postB.set('title', 'Post B');
1279
+ postB.set('slug', 'post-b');
1280
+ postB.set('created_at', new Date('2023-03-15T00:00:00.000Z'));
1281
+ postB.set('published_at', new Date('2023-04-01T00:00:00.000Z'));
1282
+ postB.set('status', 'published');
1283
+ postB.addTag({ name: 'News', slug: 'news' });
1284
+ postB.addAuthor({ name: 'Bob', slug: 'bob', email: 'bob@example.com' });
1285
+ await postB.save(ctx.db);
1286
+ const postC = await ctx.addPost();
1287
+ postC.set('title', 'Post C');
1288
+ postC.set('slug', 'post-c');
1289
+ postC.set('created_at', new Date('2023-06-15T00:00:00.000Z'));
1290
+ postC.set('published_at', new Date('2023-07-01T00:00:00.000Z'));
1291
+ postC.set('status', 'published');
1292
+ postC.addTag({ name: 'Tech', slug: 'tech' });
1293
+ postC.addAuthor({ name: 'Alice', slug: 'alice', email: 'alice@example.com' });
1294
+ await postC.save(ctx.db);
1295
+ const postD = await ctx.addPost();
1296
+ postD.set('title', 'Post D');
1297
+ postD.set('slug', 'post-d');
1298
+ postD.set('created_at', new Date('2023-09-15T00:00:00.000Z'));
1299
+ postD.addTag({ name: 'Tech', slug: 'tech' });
1300
+ postD.addAuthor({ name: 'Bob', slug: 'bob', email: 'bob@example.com' });
1301
+ await postD.save(ctx.db);
1302
+ const postE = await ctx.addPost();
1303
+ postE.set('title', 'Post E');
1304
+ postE.set('slug', 'post-e');
1305
+ postE.set('created_at', new Date('2023-12-15T00:00:00.000Z'));
1306
+ postE.set('published_at', new Date('2023-12-20T00:00:00.000Z'));
1307
+ postE.set('status', 'published');
1308
+ postE.addAuthor({ name: 'Alice', slug: 'alice', email: 'alice@example.com' });
1309
+ await postE.save(ctx.db);
1310
+ });
1311
+ after(async () => {
1312
+ await ctx.close();
1313
+ });
1314
+ async function collectTitles(filter) {
1315
+ const titles = [];
1316
+ await ctx.forEachPost(async (post) => {
1317
+ titles.push(post.data.title);
1318
+ }, { filter });
1319
+ return titles;
1320
+ }
1321
+ describe('forEachPost', () => {
1322
+ it('No filter returns all 5 posts', async () => {
1323
+ const titles = await collectTitles({});
1324
+ assert.equal(titles.length, 5);
1325
+ });
1326
+ it('Tag slug filter returns matching posts', async () => {
1327
+ const titles = await collectTitles({ tag: { slug: 'news' } });
1328
+ assert.deepEqual(titles, ['Post A', 'Post B']);
1329
+ });
1330
+ it('Author slug filter returns matching posts', async () => {
1331
+ const titles = await collectTitles({ tag: { slug: 'news' }, author: { slug: 'alice' } });
1332
+ assert.deepEqual(titles, ['Post A']);
1333
+ });
1334
+ it('Author slug filter alone returns matching posts', async () => {
1335
+ const titles = await collectTitles({ author: { slug: 'alice' } });
1336
+ assert.deepEqual(titles, ['Post A', 'Post C', 'Post E']);
1337
+ });
1338
+ it('createdAt after filter', async () => {
1339
+ const titles = await collectTitles({ createdAt: { after: new Date('2023-06-01T00:00:00.000Z') } });
1340
+ assert.deepEqual(titles, ['Post C', 'Post D', 'Post E']);
1341
+ });
1342
+ it('createdAt before filter (strict)', async () => {
1343
+ const titles = await collectTitles({ createdAt: { before: new Date('2023-03-15T00:00:00.000Z') } });
1344
+ assert.deepEqual(titles, ['Post A']);
1345
+ });
1346
+ it('createdAt onOrBefore filter (inclusive)', async () => {
1347
+ const titles = await collectTitles({ createdAt: { onOrBefore: new Date('2023-03-15T00:00:00.000Z') } });
1348
+ assert.deepEqual(titles, ['Post A', 'Post B']);
1349
+ });
1350
+ it('createdAt onOrAfter filter (inclusive)', async () => {
1351
+ const titles = await collectTitles({ createdAt: { onOrAfter: new Date('2023-06-15T00:00:00.000Z') } });
1352
+ assert.deepEqual(titles, ['Post C', 'Post D', 'Post E']);
1353
+ });
1354
+ it('publishedAt range excludes drafts', async () => {
1355
+ const titles = await collectTitles({
1356
+ publishedAt: {
1357
+ after: new Date('2023-01-01T00:00:00.000Z'),
1358
+ before: new Date('2023-05-01T00:00:00.000Z')
1359
+ }
1360
+ });
1361
+ assert.deepEqual(titles, ['Post A', 'Post B']);
1362
+ });
1363
+ it('Combined tag + date filter', async () => {
1364
+ const titles = await collectTitles({
1365
+ tag: { slug: 'news' },
1366
+ createdAt: { after: new Date('2023-02-01T00:00:00.000Z') }
1367
+ });
1368
+ assert.deepEqual(titles, ['Post B']);
1369
+ });
1370
+ it('Combined tag + author filter', async () => {
1371
+ const titles = await collectTitles({ tag: { slug: 'news' }, author: { slug: 'alice' } });
1372
+ assert.deepEqual(titles, ['Post A']);
1373
+ });
1374
+ it('Tag name filter returns matching posts', async () => {
1375
+ const titles = await collectTitles({ tag: { name: 'Tech' } });
1376
+ assert.deepEqual(titles, ['Post C', 'Post D']);
1377
+ });
1378
+ it('Author name filter returns matching posts', async () => {
1379
+ const titles = await collectTitles({ author: { name: 'Bob' } });
1380
+ assert.deepEqual(titles, ['Post B', 'Post D']);
1381
+ });
1382
+ it('Author email filter returns matching posts', async () => {
1383
+ const titles = await collectTitles({ author: { email: 'bob@example.com' } });
1384
+ assert.deepEqual(titles, ['Post B', 'Post D']);
1385
+ });
1386
+ it('publishedAt after excludes earlier posts', async () => {
1387
+ const titles = await collectTitles({
1388
+ publishedAt: { after: new Date('2023-06-01T00:00:00.000Z') }
1389
+ });
1390
+ // A (Feb), B (Apr) excluded by after; D excluded by null; C (Jul) and E (Dec) pass
1391
+ assert.deepEqual(titles, ['Post C', 'Post E']);
1392
+ });
1393
+ it('publishedAt onOrAfter includes boundary', async () => {
1394
+ const titles = await collectTitles({
1395
+ publishedAt: { onOrAfter: new Date('2023-07-01T00:00:00.000Z') }
1396
+ });
1397
+ // C (Jul 01) included at boundary; D excluded by null; E (Dec 20) included
1398
+ assert.deepEqual(titles, ['Post C', 'Post E']);
1399
+ });
1400
+ it('publishedAt onOrBefore includes boundary', async () => {
1401
+ const titles = await collectTitles({
1402
+ publishedAt: { onOrBefore: new Date('2023-04-01T00:00:00.000Z') }
1403
+ });
1404
+ // A (Feb 01), B (Apr 01) included; D excluded by null
1405
+ assert.deepEqual(titles, ['Post A', 'Post B']);
1406
+ });
1407
+ it('Non-matching filter returns 0 posts', async () => {
1408
+ const titles = await collectTitles({ tag: { slug: 'nonexistent' } });
1409
+ assert.equal(titles.length, 0);
1410
+ });
1411
+ it('Progress reports correct filtered total', async () => {
1412
+ const progressCalls = [];
1413
+ // eslint-disable-next-line no-unused-vars
1414
+ await ctx.forEachPost(async (_post) => { }, {
1415
+ filter: { tag: { slug: 'news' } },
1416
+ progress(processed, total) {
1417
+ progressCalls.push([processed, total]);
1418
+ }
1419
+ });
1420
+ assert.ok(progressCalls.length > 0);
1421
+ const lastCall = progressCalls[progressCalls.length - 1];
1422
+ assert.equal(lastCall[0], 2);
1423
+ assert.equal(lastCall[1], 2);
1424
+ });
1425
+ it('forEachPost on empty context processes zero posts', async () => {
1426
+ const empty = new MigrateContext();
1427
+ await empty.init();
1428
+ let count = 0;
1429
+ await empty.forEachPost(async () => {
1430
+ count += 1;
1431
+ });
1432
+ assert.equal(count, 0);
1433
+ await empty.close();
1434
+ });
1435
+ });
1436
+ describe('forEachGhostPost', () => {
1437
+ it('Tag filter works read-only', async () => {
1438
+ const titles = [];
1439
+ // eslint-disable-next-line no-unused-vars
1440
+ await ctx.forEachGhostPost(async (json, _post) => {
1441
+ titles.push(json.title);
1442
+ }, { filter: { tag: { slug: 'tech' } } });
1443
+ assert.deepEqual(titles, ['Post C', 'Post D']);
1444
+ });
1445
+ it('Tag filter with progress reports correct total', async () => {
1446
+ const progressCalls = [];
1447
+ // eslint-disable-next-line no-unused-vars
1448
+ await ctx.forEachGhostPost(async (_json, _post) => { }, {
1449
+ filter: { tag: { slug: 'news' } },
1450
+ progress(processed, total) {
1451
+ progressCalls.push([processed, total]);
1452
+ }
1453
+ });
1454
+ assert.ok(progressCalls.length > 0);
1455
+ const lastCall = progressCalls[progressCalls.length - 1];
1456
+ assert.equal(lastCall[0], 2);
1457
+ assert.equal(lastCall[1], 2);
1458
+ });
1459
+ it('Date-only filter works without tag/author', async () => {
1460
+ const titles = [];
1461
+ // eslint-disable-next-line no-unused-vars
1462
+ await ctx.forEachGhostPost(async (json, _post) => {
1463
+ titles.push(json.title);
1464
+ }, { filter: { createdAt: { after: new Date('2023-09-01T00:00:00.000Z') } } });
1465
+ assert.deepEqual(titles, ['Post D', 'Post E']);
1466
+ });
1467
+ it('Tag + date filter skips date-excluded posts', async () => {
1468
+ const titles = [];
1469
+ // eslint-disable-next-line no-unused-vars
1470
+ await ctx.forEachGhostPost(async (json, _post) => {
1471
+ titles.push(json.title);
1472
+ }, { filter: { tag: { slug: 'tech' }, createdAt: { after: new Date('2023-08-01T00:00:00.000Z') } } });
1473
+ assert.deepEqual(titles, ['Post D']);
1474
+ });
1475
+ });
1476
+ describe('writeGhostJson', () => {
1477
+ it('Tag filter outputs only matching posts', async () => {
1478
+ const dir = join(tmpdir(), `mg-filter-write-${Date.now()}`);
1479
+ const files = await ctx.writeGhostJson(dir, { filter: { tag: { slug: 'news' } } });
1480
+ assert.equal(files.length, 1);
1481
+ assert.equal(files[0].posts, 2);
1482
+ const content = JSON.parse(await readFile(files[0].path, 'utf-8'));
1483
+ const postTitles = content.data.posts.map((p) => p.title);
1484
+ assert.deepEqual(postTitles, ['Post A', 'Post B']);
1485
+ await rm(dir, { recursive: true, force: true });
1486
+ });
1487
+ it('onWrite callback fires for each file', async () => {
1488
+ const dir = join(tmpdir(), `mg-filter-onwrite-${Date.now()}`);
1489
+ const written = [];
1490
+ const files = await ctx.writeGhostJson(dir, {
1491
+ filter: { tag: { slug: 'news' } },
1492
+ batchSize: 1,
1493
+ onWrite(f) {
1494
+ written.push(f);
1495
+ }
1496
+ });
1497
+ assert.equal(written.length, 2);
1498
+ assert.deepEqual(written, files);
1499
+ await rm(dir, { recursive: true, force: true });
1500
+ });
1501
+ it('Batched output with filter produces correct file count', async () => {
1502
+ const dir = join(tmpdir(), `mg-filter-batch-${Date.now()}`);
1503
+ const files = await ctx.writeGhostJson(dir, { filter: { tag: { slug: 'news' } }, batchSize: 1 });
1504
+ assert.equal(files.length, 2);
1505
+ assert.equal(files[0].posts, 1);
1506
+ assert.equal(files[1].posts, 1);
1507
+ await rm(dir, { recursive: true, force: true });
1508
+ });
1509
+ it('Tag + date filter outputs only matching posts', async () => {
1510
+ const dir = join(tmpdir(), `mg-filter-tagdate-${Date.now()}`);
1511
+ const files = await ctx.writeGhostJson(dir, {
1512
+ filter: { tag: { slug: 'news' }, createdAt: { after: new Date('2023-02-01T00:00:00.000Z') } }
1513
+ });
1514
+ assert.equal(files.length, 1);
1515
+ assert.equal(files[0].posts, 1);
1516
+ const content = JSON.parse(await readFile(files[0].path, 'utf-8'));
1517
+ assert.equal(content.data.posts[0].title, 'Post B');
1518
+ await rm(dir, { recursive: true, force: true });
1519
+ });
1520
+ it('Date-only filter outputs only matching posts', async () => {
1521
+ const dir = join(tmpdir(), `mg-filter-dateonly-${Date.now()}`);
1522
+ const files = await ctx.writeGhostJson(dir, {
1523
+ batchSize: 1,
1524
+ filter: { createdAt: { onOrBefore: new Date('2023-03-15T00:00:00.000Z') } }
1525
+ });
1526
+ assert.equal(files.length, 2);
1527
+ assert.equal(files[0].posts, 1);
1528
+ assert.equal(files[1].posts, 1);
1529
+ await rm(dir, { recursive: true, force: true });
1530
+ });
1531
+ it('Empty result produces single empty JSON file', async () => {
1532
+ const dir = join(tmpdir(), `mg-filter-empty-${Date.now()}`);
1533
+ const files = await ctx.writeGhostJson(dir, { filter: { tag: { slug: 'nonexistent' } } });
1534
+ assert.equal(files.length, 1);
1535
+ assert.equal(files[0].posts, 0);
1536
+ const content = JSON.parse(await readFile(files[0].path, 'utf-8'));
1537
+ assert.equal(content.data.posts.length, 0);
1538
+ await rm(dir, { recursive: true, force: true });
1539
+ });
1540
+ it('Uneven batch remainder gets numbered filename (tag filter)', async () => {
1541
+ const dir = join(tmpdir(), `mg-filter-remainder-tag-${Date.now()}`);
1542
+ const files = await ctx.writeGhostJson(dir, {
1543
+ batchSize: 2,
1544
+ filter: { author: { slug: 'alice' } } // 3 matches: A, C, E
1545
+ });
1546
+ assert.equal(files.length, 2);
1547
+ assert.equal(files[0].posts, 2);
1548
+ assert.equal(files[1].posts, 1);
1549
+ assert.ok(files[1].name.includes('-2'));
1550
+ await rm(dir, { recursive: true, force: true });
1551
+ });
1552
+ it('Uneven batch remainder gets numbered filename (date filter)', async () => {
1553
+ const dir = join(tmpdir(), `mg-filter-remainder-date-${Date.now()}`);
1554
+ const files = await ctx.writeGhostJson(dir, {
1555
+ batchSize: 3,
1556
+ filter: { createdAt: { onOrBefore: new Date('2023-09-15T00:00:00.000Z') } } // 4 matches: A, B, C, D
1557
+ });
1558
+ assert.equal(files.length, 2);
1559
+ assert.equal(files[0].posts, 3);
1560
+ assert.equal(files[1].posts, 1);
1561
+ assert.ok(files[1].name.includes('-2'));
1562
+ await rm(dir, { recursive: true, force: true });
1563
+ });
1564
+ it('Single match with batchSize 1 produces single file (tag filter)', async () => {
1565
+ const dir = join(tmpdir(), `mg-filter-single-tag-${Date.now()}`);
1566
+ const files = await ctx.writeGhostJson(dir, {
1567
+ batchSize: 1,
1568
+ filter: { tag: { slug: 'news' }, author: { slug: 'alice' } }
1569
+ });
1570
+ assert.equal(files.length, 1);
1571
+ assert.equal(files[0].posts, 1);
1572
+ assert.ok(!files[0].name.includes('-1'));
1573
+ await rm(dir, { recursive: true, force: true });
1574
+ });
1575
+ it('Single match with batchSize 1 produces single file (date filter)', async () => {
1576
+ const dir = join(tmpdir(), `mg-filter-single-date-${Date.now()}`);
1577
+ const files = await ctx.writeGhostJson(dir, {
1578
+ batchSize: 1,
1579
+ filter: { createdAt: { after: new Date('2023-12-14T00:00:00.000Z'), before: new Date('2023-12-16T00:00:00.000Z') } }
1580
+ });
1581
+ assert.equal(files.length, 1);
1582
+ assert.equal(files[0].posts, 1);
1583
+ assert.ok(!files[0].name.includes('-1'));
1584
+ await rm(dir, { recursive: true, force: true });
1585
+ });
1586
+ it('publishedAt-only filter outputs matching posts', async () => {
1587
+ const dir = join(tmpdir(), `mg-filter-pubonly-${Date.now()}`);
1588
+ const files = await ctx.writeGhostJson(dir, {
1589
+ filter: { publishedAt: { after: new Date('2023-06-01T00:00:00.000Z') } }
1590
+ });
1591
+ assert.equal(files.length, 1);
1592
+ assert.equal(files[0].posts, 2); // C (Jul) and E (Dec), D excluded (null)
1593
+ await rm(dir, { recursive: true, force: true });
1594
+ });
1595
+ it('Date-only filter with no matches produces single empty JSON file', async () => {
1596
+ const dir = join(tmpdir(), `mg-filter-dateempty-${Date.now()}`);
1597
+ const files = await ctx.writeGhostJson(dir, {
1598
+ filter: { createdAt: { after: new Date('2099-01-01T00:00:00.000Z') } }
1599
+ });
1600
+ assert.equal(files.length, 1);
1601
+ assert.equal(files[0].posts, 0);
1602
+ await rm(dir, { recursive: true, force: true });
1603
+ });
1604
+ });
1605
+ });
1606
+ describe('writeGhostTagsJson', () => {
1607
+ it('Writes all tags to a single JSON file', async () => {
1608
+ const ctx = new MigrateContext();
1609
+ await ctx.init();
1610
+ const post = await ctx.addPost();
1611
+ post.set('title', 'Test');
1612
+ post.set('slug', 'test');
1613
+ post.addTag({ name: 'Alpha', slug: 'alpha' });
1614
+ post.addTag({ name: 'Beta', slug: 'beta' });
1615
+ await post.save(ctx.db);
1616
+ const dir = join(tmpdir(), `mg-tags-json-${Date.now()}`);
1617
+ const file = await ctx.writeGhostTagsJson(dir);
1618
+ assert.equal(file.name, 'tags.json');
1619
+ assert.equal(file.posts, 0);
1620
+ const content = JSON.parse(await readFile(file.path, 'utf-8'));
1621
+ assert.equal(content.data.tags.length, 2);
1622
+ assert.equal(content.data.tags[0].name, 'Alpha');
1623
+ assert.equal(content.data.tags[1].name, 'Beta');
1624
+ assert.ok(content.data.tags[0].id);
1625
+ assert.ok(content.meta.exported_on);
1626
+ assert.ok(!content.data.posts);
1627
+ assert.ok(!content.data.posts_tags);
1628
+ await rm(dir, { recursive: true, force: true });
1629
+ await ctx.close();
1630
+ });
1631
+ it('Supports custom filename', async () => {
1632
+ const ctx = new MigrateContext();
1633
+ await ctx.init();
1634
+ const post = await ctx.addPost();
1635
+ post.set('title', 'Test');
1636
+ post.set('slug', 'test');
1637
+ post.addTag({ name: 'Gamma', slug: 'gamma' });
1638
+ await post.save(ctx.db);
1639
+ const dir = join(tmpdir(), `mg-tags-custom-${Date.now()}`);
1640
+ const file = await ctx.writeGhostTagsJson(dir, { filename: 'my-tags' });
1641
+ assert.equal(file.name, 'my-tags.json');
1642
+ await rm(dir, { recursive: true, force: true });
1643
+ await ctx.close();
1644
+ });
1645
+ it('Writes empty tags array when no tags exist', async () => {
1646
+ const ctx = new MigrateContext();
1647
+ await ctx.init();
1648
+ const dir = join(tmpdir(), `mg-tags-empty-${Date.now()}`);
1649
+ const file = await ctx.writeGhostTagsJson(dir);
1650
+ const content = JSON.parse(await readFile(file.path, 'utf-8'));
1651
+ assert.deepEqual(content.data.tags, []);
1652
+ await rm(dir, { recursive: true, force: true });
1653
+ await ctx.close();
1654
+ });
1655
+ it('Excludes orphan tags not assigned to any post', async () => {
1656
+ const ctx = new MigrateContext();
1657
+ await ctx.init();
1658
+ const post = await ctx.addPost();
1659
+ post.set('title', 'Test');
1660
+ post.set('slug', 'test');
1661
+ post.addTag({ name: 'Used', slug: 'used' });
1662
+ post.addTag({ name: 'Orphan', slug: 'orphan' });
1663
+ await post.save(ctx.db);
1664
+ // Remove one tag so it becomes orphaned in the Tags table
1665
+ post.removeTag('orphan');
1666
+ await post.save(ctx.db);
1667
+ const dir = join(tmpdir(), `mg-tags-orphan-${Date.now()}`);
1668
+ const file = await ctx.writeGhostTagsJson(dir);
1669
+ const content = JSON.parse(await readFile(file.path, 'utf-8'));
1670
+ assert.equal(content.data.tags.length, 1);
1671
+ assert.equal(content.data.tags[0].name, 'Used');
1672
+ await rm(dir, { recursive: true, force: true });
1673
+ await ctx.close();
1674
+ });
1675
+ });
1676
+ describe('writeGhostUsersJson', () => {
1677
+ it('Writes all users to a single JSON file', async () => {
1678
+ const ctx = new MigrateContext();
1679
+ await ctx.init();
1680
+ const post = await ctx.addPost();
1681
+ post.set('title', 'Test');
1682
+ post.set('slug', 'test');
1683
+ post.addAuthor({ name: 'Alice', slug: 'alice', email: 'alice@example.com' });
1684
+ post.addAuthor({ name: 'Bob', slug: 'bob', email: 'bob@example.com' });
1685
+ await post.save(ctx.db);
1686
+ const dir = join(tmpdir(), `mg-users-json-${Date.now()}`);
1687
+ const file = await ctx.writeGhostUsersJson(dir);
1688
+ assert.equal(file.name, 'users.json');
1689
+ assert.equal(file.posts, 0);
1690
+ const content = JSON.parse(await readFile(file.path, 'utf-8'));
1691
+ assert.equal(content.data.users.length, 2);
1692
+ assert.equal(content.data.users[0].name, 'Alice');
1693
+ assert.equal(content.data.users[1].name, 'Bob');
1694
+ assert.ok(content.data.users[0].id);
1695
+ assert.ok(content.meta.exported_on);
1696
+ assert.ok(!content.data.posts);
1697
+ assert.ok(!content.data.posts_authors);
1698
+ await rm(dir, { recursive: true, force: true });
1699
+ await ctx.close();
1700
+ });
1701
+ it('Supports custom filename', async () => {
1702
+ const ctx = new MigrateContext();
1703
+ await ctx.init();
1704
+ const post = await ctx.addPost();
1705
+ post.set('title', 'Test');
1706
+ post.set('slug', 'test');
1707
+ post.addAuthor({ name: 'Carol', slug: 'carol', email: 'carol@example.com' });
1708
+ await post.save(ctx.db);
1709
+ const dir = join(tmpdir(), `mg-users-custom-${Date.now()}`);
1710
+ const file = await ctx.writeGhostUsersJson(dir, { filename: 'my-users' });
1711
+ assert.equal(file.name, 'my-users.json');
1712
+ await rm(dir, { recursive: true, force: true });
1713
+ await ctx.close();
1714
+ });
1715
+ it('Writes empty users array when no authors exist', async () => {
1716
+ const ctx = new MigrateContext();
1717
+ await ctx.init();
1718
+ const dir = join(tmpdir(), `mg-users-empty-${Date.now()}`);
1719
+ const file = await ctx.writeGhostUsersJson(dir);
1720
+ const content = JSON.parse(await readFile(file.path, 'utf-8'));
1721
+ assert.deepEqual(content.data.users, []);
1722
+ await rm(dir, { recursive: true, force: true });
1723
+ await ctx.close();
1724
+ });
1725
+ it('Excludes orphan authors not assigned to any post', async () => {
1726
+ const ctx = new MigrateContext();
1727
+ await ctx.init();
1728
+ const post = await ctx.addPost();
1729
+ post.set('title', 'Test');
1730
+ post.set('slug', 'test');
1731
+ post.addAuthor({ name: 'Used', slug: 'used', email: 'used@example.com' });
1732
+ post.addAuthor({ name: 'Orphan', slug: 'orphan', email: 'orphan@example.com' });
1733
+ await post.save(ctx.db);
1734
+ // Remove one author so it becomes orphaned in the Authors table
1735
+ post.removeAuthor('orphan');
1736
+ await post.save(ctx.db);
1737
+ const dir = join(tmpdir(), `mg-users-orphan-${Date.now()}`);
1738
+ const file = await ctx.writeGhostUsersJson(dir);
1739
+ const content = JSON.parse(await readFile(file.path, 'utf-8'));
1740
+ assert.equal(content.data.users.length, 1);
1741
+ assert.equal(content.data.users[0].name, 'Used');
1742
+ await rm(dir, { recursive: true, force: true });
1743
+ await ctx.close();
280
1744
  });
281
1745
  });
282
1746
  });