@cyc-seattle/gsuite-sdk 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,330 @@
1
+ import { GoogleSpreadsheet } from "google-spreadsheet";
2
+ import { google } from "googleapis";
3
+ import winston from "winston";
4
+ import { safeCall } from "./common.js";
5
+ /**
6
+ * Represents a table in a Google Spreadsheet with cached cell access
7
+ */
8
+ export class Table {
9
+ worksheet;
10
+ headerColumns;
11
+ addedRows = [];
12
+ // Cell values keyed by "row,col", populated lazily on read and kept in sync on
13
+ // write. google-spreadsheet's `cell.value` getter throws "Value has been changed"
14
+ // once a cell has been assigned but not yet saved, so findRows must never re-read
15
+ // a cell that an earlier updateRow modified. Caching the value we read (or wrote)
16
+ // avoids touching the live getter a second time.
17
+ valueCache = new Map();
18
+ constructor(worksheet, headerColumns) {
19
+ this.worksheet = worksheet;
20
+ this.headerColumns = headerColumns;
21
+ }
22
+ cacheKey(rowIndex, columnIndex) {
23
+ return `${rowIndex},${columnIndex}`;
24
+ }
25
+ getCellValue(header, rowIndex) {
26
+ const columnIndex = this.headerColumns.get(header);
27
+ if (columnIndex === undefined) {
28
+ return undefined;
29
+ }
30
+ const key = this.cacheKey(rowIndex, columnIndex);
31
+ if (this.valueCache.has(key)) {
32
+ return this.valueCache.get(key);
33
+ }
34
+ // Safe to read the live cell here: it has not been modified this session.
35
+ const value = this.worksheet.getCell(rowIndex, columnIndex).value;
36
+ this.valueCache.set(key, value);
37
+ return value;
38
+ }
39
+ /**
40
+ * Finds all rows (by index) containing the values in "needle". This object may be a partial record to only
41
+ * match on key fields.
42
+ */
43
+ findRows(needle) {
44
+ const rows = [];
45
+ const needleKeys = Object.keys(needle);
46
+ for (let row = 1; row < this.worksheet.rowCount; row++) {
47
+ const found = needleKeys.every((header) => {
48
+ const rowValue = this.getCellValue(header, row);
49
+ const needleValue = needle[header];
50
+ return rowValue === needleValue;
51
+ });
52
+ if (found) {
53
+ rows.push(row);
54
+ }
55
+ }
56
+ return rows;
57
+ }
58
+ updateRow(rowIndex, values) {
59
+ winston.info("Updating existing row", { rowIndex, values });
60
+ const headers = Object.keys(values);
61
+ for (const header of headers) {
62
+ const columnIndex = this.headerColumns.get(header);
63
+ if (columnIndex !== undefined) {
64
+ const cell = this.worksheet.getCell(rowIndex, columnIndex);
65
+ const value = values[header];
66
+ cell.value = value;
67
+ // Keep the cache consistent with the write so later reads don't hit the
68
+ // now-dirty cell's throwing getter and so findRows reflects the update.
69
+ this.valueCache.set(this.cacheKey(rowIndex, columnIndex), value ?? null);
70
+ }
71
+ }
72
+ }
73
+ addRow(values) {
74
+ winston.info("Adding new row", { values });
75
+ const newRow = [];
76
+ const headers = Object.keys(values);
77
+ for (const header of headers) {
78
+ const columnIndex = this.headerColumns.get(header);
79
+ if (columnIndex !== undefined) {
80
+ newRow[columnIndex] = values[header] ?? "";
81
+ }
82
+ }
83
+ this.addedRows.push(newRow);
84
+ }
85
+ updateRows(keys, values) {
86
+ const needle = {};
87
+ for (const key of keys) {
88
+ needle[key] = values[key];
89
+ }
90
+ const rows = this.findRows(needle);
91
+ for (const rowIndex of rows) {
92
+ this.updateRow(rowIndex, values);
93
+ }
94
+ }
95
+ /**
96
+ * Updates ALL rows where the key columns matched the supplied values, or if
97
+ * no such rows exist, adds a new one.
98
+ */
99
+ addOrUpdate(keys, values) {
100
+ const needle = {};
101
+ for (const key of keys) {
102
+ needle[key] = values[key];
103
+ }
104
+ const rows = this.findRows(needle);
105
+ if (rows.length == 0) {
106
+ this.addRow(values);
107
+ return { existing: false };
108
+ }
109
+ else {
110
+ for (const rowIndex of rows) {
111
+ this.updateRow(rowIndex, values);
112
+ }
113
+ return { existing: true };
114
+ }
115
+ }
116
+ async save(reload) {
117
+ winston.debug("Saving updated cells");
118
+ await safeCall(() => this.worksheet.saveUpdatedCells());
119
+ if (this.addedRows.length > 0) {
120
+ winston.debug("Adding new rows", { count: this.addedRows.length });
121
+ await safeCall(() => this.worksheet.addRows(this.addedRows));
122
+ }
123
+ if (reload) {
124
+ await safeCall(() => this.worksheet.loadCells());
125
+ }
126
+ }
127
+ }
128
+ /**
129
+ * Represents a worksheet in a Google Spreadsheet
130
+ */
131
+ export class Worksheet {
132
+ worksheet;
133
+ constructor(worksheet) {
134
+ this.worksheet = worksheet;
135
+ }
136
+ /** The numeric sheet id, needed to target this worksheet in raw Sheets API requests. */
137
+ get sheetId() {
138
+ return this.worksheet.sheetId;
139
+ }
140
+ async getRows() {
141
+ return safeCall(() => this.worksheet.getRows());
142
+ }
143
+ async getTable() {
144
+ winston.debug("Loading worksheet cells", { title: this.worksheet.title });
145
+ await safeCall(() => this.worksheet.loadCells());
146
+ winston.debug("Loaded worksheet cells", this.worksheet.cellStats);
147
+ const headerColumns = new Map();
148
+ for (let col = 0; col < this.worksheet.columnCount; col++) {
149
+ const cellValue = this.worksheet.getCell(0, col).stringValue;
150
+ if (cellValue !== undefined) {
151
+ headerColumns.set(cellValue, col);
152
+ }
153
+ }
154
+ return new Table(this.worksheet, headerColumns);
155
+ }
156
+ }
157
+ /**
158
+ * Extended GoogleSpreadsheet with helper methods
159
+ */
160
+ export class Spreadsheet extends GoogleSpreadsheet {
161
+ async createWorksheet(title, headerValues) {
162
+ winston.debug("Creating worksheet", { title, headerValues: headerValues });
163
+ return safeCall(() => this.addSheet({
164
+ title: title,
165
+ headerValues: headerValues,
166
+ gridProperties: {
167
+ rowCount: 1,
168
+ columnCount: headerValues.length,
169
+ },
170
+ }));
171
+ }
172
+ async getOrCreateWorksheet(title, headerValues) {
173
+ const worksheet = this.sheetsByTitle[title] ?? (await this.createWorksheet(title, headerValues));
174
+ return new Worksheet(worksheet);
175
+ }
176
+ /**
177
+ * Adds a worksheet with the given headers, returning the typed wrapper. Unlike
178
+ * {@link getOrCreateWorksheet}, this always creates a new sheet (used when building a
179
+ * fresh spreadsheet where each tab is written once).
180
+ */
181
+ async addWorksheet(title, headerValues) {
182
+ const worksheet = await this.createWorksheet(title, headerValues);
183
+ return new Worksheet(worksheet);
184
+ }
185
+ /** Deletes the worksheet with the given title, if it exists. */
186
+ async deleteWorksheet(title) {
187
+ const worksheet = this.sheetsByTitle[title];
188
+ if (worksheet !== undefined) {
189
+ await safeCall(() => worksheet.delete());
190
+ }
191
+ }
192
+ /**
193
+ * Clears every existing worksheet so the spreadsheet can be rebuilt from scratch,
194
+ * leaving a single empty placeholder sheet (a spreadsheet must always have ≥1 sheet).
195
+ * The placeholder is created first so it survives while the originals are deleted, and
196
+ * its title is returned so the caller can remove it after adding the real sheets.
197
+ */
198
+ async resetSheets() {
199
+ const placeholderTitle = `_rebuild_${Date.now()}`;
200
+ const existing = [...this.sheetsByIndex];
201
+ await safeCall(() => this.addSheet({ title: placeholderTitle, gridProperties: { rowCount: 1, columnCount: 1 } }));
202
+ for (const worksheet of existing) {
203
+ await safeCall(() => worksheet.delete());
204
+ }
205
+ return placeholderTitle;
206
+ }
207
+ }
208
+ /**
209
+ * Extracts spreadsheet ID from a URL or returns the ID as-is
210
+ */
211
+ function extractSpreadsheetId(urlOrId) {
212
+ try {
213
+ const url = new URL(urlOrId);
214
+ const pathSegments = url.pathname.split("/");
215
+ if (pathSegments.length < 4) {
216
+ throw new Error(`Cannot extract spreadsheet ID from ${urlOrId}`);
217
+ }
218
+ return pathSegments[3];
219
+ }
220
+ catch {
221
+ // If it's not a valid URL, assume it's already an ID
222
+ return urlOrId;
223
+ }
224
+ }
225
+ /**
226
+ * Client for loading Google Spreadsheets
227
+ */
228
+ export class SpreadsheetClient {
229
+ auth;
230
+ constructor(auth) {
231
+ this.auth = auth;
232
+ }
233
+ /**
234
+ * Creates a new, empty Google Spreadsheet inside the given Drive folder and returns it
235
+ * loaded and ready to write.
236
+ *
237
+ * The Drive API is used (rather than google-spreadsheet's createNewSpreadsheetDocument,
238
+ * which only lands the file in "My Drive") so the file can be parented directly in a
239
+ * folder. `supportsAllDrives` is required because our target folders live in shared
240
+ * drives. Requires the `drive` OAuth scope.
241
+ */
242
+ async createSpreadsheet(title, folderId) {
243
+ const drive = google.drive("v3");
244
+ const file = await safeCall(async () => {
245
+ const response = await drive.files.create({
246
+ auth: this.auth,
247
+ requestBody: {
248
+ name: title,
249
+ mimeType: "application/vnd.google-apps.spreadsheet",
250
+ parents: [folderId],
251
+ },
252
+ fields: "id",
253
+ supportsAllDrives: true,
254
+ });
255
+ return response.data;
256
+ });
257
+ const spreadsheetId = file.id;
258
+ if (!spreadsheetId) {
259
+ throw new Error(`Drive did not return an id for the new spreadsheet "${title}"`);
260
+ }
261
+ winston.info("Created spreadsheet", { title, spreadsheetId, folderId });
262
+ return this.loadSpreadsheet(spreadsheetId);
263
+ }
264
+ /**
265
+ * Finds the id of a non-trashed spreadsheet with the exact given name inside the folder,
266
+ * or undefined if none exists. `supportsAllDrives` / `includeItemsFromAllDrives` are set
267
+ * because our folders live in shared drives.
268
+ */
269
+ async findSpreadsheetInFolder(title, folderId) {
270
+ const drive = google.drive("v3");
271
+ const escapedTitle = title.replace(/'/g, "\\'");
272
+ const fileList = await safeCall(async () => {
273
+ const response = await drive.files.list({
274
+ auth: this.auth,
275
+ q: `name = '${escapedTitle}' and '${folderId}' in parents and mimeType = 'application/vnd.google-apps.spreadsheet' and trashed = false`,
276
+ fields: "files(id,name)",
277
+ supportsAllDrives: true,
278
+ includeItemsFromAllDrives: true,
279
+ pageSize: 1,
280
+ });
281
+ return response.data;
282
+ });
283
+ return fileList.files?.[0]?.id ?? undefined;
284
+ }
285
+ /**
286
+ * Returns a spreadsheet named `title` in the folder, ready to be rebuilt: if one already
287
+ * exists it is reused (and its sheets cleared) so the file id / URL stays stable across
288
+ * runs; otherwise a new one is created. The returned `placeholderTitle` is a throwaway
289
+ * sheet the caller should delete after adding the real worksheets.
290
+ */
291
+ async getOrCreateSpreadsheet(title, folderId) {
292
+ const existingId = await this.findSpreadsheetInFolder(title, folderId);
293
+ if (existingId !== undefined) {
294
+ winston.info("Reusing existing spreadsheet", { title, spreadsheetId: existingId });
295
+ const spreadsheet = await this.loadSpreadsheet(existingId);
296
+ const placeholderTitle = await spreadsheet.resetSheets();
297
+ return { spreadsheet, placeholderTitle, reused: true };
298
+ }
299
+ const spreadsheet = await this.createSpreadsheet(title, folderId);
300
+ return { spreadsheet, placeholderTitle: "Sheet1", reused: false };
301
+ }
302
+ /**
303
+ * Applies raw Sheets API requests (formatting, banding, borders, etc.) that the
304
+ * google-spreadsheet abstraction doesn't expose. Requests are sent as a single atomic
305
+ * batchUpdate.
306
+ */
307
+ async batchUpdate(spreadsheetId, requests) {
308
+ if (requests.length === 0) {
309
+ return;
310
+ }
311
+ const sheets = google.sheets("v4");
312
+ await safeCall(() => sheets.spreadsheets.batchUpdate({
313
+ auth: this.auth,
314
+ spreadsheetId,
315
+ requestBody: { requests },
316
+ }));
317
+ }
318
+ async loadSpreadsheet(spreadsheetUrlOrId) {
319
+ const spreadsheetId = extractSpreadsheetId(spreadsheetUrlOrId);
320
+ const spreadsheet = new Spreadsheet(spreadsheetId, this.auth);
321
+ await safeCall(() => spreadsheet.loadInfo());
322
+ winston.debug("Loaded spreadsheet", {
323
+ spreadsheetId,
324
+ title: spreadsheet.title,
325
+ locale: spreadsheet.locale,
326
+ timeZone: spreadsheet.timeZone,
327
+ });
328
+ return spreadsheet;
329
+ }
330
+ }
package/package.json CHANGED
@@ -1,6 +1,52 @@
1
1
  {
2
2
  "name": "@cyc-seattle/gsuite-sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "Domain-agnostic wrappers around Google Workspace APIs",
5
+ "author": "CYC Community Sailing Center",
6
+ "license": "Apache-2.0",
7
+ "homepage": "https://github.com/cyc-seattle/gsuite-sdk#readme",
8
+ "bugs": {
9
+ "url": "https://github.com/cyc-seattle/gsuite-sdk/issues"
10
+ },
11
+ "type": "module",
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "git+https://github.com/cyc-seattle/gsuite-sdk.git"
15
+ },
16
+ "publishConfig": {
17
+ "access": "public"
18
+ },
19
+ "engines": {
20
+ "node": ">=22"
21
+ },
22
+ "prettier": "@cyc-seattle/ts-config/prettier",
23
+ "exports": {
24
+ ".": {
25
+ "types": "./dist/index.d.ts",
26
+ "default": "./dist/index.js"
27
+ },
28
+ "./package.json": "./package.json"
29
+ },
30
+ "files": [
31
+ "dist"
32
+ ],
33
+ "dependencies": {
34
+ "exponential-backoff": "^3.1.3",
35
+ "google-spreadsheet": "^4.1.5",
36
+ "googleapis": "^144.0.0",
37
+ "luxon": "^3.7.2",
38
+ "winston": "^3.18.3"
39
+ },
40
+ "devDependencies": {
41
+ "@cyc-seattle/ts-config": "^0.1.2",
42
+ "@types/luxon": "^3.7.1",
43
+ "@types/node": "^22.20.5",
44
+ "eslint": "^9.39.5",
45
+ "prettier": "^3.9.10",
46
+ "typescript": "^5.9.3",
47
+ "vitest": "^4.1.11"
48
+ },
49
+ "scripts": {
50
+ "build": "tsc -p tsconfig.build.json"
51
+ }
6
52
  }