@kamilio/wire 0.1.44 → 0.1.46

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.
Files changed (41) hide show
  1. package/README.md +7 -1
  2. package/dist/adapters/root.d.ts.map +1 -1
  3. package/dist/adapters/root.js +5 -2
  4. package/dist/adapters/root.js.map +1 -1
  5. package/node_modules/provider-google-docs/dist/doc-blocks.d.ts +10 -0
  6. package/node_modules/provider-google-docs/dist/doc-blocks.d.ts.map +1 -0
  7. package/node_modules/provider-google-docs/dist/doc-blocks.js +142 -0
  8. package/node_modules/provider-google-docs/dist/doc-blocks.js.map +1 -0
  9. package/node_modules/provider-google-docs/dist/google-docs.d.ts.map +1 -1
  10. package/node_modules/provider-google-docs/dist/google-docs.js +134 -252
  11. package/node_modules/provider-google-docs/dist/google-docs.js.map +1 -1
  12. package/node_modules/provider-google-docs/dist/google-read.d.ts +6 -0
  13. package/node_modules/provider-google-docs/dist/google-read.d.ts.map +1 -0
  14. package/node_modules/provider-google-docs/dist/google-read.js +22 -0
  15. package/node_modules/provider-google-docs/dist/google-read.js.map +1 -0
  16. package/node_modules/provider-google-docs/dist/native-docs.d.ts +9 -0
  17. package/node_modules/provider-google-docs/dist/native-docs.d.ts.map +1 -0
  18. package/node_modules/provider-google-docs/dist/native-docs.js +624 -0
  19. package/node_modules/provider-google-docs/dist/native-docs.js.map +1 -0
  20. package/node_modules/provider-google-docs/src/doc-blocks.ts +119 -0
  21. package/node_modules/provider-google-docs/src/google-docs.ts +127 -238
  22. package/node_modules/provider-google-docs/src/google-read.ts +22 -0
  23. package/node_modules/provider-google-docs/src/native-docs.ts +504 -0
  24. package/node_modules/wire-core/dist/core/model.d.ts +1 -0
  25. package/node_modules/wire-core/dist/core/model.d.ts.map +1 -1
  26. package/node_modules/wire-core/dist/operations.d.ts.map +1 -1
  27. package/node_modules/wire-core/dist/operations.js +108 -28
  28. package/node_modules/wire-core/dist/operations.js.map +1 -1
  29. package/node_modules/wire-core/dist/runtime/node.d.ts.map +1 -1
  30. package/node_modules/wire-core/dist/runtime/node.js +7 -2
  31. package/node_modules/wire-core/dist/runtime/node.js.map +1 -1
  32. package/node_modules/wire-core/dist/storage/registry.d.ts +3 -1
  33. package/node_modules/wire-core/dist/storage/registry.d.ts.map +1 -1
  34. package/node_modules/wire-core/dist/storage/registry.js +50 -1
  35. package/node_modules/wire-core/dist/storage/registry.js.map +1 -1
  36. package/node_modules/wire-core/src/core/model.ts +1 -0
  37. package/node_modules/wire-core/src/operations.ts +91 -28
  38. package/node_modules/wire-core/src/runtime/node.ts +6 -2
  39. package/node_modules/wire-core/src/storage/registry.ts +41 -2
  40. package/package.json +1 -1
  41. package/src/adapters/root.ts +5 -2
@@ -1,4 +1,7 @@
1
1
  import { defineService } from "wire-core";
2
+ import { mergeDocBlocks } from "./doc-blocks.js";
3
+ import { googleRead } from "./google-read.js";
4
+ import { nativeDocMarkdownEqual, nativeDocsGrant, tryUploadDocBlocks } from "./native-docs.js";
2
5
  import { inflateRawSync } from "node:zlib";
3
6
  async function cookieHeader(runtime) {
4
7
  const cookies = await runtime.cookies.loadSaved("google-docs");
@@ -18,26 +21,56 @@ function filenameTitle(value, label) {
18
21
  const filename = encoded !== null ? decodeURIComponent(encoded[1]) : quoted !== null ? quoted[1] : bare[1].trim();
19
22
  return filename.replace(/\.(csv|html|md|pptx|txt|xlsx)$/i, "");
20
23
  }
21
- async function googleExport(runtime, url, label) {
22
- const response = await runtime.http.request(url, { headers: { Cookie: await cookieHeader(runtime) } });
23
- if (response.status === 401 || response.status === 403)
24
+ async function docExportRequest(runtime, url, token) {
25
+ if (token === null) {
26
+ const init = { headers: { Cookie: await cookieHeader(runtime) } };
27
+ return url.startsWith("https://docs.google.com/document/") ? googleRead(runtime, url, init) : runtime.http.request(url, init);
28
+ }
29
+ // The tab-specific export accepts OAuth and returns a signed download URL.
30
+ // Never forward the access token to the download host or to a login page.
31
+ const first = await googleRead(runtime, url, { headers: { Authorization: "Bearer " + token }, redirect: "manual" });
32
+ if (first.status < 300 || first.status >= 400)
33
+ return first;
34
+ const location = first.headers.get("location");
35
+ if (!location)
36
+ throw new Error("Google Docs export did not include a download URL");
37
+ const target = new URL(location);
38
+ if (target.protocol !== "https:" || !target.hostname.endsWith(".googleusercontent.com") || target.username || target.password || target.port)
39
+ throw new Error("Google Docs export returned an unexpected download URL");
40
+ return googleRead(runtime, target, { redirect: "error" });
41
+ }
42
+ async function googleExport(runtime, url, label, token = null) {
43
+ const response = await docExportRequest(runtime, url, token);
44
+ if (response.status === 401 || response.status === 403) {
45
+ if (token !== null)
46
+ throw new Error(`Google ${label} failed: OAuth access denied (HTTP ${response.status})`);
24
47
  throw cookieAuthenticationError();
48
+ }
25
49
  if (!response.ok)
26
50
  throw new Error(`Google ${label} failed: HTTP ${response.status}`);
27
51
  const disposition = response.headers.get("content-disposition");
28
- if (disposition === null)
52
+ if (disposition === null) {
53
+ if (token !== null)
54
+ throw new Error(`Google ${label} did not include a filename`);
29
55
  throw cookieAuthenticationError();
56
+ }
30
57
  return Object.freeze({ title: filenameTitle(disposition, label), text: await response.text() });
31
58
  }
32
- async function googleExportBytes(runtime, url, label) {
33
- const response = await runtime.http.request(url, { headers: { Cookie: await cookieHeader(runtime) } });
34
- if (response.status === 401 || response.status === 403)
59
+ async function googleExportBytes(runtime, url, label, token = null) {
60
+ const response = await docExportRequest(runtime, url, token);
61
+ if (response.status === 401 || response.status === 403) {
62
+ if (token !== null)
63
+ throw new Error(`Google ${label} failed: OAuth access denied (HTTP ${response.status})`);
35
64
  throw cookieAuthenticationError();
65
+ }
36
66
  if (!response.ok)
37
67
  throw new Error(`Google ${label} failed: HTTP ${response.status}`);
38
68
  const disposition = response.headers.get("content-disposition");
39
- if (disposition === null)
69
+ if (disposition === null) {
70
+ if (token !== null)
71
+ throw new Error(`Google ${label} did not include a filename`);
40
72
  throw cookieAuthenticationError();
73
+ }
41
74
  return Object.freeze({ title: filenameTitle(disposition, label), bytes: new Uint8Array(await response.arrayBuffer()) });
42
75
  }
43
76
  async function googleText(runtime, url, label) {
@@ -215,13 +248,6 @@ function sheetEditUrl(documentId, gid, key) {
215
248
  url.searchParams.set("resourcekey", key);
216
249
  return url.toString();
217
250
  }
218
- function docEditUrl(documentId, key, tab) {
219
- const url = new URL(`https://docs.google.com/document/d/${encodeURIComponent(documentId)}/edit`);
220
- url.searchParams.set("tab", tab);
221
- if (key !== null)
222
- url.searchParams.set("resourcekey", key);
223
- return url.toString();
224
- }
225
251
  function documentTab(source) {
226
252
  const tab = source["document_tab"];
227
253
  return typeof tab === "string" && tab !== "" ? tab : null;
@@ -593,29 +619,6 @@ async function uploadSheetRows(runtime, documentId, gid, key, cells) {
593
619
  if (result["revisionRanges"] === undefined)
594
620
  throw new Error("Google Sheets save failed: missing revision ranges");
595
621
  }
596
- function docSession(html) {
597
- const tokenMatch = /"info_params":\{"token":"([^"]+)"/.exec(html);
598
- if (tokenMatch === null)
599
- throw cookieAuthenticationError();
600
- const token = tokenMatch[1];
601
- const ouidMatch = /"ouid":"([^"]+)"/.exec(html);
602
- const revisionMatch = /DOCS_warmStartDocumentLoader\.startLoad\(\s*([0-9.]+)/.exec(html);
603
- if (ouidMatch === null || revisionMatch === null)
604
- throw new Error("Google Docs editor did not include save metadata");
605
- const ouid = ouidMatch[1];
606
- const revision = Number(revisionMatch[1]);
607
- const chunks = [];
608
- const pattern = /DOCS_modelChunk = (\{[\s\S]*?\}); DOCS_modelChunkLoadStart/g;
609
- let match = pattern.exec(html);
610
- while (match !== null) {
611
- const chunk = JSON.parse(match[1]);
612
- for (const command of chunk.chunk)
613
- if (command["ty"] === "is")
614
- chunks.push(command["s"]);
615
- match = pattern.exec(html);
616
- }
617
- return Object.freeze({ token, ouid, revision, text: chunks.join("") });
618
- }
619
622
  function markdownDocTable(value) {
620
623
  const lines = value.trimEnd().split(/\r?\n/);
621
624
  const separator = lines.findIndex((line) => markdownTableRow(line).every((cell) => /^:?-{3,}:?$/.test(cell)));
@@ -667,222 +670,87 @@ export async function googleDocListMarkdown(markdown, wordExport) {
667
670
  return text && outer.has(text) && !other.has(text) ? line.slice(2) : line;
668
671
  }).join("\n");
669
672
  }
670
- function comparableDocMarkdown(value) {
671
- return markdownEntities(markdownHtmlTags(markdownCombinedEmphasis(value.replace(/[ \t]{2,}(?=\r?\n|$)/g, "").replace(/\\([\\`*_{}\[\]()#+\-.!|=~])/g, "$1").replace(/\s+$/g, ""))));
672
- }
673
- function docMarkdownEqual(left, right) {
674
- return comparableDocMarkdown(left) === comparableDocMarkdown(right);
675
- }
676
- function textEdit(base, local) {
677
- let start = 0;
678
- while (start < base.length && start < local.length && base[start] === local[start])
679
- start += 1;
680
- for (let window = 80; window >= 10; window -= 10) {
681
- for (let baseEnd = start; baseEnd <= Math.min(base.length - window, start + 2000); baseEnd += 1) {
682
- const anchor = base.slice(baseEnd, baseEnd + window);
683
- const localEnd = local.indexOf(anchor, start);
684
- if (localEnd !== -1 && localEnd <= start + 2000)
685
- return Object.freeze({ base: base.slice(start, baseEnd), local: local.slice(start, localEnd), before: base.slice(0, start), localBefore: "", after: base.slice(baseEnd), localAfter: local.slice(localEnd) });
673
+ async function fetchGoogleDocument(runtime, source, previous) {
674
+ const id = source["document_id"] ?? source.identifier;
675
+ const key = resourceKey(source);
676
+ const gid = source["sheet_gid"];
677
+ const tab = documentTab(source);
678
+ const query = new URLSearchParams();
679
+ if (gid !== undefined || source.type === "presentation") {
680
+ const slide = source.type === "presentation";
681
+ query.set("format", slide ? "pptx" : "csv");
682
+ if (gid != null)
683
+ query.set("gid", gid);
684
+ if (key)
685
+ query.set("resourcekey", key);
686
+ const url = `https://docs.google.com/${slide ? "presentation" : "spreadsheets"}/d/${encodeURIComponent(id)}/export?${query}`;
687
+ if (slide) {
688
+ const { bytes, title } = await googleExportBytes(runtime, url, "Slides PPTX export");
689
+ const markdown = slidesMarkdown(bytes);
690
+ return { title, markdown, data: { document_id: id, title, output_path: null, sheet_gid: null, markdown, rows: null, presentation: true } };
686
691
  }
692
+ const { text, title } = await googleExport(runtime, url, "Sheets CSV export");
693
+ const rows = parseCsv(text), markdown = sheetMarkdown(rows);
694
+ return { title, markdown, data: { document_id: id, title, output_path: null, sheet_gid: gid ?? null, markdown, rows } };
687
695
  }
688
- let baseEnd = base.length;
689
- let localEnd = local.length;
690
- while (baseEnd > start && localEnd > start && base[baseEnd - 1] === local[localEnd - 1]) {
691
- baseEnd -= 1;
692
- localEnd -= 1;
693
- }
694
- return Object.freeze({ base: base.slice(start, baseEnd), local: local.slice(start, localEnd), before: base.slice(0, start), localBefore: "", after: base.slice(baseEnd), localAfter: local.slice(localEnd) });
695
- }
696
- function textEdits(base, local) {
697
- const edits = [];
698
- let basePrefix = "";
699
- let localPrefix = "";
700
- let baseRest = base;
701
- let localRest = local;
702
- while (baseRest !== localRest) {
703
- const edit = textEdit(baseRest, localRest);
704
- const before = `${basePrefix}${edit.before}`;
705
- const localBefore = `${localPrefix}${edit.before}`;
706
- edits.push(Object.freeze({ ...edit, before, localBefore }));
707
- basePrefix = base.slice(0, base.length - edit.after.length);
708
- localPrefix = local.slice(0, local.length - edit.localAfter.length);
709
- baseRest = edit.after;
710
- localRest = edit.localAfter;
711
- }
712
- return edits;
713
- }
714
- function inlineMarkdownSpans(value) {
715
- const spans = [];
716
- for (const pattern of [/\[[^\]\n]+\]\([^)]+\)/g, /!\[[^\]\n]*\]\([^)]+\)/g, /`[^`\n]+`/g, /~~[^~\n]+~~/g, /\*\*[^*\n]+\*\*/g, /\*[^*\n]+\*/g, /(^|[^\w])__[^_\n]+__(?=[^\w]|$)/g, /(^|[^\w])_[^_\n]+_(?=[^\w]|$)/g, /<((?:https?|mailto):[^>\s]+)>/g, /<\/?(?:u|sup|sub|mark|span)(?:\s+[^>]*)?>/gi]) {
717
- let match = pattern.exec(value);
718
- while (match !== null) {
719
- spans.push(Object.freeze({ start: match.index, end: match.index + match[0].length }));
720
- match = pattern.exec(value);
696
+ const grant = await nativeDocsGrant(runtime, true);
697
+ const read = async (url) => {
698
+ const response = await googleRead(runtime, url, { headers: { Authorization: "Bearer " + grant.token, ...(key && { "X-Goog-Drive-Resource-Keys": id + "/" + key }) }, redirect: "error" });
699
+ if (!response.ok)
700
+ throw new Error("Google Docs export failed: HTTP " + response.status);
701
+ return response;
702
+ };
703
+ let readRevision, docTitle;
704
+ if (grant && (previous !== undefined || grant.canWrite)) {
705
+ const url = "https://docs.googleapis.com/v1/documents/" + encodeURIComponent(id) + "?fields=documentId,title,revisionId";
706
+ const meta = await (await read(url)).json();
707
+ if (meta.documentId !== id || typeof meta.title !== "string")
708
+ throw new Error("Google Docs export returned unexpected document metadata");
709
+ readRevision = meta.revisionId;
710
+ docTitle = meta.title;
711
+ const snapshot = previous === undefined ? {} : objectValue(previous);
712
+ // Only a successfully verified, revision-controlled batch sets this key.
713
+ // Never use Drive's version, ETag, or modifiedTime as a document revision.
714
+ if (readRevision && snapshot["verified_revision"] === readRevision && snapshot["document_id"] === id && (snapshot["document_tab"] ?? null) === tab && typeof snapshot["markdown"] === "string") {
715
+ return { title: docTitle, markdown: snapshot["markdown"], readRevision, data: { ...snapshot, title: docTitle } };
721
716
  }
722
717
  }
723
- return spans;
724
- }
725
- function editTouchesMarkdownSpan(before, value, edited) {
726
- const start = before.length;
727
- const end = start + edited.length;
728
- return inlineMarkdownSpans(value).some((span) => start === end ? start > span.start && start < span.end : start < span.end && end > span.start);
729
- }
730
- function context(value, side, length) {
731
- return side === "before" ? value.slice(Math.max(0, value.length - length)) : value.slice(0, length);
732
- }
733
- function followingWhitespaceEnd(text, index) {
734
- let end = index;
735
- while (end < text.length && /\s/.test(text[end]))
736
- end += 1;
737
- return end;
738
- }
739
- function docTextRange(text, edit) {
740
- const base = markdownText(edit.base);
741
- const beforeText = markdownText(edit.before);
742
- const afterText = markdownText(edit.after);
743
- const candidates = [];
744
- if (base === "") {
745
- if (beforeText !== "") {
746
- const anchor = context(beforeText, "before", Math.min(80, beforeText.length));
747
- const trimmed = anchor.replace(/\s+$/g, "");
748
- let index = 0;
749
- for (;;) {
750
- const found = text.indexOf(anchor, index);
751
- if (found === -1)
752
- break;
753
- candidates.push(found + anchor.length);
754
- index = found + 1;
755
- }
756
- if (trimmed !== anchor) {
757
- index = 0;
758
- for (;;) {
759
- const found = text.indexOf(trimmed, index);
760
- if (found === -1)
761
- break;
762
- candidates.push(followingWhitespaceEnd(text, found + trimmed.length));
763
- index = found + 1;
764
- }
765
- }
766
- }
767
- if (afterText === "") {
768
- candidates.push(text.length);
769
- }
718
+ let title, markdown;
719
+ if (grant?.driveExport && tab === null) {
720
+ // Drive export is unscoped and includes every tab. Never route an explicit
721
+ // tab, including t.0, through this endpoint.
722
+ const url = "https://www.googleapis.com/drive/v3/files/" + encodeURIComponent(id);
723
+ if (docTitle !== undefined)
724
+ title = docTitle;
770
725
  else {
771
- const anchor = context(afterText, "after", Math.min(80, afterText.length));
772
- let index = 0;
773
- for (;;) {
774
- const found = text.indexOf(anchor, index);
775
- if (found === -1)
776
- break;
777
- candidates.push(found);
778
- index = found + 1;
779
- }
726
+ const meta = await (await read(url + "?fields=id,name&supportsAllDrives=true")).json();
727
+ if (meta.id !== id || typeof meta.name !== "string")
728
+ throw new Error("Google Docs export returned unexpected Drive file metadata");
729
+ title = meta.name;
780
730
  }
731
+ const format = (mime) => read(url + "/export?" + new URLSearchParams({ mimeType: mime }));
732
+ const text = await (await format("text/markdown")).text();
733
+ markdown = await googleDocListMarkdown(text, async () => new Uint8Array(await (await format("application/vnd.openxmlformats-officedocument.wordprocessingml.document")).arrayBuffer()));
781
734
  }
782
735
  else {
783
- let index = 0;
784
- for (;;) {
785
- const found = text.indexOf(base, index);
786
- if (found === -1)
787
- break;
788
- candidates.push(found);
789
- index = found + 1;
790
- }
791
- }
792
- const uniqueCandidates = [...new Set(candidates)];
793
- for (const length of [80, 40, 20, 10, 0]) {
794
- const before = context(beforeText, "before", length);
795
- const after = context(afterText, "after", length);
796
- const matched = uniqueCandidates.filter((index) => text.slice(Math.max(0, index - before.length), index) === before && text.slice(index + base.length, index + base.length + after.length) === after);
797
- if (matched.length === 1)
798
- return Object.freeze({ start: matched[0], end: matched[0] + base.length });
799
- }
800
- throw new Error("Google Docs local edit cannot be mapped to the live document text");
801
- }
802
- async function uploadDocText(runtime, documentId, key, tab, baseMarkdown, localMarkdown) {
803
- const edits = textEdits(baseMarkdown, localMarkdown);
804
- // The editor endpoint writes text only. Never let a multiline replacement
805
- // recreate list paragraphs without their original list and nesting metadata.
806
- const prefixes = (s) => s.match(/^[ \t]*(?:[-*+]|\d+[.)])[ \t]+/gm) ?? [];
807
- if (prefixes(baseMarkdown).join("\n") !== prefixes(localMarkdown).join("\n") ||
808
- edits.some(edit => [edit.base, edit.local].some(s => /\n[ \t]*(?:[-*+]|\d+[.)])[ \t]+/.test(s)))) {
809
- throw new Error("Google Docs sync cannot preserve formatting in edited text: change the list structure in Google Docs");
810
- }
811
- if (edits.some((edit) => editTouchesMarkdownSpan(edit.before, baseMarkdown, edit.base) || editTouchesMarkdownSpan(edit.localBefore, localMarkdown, edit.local)))
812
- throw new Error("Google Docs sync cannot preserve formatting in edited text");
813
- const editUrl = docEditUrl(documentId, key, tab);
814
- const session = docSession(await googleText(runtime, editUrl, "Docs editor"));
815
- const ranges = edits.map((edit) => ({ edit, range: docTextRange(session.text, edit) })).sort((left, right) => right.range.start - left.range.start);
816
- const sid = runtime.clock.now().getTime().toString(16).padStart(16, "0").slice(-16);
817
- const commands = ranges.flatMap(({ edit, range }) => [
818
- ...(range.start === range.end ? [] : [{ ty: "ds", si: range.start + 1, ei: range.end }]),
819
- ...(edit.local === "" ? [] : [{ ty: "is", ibi: range.start + 1, s: markdownText(edit.local) }]),
820
- ]);
821
- const params = new URLSearchParams({ id: documentId, sid, vc: "1", c: "1", w: "1", flr: "0", smv: "2147483647", smb: "[2147483647, AAE=]", token: session.token, ouid: session.ouid, includes_info_params: "true", cros_files: "false", nded: "false", tab });
822
- const body = new URLSearchParams({ rev: String(session.revision), bundles: JSON.stringify([{ commands, sid, reqId: 0 }]) });
823
- const response = await runtime.http.request(`https://docs.google.com/document/d/${encodeURIComponent(documentId)}/save?${params}`, { method: "POST", headers: { Cookie: await cookieHeader(runtime), "content-type": "application/x-www-form-urlencoded;charset=UTF-8", origin: "https://docs.google.com", referer: editUrl }, body: body.toString() });
824
- if (response.status === 401 || response.status === 403)
825
- throw cookieAuthenticationError();
826
- if (!response.ok)
827
- throw new Error(`Google Docs save failed: HTTP ${response.status}`);
828
- const text = await response.text();
829
- const result = saveResult(text, "Docs");
830
- if (result["revisionRanges"] === undefined)
831
- throw new Error("Google Docs save failed: missing revision ranges");
832
- }
833
- async function fetchGoogleDocument(runtime, source) {
834
- const documentId = source["document_id"] ?? source.identifier;
835
- let sheetGid = null;
836
- let exportUrl;
837
- let label;
838
- if (source["sheet_gid"] !== undefined) {
839
- const gid = source["sheet_gid"];
840
- const query = new URLSearchParams({ format: "csv" });
841
- if (gid !== null)
842
- query.set("gid", gid);
843
- const key = resourceKey(source);
844
- if (key !== null)
845
- query.set("resourcekey", key);
846
- exportUrl = `https://docs.google.com/spreadsheets/d/${encodeURIComponent(documentId)}/export?${query}`;
847
- label = "Sheets CSV export";
848
- sheetGid = gid;
849
- }
850
- else if (source.type === "presentation") {
851
- const query = new URLSearchParams({ format: "pptx" });
852
- const key = resourceKey(source);
853
- if (key !== null)
854
- query.set("resourcekey", key);
855
- exportUrl = `https://docs.google.com/presentation/d/${encodeURIComponent(documentId)}/export?${query}`;
856
- label = "Slides PPTX export";
857
- }
858
- else {
859
- const query = new URLSearchParams({ format: "md" });
860
- const key = resourceKey(source);
861
- if (key !== null)
736
+ query.set("format", "md");
737
+ if (key)
862
738
  query.set("resourcekey", key);
863
- const tab = documentTab(source);
864
- if (tab !== null)
739
+ if (tab)
865
740
  query.set("tab", tab);
866
- exportUrl = `https://docs.google.com/document/d/${encodeURIComponent(documentId)}/export?${query}`;
867
- label = "Docs Markdown export";
868
- }
869
- if (source.type === "presentation") {
870
- const exported = await googleExportBytes(runtime, exportUrl, label);
871
- const markdown = slidesMarkdown(exported.bytes);
872
- return Object.freeze({ title: exported.title, markdown, data: { document_id: documentId, title: exported.title, output_path: null, sheet_gid: sheetGid, markdown, rows: null, presentation: true } });
741
+ const url = `https://docs.google.com/document/d/${encodeURIComponent(id)}/export?${query}`;
742
+ const exp = await googleExport(runtime, url, "Docs Markdown export", grant?.token ?? null);
743
+ title = exp.title;
744
+ markdown = await googleDocListMarkdown(exp.text, async () => {
745
+ const word = new URL(url);
746
+ word.searchParams.set("format", "docx");
747
+ return (await googleExportBytes(runtime, word.toString(), "Docs Word export", grant?.token ?? null)).bytes;
748
+ });
873
749
  }
874
- const exported = await googleExport(runtime, exportUrl, label);
875
- const rows = source["sheet_gid"] === undefined ? null : parseCsv(exported.text);
876
- const markdown = rows === null ? await googleDocListMarkdown(exported.text, async () => {
877
- const word = new URL(exportUrl);
878
- word.searchParams.set("format", "docx");
879
- return (await googleExportBytes(runtime, word.toString(), "Docs Word export")).bytes;
880
- }) : sheetMarkdown(rows);
881
- const tab = source["sheet_gid"] === undefined ? documentTab(source) : null;
882
- return Object.freeze({ title: exported.title, markdown, data: { document_id: documentId, title: exported.title, output_path: null, sheet_gid: sheetGid, markdown, rows, ...(tab === null ? {} : { document_tab: tab }) } });
750
+ return { title, markdown, ...(readRevision ? { readRevision } : {}), data: { document_id: id, title, output_path: null, sheet_gid: null, markdown, rows: null, ...(readRevision ? { position_revision: readRevision } : {}), ...(tab === null ? {} : { document_tab: tab }) } };
883
751
  }
884
752
  async function synchronizeGoogleDocument(runtime, _url, source, base, markdown) {
885
- const remote = await fetchGoogleDocument(runtime, source);
753
+ const remote = await fetchGoogleDocument(runtime, source, base);
886
754
  if (source.type === "presentation") {
887
755
  const baseMarkdown = objectValue(base)["markdown"];
888
756
  if (typeof baseMarkdown !== "string")
@@ -897,7 +765,7 @@ async function synchronizeGoogleDocument(runtime, _url, source, base, markdown)
897
765
  const label = source["sheet_gid"] === undefined ? "Google Docs" : "Google Sheets";
898
766
  if (typeof baseMarkdown !== "string")
899
767
  throw new Error("Google sync base must include markdown");
900
- if (source["sheet_gid"] === undefined && (docMarkdownEqual(markdown, baseMarkdown) || docMarkdownEqual(markdown, remote.markdown)))
768
+ if (source["sheet_gid"] === undefined && (markdown.trimEnd() === baseMarkdown.trimEnd() || markdown.trimEnd() === remote.markdown.trimEnd()))
901
769
  return remote;
902
770
  if (source["sheet_gid"] !== undefined) {
903
771
  const baseObject = objectValue(base);
@@ -926,16 +794,30 @@ async function synchronizeGoogleDocument(runtime, _url, source, base, markdown)
926
794
  throw new Error("Google Sheets save verification failed");
927
795
  return uploaded;
928
796
  }
929
- if (source["sheet_gid"] === undefined && docMarkdownEqual(remote.markdown, baseMarkdown)) {
930
- if (markdownText(markdown) === markdownText(baseMarkdown))
931
- throw new Error("Google Docs sync cannot upload formatting-only Markdown edits");
932
- await uploadDocText(runtime, source["document_id"] ?? source.identifier, resourceKey(source), documentTab(source) ?? "t.0", baseMarkdown, markdown);
933
- const uploaded = await fetchGoogleDocument(runtime, source);
934
- if (!docMarkdownEqual(uploaded.markdown, markdown))
935
- throw new Error("Google Docs save verification failed");
936
- return uploaded;
797
+ if (documentTab(source) === "t.0" && objectValue(base)["document_id"] && !objectValue(base)["document_tab"] && baseMarkdown !== remote.markdown) {
798
+ throw new Error("Google Docs saved snapshot predates explicit tab selection. Keep the local edits and reconcile them with a fresh download of this tab.");
799
+ }
800
+ const merged = mergeDocBlocks(baseMarkdown, markdown, remote.markdown, nativeDocMarkdownEqual);
801
+ if (merged === remote.markdown)
802
+ return remote;
803
+ const id = source["document_id"] ?? source.identifier;
804
+ const key = resourceKey(source), tab = documentTab(source);
805
+ const snapshot = objectValue(base);
806
+ // A same-looking paragraph can move (or be recreated) without changing
807
+ // Markdown. Positional lookup needs the actual revision of the local base.
808
+ const positionRevision = snapshot["document_id"] === id && (snapshot["document_tab"] ?? null) === tab && baseMarkdown === remote.markdown
809
+ ? snapshot["position_revision"] ?? snapshot["verified_revision"] : undefined;
810
+ let writtenRevision;
811
+ const native = await tryUploadDocBlocks(runtime, id, key, tab, remote.markdown, merged, async (revision) => remote.readRevision === revision ? remote.markdown : (await fetchGoogleDocument(runtime, source)).markdown, revision => { writtenRevision = revision; }, typeof positionRevision === "string" ? positionRevision : undefined);
812
+ if (!native)
813
+ throw new Error("Google Docs uploads require an OAuth token with drive, drive.file, or both documents and drive.readonly scopes. Set GOOGLE_DOCS_TOKEN_FILE or GOOGLE_FORMS_TOKEN_FILE. Browser login supports downloads only.");
814
+ const uploaded = await fetchGoogleDocument(runtime, source, {});
815
+ if (!nativeDocMarkdownEqual(uploaded.markdown, merged))
816
+ throw new Error("Google Docs save verification failed");
817
+ if (writtenRevision && writtenRevision === uploaded.readRevision) {
818
+ return { ...uploaded, data: { ...objectValue(uploaded.data), verified_revision: writtenRevision } };
937
819
  }
938
- throw new Error(`${label} changed remotely and locally. Resolve the conflict in ${label} or the local Markdown file before syncing again.`);
820
+ return uploaded;
939
821
  }
940
822
  export const googleDocsService = defineService({
941
823
  name: "google-docs",
@@ -954,7 +836,7 @@ export const googleDocsService = defineService({
954
836
  return Object.freeze({ service: "google-docs", identifier: `${documentId}#gid=${gid ?? "default"}`, type: "spreadsheet", document_id: documentId, sheet_gid: gid, ...resource_key });
955
837
  }
956
838
  const tab = urlParam(url, "tab");
957
- if (tab !== null && tab !== "" && tab !== "t.0")
839
+ if (tab !== null && tab !== "")
958
840
  return Object.freeze({ service: "google-docs", identifier: `${documentId}#tab=${tab}`, type: "document", document_id: documentId, document_tab: tab, ...resource_key });
959
841
  return Object.freeze({ service: "google-docs", identifier: documentId, type: "document", ...resource_key });
960
842
  },