@kamilio/wire 0.1.44 → 0.1.45

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.
Files changed (41) hide show
  1. package/README.md +7 -1
  2. package/dist/adapters/root.d.ts.map +1 -1
  3. package/dist/adapters/root.js +5 -2
  4. package/dist/adapters/root.js.map +1 -1
  5. package/node_modules/provider-google-docs/dist/doc-blocks.d.ts +10 -0
  6. package/node_modules/provider-google-docs/dist/doc-blocks.d.ts.map +1 -0
  7. package/node_modules/provider-google-docs/dist/doc-blocks.js +142 -0
  8. package/node_modules/provider-google-docs/dist/doc-blocks.js.map +1 -0
  9. package/node_modules/provider-google-docs/dist/google-docs.d.ts.map +1 -1
  10. package/node_modules/provider-google-docs/dist/google-docs.js +134 -252
  11. package/node_modules/provider-google-docs/dist/google-docs.js.map +1 -1
  12. package/node_modules/provider-google-docs/dist/google-read.d.ts +6 -0
  13. package/node_modules/provider-google-docs/dist/google-read.d.ts.map +1 -0
  14. package/node_modules/provider-google-docs/dist/google-read.js +22 -0
  15. package/node_modules/provider-google-docs/dist/google-read.js.map +1 -0
  16. package/node_modules/provider-google-docs/dist/native-docs.d.ts +9 -0
  17. package/node_modules/provider-google-docs/dist/native-docs.d.ts.map +1 -0
  18. package/node_modules/provider-google-docs/dist/native-docs.js +593 -0
  19. package/node_modules/provider-google-docs/dist/native-docs.js.map +1 -0
  20. package/node_modules/provider-google-docs/src/doc-blocks.ts +119 -0
  21. package/node_modules/provider-google-docs/src/google-docs.ts +127 -238
  22. package/node_modules/provider-google-docs/src/google-read.ts +22 -0
  23. package/node_modules/provider-google-docs/src/native-docs.ts +476 -0
  24. package/node_modules/wire-core/dist/core/model.d.ts +1 -0
  25. package/node_modules/wire-core/dist/core/model.d.ts.map +1 -1
  26. package/node_modules/wire-core/dist/operations.d.ts.map +1 -1
  27. package/node_modules/wire-core/dist/operations.js +108 -28
  28. package/node_modules/wire-core/dist/operations.js.map +1 -1
  29. package/node_modules/wire-core/dist/runtime/node.d.ts.map +1 -1
  30. package/node_modules/wire-core/dist/runtime/node.js +7 -2
  31. package/node_modules/wire-core/dist/runtime/node.js.map +1 -1
  32. package/node_modules/wire-core/dist/storage/registry.d.ts +3 -1
  33. package/node_modules/wire-core/dist/storage/registry.d.ts.map +1 -1
  34. package/node_modules/wire-core/dist/storage/registry.js +50 -1
  35. package/node_modules/wire-core/dist/storage/registry.js.map +1 -1
  36. package/node_modules/wire-core/src/core/model.ts +1 -0
  37. package/node_modules/wire-core/src/operations.ts +91 -28
  38. package/node_modules/wire-core/src/runtime/node.ts +6 -2
  39. package/node_modules/wire-core/src/storage/registry.ts +41 -2
  40. package/package.json +1 -1
  41. package/src/adapters/root.ts +5 -2
@@ -1,8 +1,9 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
3
3
 
4
+ import { stableJsonCompact } from "./core/json.js";
4
5
  import { extractRelationships, markdownFilename } from "./core/transform.js";
5
- import type { FetchedDocument, JsonObject, JsonValue, Registry, Resource, ResourceData, ServiceCatalog } from "./core/model.js";
6
+ import type { FetchedDocument, JsonObject, JsonValue, Registry, Resource, ResourceData, ServiceCatalog, Source } from "./core/model.js";
6
7
  import { resourceId } from "./core/resource.js";
7
8
  import { fetchSource, parseSourceUrl, synchronizeSource, uploadSource } from "./core/source.js";
8
9
  import type { InitializedWire, SwitchedWireBackend, WatchCapability, WatchHandle, WireBackend, WireConfig, WireWatchConfig, WireWorkspace } from "./ports.js";
@@ -139,9 +140,28 @@ function changeSummary(before: string, after: string) {
139
140
  return { added: added - modified, removed: removed - modified, modified };
140
141
  }
141
142
 
142
- async function existingResource(registry: Registry, service: string, identifier: string): Promise<Resource | null> {
143
- const resources = await registry.listResources();
144
- return resources.find((resource) => resource.identifiers.some((item) => item.service === service && item.identifier === identifier)) ?? null;
143
+ function legacyDefaultTab<FetchInput>(resource: Resource, catalog: ServiceCatalog<FetchInput>): Source | null {
144
+ if (resource.type !== "document" || !resource.id.startsWith("google-docs:") || resource.id.includes("#tab=")) return null;
145
+ for (const url of resource.urls) {
146
+ const parsed = new URL(url);
147
+ const service = catalog.find((item) => item.name === "google-docs" && item.matches(parsed));
148
+ const source = service?.parse(parsed);
149
+ if (source && source["document_tab"] === "t.0" && resource.id === `google-docs:${source["document_id"]}`) return source;
150
+ }
151
+ return null;
152
+ }
153
+
154
+ function findResource<FetchInput>(resources: readonly Resource[], source: Source, catalog: ServiceCatalog<FetchInput>): Resource | null {
155
+ const current = resources.find((item) => item.identifiers.some((identifier) => identifier.service === source.service && identifier.identifier === source.identifier));
156
+ if (source.service !== "google-docs" || source.type !== "document") return current ?? null;
157
+ if (current && legacyDefaultTab(current, catalog) && !source["document_tab"]) throw new Error(`The existing file ${primaryLink(current).path} is registered to the explicit default tab. Sync that path before attaching the whole document.`);
158
+ if (source["document_tab"] !== "t.0") return current ?? null;
159
+ const legacy = resources.find((item) => item.id === `google-docs:${source["document_id"]}` && legacyDefaultTab(item, catalog) !== null);
160
+ if (!legacy) return current ?? null;
161
+ if (current && stableJsonCompact({ ...legacy, id: resourceId(source), identifiers: [{ service: source.service, identifier: source.identifier }] }) !== stableJsonCompact(current)) {
162
+ throw new Error(`Two Wire records point to the default tab: ${primaryLink(legacy).path} and ${primaryLink(current).path}. Back up both files and reconcile them before detaching the duplicate by its resource ID (${current.id}). No files were changed.`);
163
+ }
164
+ return legacy;
145
165
  }
146
166
 
147
167
  function jsonObject(value: JsonValue): value is JsonObject {
@@ -191,11 +211,12 @@ function errorMessage(error: unknown): string {
191
211
  }
192
212
 
193
213
  export function composeWire<FetchInput>(dependencies: WireDependencies<FetchInput>): Wire {
194
- const store = async (url: string, path: string, fetched: FetchedDocument, previousMarkdown: string | null, action: WireAction, fixedOutputPath: string | undefined, summaryMarkdown: string | undefined, summaryAfterMarkdown: string): Promise<WireResult> => {
214
+ const store = async (url: string, path: string, fetched: FetchedDocument, previousMarkdown: string | null | undefined, action: WireAction, fixedOutputPath: string | undefined, summaryMarkdown: string | undefined, summaryAfterMarkdown: string): Promise<WireResult> => {
195
215
  const source = parseSourceUrl(url, dependencies.catalog);
196
216
  const root = await wireRoot(dependencies, path);
197
217
  const registry = await dependencies.workspace.openRegistry(root, dependencies.home);
198
- const current = await existingResource(registry, source.service, source.identifier);
218
+ const current = findResource(await registry.listResources(), source, dependencies.catalog);
219
+ if (current && legacyDefaultTab(current, dependencies.catalog)) throw new Error(`Sync ${primaryLink(current).path} first to migrate its default-tab registration.`);
199
220
  let outputPath: string;
200
221
  if (current !== null) outputPath = join(dirname(root), primaryLink(current).path);
201
222
  else if (fixedOutputPath !== undefined) outputPath = fixedOutputPath;
@@ -204,13 +225,19 @@ export function composeWire<FetchInput>(dependencies: WireDependencies<FetchInpu
204
225
  await dependencies.filesystem.exists(candidate) || (await registry.findByPath(dependencies.workspace.relativePath(candidate, root))).length > 0);
205
226
  }
206
227
  const relativePath = dependencies.workspace.relativePath(outputPath, root);
207
- const previous = previousMarkdown === null ? await dependencies.filesystem.exists(outputPath) ? await dependencies.filesystem.readText(outputPath) : "" : previousMarkdown;
228
+ const onDisk = await dependencies.filesystem.exists(outputPath) ? await dependencies.filesystem.readText(outputPath) : null;
229
+ const previous = (previousMarkdown === undefined ? onDisk : previousMarkdown) ?? "";
230
+ const concurrentEdit = previousMarkdown !== undefined && onDisk !== previousMarkdown && onDisk !== fetched.markdown;
231
+ const retry = `Local file changed during sync: ${relativePath}. Local changes were preserved. Run wire sync again.`;
232
+ // Only advance the common base if the editor saw that version. Otherwise a retry
233
+ // could mistake remote additions that never reached disk for local deletions.
234
+ if (concurrentEdit && current !== null && fetched.markdown !== previousMarkdown) throw new Error(retry);
208
235
  if (action === "attached" && current !== null) {
209
236
  const snapshot = current.data.find((item) => item.namespace === source.service && item.key === "snapshot")!.value;
210
237
  const baseMarkdown = markdownSnapshot(syncBase(source.service, snapshot, current.data));
211
238
  if (baseMarkdown !== null && previous !== baseMarkdown) throw new Error(`Local edits exist for ${primaryLink(current).path}. Run \`wire sync ${primaryLink(current).path}\` before attaching this URL again.`);
212
239
  }
213
- await dependencies.filesystem.writeText(outputPath, fetched.markdown);
240
+ if (!concurrentEdit && onDisk !== fetched.markdown) await dependencies.filesystem.writeText(outputPath, fetched.markdown);
214
241
  const id = resourceId(source);
215
242
  const primary = current?.filesystem_links.find((link) => link.path === relativePath && link.role === "primary");
216
243
  const resource: Resource = {
@@ -233,6 +260,7 @@ export function composeWire<FetchInput>(dependencies: WireDependencies<FetchInpu
233
260
  relationships: extractRelationships(fetched.markdown, id, dependencies.catalog),
234
261
  };
235
262
  const stored = await registry.put(resource);
263
+ if (concurrentEdit) throw new Error(retry);
236
264
  const changes = changeSummary(summaryMarkdown ?? previous, summaryAfterMarkdown);
237
265
  const resolvedAction = action === "attached" && current !== null && previous !== "" ? changes.added === 0 && changes.modified === 0 && changes.removed === 0 ? "synced" : "downloaded" : action;
238
266
  return { resource: stored, path: outputPath, markdown: fetched.markdown, summary: { action: resolvedAction, ...changes, remote: url, local: outputPath } };
@@ -240,7 +268,7 @@ export function composeWire<FetchInput>(dependencies: WireDependencies<FetchInpu
240
268
 
241
269
  const attach = async (url: string, path: string): Promise<WireResult> => {
242
270
  const fetched = await fetchSource(dependencies.fetchInput, url, dependencies.catalog);
243
- return store(url, path, fetched, null, "attached", undefined, undefined, fetched.markdown);
271
+ return store(url, path, fetched, undefined, "attached", undefined, undefined, fetched.markdown);
244
272
  };
245
273
  const create = attach;
246
274
 
@@ -305,8 +333,8 @@ export function composeWire<FetchInput>(dependencies: WireDependencies<FetchInpu
305
333
  if (value.startsWith("http://") || value.startsWith("https://")) {
306
334
  const source = parseSourceUrl(value, dependencies.catalog);
307
335
  const resources = await registry.listResources();
308
- const resource = resources.find((item) => item.identifiers.some((identifier) => identifier.service === source.service && identifier.identifier === source.identifier));
309
- if (resource === undefined) throw new Error(`Resource URL not found: ${value}`);
336
+ const resource = findResource(resources, source, dependencies.catalog);
337
+ if (resource === null) throw new Error(`Resource URL not found: ${value}`);
310
338
  return resource;
311
339
  }
312
340
  const candidatePath = resolve(path, value);
@@ -314,6 +342,10 @@ export function composeWire<FetchInput>(dependencies: WireDependencies<FetchInpu
314
342
  const resources = await registry.findByPath(relativePath);
315
343
  if (resources.length > 0 || await dependencies.filesystem.exists(candidatePath)) {
316
344
  if (resources.length === 0) throw new Error(`Resource path is not registered: ${value}`);
345
+ if (resources.length === 2) {
346
+ const tab = resources.map((item) => legacyDefaultTab(item, dependencies.catalog)).find((item) => item !== null);
347
+ if (tab && resources.some((item) => item.id === resourceId(tab))) return findResource(resources, tab, dependencies.catalog)!;
348
+ }
317
349
  if (resources.length > 1) throw new Error(`Ambiguous resource path ${relativePath}: ${resources.map((resource) => resource.id).join(", ")}. Use a resource id or URL.`);
318
350
  return resources[0]!;
319
351
  }
@@ -335,14 +367,27 @@ export function composeWire<FetchInput>(dependencies: WireDependencies<FetchInpu
335
367
  const resource = await resolveResource(registry, value, root, path);
336
368
  const outputPath = join(dirname(root), primaryLink(resource).path);
337
369
  const outputDirectory = dirname(outputPath);
338
- const source = parseSourceUrl(resource.urls[0]!, dependencies.catalog);
339
- const snapshot = resource.data.find((item) => item.namespace === source.service && item.key === "snapshot")!.value;
370
+ const source = legacyDefaultTab(resource, dependencies.catalog) ?? parseSourceUrl(resource.urls[0]!, dependencies.catalog);
371
+ const snapshot = resource.data.find((item) => item.namespace === source.service && item.key === "snapshot")?.value;
372
+ if (snapshot === undefined) throw new Error(`Missing saved snapshot for ${primaryLink(resource).path}. Keep the local file and download a separate copy to reconcile before syncing.`);
340
373
  if (!(await dependencies.filesystem.exists(outputPath))) throw new Error(`Linked file missing: ${primaryLink(resource).path} - restore it or run wire detach`);
341
374
  const markdown = await dependencies.filesystem.readText(outputPath);
342
375
  const base = syncBase(source.service, snapshot, resource.data);
343
376
  const baseMarkdown = markdownSnapshot(base);
344
377
  const localChanged = baseMarkdown !== null && markdown !== baseMarkdown;
345
378
  if (localChanged && !serviceCanSynchronize(resource.urls[0]!, dependencies.catalog)) throw new Error(`${source.service} is download-only and the local file has edits. Run \`wire download ${primaryLink(resource).path}\` to discard them.`);
379
+ if (source.service === "google-docs" && source["document_tab"] === "t.0") {
380
+ const registered = findResource(await registry.listResources(), source, dependencies.catalog);
381
+ if (registered && legacyDefaultTab(registered, dependencies.catalog)) {
382
+ if (registered.urls.length !== 1 || registered.identifiers.length !== 1 || registered.identifiers[0]!.identifier !== source["document_id"] || registered.filesystem_links.filter((link) => link.role === "primary").length !== 1 || !registry.rekey) {
383
+ throw new Error(`Cannot migrate the ambiguous default-tab registration ${registered.id}. Back up the linked files and check the URLs, primary paths, and registry backend before syncing. No files were changed.`);
384
+ }
385
+ if (baseMarkdown === null || markdown !== baseMarkdown) {
386
+ throw new Error(`Cannot migrate the old default-tab registration for ${primaryLink(registered).path}. Copy the local file somewhere safe, restore the linked file to its saved snapshot, then sync it and reapply only the edits for this tab. The local file and saved snapshot were kept.`);
387
+ }
388
+ await registry.rekey(registered, { service: source.service, identifier: source.identifier });
389
+ }
390
+ }
346
391
  const fetched = await synchronizeSource(dependencies.fetchInput, resource.urls[0]!, dependencies.catalog, base, markdown, outputPath);
347
392
  const action = localChanged ? fetched.markdown === baseMarkdown ? "synced" : "uploaded" : fetched.markdown === markdown ? "synced" : "downloaded";
348
393
  return store(resource.urls[0]!, outputDirectory, fetched, markdown, action, undefined, action === "uploaded" && baseMarkdown !== null ? baseMarkdown : undefined, action === "uploaded" ? markdown : fetched.markdown);
@@ -354,7 +399,7 @@ export function composeWire<FetchInput>(dependencies: WireDependencies<FetchInpu
354
399
  const registry = await dependencies.workspace.openRegistry(root, dependencies.home);
355
400
  const resource = await resolveResource(registry, value, root, path);
356
401
  const outputPath = join(dirname(root), primaryLink(resource).path);
357
- const markdown = await dependencies.filesystem.exists(outputPath) ? await dependencies.filesystem.readText(outputPath) : "";
402
+ const markdown = await dependencies.filesystem.exists(outputPath) ? await dependencies.filesystem.readText(outputPath) : null;
358
403
  const fetched = await fetchSource(dependencies.fetchInput, resource.urls[0]!, dependencies.catalog);
359
404
  return store(resource.urls[0]!, dirname(outputPath), fetched, markdown, "downloaded", undefined, undefined, fetched.markdown);
360
405
  };
@@ -392,21 +437,38 @@ export function composeWire<FetchInput>(dependencies: WireDependencies<FetchInpu
392
437
  let resolveClosed!: () => void;
393
438
  const closed = new Promise<void>((resolveClosedPromise) => { resolveClosed = resolveClosedPromise; });
394
439
  const handles: WatchHandle[] = [];
395
- const synchronize = async () => {
396
- const result = config.mode === "download" ? await runWatchHooks(hooks, "download", await download(value, path)) : await runWatchHooks(hooks, "sync", await sync(value, path));
397
- lastSyncedMarkdown = result.markdown;
398
- };
399
- const schedule = () => {
400
- if (debounce !== undefined) clearTimeout(debounce);
401
- debounce = setTimeout(() => {
402
- debounce = undefined;
403
- void synchronize();
404
- }, config.debounceMs);
440
+ let active = false, pending = false, poll = false, stopped = false;
441
+ const synchronize = async (forcePoll: boolean) => {
442
+ if (stopped) return;
443
+ pending = true;
444
+ poll ||= forcePoll;
445
+ if (active) return;
446
+ active = true;
447
+ try {
448
+ while (pending && !stopped) {
449
+ const checkRemote = poll;
450
+ pending = poll = false;
451
+ try {
452
+ if (!checkRemote && await dependencies.filesystem.readText(outputPath) === lastSyncedMarkdown) continue;
453
+ const result = config.mode === "download" ? await runWatchHooks(hooks, "download", await download(value, path)) : await runWatchHooks(hooks, "sync", await sync(value, path));
454
+ lastSyncedMarkdown = result.markdown;
455
+ } catch (error) {
456
+ console.warn(`Wire watch: ${errorMessage(error)}`);
457
+ }
458
+ }
459
+ } finally {
460
+ active = false;
461
+ if (stopped) resolveClosed();
462
+ }
405
463
  };
406
- handles.push(dependencies.watch!.every(config.pollMs, synchronize));
464
+ handles.push(dependencies.watch!.every(config.pollMs, () => synchronize(true)));
407
465
  if (config.mode === "two-way") {
408
- handles.push(dependencies.watch!.watchFile(outputPath, async () => {
409
- if (await dependencies.filesystem.readText(outputPath) !== lastSyncedMarkdown) schedule();
466
+ handles.push(dependencies.watch!.watchFile(outputPath, () => {
467
+ if (debounce !== undefined) clearTimeout(debounce);
468
+ debounce = setTimeout(() => {
469
+ debounce = undefined;
470
+ void synchronize(false);
471
+ }, config.debounceMs);
410
472
  }));
411
473
  }
412
474
  return Object.freeze({
@@ -417,9 +479,10 @@ export function composeWire<FetchInput>(dependencies: WireDependencies<FetchInpu
417
479
  pollMs: config.pollMs,
418
480
  closed,
419
481
  close: () => {
482
+ stopped = true;
420
483
  if (debounce !== undefined) clearTimeout(debounce);
421
484
  for (const handle of handles) handle.close();
422
- resolveClosed();
485
+ if (!active) resolveClosed();
423
486
  },
424
487
  });
425
488
  };
@@ -1,7 +1,7 @@
1
1
  import { execFile } from "node:child_process";
2
2
  import { existsSync, watch } from "node:fs";
3
3
  import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
4
- import { dirname } from "node:path";
4
+ import { basename, dirname } from "node:path";
5
5
  import { promisify } from "node:util";
6
6
  import { createCookiesCapability } from "./cookies.js";
7
7
  import { createGoogleTokensCapability } from "./google.js";
@@ -57,7 +57,11 @@ export function createNodeOpenFiles(processCapability: ProcessCapability): OpenF
57
57
  export function createNodeWatch(): WatchCapability {
58
58
  return Object.freeze({
59
59
  watchFile: (path: string, onChange: () => void | Promise<void>) => {
60
- const watcher = watch(path, () => { void onChange(); });
60
+ // Editors often replace the inode on save. Watch its name in the directory.
61
+ const name = basename(path);
62
+ const watcher = watch(dirname(path), (_event, filename) => {
63
+ if (filename === null || filename === name) void onChange();
64
+ });
61
65
  return Object.freeze({ close: () => watcher.close() });
62
66
  },
63
67
  every: (milliseconds: number, onTick: () => void | Promise<void>) => {
@@ -1,12 +1,12 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { existsSync, mkdirSync, realpathSync } from "node:fs";
3
- import { open, readdir, readFile, rename, unlink } from "node:fs/promises";
3
+ import { link, open, readdir, readFile, rename, unlink } from "node:fs/promises";
4
4
  import { createRequire } from "node:module";
5
5
  import { basename, dirname, extname, join, sep } from "node:path";
6
6
  import type { DatabaseSync } from "node:sqlite";
7
7
 
8
8
  import { stableJsonCompact, stableJsonPretty } from "../core/json.js";
9
- import type { JsonObject, JsonValue, Registry, Resource, ResourceType } from "../core/model.js";
9
+ import type { Identifier, JsonObject, JsonValue, Registry, Resource, ResourceType } from "../core/model.js";
10
10
  import { normalizeResource } from "../core/resource.js";
11
11
 
12
12
  type ResourceRow = Readonly<{ id: string; type: ResourceType }>;
@@ -164,6 +164,24 @@ export class SqliteRegistry implements Registry {
164
164
  return normalized;
165
165
  }
166
166
 
167
+ async rekey(previous: Resource, identifier: Identifier): Promise<Resource> {
168
+ const database = this.connect();
169
+ const id = `${identifier.service}:${identifier.identifier}`;
170
+ try {
171
+ database.exec("BEGIN IMMEDIATE; PRAGMA defer_foreign_keys=ON");
172
+ if (stableJsonCompact(this.getResource(database, previous.id)) !== stableJsonCompact(previous)) throw new Error("The Wire record changed during migration. Retry sync.");
173
+ database.prepare("UPDATE resources SET id = ? WHERE id = ?").run(id, previous.id);
174
+ database.prepare("UPDATE resource_identifiers SET resource_id = ?, identifier = ? WHERE resource_id = ?").run(id, identifier.identifier, previous.id);
175
+ for (const table of ["resource_urls", "filesystem_links", "resource_data"]) database.prepare(`UPDATE ${table} SET resource_id = ? WHERE resource_id = ?`).run(id, previous.id);
176
+ database.prepare("UPDATE resource_relationships SET source_id = ? WHERE source_id = ?").run(id, previous.id);
177
+ const migrated = this.getResource(database, id);
178
+ database.exec("COMMIT");
179
+ return migrated;
180
+ } finally {
181
+ database.close();
182
+ }
183
+ }
184
+
167
185
  async get(resourceId: string): Promise<Resource> {
168
186
  const database = this.connect();
169
187
  const row = database.prepare("SELECT id FROM resources WHERE id = ?").get(resourceId) as IdRow | undefined;
@@ -286,6 +304,27 @@ export class FileRegistry implements Registry {
286
304
  return normalized;
287
305
  }
288
306
 
307
+ async rekey(previous: Resource, identifier: Identifier): Promise<Resource> {
308
+ const migrated = storageResource({ ...previous, id: `${identifier.service}:${identifier.identifier}`, identifiers: [identifier] });
309
+ if (stableJsonCompact(await this.get(previous.id)) !== stableJsonCompact(previous)) throw new Error("The Wire record changed during migration. Retry sync.");
310
+ // Publish a complete replacement without overwriting another record. If the
311
+ // process stops before unlinking the old file, a retry recognizes its exact copy.
312
+ const temp = join(this.path, randomUUID());
313
+ const handle = await open(temp, "wx", 0o600);
314
+ try {
315
+ try { await handle.writeFile(`${stableJsonPretty(migrated)}\n`, "utf8"); } finally { await handle.close(); }
316
+ try {
317
+ await link(temp, this.resourcePath(migrated.id));
318
+ } catch (error) {
319
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST" || stableJsonCompact(await this.get(migrated.id)) !== stableJsonCompact(migrated)) throw error;
320
+ }
321
+ await unlink(this.resourcePath(previous.id));
322
+ } finally {
323
+ await unlink(temp);
324
+ }
325
+ return migrated;
326
+ }
327
+
289
328
  async get(resourceId: string): Promise<Resource> {
290
329
  if (!existsSync(this.resourcePath(resourceId))) throw missingResource(resourceId);
291
330
  return parseResource(await readFile(this.resourcePath(resourceId), "utf8"));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kamilio/wire",
3
- "version": "0.1.44",
3
+ "version": "0.1.45",
4
4
  "description": "Attach Notion, Google Docs, Slack, Gmail, Asana, ChatGPT, and Zoom resources as local Markdown you can sync.",
5
5
  "keywords": [
6
6
  "markdown",
@@ -220,6 +220,9 @@ function wireUserErrorMessage(message: string): boolean {
220
220
  || /^Indented Notion Markdown block has no parent at indent \d+$/.test(message)
221
221
  || /^POST [A-Za-z0-9]+ failed: \d+ /.test(message)
222
222
  || /^Google (Docs|Sheets|Slides) changed remotely and locally\./.test(message)
223
+ || /^Google Docs (uploads require|saved snapshot predates|OAuth |block |read rate limited|changed before|export (?:did not include|returned an unexpected))/.test(message)
224
+ || /^Google Drive comment check failed: HTTP/.test(message)
225
+ || /^Google Docs (?:Markdown|Word) export failed: OAuth access denied/.test(message)
223
226
  || /^Google Docs local edit cannot be mapped to the live document text$/.test(message)
224
227
  || /^Google Docs sync cannot upload formatting-only Markdown edits$/.test(message)
225
228
  || /^Google Docs sync cannot preserve formatting in edited text$/.test(message)
@@ -288,8 +291,8 @@ function wireUserErrorDisplayMessage(message: string): string {
288
291
  if (googleSaveFailed !== null) return `save failed\nservice: Google Docs/Sheets/Slides\nsource: Google ${googleSaveFailed[1]!}\ndetail: ${lineText(googleSaveFailed[2]!)}`;
289
292
  const googleSaveVerification = /^Google (Docs|Sheets) save verification failed$/.exec(message);
290
293
  if (googleSaveVerification !== null) return `save verification failed\nservice: Google Docs/Sheets/Slides\nsource: Google ${googleSaveVerification[1]!}`;
291
- const googleConflict = /^Google (Docs|Sheets|Slides) changed remotely and locally\. Resolve the conflict in Google (Docs|Sheets|Slides) or the local Markdown file before syncing again\.$/.exec(message);
292
- if (googleConflict !== null) return `sync conflict\nservice: Google Docs/Sheets/Slides\nsource: Google ${googleConflict[1]!}\nresolve: edit Google ${googleConflict[2]!} or local Markdown, then sync again`;
294
+ const googleConflict = /^Google (Docs|Sheets|Slides) changed remotely and locally\.(?: Local Markdown (lines?) (\d+(?:-\d+)?(?: \(start of block\))?)\.)? Resolve the conflict in Google (Docs|Sheets|Slides) or the local Markdown file before syncing again\.$/.exec(message);
295
+ if (googleConflict !== null) return `sync conflict\nservice: Google Docs/Sheets/Slides\nsource: Google ${googleConflict[1]!}${googleConflict[2] ? `\nlocal Markdown ${googleConflict[2]}: ${googleConflict[3]}` : ""}\nresolve: edit Google ${googleConflict[4]!} or local Markdown, then sync again`;
293
296
  const googleDocsMapping = /^Google Docs local edit cannot be mapped to the live document text$/.exec(message);
294
297
  if (googleDocsMapping !== null) return "local edit not mappable\nservice: Google Docs/Sheets/Slides\nsource: Google Docs\nresolve: edit Google Docs or simplify local Markdown";
295
298
  const googleFormattingOnly = /^Google Docs sync cannot upload formatting-only Markdown edits$/.exec(message);