@kamilio/wire 0.1.43 → 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.
- package/README.md +8 -2
- package/dist/adapters/gdrive.d.ts.map +1 -1
- package/dist/adapters/gdrive.js +31 -15
- package/dist/adapters/gdrive.js.map +1 -1
- package/dist/adapters/root.d.ts.map +1 -1
- package/dist/adapters/root.js +5 -2
- package/dist/adapters/root.js.map +1 -1
- package/dist/adapters/sheet-markdown.d.ts +48 -0
- package/dist/adapters/sheet-markdown.d.ts.map +1 -0
- package/dist/adapters/sheet-markdown.js +89 -0
- package/dist/adapters/sheet-markdown.js.map +1 -0
- package/node_modules/provider-google-docs/dist/doc-blocks.d.ts +10 -0
- package/node_modules/provider-google-docs/dist/doc-blocks.d.ts.map +1 -0
- package/node_modules/provider-google-docs/dist/doc-blocks.js +142 -0
- package/node_modules/provider-google-docs/dist/doc-blocks.js.map +1 -0
- package/node_modules/provider-google-docs/dist/google-docs.d.ts +1 -0
- package/node_modules/provider-google-docs/dist/google-docs.d.ts.map +1 -1
- package/node_modules/provider-google-docs/dist/google-docs.js +166 -241
- package/node_modules/provider-google-docs/dist/google-docs.js.map +1 -1
- package/node_modules/provider-google-docs/dist/google-read.d.ts +6 -0
- package/node_modules/provider-google-docs/dist/google-read.d.ts.map +1 -0
- package/node_modules/provider-google-docs/dist/google-read.js +22 -0
- package/node_modules/provider-google-docs/dist/google-read.js.map +1 -0
- package/node_modules/provider-google-docs/dist/index.d.ts +1 -1
- package/node_modules/provider-google-docs/dist/index.d.ts.map +1 -1
- package/node_modules/provider-google-docs/dist/index.js +1 -1
- package/node_modules/provider-google-docs/dist/index.js.map +1 -1
- package/node_modules/provider-google-docs/dist/native-docs.d.ts +9 -0
- package/node_modules/provider-google-docs/dist/native-docs.d.ts.map +1 -0
- package/node_modules/provider-google-docs/dist/native-docs.js +593 -0
- package/node_modules/provider-google-docs/dist/native-docs.js.map +1 -0
- package/node_modules/provider-google-docs/src/doc-blocks.ts +119 -0
- package/node_modules/provider-google-docs/src/google-docs.ts +156 -227
- package/node_modules/provider-google-docs/src/google-read.ts +22 -0
- package/node_modules/provider-google-docs/src/index.ts +1 -1
- package/node_modules/provider-google-docs/src/native-docs.ts +476 -0
- package/node_modules/wire-core/dist/core/model.d.ts +1 -0
- 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 +108 -28
- package/node_modules/wire-core/dist/operations.js.map +1 -1
- package/node_modules/wire-core/dist/runtime/node.d.ts.map +1 -1
- package/node_modules/wire-core/dist/runtime/node.js +7 -2
- package/node_modules/wire-core/dist/runtime/node.js.map +1 -1
- package/node_modules/wire-core/dist/storage/registry.d.ts +3 -1
- package/node_modules/wire-core/dist/storage/registry.d.ts.map +1 -1
- package/node_modules/wire-core/dist/storage/registry.js +50 -1
- package/node_modules/wire-core/dist/storage/registry.js.map +1 -1
- package/node_modules/wire-core/src/core/model.ts +1 -0
- package/node_modules/wire-core/src/operations.ts +91 -28
- package/node_modules/wire-core/src/runtime/node.ts +6 -2
- package/node_modules/wire-core/src/storage/registry.ts +41 -2
- package/package.json +1 -1
- package/src/adapters/gdrive.ts +34 -22
- package/src/adapters/root.ts +5 -2
- package/src/adapters/sheet-markdown.ts +89 -0
|
@@ -0,0 +1,593 @@
|
|
|
1
|
+
import { createGoogleTokensCapability, googleTokenExpired, parseGoogleToken } from "wire-core";
|
|
2
|
+
import { googleRead } from "./google-read.js";
|
|
3
|
+
import { docBlocks, docChanges } from "./doc-blocks.js";
|
|
4
|
+
function eligible(scopes, requireWrite) {
|
|
5
|
+
const has = (name) => scopes?.includes("https://www.googleapis.com/auth/" + name);
|
|
6
|
+
if (!requireWrite && (has("documents.readonly") || has("documents") || has("drive.readonly")))
|
|
7
|
+
return true;
|
|
8
|
+
return !!(has("drive") || has("drive.file") || (has("documents") && has("drive.readonly")));
|
|
9
|
+
}
|
|
10
|
+
export async function nativeDocsGrant(runtime, readOnly = false) {
|
|
11
|
+
const optional = (key) => runtime.configuration.getOptional?.(key);
|
|
12
|
+
for (const requireWrite of readOnly ? [true, false] : [true])
|
|
13
|
+
for (const name of ["GOOGLE_DOCS_TOKEN_FILE", "GOOGLE_FORMS_TOKEN_FILE"]) {
|
|
14
|
+
const path = optional(name);
|
|
15
|
+
if (!path || !await runtime.filesystem.exists(path))
|
|
16
|
+
continue;
|
|
17
|
+
let grant = parseGoogleToken(await runtime.filesystem.readText(path));
|
|
18
|
+
if (!eligible(grant.scopes, requireWrite))
|
|
19
|
+
continue;
|
|
20
|
+
if (googleTokenExpired(grant, runtime.clock.now())) {
|
|
21
|
+
const credentials = optional("GOOGLE_CREDENTIALS_FILE");
|
|
22
|
+
if (!credentials)
|
|
23
|
+
throw new Error("Google Docs OAuth refresh requires GOOGLE_CREDENTIALS_FILE.");
|
|
24
|
+
const oauth = { request: (input, init) => {
|
|
25
|
+
if (String(input) !== "https://oauth2.googleapis.com/token" && String(input) !== "https://accounts.google.com/o/oauth2/token")
|
|
26
|
+
throw new Error("Unrecognized Google OAuth token endpoint.");
|
|
27
|
+
return runtime.http.request(input, { ...init, redirect: "error" });
|
|
28
|
+
} };
|
|
29
|
+
grant = await createGoogleTokensCapability(runtime.filesystem, oauth, runtime.clock, credentials, path).refresh();
|
|
30
|
+
if (!eligible(grant.scopes, requireWrite))
|
|
31
|
+
continue;
|
|
32
|
+
}
|
|
33
|
+
if (!grant.token)
|
|
34
|
+
throw new Error("Google Docs OAuth token is missing.");
|
|
35
|
+
return { token: grant.token, canWrite: eligible(grant.scopes, true), driveExport: !!grant.scopes?.some(scope => ["drive", "drive.file", "drive.readonly"].some(name => scope === "https://www.googleapis.com/auth/" + name)) };
|
|
36
|
+
}
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
39
|
+
const unsafe = (detail) => { throw new Error("Google Docs block sync cannot safely apply this edit: " + detail); };
|
|
40
|
+
function paragraph(line) {
|
|
41
|
+
let content = line.replace(/\r?\n$/, "").replace(/ {2}$/, "");
|
|
42
|
+
if (!content || /[\n\r\u0000-\u0008\u000b-\u001f\u007f-\u009f\ue000-\uf8ff]/.test(content) || /^\s*(?:>|`{3}|~{3}|\||!\[|\[[^\]]+\]:|(?:-\s*){3,}$|(?:\*\s*){3,}$)/.test(content))
|
|
43
|
+
return unsafe("unsupported Markdown block");
|
|
44
|
+
const list = /^([ \t]*)([-*+]|\d+[.)]) +/.exec(content);
|
|
45
|
+
const heading = /^(#{1,6}) +/.exec(content);
|
|
46
|
+
let level = null;
|
|
47
|
+
if (list) {
|
|
48
|
+
const indent = list[1].replace(/\t/g, " ").length;
|
|
49
|
+
if (indent % 2 || indent > 16)
|
|
50
|
+
return unsafe("unsupported list indentation");
|
|
51
|
+
level = indent / 2;
|
|
52
|
+
content = content.slice(list[0].length);
|
|
53
|
+
}
|
|
54
|
+
else if (heading)
|
|
55
|
+
content = content.slice(heading[0].length);
|
|
56
|
+
// Interpret only the markup we can encode in Docs. Unknown constructs
|
|
57
|
+
// must never become literal markup, or lose their rich-text semantics.
|
|
58
|
+
let text = "";
|
|
59
|
+
const spans = [];
|
|
60
|
+
const emit = (value, style) => {
|
|
61
|
+
const from = text.length;
|
|
62
|
+
text += value;
|
|
63
|
+
if (value && Object.keys(style).length)
|
|
64
|
+
spans.push({ from, to: text.length, style });
|
|
65
|
+
};
|
|
66
|
+
const read = (s, style, depth) => {
|
|
67
|
+
if (depth > 5)
|
|
68
|
+
return unsafe("unsupported inline formatting");
|
|
69
|
+
let i = 0, begin = 0;
|
|
70
|
+
while (i < s.length) {
|
|
71
|
+
const c = s[i];
|
|
72
|
+
if (c === "\\" && /[\\`*_{}\[\]()#+\-.!|=~>]/.test(s[i + 1] ?? " ")) {
|
|
73
|
+
emit(s.slice(begin, i), style);
|
|
74
|
+
emit(s[i + 1], style);
|
|
75
|
+
begin = i += 2;
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
if (c === "!" && s[i + 1] === "[" || c === "`" || c === "<" && /^<\/?[\w!]/.test(s.slice(i)) || c === "&" && /^&(?:#\d+|#x[\da-f]+|[a-z]+);/i.test(s.slice(i)))
|
|
79
|
+
return unsafe("unsupported inline content");
|
|
80
|
+
if (c === "[") {
|
|
81
|
+
const link = /^\[([^\[\]]+)\]\((https?:\/\/[^\s()]+|mailto:[^\s()]+)\)/.exec(s.slice(i));
|
|
82
|
+
if (!link)
|
|
83
|
+
return unsafe("unsupported link syntax");
|
|
84
|
+
emit(s.slice(begin, i), style);
|
|
85
|
+
read(link[1], { ...style, link: { url: link[2] } }, depth + 1);
|
|
86
|
+
begin = i += link[0].length;
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
const marker = /^(\*{1,3}|_{1,3}|~~)/.exec(s.slice(i))?.[0];
|
|
90
|
+
if (marker && !(c === "_" && /\w/.test(s[i - 1] ?? "") && /\w/.test(s[i + marker.length] ?? ""))) {
|
|
91
|
+
const end = s.indexOf(marker, i + marker.length);
|
|
92
|
+
if (end <= i + marker.length || /\s/.test(s[i + marker.length]) || /\s/.test(s[end - 1]))
|
|
93
|
+
return unsafe("ambiguous emphasis");
|
|
94
|
+
emit(s.slice(begin, i), style);
|
|
95
|
+
read(s.slice(i + marker.length, end), { ...style, ...(marker === "~~" ? { strikethrough: true } : { ...(marker.length >= 2 && { bold: true }), ...(marker.length !== 2 && { italic: true }) }) }, depth + 1);
|
|
96
|
+
begin = i = end + marker.length;
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
i++;
|
|
100
|
+
}
|
|
101
|
+
emit(s.slice(begin), style);
|
|
102
|
+
};
|
|
103
|
+
read(content, {}, 0);
|
|
104
|
+
if (!text || text.startsWith("\t"))
|
|
105
|
+
return unsafe("empty or tab-prefixed paragraph");
|
|
106
|
+
return { text, spans, heading: heading ? "HEADING_" + heading[1].length : "NORMAL_TEXT", level, numbered: !!list && /^\d/.test(list[2]) };
|
|
107
|
+
}
|
|
108
|
+
// One blank separator around a heading or a list is supplied by the Google
|
|
109
|
+
// exporter. Other blank paragraphs are content and must not disappear.
|
|
110
|
+
const blank = "\n";
|
|
111
|
+
function spacedBlocks(md) {
|
|
112
|
+
const rows = docBlocks(md).map(l => l.replace(/\r?\n$/, "").replace(/ {2}$/, ""));
|
|
113
|
+
const separated = (s) => !!s && /^\s*(?:#{1,6}|[-*+]|\d+[.)]) +/.test(s);
|
|
114
|
+
const result = [];
|
|
115
|
+
for (let i = 0; i < rows.length;) {
|
|
116
|
+
if (rows[i].trim()) {
|
|
117
|
+
result.push(rows[i++]);
|
|
118
|
+
continue;
|
|
119
|
+
}
|
|
120
|
+
const start = i;
|
|
121
|
+
while (i < rows.length && !rows[i].trim())
|
|
122
|
+
i++;
|
|
123
|
+
const optional = separated(rows[start - 1]) || separated(rows[i]);
|
|
124
|
+
for (let n = start + Number(optional); n < i; n++)
|
|
125
|
+
result.push(blank);
|
|
126
|
+
}
|
|
127
|
+
return result;
|
|
128
|
+
}
|
|
129
|
+
// In Markdown the first numeric marker sets a list's starting number.
|
|
130
|
+
// Following marker numbers can be rewritten by Docs when a sibling is added.
|
|
131
|
+
function numberStarts(rows) {
|
|
132
|
+
const ordered = [], starts = [];
|
|
133
|
+
for (const row of rows) {
|
|
134
|
+
if (row === blank)
|
|
135
|
+
continue;
|
|
136
|
+
const marker = /^([ \t]*)([-*+]|(\d+)[.)]) +/.exec(row);
|
|
137
|
+
if (!marker) {
|
|
138
|
+
ordered.length = 0;
|
|
139
|
+
continue;
|
|
140
|
+
}
|
|
141
|
+
const indent = marker[1].replace(/\t/g, " ").length, number = marker[3];
|
|
142
|
+
ordered.splice(indent + 1);
|
|
143
|
+
if (number && !ordered[indent])
|
|
144
|
+
starts.push(number);
|
|
145
|
+
ordered[indent] = !!number;
|
|
146
|
+
}
|
|
147
|
+
return starts;
|
|
148
|
+
}
|
|
149
|
+
export function nativeDocMarkdownEqual(left, right) {
|
|
150
|
+
const normalized = (s) => spacedBlocks(s).map(l => {
|
|
151
|
+
try {
|
|
152
|
+
return paragraph(l);
|
|
153
|
+
}
|
|
154
|
+
catch {
|
|
155
|
+
return l;
|
|
156
|
+
}
|
|
157
|
+
});
|
|
158
|
+
return JSON.stringify(numberStarts(spacedBlocks(left))) === JSON.stringify(numberStarts(spacedBlocks(right))) && JSON.stringify(normalized(left)) === JSON.stringify(normalized(right));
|
|
159
|
+
}
|
|
160
|
+
// Keep disjoint unchanged runs in place, including their native formatting
|
|
161
|
+
// and anchored comments. Bounds apply only to the middle after trimming the
|
|
162
|
+
// common ends. Oversized ambiguous rewrites are rejected before submission.
|
|
163
|
+
function characters(block) {
|
|
164
|
+
let pos = 0, span = 0;
|
|
165
|
+
return Array.from(block.text, text => {
|
|
166
|
+
while (span < block.spans.length && block.spans[span].to <= pos)
|
|
167
|
+
span++;
|
|
168
|
+
const s = block.spans[span];
|
|
169
|
+
const c = { text, pos, style: s && s.from <= pos ? s.style : {} };
|
|
170
|
+
pos += text.length;
|
|
171
|
+
return c;
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
function characterMatches(a, b) {
|
|
175
|
+
let l = 0, r = 0;
|
|
176
|
+
while (l < a.length && l < b.length && a[l].text === b[l].text)
|
|
177
|
+
l++;
|
|
178
|
+
while (r < a.length - l && r < b.length - l && a[a.length - r - 1].text === b[b.length - r - 1].text)
|
|
179
|
+
r++;
|
|
180
|
+
const n = a.length - r - l, m = b.length - r - l, stride = m + 1;
|
|
181
|
+
if (n && m && (n + 1) * stride > 1_000_000)
|
|
182
|
+
return unsafe("paragraph rewrite is too large to preserve native ranges");
|
|
183
|
+
const matches = Array.from({ length: l }, (_, i) => [i, i]);
|
|
184
|
+
if (n && m) {
|
|
185
|
+
const dp = new Uint32Array((n + 1) * stride);
|
|
186
|
+
for (let i = n - 1; i >= 0; i--)
|
|
187
|
+
for (let j = m - 1; j >= 0; j--) {
|
|
188
|
+
dp[i * stride + j] = a[i + l].text === b[j + l].text ? dp[(i + 1) * stride + j + 1] + 1 : Math.max(dp[(i + 1) * stride + j], dp[i * stride + j + 1]);
|
|
189
|
+
}
|
|
190
|
+
for (let i = 0, j = 0; i < n && j < m;) {
|
|
191
|
+
if (a[i + l].text === b[j + l].text) {
|
|
192
|
+
matches.push([i + l, j + l]);
|
|
193
|
+
i++;
|
|
194
|
+
j++;
|
|
195
|
+
}
|
|
196
|
+
else if (dp[(i + 1) * stride + j] >= dp[i * stride + j + 1])
|
|
197
|
+
i++;
|
|
198
|
+
else
|
|
199
|
+
j++;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
for (let i = 0; i < r; i++)
|
|
203
|
+
matches.push([a.length - r + i, b.length - r + i]);
|
|
204
|
+
matches.push([a.length, b.length]);
|
|
205
|
+
return matches;
|
|
206
|
+
}
|
|
207
|
+
function plan(tab, previous, desired, comments, allowDuplicatePosition) {
|
|
208
|
+
const oldLayout = spacedBlocks(previous), newLayout = spacedBlocks(desired);
|
|
209
|
+
if (JSON.stringify(numberStarts(oldLayout)) !== JSON.stringify(numberStarts(newLayout)))
|
|
210
|
+
return unsafe("cannot reproduce a change in native list numbering");
|
|
211
|
+
for (const c of docChanges(oldLayout, newLayout)) {
|
|
212
|
+
const was = oldLayout.slice(c.start, c.end);
|
|
213
|
+
if ((was.includes(blank) || c.replacement.includes(blank)) &&
|
|
214
|
+
(was.length !== c.replacement.length || was.some((v, i) => (v === blank) !== (c.replacement[i] === blank))))
|
|
215
|
+
return unsafe("editing blank paragraph spacing");
|
|
216
|
+
}
|
|
217
|
+
// Later numeric markers in the same Markdown list are not independent
|
|
218
|
+
// identities. Inserting an item can renumber every following sibling.
|
|
219
|
+
const rows = (layout) => layout.filter(l => l !== blank).map(l => l.replace(/^([ \t]*)\d+([.)] +)/, (_, indent, marker) => indent + "1" + marker));
|
|
220
|
+
const before = rows(oldLayout), after = rows(newLayout);
|
|
221
|
+
let offset = 0;
|
|
222
|
+
const changes = docChanges(before, after).map(c => {
|
|
223
|
+
const next = c.start + offset;
|
|
224
|
+
offset += c.replacement.length - (c.end - c.start);
|
|
225
|
+
return { ...c, next };
|
|
226
|
+
});
|
|
227
|
+
const body = tab.documentTab.body.content, last = body.at(-1), tabId = tab.tabProperties.tabId;
|
|
228
|
+
const range = (startIndex, endIndex) => ({ startIndex, endIndex, tabId });
|
|
229
|
+
const location = (index) => ({ index, tabId });
|
|
230
|
+
const requests = [];
|
|
231
|
+
const named = Object.values(tab.documentTab.namedRanges ?? {}).flatMap(n => n.namedRanges?.flatMap(n => n.ranges) ?? []);
|
|
232
|
+
const protectedRanges = [...named, ...comments];
|
|
233
|
+
const guardText = (start, end) => {
|
|
234
|
+
if (protectedRanges.some(r => start === end ? start >= r.startIndex && start <= r.endIndex : start < r.endIndex && end > r.startIndex))
|
|
235
|
+
return unsafe("edit overlaps a named range or anchored comment");
|
|
236
|
+
};
|
|
237
|
+
function matches(e, block) {
|
|
238
|
+
const p = e.paragraph;
|
|
239
|
+
return p && p.elements.every(run => run.textRun) && p.elements.map(run => run.textRun.content).join("") === block.text + "\n"
|
|
240
|
+
&& (p.paragraphStyle?.namedStyleType ?? "NORMAL_TEXT") === block.heading
|
|
241
|
+
&& (p.bullet ? p.bullet.nestingLevel ?? 0 : null) === block.level;
|
|
242
|
+
}
|
|
243
|
+
// Paragraphs have no stable IDs. For repeated labels, the occurrence is
|
|
244
|
+
// provable only when the entire tab aligns and the edit did not move,
|
|
245
|
+
// insert, or remove paragraphs. Never guess from two nearby anchors.
|
|
246
|
+
let ordered;
|
|
247
|
+
function byPosition(i) {
|
|
248
|
+
if (!ordered) {
|
|
249
|
+
if (!allowDuplicatePosition || changes.some(c => c.end - c.start !== 1 || c.replacement.length !== 1 || before.includes(c.replacement[0])))
|
|
250
|
+
return unsafe("duplicate paragraph identity is ambiguous");
|
|
251
|
+
ordered = body.filter((e, n) => {
|
|
252
|
+
if (!e.paragraph) {
|
|
253
|
+
if (n === 0 && "sectionBreak" in e)
|
|
254
|
+
return false;
|
|
255
|
+
return unsafe("opaque native content makes duplicate paragraph identity ambiguous");
|
|
256
|
+
}
|
|
257
|
+
return !e.paragraph.elements.every(r => r.textRun) || e.paragraph.elements.map(r => r.textRun.content).join("") !== "\n";
|
|
258
|
+
});
|
|
259
|
+
if (ordered.length !== before.length || !ordered.every((e, n) => {
|
|
260
|
+
let b;
|
|
261
|
+
try {
|
|
262
|
+
b = paragraph(before[n]);
|
|
263
|
+
}
|
|
264
|
+
catch {
|
|
265
|
+
return false;
|
|
266
|
+
}
|
|
267
|
+
if (!matches(e, b))
|
|
268
|
+
return false;
|
|
269
|
+
const bullet = e.paragraph.bullet;
|
|
270
|
+
if (!bullet)
|
|
271
|
+
return true;
|
|
272
|
+
const level = tab.documentTab.lists?.[bullet.listId]?.listProperties.nestingLevels[bullet.nestingLevel ?? 0];
|
|
273
|
+
return !!level && !!level.glyphType === b.numbered;
|
|
274
|
+
}))
|
|
275
|
+
return unsafe("duplicate paragraphs do not align with the entire native tab");
|
|
276
|
+
}
|
|
277
|
+
return ordered[i];
|
|
278
|
+
}
|
|
279
|
+
const locate = (i) => {
|
|
280
|
+
const block = paragraph(before[i]);
|
|
281
|
+
const candidates = body.filter(e => matches(e, block));
|
|
282
|
+
if (!candidates.length)
|
|
283
|
+
return unsafe("paragraph is missing");
|
|
284
|
+
const e = candidates.length === 1 ? candidates[0] : byPosition(i);
|
|
285
|
+
if (!Number.isInteger(e.startIndex) || e.endIndex - e.startIndex !== block.text.length + 1)
|
|
286
|
+
return unsafe("unrecognized paragraph range");
|
|
287
|
+
return { block, e, start: e.startIndex, end: e.endIndex };
|
|
288
|
+
};
|
|
289
|
+
const style = (block, start, reset) => {
|
|
290
|
+
if (reset)
|
|
291
|
+
requests.push({ updateTextStyle: { range: range(start, start + block.text.length), textStyle: block.heading === "NORMAL_TEXT" ? {} : { bold: false, italic: false, strikethrough: false }, fields: "bold,italic,strikethrough,link" } });
|
|
292
|
+
for (const s of block.spans)
|
|
293
|
+
requests.push({ updateTextStyle: { range: range(start + s.from, start + s.to), textStyle: s.style, fields: Object.keys(s.style).join(",") } });
|
|
294
|
+
};
|
|
295
|
+
const setParagraph = (block, start, hasBullet, structure, priorLevel, headingChanged) => {
|
|
296
|
+
if (!structure)
|
|
297
|
+
return;
|
|
298
|
+
const part = range(start, start + 1);
|
|
299
|
+
if (hasBullet)
|
|
300
|
+
requests.push({ deleteParagraphBullets: { range: part } });
|
|
301
|
+
if (headingChanged || hasBullet)
|
|
302
|
+
requests.push({ updateParagraphStyle: { range: part, paragraphStyle: headingChanged ? { namedStyleType: block.heading } : {}, fields: headingChanged ? "namedStyleType,indentStart,indentFirstLine" : "indentStart,indentFirstLine" } });
|
|
303
|
+
if (block.level !== null) {
|
|
304
|
+
// The API cannot set a paragraph's existing listId. Applying a number
|
|
305
|
+
// preset may silently start a new list even when Markdown looks right.
|
|
306
|
+
if (block.numbered)
|
|
307
|
+
return unsafe("cannot create a numbered level without a matching native list paragraph");
|
|
308
|
+
// Docs subtracts the shallowest level in each create request. Use a
|
|
309
|
+
// temporary root in this atomic batch, rather than re-listing a real
|
|
310
|
+
// adjacent paragraph and changing its list ID or styling.
|
|
311
|
+
const relative = block.level - priorLevel;
|
|
312
|
+
if (relative < 0)
|
|
313
|
+
return unsafe("outdent would split the preceding native list");
|
|
314
|
+
const prefix = relative ? "x\n" + "\t".repeat(relative) : "";
|
|
315
|
+
if (prefix)
|
|
316
|
+
requests.push({ insertText: { location: location(start), text: prefix } });
|
|
317
|
+
requests.push({ createParagraphBullets: { range: range(start, start + prefix.length + 1), bulletPreset: "BULLET_DISC_CIRCLE_SQUARE" } });
|
|
318
|
+
if (prefix)
|
|
319
|
+
requests.push({ deleteContentRange: { range: range(start, start + 2) } });
|
|
320
|
+
}
|
|
321
|
+
};
|
|
322
|
+
const precedingLevel = (at, b) => {
|
|
323
|
+
const para = body.find(e => e.endIndex === at)?.paragraph;
|
|
324
|
+
const bullet = para?.bullet;
|
|
325
|
+
if (!bullet || b.level === null)
|
|
326
|
+
return 0;
|
|
327
|
+
const levels = tab.documentTab.lists?.[bullet.listId]?.listProperties.nestingLevels;
|
|
328
|
+
if (!levels?.length)
|
|
329
|
+
return unsafe("cannot determine previous list format");
|
|
330
|
+
if (!!levels[0]?.glyphType !== b.numbered)
|
|
331
|
+
return 0;
|
|
332
|
+
if (levels.some((l, i) => l.glyphSymbol !== ["●", "○", "■"][i % 3] || (l.glyphFormat && l.glyphFormat !== "%" + i)))
|
|
333
|
+
return unsafe("cannot reproduce the existing native list preset");
|
|
334
|
+
return bullet.nestingLevel ?? 0;
|
|
335
|
+
};
|
|
336
|
+
function editable(target, destructive) {
|
|
337
|
+
const p = target.e.paragraph;
|
|
338
|
+
if (JSON.stringify(p).includes('"suggested') || p["positionedObjectIds"] || p["pageBreakBefore"] || (destructive && p.paragraphStyle?.headingId))
|
|
339
|
+
return unsafe("paragraph has a named range, suggestion, object or heading anchor");
|
|
340
|
+
}
|
|
341
|
+
for (const c of [...changes].reverse()) {
|
|
342
|
+
const old = before.slice(c.start, c.end).map((_line, i) => locate(c.start + i));
|
|
343
|
+
const added = c.replacement.map(paragraph);
|
|
344
|
+
for (const [i, b] of added.entries()) {
|
|
345
|
+
if (b.level === null || b.level === 0 || old.length === added.length && old[i]?.block.level === b.level && old[i]?.block.numbered === b.numbered)
|
|
346
|
+
continue;
|
|
347
|
+
const prior = after[c.next + i - 1];
|
|
348
|
+
const p = prior ? paragraph(prior) : null;
|
|
349
|
+
if (p?.level == null || p.numbered !== b.numbered || b.level > p.level + 1)
|
|
350
|
+
return unsafe("nested item needs a matching parent list level");
|
|
351
|
+
}
|
|
352
|
+
if (old.length === 1 && added.length === 1) {
|
|
353
|
+
const o = old[0], b = added[0];
|
|
354
|
+
editable(o, false);
|
|
355
|
+
const structure = b.heading !== o.block.heading || b.level !== o.block.level || b.numbered !== o.block.numbered;
|
|
356
|
+
if (structure && o.block.numbered)
|
|
357
|
+
return unsafe("recreating an existing numbered paragraph could restart its list");
|
|
358
|
+
const from = characters(o.block), to = characters(b), keep = characterMatches(from, to);
|
|
359
|
+
let ai = 0, bi = 0;
|
|
360
|
+
const edits = [];
|
|
361
|
+
const previous = new Map();
|
|
362
|
+
for (const [i, j] of keep) {
|
|
363
|
+
const at = o.start + (from[ai]?.pos ?? o.block.text.length);
|
|
364
|
+
const removed = (from[i]?.pos ?? o.block.text.length) - (at - o.start);
|
|
365
|
+
const added = b.text.slice(to[bi]?.pos ?? b.text.length, to[j]?.pos ?? b.text.length);
|
|
366
|
+
if (removed || added) {
|
|
367
|
+
if (removed)
|
|
368
|
+
guardText(at, at + removed);
|
|
369
|
+
if (added)
|
|
370
|
+
guardText(at, at);
|
|
371
|
+
// Anchor the unchanged text before removing old characters.
|
|
372
|
+
edits.push([
|
|
373
|
+
...(added ? [{ insertText: { location: location(at), text: added } }] : []),
|
|
374
|
+
...(removed ? [{ deleteContentRange: { range: range(at + added.length, at + added.length + removed) } }] : []),
|
|
375
|
+
]);
|
|
376
|
+
}
|
|
377
|
+
if (i < from.length)
|
|
378
|
+
previous.set(j, from[i].style);
|
|
379
|
+
ai = i + 1;
|
|
380
|
+
bi = j + 1;
|
|
381
|
+
}
|
|
382
|
+
for (const edit of edits.reverse())
|
|
383
|
+
requests.push(...edit);
|
|
384
|
+
const headingChanged = b.heading !== o.block.heading;
|
|
385
|
+
if (headingChanged && o.e.paragraph.paragraphStyle?.headingId)
|
|
386
|
+
return unsafe("changing a linked heading");
|
|
387
|
+
if (headingChanged && o.e.paragraph.elements.some(el => Object.keys(el.textRun?.textStyle ?? {}).some(k => !["bold", "italic", "strikethrough", "link"].includes(k))))
|
|
388
|
+
return unsafe("heading change would reset extra text styling");
|
|
389
|
+
if (structure)
|
|
390
|
+
guardText(o.start, o.end);
|
|
391
|
+
setParagraph(b, o.start, !!o.e.paragraph.bullet, structure, structure ? precedingLevel(o.start, b) : 0, headingChanged);
|
|
392
|
+
// A change in paragraph style can reset native inline styling. Text
|
|
393
|
+
// edits alone touch only fields whose Markdown representation changed.
|
|
394
|
+
let pending;
|
|
395
|
+
const flush = () => {
|
|
396
|
+
if (pending)
|
|
397
|
+
requests.push({ updateTextStyle: { range: range(o.start + pending.start, o.start + pending.end), textStyle: pending.style, fields: pending.fields } });
|
|
398
|
+
pending = undefined;
|
|
399
|
+
};
|
|
400
|
+
for (let j = 0; j < to.length; j++) {
|
|
401
|
+
const c = to[j], prior = previous.get(j);
|
|
402
|
+
const fields = ["bold", "italic", "strikethrough", "link"].filter(k => !prior || headingChanged || JSON.stringify(prior[k]) !== JSON.stringify(c.style[k]));
|
|
403
|
+
if (!fields.length) {
|
|
404
|
+
flush();
|
|
405
|
+
continue;
|
|
406
|
+
}
|
|
407
|
+
const s = Object.fromEntries(fields.filter(k => c.style[k] !== undefined || k !== "link" && b.heading !== "NORMAL_TEXT").map(k => [k, c.style[k] ?? false]));
|
|
408
|
+
const mask = fields.join(",");
|
|
409
|
+
if (pending && pending.fields === mask && JSON.stringify(pending.style) === JSON.stringify(s))
|
|
410
|
+
pending.end = c.pos + c.text.length;
|
|
411
|
+
else {
|
|
412
|
+
flush();
|
|
413
|
+
pending = { start: c.pos, end: c.pos + c.text.length, fields: mask, style: s };
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
flush();
|
|
417
|
+
continue;
|
|
418
|
+
}
|
|
419
|
+
if (old.length && added.length)
|
|
420
|
+
return unsafe("cannot replace a range of different-sized paragraph groups");
|
|
421
|
+
if (old.length) {
|
|
422
|
+
for (const o of old)
|
|
423
|
+
editable(o, true);
|
|
424
|
+
if (old.some((o, i) => i && old[i - 1].end !== o.start))
|
|
425
|
+
return unsafe("native content between deleted paragraphs");
|
|
426
|
+
let a = old[0].start, z = old.at(-1).end;
|
|
427
|
+
if (z === last?.endIndex) {
|
|
428
|
+
if (a === 1)
|
|
429
|
+
return unsafe("deleting the entire document");
|
|
430
|
+
const preceding = body.find(e => e.endIndex === a);
|
|
431
|
+
if (!preceding?.paragraph)
|
|
432
|
+
return unsafe("cannot delete the last paragraph after a native object");
|
|
433
|
+
a--;
|
|
434
|
+
z--;
|
|
435
|
+
}
|
|
436
|
+
guardText(a, z);
|
|
437
|
+
requests.push({ deleteContentRange: { range: range(a, z) } });
|
|
438
|
+
continue;
|
|
439
|
+
}
|
|
440
|
+
const right = c.start < before.length ? locate(c.start) : undefined;
|
|
441
|
+
const left = c.start > 0 ? locate(c.start - 1) : undefined;
|
|
442
|
+
if (left && right && left.end !== right.start)
|
|
443
|
+
return unsafe("native content between insertion anchors");
|
|
444
|
+
const sameLevel = (n) => {
|
|
445
|
+
const bullet = n?.e.paragraph?.bullet;
|
|
446
|
+
if (!bullet || !n || !added.every(b => b.level === n.block.level && b.numbered === n.block.numbered && b.heading === n.block.heading))
|
|
447
|
+
return false;
|
|
448
|
+
const level = tab.documentTab.lists?.[bullet.listId]?.listProperties.nestingLevels[bullet.nestingLevel ?? 0];
|
|
449
|
+
if (!level)
|
|
450
|
+
return unsafe("cannot determine native list preset");
|
|
451
|
+
return n.block.numbered ? /^(DECIMAL|ZERO_DECIMAL|ALPHA|UPPER_ALPHA|ROMAN|UPPER_ROMAN)$/.test(level.glyphType ?? "") : !!level.glyphSymbol;
|
|
452
|
+
};
|
|
453
|
+
const inheritLeft = sameLevel(left), inheritRight = sameLevel(right);
|
|
454
|
+
if (inheritLeft && inheritRight && left.e.paragraph.bullet.listId !== right.e.paragraph.bullet.listId)
|
|
455
|
+
return unsafe("insertion is between two different native lists");
|
|
456
|
+
const inherit = inheritRight || inheritLeft;
|
|
457
|
+
if (!inherit && added.some(b => b.numbered))
|
|
458
|
+
return unsafe("cannot insert numbered items without a matching native list paragraph");
|
|
459
|
+
if (!inherit && left?.e.paragraph?.bullet && left.e.paragraph.bullet.listId === right?.e.paragraph?.bullet?.listId && left.block.numbered)
|
|
460
|
+
return unsafe("insertion could split a numbered list");
|
|
461
|
+
const append = !right && !!left;
|
|
462
|
+
if (append && left.end !== last?.endIndex || !left && right && right.start !== 1)
|
|
463
|
+
return unsafe("native content beyond insertion anchor");
|
|
464
|
+
if (!right && !left && !(last?.startIndex === 1 && last?.paragraph?.elements[0]?.textRun?.content === "\n"))
|
|
465
|
+
return unsafe("no native insertion anchor");
|
|
466
|
+
// Inserting a newline inside an existing item gives the new paragraph the
|
|
467
|
+
// exact same list ID, level, glyph preset and counter. No list API call.
|
|
468
|
+
const splitLeft = append || !inheritRight && inheritLeft;
|
|
469
|
+
const neighbor = splitLeft ? left : right;
|
|
470
|
+
if (neighbor) {
|
|
471
|
+
editable(neighbor, false);
|
|
472
|
+
if (!splitLeft && right?.e.paragraph?.paragraphStyle?.headingId)
|
|
473
|
+
return unsafe("splitting a heading may move its anchor");
|
|
474
|
+
}
|
|
475
|
+
const at = splitLeft ? left.end - 1 : right?.start ?? 1;
|
|
476
|
+
guardText(at, at);
|
|
477
|
+
const text = added.map(b => b.text).join("\n");
|
|
478
|
+
requests.push({ insertText: { location: location(at), text: splitLeft ? "\n" + text : right ? text + "\n" : text } });
|
|
479
|
+
let pos = at + Number(splitLeft);
|
|
480
|
+
let previousAdded;
|
|
481
|
+
for (const b of added) {
|
|
482
|
+
const preceding = inherit ? 0 : previousAdded ? previousAdded.numbered === b.numbered ? previousAdded.level ?? 0 : 0 : precedingLevel(append ? left.end : pos, b);
|
|
483
|
+
setParagraph(b, pos, !!neighbor?.e.paragraph?.bullet, !inherit, preceding, (neighbor?.block.heading ?? "NORMAL_TEXT") !== b.heading);
|
|
484
|
+
previousAdded = b;
|
|
485
|
+
style(b, pos, true);
|
|
486
|
+
pos += b.text.length + 1;
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
return requests;
|
|
490
|
+
}
|
|
491
|
+
// Docs API omits comments. Drive's anchor is not a Docs API index; only
|
|
492
|
+
// quoted content can be reconciled with ranges in this exact native snapshot.
|
|
493
|
+
async function anchoredComments(runtime, id, headers, tab, tabs) {
|
|
494
|
+
const found = [], pages = new Set();
|
|
495
|
+
const locate = (t, quote) => {
|
|
496
|
+
const ranges = [];
|
|
497
|
+
let content = "", first = 0;
|
|
498
|
+
function scan() {
|
|
499
|
+
for (let i = content.indexOf(quote); i !== -1; i = content.indexOf(quote, i + 1))
|
|
500
|
+
ranges.push({ startIndex: first + i, endIndex: first + i + quote.length });
|
|
501
|
+
content = "";
|
|
502
|
+
}
|
|
503
|
+
for (const row of t.documentTab.body.content) {
|
|
504
|
+
if (!row.paragraph) {
|
|
505
|
+
scan();
|
|
506
|
+
continue;
|
|
507
|
+
}
|
|
508
|
+
for (const el of row.paragraph.elements) {
|
|
509
|
+
const s = el.textRun?.content, start = Number(el["startIndex"] ?? row.startIndex);
|
|
510
|
+
if (!s) {
|
|
511
|
+
scan();
|
|
512
|
+
continue;
|
|
513
|
+
}
|
|
514
|
+
if (content && first + content.length !== start)
|
|
515
|
+
scan();
|
|
516
|
+
if (!content)
|
|
517
|
+
first = start;
|
|
518
|
+
content += s;
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
scan();
|
|
522
|
+
return ranges;
|
|
523
|
+
};
|
|
524
|
+
let cursor = "";
|
|
525
|
+
do {
|
|
526
|
+
const query = new URLSearchParams({ fields: "nextPageToken,comments(anchor,quotedFileContent)", pageSize: "100", ...(cursor && { pageToken: cursor }) });
|
|
527
|
+
const res = await googleRead(runtime, "https://www.googleapis.com/drive/v3/files/" + encodeURIComponent(id) + "/comments?" + query, { headers, redirect: "error" });
|
|
528
|
+
if (!res.ok)
|
|
529
|
+
throw new Error("Google Drive comment check failed: HTTP " + res.status + ". Block uploads require permission to read document comments.");
|
|
530
|
+
const data = await res.json();
|
|
531
|
+
if (!Array.isArray(data.comments))
|
|
532
|
+
return unsafe("incomplete comment metadata");
|
|
533
|
+
for (const c of data.comments) {
|
|
534
|
+
if (!c.anchor && !c.quotedFileContent)
|
|
535
|
+
continue; // Whole-file comment
|
|
536
|
+
const quote = c.quotedFileContent?.value;
|
|
537
|
+
const mime = c.quotedFileContent?.mimeType;
|
|
538
|
+
// Drive returns text/html even for a plain-text quote. Only accept it
|
|
539
|
+
// verbatim if there are no entities or tags to interpret.
|
|
540
|
+
if (!quote || mime && mime !== "text/plain" && !(mime === "text/html" && !/[<&]/.test(quote)))
|
|
541
|
+
return unsafe("comment has no mappable quoted text");
|
|
542
|
+
const matches = locate(tab, quote);
|
|
543
|
+
if (!matches.length && !tabs.some(t => t !== tab && locate(t, quote).length))
|
|
544
|
+
return unsafe("cannot locate an anchored comment");
|
|
545
|
+
found.push(...matches);
|
|
546
|
+
}
|
|
547
|
+
cursor = data.nextPageToken ?? "";
|
|
548
|
+
if (cursor && pages.has(cursor))
|
|
549
|
+
return unsafe("repeated comment page token");
|
|
550
|
+
pages.add(cursor);
|
|
551
|
+
} while (cursor);
|
|
552
|
+
return found;
|
|
553
|
+
}
|
|
554
|
+
export async function tryUploadDocBlocks(runtime, documentId, key, tabId, remoteMarkdown, desiredMarkdown, confirmRemote, wroteRevision, positionRevision) {
|
|
555
|
+
const token = (await nativeDocsGrant(runtime))?.token;
|
|
556
|
+
if (!token)
|
|
557
|
+
return false;
|
|
558
|
+
const url = "https://docs.googleapis.com/v1/documents/" + encodeURIComponent(documentId);
|
|
559
|
+
const headers = { authorization: "Bearer " + token, ...(key && { "X-Goog-Drive-Resource-Keys": documentId + "/" + key }) };
|
|
560
|
+
const response = await googleRead(runtime, url + "?includeTabsContent=true&suggestionsViewMode=SUGGESTIONS_INLINE", { headers, redirect: "error" });
|
|
561
|
+
if (!response.ok)
|
|
562
|
+
throw new Error("Google Docs block read failed: HTTP " + response.status);
|
|
563
|
+
const data = await response.json();
|
|
564
|
+
if (data.documentId !== documentId || !data.revisionId)
|
|
565
|
+
return unsafe("missing document identity or revision");
|
|
566
|
+
const tabs = [];
|
|
567
|
+
function visit(items) { for (const t of items) {
|
|
568
|
+
tabs.push(t);
|
|
569
|
+
visit(t.childTabs ?? []);
|
|
570
|
+
} }
|
|
571
|
+
visit(data.tabs ?? []);
|
|
572
|
+
if (!tabId && tabs.length > 1)
|
|
573
|
+
return unsafe("this document has multiple tabs; sync the URL with an explicit tab ID");
|
|
574
|
+
const tab = tabId ? tabs.find(t => t.tabProperties.tabId === tabId) : tabs[0];
|
|
575
|
+
if (!tab?.documentTab?.body?.content)
|
|
576
|
+
return unsafe("missing target tab");
|
|
577
|
+
const comments = await anchoredComments(runtime, documentId, headers, tab, tabs);
|
|
578
|
+
const requests = plan(tab, remoteMarkdown, desiredMarkdown, comments, positionRevision === data.revisionId);
|
|
579
|
+
if (await confirmRemote(data.revisionId) !== remoteMarkdown)
|
|
580
|
+
throw new Error("Google Docs changed before writing; sync again.");
|
|
581
|
+
if (!requests.length)
|
|
582
|
+
return true;
|
|
583
|
+
const update = await runtime.http.request(url + ":batchUpdate", { method: "POST", headers: { ...headers, "content-type": "application/json" }, redirect: "error", body: JSON.stringify({ writeControl: { requiredRevisionId: data.revisionId }, requests }) });
|
|
584
|
+
if (!update.ok)
|
|
585
|
+
throw new Error("Google Docs block update failed: HTTP " + update.status + ". Sync again to check the current revision.");
|
|
586
|
+
if (wroteRevision) {
|
|
587
|
+
const ack = await update.json();
|
|
588
|
+
if (typeof ack.writeControl?.requiredRevisionId === "string")
|
|
589
|
+
wroteRevision(ack.writeControl.requiredRevisionId);
|
|
590
|
+
}
|
|
591
|
+
return true;
|
|
592
|
+
}
|
|
593
|
+
//# sourceMappingURL=native-docs.js.map
|