@superdurable/connector-google-docs 0.0.0-stage → 0.1.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.
- package/LICENSE +21 -0
- package/README.md +19 -2
- package/dex-connector.json +327 -0
- package/dist/chunk-2AMHZOKT.js +381 -0
- package/dist/connection-CAHPwRm8.d.ts +307 -0
- package/dist/index.d.ts +316 -0
- package/dist/index.js +1432 -0
- package/dist/mock.d.ts +142 -0
- package/dist/mock.js +338 -0
- package/package.json +58 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,1432 @@
|
|
|
1
|
+
import {
|
|
2
|
+
AppendTextBranch,
|
|
3
|
+
AppendTextBranchAppended,
|
|
4
|
+
AppendTextBranchDefect,
|
|
5
|
+
AppendTextBranchInvalidResponse,
|
|
6
|
+
AppendTextBranchNotFound,
|
|
7
|
+
AppendTextBranchProviderRejected,
|
|
8
|
+
AppendTextBranchRevisionChanged,
|
|
9
|
+
AppendTextDefinition,
|
|
10
|
+
AppendTextInputSchema,
|
|
11
|
+
AppendTextMetadata,
|
|
12
|
+
AppendTextOutputSchema,
|
|
13
|
+
ConfigSchema,
|
|
14
|
+
Connection,
|
|
15
|
+
ConnectorID,
|
|
16
|
+
CreateDocumentBranch,
|
|
17
|
+
CreateDocumentBranchCreated,
|
|
18
|
+
CreateDocumentBranchDefect,
|
|
19
|
+
CreateDocumentBranchInvalidResponse,
|
|
20
|
+
CreateDocumentBranchProviderRejected,
|
|
21
|
+
CreateDocumentBranchUncertain,
|
|
22
|
+
CreateDocumentDefinition,
|
|
23
|
+
CreateDocumentInputSchema,
|
|
24
|
+
CreateDocumentMetadata,
|
|
25
|
+
CreateDocumentOutputSchema,
|
|
26
|
+
CreatedDocumentSchema,
|
|
27
|
+
CredentialMaterialError,
|
|
28
|
+
GetDocumentTextBranch,
|
|
29
|
+
GetDocumentTextBranchDefect,
|
|
30
|
+
GetDocumentTextBranchInvalidResponse,
|
|
31
|
+
GetDocumentTextBranchNotFound,
|
|
32
|
+
GetDocumentTextBranchProviderRejected,
|
|
33
|
+
GetDocumentTextBranchRead,
|
|
34
|
+
GetDocumentTextBranchTooLarge,
|
|
35
|
+
GetDocumentTextDefinition,
|
|
36
|
+
GetDocumentTextInputSchema,
|
|
37
|
+
GetDocumentTextMetadata,
|
|
38
|
+
GetDocumentTextOutputSchema,
|
|
39
|
+
PlaceholderReplacementResultSchema,
|
|
40
|
+
PlaceholderReplacementSchema,
|
|
41
|
+
ProviderID,
|
|
42
|
+
ReplaceDocumentTextBranch,
|
|
43
|
+
ReplaceDocumentTextBranchDefect,
|
|
44
|
+
ReplaceDocumentTextBranchInvalidResponse,
|
|
45
|
+
ReplaceDocumentTextBranchNotFound,
|
|
46
|
+
ReplaceDocumentTextBranchPlaceholderNotFound,
|
|
47
|
+
ReplaceDocumentTextBranchProviderRejected,
|
|
48
|
+
ReplaceDocumentTextBranchReplaced,
|
|
49
|
+
ReplaceDocumentTextBranchRevisionChanged,
|
|
50
|
+
ReplaceDocumentTextDefinition,
|
|
51
|
+
ReplaceDocumentTextInputSchema,
|
|
52
|
+
ReplaceDocumentTextMetadata,
|
|
53
|
+
ReplaceDocumentTextOutputSchema,
|
|
54
|
+
decodeCredentials,
|
|
55
|
+
decodeSharedCredentials,
|
|
56
|
+
isCredentialMaterialError,
|
|
57
|
+
newConnection,
|
|
58
|
+
newConnectionWithOperations,
|
|
59
|
+
newProjectCredentialProvider
|
|
60
|
+
} from "./chunk-2AMHZOKT.js";
|
|
61
|
+
|
|
62
|
+
// src/generated/steps.ts
|
|
63
|
+
import { goToBranch, newMutationStep, newQueryStep } from "@superdurable/connectors-sdk";
|
|
64
|
+
function newGetDocumentTextStep(configuration) {
|
|
65
|
+
const { connection, connectionName, read, notFound, tooLarge, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
|
|
66
|
+
if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
|
|
67
|
+
return newQueryStep({ ...stepConfiguration, operation: connection.operations.getDocumentText(), connection: connection.reference, branches: [
|
|
68
|
+
goToBranch("read", read),
|
|
69
|
+
...notFound ? [goToBranch("notFound", notFound)] : [],
|
|
70
|
+
...tooLarge ? [goToBranch("tooLarge", tooLarge)] : [],
|
|
71
|
+
...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
|
|
72
|
+
...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
|
|
73
|
+
...defect ? [goToBranch("defect", defect)] : []
|
|
74
|
+
] });
|
|
75
|
+
}
|
|
76
|
+
function newCreateDocumentStep(configuration) {
|
|
77
|
+
const { connection, connectionName, created, providerRejected, invalidResponse, uncertain, defect, ...stepConfiguration } = configuration;
|
|
78
|
+
if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
|
|
79
|
+
return newMutationStep({ ...stepConfiguration, operation: connection.operations.createDocument(), connection: connection.reference, branches: [
|
|
80
|
+
goToBranch("created", created),
|
|
81
|
+
...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
|
|
82
|
+
...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
|
|
83
|
+
...uncertain ? [goToBranch("uncertain", uncertain)] : [],
|
|
84
|
+
...defect ? [goToBranch("defect", defect)] : []
|
|
85
|
+
] });
|
|
86
|
+
}
|
|
87
|
+
function newReplaceDocumentTextStep(configuration) {
|
|
88
|
+
const { connection, connectionName, replaced, placeholderNotFound, revisionChanged, notFound, providerRejected, invalidResponse, defect, maxSends, ...stepConfiguration } = configuration;
|
|
89
|
+
if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
|
|
90
|
+
return newMutationStep({ ...stepConfiguration, operation: connection.operations.replaceDocumentText(), connection: connection.reference, branches: [
|
|
91
|
+
goToBranch("replaced", replaced),
|
|
92
|
+
...placeholderNotFound ? [goToBranch("placeholderNotFound", placeholderNotFound)] : [],
|
|
93
|
+
...revisionChanged ? [goToBranch("revisionChanged", revisionChanged)] : [],
|
|
94
|
+
...notFound ? [goToBranch("notFound", notFound)] : [],
|
|
95
|
+
...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
|
|
96
|
+
...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
|
|
97
|
+
...defect ? [goToBranch("defect", defect)] : []
|
|
98
|
+
] });
|
|
99
|
+
}
|
|
100
|
+
function newAppendTextStep(configuration) {
|
|
101
|
+
const { connection, connectionName, appended, revisionChanged, notFound, providerRejected, invalidResponse, defect, maxSends, ...stepConfiguration } = configuration;
|
|
102
|
+
if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
|
|
103
|
+
return newMutationStep({ ...stepConfiguration, operation: connection.operations.appendText(), connection: connection.reference, branches: [
|
|
104
|
+
goToBranch("appended", appended),
|
|
105
|
+
...revisionChanged ? [goToBranch("revisionChanged", revisionChanged)] : [],
|
|
106
|
+
...notFound ? [goToBranch("notFound", notFound)] : [],
|
|
107
|
+
...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
|
|
108
|
+
...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
|
|
109
|
+
...defect ? [goToBranch("defect", defect)] : []
|
|
110
|
+
] });
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// src/project.ts
|
|
114
|
+
import { ConnectionRefSchema } from "@superdurable/connectors-sdk";
|
|
115
|
+
|
|
116
|
+
// src/client.ts
|
|
117
|
+
import { ReauthorizationRequiredError as ReauthorizationRequiredError2, resolveCredential, resolveCredentialAfterRejection } from "@superdurable/connectors-sdk";
|
|
118
|
+
import { BodyTooLargeError, ProviderStalledError, ProviderTransportError, isHeaderSafeCredential, parseRetryAfter, readErrorTokens, sendProviderRequest, validateBaseURL } from "@superdurable/connectors-sdk/providerhttp";
|
|
119
|
+
import { ManifestCredentialRefreshDriver } from "@superdurable/connectors-sdk/oauthtoken";
|
|
120
|
+
import { ConnectionNotSelectedError, CredentialBrokerRejectedError, ObjectNotFoundError } from "@superdurable/connectors-sdk/projectconfig";
|
|
121
|
+
|
|
122
|
+
// src/generated/refresh.ts
|
|
123
|
+
var Authorization = {
|
|
124
|
+
"defaultMethod": "google-oauth",
|
|
125
|
+
"methods": [
|
|
126
|
+
{
|
|
127
|
+
"fields": [
|
|
128
|
+
{
|
|
129
|
+
"name": "oauth_client_id",
|
|
130
|
+
"required": true,
|
|
131
|
+
"type": "string"
|
|
132
|
+
},
|
|
133
|
+
{
|
|
134
|
+
"name": "oauth_client_secret",
|
|
135
|
+
"required": true,
|
|
136
|
+
"type": "secretString"
|
|
137
|
+
},
|
|
138
|
+
{
|
|
139
|
+
"name": "access_token",
|
|
140
|
+
"required": true,
|
|
141
|
+
"type": "secretString"
|
|
142
|
+
},
|
|
143
|
+
{
|
|
144
|
+
"name": "refresh_token",
|
|
145
|
+
"required": true,
|
|
146
|
+
"type": "secretString"
|
|
147
|
+
}
|
|
148
|
+
],
|
|
149
|
+
"id": "google-oauth",
|
|
150
|
+
"oauth2": {
|
|
151
|
+
"clientIDCredential": "oauth_client_id",
|
|
152
|
+
"clientSecretCredential": "oauth_client_secret",
|
|
153
|
+
"credentialMappings": [
|
|
154
|
+
{
|
|
155
|
+
"credential": "access_token",
|
|
156
|
+
"source": "access_token"
|
|
157
|
+
},
|
|
158
|
+
{
|
|
159
|
+
"credential": "refresh_token",
|
|
160
|
+
"source": "refresh_token"
|
|
161
|
+
}
|
|
162
|
+
],
|
|
163
|
+
"refresh": {
|
|
164
|
+
"missingExpiry": "reject",
|
|
165
|
+
"scopeSeparators": "whitespaceAndComma",
|
|
166
|
+
"storedMissingExpiry": "refresh",
|
|
167
|
+
"terminalErrorCodes": [
|
|
168
|
+
"invalid_grant",
|
|
169
|
+
"invalid_client",
|
|
170
|
+
"unauthorized_client"
|
|
171
|
+
],
|
|
172
|
+
"tokenExchangeTimeout": "25s"
|
|
173
|
+
},
|
|
174
|
+
"scopes": [
|
|
175
|
+
"https://www.googleapis.com/auth/documents",
|
|
176
|
+
"https://www.googleapis.com/auth/drive.file",
|
|
177
|
+
"https://www.googleapis.com/auth/drive.metadata.readonly"
|
|
178
|
+
],
|
|
179
|
+
"tokenEndpoint": "https://oauth2.googleapis.com/token"
|
|
180
|
+
},
|
|
181
|
+
"type": "oauth2"
|
|
182
|
+
},
|
|
183
|
+
{
|
|
184
|
+
"fields": [
|
|
185
|
+
{
|
|
186
|
+
"name": "service_account_key",
|
|
187
|
+
"required": true,
|
|
188
|
+
"type": "secretString"
|
|
189
|
+
},
|
|
190
|
+
{
|
|
191
|
+
"name": "delegated_user",
|
|
192
|
+
"required": true,
|
|
193
|
+
"type": "string"
|
|
194
|
+
},
|
|
195
|
+
{
|
|
196
|
+
"name": "access_token",
|
|
197
|
+
"required": false,
|
|
198
|
+
"type": "secretString"
|
|
199
|
+
}
|
|
200
|
+
],
|
|
201
|
+
"id": "workspace-domain-delegation",
|
|
202
|
+
"serviceAccount": {
|
|
203
|
+
"jwtBearer": {
|
|
204
|
+
"audience": {
|
|
205
|
+
"fromKey": "token_uri"
|
|
206
|
+
},
|
|
207
|
+
"credentialMappings": [
|
|
208
|
+
{
|
|
209
|
+
"credential": "access_token",
|
|
210
|
+
"source": "access_token"
|
|
211
|
+
}
|
|
212
|
+
],
|
|
213
|
+
"issuer": {
|
|
214
|
+
"fromKey": "client_email"
|
|
215
|
+
},
|
|
216
|
+
"keyCredential": "service_account_key",
|
|
217
|
+
"lifetime": "1h",
|
|
218
|
+
"missingExpiry": "reject",
|
|
219
|
+
"privateKey": {
|
|
220
|
+
"fromKey": "private_key"
|
|
221
|
+
},
|
|
222
|
+
"scopeSeparators": "whitespaceAndComma",
|
|
223
|
+
"scopes": [
|
|
224
|
+
"https://www.googleapis.com/auth/documents",
|
|
225
|
+
"https://www.googleapis.com/auth/drive.file",
|
|
226
|
+
"https://www.googleapis.com/auth/drive.metadata.readonly"
|
|
227
|
+
],
|
|
228
|
+
"storedMissingExpiry": "refresh",
|
|
229
|
+
"subject": {
|
|
230
|
+
"fromCredential": "delegated_user"
|
|
231
|
+
},
|
|
232
|
+
"subjectValidation": "goMailAddress",
|
|
233
|
+
"terminalErrorCodes": [
|
|
234
|
+
"invalid_grant",
|
|
235
|
+
"invalid_client",
|
|
236
|
+
"unauthorized_client"
|
|
237
|
+
],
|
|
238
|
+
"tokenEndpoint": {
|
|
239
|
+
"fromKey": "token_uri"
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
},
|
|
243
|
+
"type": "serviceAccount"
|
|
244
|
+
}
|
|
245
|
+
],
|
|
246
|
+
"refreshable": true
|
|
247
|
+
};
|
|
248
|
+
var CredentialFields = {
|
|
249
|
+
"access_token": "accessToken",
|
|
250
|
+
"delegated_user": "delegatedUser",
|
|
251
|
+
"oauth_client_id": "oauthClientId",
|
|
252
|
+
"oauth_client_secret": "oauthClientSecret",
|
|
253
|
+
"refresh_token": "refreshToken",
|
|
254
|
+
"service_account_key": "serviceAccountKey"
|
|
255
|
+
};
|
|
256
|
+
|
|
257
|
+
// src/operations.ts
|
|
258
|
+
import { ReauthorizationRequiredError, definitionMaxSends, newMutationBranch, newMutationRetry, newMutationUncertain, newQueryBranch, newQueryRetry } from "@superdurable/connectors-sdk";
|
|
259
|
+
import { newFence } from "@superdurable/connectors-sdk/singledispatch";
|
|
260
|
+
import { randomBytes } from "crypto";
|
|
261
|
+
|
|
262
|
+
// src/document.ts
|
|
263
|
+
function decodeDocument(body) {
|
|
264
|
+
const raw = parseObject(body);
|
|
265
|
+
validateDocumentResource(raw);
|
|
266
|
+
const documentId = stringField(raw, "documentId");
|
|
267
|
+
if (!isDriveID(documentId)) throw new TypeError("invalid document ID");
|
|
268
|
+
const tabs = arrayField(raw, "tabs");
|
|
269
|
+
const first = objectValue(tabs[0]);
|
|
270
|
+
const tabId = stringField(objectField(first, "tabProperties"), "tabId");
|
|
271
|
+
if (!/^[A-Za-z0-9_.-]{1,256}$/.test(tabId)) throw new TypeError("invalid tab ID");
|
|
272
|
+
const documentTab = objectField(first, "documentTab");
|
|
273
|
+
const content = arrayField(objectField(documentTab, "body"), "content").map(objectValue);
|
|
274
|
+
const last = content.at(-1);
|
|
275
|
+
if (!last || !isObject(last.paragraph) || !Number.isInteger(last.endIndex) || Number(last.endIndex) < 2) throw new TypeError("invalid last paragraph");
|
|
276
|
+
const firstContent = content[0];
|
|
277
|
+
const bodyStartIndex = Object.hasOwn(firstContent, "sectionBreak") ? integerField(firstContent, "endIndex", 0) : integerField(firstContent, "startIndex", 0);
|
|
278
|
+
const lists = documentTab.lists == null ? {} : objectValue(documentTab.lists);
|
|
279
|
+
return {
|
|
280
|
+
documentId,
|
|
281
|
+
title: stringField(raw, "title", ""),
|
|
282
|
+
revisionId: stringField(raw, "revisionId", ""),
|
|
283
|
+
hasOtherTabs: tabs.length > 1 || Array.isArray(first.childTabs) && first.childTabs.length > 0,
|
|
284
|
+
tabId,
|
|
285
|
+
content,
|
|
286
|
+
lists,
|
|
287
|
+
bodyEndIndex: Number(last.endIndex),
|
|
288
|
+
bodyStartIndex
|
|
289
|
+
};
|
|
290
|
+
}
|
|
291
|
+
function documentBodyText(document) {
|
|
292
|
+
return structuralText(document.content, 0);
|
|
293
|
+
}
|
|
294
|
+
function structuralText(content, depth) {
|
|
295
|
+
if (depth > 16) throw new TypeError("document tables are nested too deeply");
|
|
296
|
+
let text = "";
|
|
297
|
+
for (const element of content) {
|
|
298
|
+
if (isObject(element.paragraph)) {
|
|
299
|
+
for (const part of arrayField(element.paragraph, "elements", [])) {
|
|
300
|
+
const item = objectValue(part);
|
|
301
|
+
text += isObject(item.textRun) ? stringField(item.textRun, "content", "") : "\uE907";
|
|
302
|
+
}
|
|
303
|
+
} else if (isObject(element.table)) {
|
|
304
|
+
for (const row of arrayField(element.table, "tableRows", [])) {
|
|
305
|
+
for (const cell of arrayField(objectValue(row), "tableCells", [])) {
|
|
306
|
+
text += structuralText(arrayField(objectValue(cell), "content", []).map(objectValue), depth + 1);
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
return text;
|
|
312
|
+
}
|
|
313
|
+
function renderDocumentText(document, format) {
|
|
314
|
+
const counters = /* @__PURE__ */ new Map();
|
|
315
|
+
const blocks = renderContent(document.content, document.lists, format, counters, 0);
|
|
316
|
+
return blocks.map((block, index) => index === 0 ? block.text : `${format === "plainText" || blocks[index - 1].list && block.list ? "\n" : "\n\n"}${block.text}`).join("").replace(/^\n+|\n+$/g, "");
|
|
317
|
+
}
|
|
318
|
+
function renderContent(content, lists, format, counters, depth) {
|
|
319
|
+
if (depth > 16) throw new TypeError("document tables are nested too deeply");
|
|
320
|
+
const blocks = [];
|
|
321
|
+
for (const element of content) {
|
|
322
|
+
if (isObject(element.paragraph)) {
|
|
323
|
+
const paragraph = element.paragraph;
|
|
324
|
+
const { text, hasRule } = inlineText(paragraph, format);
|
|
325
|
+
if (isObject(paragraph.bullet)) {
|
|
326
|
+
const bullet = paragraph.bullet;
|
|
327
|
+
const listId = stringField(bullet, "listId", "");
|
|
328
|
+
const level = Math.min(8, Math.max(0, integerField(bullet, "nestingLevel", 0)));
|
|
329
|
+
const list = isObject(lists[listId]) ? lists[listId] : {};
|
|
330
|
+
const nesting = isObject(list) && isObject(list.listProperties) ? arrayField(list.listProperties, "nestingLevels", []) : [];
|
|
331
|
+
const glyph = level < nesting.length ? stringField(objectValue(nesting[level]), "glyphType", "") : "";
|
|
332
|
+
let marker = "- ";
|
|
333
|
+
if (["DECIMAL", "ZERO_DECIMAL", "UPPER_ALPHA", "ALPHA", "UPPER_ROMAN", "ROMAN"].includes(glyph)) {
|
|
334
|
+
const counts = counters.get(listId) ?? [];
|
|
335
|
+
while (counts.length <= level) counts.push(0);
|
|
336
|
+
counts[level] = (counts[level] ?? 0) + 1;
|
|
337
|
+
for (let index = level + 1; index < counts.length; index++) counts[index] = 0;
|
|
338
|
+
counters.set(listId, counts);
|
|
339
|
+
marker = `${counts[level]}. `;
|
|
340
|
+
}
|
|
341
|
+
blocks.push({ text: `${(format === "markdown" ? " " : " ").repeat(level)}${marker}${text.replace(/\n/g, " ")}`, list: true });
|
|
342
|
+
continue;
|
|
343
|
+
}
|
|
344
|
+
const style = isObject(paragraph.paragraphStyle) ? stringField(paragraph.paragraphStyle, "namedStyleType", "") : "";
|
|
345
|
+
const heading = { TITLE: 1, SUBTITLE: 2, HEADING_1: 1, HEADING_2: 2, HEADING_3: 3, HEADING_4: 4, HEADING_5: 5, HEADING_6: 6 }[style];
|
|
346
|
+
if (heading && goHasNonSpace(text)) blocks.push({ text: format === "markdown" ? `${"#".repeat(heading)} ${text.replace(/\n/g, " ")}` : text.replace(/\n/g, " "), list: false });
|
|
347
|
+
else if (!goHasNonSpace(text)) {
|
|
348
|
+
if (hasRule && format === "markdown") blocks.push({ text: "---", list: false });
|
|
349
|
+
else if (format === "plainText") blocks.push({ text: "", list: false });
|
|
350
|
+
} else {
|
|
351
|
+
blocks.push({ text: format === "markdown" ? escapeMarkdownLineStarts(text) : text, list: false });
|
|
352
|
+
}
|
|
353
|
+
} else if (isObject(element.table)) {
|
|
354
|
+
const rows = arrayField(element.table, "tableRows", []).map((row) => arrayField(objectValue(row), "tableCells", []).map((cell) => cellText(arrayField(objectValue(cell), "content", []).map(objectValue), format, 1)));
|
|
355
|
+
const columns = Math.max(0, ...rows.map((row) => row.length));
|
|
356
|
+
if (columns) {
|
|
357
|
+
const lines = [];
|
|
358
|
+
rows.forEach((row, index) => {
|
|
359
|
+
while (row.length < columns) row.push("");
|
|
360
|
+
if (format === "plainText") lines.push(row.join(" "));
|
|
361
|
+
else {
|
|
362
|
+
lines.push(`| ${row.join(" | ")} |`);
|
|
363
|
+
if (index === 0) lines.push(`|${" --- |".repeat(columns)}`);
|
|
364
|
+
}
|
|
365
|
+
});
|
|
366
|
+
blocks.push({ text: lines.join("\n"), list: false });
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
return blocks;
|
|
371
|
+
}
|
|
372
|
+
function cellText(content, format, depth) {
|
|
373
|
+
if (depth > 16) throw new TypeError("document tables are nested too deeply");
|
|
374
|
+
const parts = [];
|
|
375
|
+
for (const element of content) {
|
|
376
|
+
if (isObject(element.paragraph)) {
|
|
377
|
+
const { text } = inlineText(element.paragraph, format);
|
|
378
|
+
if (goHasNonSpace(text)) parts.push(text);
|
|
379
|
+
} else if (isObject(element.table)) {
|
|
380
|
+
for (const row of arrayField(element.table, "tableRows", [])) for (const cell of arrayField(objectValue(row), "tableCells", [])) {
|
|
381
|
+
const nested = cellText(arrayField(objectValue(cell), "content", []).map(objectValue), format, depth + 1);
|
|
382
|
+
if (nested) parts.push(nested);
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
const joined = parts.join(" ").replace(/[\n\t]/g, " ");
|
|
387
|
+
return format === "markdown" ? joined.replace(/\|/g, "\\|") : joined;
|
|
388
|
+
}
|
|
389
|
+
function inlineText(paragraph, format) {
|
|
390
|
+
let text = "";
|
|
391
|
+
let hasRule = false;
|
|
392
|
+
for (const part of arrayField(paragraph, "elements", [])) {
|
|
393
|
+
const value = objectValue(part);
|
|
394
|
+
if (isObject(value.textRun)) text += stringField(value.textRun, "content", "").replace(/\uE907/g, "").replace(/\v/g, "\n");
|
|
395
|
+
else if (isObject(value.person)) {
|
|
396
|
+
const properties = isObject(value.person.personProperties) ? value.person.personProperties : {};
|
|
397
|
+
text += stringField(properties, "name", "") || stringField(properties, "email", "");
|
|
398
|
+
} else if (isObject(value.richLink)) {
|
|
399
|
+
const properties = isObject(value.richLink.richLinkProperties) ? value.richLink.richLinkProperties : {};
|
|
400
|
+
const uri = stringField(properties, "uri", "");
|
|
401
|
+
const label = stringField(properties, "title", "") || uri;
|
|
402
|
+
text += format === "markdown" && uri ? `[${label.replace(/\\/g, "\\\\").replace(/\[/g, "\\[").replace(/\]/g, "\\]")}](${uri.replace(/ /g, "%20").replace(/\(/g, "%28").replace(/\)/g, "%29").replace(/</g, "%3C").replace(/>/g, "%3E")})` : label;
|
|
403
|
+
} else if (isObject(value.dateElement)) text += stringField(isObject(value.dateElement.dateElementProperties) ? value.dateElement.dateElementProperties : {}, "displayText", "");
|
|
404
|
+
else if (isObject(value.footnoteReference)) text += `${format === "markdown" ? "[^" : "["}${stringField(value.footnoteReference, "footnoteNumber", "")}]`;
|
|
405
|
+
else if (Object.hasOwn(value, "horizontalRule")) hasRule = true;
|
|
406
|
+
}
|
|
407
|
+
return { text: text.endsWith("\n") ? text.slice(0, -1) : text, hasRule };
|
|
408
|
+
}
|
|
409
|
+
function escapeMarkdownLineStarts(value) {
|
|
410
|
+
return value.split("\n").map((line) => /^\d{1,9}[.)](?:[ \t\f\r]|$)/.test(line) ? line.replace(/^(\d{1,9})([.)])/, "$1\\$2") : /^(?:#{1,6}(?:[ \t\f\r]|$)|[-+*](?:[ \t\f\r]|$)|>|```|~~~|(?:-[ \t\f\r]*){3,}$|(?:\*[ \t\f\r]*){3,}$|(?:_[ \t\f\r]*){3,}$|=+[ \t\f\r]*$)/.test(line) ? `\\${line}` : line).join("\n");
|
|
411
|
+
}
|
|
412
|
+
function parseObject(body) {
|
|
413
|
+
return objectValue(JSON.parse(Buffer.from(body).toString("utf8"), (key, value, context) => {
|
|
414
|
+
if (typeof value === "number" && ["startIndex", "endIndex", "nestingLevel", "occurrencesChanged"].includes(key) && !/^-?\d+$/.test(context?.source ?? "")) throw new TypeError("invalid Docs integer");
|
|
415
|
+
return value;
|
|
416
|
+
}));
|
|
417
|
+
}
|
|
418
|
+
function objectValue(value) {
|
|
419
|
+
if (!isObject(value)) throw new TypeError("provider object is invalid");
|
|
420
|
+
return value;
|
|
421
|
+
}
|
|
422
|
+
function objectField(value, name) {
|
|
423
|
+
return objectValue(value[name]);
|
|
424
|
+
}
|
|
425
|
+
function stringField(value, name, fallback) {
|
|
426
|
+
const field = value[name];
|
|
427
|
+
if (field == null && fallback !== void 0) return fallback;
|
|
428
|
+
if (typeof field !== "string") throw new TypeError(`provider ${name} is invalid`);
|
|
429
|
+
return field;
|
|
430
|
+
}
|
|
431
|
+
function integerField(value, name, fallback) {
|
|
432
|
+
const field = value[name];
|
|
433
|
+
if (field == null && fallback !== void 0) return fallback;
|
|
434
|
+
if (!Number.isSafeInteger(field)) throw new TypeError(`provider ${name} is invalid`);
|
|
435
|
+
return field;
|
|
436
|
+
}
|
|
437
|
+
function arrayField(value, name, fallback) {
|
|
438
|
+
const field = name ? value[name] : value;
|
|
439
|
+
if (field == null && fallback !== void 0) return fallback;
|
|
440
|
+
if (!Array.isArray(field)) throw new TypeError(`provider ${name} is invalid`);
|
|
441
|
+
return field;
|
|
442
|
+
}
|
|
443
|
+
function isDriveID(value) {
|
|
444
|
+
return /^[A-Za-z0-9_-]{1,256}$/.test(value);
|
|
445
|
+
}
|
|
446
|
+
function goHasNonSpace(value) {
|
|
447
|
+
return /[^\p{White_Space}]/u.test(value);
|
|
448
|
+
}
|
|
449
|
+
function isObject(value) {
|
|
450
|
+
return !!value && typeof value === "object" && !Array.isArray(value);
|
|
451
|
+
}
|
|
452
|
+
function validateDocumentResource(document) {
|
|
453
|
+
checkString(document, "documentId");
|
|
454
|
+
checkString(document, "title");
|
|
455
|
+
checkString(document, "revisionId");
|
|
456
|
+
const tabs = checkArray(document, "tabs");
|
|
457
|
+
tabs?.forEach((tabValue) => validateTab(objectValue(tabValue)));
|
|
458
|
+
}
|
|
459
|
+
function validateTab(tab) {
|
|
460
|
+
const properties = checkObject(tab, "tabProperties");
|
|
461
|
+
if (properties) checkString(properties, "tabId");
|
|
462
|
+
checkArray(tab, "childTabs")?.forEach((child) => validateTab(objectValue(child)));
|
|
463
|
+
const documentTab = checkObject(tab, "documentTab");
|
|
464
|
+
if (!documentTab) return;
|
|
465
|
+
const body = checkObject(documentTab, "body");
|
|
466
|
+
if (body) checkArray(body, "content")?.forEach((value) => validateElement(objectValue(value), 0));
|
|
467
|
+
const lists = checkObject(documentTab, "lists");
|
|
468
|
+
if (lists) for (const value of Object.values(lists)) {
|
|
469
|
+
if (value == null) continue;
|
|
470
|
+
const list = objectValue(value);
|
|
471
|
+
const listProperties = checkObject(list, "listProperties");
|
|
472
|
+
if (listProperties) checkArray(listProperties, "nestingLevels")?.forEach((level) => {
|
|
473
|
+
const item = objectValue(level);
|
|
474
|
+
checkString(item, "glyphType");
|
|
475
|
+
checkString(item, "glyphSymbol");
|
|
476
|
+
});
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
function validateElement(element, depth) {
|
|
480
|
+
if (depth > 16) throw new TypeError("document tables are nested too deeply");
|
|
481
|
+
checkInteger(element, "startIndex");
|
|
482
|
+
checkInteger(element, "endIndex");
|
|
483
|
+
const paragraph = checkObject(element, "paragraph");
|
|
484
|
+
if (paragraph) {
|
|
485
|
+
const style = checkObject(paragraph, "paragraphStyle");
|
|
486
|
+
if (style) checkString(style, "namedStyleType");
|
|
487
|
+
const bullet = checkObject(paragraph, "bullet");
|
|
488
|
+
if (bullet) {
|
|
489
|
+
checkString(bullet, "listId");
|
|
490
|
+
checkInteger(bullet, "nestingLevel");
|
|
491
|
+
}
|
|
492
|
+
checkArray(paragraph, "elements")?.forEach((value) => {
|
|
493
|
+
const item = objectValue(value);
|
|
494
|
+
const textRun = checkObject(item, "textRun");
|
|
495
|
+
if (textRun) checkString(textRun, "content");
|
|
496
|
+
const footnote = checkObject(item, "footnoteReference");
|
|
497
|
+
if (footnote) checkString(footnote, "footnoteNumber");
|
|
498
|
+
const person = checkObject(item, "person");
|
|
499
|
+
if (person) {
|
|
500
|
+
const properties = checkObject(person, "personProperties");
|
|
501
|
+
if (properties) {
|
|
502
|
+
checkString(properties, "name");
|
|
503
|
+
checkString(properties, "email");
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
const link = checkObject(item, "richLink");
|
|
507
|
+
if (link) {
|
|
508
|
+
const properties = checkObject(link, "richLinkProperties");
|
|
509
|
+
if (properties) {
|
|
510
|
+
checkString(properties, "title");
|
|
511
|
+
checkString(properties, "uri");
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
const date = checkObject(item, "dateElement");
|
|
515
|
+
if (date) {
|
|
516
|
+
const properties = checkObject(date, "dateElementProperties");
|
|
517
|
+
if (properties) checkString(properties, "displayText");
|
|
518
|
+
}
|
|
519
|
+
});
|
|
520
|
+
}
|
|
521
|
+
const table = checkObject(element, "table");
|
|
522
|
+
if (table) checkArray(table, "tableRows")?.forEach((rowValue) => {
|
|
523
|
+
const row = objectValue(rowValue);
|
|
524
|
+
checkArray(row, "tableCells")?.forEach((cellValue) => {
|
|
525
|
+
const cell = objectValue(cellValue);
|
|
526
|
+
checkArray(cell, "content")?.forEach((value) => validateElement(objectValue(value), depth + 1));
|
|
527
|
+
});
|
|
528
|
+
});
|
|
529
|
+
const toc = checkObject(element, "tableOfContents");
|
|
530
|
+
if (toc) checkArray(toc, "content")?.forEach((value) => validateElement(objectValue(value), depth + 1));
|
|
531
|
+
}
|
|
532
|
+
function checkObject(value, field) {
|
|
533
|
+
return value[field] == null ? void 0 : objectValue(value[field]);
|
|
534
|
+
}
|
|
535
|
+
function checkArray(value, field) {
|
|
536
|
+
const item = value[field];
|
|
537
|
+
if (item == null) return void 0;
|
|
538
|
+
if (!Array.isArray(item)) throw new TypeError(`provider ${field} is invalid`);
|
|
539
|
+
return item;
|
|
540
|
+
}
|
|
541
|
+
function checkString(value, field) {
|
|
542
|
+
if (value[field] != null && typeof value[field] !== "string") throw new TypeError(`provider ${field} is invalid`);
|
|
543
|
+
}
|
|
544
|
+
function checkInteger(value, field) {
|
|
545
|
+
if (value[field] != null && !Number.isSafeInteger(value[field])) throw new TypeError(`provider ${field} is invalid`);
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
// src/operations.ts
|
|
549
|
+
var readFields = "documentId,title,revisionId,tabs(tabProperties/tabId,childTabs/tabProperties/tabId,documentTab(body,lists))";
|
|
550
|
+
var writeFields = "documentId,revisionId,tabs(tabProperties/tabId,documentTab/body)";
|
|
551
|
+
var fileFields = "id,name,mimeType,parents,webViewLink,createdTime,trashed";
|
|
552
|
+
var zeroRead = { documentId: "", title: "", format: "", byteCount: 0 };
|
|
553
|
+
var zeroCreate = { document: { documentId: "", title: "" } };
|
|
554
|
+
var zeroReplace = { documentId: "" };
|
|
555
|
+
var zeroAppend = { documentId: "" };
|
|
556
|
+
var GetDocumentTextOperation = class {
|
|
557
|
+
/** Bind a validated Docs client. */
|
|
558
|
+
constructor(client) {
|
|
559
|
+
this.client = client;
|
|
560
|
+
}
|
|
561
|
+
client;
|
|
562
|
+
/** Return the immutable operation definition. */
|
|
563
|
+
definition() {
|
|
564
|
+
return GetDocumentTextDefinition;
|
|
565
|
+
}
|
|
566
|
+
/** Validate, read, and render one Google Docs revision. */
|
|
567
|
+
async invoke(call, input) {
|
|
568
|
+
if (!GetDocumentTextInputSchema.safeParse(input).success) return newQueryBranch("defect", zeroRead, {}, docsFailure("getDocumentText", "VALIDATION", "documentId must be a Google Docs document ID and format must be markdown or plainText"));
|
|
569
|
+
const format = input.format || "markdown";
|
|
570
|
+
if (!isDriveID(input.documentId) || !["markdown", "plainText"].includes(format)) return newQueryBranch("defect", zeroRead, {}, docsFailure("getDocumentText", "VALIDATION", "documentId must be a Google Docs document ID and format must be markdown or plainText"));
|
|
571
|
+
let credentials;
|
|
572
|
+
try {
|
|
573
|
+
credentials = await this.client.resolveCredentials(call);
|
|
574
|
+
} catch (error) {
|
|
575
|
+
if (!(error instanceof ReauthorizationRequiredError)) return newQueryRetry(docsFailure("getDocumentText", "AUTHENTICATION", "connection credentials are temporarily unavailable"));
|
|
576
|
+
return newQueryBranch("defect", zeroRead, {}, docsFailure("getDocumentText", "AUTHENTICATION", "connection credentials are unavailable"));
|
|
577
|
+
}
|
|
578
|
+
const url = documentURL(this.client, input.documentId, "PREVIEW_WITHOUT_SUGGESTIONS", readFields);
|
|
579
|
+
const read = await sendRead(this.client, call, credentials, "getDocumentText", url, "tooLarge", "notFound", zeroRead);
|
|
580
|
+
if ("attempt" in read) return read.attempt;
|
|
581
|
+
const receipt = this.client.receipt(call, read.response, input.documentId);
|
|
582
|
+
let document;
|
|
583
|
+
try {
|
|
584
|
+
document = decodeDocument(read.response.body);
|
|
585
|
+
} catch {
|
|
586
|
+
return newQueryBranch("invalidResponse", zeroRead, receipt, docsFailure("getDocumentText", "PROTOCOL", "provider returned an invalid document"));
|
|
587
|
+
}
|
|
588
|
+
const output = { documentId: document.documentId, title: document.title, ...document.revisionId ? { revisionId: document.revisionId } : {}, format, byteCount: 0, ...document.hasOtherTabs ? { hasOtherTabs: true } : {} };
|
|
589
|
+
let text;
|
|
590
|
+
try {
|
|
591
|
+
text = renderDocumentText(document, format);
|
|
592
|
+
} catch {
|
|
593
|
+
return newQueryBranch("invalidResponse", output, receipt, docsFailure("getDocumentText", "PROTOCOL", "document structure could not be rendered"));
|
|
594
|
+
}
|
|
595
|
+
if (Buffer.byteLength(text, "utf8") > this.client.maxTextBytes) return newQueryBranch("tooLarge", output, receipt, docsFailure("getDocumentText", "RESPONSE_TOO_LARGE", "document text exceeds the configured limit"));
|
|
596
|
+
if (text) output.text = text;
|
|
597
|
+
output.byteCount = Buffer.byteLength(text, "utf8");
|
|
598
|
+
return newQueryBranch("read", output, receipt);
|
|
599
|
+
}
|
|
600
|
+
};
|
|
601
|
+
async function sendRead(client, call, credentials, operation, url, tooLargeBranch, notFoundBranch, zero, signal) {
|
|
602
|
+
let response;
|
|
603
|
+
try {
|
|
604
|
+
response = await client.request(call, credentials, "GET", url, void 0, void 0, false, signal);
|
|
605
|
+
} catch (error) {
|
|
606
|
+
if (error instanceof DocsRequestError && error.tooLarge) return { attempt: newQueryBranch(tooLargeBranch, zero, client.receipt(call, { status: error.status, headers: error.headers, body: new Uint8Array() }), docsFailure(operation, "RESPONSE_TOO_LARGE", "provider response exceeds the configured limit")) };
|
|
607
|
+
return { attempt: newQueryRetry(docsFailure(operation, "TRANSPORT", "provider is unavailable")) };
|
|
608
|
+
}
|
|
609
|
+
if (response.status >= 200 && response.status < 300) return { response };
|
|
610
|
+
const tokens = googleTokens(response);
|
|
611
|
+
if (isRetryable(response.status, tokens)) return { attempt: newQueryRetry(docsFailure(operation, statusFailureKind(response.status, tokens), "provider temporarily rejected the request"), retryAfterMs(response, client.now())) };
|
|
612
|
+
const receipt = client.receipt(call, response);
|
|
613
|
+
if (response.status === 404) return { attempt: newQueryBranch(notFoundBranch, zero, receipt, docsFailure(operation, "NOT_FOUND", "document was not found or is not visible to the connection")) };
|
|
614
|
+
return { attempt: newQueryBranch("providerRejected", zero, receipt, docsFailure(operation, statusFailureKind(response.status, tokens), "provider rejected the request")) };
|
|
615
|
+
}
|
|
616
|
+
function documentURL(client, documentId, suggestionsViewMode, fields) {
|
|
617
|
+
return `${client.documentsBaseURL}/${goPathEscape(documentId)}?${goQuery({ includeTabsContent: "true", suggestionsViewMode, fields })}`;
|
|
618
|
+
}
|
|
619
|
+
function filesListURL(client, values) {
|
|
620
|
+
return `${client.driveBaseURL}/files?${goQuery({ ...values, corpora: "allDrives", supportsAllDrives: "true", includeItemsFromAllDrives: "true" })}`;
|
|
621
|
+
}
|
|
622
|
+
var ReplaceDocumentTextOperation = class {
|
|
623
|
+
/** Bind a validated Docs client. */
|
|
624
|
+
constructor(client) {
|
|
625
|
+
this.client = client;
|
|
626
|
+
}
|
|
627
|
+
client;
|
|
628
|
+
/** Return the immutable operation definition. */
|
|
629
|
+
definition() {
|
|
630
|
+
return ReplaceDocumentTextDefinition;
|
|
631
|
+
}
|
|
632
|
+
/** Use the stable Dex Call ID; the revision guards the write. */
|
|
633
|
+
idempotencyKey(callId) {
|
|
634
|
+
return callId;
|
|
635
|
+
}
|
|
636
|
+
/** Validate and run one revision-guarded replacement. */
|
|
637
|
+
async invoke(call, input) {
|
|
638
|
+
if (!ReplaceDocumentTextInputSchema.safeParse(input).success) return newMutationBranch("defect", zeroReplace, {}, docsFailure("replaceDocumentText", "VALIDATION", "replaceDocumentText input is invalid"));
|
|
639
|
+
try {
|
|
640
|
+
validateGuardedTarget(input.documentId, input.requiredRevisionId);
|
|
641
|
+
validateReplaceInput(input, this.client.maxTextBytes);
|
|
642
|
+
} catch (error) {
|
|
643
|
+
return newMutationBranch("defect", zeroReplace, {}, docsFailure("replaceDocumentText", "VALIDATION", safeError(error)));
|
|
644
|
+
}
|
|
645
|
+
return runGuardedWrite(
|
|
646
|
+
this.client,
|
|
647
|
+
call,
|
|
648
|
+
input.documentId,
|
|
649
|
+
input.requiredRevisionId,
|
|
650
|
+
"replaceDocumentText",
|
|
651
|
+
zeroReplace,
|
|
652
|
+
"replaced",
|
|
653
|
+
(document, bodyText) => buildReplacement(document, bodyText, input),
|
|
654
|
+
(bodyText) => input.target === "wholeBody" ? bodyText === `${input.text ?? ""}
|
|
655
|
+
` : (input.placeholders ?? []).every((item) => !bodyText.includes(item.placeholder) && bodyText.includes(item.text)),
|
|
656
|
+
(revisionId, replies, wasAlreadyApplied) => ({ documentId: input.documentId, ...revisionId ? { revisionId } : {}, ...wasAlreadyApplied ? { wasAlreadyApplied: true } : {}, ...input.target === "placeholders" && replies.length ? { replacements: (input.placeholders ?? []).map((item, index) => ({ placeholder: item.placeholder, occurrencesChanged: isObject2(replies[index]?.replaceAllText) ? integerField(replies[index].replaceAllText, "occurrencesChanged", 0) : 0 })) } : {} })
|
|
657
|
+
);
|
|
658
|
+
}
|
|
659
|
+
};
|
|
660
|
+
var AppendTextOperation = class {
|
|
661
|
+
/** Bind a validated Docs client. */
|
|
662
|
+
constructor(client) {
|
|
663
|
+
this.client = client;
|
|
664
|
+
}
|
|
665
|
+
client;
|
|
666
|
+
/** Return the immutable operation definition. */
|
|
667
|
+
definition() {
|
|
668
|
+
return AppendTextDefinition;
|
|
669
|
+
}
|
|
670
|
+
/** Use the stable Dex Call ID; the revision guards the write. */
|
|
671
|
+
idempotencyKey(callId) {
|
|
672
|
+
return callId;
|
|
673
|
+
}
|
|
674
|
+
/** Validate and run one revision-guarded append. */
|
|
675
|
+
async invoke(call, input) {
|
|
676
|
+
if (!AppendTextInputSchema.safeParse(input).success) return newMutationBranch("defect", zeroAppend, {}, docsFailure("appendText", "VALIDATION", "appendText input is invalid"));
|
|
677
|
+
try {
|
|
678
|
+
validateGuardedTarget(input.documentId, input.requiredRevisionId);
|
|
679
|
+
if (!goHasNonSpace(input.text)) throw new TypeError("text must not be blank");
|
|
680
|
+
validateWriteText("text", input.text);
|
|
681
|
+
if (Buffer.byteLength(input.text) > this.client.maxTextBytes) throw new TypeError("text exceeds the configured text limit");
|
|
682
|
+
} catch (error) {
|
|
683
|
+
return newMutationBranch("defect", zeroAppend, {}, docsFailure("appendText", "VALIDATION", safeError(error)));
|
|
684
|
+
}
|
|
685
|
+
return runGuardedWrite(this.client, call, input.documentId, input.requiredRevisionId, "appendText", zeroAppend, "appended", (document, bodyText) => {
|
|
686
|
+
const separator = bodyText === "\n" ? "" : "\n";
|
|
687
|
+
const insertIndex = document.bodyEndIndex - 1;
|
|
688
|
+
const start = insertIndex + separator.length;
|
|
689
|
+
return { requests: [{ insertText: { text: separator + input.text, location: { index: insertIndex, tabId: document.tabId } } }, ...plainParagraphRequests(document.tabId, start, start + input.text.length)] };
|
|
690
|
+
}, (bodyText) => bodyText === `${input.text}
|
|
691
|
+
` || bodyText.endsWith(`
|
|
692
|
+
${input.text}
|
|
693
|
+
`), (revisionId, _replies, wasAlreadyApplied) => ({ documentId: input.documentId, ...revisionId ? { revisionId } : {}, ...wasAlreadyApplied ? { wasAlreadyApplied: true } : {} }));
|
|
694
|
+
}
|
|
695
|
+
};
|
|
696
|
+
async function runGuardedWrite(client, call, documentId, requiredRevisionId, operation, zero, appliedBranch, build, held, output) {
|
|
697
|
+
let credentials;
|
|
698
|
+
try {
|
|
699
|
+
credentials = await client.resolveCredentials(call);
|
|
700
|
+
} catch (error) {
|
|
701
|
+
const failure = docsFailure(operation, "AUTHENTICATION", "connection credentials are unavailable");
|
|
702
|
+
if (!(error instanceof ReauthorizationRequiredError) || call.context.attempt > 1) return newMutationRetry(failure);
|
|
703
|
+
return newMutationBranch("defect", zero, {}, failure);
|
|
704
|
+
}
|
|
705
|
+
const read = async () => {
|
|
706
|
+
const result = await sendRead(client, call, credentials, operation, documentURL(client, documentId, "SUGGESTIONS_INLINE", writeFields), "invalidResponse", "notFound", zero);
|
|
707
|
+
if ("attempt" in result) return { attempt: result.attempt };
|
|
708
|
+
const receipt2 = client.receipt(call, result.response, documentId);
|
|
709
|
+
let document;
|
|
710
|
+
try {
|
|
711
|
+
document = decodeDocument(result.response.body);
|
|
712
|
+
} catch {
|
|
713
|
+
return { attempt: newMutationBranch("invalidResponse", zero, receipt2, docsFailure(operation, "PROTOCOL", "provider returned an invalid document")) };
|
|
714
|
+
}
|
|
715
|
+
if (!document.revisionId) return { attempt: newMutationBranch("providerRejected", zero, receipt2, docsFailure(operation, "AUTHORIZATION", "connection cannot edit the document")) };
|
|
716
|
+
try {
|
|
717
|
+
return { document, bodyText: documentBodyText(document), receipt: receipt2 };
|
|
718
|
+
} catch {
|
|
719
|
+
return { attempt: newMutationBranch("invalidResponse", zero, receipt2, docsFailure(operation, "PROTOCOL", "document structure could not be read")) };
|
|
720
|
+
}
|
|
721
|
+
};
|
|
722
|
+
const first = await read();
|
|
723
|
+
if ("attempt" in first) return first.attempt;
|
|
724
|
+
const changed = (observed) => held(observed.bodyText) ? newMutationBranch(appliedBranch, output(observed.document.revisionId, [], true), observed.receipt) : newMutationBranch("revisionChanged", output(observed.document.revisionId, [], false), observed.receipt, docsFailure(operation, "CONFLICT", "document changed after the required revision; nothing was written"));
|
|
725
|
+
if (first.document.revisionId !== requiredRevisionId) return changed(first);
|
|
726
|
+
const prepared = build(first.document, first.bodyText);
|
|
727
|
+
if (prepared.terminal) return prepared.terminal;
|
|
728
|
+
if (prepared.requests.length === 0) return newMutationBranch(appliedBranch, output(first.document.revisionId, [], true), first.receipt);
|
|
729
|
+
let response;
|
|
730
|
+
try {
|
|
731
|
+
response = await client.request(call, credentials, "POST", `${client.documentsBaseURL}/${goPathEscape(documentId)}:batchUpdate`, Buffer.from(JSON.stringify({ requests: prepared.requests, writeControl: { requiredRevisionId } })), "application/json; charset=UTF-8");
|
|
732
|
+
} catch {
|
|
733
|
+
return newMutationRetry(docsFailure(operation, "TRANSPORT", "provider update outcome is unknown; the next attempt reads the revision"));
|
|
734
|
+
}
|
|
735
|
+
const receipt = client.receipt(call, response, documentId);
|
|
736
|
+
const tokens = googleTokens(response);
|
|
737
|
+
if (response.status >= 200 && response.status < 300) {
|
|
738
|
+
try {
|
|
739
|
+
const body = parseObject(response.body);
|
|
740
|
+
stringField(body, "documentId", "");
|
|
741
|
+
const replies = arrayField(body, "replies", []).map(objectValue);
|
|
742
|
+
for (const reply of replies) {
|
|
743
|
+
if (reply.replaceAllText != null) {
|
|
744
|
+
if (!isObject2(reply.replaceAllText)) throw new TypeError("replaceAllText reply is invalid");
|
|
745
|
+
integerField(reply.replaceAllText, "occurrencesChanged", 0);
|
|
746
|
+
}
|
|
747
|
+
}
|
|
748
|
+
if (body.writeControl != null && !isObject2(body.writeControl)) throw new TypeError("writeControl is invalid");
|
|
749
|
+
const revisionId = isObject2(body.writeControl) ? stringField(body.writeControl, "requiredRevisionId", "") : "";
|
|
750
|
+
return newMutationBranch(appliedBranch, output(revisionId, replies, false), receipt);
|
|
751
|
+
} catch {
|
|
752
|
+
return newMutationRetry(docsFailure(operation, "PROTOCOL", "provider returned an invalid update response; the next attempt reads the revision"));
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
if (isRetryable(response.status, tokens)) return newMutationRetry(docsFailure(operation, statusFailureKind(response.status, tokens), "provider temporarily rejected the update"), retryAfterMs(response, client.now()));
|
|
756
|
+
if (response.status === 400) {
|
|
757
|
+
const reread = await read();
|
|
758
|
+
if ("attempt" in reread) return reread.attempt;
|
|
759
|
+
if (reread.document.revisionId === requiredRevisionId) return newMutationBranch("providerRejected", zero, receipt, docsFailure(operation, "PROVIDER_REJECTION", "provider rejected the update at the required revision"));
|
|
760
|
+
return changed(reread);
|
|
761
|
+
}
|
|
762
|
+
if (response.status === 404) return newMutationBranch("notFound", zero, receipt, docsFailure(operation, "NOT_FOUND", "document was not found or is not visible to the connection"));
|
|
763
|
+
if (definiteRefusalStatuses.has(response.status)) return newMutationBranch("providerRejected", zero, receipt, docsFailure(operation, statusFailureKind(response.status, tokens), "provider rejected the update"));
|
|
764
|
+
return newMutationRetry(docsFailure(operation, statusFailureKind(response.status, tokens), "provider update outcome is unknown; the next attempt reads the revision"));
|
|
765
|
+
}
|
|
766
|
+
var definiteRefusalStatuses = /* @__PURE__ */ new Set([400, 401, 403, 404, 411, 413, 414, 415, 422]);
|
|
767
|
+
function buildReplacement(document, bodyText, input) {
|
|
768
|
+
if (input.target === "wholeBody") {
|
|
769
|
+
const start = document.bodyStartIndex;
|
|
770
|
+
const end = document.bodyEndIndex - 1;
|
|
771
|
+
const requests = [];
|
|
772
|
+
if (end > start) requests.push({ deleteContentRange: { range: { startIndex: start, endIndex: end, tabId: document.tabId } } });
|
|
773
|
+
if (input.text) {
|
|
774
|
+
requests.push({ insertText: { text: input.text, location: { index: start, tabId: document.tabId } } });
|
|
775
|
+
requests.push(...plainParagraphRequests(document.tabId, start, start + input.text.length));
|
|
776
|
+
}
|
|
777
|
+
return { requests };
|
|
778
|
+
}
|
|
779
|
+
const missing = (input.placeholders ?? []).filter((item) => !bodyText.includes(item.placeholder)).map((item) => item.placeholder);
|
|
780
|
+
if (missing.length) return { requests: [], terminal: newMutationBranch("placeholderNotFound", { documentId: input.documentId, revisionId: document.revisionId, missingPlaceholders: missing }, {}, docsFailure("replaceDocumentText", "VALIDATION", "a placeholder does not occur in the document body; nothing was written")) };
|
|
781
|
+
return { requests: (input.placeholders ?? []).map((item) => ({ replaceAllText: { replaceText: item.text, containsText: { text: item.placeholder, matchCase: true }, tabsCriteria: { tabIds: [document.tabId] } } })) };
|
|
782
|
+
}
|
|
783
|
+
function plainParagraphRequests(tabId, startIndex, endIndex) {
|
|
784
|
+
const range = { startIndex, endIndex, tabId };
|
|
785
|
+
return [
|
|
786
|
+
{ deleteParagraphBullets: { range } },
|
|
787
|
+
{ updateParagraphStyle: { range, paragraphStyle: { namedStyleType: "NORMAL_TEXT" }, fields: "*" } },
|
|
788
|
+
{ updateTextStyle: { range, textStyle: {}, fields: "*" } }
|
|
789
|
+
];
|
|
790
|
+
}
|
|
791
|
+
function validateGuardedTarget(documentId, revisionId) {
|
|
792
|
+
if (!isDriveID(documentId)) throw new TypeError("documentId must be a Google Docs document ID");
|
|
793
|
+
if (!revisionId || Buffer.byteLength(revisionId) > 1024 || /[\p{C}\p{Z}\u0085\u1680\u2028\u2029]/u.test(revisionId)) throw new TypeError("requiredRevisionId must be the revisionId a getDocumentText Step returned");
|
|
794
|
+
}
|
|
795
|
+
function validateReplaceInput(input, maxTextBytes) {
|
|
796
|
+
if (input.target === "wholeBody") {
|
|
797
|
+
if (input.placeholders?.length) throw new TypeError("wholeBody takes text, not placeholders");
|
|
798
|
+
if (Buffer.byteLength(input.text ?? "") > maxTextBytes) throw new TypeError("text exceeds the configured text limit");
|
|
799
|
+
validateWriteText("text", input.text ?? "");
|
|
800
|
+
return;
|
|
801
|
+
}
|
|
802
|
+
if (input.target !== "placeholders") throw new TypeError("target must be wholeBody or placeholders");
|
|
803
|
+
if (input.text) throw new TypeError("placeholders takes placeholders, not text");
|
|
804
|
+
const items = input.placeholders ?? [];
|
|
805
|
+
if (items.length === 0 || items.length > 50) throw new TypeError("placeholders must list 1 to 50 placeholders");
|
|
806
|
+
let totalBytes = 0;
|
|
807
|
+
items.forEach((item, index) => {
|
|
808
|
+
if (!goHasNonSpace(item.placeholder) || Buffer.byteLength(item.placeholder) > 256 || /[\n\v]/.test(item.placeholder)) throw new TypeError(`placeholders[${index}].placeholder must be 1 to 256 bytes on one line`);
|
|
809
|
+
validateWriteText(`placeholders[${index}].placeholder`, item.placeholder);
|
|
810
|
+
validateWriteText(`placeholders[${index}].text`, item.text);
|
|
811
|
+
totalBytes += Buffer.byteLength(item.text);
|
|
812
|
+
if (items.some((other, otherIndex) => otherIndex !== index && other.placeholder.includes(item.placeholder))) throw new TypeError(`placeholders[${index}].placeholder repeats or is part of another placeholder`);
|
|
813
|
+
if (items.some((other) => item.text.includes(other.placeholder))) throw new TypeError(`placeholders[${index}].text cannot contain a requested placeholder`);
|
|
814
|
+
});
|
|
815
|
+
if (totalBytes > maxTextBytes) throw new TypeError("placeholder replacements exceed the configured text limit");
|
|
816
|
+
}
|
|
817
|
+
function validateWriteText(field, value) {
|
|
818
|
+
if (value.includes("\r")) throw new TypeError(`${field} must use \\n line breaks without \\r`);
|
|
819
|
+
for (const character of value) {
|
|
820
|
+
const code = character.codePointAt(0);
|
|
821
|
+
if (code <= 8 || code >= 12 && code <= 31) throw new TypeError(`${field} cannot contain control characters other than tab and line breaks`);
|
|
822
|
+
if (code >= 57344 && code <= 63743) throw new TypeError(`${field} cannot contain private-use characters, which Google strips`);
|
|
823
|
+
}
|
|
824
|
+
}
|
|
825
|
+
function safeError(error) {
|
|
826
|
+
return error instanceof Error ? error.message : "invalid input";
|
|
827
|
+
}
|
|
828
|
+
function isObject2(value) {
|
|
829
|
+
return !!value && typeof value === "object" && !Array.isArray(value);
|
|
830
|
+
}
|
|
831
|
+
var CreateDocumentOperation = class {
|
|
832
|
+
/** Bind a validated Docs client. */
|
|
833
|
+
constructor(client) {
|
|
834
|
+
this.client = client;
|
|
835
|
+
}
|
|
836
|
+
client;
|
|
837
|
+
/** Return the immutable operation definition. */
|
|
838
|
+
definition() {
|
|
839
|
+
return CreateDocumentDefinition;
|
|
840
|
+
}
|
|
841
|
+
/** Use the stable Dex Call ID as Drive's private app-property value. */
|
|
842
|
+
idempotencyKey(callId) {
|
|
843
|
+
return callId;
|
|
844
|
+
}
|
|
845
|
+
/** Validate, reconcile, and create no more than once per Dex Call. */
|
|
846
|
+
async invoke(call, input) {
|
|
847
|
+
if (!CreateDocumentInputSchema.safeParse(input).success) return newMutationBranch("defect", zeroCreate, {}, docsFailure("createDocument", "VALIDATION", "createDocument input is invalid"));
|
|
848
|
+
return createDocument(this.client, call, input);
|
|
849
|
+
}
|
|
850
|
+
};
|
|
851
|
+
async function createDocument(client, call, input) {
|
|
852
|
+
let format;
|
|
853
|
+
try {
|
|
854
|
+
format = validateCreateInput(input, client.maxTextBytes);
|
|
855
|
+
} catch (error) {
|
|
856
|
+
return newMutationBranch("defect", zeroCreate, {}, docsFailure("createDocument", "VALIDATION", safeError(error)));
|
|
857
|
+
}
|
|
858
|
+
const key = call.idempotencyKey ?? "";
|
|
859
|
+
if (!key || Buffer.byteLength(key) > 100) return newMutationBranch("defect", zeroCreate, {}, docsFailure("createDocument", "LOCAL_DEFECT", "idempotency key is missing or too long"));
|
|
860
|
+
const operationMaxSends = definitionMaxSends(CreateDocumentDefinition);
|
|
861
|
+
let fence;
|
|
862
|
+
try {
|
|
863
|
+
fence = newFence(call, 3e4, { maxSends: operationMaxSends });
|
|
864
|
+
} catch {
|
|
865
|
+
return newMutationBranch("defect", zeroCreate, {}, docsFailure("createDocument", "LOCAL_DEFECT", "single-dispatch fence could not be constructed"));
|
|
866
|
+
}
|
|
867
|
+
const decision = fence.decide();
|
|
868
|
+
const priorSendUpperBound = decision.priorSendUpperBound ?? 0;
|
|
869
|
+
const canResendUnknownOutcome = priorSendUpperBound + 1 < (operationMaxSends >= 2 ? call.maxSendsOverride ?? operationMaxSends : 1);
|
|
870
|
+
const hasPossibleEarlierSend = priorSendUpperBound > 0;
|
|
871
|
+
let credentials;
|
|
872
|
+
try {
|
|
873
|
+
credentials = await client.resolveCredentials(call);
|
|
874
|
+
} catch (error) {
|
|
875
|
+
const isRetryable2 = !(error instanceof ReauthorizationRequiredError);
|
|
876
|
+
const isFirstAttemptSend = decision.kind === "sendAllowed" && !hasPossibleEarlierSend;
|
|
877
|
+
if (isRetryable2 && isFirstAttemptSend) {
|
|
878
|
+
try {
|
|
879
|
+
await fence.recordNotSent();
|
|
880
|
+
} catch {
|
|
881
|
+
return newMutationRetry(docsFailure("createDocument", "AVAILABILITY", "Dex could not record a pre-send retry"));
|
|
882
|
+
}
|
|
883
|
+
return newMutationRetry(docsFailure("createDocument", "AUTHENTICATION", "connection credentials are temporarily unavailable"));
|
|
884
|
+
}
|
|
885
|
+
if (isRetryable2 || decision.kind === "failClosed") return newMutationRetry(docsFailure("createDocument", "AUTHENTICATION", "connection credentials are unavailable for duplicate lookup"));
|
|
886
|
+
const failure = docsFailure("createDocument", "AUTHENTICATION", "connection credentials are unavailable; reconnect the connection");
|
|
887
|
+
if (!isFirstAttemptSend) return newMutationUncertain(zeroCreate, { ...failure, message: `${failure.message} after an earlier unconfirmed send` }, {});
|
|
888
|
+
return newMutationBranch("defect", zeroCreate, {}, failure);
|
|
889
|
+
}
|
|
890
|
+
const lookupQuery = { q: `appProperties has { key='dexIdempotencyKey' and value='${key.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}' }`, fields: `incompleteSearch,files(${fileFields})`, pageSize: "10", spaces: "drive" };
|
|
891
|
+
const lookupURL = filesListURL(client, lookupQuery);
|
|
892
|
+
const lookup = async () => {
|
|
893
|
+
const result = await sendRead(client, call, credentials, "createDocument", lookupURL, "invalidResponse", "providerRejected", zeroCreate, createLookupSignal(call));
|
|
894
|
+
if ("attempt" in result) return result;
|
|
895
|
+
try {
|
|
896
|
+
return { ...decodeEarlierDocument(result.response.body), response: result.response };
|
|
897
|
+
} catch {
|
|
898
|
+
return { attempt: newQueryBranch("invalidResponse", zeroCreate, client.receipt(call, result.response), docsFailure("createDocument", "PROTOCOL", "provider returned an invalid duplicate-lookup response")), isInvalidLookup: true };
|
|
899
|
+
}
|
|
900
|
+
};
|
|
901
|
+
if (decision.kind === "failClosed") {
|
|
902
|
+
const found = await lookup();
|
|
903
|
+
if ("response" in found && !found.incomplete && found.document) return newMutationBranch("created", { document: found.document, isFromEarlierAttempt: true }, client.receipt(call, void 0, found.document.documentId));
|
|
904
|
+
return newMutationRetry(docsFailure("createDocument", "AVAILABILITY", "dispatch checkpoint is unreadable; no document was created in this attempt"));
|
|
905
|
+
}
|
|
906
|
+
const hasSavedDocumentId = !!decision.marker?.providerId;
|
|
907
|
+
const isAtSendCap = decision.kind === "readBackRequired";
|
|
908
|
+
const isFirstSend = decision.kind === "sendAllowed" && !hasPossibleEarlierSend && !hasSavedDocumentId;
|
|
909
|
+
const hasPossibleCreate = hasPossibleEarlierSend || hasSavedDocumentId;
|
|
910
|
+
const retryLookupOrSelectUncertain = (kind, message, receiptDraft) => isAtSendCap ? newMutationUncertain(zeroCreate, docsFailure("createDocument", kind, message), receiptDraft) : newMutationRetry(docsFailure("createDocument", kind, `${message}; the next attempt looks it up again`));
|
|
911
|
+
if (hasSavedDocumentId && decision.marker?.providerId && isDriveID(decision.marker.providerId)) {
|
|
912
|
+
const url = `${client.driveBaseURL}/files/${goPathEscape(decision.marker.providerId)}?${goQuery({ fields: fileFields, supportsAllDrives: "true" })}`;
|
|
913
|
+
const found = await sendRead(client, call, credentials, "createDocument", url, "invalidResponse", "providerRejected", zeroCreate, createLookupSignal(call));
|
|
914
|
+
if ("response" in found) {
|
|
915
|
+
try {
|
|
916
|
+
const document = convertCreatedDocument(parseObject(found.response.body));
|
|
917
|
+
if (document.documentId === decision.marker.providerId) return newMutationBranch("created", { document, isFromEarlierAttempt: true }, client.receipt(call, found.response, document.documentId));
|
|
918
|
+
} catch {
|
|
919
|
+
}
|
|
920
|
+
} else if (found.attempt.kind === "retry") return newMutationRetry(found.attempt.failure, found.attempt.retryAfterMs);
|
|
921
|
+
}
|
|
922
|
+
const firstLookup = await lookup();
|
|
923
|
+
if ("attempt" in firstLookup) {
|
|
924
|
+
const attempt = firstLookup.attempt;
|
|
925
|
+
if (firstLookup.isInvalidLookup) {
|
|
926
|
+
if (hasPossibleCreate) return retryLookupOrSelectUncertain("PROTOCOL", "a prior create cannot be confirmed because duplicate lookup was invalid", attempt.kind === "branch" ? attempt.receipt : {});
|
|
927
|
+
return attempt;
|
|
928
|
+
}
|
|
929
|
+
if (isFirstSend && attempt.kind === "retry") return retryBeforeSend(fence, "AVAILABILITY", "duplicate lookup is unavailable");
|
|
930
|
+
if (hasPossibleCreate && attempt.kind === "branch") return retryLookupOrSelectUncertain(attempt.failure?.kind ?? "PROTOCOL", "a prior create cannot be confirmed because duplicate lookup was rejected", attempt.receipt);
|
|
931
|
+
return attempt;
|
|
932
|
+
}
|
|
933
|
+
const lookupReceipt = client.receipt(call, firstLookup.response);
|
|
934
|
+
if (firstLookup.document) return newMutationBranch("created", { document: firstLookup.document, isFromEarlierAttempt: true }, client.receipt(call, firstLookup.response, firstLookup.document.documentId));
|
|
935
|
+
if (firstLookup.incomplete) return isFirstSend ? retryBeforeSend(fence, "AVAILABILITY", "provider did not complete the duplicate lookup") : newMutationRetry(docsFailure("createDocument", "AVAILABILITY", "provider did not complete the duplicate lookup"));
|
|
936
|
+
if (isAtSendCap || hasSavedDocumentId) return retryLookupOrSelectUncertain("TRANSPORT", "an earlier attempt of this Step may have created the document, the duplicate lookup does not show it, and no further send is allowed", lookupReceipt);
|
|
937
|
+
const rejectOrSelectUncertain = async (branch, kind, message, receiptDraft) => {
|
|
938
|
+
if (hasPossibleEarlierSend) return newMutationUncertain(zeroCreate, docsFailure("createDocument", kind, `${message} after an earlier unconfirmed send`), receiptDraft);
|
|
939
|
+
if (branch === "providerRejected") {
|
|
940
|
+
try {
|
|
941
|
+
await fence.recordCanResend();
|
|
942
|
+
} catch {
|
|
943
|
+
}
|
|
944
|
+
}
|
|
945
|
+
return newMutationBranch(branch, zeroCreate, receiptDraft, docsFailure("createDocument", kind, message));
|
|
946
|
+
};
|
|
947
|
+
let request;
|
|
948
|
+
try {
|
|
949
|
+
request = buildCreateRequest(client, input, format, key);
|
|
950
|
+
} catch {
|
|
951
|
+
return rejectOrSelectUncertain("defect", "LOCAL_DEFECT", "create request could not be encoded", {});
|
|
952
|
+
}
|
|
953
|
+
let response;
|
|
954
|
+
let sendError;
|
|
955
|
+
try {
|
|
956
|
+
response = await fence.dispatch((signal) => client.request(call, credentials, "POST", request.url, request.body, request.contentType, true, signal));
|
|
957
|
+
} catch (error) {
|
|
958
|
+
sendError = error;
|
|
959
|
+
}
|
|
960
|
+
if (sendError && !(sendError instanceof DocsRequestError)) return newMutationRetry(docsFailure("createDocument", "AVAILABILITY", "Dex could not record a dispatch claim or the attempt has too little time"));
|
|
961
|
+
const receipt = client.receipt(call, response);
|
|
962
|
+
const tokens = response ? googleTokens(response) : [];
|
|
963
|
+
const confirmAfterSend = async (kind, message) => {
|
|
964
|
+
const found = await lookup();
|
|
965
|
+
if ("response" in found && !found.incomplete && found.document) {
|
|
966
|
+
try {
|
|
967
|
+
await fence.recordProviderId(found.document.documentId);
|
|
968
|
+
} catch {
|
|
969
|
+
}
|
|
970
|
+
return newMutationBranch("created", { document: found.document }, { ...receipt, providerObjectId: found.document.documentId });
|
|
971
|
+
}
|
|
972
|
+
if (canResendUnknownOutcome) return newMutationRetry(docsFailure("createDocument", kind, message));
|
|
973
|
+
return newMutationUncertain(zeroCreate, docsFailure("createDocument", kind, `${message}; the send cap is reached`), receipt);
|
|
974
|
+
};
|
|
975
|
+
const reconcileAccepted = async (kind, body) => {
|
|
976
|
+
const documentId = createdDocumentID(body);
|
|
977
|
+
let isAcceptanceSaved = true;
|
|
978
|
+
try {
|
|
979
|
+
await fence.recordProviderId(documentId || acceptedCreateWithoutDocumentID);
|
|
980
|
+
} catch {
|
|
981
|
+
isAcceptanceSaved = false;
|
|
982
|
+
}
|
|
983
|
+
const found = await lookup();
|
|
984
|
+
if ("response" in found && !found.incomplete && found.document) {
|
|
985
|
+
try {
|
|
986
|
+
await fence.recordProviderId(found.document.documentId);
|
|
987
|
+
} catch {
|
|
988
|
+
}
|
|
989
|
+
return newMutationBranch("created", { document: found.document }, { ...receipt, providerObjectId: found.document.documentId });
|
|
990
|
+
}
|
|
991
|
+
if (isAcceptanceSaved && documentId)
|
|
992
|
+
return newMutationRetry(docsFailure("createDocument", kind, "provider accepted the create with an unusable response; the next attempt reads the document back"));
|
|
993
|
+
if (isAcceptanceSaved)
|
|
994
|
+
return newMutationRetry(docsFailure("createDocument", kind, "provider accepted the create with an unusable response, and the duplicate lookup does not show it yet; the next attempt looks it up again"));
|
|
995
|
+
return newMutationUncertain(zeroCreate, docsFailure("createDocument", kind, "provider accepted the create with an unusable response, the duplicate lookup does not show it, and its acceptance checkpoint failed, so it is not sent again"), receipt);
|
|
996
|
+
};
|
|
997
|
+
if (response && response.status >= 200 && response.status < 300) {
|
|
998
|
+
try {
|
|
999
|
+
const document = convertCreatedDocument(parseObject(response.body));
|
|
1000
|
+
try {
|
|
1001
|
+
await fence.recordProviderId(document.documentId);
|
|
1002
|
+
} catch {
|
|
1003
|
+
}
|
|
1004
|
+
return newMutationBranch("created", { document }, { ...receipt, providerObjectId: document.documentId });
|
|
1005
|
+
} catch {
|
|
1006
|
+
return reconcileAccepted("PROTOCOL", response.body);
|
|
1007
|
+
}
|
|
1008
|
+
}
|
|
1009
|
+
if (sendError instanceof DocsRequestError && sendError.status >= 200 && sendError.status < 300)
|
|
1010
|
+
return reconcileAccepted(sendError.tooLarge ? "RESPONSE_TOO_LARGE" : "TRANSPORT", void 0);
|
|
1011
|
+
if (response && createdDocumentID(response.body)) return reconcileAccepted("PROTOCOL", response.body);
|
|
1012
|
+
const isBrokenThrottleBody = sendError instanceof DocsRequestError && (sendError.status === 429 || sendError.status === 503);
|
|
1013
|
+
if (response && (isRateLimit(response.status, tokens) || response.status === 503) || isBrokenThrottleBody) {
|
|
1014
|
+
const throttled = response ?? { status: sendError.status, headers: sendError.headers, body: new Uint8Array() };
|
|
1015
|
+
const found = await lookup();
|
|
1016
|
+
if ("response" in found && !found.incomplete && found.document) {
|
|
1017
|
+
try {
|
|
1018
|
+
await fence.recordProviderId(found.document.documentId);
|
|
1019
|
+
} catch {
|
|
1020
|
+
}
|
|
1021
|
+
return newMutationBranch("created", { document: found.document }, { ...receipt, providerObjectId: found.document.documentId });
|
|
1022
|
+
}
|
|
1023
|
+
try {
|
|
1024
|
+
await fence.recordCanResend();
|
|
1025
|
+
} catch {
|
|
1026
|
+
return newMutationRetry(docsFailure("createDocument", "AVAILABILITY", "Dex could not record safe resend after provider rejection"));
|
|
1027
|
+
}
|
|
1028
|
+
return newMutationRetry(docsFailure("createDocument", statusFailureKind(throttled.status, tokens), "provider temporarily rejected the create"), retryAfterMs(throttled, client.now()));
|
|
1029
|
+
}
|
|
1030
|
+
if (response?.status === 401 && !response.isErrorBodyTooLarge) {
|
|
1031
|
+
try {
|
|
1032
|
+
await client.refreshCredentialsAfterRejection(call);
|
|
1033
|
+
} catch (error) {
|
|
1034
|
+
if (error instanceof ReauthorizationRequiredError) return rejectOrSelectUncertain("providerRejected", "AUTHENTICATION", "provider rejected the create credential", receipt);
|
|
1035
|
+
try {
|
|
1036
|
+
await fence.recordCanResend();
|
|
1037
|
+
} catch {
|
|
1038
|
+
}
|
|
1039
|
+
return newMutationRetry(docsFailure("createDocument", "AUTHENTICATION", "provider rejected the create credential, and its refresh is temporarily unavailable"));
|
|
1040
|
+
}
|
|
1041
|
+
try {
|
|
1042
|
+
await fence.recordCanResend();
|
|
1043
|
+
} catch {
|
|
1044
|
+
return newMutationRetry(docsFailure("createDocument", "AUTHENTICATION", "Dex could not record safe resend after credential refresh"));
|
|
1045
|
+
}
|
|
1046
|
+
return newMutationRetry(docsFailure("createDocument", "AUTHENTICATION", "provider rejected the create credential; refreshed for the next attempt"));
|
|
1047
|
+
}
|
|
1048
|
+
if (sendError) {
|
|
1049
|
+
if (sendError instanceof DocsRequestError && sendError.beforeSend) {
|
|
1050
|
+
try {
|
|
1051
|
+
await fence.recordCanResend();
|
|
1052
|
+
} catch {
|
|
1053
|
+
return newMutationRetry(docsFailure("createDocument", "TRANSPORT", "Dex could not record a proven no-send"));
|
|
1054
|
+
}
|
|
1055
|
+
return newMutationRetry(docsFailure("createDocument", "TRANSPORT", "provider connection failed before the create was sent"));
|
|
1056
|
+
}
|
|
1057
|
+
return confirmAfterSend("TRANSPORT", "provider create outcome is unknown");
|
|
1058
|
+
}
|
|
1059
|
+
const status = response?.status ?? 0;
|
|
1060
|
+
if (definiteRefusalStatuses.has(status) && !response?.isErrorBodyTooLarge) return rejectOrSelectUncertain("providerRejected", statusFailureKind(status, tokens), "provider rejected the create", receipt);
|
|
1061
|
+
return confirmAfterSend(statusFailureKind(status, tokens), `provider create outcome is unknown after HTTP ${status}`);
|
|
1062
|
+
}
|
|
1063
|
+
var acceptedCreateWithoutDocumentID = "dex:acceptedWithoutDocumentId";
|
|
1064
|
+
function createdDocumentID(body) {
|
|
1065
|
+
if (!body) return "";
|
|
1066
|
+
try {
|
|
1067
|
+
const id = parseObject(body).id;
|
|
1068
|
+
return typeof id === "string" && isDriveID(id) ? id : "";
|
|
1069
|
+
} catch {
|
|
1070
|
+
return "";
|
|
1071
|
+
}
|
|
1072
|
+
}
|
|
1073
|
+
async function retryBeforeSend(fence, kind, reason) {
|
|
1074
|
+
try {
|
|
1075
|
+
await fence.recordNotSent();
|
|
1076
|
+
} catch {
|
|
1077
|
+
return newMutationRetry(docsFailure("createDocument", "AVAILABILITY", "Dex could not record a pre-send retry"));
|
|
1078
|
+
}
|
|
1079
|
+
return newMutationRetry(docsFailure("createDocument", kind, reason));
|
|
1080
|
+
}
|
|
1081
|
+
function validateCreateInput(input, limit) {
|
|
1082
|
+
if (!goHasNonSpace(input.title) || Buffer.byteLength(input.title) > 1024 || /[\n\v]/.test(input.title)) throw new TypeError("title must be 1 to 1024 bytes on one line");
|
|
1083
|
+
validateWriteText("title", input.title);
|
|
1084
|
+
if (input.parentFolderId && !isDriveID(input.parentFolderId)) throw new TypeError("parentFolderId must be a Drive folder ID or root");
|
|
1085
|
+
const format = input.initialTextFormat || "plainText";
|
|
1086
|
+
if (format !== "plainText" && format !== "markdown") throw new TypeError("initialTextFormat must be plainText or markdown");
|
|
1087
|
+
if (Buffer.byteLength(input.initialText ?? "") > limit) throw new TypeError("initialText exceeds the configured text limit");
|
|
1088
|
+
validateWriteText("initialText", input.initialText ?? "");
|
|
1089
|
+
return format;
|
|
1090
|
+
}
|
|
1091
|
+
function buildCreateRequest(client, input, format, key) {
|
|
1092
|
+
const metadata = { appProperties: { dexIdempotencyKey: key }, mimeType: "application/vnd.google-apps.document", name: input.title, ...input.parentFolderId ? { parents: [input.parentFolderId] } : {} };
|
|
1093
|
+
const encoded = JSON.stringify(metadata);
|
|
1094
|
+
if (!input.initialText) return { url: `${client.driveBaseURL}/files?${goQuery({ fields: fileFields, supportsAllDrives: "true" })}`, body: Buffer.from(encoded), contentType: "application/json; charset=UTF-8" };
|
|
1095
|
+
const boundary = randomBytes(18).toString("hex");
|
|
1096
|
+
const body = Buffer.from(`--${boundary}\r
|
|
1097
|
+
Content-Type: application/json; charset=UTF-8\r
|
|
1098
|
+
\r
|
|
1099
|
+
${encoded}\r
|
|
1100
|
+
--${boundary}\r
|
|
1101
|
+
Content-Type: ${format === "markdown" ? "text/markdown" : "text/plain"}; charset=UTF-8\r
|
|
1102
|
+
\r
|
|
1103
|
+
${input.initialText}\r
|
|
1104
|
+
--${boundary}--\r
|
|
1105
|
+
`);
|
|
1106
|
+
return { url: `${client.driveUploadBaseURL}/files?${goQuery({ uploadType: "multipart", fields: fileFields, supportsAllDrives: "true" })}`, body, contentType: `multipart/related; boundary=${boundary}` };
|
|
1107
|
+
}
|
|
1108
|
+
function decodeEarlierDocument(body) {
|
|
1109
|
+
const value = parseObject(body);
|
|
1110
|
+
const files = arrayField(value, "files", []);
|
|
1111
|
+
let document;
|
|
1112
|
+
for (const file of files) {
|
|
1113
|
+
const current = convertCreatedDocument(objectValue(file));
|
|
1114
|
+
if (!document || Date.parse(current.createdTime ?? "0001-01-01T00:00:00Z") < Date.parse(document.createdTime ?? "0001-01-01T00:00:00Z")) document = current;
|
|
1115
|
+
}
|
|
1116
|
+
if (value.incompleteSearch != null && typeof value.incompleteSearch !== "boolean") throw new TypeError("incompleteSearch is invalid");
|
|
1117
|
+
return { ...document ? { document } : {}, incomplete: value.incompleteSearch === true };
|
|
1118
|
+
}
|
|
1119
|
+
function convertCreatedDocument(value) {
|
|
1120
|
+
const id = stringField(value, "id", "");
|
|
1121
|
+
if (!isDriveID(id) || stringField(value, "mimeType", "") !== "application/vnd.google-apps.document") throw new TypeError("file resource is not a Google Doc with a valid ID");
|
|
1122
|
+
const parents = arrayField(value, "parents", []).map((item) => {
|
|
1123
|
+
if (typeof item !== "string") throw new TypeError("parent ID is invalid");
|
|
1124
|
+
return item;
|
|
1125
|
+
});
|
|
1126
|
+
const createdTime = stringField(value, "createdTime", "0001-01-01T00:00:00Z");
|
|
1127
|
+
if (value.trashed != null && typeof value.trashed !== "boolean") throw new TypeError("trashed is invalid");
|
|
1128
|
+
const document = { documentId: id, title: stringField(value, "name", ""), ...parents.length ? { parents } : {}, ...stringField(value, "webViewLink", "") ? { webViewLink: stringField(value, "webViewLink") } : {}, ...createdTime !== "0001-01-01T00:00:00Z" ? { createdTime } : {}, ...value.trashed === true ? { isTrashed: true } : {} };
|
|
1129
|
+
return CreatedDocumentSchema.parse(document);
|
|
1130
|
+
}
|
|
1131
|
+
function createLookupSignal(call) {
|
|
1132
|
+
const deadline = call.context.deadline?.getTime();
|
|
1133
|
+
const remaining = deadline === void 0 ? 25e3 : Math.max(0, deadline - Date.now());
|
|
1134
|
+
const margin = deadline === void 0 ? 0 : Math.min(1e3, Math.max(1, remaining / 10));
|
|
1135
|
+
return AbortSignal.any([call.context.cancellationSignal, AbortSignal.timeout(Math.max(0, remaining - margin))]);
|
|
1136
|
+
}
|
|
1137
|
+
|
|
1138
|
+
// src/client.ts
|
|
1139
|
+
var DocsRequestError = class extends Error {
|
|
1140
|
+
/** Whether a provider write provably never reached the provider. */
|
|
1141
|
+
beforeSend;
|
|
1142
|
+
/** Whether the accepted response exceeded the configured limit. */
|
|
1143
|
+
tooLarge;
|
|
1144
|
+
/** HTTP status if a response was received. */
|
|
1145
|
+
status;
|
|
1146
|
+
/** Response headers if a response was received. */
|
|
1147
|
+
headers;
|
|
1148
|
+
/** Capture only safe transport facts for branch classification. */
|
|
1149
|
+
constructor(beforeSend, tooLarge = false, status = 0, headers = {}) {
|
|
1150
|
+
super("provider request failed");
|
|
1151
|
+
this.beforeSend = beforeSend;
|
|
1152
|
+
this.tooLarge = tooLarge;
|
|
1153
|
+
this.status = status;
|
|
1154
|
+
this.headers = headers;
|
|
1155
|
+
}
|
|
1156
|
+
};
|
|
1157
|
+
var DocsClient2 = class {
|
|
1158
|
+
/** Documents API root including /v1/documents. */
|
|
1159
|
+
documentsBaseURL;
|
|
1160
|
+
/** Drive files API root. */
|
|
1161
|
+
driveBaseURL;
|
|
1162
|
+
/** Drive upload API root. */
|
|
1163
|
+
driveUploadBaseURL;
|
|
1164
|
+
/** Maximum accepted successful response size. */
|
|
1165
|
+
maxResponseBytes;
|
|
1166
|
+
/** Maximum UTF-8 text size. */
|
|
1167
|
+
maxTextBytes;
|
|
1168
|
+
#credentials;
|
|
1169
|
+
#refreshDriver;
|
|
1170
|
+
#transport;
|
|
1171
|
+
#now;
|
|
1172
|
+
/** Apply manifest defaults and bind required host dependencies. */
|
|
1173
|
+
constructor(config, credentials, options = {}) {
|
|
1174
|
+
if (!credentials) throw new TypeError("credential provider is required");
|
|
1175
|
+
const docsEndpoint = validateBaseURL(config.docsEndpoint || "https://docs.googleapis.com");
|
|
1176
|
+
const driveEndpoint = validateBaseURL(config.driveEndpoint || "https://www.googleapis.com");
|
|
1177
|
+
const maxResponseBytes = config.maxResponseBytes ?? 8388608;
|
|
1178
|
+
const maxTextBytes = config.maxTextBytes ?? 1048576;
|
|
1179
|
+
if (!Number.isSafeInteger(maxResponseBytes) || maxResponseBytes < 1) throw new TypeError("Google Docs response limit must be positive");
|
|
1180
|
+
if (!Number.isSafeInteger(maxTextBytes) || maxTextBytes < 1 || maxTextBytes > 4194304) throw new TypeError("Google Docs text limit must be from 1 to 4194304 bytes");
|
|
1181
|
+
this.documentsBaseURL = `${docsEndpoint}/v1/documents`;
|
|
1182
|
+
this.driveBaseURL = `${driveEndpoint}/drive/v3`;
|
|
1183
|
+
this.driveUploadBaseURL = `${driveEndpoint}/upload/drive/v3`;
|
|
1184
|
+
this.maxResponseBytes = maxResponseBytes;
|
|
1185
|
+
this.maxTextBytes = maxTextBytes;
|
|
1186
|
+
this.#credentials = credentials;
|
|
1187
|
+
this.#now = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
1188
|
+
this.#transport = options.transport ?? sendProviderRequest;
|
|
1189
|
+
this.#refreshDriver = options.refreshDriver ?? new ManifestCredentialRefreshDriver({
|
|
1190
|
+
providerName: "google-docs",
|
|
1191
|
+
auth: Authorization,
|
|
1192
|
+
credentialFields: CredentialFields,
|
|
1193
|
+
now: this.#now
|
|
1194
|
+
});
|
|
1195
|
+
}
|
|
1196
|
+
/** Bind the getDocumentText operation. */
|
|
1197
|
+
getDocumentText() {
|
|
1198
|
+
return new GetDocumentTextOperation(this);
|
|
1199
|
+
}
|
|
1200
|
+
/** Bind the createDocument operation. */
|
|
1201
|
+
createDocument() {
|
|
1202
|
+
return new CreateDocumentOperation(this);
|
|
1203
|
+
}
|
|
1204
|
+
/** Bind the replaceDocumentText operation. */
|
|
1205
|
+
replaceDocumentText() {
|
|
1206
|
+
return new ReplaceDocumentTextOperation(this);
|
|
1207
|
+
}
|
|
1208
|
+
/** Bind the appendText operation. */
|
|
1209
|
+
appendText() {
|
|
1210
|
+
return new AppendTextOperation(this);
|
|
1211
|
+
}
|
|
1212
|
+
/** Resolve the current access token, including a host-coordinated refresh. */
|
|
1213
|
+
/**
|
|
1214
|
+
* Resolve one call's credentials. Throws ReauthorizationRequiredError when the connection must be
|
|
1215
|
+
* reconnected or holds an unusable credential, and a TypeError for an outage a later attempt may clear.
|
|
1216
|
+
*/
|
|
1217
|
+
async resolveCredentials(call) {
|
|
1218
|
+
let credentials;
|
|
1219
|
+
try {
|
|
1220
|
+
credentials = await resolveCredential(this.#credentials, call, this.#refreshDriver, call.context.cancellationSignal);
|
|
1221
|
+
} catch (error) {
|
|
1222
|
+
if (isTerminalCredentialError(error)) throw new ReauthorizationRequiredError2();
|
|
1223
|
+
throw new TypeError("connection credentials are unavailable");
|
|
1224
|
+
}
|
|
1225
|
+
if (!isHeaderSafeCredential(credentials.accessToken?.reveal() ?? "") || !["google-oauth", "workspace-domain-delegation", ""].includes(credentials.authMethodId ?? "")) throw new ReauthorizationRequiredError2();
|
|
1226
|
+
return credentials;
|
|
1227
|
+
}
|
|
1228
|
+
/** Ask the host to refresh after one rejected access token. */
|
|
1229
|
+
/** Throws ReauthorizationRequiredError for a terminal or unusable refresh, and a TypeError for a transient one. */
|
|
1230
|
+
async refreshCredentialsAfterRejection(call) {
|
|
1231
|
+
let credentials;
|
|
1232
|
+
try {
|
|
1233
|
+
credentials = await resolveCredentialAfterRejection(this.#credentials, call, this.#refreshDriver, call.context.cancellationSignal);
|
|
1234
|
+
} catch (error) {
|
|
1235
|
+
if (isTerminalCredentialError(error)) throw new ReauthorizationRequiredError2();
|
|
1236
|
+
throw new TypeError("connection credentials are temporarily unavailable");
|
|
1237
|
+
}
|
|
1238
|
+
if (!isHeaderSafeCredential(credentials.accessToken?.reveal() ?? "")) throw new ReauthorizationRequiredError2();
|
|
1239
|
+
return credentials;
|
|
1240
|
+
}
|
|
1241
|
+
/** Send one request; an idempotent request may refresh once after a 401. */
|
|
1242
|
+
async request(call, credentials, method, url, body, contentType, singleDispatch = false, signal) {
|
|
1243
|
+
let current = credentials;
|
|
1244
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
1245
|
+
const token = current.accessToken?.reveal() ?? "";
|
|
1246
|
+
if (!isHeaderSafeCredential(token)) throw new DocsRequestError(true);
|
|
1247
|
+
const request = {
|
|
1248
|
+
url,
|
|
1249
|
+
method,
|
|
1250
|
+
headers: { Authorization: `Bearer ${token}`, ...contentType ? { "Content-Type": contentType } : {} },
|
|
1251
|
+
...body ? { body } : {},
|
|
1252
|
+
maxResponseBytes: this.maxResponseBytes,
|
|
1253
|
+
maxErrorResponseBytes: Math.min(Number.MAX_SAFE_INTEGER, Math.max(this.maxResponseBytes, 65536) + 1),
|
|
1254
|
+
addressPolicy: "unrestricted",
|
|
1255
|
+
timeoutMs: 25e3,
|
|
1256
|
+
...signal ? { signal } : { signal: call.context.cancellationSignal }
|
|
1257
|
+
};
|
|
1258
|
+
let response;
|
|
1259
|
+
try {
|
|
1260
|
+
response = await this.#transport(request);
|
|
1261
|
+
} catch (error) {
|
|
1262
|
+
if (error instanceof BodyTooLargeError) {
|
|
1263
|
+
if (error.status && (error.status < 200 || error.status >= 300)) response = { status: error.status, headers: error.headers ?? {}, body: new Uint8Array(), isErrorBodyTooLarge: true };
|
|
1264
|
+
else throw new DocsRequestError(false, true, error.status ?? 0, error.headers ?? {});
|
|
1265
|
+
} else {
|
|
1266
|
+
const isBeforeSend = !!error && typeof error === "object" && ("beforeSend" in error && error.beforeSend === true || "isProvablyNotSent" in error && error.isProvablyNotSent === true);
|
|
1267
|
+
const isHeaderFailure = error instanceof ProviderTransportError || error instanceof ProviderStalledError;
|
|
1268
|
+
throw new DocsRequestError(isBeforeSend, false, isHeaderFailure ? error.status ?? 0 : 0, isHeaderFailure ? error.headers ?? {} : {});
|
|
1269
|
+
}
|
|
1270
|
+
}
|
|
1271
|
+
if (response.status >= 200 && response.status < 300 && response.body.byteLength > this.maxResponseBytes) {
|
|
1272
|
+
throw new DocsRequestError(false, true, response.status, response.headers);
|
|
1273
|
+
}
|
|
1274
|
+
if ((response.status < 200 || response.status >= 300) && response.body.byteLength > Math.max(this.maxResponseBytes, 65536)) {
|
|
1275
|
+
response = { ...response, body: new Uint8Array(), isErrorBodyTooLarge: true };
|
|
1276
|
+
}
|
|
1277
|
+
if (response.status !== 401 || attempt !== 0 || singleDispatch || !("resolveAfterRejection" in this.#credentials)) return response;
|
|
1278
|
+
try {
|
|
1279
|
+
current = await resolveCredentialAfterRejection(this.#credentials, call, this.#refreshDriver, call.context.cancellationSignal);
|
|
1280
|
+
if (!isHeaderSafeCredential(current.accessToken?.reveal() ?? "")) return response;
|
|
1281
|
+
} catch {
|
|
1282
|
+
return response;
|
|
1283
|
+
}
|
|
1284
|
+
}
|
|
1285
|
+
throw new DocsRequestError(true);
|
|
1286
|
+
}
|
|
1287
|
+
/** Return a receipt with only provider-safe identifiers. */
|
|
1288
|
+
receipt(call, response, objectID = "") {
|
|
1289
|
+
return { callId: call.id, ...call.idempotencyKey ? { idempotencyKey: call.idempotencyKey } : {}, provider: "google-docs", providerObjectId: objectID, providerRequestId: header(response?.headers ?? {}, "x-goog-request-id") || header(response?.headers ?? {}, "x-request-id"), observedAt: this.#now().toISOString() };
|
|
1290
|
+
}
|
|
1291
|
+
/** Return the observation clock for Retry-After dates. */
|
|
1292
|
+
now() {
|
|
1293
|
+
return this.#now();
|
|
1294
|
+
}
|
|
1295
|
+
};
|
|
1296
|
+
function isTerminalCredentialError(error) {
|
|
1297
|
+
return error instanceof ReauthorizationRequiredError2 || error instanceof ObjectNotFoundError || error instanceof ConnectionNotSelectedError || error instanceof CredentialBrokerRejectedError || isCredentialMaterialError(error);
|
|
1298
|
+
}
|
|
1299
|
+
function header(headers, name) {
|
|
1300
|
+
const value = headers[name] ?? headers[name.toLowerCase()] ?? headers[name.toUpperCase()];
|
|
1301
|
+
return Array.isArray(value) ? value[0] ?? "" : value ?? "";
|
|
1302
|
+
}
|
|
1303
|
+
function docsFailure(operation, kind, message) {
|
|
1304
|
+
return { provider: "google-docs", operation, kind, message };
|
|
1305
|
+
}
|
|
1306
|
+
function statusFailureKind(status, tokens) {
|
|
1307
|
+
if (status === 401) return "AUTHENTICATION";
|
|
1308
|
+
if (isRateLimit(status, tokens)) return "RATE_LIMIT";
|
|
1309
|
+
if (status === 403) return "AUTHORIZATION";
|
|
1310
|
+
if (status === 404) return "NOT_FOUND";
|
|
1311
|
+
if (status === 409) return "CONFLICT";
|
|
1312
|
+
if (status >= 500 || status === 408) return "AVAILABILITY";
|
|
1313
|
+
return "PROVIDER_REJECTION";
|
|
1314
|
+
}
|
|
1315
|
+
function isRateLimit(status, tokens) {
|
|
1316
|
+
return status === 429 || status === 403 && tokens.some((token) => ["rateLimitExceeded", "userRateLimitExceeded", "RATE_LIMIT_EXCEEDED"].includes(token));
|
|
1317
|
+
}
|
|
1318
|
+
function isRetryable(status, tokens) {
|
|
1319
|
+
return status >= 500 || status === 408 || isRateLimit(status, tokens);
|
|
1320
|
+
}
|
|
1321
|
+
function googleTokens(response) {
|
|
1322
|
+
return readErrorTokens(response.body, ["/error/errors/0/reason", "/error/status", "/error/details/0/reason"]);
|
|
1323
|
+
}
|
|
1324
|
+
function retryAfterMs(response, now) {
|
|
1325
|
+
return parseRetryAfter(header(response.headers, "retry-after"), now);
|
|
1326
|
+
}
|
|
1327
|
+
function goQuery(values) {
|
|
1328
|
+
return Object.keys(values).sort((left, right) => Buffer.compare(Buffer.from(left), Buffer.from(right))).flatMap((key) => (Array.isArray(values[key]) ? values[key] : [values[key]]).map((value) => `${goQueryEscape(key)}=${goQueryEscape(value)}`)).join("&");
|
|
1329
|
+
}
|
|
1330
|
+
function goQueryEscape(value) {
|
|
1331
|
+
return encodeURIComponent(value).replace(/[!'()*]/g, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`).replace(/%20/g, "+");
|
|
1332
|
+
}
|
|
1333
|
+
function goPathEscape(value) {
|
|
1334
|
+
let escaped = "";
|
|
1335
|
+
for (const byte of Buffer.from(value, "utf8")) {
|
|
1336
|
+
const character = String.fromCharCode(byte);
|
|
1337
|
+
escaped += /[A-Za-z0-9._~$&+=:@-]/.test(character) ? character : `%${byte.toString(16).toUpperCase().padStart(2, "0")}`;
|
|
1338
|
+
}
|
|
1339
|
+
return escaped;
|
|
1340
|
+
}
|
|
1341
|
+
|
|
1342
|
+
// src/project.ts
|
|
1343
|
+
function newProjectConnection(project, connectionName, options = {}) {
|
|
1344
|
+
if (!project) throw new TypeError("Google Docs project configuration is required");
|
|
1345
|
+
const reference = ConnectionRefSchema.parse({ provider: ProviderID, name: connectionName });
|
|
1346
|
+
const entry = project.configuration.connections.find((connection) => connection.connectorId === ConnectorID && connection.connectionName === connectionName);
|
|
1347
|
+
if (!entry || entry.provider !== ProviderID) throw new TypeError("Google Docs project connection is not configured");
|
|
1348
|
+
const config = ConfigSchema.parse(entry.configuration);
|
|
1349
|
+
const provider = newProjectCredentialProvider(project, connectionName, decodeCredentials, encodeCredentials, decodeSharedCredentials);
|
|
1350
|
+
return newConnection(new DocsClient2(config, provider, options), reference);
|
|
1351
|
+
}
|
|
1352
|
+
function encodeCredentials(credentials) {
|
|
1353
|
+
const fields = { auth_method: credentials.authMethodId || "google-oauth" };
|
|
1354
|
+
for (const [name, value] of [
|
|
1355
|
+
["access_token", credentials.accessToken?.reveal()],
|
|
1356
|
+
["delegated_user", credentials.delegatedUser],
|
|
1357
|
+
["oauth_client_id", credentials.oauthClientId],
|
|
1358
|
+
["oauth_client_secret", credentials.oauthClientSecret?.reveal()],
|
|
1359
|
+
["refresh_token", credentials.refreshToken?.reveal()],
|
|
1360
|
+
["service_account_key", credentials.serviceAccountKey?.reveal()]
|
|
1361
|
+
]) if (value) fields[name] = value;
|
|
1362
|
+
return fields;
|
|
1363
|
+
}
|
|
1364
|
+
export {
|
|
1365
|
+
AppendTextBranch,
|
|
1366
|
+
AppendTextBranchAppended,
|
|
1367
|
+
AppendTextBranchDefect,
|
|
1368
|
+
AppendTextBranchInvalidResponse,
|
|
1369
|
+
AppendTextBranchNotFound,
|
|
1370
|
+
AppendTextBranchProviderRejected,
|
|
1371
|
+
AppendTextBranchRevisionChanged,
|
|
1372
|
+
AppendTextDefinition,
|
|
1373
|
+
AppendTextInputSchema,
|
|
1374
|
+
AppendTextMetadata,
|
|
1375
|
+
AppendTextOperation,
|
|
1376
|
+
AppendTextOutputSchema,
|
|
1377
|
+
ConfigSchema,
|
|
1378
|
+
Connection,
|
|
1379
|
+
ConnectorID,
|
|
1380
|
+
CreateDocumentBranch,
|
|
1381
|
+
CreateDocumentBranchCreated,
|
|
1382
|
+
CreateDocumentBranchDefect,
|
|
1383
|
+
CreateDocumentBranchInvalidResponse,
|
|
1384
|
+
CreateDocumentBranchProviderRejected,
|
|
1385
|
+
CreateDocumentBranchUncertain,
|
|
1386
|
+
CreateDocumentDefinition,
|
|
1387
|
+
CreateDocumentInputSchema,
|
|
1388
|
+
CreateDocumentMetadata,
|
|
1389
|
+
CreateDocumentOperation,
|
|
1390
|
+
CreateDocumentOutputSchema,
|
|
1391
|
+
CreatedDocumentSchema,
|
|
1392
|
+
CredentialMaterialError,
|
|
1393
|
+
DocsClient2 as DocsClient,
|
|
1394
|
+
GetDocumentTextBranch,
|
|
1395
|
+
GetDocumentTextBranchDefect,
|
|
1396
|
+
GetDocumentTextBranchInvalidResponse,
|
|
1397
|
+
GetDocumentTextBranchNotFound,
|
|
1398
|
+
GetDocumentTextBranchProviderRejected,
|
|
1399
|
+
GetDocumentTextBranchRead,
|
|
1400
|
+
GetDocumentTextBranchTooLarge,
|
|
1401
|
+
GetDocumentTextDefinition,
|
|
1402
|
+
GetDocumentTextInputSchema,
|
|
1403
|
+
GetDocumentTextMetadata,
|
|
1404
|
+
GetDocumentTextOperation,
|
|
1405
|
+
GetDocumentTextOutputSchema,
|
|
1406
|
+
PlaceholderReplacementResultSchema,
|
|
1407
|
+
PlaceholderReplacementSchema,
|
|
1408
|
+
ProviderID,
|
|
1409
|
+
ReplaceDocumentTextBranch,
|
|
1410
|
+
ReplaceDocumentTextBranchDefect,
|
|
1411
|
+
ReplaceDocumentTextBranchInvalidResponse,
|
|
1412
|
+
ReplaceDocumentTextBranchNotFound,
|
|
1413
|
+
ReplaceDocumentTextBranchPlaceholderNotFound,
|
|
1414
|
+
ReplaceDocumentTextBranchProviderRejected,
|
|
1415
|
+
ReplaceDocumentTextBranchReplaced,
|
|
1416
|
+
ReplaceDocumentTextBranchRevisionChanged,
|
|
1417
|
+
ReplaceDocumentTextDefinition,
|
|
1418
|
+
ReplaceDocumentTextInputSchema,
|
|
1419
|
+
ReplaceDocumentTextMetadata,
|
|
1420
|
+
ReplaceDocumentTextOperation,
|
|
1421
|
+
ReplaceDocumentTextOutputSchema,
|
|
1422
|
+
decodeCredentials,
|
|
1423
|
+
decodeSharedCredentials,
|
|
1424
|
+
isCredentialMaterialError,
|
|
1425
|
+
newAppendTextStep,
|
|
1426
|
+
newConnection,
|
|
1427
|
+
newConnectionWithOperations,
|
|
1428
|
+
newCreateDocumentStep,
|
|
1429
|
+
newGetDocumentTextStep,
|
|
1430
|
+
newProjectConnection,
|
|
1431
|
+
newReplaceDocumentTextStep
|
|
1432
|
+
};
|