@tryghost/mg-context 0.1.27 → 0.3.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 +574 -156
- package/build/index.d.ts +1 -0
- package/build/lib/AuthorContext.d.ts +3 -0
- package/build/lib/AuthorContext.js +40 -0
- package/build/lib/AuthorContext.js.map +1 -1
- package/build/lib/MigrateBase.d.ts +2 -0
- package/build/lib/MigrateBase.js +7 -0
- package/build/lib/MigrateBase.js.map +1 -1
- package/build/lib/MigrateContext.d.ts +74 -9
- package/build/lib/MigrateContext.js +504 -102
- package/build/lib/MigrateContext.js.map +1 -1
- package/build/lib/PostContext.d.ts +28 -5
- package/build/lib/PostContext.js +263 -19
- package/build/lib/PostContext.js.map +1 -1
- package/build/lib/TagContext.d.ts +3 -0
- package/build/lib/TagContext.js +40 -0
- package/build/lib/TagContext.js.map +1 -1
- package/build/lib/database.d.ts +63 -0
- package/build/lib/database.js +123 -0
- package/build/lib/database.js.map +1 -0
- package/build/lib/db-helpers.d.ts +25 -0
- package/build/lib/db-helpers.js +110 -0
- package/build/lib/db-helpers.js.map +1 -0
- package/build/test/migrate-context.test.js +1942 -107
- package/build/test/migrate-context.test.js.map +1 -1
- package/build/test/post-context.test.js +284 -4
- package/build/test/post-context.test.js.map +1 -1
- package/build/test/tasks.test.js +23 -5
- package/build/test/tasks.test.js.map +1 -1
- package/package.json +20 -13
package/README.md
CHANGED
|
@@ -1,272 +1,690 @@
|
|
|
1
1
|
# Migrate Context
|
|
2
2
|
|
|
3
|
-
|
|
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
|
-
|
|
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 converted to Lexical or Mobiledoc during an explicit preparation step before export.
|
|
9
6
|
|
|
10
7
|
## Install
|
|
11
8
|
|
|
12
|
-
|
|
9
|
+
```bash
|
|
10
|
+
npm install @tryghost/mg-context --save
|
|
11
|
+
# or
|
|
12
|
+
yarn add @tryghost/mg-context
|
|
13
|
+
```
|
|
13
14
|
|
|
14
|
-
|
|
15
|
+
## Quick start
|
|
15
16
|
|
|
16
|
-
|
|
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
|
-
|
|
43
|
+
// Prepare for export (deduplicate slugs, convert HTML to Lexical)
|
|
44
|
+
await context.prepareForExport();
|
|
20
45
|
|
|
21
|
-
|
|
46
|
+
await context.writeGhostJson('./output/');
|
|
47
|
+
await context.close();
|
|
48
|
+
```
|
|
22
49
|
|
|
23
|
-
|
|
50
|
+
See the [examples/](examples/) directory for complete runnable scripts, including bulk generation and iteration patterns.
|
|
51
|
+
|
|
52
|
+
## Architecture
|
|
24
53
|
|
|
25
|
-
```js
|
|
26
|
-
import {MigrateContext} from '@tryghost/mg-context';
|
|
27
|
-
const context = new MigrateContext();
|
|
28
54
|
```
|
|
55
|
+
MigrateContext
|
|
56
|
+
└─ PostContext
|
|
57
|
+
├─ TagContext
|
|
58
|
+
└─ AuthorContext
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
`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.
|
|
62
|
+
|
|
63
|
+
---
|
|
64
|
+
|
|
65
|
+
# API Reference
|
|
66
|
+
|
|
67
|
+
## MigrateContext
|
|
68
|
+
|
|
69
|
+
The top-level class that manages the database and all entity operations.
|
|
29
70
|
|
|
30
|
-
|
|
71
|
+
### Constructor
|
|
31
72
|
|
|
32
73
|
```js
|
|
33
|
-
|
|
74
|
+
new MigrateContext(options?)
|
|
34
75
|
```
|
|
35
76
|
|
|
36
|
-
|
|
77
|
+
| Option | Type | Default | Description |
|
|
78
|
+
|----------------------------|--------------------------------------|---------------------|----------------------------------------------|
|
|
79
|
+
| `contentFormat` | `'lexical' \| 'mobiledoc' \| 'html'` | `'lexical'` | Target format for HTML conversion on export |
|
|
80
|
+
| `dbPath` | `string` | — | Path to a SQLite file for persistent storage |
|
|
81
|
+
| `ephemeral` | `boolean` | `true` if no dbPath | Use in-memory database |
|
|
82
|
+
| `emitEvents` | `boolean` | `true` | Emit progress events (see [Events](#events)) |
|
|
83
|
+
| `warnOnLookupKeyDuplicate` | `boolean` | `false` | Log when a duplicate lookupKey is skipped |
|
|
37
84
|
|
|
38
85
|
```js
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
86
|
+
// In-memory (default)
|
|
87
|
+
const ctx = new MigrateContext();
|
|
88
|
+
|
|
89
|
+
// Persistent file-based
|
|
90
|
+
const ctx = new MigrateContext({dbPath: './migration.sqlite'});
|
|
91
|
+
|
|
92
|
+
// Mobiledoc output instead of Lexical
|
|
93
|
+
const ctx = new MigrateContext({contentFormat: 'mobiledoc'});
|
|
94
|
+
|
|
95
|
+
// Server mode — disable events for zero overhead
|
|
96
|
+
const ctx = new MigrateContext({emitEvents: false});
|
|
47
97
|
```
|
|
48
98
|
|
|
49
|
-
|
|
99
|
+
### Lifecycle
|
|
100
|
+
|
|
101
|
+
#### `init(): Promise<void>`
|
|
102
|
+
|
|
103
|
+
Initialize the database. Must be called before any other operations. Throws if called twice without `close()` in between.
|
|
50
104
|
|
|
51
|
-
|
|
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`.
|
|
105
|
+
#### `close(): Promise<void>`
|
|
54
106
|
|
|
55
|
-
|
|
107
|
+
Close the database connection. Always call this when done, ideally in a `finally` block.
|
|
56
108
|
|
|
57
109
|
```js
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
110
|
+
const ctx = new MigrateContext();
|
|
111
|
+
await ctx.init();
|
|
112
|
+
try {
|
|
113
|
+
// ... work
|
|
114
|
+
} finally {
|
|
115
|
+
await ctx.close();
|
|
116
|
+
}
|
|
62
117
|
```
|
|
63
118
|
|
|
64
|
-
|
|
119
|
+
#### `db: DatabaseModels`
|
|
120
|
+
|
|
121
|
+
Access the underlying database models. Needed for `post.save(ctx.db)`.
|
|
122
|
+
|
|
123
|
+
### Adding posts
|
|
124
|
+
|
|
125
|
+
#### `addPost(options?): Promise<PostContext>`
|
|
126
|
+
|
|
127
|
+
Create a new post. Returns an unsaved `PostContext` — call `post.save(ctx.db)` to persist.
|
|
65
128
|
|
|
66
129
|
```js
|
|
67
|
-
post
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
});
|
|
130
|
+
// Empty post
|
|
131
|
+
const post = await ctx.addPost();
|
|
132
|
+
|
|
133
|
+
// With a lookup key for deduplication
|
|
134
|
+
const post = await ctx.addPost({lookupKey: 'https://example.com/original-url'});
|
|
135
|
+
|
|
136
|
+
// With source metadata (preserved but not exported)
|
|
137
|
+
const post = await ctx.addPost({source: {originalId: 123}});
|
|
72
138
|
```
|
|
73
139
|
|
|
74
|
-
|
|
140
|
+
When called with a `PostContext` instance, saves it immediately instead.
|
|
75
141
|
|
|
76
|
-
|
|
142
|
+
#### `addPost(postContext): Promise<PostContext>`
|
|
77
143
|
|
|
78
144
|
```js
|
|
79
|
-
const
|
|
145
|
+
const post = new PostContext({contentFormat: 'html'});
|
|
146
|
+
post.set('title', 'Pre-built');
|
|
147
|
+
post.set('slug', 'pre-built');
|
|
148
|
+
post.set('created_at', new Date());
|
|
149
|
+
await ctx.addPost(post); // saves immediately
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
### Transactions
|
|
153
|
+
|
|
154
|
+
#### `transaction(callback): Promise<T>`
|
|
80
155
|
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
156
|
+
Wrap operations in a database transaction. Significantly improves write performance for bulk inserts.
|
|
157
|
+
|
|
158
|
+
```js
|
|
159
|
+
await ctx.transaction(async () => {
|
|
160
|
+
for (const row of data) {
|
|
161
|
+
const post = await ctx.addPost();
|
|
162
|
+
post.set('title', row.title);
|
|
163
|
+
// ...
|
|
164
|
+
await post.save(ctx.db);
|
|
165
|
+
}
|
|
85
166
|
});
|
|
86
167
|
```
|
|
87
168
|
|
|
169
|
+
### Finding entities
|
|
170
|
+
|
|
171
|
+
#### `findPosts(options): Promise<PostContext[] | null>`
|
|
88
172
|
|
|
89
|
-
|
|
173
|
+
Find posts by various criteria. Only one criterion is used at a time (first match wins).
|
|
174
|
+
|
|
175
|
+
| Option | Type | Description |
|
|
176
|
+
|---------------|----------------|--------------------------------------------------|
|
|
177
|
+
| `slug` | `string` | Match post slug |
|
|
178
|
+
| `title` | `string` | Match post title |
|
|
179
|
+
| `sourceAttr` | `{key, value}` | Match a key/value pair in the post's source data |
|
|
180
|
+
| `tagSlug` | `string` | Find posts with this tag slug |
|
|
181
|
+
| `tagName` | `string` | Find posts with this tag name |
|
|
182
|
+
| `authorSlug` | `string` | Find posts by this author slug |
|
|
183
|
+
| `authorName` | `string` | Find posts by this author name |
|
|
184
|
+
| `authorEmail` | `string` | Find posts by this author email |
|
|
90
185
|
|
|
91
186
|
```js
|
|
92
|
-
const
|
|
93
|
-
|
|
187
|
+
const posts = await ctx.findPosts({tagSlug: 'news'});
|
|
188
|
+
const posts = await ctx.findPosts({authorEmail: 'alice@example.com'});
|
|
189
|
+
const posts = await ctx.findPosts({sourceAttr: {key: 'url', value: 'https://example.com/post'}});
|
|
94
190
|
```
|
|
95
191
|
|
|
192
|
+
#### `findTags(options): Promise<TagContext[] | null>`
|
|
193
|
+
|
|
194
|
+
Find tags by `slug` or `name`.
|
|
96
195
|
|
|
196
|
+
#### `findAuthors(options): Promise<AuthorContext[] | null>`
|
|
97
197
|
|
|
198
|
+
Find authors by `slug`, `name`, or `email`.
|
|
98
199
|
|
|
200
|
+
#### `getAllPosts(): Promise<PostContext[]>`
|
|
99
201
|
|
|
100
|
-
|
|
202
|
+
Load all posts. Use `forEachPost` for large datasets to avoid loading everything into memory.
|
|
101
203
|
|
|
102
|
-
|
|
204
|
+
### Iterating posts
|
|
103
205
|
|
|
206
|
+
#### `forEachPost(callback, options?): Promise<void>`
|
|
104
207
|
|
|
105
|
-
|
|
208
|
+
Iterate all posts in batches. Each post is automatically saved after the callback.
|
|
106
209
|
|
|
107
|
-
|
|
210
|
+
```js
|
|
211
|
+
await ctx.forEachPost(async (post) => {
|
|
212
|
+
post.set('status', 'published');
|
|
213
|
+
// post is saved automatically after callback
|
|
214
|
+
}, {batchSize: 200});
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
#### `forEachGhostPost(callback, options?): Promise<void>`
|
|
218
|
+
|
|
219
|
+
Iterate posts as processed Ghost JSON with tags and authors inlined. Read-only — mutations are not saved.
|
|
220
|
+
|
|
221
|
+
```js
|
|
222
|
+
await ctx.forEachGhostPost(async (json, post) => {
|
|
223
|
+
// json: { id, title, slug, tags: [...], authors: [...], ... }
|
|
224
|
+
await ghostApi.posts.add(json);
|
|
225
|
+
}, {batchSize: 50});
|
|
226
|
+
```
|
|
108
227
|
|
|
109
|
-
|
|
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`
|
|
228
|
+
#### Iteration options
|
|
117
229
|
|
|
118
|
-
|
|
230
|
+
| Option | Type | Default | Description |
|
|
231
|
+
|-------------|--------------|---------|-----------------------------------------------|
|
|
232
|
+
| `batchSize` | `number` | `100` | Posts loaded per batch |
|
|
233
|
+
| `filter` | `PostFilter` | — | Filter criteria (see [Filtering](#filtering)) |
|
|
119
234
|
|
|
120
|
-
|
|
235
|
+
Progress is reported via the `progress` event (see [Events](#events)).
|
|
121
236
|
|
|
122
|
-
|
|
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`
|
|
237
|
+
### Exporting
|
|
143
238
|
|
|
144
|
-
|
|
239
|
+
#### `prepareForExport(options?): Promise<void>`
|
|
145
240
|
|
|
146
|
-
|
|
241
|
+
Prepare all posts for export. Must be called before `writeGhostJson()` or `forEachGhostPost()`. This:
|
|
147
242
|
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
- `tag.get(prop)`
|
|
151
|
-
- `tag.meta`
|
|
243
|
+
1. Deduplicates slugs (calls `deduplicateSlugs()` internally)
|
|
244
|
+
2. Converts HTML to Lexical or Mobiledoc for all posts that need it
|
|
152
245
|
|
|
153
|
-
|
|
246
|
+
The method is idempotent — posts that already have converted content are skipped. Call it again after modifying posts via `forEachPost()` to re-convert changed content.
|
|
154
247
|
|
|
155
|
-
|
|
248
|
+
| Option | Type | Default | Description |
|
|
249
|
+
|-------------|----------|---------|---------------------------|
|
|
250
|
+
| `batchSize` | `number` | `200` | Posts processed per batch |
|
|
156
251
|
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
- `author.meta`
|
|
252
|
+
```js
|
|
253
|
+
await ctx.prepareForExport();
|
|
254
|
+
```
|
|
161
255
|
|
|
162
|
-
|
|
256
|
+
#### `writeGhostJson(outputDir, options?): Promise<WrittenFile[]>`
|
|
163
257
|
|
|
164
|
-
|
|
258
|
+
Write posts, tags, authors, and junction tables to Ghost JSON files.
|
|
165
259
|
|
|
166
|
-
|
|
260
|
+
| Option | Type | Default | Description |
|
|
261
|
+
|-------------|-------------------------------|-----------|-------------------------------------|
|
|
262
|
+
| `batchSize` | `number` | `5000` | Posts per output file |
|
|
263
|
+
| `filename` | `string` | `'posts'` | Base filename (without `.json`) |
|
|
264
|
+
| `filter` | `PostFilter` | — | Filter criteria |
|
|
265
|
+
| `onWrite` | `(file: WrittenFile) => void` | — | Callback after each file is written |
|
|
167
266
|
|
|
168
|
-
|
|
267
|
+
Returns an array of `WrittenFile` objects:
|
|
169
268
|
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
269
|
+
| Field | Type | Description |
|
|
270
|
+
|---------|----------|--------------------------------|
|
|
271
|
+
| `path` | `string` | Absolute path to the file |
|
|
272
|
+
| `name` | `string` | Filename (e.g. `posts-1.json`) |
|
|
273
|
+
| `size` | `number` | File size in bytes |
|
|
274
|
+
| `posts` | `number` | Number of posts in this file |
|
|
175
275
|
|
|
176
276
|
```js
|
|
177
|
-
const
|
|
277
|
+
const files = await ctx.writeGhostJson('./output/', {
|
|
278
|
+
filename: 'export',
|
|
279
|
+
batchSize: 2000,
|
|
280
|
+
onWrite(f) {
|
|
281
|
+
console.log(`Wrote ${f.name} (${f.posts} posts)`);
|
|
282
|
+
}
|
|
283
|
+
});
|
|
284
|
+
```
|
|
178
285
|
|
|
179
|
-
|
|
180
|
-
const posts = context.findPosts({tagName: 'My Tag'});
|
|
286
|
+
#### `writeGhostTagsJson(outputDir, options?): Promise<WrittenFile>`
|
|
181
287
|
|
|
182
|
-
|
|
183
|
-
const posts = context.findPosts({authorName: 'Author Name'});
|
|
184
|
-
const posts = context.findPosts({authorEmail: 'author@example.com'});
|
|
288
|
+
Export tags as a standalone JSON file. Only tags referenced by at least one post are included.
|
|
185
289
|
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
}
|
|
290
|
+
#### `writeGhostUsersJson(outputDir, options?): Promise<WrittenFile>`
|
|
291
|
+
|
|
292
|
+
Export authors/users as a standalone JSON file. Only authors referenced by at least one post are included.
|
|
293
|
+
|
|
294
|
+
```js
|
|
295
|
+
await ctx.writeGhostTagsJson('./output/', {filename: 'my-tags'});
|
|
296
|
+
await ctx.writeGhostUsersJson('./output/', {filename: 'my-users'});
|
|
192
297
|
```
|
|
193
298
|
|
|
194
|
-
###
|
|
299
|
+
### Filtering
|
|
195
300
|
|
|
196
|
-
|
|
301
|
+
All iteration and export methods accept a `filter` option. Criteria combine with AND logic.
|
|
197
302
|
|
|
198
303
|
```js
|
|
199
|
-
|
|
304
|
+
await ctx.forEachPost(async (post) => { /* ... */ }, {
|
|
305
|
+
filter: {
|
|
306
|
+
tag: {slug: 'news'},
|
|
307
|
+
createdAt: {onOrAfter: new Date('2025-01-01')}
|
|
308
|
+
}
|
|
309
|
+
});
|
|
310
|
+
```
|
|
200
311
|
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
312
|
+
| Filter | Type | Description |
|
|
313
|
+
|-------------------------------------------------------------|----------|----------------------------|
|
|
314
|
+
| `tag.slug` | `string` | Posts with this tag slug |
|
|
315
|
+
| `tag.name` | `string` | Posts with this tag name |
|
|
316
|
+
| `author.slug` | `string` | Posts by this author slug |
|
|
317
|
+
| `author.name` | `string` | Posts by this author name |
|
|
318
|
+
| `author.email` | `string` | Posts by this author email |
|
|
319
|
+
| `createdAt.before` / `after` / `onOrBefore` / `onOrAfter` | `Date` | Filter by `created_at` |
|
|
320
|
+
| `publishedAt.before` / `after` / `onOrBefore` / `onOrAfter` | `Date` | Filter by `published_at` |
|
|
321
|
+
|
|
322
|
+
Posts with `null` `published_at` (drafts) are excluded by a `publishedAt` filter.
|
|
323
|
+
|
|
324
|
+
### Events
|
|
325
|
+
|
|
326
|
+
MigrateContext emits events via `on`/`off`, powered by `node:events`. This lets you set up a single listener for progress across all operations instead of passing callbacks to each method.
|
|
327
|
+
|
|
328
|
+
#### `on(event, listener): this`
|
|
329
|
+
|
|
330
|
+
Register an event listener. Returns `this` for chaining.
|
|
331
|
+
|
|
332
|
+
#### `off(event, listener): this`
|
|
333
|
+
|
|
334
|
+
Remove an event listener.
|
|
335
|
+
|
|
336
|
+
#### `progress` event
|
|
337
|
+
|
|
338
|
+
Emitted after each batch during `prepareForExport()`, `forEachPost()`, and `forEachGhostPost()`.
|
|
339
|
+
|
|
340
|
+
```js
|
|
341
|
+
ctx.on('progress', (event, processed, total) => {
|
|
342
|
+
console.log(`[${event}] ${processed}/${total}`);
|
|
206
343
|
});
|
|
207
344
|
```
|
|
208
345
|
|
|
209
|
-
|
|
346
|
+
| Argument | Type | Description |
|
|
347
|
+
|-------------|----------|--------------------------------------------------------------|
|
|
348
|
+
| `event` | `string` | Operation name: `prepareForExport`, `forEachPost`, or `forEachGhostPost` |
|
|
349
|
+
| `processed` | `number` | Posts processed so far |
|
|
350
|
+
| `total` | `number` | Total posts to process |
|
|
351
|
+
|
|
352
|
+
Events can be disabled entirely at construction with `emitEvents: false` for server environments where the overhead is unwanted:
|
|
353
|
+
|
|
354
|
+
```js
|
|
355
|
+
const ctx = new MigrateContext({emitEvents: false});
|
|
356
|
+
```
|
|
357
|
+
|
|
358
|
+
---
|
|
359
|
+
|
|
360
|
+
## PostContext
|
|
361
|
+
|
|
362
|
+
Represents a single post with validated properties, tag/author relationships, and source metadata.
|
|
363
|
+
|
|
364
|
+
### Properties
|
|
365
|
+
|
|
366
|
+
#### `post.get(prop): any`
|
|
367
|
+
|
|
368
|
+
Get a property value.
|
|
369
|
+
|
|
370
|
+
#### `post.set(prop, value): PostContext`
|
|
371
|
+
|
|
372
|
+
Set a property value. Validates against the schema (type, max length, allowed values). Returns `this` for chaining.
|
|
373
|
+
|
|
374
|
+
Setting `html` invalidates cached `lexical`/`mobiledoc` — call `prepareForExport()` again to re-convert.
|
|
375
|
+
|
|
376
|
+
#### `post.remove(prop): PostContext`
|
|
377
|
+
|
|
378
|
+
Reset a property to its default value (or `null`).
|
|
379
|
+
|
|
380
|
+
#### `post.save(db): void`
|
|
381
|
+
|
|
382
|
+
Persist the post and its tag/author relationships to the database.
|
|
383
|
+
|
|
384
|
+
### Post fields
|
|
385
|
+
|
|
386
|
+
| Field | Type | Max | Default | Notes |
|
|
387
|
+
|-------------------------|-----------|-------|------------|-------------------------------------------|
|
|
388
|
+
| `title` | `string` | 255 | — | **Required** |
|
|
389
|
+
| `slug` | `string` | 191 | — | **Required** |
|
|
390
|
+
| `html` | `string?` | — | `null` | Source HTML content |
|
|
391
|
+
| `lexical` | `string?` | — | `null` | Auto-generated on export |
|
|
392
|
+
| `mobiledoc` | `string?` | — | `null` | Auto-generated on export |
|
|
393
|
+
| `status` | `enum` | — | `'draft'` | `published`, `draft`, `scheduled`, `sent` |
|
|
394
|
+
| `type` | `enum` | — | `'post'` | `post`, `page` |
|
|
395
|
+
| `visibility` | `enum` | — | `'public'` | `public`, `members`, `paid` |
|
|
396
|
+
| `featured` | `boolean` | — | `false` | |
|
|
397
|
+
| `created_at` | `Date` | — | — | **Required** |
|
|
398
|
+
| `updated_at` | `Date?` | — | `null` | |
|
|
399
|
+
| `published_at` | `Date?` | — | `null` | |
|
|
400
|
+
| `feature_image` | `string?` | 2000 | `null` | |
|
|
401
|
+
| `feature_image_alt` | `string?` | 125 | `null` | |
|
|
402
|
+
| `feature_image_caption` | `string?` | 65535 | `null` | |
|
|
403
|
+
| `custom_excerpt` | `string?` | 300 | `null` | |
|
|
404
|
+
| `canonical_url` | `string?` | 2000 | `null` | |
|
|
405
|
+
| `meta_title` | `string?` | 300 | `null` | |
|
|
406
|
+
| `meta_description` | `string?` | 500 | `null` | |
|
|
407
|
+
| `og_title` | `string?` | 300 | `null` | |
|
|
408
|
+
| `og_description` | `string?` | 500 | `null` | |
|
|
409
|
+
| `og_image` | `string?` | 2000 | `null` | |
|
|
410
|
+
| `twitter_title` | `string?` | 300 | `null` | |
|
|
411
|
+
| `twitter_description` | `string?` | 500 | `null` | |
|
|
412
|
+
| `twitter_image` | `string?` | 2000 | `null` | |
|
|
413
|
+
| `codeinjection_head` | `string?` | 65535 | `null` | |
|
|
414
|
+
| `codeinjection_foot` | `string?` | 65535 | `null` | |
|
|
415
|
+
| `custom_template` | `string?` | 100 | `null` | |
|
|
416
|
+
| `comment_id` | `string?` | 50 | `null` | |
|
|
417
|
+
| `plaintext` | `string?` | — | `null` | |
|
|
418
|
+
|
|
419
|
+
### Tags
|
|
420
|
+
|
|
421
|
+
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, ...`).
|
|
422
|
+
|
|
423
|
+
#### `post.addTag(tag, options?): TagContext | false`
|
|
210
424
|
|
|
211
|
-
|
|
425
|
+
Add a tag by object or `TagContext`. Returns `false` if the slug already exists on this post.
|
|
212
426
|
|
|
213
427
|
```js
|
|
214
|
-
|
|
428
|
+
post.addTag({name: 'News', slug: 'news'});
|
|
215
429
|
|
|
216
|
-
|
|
217
|
-
|
|
430
|
+
// Insert at a specific position (0-based index)
|
|
431
|
+
post.addTag({name: 'Breaking', slug: 'breaking', sortOrder: 0});
|
|
432
|
+
```
|
|
433
|
+
|
|
434
|
+
| Option | Type | Required | Description |
|
|
435
|
+
|-------------|----------|----------|--------------------------------------------------|
|
|
436
|
+
| `name` | `string` | Yes | Tag name |
|
|
437
|
+
| `slug` | `string` | Yes | Tag slug |
|
|
438
|
+
| `sortOrder` | `number` | No | Position to insert at. Appends if out of bounds. |
|
|
439
|
+
|
|
440
|
+
#### `post.removeTag(slug): void`
|
|
441
|
+
|
|
442
|
+
Remove a tag by slug.
|
|
443
|
+
|
|
444
|
+
#### `post.hasTagSlug(slug): boolean` / `post.hasTagName(name): boolean`
|
|
445
|
+
|
|
446
|
+
Check if the post has a specific tag.
|
|
447
|
+
|
|
448
|
+
#### `post.setPrimaryTag({name, slug}): void`
|
|
449
|
+
|
|
450
|
+
Set a tag as primary (moves it to sort order 1). Adds the tag if it doesn't exist.
|
|
451
|
+
|
|
452
|
+
#### `post.setTagOrder(callback): void`
|
|
453
|
+
|
|
454
|
+
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.
|
|
455
|
+
|
|
456
|
+
```js
|
|
457
|
+
// Move internal tags to the end
|
|
458
|
+
post.setTagOrder((tags) => {
|
|
459
|
+
const regular = tags.filter(t => !t.data.slug.startsWith('hash-'));
|
|
460
|
+
const internal = tags.filter(t => t.data.slug.startsWith('hash-'));
|
|
461
|
+
return [...regular, ...internal];
|
|
218
462
|
});
|
|
219
463
|
```
|
|
220
464
|
|
|
221
|
-
|
|
465
|
+
### Authors
|
|
466
|
+
|
|
467
|
+
Authors follow the same ordering model as tags — `sort_order` is tracked automatically, persisted, and exported as a 1-based integer.
|
|
468
|
+
|
|
469
|
+
#### `post.addAuthor(author, options?): AuthorContext | false`
|
|
222
470
|
|
|
223
|
-
|
|
471
|
+
Add an author by object or `AuthorContext`. Returns `false` if the slug already exists on this post.
|
|
224
472
|
|
|
225
473
|
```js
|
|
226
|
-
|
|
474
|
+
post.addAuthor({name: 'Alice', slug: 'alice', email: 'alice@example.com'});
|
|
227
475
|
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
});
|
|
476
|
+
// Insert at a specific position
|
|
477
|
+
post.addAuthor({name: 'Bob', slug: 'bob', email: 'bob@example.com', sortOrder: 0});
|
|
231
478
|
```
|
|
232
479
|
|
|
480
|
+
| Option | Type | Required | Description |
|
|
481
|
+
|-------------|----------|----------|--------------------------------------------------|
|
|
482
|
+
| `name` | `string` | Yes | Author name |
|
|
483
|
+
| `slug` | `string` | Yes | Author slug |
|
|
484
|
+
| `email` | `string` | Yes | Author email |
|
|
485
|
+
| `sortOrder` | `number` | No | Position to insert at. Appends if out of bounds. |
|
|
486
|
+
|
|
487
|
+
#### `post.removeAuthor(slug): void`
|
|
488
|
+
|
|
489
|
+
Remove an author by slug.
|
|
490
|
+
|
|
491
|
+
#### `post.hasAuthorSlug(slug): boolean` / `post.hasAuthorName(name): boolean` / `post.hasAuthorEmail(email): boolean`
|
|
492
|
+
|
|
493
|
+
Check if the post has a specific author.
|
|
494
|
+
|
|
495
|
+
#### `post.setPrimaryAuthor({name, slug, email}): void`
|
|
496
|
+
|
|
497
|
+
Set an author as primary (moves them to sort order 1). Adds the author if they don't exist.
|
|
498
|
+
|
|
499
|
+
#### `post.setAuthorOrder(callback): void`
|
|
233
500
|
|
|
234
|
-
|
|
501
|
+
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.
|
|
235
502
|
|
|
503
|
+
```js
|
|
504
|
+
// Reverse the author order
|
|
505
|
+
post.setAuthorOrder((authors) => [...authors].reverse());
|
|
236
506
|
```
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
507
|
+
|
|
508
|
+
### Source & metadata
|
|
509
|
+
|
|
510
|
+
#### `post.source`
|
|
511
|
+
|
|
512
|
+
Access the source data object (set at construction). Not exported to Ghost JSON — use this to store original platform data for reference during migration.
|
|
513
|
+
|
|
514
|
+
#### `post.getSourceValue(key): any`
|
|
515
|
+
|
|
516
|
+
Get a single value from the source data.
|
|
517
|
+
|
|
518
|
+
#### `post.meta`
|
|
519
|
+
|
|
520
|
+
Access the metadata object.
|
|
521
|
+
|
|
522
|
+
#### `post.setMeta(value): void`
|
|
523
|
+
|
|
524
|
+
Replace the metadata object.
|
|
525
|
+
|
|
526
|
+
#### `post.getMetaValue(key): any`
|
|
527
|
+
|
|
528
|
+
Get a single metadata value.
|
|
529
|
+
|
|
530
|
+
### Deduplication
|
|
531
|
+
|
|
532
|
+
#### `post.lookupKey: string | null`
|
|
533
|
+
|
|
534
|
+
Get or set the lookup key. When a post with a matching lookup key already exists in the database, `save()` silently skips the insert.
|
|
535
|
+
|
|
536
|
+
```js
|
|
537
|
+
const post = await ctx.addPost({lookupKey: 'https://example.com/post-url'});
|
|
538
|
+
// ... set fields ...
|
|
539
|
+
await post.save(ctx.db);
|
|
540
|
+
|
|
541
|
+
// Second save with same key is a no-op
|
|
542
|
+
const dupe = await ctx.addPost({lookupKey: 'https://example.com/post-url'});
|
|
543
|
+
await dupe.save(ctx.db); // skipped
|
|
247
544
|
```
|
|
248
545
|
|
|
546
|
+
### Slug deduplication
|
|
249
547
|
|
|
250
|
-
|
|
548
|
+
#### `deduplicateSlugs(): Promise<DuplicateSlugEntry[]>`
|
|
251
549
|
|
|
252
|
-
|
|
550
|
+
Ghost requires unique slugs. When a migration source contains multiple posts with the same slug, this method renames newer duplicates by appending `-2`, `-3`, etc., while the oldest post keeps the original slug.
|
|
253
551
|
|
|
254
|
-
|
|
255
|
-
1. `git clone` this repo & `cd` into it as usual
|
|
256
|
-
2. Run `yarn` to install top-level dependencies.
|
|
552
|
+
Called automatically by `prepareForExport()`, so you typically don't need to call it directly. It only runs once — subsequent calls reuse the cached result.
|
|
257
553
|
|
|
554
|
+
After preparing, access the results via the `duplicateSlugs` getter to log renamed slugs for redirect handling:
|
|
258
555
|
|
|
259
|
-
|
|
556
|
+
```js
|
|
557
|
+
await ctx.prepareForExport();
|
|
558
|
+
|
|
559
|
+
for (const entry of ctx.duplicateSlugs) {
|
|
560
|
+
const label = entry.oldSlug === entry.newSlug ? 'kept' : 'renamed';
|
|
561
|
+
console.log(`[${label}] ${entry.newSlug} ${entry.url}`);
|
|
562
|
+
}
|
|
563
|
+
```
|
|
564
|
+
|
|
565
|
+
#### `duplicateSlugs: DuplicateSlugEntry[]`
|
|
566
|
+
|
|
567
|
+
Getter that returns the results of the most recent deduplication. Results are grouped by original slug. The first entry in each group is the retained post (`oldSlug === newSlug`), followed by the renamed ones.
|
|
568
|
+
|
|
569
|
+
| Field | Type | Description |
|
|
570
|
+
|-----------|----------|-------------------------------------------------------------------|
|
|
571
|
+
| `oldSlug` | `string` | The original (duplicate) slug |
|
|
572
|
+
| `newSlug` | `string` | The final slug — same as `oldSlug` for the retained post |
|
|
573
|
+
| `url` | `string` | Original URL from `source.url` or `canonical_url` (empty if none) |
|
|
574
|
+
|
|
575
|
+
Ordering is determined by `published_at` (falling back to `created_at`), so the earliest post keeps the original slug. If a suffix like `-2` already belongs to a real post, it skips to `-3`, etc.
|
|
576
|
+
|
|
577
|
+
See [examples/deduplicate-slugs.ts](examples/deduplicate-slugs.ts) for a complete example.
|
|
578
|
+
|
|
579
|
+
---
|
|
580
|
+
|
|
581
|
+
## TagContext
|
|
582
|
+
|
|
583
|
+
Represents a tag with validated properties.
|
|
260
584
|
|
|
261
|
-
|
|
585
|
+
### Constructor
|
|
262
586
|
|
|
587
|
+
```js
|
|
588
|
+
new TagContext({name: 'News', slug: 'news'})
|
|
589
|
+
// or
|
|
590
|
+
new TagContext({initialData: {name: 'News', slug: 'news'}})
|
|
591
|
+
```
|
|
592
|
+
|
|
593
|
+
### Methods
|
|
594
|
+
|
|
595
|
+
- `tag.get(prop): any`
|
|
596
|
+
- `tag.set(prop, value): TagContext`
|
|
597
|
+
- `tag.remove(prop): TagContext`
|
|
598
|
+
- `tag.save(db): void`
|
|
599
|
+
|
|
600
|
+
### Tag fields
|
|
601
|
+
|
|
602
|
+
| Field | Type | Max | Notes |
|
|
603
|
+
|-----------------------|-----------|-------|--------------|
|
|
604
|
+
| `name` | `string` | 255 | **Required** |
|
|
605
|
+
| `slug` | `string` | 191 | **Required** |
|
|
606
|
+
| `description` | `string?` | 500 | |
|
|
607
|
+
| `feature_image` | `string?` | 2000 | |
|
|
608
|
+
| `og_image` | `string?` | 2000 | |
|
|
609
|
+
| `og_title` | `string?` | 300 | |
|
|
610
|
+
| `og_description` | `string?` | 500 | |
|
|
611
|
+
| `twitter_image` | `string?` | 2000 | |
|
|
612
|
+
| `twitter_title` | `string?` | 300 | |
|
|
613
|
+
| `twitter_description` | `string?` | 500 | |
|
|
614
|
+
| `meta_title` | `string?` | 300 | |
|
|
615
|
+
| `meta_description` | `string?` | 500 | |
|
|
616
|
+
| `codeinjection_head` | `string?` | 65535 | |
|
|
617
|
+
| `codeinjection_foot` | `string?` | 65535 | |
|
|
618
|
+
| `canonical_url` | `string?` | 2000 | |
|
|
619
|
+
|
|
620
|
+
---
|
|
621
|
+
|
|
622
|
+
## AuthorContext
|
|
623
|
+
|
|
624
|
+
Represents an author with validated properties.
|
|
625
|
+
|
|
626
|
+
### Constructor
|
|
627
|
+
|
|
628
|
+
```js
|
|
629
|
+
new AuthorContext({name: 'Alice', slug: 'alice', email: 'alice@example.com'})
|
|
630
|
+
```
|
|
631
|
+
|
|
632
|
+
### Methods
|
|
633
|
+
|
|
634
|
+
- `author.get(prop): any`
|
|
635
|
+
- `author.set(prop, value): AuthorContext`
|
|
636
|
+
- `author.remove(prop): AuthorContext`
|
|
637
|
+
- `author.save(db): void`
|
|
638
|
+
|
|
639
|
+
### Author fields
|
|
640
|
+
|
|
641
|
+
| Field | Type | Max | Notes |
|
|
642
|
+
|--------------------|-----------|------|--------------------------------------------------------------|
|
|
643
|
+
| `name` | `string` | 191 | **Required** |
|
|
644
|
+
| `slug` | `string` | 191 | **Required** |
|
|
645
|
+
| `email` | `string` | 191 | **Required**, validated |
|
|
646
|
+
| `profile_image` | `string?` | 2000 | |
|
|
647
|
+
| `cover_image` | `string?` | 2000 | |
|
|
648
|
+
| `bio` | `string?` | 250 | |
|
|
649
|
+
| `website` | `string?` | 2000 | |
|
|
650
|
+
| `location` | `string?` | 150 | |
|
|
651
|
+
| `facebook` | `string?` | 2000 | |
|
|
652
|
+
| `twitter` | `string?` | 2000 | |
|
|
653
|
+
| `meta_title` | `string?` | 300 | |
|
|
654
|
+
| `meta_description` | `string?` | 500 | |
|
|
655
|
+
| `role` | `enum` | — | `Contributor` (default), `Author`, `Editor`, `Administrator` |
|
|
656
|
+
|
|
657
|
+
---
|
|
658
|
+
|
|
659
|
+
## Examples
|
|
660
|
+
|
|
661
|
+
The [examples/](examples/) directory contains runnable scripts demonstrating common patterns:
|
|
662
|
+
|
|
663
|
+
- **generate-and-export.ts** — Create 500 posts in-memory and export to Ghost JSON
|
|
664
|
+
- **reorder-tags-authors.ts** — Reorder tags and authors using `setTagOrder`, `setPrimaryTag`, and `addTag` with `sortOrder`
|
|
665
|
+
- **generate-large-export.ts** — Stress-test with 500k posts, benchmarking memory and performance
|
|
666
|
+
- **foreach-ghost-post.ts** — Iterate an existing database and log each post as Ghost JSON
|
|
667
|
+
- **deduplicate-slugs.ts** — Detect and rename duplicate slugs, then log the changes for manual redirect handling
|
|
668
|
+
|
|
669
|
+
Run any example from the package directory:
|
|
670
|
+
|
|
671
|
+
```bash
|
|
672
|
+
npx tsx examples/generate-and-export.ts
|
|
673
|
+
```
|
|
674
|
+
|
|
675
|
+
## Develop
|
|
676
|
+
|
|
677
|
+
This is a mono repository, managed with [Nx](https://nx.dev/) and yarn workspaces.
|
|
678
|
+
|
|
679
|
+
Follow the instructions for the top-level repo.
|
|
680
|
+
1. `git clone` this repo & `cd` into it as usual
|
|
681
|
+
2. Run `yarn` to install top-level dependencies.
|
|
263
682
|
|
|
264
683
|
## Test
|
|
265
684
|
|
|
266
685
|
- `yarn lint` run just eslint
|
|
267
686
|
- `yarn test` run lint and tests
|
|
268
687
|
|
|
269
|
-
|
|
270
688
|
# Copyright & License
|
|
271
689
|
|
|
272
690
|
Copyright (c) 2013-2026 Ghost Foundation - Released under the [MIT license](LICENSE).
|