@kamilio/wire 0.1.39 → 0.1.41

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.
@@ -1,6 +1,7 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
2
  import { lstat, mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
3
- import { basename, extname, join } from "node:path";
3
+ import { basename, dirname, extname, join } from "node:path";
4
+ import { googleDocOriginalImages } from "provider-google-docs";
4
5
  import type { RuntimeCapabilities } from "wire-core";
5
6
 
6
7
  const google = "application/vnd.google-apps.";
@@ -11,8 +12,8 @@ const formats: Record<string, [string, string]> = {
11
12
  drawing: [".svg", "image/svg+xml"],
12
13
  };
13
14
  type File = { id: string; name: string; mimeType: string; version: string };
14
- type Entry = { id: string; version?: string; hash?: string; noText?: true; markdownOnly?: true };
15
- type State = { folder: string; entries: Record<string, Entry> };
15
+ type Entry = { id: string; version?: string; hash?: string; noText?: true; markdownOnly?: true; images?: string[]; originalImages?: true };
16
+ type State = { folder?: string; spreadsheet?: string; links?: Record<string, string[]>; entries: Record<string, Entry> };
16
17
  const digest = (data: Uint8Array) => createHash("sha256").update(data).digest("hex");
17
18
  async function stat(path: string) {
18
19
  try {
@@ -27,8 +28,64 @@ async function save(path: string, data: string | Uint8Array) {
27
28
  await rename(tmp, path);
28
29
  }
29
30
 
31
+ const imageData = /data:image\/(png|jpeg|gif|webp);base64,([a-zA-Z0-9+/]+=*)/;
32
+ const imageDefinition = new RegExp("^\\[(image\\d+)\\]:[ \\t]*<?(" + imageData.source + ")>?[ \\t]*\\r?$", "gm");
33
+ const imageUse = new RegExp("(!\\[(?:\\\\.|[^\\]\\\\\\n])*\\])(?:\\[(image\\d+)\\]|\\(<?" + imageData.source + ">?\\))", "g");
34
+
35
+ async function docImageDir(full: string, create: boolean) {
36
+ const root = join(dirname(full), "attachments"), folder = join(root, basename(full, ".md"));
37
+ for (const path of [root, folder]) {
38
+ const info = await stat(path);
39
+ if (info && !info.isDirectory()) throw new Error("Expected an attachment directory: " + path);
40
+ if (!info && create) await mkdir(path, { mode: 0o700 });
41
+ if (!info && !create) break;
42
+ }
43
+ return folder;
44
+ }
45
+
46
+ async function checkDocImage(folder: string, name: string) {
47
+ const hash = /^([a-f0-9]{64})\.(png|jpeg|gif|webp)$/.exec(name)?.[1];
48
+ if (!hash) throw new Error("Invalid attachment name: " + name);
49
+ const path = join(folder, name), info = await stat(path);
50
+ if (!info) return false;
51
+ if (!info.isFile() || digest(await readFile(path)) !== hash) throw new Error("Local attachment changed: " + path);
52
+ return true;
53
+ }
54
+
55
+ async function extractDocImages(runtime: DriveRuntime, id: string, full: string, text: string) {
56
+ const labels = new Set([...text.matchAll(imageDefinition)].map(m => m[1]));
57
+ const images = [...text.matchAll(imageUse)].filter(m => m[2] === undefined || labels.has(m[2]));
58
+ if (!images.length) return { bytes: Buffer.from(text), images: [] };
59
+ const response = await drive(runtime, "/" + id + "/export", { mimeType: "application/zip" });
60
+ const originals = googleDocOriginalImages(new Uint8Array(await response.arrayBuffer()));
61
+ if (images.length !== originals.length) throw new Error("Image count differs between Google Docs Markdown and HTML exports; kept local copy.");
62
+ const files = new Map<string, Uint8Array>(), links = new Map<string, string>();
63
+ const dir = encodeURIComponent(basename(full, ".md")).replace(/[()]/g, c => c === "(" ? "%28" : "%29");
64
+ let index = 0;
65
+ text = text.replace(imageUse, (all, alt, label) => {
66
+ if (label !== undefined && !labels.has(label)) return all;
67
+ const { data, ext } = originals[index++]!;
68
+ const name = digest(data) + "." + ext, url = "attachments/" + dir + "/" + name;
69
+ files.set(name, data);
70
+ if (label) links.set(label, url);
71
+ return alt + "(" + url + ")";
72
+ });
73
+ text = text.replace(imageDefinition, (line, label, _uri, _ext, _data, offset) => {
74
+ const url = links.get(label);
75
+ if (!url) return line;
76
+ return (text.slice(0, offset) + text.slice(offset + line.length)).includes("[" + label + "]")
77
+ ? "[" + label + "]: <" + url + ">" : "";
78
+ });
79
+ const folder = await docImageDir(full, true);
80
+ for (const [name, data] of files) {
81
+ if (!(await checkDocImage(folder, name))) await writeFile(join(folder, name), data, { flag: "wx", mode: 0o600 });
82
+ }
83
+ return { bytes: Buffer.from(text), images: [...files.keys()] };
84
+ }
85
+
30
86
  type DriveRuntime = Pick<RuntimeCapabilities, "googleFormsTokens" | "http">;
31
87
  const folderUrl = /^https:\/\/drive\.google\.com\/drive\/(?:u\/\d+\/)?folders\/([\w-]+)\/?(?:[?#].*)?$/;
88
+ const sheetUrl = /^https:\/\/docs\.google\.com\/spreadsheets\/(?:u\/\d+\/)?d\/([\w-]+)(?:[/?#].*)?$/;
32
89
  const safeName = (name: string) => name.replace(/[/\\:\x00-\x1f]/g, "_").replace(/^\.+/, "_") || "_";
33
90
  async function drive(runtime: DriveRuntime, path: string, params: Record<string, string>) {
34
91
  const token = await runtime.googleFormsTokens.load();
@@ -95,12 +152,52 @@ export async function previewDrive(runtime: DriveRuntime, url: string) {
95
152
  return "# " + item.name + "\n\n" + item.mimeType;
96
153
  }
97
154
 
155
+ type SheetCell = {
156
+ formattedValue?: string; hyperlink?: string; userEnteredValue?: { stringValue?: string; formulaValue?: string };
157
+ textFormatRuns?: { format?: { link?: { uri?: string } } }[];
158
+ userEnteredFormat?: { textFormat?: { link?: { uri?: string } } };
159
+ chipRuns?: { chip?: { richLinkProperties?: { uri?: string } } }[];
160
+ };
161
+
162
+ async function sheetLinks(runtime: DriveRuntime, id: string) {
163
+ const fields = "sheets(properties(title),data(startRow,startColumn,rowData(values(formattedValue,hyperlink,userEnteredValue,textFormatRuns(format/link),userEnteredFormat/textFormat/link,chipRuns(chip/richLinkProperties/uri)))))";
164
+ const token = await runtime.googleFormsTokens.load();
165
+ const response = await runtime.http.request("https://sheets.googleapis.com/v4/spreadsheets/" + encodeURIComponent(id) + "?" + new URLSearchParams({ fields }), { headers: { authorization: "Bearer " + token.token } });
166
+ if (!response.ok) throw new Error("Sheets HTTP " + response.status + ": " + (await response.text()).slice(0, 600));
167
+ type Sheet = { properties: { title: string }; data?: { startRow?: number; startColumn?: number; rowData?: { values?: SheetCell[] }[] }[] };
168
+ const { sheets } = await response.json() as { sheets: Sheet[] };
169
+ const links: Record<string, string[]> = Object.create(null);
170
+ for (const tab of sheets) for (const grid of tab.data ?? []) {
171
+ for (const [r, row] of (grid.rowData ?? []).entries()) for (const [c, cell] of (row.values ?? []).entries()) {
172
+ const texts = [cell.hyperlink, cell.formattedValue, cell.userEnteredValue?.stringValue, cell.userEnteredValue?.formulaValue,
173
+ cell.userEnteredFormat?.textFormat?.link?.uri,
174
+ ...(cell.textFormatRuns ?? []).map(run => run.format?.link?.uri),
175
+ ...(cell.chipRuns ?? []).map(run => run.chip?.richLinkProperties?.uri)];
176
+ for (const text of texts) for (const m of (text ?? "").matchAll(/https?:\/\/[^\s"'<>]+/gi)) {
177
+ let url: URL;
178
+ try { url = new URL(m[0]); } catch { continue; }
179
+ if (url.hostname !== "docs.google.com" && url.hostname !== "drive.google.com") continue;
180
+ const target = /\/(?:d|folders)\/([\w-]+)(?:\/|$)/.exec(url.pathname)?.[1] ?? url.searchParams.get("id");
181
+ if (!target || !/^[\w-]+$/.test(target) || target === id) continue;
182
+ let n = c + (grid.startColumn ?? 0) + 1, col = "";
183
+ while (n) { n--; col = String.fromCharCode(65 + n % 26) + col; n = Math.floor(n / 26); }
184
+ const ref = tab.properties.title + "!" + col + (r + (grid.startRow ?? 0) + 1);
185
+ const refs = links[target] ??= [];
186
+ if (!refs.includes(ref)) refs.push(ref);
187
+ }
188
+ }
189
+ }
190
+ return links;
191
+ }
192
+
98
193
  export async function scrapeDrive(runtime: DriveRuntime, cwd: string, url?: string) {
99
- const match = url?.match(folderUrl);
100
- if (url && !match) throw new Error("Expected a Google Drive folder URL.");
101
- if (match) {
102
- const root = await (await drive(runtime, "/" + match[1], { fields: "name,mimeType", supportsAllDrives: "true" })).json();
103
- if (root.mimeType !== google + "folder") throw new Error("The URL must identify a Drive folder.");
194
+ const sheet = url?.match(sheetUrl)?.[1], folder = url?.match(folderUrl)?.[1];
195
+ if (url && !sheet && !folder) throw new Error("Expected a Google Drive folder or Google Sheets URL.");
196
+ const metadata = async (id: string): Promise<File> => (await drive(runtime, "/" + encodeURIComponent(id), { fields: "id,name,mimeType,version", supportsAllDrives: "true" })).json();
197
+ let root: File | undefined;
198
+ if (sheet || folder) {
199
+ root = await metadata((sheet ?? folder)!);
200
+ if (root.mimeType !== google + (sheet ? "spreadsheet" : "folder")) throw new Error("Drive file type does not match the URL.");
104
201
  const name = safeName(root.name);
105
202
  if (basename(cwd) !== name) {
106
203
  cwd = join(cwd, name);
@@ -111,18 +208,19 @@ export async function scrapeDrive(runtime: DriveRuntime, cwd: string, url?: stri
111
208
  const manifest = join(cwd, ".wire-gdrive.json");
112
209
  const state: State = (await stat(manifest))?.isFile()
113
210
  ? JSON.parse(await readFile(manifest, "utf8"))
114
- : { folder: match?.[1], entries: {} };
115
- if (!state.folder) throw new Error("Pass a Drive folder URL on the first scrape.");
116
- if (!match) await drive(runtime, "/" + encodeURIComponent(state.folder), { fields: "id", supportsAllDrives: "true" });
117
- if (match && state.folder !== match[1]) throw new Error("This directory tracks a different Drive folder.");
211
+ : { ...(sheet ? { spreadsheet: sheet } : { folder }), entries: {} };
212
+ const source = state.spreadsheet ?? state.folder;
213
+ if (!source) throw new Error("Pass a Drive folder or Google Sheets URL on the first scrape.");
214
+ if ((sheet && sheet !== state.spreadsheet) || (folder && folder !== state.folder)) throw new Error("This directory tracks a different Drive source.");
215
+ root ??= await metadata(source);
118
216
  let downloaded = 0,
119
217
  unchanged = 0,
120
218
  removed = 0;
121
219
  const errors: string[] = [],
122
220
  skipped: string[] = [],
123
221
  images: string[] = [];
124
- async function visit(parent: string, dir: string) {
125
- for await (const f of children(runtime, parent)) {
222
+ async function visit(files: AsyncIterable<File> | Iterable<File>, dir: string) {
223
+ for await (const f of files) {
126
224
  try {
127
225
  if (f.name.endsWith(".cannedSearch") || f.name === ".DS_Store") continue;
128
226
  const folder = f.mimeType === google + "folder",
@@ -154,7 +252,7 @@ export async function scrapeDrive(runtime: DriveRuntime, cwd: string, url?: stri
154
252
  if (!(await stat(full))) await mkdir(full, { mode: 0o700 });
155
253
  if (!(await lstat(full)).isDirectory()) throw new Error("Expected a local directory.");
156
254
  state.entries[key(path)] = { id: f.id };
157
- await visit(f.id, path);
255
+ await visit(children(runtime, f.id), path);
158
256
  continue;
159
257
  }
160
258
  const original = state.entries[key(path)];
@@ -181,6 +279,22 @@ export async function scrapeDrive(runtime: DriveRuntime, cwd: string, url?: stri
181
279
  throw new Error("Local file changed: " + p);
182
280
  if (!info || entry?.version !== f.version) current = false;
183
281
  }
282
+ if (current && f.mimeType === google + "document") {
283
+ if (original?.images?.length) {
284
+ const dir = await docImageDir(full, false);
285
+ for (const image of original.images) if (!(await checkDocImage(dir, image))) current = false;
286
+ if (!original.originalImages) current = false;
287
+ } else if (!original?.images) {
288
+ // Upgrade prior exports using their Markdown and the original HTML media.
289
+ const local = await extractDocImages(runtime, f.id, full, await readFile(full, "utf8"));
290
+ if (local.images.length) {
291
+ await save(full, local.bytes);
292
+ original!.hash = digest(local.bytes);
293
+ }
294
+ original!.images = local.images;
295
+ original!.originalImages = true;
296
+ }
297
+ }
184
298
  if (current) {
185
299
  if (state.entries[key(path)]?.noText) images.push(path);
186
300
  if (pdf && !original?.noText && (await stat(full)))
@@ -191,9 +305,11 @@ export async function scrapeDrive(runtime: DriveRuntime, cwd: string, url?: stri
191
305
  const response = format
192
306
  ? await drive(runtime, "/" + f.id + "/export", { mimeType: format[1] })
193
307
  : await drive(runtime, "/" + f.id, { alt: "media", supportsAllDrives: "true" });
194
- const bytes = new Uint8Array(await response.arrayBuffer());
308
+ const raw = new Uint8Array(await response.arrayBuffer());
309
+ const doc = f.mimeType === google + "document" ? await extractDocImages(runtime, f.id, full, Buffer.from(raw).toString("utf8")) : undefined;
310
+ const bytes = doc?.bytes ?? raw;
195
311
  await save(full, bytes);
196
- state.entries[key(path)] = { id: f.id, version: f.version, hash: digest(bytes) };
312
+ state.entries[key(path)] = { id: f.id, version: f.version, hash: digest(bytes), ...(doc ? { images: doc.images, originalImages: true } : {}) };
197
313
  if (pdf) {
198
314
  const { pdfMarkdown } = await import("./drive-pdf.js");
199
315
  const text = pdfMarkdown(bytes);
@@ -215,7 +331,17 @@ export async function scrapeDrive(runtime: DriveRuntime, cwd: string, url?: stri
215
331
  }
216
332
  }
217
333
  try {
218
- await visit(state.folder, "");
334
+ if (state.spreadsheet) {
335
+ await visit([root], "");
336
+ state.links = await sheetLinks(runtime, source);
337
+ for (const [id, refs] of Object.entries(state.links)) {
338
+ try {
339
+ const file = await metadata(id);
340
+ if (file.mimeType === google + "folder") skipped.push(file.name + " (linked folder)");
341
+ else await visit([file], "");
342
+ } catch (e) { errors.push(refs.join(", ") + " (" + id + "): " + (e as Error).message); }
343
+ }
344
+ } else await visit(children(runtime, source), "");
219
345
  } finally {
220
346
  await save(manifest, JSON.stringify(state, null, 2) + "\n");
221
347
  }
@@ -602,13 +602,13 @@ export function createRoot(wire: Wire, currentDirectory: string, auth?: Auth, re
602
602
  scope: ["cli", "mcp", "sdk"],
603
603
  children: [
604
604
  defaultAttach,
605
- ...(options.scrapeDrive ? [defineGroup({ name: "gdrive", description: "Download Google Drive folders.", scope: ["cli"], children: [
605
+ ...(options.scrapeDrive ? [defineGroup({ name: "gdrive", description: "Download Google Drive folders and spreadsheets.", scope: ["cli"], children: [
606
606
  ...(options.previewDrive ? [defineCommand({ name: "preview", description: "List a Drive folder or read a file without saving it.", scope: ["cli"], positional: ["url"],
607
607
  params: S.Object({ url: S.String({description: "Google Drive folder or file URL."}) }),
608
608
  handler: ({ params }) => userFacing(() => options.previewDrive!(params.url)), render: render<string>(v => v),
609
609
  })] : []),
610
- defineCommand({ name: "scrape", description: "Download into a directory named after the Drive folder. Run there without a URL to refresh.", scope: ["cli"], positional: ["url"],
611
- params: S.Object({ url: S.Optional(S.String({ description: "Google Drive folder URL." })) }),
610
+ defineCommand({ name: "scrape", description: "Download a folder, or a spreadsheet and its linked Drive files, into its own directory. Run there without a URL to refresh.", scope: ["cli"], positional: ["url"],
611
+ params: S.Object({ url: S.Optional(S.String({ description: "Google Drive folder or Google Sheets URL." })) }),
612
612
  handler: ({ params }) => userFacing(() => options.scrapeDrive!(params.url)), render: render<string>(v => v),
613
613
  }),
614
614
  ] })] : []),
package/src/index.ts CHANGED
@@ -3,7 +3,7 @@ export * from "provider-asana";
3
3
  export * from "provider-notion";
4
4
  export * from "provider-chatgpt";
5
5
  export * from "provider-gmail";
6
- export * from "provider-google-docs";
6
+ export { googleDocsProvider, googleDocsService, googleFormsService } from "provider-google-docs";
7
7
  export * from "provider-slack";
8
8
  export * from "provider-zoom";
9
9
  export { composeAuth } from "./auth.js";