@kamilio/wire 0.1.74 → 0.1.75
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/node_modules/provider-asana/dist/asana-project.d.ts +10 -1
- package/node_modules/provider-asana/dist/asana-project.d.ts.map +1 -1
- package/node_modules/provider-asana/dist/asana-task.d.ts +10 -1
- package/node_modules/provider-asana/dist/asana-task.d.ts.map +1 -1
- package/node_modules/provider-asana/dist/index.d.ts +20 -2
- package/node_modules/provider-asana/dist/index.d.ts.map +1 -1
- package/node_modules/provider-chatgpt/dist/chatgpt.d.ts +10 -1
- package/node_modules/provider-chatgpt/dist/chatgpt.d.ts.map +1 -1
- package/node_modules/provider-chatgpt/dist/index.d.ts +10 -1
- package/node_modules/provider-chatgpt/dist/index.d.ts.map +1 -1
- package/node_modules/provider-gmail/dist/gmail.d.ts +10 -1
- package/node_modules/provider-gmail/dist/gmail.d.ts.map +1 -1
- package/node_modules/provider-gmail/dist/index.d.ts +10 -1
- package/node_modules/provider-gmail/dist/index.d.ts.map +1 -1
- package/node_modules/provider-google-docs/dist/google-docs.d.ts +10 -1
- package/node_modules/provider-google-docs/dist/google-docs.d.ts.map +1 -1
- package/node_modules/provider-google-docs/dist/google-forms.d.ts +10 -1
- package/node_modules/provider-google-docs/dist/google-forms.d.ts.map +1 -1
- package/node_modules/provider-google-docs/dist/index.d.ts +20 -2
- package/node_modules/provider-google-docs/dist/index.d.ts.map +1 -1
- package/node_modules/provider-lattice/dist/index.d.ts +20 -2
- package/node_modules/provider-lattice/dist/index.d.ts.map +1 -1
- package/node_modules/provider-notion/dist/index.d.ts +10 -1
- package/node_modules/provider-notion/dist/index.d.ts.map +1 -1
- package/node_modules/provider-notion/dist/notion-sync.d.ts +5 -4
- package/node_modules/provider-notion/dist/notion-sync.d.ts.map +1 -1
- package/node_modules/provider-notion/dist/notion-sync.js +180 -11
- package/node_modules/provider-notion/dist/notion-sync.js.map +1 -1
- package/node_modules/provider-notion/dist/notion.d.ts +10 -1
- package/node_modules/provider-notion/dist/notion.d.ts.map +1 -1
- package/node_modules/provider-notion/dist/notion.js +2 -1
- package/node_modules/provider-notion/dist/notion.js.map +1 -1
- package/node_modules/provider-notion/src/notion-sync.ts +163 -12
- package/node_modules/provider-notion/src/notion.ts +2 -1
- package/node_modules/provider-slack/dist/index.d.ts +10 -1
- package/node_modules/provider-slack/dist/index.d.ts.map +1 -1
- package/node_modules/provider-slack/dist/slack.d.ts +10 -1
- package/node_modules/provider-slack/dist/slack.d.ts.map +1 -1
- package/node_modules/provider-slack/dist/slack.js +18 -3
- package/node_modules/provider-slack/dist/slack.js.map +1 -1
- package/node_modules/provider-slack/src/slack.ts +16 -3
- package/node_modules/provider-zoom/dist/index.d.ts +10 -1
- package/node_modules/provider-zoom/dist/index.d.ts.map +1 -1
- package/node_modules/provider-zoom/dist/zoom-hub.d.ts +10 -1
- package/node_modules/provider-zoom/dist/zoom-hub.d.ts.map +1 -1
- package/node_modules/wire-core/dist/core/model.d.ts +2 -1
- package/node_modules/wire-core/dist/core/model.d.ts.map +1 -1
- package/node_modules/wire-core/dist/operations.d.ts.map +1 -1
- package/node_modules/wire-core/dist/operations.js +11 -3
- package/node_modules/wire-core/dist/operations.js.map +1 -1
- package/node_modules/wire-core/src/core/model.ts +2 -1
- package/node_modules/wire-core/src/operations.ts +8 -4
- package/package.json +1 -1
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
-
import { posix } from "node:path";
|
|
2
|
+
import { basename, dirname, extname, posix, resolve } from "node:path";
|
|
3
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
3
4
|
|
|
4
|
-
import type { DownloadedDocument, DownloadWriter, FetchedDocument, JsonObject, JsonValue, Source, SynchronizedDocument, UploadedDocument } from "wire-core";
|
|
5
|
+
import type { AddMarkdown, DownloadedDocument, DownloadWriter, FetchedDocument, JsonObject, JsonValue, Source, SynchronizedDocument, UploadedDocument } from "wire-core";
|
|
5
6
|
import { WireMergeConflict, markdownFilename, stableJsonCompact, stableJsonPretty } from "wire-core";
|
|
6
7
|
import type { RuntimeCapabilities } from "wire-core";
|
|
7
8
|
|
|
@@ -11,6 +12,8 @@ export type NotionTree = Readonly<{ id: string; block: JsonObject; children: rea
|
|
|
11
12
|
export type NotionOperation = Readonly<{ pointer: JsonObject; path: readonly JsonValue[]; command: string; args: JsonValue }>;
|
|
12
13
|
export type NotionSidecarBlock = Readonly<{ id: string; path: readonly number[]; type: string; hash: string; snapshot: JsonObject }>;
|
|
13
14
|
export type NotionDiffSummary = Readonly<{ inserted: number; updated: number; deleted: number; moved: number }>;
|
|
15
|
+
type HtmlAsset = { source: string; path: string; hash: string };
|
|
16
|
+
type HtmlEmbed = { source: string; block_id: string; space_id: string };
|
|
14
17
|
type UserMentions = Readonly<Record<string, string>>;
|
|
15
18
|
type EmailMentions = Record<string, string>;
|
|
16
19
|
|
|
@@ -253,7 +256,14 @@ function baseUserMentions(base: JsonObject): UserMentions | undefined {
|
|
|
253
256
|
}
|
|
254
257
|
|
|
255
258
|
function notionData(pageId: string, markdown: string, tree: NotionTree, mentions: UserMentions | undefined, emailMentions: EmailMentions = {}): JsonObject {
|
|
256
|
-
|
|
259
|
+
const embeds: HtmlEmbed[] = [];
|
|
260
|
+
const visit = (node: NotionTree) => {
|
|
261
|
+
const source = object(node.block["properties"] ?? {})["source"];
|
|
262
|
+
if (node.block["type"] === "embed" && source !== undefined && /^attachment:[a-f0-9-]{36}:[^/\\]+\.html?$/i.test(richTextText(source))) embeds.push({ source: richTextText(source), block_id: node.id, space_id: node.block["space_id"] as string });
|
|
263
|
+
node.children.forEach(visit);
|
|
264
|
+
};
|
|
265
|
+
visit(tree);
|
|
266
|
+
return { ...(embeds.length === 0 ? {} : { html_embeds: embeds }), page_id: pageId, markdown, blocks: sidecarBlocksFromNotionTree(tree), ...(mentions === undefined ? {} : { user_mentions: mentions }), ...(Object.keys(emailMentions).length === 0 ? {} : { email_mentions: emailMentions }) };
|
|
257
267
|
}
|
|
258
268
|
|
|
259
269
|
function lineIndent(line: string): number { return Math.floor(line.match(/^ */)![0].length / 2); }
|
|
@@ -288,7 +298,7 @@ function isTableSeparator(row: readonly string[]): boolean {
|
|
|
288
298
|
}
|
|
289
299
|
|
|
290
300
|
function markdownBlockStart(stripped: string): boolean {
|
|
291
|
-
return /^(#{1,6})\s+|^[-*]\s+|^\d+\.\s+|^-\s+\[[ xX]\]\s+|^```|^---$|^!\[
|
|
301
|
+
return /^(#{1,6})\s+|^[-*]\s+|^\d+\.\s+|^-\s+\[[ xX]\]\s+|^```|^---$|^!\[|^>|^\||^:::|^<iframe\s/.test(stripped);
|
|
292
302
|
}
|
|
293
303
|
|
|
294
304
|
function escapeBlockMarkdownLine(line: string): string {
|
|
@@ -364,6 +374,28 @@ function parseLines(lines: readonly string[], baseIndent = 0): NotionBlock[] {
|
|
|
364
374
|
index += 1;
|
|
365
375
|
continue;
|
|
366
376
|
}
|
|
377
|
+
if (stripped.startsWith("<iframe ")) {
|
|
378
|
+
const iframe = /^<iframe\s+(.+?)><\/iframe>$/.exec(stripped);
|
|
379
|
+
if (iframe === null) throw new Error("HTML embeds require a single-line iframe with src, width and height attributes");
|
|
380
|
+
const attributes: Record<string, string> = {};
|
|
381
|
+
const rest = iframe[1]!.replace(/([\w-]+)=(?:"([^"]*)"|'([^']*)')/g, (_match, name: string, double: string | undefined, single: string) => {
|
|
382
|
+
if (!["src", "width", "height"].includes(name) || attributes[name] !== undefined) throw new Error(`Unsupported iframe attribute: ${name}`);
|
|
383
|
+
attributes[name] = unescapeHtml(double ?? single);
|
|
384
|
+
return "";
|
|
385
|
+
});
|
|
386
|
+
if (rest.trim() !== "" || !attributes["src"]) throw new Error("HTML embeds require a src attribute");
|
|
387
|
+
const format: Record<string, JsonValue> = {};
|
|
388
|
+
for (const dimension of ["width", "height"]) {
|
|
389
|
+
const value = attributes[dimension];
|
|
390
|
+
if (value === undefined) continue;
|
|
391
|
+
if (dimension === "width" && value === "100%") format["block_page_width"] = true;
|
|
392
|
+
else if (/^[1-9]\d*$/.test(value)) format[`block_${dimension}`] = Number(value);
|
|
393
|
+
else throw new Error(`Unsupported iframe ${dimension}: ${value}`);
|
|
394
|
+
}
|
|
395
|
+
blocks.push({ type: "embed", content: "", properties: { source: attributes["src"]!, format }, rich_text: [], indent });
|
|
396
|
+
index += 1;
|
|
397
|
+
continue;
|
|
398
|
+
}
|
|
367
399
|
const image = stripped.startsWith("![") ? markdownLink(stripped.slice(1)) : null;
|
|
368
400
|
if (image !== null && image.length + 1 === stripped.length) {
|
|
369
401
|
blocks.push({ type: "image", content: "", properties: { alt_text: unescapeInlineMarkdown(image.label), source: decodeURI(image.url) }, rich_text: [], indent });
|
|
@@ -533,6 +565,10 @@ function parserBlockToNotionBlock(block: NotionBlock, id: string, parentId: stri
|
|
|
533
565
|
if (block.type === "toggle") return { ...base, type: "text", properties: { title: block.rich_text }, format: { toggleable: true } };
|
|
534
566
|
if (block.type === "code") return { ...base, properties: { title: [[block.content]], language: [[block.properties["language"]!]] } };
|
|
535
567
|
if (block.type === "to_do") return { ...base, properties: { title: block.rich_text, checked: [[block.properties["checked"] === true ? "Yes" : "No"]] } };
|
|
568
|
+
if (block.type === "embed") {
|
|
569
|
+
const source = block.properties["source"] as string;
|
|
570
|
+
return { ...base, properties: { source: [[source]] }, format: block.properties["format"]!, ...(source.startsWith("attachment:") ? { file_ids: [source.split(":")[1]!] } : {}) };
|
|
571
|
+
}
|
|
536
572
|
if (block.type === "image") return { ...base, properties: { source: [[block.properties["source"]!]], alt_text: [[block.properties["alt_text"]!]], ...(block.properties["caption"] === undefined ? {} : { caption: block.properties["caption"]! }) } };
|
|
537
573
|
if (block.type === "table") return { ...base, properties: {}, format: { table_block_column_order: columnOrder ?? block.properties["column_ids"]!, table_block_column_header: block.properties["has_header"]!, table_block_row_header: block.properties["has_row_header"]! } };
|
|
538
574
|
if (block.type === "table_row") return { ...base, properties: tableRowCells(block, columnOrder) };
|
|
@@ -575,6 +611,10 @@ export function buildNotionCreateOperations(blocks: readonly NotionBlock[], page
|
|
|
575
611
|
return { operations, topLevelIds };
|
|
576
612
|
}
|
|
577
613
|
|
|
614
|
+
function embedDimensions(format: JsonObject): JsonObject {
|
|
615
|
+
return Object.fromEntries(Object.entries(format).filter(([key, value]) => ["block_width", "block_height"].includes(key) || key === "block_page_width" && value === true));
|
|
616
|
+
}
|
|
617
|
+
|
|
578
618
|
function canonicalBlock(value: JsonObject, columnOrder?: readonly string[]): JsonObject {
|
|
579
619
|
const type = value["type"] as string;
|
|
580
620
|
if (type === "text" && object(value["format"] ?? {})["toggleable"] === true) return { type: "toggle", title: normalizeRichText(object(value["properties"]!)["title"]!) };
|
|
@@ -582,6 +622,7 @@ function canonicalBlock(value: JsonObject, columnOrder?: readonly string[]): Jso
|
|
|
582
622
|
if (type === "to_do") return { type, title: normalizeRichText(object(value["properties"]!)["title"]!), checked: object(value["properties"]!)["checked"] ?? [["No"]] };
|
|
583
623
|
if (type === "table") return { type, column_count: (object(value["format"]!)["table_block_column_order"] as JsonValue[]).length };
|
|
584
624
|
if (type === "table_row") return { type, cells: columnOrder!.map((column) => normalizeRichText(object(value["properties"]!)[column] ?? [])) };
|
|
625
|
+
if (type === "embed") return { type, source: object(value["properties"] ?? {})["source"] ?? null, format: embedDimensions(object(value["format"] ?? {})) };
|
|
585
626
|
if (type === "image") return { type, source: object(value["properties"]!)["source"]!, alt_text: object(value["properties"]!)["alt_text"] ?? [[""]], caption: object(value["properties"]!)["caption"] ?? null };
|
|
586
627
|
if (["divider", "column_list", "transclusion_container"].includes(type)) return { type };
|
|
587
628
|
if (type === "column") return { type, column_ratio: object(value["format"] ?? {})["column_ratio"] ?? null };
|
|
@@ -600,6 +641,7 @@ function canonicalParserBlock(block: NotionBlock, columnOrder?: readonly string[
|
|
|
600
641
|
const cells = tableRowCells(block, columnOrder);
|
|
601
642
|
return { type: "table_row", cells: columnOrder!.map((column) => normalizeRichText(cells[column] ?? [])) };
|
|
602
643
|
}
|
|
644
|
+
if (block.type === "embed") return { type: "embed", source: [[block.properties["source"]!]], format: block.properties["format"]! };
|
|
603
645
|
if (block.type === "image") return { type: "image", source: [[block.properties["source"]!]], alt_text: [[block.properties["alt_text"]!]], caption: block.properties["caption"] ?? null };
|
|
604
646
|
if (block.type === "page" || block.type === "equation") return { type: block.type, title: normalizeRichText(block.rich_text) };
|
|
605
647
|
if (block.type === "column") return { type: "column", column_ratio: object(block.properties["format"] ?? {})["column_ratio"] ?? null };
|
|
@@ -659,7 +701,8 @@ function emitUpdates(remote: JsonObject, local: NotionBlock, blockId: string, sp
|
|
|
659
701
|
} else {
|
|
660
702
|
for (const key of Object.keys(nextProperties)) if (compact(remoteProperties[key] ?? null) !== compact(nextProperties[key]!)) operations.push({ pointer: pointer(blockId, spaceId), path: ["properties", key], command: "updateBlockPropertyValue", args: { primitiveOp: { command: "set", args: nextProperties[key]! } } });
|
|
661
703
|
}
|
|
662
|
-
|
|
704
|
+
if (local.type === "embed" && compact(remote["file_ids"] ?? []) !== compact(args["file_ids"] ?? [])) operations.push({ pointer: pointer(blockId, spaceId), path: ["file_ids"], command: "set", args: [...new Set([...(remote["file_ids"] as string[] | undefined ?? []), ...(args["file_ids"] as string[] | undefined ?? [])])] });
|
|
705
|
+
const nextFormat = local.type === "embed" ? { ...Object.fromEntries(Object.entries(object(remote["format"] ?? {})).filter(([key]) => !["block_width", "block_height", "block_page_width"].includes(key))), ...object(args["format"] ?? {}) } : object(args["format"] ?? {});
|
|
663
706
|
if ((typeChanged || args["format"] !== undefined || remote["format"] !== undefined) && compact(remote["format"] ?? {}) !== compact(nextFormat)) operations.push({ pointer: pointer(blockId, spaceId), path: ["format"], command: "set", args: nextFormat });
|
|
664
707
|
return operations;
|
|
665
708
|
}
|
|
@@ -811,6 +854,10 @@ function renderNode(tree: NotionTree, indent: number, parentType = "", download
|
|
|
811
854
|
const language = richTextText(properties["language"]!).replace("Plain Text", "");
|
|
812
855
|
return [`${prefix}${fence}${language}`, ...code.split("\n").map((line) => `${prefix}${line}`), `${prefix}${fence}`];
|
|
813
856
|
}
|
|
857
|
+
if (type === "embed" && properties["source"] !== undefined && /^attachment:[a-f0-9-]{36}:[^/\\]+\.html?$/i.test(richTextText(properties["source"]!))) {
|
|
858
|
+
const width = format["block_page_width"] === true ? "100%" : format["block_width"];
|
|
859
|
+
return [`${prefix}<iframe src="${escapeHtml(richTextText(properties["source"]!))}"${width === undefined ? "" : ` width="${width}"`}${format["block_height"] === undefined ? "" : ` height="${format["block_height"]}"`}></iframe>`];
|
|
860
|
+
}
|
|
814
861
|
if (type === "image") return [`${prefix}![${escapeInlineMarkdown(richTextText(properties["alt_text"] ?? []))}](${encodeURI(richTextText(properties["source"]!))})`];
|
|
815
862
|
if (type === "equation") return [`${prefix}:::equation`, ...title.split("\n").map((line) => `${prefix}${line}`), `${prefix}:::`];
|
|
816
863
|
if (type === "page") return [`${prefix}:::page`, `${prefix}${title}`, ...children(), `${prefix}:::`];
|
|
@@ -1108,7 +1155,7 @@ export async function fetchNotionDocument(runtime: RuntimeCapabilities, url: str
|
|
|
1108
1155
|
return notionDocument(source.identifier, tree, undefined, {}, comments);
|
|
1109
1156
|
}
|
|
1110
1157
|
|
|
1111
|
-
export async function downloadNotionDirectory(runtime: RuntimeCapabilities, url: string, source: Source, write: DownloadWriter): Promise<DownloadedDocument | null> {
|
|
1158
|
+
export async function downloadNotionDirectory(runtime: RuntimeCapabilities, url: string, source: Source, write: DownloadWriter, _addMarkdown?: AddMarkdown, destination?: string): Promise<DownloadedDocument | null> {
|
|
1112
1159
|
const cookies = await runtime.cookies.loadSaved("notion");
|
|
1113
1160
|
if (cookies === null) throw notionAuthError();
|
|
1114
1161
|
const cookie = cookies.map(({ name, value }) => `${name}=${value}`).join("; ");
|
|
@@ -1194,12 +1241,87 @@ export async function downloadNotionDirectory(runtime: RuntimeCapabilities, url:
|
|
|
1194
1241
|
};
|
|
1195
1242
|
const tree = await build(id, true);
|
|
1196
1243
|
const markdown = renderNotionTreeToMarkdown(tree, undefined, {}, true) + renderComments(id, threads, comments, users);
|
|
1197
|
-
|
|
1244
|
+
const document = { title: richTextText(object(page["properties"]!)["title"]!), markdown, data: notionData(id, markdown, tree, undefined) };
|
|
1245
|
+
return { path, ...destination === undefined ? document : await materializeNotionDocument(runtime, document, resolve(destination, path)) };
|
|
1198
1246
|
};
|
|
1199
1247
|
return exportPage(root, directoryName(root));
|
|
1200
1248
|
}
|
|
1201
1249
|
|
|
1202
|
-
|
|
1250
|
+
function replaceIframeSources(markdown: string, sources: ReadonlyMap<string, string>): string {
|
|
1251
|
+
let fence: string | undefined;
|
|
1252
|
+
return markdown.split("\n").map((line) => {
|
|
1253
|
+
const marker = /^ *(`{3,})/.exec(line)?.[1];
|
|
1254
|
+
if (marker !== undefined) {
|
|
1255
|
+
if (fence === undefined) fence = marker;
|
|
1256
|
+
else if (marker.length >= fence.length) fence = undefined;
|
|
1257
|
+
return line;
|
|
1258
|
+
}
|
|
1259
|
+
if (fence !== undefined) return line;
|
|
1260
|
+
return line.replace(/^( *<iframe\s+[^\n]*?src=)(["'])(.*?)\2/, (match, prefix: string, quote: string, source: string) => {
|
|
1261
|
+
const replacement = sources.get(unescapeHtml(source));
|
|
1262
|
+
return replacement === undefined ? match : `${prefix}${quote}${escapeHtml(replacement)}${quote}`;
|
|
1263
|
+
});
|
|
1264
|
+
}).join("\n");
|
|
1265
|
+
}
|
|
1266
|
+
|
|
1267
|
+
export async function materializeNotionDocument(runtime: RuntimeCapabilities, document: FetchedDocument, markdownPath: string, previous?: JsonValue): Promise<FetchedDocument> {
|
|
1268
|
+
const data = object(document.data);
|
|
1269
|
+
const embeds = data["html_embeds"] as HtmlEmbed[] | undefined;
|
|
1270
|
+
if (embeds === undefined || embeds.length === 0) return document;
|
|
1271
|
+
const known = data["html_assets"] as HtmlAsset[] | undefined ?? (previous === undefined ? [] : object(previous)["html_assets"] as HtmlAsset[] | undefined ?? []);
|
|
1272
|
+
const assets: HtmlAsset[] = [];
|
|
1273
|
+
const sources = new Map<string, string>();
|
|
1274
|
+
for (const embed of embeds) {
|
|
1275
|
+
let asset = known.find((item) => item.source === embed.source);
|
|
1276
|
+
if (asset === undefined || !await runtime.filesystem.exists(asset.path)) {
|
|
1277
|
+
const cookies = await runtime.cookies.loadSaved("notion");
|
|
1278
|
+
if (cookies === null) throw notionAuthError();
|
|
1279
|
+
const cookie = cookies.map((value) => `${value.name}=${value.value}`).join("; ");
|
|
1280
|
+
const signed = await notionPost(runtime, "getSignedFileUrls", cookie, { urls: [{ url: embed.source, permissionRecord: { table: "block", id: embed.block_id, spaceId: embed.space_id } }] }, {});
|
|
1281
|
+
const url = (signed["signedUrls"] as string[])[0]!;
|
|
1282
|
+
const target = new URL(url);
|
|
1283
|
+
if (target.protocol !== "https:" || target.hostname !== "file.notion.so") throw new Error("Unexpected Notion HTML download host");
|
|
1284
|
+
const response = await runtime.http.request(url, { headers: { cookie } });
|
|
1285
|
+
if (!response.ok) throw new Error(`Notion HTML download failed: ${response.status}`);
|
|
1286
|
+
const contents = await response.text();
|
|
1287
|
+
const path = asset?.path ?? resolve(dirname(markdownPath), `${basename(markdownPath, extname(markdownPath))}.assets`, `${embed.source.split(":")[1]!}.html`);
|
|
1288
|
+
if (await runtime.filesystem.exists(path) && await runtime.filesystem.readText(path) !== contents) throw new Error(`Local HTML edits exist: ${path}`);
|
|
1289
|
+
await runtime.filesystem.writeText(path, contents);
|
|
1290
|
+
asset = { source: embed.source, path, hash: hash(contents) };
|
|
1291
|
+
}
|
|
1292
|
+
assets.push(asset);
|
|
1293
|
+
sources.set(embed.source, pathToFileURL(asset.path).href);
|
|
1294
|
+
}
|
|
1295
|
+
const remoteMarkdown = data["remote_markdown"] as string | undefined ?? document.markdown;
|
|
1296
|
+
const markdown = replaceIframeSources(remoteMarkdown, sources);
|
|
1297
|
+
return { ...document, markdown, data: { ...data, markdown, remote_markdown: remoteMarkdown, html_assets: assets } };
|
|
1298
|
+
}
|
|
1299
|
+
|
|
1300
|
+
async function uploadHtmlEmbeds(runtime: RuntimeCapabilities, blocks: readonly NotionBlock[], markdownPath: string, pageId: string, spaceId: string, cookie: string, headers: HeadersInit, assets: HtmlAsset[]): Promise<void> {
|
|
1301
|
+
for (const block of blocks) {
|
|
1302
|
+
const source = block.properties["source"] as string | undefined;
|
|
1303
|
+
if (block.type !== "embed" || source === undefined || source.startsWith("attachment:") || /^https?:/.test(source)) continue;
|
|
1304
|
+
const path = source.startsWith("file:") ? fileURLToPath(new URL(source)) : resolve(dirname(markdownPath), source);
|
|
1305
|
+
if (!/\.html?$/i.test(path)) throw new Error(`HTML embed must reference an HTML file: ${path}`);
|
|
1306
|
+
const contents = await runtime.filesystem.readText(path);
|
|
1307
|
+
const uploaded = assets.find((asset) => asset.path === path && asset.hash === hash(contents));
|
|
1308
|
+
if (uploaded !== undefined) {
|
|
1309
|
+
(block.properties as Record<string, JsonValue>)["source"] = uploaded.source;
|
|
1310
|
+
continue;
|
|
1311
|
+
}
|
|
1312
|
+
const upload = await notionPost(runtime, "getUploadFileUrl", cookie, { bucket: "secure", contentType: "text/html", name: basename(path), record: { table: "block", id: pageId, spaceId } }, headers);
|
|
1313
|
+
const body = new FormData();
|
|
1314
|
+
for (const [key, value] of Object.entries(object(upload["fields"]!))) body.append(key, text(value));
|
|
1315
|
+
body.append("file", new Blob([contents], { type: "text/html" }), basename(path));
|
|
1316
|
+
const response = await runtime.http.request(text(upload["signedUploadPostUrl"]!), { method: "POST", headers: upload["postHeaders"] as Record<string, string>, body });
|
|
1317
|
+
if (!response.ok) throw new Error(`Notion HTML upload failed: ${response.status}`);
|
|
1318
|
+
const uploadedSource = text(upload["url"]!);
|
|
1319
|
+
(block.properties as Record<string, JsonValue>)["source"] = uploadedSource;
|
|
1320
|
+
assets.push({ source: uploadedSource, path, hash: hash(contents) });
|
|
1321
|
+
}
|
|
1322
|
+
}
|
|
1323
|
+
|
|
1324
|
+
export async function uploadNotionDocument(runtime: RuntimeCapabilities, markdown: string, markdownPath: string): Promise<UploadedDocument> {
|
|
1203
1325
|
const split = splitTitle(withoutComments(markdown));
|
|
1204
1326
|
if (split.title === "") throw new Error("Markdown document requires a first heading");
|
|
1205
1327
|
const cookies = await runtime.cookies.loadSaved("notion");
|
|
@@ -1237,9 +1359,15 @@ export async function uploadNotionDocument(runtime: RuntimeCapabilities, markdow
|
|
|
1237
1359
|
},
|
|
1238
1360
|
};
|
|
1239
1361
|
const localBlocks = parseNotionMarkdown(split.body);
|
|
1362
|
+
const assets: HtmlAsset[] = [];
|
|
1363
|
+
const hasEmbeds = localBlocks.some((block) => block.type === "embed" && block.properties["source"] !== undefined);
|
|
1364
|
+
if (hasEmbeds) {
|
|
1365
|
+
await notionPost(runtime, "saveTransactionsFanout", cookie, { requestId: randomUUID(), transactions: [{ id: randomUUID(), spaceId, operations: [pageOperation] }] }, headers);
|
|
1366
|
+
await uploadHtmlEmbeds(runtime, localBlocks, markdownPath, pageId, spaceId, cookie, headers, assets);
|
|
1367
|
+
}
|
|
1240
1368
|
const emailMentions: EmailMentions = {};
|
|
1241
1369
|
await resolveNotionEmailMentions(runtime, localBlocks, cookie, spaceId, headers, emailMentions);
|
|
1242
|
-
const operations = [pageOperation, ...buildNotionCreateOperations(localBlocks, pageId, spaceId, userId, currentTime).operations];
|
|
1370
|
+
const operations = [...(hasEmbeds ? [] : [pageOperation]), ...buildNotionCreateOperations(localBlocks, pageId, spaceId, userId, currentTime).operations];
|
|
1243
1371
|
await notionPost(runtime, "saveTransactionsFanout", cookie, { requestId: randomUUID(), transactions: [{ id: randomUUID(), spaceId, operations }] }, headers);
|
|
1244
1372
|
const pageTree: NotionTree = {
|
|
1245
1373
|
id: pageId,
|
|
@@ -1248,7 +1376,8 @@ export async function uploadNotionDocument(runtime: RuntimeCapabilities, markdow
|
|
|
1248
1376
|
};
|
|
1249
1377
|
const output = renderNotionTreeToMarkdown(pageTree, undefined, emailMentions);
|
|
1250
1378
|
const slug = split.title.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
|
|
1251
|
-
|
|
1379
|
+
const document = await materializeNotionDocument(runtime, { title: split.title, markdown: output, data: { ...notionData(compactPageId, output, pageTree, undefined, emailMentions), html_assets: assets } }, markdownPath);
|
|
1380
|
+
return { ...document, url: slug === "" ? `https://www.notion.so/${compactPageId}` : `https://www.notion.so/${slug}-${compactPageId}` };
|
|
1252
1381
|
}
|
|
1253
1382
|
|
|
1254
1383
|
function splitTitle(markdown: string): Readonly<{ title: string; body: string }> {
|
|
@@ -1259,13 +1388,31 @@ function splitTitle(markdown: string): Readonly<{ title: string; body: string }>
|
|
|
1259
1388
|
return { title: "", body: markdown };
|
|
1260
1389
|
}
|
|
1261
1390
|
|
|
1262
|
-
export async function synchronizeNotionDocument(runtime: RuntimeCapabilities, url: string, source: Source, base: JsonValue, markdown: string,
|
|
1391
|
+
export async function synchronizeNotionDocument(runtime: RuntimeCapabilities, url: string, source: Source, base: JsonValue, markdown: string, markdownPath: string, observeRemote?: (remote: FetchedDocument) => void | Promise<void>, requireConditionalWrite = false): Promise<SynchronizedDocument> {
|
|
1392
|
+
const data = object(base);
|
|
1393
|
+
const assets = [...(data["html_assets"] as HtmlAsset[] | undefined ?? [])];
|
|
1394
|
+
const sources = new Map<string, string>();
|
|
1395
|
+
for (const block of parseNotionMarkdown(splitTitle(withoutComments(markdown)).body)) {
|
|
1396
|
+
const src = block.properties["source"] as string | undefined;
|
|
1397
|
+
if (block.type !== "embed" || src === undefined || src.startsWith("attachment:") || /^https?:/.test(src)) continue;
|
|
1398
|
+
const path = src.startsWith("file:") ? fileURLToPath(src) : resolve(dirname(markdownPath), src);
|
|
1399
|
+
const digest = hash(await runtime.filesystem.readText(path));
|
|
1400
|
+
const asset = assets.find((item) => item.path === path && item.hash === digest);
|
|
1401
|
+
sources.set(src, asset?.source ?? `${pathToFileURL(path).href}#${digest}`);
|
|
1402
|
+
}
|
|
1403
|
+
const remoteBase = { ...data, markdown: data["remote_markdown"] ?? data["markdown"]! };
|
|
1404
|
+
const result = await synchronizeNotionContent(runtime, url, source, remoteBase, replaceIframeSources(markdown, sources), markdownPath, assets, async (remote) => { await observeRemote?.(await materializeNotionDocument(runtime, { ...remote, data: { ...object(remote.data), html_assets: assets } }, markdownPath)); }, requireConditionalWrite);
|
|
1405
|
+
return { ...await materializeNotionDocument(runtime, { ...result, data: { ...object(result.data), html_assets: assets } }, markdownPath), wroteRemote: result.wroteRemote! };
|
|
1406
|
+
}
|
|
1407
|
+
|
|
1408
|
+
async function synchronizeNotionContent(runtime: RuntimeCapabilities, url: string, source: Source, base: JsonValue, markdown: string, markdownPath: string, assets: HtmlAsset[], observeRemote: (remote: FetchedDocument) => Promise<void>, requireConditionalWrite: boolean): Promise<SynchronizedDocument> {
|
|
1263
1409
|
const remote = await fetchTree(runtime, url, source);
|
|
1410
|
+
let expectedRemote = remote.tree;
|
|
1264
1411
|
const save = async (operations: readonly NotionOperation[]) => {
|
|
1265
1412
|
if (operations.length === 0) return;
|
|
1266
1413
|
if (requireConditionalWrite) {
|
|
1267
1414
|
const latest = await fetchTree(runtime, url, source);
|
|
1268
|
-
if (compact(latest.tree) !== compact(
|
|
1415
|
+
if (compact(latest.tree) !== compact(expectedRemote)) {
|
|
1269
1416
|
await observeRemote?.(notionDocument(latest.tree.id, latest.tree, mentions, emailMentions, latest.comments));
|
|
1270
1417
|
throw new WireMergeConflict("Notion changed while preparing the save");
|
|
1271
1418
|
}
|
|
@@ -1318,6 +1465,10 @@ export async function synchronizeNotionDocument(runtime: RuntimeCapabilities, ur
|
|
|
1318
1465
|
}
|
|
1319
1466
|
const localBody = mentions === undefined ? split.body : hydrateUserMentions(split.body, mentions);
|
|
1320
1467
|
const localBlocks = parseNotionMarkdown(localBody);
|
|
1468
|
+
const assetCount = assets.length;
|
|
1469
|
+
await uploadHtmlEmbeds(runtime, localBlocks, markdownPath, remote.tree.id, remote.spaceId, remote.cookie, remote.headers, assets);
|
|
1470
|
+
const uploads = assets.slice(assetCount);
|
|
1471
|
+
if (uploads.length > 0) expectedRemote = { ...remote.tree, block: { ...remote.tree.block, version: (remote.tree.block["version"] as number) + uploads.length, file_ids: [...(remote.tree.block["file_ids"] as string[] | undefined ?? []), ...uploads.map((asset) => asset.source.split(":")[1]!)] } };
|
|
1321
1472
|
await resolveNotionEmailMentions(runtime, localBlocks, remote.cookie, remote.spaceId, remote.headers, emailMentions);
|
|
1322
1473
|
const ambient = { spaceId: remote.spaceId, userId: remote.userId, currentTime: runtime.clock.now().getTime() };
|
|
1323
1474
|
const diffResult = diffNotionBlockTrees(remote.tree, localBlocks, sidecarBlocksFromNotionTree(remote.tree), ambient);
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { defineService } from "wire-core";
|
|
2
2
|
import type { RuntimeCapabilities } from "wire-core";
|
|
3
|
-
import { downloadNotionDirectory, fetchNotionDocument, synchronizeNotionDocument, uploadNotionDocument } from "./notion-sync.js";
|
|
3
|
+
import { downloadNotionDirectory, fetchNotionDocument, materializeNotionDocument, synchronizeNotionDocument, uploadNotionDocument } from "./notion-sync.js";
|
|
4
4
|
|
|
5
5
|
const notionPageId = /[a-f0-9]{32}|[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}/i;
|
|
6
6
|
|
|
@@ -10,6 +10,7 @@ export const notionService = defineService<RuntimeCapabilities>({
|
|
|
10
10
|
parse: (url) => Object.freeze({ service: "notion", identifier: notionPageId.exec(url.href)![0]!.replaceAll("-", "").toLowerCase(), type: "document" }),
|
|
11
11
|
fetch: fetchNotionDocument,
|
|
12
12
|
download: downloadNotionDirectory,
|
|
13
|
+
materialize: materializeNotionDocument,
|
|
13
14
|
synchronize: synchronizeNotionDocument,
|
|
14
15
|
upload: uploadNotionDocument,
|
|
15
16
|
});
|
|
@@ -16,12 +16,21 @@ export declare const slackProvider: Readonly<{
|
|
|
16
16
|
markdown: string;
|
|
17
17
|
data: import("wire-core").JsonValue;
|
|
18
18
|
}>>;
|
|
19
|
+
materialize?(input: import("wire-core").RuntimeCapabilities, document: Readonly<{
|
|
20
|
+
title: string;
|
|
21
|
+
markdown: string;
|
|
22
|
+
data: import("wire-core").JsonValue;
|
|
23
|
+
}>, markdownPath: string, previous?: import("wire-core").JsonValue): Promise<Readonly<{
|
|
24
|
+
title: string;
|
|
25
|
+
markdown: string;
|
|
26
|
+
data: import("wire-core").JsonValue;
|
|
27
|
+
}>>;
|
|
19
28
|
download?(input: import("wire-core").RuntimeCapabilities, url: string, source: Readonly<{
|
|
20
29
|
[key: string]: import("wire-core").JsonValue;
|
|
21
30
|
service: string;
|
|
22
31
|
identifier: string;
|
|
23
32
|
type: import("wire-core").ResourceType;
|
|
24
|
-
}>, write: import("wire-core").DownloadWriter, addMarkdown?: import("wire-core").AddMarkdown): Promise<import("wire-core").DownloadedDocument | null>;
|
|
33
|
+
}>, write: import("wire-core").DownloadWriter, addMarkdown?: import("wire-core").AddMarkdown, directory?: string): Promise<import("wire-core").DownloadedDocument | null>;
|
|
25
34
|
mergeDrafts?(base: string, editor: string, shell: string): string;
|
|
26
35
|
synchronize?(input: import("wire-core").RuntimeCapabilities, url: string, source: Readonly<{
|
|
27
36
|
[key: string]: import("wire-core").JsonValue;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,YAAY,EAAE,qBAAqB,EAAE,qBAAqB,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,KAAK,gBAAgB,EAAE,MAAM,YAAY,CAAC;AACrK,eAAO,MAAM,aAAa
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,YAAY,EAAE,qBAAqB,EAAE,qBAAqB,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,KAAK,gBAAgB,EAAE,MAAM,YAAY,CAAC;AACrK,eAAO,MAAM,aAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAExB,CAAC"}
|
|
@@ -28,12 +28,21 @@ export declare const slackService: Readonly<{
|
|
|
28
28
|
markdown: string;
|
|
29
29
|
data: import("wire-core").JsonValue;
|
|
30
30
|
}>>;
|
|
31
|
+
materialize?(input: RuntimeCapabilities, document: Readonly<{
|
|
32
|
+
title: string;
|
|
33
|
+
markdown: string;
|
|
34
|
+
data: import("wire-core").JsonValue;
|
|
35
|
+
}>, markdownPath: string, previous?: import("wire-core").JsonValue): Promise<Readonly<{
|
|
36
|
+
title: string;
|
|
37
|
+
markdown: string;
|
|
38
|
+
data: import("wire-core").JsonValue;
|
|
39
|
+
}>>;
|
|
31
40
|
download?(input: RuntimeCapabilities, url: string, source: Readonly<{
|
|
32
41
|
[key: string]: import("wire-core").JsonValue;
|
|
33
42
|
service: string;
|
|
34
43
|
identifier: string;
|
|
35
44
|
type: import("wire-core").ResourceType;
|
|
36
|
-
}>, write: import("wire-core").DownloadWriter, addMarkdown?: import("wire-core").AddMarkdown): Promise<import("wire-core").DownloadedDocument | null>;
|
|
45
|
+
}>, write: import("wire-core").DownloadWriter, addMarkdown?: import("wire-core").AddMarkdown, directory?: string): Promise<import("wire-core").DownloadedDocument | null>;
|
|
37
46
|
mergeDrafts?(base: string, editor: string, shell: string): string;
|
|
38
47
|
synchronize?(input: RuntimeCapabilities, url: string, source: Readonly<{
|
|
39
48
|
[key: string]: import("wire-core").JsonValue;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"slack.d.ts","sourceRoot":"","sources":["../src/slack.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AAC5C,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAC;AAyIrD,wBAAgB,qBAAqB,CAAC,QAAQ,EAAE,MAAM,GAAG,SAAS,UAAU,EAAE,CAO7E;AAwCD,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,SAAS,UAAU,EAAE,EAAE,KAAK,EAAE,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,MAAM,
|
|
1
|
+
{"version":3,"file":"slack.d.ts","sourceRoot":"","sources":["../src/slack.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AAC5C,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAC;AAyIrD,wBAAgB,qBAAqB,CAAC,QAAQ,EAAE,MAAM,GAAG,SAAS,UAAU,EAAE,CAO7E;AAwCD,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,SAAS,UAAU,EAAE,EAAE,KAAK,EAAE,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,MAAM,CA4D/G;AA6DD,wBAAsB,gBAAgB,CAAC,OAAO,EAAE,mBAAmB,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,SAAS,UAAU,EAAE,CAAC,CAmBlH;AA2CD,MAAM,MAAM,gBAAgB,GAAG,QAAQ,CAAC;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,EAAE,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAC;IAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAAC,OAAO,CAAC,EAAE,SAAS,gBAAgB,EAAE,CAAA;CAAE,CAAC,CAAC;AAEjJ,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,mBAAmB,EAAE,WAAW,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAE/H;AAED,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,mBAAmB,EAAE,GAAG,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAEvH;AA0ED,eAAO,MAAM,YAAY;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAwGvB,CAAC"}
|
|
@@ -259,7 +259,10 @@ export function slackBlocksToMarkdown(blocks, users) {
|
|
|
259
259
|
const prefix = block["style"] === "ordered" ? `${offset + index + 1}. ` : "- ";
|
|
260
260
|
return `${" ".repeat(indent)}${prefix}${richInline(element["elements"], users, tableCell).replace(/\n/g, `\n${" ".repeat(indent)}${" ".repeat(prefix.length)}`)}`;
|
|
261
261
|
}).join("\n");
|
|
262
|
-
case "section":
|
|
262
|
+
case "section": {
|
|
263
|
+
const accessory = block["accessory"];
|
|
264
|
+
return [...(block["text"] === undefined ? [] : [render(block["text"])]), ...(block["fields"] === undefined ? [] : block["fields"].map((child) => render(child))), ...(accessory?.["type"] === "static_select" ? [render(accessory)] : [])].join("\n\n");
|
|
265
|
+
}
|
|
263
266
|
case "mrkdwn": return cleanText(block["text"]);
|
|
264
267
|
case "raw_text":
|
|
265
268
|
case "raw_number":
|
|
@@ -284,6 +287,10 @@ export function slackBlocksToMarkdown(blocks, users) {
|
|
|
284
287
|
case "context": return elements.map((child) => render(child)).join(" · ");
|
|
285
288
|
case "image": return `![${markdownText(block["alt_text"])}](<${block["image_url"]}>)`;
|
|
286
289
|
case "actions": return elements.map((child) => render(child)).join(" · ");
|
|
290
|
+
case "static_select": {
|
|
291
|
+
const label = block["initial_option"]?.["text"] ?? block["placeholder"];
|
|
292
|
+
return label === undefined ? "Dropdown (read-only)" : `Dropdown (read-only): ${render(label)}`;
|
|
293
|
+
}
|
|
287
294
|
case "button": return block["url"] === undefined ? render(block["text"]) : `[${render(block["text"])}](<${block["url"]}>)`;
|
|
288
295
|
default: throw new Error(`Unsupported Slack block: ${block["type"]}`);
|
|
289
296
|
}
|
|
@@ -454,8 +461,16 @@ async function writeSlackMessage(runtime, destination, markdown, edit) {
|
|
|
454
461
|
if (edit)
|
|
455
462
|
editTimestamp = slackTimestamp(message.rawTimestamp);
|
|
456
463
|
thread = url.searchParams.has("thread_ts") ? url.searchParams.get("thread_ts") : slackTimestamp(message.rawTimestamp);
|
|
457
|
-
const response = await request("conversations.replies", { channel, ts: thread, limit: "1" });
|
|
458
|
-
const
|
|
464
|
+
const response = await request("conversations.replies", { channel, ts: thread, ...(editTimestamp === undefined ? { limit: "1" } : { oldest: editTimestamp, latest: editTimestamp, inclusive: "true", limit: "2" }) });
|
|
465
|
+
const messages = response["messages"];
|
|
466
|
+
const selected = editTimestamp === undefined ? messages[0] : messages.find((value) => value["ts"] === editTimestamp);
|
|
467
|
+
if (selected === undefined)
|
|
468
|
+
throw new Error("Slack message was not found");
|
|
469
|
+
if (edit) {
|
|
470
|
+
const blocks = [selected, ...(selected["attachments"] ?? [])].flatMap((part) => part["blocks"] ?? []);
|
|
471
|
+
if (blocks.some((block) => block["accessory"]?.["type"] === "static_select" || block["elements"]?.some((item) => item["type"] === "static_select")))
|
|
472
|
+
throw new Error("Cannot replace a Slack message containing a static select with Markdown");
|
|
473
|
+
}
|
|
459
474
|
if (selected["thread_ts"] !== undefined)
|
|
460
475
|
thread = selected["thread_ts"];
|
|
461
476
|
}
|