@tryghost/mg-buttondown 0.11.8-0 → 0.12.0-0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/README.md +77 -6
  2. package/build/index.d.ts +5 -6
  3. package/build/index.js +3 -10
  4. package/build/index.js.map +1 -1
  5. package/build/lib/ingest.d.ts +20 -0
  6. package/build/lib/ingest.js +102 -0
  7. package/build/lib/ingest.js.map +1 -0
  8. package/build/lib/map.d.ts +12 -0
  9. package/build/lib/map.js +75 -0
  10. package/build/lib/map.js.map +1 -0
  11. package/build/lib/process.d.ts +6 -3
  12. package/build/lib/process.js +28 -12
  13. package/build/lib/process.js.map +1 -1
  14. package/build/lib/types.d.ts +15 -0
  15. package/build/lib/types.js +3 -0
  16. package/build/lib/types.js.map +1 -0
  17. package/build/test/helpers.d.ts +19 -0
  18. package/build/test/helpers.js +63 -0
  19. package/build/test/helpers.js.map +1 -0
  20. package/build/test/ingest.test.js +132 -0
  21. package/build/test/ingest.test.js.map +1 -0
  22. package/build/test/map.test.js +145 -0
  23. package/build/test/map.test.js.map +1 -0
  24. package/build/test/process.test.js +16 -22
  25. package/build/test/process.test.js.map +1 -1
  26. package/package.json +5 -5
  27. package/build/lib/mapper.d.ts +0 -9
  28. package/build/lib/mapper.js +0 -57
  29. package/build/lib/mapper.js.map +0 -1
  30. package/build/lib/read-zip.d.ts +0 -5
  31. package/build/lib/read-zip.js +0 -39
  32. package/build/lib/read-zip.js.map +0 -1
  33. package/build/test/mapper.test.js +0 -95
  34. package/build/test/mapper.test.js.map +0 -1
  35. package/build/test/read-zip.test.js +0 -71
  36. package/build/test/read-zip.test.js.map +0 -1
  37. /package/build/test/{mapper.test.d.ts → ingest.test.d.ts} +0 -0
  38. /package/build/test/{read-zip.test.d.ts → map.test.d.ts} +0 -0
package/README.md CHANGED
@@ -34,28 +34,99 @@ It's possible to pass more options, in order to achieve a better migration file
34
34
  - Path to a zip file
35
35
  - string - default: `null`
36
36
  - **`--url`** (required)
37
- - Site URL
37
+ - Site URL. Links to `<url>/<slug>` in the content are rewritten to the imported posts.
38
38
  - string - default: `null`
39
39
  - **`-s` `--scrape`**
40
40
  - Configure scraping tasks
41
41
  - string - default: `all`
42
42
  - Choices: `all`, `web`, `assets`, `none`
43
- - `all`: Scrape web metadata and download assets
44
- - `web`: Only scrape metadata from web pages
43
+ - `all`: Download assets
44
+ - `web`: Accepted for compatibility; Buttondown migrations do not scrape web pages
45
45
  - `assets`: Only download assets (images, media, files)
46
46
  - `none`: Skip all scraping tasks
47
- - **`--fallBackHTMLCard`**
48
- - Fall back to convert to HTMLCard, if standard Mobiledoc convert fails
49
- - bool - default: `true`
47
+ - **`--rereadSource`**
48
+ - Read the export zip again, replacing the stored source while preserving downloaded assets
49
+ - bool - default: `false`
50
+ - **`--postsPerFile`**
51
+ - Maximum posts written per Ghost import JSON file
52
+ - number - default: `2000`
50
53
  - **`--cache`**
51
54
  - Persist local cache after migration is complete (Only if `--zip` is `true`)
52
55
  - bool - default: `true`
56
+ - **`--tmpPath`**
57
+ - Specify the full path where the temporary files will be stored (Defaults a hidden tmp dir)
58
+ - string - default: `null`
59
+ - **`--outputPath`**
60
+ - Specify the full path where the final zip file will be saved to (Defaults to CWD)
61
+ - string - default: `null`
62
+ - **`--cacheName`**
63
+ - Provide a unique name for the cache directory
64
+ - string - default: one based on the export's full path
53
65
  - **`-V` `--verbose`**
54
66
  - Show verbose output
55
67
  - bool - default: `false`
56
68
  - **`--zip`**
57
69
  - Create a zip file
58
70
  - bool - default: `true`
71
+ - **`--report`**
72
+ - Write a `.report.json` migration report beside the import, or a `.failed-report.json` if the run fails
73
+ - bool - default: `false`
74
+ - **`--ghostApiUrl`**, **`--ghostAdminKey`**
75
+ - Accepted for compatibility. Buttondown exports name no authors, so there are no authors to match to Ghost users.
76
+ - string - default: `null`
77
+
78
+
79
+ ## Output
80
+
81
+ The import contains HTML; Ghost's importer converts it. `--fallBackHTMLCard` has been removed. A small migration writes `ghost-import.json`, and larger ones write `ghost-import-1.json`, `ghost-import-2.json` and so on, `--postsPerFile` posts each.
82
+
83
+ Each email becomes a published, public post tagged `#buttondown`, dated by its `publish_date` (a timestamp without a timezone is read as UTC). Its HTML is converted from its Markdown body: comments are removed, embedded tweets become embed cards, footnotes become an HTML card, and `{{ subscribe_form }}` and empty paragraphs are removed. Posts have no authors, as before, so Ghost's importer assigns them its default author.
84
+
85
+ With `--report`, a `.report.json` beside the ZIP (or in the workspace when `--zip false`) lists imported and skipped counts with diagnostics. Emails without an `id` or a `slug`, or with an invalid `publish_date`, are skipped and reported. An email without a body file is imported with empty HTML and a warning. When every selected email is invalid, or the run fails, `--report` writes a `.failed-report.json` instead. An export without emails succeeds with an empty import.
86
+
87
+
88
+ ## Source storage
89
+
90
+ The first run stores the export in an `mg-context` SQLite database in the workspace; later runs map the stored export again without reading the zip, even if it has moved. Use `--rereadSource` to read it again. Without `--cacheName`, the workspace is keyed by the export's full path, so exports that share a file name do not share stored data.
91
+
92
+ The zip is read one entry at a time, and may hold its files inside a single top-level directory. Each email in `emails.json` is stored as an `email` record keyed by its `id`; when the export has no `emails.json`, each row of `emails.csv` is stored instead, read one row at a time. `emails.json` holds only metadata and is parsed whole. Each `emails/*.md` file is stored as a `body` record keyed by its path, such as `emails/my-post.md`. An `id` or path that appears twice keeps its first record and reports a `source:conflict`. An export without `emails.json` or `emails.csv`, or whose emails have no body files at all, is rejected.
93
+
94
+ Mapping joins each email to `emails/<slug>.md` and follows the order of the email list. There are no filters, so changing `--url` needs no new read. Ghost IDs derive from `--url` and the email `id` or tag slug, so they stay the same across runs.
95
+
96
+
97
+ ## Programmatic API
98
+
99
+ The package exports `parse`, `ingest` and `map` for use with `@tryghost/mg-context`. The caller owns the context, asset scraping, export and closure:
100
+
101
+ ```js
102
+ import {MigrateContext} from '@tryghost/mg-context';
103
+ import {ingest, map} from '@tryghost/mg-buttondown';
104
+
105
+ const context = new MigrateContext({dbPath: './migration.sqlite'});
106
+ const rereadSource = process.argv.includes('--rereadSource');
107
+ await context.init();
108
+ try {
109
+ if (!context.sources.hasCompletedIngestion || rereadSource) {
110
+ await ingest('/path/to/export.zip', context, {replace: rereadSource});
111
+ }
112
+ const summary = await map({url: 'https://example.com'}, context);
113
+ for await (const file of context.writeGhostJsonStream('./output', {filename: 'ghost-import'})) {
114
+ // Consume one file descriptor at a time.
115
+ }
116
+ await context.writeMigrationReport('./migration.report.json', summary);
117
+ } finally {
118
+ await context.close();
119
+ }
120
+ ```
121
+
122
+ - `ingest(pathToZip, context, {replace})` reads the export into `context.sources` inside `context.sources.ingest()`. Explicit `replace: true` is required when completed source data exists; a failed read keeps the previous data.
123
+ - `parse(pathToZip)` yields the same records as `SourceRecordInput` values, one at a time, without storing them.
124
+ - `map({url}, context)` rebuilds mapped content and returns `{selected, imported, skipped}`. `url` is required.
125
+ - `contentStats(pathToZip)` counts the export's email bodies, `processHTML(markdown)` converts one body to HTML, and `ghostId(site, kind, key)` gives the stable Ghost ID `map()` uses.
126
+
127
+ The previous default export (`ingest({options})`, which built an array of posts in memory) and `readZip()` have been removed.
128
+
129
+ The CLI's programmatic `outputStorage.upload({body, fileName, size})` receives a Node readable stream as `body`, for the ZIP and, with `--report`, the report, and must consume it before resolving to the remote path. The uploaded ZIP is named like the local one, such as `gh-buttondown-export-1700000000000.zip`.
59
130
 
60
131
 
61
132
  ## Develop
package/build/index.d.ts CHANGED
@@ -1,6 +1,5 @@
1
- import { contentStats, readZip } from './lib/read-zip.js';
2
- export default _default;
3
- declare function _default(args: any): Promise<import("@tryghost/errors").NoContentError | {
4
- posts: mappedDataObject[];
5
- }>;
6
- export { contentStats, readZip };
1
+ export { contentStats, ingest, parse } from './lib/ingest.js';
2
+ export { ghostId, map } from './lib/map.js';
3
+ export { processHTML } from './lib/process.js';
4
+ export type { MappingSummary } from './lib/map.js';
5
+ export type { ButtondownEmail, ButtondownOptions } from './lib/types.js';
package/build/index.js CHANGED
@@ -1,11 +1,4 @@
1
- import { mapContent } from './lib/mapper.js';
2
- import { contentStats, readZip } from './lib/read-zip.js';
3
- export default async (args) => {
4
- const theZip = await readZip(args.options.pathToZip);
5
- args.posts = theZip.posts;
6
- args.json = theZip.json;
7
- const result = await mapContent(args);
8
- return result;
9
- };
10
- export { contentStats, readZip };
1
+ export { contentStats, ingest, parse } from './lib/ingest.js';
2
+ export { ghostId, map } from './lib/map.js';
3
+ export { processHTML } from './lib/process.js';
11
4
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,UAAU,EAAC,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAC,YAAY,EAAE,OAAO,EAAC,MAAM,mBAAmB,CAAC;AAExD,eAAe,KAAK,EAAE,IAAS,EAAE,EAAE;IAC/B,MAAM,MAAM,GAAG,MAAM,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;IACrD,IAAI,CAAC,KAAK,GAAG,MAAM,CAAC,KAAK,CAAC;IAC1B,IAAI,CAAC,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC;IAExB,MAAM,MAAM,GAAG,MAAM,UAAU,CAAC,IAAI,CAAC,CAAC;IACtC,OAAO,MAAM,CAAC;AAClB,CAAC,CAAC;AAEF,OAAO,EAAC,YAAY,EAAE,OAAO,EAAC,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,YAAY,EAAE,MAAM,EAAE,KAAK,EAAC,MAAM,iBAAiB,CAAC;AAC5D,OAAO,EAAC,OAAO,EAAE,GAAG,EAAC,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAC,WAAW,EAAC,MAAM,kBAAkB,CAAC"}
@@ -0,0 +1,20 @@
1
+ import type { MigrateContext, SourceRecordInput } from '@tryghost/mg-context';
2
+ /** Count the email bodies in a Buttondown export without reading them. */
3
+ export declare function contentStats(pathToZip: string): Promise<{
4
+ posts: number;
5
+ }>;
6
+ /**
7
+ * Yield the export's originals one at a time without storing them: each email in `emails.json` (or, without it, each
8
+ * row of `emails.csv`) as an `email` record keyed by its `id`, and each `emails/*.md` file as a `body` record keyed
9
+ * by its `emails/` path. Emails without an `id` are yielded unkeyed. Rejects an export without an email list, and one
10
+ * whose list names emails but that has no bodies.
11
+ */
12
+ export declare function parse(pathToZip: string): AsyncGenerator<SourceRecordInput>;
13
+ /**
14
+ * Read a Buttondown export zip into `context.sources`. An email `id` or body path that appears twice keeps its first
15
+ * record, and a differing duplicate is reported as a `source:conflict`. Explicit `replace: true` is required when
16
+ * completed source data exists; a failed read keeps the previous data.
17
+ */
18
+ export declare function ingest(pathToZip: string, context: MigrateContext, { replace }?: {
19
+ replace?: boolean;
20
+ }): Promise<void>;
@@ -0,0 +1,102 @@
1
+ import { basename } from 'node:path';
2
+ import fsUtils from '@tryghost/mg-fs-utils';
3
+ // A Buttondown export holds `emails.json` or `emails.csv` with each email's metadata, and `emails/<slug>.md` with
4
+ // each email's body, optionally inside one top-level directory. Entries are matched by their full path, as
5
+ // `zip.entries()` drops a directory that holds every entry from names.
6
+ const JSON_FILE = /(?:^|\/)emails\.json$/;
7
+ const CSV_FILE = /(?:^|\/)emails\.csv$/;
8
+ const BODY = /(?:^|\/)(emails\/[^/]+\.md)$/;
9
+ const isFile = (entry, pattern) => !entry.isDirectory && pattern.test(entry.path);
10
+ /** Count the email bodies in a Buttondown export without reading them. */
11
+ export async function contentStats(pathToZip) {
12
+ let posts = 0;
13
+ for await (const _entry of fsUtils.zip.entries(pathToZip, { filter: (entry) => isFile(entry, BODY) })) {
14
+ posts += 1;
15
+ }
16
+ return { posts };
17
+ }
18
+ /** The email list to read: `emails.json` when the export has one, as the old reader preferred it, else `emails.csv`. */
19
+ async function metadataFile(pathToZip) {
20
+ let csv = false;
21
+ const filter = (entry) => isFile(entry, JSON_FILE) || isFile(entry, CSV_FILE);
22
+ for await (const entry of fsUtils.zip.entries(pathToZip, { filter })) {
23
+ if (JSON_FILE.test(entry.path)) {
24
+ return JSON_FILE;
25
+ }
26
+ csv = true;
27
+ }
28
+ if (!csv) {
29
+ throw new Error(`${pathToZip}: No emails data found in zip (expected emails.json or emails.csv)`);
30
+ }
31
+ return CSV_FILE;
32
+ }
33
+ /**
34
+ * Yield the export's originals one at a time without storing them: each email in `emails.json` (or, without it, each
35
+ * row of `emails.csv`) as an `email` record keyed by its `id`, and each `emails/*.md` file as a `body` record keyed
36
+ * by its `emails/` path. Emails without an `id` are yielded unkeyed. Rejects an export without an email list, and one
37
+ * whose list names emails but that has no bodies.
38
+ */
39
+ export async function* parse(pathToZip) {
40
+ const list = await metadataFile(pathToZip);
41
+ let emails = 0;
42
+ let bodies = 0;
43
+ const filter = (entry) => isFile(entry, list) || isFile(entry, BODY);
44
+ for await (const entry of fsUtils.zip.entries(pathToZip, { filter })) {
45
+ if (BODY.test(entry.path)) {
46
+ bodies += 1;
47
+ yield {
48
+ kind: 'body',
49
+ key: entry.path.match(BODY)[1],
50
+ content: (await entry.read()).toString('utf8'),
51
+ format: 'markdown',
52
+ metadata: { file: entry.path }
53
+ };
54
+ }
55
+ else if (list === CSV_FILE) {
56
+ let row = 0;
57
+ for await (const data of fsUtils.csv.streamRows(await entry.stream())) {
58
+ row += 1;
59
+ emails += 1;
60
+ yield {
61
+ kind: 'email',
62
+ key: data.id || undefined,
63
+ content: JSON.stringify(data),
64
+ format: 'json',
65
+ metadata: { file: entry.path, row }
66
+ };
67
+ }
68
+ }
69
+ else {
70
+ const data = JSON.parse((await entry.read()).toString('utf8'));
71
+ if (!Array.isArray(data)) {
72
+ throw new Error(`${pathToZip}: ${entry.path} is not a list of emails`);
73
+ }
74
+ for (const [index, email] of data.entries()) {
75
+ emails += 1;
76
+ yield {
77
+ kind: 'email',
78
+ key: email?.id ? String(email.id) : undefined,
79
+ content: JSON.stringify(email),
80
+ format: 'json',
81
+ metadata: { file: entry.path, index }
82
+ };
83
+ }
84
+ }
85
+ }
86
+ if (emails && !bodies) {
87
+ throw new Error(`${pathToZip}: No email bodies (emails/*.md) found in the Buttondown export`);
88
+ }
89
+ }
90
+ /**
91
+ * Read a Buttondown export zip into `context.sources`. An email `id` or body path that appears twice keeps its first
92
+ * record, and a differing duplicate is reported as a `source:conflict`. Explicit `replace: true` is required when
93
+ * completed source data exists; a failed read keeps the previous data.
94
+ */
95
+ export async function ingest(pathToZip, context, { replace = false } = {}) {
96
+ await context.sources.ingest({ replace, metadata: { adapter: 'buttondown', file: basename(pathToZip) } }, async (stage) => {
97
+ for await (const record of parse(pathToZip)) {
98
+ stage.reconcile(record);
99
+ }
100
+ });
101
+ }
102
+ //# sourceMappingURL=ingest.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ingest.js","sourceRoot":"","sources":["../../src/lib/ingest.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,QAAQ,EAAC,MAAM,WAAW,CAAC;AACnC,OAAO,OAAO,MAAM,uBAAuB,CAAC;AAQ5C,kHAAkH;AAClH,2GAA2G;AAC3G,uEAAuE;AACvE,MAAM,SAAS,GAAG,uBAAuB,CAAC;AAC1C,MAAM,QAAQ,GAAG,sBAAsB,CAAC;AACxC,MAAM,IAAI,GAAG,8BAA8B,CAAC;AAC5C,MAAM,MAAM,GAAG,CAAC,KAAe,EAAE,OAAe,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,WAAW,IAAI,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;AAEpG,0EAA0E;AAC1E,MAAM,CAAC,KAAK,UAAU,YAAY,CAAC,SAAiB;IAChD,IAAI,KAAK,GAAG,CAAC,CAAC;IACd,IAAI,KAAK,EAAE,MAAM,MAAM,IAAI,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,SAAS,EAAE,EAAC,MAAM,EAAE,CAAC,KAAe,EAAE,EAAE,CAAC,MAAM,CAAC,KAAK,EAAE,IAAI,CAAC,EAAC,C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/mg-context';
3
+ import type { ButtondownOptions } from './types.js';
4
+ export type { MappingSummary };
5
+ export declare function ghostId(site: string, kind: string, key: string): string;
6
+ /**
7
+ * Rebuild posts and tags from the stored emails and their bodies. Each email is a published, public post tagged
8
+ * `#buttondown`, whose HTML is converted from its `emails/<slug>.md` body. Emails without an `id` or a `slug`, or
9
+ * with an invalid `publish_date`, are skipped with a `record:skipped` diagnostic. An email without a body is
10
+ * imported with empty HTML and an `operation:warning` diagnostic.
11
+ */
12
+ export declare function map(options: ButtondownOptions, context: MigrateContext): Promise<MappingSummary>;
@@ -0,0 +1,75 @@
1
+ import { PostContext, TagContext, RecordDataError, ghostId as coreGhostId } from '@tryghost/mg-context';
2
+ import { dateUtils, stringUtils, urlUtils } from '@tryghost/mg-utils';
3
+ import { processHTML } from './process.js';
4
+ export function ghostId(site, kind, key) {
5
+ return coreGhostId('mg-buttondown:1', site, kind, key);
6
+ }
7
+ /** The site URL without trailing slashes. */
8
+ function siteUrl(value) {
9
+ if (!urlUtils.httpUrl(value)) {
10
+ throw new Error('Buttondown migrations need the site URL (--url) as an HTTP or HTTPS URL.');
11
+ }
12
+ return urlUtils.trimTrailingSlashes(value.trim());
13
+ }
14
+ /** Buttondown writes `2023-01-02 16:55:00+00:00`; a zoneless timestamp is read as UTC. */
15
+ function publishDate(email) {
16
+ const date = dateUtils.parseDate(email.publish_date);
17
+ if (!date) {
18
+ throw new RecordDataError('Invalid Buttondown publish date');
19
+ }
20
+ return date;
21
+ }
22
+ /**
23
+ * Rebuild posts and tags from the stored emails and their bodies. Each email is a published, public post tagged
24
+ * `#buttondown`, whose HTML is converted from its `emails/<slug>.md` body. Emails without an `id` or a `slug`, or
25
+ * with an invalid `publish_date`, are skipped with a `record:skipped` diagnostic. An email without a body is
26
+ * imported with empty HTML and an `operation:warning` diagnostic.
27
+ */
28
+ export async function map(options, context) {
29
+ if (!context.sources.hasCompletedIngestion) {
30
+ throw new Error('Ingest a complete Buttondown export before mapping.');
31
+ }
32
+ const url = siteUrl(options.url);
33
+ const site = urlUtils.canonicalSite(url);
34
+ return context.rebuildMappedContent(() => context.mapRecords(context.sources.records({ kind: 'email' }), async (record) => {
35
+ if (!record.key) {
36
+ throw new RecordDataError('Email has no id');
37
+ }
38
+ const email = JSON.parse(record.content);
39
+ const slug = String(email.slug ?? '').trim();
40
+ if (!slug) {
41
+ throw new RecordDataError('Email has no slug');
42
+ }
43
+ const date = publishDate(email);
44
+ const bodyKey = `emails/${slug}.md`;
45
+ const body = context.sources.get('body', bodyKey);
46
+ if (!body) {
47
+ context.recordDiagnostic('operation:warning', { ...record.metadata, reason: 'No body file in the export for this email', body: bodyKey }, record.id);
48
+ }
49
+ const post = new PostContext({ lookupKey: record.key });
50
+ post.ghostId = ghostId(site, 'post', record.key);
51
+ post.set('title', String(email.subject ?? ''));
52
+ post.set('slug', slug);
53
+ post.set('created_at', date);
54
+ post.set('updated_at', date);
55
+ post.set('published_at', date);
56
+ post.set('type', 'post');
57
+ post.set('status', 'published');
58
+ post.set('visibility', 'public');
59
+ post.set('custom_excerpt', null);
60
+ // Trimmed here, so Ghost's schema does not report a change for every post.
61
+ post.set('html', processHTML(body?.content ?? '').trim());
62
+ const tag = new TagContext({ name: '#buttondown', slug: 'hash-buttondown' });
63
+ tag.ghostId = ghostId(site, 'tag', 'hash-buttondown');
64
+ tag.save(context.db);
65
+ post.addTag(tag);
66
+ context.sources.link(record.id, { type: 'tag', id: tag.dbId });
67
+ post.save(context.db);
68
+ context.sources.link(record.id, { type: 'post', id: post.dbId });
69
+ if (body) {
70
+ context.sources.link(body.id, { type: 'post', id: post.dbId });
71
+ }
72
+ context.addLink(stringUtils.cleanURL(`${url}/${slug}`), `/${post.get('slug')}/`);
73
+ }));
74
+ }
75
+ //# sourceMappingURL=map.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"map.js","sourceRoot":"","sources":["../../src/lib/map.ts"],"names":[],"mappings":"AAAA,OAAO,EAAiB,WAAW,EAAE,UAAU,EAAE,eAAe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AAE,EAAE,EAAE,IAAI,CAAC,IAAK,EAAC,CAAC,CAAC;QAChE,IAAI,IAAI,EAAE,CAAC;YACP,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,EAAE,EAAC,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,IAAI,CAAC,IAAK,EAAC,CAAC,CAAC;QAClE,CAAC;QACD,OAAO,CAAC,OAAO,CAAC,WAAW,CAAC,QAAQ,CAAC,GAAG,GAAG,IAAI,IAAI,EAAE,CAAC,EAAE,IAAI,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;IACrF,CAAC,CAAC,CACL,CAAC;AACN,CAAC"}
@@ -1,4 +1,7 @@
1
- declare const processHTML: ({ postData }: {
2
- postData?: mappedDataObject;
3
- }) => string;
1
+ /**
2
+ * Convert an email body from a Buttondown export, Markdown that may hold HTML, to Ghost HTML: comments are removed,
3
+ * embedded tweets become embed cards, footnotes become an HTML card, and `{{ subscribe_form }}` and empty
4
+ * paragraphs are removed.
5
+ */
6
+ declare const processHTML: (markdown: string) => string;
4
7
  export { processHTML };
@@ -2,22 +2,37 @@ import MarkdownIt from 'markdown-it';
2
2
  import MarkdownItFootnote from 'markdown-it-footnote';
3
3
  import { domUtils } from '@tryghost/mg-utils';
4
4
  const { serializeChildren, replaceWith, insertBefore, insertAfter, wrap, createElement } = domUtils;
5
- const processHTML = ({ postData }) => {
5
+ const MEDIA = 'img, picture, video, audio, iframe, embed, object, svg';
6
+ /**
7
+ * `html` without comments, including multi-line ones. A `<!--` with no `-->` after it is kept. Removing a comment can
8
+ * join the text around it into a new `<!--`, so the search resumes just before the removed comment.
9
+ */
10
+ const stripComments = (html) => {
11
+ let result = html;
12
+ let start = result.indexOf('<!--');
13
+ while (start !== -1) {
14
+ const end = result.indexOf('-->', start + 4);
15
+ if (end === -1) {
16
+ break;
17
+ }
18
+ result = result.slice(0, start) + result.slice(end + 3);
19
+ start = result.indexOf('<!--', Math.max(0, start - 3));
20
+ }
21
+ return result;
22
+ };
23
+ /**
24
+ * Convert an email body from a Buttondown export, Markdown that may hold HTML, to Ghost HTML: comments are removed,
25
+ * embedded tweets become embed cards, footnotes become an HTML card, and `{{ subscribe_form }}` and empty
26
+ * paragraphs are removed.
27
+ */
28
+ const processHTML = (markdown) => {
6
29
  const md = new MarkdownIt({
7
30
  html: true
8
31
  }).use(MarkdownItFootnote);
9
- if (!postData?.data?.html) {
32
+ if (!markdown) {
10
33
  return '';
11
34
  }
12
- let html = postData.data.html;
13
- // Strip HTML comments. `.` doesn't match newlines and a single pass can
14
- // leave `<!--` behind on nested comments, so match across lines and loop.
15
- let previousHtml;
16
- do {
17
- previousHtml = html;
18
- html = html.replace(/<!--[\s\S]*?-->/g, '');
19
- } while (html !== previousHtml);
20
- let renderedHtml = md.render(html);
35
+ let renderedHtml = md.render(stripComments(markdown));
21
36
  let finalHtml = domUtils.processFragment(renderedHtml, parsed => {
22
37
  // Handle embedded tweets
23
38
  parsed.$('blockquote.twitter-tweet').forEach(el => {
@@ -49,8 +64,9 @@ const processHTML = ({ postData }) => {
49
64
  el.remove();
50
65
  }
51
66
  });
67
+ // Remove empty paragraphs, but keep those that only hold media, such as a Markdown image.
52
68
  parsed.$('p').forEach(el => {
53
- if ((el.textContent || '').trim().length === 0) {
69
+ if ((el.textContent || '').trim().length === 0 && !el.querySelector(MEDIA)) {
54
70
  el.remove();
55
71
  }
56
72
  });
@@ -1 +1 @@
1
- {"version":3,"file":"process.js","sourceRoot":"","sources":["../../src/lib/process.ts"],"names":[],"mappings":"AAAA,OAAO,UAAU,MAAM,aAAa,CAAC;AACrC,OAAO,kBAAkB,MAAM,sBAAsB,CAAC;AACtD,OAAO,EAAC,QAAQ,EAAC,MAAM,oBAAoB,CAAC;AAE5C,MAAM,EAAC,iBAAiB,EAAE,WAAW,EAAE,YAAY,EAAE,WAAW,EAAE,IAAI,EAAE,aAAa,EAAC,GAAG,QAAQ,CAAC;AAElG,MAAM,WAAW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CAAC,OAAO,CAAC,EAAE,CAAC,EAAE;YAChC,YAAY,CAAC,EAAE,EAAE,4BAA4B,CAAC,CAAC;YAC/C,WAAW,CAAC,EAAE,EAAE,0BAA0B,CAAC,CAAC;QAChD,CAAC,CAAC,CAAC;QAEH,MAAM,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,OAAO,CAAC,EAAE,CAAC,EAAE;YACvB,IAAI,CAAC,EAAE,CAAC,WAAW,IAAI,EAAE,CAAC,CAAC,QAAQ,CAAC,sBAAsB,CAAC,EAAE,CAAC;gBAC1D,EAAE,CAAC,MAAM,EAAE,CAAC;YAChB,CAAC;QACL,CAAC,CAAC,CAAC;QAEH,0FAA0F;QAC1F,MAAM,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,OAAO,CAAC,EAAE,CAAC,EAAE;YACvB,IAAI,CAAC,EAAE,CAAC,WAAW,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC,MAAM,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC,aAAa,CAAC,KAAK,CAAC,EAAE,CAAC;gBACzE,EAAE,CAAC,MAAM,EAAE,CAAC;YAChB,CAAC;QACL,CAAC,CAAC,CAAC;QAEH,OAAO,MAAM,CAAC,IAAI,EAAE,CAAC;IACzB,CAAC,CAAC,CAAC;IAEH,OAAO,SAAS,CAAC;AACrB,CAAC,CAAC;AAEF,OAAO,EAAC,WAAW,EAAC,CAAC"}
@@ -0,0 +1,15 @@
1
+ /** One email from a Buttondown export's `emails.json`, or one row of its `emails.csv`. */
2
+ export interface ButtondownEmail {
3
+ id?: string;
4
+ secondary_id?: string | number;
5
+ subject?: string;
6
+ publish_date?: string;
7
+ source?: string;
8
+ slug?: string;
9
+ [field: string]: unknown;
10
+ }
11
+ export interface ButtondownOptions {
12
+ /** The live site URL, such as `https://example.com`. Each email's old URL is `<url>/<slug>`. Required. */
13
+ url: string;
14
+ [key: string]: any;
15
+ }
@@ -0,0 +1,3 @@
1
+ export {};
2
+ /* c8 ignore stop */
3
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/lib/types.ts"],"names":[],"mappings":";AAiBA,oBAAoB"}
@@ -0,0 +1,19 @@
1
+ import { MigrateContext } from '@tryghost/mg-context';
2
+ export declare const SITE = "https://example.com";
3
+ /** A fixture file's contents, by its path under `fixtures`. */
4
+ export declare function fixture(path: string): Promise<string>;
5
+ /** The fixture export's files: `emails.json` or `emails.csv`, and both email bodies. */
6
+ export declare function fixtureExport(list?: 'emails.json' | 'emails.csv'): Promise<Record<string, string>>;
7
+ /** A new temporary directory, removed by `cleanUp()`. */
8
+ export declare function tempDirectory(): Promise<string>;
9
+ /** Write `files` (path in the zip → contents) into a zip, and return its path. */
10
+ export declare function makeZip(files: Record<string, string>): Promise<string>;
11
+ /** An `emails.json` listing `emails`. */
12
+ export declare function emailsJson(emails: unknown[]): string;
13
+ export declare function cleanUp(): Promise<void>;
14
+ export declare function memoryContext(): Promise<MigrateContext>;
15
+ /** A context holding the ingested export at `path`, or a zip of `files`. */
16
+ export declare function ingested(input: string | Record<string, string>): Promise<MigrateContext>;
17
+ export declare function events(context: MigrateContext, type: string): {
18
+ details: Record<string, any>;
19
+ }[];
@@ -0,0 +1,63 @@
1
+ import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
2
+ import { tmpdir } from 'node:os';
3
+ import { dirname, join } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import fsUtils from '@tryghost/mg-fs-utils';
6
+ import { MigrateContext } from '@tryghost/mg-context';
7
+ import { ingest } from '../index.js';
8
+ export const SITE = 'https://example.com';
9
+ const fixtures = fileURLToPath(new URL('../../src/test/fixtures/', import.meta.url));
10
+ /** A fixture file's contents, by its path under `fixtures`. */
11
+ export function fixture(path) {
12
+ return readFile(join(fixtures, path), 'utf8');
13
+ }
14
+ /** The fixture export's files: `emails.json` or `emails.csv`, and both email bodies. */
15
+ export async function fixtureExport(list = 'emails.json') {
16
+ return {
17
+ [list]: await fixture(list),
18
+ 'emails/plain-post.md': await fixture('emails/plain-post.md'),
19
+ 'emails/fancy-post.md': await fixture('emails/fancy-post.md')
20
+ };
21
+ }
22
+ const directories = [];
23
+ /** A new temporary directory, removed by `cleanUp()`. */
24
+ export async function tempDirectory() {
25
+ const directory = await mkdtemp(join(tmpdir(), 'mg-buttondown-test-'));
26
+ directories.push(directory);
27
+ return directory;
28
+ }
29
+ /** Write `files` (path in the zip → contents) into a zip, and return its path. */
30
+ export async function makeZip(files) {
31
+ const directory = await tempDirectory();
32
+ const content = join(directory, 'content');
33
+ for (const [path, contents] of Object.entries(files)) {
34
+ await mkdir(dirname(join(content, path)), { recursive: true });
35
+ await writeFile(join(content, path), contents);
36
+ }
37
+ const result = await fsUtils.zip.write(directory, content, 'export.zip');
38
+ return result.path;
39
+ }
40
+ /** An `emails.json` listing `emails`. */
41
+ export function emailsJson(emails) {
42
+ return JSON.stringify(emails);
43
+ }
44
+ export async function cleanUp() {
45
+ for (const directory of directories.splice(0)) {
46
+ await rm(directory, { recursive: true, force: true });
47
+ }
48
+ }
49
+ export async function memoryContext() {
50
+ const context = new MigrateContext({ storage: 'memory' });
51
+ await context.init();
52
+ return context;
53
+ }
54
+ /** A context holding the ingested export at `path`, or a zip of `files`. */
55
+ export async function ingested(input) {
56
+ const context = await memoryContext();
57
+ await ingest(typeof input === 'string' ? input : await makeZip(input), context);
58
+ return context;
59
+ }
60
+ export function events(context, type) {
61
+ return context.getMigrationReport().events.filter(event => event.type === type);
62
+ }
63
+ //# sourceMappingURL=helpers.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"helpers.js","sourceRoot":"","sources":["../../src/test/helpers.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,EAAE,EAAE,SAAS,EAAC,MAAM,kBAAkB,CAAC;AACzE,OAAO,EAAC,MAAM,EAAC,MAAM,SAAS,CAAC;AAC/B,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