@tryghost/mg-tinynews 0.0.2

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2013-2023 Ghost Foundation
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,103 @@
1
+ # Migrate Tiny News
2
+
3
+ Export content from Tiny News using JSON files, and generate a `zip` file you can import into a Ghost installation.
4
+
5
+
6
+ ## Install
7
+
8
+ To install the CLI, which is required for the Usage commands below:
9
+
10
+ ```sh
11
+ npm install --global @tryghost/migrate
12
+ ```
13
+
14
+ To use this package in your own project:
15
+
16
+ `npm install @tryghost/mg-tinynews --save`
17
+
18
+ or
19
+
20
+ `yarn add @tryghost/mg-tinynews`
21
+
22
+
23
+ ## Usage
24
+
25
+ To run a Ghost API migration, the required command is:
26
+
27
+ ```sh
28
+ migrate tinynews --url https://example.com --articles /path/to/articles.json
29
+ ```
30
+
31
+ It's possible to pass more options, in order to achieve a better migration file for Ghost:
32
+
33
+ - **`--url`** (required)
34
+ - string - default: `null`
35
+ - URL to live site
36
+ - **`--articles`** (required)
37
+ - string - default: `null`
38
+ - Path to articles JSON file
39
+ - **`--pages`**
40
+ - string - default: `null`
41
+ - Path to pages JSON file
42
+ - **`--newsletters`**
43
+ - string - default: `null`
44
+ - Path to newsletters JSON file
45
+ - **`--authors`**
46
+ - string - default: `null`
47
+ - Path to authors JSON file
48
+ - **`--verbose`**
49
+ - bool - default: `false`
50
+ - Show verbose output
51
+ - **`--zip`**
52
+ - bool - default: `true`
53
+ - Create a zip file
54
+ - **`--scrape`**
55
+ - Configure scraping tasks
56
+ - string - default: `all`
57
+ - Choices: `all`, `web`, `none`
58
+ - **`--addPrimaryTag`**
59
+ - string - default: `null`
60
+ - Provide a tag name which should be added to every post as primary tag
61
+ - **`--fallBackHTMLCard`**
62
+ - bool - default: `true`
63
+ - Fall back to convert to HTMLCard, if standard Mobiledoc convert fails
64
+ - **`--cache`**
65
+ - Persist local cache after migration is complete (Only if `--zip` is `true`)
66
+ - bool - default: `true`
67
+
68
+ A more complete migration command could look like this:
69
+
70
+ ```sh
71
+ migrate tinynews --url http://example.com --articles /path/to/articles.json --pages /path/to/pages.json --newsletters /path/to/newsletters.json --authors /path/to/authors.json
72
+ ```
73
+
74
+ This will get all posts, pages, newsletters, and authors.
75
+
76
+
77
+ ## Develop
78
+
79
+ This is a mono repository, managed with [lerna](https://lerna.js.org).
80
+
81
+ Follow the instructions for the top-level repo.
82
+ 1. `git clone` this repo & `cd` into it as usual
83
+ 2. Run `yarn` to install top-level dependencies.
84
+
85
+
86
+ ## Run
87
+
88
+ To run a local development copy, `cd` into this directory, and use `yarn dev` instead of `migrate` like so:
89
+
90
+ ```sh
91
+ yarn dev tinynews [options]
92
+ ```
93
+
94
+
95
+ ## Test
96
+
97
+ - `yarn lint` run just eslint
98
+ - `yarn test` run lint and tests
99
+
100
+
101
+ # Copyright & License
102
+
103
+ Copyright (c) 2013-2023 Ghost Foundation - Released under the [MIT license](LICENSE).
package/index.js ADDED
@@ -0,0 +1,7 @@
1
+ import {mapContent} from './lib/mapper.js';
2
+
3
+ export default async (args, logger) => {
4
+ let result = await mapContent(args, logger);
5
+
6
+ return result;
7
+ };
@@ -0,0 +1,310 @@
1
+ import SimpleDom from 'simple-dom';
2
+ import imageCard from '@tryghost/kg-default-cards/lib/cards/image.js';
3
+ import {TextNode} from './text.js';
4
+
5
+ const serializer = new SimpleDom.HTMLSerializer(SimpleDom.voidMap);
6
+
7
+ // From https://gist.github.com/takien/4077195
8
+ const getYouTubeID = (url) => {
9
+ const arr = url.split(/(vi\/|v%3D|v=|\/v\/|youtu\.be\/|\/embed\/)/);
10
+ return undefined !== arr[2] ? arr[2].split(/[^\w-]/i)[0] : arr[0];
11
+ };
12
+
13
+ const formatChildStyles = (child) => {
14
+ let html = [];
15
+
16
+ if (child?.link) {
17
+ html.push(`<a href="${child.link}">`);
18
+ }
19
+
20
+ if (child?.style?.bold) {
21
+ html.push('<strong>');
22
+ }
23
+
24
+ if (child?.style?.italic) {
25
+ html.push('<em>');
26
+ }
27
+
28
+ if (child?.style?.underline) {
29
+ html.push('<u>');
30
+ }
31
+
32
+ html.push(child.content);
33
+
34
+ if (child?.style?.underline) {
35
+ html.push('</u>');
36
+ }
37
+
38
+ if (child?.style?.italic) {
39
+ html.push('</em>');
40
+ }
41
+
42
+ if (child?.style?.bold) {
43
+ html.push('</strong>');
44
+ }
45
+
46
+ if (child?.link) {
47
+ html.push(`</a>`);
48
+ }
49
+
50
+ return html.join('');
51
+ };
52
+
53
+ const EntryList = (block) => {
54
+ const listTypeEl = (block.listType === 'NUMBER') ? 'ol' : 'ul';
55
+
56
+ let html = [];
57
+
58
+ html.push(`<${listTypeEl}>`);
59
+
60
+ block.items.forEach((item) => {
61
+ item.children.forEach((child) => {
62
+ html.push(`<li>${formatChildStyles(child)}</li>`);
63
+ });
64
+ });
65
+
66
+ html.push(`</${listTypeEl}>`);
67
+
68
+ return html.join('');
69
+ };
70
+
71
+ const EntryText = (block) => {
72
+ return TextNode({node: block});
73
+ };
74
+
75
+ const EntryImage = (block) => {
76
+ if (block.children.length === 0) {
77
+ return;
78
+ }
79
+
80
+ let html = [];
81
+
82
+ block.children.forEach((child) => {
83
+ let cardOpts = {
84
+ env: {dom: new SimpleDom.Document()},
85
+ payload: {
86
+ src: child.imageUrl,
87
+ alt: child.imageAlt,
88
+ caption: child.imageAlt
89
+ }
90
+ };
91
+
92
+ if (block?.link) {
93
+ cardOpts.payload.href = block.link;
94
+ }
95
+
96
+ html.push(serializer.serialize(imageCard.render(cardOpts)));
97
+ });
98
+
99
+ return html.join('');
100
+ };
101
+
102
+ const EntryHeading = (block) => {
103
+ return TextNode({node: block});
104
+ };
105
+
106
+ const EntryBlockquote = (block) => {
107
+ if (block.children[0].content.trim() === '') {
108
+ return;
109
+ }
110
+
111
+ let html = [];
112
+
113
+ html.push('<blockquote><p>');
114
+
115
+ block.children.forEach((child) => {
116
+ if (child.content.trim() === '') {
117
+ return;
118
+ }
119
+
120
+ html.push(formatChildStyles(child));
121
+ });
122
+
123
+ html.push('</p></blockquote>');
124
+
125
+ return html.join('');
126
+ };
127
+
128
+ const EntryHorizontalRule = () => {
129
+ let html = [];
130
+ html.push('<hr>');
131
+ return html.join('');
132
+ };
133
+
134
+ const EntryTwitterEmbed = (block) => {
135
+ const blockHtml = `<figure class="kg-card kg-embed-card"><blockquote class="twitter-tweet"><a href="${block.link}"></a></blockquote><script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script></figure>`;
136
+
137
+ return blockHtml;
138
+ };
139
+
140
+ const EntryTikTokEmbed = (block) => {
141
+ const usernameRegexp = new RegExp('(?<username>@[a-zA-Z0-9-_]+)');
142
+ const usernameMatches = block.link.match(usernameRegexp);
143
+
144
+ const videoIDRegexp = new RegExp('(?<videoID>[0-9]{10,})');
145
+ const videoIDMatches = block.link.match(videoIDRegexp);
146
+
147
+ if (usernameMatches?.groups?.username && videoIDMatches?.groups?.videoID) {
148
+ return `<figure class="kg-card kg-embed-card"><blockquote class="tiktok-embed" cite="https://www.tiktok.com/${usernameMatches.groups.username}/video/${videoIDMatches.groups.videoID}" data-video-id="${videoIDMatches.groups.videoID}" style="max-width: 605px;min-width: 325px;"><section><a target="_blank" title="${usernameMatches.groups.username}" href="https://www.tiktok.com/${usernameMatches.groups.username}?refer=embed">${usernameMatches.groups.username}</a></section></blockquote><script async src="https://www.tiktok.com/embed.js"></script></figure>`;
149
+ } else {
150
+ return `<p><a href="${block.link}">${block.link}</a></p>`;
151
+ }
152
+ };
153
+
154
+ const EntryFacebookEmbed = (block) => {
155
+ if (block?.html) {
156
+ const blockHtml = `<!--kg-card-begin: html-->${block.html}<!--kg-card-end: html-->`;
157
+ return blockHtml;
158
+ } else {
159
+ return `<p><a href="${block.link}">${block.link}</a></p>`;
160
+ }
161
+ };
162
+
163
+ const EntryVimeoEmbed = (block) => {
164
+ const videoIDRegexp = new RegExp('(?<videoID>[0-9]{3,})');
165
+ const videoIDMatches = block.link.match(videoIDRegexp);
166
+
167
+ if (videoIDMatches?.groups?.videoID) {
168
+ const blockHtml = `<iframe src="https://player.vimeo.com/video/${videoIDMatches.groups.videoID}" width="160" height="90" frameborder="0" allow="autoplay; fullscreen; picture-in-picture" allowfullscreen></iframe>`;
169
+
170
+ return blockHtml;
171
+ } else {
172
+ return `<p><a href="${block.link}">${block.link}</a></p>`;
173
+ }
174
+ };
175
+
176
+ const EntryYoutubeEmbed = (block) => {
177
+ const videoID = getYouTubeID(block.link);
178
+
179
+ const blockHtml = `<iframe width="160" height="90" src="https://www.youtube.com/embed/${videoID}" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>`;
180
+
181
+ return blockHtml;
182
+ };
183
+
184
+ const EntryApplePodcastsEmbed = (block) => {
185
+ const iframeSrc = block.link.replace('https://podcasts.apple.com', 'https://embed.podcasts.apple.com');
186
+ const blockHtml = `<iframe allow="autoplay *; encrypted-media *; fullscreen *; clipboard-write" frameborder="0" height="450" style="width:100%;max-width:660px;overflow:hidden;border-radius:10px;" sandbox="allow-forms allow-popups allow-same-origin allow-scripts allow-storage-access-by-user-activation allow-top-navigation-by-user-activation" src="${iframeSrc}"></iframe>`;
187
+
188
+ return blockHtml;
189
+ };
190
+
191
+ const EntryInstagramPostEmbed = (block) => {
192
+ const blockHtml = `<iframe src="${block.link}embed/captioned/" class="instagram-media" allowtransparency="true" allowfullscreen="true" frameborder="0" scrolling="no" style="background: white; max-width: 658px; width: calc(100% - 2px); border-radius: 3px; border: 1px solid rgb(219, 219, 219); box-shadow: none; display: block; margin: 0px; min-width: 326px; padding: 0px;"></iframe><script async="" src="//www.instagram.com/embed.js"></script>`;
193
+
194
+ return blockHtml;
195
+ };
196
+
197
+ const EntryInstagramReelEmbed = (block) => {
198
+ const blockHtml = `<iframe class="instagram-media" src="${block.link}embed/captioned/" allowtransparency="true" allowfullscreen="true" frameborder="0" scrolling="no" style="background: white; max-width: 540px; width: calc(100% - 2px); border-radius: 3px; border: 1px solid rgb(219, 219, 219); box-shadow: none; display: block; margin: 0px; min-width: 326px; padding: 0px; position: relative;"></iframe><script async="" src="//www.instagram.com/embed.js"></script>`;
199
+
200
+ return blockHtml;
201
+ };
202
+
203
+ const EntryGoogleDocsEmbed = (block) => {
204
+ const blockHtml = `<iframe class="googledocs-embed" src="${block.link}" allowtransparency="true" allowfullscreen="true" frameborder="0" style="width: 100%; height: 500px;"></iframe>`;
205
+
206
+ return blockHtml;
207
+ };
208
+
209
+ const EntrySpotifyEmbed = (block) => {
210
+ let embedUrl = block.link.replace('https://open.spotify.com/episode/', 'https://open.spotify.com/embed/episode/');
211
+ embedUrl = embedUrl.replace('https://open.spotify.com/show/', 'https://open.spotify.com/embed/show/');
212
+ const blockHtml = `<iframe src="${embedUrl}" width="300" height="380" frameborder="0" allowtransparency="true" allow="encrypted-media"></iframe>`;
213
+
214
+ return blockHtml;
215
+ };
216
+
217
+ const jsonToHtml = (blocks, logger) => {
218
+ let html = [];
219
+
220
+ if (typeof blocks === 'string') {
221
+ return blocks;
222
+ }
223
+
224
+ blocks.forEach((block) => {
225
+ const itemType = block.type ?? null;
226
+ const itemStyle = block.style ?? null;
227
+
228
+ if (itemType === 'mainImage') {
229
+ // This element is skipped as we use the top level 'featured_image' instead
230
+ // Using this would result in duplicates
231
+ return;
232
+ }
233
+
234
+ if (itemType === 'text') {
235
+ if (itemStyle === 'TITLE' || itemStyle === 'SUBTITLE' || itemStyle === 'HEADING_1' || itemStyle === 'HEADING_2' || itemStyle === 'HEADING_3' || itemStyle === 'HEADING_4') {
236
+ html.push(EntryHeading(block));
237
+ } else if (itemStyle === 'NORMAL_TEXT') {
238
+ html.push(EntryText(block));
239
+ } else {
240
+ logger.error({
241
+ message: `Unhandled text type: ${itemType} - Unhandled style: ${itemStyle}`,
242
+ context: block
243
+ });
244
+ }
245
+ } else if (itemType === 'blockquote') {
246
+ html.push(EntryBlockquote(block));
247
+ } else if (itemType === 'hr') {
248
+ html.push(EntryHorizontalRule());
249
+ } else if (itemType === 'list') {
250
+ html.push(EntryList(block));
251
+ } else if (itemType === 'image') {
252
+ html.push(EntryImage(block));
253
+ } else if (itemType === 'embed') {
254
+ if (block.link.includes('https://twitter.com')) {
255
+ html.push(EntryTwitterEmbed(block));
256
+ } else if (block.link.includes('https://www.tiktok.com')) {
257
+ html.push(EntryTikTokEmbed(block));
258
+ } else if (block.link.includes('https://www.facebook.com')) {
259
+ html.push(EntryFacebookEmbed(block));
260
+ } else if (block.link.includes('https://vimeo.com')) {
261
+ html.push(EntryVimeoEmbed(block));
262
+ } else if (block.link.includes('https://www.youtube.com') || block.link.includes('https://youtu.be')) {
263
+ html.push(EntryYoutubeEmbed(block));
264
+ } else if (block.link.includes('https://podcasts.apple.com')) {
265
+ html.push(EntryApplePodcastsEmbed(block));
266
+ } else if (block.link.includes('https://open.spotify.com/episode/') || block.link.includes('https://open.spotify.com/show/')) {
267
+ html.push(EntrySpotifyEmbed(block));
268
+ } else if (block.link.includes('https://www.instagram.com/p/')) {
269
+ html.push(EntryInstagramPostEmbed(block));
270
+ } else if (block.link.includes('https://www.instagram.com/reel/')) {
271
+ html.push(EntryInstagramReelEmbed(block));
272
+ } else if (block.link.includes('https://docs.google.com')) {
273
+ html.push(EntryGoogleDocsEmbed(block));
274
+ } else {
275
+ logger.error({
276
+ message: `Unhandled embed: ${block.link}`,
277
+ context: block
278
+ });
279
+ }
280
+ } else {
281
+ logger.error({
282
+ message: `Unhandled type: ${itemType} - Unhandled style: ${itemStyle}`,
283
+ context: block
284
+ });
285
+ }
286
+ });
287
+
288
+ return html.join('');
289
+ };
290
+
291
+ export {
292
+ jsonToHtml,
293
+ getYouTubeID,
294
+ formatChildStyles,
295
+ EntryList,
296
+ EntryText,
297
+ EntryImage,
298
+ EntryHeading,
299
+ EntryBlockquote,
300
+ EntryHorizontalRule,
301
+ EntryTwitterEmbed,
302
+ EntryTikTokEmbed,
303
+ EntryFacebookEmbed,
304
+ EntryVimeoEmbed,
305
+ EntryYoutubeEmbed,
306
+ EntryApplePodcastsEmbed,
307
+ EntryInstagramPostEmbed,
308
+ EntryInstagramReelEmbed,
309
+ EntryGoogleDocsEmbed
310
+ };
package/lib/mapper.js ADDED
@@ -0,0 +1,346 @@
1
+ import {readFile} from 'node:fs/promises';
2
+ import sanitizeHtml from 'sanitize-html';
3
+ import $ from 'cheerio';
4
+ import {slugify} from '@tryghost/string';
5
+ import {_base as debugFactory} from '@tryghost/debug';
6
+ import {jsonToHtml} from './json-to-html.js';
7
+
8
+ const debug = debugFactory('migrate:tinynews:lib:mapper');
9
+
10
+ const textOnly = (htmlContent) => {
11
+ const cleanedContent = sanitizeHtml(htmlContent, {
12
+ allowedTags: [],
13
+ allowedAttributes: {}
14
+ });
15
+ return cleanedContent.trim();
16
+ };
17
+
18
+ const processAuthor = (author, authorsData) => {
19
+ const name = [author.first_names, author.last_name].join(' ').trim();
20
+ const slug = slugify(name);
21
+ const email = (author?.email && author.email.length > 0) ? author.email : `${slug}@example.com`;
22
+
23
+ let authorObject = {
24
+ url: `/author/${slug}`,
25
+ data: {
26
+ slug: slug,
27
+ name: name,
28
+ email: email
29
+ }
30
+ };
31
+
32
+ if (author?.photoUrl) {
33
+ authorObject.data.profile_image = author.photoUrl;
34
+ }
35
+
36
+ if (author?.translations?.length && author.translations[0].bio) {
37
+ authorObject.data.bio = textOnly(author.translations[0].bio);
38
+ }
39
+
40
+ // If we have a global authorsData object
41
+ if (authorsData?.data) {
42
+ // Find th author by first & last name
43
+ const thisAuthorInfo = authorsData.data.authors.find((filterAuthor) => {
44
+ return filterAuthor.first_names === author.first_names && filterAuthor.last_name === author.last_name;
45
+ });
46
+
47
+ // Update values from the globally supplied authorsData to the individual author object
48
+ if (thisAuthorInfo) {
49
+ authorObject.data.email = thisAuthorInfo.email;
50
+ authorObject.data.bio = textOnly(thisAuthorInfo.translations[0].bio);
51
+ authorObject.data.profile_image = thisAuthorInfo.photoUrl;
52
+ }
53
+ }
54
+
55
+ return authorObject;
56
+ };
57
+
58
+ const mapPostPageConfig = (args, logger) => {
59
+ const {postData, authorsData, postType} = args;
60
+
61
+ debug(`Mapping data for ${postData.slug}`);
62
+
63
+ const dateNow = new Date().toISOString();
64
+
65
+ const mappedData = {
66
+ url: postData.live_url,
67
+ data: {
68
+ slug: postData.slug,
69
+ published_at: postData.translations[0].first_published_at ?? dateNow,
70
+ updated_at: postData.translations[0].last_published_at ?? dateNow,
71
+ created_at: postData.translations[0].first_published_at ?? dateNow,
72
+ title: postData.translations[0].headline,
73
+ type: (postType === 'page') ? 'page' : 'post',
74
+ html: null,
75
+ status: postData.translations[0].published ? 'published' : 'draft',
76
+ og_title: postData.translations[0].facebook_title ?? null,
77
+ og_description: postData.translations[0].facebook_description ?? null,
78
+ twitter_title: postData.translations[0].twitter_title ?? null,
79
+ twitter_description: postData.translations[0].twitter_description ?? null,
80
+ meta_title: postData.translations[0].search_title ?? null,
81
+ meta_description: postData.translations[0].search_description ?? null,
82
+ custom_excerpt: postData.translations[0].search_description ?? null,
83
+ visibility: 'public',
84
+ tags: []
85
+ }
86
+ };
87
+
88
+ if (postType !== 'newsletter' && postData.translations[0].content) {
89
+ mappedData.data.html = jsonToHtml(postData.translations[0].content, logger);
90
+ }
91
+
92
+ if (mappedData.data.html.includes('class="fb-post')) {
93
+ mappedData.data.codeinjection_head = '<div id="fb-root"></div><script async defer src="https://connect.facebook.net/en_US/sdk.js#xfbml=1&version=v3.2"></script>';
94
+ }
95
+
96
+ if (postData?.translations[0].main_image?.children && postData?.translations[0].main_image?.children[0]?.imageUrl) {
97
+ mappedData.data.feature_image = postData.translations[0].main_image.children[0].imageUrl;
98
+ mappedData.data.feature_image_alt = postData.translations[0].main_image.children[0]?.imageAlt ?? null;
99
+ mappedData.data.feature_image_caption = postData.translations[0].main_image.children[0]?.imageAlt ?? null;
100
+ }
101
+
102
+ // Handle mainImage from pages (its in the content object)
103
+ if (postType === 'page' && typeof postData.translations[0].content === 'object') {
104
+ const hasMainImageInContent = postData.translations[0].content.find((block) => {
105
+ return block.type === 'mainImage';
106
+ });
107
+ if (hasMainImageInContent?.children[0]?.imageUrl) {
108
+ mappedData.data.feature_image = hasMainImageInContent.children[0].imageUrl;
109
+ }
110
+ }
111
+
112
+ if (postData.author && postData.author.length) {
113
+ mappedData.data.author = processAuthor(postData.author[0].author, authorsData);
114
+ } else if (postData.translations[0].created_by_email) {
115
+ const authorEmailName = postData.translations[0].created_by_email.split('@')[0];
116
+ mappedData.data.author = {
117
+ url: `/author/${authorEmailName}`,
118
+ data: {
119
+ slug: authorEmailName,
120
+ name: authorEmailName,
121
+ email: postData.translations[0].created_by_email
122
+ }
123
+ };
124
+ } else if (authorsData?.data?.authors?.length === 1) {
125
+ mappedData.data.author = processAuthor(authorsData.data.authors[0]);
126
+ } else {
127
+ mappedData.data.author = {
128
+ url: `/author/author`,
129
+ data: {
130
+ slug: `author`,
131
+ name: 'Author',
132
+ email: 'author@example.com'
133
+ }
134
+ };
135
+ }
136
+
137
+ if (postData.category) {
138
+ const categoryPublished = postData.category.published;
139
+ let categoryName = postData.category.title ?? postData.category.slug;
140
+ let categorySlug = postData.category.slug;
141
+
142
+ if (categoryPublished && categoryPublished === false) {
143
+ categoryName = `#${categoryName}`;
144
+ categorySlug = `hash-${categorySlug}`;
145
+ }
146
+
147
+ mappedData.data.tags.push({
148
+ url: `/tag/${categorySlug}`,
149
+ data: {
150
+ slug: categorySlug,
151
+ name: categoryName
152
+ }
153
+ });
154
+ }
155
+
156
+ if (postData.tags) {
157
+ postData.tags.forEach((tag) => {
158
+ const tagData = tag.tag;
159
+ const tagPublished = tagData.published;
160
+ let tagName = tagData.tag_translations[0].title;
161
+ let tagSlug = tagData.slug;
162
+
163
+ if (tagPublished && tagPublished === false) {
164
+ tagName = `#${tagName}`;
165
+ tagSlug = `hash-${tagSlug}`;
166
+ }
167
+
168
+ mappedData.data.tags.push({
169
+ url: `/tag/${tagSlug}`,
170
+ data: {
171
+ slug: tagSlug,
172
+ name: tagName
173
+ }
174
+ });
175
+ });
176
+ }
177
+
178
+ mappedData.data.tags.push({
179
+ url: `migrator-added-tag`,
180
+ data: {
181
+ slug: `hash-tinynews`,
182
+ name: `#tinynews`
183
+ }
184
+ });
185
+
186
+ return mappedData;
187
+ };
188
+
189
+ const processNewsletterContent = (html, options) => { // eslint-disable-line no-unused-vars
190
+ const cleanedContent = sanitizeHtml(html, {
191
+ allowedTags: [
192
+ 'b', 'i', 'em', 'strong', 'a', 'p', 'br', 'ul', 'ol', 'li', 'blockquote',
193
+ 'figure', 'figcaption', 'img', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
194
+ 'div'
195
+ ],
196
+ allowedAttributes: {
197
+ a: ['href', 'title', 'rel', 'target'],
198
+ img: ['src', 'alt', 'title']
199
+ },
200
+ transformTags: {
201
+ 'div': 'p' // eslint-disable-line quote-props
202
+ }
203
+ });
204
+
205
+ const $html = $.load(cleanedContent, {
206
+ decodeEntities: false
207
+ });
208
+
209
+ $html('p').each((i, el) => {
210
+ const innerHtml = $html(el).html().trim();
211
+ if (!innerHtml.length || innerHtml === '<br>' || innerHtml === '<br/>') {
212
+ $(el).remove();
213
+ }
214
+ });
215
+
216
+ $html('a:contains("Made with Letterhead")').each((i, el) => {
217
+ $(el).remove();
218
+ });
219
+
220
+ const cleanedHTML = $html.html().trim();
221
+
222
+ return `<!--kg-card-begin: html-->${cleanedHTML}<!--kg-card-end: html-->`;
223
+ };
224
+
225
+ const mapNewsletterConfig = (args, logger) => { // eslint-disable-line no-unused-vars
226
+ const {postData, options} = args;
227
+
228
+ debug(`Mapping data for ${postData.slug}`);
229
+
230
+ const dateNow = new Date().toISOString();
231
+
232
+ const mappedData = {
233
+ url: `${options.url}/newsletters/${postData.slug}`,
234
+ data: {
235
+ slug: postData.slug,
236
+ published_at: postData.newsletter_published_at ?? dateNow,
237
+ updated_at: postData.newsletter_published_at ?? dateNow,
238
+ created_at: postData.newsletter_created_at ?? dateNow,
239
+ title: postData.headline,
240
+ custom_excerpt: postData.subheadline ?? null,
241
+ type: 'post',
242
+ html: null,
243
+ status: 'published',
244
+ visibility: 'public',
245
+ tags: []
246
+ }
247
+ };
248
+
249
+ mappedData.data.html = processNewsletterContent(postData.content, options);
250
+
251
+ mappedData.data.tags.push({
252
+ url: `migrator-added-tag-newsletter`,
253
+ data: {
254
+ slug: `hash-newsletter`,
255
+ name: `#newsletter`
256
+ }
257
+ });
258
+
259
+ mappedData.data.tags.push({
260
+ url: `migrator-added-tag`,
261
+ data: {
262
+ slug: `hash-tinynews`,
263
+ name: `#tinynews`
264
+ }
265
+ });
266
+
267
+ mappedData.data.author = {
268
+ url: `/author/newsletter-author`,
269
+ data: {
270
+ slug: `newsletter`,
271
+ name: 'Newsletter',
272
+ email: 'newsletter@example.com'
273
+ }
274
+ };
275
+
276
+ return mappedData;
277
+ };
278
+
279
+ const mapContent = async (args, logger) => {
280
+ const {options} = args;
281
+ const {articles, pages, newsletters, authors} = options;
282
+
283
+ const output = {
284
+ posts: []
285
+ };
286
+
287
+ let authorDataJSON = null;
288
+ if (authors) {
289
+ debug(`Parsing Author info from ${authors}`);
290
+ const authorDataJSONString = await readFile(authors, 'utf8');
291
+ authorDataJSON = JSON.parse(authorDataJSONString);
292
+ }
293
+
294
+ if (articles) {
295
+ debug(`Parsing Article info from ${articles}`);
296
+ const articlesJSONString = await readFile(articles, 'utf8');
297
+ const articlesJSON = JSON.parse(articlesJSONString);
298
+
299
+ await articlesJSON.forEach((data) => {
300
+ output.posts.push(mapPostPageConfig({
301
+ postData: data,
302
+ authorsData: authorDataJSON,
303
+ postType: 'post',
304
+ options
305
+ }, logger));
306
+ });
307
+ }
308
+
309
+ if (pages) {
310
+ debug(`Parsing Pages info from ${pages}`);
311
+ const pagesJSONString = await readFile(pages, 'utf8');
312
+ const pagesJSON = JSON.parse(pagesJSONString);
313
+
314
+ await pagesJSON.forEach((data) => {
315
+ output.posts.push(mapPostPageConfig({
316
+ postData: data,
317
+ authorsData: authorDataJSON,
318
+ postType: 'page',
319
+ options
320
+ }, logger));
321
+ });
322
+ }
323
+
324
+ if (newsletters) {
325
+ debug(`Parsing Newsletters info from ${newsletters}`);
326
+ const newslettersJSONString = await readFile(newsletters, 'utf8');
327
+ const newslettersJSON = JSON.parse(newslettersJSONString);
328
+
329
+ await newslettersJSON.data.newsletter_editions.forEach((data) => {
330
+ output.posts.push(mapNewsletterConfig({
331
+ postData: data,
332
+ options
333
+ }, logger));
334
+ });
335
+ }
336
+
337
+ return output;
338
+ };
339
+
340
+ export {
341
+ textOnly,
342
+ mapPostPageConfig,
343
+ mapNewsletterConfig,
344
+ processNewsletterContent,
345
+ mapContent
346
+ };
package/lib/text.js ADDED
@@ -0,0 +1,96 @@
1
+ const TextNode = ({node}) => {
2
+ const processChild = function (child, nextChild) {
3
+ let supportedPunctuation = [',', '.', '?', '!', ';', ':', '"', '“', '”', ')'];
4
+ // Add a space after this list of punctuation: colon, comma, period
5
+ let supportedTrailingPunctuation = ['?', '!', ';', '"', '“', '”', '('];
6
+ let delimiterSpaceChar = ' ';
7
+
8
+ // If the next node/child starts with one of the punctuation marks above, don't add a space
9
+ if (
10
+ (nextChild &&
11
+ nextChild.content &&
12
+ nextChild.content[0] &&
13
+ supportedPunctuation.includes(nextChild.content[0])) ||
14
+ (child &&
15
+ child.content &&
16
+ child.content.slice(-1) &&
17
+ supportedTrailingPunctuation.includes(child.content.slice(-1)))
18
+ ) {
19
+ delimiterSpaceChar = '';
20
+ }
21
+
22
+ let text = `${child.content}${child.link ? '' : delimiterSpaceChar}`;
23
+
24
+ if (
25
+ child &&
26
+ child.content &&
27
+ child.content.trim().length === 0 &&
28
+ nextChild &&
29
+ nextChild.content &&
30
+ nextChild.content.trim().length !== 0) {
31
+ text = '<br />';
32
+ }
33
+
34
+ if (child.style) {
35
+ if (child.style.underline && !child.link) {
36
+ text = `${delimiterSpaceChar}<u>${text}</u>${delimiterSpaceChar}`;
37
+ }
38
+ if (child.style.italic) {
39
+ text = `<em>${text}</em>${delimiterSpaceChar}`;
40
+ }
41
+ if (child.style.bold) {
42
+ text = `<strong>${text}</strong>${delimiterSpaceChar}`;
43
+ }
44
+ } else {
45
+ text = `${text}${child.link ? '' : delimiterSpaceChar}`;
46
+ }
47
+
48
+ if (child.link) {
49
+ text = `${delimiterSpaceChar}<a href="${child.link}">${text}</a>${delimiterSpaceChar}`;
50
+ }
51
+
52
+ return text;
53
+ };
54
+
55
+ const children = node.children
56
+ .filter(function (child) {
57
+ if (!child.content || child.content === 'FORMAT START' || child.content === 'FORMAT END') {
58
+ return false; // skip
59
+ }
60
+ return true;
61
+ })
62
+ .map((child, i) => {
63
+ let mapped = processChild(child, node.children[i + 1]);
64
+ return mapped;
65
+ });
66
+
67
+ if (!children || children.length <= 0) {
68
+ return null;
69
+ }
70
+
71
+ let wrapper = null;
72
+
73
+ if (node.style === 'TITLE') {
74
+ wrapper = `<h1>${children.join('')}</h1>`;
75
+ } else if (node.style === 'SUBTITLE') {
76
+ wrapper = `<h2>${children.join('')}</h2>`;
77
+ } else if (node.style === 'HEADING_1') {
78
+ wrapper = `<h1>${children.join('')}</h1>`;
79
+ } else if (node.style === 'HEADING_2') {
80
+ wrapper = `<h2>${children.join('')}</h2>`;
81
+ } else if (node.style === 'HEADING_3') {
82
+ wrapper = `<h3>${children.join('')}</h3>`;
83
+ } else if (node.style === 'NORMAL_TEXT') {
84
+ wrapper = `<p>${children.join('')}</p>`;
85
+ } else if (node.style === 'FORMATTED_TEXT') {
86
+ wrapper = `<pre>${children.join('')}</pre>`;
87
+ } else {
88
+ wrapper = `${children.join('')}`;
89
+ }
90
+
91
+ return wrapper;
92
+ };
93
+
94
+ export {
95
+ TextNode
96
+ };
package/package.json ADDED
@@ -0,0 +1,37 @@
1
+ {
2
+ "name": "@tryghost/mg-tinynews",
3
+ "version": "0.0.2",
4
+ "repository": "https://github.com/TryGhost/migrate/tree/main/packages/mg-tinynews",
5
+ "author": "Ghost Foundation",
6
+ "license": "MIT",
7
+ "main": "index.js",
8
+ "type": "module",
9
+ "scripts": {
10
+ "dev": "echo \"Implement me!\"",
11
+ "test": "NODE_OPTIONS=--experimental-vm-modules jest",
12
+ "lint": "eslint . --ext .js --cache",
13
+ "posttest": "yarn lint"
14
+ },
15
+ "files": [
16
+ "index.js",
17
+ "lib"
18
+ ],
19
+ "publishConfig": {
20
+ "access": "public"
21
+ },
22
+ "devDependencies": {
23
+ "eslint": "8.47.0",
24
+ "jest": "29.6.2",
25
+ "jest-extended": "3.2.4"
26
+ },
27
+ "dependencies": {
28
+ "@tryghost/debug": "0.1.26",
29
+ "@tryghost/errors": "1.2.26",
30
+ "@tryghost/kg-default-cards": "9.1.1",
31
+ "@tryghost/string": "0.2.8",
32
+ "cheerio": "1.0.0-rc.12",
33
+ "sanitize-html": "2.11.0",
34
+ "simple-dom": "1.4.0"
35
+ },
36
+ "gitHead": "0df990176ed00c9076d1bec7ddafa2a6b2ddd967"
37
+ }