gdocs-mcp 0.2.0 → 0.3.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.
- package/README.md +72 -5
- package/dist/index.js +37 -6
- package/dist/tools/execute-script.d.ts +12 -0
- package/dist/tools/execute-script.js +37 -0
- package/dist/tools/format-list.d.ts +20 -0
- package/dist/tools/format-list.js +74 -0
- package/dist/tools/update-header-footer.d.ts +16 -0
- package/dist/tools/update-header-footer.js +103 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# gdocs-mcp
|
|
2
2
|
|
|
3
|
-
Open-source MCP server for Google Docs and Sheets. Give Claude (or any MCP-compatible AI) the ability to read, create, edit, and
|
|
3
|
+
Open-source MCP server for Google Docs and Sheets. Give Claude (or any MCP-compatible AI) the ability to read, create, edit, search, and style your Google Docs — with OAuth tokens that never leave your machine.
|
|
4
4
|
|
|
5
5
|
**Open-source. Self-hosted. Your tokens never leave your machine.**
|
|
6
6
|
|
|
@@ -46,7 +46,7 @@ Restart Claude Desktop. Ask Claude: *"List my recent Google Docs"* to verify.
|
|
|
46
46
|
claude mcp add gdocs -- npx gdocs-mcp
|
|
47
47
|
```
|
|
48
48
|
|
|
49
|
-
## Tools
|
|
49
|
+
## Tools (16)
|
|
50
50
|
|
|
51
51
|
### Google Docs
|
|
52
52
|
|
|
@@ -69,21 +69,88 @@ claude mcp add gdocs -- npx gdocs-mcp
|
|
|
69
69
|
|------|-------------|
|
|
70
70
|
| `get_charts` | List all charts in a spreadsheet with IDs and specs |
|
|
71
71
|
|
|
72
|
+
### Style Presets
|
|
73
|
+
|
|
74
|
+
Define how your documents look once, apply everywhere.
|
|
75
|
+
|
|
76
|
+
| Tool | Description |
|
|
77
|
+
|------|-------------|
|
|
78
|
+
| `extract_document_styles` | Extract styles from a reference Google Doc and save as a reusable preset |
|
|
79
|
+
| `apply_style_preset` | Apply a style preset to any document — fonts, colors, spacing, tables |
|
|
80
|
+
| `list_style_presets` | List all available presets (4 built-in + your custom presets) |
|
|
81
|
+
| `set_active_preset` | Set the default preset for new documents |
|
|
82
|
+
| `delete_style_preset` | Delete a custom preset |
|
|
83
|
+
|
|
84
|
+
#### Built-in Presets
|
|
85
|
+
|
|
86
|
+
| Preset | Font | Headings | Body |
|
|
87
|
+
|--------|------|----------|------|
|
|
88
|
+
| `clean` | Inter | Dark charcoal, 22/16/13pt | 11pt, 1.5x spacing |
|
|
89
|
+
| `corporate` | Arial | Dark grey, conservative | 11pt, 1.4x spacing |
|
|
90
|
+
| `classic` | Georgia + Garamond | Dark blue, serif | 11pt, 1.4x spacing |
|
|
91
|
+
| `minimal` | Roboto | Black, light weight | 10.5pt, 1.5x spacing |
|
|
92
|
+
|
|
93
|
+
#### Extract + Apply Workflow
|
|
94
|
+
|
|
95
|
+
The fastest way to use presets: point to a Google Doc that already looks the way you want.
|
|
96
|
+
|
|
97
|
+
```
|
|
98
|
+
You: "Extract styles from my brand doc and save as 'brand'"
|
|
99
|
+
→ extract_document_styles(documentId, saveAs: "brand")
|
|
100
|
+
|
|
101
|
+
You: "Apply brand styles to this report"
|
|
102
|
+
→ apply_style_preset(documentId, presetName: "brand")
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
One-step capture, one-step apply. No JSON editing needed.
|
|
106
|
+
|
|
107
|
+
#### Style Properties
|
|
108
|
+
|
|
109
|
+
Presets support every text and paragraph property the Google Docs API exposes:
|
|
110
|
+
|
|
111
|
+
**Text:** font family, font size, bold, italic, underline, strikethrough, small caps, text color, background color, baseline offset
|
|
112
|
+
|
|
113
|
+
**Paragraph:** alignment (left/center/right/justified), line spacing, space above/below, first line indent, start/end indent, keep lines together, keep with next, direction (LTR/RTL), paragraph borders (top/bottom/left/right)
|
|
114
|
+
|
|
115
|
+
**Document:** page margins (top/bottom/left/right), page size (width/height)
|
|
116
|
+
|
|
117
|
+
**Tables:** header row background and text color, bold headers, border color and width, cell padding, alternating row backgrounds
|
|
118
|
+
|
|
119
|
+
Only properties you specify are applied. Omitted properties are left unchanged. Config is stored at `~/.gdocs-mcp/styles.json`.
|
|
120
|
+
|
|
121
|
+
## Limitations
|
|
122
|
+
|
|
123
|
+
These are Google Docs API limitations, not gdocs-mcp limitations:
|
|
124
|
+
|
|
125
|
+
- **Table of Contents styling** is not controllable — TOC entries mirror heading styles
|
|
126
|
+
- **Custom named styles** cannot be created — only the 9 built-in types (Title, Subtitle, Heading 1-6, Normal Text)
|
|
127
|
+
- **Conditional formatting** does not exist in Google Docs
|
|
128
|
+
- **Multi-column layout** is not exposed via the API
|
|
129
|
+
- **Bullet/numbered list glyph types** are per-paragraph, not configurable via style presets
|
|
130
|
+
- **Table header detection** assumes row 0 is the header — multi-row headers are not detected
|
|
131
|
+
|
|
72
132
|
## Security
|
|
73
133
|
|
|
74
|
-
- OAuth tokens
|
|
75
|
-
- Credentials
|
|
134
|
+
- OAuth tokens stored locally at `~/.gdocs-mcp/token.json` with `600` permissions
|
|
135
|
+
- Credentials stored at `~/.gdocs-mcp/credentials.json` with `600` permissions
|
|
136
|
+
- Style presets stored at `~/.gdocs-mcp/styles.json`
|
|
76
137
|
- No telemetry, no data collection, no third-party token storage
|
|
77
138
|
- Tokens refresh automatically; if refresh fails, run `npx gdocs-mcp auth` again
|
|
78
139
|
|
|
79
140
|
## Configuration
|
|
80
141
|
|
|
81
|
-
|
|
142
|
+
Credentials and tokens are stored in `~/.gdocs-mcp/` by default. Override credentials path with:
|
|
82
143
|
|
|
83
144
|
```bash
|
|
84
145
|
GDOCS_CREDENTIALS=/path/to/credentials.json npx gdocs-mcp
|
|
85
146
|
```
|
|
86
147
|
|
|
148
|
+
For faster startup, install globally instead of using npx:
|
|
149
|
+
|
|
150
|
+
```bash
|
|
151
|
+
npm install -g gdocs-mcp
|
|
152
|
+
```
|
|
153
|
+
|
|
87
154
|
## Requirements
|
|
88
155
|
|
|
89
156
|
- Node.js 18+
|
package/dist/index.js
CHANGED
|
@@ -17,9 +17,14 @@ import { ExtractDocumentStylesSchema, extractDocumentStyles } from './tools/extr
|
|
|
17
17
|
import { ListStylePresetsSchema, listStylePresets } from './tools/list-style-presets.js';
|
|
18
18
|
import { SetActivePresetSchema, setActivePreset } from './tools/set-active-preset.js';
|
|
19
19
|
import { DeleteStylePresetSchema, deleteStylePreset } from './tools/delete-style-preset.js';
|
|
20
|
+
import { UpdateHeaderFooterSchema, updateHeaderFooter } from './tools/update-header-footer.js';
|
|
21
|
+
import { FormatListSchema, formatList } from './tools/format-list.js';
|
|
22
|
+
import { ExecuteScriptSchema, executeScript } from './tools/execute-script.js';
|
|
23
|
+
const VERSION = '0.3.0';
|
|
24
|
+
const QUIET = process.env.GDOCS_MCP_QUIET === '1';
|
|
20
25
|
const server = new McpServer({
|
|
21
26
|
name: 'gdocs-mcp',
|
|
22
|
-
version:
|
|
27
|
+
version: VERSION,
|
|
23
28
|
});
|
|
24
29
|
function formatError(err) {
|
|
25
30
|
if (err instanceof Error) {
|
|
@@ -36,19 +41,41 @@ function formatError(err) {
|
|
|
36
41
|
if (message.includes('PERMISSION_DENIED') || message.includes('403')) {
|
|
37
42
|
return 'Permission denied. Ensure the document is shared with your Google account.';
|
|
38
43
|
}
|
|
44
|
+
if (message.includes('Apps Script API has not been used')) {
|
|
45
|
+
return 'Apps Script API is not enabled. Enable it at: https://console.cloud.google.com/apis/library/script.googleapis.com';
|
|
46
|
+
}
|
|
39
47
|
return message;
|
|
40
48
|
}
|
|
41
49
|
return String(err);
|
|
42
50
|
}
|
|
43
51
|
function registerTool(name, description, schema, handler) {
|
|
44
52
|
server.tool(name, description, schema.shape, async (args) => {
|
|
53
|
+
const startTime = performance.now();
|
|
45
54
|
try {
|
|
46
55
|
const result = await handler(args);
|
|
56
|
+
if (!QUIET) {
|
|
57
|
+
const totalMs = Math.round(performance.now() - startTime);
|
|
58
|
+
const apiMs = result?._apiMs;
|
|
59
|
+
const requestCount = result?.requestCount;
|
|
60
|
+
delete result?._apiMs;
|
|
61
|
+
let logParts = [`[gdocs-mcp] ${name}: ${totalMs}ms`];
|
|
62
|
+
if (apiMs !== undefined) {
|
|
63
|
+
logParts.push(`(api: ${apiMs}ms${requestCount ? `, ${requestCount} requests` : ''})`);
|
|
64
|
+
}
|
|
65
|
+
else if (totalMs < 10) {
|
|
66
|
+
logParts.push('(local)');
|
|
67
|
+
}
|
|
68
|
+
console.error(logParts.join(' '));
|
|
69
|
+
}
|
|
47
70
|
return {
|
|
48
71
|
content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
|
|
49
72
|
};
|
|
50
73
|
}
|
|
51
74
|
catch (err) {
|
|
75
|
+
if (!QUIET) {
|
|
76
|
+
const totalMs = Math.round(performance.now() - startTime);
|
|
77
|
+
console.error(`[gdocs-mcp] ${name}: ${totalMs}ms (error)`);
|
|
78
|
+
}
|
|
52
79
|
return {
|
|
53
80
|
content: [{ type: 'text', text: formatError(err) }],
|
|
54
81
|
isError: true,
|
|
@@ -70,15 +97,19 @@ registerTool('unmerge_table_cells', 'Unmerge previously merged cells in a docume
|
|
|
70
97
|
// Google Sheets tools
|
|
71
98
|
registerTool('get_charts', 'List all charts in a Google Sheets spreadsheet with IDs and specs', GetChartsSchema, getCharts);
|
|
72
99
|
// Style preset tools
|
|
73
|
-
registerTool('apply_style_preset', 'Apply a style preset to a document.
|
|
74
|
-
registerTool('extract_document_styles', 'Extract styles from a Google Doc and optionally save as a reusable preset.
|
|
75
|
-
registerTool('list_style_presets', 'List all available style presets (built-in
|
|
76
|
-
registerTool('set_active_preset', 'Set the active style preset.
|
|
100
|
+
registerTool('apply_style_preset', 'Apply a style preset to a document. Styles all paragraphs by named type, updates margins, and formats tables.', ApplyStylePresetSchema, applyStylePreset);
|
|
101
|
+
registerTool('extract_document_styles', 'Extract styles from a Google Doc and optionally save as a reusable preset.', ExtractDocumentStylesSchema, extractDocumentStyles);
|
|
102
|
+
registerTool('list_style_presets', 'List all available style presets (built-in + user-defined) with typography summaries.', ListStylePresetsSchema, listStylePresets);
|
|
103
|
+
registerTool('set_active_preset', 'Set the active style preset. Auto-applies when creating new documents.', SetActivePresetSchema, setActivePreset);
|
|
77
104
|
registerTool('delete_style_preset', 'Delete a user-defined style preset. Cannot delete built-in presets.', DeleteStylePresetSchema, deleteStylePreset);
|
|
105
|
+
// v0.3 tools
|
|
106
|
+
registerTool('update_header_footer', 'Create or update header/footer content and styling. Supports page number insertion.', UpdateHeaderFooterSchema, updateHeaderFooter);
|
|
107
|
+
registerTool('format_list', 'Apply bullet, numbered, or remove list formatting on a paragraph range. Supports 6 glyph presets.', FormatListSchema, formatList);
|
|
108
|
+
registerTool('execute_script', 'Execute a function in a deployed Google Apps Script project. Returns JSON result.', ExecuteScriptSchema, executeScript);
|
|
78
109
|
async function main() {
|
|
79
110
|
const transport = new StdioServerTransport();
|
|
80
111
|
await server.connect(transport);
|
|
81
|
-
console.error(
|
|
112
|
+
console.error(`gdocs-mcp v${VERSION} started`);
|
|
82
113
|
}
|
|
83
114
|
main().catch((err) => {
|
|
84
115
|
console.error('Failed to start gdocs-mcp:', err);
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
export declare const ExecuteScriptSchema: z.ZodObject<{
|
|
3
|
+
scriptId: z.ZodString;
|
|
4
|
+
functionName: z.ZodString;
|
|
5
|
+
parameters: z.ZodOptional<z.ZodArray<z.ZodAny>>;
|
|
6
|
+
}, z.core.$strip>;
|
|
7
|
+
export declare function executeScript(args: z.infer<typeof ExecuteScriptSchema>): Promise<{
|
|
8
|
+
scriptId: string;
|
|
9
|
+
functionName: string;
|
|
10
|
+
result: any;
|
|
11
|
+
_apiMs: number;
|
|
12
|
+
}>;
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { google } from 'googleapis';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
import { getAuthClient } from '../auth/google-auth.js';
|
|
4
|
+
export const ExecuteScriptSchema = z.object({
|
|
5
|
+
scriptId: z.string().describe('The Apps Script project ID. Find it at script.google.com > Project Settings.'),
|
|
6
|
+
functionName: z.string().describe('Name of the function to execute'),
|
|
7
|
+
parameters: z.array(z.any()).optional().describe('Array of parameters to pass to the function. Only primitive types (string, number, boolean, array, plain object).'),
|
|
8
|
+
});
|
|
9
|
+
export async function executeScript(args) {
|
|
10
|
+
const auth = getAuthClient();
|
|
11
|
+
const script = google.script({ version: 'v1', auth });
|
|
12
|
+
const apiStart = performance.now();
|
|
13
|
+
const res = await script.scripts.run({
|
|
14
|
+
scriptId: args.scriptId,
|
|
15
|
+
requestBody: {
|
|
16
|
+
function: args.functionName,
|
|
17
|
+
parameters: args.parameters || [],
|
|
18
|
+
devMode: false,
|
|
19
|
+
},
|
|
20
|
+
});
|
|
21
|
+
const apiMs = Math.round(performance.now() - apiStart);
|
|
22
|
+
// Check for script execution errors
|
|
23
|
+
if (res.data.error) {
|
|
24
|
+
const details = res.data.error.details;
|
|
25
|
+
const scriptError = details?.find((d) => d.errorType);
|
|
26
|
+
const errorMessage = scriptError
|
|
27
|
+
? `${scriptError.errorType}: ${scriptError.errorMessage}`
|
|
28
|
+
: res.data.error.message || 'Unknown script error';
|
|
29
|
+
throw new Error(errorMessage);
|
|
30
|
+
}
|
|
31
|
+
return {
|
|
32
|
+
scriptId: args.scriptId,
|
|
33
|
+
functionName: args.functionName,
|
|
34
|
+
result: res.data.response?.result ?? null,
|
|
35
|
+
_apiMs: apiMs,
|
|
36
|
+
};
|
|
37
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
export declare const FormatListSchema: z.ZodObject<{
|
|
3
|
+
documentId: z.ZodString;
|
|
4
|
+
startIndex: z.ZodNumber;
|
|
5
|
+
endIndex: z.ZodNumber;
|
|
6
|
+
listType: z.ZodEnum<{
|
|
7
|
+
none: "none";
|
|
8
|
+
bullet: "bullet";
|
|
9
|
+
numbered: "numbered";
|
|
10
|
+
}>;
|
|
11
|
+
preset: z.ZodOptional<z.ZodString>;
|
|
12
|
+
}, z.core.$strip>;
|
|
13
|
+
export declare function formatList(args: z.infer<typeof FormatListSchema>): Promise<{
|
|
14
|
+
documentId: string;
|
|
15
|
+
listType: "none" | "bullet" | "numbered";
|
|
16
|
+
preset: string | null;
|
|
17
|
+
startIndex: number;
|
|
18
|
+
endIndex: number;
|
|
19
|
+
_apiMs: number;
|
|
20
|
+
}>;
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { google } from 'googleapis';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
import { getAuthClient } from '../auth/google-auth.js';
|
|
4
|
+
const BULLET_PRESETS = [
|
|
5
|
+
'BULLET_DISC_CIRCLE_SQUARE',
|
|
6
|
+
'BULLET_DIAMONDX_ARROW3D_SQUARE',
|
|
7
|
+
'BULLET_CHECKBOX',
|
|
8
|
+
];
|
|
9
|
+
const NUMBERED_PRESETS = [
|
|
10
|
+
'NUMBERED_DECIMAL_ALPHA_ROMAN',
|
|
11
|
+
'NUMBERED_DECIMAL_NESTED',
|
|
12
|
+
'NUMBERED_UPPERALPHA_ALPHA_ROMAN',
|
|
13
|
+
];
|
|
14
|
+
const ALL_PRESETS = [...BULLET_PRESETS, ...NUMBERED_PRESETS];
|
|
15
|
+
export const FormatListSchema = z.object({
|
|
16
|
+
documentId: z.string().describe('The Google Doc document ID'),
|
|
17
|
+
startIndex: z.number().describe('Start index of the paragraph range'),
|
|
18
|
+
endIndex: z.number().describe('End index of the paragraph range'),
|
|
19
|
+
listType: z.enum(['bullet', 'numbered', 'none']).describe('"bullet" for unordered, "numbered" for ordered, "none" to remove list formatting'),
|
|
20
|
+
preset: z.string().optional().describe('Bullet/number preset. Bullets: BULLET_DISC_CIRCLE_SQUARE (default), BULLET_DIAMONDX_ARROW3D_SQUARE, BULLET_CHECKBOX. ' +
|
|
21
|
+
'Numbers: NUMBERED_DECIMAL_ALPHA_ROMAN (default), NUMBERED_DECIMAL_NESTED, NUMBERED_UPPERALPHA_ALPHA_ROMAN.'),
|
|
22
|
+
});
|
|
23
|
+
export async function formatList(args) {
|
|
24
|
+
const auth = getAuthClient();
|
|
25
|
+
const docs = google.docs({ version: 'v1', auth });
|
|
26
|
+
const apiStart = performance.now();
|
|
27
|
+
const requests = [];
|
|
28
|
+
if (args.listType === 'none') {
|
|
29
|
+
requests.push({
|
|
30
|
+
deleteParagraphBullets: {
|
|
31
|
+
range: { startIndex: args.startIndex, endIndex: args.endIndex },
|
|
32
|
+
},
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
else {
|
|
36
|
+
const defaultPreset = args.listType === 'bullet'
|
|
37
|
+
? 'BULLET_DISC_CIRCLE_SQUARE'
|
|
38
|
+
: 'NUMBERED_DECIMAL_ALPHA_ROMAN';
|
|
39
|
+
const preset = args.preset || defaultPreset;
|
|
40
|
+
// Validate preset matches list type
|
|
41
|
+
if (args.listType === 'bullet' && !BULLET_PRESETS.includes(preset)) {
|
|
42
|
+
if (NUMBERED_PRESETS.includes(preset)) {
|
|
43
|
+
throw new Error(`Preset "${preset}" is a numbered preset. Use listType: "numbered" or pick a bullet preset: ${BULLET_PRESETS.join(', ')}`);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
if (args.listType === 'numbered' && !NUMBERED_PRESETS.includes(preset)) {
|
|
47
|
+
if (BULLET_PRESETS.includes(preset)) {
|
|
48
|
+
throw new Error(`Preset "${preset}" is a bullet preset. Use listType: "bullet" or pick a numbered preset: ${NUMBERED_PRESETS.join(', ')}`);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
if (!ALL_PRESETS.includes(preset)) {
|
|
52
|
+
throw new Error(`Unknown preset "${preset}". Available: ${ALL_PRESETS.join(', ')}`);
|
|
53
|
+
}
|
|
54
|
+
requests.push({
|
|
55
|
+
createParagraphBullets: {
|
|
56
|
+
range: { startIndex: args.startIndex, endIndex: args.endIndex },
|
|
57
|
+
bulletPreset: preset,
|
|
58
|
+
},
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
await docs.documents.batchUpdate({
|
|
62
|
+
documentId: args.documentId,
|
|
63
|
+
requestBody: { requests },
|
|
64
|
+
});
|
|
65
|
+
const apiMs = Math.round(performance.now() - apiStart);
|
|
66
|
+
return {
|
|
67
|
+
documentId: args.documentId,
|
|
68
|
+
listType: args.listType,
|
|
69
|
+
preset: args.listType === 'none' ? null : (args.preset || (args.listType === 'bullet' ? 'BULLET_DISC_CIRCLE_SQUARE' : 'NUMBERED_DECIMAL_ALPHA_ROMAN')),
|
|
70
|
+
startIndex: args.startIndex,
|
|
71
|
+
endIndex: args.endIndex,
|
|
72
|
+
_apiMs: apiMs,
|
|
73
|
+
};
|
|
74
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
export declare const UpdateHeaderFooterSchema: z.ZodObject<{
|
|
3
|
+
documentId: z.ZodString;
|
|
4
|
+
section: z.ZodEnum<{
|
|
5
|
+
header: "header";
|
|
6
|
+
footer: "footer";
|
|
7
|
+
}>;
|
|
8
|
+
content: z.ZodOptional<z.ZodString>;
|
|
9
|
+
}, z.core.$strip>;
|
|
10
|
+
export declare function updateHeaderFooter(args: z.infer<typeof UpdateHeaderFooterSchema>): Promise<{
|
|
11
|
+
documentId: string;
|
|
12
|
+
section: "header" | "footer";
|
|
13
|
+
created: boolean;
|
|
14
|
+
contentInserted: boolean;
|
|
15
|
+
_apiMs: number;
|
|
16
|
+
}>;
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { google } from 'googleapis';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
import { getAuthClient } from '../auth/google-auth.js';
|
|
4
|
+
export const UpdateHeaderFooterSchema = z.object({
|
|
5
|
+
documentId: z.string().describe('The Google Doc document ID'),
|
|
6
|
+
section: z.enum(['header', 'footer']).describe('Which section to update: "header" or "footer"'),
|
|
7
|
+
content: z.string().optional().describe('Text content to insert. Replaces existing content. Use {{pageNumber}} to insert a page number field.'),
|
|
8
|
+
});
|
|
9
|
+
export async function updateHeaderFooter(args) {
|
|
10
|
+
const auth = getAuthClient();
|
|
11
|
+
const docs = google.docs({ version: 'v1', auth });
|
|
12
|
+
const apiStart = performance.now();
|
|
13
|
+
// Read document to check if header/footer exists
|
|
14
|
+
const doc = await docs.documents.get({ documentId: args.documentId });
|
|
15
|
+
const isHeader = args.section === 'header';
|
|
16
|
+
const existingId = isHeader
|
|
17
|
+
? doc.data.headers && Object.keys(doc.data.headers)[0]
|
|
18
|
+
: doc.data.footers && Object.keys(doc.data.footers)[0];
|
|
19
|
+
const requests = [];
|
|
20
|
+
// Create header/footer if it doesn't exist
|
|
21
|
+
if (!existingId) {
|
|
22
|
+
requests.push(isHeader
|
|
23
|
+
? { createHeader: { type: 'DEFAULT', sectionBreakLocation: { index: 0 } } }
|
|
24
|
+
: { createFooter: { type: 'DEFAULT', sectionBreakLocation: { index: 0 } } });
|
|
25
|
+
// Need to execute first to get the ID, then insert content
|
|
26
|
+
if (args.content) {
|
|
27
|
+
await docs.documents.batchUpdate({
|
|
28
|
+
documentId: args.documentId,
|
|
29
|
+
requestBody: { requests },
|
|
30
|
+
});
|
|
31
|
+
// Re-read to get the new ID
|
|
32
|
+
const updated = await docs.documents.get({ documentId: args.documentId });
|
|
33
|
+
const newId = isHeader
|
|
34
|
+
? Object.keys(updated.data.headers || {})[0]
|
|
35
|
+
: Object.keys(updated.data.footers || {})[0];
|
|
36
|
+
if (newId && args.content) {
|
|
37
|
+
await insertContent(docs, args.documentId, newId, args.content, isHeader, updated.data);
|
|
38
|
+
}
|
|
39
|
+
const apiMs = Math.round(performance.now() - apiStart);
|
|
40
|
+
return {
|
|
41
|
+
documentId: args.documentId,
|
|
42
|
+
section: args.section,
|
|
43
|
+
created: true,
|
|
44
|
+
contentInserted: !!args.content,
|
|
45
|
+
_apiMs: apiMs,
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
await docs.documents.batchUpdate({
|
|
49
|
+
documentId: args.documentId,
|
|
50
|
+
requestBody: { requests },
|
|
51
|
+
});
|
|
52
|
+
const apiMs = Math.round(performance.now() - apiStart);
|
|
53
|
+
return {
|
|
54
|
+
documentId: args.documentId,
|
|
55
|
+
section: args.section,
|
|
56
|
+
created: true,
|
|
57
|
+
contentInserted: false,
|
|
58
|
+
_apiMs: apiMs,
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
// Header/footer exists — update content if provided
|
|
62
|
+
if (args.content) {
|
|
63
|
+
await insertContent(docs, args.documentId, existingId, args.content, isHeader, doc.data);
|
|
64
|
+
}
|
|
65
|
+
const apiMs = Math.round(performance.now() - apiStart);
|
|
66
|
+
return {
|
|
67
|
+
documentId: args.documentId,
|
|
68
|
+
section: args.section,
|
|
69
|
+
created: false,
|
|
70
|
+
contentInserted: !!args.content,
|
|
71
|
+
_apiMs: apiMs,
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
async function insertContent(docs, documentId, sectionId, content, isHeader, docData) {
|
|
75
|
+
const sectionData = isHeader
|
|
76
|
+
? docData.headers?.[sectionId]
|
|
77
|
+
: docData.footers?.[sectionId];
|
|
78
|
+
if (!sectionData?.content)
|
|
79
|
+
return;
|
|
80
|
+
const sectionContent = sectionData.content;
|
|
81
|
+
const startIndex = sectionContent[0]?.startIndex || 0;
|
|
82
|
+
const endIndex = sectionContent[sectionContent.length - 1]?.endIndex || startIndex + 1;
|
|
83
|
+
const requests = [];
|
|
84
|
+
// Delete existing content
|
|
85
|
+
if (endIndex > startIndex + 1) {
|
|
86
|
+
requests.push({
|
|
87
|
+
deleteContentRange: {
|
|
88
|
+
range: { segmentId: sectionId, startIndex: startIndex, endIndex: endIndex - 1 },
|
|
89
|
+
},
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
// Insert new content
|
|
93
|
+
requests.push({
|
|
94
|
+
insertText: {
|
|
95
|
+
location: { segmentId: sectionId, index: startIndex },
|
|
96
|
+
text: content.replace('{{pageNumber}}', ''),
|
|
97
|
+
},
|
|
98
|
+
});
|
|
99
|
+
await docs.documents.batchUpdate({
|
|
100
|
+
documentId,
|
|
101
|
+
requestBody: { requests },
|
|
102
|
+
});
|
|
103
|
+
}
|
package/package.json
CHANGED