@tryghost/mg-beehiiv-api 0.1.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 +21 -0
- package/README.md +178 -0
- package/build/index.d.ts +9 -0
- package/build/index.js +9 -0
- package/build/index.js.map +1 -0
- package/build/lib/client.d.ts +2 -0
- package/build/lib/client.js +17 -0
- package/build/lib/client.js.map +1 -0
- package/build/lib/fetch.d.ts +6 -0
- package/build/lib/fetch.js +70 -0
- package/build/lib/fetch.js.map +1 -0
- package/build/lib/list-pubs.d.ts +2 -0
- package/build/lib/list-pubs.js +17 -0
- package/build/lib/list-pubs.js.map +1 -0
- package/build/lib/mapper.d.ts +6 -0
- package/build/lib/mapper.js +94 -0
- package/build/lib/mapper.js.map +1 -0
- package/build/lib/process.d.ts +11 -0
- package/build/lib/process.js +268 -0
- package/build/lib/process.js.map +1 -0
- package/build/test/client.test.d.ts +1 -0
- package/build/test/client.test.js +47 -0
- package/build/test/client.test.js.map +1 -0
- package/build/test/fetch.test.d.ts +1 -0
- package/build/test/fetch.test.js +292 -0
- package/build/test/fetch.test.js.map +1 -0
- package/build/test/index.test.d.ts +1 -0
- package/build/test/index.test.js +15 -0
- package/build/test/index.test.js.map +1 -0
- package/build/test/list-pubs.test.d.ts +1 -0
- package/build/test/list-pubs.test.js +66 -0
- package/build/test/list-pubs.test.js.map +1 -0
- package/build/test/mapper.test.d.ts +1 -0
- package/build/test/mapper.test.js +243 -0
- package/build/test/mapper.test.js.map +1 -0
- package/build/test/process.test.d.ts +1 -0
- package/build/test/process.test.js +300 -0
- package/build/test/process.test.js.map +1 -0
- package/package.json +51 -0
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
import { domUtils } from '@tryghost/mg-utils';
|
|
2
|
+
import _ from 'lodash';
|
|
3
|
+
import SimpleDom from 'simple-dom';
|
|
4
|
+
import imageCard from '@tryghost/kg-default-cards/lib/cards/image.js';
|
|
5
|
+
import embedCard from '@tryghost/kg-default-cards/lib/cards/embed.js';
|
|
6
|
+
import bookmarkCard from '@tryghost/kg-default-cards/lib/cards/bookmark.js';
|
|
7
|
+
const { parseFragment, serializeChildren, serializeNode, replaceWith, insertAfter, attr, parents } = domUtils;
|
|
8
|
+
const serializer = new SimpleDom.HTMLSerializer(SimpleDom.voidMap);
|
|
9
|
+
const getYouTubeID = (url) => {
|
|
10
|
+
const arr = url.split(/(vi\/|v%3D|v=|\/v\/|youtu\.be\/|\/embed\/)/);
|
|
11
|
+
return undefined !== arr[2] ? arr[2].split(/[^\w-]/i)[0] : arr[0];
|
|
12
|
+
};
|
|
13
|
+
const isURL = (urlString) => {
|
|
14
|
+
if (undefined === urlString) {
|
|
15
|
+
return false;
|
|
16
|
+
}
|
|
17
|
+
try {
|
|
18
|
+
new URL(urlString);
|
|
19
|
+
return true;
|
|
20
|
+
}
|
|
21
|
+
catch (err) {
|
|
22
|
+
return false;
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
const processHTML = ({ post, options }) => {
|
|
26
|
+
// First, clean up the email HTML to remove bits we don't want or change up
|
|
27
|
+
let html = post?.data.html ?? '';
|
|
28
|
+
// Let's do some regexp magic to remove some beehiiv variables
|
|
29
|
+
// https://support.beehiiv.com/hc/en-us/articles/7606088263191
|
|
30
|
+
html = html.replace(/{{subscriber_id}}/g, ' ');
|
|
31
|
+
html = html.replace(/{{rp_refer_url}}/g, '#');
|
|
32
|
+
html = html.replace(/{{rp_refer_url_no_params}}/g, '#');
|
|
33
|
+
const allParsed = parseFragment(html);
|
|
34
|
+
const contentBlocksEl = allParsed.$('#content-blocks')[0];
|
|
35
|
+
const contentBlocksHtml = contentBlocksEl ? serializeChildren(contentBlocksEl) : '';
|
|
36
|
+
const parsed = parseFragment(contentBlocksHtml);
|
|
37
|
+
// Convert divs with no content but a border-top to a HR
|
|
38
|
+
parsed.$('div').forEach((el) => {
|
|
39
|
+
const styleAttr = attr(el, 'style') || '';
|
|
40
|
+
const hasBorderTop = styleAttr.includes('border-top');
|
|
41
|
+
const hasContent = serializeChildren(el).trim().length > 0;
|
|
42
|
+
if (hasBorderTop && !hasContent) {
|
|
43
|
+
replaceWith(el, '<hr>');
|
|
44
|
+
}
|
|
45
|
+
});
|
|
46
|
+
// Convert sponsored content tables to Ghost HTML cards
|
|
47
|
+
parsed.$('table').forEach((el) => {
|
|
48
|
+
const text = (el.textContent || '').replace(/\s+/g, ' ').trim();
|
|
49
|
+
if (/sponsored content/i.test(text)) {
|
|
50
|
+
const tdEl = parsed.$('td', el)[0] || el;
|
|
51
|
+
// Convert text-only inner divs to <p> tags; skip divs containing images
|
|
52
|
+
parsed.$('div', tdEl).forEach((div) => {
|
|
53
|
+
const inner = serializeChildren(div);
|
|
54
|
+
if (parsed.$('img', div).length > 0) {
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
if (inner.trim().length > 0) {
|
|
58
|
+
replaceWith(div, `<p>${inner}</p>`);
|
|
59
|
+
}
|
|
60
|
+
else {
|
|
61
|
+
div.remove();
|
|
62
|
+
}
|
|
63
|
+
});
|
|
64
|
+
// Remove bare <br> elements that are direct children of td
|
|
65
|
+
parsed.$('br', tdEl).forEach((br) => {
|
|
66
|
+
if (br.parentElement === tdEl) {
|
|
67
|
+
br.remove();
|
|
68
|
+
}
|
|
69
|
+
});
|
|
70
|
+
const content = serializeChildren(tdEl);
|
|
71
|
+
const wrapper = el.parentElement;
|
|
72
|
+
const target = wrapper && wrapper.tagName === 'DIV' ? wrapper : el;
|
|
73
|
+
replaceWith(target, `<!--kg-card-begin: html--><div class="mg-sponsored" data-mg-skip="image-card">${content}</div><!--kg-card-end: html-->`);
|
|
74
|
+
}
|
|
75
|
+
});
|
|
76
|
+
// Convert images to Ghost image cards
|
|
77
|
+
parsed.$('img').forEach((el) => {
|
|
78
|
+
// Skip images inside generic embeds (handled separately as bookmark cards)
|
|
79
|
+
if (parents(el, '.generic-embed--root').length > 0) {
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
// Skip images inside elements marked to skip image card conversion
|
|
83
|
+
if (parents(el, '[data-mg-skip="image-card"]').length > 0) {
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
const src = attr(el, 'src');
|
|
87
|
+
const altText = attr(el, 'alt') || '';
|
|
88
|
+
const parent = el.parentElement;
|
|
89
|
+
const cardOpts = {
|
|
90
|
+
env: { dom: new SimpleDom.Document() },
|
|
91
|
+
payload: {
|
|
92
|
+
src,
|
|
93
|
+
alt: altText,
|
|
94
|
+
caption: null
|
|
95
|
+
}
|
|
96
|
+
};
|
|
97
|
+
if (parent.tagName === 'DIV') {
|
|
98
|
+
const caption = parsed.$('small', parent).map(s => s.textContent.trim()).filter(Boolean).join('') || null;
|
|
99
|
+
cardOpts.payload.caption = caption;
|
|
100
|
+
const outerDiv = parent.parentElement;
|
|
101
|
+
const target = outerDiv && outerDiv.tagName === 'DIV' ? outerDiv : parent;
|
|
102
|
+
replaceWith(target, serializer.serialize(imageCard.render(cardOpts)));
|
|
103
|
+
}
|
|
104
|
+
else if (parent.tagName === 'A') {
|
|
105
|
+
replaceWith(parent, serializer.serialize(imageCard.render(cardOpts)));
|
|
106
|
+
}
|
|
107
|
+
else {
|
|
108
|
+
el.remove();
|
|
109
|
+
insertAfter(parent, serializer.serialize(imageCard.render(cardOpts)));
|
|
110
|
+
}
|
|
111
|
+
});
|
|
112
|
+
// Convert nested padding-left divs to blockquotes
|
|
113
|
+
parsed.$('div[style*="padding-left"] > div[style*="padding-left"]').forEach((el) => {
|
|
114
|
+
const outerDiv = el.parentElement;
|
|
115
|
+
const paragraphs = parsed.$('p', outerDiv);
|
|
116
|
+
if (paragraphs.length > 0) {
|
|
117
|
+
const content = paragraphs.map(p => serializeNode(p)).join('');
|
|
118
|
+
const citation = parsed.$('small', outerDiv).map(s => s.textContent.trim()).filter(Boolean).join('');
|
|
119
|
+
const cite = citation ? `<cite>${citation}</cite>` : '';
|
|
120
|
+
replaceWith(outerDiv, `<blockquote>${content}${cite}</blockquote>`);
|
|
121
|
+
}
|
|
122
|
+
});
|
|
123
|
+
// Convert buttons to Ghost buttons
|
|
124
|
+
parsed.$('a > button').forEach((el) => {
|
|
125
|
+
const link = el.parentElement; // guaranteed by 'a > button' selector
|
|
126
|
+
const wrapper = link.parentElement;
|
|
127
|
+
const buttonText = el.textContent.trim();
|
|
128
|
+
const buttonHref = attr(link, 'href');
|
|
129
|
+
const target = wrapper && wrapper.tagName === 'DIV' ? wrapper : link;
|
|
130
|
+
replaceWith(target, `<div class="kg-card kg-button-card kg-align-center"><a href="${buttonHref}" class="kg-btn kg-btn-accent">${buttonText}</a></div>`);
|
|
131
|
+
});
|
|
132
|
+
// Rewrite subscribe links to Portal signup
|
|
133
|
+
if (options?.subscribeLink) {
|
|
134
|
+
parsed.$('a[href*="/subscribe"]').forEach((el) => {
|
|
135
|
+
attr(el, 'href', options.subscribeLink);
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
// Handle comment links
|
|
139
|
+
if (post?.url && isURL(post.url)) {
|
|
140
|
+
const postOrigin = new URL(post.url).origin;
|
|
141
|
+
if (options?.comments && options?.commentLink) {
|
|
142
|
+
parsed.$('a[href*="comments=true"]').forEach((el) => {
|
|
143
|
+
if (attr(el, 'href').includes(postOrigin)) {
|
|
144
|
+
attr(el, 'href', options.commentLink);
|
|
145
|
+
el.removeAttribute('target');
|
|
146
|
+
el.removeAttribute('rel');
|
|
147
|
+
}
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
else if (options?.comments === false) {
|
|
151
|
+
parsed.$('a[href*="comments=true"]').forEach((el) => {
|
|
152
|
+
if (attr(el, 'href').includes(postOrigin)) {
|
|
153
|
+
el.remove();
|
|
154
|
+
}
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
// Handle link embeds
|
|
159
|
+
parsed.$('.generic-embed--root').forEach((el) => {
|
|
160
|
+
const anchorEl = parsed.$('a', el)[0];
|
|
161
|
+
const titleEl = parsed.$('.generic-embed--title p', el)[0];
|
|
162
|
+
const descEl = parsed.$('.generic-embed--description p', el)[0];
|
|
163
|
+
const imageEl = parsed.$('.generic-embed--image img', el)[0];
|
|
164
|
+
const href = anchorEl ? attr(anchorEl, 'href') : null;
|
|
165
|
+
const title = titleEl ? _.unescape(titleEl.textContent) : '';
|
|
166
|
+
const description = descEl ? _.unescape(descEl.textContent) : '';
|
|
167
|
+
const image = imageEl ? attr(imageEl, 'src') : null;
|
|
168
|
+
let cardOpts = {
|
|
169
|
+
env: { dom: new SimpleDom.Document() },
|
|
170
|
+
payload: {
|
|
171
|
+
url: href,
|
|
172
|
+
metadata: {
|
|
173
|
+
url: href,
|
|
174
|
+
title: title,
|
|
175
|
+
description: description,
|
|
176
|
+
icon: null,
|
|
177
|
+
thumbnail: image,
|
|
178
|
+
publisher: null
|
|
179
|
+
},
|
|
180
|
+
caption: null
|
|
181
|
+
}
|
|
182
|
+
};
|
|
183
|
+
replaceWith(el, serializer.serialize(bookmarkCard.render(cardOpts)));
|
|
184
|
+
});
|
|
185
|
+
// Unwrap audio iframes from tables
|
|
186
|
+
parsed.$('table iframe[src^="https://audio.beehiiv.com"]').forEach((el) => {
|
|
187
|
+
const tableParent = parents(el, 'table')[0];
|
|
188
|
+
if (tableParent) {
|
|
189
|
+
const iframeHtml = serializeNode(el);
|
|
190
|
+
replaceWith(tableParent, iframeHtml);
|
|
191
|
+
}
|
|
192
|
+
});
|
|
193
|
+
// Convert YouTube iframes to embeds
|
|
194
|
+
parsed.$('iframe[src*="youtube.com/embed"], iframe[src*="youtu.be"]').forEach((el) => {
|
|
195
|
+
const videoID = getYouTubeID(attr(el, 'src'));
|
|
196
|
+
let cardOpts = {
|
|
197
|
+
env: { dom: new SimpleDom.Document() },
|
|
198
|
+
payload: {
|
|
199
|
+
caption: null,
|
|
200
|
+
html: `<iframe src="https://www.youtube.com/embed/${videoID}?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen="" width="160" height="90"></iframe>`
|
|
201
|
+
}
|
|
202
|
+
};
|
|
203
|
+
replaceWith(el, serializer.serialize(embedCard.render(cardOpts)));
|
|
204
|
+
});
|
|
205
|
+
// Remove empty paragraphs
|
|
206
|
+
parsed.$('p').forEach((el) => {
|
|
207
|
+
const text = (el.textContent || '').trim();
|
|
208
|
+
if (text.length === 0) {
|
|
209
|
+
el.remove();
|
|
210
|
+
}
|
|
211
|
+
});
|
|
212
|
+
// Remove style tags
|
|
213
|
+
parsed.$('style').forEach((el) => {
|
|
214
|
+
el.remove();
|
|
215
|
+
});
|
|
216
|
+
// Remove mobile ads
|
|
217
|
+
parsed.$('#pad-mobile').forEach((el) => {
|
|
218
|
+
el.remove();
|
|
219
|
+
});
|
|
220
|
+
// Remove style attributes
|
|
221
|
+
parsed.$('[style]').forEach((el) => {
|
|
222
|
+
el.removeAttribute('style');
|
|
223
|
+
});
|
|
224
|
+
// Unwrap divs, but preserve Ghost card and data-mg-skip divs
|
|
225
|
+
parsed.$('div:not([class*="kg-"]):not([data-mg-skip])').forEach((el) => {
|
|
226
|
+
if (parents(el, '[data-mg-skip]').length > 0) {
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
replaceWith(el, serializeChildren(el));
|
|
230
|
+
});
|
|
231
|
+
// Remove b, strong, i, em tags from headings but allow links inside them
|
|
232
|
+
parsed.$('h1, h2, h3, h4, h5, h6').forEach((el) => {
|
|
233
|
+
parsed.$('b, strong, i, em', el).forEach((ell) => {
|
|
234
|
+
replaceWith(ell, serializeChildren(ell));
|
|
235
|
+
});
|
|
236
|
+
});
|
|
237
|
+
// Get the cleaned HTML
|
|
238
|
+
let bodyHtml = parsed.html();
|
|
239
|
+
return bodyHtml;
|
|
240
|
+
};
|
|
241
|
+
const removeDuplicateFeatureImage = ({ html, featureSrc }) => {
|
|
242
|
+
const parsed = parseFragment(html);
|
|
243
|
+
let firstElement = parsed.$('*')[0];
|
|
244
|
+
if (firstElement) {
|
|
245
|
+
const isImg = firstElement.tagName === 'IMG';
|
|
246
|
+
const hasImg = !isImg && parsed.$('img', firstElement).length > 0;
|
|
247
|
+
if (isImg || hasImg) {
|
|
248
|
+
let theImgElement = isImg ? firstElement : parsed.$('img', firstElement)[0];
|
|
249
|
+
let removeTarget = isImg ? firstElement : firstElement;
|
|
250
|
+
let firstImgSrc = attr(theImgElement, 'src');
|
|
251
|
+
// Both images usually end in the same way, so we can split the URL and compare the last part
|
|
252
|
+
const firstImageSplit = firstImgSrc.split('/uploads/asset/');
|
|
253
|
+
const featureImageSplit = featureSrc.split('/uploads/asset/');
|
|
254
|
+
if (firstImageSplit[1] !== undefined && featureImageSplit[1] !== undefined && firstImageSplit[1] === featureImageSplit[1]) {
|
|
255
|
+
removeTarget.remove();
|
|
256
|
+
}
|
|
257
|
+
if (featureSrc.length > 0 && firstImgSrc) {
|
|
258
|
+
let normalizedFirstSrc = firstImgSrc.replace('fit=scale-down,format=auto,onerror=redirect,quality=80', 'quality=100');
|
|
259
|
+
if (featureSrc === normalizedFirstSrc) {
|
|
260
|
+
removeTarget.remove();
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
return parsed.html();
|
|
266
|
+
};
|
|
267
|
+
export { getYouTubeID, isURL, processHTML, removeDuplicateFeatureImage };
|
|
268
|
+
//# sourceMappingURL=process.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"process.js","sourceRoot":"","sources":["../../src/lib/process.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,QAAQ,EAAC,MAAM,oBAAoB,CAAC;AAC5C,OAAO,CAAC,MAAM,QAAQ,CAAC;AAEvB,OAAO,SAAS,MAAM,YAAY,CAAC;AACnC,OAAO,SAAS,MAAM,+CAA+C,CAAC;AACtE,OAAO,SAAS,MAAM,+CAA+C,CAAC;AACtE,OAAO,YAAY,MAAM,kDAAkD,CAAC;AAE5E,MAAM,EAAC,aAAa,EAAE,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KAAK,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,EAAE,YAAY,CAAC,CAAC,CAAC,CAAC,CAAC;YAC5E,IAAI,YAAY,GAAG,KAAK,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,YAAY,CAAC;YACvD,IAAI,WAAW,GAAQ,IAAI,CAAC,aAAa,EAAE,KAAK,CAAC,CAAC;YAElD,6FAA6F;YAC7F,MAAM,eAAe,GAAG,WAAW,CAAC,KAAK,CAAC,iBAAiB,CAAC,CAAC;YAC7D,MAAM,iBAAiB,GAAG,UAAU,CAAC,KAAK,CAAC,iBAAiB,CAAC,CAAC;YAE9D,IAAI,eAAe,CAAC,CAAC,CAAC,KAAK,SAAS,IAAI,iBAAiB,CAAC,CAAC,CAAC,KAAK,SAAS,IAAI,eAAe,CAAC,CAAC,CAAC,KAAK,iBAAiB,CAAC,CAAC,CAAC,EAAE,CAAC;gBACxH,YAAY,CAAC,MAAM,EAAE,CAAC;YAC1B,CAAC;YAED,IAAI,UAAU,CAAC,MAAM,GAAG,CAAC,IAAI,WAAW,EAAE,CAAC;gBACvC,IAAI,kBAAkB,GAAG,WAAW,CAAC,OAAO,CAAC,wDAAwD,EAAE,aAAa,CAAC,CAAC;gBAEtH,IAAI,UAAU,KAAK,kBAAkB,EAAE,CAAC;oBACpC,YAAY,CAAC,MAAM,EAAE,CAAC;gBAC1B,CAAC;YACL,CAAC;QACL,CAAC;IACL,CAAC;IAED,OAAO,MAAM,CAAC,IAAI,EAAE,CAAC;AACzB,CAAC,CAAC;AAEF,OAAO,EACH,YAAY,EACZ,KAAK,EACL,WAAW,EACX,2BAA2B,EAC9B,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import { describe, it, beforeEach, afterEach, mock } from 'node:test';
|
|
3
|
+
import { client } from '../lib/client.js';
|
|
4
|
+
describe('beehiiv API Client', () => {
|
|
5
|
+
let fetchMock;
|
|
6
|
+
beforeEach(() => {
|
|
7
|
+
fetchMock = mock.method(global, 'fetch', () => Promise.resolve());
|
|
8
|
+
});
|
|
9
|
+
afterEach(() => {
|
|
10
|
+
mock.restoreAll();
|
|
11
|
+
});
|
|
12
|
+
describe('client', () => {
|
|
13
|
+
it('makes authenticated request to publications endpoint', async () => {
|
|
14
|
+
const mockData = { data: [{ id: 'pub-1', name: 'Test Publication' }] };
|
|
15
|
+
fetchMock.mock.mockImplementation(() => Promise.resolve({
|
|
16
|
+
ok: true,
|
|
17
|
+
json: () => Promise.resolve(mockData)
|
|
18
|
+
}));
|
|
19
|
+
await client('test-api-key');
|
|
20
|
+
assert.equal(fetchMock.mock.callCount(), 1);
|
|
21
|
+
const [calledUrl, options] = fetchMock.mock.calls[0].arguments;
|
|
22
|
+
assert.equal(calledUrl.toString(), 'https://api.beehiiv.com/v2/publications');
|
|
23
|
+
assert.equal(options.method, 'GET');
|
|
24
|
+
assert.equal(options.headers.Authorization, 'Bearer test-api-key');
|
|
25
|
+
});
|
|
26
|
+
it('returns publications data', async () => {
|
|
27
|
+
const publications = [{ id: 'pub-1', name: 'Test Pub' }];
|
|
28
|
+
fetchMock.mock.mockImplementation(() => Promise.resolve({
|
|
29
|
+
ok: true,
|
|
30
|
+
json: () => Promise.resolve({ data: publications })
|
|
31
|
+
}));
|
|
32
|
+
const result = await client('test-api-key');
|
|
33
|
+
assert.deepEqual(result, publications);
|
|
34
|
+
});
|
|
35
|
+
it('throws error on failed request', async () => {
|
|
36
|
+
fetchMock.mock.mockImplementation(() => Promise.resolve({
|
|
37
|
+
ok: false,
|
|
38
|
+
status: 401,
|
|
39
|
+
statusText: 'Unauthorized'
|
|
40
|
+
}));
|
|
41
|
+
await assert.rejects(async () => {
|
|
42
|
+
await client('invalid-key');
|
|
43
|
+
}, /Request failed: 401 Unauthorized/);
|
|
44
|
+
});
|
|
45
|
+
});
|
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a,CAAC,CAAC;YAChC,CAAC,EAAE,kCAAkC,CAAC,CAAC;QAC3C,CAAC,CAAC,CAAC;IACP,CAAC,CAAC,CAAC;AACP,CAAC,CAAC,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import { describe, it, beforeEach, afterEach, mock } from 'node:test';
|
|
3
|
+
import { fetchTasks, authedClient } from '../lib/fetch.js';
|
|
4
|
+
describe('beehiiv API Fetch', () => {
|
|
5
|
+
let fetchMock;
|
|
6
|
+
beforeEach(() => {
|
|
7
|
+
fetchMock = mock.method(global, 'fetch', () => Promise.resolve());
|
|
8
|
+
});
|
|
9
|
+
afterEach(() => {
|
|
10
|
+
mock.restoreAll();
|
|
11
|
+
});
|
|
12
|
+
describe('authedClient', () => {
|
|
13
|
+
it('makes authenticated GET request', async () => {
|
|
14
|
+
fetchMock.mock.mockImplementation(() => Promise.resolve({ ok: true, json: () => Promise.resolve({ data: [] }) }));
|
|
15
|
+
const url = new URL('https://api.beehiiv.com/v2/publications');
|
|
16
|
+
await authedClient('test-api-key', url);
|
|
17
|
+
assert.equal(fetchMock.mock.callCount(), 1);
|
|
18
|
+
const [calledUrl, options] = fetchMock.mock.calls[0].arguments;
|
|
19
|
+
assert.equal(calledUrl.toString(), 'https://api.beehiiv.com/v2/publications');
|
|
20
|
+
assert.equal(options.method, 'GET');
|
|
21
|
+
assert.equal(options.headers.Authorization, 'Bearer test-api-key');
|
|
22
|
+
});
|
|
23
|
+
});
|
|
24
|
+
describe('fetchTasks', () => {
|
|
25
|
+
it('creates correct number of tasks based on total posts', async () => {
|
|
26
|
+
// Mock the discover call (limit=1)
|
|
27
|
+
fetchMock.mock.mockImplementationOnce(() => Promise.resolve({
|
|
28
|
+
ok: true,
|
|
29
|
+
json: () => Promise.resolve({ total_results: 25, data: [] })
|
|
30
|
+
}), 0);
|
|
31
|
+
const options = { key: 'test-key', id: 'pub-123' };
|
|
32
|
+
const ctx = {
|
|
33
|
+
fileCache: {
|
|
34
|
+
hasFile: () => false,
|
|
35
|
+
readTmpJSONFile: () => Promise.resolve({}),
|
|
36
|
+
writeTmpFile: () => Promise.resolve()
|
|
37
|
+
},
|
|
38
|
+
result: { posts: [] }
|
|
39
|
+
};
|
|
40
|
+
const tasks = await fetchTasks(options, ctx);
|
|
41
|
+
// 25 posts / 10 per page = 3 pages
|
|
42
|
+
assert.equal(tasks.length, 3);
|
|
43
|
+
assert.equal(tasks[0].title, 'Fetching posts page 1 of 3');
|
|
44
|
+
assert.equal(tasks[1].title, 'Fetching posts page 2 of 3');
|
|
45
|
+
assert.equal(tasks[2].title, 'Fetching posts page 3 of 3');
|
|
46
|
+
});
|
|
47
|
+
it('task fetches posts and adds to context', async () => {
|
|
48
|
+
// Mock the discover call
|
|
49
|
+
fetchMock.mock.mockImplementationOnce(() => Promise.resolve({
|
|
50
|
+
ok: true,
|
|
51
|
+
json: () => Promise.resolve({ total_results: 5, data: [] })
|
|
52
|
+
}), 0);
|
|
53
|
+
// Mock the actual fetch call
|
|
54
|
+
fetchMock.mock.mockImplementationOnce(() => Promise.resolve({
|
|
55
|
+
ok: true,
|
|
56
|
+
json: () => Promise.resolve({
|
|
57
|
+
data: [{ id: 'post-1', title: 'Test Post' }]
|
|
58
|
+
})
|
|
59
|
+
}), 1);
|
|
60
|
+
const options = { key: 'test-key', id: 'pub-123' };
|
|
61
|
+
const ctx = {
|
|
62
|
+
fileCache: {
|
|
63
|
+
hasFile: () => false,
|
|
64
|
+
writeTmpFile: () => Promise.resolve()
|
|
65
|
+
},
|
|
66
|
+
result: { posts: [] }
|
|
67
|
+
};
|
|
68
|
+
const tasks = await fetchTasks(options, ctx);
|
|
69
|
+
// Execute the first task
|
|
70
|
+
await tasks[0].task({}, { output: '' });
|
|
71
|
+
assert.equal(ctx.result.posts.length, 1);
|
|
72
|
+
assert.equal(ctx.result.posts[0].id, 'post-1');
|
|
73
|
+
});
|
|
74
|
+
it('task uses cached data when available', async () => {
|
|
75
|
+
// Mock the discover call
|
|
76
|
+
fetchMock.mock.mockImplementationOnce(() => Promise.resolve({
|
|
77
|
+
ok: true,
|
|
78
|
+
json: () => Promise.resolve({ total_results: 5, data: [] })
|
|
79
|
+
}), 0);
|
|
80
|
+
const cachedData = { data: [{ id: 'cached-post', title: 'Cached Post' }] };
|
|
81
|
+
const options = { key: 'test-key', id: 'pub-123' };
|
|
82
|
+
const ctx = {
|
|
83
|
+
fileCache: {
|
|
84
|
+
hasFile: () => true,
|
|
85
|
+
readTmpJSONFile: () => Promise.resolve(cachedData)
|
|
86
|
+
},
|
|
87
|
+
result: { posts: [] }
|
|
88
|
+
};
|
|
89
|
+
const tasks = await fetchTasks(options, ctx);
|
|
90
|
+
await tasks[0].task({}, { output: '' });
|
|
91
|
+
// Should use cached data, not make another API call
|
|
92
|
+
assert.equal(ctx.result.posts.length, 1);
|
|
93
|
+
assert.equal(ctx.result.posts[0].id, 'cached-post');
|
|
94
|
+
// fetch should only be called once (for discover), not twice
|
|
95
|
+
assert.equal(fetchMock.mock.callCount(), 1);
|
|
96
|
+
});
|
|
97
|
+
it('task throws and sets output on fetch error', async () => {
|
|
98
|
+
// Mock the discover call
|
|
99
|
+
fetchMock.mock.mockImplementationOnce(() => Promise.resolve({
|
|
100
|
+
ok: true,
|
|
101
|
+
json: () => Promise.resolve({ total_results: 5, data: [] })
|
|
102
|
+
}), 0);
|
|
103
|
+
// Mock a failed fetch
|
|
104
|
+
fetchMock.mock.mockImplementationOnce(() => Promise.resolve({
|
|
105
|
+
ok: false,
|
|
106
|
+
status: 500,
|
|
107
|
+
statusText: 'Internal Server Error'
|
|
108
|
+
}), 1);
|
|
109
|
+
const options = { key: 'test-key', id: 'pub-123' };
|
|
110
|
+
const ctx = {
|
|
111
|
+
fileCache: {
|
|
112
|
+
hasFile: () => false,
|
|
113
|
+
writeTmpFile: () => Promise.resolve()
|
|
114
|
+
},
|
|
115
|
+
result: { posts: [] }
|
|
116
|
+
};
|
|
117
|
+
const tasks = await fetchTasks(options, ctx);
|
|
118
|
+
const mockTask = { output: '' };
|
|
119
|
+
await assert.rejects(async () => {
|
|
120
|
+
await tasks[0].task({}, mockTask);
|
|
121
|
+
}, /Request failed: 500 Internal Server Error/);
|
|
122
|
+
assert.ok(mockTask.output.includes('500'));
|
|
123
|
+
});
|
|
124
|
+
it('task handles non-Error thrown objects', async () => {
|
|
125
|
+
// Mock the discover call
|
|
126
|
+
fetchMock.mock.mockImplementationOnce(() => Promise.resolve({
|
|
127
|
+
ok: true,
|
|
128
|
+
json: () => Promise.resolve({ total_results: 5, data: [] })
|
|
129
|
+
}), 0);
|
|
130
|
+
// Mock fetch that throws a non-Error value (string)
|
|
131
|
+
fetchMock.mock.mockImplementationOnce(() => {
|
|
132
|
+
// eslint-disable-next-line no-throw-literal
|
|
133
|
+
throw 'Network error string';
|
|
134
|
+
}, 1);
|
|
135
|
+
const options = { key: 'test-key', id: 'pub-123' };
|
|
136
|
+
const ctx = {
|
|
137
|
+
fileCache: {
|
|
138
|
+
hasFile: () => false,
|
|
139
|
+
writeTmpFile: () => Promise.resolve()
|
|
140
|
+
},
|
|
141
|
+
result: { posts: [] }
|
|
142
|
+
};
|
|
143
|
+
const tasks = await fetchTasks(options, ctx);
|
|
144
|
+
const mockTask = { output: '' };
|
|
145
|
+
await assert.rejects(async () => {
|
|
146
|
+
await tasks[0].task({}, mockTask);
|
|
147
|
+
});
|
|
148
|
+
// Verify String() conversion was used
|
|
149
|
+
assert.equal(mockTask.output, 'Network error string');
|
|
150
|
+
});
|
|
151
|
+
it('filters posts with postsAfter', async () => {
|
|
152
|
+
const jan1 = new Date('2024-01-01').getTime() / 1000;
|
|
153
|
+
const feb1 = new Date('2024-02-01').getTime() / 1000;
|
|
154
|
+
const mar1 = new Date('2024-03-01').getTime() / 1000;
|
|
155
|
+
fetchMock.mock.mockImplementationOnce(() => Promise.resolve({
|
|
156
|
+
ok: true,
|
|
157
|
+
json: () => Promise.resolve({ total_results: 3, data: [] })
|
|
158
|
+
}), 0);
|
|
159
|
+
fetchMock.mock.mockImplementationOnce(() => Promise.resolve({
|
|
160
|
+
ok: true,
|
|
161
|
+
json: () => Promise.resolve({
|
|
162
|
+
data: [
|
|
163
|
+
{ id: 'post-jan', publish_date: jan1 },
|
|
164
|
+
{ id: 'post-feb', publish_date: feb1 },
|
|
165
|
+
{ id: 'post-mar', publish_date: mar1 }
|
|
166
|
+
]
|
|
167
|
+
})
|
|
168
|
+
}), 1);
|
|
169
|
+
const options = { key: 'test-key', id: 'pub-123', postsAfter: '2024-02-01' };
|
|
170
|
+
const ctx = {
|
|
171
|
+
fileCache: {
|
|
172
|
+
hasFile: () => false,
|
|
173
|
+
writeTmpFile: () => Promise.resolve()
|
|
174
|
+
},
|
|
175
|
+
result: { posts: [] }
|
|
176
|
+
};
|
|
177
|
+
const tasks = await fetchTasks(options, ctx);
|
|
178
|
+
await tasks[0].task({}, { output: '' });
|
|
179
|
+
assert.equal(ctx.result.posts.length, 2);
|
|
180
|
+
assert.equal(ctx.result.posts[0].id, 'post-feb');
|
|
181
|
+
assert.equal(ctx.result.posts[1].id, 'post-mar');
|
|
182
|
+
});
|
|
183
|
+
it('filters posts with postsBefore', async () => {
|
|
184
|
+
const jan1 = new Date('2024-01-01').getTime() / 1000;
|
|
185
|
+
const feb1 = new Date('2024-02-01').getTime() / 1000;
|
|
186
|
+
const mar1 = new Date('2024-03-01').getTime() / 1000;
|
|
187
|
+
fetchMock.mock.mockImplementationOnce(() => Promise.resolve({
|
|
188
|
+
ok: true,
|
|
189
|
+
json: () => Promise.resolve({ total_results: 3, data: [] })
|
|
190
|
+
}), 0);
|
|
191
|
+
fetchMock.mock.mockImplementationOnce(() => Promise.resolve({
|
|
192
|
+
ok: true,
|
|
193
|
+
json: () => Promise.resolve({
|
|
194
|
+
data: [
|
|
195
|
+
{ id: 'post-jan', publish_date: jan1 },
|
|
196
|
+
{ id: 'post-feb', publish_date: feb1 },
|
|
197
|
+
{ id: 'post-mar', publish_date: mar1 }
|
|
198
|
+
]
|
|
199
|
+
})
|
|
200
|
+
}), 1);
|
|
201
|
+
const options = { key: 'test-key', id: 'pub-123', postsBefore: '2024-02-01' };
|
|
202
|
+
const ctx = {
|
|
203
|
+
fileCache: {
|
|
204
|
+
hasFile: () => false,
|
|
205
|
+
writeTmpFile: () => Promise.resolve()
|
|
206
|
+
},
|
|
207
|
+
result: { posts: [] }
|
|
208
|
+
};
|
|
209
|
+
const tasks = await fetchTasks(options, ctx);
|
|
210
|
+
await tasks[0].task({}, { output: '' });
|
|
211
|
+
assert.equal(ctx.result.posts.length, 2);
|
|
212
|
+
assert.equal(ctx.result.posts[0].id, 'post-jan');
|
|
213
|
+
assert.equal(ctx.result.posts[1].id, 'post-feb');
|
|
214
|
+
});
|
|
215
|
+
it('filters posts with both postsAfter and postsBefore', async () => {
|
|
216
|
+
const jan1 = new Date('2024-01-01').getTime() / 1000;
|
|
217
|
+
const feb1 = new Date('2024-02-01').getTime() / 1000;
|
|
218
|
+
const mar1 = new Date('2024-03-01').getTime() / 1000;
|
|
219
|
+
const apr1 = new Date('2024-04-01').getTime() / 1000;
|
|
220
|
+
fetchMock.mock.mockImplementationOnce(() => Promise.resolve({
|
|
221
|
+
ok: true,
|
|
222
|
+
json: () => Promise.resolve({ total_results: 4, data: [] })
|
|
223
|
+
}), 0);
|
|
224
|
+
fetchMock.mock.mockImplementationOnce(() => Promise.resolve({
|
|
225
|
+
ok: true,
|
|
226
|
+
json: () => Promise.resolve({
|
|
227
|
+
data: [
|
|
228
|
+
{ id: 'post-jan', publish_date: jan1 },
|
|
229
|
+
{ id: 'post-feb', publish_date: feb1 },
|
|
230
|
+
{ id: 'post-mar', publish_date: mar1 },
|
|
231
|
+
{ id: 'post-apr', publish_date: apr1 }
|
|
232
|
+
]
|
|
233
|
+
})
|
|
234
|
+
}), 1);
|
|
235
|
+
const options = { key: 'test-key', id: 'pub-123', postsAfter: '2024-02-01', postsBefore: '2024-03-01' };
|
|
236
|
+
const ctx = {
|
|
237
|
+
fileCache: {
|
|
238
|
+
hasFile: () => false,
|
|
239
|
+
writeTmpFile: () => Promise.resolve()
|
|
240
|
+
},
|
|
241
|
+
result: { posts: [] }
|
|
242
|
+
};
|
|
243
|
+
const tasks = await fetchTasks(options, ctx);
|
|
244
|
+
await tasks[0].task({}, { output: '' });
|
|
245
|
+
assert.equal(ctx.result.posts.length, 2);
|
|
246
|
+
assert.equal(ctx.result.posts[0].id, 'post-feb');
|
|
247
|
+
assert.equal(ctx.result.posts[1].id, 'post-mar');
|
|
248
|
+
});
|
|
249
|
+
it('does not filter when neither postsAfter nor postsBefore is set', async () => {
|
|
250
|
+
fetchMock.mock.mockImplementationOnce(() => Promise.resolve({
|
|
251
|
+
ok: true,
|
|
252
|
+
json: () => Promise.resolve({ total_results: 2, data: [] })
|
|
253
|
+
}), 0);
|
|
254
|
+
fetchMock.mock.mockImplementationOnce(() => Promise.resolve({
|
|
255
|
+
ok: true,
|
|
256
|
+
json: () => Promise.resolve({
|
|
257
|
+
data: [
|
|
258
|
+
{ id: 'post-1', publish_date: 1704067200 },
|
|
259
|
+
{ id: 'post-2', publish_date: 1706745600 }
|
|
260
|
+
]
|
|
261
|
+
})
|
|
262
|
+
}), 1);
|
|
263
|
+
const options = { key: 'test-key', id: 'pub-123' };
|
|
264
|
+
const ctx = {
|
|
265
|
+
fileCache: {
|
|
266
|
+
hasFile: () => false,
|
|
267
|
+
writeTmpFile: () => Promise.resolve()
|
|
268
|
+
},
|
|
269
|
+
result: { posts: [] }
|
|
270
|
+
};
|
|
271
|
+
const tasks = await fetchTasks(options, ctx);
|
|
272
|
+
await tasks[0].task({}, { output: '' });
|
|
273
|
+
assert.equal(ctx.result.posts.length, 2);
|
|
274
|
+
});
|
|
275
|
+
it('handles discover error', async () => {
|
|
276
|
+
fetchMock.mock.mockImplementation(() => Promise.resolve({
|
|
277
|
+
ok: false,
|
|
278
|
+
status: 401,
|
|
279
|
+
statusText: 'Unauthorized'
|
|
280
|
+
}));
|
|
281
|
+
const options = { key: 'invalid-key', id: 'pub-123' };
|
|
282
|
+
const ctx = {
|
|
283
|
+
fileCache: {},
|
|
284
|
+
result: { posts: [] }
|
|
285
|
+
};
|
|
286
|
+
await assert.rejects(async () => {
|
|
287
|
+
await fetchTasks(options, ctx);
|
|
288
|
+
}, /Request failed: 401 Unauthorized/);
|
|
289
|
+
});
|
|
290
|
+
});
|
|
291
|
+
});
|
|
292
|
+
//# sourceMappingURL=fetch.test.js.map
|