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,6 +1,11 @@
1
1
  'use strict';
2
2
 
3
3
  var zod = require('zod');
4
+ var sanitizeHtml = require('sanitize-html');
5
+
6
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
7
+
8
+ var sanitizeHtml__default = /*#__PURE__*/_interopDefault(sanitizeHtml);
4
9
 
5
10
  // src/server/errors.ts
6
11
  var NOTE_ERROR_CODES = /* @__PURE__ */ new Set([
@@ -128,6 +133,182 @@ async function fetchNoteJson(url, options) {
128
133
  });
129
134
  }
130
135
  }
136
+
137
+ // src/server/patterns.ts
138
+ var NOTE_KEY_RE = /^n[0-9a-z]{1,32}$/;
139
+ var NOTE_USER_RE = /^[A-Za-z0-9_-]{1,64}$/;
140
+ var ALLOWED_TAGS = [
141
+ "p",
142
+ "br",
143
+ "h2",
144
+ "h3",
145
+ "h4",
146
+ "strong",
147
+ "em",
148
+ "s",
149
+ "a",
150
+ "ul",
151
+ "ol",
152
+ "li",
153
+ "blockquote",
154
+ "figure",
155
+ "figcaption",
156
+ "img",
157
+ "pre",
158
+ "code",
159
+ "hr",
160
+ "table",
161
+ "thead",
162
+ "tbody",
163
+ "tr",
164
+ "th",
165
+ "td",
166
+ "div"
167
+ ];
168
+ var DISCARD_WITH_CONTENT = [
169
+ "script",
170
+ "style",
171
+ "iframe",
172
+ "frame",
173
+ "frameset",
174
+ "object",
175
+ "embed",
176
+ "applet",
177
+ "form",
178
+ "input",
179
+ "button",
180
+ "textarea",
181
+ "select",
182
+ "option",
183
+ "svg",
184
+ "math",
185
+ "template",
186
+ "noscript",
187
+ "meta",
188
+ "link",
189
+ "base",
190
+ "title",
191
+ "xmp",
192
+ "plaintext"
193
+ ];
194
+ var ALLOWED_ATTRIBUTES = {
195
+ "*": ["id"],
196
+ a: ["href", "target", "rel"],
197
+ img: ["src", "alt", "width", "height", "loading", "decoding"],
198
+ th: ["colspan", "rowspan"],
199
+ td: ["colspan", "rowspan"],
200
+ figure: ["data-nbk-embed-service", "data-nbk-embed-key", "data-nbk-embed-url"],
201
+ div: ["data-nbk-toc"]
202
+ };
203
+ var LINK_SCHEMES = /* @__PURE__ */ new Set(["http:", "https:", "mailto:"]);
204
+ var IMAGE_PREFIX = "https://assets.st-note.com/";
205
+ var IMAGE_HOST = "assets.st-note.com";
206
+ var SAFE_VALUE = /^[A-Za-z0-9\-_.:/]+$/;
207
+ var DIGITS = /^\d+$/;
208
+ var AMAZON_HOSTS = /* @__PURE__ */ new Set(["amazon.co.jp", "www.amazon.co.jp", "amazon.com", "www.amazon.com"]);
209
+ var AFFILIATE_HOSTS = /* @__PURE__ */ new Set([
210
+ "amzn.to",
211
+ "amzn.asia",
212
+ "hb.afl.rakuten.co.jp",
213
+ "af.moshimo.com",
214
+ "px.a8.net",
215
+ "ck.jp.ap.valuecommerce.com"
216
+ ]);
217
+ function parseAbsoluteUrl(raw) {
218
+ const value = raw.replace(/[\t\n\r]/g, "").replace(/^[\u0000- ]+|[\u0000- ]+$/g, "");
219
+ if (!URL.canParse(value)) return void 0;
220
+ return { value, url: new URL(value) };
221
+ }
222
+ function isAffiliate(url) {
223
+ const host = url.hostname.toLowerCase();
224
+ if (AFFILIATE_HOSTS.has(host)) return true;
225
+ return AMAZON_HOSTS.has(host) && url.searchParams.has("tag");
226
+ }
227
+ function transformLink(attribs) {
228
+ const out = {};
229
+ const parsed = attribs.href === void 0 ? void 0 : parseAbsoluteUrl(attribs.href);
230
+ const href = parsed && LINK_SCHEMES.has(parsed.url.protocol) ? parsed : void 0;
231
+ if (href) out.href = href.value;
232
+ const blank = attribs.target?.trim().toLowerCase() === "_blank";
233
+ if (blank) out.target = "_blank";
234
+ const rel = [];
235
+ if (blank) rel.push("nofollow", "noopener", "noreferrer");
236
+ if (href && isAffiliate(href.url)) rel.push("sponsored");
237
+ if (rel.length > 0) out.rel = rel.join(" ");
238
+ return out;
239
+ }
240
+ function transformImage(attribs) {
241
+ const parsed = attribs.src === void 0 ? void 0 : parseAbsoluteUrl(attribs.src);
242
+ if (!parsed || parsed.url.protocol !== "https:" || parsed.url.host !== IMAGE_HOST || parsed.url.username !== "" || parsed.url.password !== "" || !parsed.value.toLowerCase().startsWith(IMAGE_PREFIX)) {
243
+ return void 0;
244
+ }
245
+ const out = { src: parsed.value };
246
+ if (attribs.alt !== void 0) out.alt = attribs.alt;
247
+ if (attribs.width !== void 0 && DIGITS.test(attribs.width)) out.width = attribs.width;
248
+ if (attribs.height !== void 0 && DIGITS.test(attribs.height)) out.height = attribs.height;
249
+ out.loading = "lazy";
250
+ out.decoding = "async";
251
+ return out;
252
+ }
253
+ function transformEmbed(attribs, out) {
254
+ const service = attribs["embedded-service"];
255
+ if (service !== void 0 && SAFE_VALUE.test(service)) out["data-nbk-embed-service"] = service;
256
+ const key = attribs["embedded-content-key"];
257
+ if (key !== void 0 && SAFE_VALUE.test(key)) out["data-nbk-embed-key"] = key;
258
+ const parsed = attribs["data-src"] === void 0 ? void 0 : parseAbsoluteUrl(attribs["data-src"]);
259
+ if (parsed && parsed.url.protocol === "https:") out["data-nbk-embed-url"] = parsed.value;
260
+ }
261
+ function transform(tagName, attribs) {
262
+ if (tagName === "table-of-contents") return { tagName: "div", attribs: { "data-nbk-toc": "" } };
263
+ if (tagName === "div") return { tagName, attribs: {} };
264
+ let out = {};
265
+ if (tagName === "a") {
266
+ out = transformLink(attribs);
267
+ } else if (tagName === "img") {
268
+ const image = transformImage(attribs);
269
+ if (!image) return { tagName, attribs: {} };
270
+ out = image;
271
+ } else if (tagName === "th" || tagName === "td") {
272
+ for (const name of ["colspan", "rowspan"]) {
273
+ const value = attribs[name];
274
+ if (value !== void 0 && DIGITS.test(value)) out[name] = value;
275
+ }
276
+ } else if (tagName === "figure") {
277
+ transformEmbed(attribs, out);
278
+ }
279
+ if (attribs.id !== void 0 && SAFE_VALUE.test(attribs.id)) out.id = `nbk-${attribs.id}`;
280
+ return { tagName, attribs: out };
281
+ }
282
+ function sanitizeNoteBody(html) {
283
+ let tocDepth = 0;
284
+ return sanitizeHtml__default.default(html, {
285
+ allowedTags: ALLOWED_TAGS,
286
+ allowedAttributes: ALLOWED_ATTRIBUTES,
287
+ allowedSchemes: ["http", "https", "mailto"],
288
+ allowedSchemesByTag: { img: ["https"] },
289
+ allowProtocolRelative: false,
290
+ disallowedTagsMode: "discard",
291
+ nonTextTags: DISCARD_WITH_CONTENT,
292
+ selfClosing: ["img", "br", "hr"],
293
+ enforceHtmlBoundary: false,
294
+ // 属性値の実体参照を解いた値で URL を判定し、出力時にエスケープする前提(既定値だが明示する)
295
+ parser: { decodeEntities: true },
296
+ onOpenTag: (name) => {
297
+ if (tocDepth > 0 || name === "table-of-contents") tocDepth++;
298
+ },
299
+ onCloseTag: () => {
300
+ if (tocDepth > 0) tocDepth--;
301
+ },
302
+ transformTags: { "*": transform },
303
+ exclusiveFilter: (frame) => {
304
+ if (tocDepth > 0) return true;
305
+ if (frame.tag === "div") return "excludeTag";
306
+ if (frame.tag === "img" && frame.attribs.src === void 0) return true;
307
+ return false;
308
+ },
309
+ textFilter: (text) => tocDepth > 0 ? "" : text
310
+ });
311
+ }
131
312
  function hasControlOrSpace(value) {
132
313
  for (let i = 0; i < value.length; i += 1) {
133
314
  const code = value.charCodeAt(i);
@@ -145,67 +326,116 @@ function isHttpsUrl(value) {
145
326
  }
146
327
  var httpsUrl = zod.z.string().refine(isHttpsUrl, "https \u306E URL \u3067\u306F\u3042\u308A\u307E\u305B\u3093");
147
328
  var optionalHttpsUrl = zod.z.string().refine((value) => value.trim() === "" || isHttpsUrl(value), "https \u306E URL \u3067\u306F\u3042\u308A\u307E\u305B\u3093");
148
- var contentSchema = zod.z.object({
149
- key: zod.z.string().min(1),
329
+ function emptyToNull(value) {
330
+ return value.trim() === "" ? null : value;
331
+ }
332
+
333
+ // src/server/normalize/note.ts
334
+ var EXCERPT_LENGTH = 240;
335
+ var noteSchema = zod.z.object({
336
+ key: zod.z.string().regex(NOTE_KEY_RE),
150
337
  name: zod.z.string(),
151
- noteUrl: httpsUrl,
152
- publishAt: zod.z.string().refine((value) => !Number.isNaN(Date.parse(value)), "\u65E5\u6642\u3068\u3057\u3066\u89E3\u91C8\u3067\u304D\u307E\u305B\u3093"),
153
338
  body: zod.z.string(),
154
- eyecatch: optionalHttpsUrl,
155
- hashtags: zod.z.array(zod.z.object({ hashtag: zod.z.object({ name: zod.z.string() }) })),
156
- likeCount: zod.z.number(),
339
+ note_url: httpsUrl,
340
+ publish_at: zod.z.string().refine((value) => !Number.isNaN(Date.parse(value)), "\u65E5\u6642\u3068\u3057\u3066\u89E3\u91C8\u3067\u304D\u307E\u305B\u3093"),
341
+ // 見出し画像のない記事の例は fixture にないため、null も「画像なし」として受け付ける
342
+ eyecatch: optionalHttpsUrl.nullable(),
343
+ eyecatch_alt: zod.z.string().nullable(),
344
+ eyecatch_width: zod.z.number().nullable(),
345
+ eyecatch_height: zod.z.number().nullable(),
346
+ hashtag_notes: zod.z.array(zod.z.object({ hashtag: zod.z.object({ name: zod.z.string() }) })),
347
+ like_count: zod.z.number(),
157
348
  price: zod.z.number(),
349
+ can_read: zod.z.boolean(),
350
+ // 目次と埋め込みは、1件の形が違うだけで記事全体を失敗させないよう、項目ごとに検証して除く
351
+ index: zod.z.array(zod.z.unknown()),
352
+ embedded_contents: zod.z.array(zod.z.unknown()),
158
353
  user: zod.z.object({
159
354
  nickname: zod.z.string(),
160
- urlname: zod.z.string(),
161
- userProfileImagePath: optionalHttpsUrl
355
+ // 著者の確認やリンクの組み立てに使われるため、note のユーザー名の形式に限る
356
+ urlname: zod.z.string().regex(NOTE_USER_RE),
357
+ user_profile_image_path: optionalHttpsUrl
162
358
  })
163
359
  });
164
- var contentsResponseSchema = zod.z.object({
165
- data: zod.z.object({
166
- contents: zod.z.array(contentSchema),
167
- isLastPage: zod.z.boolean(),
168
- totalCount: zod.z.number()
169
- })
360
+ var responseSchema = zod.z.object({ data: noteSchema });
361
+ var tocItemSchema = zod.z.object({
362
+ body: zod.z.string(),
363
+ name: zod.z.string().regex(SAFE_VALUE),
364
+ level: zod.z.enum(["h2", "h3"])
170
365
  });
171
- function emptyToNull(value) {
172
- return value.trim() === "" ? null : value;
366
+ var embedSchema = zod.z.object({
367
+ key: zod.z.string().regex(SAFE_VALUE),
368
+ service: zod.z.string().regex(SAFE_VALUE),
369
+ url: zod.z.string().refine(isHttpsUrl)
370
+ });
371
+ function toToc(index) {
372
+ return index.flatMap((item) => {
373
+ const result = tocItemSchema.safeParse(item);
374
+ if (!result.success) return [];
375
+ const { body, name, level } = result.data;
376
+ return [{ id: `nbk-${name}`, text: body, level: level === "h2" ? 2 : 3 }];
377
+ });
173
378
  }
174
- function toSummary(content) {
175
- return {
176
- key: content.key,
177
- title: content.name,
178
- url: content.noteUrl,
179
- publishedAt: new Date(content.publishAt).toISOString(),
180
- excerpt: content.body.trim(),
181
- eyecatchUrl: emptyToNull(content.eyecatch),
182
- hashtags: content.hashtags.map(({ hashtag }) => hashtag.name.replace(/^#/, "")),
183
- likeCount: content.likeCount,
184
- price: content.price,
185
- author: {
186
- name: content.user.nickname,
187
- urlname: content.user.urlname,
188
- imageUrl: emptyToNull(content.user.userProfileImagePath)
189
- },
190
- source: "api"
191
- };
379
+ function toEmbeds(contents) {
380
+ return contents.flatMap((item) => {
381
+ const result = embedSchema.safeParse(item);
382
+ return result.success ? [{ key: result.data.key, service: result.data.service, url: result.data.url }] : [];
383
+ });
192
384
  }
193
- function normalizeContentsPage(json, page) {
194
- const result = contentsResponseSchema.safeParse(json);
385
+ function toEyecatch(note) {
386
+ const url = note.eyecatch === null ? null : emptyToNull(note.eyecatch);
387
+ if (url === null) return null;
388
+ return { url, width: note.eyecatch_width, height: note.eyecatch_height, alt: note.eyecatch_alt ?? "" };
389
+ }
390
+ var BLOCK_END = /<br \/>|<\/(?:p|h2|h3|h4|li|blockquote|figcaption|pre|td|th|tr)>/g;
391
+ function toExcerpt(bodyHtml) {
392
+ 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();
393
+ return Array.from(text).slice(0, EXCERPT_LENGTH).join("");
394
+ }
395
+ function normalizeNote(json) {
396
+ const result = responseSchema.safeParse(json);
195
397
  if (!result.success) {
196
- throw new NoteSchemaError("Unexpected shape of the note article list response", {
398
+ throw new NoteSchemaError("Unexpected shape of the note article response", {
197
399
  issues: result.error.issues.map((issue) => ({ path: issue.path.map(String).join("."), message: issue.message }))
198
400
  });
199
401
  }
200
- const { data } = result.data;
402
+ const note = result.data.data;
403
+ const bodyHtml = sanitizeNoteBody(note.body);
404
+ const eyecatch = toEyecatch(note);
201
405
  return {
202
- articles: data.contents.map(toSummary),
203
- page,
204
- totalCount: data.totalCount,
205
- isLastPage: data.isLastPage
406
+ key: note.key,
407
+ title: note.name,
408
+ url: note.note_url,
409
+ publishedAt: new Date(note.publish_at).toISOString(),
410
+ excerpt: toExcerpt(bodyHtml),
411
+ eyecatchUrl: eyecatch?.url ?? null,
412
+ hashtags: note.hashtag_notes.map(({ hashtag }) => hashtag.name.replace(/^#/, "")),
413
+ likeCount: note.like_count,
414
+ price: note.price,
415
+ author: {
416
+ name: note.user.nickname,
417
+ urlname: note.user.urlname,
418
+ imageUrl: emptyToNull(note.user.user_profile_image_path)
419
+ },
420
+ source: "api",
421
+ bodyHtml,
422
+ isPartial: !note.can_read,
423
+ eyecatch,
424
+ toc: toToc(note.index),
425
+ embeds: toEmbeds(note.embedded_contents)
206
426
  };
207
427
  }
208
428
 
429
+ // src/server/request-options.ts
430
+ var DEFAULT_TIMEOUT_MS = 1e4;
431
+ var DEFAULT_MIN_INTERVAL_MS = 1e3;
432
+ var MAX_TIMER_MS = 2 ** 31 - 1;
433
+ function assertMilliseconds(name, value, min) {
434
+ if (typeof value !== "number" || !Number.isFinite(value) || value < min || value > MAX_TIMER_MS) {
435
+ throw new TypeError(`${name} must be a finite number between ${min} and ${MAX_TIMER_MS}: ${String(value)}`);
436
+ }
437
+ }
438
+
209
439
  // src/server/throttle.ts
210
440
  function sleep(ms, signal) {
211
441
  return new Promise((resolve, reject) => {
@@ -248,19 +478,90 @@ function getDefaultThrottle() {
248
478
  return store[GLOBAL_KEY];
249
479
  }
250
480
 
251
- // src/server/list-articles.ts
252
- var USER_RE = /^[A-Za-z0-9_-]{1,64}$/;
253
- var DEFAULT_TIMEOUT_MS = 1e4;
254
- var DEFAULT_MIN_INTERVAL_MS = 1e3;
255
- var MAX_TIMER_MS = 2 ** 31 - 1;
256
- function assertMilliseconds(name, value, min) {
257
- if (typeof value !== "number" || !Number.isFinite(value) || value < min || value > MAX_TIMER_MS) {
258
- throw new TypeError(`${name} must be a finite number between ${min} and ${MAX_TIMER_MS}: ${String(value)}`);
481
+ // src/server/get-article.ts
482
+ async function getArticle(options) {
483
+ const { key, timeoutMs = DEFAULT_TIMEOUT_MS, minIntervalMs = DEFAULT_MIN_INTERVAL_MS, signal } = options;
484
+ if (typeof key !== "string" || !NOTE_KEY_RE.test(key)) {
485
+ throw new TypeError(`Invalid note article key: ${typeof key === "string" ? JSON.stringify(key) : typeof key}`);
259
486
  }
487
+ assertMilliseconds("timeoutMs", timeoutMs, 1);
488
+ assertMilliseconds("minIntervalMs", minIntervalMs, 0);
489
+ const url = `${NOTE_ORIGIN}/api/v3/notes/${key}`;
490
+ await getDefaultThrottle()(minIntervalMs, signal);
491
+ const json = await fetchNoteJson(url, { fetch: options.fetch ?? globalThis.fetch, timeoutMs, signal });
492
+ const article = normalizeNote(json);
493
+ if (article.key !== key) {
494
+ throw new NoteSchemaError("note returned a different article than requested", {
495
+ issues: [{ path: "data.key", message: `Expected ${key}` }]
496
+ });
497
+ }
498
+ return article;
260
499
  }
500
+ var contentSchema = zod.z.object({
501
+ // リンク・キャッシュキーに使われるため、記事キーの形式に限る
502
+ key: zod.z.string().regex(NOTE_KEY_RE),
503
+ name: zod.z.string(),
504
+ noteUrl: httpsUrl,
505
+ publishAt: zod.z.string().refine((value) => !Number.isNaN(Date.parse(value)), "\u65E5\u6642\u3068\u3057\u3066\u89E3\u91C8\u3067\u304D\u307E\u305B\u3093"),
506
+ body: zod.z.string(),
507
+ // 見出し画像のない記事は null になる(実データで確認。fixture には例がない)
508
+ eyecatch: optionalHttpsUrl.nullable(),
509
+ hashtags: zod.z.array(zod.z.object({ hashtag: zod.z.object({ name: zod.z.string() }) })),
510
+ likeCount: zod.z.number(),
511
+ price: zod.z.number(),
512
+ user: zod.z.object({
513
+ nickname: zod.z.string(),
514
+ // 著者の確認やリンクの組み立てに使われるため、note のユーザー名の形式に限る
515
+ urlname: zod.z.string().regex(NOTE_USER_RE),
516
+ userProfileImagePath: optionalHttpsUrl
517
+ })
518
+ });
519
+ var contentsResponseSchema = zod.z.object({
520
+ data: zod.z.object({
521
+ contents: zod.z.array(contentSchema),
522
+ isLastPage: zod.z.boolean(),
523
+ totalCount: zod.z.number()
524
+ })
525
+ });
526
+ function toSummary(content) {
527
+ return {
528
+ key: content.key,
529
+ title: content.name,
530
+ url: content.noteUrl,
531
+ publishedAt: new Date(content.publishAt).toISOString(),
532
+ excerpt: content.body.trim(),
533
+ eyecatchUrl: content.eyecatch === null ? null : emptyToNull(content.eyecatch),
534
+ hashtags: content.hashtags.map(({ hashtag }) => hashtag.name.replace(/^#/, "")),
535
+ likeCount: content.likeCount,
536
+ price: content.price,
537
+ author: {
538
+ name: content.user.nickname,
539
+ urlname: content.user.urlname,
540
+ imageUrl: emptyToNull(content.user.userProfileImagePath)
541
+ },
542
+ source: "api"
543
+ };
544
+ }
545
+ function normalizeContentsPage(json, page) {
546
+ const result = contentsResponseSchema.safeParse(json);
547
+ if (!result.success) {
548
+ throw new NoteSchemaError("Unexpected shape of the note article list response", {
549
+ issues: result.error.issues.map((issue) => ({ path: issue.path.map(String).join("."), message: issue.message }))
550
+ });
551
+ }
552
+ const { data } = result.data;
553
+ return {
554
+ articles: data.contents.map(toSummary),
555
+ page,
556
+ totalCount: data.totalCount,
557
+ isLastPage: data.isLastPage
558
+ };
559
+ }
560
+
561
+ // src/server/list-articles.ts
261
562
  async function listArticles(options) {
262
563
  const { user, page = 1, timeoutMs = DEFAULT_TIMEOUT_MS, minIntervalMs = DEFAULT_MIN_INTERVAL_MS, signal } = options;
263
- if (typeof user !== "string" || !USER_RE.test(user)) {
564
+ if (typeof user !== "string" || !NOTE_USER_RE.test(user)) {
264
565
  throw new TypeError(`Invalid note user name: ${typeof user === "string" ? JSON.stringify(user) : typeof user}`);
265
566
  }
266
567
  if (typeof page !== "number" || !Number.isInteger(page) || page < 1) {
@@ -318,6 +619,7 @@ exports.NoteNetworkError = NoteNetworkError;
318
619
  exports.NoteNotFoundError = NoteNotFoundError;
319
620
  exports.NoteSchemaError = NoteSchemaError;
320
621
  exports.NoteTimeoutError = NoteTimeoutError;
622
+ exports.getArticle = getArticle;
321
623
  exports.isNoteError = isNoteError;
322
624
  exports.iterateArticles = iterateArticles;
323
625
  exports.listAllArticles = listAllArticles;
@@ -1,5 +1,7 @@
1
- import { NoteArticlePage, NoteArticleSummary } from '../index.cjs';
2
- export { NoteArticle, NoteAuthor, NoteEmbed, NoteEyecatch, NoteSource, NoteTocItem } from '../index.cjs';
1
+ import { NoteArticle } from '../index.cjs';
2
+ export { NoteArticlePage, NoteArticleSummary, NoteAuthor, NoteEmbed, NoteEyecatch, NoteSource, NoteTocItem } from '../index.cjs';
3
+ import { N as NoteRequestOptions } from '../iterate-articles-BeI9bBh3.cjs';
4
+ export { I as IterateArticlesOptions, a as IterateArticlesResult, b as ListAllArticlesResult, L as ListArticlesOptions, i as iterateArticles, l as listAllArticles, c as listArticles } from '../iterate-articles-BeI9bBh3.cjs';
3
5
 
4
6
  /** エラーの種類を表す安定した識別子 */
5
7
  type NoteErrorCode = 'NOTE_NOT_FOUND' | 'NOTE_HTTP_ERROR' | 'NOTE_NETWORK_ERROR' | 'NOTE_TIMEOUT' | 'NOTE_SCHEMA_ERROR';
@@ -81,80 +83,27 @@ type AnyNoteError = NoteNotFoundError | NoteHttpError | NoteNetworkError | NoteT
81
83
  */
82
84
  declare function isNoteError(value: unknown): value is AnyNoteError;
83
85
 
84
- /** {@link listArticles} のオプション */
85
- interface ListArticlesOptions {
86
- /** note のユーザー名(note.com/{user} の部分)。英数字・_・- のみ */
87
- user: string;
88
- /** ページ番号(1 始まり)。既定は 1。1ページは6件 */
89
- page?: number;
90
- /**
91
- * fetch の差し替え(テストやキャッシュ層のため)。既定は globalThis.fetch。
92
- * 差し替えた fetch でも Cookie・認証ヘッダーを付けないこと(note の公開情報だけを取得する前提)
93
- */
94
- fetch?: typeof globalThis.fetch;
95
- /** 中断用のシグナル。間隔の制限で待っている間も含め、中断したらすぐにその理由をそのまま投げる */
96
- signal?: AbortSignal;
97
- /** タイムアウト(ミリ秒)。1〜2147483647。既定は 10000 */
98
- timeoutMs?: number;
99
- /**
100
- * 連続リクエストの最小間隔(ミリ秒)。0〜2147483647。既定は 1000。
101
- * 送信順はプロセス全体(ESM・CJS の併用やパッケージの重複を含む)で1本の列にまとめられ、
102
- * この呼び出しは「直前の送信から minIntervalMs 経つまで」待ってから送られる。
103
- */
104
- minIntervalMs?: number;
86
+ /** {@link getArticle} のオプション */
87
+ interface GetArticleOptions extends NoteRequestOptions {
88
+ /** 記事キー(例: n55256baa5425。記事 URL の /n/ の後ろ)。n と英小文字・数字のみ */
89
+ key: string;
105
90
  }
106
91
  /**
107
- * 記事一覧の1ページを取得する(サーバー専用。note は CORS に対応していない)。
92
+ * 記事1件を取得する(サーバー専用。note は CORS に対応していない)。
93
+ * 本文(`bodyHtml`)はサニタイズ済み。有料記事は無料部分だけで、`isPartial` が true になる。
94
+ * 有料記事の `toc` は有料部分の見出しも含むため、一部の `id` は `bodyHtml` の中にない。
108
95
  *
109
- * @throws {TypeError} user・page が不正なとき
110
- * @throws {NoteNotFoundError} ユーザーが見つからないとき
96
+ * note の API は記事キーだけで誰の記事でも返す。ページの URL から受け取ったキーをそのまま渡す場合は、
97
+ * 他人の記事を表示しないよう、`article.author.urlname` が自分のユーザー名か確かめること。
98
+ *
99
+ * @throws {TypeError} key やオプションが不正なとき
100
+ * @throws {NoteNotFoundError} 記事が見つからないとき
111
101
  * @throws {NoteHttpError} その他の 2xx でないステータス
112
102
  * @throws {NoteNetworkError} 通信に失敗したとき
113
103
  * @throws {NoteTimeoutError} タイムアウトしたとき
114
104
  * @throws {NoteSchemaError} レスポンスの形が想定と違うとき
115
105
  */
116
- declare function listArticles(options: ListArticlesOptions): Promise<NoteArticlePage>;
117
-
118
- /** {@link iterateArticles}・{@link listAllArticles} のオプション。`listArticles` のオプションから `page` を除いたもの */
119
- interface IterateArticlesOptions extends Omit<ListArticlesOptions, 'page'> {
120
- /** 取得する最大ページ数(1 以上の整数)。既定は 20(1ページ6件なので120件) */
121
- maxPages?: number;
122
- }
123
- /** 全件取得の結果のうち、記事以外の情報 */
124
- interface IterateArticlesResult {
125
- /** maxPages に達して打ち切ったとき true(続きのページがある可能性がある) */
126
- truncated: boolean;
127
- /** 最後に取得したページの totalCount */
128
- totalCount: number | null;
129
- /** 実際に取得したページ数 */
130
- pages: number;
131
- }
132
- /** {@link listAllArticles} の結果 */
133
- interface ListAllArticlesResult extends IterateArticlesResult {
134
- /** 取得した記事(新しい順、key で重複を除いたもの) */
135
- articles: NoteArticleSummary[];
136
- }
137
- /**
138
- * 記事を新しい順に1件ずつ返す(サーバー専用)。最終ページか maxPages に達したら終わる。
139
- * ページの取得には `listArticles` を使うため、取得間隔の制限・タイムアウト・中断もそのまま効く。
140
- * 取得中にページがずれて同じ記事が再び出た場合は、`key` で重複を除く。
141
- *
142
- * 打ち切りの有無などはジェネレーターの戻り値(`IterateArticlesResult`)で返す。
143
- * `for await` ではこの戻り値を受け取れないため、必要なら {@link listAllArticles} を使うか `next()` を手で回す。
144
- *
145
- * @throws {TypeError} maxPages などが不正なとき(呼び出した時点ではなく、最初の `next()` で投げる)
146
- * @throws 途中のページの取得で起きたエラー(それまでに返した記事はそのまま)
147
- */
148
- declare function iterateArticles(options: IterateArticlesOptions): AsyncGenerator<NoteArticleSummary, IterateArticlesResult, undefined>;
149
- /**
150
- * 全件(maxPages まで。既定は 20 ページ)を配列で返す(サーバー専用)。
151
- * `truncated` が true なら maxPages で打ち切っており、続きのページがある可能性がある。
152
- *
153
- * @throws {TypeError} maxPages などが不正なとき
154
- * @throws 途中のページの取得で起きたエラー。それまでに集めた記事は返らない
155
- * (途中までの記事も使いたい場合は {@link iterateArticles} を使う)
156
- */
157
- declare function listAllArticles(options: IterateArticlesOptions): Promise<ListAllArticlesResult>;
106
+ declare function getArticle(options: GetArticleOptions): Promise<NoteArticle>;
158
107
 
159
- export { NoteArticlePage, NoteArticleSummary, NoteError, NoteHttpError, NoteNetworkError, NoteNotFoundError, NoteSchemaError, NoteTimeoutError, isNoteError, iterateArticles, listAllArticles, listArticles };
160
- export type { AnyNoteError, IterateArticlesOptions, IterateArticlesResult, ListAllArticlesResult, ListArticlesOptions, NoteErrorCode, NoteErrorOptions, NoteSchemaIssue };
108
+ export { NoteArticle, NoteError, NoteHttpError, NoteNetworkError, NoteNotFoundError, NoteRequestOptions, NoteSchemaError, NoteTimeoutError, getArticle, isNoteError };
109
+ export type { AnyNoteError, GetArticleOptions, NoteErrorCode, NoteErrorOptions, NoteSchemaIssue };