@secret-momo/notion 2.2.0 → 2.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,35 +1 @@
1
- import { logger, sleep } from '@secret-momo/utils';
2
-
3
- const NOTION_TLS_MAX_RETRIES = 5;
4
- function isCertOrTlsError(message) {
5
- return ["certificate", "unknown cert", "ssl", "tls"].some((m) => message.includes(m));
6
- }
7
- async function customFetch(input, init) {
8
- const mergedInit = {
9
- ...init,
10
- // https://github.com/oven-sh/bun/blob/7abe6c38/src/bun.js/webcore/fetch.zig
11
- // @ts-expect-error Bun 专有参数:关闭 fetch 内置的 5 分钟空闲超时
12
- timeout: false,
13
- headers: {
14
- ...init?.headers,
15
- Connection: "close"
16
- // 关闭 HTTP keep-alive,防止 Bun 底层连接复用带来的问题
17
- }
18
- };
19
- for (let attempt = 0; attempt <= NOTION_TLS_MAX_RETRIES; attempt++) {
20
- try {
21
- return await fetch(input, mergedInit);
22
- } catch (error) {
23
- const message = (error?.message ?? String(error)).toLowerCase();
24
- const isLastAttempt = attempt >= NOTION_TLS_MAX_RETRIES;
25
- if (isLastAttempt || !isCertOrTlsError(message)) {
26
- throw error;
27
- }
28
- logger.child({ name: "notion" }).warn(`Notion TLS \u91CD\u8BD5\u7B2C ${attempt + 1} \u6B21, \u9519\u8BEF\u4FE1\u606F\uFF1A${message}`);
29
- await sleep(1e3 * attempt);
30
- }
31
- }
32
- throw new Error("Unexpected notion fetch retry failure");
33
- }
34
-
35
- export { customFetch };
1
+ import{logger as s,sleep as u}from"@secret-momo/utils";const c=5;function a(o){return["certificate","unknown cert","ssl","tls"].some(t=>o.includes(t))}async function f(o,t){const i={...t,timeout:!1,headers:{...t?.headers,Connection:"close"}};for(let e=0;e<=c;e++)try{return await fetch(o,i)}catch(n){const r=(n?.message??String(n)).toLowerCase();if(e>=c||!a(r))throw n;s.child({name:"notion"}).warn(`Notion TLS \u91CD\u8BD5\u7B2C ${e+1} \u6B21, \u9519\u8BEF\u4FE1\u606F\uFF1A${r}`),await u(1e3*e)}throw new Error("Unexpected notion fetch retry failure")}export{f as customFetch};
@@ -1,16 +1 @@
1
- function buildNotionPageWebUrl(pageId) {
2
- return `https://www.notion.so/${pageId.replace(/-/g, "")}`;
3
- }
4
- function getId(page) {
5
- const idProperty = page.properties["ID"];
6
- if (idProperty?.type !== "unique_id") {
7
- throw new Error("ID \u5C5E\u6027\u4E0D\u662F unique_id \u7C7B\u578B");
8
- }
9
- const id = idProperty.unique_id.number;
10
- if (id === null) {
11
- throw new Error("ID \u5C5E\u6027\u4E3A\u7A7A");
12
- }
13
- return id;
14
- }
15
-
16
- export { buildNotionPageWebUrl, getId };
1
+ function e(u){return`https://www.notion.so/${u.replace(/-/g,"")}`}function t(u){const n=u.properties.ID;if(n?.type!=="unique_id")throw new Error("ID \u5C5E\u6027\u4E0D\u662F unique_id \u7C7B\u578B");const r=n.unique_id.number;if(r===null)throw new Error("ID \u5C5E\u6027\u4E3A\u7A7A");return r}export{e as buildNotionPageWebUrl,t as getId};
@@ -1,32 +1 @@
1
- const SINGLE_PART_MAX_BYTES = 20 * 1024 * 1024;
2
- const MULTIPART_CHUNK_BYTES = 18 * 1024 * 1024;
3
- const MULTIPART_UPLOAD_CONCURRENCY = 3;
4
- const MIME_BY_EXT = {
5
- ".avif": "image/avif",
6
- ".bmp": "image/bmp",
7
- ".gif": "image/gif",
8
- ".heic": "image/heic",
9
- ".heif": "image/heif",
10
- ".ico": "image/x-icon",
11
- ".jpeg": "image/jpeg",
12
- ".jpg": "image/jpeg",
13
- ".png": "image/png",
14
- ".svg": "image/svg+xml",
15
- ".webp": "image/webp",
16
- ".html": "text/html",
17
- ".htm": "text/html",
18
- ".mp4": "video/mp4",
19
- ".webm": "video/webm",
20
- ".mov": "video/quicktime",
21
- ".m4v": "video/x-m4v",
22
- ".mkv": "video/x-matroska",
23
- ".mpeg": "video/mpeg",
24
- ".mpg": "video/mpeg",
25
- ".avi": "video/x-msvideo",
26
- ".pdf": "application/pdf",
27
- ".zip": "application/zip",
28
- ".json": "application/json",
29
- ".txt": "text/plain"
30
- };
31
-
32
- export { MIME_BY_EXT, MULTIPART_CHUNK_BYTES, MULTIPART_UPLOAD_CONCURRENCY, SINGLE_PART_MAX_BYTES };
1
+ const i=20971520,e=18874368,m=3,p={".avif":"image/avif",".bmp":"image/bmp",".gif":"image/gif",".heic":"image/heic",".heif":"image/heif",".ico":"image/x-icon",".jpeg":"image/jpeg",".jpg":"image/jpeg",".png":"image/png",".svg":"image/svg+xml",".webp":"image/webp",".html":"text/html",".htm":"text/html",".mp4":"video/mp4",".webm":"video/webm",".mov":"video/quicktime",".m4v":"video/x-m4v",".mkv":"video/x-matroska",".mpeg":"video/mpeg",".mpg":"video/mpeg",".avi":"video/x-msvideo",".pdf":"application/pdf",".zip":"application/zip",".json":"application/json",".txt":"text/plain"};export{p as MIME_BY_EXT,e as MULTIPART_CHUNK_BYTES,m as MULTIPART_UPLOAD_CONCURRENCY,i as SINGLE_PART_MAX_BYTES};
@@ -1,45 +1 @@
1
- import { extname } from 'node:path';
2
- import { access } from 'node:fs/promises';
3
- import { gzipSync } from 'node:zlib';
4
- import { MIME_BY_EXT } from './config.js';
5
-
6
- function contentTypeFromPath(absolutePath) {
7
- const ext = extname(absolutePath).toLowerCase();
8
- return MIME_BY_EXT[ext] ?? "application/octet-stream";
9
- }
10
- function prepareBufferForNotionUpload(absolutePath, fileBuffer, displayName, mime) {
11
- const ext = extname(absolutePath).toLowerCase();
12
- if (ext !== ".html") {
13
- return { buffer: fileBuffer, displayName, mime };
14
- }
15
- return {
16
- buffer: gzipSync(fileBuffer),
17
- displayName: displayName.endsWith(".gz") ? displayName : `${displayName}.gz`,
18
- mime: "application/gzip"
19
- };
20
- }
21
- async function ensureLocalFileReadable(absolutePath) {
22
- try {
23
- await access(absolutePath);
24
- } catch {
25
- throw new Error(`\u627E\u4E0D\u5230\u8981\u4E0A\u4F20\u7684\u6587\u4EF6: ${absolutePath}`);
26
- }
27
- }
28
- async function runWithConcurrency(items, concurrency, worker) {
29
- let nextIndex = 0;
30
- const workerCount = Math.min(concurrency, items.length);
31
- await Promise.all(
32
- Array.from({ length: workerCount }, async () => {
33
- while (nextIndex < items.length) {
34
- const currentIndex = nextIndex++;
35
- const item = items[currentIndex];
36
- if (item === void 0) {
37
- return;
38
- }
39
- await worker(item);
40
- }
41
- })
42
- );
43
- }
44
-
45
- export { contentTypeFromPath, ensureLocalFileReadable, prepareBufferForNotionUpload, runWithConcurrency };
1
+ import{extname as n}from"node:path";import{access as u}from"node:fs/promises";import{gzipSync as m}from"node:zlib";import{MIME_BY_EXT as f}from"./config.js";function p(t){const e=n(t).toLowerCase();return f[e]??"application/octet-stream"}function s(t,e,o,r){return n(t).toLowerCase()!==".html"?{buffer:e,displayName:o,mime:r}:{buffer:m(e),displayName:o.endsWith(".gz")?o:`${o}.gz`,mime:"application/gzip"}}async function l(t){try{await u(t)}catch{throw new Error(`\u627E\u4E0D\u5230\u8981\u4E0A\u4F20\u7684\u6587\u4EF6: ${t}`)}}async function h(t,e,o){let r=0;const i=Math.min(e,t.length);await Promise.all(Array.from({length:i},async()=>{for(;r<t.length;){const c=r++,a=t[c];if(a===void 0)return;await o(a)}}))}export{p as contentTypeFromPath,l as ensureLocalFileReadable,s as prepareBufferForNotionUpload,h as runWithConcurrency};
@@ -1,96 +1 @@
1
- import { basename } from 'node:path';
2
- import { readFile } from 'node:fs/promises';
3
- import { SINGLE_PART_MAX_BYTES, MULTIPART_CHUNK_BYTES, MULTIPART_UPLOAD_CONCURRENCY } from './config.js';
4
- import { ensureLocalFileReadable, contentTypeFromPath, prepareBufferForNotionUpload, runWithConcurrency } from './helper.js';
5
-
6
- async function completeFileUpload({
7
- client,
8
- displayName,
9
- contentType,
10
- fileBuffer
11
- }) {
12
- if (fileBuffer.length <= SINGLE_PART_MAX_BYTES) {
13
- const data = new Blob([fileBuffer], { type: contentType });
14
- const created2 = await client.fileUploads.create({
15
- mode: "single_part",
16
- filename: displayName,
17
- content_type: contentType
18
- });
19
- const afterSend = await client.fileUploads.send({
20
- file_upload_id: created2.id,
21
- file: { filename: displayName, data }
22
- });
23
- if (afterSend.status !== "uploaded") {
24
- throw new Error(`\u6587\u4EF6\u4E0A\u4F20\u672A\u5C31\u7EEA\uFF0C\u72B6\u6001: ${afterSend.status}`);
25
- }
26
- return created2.id;
27
- }
28
- const number_of_parts = Math.ceil(fileBuffer.length / MULTIPART_CHUNK_BYTES);
29
- const created = await client.fileUploads.create({
30
- mode: "multi_part",
31
- filename: displayName,
32
- content_type: contentType,
33
- number_of_parts
34
- });
35
- await runWithConcurrency(
36
- Array.from({ length: number_of_parts }, (_, index) => index + 1),
37
- MULTIPART_UPLOAD_CONCURRENCY,
38
- async (part) => {
39
- const start = (part - 1) * MULTIPART_CHUNK_BYTES;
40
- const end = Math.min(start + MULTIPART_CHUNK_BYTES, fileBuffer.length);
41
- const slice = fileBuffer.subarray(start, end);
42
- const data = new Blob([slice], { type: contentType });
43
- await client.fileUploads.send({
44
- file_upload_id: created.id,
45
- part_number: String(part),
46
- file: { filename: displayName, data }
47
- });
48
- }
49
- );
50
- const afterComplete = await client.fileUploads.complete({
51
- file_upload_id: created.id
52
- });
53
- if (afterComplete.status !== "uploaded") {
54
- throw new Error(`\u591A\u6BB5\u6587\u4EF6\u4E0A\u4F20\u672A\u5B8C\u6210\uFF0C\u72B6\u6001: ${afterComplete.status}`);
55
- }
56
- return created.id;
57
- }
58
- async function uploadFileToNotion(client, absolutePath) {
59
- const displayName = basename(absolutePath);
60
- await ensureLocalFileReadable(absolutePath);
61
- const mime = contentTypeFromPath(absolutePath);
62
- const rawBuffer = await readFile(absolutePath);
63
- const {
64
- buffer,
65
- displayName: uploadName,
66
- mime: uploadMime
67
- } = prepareBufferForNotionUpload(absolutePath, rawBuffer, displayName, mime);
68
- return completeFileUpload({
69
- client,
70
- displayName: uploadName,
71
- contentType: uploadMime,
72
- fileBuffer: buffer
73
- });
74
- }
75
- async function uploadImageToNotion(client, absolutePath) {
76
- await ensureLocalFileReadable(absolutePath);
77
- const displayName = basename(absolutePath);
78
- const contentType = contentTypeFromPath(absolutePath);
79
- if (!contentType.startsWith("image/")) {
80
- throw new Error(`\u4E0D\u662F\u56FE\u7247 MIME\uFF08${contentType}\uFF09\uFF0C\u8BF7\u4F20\u56FE\u7247\u8DEF\u5F84\u6216\u663E\u5F0F\u6307\u5B9A contentType`);
81
- }
82
- const fileBuffer = await readFile(absolutePath);
83
- return completeFileUpload({ client, displayName, contentType, fileBuffer });
84
- }
85
- async function uploadVideoToNotion(client, absolutePath) {
86
- const displayName = basename(absolutePath);
87
- await ensureLocalFileReadable(absolutePath);
88
- const contentType = contentTypeFromPath(absolutePath);
89
- if (!contentType.startsWith("video/")) {
90
- throw new Error(`\u4E0D\u662F\u89C6\u9891 MIME\uFF08${contentType}\uFF09\uFF0C\u8BF7\u4F20\u89C6\u9891\u8DEF\u5F84\u6216\u663E\u5F0F\u6307\u5B9A contentType`);
91
- }
92
- const fileBuffer = await readFile(absolutePath);
93
- return completeFileUpload({ client, displayName, contentType, fileBuffer });
94
- }
95
-
96
- export { uploadFileToNotion, uploadImageToNotion, uploadVideoToNotion };
1
+ import{basename as f}from"node:path";import{readFile as p}from"node:fs/promises";import{SINGLE_PART_MAX_BYTES as w,MULTIPART_CHUNK_BYTES as F,MULTIPART_UPLOAD_CONCURRENCY as _}from"./config.js";import{ensureLocalFileReadable as c,contentTypeFromPath as d,prepareBufferForNotionUpload as B,runWithConcurrency as T}from"./helper.js";async function m({client:u,displayName:t,contentType:a,fileBuffer:e}){if(e.length<=w){const o=new Blob([e],{type:a}),n=await u.fileUploads.create({mode:"single_part",filename:t,content_type:a}),s=await u.fileUploads.send({file_upload_id:n.id,file:{filename:t,data:o}});if(s.status!=="uploaded")throw new Error(`\u6587\u4EF6\u4E0A\u4F20\u672A\u5C31\u7EEA\uFF0C\u72B6\u6001: ${s.status}`);return n.id}const i=Math.ceil(e.length/F),r=await u.fileUploads.create({mode:"multi_part",filename:t,content_type:a,number_of_parts:i});await T(Array.from({length:i},(o,n)=>n+1),_,async o=>{const n=(o-1)*F,s=Math.min(n+F,e.length),y=e.subarray(n,s),E=new Blob([y],{type:a});await u.fileUploads.send({file_upload_id:r.id,part_number:String(o),file:{filename:t,data:E}})});const l=await u.fileUploads.complete({file_upload_id:r.id});if(l.status!=="uploaded")throw new Error(`\u591A\u6BB5\u6587\u4EF6\u4E0A\u4F20\u672A\u5B8C\u6210\uFF0C\u72B6\u6001: ${l.status}`);return r.id}async function h(u,t){const a=f(t);await c(t);const e=d(t),i=await p(t),{buffer:r,displayName:l,mime:o}=B(t,i,a,e);return m({client:u,displayName:l,contentType:o,fileBuffer:r})}async function A(u,t){await c(t);const a=f(t),e=d(t);if(!e.startsWith("image/"))throw new Error(`\u4E0D\u662F\u56FE\u7247 MIME\uFF08${e}\uFF09\uFF0C\u8BF7\u4F20\u56FE\u7247\u8DEF\u5F84\u6216\u663E\u5F0F\u6307\u5B9A contentType`);const i=await p(t);return m({client:u,displayName:a,contentType:e,fileBuffer:i})}async function C(u,t){const a=f(t);await c(t);const e=d(t);if(!e.startsWith("video/"))throw new Error(`\u4E0D\u662F\u89C6\u9891 MIME\uFF08${e}\uFF09\uFF0C\u8BF7\u4F20\u89C6\u9891\u8DEF\u5F84\u6216\u663E\u5F0F\u6307\u5B9A contentType`);const i=await p(t);return m({client:u,displayName:a,contentType:e,fileBuffer:i})}export{h as uploadFileToNotion,A as uploadImageToNotion,C as uploadVideoToNotion};
package/lib/index.js CHANGED
@@ -1,4 +1 @@
1
- import '@notionhq/client';
2
- export { n } from './utils.js';
3
- export { buildNotionPageWebUrl, getId } from './helpers/page.js';
4
- export { NotionClient } from './notion-client.js';
1
+ import"@notionhq/client";import{n as e}from"./utils.js";import{buildNotionPageWebUrl as m,getId as n}from"./helpers/page.js";import{NotionClient as f}from"./notion-client.js";export{f as NotionClient,m as buildNotionPageWebUrl,n as getId,e as n};
@@ -1 +1 @@
1
- {"version":3,"file":"notion-client.d.ts","sourceRoot":"","sources":["../src/notion-client.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,QAAQ,EACb,KAAK,oBAAoB,EACzB,KAAK,kBAAkB,EACxB,MAAM,kBAAkB,CAAC;AAM1B,UAAU,uBAAuB;IAC/B,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,MAAM,CAAC;IAChB,YAAY,EAAE,OAAO,CAAC;IACtB,KAAK,CAAC,EAAE,QAAQ,CAAC;CAClB;AAED,qBAAa,YAAY;IACvB,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAS;gBAEpB,SAAS,CAAC,EAAE,MAAM;IAQxB,UAAU,CAAC,IAAI,EAAE,oBAAoB;IAIrC,kBAAkB,CAAC,EAAE,EAAE,CAAC,IAAI,EAAE,kBAAkB,KAAK,IAAI,EAAE,YAAY,CAAC,EAAE,MAAM;IAOhF,mBAAmB,CAAC,MAAM,EAAE,uBAAuB;IAmBnD,qBAAqB,CAAC,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM;IAOvD,aAAa,CAAC,OAAO,EAAE,MAAM;IAO7B,cAAc,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM;IAQrD;;;;OAIG;IACG,oBAAoB,CAAC,MAAM,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM;IAiB/D;;;;OAIG;IACG,mBAAmB,CAAC,YAAY,EAAE,MAAM;IAI9C;;OAEG;IACG,qBAAqB,CAAC,MAAM,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM;IAiBhE;;OAEG;IACG,qBAAqB,CAAC,MAAM,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM;CAUjE"}
1
+ {"version":3,"file":"notion-client.d.ts","sourceRoot":"","sources":["../src/notion-client.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,QAAQ,EACb,KAAK,oBAAoB,EACzB,KAAK,kBAAkB,EACxB,MAAM,kBAAkB,CAAC;AAM1B,UAAU,uBAAuB;IAC/B,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,MAAM,CAAC;IAChB,YAAY,EAAE,OAAO,CAAC;IACtB,KAAK,CAAC,EAAE,QAAQ,CAAC;CAClB;AAED,qBAAa,YAAY;IACvB,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAS;gBAEpB,SAAS,CAAC,EAAE,MAAM;IAQxB,UAAU,CAAC,IAAI,EAAE,oBAAoB;IAIrC,kBAAkB,CAAC,EAAE,EAAE,CAAC,IAAI,EAAE,kBAAkB,KAAK,IAAI,EAAE,YAAY,CAAC,EAAE,MAAM;IAehF,mBAAmB,CAAC,MAAM,EAAE,uBAAuB;IAmBnD,qBAAqB,CAAC,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM;IAOvD,aAAa,CAAC,OAAO,EAAE,MAAM;IAO7B,cAAc,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM;IAQrD;;;;OAIG;IACG,oBAAoB,CAAC,MAAM,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM;IAiB/D;;;;OAIG;IACG,mBAAmB,CAAC,YAAY,EAAE,MAAM;IAI9C;;OAEG;IACG,qBAAqB,CAAC,MAAM,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM;IAiBhE;;OAEG;IACG,qBAAqB,CAAC,MAAM,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM;CAUjE"}
@@ -1,120 +1 @@
1
- import { Client } from '@notionhq/client';
2
- import { markdownToBlocks } from '@tryfabric/martian';
3
- import { customFetch } from './helpers/custom-fetch.js';
4
- import { uploadFileToNotion, uploadImageToNotion, uploadVideoToNotion } from './helpers/upload/index.js';
5
-
6
- class NotionClient {
7
- client;
8
- constructor(authToken) {
9
- this.client = new Client({
10
- auth: authToken ?? process.env.NOTION_AUTH_TOKEN,
11
- fetch: customFetch,
12
- timeoutMs: 1e3 * 60 * 10
13
- // 10 分钟超时的时间
14
- });
15
- }
16
- async createPage(args) {
17
- return this.client.pages.create(args);
18
- }
19
- async traverseDataSource(cb, dataSourceId) {
20
- const data_source_id = dataSourceId ?? process.env.NOTION_DATA_SOURCE_ID ?? "";
21
- const data = await this.client.dataSources.query({ data_source_id });
22
- data.results.forEach((item) => cb(item));
23
- }
24
- async appendHeading1Block(params) {
25
- const { blockId, content, color, isToggleable } = params;
26
- const { results } = await this.client.blocks.children.append({
27
- block_id: blockId,
28
- children: [
29
- {
30
- type: "heading_1",
31
- heading_1: {
32
- rich_text: [{ type: "text", text: { content } }],
33
- color,
34
- is_toggleable: isToggleable
35
- }
36
- }
37
- ]
38
- });
39
- return results[0]?.id ?? "";
40
- }
41
- async appendMarkdownToBlock(blockId, markdown) {
42
- await this.client.blocks.children.append({
43
- block_id: blockId,
44
- children: markdownToBlocks(markdown)
45
- });
46
- }
47
- async appendDivider(blockId) {
48
- await this.client.blocks.children.append({
49
- block_id: blockId,
50
- children: [{ type: "divider", divider: {} }]
51
- });
52
- }
53
- async appendMarkdown(pageId, markdown) {
54
- await this.client.pages.updateMarkdown({
55
- page_id: pageId,
56
- type: "insert_content",
57
- insert_content: { content: markdown }
58
- });
59
- }
60
- /**
61
- * 将本地文件经 Notion File Upload API 上传后,作为「文件」块挂到页面正文中。
62
- * @param pageId - 页面 ID
63
- * @param absolutePath - 本地文件路径
64
- */
65
- async uploadFileToPageBody(pageId, absolutePath) {
66
- const fileUploadId = await uploadFileToNotion(this.client, absolutePath);
67
- await this.client.blocks.children.append({
68
- block_id: pageId,
69
- children: [
70
- {
71
- type: "file",
72
- file: {
73
- type: "file_upload",
74
- file_upload: { id: fileUploadId }
75
- }
76
- }
77
- ]
78
- });
79
- }
80
- /**
81
- * 上传本地图片到 Notion(数据库中附件属性中需要使用到这个函数)
82
- * @param absolutePath - 本地图片路径
83
- * @returns - 文件上传 ID
84
- */
85
- async uploadImageToNotion(absolutePath) {
86
- return uploadImageToNotion(this.client, absolutePath);
87
- }
88
- /**
89
- * 上传本地图片并在页面正文插入「图片」块(`image`)。
90
- */
91
- async uploadImageToPageBody(pageId, absolutePath) {
92
- const fileUploadId = await uploadImageToNotion(this.client, absolutePath);
93
- await this.client.blocks.children.append({
94
- block_id: pageId,
95
- children: [
96
- {
97
- type: "image",
98
- image: {
99
- type: "file_upload",
100
- file_upload: { id: fileUploadId }
101
- }
102
- }
103
- ]
104
- });
105
- }
106
- /**
107
- * 上传本地视频并在页面正文插入「视频」块(`video`)。
108
- */
109
- async uploadVideoToPageBody(pageId, absolutePath) {
110
- const fileUploadId = await uploadVideoToNotion(this.client, absolutePath);
111
- await this.client.blocks.children.append({
112
- block_id: pageId,
113
- children: [
114
- { type: "video", video: { type: "file_upload", file_upload: { id: fileUploadId } } }
115
- ]
116
- });
117
- }
118
- }
119
-
120
- export { NotionClient };
1
+ import{Client as l}from"@notionhq/client";import{markdownToBlocks as d}from"@tryfabric/martian";import{customFetch as s}from"./helpers/custom-fetch.js";import{uploadFileToNotion as r,uploadImageToNotion as c,uploadVideoToNotion as p}from"./helpers/upload/index.js";class h{client;constructor(e){this.client=new l({auth:e??process.env.NOTION_AUTH_TOKEN,fetch:s,timeoutMs:1e3*60*10})}async createPage(e){return this.client.pages.create(e)}async traverseDataSource(e,i){const t=i??process.env.NOTION_DATA_SOURCE_ID??"";let o;do{const a=await this.client.dataSources.query({data_source_id:t,start_cursor:o});a.results.forEach(n=>e(n)),o=a.next_cursor??void 0}while(o)}async appendHeading1Block(e){const{blockId:i,content:t,color:o,isToggleable:a}=e,{results:n}=await this.client.blocks.children.append({block_id:i,children:[{type:"heading_1",heading_1:{rich_text:[{type:"text",text:{content:t}}],color:o,is_toggleable:a}}]});return n[0]?.id??""}async appendMarkdownToBlock(e,i){await this.client.blocks.children.append({block_id:e,children:d(i)})}async appendDivider(e){await this.client.blocks.children.append({block_id:e,children:[{type:"divider",divider:{}}]})}async appendMarkdown(e,i){await this.client.pages.updateMarkdown({page_id:e,type:"insert_content",insert_content:{content:i}})}async uploadFileToPageBody(e,i){const t=await r(this.client,i);await this.client.blocks.children.append({block_id:e,children:[{type:"file",file:{type:"file_upload",file_upload:{id:t}}}]})}async uploadImageToNotion(e){return c(this.client,e)}async uploadImageToPageBody(e,i){const t=await c(this.client,i);await this.client.blocks.children.append({block_id:e,children:[{type:"image",image:{type:"file_upload",file_upload:{id:t}}}]})}async uploadVideoToPageBody(e,i){const t=await p(this.client,i);await this.client.blocks.children.append({block_id:e,children:[{type:"video",video:{type:"file_upload",file_upload:{id:t}}}]})}}export{h as NotionClient};
package/lib/utils.js CHANGED
@@ -1,5 +1 @@
1
- function n(num) {
2
- return num ?? null;
3
- }
4
-
5
- export { n };
1
+ function r(n){return n??null}export{r as n};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@secret-momo/notion",
3
- "version": "2.2.0",
3
+ "version": "2.2.2",
4
4
  "files": [
5
5
  "lib"
6
6
  ],