@kamilio/wire 0.1.40 → 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
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; images?: string[] };
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 {
@@ -29,7 +30,7 @@ async function save(path: string, data: string | Uint8Array) {
29
30
 
30
31
  const imageData = /data:image\/(png|jpeg|gif|webp);base64,([a-zA-Z0-9+/]+=*)/;
31
32
  const imageDefinition = new RegExp("^\\[(image\\d+)\\]:[ \\t]*<?(" + imageData.source + ")>?[ \\t]*\\r?$", "gm");
32
- const inlineImage = new RegExp("(!\\[(?:\\\\.|[^\\]\\\\\\n])*\\])\\(<?(" + imageData.source + ")>?\\)", "g");
33
+ const imageUse = new RegExp("(!\\[(?:\\\\.|[^\\]\\\\\\n])*\\])(?:\\[(image\\d+)\\]|\\(<?" + imageData.source + ">?\\))", "g");
33
34
 
34
35
  async function docImageDir(full: string, create: boolean) {
35
36
  const root = join(dirname(full), "attachments"), folder = join(root, basename(full, ".md"));
@@ -51,36 +52,40 @@ async function checkDocImage(folder: string, name: string) {
51
52
  return true;
52
53
  }
53
54
 
54
- async function extractDocImages(full: string, text: string) {
55
- const files = new Map<string, Buffer>(), links = new Map<string, string>();
56
- const link = (ext: string, base64: string) => {
57
- const data = Buffer.from(base64, "base64");
58
- if (data.toString("base64") !== base64) throw new Error("Invalid image encoding.");
59
- const name = digest(data) + "." + ext;
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;
60
69
  files.set(name, data);
61
- return "attachments/" + encodeURIComponent(basename(full, ".md")).replace(/[()]/g, c => c === "(" ? "%28" : "%29") + "/" + name;
62
- };
63
- for (const m of text.matchAll(imageDefinition)) links.set(m[1]!, link(m[3]!, m[4]!));
64
- text = text.replace(inlineImage, (_, alt, _uri, ext, data) => alt + "(" + link(ext, data) + ")");
65
- if (links.size) {
66
- text = text.replace(/(!\[(?:\\.|[^\]\\\n])*\])\[(image\d+)\]/g, (all, alt, id) =>
67
- links.has(id) ? alt + "(" + links.get(id) + ")" : all);
68
- // Keep a relative definition for ordinary links that use the same reference.
69
- text = text.replace(imageDefinition, (line, id, _uri, _ext, _data, offset) =>
70
- (text.slice(0, offset) + text.slice(offset + line.length)).includes("[" + id + "]")
71
- ? "[" + id + "]: <" + links.get(id) + ">" : "");
72
- }
73
- if (files.size) {
74
- const folder = await docImageDir(full, true);
75
- for (const [name, data] of files) {
76
- if (!(await checkDocImage(folder, name))) await writeFile(join(folder, name), data, { flag: "wx", mode: 0o600 });
77
- }
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 });
78
82
  }
79
83
  return { bytes: Buffer.from(text), images: [...files.keys()] };
80
84
  }
81
85
 
82
86
  type DriveRuntime = Pick<RuntimeCapabilities, "googleFormsTokens" | "http">;
83
87
  const folderUrl = /^https:\/\/drive\.google\.com\/drive\/(?:u\/\d+\/)?folders\/([\w-]+)\/?(?:[?#].*)?$/;
88
+ const sheetUrl = /^https:\/\/docs\.google\.com\/spreadsheets\/(?:u\/\d+\/)?d\/([\w-]+)(?:[/?#].*)?$/;
84
89
  const safeName = (name: string) => name.replace(/[/\\:\x00-\x1f]/g, "_").replace(/^\.+/, "_") || "_";
85
90
  async function drive(runtime: DriveRuntime, path: string, params: Record<string, string>) {
86
91
  const token = await runtime.googleFormsTokens.load();
@@ -147,12 +152,52 @@ export async function previewDrive(runtime: DriveRuntime, url: string) {
147
152
  return "# " + item.name + "\n\n" + item.mimeType;
148
153
  }
149
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
+
150
193
  export async function scrapeDrive(runtime: DriveRuntime, cwd: string, url?: string) {
151
- const match = url?.match(folderUrl);
152
- if (url && !match) throw new Error("Expected a Google Drive folder URL.");
153
- if (match) {
154
- const root = await (await drive(runtime, "/" + match[1], { fields: "name,mimeType", supportsAllDrives: "true" })).json();
155
- 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.");
156
201
  const name = safeName(root.name);
157
202
  if (basename(cwd) !== name) {
158
203
  cwd = join(cwd, name);
@@ -163,18 +208,19 @@ export async function scrapeDrive(runtime: DriveRuntime, cwd: string, url?: stri
163
208
  const manifest = join(cwd, ".wire-gdrive.json");
164
209
  const state: State = (await stat(manifest))?.isFile()
165
210
  ? JSON.parse(await readFile(manifest, "utf8"))
166
- : { folder: match?.[1], entries: {} };
167
- if (!state.folder) throw new Error("Pass a Drive folder URL on the first scrape.");
168
- if (!match) await drive(runtime, "/" + encodeURIComponent(state.folder), { fields: "id", supportsAllDrives: "true" });
169
- 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);
170
216
  let downloaded = 0,
171
217
  unchanged = 0,
172
218
  removed = 0;
173
219
  const errors: string[] = [],
174
220
  skipped: string[] = [],
175
221
  images: string[] = [];
176
- async function visit(parent: string, dir: string) {
177
- 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) {
178
224
  try {
179
225
  if (f.name.endsWith(".cannedSearch") || f.name === ".DS_Store") continue;
180
226
  const folder = f.mimeType === google + "folder",
@@ -206,7 +252,7 @@ export async function scrapeDrive(runtime: DriveRuntime, cwd: string, url?: stri
206
252
  if (!(await stat(full))) await mkdir(full, { mode: 0o700 });
207
253
  if (!(await lstat(full)).isDirectory()) throw new Error("Expected a local directory.");
208
254
  state.entries[key(path)] = { id: f.id };
209
- await visit(f.id, path);
255
+ await visit(children(runtime, f.id), path);
210
256
  continue;
211
257
  }
212
258
  const original = state.entries[key(path)];
@@ -237,14 +283,16 @@ export async function scrapeDrive(runtime: DriveRuntime, cwd: string, url?: stri
237
283
  if (original?.images?.length) {
238
284
  const dir = await docImageDir(full, false);
239
285
  for (const image of original.images) if (!(await checkDocImage(dir, image))) current = false;
286
+ if (!original.originalImages) current = false;
240
287
  } else if (!original?.images) {
241
- // Upgrade prior exports on refresh, without another network request.
242
- const local = await extractDocImages(full, await readFile(full, "utf8"));
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"));
243
290
  if (local.images.length) {
244
291
  await save(full, local.bytes);
245
292
  original!.hash = digest(local.bytes);
246
293
  }
247
294
  original!.images = local.images;
295
+ original!.originalImages = true;
248
296
  }
249
297
  }
250
298
  if (current) {
@@ -258,10 +306,10 @@ export async function scrapeDrive(runtime: DriveRuntime, cwd: string, url?: stri
258
306
  ? await drive(runtime, "/" + f.id + "/export", { mimeType: format[1] })
259
307
  : await drive(runtime, "/" + f.id, { alt: "media", supportsAllDrives: "true" });
260
308
  const raw = new Uint8Array(await response.arrayBuffer());
261
- const doc = f.mimeType === google + "document" ? await extractDocImages(full, Buffer.from(raw).toString("utf8")) : undefined;
309
+ const doc = f.mimeType === google + "document" ? await extractDocImages(runtime, f.id, full, Buffer.from(raw).toString("utf8")) : undefined;
262
310
  const bytes = doc?.bytes ?? raw;
263
311
  await save(full, bytes);
264
- state.entries[key(path)] = { id: f.id, version: f.version, hash: digest(bytes), ...(doc ? { images: doc.images } : {}) };
312
+ state.entries[key(path)] = { id: f.id, version: f.version, hash: digest(bytes), ...(doc ? { images: doc.images, originalImages: true } : {}) };
265
313
  if (pdf) {
266
314
  const { pdfMarkdown } = await import("./drive-pdf.js");
267
315
  const text = pdfMarkdown(bytes);
@@ -283,7 +331,17 @@ export async function scrapeDrive(runtime: DriveRuntime, cwd: string, url?: stri
283
331
  }
284
332
  }
285
333
  try {
286
- 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), "");
287
345
  } finally {
288
346
  await save(manifest, JSON.stringify(state, null, 2) + "\n");
289
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";