@mindstone/mcp-server-google-workspace 0.4.1 → 0.5.0

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 (42) hide show
  1. package/README.md +43 -5
  2. package/dist/modules/docs/service.d.ts +76 -6
  3. package/dist/modules/docs/service.js +791 -103
  4. package/dist/modules/docs/tabCopy.d.ts +266 -0
  5. package/dist/modules/docs/tabCopy.js +794 -0
  6. package/dist/modules/docs/tabs.d.ts +161 -0
  7. package/dist/modules/docs/tabs.js +416 -0
  8. package/dist/modules/docs/types.d.ts +141 -1
  9. package/dist/modules/drive/service.d.ts +15 -0
  10. package/dist/modules/drive/service.js +77 -2
  11. package/dist/modules/drive/types.d.ts +1 -1
  12. package/dist/modules/sheets/a1Utils.d.ts +13 -0
  13. package/dist/modules/sheets/a1Utils.js +33 -7
  14. package/dist/modules/sheets/formatters.d.ts +33 -2
  15. package/dist/modules/sheets/formatters.js +84 -5
  16. package/dist/modules/sheets/service.d.ts +26 -1
  17. package/dist/modules/sheets/service.js +264 -8
  18. package/dist/modules/sheets/types.d.ts +71 -0
  19. package/dist/modules/sheets/types.js +12 -1
  20. package/dist/modules/sheets/writeGuards.js +2 -2
  21. package/dist/tools/definitions/destructive-overrides.json +8 -0
  22. package/dist/tools/definitions/docs.js +395 -9
  23. package/dist/tools/definitions/drive.js +9 -4
  24. package/dist/tools/definitions/gmail.js +30 -3
  25. package/dist/tools/definitions/open-world-overrides.json +8 -0
  26. package/dist/tools/definitions/sheets.js +177 -1
  27. package/dist/tools/docs-handlers.d.ts +125 -0
  28. package/dist/tools/docs-handlers.js +397 -15
  29. package/dist/tools/gmail-handlers.d.ts +3 -0
  30. package/dist/tools/gmail-handlers.js +19 -5
  31. package/dist/tools/param-normalizer.js +16 -0
  32. package/dist/tools/server.js +35 -3
  33. package/dist/tools/sheets-handlers.d.ts +54 -1
  34. package/dist/tools/sheets-handlers.js +107 -13
  35. package/dist/tools/type-guards.d.ts +89 -0
  36. package/dist/tools/type-guards.js +190 -6
  37. package/dist/tools/types.d.ts +1 -1
  38. package/dist/utils/apiError.d.ts +6 -0
  39. package/dist/utils/apiError.js +12 -0
  40. package/dist/utils/tabPosition.d.ts +20 -0
  41. package/dist/utils/tabPosition.js +19 -0
  42. package/package.json +1 -1
@@ -0,0 +1,794 @@
1
+ import { ALL_TEXT_KEYS, DocsInputError, flatParagraphs } from './tabs.js';
2
+ /** Requests per batchUpdate call. */
3
+ export const CHUNK = 150;
4
+ /** Paragraph-style fields never copied (a heading id belongs to the source paragraph). */
5
+ export const PSTYLE_DROP = ['headingId'];
6
+ /** Dropped from bullet paragraphs in Phase 3: createParagraphBullets sets its own indents. */
7
+ const BULLET_INDENT_DROP = ['indentStart', 'indentFirstLine'];
8
+ /**
9
+ * Document-style (page setup) fields copied in Phase 0. Never
10
+ * `useCustomHeaderFooterMargins`: the API rejects it in updateDocumentStyle.
11
+ */
12
+ export const DOCUMENT_STYLE_KEYS = [
13
+ 'marginTop',
14
+ 'marginBottom',
15
+ 'marginLeft',
16
+ 'marginRight',
17
+ 'pageSize',
18
+ 'marginHeader',
19
+ 'marginFooter',
20
+ 'pageNumberStart',
21
+ ];
22
+ const NAMED_STYLE_FIELDS = 'namedStyleType,textStyle,paragraphStyle';
23
+ /**
24
+ * A failure inside the copy, naming the phase, whether a content write was
25
+ * confirmed (`wroteContent`) and whether one had been sent at all
26
+ * (`attemptedWrite`: a write whose reply was lost may still have applied).
27
+ */
28
+ export class TabCopyError extends Error {
29
+ phase;
30
+ wroteContent;
31
+ attemptedWrite;
32
+ cause;
33
+ constructor(phase, wroteContent, attemptedWrite, cause) {
34
+ super(`Copy failed during "${phase}": ${cause instanceof Error ? cause.message : String(cause)}`);
35
+ this.phase = phase;
36
+ this.wroteContent = wroteContent;
37
+ this.attemptedWrite = attemptedWrite;
38
+ this.cause = cause;
39
+ this.name = 'TabCopyError';
40
+ }
41
+ }
42
+ /** Drive file id of a Docs/Sheets/Slides/Drive link (`/d/<id>`), or null. */
43
+ export function idFromUri(uri) {
44
+ const match = /\/d\/([A-Za-z0-9_-]+)/.exec(uri);
45
+ return match ? match[1] : null;
46
+ }
47
+ function elementKind(element) {
48
+ return Object.keys(element).find((key) => key !== 'startIndex' && key !== 'endIndex') ?? 'unknown';
49
+ }
50
+ function bump(counts, key) {
51
+ counts[key] = (counts[key] ?? 0) + 1;
52
+ }
53
+ function hasKeys(style) {
54
+ return style !== undefined && Object.keys(style).length > 0;
55
+ }
56
+ /** JSON-shape equality for API objects (key order ignored). */
57
+ function deepEqual(a, b) {
58
+ if (a === b)
59
+ return true;
60
+ if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null)
61
+ return false;
62
+ if (Array.isArray(a) !== Array.isArray(b))
63
+ return false;
64
+ const aKeys = Object.keys(a).filter((k) => a[k] !== undefined);
65
+ const bKeys = Object.keys(b).filter((k) => b[k] !== undefined);
66
+ if (aKeys.length !== bKeys.length)
67
+ return false;
68
+ return aKeys.every((k) => deepEqual(a[k], b[k]));
69
+ }
70
+ function sameContainer(a, b) {
71
+ if (a === 'body' || b === 'body')
72
+ return a === b;
73
+ return a.table === b.table && a.row === b.row && a.col === b.col;
74
+ }
75
+ /** Cell paragraphs of a body (one level of tables), like flatParagraphs. */
76
+ function forEachCellParagraph(content, visit) {
77
+ for (const element of content ?? []) {
78
+ if (element.paragraph)
79
+ visit(element.paragraph);
80
+ }
81
+ }
82
+ /**
83
+ * Every smart-chip URI in the tab (body and table cells), in document order,
84
+ * without duplicates. Collected before any write so each one is checked once.
85
+ */
86
+ export function collectChipUris(tab) {
87
+ const uris = new Set();
88
+ const fromParagraph = (paragraph) => {
89
+ for (const element of paragraph.elements ?? []) {
90
+ const uri = element.richLink?.richLinkProperties?.uri;
91
+ if (uri)
92
+ uris.add(uri);
93
+ }
94
+ };
95
+ for (const element of tab.documentTab?.body?.content ?? []) {
96
+ if (element.paragraph)
97
+ fromParagraph(element.paragraph);
98
+ for (const row of element.table?.tableRows ?? []) {
99
+ for (const cell of row.tableCells ?? [])
100
+ forEachCellParagraph(cell.content, fromParagraph);
101
+ }
102
+ }
103
+ return [...uris];
104
+ }
105
+ /**
106
+ * Docs bullet preset for a source list. Only preset styles can be created, so
107
+ * the first nesting level's glyph decides: decimal numbering, letter
108
+ * numbering, or discs (●/○/■ or no symbol; an unknown symbol also becomes
109
+ * discs, with a note).
110
+ */
111
+ export function presetFor(list, notes) {
112
+ const level = list?.listProperties?.nestingLevels?.[0] ?? {};
113
+ const glyphType = level.glyphType ?? undefined;
114
+ const glyphSymbol = level.glyphSymbol ?? undefined;
115
+ if (glyphType === 'DECIMAL' || glyphType === 'ZERO_DECIMAL')
116
+ return 'NUMBERED_DECIMAL_ALPHA_ROMAN';
117
+ if (glyphType === 'ALPHA' || glyphType === 'UPPER_ALPHA')
118
+ return 'NUMBERED_UPPERALPHA_ALPHA_ROMAN';
119
+ if (glyphSymbol === undefined || ['●', '○', '■'].includes(glyphSymbol)) {
120
+ if (glyphSymbol === undefined && glyphType !== undefined && !['GLYPH_TYPE_UNSPECIFIED', 'NONE'].includes(glyphType)) {
121
+ // Same mapping as before (discs); say so rather than change a numbered list silently.
122
+ notes.push(`numbered list style ${glyphType} copied as bullets`);
123
+ }
124
+ return 'BULLET_DISC_CIRCLE_SQUARE';
125
+ }
126
+ notes.push(`unmapped glyph ${glyphType ?? 'none'}/${glyphSymbol}`);
127
+ return 'BULLET_DISC_CIRCLE_SQUARE';
128
+ }
129
+ function addText(tokens, text) {
130
+ const last = tokens[tokens.length - 1];
131
+ if (last?.kind === 'text') {
132
+ tokens[tokens.length - 1] = { kind: 'text', text: last.text + text };
133
+ }
134
+ else {
135
+ tokens.push({ kind: 'text', text });
136
+ }
137
+ }
138
+ /** Append a paragraph's pieces as tokens; text right after a page break loses its leading newline. */
139
+ function tokensForParagraph(pieces, tokens) {
140
+ let afterPageBreak = false;
141
+ for (const piece of pieces) {
142
+ if (piece.kind === 'text') {
143
+ const text = afterPageBreak && piece.text.startsWith('\n') ? piece.text.slice(1) : piece.text;
144
+ afterPageBreak = false;
145
+ if (text)
146
+ addText(tokens, text);
147
+ }
148
+ else if (piece.kind === 'chip') {
149
+ tokens.push({ kind: 'chip', uri: piece.uri });
150
+ afterPageBreak = false;
151
+ }
152
+ else {
153
+ tokens.push({ kind: 'pagebreak' });
154
+ afterPageBreak = true;
155
+ }
156
+ }
157
+ }
158
+ /** Drop the trailing newline of the last text token; true when there was one. */
159
+ function stripTrailingNewline(tokens) {
160
+ const last = tokens[tokens.length - 1];
161
+ if (last?.kind === 'text' && last.text.endsWith('\n')) {
162
+ tokens[tokens.length - 1] = { kind: 'text', text: last.text.slice(0, -1) };
163
+ return true;
164
+ }
165
+ return false;
166
+ }
167
+ /**
168
+ * Plan the source tab: every paragraph's pieces (computed exactly once and
169
+ * reused by Phases 1-3 and verification), the Phase 1 and Phase 2 tokens, and
170
+ * the report counts. `chipAccess` holds the result of the per-URI access check;
171
+ * a URI that is missing or false falls back to a titled link.
172
+ */
173
+ export function buildSourcePlan(sourceTab, chipAccess) {
174
+ const documentTab = sourceTab.documentTab ?? {};
175
+ const plan = {
176
+ paragraphs: [],
177
+ bodyTokens: [],
178
+ tables: [],
179
+ cellTokens: [],
180
+ lists: (documentTab.lists ?? {}),
181
+ chipsCopied: 0,
182
+ chipFallbacks: [],
183
+ convertedToText: { people: 0, dates: 0 },
184
+ placeholders: 0,
185
+ notCopied: {},
186
+ notes: [],
187
+ };
188
+ const fallbackUris = new Set();
189
+ const placeholder = (kind) => {
190
+ const text = `[${kind}]`;
191
+ bump(plan.notCopied, kind);
192
+ plan.placeholders++;
193
+ return { kind: 'text', text, length: text.length, style: {}, placeholder: true };
194
+ };
195
+ const piecesFor = (paragraph) => {
196
+ // Floating images sit outside paragraph.elements: counted, never copied, no placeholder.
197
+ const floating = paragraph.positionedObjectIds?.length ?? 0;
198
+ if (floating > 0)
199
+ plan.notCopied['positionedObject'] = (plan.notCopied['positionedObject'] ?? 0) + floating;
200
+ const pieces = [];
201
+ const nest = paragraph.bullet ? paragraph.bullet.nestingLevel ?? 0 : 0;
202
+ if (nest)
203
+ pieces.push({ kind: 'text', text: '\t'.repeat(nest), length: nest, nesting: true });
204
+ for (const element of paragraph.elements ?? []) {
205
+ if (element.textRun) {
206
+ const text = element.textRun.content ?? '';
207
+ pieces.push({ kind: 'text', text, length: text.length, style: element.textRun.textStyle ?? {} });
208
+ }
209
+ else if (element.richLink) {
210
+ const props = element.richLink.richLinkProperties ?? {};
211
+ const style = element.richLink.textStyle ?? {};
212
+ const uri = props.uri ?? '';
213
+ if (!uri) {
214
+ pieces.push(placeholder('richLink'));
215
+ }
216
+ else if (chipAccess.get(uri) === true) {
217
+ pieces.push({ kind: 'chip', uri, length: 1, style });
218
+ plan.chipsCopied++;
219
+ }
220
+ else {
221
+ const title = props.title || uri;
222
+ if (!fallbackUris.has(uri)) {
223
+ fallbackUris.add(uri);
224
+ plan.chipFallbacks.push({ uri, title });
225
+ }
226
+ pieces.push({ kind: 'text', text: title, length: title.length, style: { ...style, link: { url: uri } } });
227
+ }
228
+ }
229
+ else if (element.pageBreak) {
230
+ pieces.push({ kind: 'pagebreak', length: 1, style: element.pageBreak.textStyle ?? {} });
231
+ }
232
+ else if (element.person) {
233
+ const props = element.person.personProperties ?? {};
234
+ const text = props.name || props.email;
235
+ if (!text) {
236
+ pieces.push(placeholder('person'));
237
+ }
238
+ else {
239
+ const style = element.person.textStyle ?? {};
240
+ pieces.push({
241
+ kind: 'text',
242
+ text,
243
+ length: text.length,
244
+ style: props.email ? { ...style, link: { url: `mailto:${props.email}` } } : style,
245
+ });
246
+ plan.convertedToText.people++;
247
+ }
248
+ }
249
+ else if (element.dateElement) {
250
+ const text = element.dateElement.dateElementProperties?.displayText;
251
+ if (!text) {
252
+ pieces.push(placeholder('dateElement'));
253
+ }
254
+ else {
255
+ pieces.push({ kind: 'text', text, length: text.length, style: element.dateElement.textStyle ?? {} });
256
+ plan.convertedToText.dates++;
257
+ }
258
+ }
259
+ else {
260
+ pieces.push(placeholder(elementKind(element)));
261
+ }
262
+ }
263
+ return pieces;
264
+ };
265
+ for (const element of documentTab.body?.content ?? []) {
266
+ if (element.sectionBreak)
267
+ continue;
268
+ if (element.paragraph) {
269
+ const pieces = piecesFor(element.paragraph);
270
+ plan.paragraphs.push({ container: 'body', paragraph: element.paragraph, pieces });
271
+ tokensForParagraph(pieces, plan.bodyTokens);
272
+ }
273
+ else if (element.table) {
274
+ const table = element.table;
275
+ // insertTable always builds a full rows x columns grid, so a ragged table could never match.
276
+ const tableRows = table.tableRows ?? [];
277
+ if (tableRows.length !== (table.rows ?? 0) ||
278
+ tableRows.some((row) => (row.tableCells ?? []).length !== (table.columns ?? 0))) {
279
+ throw new DocsInputError("This tab has a table with merged cells in a shape that can't be copied. Nothing was written.");
280
+ }
281
+ const tableNumber = plan.tables.length;
282
+ plan.tables.push(table);
283
+ if (!stripTrailingNewline(plan.bodyTokens))
284
+ plan.notes.push('table without preceding newline');
285
+ plan.bodyTokens.push({ kind: 'table', rows: table.rows ?? 0, columns: table.columns ?? 0 });
286
+ let merged = false;
287
+ const rowTokens = [];
288
+ (table.tableRows ?? []).forEach((row, rowIndex) => {
289
+ const colTokens = [];
290
+ (row.tableCells ?? []).forEach((cell, colIndex) => {
291
+ const style = cell.tableCellStyle;
292
+ if ((style?.rowSpan ?? 1) > 1 || (style?.columnSpan ?? 1) > 1)
293
+ merged = true;
294
+ const tokens = [];
295
+ for (const cellElement of cell.content ?? []) {
296
+ if (cellElement.paragraph) {
297
+ const pieces = piecesFor(cellElement.paragraph);
298
+ plan.paragraphs.push({
299
+ container: { table: tableNumber, row: rowIndex, col: colIndex },
300
+ paragraph: cellElement.paragraph,
301
+ pieces,
302
+ });
303
+ tokensForParagraph(pieces, tokens);
304
+ }
305
+ else if (cellElement.table) {
306
+ bump(plan.notCopied, 'table inside a table cell');
307
+ }
308
+ }
309
+ stripTrailingNewline(tokens);
310
+ colTokens.push(tokens);
311
+ });
312
+ rowTokens.push(colTokens);
313
+ });
314
+ plan.cellTokens.push(rowTokens);
315
+ if (merged)
316
+ bump(plan.notCopied, 'merged table cells');
317
+ }
318
+ else {
319
+ bump(plan.notCopied, elementKind(element));
320
+ }
321
+ }
322
+ stripTrailingNewline(plan.bodyTokens);
323
+ return plan;
324
+ }
325
+ /**
326
+ * Phase 0: clear the target body, reset its remaining paragraph (no bullet,
327
+ * NORMAL_TEXT, no character style), copy page setup and any named style that
328
+ * differs from the target's.
329
+ */
330
+ export function planClear(sourceTab, targetTab, targetTabId) {
331
+ const requests = [];
332
+ const content = targetTab.documentTab?.body?.content ?? [];
333
+ const end = content.length > 0 ? content[content.length - 1].endIndex ?? 1 : 1;
334
+ if (end > 2) {
335
+ requests.push({ deleteContentRange: { range: { startIndex: 1, endIndex: end - 1, tabId: targetTabId } } });
336
+ }
337
+ const first = { startIndex: 1, endIndex: 2, tabId: targetTabId };
338
+ requests.push({ deleteParagraphBullets: { range: first } }, {
339
+ updateParagraphStyle: {
340
+ range: first,
341
+ paragraphStyle: { namedStyleType: 'NORMAL_TEXT' },
342
+ fields: 'namedStyleType',
343
+ },
344
+ }, { updateTextStyle: { range: first, textStyle: {}, fields: ALL_TEXT_KEYS } });
345
+ const sourceDocStyle = sourceTab.documentTab?.documentStyle ?? {};
346
+ const keys = DOCUMENT_STYLE_KEYS.filter((key) => sourceDocStyle[key] !== undefined && sourceDocStyle[key] !== null);
347
+ if (keys.length > 0) {
348
+ const documentStyle = {};
349
+ for (const key of keys) {
350
+ documentStyle[key] = sourceDocStyle[key];
351
+ }
352
+ requests.push({ updateDocumentStyle: { tabId: targetTabId, documentStyle, fields: keys.join(',') } });
353
+ }
354
+ const targetStyles = new Map((targetTab.documentTab?.namedStyles?.styles ?? []).map((style) => [style.namedStyleType, style]));
355
+ let namedStylesCopied = 0;
356
+ for (const style of sourceTab.documentTab?.namedStyles?.styles ?? []) {
357
+ if (!deepEqual(style, targetStyles.get(style.namedStyleType))) {
358
+ requests.push({ updateNamedStyle: { tabId: targetTabId, namedStyle: style, fields: NAMED_STYLE_FIELDS } });
359
+ namedStylesCopied++;
360
+ }
361
+ }
362
+ return { requests, namedStylesCopied };
363
+ }
364
+ /** Phase 1: the skeleton, appended at the end of the target in document order. */
365
+ export function planSkeleton(plan, targetTabId) {
366
+ const endOfSegmentLocation = { tabId: targetTabId };
367
+ const requests = [];
368
+ for (const token of plan.bodyTokens) {
369
+ if (token.kind === 'text') {
370
+ if (token.text)
371
+ requests.push({ insertText: { endOfSegmentLocation, text: token.text } });
372
+ }
373
+ else if (token.kind === 'chip') {
374
+ requests.push({ insertRichLink: { endOfSegmentLocation, richLinkProperties: { uri: token.uri } } });
375
+ }
376
+ else if (token.kind === 'pagebreak') {
377
+ requests.push({ insertPageBreak: { endOfSegmentLocation } });
378
+ }
379
+ else {
380
+ requests.push({ insertTable: { endOfSegmentLocation, rows: token.rows, columns: token.columns } });
381
+ }
382
+ }
383
+ return requests;
384
+ }
385
+ function bodyTables(tab) {
386
+ return (tab.documentTab?.body?.content ?? []).filter((element) => element.table);
387
+ }
388
+ /**
389
+ * Phase 2: fill table cells, last table / row / column first and each cell's
390
+ * tokens in reverse, all at the cell's first index, so no insert shifts an
391
+ * index still to be used.
392
+ */
393
+ export function planTableCells(plan, targetTab, targetTabId) {
394
+ const targetTables = bodyTables(targetTab);
395
+ if (targetTables.length !== plan.tables.length) {
396
+ throw new Error(`table count mismatch after the skeleton: source ${plan.tables.length}, target ${targetTables.length}`);
397
+ }
398
+ const requests = [];
399
+ for (let t = plan.tables.length - 1; t >= 0; t--) {
400
+ const targetRows = targetTables[t].table?.tableRows ?? [];
401
+ const rows = plan.cellTokens[t];
402
+ for (let r = rows.length - 1; r >= 0; r--) {
403
+ for (let c = rows[r].length - 1; c >= 0; c--) {
404
+ const at = targetRows[r]?.tableCells?.[c]?.content?.[0]?.startIndex;
405
+ if (at === undefined || at === null) {
406
+ throw new Error(`target table ${t} has no cell at row ${r}, column ${c}`);
407
+ }
408
+ const location = { index: at, tabId: targetTabId };
409
+ for (const token of [...rows[r][c]].reverse()) {
410
+ if (token.kind === 'text') {
411
+ if (token.text)
412
+ requests.push({ insertText: { location, text: token.text } });
413
+ }
414
+ else if (token.kind === 'chip') {
415
+ requests.push({ insertRichLink: { location, richLinkProperties: { uri: token.uri } } });
416
+ }
417
+ }
418
+ }
419
+ }
420
+ }
421
+ return requests;
422
+ }
423
+ function assertParagraphCount(plan, count) {
424
+ if (count !== plan.paragraphs.length) {
425
+ throw new Error(`paragraph count mismatch: source ${plan.paragraphs.length}, target ${count}`);
426
+ }
427
+ }
428
+ /** An API style object without the given fields (and without unset values). */
429
+ function withoutFields(style, drop) {
430
+ const out = {};
431
+ for (const [key, value] of Object.entries(style ?? {})) {
432
+ if (value !== undefined && !drop.includes(key))
433
+ out[key] = value;
434
+ }
435
+ return out;
436
+ }
437
+ /**
438
+ * Phase 3: per unit (one paragraph, or a run of consecutive bullet paragraphs
439
+ * of one list in one container), in this order: paragraph style (incl.
440
+ * namedStyleType) → bullet removal → text-style clear → run styles, per
441
+ * paragraph; then createParagraphBullets over the unit. Units are emitted last
442
+ * first, because createParagraphBullets removes the nesting tabs and shifts
443
+ * every later index. Throws when the target's paragraph count differs.
444
+ */
445
+ export function planStyles(plan, targetTab, targetTabId) {
446
+ const target = flatParagraphs(targetTab.documentTab?.body);
447
+ assertParagraphCount(plan, target.length);
448
+ const source = plan.paragraphs;
449
+ const units = [];
450
+ let i = 0;
451
+ while (i < source.length) {
452
+ const head = source[i];
453
+ let j = i;
454
+ if (head.paragraph.bullet) {
455
+ const listId = head.paragraph.bullet.listId;
456
+ while (j + 1 < source.length &&
457
+ sameContainer(source[j + 1].container, head.container) &&
458
+ // A paragraph without a bullet never joins (an absent listId must not match one).
459
+ Boolean(source[j + 1].paragraph.bullet) &&
460
+ source[j + 1].paragraph.bullet?.listId === listId) {
461
+ j++;
462
+ }
463
+ }
464
+ const requests = [];
465
+ for (let k = i; k <= j; k++) {
466
+ const { paragraph, pieces } = source[k];
467
+ const targetParagraph = target[k];
468
+ const range = { startIndex: targetParagraph.startIndex, endIndex: targetParagraph.endIndex, tabId: targetTabId };
469
+ const drop = paragraph.bullet ? [...PSTYLE_DROP, ...BULLET_INDENT_DROP] : PSTYLE_DROP;
470
+ const paragraphStyle = withoutFields(paragraph.paragraphStyle, drop);
471
+ if (hasKeys(paragraphStyle)) {
472
+ requests.push({ updateParagraphStyle: { range, paragraphStyle, fields: Object.keys(paragraphStyle).join(',') } });
473
+ }
474
+ if (!paragraph.bullet && targetParagraph.paragraph.bullet) {
475
+ requests.push({ deleteParagraphBullets: { range } });
476
+ }
477
+ requests.push({ updateTextStyle: { range, textStyle: {}, fields: ALL_TEXT_KEYS } });
478
+ let cursor = targetParagraph.startIndex;
479
+ for (const piece of pieces) {
480
+ // Nesting tabs have a length but no style.
481
+ const style = piece.style;
482
+ if (hasKeys(style) && piece.length) {
483
+ requests.push({
484
+ updateTextStyle: {
485
+ range: { startIndex: cursor, endIndex: cursor + piece.length, tabId: targetTabId },
486
+ textStyle: style,
487
+ fields: Object.keys(style).join(','),
488
+ },
489
+ });
490
+ }
491
+ cursor += piece.length;
492
+ }
493
+ }
494
+ if (head.paragraph.bullet) {
495
+ requests.push({
496
+ createParagraphBullets: {
497
+ range: { startIndex: target[i].startIndex, endIndex: target[j].endIndex, tabId: targetTabId },
498
+ bulletPreset: presetFor(plan.lists[head.paragraph.bullet.listId ?? ''], plan.notes),
499
+ },
500
+ });
501
+ }
502
+ units.push({ start: target[i].startIndex, requests });
503
+ i = j + 1;
504
+ }
505
+ return units
506
+ .sort((a, b) => b.start - a.start)
507
+ .flatMap((unit) => unit.requests);
508
+ }
509
+ /**
510
+ * Phase 3b: createParagraphBullets resets indents and spacing, so re-apply each
511
+ * bullet paragraph's source style, without namedStyleType (re-applying it
512
+ * would wipe the run styles) and without headingId.
513
+ */
514
+ export function planBulletParagraphStyles(plan, targetTab, targetTabId) {
515
+ const target = flatParagraphs(targetTab.documentTab?.body);
516
+ assertParagraphCount(plan, target.length);
517
+ const requests = [];
518
+ plan.paragraphs.forEach(({ paragraph }, k) => {
519
+ if (!paragraph.bullet)
520
+ return;
521
+ const paragraphStyle = withoutFields(paragraph.paragraphStyle, [...PSTYLE_DROP, 'namedStyleType']);
522
+ if (!hasKeys(paragraphStyle))
523
+ return;
524
+ requests.push({
525
+ updateParagraphStyle: {
526
+ range: { startIndex: target[k].startIndex, endIndex: target[k].endIndex, tabId: targetTabId },
527
+ paragraphStyle,
528
+ fields: Object.keys(paragraphStyle).join(','),
529
+ },
530
+ });
531
+ });
532
+ return requests;
533
+ }
534
+ /**
535
+ * Phase 4: table column properties and cell styles (merges are not
536
+ * reproduced, so rowSpan/columnSpan are dropped).
537
+ */
538
+ export function planTableStyles(plan, targetTab, targetTabId) {
539
+ const targetTables = bodyTables(targetTab);
540
+ if (targetTables.length !== plan.tables.length) {
541
+ throw new Error(`table count mismatch: source ${plan.tables.length}, target ${targetTables.length}`);
542
+ }
543
+ const requests = [];
544
+ plan.tables.forEach((table, t) => {
545
+ const tableStartLocation = { index: targetTables[t].startIndex ?? 0, tabId: targetTabId };
546
+ (table.tableStyle?.tableColumnProperties ?? []).forEach((properties, columnIndex) => {
547
+ const tableColumnProperties = withoutFields(properties, []);
548
+ if (!hasKeys(tableColumnProperties))
549
+ return;
550
+ requests.push({
551
+ updateTableColumnProperties: {
552
+ tableStartLocation,
553
+ columnIndices: [columnIndex],
554
+ tableColumnProperties,
555
+ fields: Object.keys(tableColumnProperties).join(','),
556
+ },
557
+ });
558
+ });
559
+ (table.tableRows ?? []).forEach((row, rowIndex) => {
560
+ (row.tableCells ?? []).forEach((cell, columnIndex) => {
561
+ const tableCellStyle = withoutFields(cell.tableCellStyle, ['rowSpan', 'columnSpan']);
562
+ if (!hasKeys(tableCellStyle))
563
+ return;
564
+ requests.push({
565
+ updateTableCellStyle: {
566
+ tableRange: {
567
+ tableCellLocation: { tableStartLocation, rowIndex, columnIndex },
568
+ rowSpan: 1,
569
+ columnSpan: 1,
570
+ },
571
+ tableCellStyle,
572
+ fields: Object.keys(tableCellStyle).join(','),
573
+ },
574
+ });
575
+ });
576
+ });
577
+ });
578
+ return requests;
579
+ }
580
+ // Sentinels for non-text elements in verification text (control characters
581
+ // never occur in Docs text, so they cannot collide with real content).
582
+ const CHIP_MARK = '\u0001chip\u0001';
583
+ const PAGE_BREAK_MARK = '\u0001pagebreak\u0001';
584
+ function expectedText(pieces) {
585
+ return pieces
586
+ .map((piece) => {
587
+ if (piece.kind === 'chip')
588
+ return CHIP_MARK;
589
+ if (piece.kind === 'pagebreak')
590
+ return PAGE_BREAK_MARK;
591
+ return piece.nesting ? '' : piece.text;
592
+ })
593
+ .join('');
594
+ }
595
+ function actualText(paragraph) {
596
+ return (paragraph.elements ?? [])
597
+ .map((element) => {
598
+ if (element.textRun)
599
+ return element.textRun.content ?? '';
600
+ if (element.richLink)
601
+ return CHIP_MARK;
602
+ if (element.pageBreak)
603
+ return PAGE_BREAK_MARK;
604
+ return `\u0001${elementKind(element)}\u0001`;
605
+ })
606
+ .join('');
607
+ }
608
+ /**
609
+ * Paragraph-format fields compared by verification, when set on the source
610
+ * paragraph. headingId is never compared. If the live API normalises one of
611
+ * these on every paragraph (a difference that is not a copy defect), remove
612
+ * that field here with a comment saying why.
613
+ */
614
+ export const VERIFIED_PARAGRAPH_FIELDS = [
615
+ 'alignment',
616
+ 'direction',
617
+ 'indentStart',
618
+ 'indentEnd',
619
+ 'indentFirstLine',
620
+ 'spaceAbove',
621
+ 'spaceBelow',
622
+ 'lineSpacing',
623
+ 'spacingMode',
624
+ ];
625
+ const DIMENSION_FIELDS = new Set(['indentStart', 'indentEnd', 'indentFirstLine', 'spaceAbove', 'spaceBelow']);
626
+ /**
627
+ * A paragraph-style field as it takes effect: the paragraph's own value, else
628
+ * its named style's, else (for lengths) 0. Lengths compare by magnitude.
629
+ */
630
+ function effectiveParagraphValue(style, namedStyles, field) {
631
+ let value = style?.[field];
632
+ if (value === undefined || value === null) {
633
+ const type = style?.namedStyleType ?? 'NORMAL_TEXT';
634
+ value = namedStyles?.styles?.find((named) => named.namedStyleType === type)?.paragraphStyle?.[field];
635
+ }
636
+ if (DIMENSION_FIELDS.has(field)) {
637
+ return value?.magnitude ?? 0;
638
+ }
639
+ return value ?? undefined;
640
+ }
641
+ /**
642
+ * Compare the copied tab with the source: per paragraph the text (with chip
643
+ * fallbacks, people and dates as the text that was inserted), named style,
644
+ * paragraph formatting, bullet and nesting; list grouping (one-to-one list
645
+ * mapping); table count and shapes. Run styles and table cell styles are not
646
+ * compared. Reports indices and kinds only, never document text.
647
+ */
648
+ export function verifyCopy(plan, sourceTab, targetTab) {
649
+ const mismatches = [];
650
+ const target = flatParagraphs(targetTab.documentTab?.body);
651
+ const sourceNamed = sourceTab.documentTab?.namedStyles;
652
+ const targetNamed = targetTab.documentTab?.namedStyles;
653
+ if (target.length !== plan.paragraphs.length) {
654
+ mismatches.push({ kind: 'paragraphCount' });
655
+ }
656
+ const sourceToTarget = new Map();
657
+ const targetToSource = new Map();
658
+ const count = Math.min(target.length, plan.paragraphs.length);
659
+ for (let k = 0; k < count; k++) {
660
+ const { paragraph: src, pieces } = plan.paragraphs[k];
661
+ const tgt = target[k].paragraph;
662
+ if (expectedText(pieces) !== actualText(tgt)) {
663
+ mismatches.push({ paragraphIndex: k, kind: 'text' });
664
+ }
665
+ const srcType = src.paragraphStyle?.namedStyleType ?? 'NORMAL_TEXT';
666
+ const tgtType = tgt.paragraphStyle?.namedStyleType ?? 'NORMAL_TEXT';
667
+ if (srcType !== tgtType) {
668
+ mismatches.push({ paragraphIndex: k, kind: 'namedStyle' });
669
+ }
670
+ for (const field of VERIFIED_PARAGRAPH_FIELDS) {
671
+ const own = src.paragraphStyle?.[field];
672
+ if (own === undefined || own === null)
673
+ continue;
674
+ const expected = effectiveParagraphValue(src.paragraphStyle, sourceNamed, field);
675
+ const actual = effectiveParagraphValue(tgt.paragraphStyle, targetNamed, field);
676
+ if (!deepEqual(expected, actual)) {
677
+ mismatches.push({ paragraphIndex: k, kind: `paragraphStyle.${field}` });
678
+ }
679
+ }
680
+ if (Boolean(src.bullet) !== Boolean(tgt.bullet) || (src.bullet?.nestingLevel ?? 0) !== (tgt.bullet?.nestingLevel ?? 0)) {
681
+ mismatches.push({ paragraphIndex: k, kind: 'bullet' });
682
+ }
683
+ else if (src.bullet && tgt.bullet) {
684
+ const srcList = src.bullet.listId ?? '';
685
+ const tgtList = tgt.bullet.listId ?? '';
686
+ const mapped = sourceToTarget.get(srcList);
687
+ const back = targetToSource.get(tgtList);
688
+ if ((mapped !== undefined && mapped !== tgtList) || (back !== undefined && back !== srcList)) {
689
+ mismatches.push({ paragraphIndex: k, kind: 'listGrouping' });
690
+ }
691
+ else {
692
+ sourceToTarget.set(srcList, tgtList);
693
+ targetToSource.set(tgtList, srcList);
694
+ }
695
+ }
696
+ }
697
+ const targetTables = bodyTables(targetTab);
698
+ plan.tables.forEach((table, t) => {
699
+ const other = targetTables[t]?.table;
700
+ if (!other || other.rows !== table.rows || other.columns !== table.columns) {
701
+ mismatches.push({ tableIndex: t, kind: 'tableShape' });
702
+ }
703
+ });
704
+ if (targetTables.length > plan.tables.length) {
705
+ mismatches.push({ tableIndex: plan.tables.length, kind: 'tableShape' });
706
+ }
707
+ return {
708
+ passed: mismatches.length === 0,
709
+ checkedParagraphs: plan.paragraphs.length,
710
+ tables: plan.tables.length,
711
+ lists: new Set(plan.paragraphs.flatMap((p) => (p.paragraph.bullet ? [p.paragraph.bullet.listId ?? ''] : []))).size,
712
+ placeholders: plan.placeholders,
713
+ mismatchCount: mismatches.length,
714
+ mismatches: mismatches.slice(0, 5),
715
+ };
716
+ }
717
+ /**
718
+ * Run the copy: read and plan the source, check every chip, prepare the
719
+ * target, then Phases 0-4 and a verification read. Requests are sent in
720
+ * chunks of CHUNK per batchUpdate. Any failure is rethrown as a TabCopyError
721
+ * naming the phase and whether content had already been written.
722
+ */
723
+ export async function copyTabContent(deps) {
724
+ let phase = 'read source';
725
+ let wroteContent = false;
726
+ let attemptedWrite = false;
727
+ let requests = 0;
728
+ let rounds = 0;
729
+ const send = async (label, batch) => {
730
+ phase = label;
731
+ if (batch.length === 0)
732
+ return;
733
+ for (let i = 0; i < batch.length; i += CHUNK) {
734
+ attemptedWrite = true;
735
+ await deps.batchUpdate(batch.slice(i, i + CHUNK));
736
+ wroteContent = true;
737
+ }
738
+ requests += batch.length;
739
+ rounds++;
740
+ };
741
+ try {
742
+ const source = await deps.getSourceTab();
743
+ phase = 'check smart chips';
744
+ const chipAccess = new Map();
745
+ for (const uri of collectChipUris(source)) {
746
+ chipAccess.set(uri, idFromUri(uri) ? await deps.checkChip(uri) : false);
747
+ }
748
+ phase = 'plan source';
749
+ const plan = buildSourcePlan(source, chipAccess);
750
+ phase = 'prepare target';
751
+ const targetTabId = await deps.prepareTarget();
752
+ phase = 'read target';
753
+ let target = await deps.getTab(targetTabId);
754
+ // Phase 0: clear target body, reset its last paragraph, copy doc + named styles
755
+ const clear = planClear(source, target, targetTabId);
756
+ await send('clear + document styles', clear.requests);
757
+ // Phase 1: skeleton appended in order
758
+ await send('skeleton', planSkeleton(plan, targetTabId));
759
+ // Phase 2: table cells, reverse order
760
+ phase = 'table cells';
761
+ target = await deps.getTab(targetTabId);
762
+ await send('table cells', planTableCells(plan, target, targetTabId));
763
+ // Phase 3: per unit (descending): named/para style -> clear text style -> run styles -> bullets
764
+ phase = 'styles + bullets';
765
+ target = await deps.getTab(targetTabId);
766
+ await send('styles + bullets', planStyles(plan, target, targetTabId));
767
+ // Phase 3b: bullets reset paragraph style; re-apply it minus namedStyleType (re-applying that wipes run styles)
768
+ phase = 'bullet paragraph styles';
769
+ target = await deps.getTab(targetTabId);
770
+ await send('bullet paragraph styles', planBulletParagraphStyles(plan, target, targetTabId));
771
+ // Phase 4: tables (from the Phase 3b read; 3b changes no indices)
772
+ phase = 'table styles';
773
+ await send('table styles', planTableStyles(plan, target, targetTabId));
774
+ phase = 'verify';
775
+ const final = await deps.getTab(targetTabId);
776
+ const verification = verifyCopy(plan, source, final);
777
+ return {
778
+ targetTabId,
779
+ requests,
780
+ rounds,
781
+ chipsCopied: plan.chipsCopied,
782
+ chipFallbacks: plan.chipFallbacks,
783
+ convertedToText: plan.convertedToText,
784
+ namedStylesCopied: clear.namedStylesCopied,
785
+ notCopied: plan.notCopied,
786
+ notes: [...new Set(plan.notes)].sort(),
787
+ verification,
788
+ };
789
+ }
790
+ catch (error) {
791
+ throw new TabCopyError(phase, wroteContent, attemptedWrite, error);
792
+ }
793
+ }
794
+ //# sourceMappingURL=tabCopy.js.map