@mutallip/google-workspace-mcp 0.0.0-stage → 2.8.1

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 (105) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +353 -2
  3. package/README.npm.md +34 -0
  4. package/auth/__init__.py +1 -0
  5. package/auth/auth_info_middleware.py +419 -0
  6. package/auth/client_secrets.py +76 -0
  7. package/auth/credential_store.py +598 -0
  8. package/auth/external_oauth_provider.py +369 -0
  9. package/auth/gateway_identity.py +164 -0
  10. package/auth/google_auth.py +1550 -0
  11. package/auth/google_oauth_provider.py +20 -0
  12. package/auth/mcp_session_middleware.py +95 -0
  13. package/auth/oauth21_session_store.py +1332 -0
  14. package/auth/oauth_callback_server.py +466 -0
  15. package/auth/oauth_config.py +693 -0
  16. package/auth/oauth_proxy_config.py +122 -0
  17. package/auth/oauth_responses.py +230 -0
  18. package/auth/oauth_types.py +92 -0
  19. package/auth/permissions.py +330 -0
  20. package/auth/port_resolver.py +153 -0
  21. package/auth/request_identity.py +89 -0
  22. package/auth/scopes.py +369 -0
  23. package/auth/service_decorator.py +1109 -0
  24. package/bin/google-workspace-mcp.cjs +123 -0
  25. package/core/__init__.py +1 -0
  26. package/core/api_enablement.py +108 -0
  27. package/core/attachment_storage.py +496 -0
  28. package/core/camel_case_middleware.py +98 -0
  29. package/core/cli.py +161 -0
  30. package/core/comments.py +609 -0
  31. package/core/config.py +57 -0
  32. package/core/context.py +43 -0
  33. package/core/file_limits.py +632 -0
  34. package/core/gcs_attachment_storage.py +253 -0
  35. package/core/http_utils.py +339 -0
  36. package/core/log_formatter.py +270 -0
  37. package/core/portable_schema_middleware.py +67 -0
  38. package/core/server.py +1192 -0
  39. package/core/startup_ui.py +239 -0
  40. package/core/storage.py +23 -0
  41. package/core/telemetry.py +194 -0
  42. package/core/tool_descriptions.py +19 -0
  43. package/core/tool_registry.py +311 -0
  44. package/core/tool_tier_loader.py +197 -0
  45. package/core/tool_tiers.yaml +179 -0
  46. package/core/toolset_header_middleware.py +67 -0
  47. package/core/utils.py +1537 -0
  48. package/core/valkey_storage.py +271 -0
  49. package/core/warning_filters.py +19 -0
  50. package/fastmcp_server.py +198 -0
  51. package/gappsscript/README.md +512 -0
  52. package/gappsscript/TESTING.md +254 -0
  53. package/gappsscript/__init__.py +0 -0
  54. package/gappsscript/apps_script_tools.py +1940 -0
  55. package/gcalendar/__init__.py +1 -0
  56. package/gcalendar/calendar_helpers.py +1323 -0
  57. package/gcalendar/calendar_tools.py +2252 -0
  58. package/gchat/__init__.py +7 -0
  59. package/gchat/chat_helpers.py +410 -0
  60. package/gchat/chat_tools.py +798 -0
  61. package/gcontacts/__init__.py +1 -0
  62. package/gcontacts/contacts_helpers.py +765 -0
  63. package/gcontacts/contacts_tools.py +1685 -0
  64. package/gdocs/__init__.py +0 -0
  65. package/gdocs/docs_anchors.py +163 -0
  66. package/gdocs/docs_comments.py +89 -0
  67. package/gdocs/docs_helpers.py +2201 -0
  68. package/gdocs/docs_links.py +87 -0
  69. package/gdocs/docs_markdown.py +828 -0
  70. package/gdocs/docs_markdown_writer.py +592 -0
  71. package/gdocs/docs_plain_text.py +463 -0
  72. package/gdocs/docs_structure.py +621 -0
  73. package/gdocs/docs_tables.py +425 -0
  74. package/gdocs/docs_tools.py +3300 -0
  75. package/gdocs/managers/__init__.py +18 -0
  76. package/gdocs/managers/batch_operation_manager.py +1694 -0
  77. package/gdocs/managers/header_footer_manager.py +526 -0
  78. package/gdocs/managers/table_operation_manager.py +488 -0
  79. package/gdocs/managers/validation_manager.py +1504 -0
  80. package/gdocs/operation_schemas.py +594 -0
  81. package/gdrive/__init__.py +0 -0
  82. package/gdrive/drive_helpers.py +1738 -0
  83. package/gdrive/drive_tools.py +3085 -0
  84. package/gforms/__init__.py +3 -0
  85. package/gforms/forms_tools.py +575 -0
  86. package/gmail/__init__.py +1 -0
  87. package/gmail/gmail_helpers.py +2107 -0
  88. package/gmail/gmail_tools.py +4895 -0
  89. package/gmail/gmail_web_mime.py +441 -0
  90. package/gsearch/__init__.py +0 -0
  91. package/gsearch/search_tools.py +253 -0
  92. package/gsheets/__init__.py +31 -0
  93. package/gsheets/sheets_helpers.py +2236 -0
  94. package/gsheets/sheets_tools.py +3280 -0
  95. package/gslides/__init__.py +0 -0
  96. package/gslides/slides_digest.py +390 -0
  97. package/gslides/slides_helpers.py +392 -0
  98. package/gslides/slides_markup.py +770 -0
  99. package/gslides/slides_tools.py +376 -0
  100. package/gtasks/__init__.py +5 -0
  101. package/gtasks/tasks_tools.py +936 -0
  102. package/main.py +1170 -0
  103. package/package.json +43 -4
  104. package/pyproject.toml +173 -0
  105. package/uv.lock +2504 -0
@@ -0,0 +1,592 @@
1
+ """Markdown to Google Docs API batchUpdate request converter.
2
+
3
+ Parses CommonMark markdown via markdown-it-py (commonmark preset) and emits
4
+ a list of Docs API request dicts that, when applied in order, render the
5
+ markdown into a document or a specific tab within a document.
6
+
7
+ Supported constructs - headings H1-H6, paragraphs with inline bold/italic/
8
+ code/links, ordered and unordered lists, fenced code blocks, blockquotes,
9
+ horizontal rules, image alt text linked to the image URL, and GFM pipe
10
+ tables (rendered as native Docs tables with bold header rows). Other
11
+ GFM-only features (strikethrough, task lists, autolinks) are not enabled;
12
+ extend the parser config below if they become needed.
13
+
14
+ Primary entry point - markdown_to_docs_requests(markdown_text, tab_id=None).
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from typing import Optional
20
+
21
+ from markdown_it import MarkdownIt
22
+
23
+ from gdocs.docs_helpers import (
24
+ create_delete_bullet_list_request,
25
+ create_delete_range_request,
26
+ create_insert_text_request,
27
+ )
28
+
29
+ _NORMAL_TEXT = {"namedStyleType": "NORMAL_TEXT"}
30
+ _BLOCK_GAP = {"spaceBelow": {"magnitude": 12, "unit": "PT"}}
31
+ _DOCS_MAX_TABLE_ROWS = 1000
32
+ _DOCS_MAX_TABLE_COLS = 20
33
+
34
+
35
+ def markdown_to_docs_requests(
36
+ markdown_text: str,
37
+ tab_id: Optional[str] = None,
38
+ start_index: int = 1,
39
+ ) -> list[dict]:
40
+ """Convert markdown to a list of Docs API batchUpdate request dicts.
41
+
42
+ Args:
43
+ markdown_text - the markdown source
44
+ tab_id - optional tab ID; when provided, every range targets this tab
45
+ start_index - document index at which content insertion begins
46
+
47
+ Returns:
48
+ Ordered list of request dicts. Empty list for empty input.
49
+ """
50
+ if not markdown_text.strip():
51
+ return []
52
+
53
+ md = MarkdownIt("commonmark").enable("table")
54
+ tokens = md.parse(markdown_text)
55
+
56
+ requests: list[dict] = []
57
+ _emit_requests(tokens, requests, tab_id, start_index)
58
+ return requests
59
+
60
+
61
+ def _utf16_len(text: str) -> int:
62
+ """Return the length of text in UTF-16 code units, the Docs API index unit."""
63
+ return len(text.encode("utf-16-le", errors="surrogatepass")) // 2
64
+
65
+
66
+ def _emit_requests(tokens, requests, tab_id, start_index):
67
+ """Walk markdown-it tokens and append Docs API requests.
68
+
69
+ Maintains a running `cursor` that represents the current insertion point
70
+ in the document. Each insertText advances cursor by _utf16_len(text).
71
+ """
72
+ cursor = [start_index] # mutable via list so helpers can advance it
73
+
74
+ i = 0
75
+ while i < len(tokens):
76
+ tok = tokens[i]
77
+
78
+ if tok.type == "heading_open":
79
+ level = int(tok.tag[1]) # 'h1' -> 1
80
+ inline_tok = tokens[i + 1]
81
+ text, inline_styles = _render_inline_with_styles(
82
+ inline_tok.children or [], cursor[0], tab_id
83
+ )
84
+ text += "\n"
85
+ range_start = cursor[0]
86
+ requests.append(_build_insert_text(cursor[0], text, tab_id))
87
+ cursor[0] += _utf16_len(text)
88
+ requests.append(
89
+ _build_paragraph_style(
90
+ range_start,
91
+ cursor[0],
92
+ {"namedStyleType": f"HEADING_{level}"},
93
+ tab_id,
94
+ )
95
+ )
96
+ requests.extend(inline_styles)
97
+ i += 3
98
+ continue
99
+
100
+ if tok.type in ("bullet_list_open", "ordered_list_open"):
101
+ preset = (
102
+ "BULLET_DISC_CIRCLE_SQUARE"
103
+ if tok.type == "bullet_list_open"
104
+ else "NUMBERED_DECIMAL_ALPHA_ROMAN"
105
+ )
106
+ list_start = cursor[0]
107
+ # Find the matching closing token
108
+ close_type = tok.type.replace("_open", "_close")
109
+ depth = 1
110
+ j = i + 1
111
+ while j < len(tokens) and depth > 0:
112
+ if tokens[j].type == tok.type:
113
+ depth += 1
114
+ elif tokens[j].type == close_type:
115
+ depth -= 1
116
+ if depth == 0:
117
+ break
118
+ j += 1
119
+ # Iterate items between i and j
120
+ k = i + 1
121
+ while k < j:
122
+ item = tokens[k]
123
+ if item.type == "table_open":
124
+ row_cells, k = _collect_table_cells(tokens, k)
125
+ _emit_table_rows_as_text(row_cells, requests, cursor, tab_id)
126
+ elif item.type == "list_item_open":
127
+ # Inner structure typically - list_item_open, paragraph_open, inline, paragraph_close, list_item_close
128
+ # Find the inline token within this list_item
129
+ if k + 2 < j and tokens[k + 2].type == "inline":
130
+ inline_tok = tokens[k + 2]
131
+ text, inline_styles = _render_inline_with_styles(
132
+ inline_tok.children or [], cursor[0], tab_id
133
+ )
134
+ text += "\n"
135
+ requests.append(_build_insert_text(cursor[0], text, tab_id))
136
+ cursor[0] += _utf16_len(text)
137
+ requests.extend(inline_styles)
138
+ k += 1
139
+ list_end = cursor[0]
140
+ if list_end > list_start:
141
+ requests.append(
142
+ _build_paragraph_style(list_start, list_end, _NORMAL_TEXT, tab_id)
143
+ )
144
+ # One createParagraphBullets covering the full list range
145
+ rng = {"startIndex": list_start, "endIndex": list_end}
146
+ if tab_id:
147
+ rng["tabId"] = tab_id
148
+ requests.append(
149
+ {
150
+ "createParagraphBullets": {
151
+ "range": rng,
152
+ "bulletPreset": preset,
153
+ }
154
+ }
155
+ )
156
+ _append_block_gap(requests, list_start, list_end, tab_id)
157
+ i = j + 1
158
+ continue
159
+
160
+ if tok.type == "fence":
161
+ content = tok.content
162
+ start_idx = cursor[0]
163
+ # Ensure exactly one trailing newline to end the code paragraph.
164
+ text = content if content.endswith("\n") else content + "\n"
165
+ requests.append(_build_insert_text(cursor[0], text, tab_id))
166
+ cursor[0] += _utf16_len(text)
167
+ requests.append(
168
+ _build_paragraph_style(start_idx, cursor[0], _NORMAL_TEXT, tab_id)
169
+ )
170
+ # Style the code characters but not the paragraph-ending newline.
171
+ code_end = cursor[0] - 1
172
+ _append_text_style(
173
+ requests,
174
+ start_idx,
175
+ code_end,
176
+ {"weightedFontFamily": {"fontFamily": "Courier New", "weight": 400}},
177
+ "weightedFontFamily",
178
+ tab_id,
179
+ )
180
+ _append_block_gap(requests, start_idx, cursor[0], tab_id)
181
+ i += 1
182
+ continue
183
+
184
+ if tok.type == "blockquote_open":
185
+ close_type = "blockquote_close"
186
+ depth = 1
187
+ j = i + 1
188
+ while j < len(tokens) and depth > 0:
189
+ if tokens[j].type == tok.type:
190
+ depth += 1
191
+ elif tokens[j].type == close_type:
192
+ depth -= 1
193
+ if depth == 0:
194
+ break
195
+ j += 1
196
+ quote_start = cursor[0]
197
+ # Process paragraphs inside the blockquote
198
+ k = i + 1
199
+ while k < j:
200
+ if tokens[k].type == "table_open":
201
+ row_cells, k = _collect_table_cells(tokens, k)
202
+ _emit_table_rows_as_text(row_cells, requests, cursor, tab_id)
203
+ k += 1
204
+ continue
205
+ if (
206
+ tokens[k].type == "paragraph_open"
207
+ and k + 1 < j
208
+ and tokens[k + 1].type == "inline"
209
+ ):
210
+ inline_tok = tokens[k + 1]
211
+ text, inline_styles = _render_inline_with_styles(
212
+ inline_tok.children or [], cursor[0], tab_id
213
+ )
214
+ text += "\n"
215
+ requests.append(_build_insert_text(cursor[0], text, tab_id))
216
+ cursor[0] += _utf16_len(text)
217
+ requests.extend(inline_styles)
218
+ k += 3
219
+ continue
220
+ k += 1
221
+ quote_end = cursor[0]
222
+ if quote_end > quote_start:
223
+ # One request: Docs applies namedStyleType before indentStart.
224
+ requests.append(
225
+ _build_paragraph_style(
226
+ quote_start,
227
+ quote_end,
228
+ {
229
+ **_NORMAL_TEXT,
230
+ "indentStart": {"magnitude": 36, "unit": "PT"},
231
+ },
232
+ tab_id,
233
+ )
234
+ )
235
+ _append_block_gap(requests, quote_start, quote_end, tab_id)
236
+ i = j + 1
237
+ continue
238
+
239
+ if tok.type == "hr":
240
+ _append_spacer(requests, cursor, tab_id)
241
+ i += 1
242
+ continue
243
+
244
+ if tok.type == "table_open":
245
+ row_cells, i = _collect_table_cells(tokens, i)
246
+ _emit_table(row_cells, requests, cursor, tab_id)
247
+ i += 1
248
+ continue
249
+
250
+ if tok.type == "paragraph_open":
251
+ # paragraph_open is followed by inline (children), then paragraph_close
252
+ inline_tok = tokens[i + 1]
253
+ text, inline_styles = _render_inline_with_styles(
254
+ inline_tok.children or [], cursor[0], tab_id
255
+ )
256
+ text += "\n"
257
+ range_start = cursor[0]
258
+ requests.append(_build_insert_text(cursor[0], text, tab_id))
259
+ cursor[0] += _utf16_len(text)
260
+ requests.append(
261
+ _build_paragraph_style(range_start, cursor[0], _NORMAL_TEXT, tab_id)
262
+ )
263
+ requests.extend(inline_styles)
264
+ _append_block_gap(requests, range_start, cursor[0], tab_id)
265
+ i += 3 # skip paragraph_open, inline, paragraph_close
266
+ continue
267
+
268
+ i += 1
269
+
270
+
271
+ def _collect_table_cells(tokens, start):
272
+ """Return (rows of cell inline children, index of the matching table_close)."""
273
+ rows: list[list] = []
274
+ k = start
275
+ while tokens[k].type != "table_close":
276
+ if tokens[k].type == "tr_open":
277
+ rows.append([])
278
+ elif tokens[k].type == "inline":
279
+ rows[-1].append(tokens[k].children or [])
280
+ k += 1
281
+ return rows, k
282
+
283
+
284
+ def _emit_table_rows_as_text(row_cells, requests, cursor, tab_id):
285
+ """Emit each table row as one plain-text paragraph with cells joined by ' | '."""
286
+ for row in row_cells:
287
+ cells = (_render_inline_with_styles(cell, 0, tab_id)[0] for cell in row)
288
+ line = " | ".join(cells) + "\n"
289
+ requests.append(_build_insert_text(cursor[0], line, tab_id))
290
+ cursor[0] += _utf16_len(line)
291
+
292
+
293
+ def _emit_table(row_cells, requests, cursor, tab_id):
294
+ """Emit insertTable plus cell fills for one table and advance cursor past it.
295
+
296
+ An empty R x C table inserted at L keeps a newline paragraph at L, puts
297
+ cell (r, c)'s paragraph at L + 4 + r * (1 + 2C) + 2c and ends at
298
+ L + 3 + R * (1 + 2C); cells fill last to first so those indexes hold.
299
+ """
300
+ rows, cols = len(row_cells), len(row_cells[0])
301
+ start = cursor[0]
302
+ if rows > _DOCS_MAX_TABLE_ROWS or cols > _DOCS_MAX_TABLE_COLS:
303
+ _emit_table_rows_as_text(row_cells, requests, cursor, tab_id)
304
+ requests.append(_build_paragraph_style(start, cursor[0], _NORMAL_TEXT, tab_id))
305
+ return
306
+
307
+ if requests and requests[-1] == _build_paragraph_style(
308
+ start - 1, start, _BLOCK_GAP, tab_id
309
+ ):
310
+ requests.pop()
311
+ requests.append(_build_insert_table(start, rows, cols, tab_id))
312
+ requests.append(_build_paragraph_style(start, start + 1, _NORMAL_TEXT, tab_id))
313
+ stride = 1 + 2 * cols
314
+ cursor[0] = start + 3 + rows * stride
315
+ for r in reversed(range(rows)):
316
+ for c in reversed(range(cols)):
317
+ index = start + 4 + r * stride + 2 * c
318
+ text, styles = _render_inline_with_styles(row_cells[r][c], index, tab_id)
319
+ if not text:
320
+ continue
321
+ end = index + _utf16_len(text)
322
+ requests.append(_build_insert_text(index, text, tab_id))
323
+ requests.extend(styles)
324
+ if r == 0:
325
+ _append_text_style(requests, index, end, {"bold": True}, "bold", tab_id)
326
+ cursor[0] += end - index
327
+
328
+
329
+ def _build_insert_table(
330
+ index: int, rows: int, cols: int, tab_id: Optional[str]
331
+ ) -> dict:
332
+ """Build an insertTable request dict, threading tab_id if provided."""
333
+ location = {"index": index}
334
+ if tab_id:
335
+ location["tabId"] = tab_id
336
+ return {
337
+ "insertTable": {
338
+ "location": location,
339
+ "rows": rows,
340
+ "columns": cols,
341
+ }
342
+ }
343
+
344
+
345
+ def _render_inline_with_styles(
346
+ children,
347
+ base_index: int,
348
+ tab_id: Optional[str],
349
+ ) -> tuple[str, list[dict]]:
350
+ """Walk inline tokens, returning plain text and style requests.
351
+
352
+ Args:
353
+ children - inline tokens from markdown-it
354
+ base_index - the document index where this inline block starts
355
+ tab_id - optional tab ID for ranges
356
+
357
+ Returns:
358
+ (plain_text, style_requests). The caller emits insertText with
359
+ plain_text starting at base_index, then appends the style_requests.
360
+ """
361
+ text_parts: list[str] = []
362
+ style_requests: list[dict] = []
363
+ local_pos = 0 # position within this inline block (0-based)
364
+ # Stack entries are tuples. For strong/em: (style_name, start_local_pos).
365
+ # For link: (style_name, start_local_pos, href).
366
+ stack: list[tuple] = []
367
+
368
+ for tok in children:
369
+ if tok.type == "text":
370
+ text_parts.append(tok.content)
371
+ local_pos += _utf16_len(tok.content)
372
+ elif tok.type == "softbreak":
373
+ text_parts.append(" ")
374
+ local_pos += 1
375
+ elif tok.type == "hardbreak":
376
+ text_parts.append("\n")
377
+ local_pos += 1
378
+ elif tok.type == "code_inline":
379
+ # self-contained - emit style immediately
380
+ start_local = local_pos
381
+ text_parts.append(tok.content)
382
+ local_pos += _utf16_len(tok.content)
383
+ _append_text_style(
384
+ style_requests,
385
+ base_index + start_local,
386
+ base_index + local_pos,
387
+ {"weightedFontFamily": {"fontFamily": "Courier New", "weight": 400}},
388
+ "weightedFontFamily",
389
+ tab_id,
390
+ )
391
+ elif tok.type in ("strong_open", "em_open"):
392
+ stack.append((tok.type, local_pos))
393
+ elif tok.type in ("strong_close", "em_close"):
394
+ opener_type = tok.type.replace("_close", "_open")
395
+ for idx in range(len(stack) - 1, -1, -1):
396
+ if stack[idx][0] == opener_type:
397
+ _, start_local = stack.pop(idx)
398
+ style_key = "bold" if opener_type == "strong_open" else "italic"
399
+ _append_text_style(
400
+ style_requests,
401
+ base_index + start_local,
402
+ base_index + local_pos,
403
+ {style_key: True},
404
+ style_key,
405
+ tab_id,
406
+ )
407
+ break
408
+ elif tok.type == "link_open":
409
+ # tok.attrs may be a dict (newer markdown-it-py) or list of [key, val]
410
+ # pairs (older). Support both.
411
+ href = _token_attr(tok, "href")
412
+ stack.append(("link_open", local_pos, href))
413
+ elif tok.type == "link_close":
414
+ for idx in range(len(stack) - 1, -1, -1):
415
+ if stack[idx][0] == "link_open":
416
+ _, start_local, href = stack.pop(idx)
417
+ if href:
418
+ _append_text_style(
419
+ style_requests,
420
+ base_index + start_local,
421
+ base_index + local_pos,
422
+ {"link": {"url": href}},
423
+ "link",
424
+ tab_id,
425
+ )
426
+ break
427
+ elif tok.type == "image":
428
+ src = _token_attr(tok, "src")
429
+ label = tok.content or src or ""
430
+ if label:
431
+ start_local = local_pos
432
+ text_parts.append(label)
433
+ local_pos += _utf16_len(label)
434
+ if src:
435
+ _append_text_style(
436
+ style_requests,
437
+ base_index + start_local,
438
+ base_index + local_pos,
439
+ {"link": {"url": src}},
440
+ "link",
441
+ tab_id,
442
+ )
443
+ elif tok.type in ("html_inline", "html_block"):
444
+ text_parts.append(tok.content)
445
+ local_pos += _utf16_len(tok.content)
446
+
447
+ return "".join(text_parts), style_requests
448
+
449
+
450
+ def _append_text_style(
451
+ requests: list[dict],
452
+ start: int,
453
+ end: int,
454
+ style: dict,
455
+ fields: str,
456
+ tab_id: Optional[str],
457
+ ) -> None:
458
+ """Append an updateTextStyle request when Google Docs will accept the range."""
459
+ if end <= start:
460
+ return
461
+ requests.append(_build_text_style(start, end, style, fields, tab_id))
462
+
463
+
464
+ def _token_attr(token, name: str) -> Optional[str]:
465
+ """Return a markdown-it token attr across supported markdown-it-py versions."""
466
+ attrs = token.attrs
467
+ if isinstance(attrs, dict):
468
+ return attrs.get(name)
469
+ return next((attr[1] for attr in attrs or [] if attr[0] == name), None)
470
+
471
+
472
+ def _build_text_style(
473
+ start: int,
474
+ end: int,
475
+ style: dict,
476
+ fields: str,
477
+ tab_id: Optional[str],
478
+ ) -> dict:
479
+ """Build an updateTextStyle request."""
480
+ rng = {"startIndex": start, "endIndex": end}
481
+ if tab_id:
482
+ rng["tabId"] = tab_id
483
+ return {
484
+ "updateTextStyle": {
485
+ "range": rng,
486
+ "textStyle": style,
487
+ "fields": fields,
488
+ }
489
+ }
490
+
491
+
492
+ def _build_insert_text(index: int, text: str, tab_id: Optional[str]) -> dict:
493
+ """Build an insertText request dict, threading tab_id if provided."""
494
+ location = {"index": index}
495
+ if tab_id:
496
+ location["tabId"] = tab_id
497
+ return {"insertText": {"location": location, "text": text}}
498
+
499
+
500
+ def _build_paragraph_style(
501
+ start: int, end: int, style: dict, tab_id: Optional[str]
502
+ ) -> dict:
503
+ """Build an updateParagraphStyle request covering every key in style."""
504
+ rng = {"startIndex": start, "endIndex": end}
505
+ if tab_id:
506
+ rng["tabId"] = tab_id
507
+ return {
508
+ "updateParagraphStyle": {
509
+ "range": rng,
510
+ "paragraphStyle": dict(style),
511
+ "fields": ",".join(style),
512
+ }
513
+ }
514
+
515
+
516
+ def _append_spacer(
517
+ requests: list[dict], cursor: list[int], tab_id: Optional[str]
518
+ ) -> None:
519
+ """Append a blank NORMAL_TEXT spacer paragraph and advance cursor."""
520
+ requests.append(_build_insert_text(cursor[0], "\n", tab_id))
521
+ cursor[0] += 1
522
+ requests.append(
523
+ _build_paragraph_style(cursor[0] - 1, cursor[0], _NORMAL_TEXT, tab_id)
524
+ )
525
+
526
+
527
+ def _append_block_gap(
528
+ requests: list[dict], start: int, end: int, tab_id: Optional[str]
529
+ ) -> None:
530
+ """Append spaceBelow on the last paragraph of a non-empty block."""
531
+ if end > start:
532
+ requests.append(_build_paragraph_style(end - 1, end, _BLOCK_GAP, tab_id))
533
+
534
+
535
+ def build_markdown_insert_requests(
536
+ markdown_text: str,
537
+ insert_at: int,
538
+ tab_id: Optional[str] = None,
539
+ split_paragraph: bool = False,
540
+ drop_bullet: bool = False,
541
+ ) -> list[dict]:
542
+ """Build requests inserting markdown at ``insert_at``; [] if it renders empty.
543
+
544
+ ``split_paragraph`` opens a new paragraph when ``insert_at`` is mid-paragraph;
545
+ ``drop_bullet`` stops the first rendered paragraph inheriting a bullet.
546
+ """
547
+ content_start = insert_at + 1 if split_paragraph else insert_at
548
+ markdown_requests = markdown_to_docs_requests(
549
+ markdown_text, tab_id=tab_id, start_index=content_start
550
+ )
551
+ if not markdown_requests:
552
+ return []
553
+
554
+ requests: list[dict] = []
555
+ if split_paragraph:
556
+ requests.append(create_insert_text_request(insert_at, "\n", tab_id))
557
+ if drop_bullet:
558
+ requests.append(
559
+ create_delete_bullet_list_request(content_start, content_start + 1, tab_id)
560
+ )
561
+ requests.extend(markdown_requests)
562
+ return requests
563
+
564
+
565
+ def build_section_markdown_requests(
566
+ section: dict,
567
+ markdown_text: str,
568
+ append: bool,
569
+ tab_id: Optional[str] = None,
570
+ ) -> list[dict]:
571
+ """Build requests replacing, or appending to, a heading section with markdown."""
572
+ body_start, section_end = section["body_start"], section["section_end"]
573
+ last_paragraph = section["last_paragraph"]
574
+ at_body_end = section_end == last_paragraph["endIndex"] - 1
575
+ drop_bullet = at_body_end and "bullet" in last_paragraph.get("paragraph", {})
576
+ if append or section_end <= body_start:
577
+ return build_markdown_insert_requests(
578
+ markdown_text,
579
+ section_end,
580
+ tab_id,
581
+ split_paragraph=at_body_end and last_paragraph["startIndex"] < section_end,
582
+ drop_bullet=drop_bullet,
583
+ )
584
+ insert_requests = build_markdown_insert_requests(
585
+ markdown_text, body_start, tab_id, drop_bullet=drop_bullet
586
+ )
587
+ if not insert_requests:
588
+ return []
589
+ return [
590
+ create_delete_range_request(body_start, section_end, tab_id),
591
+ *insert_requests,
592
+ ]