note-blog-kit 0.1.0 → 0.2.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.
@@ -1 +1,375 @@
1
+ import { z } from 'zod';
1
2
 
3
+ // src/react/safe-url.ts
4
+ function safeHttpUrl(url) {
5
+ if (typeof url !== "string" || !/^https?:\/\//i.test(url)) return null;
6
+ for (let i = 0; i < url.length; i += 1) {
7
+ const code = url.charCodeAt(i);
8
+ if (code <= 32 || code === 127) return null;
9
+ }
10
+ return url;
11
+ }
12
+
13
+ // src/next/metadata.ts
14
+ function httpsOnly(url) {
15
+ const safe = safeHttpUrl(url);
16
+ return safe !== null && /^https:\/\//i.test(safe) ? safe : null;
17
+ }
18
+ function toImage(article) {
19
+ const eyecatch = "eyecatch" in article ? article.eyecatch : null;
20
+ if (eyecatch) {
21
+ const url2 = httpsOnly(eyecatch.url);
22
+ if (url2 === null) return null;
23
+ const image = { url: url2 };
24
+ if (eyecatch.width !== null) image.width = eyecatch.width;
25
+ if (eyecatch.height !== null) image.height = eyecatch.height;
26
+ if (eyecatch.alt !== "") image.alt = eyecatch.alt;
27
+ return image;
28
+ }
29
+ const url = httpsOnly(article.eyecatchUrl);
30
+ return url === null ? null : { url };
31
+ }
32
+ function generateNoteMetadata(article, options = {}) {
33
+ const title = options.formatTitle ? options.formatTitle(article.title) : article.title;
34
+ const canonical = options.canonical ?? httpsOnly(article.url);
35
+ if (canonical === null) throw new TypeError(`article.url must be an https URL: ${JSON.stringify(article.url)}`);
36
+ const image = toImage(article);
37
+ const openGraph = {
38
+ type: "article",
39
+ title,
40
+ description: article.excerpt,
41
+ url: canonical,
42
+ publishedTime: article.publishedAt
43
+ };
44
+ const twitter = {
45
+ card: image ? "summary_large_image" : "summary",
46
+ title,
47
+ description: article.excerpt
48
+ };
49
+ if (image) {
50
+ openGraph.images = [image];
51
+ twitter.images = [image.url];
52
+ }
53
+ return { title, description: article.excerpt, alternates: { canonical }, openGraph, twitter };
54
+ }
55
+
56
+ // src/server/errors.ts
57
+ function toErrorOptions(options) {
58
+ return options !== void 0 && "cause" in options ? { cause: options.cause } : void 0;
59
+ }
60
+ var NoteError = class extends Error {
61
+ // 利用者側のバンドラがクラス名を圧縮しても変わらないよう、name は文字列で持つ
62
+ name = "NoteError";
63
+ code;
64
+ constructor(message, options) {
65
+ super(message, toErrorOptions(options));
66
+ this.code = options.code;
67
+ }
68
+ };
69
+ var NoteNotFoundError = class extends NoteError {
70
+ name = "NoteNotFoundError";
71
+ code = "NOTE_NOT_FOUND";
72
+ /** リクエストした URL */
73
+ url;
74
+ constructor(message, options) {
75
+ super(message, { ...options, code: "NOTE_NOT_FOUND" });
76
+ this.url = options.url;
77
+ }
78
+ };
79
+ var NoteHttpError = class extends NoteError {
80
+ name = "NoteHttpError";
81
+ code = "NOTE_HTTP_ERROR";
82
+ status;
83
+ /** リクエストした URL */
84
+ url;
85
+ constructor(message, options) {
86
+ super(message, { ...options, code: "NOTE_HTTP_ERROR" });
87
+ this.status = options.status;
88
+ this.url = options.url;
89
+ }
90
+ };
91
+ var NoteNetworkError = class extends NoteError {
92
+ name = "NoteNetworkError";
93
+ code = "NOTE_NETWORK_ERROR";
94
+ constructor(message, options) {
95
+ super(message, { ...options, code: "NOTE_NETWORK_ERROR" });
96
+ }
97
+ };
98
+ var NoteTimeoutError = class extends NoteError {
99
+ name = "NoteTimeoutError";
100
+ code = "NOTE_TIMEOUT";
101
+ constructor(message, options) {
102
+ super(message, { ...options, code: "NOTE_TIMEOUT" });
103
+ }
104
+ };
105
+ var NoteSchemaError = class extends NoteError {
106
+ name = "NoteSchemaError";
107
+ code = "NOTE_SCHEMA_ERROR";
108
+ issues;
109
+ constructor(message, options) {
110
+ const detail = options.issues.slice(0, 5).map((issue) => `${issue.path || "(root)"}: ${issue.message}`).join("; ");
111
+ super(detail === "" ? message : `${message} (${detail})`, { ...options, code: "NOTE_SCHEMA_ERROR" });
112
+ this.issues = options.issues;
113
+ }
114
+ };
115
+
116
+ // src/server/fetch-json.ts
117
+ var NOTE_ORIGIN = "https://note.com";
118
+ async function fetchNoteJson(url, options) {
119
+ if (new URL(url).origin !== NOTE_ORIGIN) {
120
+ throw new TypeError(`Refusing to request a non-note.com URL: ${url}`);
121
+ }
122
+ options.signal?.throwIfAborted();
123
+ const controller = new AbortController();
124
+ let timedOut = false;
125
+ const timer = setTimeout(() => {
126
+ timedOut = true;
127
+ controller.abort(new Error(`Timed out after ${options.timeoutMs}ms`));
128
+ }, options.timeoutMs);
129
+ const onAbort = () => controller.abort(options.signal?.reason);
130
+ options.signal?.addEventListener("abort", onAbort, { once: true });
131
+ let response;
132
+ let body;
133
+ try {
134
+ response = await options.fetch(url, {
135
+ method: "GET",
136
+ headers: { Accept: "application/json" },
137
+ credentials: "omit",
138
+ redirect: "error",
139
+ signal: controller.signal
140
+ });
141
+ body = await response.text();
142
+ } catch (error) {
143
+ if (options.signal?.aborted) throw options.signal.reason;
144
+ if (timedOut) {
145
+ throw new NoteTimeoutError(`Request to note timed out after ${options.timeoutMs}ms: ${url}`, { cause: error });
146
+ }
147
+ throw new NoteNetworkError(`Request to note failed: ${url}`, { cause: error });
148
+ } finally {
149
+ clearTimeout(timer);
150
+ options.signal?.removeEventListener("abort", onAbort);
151
+ }
152
+ if (response.redirected || response.url !== "" && new URL(response.url).origin !== NOTE_ORIGIN) {
153
+ throw new NoteNetworkError(`note redirected the request, which is not allowed: ${url}`);
154
+ }
155
+ if (response.status === 404) {
156
+ throw new NoteNotFoundError(`Not found on note: ${url}`, { url });
157
+ }
158
+ if (!response.ok) {
159
+ throw new NoteHttpError(`note responded with HTTP ${response.status}: ${url}`, { status: response.status, url });
160
+ }
161
+ try {
162
+ return JSON.parse(body);
163
+ } catch (error) {
164
+ throw new NoteSchemaError("note returned a response that is not valid JSON", {
165
+ issues: [{ path: "", message: "Invalid JSON" }],
166
+ cause: error
167
+ });
168
+ }
169
+ }
170
+
171
+ // src/server/patterns.ts
172
+ var NOTE_KEY_RE = /^n[0-9a-z]{1,32}$/;
173
+ var NOTE_USER_RE = /^[A-Za-z0-9_-]{1,64}$/;
174
+ function hasControlOrSpace(value) {
175
+ for (let i = 0; i < value.length; i += 1) {
176
+ const code = value.charCodeAt(i);
177
+ if (code <= 32 || code === 127) return true;
178
+ }
179
+ return /\s/.test(value);
180
+ }
181
+ function isHttpsUrl(value) {
182
+ if (!value.startsWith("https://") || hasControlOrSpace(value)) return false;
183
+ try {
184
+ return new URL(value).protocol === "https:";
185
+ } catch {
186
+ return false;
187
+ }
188
+ }
189
+ var httpsUrl = z.string().refine(isHttpsUrl, "https \u306E URL \u3067\u306F\u3042\u308A\u307E\u305B\u3093");
190
+ var optionalHttpsUrl = z.string().refine((value) => value.trim() === "" || isHttpsUrl(value), "https \u306E URL \u3067\u306F\u3042\u308A\u307E\u305B\u3093");
191
+ function emptyToNull(value) {
192
+ return value.trim() === "" ? null : value;
193
+ }
194
+
195
+ // src/server/normalize/contents.ts
196
+ var contentSchema = z.object({
197
+ // リンク・キャッシュキーに使われるため、記事キーの形式に限る
198
+ key: z.string().regex(NOTE_KEY_RE),
199
+ name: z.string(),
200
+ noteUrl: httpsUrl,
201
+ publishAt: z.string().refine((value) => !Number.isNaN(Date.parse(value)), "\u65E5\u6642\u3068\u3057\u3066\u89E3\u91C8\u3067\u304D\u307E\u305B\u3093"),
202
+ body: z.string(),
203
+ // 見出し画像のない記事は null になる(実データで確認。fixture には例がない)
204
+ eyecatch: optionalHttpsUrl.nullable(),
205
+ hashtags: z.array(z.object({ hashtag: z.object({ name: z.string() }) })),
206
+ likeCount: z.number(),
207
+ price: z.number(),
208
+ user: z.object({
209
+ nickname: z.string(),
210
+ // 著者の確認やリンクの組み立てに使われるため、note のユーザー名の形式に限る
211
+ urlname: z.string().regex(NOTE_USER_RE),
212
+ userProfileImagePath: optionalHttpsUrl
213
+ })
214
+ });
215
+ var contentsResponseSchema = z.object({
216
+ data: z.object({
217
+ contents: z.array(contentSchema),
218
+ isLastPage: z.boolean(),
219
+ totalCount: z.number()
220
+ })
221
+ });
222
+ function toSummary(content) {
223
+ return {
224
+ key: content.key,
225
+ title: content.name,
226
+ url: content.noteUrl,
227
+ publishedAt: new Date(content.publishAt).toISOString(),
228
+ excerpt: content.body.trim(),
229
+ eyecatchUrl: content.eyecatch === null ? null : emptyToNull(content.eyecatch),
230
+ hashtags: content.hashtags.map(({ hashtag }) => hashtag.name.replace(/^#/, "")),
231
+ likeCount: content.likeCount,
232
+ price: content.price,
233
+ author: {
234
+ name: content.user.nickname,
235
+ urlname: content.user.urlname,
236
+ imageUrl: emptyToNull(content.user.userProfileImagePath)
237
+ },
238
+ source: "api"
239
+ };
240
+ }
241
+ function normalizeContentsPage(json, page) {
242
+ const result = contentsResponseSchema.safeParse(json);
243
+ if (!result.success) {
244
+ throw new NoteSchemaError("Unexpected shape of the note article list response", {
245
+ issues: result.error.issues.map((issue) => ({ path: issue.path.map(String).join("."), message: issue.message }))
246
+ });
247
+ }
248
+ const { data } = result.data;
249
+ return {
250
+ articles: data.contents.map(toSummary),
251
+ page,
252
+ totalCount: data.totalCount,
253
+ isLastPage: data.isLastPage
254
+ };
255
+ }
256
+
257
+ // src/server/request-options.ts
258
+ var DEFAULT_TIMEOUT_MS = 1e4;
259
+ var DEFAULT_MIN_INTERVAL_MS = 1e3;
260
+ var MAX_TIMER_MS = 2 ** 31 - 1;
261
+ function assertMilliseconds(name, value, min) {
262
+ if (typeof value !== "number" || !Number.isFinite(value) || value < min || value > MAX_TIMER_MS) {
263
+ throw new TypeError(`${name} must be a finite number between ${min} and ${MAX_TIMER_MS}: ${String(value)}`);
264
+ }
265
+ }
266
+
267
+ // src/server/throttle.ts
268
+ function sleep(ms, signal) {
269
+ return new Promise((resolve, reject) => {
270
+ if (signal?.aborted) {
271
+ reject(signal.reason);
272
+ return;
273
+ }
274
+ const onAbort = () => {
275
+ clearTimeout(timer);
276
+ reject(signal?.reason);
277
+ };
278
+ const timer = setTimeout(() => {
279
+ signal?.removeEventListener("abort", onAbort);
280
+ resolve();
281
+ }, ms);
282
+ signal?.addEventListener("abort", onAbort, { once: true });
283
+ });
284
+ }
285
+ function createThrottle() {
286
+ let tail = Promise.resolve();
287
+ let lastSentAt;
288
+ return (minIntervalMs, signal) => {
289
+ const turn = tail.then(async () => {
290
+ if (lastSentAt !== void 0) {
291
+ const wait = lastSentAt + minIntervalMs - Date.now();
292
+ if (wait > 0) await sleep(wait, signal);
293
+ }
294
+ signal?.throwIfAborted();
295
+ lastSentAt = Date.now();
296
+ });
297
+ tail = turn.catch(() => {
298
+ });
299
+ return turn;
300
+ };
301
+ }
302
+ var GLOBAL_KEY = /* @__PURE__ */ Symbol.for("note-blog-kit.throttle");
303
+ function getDefaultThrottle() {
304
+ const store = globalThis;
305
+ store[GLOBAL_KEY] ??= createThrottle();
306
+ return store[GLOBAL_KEY];
307
+ }
308
+
309
+ // src/server/list-articles.ts
310
+ async function listArticles(options) {
311
+ const { user, page = 1, timeoutMs = DEFAULT_TIMEOUT_MS, minIntervalMs = DEFAULT_MIN_INTERVAL_MS, signal } = options;
312
+ if (typeof user !== "string" || !NOTE_USER_RE.test(user)) {
313
+ throw new TypeError(`Invalid note user name: ${typeof user === "string" ? JSON.stringify(user) : typeof user}`);
314
+ }
315
+ if (typeof page !== "number" || !Number.isInteger(page) || page < 1) {
316
+ throw new TypeError(`page must be a positive integer: ${typeof page === "number" ? page : typeof page}`);
317
+ }
318
+ assertMilliseconds("timeoutMs", timeoutMs, 1);
319
+ assertMilliseconds("minIntervalMs", minIntervalMs, 0);
320
+ const url = `${NOTE_ORIGIN}/api/v2/creators/${encodeURIComponent(user)}/contents?kind=note&page=${page}`;
321
+ await getDefaultThrottle()(minIntervalMs, signal);
322
+ const json = await fetchNoteJson(url, { fetch: options.fetch ?? globalThis.fetch, timeoutMs, signal });
323
+ return normalizeContentsPage(json, page);
324
+ }
325
+
326
+ // src/server/iterate-articles.ts
327
+ var DEFAULT_MAX_PAGES = 20;
328
+ async function* iterateArticles(options) {
329
+ const { maxPages = DEFAULT_MAX_PAGES, ...listOptions } = options;
330
+ if (typeof maxPages !== "number" || !Number.isInteger(maxPages) || maxPages < 1) {
331
+ throw new TypeError(
332
+ `maxPages must be a positive integer: ${typeof maxPages === "number" ? maxPages : typeof maxPages}`
333
+ );
334
+ }
335
+ const seen = /* @__PURE__ */ new Set();
336
+ let totalCount = null;
337
+ let pages = 0;
338
+ for (let page = 1; page <= maxPages; page += 1) {
339
+ const result = await listArticles({ ...listOptions, page });
340
+ pages = page;
341
+ totalCount = result.totalCount;
342
+ for (const article of result.articles) {
343
+ if (seen.has(article.key)) continue;
344
+ seen.add(article.key);
345
+ yield article;
346
+ }
347
+ if (result.isLastPage || result.articles.length === 0) {
348
+ return { truncated: false, totalCount, pages };
349
+ }
350
+ }
351
+ return { truncated: true, totalCount, pages };
352
+ }
353
+ async function listAllArticles(options) {
354
+ const articles = [];
355
+ const iterator = iterateArticles(options);
356
+ let step = await iterator.next();
357
+ while (!step.done) {
358
+ articles.push(step.value);
359
+ step = await iterator.next();
360
+ }
361
+ return { articles, ...step.value };
362
+ }
363
+
364
+ // src/next/static-params.ts
365
+ var PARAM_RE = /^[A-Za-z0-9_-]{1,64}$/;
366
+ async function generateNoteStaticParams(options) {
367
+ const { param = "key", ...listOptions } = options;
368
+ if (typeof param !== "string" || !PARAM_RE.test(param)) {
369
+ throw new TypeError(`param must be a dynamic segment name: ${JSON.stringify(param)}`);
370
+ }
371
+ const { articles } = await listAllArticles(listOptions);
372
+ return articles.map((article) => ({ [param]: article.key }));
373
+ }
374
+
375
+ export { generateNoteMetadata, generateNoteStaticParams };