@kamilio/wire 0.1.44 → 0.1.45

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 +593 -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 +476 -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
  import type { FetchedDocument, JsonObject, JsonValue, RuntimeCapabilities, Source } from "wire-core";
4
7
 
@@ -21,21 +24,49 @@ function filenameTitle(value: string, label: string): string {
21
24
  return filename.replace(/\.(csv|html|md|pptx|txt|xlsx)$/i, "");
22
25
  }
23
26
 
24
- async function googleExport(runtime: RuntimeCapabilities, url: string, label: string): Promise<Readonly<{ title: string; text: string }>> {
25
- const response = await runtime.http.request(url, { headers: { Cookie: await cookieHeader(runtime) } });
26
- if (response.status === 401 || response.status === 403) throw cookieAuthenticationError();
27
+ async function docExportRequest(runtime: RuntimeCapabilities, url: string, token: string | null): Promise<Response> {
28
+ if (token === null) {
29
+ const init = { headers: { Cookie: await cookieHeader(runtime) } };
30
+ return url.startsWith("https://docs.google.com/document/") ? googleRead(runtime, url, init) : runtime.http.request(url, init);
31
+ }
32
+ // The tab-specific export accepts OAuth and returns a signed download URL.
33
+ // Never forward the access token to the download host or to a login page.
34
+ const first = await googleRead(runtime, url, { headers: { Authorization: "Bearer " + token }, redirect: "manual" });
35
+ if (first.status < 300 || first.status >= 400) return first;
36
+ const location = first.headers.get("location");
37
+ if (!location) throw new Error("Google Docs export did not include a download URL");
38
+ const target = new URL(location);
39
+ if (target.protocol !== "https:" || !target.hostname.endsWith(".googleusercontent.com") || target.username || target.password || target.port) throw new Error("Google Docs export returned an unexpected download URL");
40
+ return googleRead(runtime, target, { redirect: "error" });
41
+ }
42
+
43
+ async function googleExport(runtime: RuntimeCapabilities, url: string, label: string, token: string | null = null): Promise<Readonly<{ title: string; text: string }>> {
44
+ const response = await docExportRequest(runtime, url, token);
45
+ if (response.status === 401 || response.status === 403) {
46
+ if (token !== null) throw new Error(`Google ${label} failed: OAuth access denied (HTTP ${response.status})`);
47
+ throw cookieAuthenticationError();
48
+ }
27
49
  if (!response.ok) throw new Error(`Google ${label} failed: HTTP ${response.status}`);
28
50
  const disposition = response.headers.get("content-disposition");
29
- if (disposition === null) throw cookieAuthenticationError();
51
+ if (disposition === null) {
52
+ if (token !== null) throw new Error(`Google ${label} did not include a filename`);
53
+ throw cookieAuthenticationError();
54
+ }
30
55
  return Object.freeze({ title: filenameTitle(disposition, label), text: await response.text() });
31
56
  }
32
57
 
33
- async function googleExportBytes(runtime: RuntimeCapabilities, url: string, label: string): Promise<Readonly<{ title: string; bytes: Uint8Array }>> {
34
- const response = await runtime.http.request(url, { headers: { Cookie: await cookieHeader(runtime) } });
35
- if (response.status === 401 || response.status === 403) throw cookieAuthenticationError();
58
+ async function googleExportBytes(runtime: RuntimeCapabilities, url: string, label: string, token: string | null = null): Promise<Readonly<{ title: string; bytes: Uint8Array }>> {
59
+ const response = await docExportRequest(runtime, url, token);
60
+ if (response.status === 401 || response.status === 403) {
61
+ if (token !== null) throw new Error(`Google ${label} failed: OAuth access denied (HTTP ${response.status})`);
62
+ throw cookieAuthenticationError();
63
+ }
36
64
  if (!response.ok) throw new Error(`Google ${label} failed: HTTP ${response.status}`);
37
65
  const disposition = response.headers.get("content-disposition");
38
- if (disposition === null) throw cookieAuthenticationError();
66
+ if (disposition === null) {
67
+ if (token !== null) throw new Error(`Google ${label} did not include a filename`);
68
+ throw cookieAuthenticationError();
69
+ }
39
70
  return Object.freeze({ title: filenameTitle(disposition, label), bytes: new Uint8Array(await response.arrayBuffer()) });
40
71
  }
41
72
 
@@ -199,13 +230,6 @@ function sheetEditUrl(documentId: string, gid: string | null, key: string | null
199
230
  return url.toString();
200
231
  }
201
232
 
202
- function docEditUrl(documentId: string, key: string | null, tab: string): string {
203
- const url = new URL(`https://docs.google.com/document/d/${encodeURIComponent(documentId)}/edit`);
204
- url.searchParams.set("tab", tab);
205
- if (key !== null) url.searchParams.set("resourcekey", key);
206
- return url.toString();
207
- }
208
-
209
233
  function documentTab(source: Source): string | null {
210
234
  const tab = source["document_tab"];
211
235
  return typeof tab === "string" && tab !== "" ? tab : null;
@@ -546,26 +570,6 @@ async function uploadSheetRows(runtime: RuntimeCapabilities, documentId: string,
546
570
  if (result["revisionRanges"] === undefined) throw new Error("Google Sheets save failed: missing revision ranges");
547
571
  }
548
572
 
549
- function docSession(html: string): Readonly<{ token: string; ouid: string; revision: number; text: string }> {
550
- const tokenMatch = /"info_params":\{"token":"([^"]+)"/.exec(html);
551
- if (tokenMatch === null) throw cookieAuthenticationError();
552
- const token = tokenMatch[1]!;
553
- const ouidMatch = /"ouid":"([^"]+)"/.exec(html);
554
- const revisionMatch = /DOCS_warmStartDocumentLoader\.startLoad\(\s*([0-9.]+)/.exec(html);
555
- if (ouidMatch === null || revisionMatch === null) throw new Error("Google Docs editor did not include save metadata");
556
- const ouid = ouidMatch[1]!;
557
- const revision = Number(revisionMatch[1]!);
558
- const chunks: string[] = [];
559
- const pattern = /DOCS_modelChunk = (\{[\s\S]*?\}); DOCS_modelChunkLoadStart/g;
560
- let match = pattern.exec(html);
561
- while (match !== null) {
562
- const chunk = JSON.parse(match[1]!) as { readonly chunk: readonly JsonObject[] };
563
- for (const command of chunk.chunk) if (command["ty"] === "is") chunks.push(command["s"] as string);
564
- match = pattern.exec(html);
565
- }
566
- return Object.freeze({ token, ouid, revision, text: chunks.join("") });
567
- }
568
-
569
573
  function markdownDocTable(value: string): string {
570
574
  const lines = value.trimEnd().split(/\r?\n/);
571
575
  const separator = lines.findIndex((line) => markdownTableRow(line).every((cell) => /^:?-{3,}:?$/.test(cell)));
@@ -618,212 +622,82 @@ export async function googleDocListMarkdown(markdown: string, wordExport: () =>
618
622
  }).join("\n");
619
623
  }
620
624
 
621
- function comparableDocMarkdown(value: string): string {
622
- return markdownEntities(markdownHtmlTags(markdownCombinedEmphasis(value.replace(/[ \t]{2,}(?=\r?\n|$)/g, "").replace(/\\([\\`*_{}\[\]()#+\-.!|=~])/g, "$1").replace(/\s+$/g, ""))));
623
- }
624
-
625
- function docMarkdownEqual(left: string, right: string): boolean {
626
- return comparableDocMarkdown(left) === comparableDocMarkdown(right);
627
- }
628
-
629
- type TextEdit = Readonly<{ base: string; local: string; before: string; localBefore: string; after: string; localAfter: string }>;
630
- type MarkdownSpan = Readonly<{ start: number; end: number }>;
631
-
632
- function textEdit(base: string, local: string): TextEdit {
633
- let start = 0;
634
- while (start < base.length && start < local.length && base[start] === local[start]) start += 1;
635
- for (let window = 80; window >= 10; window -= 10) {
636
- for (let baseEnd = start; baseEnd <= Math.min(base.length - window, start + 2000); baseEnd += 1) {
637
- const anchor = base.slice(baseEnd, baseEnd + window);
638
- const localEnd = local.indexOf(anchor, start);
639
- if (localEnd !== -1 && localEnd <= start + 2000) 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) });
625
+ type GoogleReadResult = FetchedDocument & { readRevision?: string };
626
+
627
+ async function fetchGoogleDocument(runtime: RuntimeCapabilities, source: Source, previous?: JsonValue): Promise<GoogleReadResult> {
628
+ const id = (source["document_id"] as string | undefined) ?? source.identifier;
629
+ const key = resourceKey(source);
630
+ const gid = source["sheet_gid"] as string | null | undefined;
631
+ const tab = documentTab(source);
632
+ const query = new URLSearchParams();
633
+ if (gid !== undefined || source.type === "presentation") {
634
+ const slide = source.type === "presentation";
635
+ query.set("format", slide ? "pptx" : "csv");
636
+ if (gid != null) query.set("gid", gid);
637
+ if (key) query.set("resourcekey", key);
638
+ const url = `https://docs.google.com/${slide ? "presentation" : "spreadsheets"}/d/${encodeURIComponent(id)}/export?${query}`;
639
+ if (slide) {
640
+ const { bytes, title } = await googleExportBytes(runtime, url, "Slides PPTX export");
641
+ const markdown = slidesMarkdown(bytes);
642
+ return { title, markdown, data: { document_id: id, title, output_path: null, sheet_gid: null, markdown, rows: null, presentation: true } };
640
643
  }
644
+ const { text, title } = await googleExport(runtime, url, "Sheets CSV export");
645
+ const rows = parseCsv(text), markdown = sheetMarkdown(rows);
646
+ return { title, markdown, data: { document_id: id, title, output_path: null, sheet_gid: gid ?? null, markdown, rows } };
641
647
  }
642
- let baseEnd = base.length;
643
- let localEnd = local.length;
644
- while (baseEnd > start && localEnd > start && base[baseEnd - 1] === local[localEnd - 1]) { baseEnd -= 1; localEnd -= 1; }
645
- 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) });
646
- }
647
-
648
- function textEdits(base: string, local: string): readonly TextEdit[] {
649
- const edits: TextEdit[] = [];
650
- let basePrefix = "";
651
- let localPrefix = "";
652
- let baseRest = base;
653
- let localRest = local;
654
- while (baseRest !== localRest) {
655
- const edit = textEdit(baseRest, localRest);
656
- const before = `${basePrefix}${edit.before}`;
657
- const localBefore = `${localPrefix}${edit.before}`;
658
- edits.push(Object.freeze({ ...edit, before, localBefore }));
659
- basePrefix = base.slice(0, base.length - edit.after.length);
660
- localPrefix = local.slice(0, local.length - edit.localAfter.length);
661
- baseRest = edit.after;
662
- localRest = edit.localAfter;
663
- }
664
- return edits;
665
- }
666
648
 
667
- function inlineMarkdownSpans(value: string): readonly MarkdownSpan[] {
668
- const spans: MarkdownSpan[] = [];
669
- 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]) {
670
- let match = pattern.exec(value);
671
- while (match !== null) {
672
- spans.push(Object.freeze({ start: match.index, end: match.index + match[0]!.length }));
673
- match = pattern.exec(value);
649
+ const grant = await nativeDocsGrant(runtime, true);
650
+ const read = async (url: string) => {
651
+ const response = await googleRead(runtime, url, { headers: { Authorization: "Bearer " + grant!.token, ...(key && { "X-Goog-Drive-Resource-Keys": id + "/" + key }) }, redirect: "error" });
652
+ if (!response.ok) throw new Error("Google Docs export failed: HTTP " + response.status);
653
+ return response;
654
+ };
655
+ let readRevision: string | undefined, docTitle: string | undefined;
656
+ if (grant && (previous !== undefined || grant.canWrite)) {
657
+ const url = "https://docs.googleapis.com/v1/documents/" + encodeURIComponent(id) + "?fields=documentId,title,revisionId";
658
+ const meta = await (await read(url)).json() as { documentId?: string; title?: string; revisionId?: string };
659
+ if (meta.documentId !== id || typeof meta.title !== "string") throw new Error("Google Docs export returned unexpected document metadata");
660
+ readRevision = meta.revisionId; docTitle = meta.title;
661
+ const snapshot = previous === undefined ? {} : objectValue(previous);
662
+ // Only a successfully verified, revision-controlled batch sets this key.
663
+ // Never use Drive's version, ETag, or modifiedTime as a document revision.
664
+ if (readRevision && snapshot["verified_revision"] === readRevision && snapshot["document_id"] === id && (snapshot["document_tab"] ?? null) === tab && typeof snapshot["markdown"] === "string") {
665
+ return { title: docTitle, markdown: snapshot["markdown"], readRevision, data: { ...snapshot, title: docTitle } };
674
666
  }
675
667
  }
676
- return spans;
677
- }
678
-
679
- function editTouchesMarkdownSpan(before: string, value: string, edited: string): boolean {
680
- const start = before.length;
681
- const end = start + edited.length;
682
- return inlineMarkdownSpans(value).some((span) => start === end ? start > span.start && start < span.end : start < span.end && end > span.start);
683
- }
684
-
685
- function context(value: string, side: "before" | "after", length: number): string {
686
- return side === "before" ? value.slice(Math.max(0, value.length - length)) : value.slice(0, length);
687
- }
688
668
 
689
- function followingWhitespaceEnd(text: string, index: number): number {
690
- let end = index;
691
- while (end < text.length && /\s/.test(text[end]!)) end += 1;
692
- return end;
693
- }
694
-
695
- function docTextRange(text: string, edit: Readonly<{ base: string; before: string; after: string }>): Readonly<{ start: number; end: number }> {
696
- const base = markdownText(edit.base);
697
- const beforeText = markdownText(edit.before);
698
- const afterText = markdownText(edit.after);
699
- const candidates: number[] = [];
700
- if (base === "") {
701
- if (beforeText !== "") {
702
- const anchor = context(beforeText, "before", Math.min(80, beforeText.length));
703
- const trimmed = anchor.replace(/\s+$/g, "");
704
- let index = 0;
705
- for (;;) {
706
- const found = text.indexOf(anchor, index);
707
- if (found === -1) break;
708
- candidates.push(found + anchor.length);
709
- index = found + 1;
710
- }
711
- if (trimmed !== anchor) {
712
- index = 0;
713
- for (;;) {
714
- const found = text.indexOf(trimmed, index);
715
- if (found === -1) break;
716
- candidates.push(followingWhitespaceEnd(text, found + trimmed.length));
717
- index = found + 1;
718
- }
719
- }
669
+ let title: string, markdown: string;
670
+ if (grant?.driveExport && tab === null) {
671
+ // Drive export is unscoped and includes every tab. Never route an explicit
672
+ // tab, including t.0, through this endpoint.
673
+ const url = "https://www.googleapis.com/drive/v3/files/" + encodeURIComponent(id);
674
+ if (docTitle !== undefined) title = docTitle;
675
+ else {
676
+ const meta = await (await read(url + "?fields=id,name&supportsAllDrives=true")).json() as { id?: string; name?: string };
677
+ if (meta.id !== id || typeof meta.name !== "string") throw new Error("Google Docs export returned unexpected Drive file metadata");
678
+ title = meta.name;
720
679
  }
721
- if (afterText === "") {
722
- candidates.push(text.length);
723
- } else {
724
- const anchor = context(afterText, "after", Math.min(80, afterText.length));
725
- let index = 0;
726
- for (;;) {
727
- const found = text.indexOf(anchor, index);
728
- if (found === -1) break;
729
- candidates.push(found);
730
- index = found + 1;
731
- }
732
- }
733
- } else {
734
- let index = 0;
735
- for (;;) {
736
- const found = text.indexOf(base, index);
737
- if (found === -1) break;
738
- candidates.push(found);
739
- index = found + 1;
740
- }
741
- }
742
- const uniqueCandidates = [...new Set(candidates)];
743
- for (const length of [80, 40, 20, 10, 0]) {
744
- const before = context(beforeText, "before", length);
745
- const after = context(afterText, "after", length);
746
- 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);
747
- if (matched.length === 1) return Object.freeze({ start: matched[0]!, end: matched[0]! + base.length });
748
- }
749
- throw new Error("Google Docs local edit cannot be mapped to the live document text");
750
- }
751
-
752
- async function uploadDocText(runtime: RuntimeCapabilities, documentId: string, key: string | null, tab: string, baseMarkdown: string, localMarkdown: string): Promise<void> {
753
- const edits = textEdits(baseMarkdown, localMarkdown);
754
- // The editor endpoint writes text only. Never let a multiline replacement
755
- // recreate list paragraphs without their original list and nesting metadata.
756
- const prefixes = (s: string) => s.match(/^[ \t]*(?:[-*+]|\d+[.)])[ \t]+/gm) ?? [];
757
- if (prefixes(baseMarkdown).join("\n") !== prefixes(localMarkdown).join("\n") ||
758
- edits.some(edit => [edit.base, edit.local].some(s => /\n[ \t]*(?:[-*+]|\d+[.)])[ \t]+/.test(s)))) {
759
- throw new Error("Google Docs sync cannot preserve formatting in edited text: change the list structure in Google Docs");
760
- }
761
- if (edits.some((edit) => editTouchesMarkdownSpan(edit.before, baseMarkdown, edit.base) || editTouchesMarkdownSpan(edit.localBefore, localMarkdown, edit.local))) throw new Error("Google Docs sync cannot preserve formatting in edited text");
762
- const editUrl = docEditUrl(documentId, key, tab);
763
- const session = docSession(await googleText(runtime, editUrl, "Docs editor"));
764
- const ranges = edits.map((edit) => ({ edit, range: docTextRange(session.text, edit) })).sort((left, right) => right.range.start - left.range.start);
765
- const sid = runtime.clock.now().getTime().toString(16).padStart(16, "0").slice(-16);
766
- const commands = ranges.flatMap(({ edit, range }) => [
767
- ...(range.start === range.end ? [] : [{ ty: "ds", si: range.start + 1, ei: range.end }]),
768
- ...(edit.local === "" ? [] : [{ ty: "is", ibi: range.start + 1, s: markdownText(edit.local) }]),
769
- ]);
770
- 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 });
771
- const body = new URLSearchParams({ rev: String(session.revision), bundles: JSON.stringify([{ commands, sid, reqId: 0 }]) });
772
- 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() });
773
- if (response.status === 401 || response.status === 403) throw cookieAuthenticationError();
774
- if (!response.ok) throw new Error(`Google Docs save failed: HTTP ${response.status}`);
775
- const text = await response.text();
776
- const result = saveResult(text, "Docs");
777
- if (result["revisionRanges"] === undefined) throw new Error("Google Docs save failed: missing revision ranges");
778
- }
779
-
780
- async function fetchGoogleDocument(runtime: RuntimeCapabilities, source: Source): Promise<FetchedDocument> {
781
- const documentId = (source["document_id"] as string | undefined) ?? source.identifier;
782
- let sheetGid: string | null = null;
783
- let exportUrl: string;
784
- let label: string;
785
- if (source["sheet_gid"] !== undefined) {
786
- const gid = source["sheet_gid"] as string | null;
787
- const query = new URLSearchParams({ format: "csv" });
788
- if (gid !== null) query.set("gid", gid);
789
- const key = resourceKey(source);
790
- if (key !== null) query.set("resourcekey", key);
791
- exportUrl = `https://docs.google.com/spreadsheets/d/${encodeURIComponent(documentId)}/export?${query}`;
792
- label = "Sheets CSV export";
793
- sheetGid = gid;
794
- } else if (source.type === "presentation") {
795
- const query = new URLSearchParams({ format: "pptx" });
796
- const key = resourceKey(source);
797
- if (key !== null) query.set("resourcekey", key);
798
- exportUrl = `https://docs.google.com/presentation/d/${encodeURIComponent(documentId)}/export?${query}`;
799
- label = "Slides PPTX export";
680
+ const format = (mime: string) => read(url + "/export?" + new URLSearchParams({ mimeType: mime }));
681
+ const text = await (await format("text/markdown")).text();
682
+ markdown = await googleDocListMarkdown(text, async () => new Uint8Array(await (await format("application/vnd.openxmlformats-officedocument.wordprocessingml.document")).arrayBuffer()));
800
683
  } else {
801
- const query = new URLSearchParams({ format: "md" });
802
- const key = resourceKey(source);
803
- if (key !== null) query.set("resourcekey", key);
804
- const tab = documentTab(source);
805
- if (tab !== null) query.set("tab", tab);
806
- exportUrl = `https://docs.google.com/document/d/${encodeURIComponent(documentId)}/export?${query}`;
807
- label = "Docs Markdown export";
808
- }
809
- if (source.type === "presentation") {
810
- const exported = await googleExportBytes(runtime, exportUrl, label);
811
- const markdown = slidesMarkdown(exported.bytes);
812
- 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 } });
684
+ query.set("format", "md");
685
+ if (key) query.set("resourcekey", key);
686
+ if (tab) query.set("tab", tab);
687
+ const url = `https://docs.google.com/document/d/${encodeURIComponent(id)}/export?${query}`;
688
+ const exp = await googleExport(runtime, url, "Docs Markdown export", grant?.token ?? null);
689
+ title = exp.title;
690
+ markdown = await googleDocListMarkdown(exp.text, async () => {
691
+ const word = new URL(url);
692
+ word.searchParams.set("format", "docx");
693
+ return (await googleExportBytes(runtime, word.toString(), "Docs Word export", grant?.token ?? null)).bytes;
694
+ });
813
695
  }
814
- const exported = await googleExport(runtime, exportUrl, label);
815
- const rows = source["sheet_gid"] === undefined ? null : parseCsv(exported.text);
816
- const markdown = rows === null ? await googleDocListMarkdown(exported.text, async () => {
817
- const word = new URL(exportUrl);
818
- word.searchParams.set("format", "docx");
819
- return (await googleExportBytes(runtime, word.toString(), "Docs Word export")).bytes;
820
- }) : sheetMarkdown(rows);
821
- const tab = source["sheet_gid"] === undefined ? documentTab(source) : null;
822
- 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 }) } });
696
+ 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 }) } };
823
697
  }
824
698
 
825
699
  async function synchronizeGoogleDocument(runtime: RuntimeCapabilities, _url: string, source: Source, base: JsonValue, markdown: string): Promise<FetchedDocument> {
826
- const remote = await fetchGoogleDocument(runtime, source);
700
+ const remote = await fetchGoogleDocument(runtime, source, base);
827
701
  if (source.type === "presentation") {
828
702
  const baseMarkdown = objectValue(base)["markdown"];
829
703
  if (typeof baseMarkdown !== "string") throw new Error("Google sync base must include markdown");
@@ -834,7 +708,7 @@ async function synchronizeGoogleDocument(runtime: RuntimeCapabilities, _url: str
834
708
  const baseMarkdown = objectValue(base)["markdown"];
835
709
  const label = source["sheet_gid"] === undefined ? "Google Docs" : "Google Sheets";
836
710
  if (typeof baseMarkdown !== "string") throw new Error("Google sync base must include markdown");
837
- if (source["sheet_gid"] === undefined && (docMarkdownEqual(markdown, baseMarkdown) || docMarkdownEqual(markdown, remote.markdown))) return remote;
711
+ if (source["sheet_gid"] === undefined && (markdown.trimEnd() === baseMarkdown.trimEnd() || markdown.trimEnd() === remote.markdown.trimEnd())) return remote;
838
712
  if (source["sheet_gid"] !== undefined) {
839
713
  const baseObject = objectValue(base);
840
714
  if (baseObject["rows"] === undefined) {
@@ -855,14 +729,29 @@ async function synchronizeGoogleDocument(runtime: RuntimeCapabilities, _url: str
855
729
  if (!rowsEqual(stringRows(objectValue(uploaded.data)["rows"]!), localRows)) throw new Error("Google Sheets save verification failed");
856
730
  return uploaded;
857
731
  }
858
- if (source["sheet_gid"] === undefined && docMarkdownEqual(remote.markdown, baseMarkdown)) {
859
- if (markdownText(markdown) === markdownText(baseMarkdown)) throw new Error("Google Docs sync cannot upload formatting-only Markdown edits");
860
- await uploadDocText(runtime, (source["document_id"] as string | undefined) ?? source.identifier, resourceKey(source), documentTab(source) ?? "t.0", baseMarkdown, markdown);
861
- const uploaded = await fetchGoogleDocument(runtime, source);
862
- if (!docMarkdownEqual(uploaded.markdown, markdown)) throw new Error("Google Docs save verification failed");
863
- return uploaded;
732
+ if (documentTab(source) === "t.0" && objectValue(base)["document_id"] && !objectValue(base)["document_tab"] && baseMarkdown !== remote.markdown) {
733
+ 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.");
734
+ }
735
+ const merged = mergeDocBlocks(baseMarkdown, markdown, remote.markdown, nativeDocMarkdownEqual);
736
+ if (merged === remote.markdown) return remote;
737
+ const id = (source["document_id"] as string | undefined) ?? source.identifier;
738
+ const key = resourceKey(source), tab = documentTab(source);
739
+ const snapshot = objectValue(base);
740
+ // A same-looking paragraph can move (or be recreated) without changing
741
+ // Markdown. Positional lookup needs the actual revision of the local base.
742
+ const positionRevision = snapshot["document_id"] === id && (snapshot["document_tab"] ?? null) === tab && baseMarkdown === remote.markdown
743
+ ? snapshot["position_revision"] ?? snapshot["verified_revision"] : undefined;
744
+ let writtenRevision: string | undefined;
745
+ const native = await tryUploadDocBlocks(runtime, id, key, tab, remote.markdown, merged,
746
+ async revision => remote.readRevision === revision ? remote.markdown : (await fetchGoogleDocument(runtime, source)).markdown,
747
+ revision => { writtenRevision = revision; }, typeof positionRevision === "string" ? positionRevision : undefined);
748
+ if (!native) 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.");
749
+ const uploaded = await fetchGoogleDocument(runtime, source, {});
750
+ if (!nativeDocMarkdownEqual(uploaded.markdown, merged)) throw new Error("Google Docs save verification failed");
751
+ if (writtenRevision && writtenRevision === uploaded.readRevision) {
752
+ return { ...uploaded, data: { ...objectValue(uploaded.data), verified_revision: writtenRevision } };
864
753
  }
865
- throw new Error(`${label} changed remotely and locally. Resolve the conflict in ${label} or the local Markdown file before syncing again.`);
754
+ return uploaded;
866
755
  }
867
756
 
868
757
  export const googleDocsService = defineService<RuntimeCapabilities>({
@@ -881,7 +770,7 @@ export const googleDocsService = defineService<RuntimeCapabilities>({
881
770
  return Object.freeze({ service: "google-docs", identifier: `${documentId}#gid=${gid ?? "default"}`, type: "spreadsheet", document_id: documentId, sheet_gid: gid, ...resource_key });
882
771
  }
883
772
  const tab = urlParam(url, "tab");
884
- if (tab !== null && tab !== "" && tab !== "t.0") return Object.freeze({ service: "google-docs", identifier: `${documentId}#tab=${tab}`, type: "document", document_id: documentId, document_tab: tab, ...resource_key });
773
+ if (tab !== null && tab !== "") return Object.freeze({ service: "google-docs", identifier: `${documentId}#tab=${tab}`, type: "document", document_id: documentId, document_tab: tab, ...resource_key });
885
774
  return Object.freeze({ service: "google-docs", identifier: documentId, type: "document", ...resource_key });
886
775
  },
887
776
  fetch: (runtime, _url, source) => fetchGoogleDocument(runtime, source),
@@ -0,0 +1,22 @@
1
+ import type { RuntimeCapabilities } from "wire-core";
2
+
3
+ // Only idempotent GETs. Retrying a batch or browser save can apply it twice.
4
+ export async function googleRead(runtime: RuntimeCapabilities, url: string | URL, init: { headers?: HeadersInit; redirect?: RequestRedirect }): Promise<Response> {
5
+ for (let attempt = 0; ; attempt++) {
6
+ const response = await runtime.http.request(url, init);
7
+ if (![429, 502, 503, 504].includes(response.status)) return response;
8
+ const header = response.headers.get("retry-after")?.trim();
9
+ const seconds = header && /^\d+$/.test(header) ? Number(header) : undefined;
10
+ const date = header && /^[A-Za-z]/.test(header) ? Date.parse(header) : NaN;
11
+ const delay = seconds !== undefined ? seconds * 1000 : Number.isFinite(date) ? Math.max(0, date - runtime.clock.now().getTime()) : 1000 * 2 ** attempt;
12
+ if (attempt >= 3 || delay > 30_000) {
13
+ if (response.status === 429) {
14
+ await response.body?.cancel();
15
+ throw new Error(`Google Docs read rate limited (HTTP 429); retry after ${Math.ceil(delay / 1000)} seconds.`);
16
+ }
17
+ return response;
18
+ }
19
+ await response.body?.cancel();
20
+ await new Promise(resolve => setTimeout(resolve, delay));
21
+ }
22
+ }