@kamilio/wire 0.1.77 → 0.1.79

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/README.md CHANGED
@@ -101,7 +101,7 @@ wire sync Notes.md
101
101
 
102
102
  Use `local` or `remote` instead of `working` to select a saved side. Resolution updates the local file. `wire diff` defaults to the last sync versus the working copy. Pass revision IDs from `wire history` to compare older versions. Use `wire history Notes.md -p` to read those changes in order, newest first. Each patch compares the saved text with its first parent. A revision with no recorded parent is shown against an empty document.
103
103
 
104
- For a Notion page with subpages, `wire download <url>` saves a directory with an `index.md` for each page. Open the root index and follow the local links. Ordinary links and mentions stay remote. Pages without subpages still download as one Markdown file.
104
+ For a Notion page with subpages, `wire download <url>` saves a directory with an `index.md` for each page. Open the root index and follow the local links. Ordinary links and mentions stay remote. Pages without subpages still download as one Markdown file. File, PDF, image, audio, and video attachments are downloaded into a sibling `.assets` directory and linked from the Markdown. This also applies to `wire attach`. Edit attachments in Notion, as sync does not upload local attachment changes.
105
105
 
106
106
  Run `wire --help` for the full CLI.
107
107
 
@@ -1 +1 @@
1
- {"version":3,"file":"notion-sync.d.ts","sourceRoot":"","sources":["../src/notion-sync.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,WAAW,EAAE,kBAAkB,EAAE,cAAc,EAAE,eAAe,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,EAAE,oBAAoB,EAAE,gBAAgB,EAAE,MAAM,WAAW,CAAC;AAEzK,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAC;AAErD,MAAM,MAAM,cAAc,GAAG,SAAS,EAAE,EAAE,CAAC;AAC3C,MAAM,MAAM,WAAW,GAAG,QAAQ,CAAC;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,UAAU,CAAC;IAAC,SAAS,EAAE,cAAc,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CA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0BD,wBAAsB,oBAAoB,CAAC,OAAO,EAAE,mBAAmB,EAAE,QAAQ,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAyD1I;AAUD,wBAAsB,yBAAyB,CAAC,OAAO,EAAE,mBAAmB,EAAE,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,aAAa,CAAC,EAAE,CAAC,MAAM,EAAE,eAAe,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,EAAE,uBAAuB,UAAQ,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAiBrS"}
@@ -2,6 +2,7 @@ import { createHash, randomUUID } from "node:crypto";
2
2
  import { basename, dirname, extname, posix, resolve } from "node:path";
3
3
  import { fileURLToPath, pathToFileURL } from "node:url";
4
4
  import { WireMergeConflict, markdownFilename, stableJsonCompact, stableJsonPretty } from "wire-core";
5
+ const attachmentTypes = new Set(["file", "pdf", "audio", "video", "image"]);
5
6
  function object(value) { return value; }
6
7
  function array(value) { return value; }
7
8
  function text(value) { return value; }
@@ -261,17 +262,31 @@ function baseUserMentions(base) {
261
262
  }
262
263
  function notionData(pageId, markdown, tree, mentions, emailMentions = {}) {
263
264
  const embeds = [];
265
+ const attachments = [];
264
266
  const visit = (node) => {
265
267
  const source = object(node.block["properties"] ?? {})["source"];
266
268
  if (node.block["type"] === "embed" && source !== undefined && /^attachment:[a-f0-9-]{36}:[^/\\]+\.html?$/i.test(richTextText(source)))
267
269
  embeds.push({ source: richTextText(source), block_id: node.id, space_id: node.block["space_id"] });
270
+ if (attachmentTypes.has(node.block["type"]) && source !== undefined) {
271
+ const value = richTextText(source);
272
+ if (!/^(attachment:|https:)/.test(value))
273
+ return;
274
+ const title = richTextText(object(node.block["properties"] ?? {})["title"] ?? []);
275
+ const name = title || (value.startsWith("attachment:") ? value.split(":").slice(2).join(":") : decodeURIComponent(new URL(value).pathname.split("/").at(-1))) || "attachment";
276
+ attachments.push({ source: value, block_id: node.id, space_id: node.block["space_id"], name });
277
+ }
268
278
  node.children.forEach(visit);
269
279
  };
270
280
  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 }) };
281
+ return { ...(attachments.length === 0 ? {} : { attachments }), ...(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 }) };
282
+ }
283
+ function lineIndent(line) {
284
+ let columns = 0;
285
+ for (const character of line.match(/^[ \t]*/)[0])
286
+ columns += character === "\t" ? 4 - columns % 4 : 1;
287
+ return Math.floor(columns / 2);
272
288
  }
273
- function lineIndent(line) { return Math.floor(line.match(/^ */)[0].length / 2); }
274
- function stripIndent(line) { return line.replace(/^ +/, ""); }
289
+ function stripIndent(line) { return line.replace(/^[ \t]+/, ""); }
275
290
  function tableCellText(value) {
276
291
  return value.trim().replace(/(^|[^\\])<br>/g, "$1\n").replace(/\\<br>/g, "<br>");
277
292
  }
@@ -323,7 +338,7 @@ function colonFenceBody(lines, index) {
323
338
  }
324
339
  function listContinuation(lines, index, baseIndent, indent, firstLine) {
325
340
  const content = [firstLine];
326
- while (index < lines.length && lines[index].trim() !== "" && baseIndent + lineIndent(lines[index]) === indent + 1 && !markdownBlockStart(stripIndent(lines[index]))) {
341
+ while (index < lines.length && lines[index].trim() !== "" && baseIndent + lineIndent(lines[index]) > indent && !markdownBlockStart(stripIndent(lines[index]))) {
327
342
  content.push(stripIndent(lines[index]));
328
343
  index += 1;
329
344
  }
@@ -417,12 +432,21 @@ function parseLines(lines, baseIndent = 0) {
417
432
  const codeFence = /^(`{3,})(.*)$/.exec(stripped);
418
433
  if (codeFence !== null) {
419
434
  const fence = codeFence[1];
420
- const fenceIndent = line.match(/^ */)[0].length;
435
+ let fenceIndent = 0;
436
+ for (const character of line.match(/^[ \t]*/)[0])
437
+ fenceIndent += character === "\t" ? 4 - fenceIndent % 4 : 1;
421
438
  const language = codeFence[2].trim();
422
439
  const body = [];
423
440
  index += 1;
424
441
  while (index < lines.length && !stripIndent(lines[index]).startsWith(fence)) {
425
- body.push(lines[index].slice(fenceIndent));
442
+ const bodyLine = lines[index];
443
+ let offset = 0;
444
+ let columns = 0;
445
+ while (columns < fenceIndent && (bodyLine[offset] === " " || bodyLine[offset] === "\t")) {
446
+ columns += bodyLine[offset] === "\t" ? 4 - columns % 4 : 1;
447
+ offset += 1;
448
+ }
449
+ body.push(" ".repeat(Math.max(0, columns - fenceIndent)) + bodyLine.slice(offset));
426
450
  index += 1;
427
451
  }
428
452
  index += 1;
@@ -532,7 +556,10 @@ function parseLines(lines, baseIndent = 0) {
532
556
  index += 1;
533
557
  const fenced = colonFenceBody(lines, index);
534
558
  index = fenced.index;
535
- const snapshot = JSON.parse(fenced.body.map((bodyLine) => stripIndent(bodyLine)).join("\n"));
559
+ const body = fenced.body.map((bodyLine) => stripIndent(bodyLine));
560
+ if (markdownLink(body[0] ?? "") !== null)
561
+ body.shift();
562
+ const snapshot = JSON.parse(body.join("\n"));
536
563
  blocks.push({ type: snapshot["type"], content: "", properties: { notion_opaque: snapshot }, rich_text: [], indent });
537
564
  continue;
538
565
  }
@@ -614,7 +641,8 @@ export function buildNotionCreateOperations(blocks, pageId, spaceId, userId, cur
614
641
  if (block.type === "table_row")
615
642
  parentId = lastTableId ?? pageId;
616
643
  else if (block.indent > 0) {
617
- const parent = lastAtIndent.get(block.indent - 1);
644
+ const parentIndent = Math.max(...[...lastAtIndent.keys()].filter((indent) => indent < block.indent));
645
+ const parent = lastAtIndent.get(parentIndent);
618
646
  if (parent === undefined)
619
647
  throw new Error(`Indented Notion Markdown block has no parent at indent ${block.indent - 1}`);
620
648
  parentId = parent;
@@ -626,6 +654,9 @@ export function buildNotionCreateOperations(blocks, pageId, spaceId, userId, cur
626
654
  const after = lastChildByParent.get(parentId);
627
655
  operations.push({ pointer: pointer(parentId, spaceId), path: ["content"], command: after === undefined ? "listBefore" : "listAfter", args: after === undefined ? { id: blockId } : { id: blockId, after } });
628
656
  lastChildByParent.set(parentId, blockId);
657
+ for (const indent of lastAtIndent.keys())
658
+ if (indent >= block.indent)
659
+ lastAtIndent.delete(indent);
629
660
  if (["bulleted_list", "numbered_list", "to_do", "quote", "callout", "toggle", "header", "sub_header", "sub_sub_header", "table", "page", "column_list", "column", "transclusion_container"].includes(block.type))
630
661
  lastAtIndent.set(block.indent, blockId);
631
662
  if (block.type === "table") {
@@ -930,7 +961,9 @@ function renderNode(tree, indent, parentType = "", download = false) {
930
961
  return rows.flatMap((row, index) => index === 0 ? [`${prefix}| ${row.join(" | ")} |`, `${prefix}| ${columns.map(() => "---").join(" | ")} |`] : [`${prefix}| ${row.join(" | ")} |`]);
931
962
  }
932
963
  if (type !== "text") {
933
- const opaque = [`${prefix}:::notion-opaque`, ...stableJsonPretty(tree.block).split("\n").map((line) => `${prefix}${line}`), `${prefix}:::`];
964
+ const attachment = attachmentTypes.has(type) && properties["source"] !== undefined
965
+ ? [`${prefix}[${escapeInlineMarkdown(richTextText(properties["title"] ?? [[type]]))}](${encodeURI(richTextText(properties["source"]))})`] : [];
966
+ const opaque = [`${prefix}:::notion-opaque`, ...attachment, ...stableJsonPretty(tree.block).split("\n").map((line) => `${prefix}${line}`), `${prefix}:::`];
934
967
  if (tree.block["format"] !== undefined)
935
968
  return [`${prefix}:::notion-format`, `${prefix}:::format ${compact(tree.block["format"])}`, ...opaque, `${prefix}:::`];
936
969
  return opaque;
@@ -1149,8 +1182,20 @@ function renderComments(pageId, discussions, commentsById, users) {
1149
1182
  }).filter((thread) => thread !== "");
1150
1183
  return threads.length === 0 ? "" : `\n\n<!-- wire:notion-comments -->\n\n## Comments (read-only)\n\n${threads.join("\n\n")}\n\n<!-- /wire:notion-comments -->`;
1151
1184
  }
1152
- function withoutComments(markdown) {
1153
- return markdown.replace(/\n\n<!-- wire:notion-comments -->[\s\S]*?<!-- \/wire:notion-comments -->/g, "");
1185
+ function withoutReadOnlyContent(markdown) {
1186
+ let fence;
1187
+ const lines = markdown.replace(/\n\n<!-- wire:notion-comments -->[\s\S]*?<!-- \/wire:notion-comments -->/g, "").split("\n");
1188
+ return lines.filter((line, index) => {
1189
+ const marker = /^ *(`{3,})/.exec(line)?.[1];
1190
+ if (marker !== undefined) {
1191
+ if (fence === undefined)
1192
+ fence = marker;
1193
+ else if (marker.length >= fence.length)
1194
+ fence = undefined;
1195
+ return true;
1196
+ }
1197
+ return fence !== undefined || lines[index - 1]?.trim() !== ":::notion-opaque" || markdownLink(line.trimStart()) === null;
1198
+ }).join("\n");
1154
1199
  }
1155
1200
  function notionDocument(pageId, tree, mentions, emailMentions, comments) {
1156
1201
  const markdown = renderNotionTreeToMarkdown(tree, mentions, emailMentions) + comments;
@@ -1354,15 +1399,35 @@ function replaceIframeSources(markdown, sources) {
1354
1399
  });
1355
1400
  }).join("\n");
1356
1401
  }
1402
+ function replaceAttachmentLinks(markdown, sources) {
1403
+ let fence;
1404
+ return markdown.split("\n").map((line) => {
1405
+ const marker = /^ *(`{3,})/.exec(line)?.[1];
1406
+ if (marker !== undefined) {
1407
+ if (fence === undefined)
1408
+ fence = marker;
1409
+ else if (marker.length >= fence.length)
1410
+ fence = undefined;
1411
+ return line;
1412
+ }
1413
+ if (fence !== undefined)
1414
+ return line;
1415
+ return line.replace(/^( *!?\[.*\]\()(.+)(\))$/, (match, prefix, source, suffix) => {
1416
+ const replacement = sources.get(source);
1417
+ return replacement === undefined ? match : `${prefix}${replacement}${suffix}`;
1418
+ });
1419
+ }).join("\n");
1420
+ }
1357
1421
  export async function materializeNotionDocument(runtime, document, markdownPath, previous) {
1358
1422
  const data = object(document.data);
1359
1423
  const embeds = data["html_embeds"];
1360
- if (embeds === undefined || embeds.length === 0)
1424
+ const attachments = data["attachments"] ?? [];
1425
+ if ((embeds === undefined || embeds.length === 0) && attachments.length === 0)
1361
1426
  return document;
1362
1427
  const known = data["html_assets"] ?? (previous === undefined ? [] : object(previous)["html_assets"] ?? []);
1363
1428
  const assets = [];
1364
1429
  const sources = new Map();
1365
- for (const embed of embeds) {
1430
+ for (const embed of embeds ?? []) {
1366
1431
  let asset = known.find((item) => item.source === embed.source);
1367
1432
  if (asset === undefined || !await runtime.filesystem.exists(asset.path)) {
1368
1433
  const cookies = await runtime.cookies.loadSaved("notion");
@@ -1388,8 +1453,41 @@ export async function materializeNotionDocument(runtime, document, markdownPath,
1388
1453
  sources.set(embed.source, pathToFileURL(asset.path).href);
1389
1454
  }
1390
1455
  const remoteMarkdown = data["remote_markdown"] ?? document.markdown;
1391
- const markdown = replaceIframeSources(remoteMarkdown, sources);
1392
- return { ...document, markdown, data: { ...data, markdown, remote_markdown: remoteMarkdown, html_assets: assets } };
1456
+ const attachmentAssets = [];
1457
+ const attachmentSources = new Map();
1458
+ const previousAttachments = data["attachment_assets"] ?? (previous === undefined ? [] : object(previous)["attachment_assets"] ?? []);
1459
+ for (const attachment of attachments) {
1460
+ const known = previousAttachments.find((asset) => asset.source === attachment.source);
1461
+ const name = attachment.name.replace(/[/\\<>:"|?*\x00-\x1f]/g, "_");
1462
+ const extension = extname(name);
1463
+ const filename = [...basename(name, extension)].slice(0, 40).join("") + [...extension].slice(0, 16).join("");
1464
+ const key = createHash("sha256").update(attachment.source).digest("hex").slice(0, 16);
1465
+ const path = known?.path ?? resolve(dirname(markdownPath), `${basename(markdownPath, extname(markdownPath))}.assets`, `${key}-${filename}`);
1466
+ if (!known || !await runtime.filesystem.exists(path)) {
1467
+ if (!runtime.filesystem.readBytes || !runtime.filesystem.writeBytes)
1468
+ throw new Error("This filesystem does not support binary downloads");
1469
+ const cookies = await runtime.cookies.loadSaved("notion");
1470
+ if (cookies === null)
1471
+ throw notionAuthError();
1472
+ const cookie = cookies.map(({ name, value }) => `${name}=${value}`).join("; ");
1473
+ const signed = await notionPost(runtime, "getSignedFileUrls", cookie, { urls: [{ url: attachment.source, permissionRecord: { table: "block", id: attachment.block_id, spaceId: attachment.space_id } }] }, {});
1474
+ const url = signed["signedUrls"][0];
1475
+ const target = new URL(url);
1476
+ if (target.protocol !== "https:")
1477
+ throw new Error("Unexpected Notion attachment download protocol");
1478
+ const response = await runtime.http.request(url, { ...(target.hostname === "file.notion.so" ? { headers: { cookie }, redirect: "error" } : {}) });
1479
+ if (!response.ok)
1480
+ throw new Error(`Notion attachment download failed: ${response.status}`);
1481
+ const contents = new Uint8Array(await response.arrayBuffer());
1482
+ if (await runtime.filesystem.exists(path) && !Buffer.from(await runtime.filesystem.readBytes(path)).equals(contents))
1483
+ throw new Error(`Local attachment edits exist: ${path}`);
1484
+ await runtime.filesystem.writeBytes(path, contents);
1485
+ }
1486
+ attachmentAssets.push({ source: attachment.source, path });
1487
+ attachmentSources.set(encodeURI(attachment.source), pathToFileURL(path).href);
1488
+ }
1489
+ const markdown = replaceAttachmentLinks(replaceIframeSources(remoteMarkdown, sources), attachmentSources);
1490
+ return { ...document, markdown, data: { ...data, markdown, remote_markdown: remoteMarkdown, html_assets: assets, attachment_assets: attachmentAssets } };
1393
1491
  }
1394
1492
  async function uploadHtmlEmbeds(runtime, blocks, markdownPath, pageId, spaceId, cookie, headers, assets) {
1395
1493
  for (const block of blocks) {
@@ -1419,7 +1517,7 @@ async function uploadHtmlEmbeds(runtime, blocks, markdownPath, pageId, spaceId,
1419
1517
  }
1420
1518
  }
1421
1519
  export async function uploadNotionDocument(runtime, markdown, markdownPath) {
1422
- const split = splitTitle(withoutComments(markdown));
1520
+ const split = splitTitle(withoutReadOnlyContent(markdown));
1423
1521
  if (split.title === "")
1424
1522
  throw new Error("Markdown document requires a first heading");
1425
1523
  const cookies = await runtime.cookies.loadSaved("notion");
@@ -1491,8 +1589,10 @@ function splitTitle(markdown) {
1491
1589
  export async function synchronizeNotionDocument(runtime, url, source, base, markdown, markdownPath, observeRemote, requireConditionalWrite = false) {
1492
1590
  const data = object(base);
1493
1591
  const assets = [...(data["html_assets"] ?? [])];
1592
+ const attachmentAssets = data["attachment_assets"] ?? [];
1593
+ markdown = replaceAttachmentLinks(markdown, new Map(attachmentAssets.map((asset) => [pathToFileURL(asset.path).href, encodeURI(asset.source)])));
1494
1594
  const sources = new Map();
1495
- for (const block of parseNotionMarkdown(splitTitle(withoutComments(markdown)).body)) {
1595
+ for (const block of parseNotionMarkdown(splitTitle(withoutReadOnlyContent(markdown)).body)) {
1496
1596
  const src = block.properties["source"];
1497
1597
  if (block.type !== "embed" || src === undefined || src.startsWith("attachment:") || /^https?:/.test(src))
1498
1598
  continue;
@@ -1502,8 +1602,8 @@ export async function synchronizeNotionDocument(runtime, url, source, base, mark
1502
1602
  sources.set(src, asset?.source ?? `${pathToFileURL(path).href}#${digest}`);
1503
1603
  }
1504
1604
  const remoteBase = { ...data, markdown: data["remote_markdown"] ?? data["markdown"] };
1505
- 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);
1506
- return { ...await materializeNotionDocument(runtime, { ...result, data: { ...object(result.data), html_assets: assets } }, markdownPath), wroteRemote: result.wroteRemote };
1605
+ 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, attachment_assets: attachmentAssets } }, markdownPath)); }, requireConditionalWrite);
1606
+ return { ...await materializeNotionDocument(runtime, { ...result, data: { ...object(result.data), html_assets: assets, attachment_assets: attachmentAssets } }, markdownPath), wroteRemote: result.wroteRemote };
1507
1607
  }
1508
1608
  async function synchronizeNotionContent(runtime, url, source, base, markdown, markdownPath, assets, observeRemote, requireConditionalWrite) {
1509
1609
  const remote = await fetchTree(runtime, url, source);
@@ -1525,9 +1625,9 @@ async function synchronizeNotionContent(runtime, url, source, base, markdown, ma
1525
1625
  const emailMentions = { ...baseObject["email_mentions"] };
1526
1626
  const observed = notionDocument(remote.tree.id, remote.tree, mentions, { ...emailMentions }, remote.comments);
1527
1627
  await observeRemote?.(observed);
1528
- const currentMarkdown = withoutComments(observed.markdown);
1529
- const baseMarkdown = baseObject["markdown"] === undefined ? undefined : withoutComments(baseObject["markdown"]);
1530
- let split = splitTitle(withoutComments(markdown));
1628
+ const currentMarkdown = withoutReadOnlyContent(observed.markdown);
1629
+ const baseMarkdown = baseObject["markdown"] === undefined ? undefined : withoutReadOnlyContent(baseObject["markdown"]);
1630
+ let split = splitTitle(withoutReadOnlyContent(markdown));
1531
1631
  const currentSplit = splitTitle(currentMarkdown);
1532
1632
  const baseSplit = baseMarkdown === undefined ? undefined : splitTitle(baseMarkdown);
1533
1633
  let fieldMerged = false;