@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.
package/README.md CHANGED
@@ -1,272 +1,597 @@
1
1
  # Migrate Context
2
2
 
3
- This package makes it easier to create post objects that can be used in the Ghost migration tools. It aims to provide a consistent, typed interface for posts, pages, tags, and authors. It also validates input data to ensure that the resulting object is valid for importing into Ghost.
3
+ A SQLite-backed data store for building Ghost import files. Provides a validated, typed interface for posts, tags, and authors with batched iteration for large migrations.
4
4
 
5
- It can also be used for custom migrations, and can output a JSON file that can be imported in Ghost.
6
-
7
- This package exports a few different classes: `MigrateContext`, `PostContext`, `TagContext`, and `AuthorContext`.
8
- Most of the time, you'll want the `MigrateContext` class, which is the top-level class that manages all the other classes.
5
+ Data is persisted to SQLite (in-memory by default), so migrations with tens of thousands of posts don't require excessive memory. Content is validated against Ghost's schema on write, and HTML is lazily converted to Lexical or Mobiledoc on export.
9
6
 
10
7
  ## Install
11
8
 
12
- `npm install @tryghost/mg-context --save`
9
+ ```bash
10
+ npm install @tryghost/mg-context --save
11
+ # or
12
+ yarn add @tryghost/mg-context
13
+ ```
13
14
 
14
- or
15
+ ## Quick start
15
16
 
16
- `yarn add @tryghost/mg-context`
17
+ ```js
18
+ import {MigrateContext} from '@tryghost/mg-context';
17
19
 
20
+ const context = new MigrateContext();
21
+ await context.init();
22
+
23
+ // Add a few posts
24
+ for (let i = 1; i <= 3; i++) {
25
+ const post = await context.addPost();
26
+ post.set('title', `Post ${i}`);
27
+ post.set('slug', `post-${i}`);
28
+ post.set('status', 'published');
29
+ post.set('created_at', new Date(`2025-01-${10 + i}T10:00:00Z`));
30
+ post.set('html', '<p>Hello world</p>');
31
+ post.addTag({name: 'News', slug: 'news'});
32
+ post.addAuthor({name: 'Alice', slug: 'alice', email: 'alice@example.com'});
33
+ await post.save(context.db);
34
+ }
35
+
36
+ // Update every post — find-replace content and add a tag
37
+ await context.forEachPost(async (post) => {
38
+ const html = post.get('html');
39
+ post.set('html', html.replace('Hello world', 'Lorem ipsum'));
40
+ post.addTag({name: 'Updated', slug: 'updated'});
41
+ });
18
42
 
19
- # Usage
43
+ await context.writeGhostJson('./output/');
44
+ await context.close();
45
+ ```
20
46
 
21
- Let's walk through adding a post to a context, and then outputting the final JSON that can be imported into Ghost.
47
+ See the [examples/](examples/) directory for complete runnable scripts, including bulk generation and iteration patterns.
22
48
 
23
- ### Create a context
49
+ ## Architecture
24
50
 
25
- ```js
26
- import {MigrateContext} from '@tryghost/mg-context';
27
- const context = new MigrateContext();
28
51
  ```
52
+ MigrateContext
53
+ └─ PostContext
54
+ ├─ TagContext
55
+ └─ AuthorContext
56
+ ```
57
+
58
+ `MigrateContext` manages the database and provides methods for adding, finding, iterating, and exporting posts. Each post holds references to its tags and authors. All data is stored in SQLite with JSON columns for flexible schema storage and indexed columns for fast lookups.
59
+
60
+ ---
29
61
 
30
- You can optionally set the content format to `lexical` or `mobiledoc` on the context. By default, only `html` is exported. All posts added to the context will use this format.
62
+ # API Reference
63
+
64
+ ## MigrateContext
65
+
66
+ The top-level class that manages the database and all entity operations.
67
+
68
+ ### Constructor
31
69
 
32
70
  ```js
33
- const context = new MigrateContext({contentFormat: 'lexical'});
71
+ new MigrateContext(options?)
34
72
  ```
35
73
 
36
- ### Create a post
74
+ | Option | Type | Default | Description |
75
+ |----------------------------|--------------------------------------|---------------------|----------------------------------------------|
76
+ | `contentFormat` | `'lexical' \| 'mobiledoc' \| 'html'` | `'lexical'` | Target format for HTML conversion on export |
77
+ | `dbPath` | `string` | — | Path to a SQLite file for persistent storage |
78
+ | `ephemeral` | `boolean` | `true` if no dbPath | Use in-memory database |
79
+ | `warnOnLookupKeyDuplicate` | `boolean` | `false` | Log when a duplicate lookupKey is skipped |
37
80
 
38
81
  ```js
39
- const post = context.addPost();
40
- post.set('title', 'My Post');
41
- post.set('slug', 'my-post');
42
- post.set('status', 'published');
43
- post.set('published_at', new Date('2023-12-08T13:34:22.000Z'));
44
- post.set('created_at', new Date('2023-12-08T13:23:03.000Z'));
45
- post.set('updated_at', new Date('2023-12-08T13:36:42.000Z'));
46
- post.set('html', '<p>My post content</p>');
82
+ // In-memory (default)
83
+ const ctx = new MigrateContext();
84
+
85
+ // Persistent file-based
86
+ const ctx = new MigrateContext({dbPath: './migration.sqlite'});
87
+
88
+ // Mobiledoc output instead of Lexical
89
+ const ctx = new MigrateContext({contentFormat: 'mobiledoc'});
47
90
  ```
48
91
 
49
- When you call `post.set('html', '<p>...</p>')`, the content is automatically converted based on the `contentFormat`:
92
+ ### Lifecycle
93
+
94
+ #### `init(): Promise<void>`
95
+
96
+ Initialize the database. Must be called before any other operations. Throws if called twice without `close()` in between.
50
97
 
51
- - **`html`** (default): Only `html` is populated in the export. `mobiledoc` and `lexical` will be `null`.
52
- - **`lexical`**: Both `html` and `lexical` are populated. The HTML is automatically converted to Lexical format. `mobiledoc` will be `null`.
53
- - **`mobiledoc`**: Both `html` and `mobiledoc` are populated. The HTML is automatically converted to Mobiledoc format. `lexical` will be `null`.
98
+ #### `close(): Promise<void>`
54
99
 
55
- ### Add a tag
100
+ Close the database connection. Always call this when done, ideally in a `finally` block.
56
101
 
57
102
  ```js
58
- post.addTag({
59
- name: 'My Tag',
60
- slug: 'my-tag'
61
- });
103
+ const ctx = new MigrateContext();
104
+ await ctx.init();
105
+ try {
106
+ // ... work
107
+ } finally {
108
+ await ctx.close();
109
+ }
62
110
  ```
63
111
 
64
- ### Add an author
112
+ #### `db: DatabaseModels`
113
+
114
+ Access the underlying database models. Needed for `post.save(ctx.db)`.
115
+
116
+ ### Adding posts
117
+
118
+ #### `addPost(options?): Promise<PostContext>`
119
+
120
+ Create a new post. Returns an unsaved `PostContext` — call `post.save(ctx.db)` to persist.
65
121
 
66
122
  ```js
67
- post.addAuthor({
68
- name: 'Author Name',
69
- slug: 'author-name',
70
- email: 'name@example.com'
71
- });
123
+ // Empty post
124
+ const post = await ctx.addPost();
125
+
126
+ // With a lookup key for deduplication
127
+ const post = await ctx.addPost({lookupKey: 'https://example.com/original-url'});
128
+
129
+ // With source metadata (preserved but not exported)
130
+ const post = await ctx.addPost({source: {originalId: 123}});
72
131
  ```
73
132
 
74
- ## Adding posts from another source
133
+ When called with a `PostContext` instance, saves it immediately instead.
75
134
 
76
- If you have post data in another format, get it in to some sort of array or object that can be iterated over. Then, for each row, create a new post and set the data with the same methods as above.
135
+ #### `addPost(postContext): Promise<PostContext>`
77
136
 
78
137
  ```js
79
- const arrayOfPostData = [...];
138
+ const post = new PostContext({contentFormat: 'html'});
139
+ post.set('title', 'Pre-built');
140
+ post.set('slug', 'pre-built');
141
+ post.set('created_at', new Date());
142
+ await ctx.addPost(post); // saves immediately
143
+ ```
144
+
145
+ ### Transactions
80
146
 
81
- arrayOfPostData.forEach((row) => {
82
- const post = context.addPost();
83
- // post.set('title', row.title);
84
- // ...
147
+ #### `transaction(callback): Promise<T>`
148
+
149
+ Wrap operations in a database transaction. Significantly improves write performance for bulk inserts.
150
+
151
+ ```js
152
+ await ctx.transaction(async () => {
153
+ for (const row of data) {
154
+ const post = await ctx.addPost();
155
+ post.set('title', row.title);
156
+ // ...
157
+ await post.save(ctx.db);
158
+ }
85
159
  });
86
160
  ```
87
161
 
162
+ ### Finding entities
163
+
164
+ #### `findPosts(options): Promise<PostContext[] | null>`
88
165
 
89
- ### Get a Ghost JSON string
166
+ Find posts by various criteria. Only one criterion is used at a time (first match wins).
167
+
168
+ | Option | Type | Description |
169
+ |---------------|----------------|--------------------------------------------------|
170
+ | `slug` | `string` | Match post slug |
171
+ | `title` | `string` | Match post title |
172
+ | `sourceAttr` | `{key, value}` | Match a key/value pair in the post's source data |
173
+ | `tagSlug` | `string` | Find posts with this tag slug |
174
+ | `tagName` | `string` | Find posts with this tag name |
175
+ | `authorSlug` | `string` | Find posts by this author slug |
176
+ | `authorName` | `string` | Find posts by this author name |
177
+ | `authorEmail` | `string` | Find posts by this author email |
90
178
 
91
179
  ```js
92
- const json = context.ghostJson;
93
- // `json` is a JSON string. Save it to a `.json` file and import it into Ghost
180
+ const posts = await ctx.findPosts({tagSlug: 'news'});
181
+ const posts = await ctx.findPosts({authorEmail: 'alice@example.com'});
182
+ const posts = await ctx.findPosts({sourceAttr: {key: 'url', value: 'https://example.com/post'}});
94
183
  ```
95
184
 
185
+ #### `findTags(options): Promise<TagContext[] | null>`
96
186
 
187
+ Find tags by `slug` or `name`.
97
188
 
189
+ #### `findAuthors(options): Promise<AuthorContext[] | null>`
98
190
 
191
+ Find authors by `slug`, `name`, or `email`.
99
192
 
100
- # Classes & Methods
193
+ #### `getAllPosts(): Promise<PostContext[]>`
101
194
 
102
- There's 4 main classes: `MigrateContext`, `PostContext`, `TagContext`, and `AuthorContext`. Most of the time, `MigrateContext` is what you'll use, but more advanced usage may require the usage of the other classes.
195
+ Load all posts. Use `forEachPost` for large datasets to avoid loading everything into memory.
103
196
 
197
+ ### Iterating posts
104
198
 
105
- ### `MigrateContext`
199
+ #### `forEachPost(callback, options?): Promise<void>`
106
200
 
107
- This is the main class that manages all the other classes. It has methods for adding posts, tags, and authors, and also has methods for finding posts, tags, and authors.
201
+ Iterate all posts in batches. Each post is automatically saved after the callback.
108
202
 
109
- - `context.addPost(post`
110
- - `context.findPosts({slug, title, sourceAttr, tagSlug, tagName, authorSlug, authorName, authorEmail})`
111
- - `context.findTags({slug, name})`
112
- - `context.findAuthors({slug, name, email})`
113
- - `await context.forEachPost(callback)`
114
- - `context.forEachPostSync(callback)`
115
- - `context.allPosts`
116
- - `context.ghostJson`
203
+ ```js
204
+ await ctx.forEachPost(async (post) => {
205
+ post.set('status', 'published');
206
+ // post is saved automatically after callback
207
+ }, {batchSize: 200});
208
+ ```
117
209
 
118
- ### `PostContext`
210
+ #### `forEachGhostPost(callback, options?): Promise<void>`
119
211
 
120
- This class is only for posts and related data. You can also set tags and authors.
212
+ Iterate posts as processed Ghost JSON with tags and authors inlined. Read-only — mutations are not saved.
121
213
 
122
- - `post.get(prop)`
123
- - `post.set(prop)`
124
- - `post.remove(prop)`
125
- - `post.setMeta(value)`
126
- - `post.getMetaValue(key)`
127
- - `post.getSourceValue(key)`
128
- - `post.hasTagSlug(tagSlug)`
129
- - `post.hasTagName(tagName)`
130
- - `post.addTag(value)`
131
- - `post.removeTag(tagSlug)`
132
- - `post.setTagOrder(callback)`
133
- - `post.setPrimaryTag(value)`
134
- - `post.hasAuthorSlug(authorSlug)`
135
- - `post.hasAuthorName(authorName)`
136
- - `post.hasAuthorEmail(authorEmail)`
137
- - `post.addAuthor(value)`
138
- - `post.removeAuthor(authorSlug)`
139
- - `post.setAuthorOrder(callback)`
140
- - `post.setPrimaryAuthor(value)`
141
- - `post.meta`
142
- - `post.source`
214
+ ```js
215
+ await ctx.forEachGhostPost(async (json, post) => {
216
+ // json: { id, title, slug, tags: [...], authors: [...], ... }
217
+ await ghostApi.posts.add(json);
218
+ }, {batchSize: 50});
219
+ ```
143
220
 
144
- ### `TagContext`
221
+ #### Iteration options
145
222
 
146
- This class is used to create and manage individual tags.
223
+ | Option | Type | Default | Description |
224
+ |-------------|------------------------------|---------|-----------------------------------------------|
225
+ | `batchSize` | `number` | `100` | Posts loaded per batch |
226
+ | `filter` | `PostFilter` | — | Filter criteria (see [Filtering](#filtering)) |
227
+ | `progress` | `(processed, total) => void` | — | Progress callback |
147
228
 
148
- - `tag.set(prop)`
149
- - `tag.remove(prop)`
150
- - `tag.get(prop)`
151
- - `tag.meta`
229
+ ### Exporting
152
230
 
153
- ### `AuthorContext`
231
+ #### `writeGhostJson(outputDir, options?): Promise<WrittenFile[]>`
154
232
 
155
- This class is used to create and manage individual authors.
233
+ Write posts, tags, authors, and junction tables to Ghost JSON files.
156
234
 
157
- - `author.set(prop)`
158
- - `author.remove(prop)`
159
- - `author.get(prop)`
160
- - `author.meta`
235
+ | Option | Type | Default | Description |
236
+ |-------------|-------------------------------|-----------|-------------------------------------|
237
+ | `batchSize` | `number` | `5000` | Posts per output file |
238
+ | `filename` | `string` | `'posts'` | Base filename (without `.json`) |
239
+ | `filter` | `PostFilter` | — | Filter criteria |
240
+ | `onWrite` | `(file: WrittenFile) => void` | — | Callback after each file is written |
161
241
 
162
- # Tips & tricks
242
+ Returns an array of `WrittenFile` objects:
163
243
 
164
- Knowing the methods is not that useful in itself. Here's some tips and tricks that are the heart of this package.
244
+ | Field | Type | Description |
245
+ |---------|----------|--------------------------------|
246
+ | `path` | `string` | Absolute path to the file |
247
+ | `name` | `string` | Filename (e.g. `posts-1.json`) |
248
+ | `size` | `number` | File size in bytes |
249
+ | `posts` | `number` | Number of posts in this file |
250
+
251
+ ```js
252
+ const files = await ctx.writeGhostJson('./output/', {
253
+ filename: 'export',
254
+ batchSize: 2000,
255
+ onWrite(f) {
256
+ console.log(`Wrote ${f.name} (${f.posts} posts)`);
257
+ }
258
+ });
259
+ ```
165
260
 
166
- ## Finding Posts
261
+ #### `writeGhostTagsJson(outputDir, options?): Promise<WrittenFile>`
167
262
 
168
- If you need to find posts that have a specific tag or author, use the `findPosts` method. You can supply an object with any of the following keys:
263
+ Export tags as a standalone JSON file. Only tags referenced by at least one post are included.
169
264
 
170
- - `tagSlug`
171
- - `tagName`
172
- - `authorSlug`
173
- - `authorName`
174
- - `authorEmail`
265
+ #### `writeGhostUsersJson(outputDir, options?): Promise<WrittenFile>`
266
+
267
+ Export authors/users as a standalone JSON file. Only authors referenced by at least one post are included.
175
268
 
176
269
  ```js
177
- const context = new MigrateContext();
270
+ await ctx.writeGhostTagsJson('./output/', {filename: 'my-tags'});
271
+ await ctx.writeGhostUsersJson('./output/', {filename: 'my-users'});
272
+ ```
178
273
 
179
- const posts = context.findPosts({tagSlug: 'my-tag'});
180
- const posts = context.findPosts({tagName: 'My Tag'});
274
+ ### Filtering
181
275
 
182
- const posts = context.findPosts({authorSlug: 'author-name'});
183
- const posts = context.findPosts({authorName: 'Author Name'});
184
- const posts = context.findPosts({authorEmail: 'author@example.com'});
276
+ All iteration and export methods accept a `filter` option. Criteria combine with AND logic.
185
277
 
186
- const posts = context.findPosts({slug: 'my-post'});
187
- const posts = context.findPosts({title: 'My Post'});
188
- const posts = context.findPosts({sourceAttr: {
189
- key: 'url',
190
- value: 'https://example.com/blog/2023/11/26/original-slug/'
191
- }});
278
+ ```js
279
+ await ctx.forEachPost(async (post) => { /* ... */ }, {
280
+ filter: {
281
+ tag: {slug: 'news'},
282
+ createdAt: {onOrAfter: new Date('2025-01-01')}
283
+ }
284
+ });
192
285
  ```
193
286
 
194
- ### Updating found posts
287
+ | Filter | Type | Description |
288
+ |-------------------------------------------------------------|----------|----------------------------|
289
+ | `tag.slug` | `string` | Posts with this tag slug |
290
+ | `tag.name` | `string` | Posts with this tag name |
291
+ | `author.slug` | `string` | Posts by this author slug |
292
+ | `author.name` | `string` | Posts by this author name |
293
+ | `author.email` | `string` | Posts by this author email |
294
+ | `createdAt.before` / `after` / `onOrBefore` / `onOrAfter` | `Date` | Filter by `created_at` |
295
+ | `publishedAt.before` / `after` / `onOrBefore` / `onOrAfter` | `Date` | Filter by `published_at` |
296
+
297
+ Posts with `null` `published_at` (drafts) are excluded by a `publishedAt` filter.
298
+
299
+ ---
300
+
301
+ ## PostContext
195
302
 
196
- Add a new tag to all posts with a specific tag
303
+ Represents a single post with validated properties, tag/author relationships, and source metadata.
304
+
305
+ ### Properties
306
+
307
+ #### `post.get(prop): any`
308
+
309
+ Get a property value.
310
+
311
+ #### `post.set(prop, value): PostContext`
312
+
313
+ Set a property value. Validates against the schema (type, max length, allowed values). Returns `this` for chaining.
314
+
315
+ Setting `html` invalidates cached `lexical`/`mobiledoc` — conversion is deferred until export.
316
+
317
+ #### `post.remove(prop): PostContext`
318
+
319
+ Reset a property to its default value (or `null`).
320
+
321
+ #### `post.save(db): void`
322
+
323
+ Persist the post and its tag/author relationships to the database.
324
+
325
+ ### Post fields
326
+
327
+ | Field | Type | Max | Default | Notes |
328
+ |-------------------------|-----------|-------|------------|-------------------------------------------|
329
+ | `title` | `string` | 255 | — | **Required** |
330
+ | `slug` | `string` | 191 | — | **Required** |
331
+ | `html` | `string?` | — | `null` | Source HTML content |
332
+ | `lexical` | `string?` | — | `null` | Auto-generated on export |
333
+ | `mobiledoc` | `string?` | — | `null` | Auto-generated on export |
334
+ | `status` | `enum` | — | `'draft'` | `published`, `draft`, `scheduled`, `sent` |
335
+ | `type` | `enum` | — | `'post'` | `post`, `page` |
336
+ | `visibility` | `enum` | — | `'public'` | `public`, `members`, `paid` |
337
+ | `featured` | `boolean` | — | `false` | |
338
+ | `created_at` | `Date` | — | — | **Required** |
339
+ | `updated_at` | `Date?` | — | `null` | |
340
+ | `published_at` | `Date?` | — | `null` | |
341
+ | `feature_image` | `string?` | 2000 | `null` | |
342
+ | `feature_image_alt` | `string?` | 125 | `null` | |
343
+ | `feature_image_caption` | `string?` | 65535 | `null` | |
344
+ | `custom_excerpt` | `string?` | 300 | `null` | |
345
+ | `canonical_url` | `string?` | 2000 | `null` | |
346
+ | `meta_title` | `string?` | 300 | `null` | |
347
+ | `meta_description` | `string?` | 500 | `null` | |
348
+ | `og_title` | `string?` | 300 | `null` | |
349
+ | `og_description` | `string?` | 500 | `null` | |
350
+ | `og_image` | `string?` | 2000 | `null` | |
351
+ | `twitter_title` | `string?` | 300 | `null` | |
352
+ | `twitter_description` | `string?` | 500 | `null` | |
353
+ | `twitter_image` | `string?` | 2000 | `null` | |
354
+ | `codeinjection_head` | `string?` | 65535 | `null` | |
355
+ | `codeinjection_foot` | `string?` | 65535 | `null` | |
356
+ | `custom_template` | `string?` | 100 | `null` | |
357
+ | `comment_id` | `string?` | 50 | `null` | |
358
+ | `plaintext` | `string?` | — | `null` | |
359
+
360
+ ### Tags
361
+
362
+ Tags have a `sort_order` that is tracked automatically. When tags are added, their position in the list becomes their sort order. The sort order is persisted to the database and included in the exported Ghost JSON as a 1-based integer (`sort_order: 1, 2, 3, ...`).
363
+
364
+ #### `post.addTag(tag, options?): TagContext | false`
365
+
366
+ Add a tag by object or `TagContext`. Returns `false` if the slug already exists on this post.
197
367
 
198
368
  ```js
199
- const posts = context.findPosts({tagSlug: 'my-tag'});
369
+ post.addTag({name: 'News', slug: 'news'});
200
370
 
201
- posts.forEach((post) => {
202
- post.addTag({
203
- name: 'My New Tag',
204
- slug: 'my-new-tag'
205
- });
371
+ // Insert at a specific position (0-based index)
372
+ post.addTag({name: 'Breaking', slug: 'breaking', sortOrder: 0});
373
+ ```
374
+
375
+ | Option | Type | Required | Description |
376
+ |-------------|----------|----------|--------------------------------------------------|
377
+ | `name` | `string` | Yes | Tag name |
378
+ | `slug` | `string` | Yes | Tag slug |
379
+ | `sortOrder` | `number` | No | Position to insert at. Appends if out of bounds. |
380
+
381
+ #### `post.removeTag(slug): void`
382
+
383
+ Remove a tag by slug.
384
+
385
+ #### `post.hasTagSlug(slug): boolean` / `post.hasTagName(name): boolean`
386
+
387
+ Check if the post has a specific tag.
388
+
389
+ #### `post.setPrimaryTag({name, slug}): void`
390
+
391
+ Set a tag as primary (moves it to sort order 1). Adds the tag if it doesn't exist.
392
+
393
+ #### `post.setTagOrder(callback): void`
394
+
395
+ Reorder tags. The callback receives an array of `TagContext` instances and must return the same instances in the desired order. Access tag properties via `tag.data.slug`, `tag.data.name`, etc.
396
+
397
+ ```js
398
+ // Move internal tags to the end
399
+ post.setTagOrder((tags) => {
400
+ const regular = tags.filter(t => !t.data.slug.startsWith('hash-'));
401
+ const internal = tags.filter(t => t.data.slug.startsWith('hash-'));
402
+ return [...regular, ...internal];
206
403
  });
207
404
  ```
208
405
 
209
- ## Updating found authors
406
+ ### Authors
407
+
408
+ Authors follow the same ordering model as tags — `sort_order` is tracked automatically, persisted, and exported as a 1-based integer.
409
+
410
+ #### `post.addAuthor(author, options?): AuthorContext | false`
210
411
 
211
- Change the email for found authors
412
+ Add an author by object or `AuthorContext`. Returns `false` if the slug already exists on this post.
212
413
 
213
414
  ```js
214
- const authors = context.findAuthors({slug: 'author-name'});
415
+ post.addAuthor({name: 'Alice', slug: 'alice', email: 'alice@example.com'});
215
416
 
216
- authors.forEach((author) => {
217
- author.set('email', 'real-email@exmapl.com');
218
- });
417
+ // Insert at a specific position
418
+ post.addAuthor({name: 'Bob', slug: 'bob', email: 'bob@example.com', sortOrder: 0});
219
419
  ```
220
420
 
221
- ## Updating found tags
421
+ | Option | Type | Required | Description |
422
+ |-------------|----------|----------|--------------------------------------------------|
423
+ | `name` | `string` | Yes | Author name |
424
+ | `slug` | `string` | Yes | Author slug |
425
+ | `email` | `string` | Yes | Author email |
426
+ | `sortOrder` | `number` | No | Position to insert at. Appends if out of bounds. |
427
+
428
+ #### `post.removeAuthor(slug): void`
429
+
430
+ Remove an author by slug.
431
+
432
+ #### `post.hasAuthorSlug(slug): boolean` / `post.hasAuthorName(name): boolean` / `post.hasAuthorEmail(email): boolean`
222
433
 
223
- Change the name of found tags
434
+ Check if the post has a specific author.
435
+
436
+ #### `post.setPrimaryAuthor({name, slug, email}): void`
437
+
438
+ Set an author as primary (moves them to sort order 1). Adds the author if they don't exist.
439
+
440
+ #### `post.setAuthorOrder(callback): void`
441
+
442
+ Reorder authors. The callback receives an array of `AuthorContext` instances and must return the same instances in the desired order. Access author properties via `author.data.slug`, `author.data.name`, etc.
224
443
 
225
444
  ```js
226
- const tags = context.findTags({slug: 'my-tag'});
445
+ // Reverse the author order
446
+ post.setAuthorOrder((authors) => [...authors].reverse());
447
+ ```
227
448
 
228
- tags.forEach((tag) => {
229
- tag.set('name', 'My New Tag');
230
- });
449
+ ### Source & metadata
450
+
451
+ #### `post.source`
452
+
453
+ Access the source data object (set at construction). Not exported to Ghost JSON — use this to store original platform data for reference during migration.
454
+
455
+ #### `post.getSourceValue(key): any`
456
+
457
+ Get a single value from the source data.
458
+
459
+ #### `post.meta`
460
+
461
+ Access the metadata object.
462
+
463
+ #### `post.setMeta(value): void`
464
+
465
+ Replace the metadata object.
466
+
467
+ #### `post.getMetaValue(key): any`
468
+
469
+ Get a single metadata value.
470
+
471
+ ### Deduplication
472
+
473
+ #### `post.lookupKey: string | null`
474
+
475
+ Get or set the lookup key. When a post with a matching lookup key already exists in the database, `save()` silently skips the insert.
476
+
477
+ ```js
478
+ const post = await ctx.addPost({lookupKey: 'https://example.com/post-url'});
479
+ // ... set fields ...
480
+ await post.save(ctx.db);
481
+
482
+ // Second save with same key is a no-op
483
+ const dupe = await ctx.addPost({lookupKey: 'https://example.com/post-url'});
484
+ await dupe.save(ctx.db); // skipped
231
485
  ```
232
486
 
487
+ ---
233
488
 
234
- ### Class Flow
489
+ ## TagContext
235
490
 
491
+ Represents a tag with validated properties.
492
+
493
+ ### Constructor
494
+
495
+ ```js
496
+ new TagContext({name: 'News', slug: 'news'})
497
+ // or
498
+ new TagContext({initialData: {name: 'News', slug: 'news'}})
236
499
  ```
237
- ┌────────────────┐
238
- │ MigrateContext │
239
- └───┬────────────┘
240
- ┌▼─────────────────────────────┐
241
- │ PostContext │
242
- └┬─────────────────────────────┘
243
- └─────┬───────────────┐
244
- ┌──────▼─────┐ ┌───────▼───────┐
245
- │ TagContext │ │ AuthorContext │
246
- └────────────┘ └───────────────┘
500
+
501
+ ### Methods
502
+
503
+ - `tag.get(prop): any`
504
+ - `tag.set(prop, value): TagContext`
505
+ - `tag.remove(prop): TagContext`
506
+ - `tag.save(db): void`
507
+
508
+ ### Tag fields
509
+
510
+ | Field | Type | Max | Notes |
511
+ |-----------------------|-----------|-------|--------------|
512
+ | `name` | `string` | 255 | **Required** |
513
+ | `slug` | `string` | 191 | **Required** |
514
+ | `description` | `string?` | 500 | |
515
+ | `feature_image` | `string?` | 2000 | |
516
+ | `og_image` | `string?` | 2000 | |
517
+ | `og_title` | `string?` | 300 | |
518
+ | `og_description` | `string?` | 500 | |
519
+ | `twitter_image` | `string?` | 2000 | |
520
+ | `twitter_title` | `string?` | 300 | |
521
+ | `twitter_description` | `string?` | 500 | |
522
+ | `meta_title` | `string?` | 300 | |
523
+ | `meta_description` | `string?` | 500 | |
524
+ | `codeinjection_head` | `string?` | 65535 | |
525
+ | `codeinjection_foot` | `string?` | 65535 | |
526
+ | `canonical_url` | `string?` | 2000 | |
527
+
528
+ ---
529
+
530
+ ## AuthorContext
531
+
532
+ Represents an author with validated properties.
533
+
534
+ ### Constructor
535
+
536
+ ```js
537
+ new AuthorContext({name: 'Alice', slug: 'alice', email: 'alice@example.com'})
247
538
  ```
248
539
 
540
+ ### Methods
249
541
 
250
- ## Develop
542
+ - `author.get(prop): any`
543
+ - `author.set(prop, value): AuthorContext`
544
+ - `author.remove(prop): AuthorContext`
545
+ - `author.save(db): void`
251
546
 
252
- This is a mono repository, managed with [lerna](https://lernajs.io/).
547
+ ### Author fields
253
548
 
254
- Follow the instructions for the top-level repo.
255
- 1. `git clone` this repo & `cd` into it as usual
256
- 2. Run `yarn` to install top-level dependencies.
549
+ | Field | Type | Max | Notes |
550
+ |--------------------|-----------|------|--------------------------------------------------------------|
551
+ | `name` | `string` | 191 | **Required** |
552
+ | `slug` | `string` | 191 | **Required** |
553
+ | `email` | `string` | 191 | **Required**, validated |
554
+ | `profile_image` | `string?` | 2000 | |
555
+ | `cover_image` | `string?` | 2000 | |
556
+ | `bio` | `string?` | 250 | |
557
+ | `website` | `string?` | 2000 | |
558
+ | `location` | `string?` | 150 | |
559
+ | `facebook` | `string?` | 2000 | |
560
+ | `twitter` | `string?` | 2000 | |
561
+ | `meta_title` | `string?` | 300 | |
562
+ | `meta_description` | `string?` | 500 | |
563
+ | `role` | `enum` | — | `Contributor` (default), `Author`, `Editor`, `Administrator` |
564
+
565
+ ---
566
+
567
+ ## Examples
568
+
569
+ The [examples/](examples/) directory contains runnable scripts demonstrating common patterns:
257
570
 
571
+ - **generate-and-export.ts** — Create 500 posts in-memory and export to Ghost JSON
572
+ - **reorder-tags-authors.ts** — Reorder tags and authors using `setTagOrder`, `setPrimaryTag`, and `addTag` with `sortOrder`
573
+ - **generate-large-export.ts** — Stress-test with 500k posts, benchmarking memory and performance
574
+ - **foreach-ghost-post.ts** — Iterate an existing database and log each post as Ghost JSON
258
575
 
259
- ## Run
576
+ Run any example from the package directory:
260
577
 
261
- - `yarn dev`
578
+ ```bash
579
+ npx tsx examples/generate-and-export.ts
580
+ ```
581
+
582
+ ## Develop
583
+
584
+ This is a mono repository, managed with [Nx](https://nx.dev/) and yarn workspaces.
262
585
 
586
+ Follow the instructions for the top-level repo.
587
+ 1. `git clone` this repo & `cd` into it as usual
588
+ 2. Run `yarn` to install top-level dependencies.
263
589
 
264
590
  ## Test
265
591
 
266
592
  - `yarn lint` run just eslint
267
593
  - `yarn test` run lint and tests
268
594
 
269
-
270
595
  # Copyright & License
271
596
 
272
597
  Copyright (c) 2013-2026 Ghost Foundation - Released under the [MIT license](LICENSE).