note-blog-kit 0.0.0-stage → 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.
@@ -0,0 +1,610 @@
1
+ import { z } from 'zod';
2
+ import sanitizeHtml from 'sanitize-html';
3
+
4
+ // src/server/errors.ts
5
+ var NOTE_ERROR_CODES = /* @__PURE__ */ new Set([
6
+ "NOTE_NOT_FOUND",
7
+ "NOTE_HTTP_ERROR",
8
+ "NOTE_NETWORK_ERROR",
9
+ "NOTE_TIMEOUT",
10
+ "NOTE_SCHEMA_ERROR"
11
+ ]);
12
+ function toErrorOptions(options) {
13
+ return options !== void 0 && "cause" in options ? { cause: options.cause } : void 0;
14
+ }
15
+ var NoteError = class extends Error {
16
+ // 利用者側のバンドラがクラス名を圧縮しても変わらないよう、name は文字列で持つ
17
+ name = "NoteError";
18
+ code;
19
+ constructor(message, options) {
20
+ super(message, toErrorOptions(options));
21
+ this.code = options.code;
22
+ }
23
+ };
24
+ var NoteNotFoundError = class extends NoteError {
25
+ name = "NoteNotFoundError";
26
+ code = "NOTE_NOT_FOUND";
27
+ /** リクエストした URL */
28
+ url;
29
+ constructor(message, options) {
30
+ super(message, { ...options, code: "NOTE_NOT_FOUND" });
31
+ this.url = options.url;
32
+ }
33
+ };
34
+ var NoteHttpError = class extends NoteError {
35
+ name = "NoteHttpError";
36
+ code = "NOTE_HTTP_ERROR";
37
+ status;
38
+ /** リクエストした URL */
39
+ url;
40
+ constructor(message, options) {
41
+ super(message, { ...options, code: "NOTE_HTTP_ERROR" });
42
+ this.status = options.status;
43
+ this.url = options.url;
44
+ }
45
+ };
46
+ var NoteNetworkError = class extends NoteError {
47
+ name = "NoteNetworkError";
48
+ code = "NOTE_NETWORK_ERROR";
49
+ constructor(message, options) {
50
+ super(message, { ...options, code: "NOTE_NETWORK_ERROR" });
51
+ }
52
+ };
53
+ var NoteTimeoutError = class extends NoteError {
54
+ name = "NoteTimeoutError";
55
+ code = "NOTE_TIMEOUT";
56
+ constructor(message, options) {
57
+ super(message, { ...options, code: "NOTE_TIMEOUT" });
58
+ }
59
+ };
60
+ var NoteSchemaError = class extends NoteError {
61
+ name = "NoteSchemaError";
62
+ code = "NOTE_SCHEMA_ERROR";
63
+ issues;
64
+ constructor(message, options) {
65
+ const detail = options.issues.slice(0, 5).map((issue) => `${issue.path || "(root)"}: ${issue.message}`).join("; ");
66
+ super(detail === "" ? message : `${message} (${detail})`, { ...options, code: "NOTE_SCHEMA_ERROR" });
67
+ this.issues = options.issues;
68
+ }
69
+ };
70
+ function isNoteError(value) {
71
+ if (typeof value !== "object" || value === null) return false;
72
+ const { name, message, code } = value;
73
+ return typeof name === "string" && typeof message === "string" && typeof code === "string" && NOTE_ERROR_CODES.has(code);
74
+ }
75
+
76
+ // src/server/fetch-json.ts
77
+ var NOTE_ORIGIN = "https://note.com";
78
+ async function fetchNoteJson(url, options) {
79
+ if (new URL(url).origin !== NOTE_ORIGIN) {
80
+ throw new TypeError(`Refusing to request a non-note.com URL: ${url}`);
81
+ }
82
+ options.signal?.throwIfAborted();
83
+ const controller = new AbortController();
84
+ let timedOut = false;
85
+ const timer = setTimeout(() => {
86
+ timedOut = true;
87
+ controller.abort(new Error(`Timed out after ${options.timeoutMs}ms`));
88
+ }, options.timeoutMs);
89
+ const onAbort = () => controller.abort(options.signal?.reason);
90
+ options.signal?.addEventListener("abort", onAbort, { once: true });
91
+ let response;
92
+ let body;
93
+ try {
94
+ response = await options.fetch(url, {
95
+ method: "GET",
96
+ headers: { Accept: "application/json" },
97
+ credentials: "omit",
98
+ redirect: "error",
99
+ signal: controller.signal
100
+ });
101
+ body = await response.text();
102
+ } catch (error) {
103
+ if (options.signal?.aborted) throw options.signal.reason;
104
+ if (timedOut) {
105
+ throw new NoteTimeoutError(`Request to note timed out after ${options.timeoutMs}ms: ${url}`, { cause: error });
106
+ }
107
+ throw new NoteNetworkError(`Request to note failed: ${url}`, { cause: error });
108
+ } finally {
109
+ clearTimeout(timer);
110
+ options.signal?.removeEventListener("abort", onAbort);
111
+ }
112
+ if (response.redirected || response.url !== "" && new URL(response.url).origin !== NOTE_ORIGIN) {
113
+ throw new NoteNetworkError(`note redirected the request, which is not allowed: ${url}`);
114
+ }
115
+ if (response.status === 404) {
116
+ throw new NoteNotFoundError(`Not found on note: ${url}`, { url });
117
+ }
118
+ if (!response.ok) {
119
+ throw new NoteHttpError(`note responded with HTTP ${response.status}: ${url}`, { status: response.status, url });
120
+ }
121
+ try {
122
+ return JSON.parse(body);
123
+ } catch (error) {
124
+ throw new NoteSchemaError("note returned a response that is not valid JSON", {
125
+ issues: [{ path: "", message: "Invalid JSON" }],
126
+ cause: error
127
+ });
128
+ }
129
+ }
130
+
131
+ // src/server/patterns.ts
132
+ var NOTE_KEY_RE = /^n[0-9a-z]{1,32}$/;
133
+ var NOTE_USER_RE = /^[A-Za-z0-9_-]{1,64}$/;
134
+ var ALLOWED_TAGS = [
135
+ "p",
136
+ "br",
137
+ "h2",
138
+ "h3",
139
+ "h4",
140
+ "strong",
141
+ "em",
142
+ "s",
143
+ "a",
144
+ "ul",
145
+ "ol",
146
+ "li",
147
+ "blockquote",
148
+ "figure",
149
+ "figcaption",
150
+ "img",
151
+ "pre",
152
+ "code",
153
+ "hr",
154
+ "table",
155
+ "thead",
156
+ "tbody",
157
+ "tr",
158
+ "th",
159
+ "td",
160
+ "div"
161
+ ];
162
+ var DISCARD_WITH_CONTENT = [
163
+ "script",
164
+ "style",
165
+ "iframe",
166
+ "frame",
167
+ "frameset",
168
+ "object",
169
+ "embed",
170
+ "applet",
171
+ "form",
172
+ "input",
173
+ "button",
174
+ "textarea",
175
+ "select",
176
+ "option",
177
+ "svg",
178
+ "math",
179
+ "template",
180
+ "noscript",
181
+ "meta",
182
+ "link",
183
+ "base",
184
+ "title",
185
+ "xmp",
186
+ "plaintext"
187
+ ];
188
+ var ALLOWED_ATTRIBUTES = {
189
+ "*": ["id"],
190
+ a: ["href", "target", "rel"],
191
+ img: ["src", "alt", "width", "height", "loading", "decoding"],
192
+ th: ["colspan", "rowspan"],
193
+ td: ["colspan", "rowspan"],
194
+ figure: ["data-nbk-embed-service", "data-nbk-embed-key", "data-nbk-embed-url"],
195
+ div: ["data-nbk-toc"]
196
+ };
197
+ var LINK_SCHEMES = /* @__PURE__ */ new Set(["http:", "https:", "mailto:"]);
198
+ var IMAGE_PREFIX = "https://assets.st-note.com/";
199
+ var IMAGE_HOST = "assets.st-note.com";
200
+ var SAFE_VALUE = /^[A-Za-z0-9\-_.:/]+$/;
201
+ var DIGITS = /^\d+$/;
202
+ var AMAZON_HOSTS = /* @__PURE__ */ new Set(["amazon.co.jp", "www.amazon.co.jp", "amazon.com", "www.amazon.com"]);
203
+ var AFFILIATE_HOSTS = /* @__PURE__ */ new Set([
204
+ "amzn.to",
205
+ "amzn.asia",
206
+ "hb.afl.rakuten.co.jp",
207
+ "af.moshimo.com",
208
+ "px.a8.net",
209
+ "ck.jp.ap.valuecommerce.com"
210
+ ]);
211
+ function parseAbsoluteUrl(raw) {
212
+ const value = raw.replace(/[\t\n\r]/g, "").replace(/^[\u0000- ]+|[\u0000- ]+$/g, "");
213
+ if (!URL.canParse(value)) return void 0;
214
+ return { value, url: new URL(value) };
215
+ }
216
+ function isAffiliate(url) {
217
+ const host = url.hostname.toLowerCase();
218
+ if (AFFILIATE_HOSTS.has(host)) return true;
219
+ return AMAZON_HOSTS.has(host) && url.searchParams.has("tag");
220
+ }
221
+ function transformLink(attribs) {
222
+ const out = {};
223
+ const parsed = attribs.href === void 0 ? void 0 : parseAbsoluteUrl(attribs.href);
224
+ const href = parsed && LINK_SCHEMES.has(parsed.url.protocol) ? parsed : void 0;
225
+ if (href) out.href = href.value;
226
+ const blank = attribs.target?.trim().toLowerCase() === "_blank";
227
+ if (blank) out.target = "_blank";
228
+ const rel = [];
229
+ if (blank) rel.push("nofollow", "noopener", "noreferrer");
230
+ if (href && isAffiliate(href.url)) rel.push("sponsored");
231
+ if (rel.length > 0) out.rel = rel.join(" ");
232
+ return out;
233
+ }
234
+ function transformImage(attribs) {
235
+ const parsed = attribs.src === void 0 ? void 0 : parseAbsoluteUrl(attribs.src);
236
+ if (!parsed || parsed.url.protocol !== "https:" || parsed.url.host !== IMAGE_HOST || parsed.url.username !== "" || parsed.url.password !== "" || !parsed.value.toLowerCase().startsWith(IMAGE_PREFIX)) {
237
+ return void 0;
238
+ }
239
+ const out = { src: parsed.value };
240
+ if (attribs.alt !== void 0) out.alt = attribs.alt;
241
+ if (attribs.width !== void 0 && DIGITS.test(attribs.width)) out.width = attribs.width;
242
+ if (attribs.height !== void 0 && DIGITS.test(attribs.height)) out.height = attribs.height;
243
+ out.loading = "lazy";
244
+ out.decoding = "async";
245
+ return out;
246
+ }
247
+ function transformEmbed(attribs, out) {
248
+ const service = attribs["embedded-service"];
249
+ if (service !== void 0 && SAFE_VALUE.test(service)) out["data-nbk-embed-service"] = service;
250
+ const key = attribs["embedded-content-key"];
251
+ if (key !== void 0 && SAFE_VALUE.test(key)) out["data-nbk-embed-key"] = key;
252
+ const parsed = attribs["data-src"] === void 0 ? void 0 : parseAbsoluteUrl(attribs["data-src"]);
253
+ if (parsed && parsed.url.protocol === "https:") out["data-nbk-embed-url"] = parsed.value;
254
+ }
255
+ function transform(tagName, attribs) {
256
+ if (tagName === "table-of-contents") return { tagName: "div", attribs: { "data-nbk-toc": "" } };
257
+ if (tagName === "div") return { tagName, attribs: {} };
258
+ let out = {};
259
+ if (tagName === "a") {
260
+ out = transformLink(attribs);
261
+ } else if (tagName === "img") {
262
+ const image = transformImage(attribs);
263
+ if (!image) return { tagName, attribs: {} };
264
+ out = image;
265
+ } else if (tagName === "th" || tagName === "td") {
266
+ for (const name of ["colspan", "rowspan"]) {
267
+ const value = attribs[name];
268
+ if (value !== void 0 && DIGITS.test(value)) out[name] = value;
269
+ }
270
+ } else if (tagName === "figure") {
271
+ transformEmbed(attribs, out);
272
+ }
273
+ if (attribs.id !== void 0 && SAFE_VALUE.test(attribs.id)) out.id = `nbk-${attribs.id}`;
274
+ return { tagName, attribs: out };
275
+ }
276
+ function sanitizeNoteBody(html) {
277
+ let tocDepth = 0;
278
+ return sanitizeHtml(html, {
279
+ allowedTags: ALLOWED_TAGS,
280
+ allowedAttributes: ALLOWED_ATTRIBUTES,
281
+ allowedSchemes: ["http", "https", "mailto"],
282
+ allowedSchemesByTag: { img: ["https"] },
283
+ allowProtocolRelative: false,
284
+ disallowedTagsMode: "discard",
285
+ nonTextTags: DISCARD_WITH_CONTENT,
286
+ selfClosing: ["img", "br", "hr"],
287
+ enforceHtmlBoundary: false,
288
+ // 属性値の実体参照を解いた値で URL を判定し、出力時にエスケープする前提(既定値だが明示する)
289
+ parser: { decodeEntities: true },
290
+ onOpenTag: (name) => {
291
+ if (tocDepth > 0 || name === "table-of-contents") tocDepth++;
292
+ },
293
+ onCloseTag: () => {
294
+ if (tocDepth > 0) tocDepth--;
295
+ },
296
+ transformTags: { "*": transform },
297
+ exclusiveFilter: (frame) => {
298
+ if (tocDepth > 0) return true;
299
+ if (frame.tag === "div") return "excludeTag";
300
+ if (frame.tag === "img" && frame.attribs.src === void 0) return true;
301
+ return false;
302
+ },
303
+ textFilter: (text) => tocDepth > 0 ? "" : text
304
+ });
305
+ }
306
+ function hasControlOrSpace(value) {
307
+ for (let i = 0; i < value.length; i += 1) {
308
+ const code = value.charCodeAt(i);
309
+ if (code <= 32 || code === 127) return true;
310
+ }
311
+ return /\s/.test(value);
312
+ }
313
+ function isHttpsUrl(value) {
314
+ if (!value.startsWith("https://") || hasControlOrSpace(value)) return false;
315
+ try {
316
+ return new URL(value).protocol === "https:";
317
+ } catch {
318
+ return false;
319
+ }
320
+ }
321
+ var httpsUrl = z.string().refine(isHttpsUrl, "https \u306E URL \u3067\u306F\u3042\u308A\u307E\u305B\u3093");
322
+ var optionalHttpsUrl = z.string().refine((value) => value.trim() === "" || isHttpsUrl(value), "https \u306E URL \u3067\u306F\u3042\u308A\u307E\u305B\u3093");
323
+ function emptyToNull(value) {
324
+ return value.trim() === "" ? null : value;
325
+ }
326
+
327
+ // src/server/normalize/note.ts
328
+ var EXCERPT_LENGTH = 240;
329
+ var noteSchema = z.object({
330
+ key: z.string().regex(NOTE_KEY_RE),
331
+ name: z.string(),
332
+ body: z.string(),
333
+ note_url: httpsUrl,
334
+ publish_at: z.string().refine((value) => !Number.isNaN(Date.parse(value)), "\u65E5\u6642\u3068\u3057\u3066\u89E3\u91C8\u3067\u304D\u307E\u305B\u3093"),
335
+ // 見出し画像のない記事の例は fixture にないため、null も「画像なし」として受け付ける
336
+ eyecatch: optionalHttpsUrl.nullable(),
337
+ eyecatch_alt: z.string().nullable(),
338
+ eyecatch_width: z.number().nullable(),
339
+ eyecatch_height: z.number().nullable(),
340
+ hashtag_notes: z.array(z.object({ hashtag: z.object({ name: z.string() }) })),
341
+ like_count: z.number(),
342
+ price: z.number(),
343
+ can_read: z.boolean(),
344
+ // 目次と埋め込みは、1件の形が違うだけで記事全体を失敗させないよう、項目ごとに検証して除く
345
+ index: z.array(z.unknown()),
346
+ embedded_contents: z.array(z.unknown()),
347
+ user: z.object({
348
+ nickname: z.string(),
349
+ // 著者の確認やリンクの組み立てに使われるため、note のユーザー名の形式に限る
350
+ urlname: z.string().regex(NOTE_USER_RE),
351
+ user_profile_image_path: optionalHttpsUrl
352
+ })
353
+ });
354
+ var responseSchema = z.object({ data: noteSchema });
355
+ var tocItemSchema = z.object({
356
+ body: z.string(),
357
+ name: z.string().regex(SAFE_VALUE),
358
+ level: z.enum(["h2", "h3"])
359
+ });
360
+ var embedSchema = z.object({
361
+ key: z.string().regex(SAFE_VALUE),
362
+ service: z.string().regex(SAFE_VALUE),
363
+ url: z.string().refine(isHttpsUrl)
364
+ });
365
+ function toToc(index) {
366
+ return index.flatMap((item) => {
367
+ const result = tocItemSchema.safeParse(item);
368
+ if (!result.success) return [];
369
+ const { body, name, level } = result.data;
370
+ return [{ id: `nbk-${name}`, text: body, level: level === "h2" ? 2 : 3 }];
371
+ });
372
+ }
373
+ function toEmbeds(contents) {
374
+ return contents.flatMap((item) => {
375
+ const result = embedSchema.safeParse(item);
376
+ return result.success ? [{ key: result.data.key, service: result.data.service, url: result.data.url }] : [];
377
+ });
378
+ }
379
+ function toEyecatch(note) {
380
+ const url = note.eyecatch === null ? null : emptyToNull(note.eyecatch);
381
+ if (url === null) return null;
382
+ return { url, width: note.eyecatch_width, height: note.eyecatch_height, alt: note.eyecatch_alt ?? "" };
383
+ }
384
+ var BLOCK_END = /<br \/>|<\/(?:p|h2|h3|h4|li|blockquote|figcaption|pre|td|th|tr)>/g;
385
+ function toExcerpt(bodyHtml) {
386
+ const text = bodyHtml.replace(BLOCK_END, " ").replace(/<[^>]*>/g, "").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&amp;/g, "&").replace(/\s+/g, " ").trim();
387
+ return Array.from(text).slice(0, EXCERPT_LENGTH).join("");
388
+ }
389
+ function normalizeNote(json) {
390
+ const result = responseSchema.safeParse(json);
391
+ if (!result.success) {
392
+ throw new NoteSchemaError("Unexpected shape of the note article response", {
393
+ issues: result.error.issues.map((issue) => ({ path: issue.path.map(String).join("."), message: issue.message }))
394
+ });
395
+ }
396
+ const note = result.data.data;
397
+ const bodyHtml = sanitizeNoteBody(note.body);
398
+ const eyecatch = toEyecatch(note);
399
+ return {
400
+ key: note.key,
401
+ title: note.name,
402
+ url: note.note_url,
403
+ publishedAt: new Date(note.publish_at).toISOString(),
404
+ excerpt: toExcerpt(bodyHtml),
405
+ eyecatchUrl: eyecatch?.url ?? null,
406
+ hashtags: note.hashtag_notes.map(({ hashtag }) => hashtag.name.replace(/^#/, "")),
407
+ likeCount: note.like_count,
408
+ price: note.price,
409
+ author: {
410
+ name: note.user.nickname,
411
+ urlname: note.user.urlname,
412
+ imageUrl: emptyToNull(note.user.user_profile_image_path)
413
+ },
414
+ source: "api",
415
+ bodyHtml,
416
+ isPartial: !note.can_read,
417
+ eyecatch,
418
+ toc: toToc(note.index),
419
+ embeds: toEmbeds(note.embedded_contents)
420
+ };
421
+ }
422
+
423
+ // src/server/request-options.ts
424
+ var DEFAULT_TIMEOUT_MS = 1e4;
425
+ var DEFAULT_MIN_INTERVAL_MS = 1e3;
426
+ var MAX_TIMER_MS = 2 ** 31 - 1;
427
+ function assertMilliseconds(name, value, min) {
428
+ if (typeof value !== "number" || !Number.isFinite(value) || value < min || value > MAX_TIMER_MS) {
429
+ throw new TypeError(`${name} must be a finite number between ${min} and ${MAX_TIMER_MS}: ${String(value)}`);
430
+ }
431
+ }
432
+
433
+ // src/server/throttle.ts
434
+ function sleep(ms, signal) {
435
+ return new Promise((resolve, reject) => {
436
+ if (signal?.aborted) {
437
+ reject(signal.reason);
438
+ return;
439
+ }
440
+ const onAbort = () => {
441
+ clearTimeout(timer);
442
+ reject(signal?.reason);
443
+ };
444
+ const timer = setTimeout(() => {
445
+ signal?.removeEventListener("abort", onAbort);
446
+ resolve();
447
+ }, ms);
448
+ signal?.addEventListener("abort", onAbort, { once: true });
449
+ });
450
+ }
451
+ function createThrottle() {
452
+ let tail = Promise.resolve();
453
+ let lastSentAt;
454
+ return (minIntervalMs, signal) => {
455
+ const turn = tail.then(async () => {
456
+ if (lastSentAt !== void 0) {
457
+ const wait = lastSentAt + minIntervalMs - Date.now();
458
+ if (wait > 0) await sleep(wait, signal);
459
+ }
460
+ signal?.throwIfAborted();
461
+ lastSentAt = Date.now();
462
+ });
463
+ tail = turn.catch(() => {
464
+ });
465
+ return turn;
466
+ };
467
+ }
468
+ var GLOBAL_KEY = /* @__PURE__ */ Symbol.for("note-blog-kit.throttle");
469
+ function getDefaultThrottle() {
470
+ const store = globalThis;
471
+ store[GLOBAL_KEY] ??= createThrottle();
472
+ return store[GLOBAL_KEY];
473
+ }
474
+
475
+ // src/server/get-article.ts
476
+ async function getArticle(options) {
477
+ const { key, timeoutMs = DEFAULT_TIMEOUT_MS, minIntervalMs = DEFAULT_MIN_INTERVAL_MS, signal } = options;
478
+ if (typeof key !== "string" || !NOTE_KEY_RE.test(key)) {
479
+ throw new TypeError(`Invalid note article key: ${typeof key === "string" ? JSON.stringify(key) : typeof key}`);
480
+ }
481
+ assertMilliseconds("timeoutMs", timeoutMs, 1);
482
+ assertMilliseconds("minIntervalMs", minIntervalMs, 0);
483
+ const url = `${NOTE_ORIGIN}/api/v3/notes/${key}`;
484
+ await getDefaultThrottle()(minIntervalMs, signal);
485
+ const json = await fetchNoteJson(url, { fetch: options.fetch ?? globalThis.fetch, timeoutMs, signal });
486
+ const article = normalizeNote(json);
487
+ if (article.key !== key) {
488
+ throw new NoteSchemaError("note returned a different article than requested", {
489
+ issues: [{ path: "data.key", message: `Expected ${key}` }]
490
+ });
491
+ }
492
+ return article;
493
+ }
494
+ var contentSchema = z.object({
495
+ // リンク・キャッシュキーに使われるため、記事キーの形式に限る
496
+ key: z.string().regex(NOTE_KEY_RE),
497
+ name: z.string(),
498
+ noteUrl: httpsUrl,
499
+ publishAt: z.string().refine((value) => !Number.isNaN(Date.parse(value)), "\u65E5\u6642\u3068\u3057\u3066\u89E3\u91C8\u3067\u304D\u307E\u305B\u3093"),
500
+ body: z.string(),
501
+ // 見出し画像のない記事は null になる(実データで確認。fixture には例がない)
502
+ eyecatch: optionalHttpsUrl.nullable(),
503
+ hashtags: z.array(z.object({ hashtag: z.object({ name: z.string() }) })),
504
+ likeCount: z.number(),
505
+ price: z.number(),
506
+ user: z.object({
507
+ nickname: z.string(),
508
+ // 著者の確認やリンクの組み立てに使われるため、note のユーザー名の形式に限る
509
+ urlname: z.string().regex(NOTE_USER_RE),
510
+ userProfileImagePath: optionalHttpsUrl
511
+ })
512
+ });
513
+ var contentsResponseSchema = z.object({
514
+ data: z.object({
515
+ contents: z.array(contentSchema),
516
+ isLastPage: z.boolean(),
517
+ totalCount: z.number()
518
+ })
519
+ });
520
+ function toSummary(content) {
521
+ return {
522
+ key: content.key,
523
+ title: content.name,
524
+ url: content.noteUrl,
525
+ publishedAt: new Date(content.publishAt).toISOString(),
526
+ excerpt: content.body.trim(),
527
+ eyecatchUrl: content.eyecatch === null ? null : emptyToNull(content.eyecatch),
528
+ hashtags: content.hashtags.map(({ hashtag }) => hashtag.name.replace(/^#/, "")),
529
+ likeCount: content.likeCount,
530
+ price: content.price,
531
+ author: {
532
+ name: content.user.nickname,
533
+ urlname: content.user.urlname,
534
+ imageUrl: emptyToNull(content.user.userProfileImagePath)
535
+ },
536
+ source: "api"
537
+ };
538
+ }
539
+ function normalizeContentsPage(json, page) {
540
+ const result = contentsResponseSchema.safeParse(json);
541
+ if (!result.success) {
542
+ throw new NoteSchemaError("Unexpected shape of the note article list response", {
543
+ issues: result.error.issues.map((issue) => ({ path: issue.path.map(String).join("."), message: issue.message }))
544
+ });
545
+ }
546
+ const { data } = result.data;
547
+ return {
548
+ articles: data.contents.map(toSummary),
549
+ page,
550
+ totalCount: data.totalCount,
551
+ isLastPage: data.isLastPage
552
+ };
553
+ }
554
+
555
+ // src/server/list-articles.ts
556
+ async function listArticles(options) {
557
+ const { user, page = 1, timeoutMs = DEFAULT_TIMEOUT_MS, minIntervalMs = DEFAULT_MIN_INTERVAL_MS, signal } = options;
558
+ if (typeof user !== "string" || !NOTE_USER_RE.test(user)) {
559
+ throw new TypeError(`Invalid note user name: ${typeof user === "string" ? JSON.stringify(user) : typeof user}`);
560
+ }
561
+ if (typeof page !== "number" || !Number.isInteger(page) || page < 1) {
562
+ throw new TypeError(`page must be a positive integer: ${typeof page === "number" ? page : typeof page}`);
563
+ }
564
+ assertMilliseconds("timeoutMs", timeoutMs, 1);
565
+ assertMilliseconds("minIntervalMs", minIntervalMs, 0);
566
+ const url = `${NOTE_ORIGIN}/api/v2/creators/${encodeURIComponent(user)}/contents?kind=note&page=${page}`;
567
+ await getDefaultThrottle()(minIntervalMs, signal);
568
+ const json = await fetchNoteJson(url, { fetch: options.fetch ?? globalThis.fetch, timeoutMs, signal });
569
+ return normalizeContentsPage(json, page);
570
+ }
571
+
572
+ // src/server/iterate-articles.ts
573
+ var DEFAULT_MAX_PAGES = 20;
574
+ async function* iterateArticles(options) {
575
+ const { maxPages = DEFAULT_MAX_PAGES, ...listOptions } = options;
576
+ if (typeof maxPages !== "number" || !Number.isInteger(maxPages) || maxPages < 1) {
577
+ throw new TypeError(
578
+ `maxPages must be a positive integer: ${typeof maxPages === "number" ? maxPages : typeof maxPages}`
579
+ );
580
+ }
581
+ const seen = /* @__PURE__ */ new Set();
582
+ let totalCount = null;
583
+ let pages = 0;
584
+ for (let page = 1; page <= maxPages; page += 1) {
585
+ const result = await listArticles({ ...listOptions, page });
586
+ pages = page;
587
+ totalCount = result.totalCount;
588
+ for (const article of result.articles) {
589
+ if (seen.has(article.key)) continue;
590
+ seen.add(article.key);
591
+ yield article;
592
+ }
593
+ if (result.isLastPage || result.articles.length === 0) {
594
+ return { truncated: false, totalCount, pages };
595
+ }
596
+ }
597
+ return { truncated: true, totalCount, pages };
598
+ }
599
+ async function listAllArticles(options) {
600
+ const articles = [];
601
+ const iterator = iterateArticles(options);
602
+ let step = await iterator.next();
603
+ while (!step.done) {
604
+ articles.push(step.value);
605
+ step = await iterator.next();
606
+ }
607
+ return { articles, ...step.value };
608
+ }
609
+
610
+ export { NoteError, NoteHttpError, NoteNetworkError, NoteNotFoundError, NoteSchemaError, NoteTimeoutError, getArticle, isNoteError, iterateArticles, listAllArticles, listArticles };