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.
- package/LICENSE +21 -0
- package/README.md +340 -2
- package/dist/cli/index.js +32 -0
- package/dist/index.cjs +2 -0
- package/dist/index.d.cts +76 -0
- package/dist/index.d.ts +76 -0
- package/dist/index.js +1 -0
- package/dist/iterate-articles-9dzDflSn.d.ts +84 -0
- package/dist/iterate-articles-BeI9bBh3.d.cts +84 -0
- package/dist/next/index.cjs +378 -0
- package/dist/next/index.d.cts +103 -0
- package/dist/next/index.d.ts +103 -0
- package/dist/next/index.js +375 -0
- package/dist/react/index.cjs +409 -0
- package/dist/react/index.d.cts +190 -0
- package/dist/react/index.d.ts +190 -0
- package/dist/react/index.js +404 -0
- package/dist/server/index.cjs +626 -0
- package/dist/server/index.d.cts +109 -0
- package/dist/server/index.d.ts +109 -0
- package/dist/server/index.js +610 -0
- package/dist/styles.css +427 -0
- package/package.json +109 -3
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { NoteArticlePage, NoteArticleSummary } from './index.cjs';
|
|
2
|
+
|
|
3
|
+
/** 取得関数に共通するオプションの型・既定値・検証 */
|
|
4
|
+
/** note から取得する関数(listArticles・getArticle など)に共通するオプション */
|
|
5
|
+
interface NoteRequestOptions {
|
|
6
|
+
/**
|
|
7
|
+
* fetch の差し替え(テストやキャッシュ層のため)。既定は globalThis.fetch。
|
|
8
|
+
* 差し替えた fetch でも Cookie・認証ヘッダーを付けないこと(note の公開情報だけを取得する前提)
|
|
9
|
+
*/
|
|
10
|
+
fetch?: typeof globalThis.fetch;
|
|
11
|
+
/** 中断用のシグナル。間隔の制限で待っている間も含め、中断したらすぐにその理由をそのまま投げる */
|
|
12
|
+
signal?: AbortSignal;
|
|
13
|
+
/** タイムアウト(ミリ秒)。1〜2147483647。既定は 10000 */
|
|
14
|
+
timeoutMs?: number;
|
|
15
|
+
/**
|
|
16
|
+
* 連続リクエストの最小間隔(ミリ秒)。0〜2147483647。既定は 1000。
|
|
17
|
+
* 送信順はプロセス全体(ESM・CJS の併用やパッケージの重複を含む)で1本の列にまとめられ、
|
|
18
|
+
* この呼び出しは「直前の送信から minIntervalMs 経つまで」待ってから送られる。
|
|
19
|
+
*/
|
|
20
|
+
minIntervalMs?: number;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** `listArticles` のオプション(`note-blog-kit/next` からも参照するため @link は使わない) */
|
|
24
|
+
interface ListArticlesOptions extends NoteRequestOptions {
|
|
25
|
+
/** note のユーザー名(note.com/{user} の部分)。英数字・_・- のみ */
|
|
26
|
+
user: string;
|
|
27
|
+
/** ページ番号(1 始まり)。既定は 1。1ページは6件 */
|
|
28
|
+
page?: number;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* 記事一覧の1ページを取得する(サーバー専用。note は CORS に対応していない)。
|
|
32
|
+
*
|
|
33
|
+
* @throws {TypeError} user・page が不正なとき
|
|
34
|
+
* @throws {NoteNotFoundError} ユーザーが見つからないとき
|
|
35
|
+
* @throws {NoteHttpError} その他の 2xx でないステータス
|
|
36
|
+
* @throws {NoteNetworkError} 通信に失敗したとき
|
|
37
|
+
* @throws {NoteTimeoutError} タイムアウトしたとき
|
|
38
|
+
* @throws {NoteSchemaError} レスポンスの形が想定と違うとき
|
|
39
|
+
*/
|
|
40
|
+
declare function listArticles(options: ListArticlesOptions): Promise<NoteArticlePage>;
|
|
41
|
+
|
|
42
|
+
/** `iterateArticles`・`listAllArticles` のオプション(`note-blog-kit/next` からも参照するため @link は使わない)。`listArticles` のオプションから `page` を除いたもの */
|
|
43
|
+
interface IterateArticlesOptions extends Omit<ListArticlesOptions, 'page'> {
|
|
44
|
+
/** 取得する最大ページ数(1 以上の整数)。既定は 20(1ページ6件なので120件) */
|
|
45
|
+
maxPages?: number;
|
|
46
|
+
}
|
|
47
|
+
/** 全件取得の結果のうち、記事以外の情報 */
|
|
48
|
+
interface IterateArticlesResult {
|
|
49
|
+
/** maxPages に達して打ち切ったとき true(続きのページがある可能性がある) */
|
|
50
|
+
truncated: boolean;
|
|
51
|
+
/** 最後に取得したページの totalCount */
|
|
52
|
+
totalCount: number | null;
|
|
53
|
+
/** 実際に取得したページ数 */
|
|
54
|
+
pages: number;
|
|
55
|
+
}
|
|
56
|
+
/** {@link listAllArticles} の結果 */
|
|
57
|
+
interface ListAllArticlesResult extends IterateArticlesResult {
|
|
58
|
+
/** 取得した記事(新しい順、key で重複を除いたもの) */
|
|
59
|
+
articles: NoteArticleSummary[];
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* 記事を新しい順に1件ずつ返す(サーバー専用)。最終ページか maxPages に達したら終わる。
|
|
63
|
+
* ページの取得には `listArticles` を使うため、取得間隔の制限・タイムアウト・中断もそのまま効く。
|
|
64
|
+
* 取得中にページがずれて同じ記事が再び出た場合は、`key` で重複を除く。
|
|
65
|
+
*
|
|
66
|
+
* 打ち切りの有無などはジェネレーターの戻り値(`IterateArticlesResult`)で返す。
|
|
67
|
+
* `for await` ではこの戻り値を受け取れないため、必要なら {@link listAllArticles} を使うか `next()` を手で回す。
|
|
68
|
+
*
|
|
69
|
+
* @throws {TypeError} maxPages などが不正なとき(呼び出した時点ではなく、最初の `next()` で投げる)
|
|
70
|
+
* @throws 途中のページの取得で起きたエラー(それまでに返した記事はそのまま)
|
|
71
|
+
*/
|
|
72
|
+
declare function iterateArticles(options: IterateArticlesOptions): AsyncGenerator<NoteArticleSummary, IterateArticlesResult, undefined>;
|
|
73
|
+
/**
|
|
74
|
+
* 全件(maxPages まで。既定は 20 ページ)を配列で返す(サーバー専用)。
|
|
75
|
+
* `truncated` が true なら maxPages で打ち切っており、続きのページがある可能性がある。
|
|
76
|
+
*
|
|
77
|
+
* @throws {TypeError} maxPages などが不正なとき
|
|
78
|
+
* @throws 途中のページの取得で起きたエラー。それまでに集めた記事は返らない
|
|
79
|
+
* (途中までの記事も使いたい場合は {@link iterateArticles} を使う)
|
|
80
|
+
*/
|
|
81
|
+
declare function listAllArticles(options: IterateArticlesOptions): Promise<ListAllArticlesResult>;
|
|
82
|
+
|
|
83
|
+
export { listArticles as c, iterateArticles as i, listAllArticles as l };
|
|
84
|
+
export type { IterateArticlesOptions as I, ListArticlesOptions as L, NoteRequestOptions as N, IterateArticlesResult as a, ListAllArticlesResult as b };
|
|
@@ -0,0 +1,378 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var zod = require('zod');
|
|
4
|
+
|
|
5
|
+
// src/react/safe-url.ts
|
|
6
|
+
function safeHttpUrl(url) {
|
|
7
|
+
if (typeof url !== "string" || !/^https?:\/\//i.test(url)) return null;
|
|
8
|
+
for (let i = 0; i < url.length; i += 1) {
|
|
9
|
+
const code = url.charCodeAt(i);
|
|
10
|
+
if (code <= 32 || code === 127) return null;
|
|
11
|
+
}
|
|
12
|
+
return url;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
// src/next/metadata.ts
|
|
16
|
+
function httpsOnly(url) {
|
|
17
|
+
const safe = safeHttpUrl(url);
|
|
18
|
+
return safe !== null && /^https:\/\//i.test(safe) ? safe : null;
|
|
19
|
+
}
|
|
20
|
+
function toImage(article) {
|
|
21
|
+
const eyecatch = "eyecatch" in article ? article.eyecatch : null;
|
|
22
|
+
if (eyecatch) {
|
|
23
|
+
const url2 = httpsOnly(eyecatch.url);
|
|
24
|
+
if (url2 === null) return null;
|
|
25
|
+
const image = { url: url2 };
|
|
26
|
+
if (eyecatch.width !== null) image.width = eyecatch.width;
|
|
27
|
+
if (eyecatch.height !== null) image.height = eyecatch.height;
|
|
28
|
+
if (eyecatch.alt !== "") image.alt = eyecatch.alt;
|
|
29
|
+
return image;
|
|
30
|
+
}
|
|
31
|
+
const url = httpsOnly(article.eyecatchUrl);
|
|
32
|
+
return url === null ? null : { url };
|
|
33
|
+
}
|
|
34
|
+
function generateNoteMetadata(article, options = {}) {
|
|
35
|
+
const title = options.formatTitle ? options.formatTitle(article.title) : article.title;
|
|
36
|
+
const canonical = options.canonical ?? httpsOnly(article.url);
|
|
37
|
+
if (canonical === null) throw new TypeError(`article.url must be an https URL: ${JSON.stringify(article.url)}`);
|
|
38
|
+
const image = toImage(article);
|
|
39
|
+
const openGraph = {
|
|
40
|
+
type: "article",
|
|
41
|
+
title,
|
|
42
|
+
description: article.excerpt,
|
|
43
|
+
url: canonical,
|
|
44
|
+
publishedTime: article.publishedAt
|
|
45
|
+
};
|
|
46
|
+
const twitter = {
|
|
47
|
+
card: image ? "summary_large_image" : "summary",
|
|
48
|
+
title,
|
|
49
|
+
description: article.excerpt
|
|
50
|
+
};
|
|
51
|
+
if (image) {
|
|
52
|
+
openGraph.images = [image];
|
|
53
|
+
twitter.images = [image.url];
|
|
54
|
+
}
|
|
55
|
+
return { title, description: article.excerpt, alternates: { canonical }, openGraph, twitter };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// src/server/errors.ts
|
|
59
|
+
function toErrorOptions(options) {
|
|
60
|
+
return options !== void 0 && "cause" in options ? { cause: options.cause } : void 0;
|
|
61
|
+
}
|
|
62
|
+
var NoteError = class extends Error {
|
|
63
|
+
// 利用者側のバンドラがクラス名を圧縮しても変わらないよう、name は文字列で持つ
|
|
64
|
+
name = "NoteError";
|
|
65
|
+
code;
|
|
66
|
+
constructor(message, options) {
|
|
67
|
+
super(message, toErrorOptions(options));
|
|
68
|
+
this.code = options.code;
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
var NoteNotFoundError = class extends NoteError {
|
|
72
|
+
name = "NoteNotFoundError";
|
|
73
|
+
code = "NOTE_NOT_FOUND";
|
|
74
|
+
/** リクエストした URL */
|
|
75
|
+
url;
|
|
76
|
+
constructor(message, options) {
|
|
77
|
+
super(message, { ...options, code: "NOTE_NOT_FOUND" });
|
|
78
|
+
this.url = options.url;
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
var NoteHttpError = class extends NoteError {
|
|
82
|
+
name = "NoteHttpError";
|
|
83
|
+
code = "NOTE_HTTP_ERROR";
|
|
84
|
+
status;
|
|
85
|
+
/** リクエストした URL */
|
|
86
|
+
url;
|
|
87
|
+
constructor(message, options) {
|
|
88
|
+
super(message, { ...options, code: "NOTE_HTTP_ERROR" });
|
|
89
|
+
this.status = options.status;
|
|
90
|
+
this.url = options.url;
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
var NoteNetworkError = class extends NoteError {
|
|
94
|
+
name = "NoteNetworkError";
|
|
95
|
+
code = "NOTE_NETWORK_ERROR";
|
|
96
|
+
constructor(message, options) {
|
|
97
|
+
super(message, { ...options, code: "NOTE_NETWORK_ERROR" });
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
var NoteTimeoutError = class extends NoteError {
|
|
101
|
+
name = "NoteTimeoutError";
|
|
102
|
+
code = "NOTE_TIMEOUT";
|
|
103
|
+
constructor(message, options) {
|
|
104
|
+
super(message, { ...options, code: "NOTE_TIMEOUT" });
|
|
105
|
+
}
|
|
106
|
+
};
|
|
107
|
+
var NoteSchemaError = class extends NoteError {
|
|
108
|
+
name = "NoteSchemaError";
|
|
109
|
+
code = "NOTE_SCHEMA_ERROR";
|
|
110
|
+
issues;
|
|
111
|
+
constructor(message, options) {
|
|
112
|
+
const detail = options.issues.slice(0, 5).map((issue) => `${issue.path || "(root)"}: ${issue.message}`).join("; ");
|
|
113
|
+
super(detail === "" ? message : `${message} (${detail})`, { ...options, code: "NOTE_SCHEMA_ERROR" });
|
|
114
|
+
this.issues = options.issues;
|
|
115
|
+
}
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
// src/server/fetch-json.ts
|
|
119
|
+
var NOTE_ORIGIN = "https://note.com";
|
|
120
|
+
async function fetchNoteJson(url, options) {
|
|
121
|
+
if (new URL(url).origin !== NOTE_ORIGIN) {
|
|
122
|
+
throw new TypeError(`Refusing to request a non-note.com URL: ${url}`);
|
|
123
|
+
}
|
|
124
|
+
options.signal?.throwIfAborted();
|
|
125
|
+
const controller = new AbortController();
|
|
126
|
+
let timedOut = false;
|
|
127
|
+
const timer = setTimeout(() => {
|
|
128
|
+
timedOut = true;
|
|
129
|
+
controller.abort(new Error(`Timed out after ${options.timeoutMs}ms`));
|
|
130
|
+
}, options.timeoutMs);
|
|
131
|
+
const onAbort = () => controller.abort(options.signal?.reason);
|
|
132
|
+
options.signal?.addEventListener("abort", onAbort, { once: true });
|
|
133
|
+
let response;
|
|
134
|
+
let body;
|
|
135
|
+
try {
|
|
136
|
+
response = await options.fetch(url, {
|
|
137
|
+
method: "GET",
|
|
138
|
+
headers: { Accept: "application/json" },
|
|
139
|
+
credentials: "omit",
|
|
140
|
+
redirect: "error",
|
|
141
|
+
signal: controller.signal
|
|
142
|
+
});
|
|
143
|
+
body = await response.text();
|
|
144
|
+
} catch (error) {
|
|
145
|
+
if (options.signal?.aborted) throw options.signal.reason;
|
|
146
|
+
if (timedOut) {
|
|
147
|
+
throw new NoteTimeoutError(`Request to note timed out after ${options.timeoutMs}ms: ${url}`, { cause: error });
|
|
148
|
+
}
|
|
149
|
+
throw new NoteNetworkError(`Request to note failed: ${url}`, { cause: error });
|
|
150
|
+
} finally {
|
|
151
|
+
clearTimeout(timer);
|
|
152
|
+
options.signal?.removeEventListener("abort", onAbort);
|
|
153
|
+
}
|
|
154
|
+
if (response.redirected || response.url !== "" && new URL(response.url).origin !== NOTE_ORIGIN) {
|
|
155
|
+
throw new NoteNetworkError(`note redirected the request, which is not allowed: ${url}`);
|
|
156
|
+
}
|
|
157
|
+
if (response.status === 404) {
|
|
158
|
+
throw new NoteNotFoundError(`Not found on note: ${url}`, { url });
|
|
159
|
+
}
|
|
160
|
+
if (!response.ok) {
|
|
161
|
+
throw new NoteHttpError(`note responded with HTTP ${response.status}: ${url}`, { status: response.status, url });
|
|
162
|
+
}
|
|
163
|
+
try {
|
|
164
|
+
return JSON.parse(body);
|
|
165
|
+
} catch (error) {
|
|
166
|
+
throw new NoteSchemaError("note returned a response that is not valid JSON", {
|
|
167
|
+
issues: [{ path: "", message: "Invalid JSON" }],
|
|
168
|
+
cause: error
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// src/server/patterns.ts
|
|
174
|
+
var NOTE_KEY_RE = /^n[0-9a-z]{1,32}$/;
|
|
175
|
+
var NOTE_USER_RE = /^[A-Za-z0-9_-]{1,64}$/;
|
|
176
|
+
function hasControlOrSpace(value) {
|
|
177
|
+
for (let i = 0; i < value.length; i += 1) {
|
|
178
|
+
const code = value.charCodeAt(i);
|
|
179
|
+
if (code <= 32 || code === 127) return true;
|
|
180
|
+
}
|
|
181
|
+
return /\s/.test(value);
|
|
182
|
+
}
|
|
183
|
+
function isHttpsUrl(value) {
|
|
184
|
+
if (!value.startsWith("https://") || hasControlOrSpace(value)) return false;
|
|
185
|
+
try {
|
|
186
|
+
return new URL(value).protocol === "https:";
|
|
187
|
+
} catch {
|
|
188
|
+
return false;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
var httpsUrl = zod.z.string().refine(isHttpsUrl, "https \u306E URL \u3067\u306F\u3042\u308A\u307E\u305B\u3093");
|
|
192
|
+
var optionalHttpsUrl = zod.z.string().refine((value) => value.trim() === "" || isHttpsUrl(value), "https \u306E URL \u3067\u306F\u3042\u308A\u307E\u305B\u3093");
|
|
193
|
+
function emptyToNull(value) {
|
|
194
|
+
return value.trim() === "" ? null : value;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// src/server/normalize/contents.ts
|
|
198
|
+
var contentSchema = zod.z.object({
|
|
199
|
+
// リンク・キャッシュキーに使われるため、記事キーの形式に限る
|
|
200
|
+
key: zod.z.string().regex(NOTE_KEY_RE),
|
|
201
|
+
name: zod.z.string(),
|
|
202
|
+
noteUrl: httpsUrl,
|
|
203
|
+
publishAt: zod.z.string().refine((value) => !Number.isNaN(Date.parse(value)), "\u65E5\u6642\u3068\u3057\u3066\u89E3\u91C8\u3067\u304D\u307E\u305B\u3093"),
|
|
204
|
+
body: zod.z.string(),
|
|
205
|
+
// 見出し画像のない記事は null になる(実データで確認。fixture には例がない)
|
|
206
|
+
eyecatch: optionalHttpsUrl.nullable(),
|
|
207
|
+
hashtags: zod.z.array(zod.z.object({ hashtag: zod.z.object({ name: zod.z.string() }) })),
|
|
208
|
+
likeCount: zod.z.number(),
|
|
209
|
+
price: zod.z.number(),
|
|
210
|
+
user: zod.z.object({
|
|
211
|
+
nickname: zod.z.string(),
|
|
212
|
+
// 著者の確認やリンクの組み立てに使われるため、note のユーザー名の形式に限る
|
|
213
|
+
urlname: zod.z.string().regex(NOTE_USER_RE),
|
|
214
|
+
userProfileImagePath: optionalHttpsUrl
|
|
215
|
+
})
|
|
216
|
+
});
|
|
217
|
+
var contentsResponseSchema = zod.z.object({
|
|
218
|
+
data: zod.z.object({
|
|
219
|
+
contents: zod.z.array(contentSchema),
|
|
220
|
+
isLastPage: zod.z.boolean(),
|
|
221
|
+
totalCount: zod.z.number()
|
|
222
|
+
})
|
|
223
|
+
});
|
|
224
|
+
function toSummary(content) {
|
|
225
|
+
return {
|
|
226
|
+
key: content.key,
|
|
227
|
+
title: content.name,
|
|
228
|
+
url: content.noteUrl,
|
|
229
|
+
publishedAt: new Date(content.publishAt).toISOString(),
|
|
230
|
+
excerpt: content.body.trim(),
|
|
231
|
+
eyecatchUrl: content.eyecatch === null ? null : emptyToNull(content.eyecatch),
|
|
232
|
+
hashtags: content.hashtags.map(({ hashtag }) => hashtag.name.replace(/^#/, "")),
|
|
233
|
+
likeCount: content.likeCount,
|
|
234
|
+
price: content.price,
|
|
235
|
+
author: {
|
|
236
|
+
name: content.user.nickname,
|
|
237
|
+
urlname: content.user.urlname,
|
|
238
|
+
imageUrl: emptyToNull(content.user.userProfileImagePath)
|
|
239
|
+
},
|
|
240
|
+
source: "api"
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
function normalizeContentsPage(json, page) {
|
|
244
|
+
const result = contentsResponseSchema.safeParse(json);
|
|
245
|
+
if (!result.success) {
|
|
246
|
+
throw new NoteSchemaError("Unexpected shape of the note article list response", {
|
|
247
|
+
issues: result.error.issues.map((issue) => ({ path: issue.path.map(String).join("."), message: issue.message }))
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
const { data } = result.data;
|
|
251
|
+
return {
|
|
252
|
+
articles: data.contents.map(toSummary),
|
|
253
|
+
page,
|
|
254
|
+
totalCount: data.totalCount,
|
|
255
|
+
isLastPage: data.isLastPage
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
// src/server/request-options.ts
|
|
260
|
+
var DEFAULT_TIMEOUT_MS = 1e4;
|
|
261
|
+
var DEFAULT_MIN_INTERVAL_MS = 1e3;
|
|
262
|
+
var MAX_TIMER_MS = 2 ** 31 - 1;
|
|
263
|
+
function assertMilliseconds(name, value, min) {
|
|
264
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value < min || value > MAX_TIMER_MS) {
|
|
265
|
+
throw new TypeError(`${name} must be a finite number between ${min} and ${MAX_TIMER_MS}: ${String(value)}`);
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
// src/server/throttle.ts
|
|
270
|
+
function sleep(ms, signal) {
|
|
271
|
+
return new Promise((resolve, reject) => {
|
|
272
|
+
if (signal?.aborted) {
|
|
273
|
+
reject(signal.reason);
|
|
274
|
+
return;
|
|
275
|
+
}
|
|
276
|
+
const onAbort = () => {
|
|
277
|
+
clearTimeout(timer);
|
|
278
|
+
reject(signal?.reason);
|
|
279
|
+
};
|
|
280
|
+
const timer = setTimeout(() => {
|
|
281
|
+
signal?.removeEventListener("abort", onAbort);
|
|
282
|
+
resolve();
|
|
283
|
+
}, ms);
|
|
284
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
285
|
+
});
|
|
286
|
+
}
|
|
287
|
+
function createThrottle() {
|
|
288
|
+
let tail = Promise.resolve();
|
|
289
|
+
let lastSentAt;
|
|
290
|
+
return (minIntervalMs, signal) => {
|
|
291
|
+
const turn = tail.then(async () => {
|
|
292
|
+
if (lastSentAt !== void 0) {
|
|
293
|
+
const wait = lastSentAt + minIntervalMs - Date.now();
|
|
294
|
+
if (wait > 0) await sleep(wait, signal);
|
|
295
|
+
}
|
|
296
|
+
signal?.throwIfAborted();
|
|
297
|
+
lastSentAt = Date.now();
|
|
298
|
+
});
|
|
299
|
+
tail = turn.catch(() => {
|
|
300
|
+
});
|
|
301
|
+
return turn;
|
|
302
|
+
};
|
|
303
|
+
}
|
|
304
|
+
var GLOBAL_KEY = /* @__PURE__ */ Symbol.for("note-blog-kit.throttle");
|
|
305
|
+
function getDefaultThrottle() {
|
|
306
|
+
const store = globalThis;
|
|
307
|
+
store[GLOBAL_KEY] ??= createThrottle();
|
|
308
|
+
return store[GLOBAL_KEY];
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
// src/server/list-articles.ts
|
|
312
|
+
async function listArticles(options) {
|
|
313
|
+
const { user, page = 1, timeoutMs = DEFAULT_TIMEOUT_MS, minIntervalMs = DEFAULT_MIN_INTERVAL_MS, signal } = options;
|
|
314
|
+
if (typeof user !== "string" || !NOTE_USER_RE.test(user)) {
|
|
315
|
+
throw new TypeError(`Invalid note user name: ${typeof user === "string" ? JSON.stringify(user) : typeof user}`);
|
|
316
|
+
}
|
|
317
|
+
if (typeof page !== "number" || !Number.isInteger(page) || page < 1) {
|
|
318
|
+
throw new TypeError(`page must be a positive integer: ${typeof page === "number" ? page : typeof page}`);
|
|
319
|
+
}
|
|
320
|
+
assertMilliseconds("timeoutMs", timeoutMs, 1);
|
|
321
|
+
assertMilliseconds("minIntervalMs", minIntervalMs, 0);
|
|
322
|
+
const url = `${NOTE_ORIGIN}/api/v2/creators/${encodeURIComponent(user)}/contents?kind=note&page=${page}`;
|
|
323
|
+
await getDefaultThrottle()(minIntervalMs, signal);
|
|
324
|
+
const json = await fetchNoteJson(url, { fetch: options.fetch ?? globalThis.fetch, timeoutMs, signal });
|
|
325
|
+
return normalizeContentsPage(json, page);
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
// src/server/iterate-articles.ts
|
|
329
|
+
var DEFAULT_MAX_PAGES = 20;
|
|
330
|
+
async function* iterateArticles(options) {
|
|
331
|
+
const { maxPages = DEFAULT_MAX_PAGES, ...listOptions } = options;
|
|
332
|
+
if (typeof maxPages !== "number" || !Number.isInteger(maxPages) || maxPages < 1) {
|
|
333
|
+
throw new TypeError(
|
|
334
|
+
`maxPages must be a positive integer: ${typeof maxPages === "number" ? maxPages : typeof maxPages}`
|
|
335
|
+
);
|
|
336
|
+
}
|
|
337
|
+
const seen = /* @__PURE__ */ new Set();
|
|
338
|
+
let totalCount = null;
|
|
339
|
+
let pages = 0;
|
|
340
|
+
for (let page = 1; page <= maxPages; page += 1) {
|
|
341
|
+
const result = await listArticles({ ...listOptions, page });
|
|
342
|
+
pages = page;
|
|
343
|
+
totalCount = result.totalCount;
|
|
344
|
+
for (const article of result.articles) {
|
|
345
|
+
if (seen.has(article.key)) continue;
|
|
346
|
+
seen.add(article.key);
|
|
347
|
+
yield article;
|
|
348
|
+
}
|
|
349
|
+
if (result.isLastPage || result.articles.length === 0) {
|
|
350
|
+
return { truncated: false, totalCount, pages };
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
return { truncated: true, totalCount, pages };
|
|
354
|
+
}
|
|
355
|
+
async function listAllArticles(options) {
|
|
356
|
+
const articles = [];
|
|
357
|
+
const iterator = iterateArticles(options);
|
|
358
|
+
let step = await iterator.next();
|
|
359
|
+
while (!step.done) {
|
|
360
|
+
articles.push(step.value);
|
|
361
|
+
step = await iterator.next();
|
|
362
|
+
}
|
|
363
|
+
return { articles, ...step.value };
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
// src/next/static-params.ts
|
|
367
|
+
var PARAM_RE = /^[A-Za-z0-9_-]{1,64}$/;
|
|
368
|
+
async function generateNoteStaticParams(options) {
|
|
369
|
+
const { param = "key", ...listOptions } = options;
|
|
370
|
+
if (typeof param !== "string" || !PARAM_RE.test(param)) {
|
|
371
|
+
throw new TypeError(`param must be a dynamic segment name: ${JSON.stringify(param)}`);
|
|
372
|
+
}
|
|
373
|
+
const { articles } = await listAllArticles(listOptions);
|
|
374
|
+
return articles.map((article) => ({ [param]: article.key }));
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
exports.generateNoteMetadata = generateNoteMetadata;
|
|
378
|
+
exports.generateNoteStaticParams = generateNoteStaticParams;
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { NoteArticle, NoteArticleSummary } from '../index.cjs';
|
|
2
|
+
export { NoteAuthor, NoteEmbed, NoteEyecatch, NoteSource, NoteTocItem } from '../index.cjs';
|
|
3
|
+
import { I as IterateArticlesOptions } from '../iterate-articles-BeI9bBh3.cjs';
|
|
4
|
+
export { L as ListArticlesOptions, N as NoteRequestOptions } from '../iterate-articles-BeI9bBh3.cjs';
|
|
5
|
+
|
|
6
|
+
/** OG 画像 */
|
|
7
|
+
interface NoteMetadataImage {
|
|
8
|
+
/** 画像 URL(https) */
|
|
9
|
+
url: string;
|
|
10
|
+
/** 幅(px)。見出し画像の幅がわかるとき */
|
|
11
|
+
width?: number;
|
|
12
|
+
/** 高さ(px)。見出し画像の高さがわかるとき */
|
|
13
|
+
height?: number;
|
|
14
|
+
/** 代替テキスト。見出し画像の alt が空でないとき */
|
|
15
|
+
alt?: string;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* {@link generateNoteMetadata} の戻り値。Next.js の `Metadata` にそのまま代入できる形
|
|
19
|
+
* (`next` を依存に加えないため、型は自前で定義している。代入できることは examples/next の型チェックで確かめている)。
|
|
20
|
+
*/
|
|
21
|
+
interface NoteMetadata {
|
|
22
|
+
/** タイトル(`formatTitle` を適用した後の値) */
|
|
23
|
+
title: string;
|
|
24
|
+
/** 説明(記事の抜粋 `excerpt`) */
|
|
25
|
+
description: string;
|
|
26
|
+
/** canonical。既定は `article.url`(note の元 URL) */
|
|
27
|
+
alternates: {
|
|
28
|
+
canonical: string;
|
|
29
|
+
};
|
|
30
|
+
/** Open Graph。`url` は canonical と同じ */
|
|
31
|
+
openGraph: {
|
|
32
|
+
type: 'article';
|
|
33
|
+
title: string;
|
|
34
|
+
description: string;
|
|
35
|
+
url: string;
|
|
36
|
+
publishedTime: string;
|
|
37
|
+
/** 見出し画像(https のときだけ) */
|
|
38
|
+
images?: NoteMetadataImage[];
|
|
39
|
+
};
|
|
40
|
+
/** Twitter(X)カード */
|
|
41
|
+
twitter: {
|
|
42
|
+
/** 見出し画像があれば `summary_large_image`、なければ `summary` */
|
|
43
|
+
card: 'summary_large_image' | 'summary';
|
|
44
|
+
title: string;
|
|
45
|
+
description: string;
|
|
46
|
+
images?: string[];
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
/** {@link generateNoteMetadata} のオプション */
|
|
50
|
+
interface GenerateNoteMetadataOptions {
|
|
51
|
+
/**
|
|
52
|
+
* canonical(と og:url)。既定は `article.url`(note の元 URL)。
|
|
53
|
+
* 自分のサイトの URL を正にしたい場合に渡す。渡した値はそのまま使うため、信頼できる値を渡すこと
|
|
54
|
+
*/
|
|
55
|
+
canonical?: string;
|
|
56
|
+
/** タイトルの加工(例:`(title) => \`${title} | ブログ\``)。OG・Twitter のタイトルにも使う。既定はそのまま */
|
|
57
|
+
formatTitle?: (title: string) => string;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* 記事の詳細ページの metadata を作る(Next.js App Router の `generateMetadata` から返す)。
|
|
61
|
+
* canonical の既定値は note の元 URL(検索エンジンに note の記事を正として扱わせ、重複コンテンツを避ける)。
|
|
62
|
+
*
|
|
63
|
+
* @throws {TypeError} `canonical` を渡さず、`article.url` が https の URL でないとき
|
|
64
|
+
*
|
|
65
|
+
* @example
|
|
66
|
+
* ```ts
|
|
67
|
+
* export async function generateMetadata({ params }) {
|
|
68
|
+
* // 実際には、自分の記事か(article.author.urlname)を確かめてから使う
|
|
69
|
+
* const article = await getArticle({ key: (await params).key });
|
|
70
|
+
* return generateNoteMetadata(article, { formatTitle: (title) => `${title} | ブログ` });
|
|
71
|
+
* }
|
|
72
|
+
* ```
|
|
73
|
+
*/
|
|
74
|
+
declare function generateNoteMetadata(article: NoteArticle | NoteArticleSummary, options?: GenerateNoteMetadataOptions): NoteMetadata;
|
|
75
|
+
|
|
76
|
+
/** `generateNoteStaticParams` のオプション */
|
|
77
|
+
interface GenerateNoteStaticParamsOptions<P extends string = 'key'> extends IterateArticlesOptions {
|
|
78
|
+
/** 動的セグメントの名前(`app/blog/[key]/page.tsx` なら `'key'`)。英数字・_・- のみ。既定は `'key'` */
|
|
79
|
+
param?: P;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* 記事の詳細ページの `generateStaticParams` に返す値を作る(サーバー専用。ビルド時に呼ぶ)。
|
|
83
|
+
* `listAllArticles` で記事を集めるため、1ページ(6件)ごとに1リクエストかかる。
|
|
84
|
+
* `maxPages`(既定 20 ページ = 120件)で打ち切るので、それより古い記事はビルド時には生成しない。
|
|
85
|
+
* `dynamicParams` を true(Next.js の既定)のままにしておけば、残りの記事も最初のアクセス時に表示できる。
|
|
86
|
+
*
|
|
87
|
+
* @example
|
|
88
|
+
* ```ts
|
|
89
|
+
* export const generateStaticParams = () => generateNoteStaticParams({ user: 'your_urlname' });
|
|
90
|
+
* ```
|
|
91
|
+
* @throws {TypeError} param・user・maxPages などが不正なとき
|
|
92
|
+
*/
|
|
93
|
+
declare function generateNoteStaticParams(options: GenerateNoteStaticParamsOptions & {
|
|
94
|
+
param?: undefined;
|
|
95
|
+
}): Promise<{
|
|
96
|
+
key: string;
|
|
97
|
+
}[]>;
|
|
98
|
+
declare function generateNoteStaticParams<P extends string>(options: GenerateNoteStaticParamsOptions<P> & {
|
|
99
|
+
param: P;
|
|
100
|
+
}): Promise<Record<P, string>[]>;
|
|
101
|
+
|
|
102
|
+
export { IterateArticlesOptions, NoteArticle, NoteArticleSummary, generateNoteMetadata, generateNoteStaticParams };
|
|
103
|
+
export type { GenerateNoteMetadataOptions, GenerateNoteStaticParamsOptions, NoteMetadata, NoteMetadataImage };
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { NoteArticle, NoteArticleSummary } from '../index.js';
|
|
2
|
+
export { NoteAuthor, NoteEmbed, NoteEyecatch, NoteSource, NoteTocItem } from '../index.js';
|
|
3
|
+
import { I as IterateArticlesOptions } from '../iterate-articles-9dzDflSn.js';
|
|
4
|
+
export { L as ListArticlesOptions, N as NoteRequestOptions } from '../iterate-articles-9dzDflSn.js';
|
|
5
|
+
|
|
6
|
+
/** OG 画像 */
|
|
7
|
+
interface NoteMetadataImage {
|
|
8
|
+
/** 画像 URL(https) */
|
|
9
|
+
url: string;
|
|
10
|
+
/** 幅(px)。見出し画像の幅がわかるとき */
|
|
11
|
+
width?: number;
|
|
12
|
+
/** 高さ(px)。見出し画像の高さがわかるとき */
|
|
13
|
+
height?: number;
|
|
14
|
+
/** 代替テキスト。見出し画像の alt が空でないとき */
|
|
15
|
+
alt?: string;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* {@link generateNoteMetadata} の戻り値。Next.js の `Metadata` にそのまま代入できる形
|
|
19
|
+
* (`next` を依存に加えないため、型は自前で定義している。代入できることは examples/next の型チェックで確かめている)。
|
|
20
|
+
*/
|
|
21
|
+
interface NoteMetadata {
|
|
22
|
+
/** タイトル(`formatTitle` を適用した後の値) */
|
|
23
|
+
title: string;
|
|
24
|
+
/** 説明(記事の抜粋 `excerpt`) */
|
|
25
|
+
description: string;
|
|
26
|
+
/** canonical。既定は `article.url`(note の元 URL) */
|
|
27
|
+
alternates: {
|
|
28
|
+
canonical: string;
|
|
29
|
+
};
|
|
30
|
+
/** Open Graph。`url` は canonical と同じ */
|
|
31
|
+
openGraph: {
|
|
32
|
+
type: 'article';
|
|
33
|
+
title: string;
|
|
34
|
+
description: string;
|
|
35
|
+
url: string;
|
|
36
|
+
publishedTime: string;
|
|
37
|
+
/** 見出し画像(https のときだけ) */
|
|
38
|
+
images?: NoteMetadataImage[];
|
|
39
|
+
};
|
|
40
|
+
/** Twitter(X)カード */
|
|
41
|
+
twitter: {
|
|
42
|
+
/** 見出し画像があれば `summary_large_image`、なければ `summary` */
|
|
43
|
+
card: 'summary_large_image' | 'summary';
|
|
44
|
+
title: string;
|
|
45
|
+
description: string;
|
|
46
|
+
images?: string[];
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
/** {@link generateNoteMetadata} のオプション */
|
|
50
|
+
interface GenerateNoteMetadataOptions {
|
|
51
|
+
/**
|
|
52
|
+
* canonical(と og:url)。既定は `article.url`(note の元 URL)。
|
|
53
|
+
* 自分のサイトの URL を正にしたい場合に渡す。渡した値はそのまま使うため、信頼できる値を渡すこと
|
|
54
|
+
*/
|
|
55
|
+
canonical?: string;
|
|
56
|
+
/** タイトルの加工(例:`(title) => \`${title} | ブログ\``)。OG・Twitter のタイトルにも使う。既定はそのまま */
|
|
57
|
+
formatTitle?: (title: string) => string;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* 記事の詳細ページの metadata を作る(Next.js App Router の `generateMetadata` から返す)。
|
|
61
|
+
* canonical の既定値は note の元 URL(検索エンジンに note の記事を正として扱わせ、重複コンテンツを避ける)。
|
|
62
|
+
*
|
|
63
|
+
* @throws {TypeError} `canonical` を渡さず、`article.url` が https の URL でないとき
|
|
64
|
+
*
|
|
65
|
+
* @example
|
|
66
|
+
* ```ts
|
|
67
|
+
* export async function generateMetadata({ params }) {
|
|
68
|
+
* // 実際には、自分の記事か(article.author.urlname)を確かめてから使う
|
|
69
|
+
* const article = await getArticle({ key: (await params).key });
|
|
70
|
+
* return generateNoteMetadata(article, { formatTitle: (title) => `${title} | ブログ` });
|
|
71
|
+
* }
|
|
72
|
+
* ```
|
|
73
|
+
*/
|
|
74
|
+
declare function generateNoteMetadata(article: NoteArticle | NoteArticleSummary, options?: GenerateNoteMetadataOptions): NoteMetadata;
|
|
75
|
+
|
|
76
|
+
/** `generateNoteStaticParams` のオプション */
|
|
77
|
+
interface GenerateNoteStaticParamsOptions<P extends string = 'key'> extends IterateArticlesOptions {
|
|
78
|
+
/** 動的セグメントの名前(`app/blog/[key]/page.tsx` なら `'key'`)。英数字・_・- のみ。既定は `'key'` */
|
|
79
|
+
param?: P;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* 記事の詳細ページの `generateStaticParams` に返す値を作る(サーバー専用。ビルド時に呼ぶ)。
|
|
83
|
+
* `listAllArticles` で記事を集めるため、1ページ(6件)ごとに1リクエストかかる。
|
|
84
|
+
* `maxPages`(既定 20 ページ = 120件)で打ち切るので、それより古い記事はビルド時には生成しない。
|
|
85
|
+
* `dynamicParams` を true(Next.js の既定)のままにしておけば、残りの記事も最初のアクセス時に表示できる。
|
|
86
|
+
*
|
|
87
|
+
* @example
|
|
88
|
+
* ```ts
|
|
89
|
+
* export const generateStaticParams = () => generateNoteStaticParams({ user: 'your_urlname' });
|
|
90
|
+
* ```
|
|
91
|
+
* @throws {TypeError} param・user・maxPages などが不正なとき
|
|
92
|
+
*/
|
|
93
|
+
declare function generateNoteStaticParams(options: GenerateNoteStaticParamsOptions & {
|
|
94
|
+
param?: undefined;
|
|
95
|
+
}): Promise<{
|
|
96
|
+
key: string;
|
|
97
|
+
}[]>;
|
|
98
|
+
declare function generateNoteStaticParams<P extends string>(options: GenerateNoteStaticParamsOptions<P> & {
|
|
99
|
+
param: P;
|
|
100
|
+
}): Promise<Record<P, string>[]>;
|
|
101
|
+
|
|
102
|
+
export { IterateArticlesOptions, NoteArticle, NoteArticleSummary, generateNoteMetadata, generateNoteStaticParams };
|
|
103
|
+
export type { GenerateNoteMetadataOptions, GenerateNoteStaticParamsOptions, NoteMetadata, NoteMetadataImage };
|