@sdflc/backend-helpers 1.0.148 → 1.0.150

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.
@@ -0,0 +1,390 @@
1
+ // ./src/gateways/ZohoCrmGw.ts
2
+ //
3
+ // Zoho CRM (https://www.zoho.com/crm/developer/docs/api/v8/) — connecting a host's Zoho org with Zoho's OAuth 2.0 and the
4
+ // calls that put a person into it: a Contact or a Lead created or updated by email, tags on it, and a note.
5
+ //
6
+ // const zoho = new ZohoCrmGw().configure({ clientId, clientSecret });
7
+ // const url = zoho.authorizeUrl({ state, redirectUri }); // send the host there
8
+ // const tokens = await zoho.exchangeCode(code, redirectUri, accountsServer); // on the way back
9
+ // const org = { apiDomain: tokens.getDataFirst().apiDomain, accessToken: tokens.getDataFirst().accessToken };
10
+ // const rec = await zoho.upsertRecord(org, 'Contacts', { Email, Last_Name });
11
+ // await zoho.addTags(org, 'Contacts', rec.getDataFirst().recordId, ['Volunteers']);
12
+ // await zoho.addNote(org, 'Contacts', rec.getDataFirst().recordId, 'Registered for …');
13
+ //
14
+ // The settings are the APP's (a server-based client in Zoho's API Console, "Multi DC" on): its client id and secret. An
15
+ // org's own tokens and API domain are passed per call (`ZohoCrmConnection`) — one gateway serves every connected org.
16
+ //
17
+ // ⚠ ZOHO HAS DATA CENTRES. The consent screen starts at accounts.zoho.com and Zoho moves the host to their own; the way
18
+ // back names it (`accounts-server`), and the tokens must be asked of THAT server — and the API called at the
19
+ // `api_domain` the tokens came with. Both arrive from outside (a query string, a reply), so both are checked against
20
+ // Zoho's own hosts (`zohoAccountsServerOf`, `zohoApiDomainOf`) before anything is sent there.
21
+ // ⚠ Zoho's token endpoint answers a refusal with HTTP 200 and `{ "error": "invalid_code" }` — read the body, not the status.
22
+ // ⚠ A refresh does NOT return a new refresh token: the one the org gave keeps working until the host revokes it.
23
+ // ⚠ The client secret and every token are scrubbed out of every error and reply.
24
+ import { OP_RESULT_CODES, OpResult } from '@sdflc/api-helpers';
25
+ import { BaseExternalApiGateway } from './BaseExternalApiGateway';
26
+ /** The modules a person can be added to. */
27
+ export const ZOHO_CRM_MODULES = ['Contacts', 'Leads'];
28
+ export const ZOHO_AUTHORIZE_URL = 'https://accounts.zoho.com/oauth/v2/auth';
29
+ export const ZOHO_CRM_API_VERSION = 'v8';
30
+ /**
31
+ * What a connection asks for: Contacts and Leads (find, create, update, tag), notes, and the org's name. Nothing that
32
+ * deletes, nothing of the org's settings but reading its tags.
33
+ */
34
+ export const ZOHO_CRM_SCOPES = [
35
+ 'ZohoCRM.modules.contacts.ALL',
36
+ 'ZohoCRM.modules.leads.ALL',
37
+ 'ZohoCRM.modules.notes.CREATE',
38
+ 'ZohoCRM.settings.tags.READ',
39
+ 'ZohoCRM.org.READ',
40
+ ];
41
+ /** Zoho's limit on a tag's name. */
42
+ export const ZOHO_TAG_MAX = 50;
43
+ /** Zoho's accounts servers, one per data centre (US, EU, IN, AU, CN, JP, CA, SA, UK, AE, SG). */
44
+ const ACCOUNTS_HOST = /^accounts\.(zoho\.(com|eu|in|com\.au|com\.cn|jp|sa|uk|ae|sg)|zohocloud\.ca)$/;
45
+ /** Zoho's API domains: production (www), sandbox and developer orgs, one per data centre. */
46
+ const API_HOST = /^(www|sandbox|developer)\.zohoapis\.(com|eu|in|com\.au|com\.cn|jp|ca|sa|uk|ae|sg)$/;
47
+ const text = (value) => String(value ?? '').trim();
48
+ /** An https origin whose host passes `host`, or null (a path, a port, a user, plain http — anything else is refused). */
49
+ const originOf = (raw, host) => {
50
+ try {
51
+ const url = new URL(text(raw));
52
+ if (url.protocol !== 'https:' || url.port || url.username || url.password || !host.test(url.hostname)) {
53
+ return null;
54
+ }
55
+ return url.pathname === '/' && !url.search && !url.hash ? url.origin : null;
56
+ }
57
+ catch {
58
+ return null;
59
+ }
60
+ };
61
+ /** The accounts server the way back named, when it is one of Zoho's — else null. Pure. */
62
+ export const zohoAccountsServerOf = (raw) => originOf(raw, ACCOUNTS_HOST);
63
+ /** The API domain a token reply named, when it is one of Zoho's — else null. Pure. */
64
+ export const zohoApiDomainOf = (raw) => originOf(raw, API_HOST);
65
+ /** A record's id as Zoho writes it (digits). */
66
+ const RECORD_ID = /^\d{1,32}$/;
67
+ /** The token endpoint's refusals that mean the grant or the refresh token is no use (expired, used, revoked). */
68
+ export const ZOHO_TOKEN_ENDED_ERRORS = ['invalid_code', 'invalid_token'];
69
+ class ZohoCrmGw extends BaseExternalApiGateway {
70
+ constructor(props) {
71
+ super(props);
72
+ }
73
+ validateSettings(settings) {
74
+ const problems = [];
75
+ if (!text(settings.clientId)) {
76
+ problems.push('the client id is missing');
77
+ }
78
+ if (!text(settings.clientSecret)) {
79
+ problems.push('the client secret is missing');
80
+ }
81
+ return problems;
82
+ }
83
+ secretValues() {
84
+ const secret = text(this.settings.clientSecret);
85
+ return secret ? [secret] : [];
86
+ }
87
+ /**
88
+ * Zoho's error shapes: the token endpoint's `{ error, error_description? }`, the API's `{ code, message, details }` —
89
+ * whole, or per record inside `data[]` (an upsert's MANDATORY_NOT_FOUND names the field in `details.api_name`).
90
+ */
91
+ errorMessageOf(reply) {
92
+ const body = reply.body;
93
+ if (body && typeof body === 'object') {
94
+ if (typeof body.error === 'string') {
95
+ return [body.error, body.error_description].filter(Boolean).join(': ').slice(0, 500);
96
+ }
97
+ const said = zohoErrorOf(Array.isArray(body.data) ? body.data[0] : body);
98
+ if (said) {
99
+ return said;
100
+ }
101
+ }
102
+ return super.errorMessageOf(reply);
103
+ }
104
+ badConnection(org) {
105
+ if (!zohoApiDomainOf(org?.apiDomain)) {
106
+ return OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, null, 'The org has no Zoho API domain');
107
+ }
108
+ return text(org?.accessToken)
109
+ ? null
110
+ : OpResult.fail(OP_RESULT_CODES.UNAUTHORIZED, null, 'The org has no access token');
111
+ }
112
+ orgCall(org, method, path, json) {
113
+ return this.requestWithRetries({
114
+ url: `${zohoApiDomainOf(org.apiDomain)}/crm/${ZOHO_CRM_API_VERSION}${path}`,
115
+ method,
116
+ headers: { Authorization: `Zoho-oauthtoken ${text(org.accessToken)}`, Accept: 'application/json' },
117
+ ...(json === undefined ? {} : { json }),
118
+ secrets: [text(org.accessToken)],
119
+ });
120
+ }
121
+ /**
122
+ * A token call at the org's accounts server. ⚠ Zoho says no with HTTP 200 and `{ error }`: that is turned into a
123
+ * failure here — UNAUTHORIZED for a grant or refresh token that is no use (ZOHO_TOKEN_ENDED_ERRORS), TOO_MANY_REQUESTS
124
+ * for its throttle ("Access Denied" — at most 10 access tokens per refresh token in 10 minutes), else VALIDATION_FAILED
125
+ * (our client id, secret or redirect address). The reply rides on the failure with `error` set.
126
+ */
127
+ async tokenCall(accountsServer, form, secrets, keepRefreshToken = '') {
128
+ if (!this.isConfigured()) {
129
+ return this.notConfigured();
130
+ }
131
+ const server = zohoAccountsServerOf(accountsServer);
132
+ if (!server) {
133
+ return OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, null, "The accounts server is not one of Zoho's");
134
+ }
135
+ const result = await this.requestWithRetries({
136
+ url: `${server}/oauth/v2/token`,
137
+ method: 'POST',
138
+ headers: { Accept: 'application/json', 'Content-Type': 'application/x-www-form-urlencoded' },
139
+ body: new URLSearchParams({
140
+ ...form,
141
+ client_id: text(this.settings.clientId),
142
+ client_secret: text(this.settings.clientSecret),
143
+ }),
144
+ secrets,
145
+ });
146
+ const reply = result.getDataFirst();
147
+ const body = reply?.body ?? {};
148
+ // ⓘ Read on a 200 AND on a 4xx: Zoho has answered `invalid_code` both ways.
149
+ const error = reply && typeof body?.error === 'string' ? body.error : '';
150
+ if (result.didFail() && !error) {
151
+ return result;
152
+ }
153
+ if (error) {
154
+ const code = ZOHO_TOKEN_ENDED_ERRORS.includes(error)
155
+ ? OP_RESULT_CODES.UNAUTHORIZED
156
+ : /access denied/i.test(error) || /too many requests/i.test(text(body?.error_description))
157
+ ? OP_RESULT_CODES.TOO_MANY_REQUESTS
158
+ : OP_RESULT_CODES.VALIDATION_FAILED;
159
+ return OpResult.fail(code, [{ ...reply, error }], this.scrub(this.errorMessageOf(reply), secrets));
160
+ }
161
+ const accessToken = text(body?.access_token);
162
+ const refreshToken = text(body?.refresh_token) || keepRefreshToken;
163
+ const apiDomain = zohoApiDomainOf(body?.api_domain);
164
+ if (!accessToken || !refreshToken || !apiDomain) {
165
+ return OpResult.fail(OP_RESULT_CODES.FAILED, null, apiDomain || !accessToken
166
+ ? 'Zoho answered without the tokens'
167
+ : "Zoho answered with an API domain that is not one of Zoho's");
168
+ }
169
+ const expiresIn = Number(body?.expires_in) || 3600;
170
+ const tokens = {
171
+ accessToken,
172
+ refreshToken,
173
+ apiDomain,
174
+ expiresAt: new Date(Date.now() + expiresIn * 1000).toISOString(),
175
+ };
176
+ return OpResult.ok([tokens]);
177
+ }
178
+ /**
179
+ * Where to send the host to connect their org (Zoho's consent screen, which moves them to their own data centre). An
180
+ * offline grant (a refresh token), the consent asked every time (a reconnect gets a refresh token too). Pure; '' when
181
+ * the gateway is not configured.
182
+ */
183
+ authorizeUrl(args) {
184
+ if (!this.isConfigured()) {
185
+ return '';
186
+ }
187
+ const params = new URLSearchParams({
188
+ client_id: text(this.settings.clientId),
189
+ response_type: 'code',
190
+ scope: (args.scopes?.length ? args.scopes : ZOHO_CRM_SCOPES).join(','),
191
+ access_type: 'offline',
192
+ prompt: 'consent',
193
+ redirect_uri: text(args.redirectUri),
194
+ state: text(args.state),
195
+ });
196
+ return `${ZOHO_AUTHORIZE_URL}?${params.toString()}`;
197
+ }
198
+ /** The code Zoho sent back, exchanged at the host's accounts server. OK with a `ZohoCrmTokens`. Never throws. */
199
+ async exchangeCode(code, redirectUri, accountsServer) {
200
+ if (!text(code) || !text(redirectUri)) {
201
+ return OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, null, 'The code and the redirect address are needed');
202
+ }
203
+ return this.tokenCall(accountsServer, { grant_type: 'authorization_code', code: text(code), redirect_uri: text(redirectUri) }, [text(code)]);
204
+ }
205
+ /** A new access token for the org's refresh token (which stays as it is). OK with a `ZohoCrmTokens`. Never throws. */
206
+ async refreshTokens(refreshToken, accountsServer) {
207
+ if (!text(refreshToken)) {
208
+ return OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, null, 'The refresh token is needed');
209
+ }
210
+ return this.tokenCall(accountsServer, { grant_type: 'refresh_token', refresh_token: text(refreshToken) }, [text(refreshToken)], text(refreshToken));
211
+ }
212
+ /** Disconnects: the refresh token and the access tokens made with it stop working. OK with `{ revoked: true }`. */
213
+ async revoke(refreshToken, accountsServer) {
214
+ if (!this.isConfigured()) {
215
+ return this.notConfigured();
216
+ }
217
+ const server = zohoAccountsServerOf(accountsServer);
218
+ if (!server || !text(refreshToken)) {
219
+ return OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, null, "The refresh token and one of Zoho's accounts servers are needed");
220
+ }
221
+ const result = await this.requestWithRetries({
222
+ url: `${server}/oauth/v2/token/revoke`,
223
+ method: 'POST',
224
+ headers: { Accept: 'application/json', 'Content-Type': 'application/x-www-form-urlencoded' },
225
+ body: new URLSearchParams({ token: text(refreshToken) }),
226
+ secrets: [text(refreshToken)],
227
+ });
228
+ if (result.didFail()) {
229
+ return result;
230
+ }
231
+ const error = result.getDataFirst()?.body?.error;
232
+ return typeof error === 'string' && error
233
+ ? OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, result.getData(), `Zoho refused the revoke: ${error}`)
234
+ : OpResult.ok([{ revoked: true }]);
235
+ }
236
+ /** The org a connection reaches. OK with `{ id, name, domainName, type }` (type: production, sandbox, developer…). */
237
+ async getOrg(org) {
238
+ if (!this.isConfigured()) {
239
+ return this.notConfigured();
240
+ }
241
+ const bad = this.badConnection(org);
242
+ if (bad) {
243
+ return bad;
244
+ }
245
+ const result = await this.orgCall(org, 'GET', '/org');
246
+ if (result.didFail()) {
247
+ return result;
248
+ }
249
+ const row = result.getDataFirst()?.body?.org?.[0] ?? {};
250
+ return text(row.id)
251
+ ? OpResult.ok([
252
+ {
253
+ id: text(row.id),
254
+ name: text(row.company_name) || null,
255
+ domainName: text(row.domain_name) || null,
256
+ type: text(row.type) || null,
257
+ },
258
+ ])
259
+ : OpResult.fail(OP_RESULT_CODES.FAILED, null, 'Zoho answered without the org');
260
+ }
261
+ /**
262
+ * The record with this email in `module`, created or updated (Zoho's upsert, the email the only duplicate check; the
263
+ * org's workflow rules run, as for a record typed in). Only the fields given with a value are sent — an empty one never
264
+ * blanks what Zoho holds. OK with `{ recordId, created }`; a refused record (a mandatory field missing — its name in
265
+ * the message) fails VALIDATION_FAILED with the reply. Never throws.
266
+ */
267
+ async upsertRecord(org, module, fields) {
268
+ if (!this.isConfigured()) {
269
+ return this.notConfigured();
270
+ }
271
+ const bad = this.badConnection(org) ?? this.badModule(module);
272
+ if (bad) {
273
+ return bad;
274
+ }
275
+ const record = {};
276
+ for (const [name, value] of Object.entries(fields ?? {})) {
277
+ if (/^[A-Za-z][A-Za-z0-9_]{0,99}$/.test(name) && text(value)) {
278
+ record[name] = text(value);
279
+ }
280
+ }
281
+ if (!text(record.Email).includes('@')) {
282
+ return OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, null, 'The record has no email');
283
+ }
284
+ record.Email = record.Email.toLowerCase();
285
+ const result = await this.orgCall(org, 'POST', `/${module}/upsert`, {
286
+ data: [record],
287
+ duplicate_check_fields: ['Email'],
288
+ trigger: ['workflow'],
289
+ });
290
+ const row = this.recordOf(result);
291
+ if (row.failure) {
292
+ return row.failure;
293
+ }
294
+ return OpResult.ok([{ recordId: row.id, created: row.action === 'insert' }]);
295
+ }
296
+ /** Tags on a record (added to what it has; a tag the org does not have yet is made by Zoho). OK with `{ tags }`. */
297
+ async addTags(org, module, recordId, tags) {
298
+ if (!this.isConfigured()) {
299
+ return this.notConfigured();
300
+ }
301
+ const names = Array.from(new Set((tags ?? []).map((t) => text(t).slice(0, ZOHO_TAG_MAX)).filter(Boolean)));
302
+ const bad = this.badConnection(org) ?? this.badModule(module) ?? this.badRecord(recordId);
303
+ if (bad) {
304
+ return bad;
305
+ }
306
+ if (names.length === 0) {
307
+ return OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, null, 'At least one tag is needed');
308
+ }
309
+ const result = await this.orgCall(org, 'POST', `/${module}/${text(recordId)}/actions/add_tags`, {
310
+ tags: names.map((name) => ({ name })),
311
+ over_write: false,
312
+ });
313
+ const row = this.recordOf(result);
314
+ return row.failure ?? OpResult.ok([{ tags: names }]);
315
+ }
316
+ /** A note on a record (plain text; the title optional). OK with `{ noteId }`. Never throws. */
317
+ async addNote(org, module, recordId, content, title = '') {
318
+ if (!this.isConfigured()) {
319
+ return this.notConfigured();
320
+ }
321
+ const bad = this.badConnection(org) ?? this.badModule(module) ?? this.badRecord(recordId);
322
+ if (bad) {
323
+ return bad;
324
+ }
325
+ if (!text(content)) {
326
+ return OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, null, 'The note is needed');
327
+ }
328
+ const result = await this.orgCall(org, 'POST', `/${module}/${text(recordId)}/Notes`, {
329
+ data: [
330
+ {
331
+ ...(text(title) ? { Note_Title: text(title).slice(0, 120) } : {}),
332
+ Note_Content: String(content),
333
+ Parent_Id: { module: { api_name: module }, id: text(recordId) },
334
+ },
335
+ ],
336
+ });
337
+ const row = this.recordOf(result);
338
+ return row.failure ?? OpResult.ok([{ noteId: row.id || null }]);
339
+ }
340
+ /** Can the connection read `module`? (One record asked for, nothing written.) OK with `{ ok: true }`. Never throws. */
341
+ async verify(org, module) {
342
+ if (!this.isConfigured()) {
343
+ return this.notConfigured();
344
+ }
345
+ const bad = this.badConnection(org) ?? this.badModule(module);
346
+ if (bad) {
347
+ return bad;
348
+ }
349
+ const result = await this.orgCall(org, 'GET', `/${module}?fields=Email&per_page=1`);
350
+ return result.didFail() ? result : OpResult.ok([{ ok: true }]);
351
+ }
352
+ badModule(module) {
353
+ return ZOHO_CRM_MODULES.includes(String(module))
354
+ ? null
355
+ : OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, null, `The module is one of ${ZOHO_CRM_MODULES.join(', ')}`);
356
+ }
357
+ badRecord(recordId) {
358
+ return RECORD_ID.test(text(recordId))
359
+ ? null
360
+ : OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, null, 'A record id is a number');
361
+ }
362
+ /**
363
+ * The one record a write answered: its id and action — or the failure. ⓘ Zoho answers a write 200 / 201 / 202, or 207
364
+ * (multi-status) with the record's own refusal inside `data[0]`: a 2xx is not yet a success.
365
+ */
366
+ recordOf(result) {
367
+ if (result.didFail()) {
368
+ return { id: '', action: '', failure: result };
369
+ }
370
+ const reply = result.getDataFirst();
371
+ const row = reply?.body?.data?.[0];
372
+ if (!row || String(row.status ?? '').toLowerCase() !== 'success') {
373
+ return {
374
+ id: '',
375
+ action: '',
376
+ failure: OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, [reply], zohoErrorOf(row) || 'Zoho answered without the record'),
377
+ };
378
+ }
379
+ return { id: text(row.details?.id), action: text(row.action), failure: null };
380
+ }
381
+ }
382
+ /** A Zoho error object in words: "MANDATORY_NOT_FOUND: required field not found (Last_Name)". '' when it is not one. */
383
+ const zohoErrorOf = (e) => {
384
+ if (!e || typeof e !== 'object' || (!e.code && !e.message)) {
385
+ return '';
386
+ }
387
+ const field = text(e.details?.api_name);
388
+ return `${[e.code, e.message].filter(Boolean).join(': ')}${field ? ` (${field})` : ''}`.slice(0, 500);
389
+ };
390
+ export { ZohoCrmGw };
@@ -8,5 +8,7 @@ export * from './DiscordWebhookGw';
8
8
  export * from './HubSpotGw';
9
9
  export * from './MailchimpGw';
10
10
  export * from './QuickBooksGw';
11
+ export * from './GoogleSheetsGw';
11
12
  export * from './HttpWebhookGw';
12
13
  export * from './guardedFetch';
14
+ export * from './ZohoCrmGw';
@@ -8,5 +8,7 @@ export * from './DiscordWebhookGw';
8
8
  export * from './HubSpotGw';
9
9
  export * from './MailchimpGw';
10
10
  export * from './QuickBooksGw';
11
+ export * from './GoogleSheetsGw';
11
12
  export * from './HttpWebhookGw';
12
13
  export * from './guardedFetch';
14
+ export * from './ZohoCrmGw';
@@ -0,0 +1,85 @@
1
+ import { OpResult } from '@sdflc/api-helpers';
2
+ import { BaseExternalApiGatewayPropsInterface } from '../interfaces';
3
+ import { BaseExternalApiGateway, ExternalApiReply } from './BaseExternalApiGateway';
4
+ export interface GoogleSheetsSettings {
5
+ /** The service account's email (`…@<project>.iam.gserviceaccount.com`) — what the host shares the sheet with. */
6
+ clientEmail: string;
7
+ /** The service account's private key (PEM, as in its JSON key; `\n` escapes are read as line breaks). */
8
+ privateKey: string;
9
+ }
10
+ /** A tab as `getSpreadsheet` names it. */
11
+ export interface GoogleSheetTab {
12
+ sheetId: number;
13
+ title: string;
14
+ index: number;
15
+ rowCount: number;
16
+ columnCount: number;
17
+ frozenRowCount: number;
18
+ }
19
+ /** A spreadsheet as `getSpreadsheet` answers it. */
20
+ export interface GoogleSpreadsheet {
21
+ spreadsheetId: string;
22
+ title: string;
23
+ tabs: GoogleSheetTab[];
24
+ }
25
+ /** One range to write: an A1 range (`googleSheetRange`) and its rows. */
26
+ export interface GoogleSheetValues {
27
+ range: string;
28
+ values: unknown[][];
29
+ }
30
+ export declare const GOOGLE_TOKEN_URL = "https://oauth2.googleapis.com/token";
31
+ export declare const GOOGLE_SHEETS_API_URL = "https://sheets.googleapis.com/v4/spreadsheets";
32
+ /** The only scope the writer needs — the spreadsheets shared with the account, nothing else of the host's Drive. */
33
+ export declare const GOOGLE_SHEETS_SCOPE = "https://www.googleapis.com/auth/spreadsheets";
34
+ /**
35
+ * The spreadsheet id in what a host pasted — the address of the sheet (`…/spreadsheets/d/<id>/edit#gid=0`) or the id
36
+ * itself — or '' when it is neither. Pure.
37
+ */
38
+ export declare const googleSpreadsheetIdOf: (raw: unknown) => string;
39
+ /** A tab's name inside an A1 range: always quoted, a quote doubled (`It's` → `'It''s'`). Pure. */
40
+ export declare const googleSheetRange: (title: string, a1?: string) => string;
41
+ /** A column's letters from its 1-based number (1 → A, 27 → AA). Pure. */
42
+ export declare const googleSheetColumn: (n: number) => string;
43
+ /** Forget every cached access token (a test; a key revoked). */
44
+ export declare const forgetGoogleSheetsTokens: () => void;
45
+ declare class GoogleSheetsGw extends BaseExternalApiGateway<GoogleSheetsSettings> {
46
+ constructor(props?: BaseExternalApiGatewayPropsInterface<GoogleSheetsSettings>);
47
+ protected validateSettings(settings: Partial<GoogleSheetsSettings>): string[];
48
+ protected secretValues(): string[];
49
+ /** Google's error shapes: the API's `{ error: { code, message, status } }`, the token endpoint's `{ error, error_description }`. */
50
+ protected errorMessageOf(reply: ExternalApiReply): string;
51
+ private pemOf;
52
+ private cacheKey;
53
+ /** The signed assertion a token is asked for with, or null when the key cannot sign. */
54
+ private assertion;
55
+ /**
56
+ * A live access token for the account — the cached one, else a new one from Google (`fresh`: never the cached one).
57
+ * OK with `{ accessToken, expiresAt }`. Never throws.
58
+ */
59
+ accessToken(fresh?: boolean): Promise<OpResult>;
60
+ /** One API call with the account's token; a 401 forgets it and tries once more with a new one. */
61
+ private call;
62
+ private badId;
63
+ /**
64
+ * The spreadsheet's title and tabs (each with its size and frozen rows) — readable only when it is shared with the
65
+ * account (403 FORBIDDEN otherwise; 404 NOT_FOUND when there is no such spreadsheet). OK with a `GoogleSpreadsheet`.
66
+ */
67
+ getSpreadsheet(spreadsheetId: string): Promise<OpResult>;
68
+ /**
69
+ * The values of several ranges in ONE read, in the order asked, row by row, unformatted (a number stays a number);
70
+ * trailing empty cells and rows are left out, as Google does. OK with `{ valueRanges: [{ range, values }] }`.
71
+ */
72
+ batchGetValues(spreadsheetId: string, ranges: string[]): Promise<OpResult>;
73
+ /**
74
+ * Structural changes in ONE request, all or none (add a tab, grow one, freeze its header, format cells) — Google's
75
+ * `spreadsheets.batchUpdate` requests as given. OK with `{ replies }`.
76
+ */
77
+ batchUpdate(spreadsheetId: string, requests: Record<string, unknown>[]): Promise<OpResult>;
78
+ /**
79
+ * Many ranges written in ONE request, all or none — RAW unless told otherwise (nothing typed becomes a formula, a
80
+ * date or a number it was not). A range past the tab's size is refused by Google: grow the tab first (`batchUpdate`
81
+ * with `appendDimension`). OK with `{ updatedCells, updatedRanges }`.
82
+ */
83
+ batchUpdateValues(spreadsheetId: string, data: GoogleSheetValues[], valueInputOption?: 'RAW' | 'USER_ENTERED'): Promise<OpResult>;
84
+ }
85
+ export { GoogleSheetsGw };