@tryghost/mg-jekyll-export 0.13.7 → 0.14.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.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Migrate Jekyll Export
2
2
 
3
- Migrate content from Jekyll using the supplied zip file, and generate a `zip` file you can import into a Ghost installation.
3
+ Migrate content from Jekyll using a zip (or directory) of the site, and generate a `zip` file you can import into a Ghost installation.
4
4
 
5
5
 
6
6
  ## Install
@@ -25,10 +25,10 @@ or
25
25
  To run a Jekyll migration, the required command is:
26
26
 
27
27
  ```sh
28
- migrate jekyll --pathToZip /path/to/site.zip
28
+ migrate jekyll --pathToZip /path/to/site.zip --url https://example.com
29
29
  ```
30
30
 
31
- The zip should have a structure like:
31
+ The zip, or the directory passed instead, should have a structure like:
32
32
 
33
33
  ```
34
34
  _posts/
@@ -36,55 +36,133 @@ _posts/
36
36
  ├── 2021-05-19-another-post.markdown
37
37
  └── 2023-06-03-newest-post.html
38
38
  _drafts/
39
- └── 2023-06-03-some-draft.md
39
+ └── some-draft.md
40
40
  ```
41
+
42
+ The site may also sit in one directory at the top of the zip, and a zip of the `_posts` directory alone works too.
43
+
41
44
  It's possible to pass more options, in order to achieve a better migration file for Ghost:
42
45
 
43
46
  - **`--pathToZip`** (required)
44
- - Path to a jekyll export zip
47
+ - Path to a Jekyll site zip, or the site directory, holding `_posts/` and `_drafts/`
45
48
  - string - default: `null`
46
- - **`-V` `--verbose`**
47
- - bool - default: `false`
48
- - Show verbose output
49
- - **`--zip`**
50
- - bool - default: `true`
51
- - Create a zip file
52
- - **`-s` `--scrape`**
49
+ - **`-u` `--url`** (required)
50
+ - URL to the live site. It makes root-relative links and images absolute, gives each post its old URL for scraping and link rewriting, and scopes the stable Ghost IDs
51
+ - string - default: `null`
52
+ - **`-s` `--scrape`**
53
53
  - Configure scraping tasks
54
- - string - default: `all`
54
+ - array - default: `all`
55
55
  - Choices: `all`, `web`, `assets`, `none`
56
56
  - `all`: Scrape web metadata and download assets
57
- - `web`: Only scrape metadata from web pages
57
+ - `web`: Only scrape metadata from each published post's page on the live site
58
58
  - `assets`: Only download assets (images, media, files)
59
59
  - `none`: Skip all scraping tasks
60
- - **`-u` `--url`**
61
- - string - default: `false`
62
- - Provide a URL (without trailing slash) to the hosted source site
63
60
  - **`-e` `--email`**
64
- - string - default: `false`
65
- - Provide an email domain for users e.g. example.com
61
+ - Provide an email domain for authors' placeholder emails, e.g. `example.com`
62
+ - string - default: `false` (`example.com`)
66
63
  - **`--addTags`**
64
+ - Provide one or more comma-separated tag names which should be added to every post in this migration.
65
+ This is in addition to a `#jekyll` tag, which is always added.
67
66
  - string - default: `null`
68
- - Provide one or more tag names which should be added to every post in this migration.
69
- This is addition to a '#jekyll' tag, which is always added.
70
- - **`--datedPermalinks`**
71
- - Set the dated permalink structure
72
- - string - default: `none`
73
- - Choices: `none`, `'/yyyy/mm/'`, `'/yyyy/mm/dd/'`
74
- - **`--fallBackHTMLCard`**
75
- - bool - default: `true`
76
- - Fall back to convert to HTMLCard, if standard Mobiledoc convert fails
77
- - **`--cache`**
67
+ - **`--datedPermalinks`**
68
+ - The dated permalink structure of the live site. Posts' old URLs include the date, and links to them are rewritten to dated paths, such as `/2021/08/23/my-post/`
69
+ - string - default: `none`
70
+ - Choices: `none`, `/yyyy/mm/`, `/yyyy/mm/dd/`
71
+ - **`--rereadSource`**
72
+ - Read the export again, replacing the stored source while preserving downloaded assets
73
+ - bool - default: `false`
74
+ - **`--postsPerFile`**
75
+ - Maximum posts written per Ghost import JSON file
76
+ - number - default: `2000`
77
+ - **`--cache`**
78
78
  - Persist local cache after migration is complete (Only if `--zip` is `true`)
79
79
  - bool - default: `true`
80
+ - **`--tmpPath`**
81
+ - Specify the full path where the temporary files will be stored (Defaults a hidden tmp dir)
82
+ - string - default: `null`
83
+ - **`--outputPath`**
84
+ - Specify the full path where the final zip file will be saved to (Defaults to CWD)
85
+ - string - default: `null`
86
+ - **`--cacheName`**
87
+ - Provide a unique name for the cache directory
88
+ - string - default: one based on the export's full path
89
+ - **`-V` `--verbose`**
90
+ - Show verbose output
91
+ - bool - default: `false`
92
+ - **`--zip`**
93
+ - Create a zip file
94
+ - bool - default: `true`
95
+ - **`--report`**
96
+ - Write a `.report.json` migration report beside the import, or a `.failed-report.json` if the run fails
97
+ - bool - default: `false`
98
+ - **`--ghostApiUrl`**, **`--ghostAdminKey`**
99
+ - Match authors to existing Ghost users by their placeholder email
100
+ - string - default: `null`
80
101
 
81
102
  A more complex migration command could look like this:
82
103
 
83
104
  ```sh
84
- migrate jekyll --pathToZip /path/to/site.zip --email example.com
105
+ migrate jekyll --pathToZip /path/to/site.zip --url https://example.com --email example.com --addTags "Blog, #imported"
85
106
  ```
86
107
 
87
- This will process all posts from the zip file, and all authors will have an email address ending in 'example.com'
108
+ This will process all posts from the zip file, give all authors an email address ending in `example.com`, and add the `Blog` and `#imported` tags to every post.
109
+
110
+
111
+ ## Output
112
+
113
+ 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.
114
+
115
+ Each `.md` or `.markdown` file is rendered from Markdown (raw HTML in it is kept), and each `.html` file is kept as it is. Root-relative links and image sources become absolute URLs on `--url`'s origin, and a paragraph inside a list item is unwrapped. Links to other posts in the migration point at their new paths.
116
+
117
+ A post's slug is its front matter `basename`, or its file name without the date and extension (`my-post` for `2021-08-23-my-post.md`), slugified. Its title is the front matter `title`, or `(Untitled)`. Files in `_drafts/`, and posts with `published: false`, are drafts. A post's date is its front matter `date` (Jekyll's `YYYY-MM-DD HH:MM:SS +/-TTTT`; the time, seconds and offset are optional, and a date without an offset is read as UTC), or the date in its file name when the front matter has none or an invalid one. It is used as the created, published and updated date. A draft without either is dated when the export was read; a published post without either is skipped.
118
+
119
+ A post's authors are its front matter `author` names (a name or a list), each with a `<slug>@<--email>` placeholder email and the Contributor role; a post without one gets the Example User (`exampleuser@example.com`). Authors with the same placeholder email are one user. Its tags are its `category` and `categories` (as `category-<slug>` tags, first so the first category is the primary tag), then `tag` and `tags` (a list, or space-separated names), then `--addTags`. Internal `#` tags come last: a `#<directory>` tag for a post in a subdirectory of `_posts/` or `_drafts/`, `#jekyll`, and any `#` tags from `--addTags`. Tags with the same slug are one tag.
120
+
121
+ With `--report`, a `.report.json` beside the ZIP (or in the workspace when `--zip false`) lists imported and skipped counts with diagnostics. Posts without a valid date, or whose front matter is not valid YAML, are skipped and reported, and a page that cannot be scraped is reported as a warning. When every post is invalid, or the run fails, `--report` writes a `.failed-report.json` instead.
122
+
123
+
124
+ ## Source storage
125
+
126
+ The first run stores the export in an `mg-context` SQLite database in the workspace; later runs map the stored posts again without reading the export, even if it has moved. Use `--rereadSource` to read it again. Without `--cacheName`, the workspace is keyed by the export's full path, so different exports never share stored data.
127
+
128
+ The zip is read one entry at a time. Every `.md`, `.markdown` or `.html` file in `_posts/` or `_drafts/`, at any depth, is stored unparsed as a `post` record keyed by its path from the site root, such as `_posts/2021-08-23-my-post.md`; other files are not read. An export without posts is rejected and keeps any stored data.
129
+
130
+ Front matter and Markdown are parsed when the stored posts are mapped, and every option applies then, so changing `--url`, `--email`, `--addTags` or `--datedPermalinks` needs no new read. Ghost IDs derive from `--url` and the post's path, tag slug or author email, so they stay the same across runs.
131
+
132
+
133
+ ## Programmatic API
134
+
135
+ The package exports `parse`, `ingest` and `map` for use with `@tryghost/mg-context`. The caller owns the context, export and closure:
136
+
137
+ ```js
138
+ import {MigrateContext} from '@tryghost/mg-context';
139
+ import {ingest, map} from '@tryghost/mg-jekyll-export';
140
+
141
+ const context = new MigrateContext({dbPath: './migration.sqlite'});
142
+ const rereadSource = process.argv.includes('--rereadSource');
143
+ await context.init();
144
+ try {
145
+ if (!context.sources.hasCompletedIngestion || rereadSource) {
146
+ await ingest('/path/to/site.zip', context, {replace: rereadSource});
147
+ }
148
+ const summary = await map({url: 'https://example.com', addTags: 'Blog'}, context);
149
+ for await (const file of context.writeGhostJsonStream('./output', {filename: 'ghost-import'})) {
150
+ // Consume one file descriptor at a time.
151
+ }
152
+ await context.writeMigrationReport('./migration.report.json', summary);
153
+ } finally {
154
+ await context.close();
155
+ }
156
+ ```
157
+
158
+ - `ingest(input, context, {replace})` reads a site zip or directory into `context.sources` inside `context.sources.ingest()`. Explicit `replace: true` is required when completed source data exists; a failed read keeps the previous data. A path that appears twice in a zip keeps its first copy and reports a `source:conflict`.
159
+ - `parse(input)` yields the same records as `SourceRecordInput` values, one at a time, without storing them.
160
+ - `map({url, email, addTags, datedPermalinks}, context, {ghostUsers?})` rebuilds mapped content and returns `{selected, imported, skipped}`. `url` is required. `ghostUsers` may be an iterable or async iterable of existing Ghost users; when one has an author's placeholder email, posts keep that user's Ghost ID, slug and roles, and Ghost users' slugs are reserved for them.
161
+ - `processPost(path, contents, {url, addTags})` reads one post file into its slug, title, status, date, HTML, author names and tags; `parseFrontMatter(contents)`, `parseDate(value)` and `processHtml(html, url)` are its parts. `postUrl(options, post)` and `sourceUrl(options, record)` give a post's URL on the live site, and `ghostId(site, kind, key)` the stable Ghost ID `map()` uses.
162
+
163
+ The previous default export (`(pathToZip, options)`, which read every post into memory and returned `{posts}` for `toGhostJSON`) has been removed.
164
+
165
+ 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.
88
166
 
89
167
 
90
168
  ## Develop
@@ -101,13 +179,13 @@ Follow the instructions for the top-level repo.
101
179
  To run a local development copy, `cd` into this directory, and use `pnpm dev` instead of `migrate` like so:
102
180
 
103
181
  ```sh
104
- pnpm dev jekyll --pathToZip /path/to/site.zip
182
+ pnpm dev jekyll --pathToZip /path/to/site.zip --url https://example.com
105
183
  ```
106
184
 
107
185
 
108
186
  ## Test
109
187
 
110
- - `pnpm test` runs the package tests
188
+ - `pnpm test:local` builds the package and runs its tests with 100% coverage
111
189
  - Linting and formatting are run from the repo root (`pnpm lint`, `pnpm format`)
112
190
 
113
191
 
@@ -0,0 +1,6 @@
1
+ export { ingest, parse } from './lib/ingest.js';
2
+ export { ghostId, map, postUrl, sourceUrl } from './lib/map.js';
3
+ export { parseDate, parseFrontMatter, processPost } from './lib/process-post.js';
4
+ export { default as processHtml } from './lib/process-html.js';
5
+ export type { MappingServices, MappingSummary } from './lib/map.js';
6
+ export type { JekyllOptions, JekyllPost, JekyllTag } from './lib/types.js';
package/build/index.js ADDED
@@ -0,0 +1,5 @@
1
+ export { ingest, parse } from './lib/ingest.js';
2
+ export { ghostId, map, postUrl, sourceUrl } from './lib/map.js';
3
+ export { parseDate, parseFrontMatter, processPost } from './lib/process-post.js';
4
+ export { default as processHtml } from './lib/process-html.js';
5
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,MAAM,EAAE,KAAK,EAAC,MAAM,iBAAiB,CAAC;AAC9C,OAAO,EAAC,OAAO,EAAE,GAAG,EAAE,OAAO,EAAE,SAAS,EAAC,MAAM,cAAc,CAAC;AAC9D,OAAO,EAAC,SAAS,EAAE,gBAAgB,EAAE,WAAW,EAAC,MAAM,uBAAuB,CAAC;AAC/E,OAAO,EAAC,OAAO,IAAI,WAAW,EAAC,MAAM,uBAAuB,CAAC"}
@@ -0,0 +1,15 @@
1
+ import type { MigrateContext, SourceRecordInput } from '@tryghost/mg-context';
2
+ /**
3
+ * Yield the originals of a Jekyll site one at a time without storing them: each Markdown or HTML file in `_posts/`
4
+ * or `_drafts/` as a `post` record keyed by its path from the site root, holding the file's text. `input` is a zip
5
+ * of the site or the site's directory. Other files are not read. Rejects an input without posts.
6
+ */
7
+ export declare function parse(input: string): AsyncGenerator<SourceRecordInput>;
8
+ /**
9
+ * Read a Jekyll site zip or directory into `context.sources`. A path that appears twice in a zip keeps its first
10
+ * copy and reports a `source:conflict` when the copies differ. Explicit `replace: true` is required when completed
11
+ * source data exists; a failed read keeps the previous data.
12
+ */
13
+ export declare function ingest(input: string, context: MigrateContext, { replace }?: {
14
+ replace?: boolean;
15
+ }): Promise<void>;
@@ -0,0 +1,54 @@
1
+ import { readFile, stat } from 'node:fs/promises';
2
+ import { basename, resolve } from 'node:path';
3
+ import fsUtils from '@tryghost/mg-fs-utils';
4
+ /** Jekyll keeps posts in `_posts/` and drafts in `_drafts/`, at any depth below them. */
5
+ const POST = /^_(?:posts|drafts)\/.+\.(?:md|markdown|html)$/;
6
+ /** The post files of one site zip or directory, one at a time, in archive or path order. */
7
+ async function* postFiles(input) {
8
+ if ((await stat(input)).isDirectory()) {
9
+ for (const file of await fsUtils.listInputFiles(input, '_{posts,drafts}/**/*.{md,markdown,html}')) {
10
+ yield { path: file.name, read: () => readFile(file.path) };
11
+ }
12
+ return;
13
+ }
14
+ for await (const entry of fsUtils.zip.entries(input)) {
15
+ // Entry names drop a top-level directory holding the whole site; a zip of `_posts/` alone keeps it in `path`.
16
+ const path = [entry.name, entry.path].find(name => POST.test(name));
17
+ if (path) {
18
+ yield { path, read: () => entry.read() };
19
+ }
20
+ }
21
+ }
22
+ /**
23
+ * Yield the originals of a Jekyll site one at a time without storing them: each Markdown or HTML file in `_posts/`
24
+ * or `_drafts/` as a `post` record keyed by its path from the site root, holding the file's text. `input` is a zip
25
+ * of the site or the site's directory. Other files are not read. Rejects an input without posts.
26
+ */
27
+ export async function* parse(input) {
28
+ let found = false;
29
+ for await (const file of postFiles(input)) {
30
+ found = true;
31
+ yield {
32
+ kind: 'post',
33
+ key: file.path,
34
+ content: (await file.read()).toString('utf8'),
35
+ format: file.path.endsWith('.html') ? 'html' : 'markdown'
36
+ };
37
+ }
38
+ if (!found) {
39
+ throw new Error(`${input}: No Jekyll posts found (expected .md, .markdown or .html files in _posts/ or _drafts/)`);
40
+ }
41
+ }
42
+ /**
43
+ * Read a Jekyll site zip or directory into `context.sources`. A path that appears twice in a zip keeps its first
44
+ * copy and reports a `source:conflict` when the copies differ. Explicit `replace: true` is required when completed
45
+ * source data exists; a failed read keeps the previous data.
46
+ */
47
+ export async function ingest(input, context, { replace = false } = {}) {
48
+ await context.sources.ingest({ replace, metadata: { adapter: 'jekyll', file: basename(resolve(input)) } }, async (stage) => {
49
+ for await (const record of parse(input)) {
50
+ stage.reconcile(record, { choose: () => 'keep' });
51
+ }
52
+ });
53
+ }
54
+ //# 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,EAAE,IAAI,EAAC,MAAM,kBAAkB,CAAC;AAChD,OAAO,EAAC,QAAQ,EAAE,OAAO,EAAC,MAAM,WAAW,CAAC;AAC5C,OAAO,OAAO,MAAM,uBAAuB,CAAC;AAG5C,yFAAyF;AACzF,MAAM,IAAI,GAAG,+CAA+C,CAAC;AAQ7D,4FAA4F;AAC5F,KAAK,SAAS,CAAC,CAAC,SAAS,CAAC,KAAa;IACnC,IAAI,CAAC,MAAM,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,WAAW,EAAE,EAAE,CAAC;QACpC,KAAK,MAAM,IAAI,IAAI,MAAM,OAAO,CAAC,cAAc,CAAC,KAAK,EAAE,yCAAyC,CAAC,EAAE,CAAC;YAChG,MAAM,EAAC,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,GAAG,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,EAAC,CAAC;QAC7D,CAAC;QACD,OAAO;IACX,CAAC;IACD,IAAI,KAAK,EAAE,MAAM,KAAK,IAAI,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;QACnD,8GAA8G;QAC9G,MAAM,IAAI,GAAG,CAAC,KAAK,CAAC,IAAI,EAAE,KAAK,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,IAA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AAM,IAAI,KAAK,CAAC,KAAK,CAAC,EAAE,CAAC;YACtC,KAAK,CAAC,SAAS,CAAC,MAAM,EAAE,EAAC,MAAM,EAAE,GAAG,EAAE,CAAC,MAAM,EAAC,CAAC,CAAC;QACpD,CAAC;IACL,CAAC,CACJ,CAAC;AACN,CAAC"}
@@ -0,0 +1,29 @@
1
+ import { MigrateContext } from '@tryghost/mg-context';
2
+ import type { MappingSummary } from '@tryghost/mg-context';
3
+ import type { GhostUser } from '@tryghost/mg-ghost-authors';
4
+ import type { JekyllOptions, JekyllPost } from './types.js';
5
+ export type { MappingSummary };
6
+ export interface MappingServices {
7
+ /** Existing Ghost users; an author whose placeholder email matches one keeps that user's ID, slug and roles. */
8
+ ghostUsers?: Iterable<GhostUser> | AsyncIterable<GhostUser>;
9
+ }
10
+ /** A stable Ghost ID for a post path, tag slug or author email, scoped to the site. */
11
+ export declare function ghostId(site: string, kind: string, key: string): string;
12
+ /**
13
+ * A post's URL on the live site: `--url`, the date prefix `--datedPermalinks` describes (from the post's UTC date),
14
+ * and the post's source slug, such as `https://example.com/2021/08/23/my-post`.
15
+ */
16
+ export declare function postUrl(options: Pick<JekyllOptions, 'url' | 'datedPermalinks'>, post: Pick<JekyllPost, 'sourceSlug' | 'date'>): string;
17
+ /** The live URL of a stored post record. Throws a `RecordDataError` for invalid front matter. */
18
+ export declare function sourceUrl(options: Pick<JekyllOptions, 'url' | 'datedPermalinks'>, record: {
19
+ key: string | null;
20
+ content: string;
21
+ }): string;
22
+ /**
23
+ * Rebuild posts, tags and authors from the stored post files. Each file becomes a post dated by its front matter
24
+ * `date` or the date in its file name (a draft without either is dated when the export was read), with its
25
+ * `author` names as authors (the Example User when it has none) and its categories, tags, `addTags`, and `#jekyll`
26
+ * as tags. Every option applies here, so changing one needs no new read. Posts without a valid date, and files with
27
+ * invalid front matter, are skipped with a `record:skipped` diagnostic.
28
+ */
29
+ export declare function map(options: JekyllOptions, context: MigrateContext, services?: MappingServices): Promise<MappingSummary>;
@@ -0,0 +1,157 @@
1
+ import { AuthorContext, MappingState, PostContext, RecordDataError, TagContext, ghostId as coreGhostId } from '@tryghost/mg-context';
2
+ import { mergeUsersWithGhost } from '@tryghost/mg-ghost-authors';
3
+ import { slugify } from '@tryghost/string';
4
+ import { stringUtils, urlUtils } from '@tryghost/mg-utils';
5
+ import { processPost, readPost } from './process-post.js';
6
+ const ROLES = ['Contributor', 'Author', 'Editor', 'Administrator'];
7
+ /** A stable Ghost ID for a post path, tag slug or author email, scoped to the site. */
8
+ export function ghostId(site, kind, key) {
9
+ return coreGhostId('mg-jekyll-export:1', site, kind, key);
10
+ }
11
+ function siteUrl(value) {
12
+ const url = urlUtils.httpUrl(value);
13
+ if (!url) {
14
+ throw new Error('Jekyll migrations need the site URL (--url) as an HTTP or HTTPS URL.');
15
+ }
16
+ return url;
17
+ }
18
+ /** The path prefix a dated permalink structure gives a post, such as `2021/08/23/` for `/yyyy/mm/dd/`. */
19
+ function datedPrefix(date, structure) {
20
+ if (!date || !structure) {
21
+ return '';
22
+ }
23
+ const [year, month, day] = date.toISOString().slice(0, 10).split('-');
24
+ if (structure.includes('yyyy/mm/dd')) {
25
+ return `${year}/${month}/${day}/`;
26
+ }
27
+ return structure.includes('yyyy/mm') ? `${year}/${month}/` : '';
28
+ }
29
+ /**
30
+ * A post's URL on the live site: `--url`, the date prefix `--datedPermalinks` describes (from the post's UTC date),
31
+ * and the post's source slug, such as `https://example.com/2021/08/23/my-post`.
32
+ */
33
+ export function postUrl(options, post) {
34
+ const base = urlUtils.trimTrailingSlashes(siteUrl(options.url).href);
35
+ return `${base}/${datedPrefix(post.date, options.datedPermalinks)}${post.sourceSlug}`;
36
+ }
37
+ /** The live URL of a stored post record. Throws a `RecordDataError` for invalid front matter. */
38
+ export function sourceUrl(options, record) {
39
+ return postUrl(options, readPost(record.key, record.content));
40
+ }
41
+ const placeholderEmail = (slug, domain) => `${slug.slice(0, 50).replace(/-+$/, '')}@${domain}`;
42
+ /**
43
+ * The saved author for a placeholder email. Authors are identified by that email, so names with the same slug are
44
+ * one user. A Ghost user with the same email supplies its ID, slug and roles.
45
+ */
46
+ function authorEntity(state, site, author) {
47
+ const context = state.context;
48
+ const key = author.email.toLowerCase();
49
+ const binding = state.getBinding('author', key);
50
+ if (binding) {
51
+ return AuthorContext.fromRow(context.db.stmts.findAuthorById.get(binding));
52
+ }
53
+ const match = state.get('ghost-user', key);
54
+ const user = { ...author, roles: ['Contributor'] };
55
+ const data = match ? { ...mergeUsersWithGhost([{ url: '', data: user }], [match])[0].data } : user;
56
+ const id = data.id || ghostId(site, 'author', key);
57
+ delete data.id;
58
+ if (data.roles.some((role) => !ROLES.includes(role))) {
59
+ context.recordDiagnostic('operation:warning', {
60
+ author: author.name,
61
+ reason: 'Unsupported author roles replaced by supported Ghost roles'
62
+ });
63
+ data.roles = data.roles.filter((role) => ROLES.includes(role));
64
+ if (!data.roles.length) {
65
+ data.roles = ['Contributor'];
66
+ }
67
+ }
68
+ data.slug = state.uniqueSlug('author', data.slug, id);
69
+ const entity = new AuthorContext();
70
+ for (const [field, value] of Object.entries(data)) {
71
+ if (value !== undefined) {
72
+ entity.set(field, value);
73
+ }
74
+ }
75
+ entity.ghostId = id;
76
+ entity.save(context.db);
77
+ state.bind('author', key, entity.dbId);
78
+ return entity;
79
+ }
80
+ /** The saved tag for a slug, so names with the same slug are one tag. */
81
+ function tagEntity(state, site, { name, slug }) {
82
+ const context = state.context;
83
+ const binding = state.getBinding('tag', slug);
84
+ if (binding) {
85
+ return TagContext.fromRow(context.db.stmts.findTagById.get(binding));
86
+ }
87
+ const tag = new TagContext({ name, slug: state.uniqueSlug('tag', slug) });
88
+ tag.ghostId = ghostId(site, 'tag', slug);
89
+ tag.save(context.db);
90
+ state.bind('tag', slug, tag.dbId);
91
+ return tag;
92
+ }
93
+ /**
94
+ * Rebuild posts, tags and authors from the stored post files. Each file becomes a post dated by its front matter
95
+ * `date` or the date in its file name (a draft without either is dated when the export was read), with its
96
+ * `author` names as authors (the Example User when it has none) and its categories, tags, `addTags`, and `#jekyll`
97
+ * as tags. Every option applies here, so changing one needs no new read. Posts without a valid date, and files with
98
+ * invalid front matter, are skipped with a `record:skipped` diagnostic.
99
+ */
100
+ export async function map(options, context, services = {}) {
101
+ if (!context.sources.hasCompletedIngestion) {
102
+ throw new Error('Ingest a complete Jekyll export before mapping.');
103
+ }
104
+ const url = siteUrl(options.url);
105
+ const site = urlUtils.canonicalSite(url);
106
+ const domain = (typeof options.email === 'string' && options.email.trim()) || 'example.com';
107
+ const readAt = new Date(context.sources.currentIngestion.completedAt);
108
+ const state = new MappingState(context, 'mg-jekyll-export');
109
+ return context.rebuildMappedContent(async () => {
110
+ for await (const user of services.ghostUsers ?? []) {
111
+ state.reserveSlug('author', user.slug, user.id);
112
+ if (user.email) {
113
+ state.set('ghost-user', user.email.toLowerCase(), user);
114
+ }
115
+ }
116
+ return context.mapRecords(context.sources.records({ kind: 'post' }), async (record) => {
117
+ const post = processPost(record.key, record.content, { url: url.href, addTags: options.addTags });
118
+ const date = post.date ?? (post.status === 'draft' ? readAt : null);
119
+ if (!date) {
120
+ throw new RecordDataError('No valid date in the front matter or file name');
121
+ }
122
+ const entity = new PostContext({ lookupKey: record.key });
123
+ entity.ghostId = ghostId(site, 'post', record.key);
124
+ entity.set('title', post.title);
125
+ entity.set('slug', post.slug);
126
+ entity.set('status', post.status);
127
+ entity.set('visibility', 'public');
128
+ entity.set('type', 'post');
129
+ entity.set('created_at', date);
130
+ entity.set('published_at', date);
131
+ entity.set('updated_at', date);
132
+ entity.set('html', post.html);
133
+ if (post.authors.length > 500 || post.tags.length > 500) {
134
+ throw new RecordDataError('Post exceeds Ghost author/tag relationship limits');
135
+ }
136
+ const authors = post.authors.length
137
+ ? post.authors.map(name => {
138
+ const slug = slugify(name) || 'author';
139
+ return { name, slug, email: placeholderEmail(slug, domain) };
140
+ })
141
+ : [{ name: 'Example User', slug: 'exampleuser', email: 'exampleuser@example.com' }];
142
+ for (const author of authors.map(data => authorEntity(state, site, data))) {
143
+ entity.addAuthor(author);
144
+ context.sources.link(record.id, { type: 'author', id: author.dbId });
145
+ }
146
+ for (const tag of post.tags.map(data => tagEntity(state, site, data))) {
147
+ entity.addTag(tag);
148
+ context.sources.link(record.id, { type: 'tag', id: tag.dbId });
149
+ }
150
+ entity.save(context.db);
151
+ context.sources.link(record.id, { type: 'post', id: entity.dbId });
152
+ const prefix = datedPrefix(post.date, options.datedPermalinks);
153
+ context.addLink(stringUtils.cleanURL(postUrl(options, post)), `/${prefix}${entity.get('slug')}/`);
154
+ });
155
+ });
156
+ }
157
+ //# sourceMappingURL=map.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"map.js","sourceRoot":"","sources":["../../src/lib/map.ts"],"names":[],"mappings":"AAAA,OAAO,EACH,aAAa,EACb,YAAY,EAEZ,WAAW,EACX,eAAe,EACf,UAAU,EACV,OAAO,IAAI,WAAW,EACzB,MAAM,sBAAsB,CAAC;AAE9B,OAAO,EAAC,mBAAmB,EAAC,MAAM,4BAA4B,CAAC;AAE/D,OAAO,EAAC,OAAO,EAAC,MAAM,kBAAkB,CAAC;AACzC,OAAO,EAAC,WAAW,EAAE,QAAQ,EAAC,MAAM,oBAAoB,CAAC;AACzD,OAAO,EAAC,WAAW,EAAE,QAAQ,EAAC,MAAM,mBAAmB,CAAC;AAUxD,MAAM,KAAK,GAAG,CAAC,aAAa,EAAE,QAAQ,EAAE,QAAQ,EAAE,eAAe,CAAC,CAAC;AAEnE,uFAAuF;AACvF,MAAM,UAAU,OAAO,CAAC,IAAY,EAAE,IAAY,EAAE,GAAW;IAC3D,OAAO,WAAW,CAAC,oBAAoB,EAAE,IAAI,EAAE,IAAI,EAAE,GAAG,CAAC,CAAC;AAC9D,CAAC;AAED,SAAS,OAAO,CAAC,KAAc;IAC3B,MAAM,GAAG,GAAG,QAAQ,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;IACpC,IAAI,CAAC,GAAG,EAAE,CAAC;QACP,MAAM,IAA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site's `url`, root-relative links and image sources become
3
+ * absolute URLs on the site's origin, so a site hosted in a subdirectory still resolves them. A paragraph inside a
4
+ * list item is unwrapped.
5
+ */
6
+ export default function processHtml(rawHtml: string, url?: string | null): string;
@@ -0,0 +1,38 @@
1
+ import { domUtils } from '@tryghost/mg-utils';
2
+ /** Prefix a root-relative path such as `/images/photo.jpg` with the site's origin. */
3
+ function absolute(origin, path) {
4
+ return path?.startsWith('/') ? `${origin}/${path.replace(/^\/|\/$/g, '')}` : null;
5
+ }
6
+ /**
7
+ * Clean the HTML of one Jekyll post. With the live site's `url`, root-relative links and image sources become
8
+ * absolute URLs on the site's origin, so a site hosted in a subdirectory still resolves them. A paragraph inside a
9
+ * list item is unwrapped.
10
+ */
11
+ export default function processHtml(rawHtml, url) {
12
+ return domUtils.processFragment(rawHtml, parsed => {
13
+ if (url) {
14
+ // The origin, not the full URL: relative-to-root paths ignore the subdirectory a site was hosted in.
15
+ const origin = new URL(url).origin;
16
+ for (const anchor of parsed.$('a')) {
17
+ const href = absolute(origin, anchor.getAttribute('href'));
18
+ if (href) {
19
+ anchor.setAttribute('href', href);
20
+ }
21
+ }
22
+ for (const img of parsed.$('img')) {
23
+ const src = absolute(origin, img.getAttribute('src'));
24
+ if (src) {
25
+ img.setAttribute('src', src);
26
+ }
27
+ }
28
+ }
29
+ for (const li of parsed.$('li')) {
30
+ const p = li.querySelector('p');
31
+ if (p) {
32
+ li.replaceChildren(...p.childNodes);
33
+ }
34
+ }
35
+ return parsed.html().trim();
36
+ });
37
+ }
38
+ //# sourceMappingURL=process-html.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"process-html.js","sourceRoot":"","sources":["../../src/lib/process-html.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,QAAQ,EAAC,MAAM,oBAAoB,CAAC;AAE5C,sFAAsF;AACtF,SAAS,QAAQ,CAAC,MAAc,EAAE,IAAmB;IACjD,OAAO,IAAI,EAAE,UAAU,CAAC,GAAG,CAAC,CAAC,CAA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ACL,CAAC;QAED,OAAO,MAAM,CAAC,IAAI,EAAE,CAAC,IAAI,EAAE,CAAC;IAChC,CAAC,CAAC,CAAC;AACP,CAAC"}
@@ -0,0 +1,29 @@
1
+ import type { JekyllOptions, JekyllPost } from './types.js';
2
+ /**
3
+ * Split a post file into its front matter attributes and body. A file without front matter has no attributes, and
4
+ * front matter that is not a YAML mapping is ignored. Invalid YAML is a `RecordDataError`.
5
+ */
6
+ export declare function parseFrontMatter(contents: string): {
7
+ attributes: Record<string, unknown>;
8
+ body: string;
9
+ };
10
+ /**
11
+ * Read a front matter date, which Jekyll writes as `YYYY-MM-DD HH:MM:SS +/-TTTT`; the time, seconds and offset
12
+ * are optional, and a `T` may separate the date and time. A date without an offset is read as UTC. Returns `null`
13
+ * for anything else.
14
+ */
15
+ export declare function parseDate(value: unknown): Date | null;
16
+ /**
17
+ * Read a post's slug, live URL fields and date from its path and front matter, without rendering its body. Throws
18
+ * a `RecordDataError` for invalid front matter.
19
+ */
20
+ export declare function readPost(path: string, contents: string): Pick<JekyllPost, 'sourceSlug' | 'date' | 'status'>;
21
+ /**
22
+ * Process one Jekyll post file: its front matter and its Markdown or HTML body, which is converted to clean HTML.
23
+ * `path` is the file's path from the site root, such as `_posts/2021-08-23-my-post.md` or `_drafts/my-draft.md`.
24
+ *
25
+ * Tags come from `category` and `categories` (as `category-` tags, first so the first category is the primary
26
+ * tag), then `tag` and `tags`, then `options.addTags`; a `#` tag named after a subdirectory of `_posts`, and
27
+ * `#jekyll`, come after the public tags. Throws a `RecordDataError` for invalid front matter.
28
+ */
29
+ export declare function processPost(path: string, contents: string, options?: Pick<JekyllOptions, 'url' | 'addTags'>): JekyllPost;