@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,5 +1,6 @@
|
|
|
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
|
import { WireMergeConflict, markdownFilename, stableJsonCompact, stableJsonPretty } from "wire-core";
|
|
4
5
|
function object(value) { return value; }
|
|
5
6
|
function array(value) { return value; }
|
|
@@ -259,7 +260,15 @@ function baseUserMentions(base) {
|
|
|
259
260
|
return base["user_mentions"];
|
|
260
261
|
}
|
|
261
262
|
function notionData(pageId, markdown, tree, mentions, emailMentions = {}) {
|
|
262
|
-
|
|
263
|
+
const embeds = [];
|
|
264
|
+
const visit = (node) => {
|
|
265
|
+
const source = object(node.block["properties"] ?? {})["source"];
|
|
266
|
+
if (node.block["type"] === "embed" && source !== undefined && /^attachment:[a-f0-9-]{36}:[^/\\]+\.html?$/i.test(richTextText(source)))
|
|
267
|
+
embeds.push({ source: richTextText(source), block_id: node.id, space_id: node.block["space_id"] });
|
|
268
|
+
node.children.forEach(visit);
|
|
269
|
+
};
|
|
270
|
+
visit(tree);
|
|
271
|
+
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 }) };
|
|
263
272
|
}
|
|
264
273
|
function lineIndent(line) { return Math.floor(line.match(/^ */)[0].length / 2); }
|
|
265
274
|
function stripIndent(line) { return line.replace(/^ +/, ""); }
|
|
@@ -291,7 +300,7 @@ function isTableSeparator(row) {
|
|
|
291
300
|
return row.every((cell) => /^:?-{3,}:?$/.test(cell.trim()));
|
|
292
301
|
}
|
|
293
302
|
function markdownBlockStart(stripped) {
|
|
294
|
-
return /^(#{1,6})\s+|^[-*]\s+|^\d+\.\s+|^-\s+\[[ xX]\]\s+|^```|^---$|^!\[
|
|
303
|
+
return /^(#{1,6})\s+|^[-*]\s+|^\d+\.\s+|^-\s+\[[ xX]\]\s+|^```|^---$|^!\[|^>|^\||^:::|^<iframe\s/.test(stripped);
|
|
295
304
|
}
|
|
296
305
|
function escapeBlockMarkdownLine(line) {
|
|
297
306
|
return markdownBlockStart(line) ? `\\${line}` : line;
|
|
@@ -370,6 +379,35 @@ function parseLines(lines, baseIndent = 0) {
|
|
|
370
379
|
index += 1;
|
|
371
380
|
continue;
|
|
372
381
|
}
|
|
382
|
+
if (stripped.startsWith("<iframe ")) {
|
|
383
|
+
const iframe = /^<iframe\s+(.+?)><\/iframe>$/.exec(stripped);
|
|
384
|
+
if (iframe === null)
|
|
385
|
+
throw new Error("HTML embeds require a single-line iframe with src, width and height attributes");
|
|
386
|
+
const attributes = {};
|
|
387
|
+
const rest = iframe[1].replace(/([\w-]+)=(?:"([^"]*)"|'([^']*)')/g, (_match, name, double, single) => {
|
|
388
|
+
if (!["src", "width", "height"].includes(name) || attributes[name] !== undefined)
|
|
389
|
+
throw new Error(`Unsupported iframe attribute: ${name}`);
|
|
390
|
+
attributes[name] = unescapeHtml(double ?? single);
|
|
391
|
+
return "";
|
|
392
|
+
});
|
|
393
|
+
if (rest.trim() !== "" || !attributes["src"])
|
|
394
|
+
throw new Error("HTML embeds require a src attribute");
|
|
395
|
+
const format = {};
|
|
396
|
+
for (const dimension of ["width", "height"]) {
|
|
397
|
+
const value = attributes[dimension];
|
|
398
|
+
if (value === undefined)
|
|
399
|
+
continue;
|
|
400
|
+
if (dimension === "width" && value === "100%")
|
|
401
|
+
format["block_page_width"] = true;
|
|
402
|
+
else if (/^[1-9]\d*$/.test(value))
|
|
403
|
+
format[`block_${dimension}`] = Number(value);
|
|
404
|
+
else
|
|
405
|
+
throw new Error(`Unsupported iframe ${dimension}: ${value}`);
|
|
406
|
+
}
|
|
407
|
+
blocks.push({ type: "embed", content: "", properties: { source: attributes["src"], format }, rich_text: [], indent });
|
|
408
|
+
index += 1;
|
|
409
|
+
continue;
|
|
410
|
+
}
|
|
373
411
|
const image = stripped.startsWith("![") ? markdownLink(stripped.slice(1)) : null;
|
|
374
412
|
if (image !== null && image.length + 1 === stripped.length) {
|
|
375
413
|
blocks.push({ type: "image", content: "", properties: { alt_text: unescapeInlineMarkdown(image.label), source: decodeURI(image.url) }, rich_text: [], indent });
|
|
@@ -543,6 +581,10 @@ function parserBlockToNotionBlock(block, id, parentId, parentTable, spaceId, use
|
|
|
543
581
|
return { ...base, properties: { title: [[block.content]], language: [[block.properties["language"]]] } };
|
|
544
582
|
if (block.type === "to_do")
|
|
545
583
|
return { ...base, properties: { title: block.rich_text, checked: [[block.properties["checked"] === true ? "Yes" : "No"]] } };
|
|
584
|
+
if (block.type === "embed") {
|
|
585
|
+
const source = block.properties["source"];
|
|
586
|
+
return { ...base, properties: { source: [[source]] }, format: block.properties["format"], ...(source.startsWith("attachment:") ? { file_ids: [source.split(":")[1]] } : {}) };
|
|
587
|
+
}
|
|
546
588
|
if (block.type === "image")
|
|
547
589
|
return { ...base, properties: { source: [[block.properties["source"]]], alt_text: [[block.properties["alt_text"]]], ...(block.properties["caption"] === undefined ? {} : { caption: block.properties["caption"] }) } };
|
|
548
590
|
if (block.type === "table")
|
|
@@ -595,6 +637,9 @@ export function buildNotionCreateOperations(blocks, pageId, spaceId, userId, cur
|
|
|
595
637
|
operations.push({ pointer: pointer(pageId, spaceId), path: ["last_edited_time"], command: "set", args: currentTime });
|
|
596
638
|
return { operations, topLevelIds };
|
|
597
639
|
}
|
|
640
|
+
function embedDimensions(format) {
|
|
641
|
+
return Object.fromEntries(Object.entries(format).filter(([key, value]) => ["block_width", "block_height"].includes(key) || key === "block_page_width" && value === true));
|
|
642
|
+
}
|
|
598
643
|
function canonicalBlock(value, columnOrder) {
|
|
599
644
|
const type = value["type"];
|
|
600
645
|
if (type === "text" && object(value["format"] ?? {})["toggleable"] === true)
|
|
@@ -607,6 +652,8 @@ function canonicalBlock(value, columnOrder) {
|
|
|
607
652
|
return { type, column_count: object(value["format"])["table_block_column_order"].length };
|
|
608
653
|
if (type === "table_row")
|
|
609
654
|
return { type, cells: columnOrder.map((column) => normalizeRichText(object(value["properties"])[column] ?? [])) };
|
|
655
|
+
if (type === "embed")
|
|
656
|
+
return { type, source: object(value["properties"] ?? {})["source"] ?? null, format: embedDimensions(object(value["format"] ?? {})) };
|
|
610
657
|
if (type === "image")
|
|
611
658
|
return { type, source: object(value["properties"])["source"], alt_text: object(value["properties"])["alt_text"] ?? [[""]], caption: object(value["properties"])["caption"] ?? null };
|
|
612
659
|
if (["divider", "column_list", "transclusion_container"].includes(type))
|
|
@@ -634,6 +681,8 @@ function canonicalParserBlock(block, columnOrder) {
|
|
|
634
681
|
const cells = tableRowCells(block, columnOrder);
|
|
635
682
|
return { type: "table_row", cells: columnOrder.map((column) => normalizeRichText(cells[column] ?? [])) };
|
|
636
683
|
}
|
|
684
|
+
if (block.type === "embed")
|
|
685
|
+
return { type: "embed", source: [[block.properties["source"]]], format: block.properties["format"] };
|
|
637
686
|
if (block.type === "image")
|
|
638
687
|
return { type: "image", source: [[block.properties["source"]]], alt_text: [[block.properties["alt_text"]]], caption: block.properties["caption"] ?? null };
|
|
639
688
|
if (block.type === "page" || block.type === "equation")
|
|
@@ -697,7 +746,9 @@ function emitUpdates(remote, local, blockId, spaceId, columnOrder) {
|
|
|
697
746
|
if (compact(remoteProperties[key] ?? null) !== compact(nextProperties[key]))
|
|
698
747
|
operations.push({ pointer: pointer(blockId, spaceId), path: ["properties", key], command: "updateBlockPropertyValue", args: { primitiveOp: { command: "set", args: nextProperties[key] } } });
|
|
699
748
|
}
|
|
700
|
-
|
|
749
|
+
if (local.type === "embed" && compact(remote["file_ids"] ?? []) !== compact(args["file_ids"] ?? []))
|
|
750
|
+
operations.push({ pointer: pointer(blockId, spaceId), path: ["file_ids"], command: "set", args: [...new Set([...(remote["file_ids"] ?? []), ...(args["file_ids"] ?? [])])] });
|
|
751
|
+
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"] ?? {});
|
|
701
752
|
if ((typeChanged || args["format"] !== undefined || remote["format"] !== undefined) && compact(remote["format"] ?? {}) !== compact(nextFormat))
|
|
702
753
|
operations.push({ pointer: pointer(blockId, spaceId), path: ["format"], command: "set", args: nextFormat });
|
|
703
754
|
return operations;
|
|
@@ -848,6 +899,10 @@ function renderNode(tree, indent, parentType = "", download = false) {
|
|
|
848
899
|
const language = richTextText(properties["language"]).replace("Plain Text", "");
|
|
849
900
|
return [`${prefix}${fence}${language}`, ...code.split("\n").map((line) => `${prefix}${line}`), `${prefix}${fence}`];
|
|
850
901
|
}
|
|
902
|
+
if (type === "embed" && properties["source"] !== undefined && /^attachment:[a-f0-9-]{36}:[^/\\]+\.html?$/i.test(richTextText(properties["source"]))) {
|
|
903
|
+
const width = format["block_page_width"] === true ? "100%" : format["block_width"];
|
|
904
|
+
return [`${prefix}<iframe src="${escapeHtml(richTextText(properties["source"]))}"${width === undefined ? "" : ` width="${width}"`}${format["block_height"] === undefined ? "" : ` height="${format["block_height"]}"`}></iframe>`];
|
|
905
|
+
}
|
|
851
906
|
if (type === "image")
|
|
852
907
|
return [`${prefix}![${escapeInlineMarkdown(richTextText(properties["alt_text"] ?? []))}](${encodeURI(richTextText(properties["source"]))})`];
|
|
853
908
|
if (type === "equation")
|
|
@@ -1175,7 +1230,7 @@ export async function fetchNotionDocument(runtime, url, source) {
|
|
|
1175
1230
|
const { tree, comments } = await fetchTree(runtime, url, source);
|
|
1176
1231
|
return notionDocument(source.identifier, tree, undefined, {}, comments);
|
|
1177
1232
|
}
|
|
1178
|
-
export async function downloadNotionDirectory(runtime, url, source, write) {
|
|
1233
|
+
export async function downloadNotionDirectory(runtime, url, source, write, _addMarkdown, destination) {
|
|
1179
1234
|
const cookies = await runtime.cookies.loadSaved("notion");
|
|
1180
1235
|
if (cookies === null)
|
|
1181
1236
|
throw notionAuthError();
|
|
@@ -1268,11 +1323,95 @@ export async function downloadNotionDirectory(runtime, url, source, write) {
|
|
|
1268
1323
|
};
|
|
1269
1324
|
const tree = await build(id, true);
|
|
1270
1325
|
const markdown = renderNotionTreeToMarkdown(tree, undefined, {}, true) + renderComments(id, threads, comments, users);
|
|
1271
|
-
|
|
1326
|
+
const document = { title: richTextText(object(page["properties"])["title"]), markdown, data: notionData(id, markdown, tree, undefined) };
|
|
1327
|
+
return { path, ...destination === undefined ? document : await materializeNotionDocument(runtime, document, resolve(destination, path)) };
|
|
1272
1328
|
};
|
|
1273
1329
|
return exportPage(root, directoryName(root));
|
|
1274
1330
|
}
|
|
1275
|
-
|
|
1331
|
+
function replaceIframeSources(markdown, sources) {
|
|
1332
|
+
let fence;
|
|
1333
|
+
return markdown.split("\n").map((line) => {
|
|
1334
|
+
const marker = /^ *(`{3,})/.exec(line)?.[1];
|
|
1335
|
+
if (marker !== undefined) {
|
|
1336
|
+
if (fence === undefined)
|
|
1337
|
+
fence = marker;
|
|
1338
|
+
else if (marker.length >= fence.length)
|
|
1339
|
+
fence = undefined;
|
|
1340
|
+
return line;
|
|
1341
|
+
}
|
|
1342
|
+
if (fence !== undefined)
|
|
1343
|
+
return line;
|
|
1344
|
+
return line.replace(/^( *<iframe\s+[^\n]*?src=)(["'])(.*?)\2/, (match, prefix, quote, source) => {
|
|
1345
|
+
const replacement = sources.get(unescapeHtml(source));
|
|
1346
|
+
return replacement === undefined ? match : `${prefix}${quote}${escapeHtml(replacement)}${quote}`;
|
|
1347
|
+
});
|
|
1348
|
+
}).join("\n");
|
|
1349
|
+
}
|
|
1350
|
+
export async function materializeNotionDocument(runtime, document, markdownPath, previous) {
|
|
1351
|
+
const data = object(document.data);
|
|
1352
|
+
const embeds = data["html_embeds"];
|
|
1353
|
+
if (embeds === undefined || embeds.length === 0)
|
|
1354
|
+
return document;
|
|
1355
|
+
const known = data["html_assets"] ?? (previous === undefined ? [] : object(previous)["html_assets"] ?? []);
|
|
1356
|
+
const assets = [];
|
|
1357
|
+
const sources = new Map();
|
|
1358
|
+
for (const embed of embeds) {
|
|
1359
|
+
let asset = known.find((item) => item.source === embed.source);
|
|
1360
|
+
if (asset === undefined || !await runtime.filesystem.exists(asset.path)) {
|
|
1361
|
+
const cookies = await runtime.cookies.loadSaved("notion");
|
|
1362
|
+
if (cookies === null)
|
|
1363
|
+
throw notionAuthError();
|
|
1364
|
+
const cookie = cookies.map((value) => `${value.name}=${value.value}`).join("; ");
|
|
1365
|
+
const signed = await notionPost(runtime, "getSignedFileUrls", cookie, { urls: [{ url: embed.source, permissionRecord: { table: "block", id: embed.block_id, spaceId: embed.space_id } }] }, {});
|
|
1366
|
+
const url = signed["signedUrls"][0];
|
|
1367
|
+
const target = new URL(url);
|
|
1368
|
+
if (target.protocol !== "https:" || target.hostname !== "file.notion.so")
|
|
1369
|
+
throw new Error("Unexpected Notion HTML download host");
|
|
1370
|
+
const response = await runtime.http.request(url, { headers: { cookie } });
|
|
1371
|
+
if (!response.ok)
|
|
1372
|
+
throw new Error(`Notion HTML download failed: ${response.status}`);
|
|
1373
|
+
const contents = await response.text();
|
|
1374
|
+
const path = asset?.path ?? resolve(dirname(markdownPath), `${basename(markdownPath, extname(markdownPath))}.assets`, `${embed.source.split(":")[1]}.html`);
|
|
1375
|
+
if (await runtime.filesystem.exists(path) && await runtime.filesystem.readText(path) !== contents)
|
|
1376
|
+
throw new Error(`Local HTML edits exist: ${path}`);
|
|
1377
|
+
await runtime.filesystem.writeText(path, contents);
|
|
1378
|
+
asset = { source: embed.source, path, hash: hash(contents) };
|
|
1379
|
+
}
|
|
1380
|
+
assets.push(asset);
|
|
1381
|
+
sources.set(embed.source, pathToFileURL(asset.path).href);
|
|
1382
|
+
}
|
|
1383
|
+
const remoteMarkdown = data["remote_markdown"] ?? document.markdown;
|
|
1384
|
+
const markdown = replaceIframeSources(remoteMarkdown, sources);
|
|
1385
|
+
return { ...document, markdown, data: { ...data, markdown, remote_markdown: remoteMarkdown, html_assets: assets } };
|
|
1386
|
+
}
|
|
1387
|
+
async function uploadHtmlEmbeds(runtime, blocks, markdownPath, pageId, spaceId, cookie, headers, assets) {
|
|
1388
|
+
for (const block of blocks) {
|
|
1389
|
+
const source = block.properties["source"];
|
|
1390
|
+
if (block.type !== "embed" || source === undefined || source.startsWith("attachment:") || /^https?:/.test(source))
|
|
1391
|
+
continue;
|
|
1392
|
+
const path = source.startsWith("file:") ? fileURLToPath(new URL(source)) : resolve(dirname(markdownPath), source);
|
|
1393
|
+
if (!/\.html?$/i.test(path))
|
|
1394
|
+
throw new Error(`HTML embed must reference an HTML file: ${path}`);
|
|
1395
|
+
const contents = await runtime.filesystem.readText(path);
|
|
1396
|
+
const uploaded = assets.find((asset) => asset.path === path && asset.hash === hash(contents));
|
|
1397
|
+
if (uploaded !== undefined) {
|
|
1398
|
+
block.properties["source"] = uploaded.source;
|
|
1399
|
+
continue;
|
|
1400
|
+
}
|
|
1401
|
+
const upload = await notionPost(runtime, "getUploadFileUrl", cookie, { bucket: "secure", contentType: "text/html", name: basename(path), record: { table: "block", id: pageId, spaceId } }, headers);
|
|
1402
|
+
const body = new FormData();
|
|
1403
|
+
for (const [key, value] of Object.entries(object(upload["fields"])))
|
|
1404
|
+
body.append(key, text(value));
|
|
1405
|
+
body.append("file", new Blob([contents], { type: "text/html" }), basename(path));
|
|
1406
|
+
const response = await runtime.http.request(text(upload["signedUploadPostUrl"]), { method: "POST", headers: upload["postHeaders"], body });
|
|
1407
|
+
if (!response.ok)
|
|
1408
|
+
throw new Error(`Notion HTML upload failed: ${response.status}`);
|
|
1409
|
+
const uploadedSource = text(upload["url"]);
|
|
1410
|
+
block.properties["source"] = uploadedSource;
|
|
1411
|
+
assets.push({ source: uploadedSource, path, hash: hash(contents) });
|
|
1412
|
+
}
|
|
1413
|
+
}
|
|
1414
|
+
export async function uploadNotionDocument(runtime, markdown, markdownPath) {
|
|
1276
1415
|
const split = splitTitle(withoutComments(markdown));
|
|
1277
1416
|
if (split.title === "")
|
|
1278
1417
|
throw new Error("Markdown document requires a first heading");
|
|
@@ -1313,9 +1452,15 @@ export async function uploadNotionDocument(runtime, markdown, _markdownPath) {
|
|
|
1313
1452
|
},
|
|
1314
1453
|
};
|
|
1315
1454
|
const localBlocks = parseNotionMarkdown(split.body);
|
|
1455
|
+
const assets = [];
|
|
1456
|
+
const hasEmbeds = localBlocks.some((block) => block.type === "embed" && block.properties["source"] !== undefined);
|
|
1457
|
+
if (hasEmbeds) {
|
|
1458
|
+
await notionPost(runtime, "saveTransactionsFanout", cookie, { requestId: randomUUID(), transactions: [{ id: randomUUID(), spaceId, operations: [pageOperation] }] }, headers);
|
|
1459
|
+
await uploadHtmlEmbeds(runtime, localBlocks, markdownPath, pageId, spaceId, cookie, headers, assets);
|
|
1460
|
+
}
|
|
1316
1461
|
const emailMentions = {};
|
|
1317
1462
|
await resolveNotionEmailMentions(runtime, localBlocks, cookie, spaceId, headers, emailMentions);
|
|
1318
|
-
const operations = [pageOperation, ...buildNotionCreateOperations(localBlocks, pageId, spaceId, userId, currentTime).operations];
|
|
1463
|
+
const operations = [...(hasEmbeds ? [] : [pageOperation]), ...buildNotionCreateOperations(localBlocks, pageId, spaceId, userId, currentTime).operations];
|
|
1319
1464
|
await notionPost(runtime, "saveTransactionsFanout", cookie, { requestId: randomUUID(), transactions: [{ id: randomUUID(), spaceId, operations }] }, headers);
|
|
1320
1465
|
const pageTree = {
|
|
1321
1466
|
id: pageId,
|
|
@@ -1324,7 +1469,8 @@ export async function uploadNotionDocument(runtime, markdown, _markdownPath) {
|
|
|
1324
1469
|
};
|
|
1325
1470
|
const output = renderNotionTreeToMarkdown(pageTree, undefined, emailMentions);
|
|
1326
1471
|
const slug = split.title.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
|
|
1327
|
-
|
|
1472
|
+
const document = await materializeNotionDocument(runtime, { title: split.title, markdown: output, data: { ...notionData(compactPageId, output, pageTree, undefined, emailMentions), html_assets: assets } }, markdownPath);
|
|
1473
|
+
return { ...document, url: slug === "" ? `https://www.notion.so/${compactPageId}` : `https://www.notion.so/${slug}-${compactPageId}` };
|
|
1328
1474
|
}
|
|
1329
1475
|
function splitTitle(markdown) {
|
|
1330
1476
|
const lines = markdown.replace(/^\ufeff/, "").split("\n");
|
|
@@ -1335,14 +1481,32 @@ function splitTitle(markdown) {
|
|
|
1335
1481
|
return { title: first.replace(/^#+\s+/, "").trim(), body: lines.slice(1).join("\n") };
|
|
1336
1482
|
return { title: "", body: markdown };
|
|
1337
1483
|
}
|
|
1338
|
-
export async function synchronizeNotionDocument(runtime, url, source, base, markdown,
|
|
1484
|
+
export async function synchronizeNotionDocument(runtime, url, source, base, markdown, markdownPath, observeRemote, requireConditionalWrite = false) {
|
|
1485
|
+
const data = object(base);
|
|
1486
|
+
const assets = [...(data["html_assets"] ?? [])];
|
|
1487
|
+
const sources = new Map();
|
|
1488
|
+
for (const block of parseNotionMarkdown(splitTitle(withoutComments(markdown)).body)) {
|
|
1489
|
+
const src = block.properties["source"];
|
|
1490
|
+
if (block.type !== "embed" || src === undefined || src.startsWith("attachment:") || /^https?:/.test(src))
|
|
1491
|
+
continue;
|
|
1492
|
+
const path = src.startsWith("file:") ? fileURLToPath(src) : resolve(dirname(markdownPath), src);
|
|
1493
|
+
const digest = hash(await runtime.filesystem.readText(path));
|
|
1494
|
+
const asset = assets.find((item) => item.path === path && item.hash === digest);
|
|
1495
|
+
sources.set(src, asset?.source ?? `${pathToFileURL(path).href}#${digest}`);
|
|
1496
|
+
}
|
|
1497
|
+
const remoteBase = { ...data, markdown: data["remote_markdown"] ?? data["markdown"] };
|
|
1498
|
+
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);
|
|
1499
|
+
return { ...await materializeNotionDocument(runtime, { ...result, data: { ...object(result.data), html_assets: assets } }, markdownPath), wroteRemote: result.wroteRemote };
|
|
1500
|
+
}
|
|
1501
|
+
async function synchronizeNotionContent(runtime, url, source, base, markdown, markdownPath, assets, observeRemote, requireConditionalWrite) {
|
|
1339
1502
|
const remote = await fetchTree(runtime, url, source);
|
|
1503
|
+
let expectedRemote = remote.tree;
|
|
1340
1504
|
const save = async (operations) => {
|
|
1341
1505
|
if (operations.length === 0)
|
|
1342
1506
|
return;
|
|
1343
1507
|
if (requireConditionalWrite) {
|
|
1344
1508
|
const latest = await fetchTree(runtime, url, source);
|
|
1345
|
-
if (compact(latest.tree) !== compact(
|
|
1509
|
+
if (compact(latest.tree) !== compact(expectedRemote)) {
|
|
1346
1510
|
await observeRemote?.(notionDocument(latest.tree.id, latest.tree, mentions, emailMentions, latest.comments));
|
|
1347
1511
|
throw new WireMergeConflict("Notion changed while preparing the save");
|
|
1348
1512
|
}
|
|
@@ -1403,6 +1567,11 @@ export async function synchronizeNotionDocument(runtime, url, source, base, mark
|
|
|
1403
1567
|
}
|
|
1404
1568
|
const localBody = mentions === undefined ? split.body : hydrateUserMentions(split.body, mentions);
|
|
1405
1569
|
const localBlocks = parseNotionMarkdown(localBody);
|
|
1570
|
+
const assetCount = assets.length;
|
|
1571
|
+
await uploadHtmlEmbeds(runtime, localBlocks, markdownPath, remote.tree.id, remote.spaceId, remote.cookie, remote.headers, assets);
|
|
1572
|
+
const uploads = assets.slice(assetCount);
|
|
1573
|
+
if (uploads.length > 0)
|
|
1574
|
+
expectedRemote = { ...remote.tree, block: { ...remote.tree.block, version: remote.tree.block["version"] + uploads.length, file_ids: [...(remote.tree.block["file_ids"] ?? []), ...uploads.map((asset) => asset.source.split(":")[1])] } };
|
|
1406
1575
|
await resolveNotionEmailMentions(runtime, localBlocks, remote.cookie, remote.spaceId, remote.headers, emailMentions);
|
|
1407
1576
|
const ambient = { spaceId: remote.spaceId, userId: remote.userId, currentTime: runtime.clock.now().getTime() };
|
|
1408
1577
|
const diffResult = diffNotionBlockTrees(remote.tree, localBlocks, sidecarBlocksFromNotionTree(remote.tree), ambient);
|