@kamilio/wire 0.1.55 → 0.1.57

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 (138) hide show
  1. package/README.md +44 -1
  2. package/dist/adapters/codesignal.d.ts +10 -0
  3. package/dist/adapters/codesignal.d.ts.map +1 -0
  4. package/dist/adapters/codesignal.js +165 -0
  5. package/dist/adapters/codesignal.js.map +1 -0
  6. package/dist/adapters/document-shell.d.ts +7 -0
  7. package/dist/adapters/document-shell.d.ts.map +1 -0
  8. package/dist/adapters/document-shell.js +51 -0
  9. package/dist/adapters/document-shell.js.map +1 -0
  10. package/dist/adapters/root.d.ts.map +1 -1
  11. package/dist/adapters/root.js +74 -8
  12. package/dist/adapters/root.js.map +1 -1
  13. package/dist/auth.d.ts +2 -1
  14. package/dist/auth.d.ts.map +1 -1
  15. package/dist/auth.js +4 -2
  16. package/dist/auth.js.map +1 -1
  17. package/dist/cli.d.ts.map +1 -1
  18. package/dist/cli.js +10 -4
  19. package/dist/cli.js.map +1 -1
  20. package/dist/document-shell-engine.mjs +1880 -0
  21. package/dist/executable.d.ts.map +1 -1
  22. package/dist/executable.js +3 -2
  23. package/dist/executable.js.map +1 -1
  24. package/dist/hooks.d.ts.map +1 -1
  25. package/dist/hooks.js +19 -19
  26. package/dist/hooks.js.map +1 -1
  27. package/node_modules/provider-asana/dist/asana-project.d.ts +7 -1
  28. package/node_modules/provider-asana/dist/asana-project.d.ts.map +1 -1
  29. package/node_modules/provider-asana/dist/asana-task.d.ts +7 -1
  30. package/node_modules/provider-asana/dist/asana-task.d.ts.map +1 -1
  31. package/node_modules/provider-asana/dist/index.d.ts +14 -2
  32. package/node_modules/provider-asana/dist/index.d.ts.map +1 -1
  33. package/node_modules/provider-chatgpt/dist/chatgpt.d.ts +7 -1
  34. package/node_modules/provider-chatgpt/dist/chatgpt.d.ts.map +1 -1
  35. package/node_modules/provider-chatgpt/dist/index.d.ts +7 -1
  36. package/node_modules/provider-chatgpt/dist/index.d.ts.map +1 -1
  37. package/node_modules/provider-gmail/dist/gmail.d.ts +7 -1
  38. package/node_modules/provider-gmail/dist/gmail.d.ts.map +1 -1
  39. package/node_modules/provider-gmail/dist/index.d.ts +7 -1
  40. package/node_modules/provider-gmail/dist/index.d.ts.map +1 -1
  41. package/node_modules/provider-google-docs/dist/doc-blocks.d.ts.map +1 -1
  42. package/node_modules/provider-google-docs/dist/doc-blocks.js +6 -2
  43. package/node_modules/provider-google-docs/dist/doc-blocks.js.map +1 -1
  44. package/node_modules/provider-google-docs/dist/google-docs.d.ts +7 -1
  45. package/node_modules/provider-google-docs/dist/google-docs.d.ts.map +1 -1
  46. package/node_modules/provider-google-docs/dist/google-docs.js +31 -10
  47. package/node_modules/provider-google-docs/dist/google-docs.js.map +1 -1
  48. package/node_modules/provider-google-docs/dist/google-forms.d.ts +7 -1
  49. package/node_modules/provider-google-docs/dist/google-forms.d.ts.map +1 -1
  50. package/node_modules/provider-google-docs/dist/index.d.ts +14 -2
  51. package/node_modules/provider-google-docs/dist/index.d.ts.map +1 -1
  52. package/node_modules/provider-google-docs/src/doc-blocks.ts +8 -2
  53. package/node_modules/provider-google-docs/src/google-docs.ts +26 -10
  54. package/node_modules/provider-lattice/dist/index.d.ts +14 -2
  55. package/node_modules/provider-lattice/dist/index.d.ts.map +1 -1
  56. package/node_modules/provider-notion/dist/index.d.ts +7 -1
  57. package/node_modules/provider-notion/dist/index.d.ts.map +1 -1
  58. package/node_modules/provider-notion/dist/notion-sync.d.ts +2 -2
  59. package/node_modules/provider-notion/dist/notion-sync.d.ts.map +1 -1
  60. package/node_modules/provider-notion/dist/notion-sync.js +24 -15
  61. package/node_modules/provider-notion/dist/notion-sync.js.map +1 -1
  62. package/node_modules/provider-notion/dist/notion.d.ts +7 -1
  63. package/node_modules/provider-notion/dist/notion.d.ts.map +1 -1
  64. package/node_modules/provider-notion/dist/notion.js +1 -1
  65. package/node_modules/provider-notion/dist/notion.js.map +1 -1
  66. package/node_modules/provider-notion/src/notion-sync.ts +23 -15
  67. package/node_modules/provider-notion/src/notion.ts +1 -1
  68. package/node_modules/provider-slack/dist/index.d.ts +7 -1
  69. package/node_modules/provider-slack/dist/index.d.ts.map +1 -1
  70. package/node_modules/provider-slack/dist/slack.d.ts +7 -1
  71. package/node_modules/provider-slack/dist/slack.d.ts.map +1 -1
  72. package/node_modules/provider-zoom/dist/index.d.ts +7 -1
  73. package/node_modules/provider-zoom/dist/index.d.ts.map +1 -1
  74. package/node_modules/provider-zoom/dist/zoom-hub.d.ts +7 -1
  75. package/node_modules/provider-zoom/dist/zoom-hub.d.ts.map +1 -1
  76. package/node_modules/wire-core/dist/core/editor-receipts.d.ts +5 -0
  77. package/node_modules/wire-core/dist/core/editor-receipts.d.ts.map +1 -0
  78. package/node_modules/wire-core/dist/core/editor-receipts.js +9 -0
  79. package/node_modules/wire-core/dist/core/editor-receipts.js.map +1 -0
  80. package/node_modules/wire-core/dist/core/model.d.ts +4 -1
  81. package/node_modules/wire-core/dist/core/model.d.ts.map +1 -1
  82. package/node_modules/wire-core/dist/core/owner.d.ts +3 -0
  83. package/node_modules/wire-core/dist/core/owner.d.ts.map +1 -0
  84. package/node_modules/wire-core/dist/core/owner.js +16 -0
  85. package/node_modules/wire-core/dist/core/owner.js.map +1 -0
  86. package/node_modules/wire-core/dist/core/source.d.ts +4 -1
  87. package/node_modules/wire-core/dist/core/source.d.ts.map +1 -1
  88. package/node_modules/wire-core/dist/core/source.js +12 -2
  89. package/node_modules/wire-core/dist/core/source.js.map +1 -1
  90. package/node_modules/wire-core/dist/index.d.ts +1 -1
  91. package/node_modules/wire-core/dist/index.d.ts.map +1 -1
  92. package/node_modules/wire-core/dist/index.js +1 -1
  93. package/node_modules/wire-core/dist/index.js.map +1 -1
  94. package/node_modules/wire-core/dist/operations.d.ts +11 -2
  95. package/node_modules/wire-core/dist/operations.d.ts.map +1 -1
  96. package/node_modules/wire-core/dist/operations.js +399 -31
  97. package/node_modules/wire-core/dist/operations.js.map +1 -1
  98. package/node_modules/wire-core/dist/runtime/cookies.js +1 -1
  99. package/node_modules/wire-core/dist/runtime/cookies.js.map +1 -1
  100. package/node_modules/wire-core/dist/storage/editor-receipts.d.ts +17 -0
  101. package/node_modules/wire-core/dist/storage/editor-receipts.d.ts.map +1 -0
  102. package/node_modules/wire-core/dist/storage/editor-receipts.js +27 -0
  103. package/node_modules/wire-core/dist/storage/editor-receipts.js.map +1 -0
  104. package/node_modules/wire-core/dist/storage/history-integrity.d.ts +4 -0
  105. package/node_modules/wire-core/dist/storage/history-integrity.d.ts.map +1 -0
  106. package/node_modules/wire-core/dist/storage/history-integrity.js +32 -0
  107. package/node_modules/wire-core/dist/storage/history-integrity.js.map +1 -0
  108. package/node_modules/wire-core/dist/storage/history.d.ts +93 -0
  109. package/node_modules/wire-core/dist/storage/history.d.ts.map +1 -0
  110. package/node_modules/wire-core/dist/storage/history.js +450 -0
  111. package/node_modules/wire-core/dist/storage/history.js.map +1 -0
  112. package/node_modules/wire-core/dist/storage/registry.d.ts +2 -2
  113. package/node_modules/wire-core/dist/storage/registry.d.ts.map +1 -1
  114. package/node_modules/wire-core/dist/storage/registry.js +34 -14
  115. package/node_modules/wire-core/dist/storage/registry.js.map +1 -1
  116. package/node_modules/wire-core/dist/storage/workspace.d.ts.map +1 -1
  117. package/node_modules/wire-core/dist/storage/workspace.js +183 -40
  118. package/node_modules/wire-core/dist/storage/workspace.js.map +1 -1
  119. package/node_modules/wire-core/src/core/editor-receipts.ts +8 -0
  120. package/node_modules/wire-core/src/core/model.ts +4 -1
  121. package/node_modules/wire-core/src/core/owner.ts +16 -0
  122. package/node_modules/wire-core/src/core/source.ts +13 -1
  123. package/node_modules/wire-core/src/index.ts +1 -1
  124. package/node_modules/wire-core/src/operations.ts +339 -33
  125. package/node_modules/wire-core/src/runtime/cookies.ts +1 -1
  126. package/node_modules/wire-core/src/storage/editor-receipts.ts +27 -0
  127. package/node_modules/wire-core/src/storage/history-integrity.ts +25 -0
  128. package/node_modules/wire-core/src/storage/history.ts +331 -0
  129. package/node_modules/wire-core/src/storage/registry.ts +22 -15
  130. package/node_modules/wire-core/src/storage/workspace.ts +129 -34
  131. package/package.json +6 -2
  132. package/src/adapters/codesignal.ts +244 -0
  133. package/src/adapters/document-shell.ts +43 -0
  134. package/src/adapters/root.ts +76 -8
  135. package/src/auth.ts +6 -3
  136. package/src/cli.ts +10 -4
  137. package/src/executable.ts +3 -2
  138. package/src/hooks.ts +19 -18
@@ -1,9 +1,13 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
3
+ import { FileRegistry, SqliteRegistry } from "./storage/registry.js";
4
+ import { DocumentHistory, requireHistoryVolume, withHistoryLock, working } from "./storage/history.js";
5
+ import { editorFile, editorView, plainMarkdown } from "./storage/editor-receipts.js";
6
+ import { assertWireOwner } from "./core/owner.js";
3
7
  import { stableJsonCompact } from "./core/json.js";
4
8
  import { extractRelationships, markdownFilename } from "./core/transform.js";
5
9
  import { resourceId } from "./core/resource.js";
6
- import { fetchSource, parseSourceUrl, synchronizeSource, uploadSource } from "./core/source.js";
10
+ import { fetchSource, parseSourceUrl, synchronizeSource, uploadSource, WireMergeConflict } from "./core/source.js";
7
11
  export const wireWatchHooks = Symbol("wireWatchHooks");
8
12
  async function wireRoot(dependencies, path) {
9
13
  const configured = await dependencies.workspace.configuredRoot(path, dependencies.home);
@@ -130,8 +134,31 @@ function errorMessage(error) {
130
134
  return JSON.stringify(error);
131
135
  return String(error);
132
136
  }
137
+ export { withHistoryLock };
138
+ export const sourceLock = (source) => source.service === "google-docs" && source.type === "document" ? "google-docs:" + String(source["document_id"] ?? source.identifier.split("#tab=")[0]) : resourceId(source);
133
139
  export function composeWire(dependencies) {
134
- const store = async (url, path, fetched, previousMarkdown, action, fixedOutputPath, summaryMarkdown, summaryAfterMarkdown) => {
140
+ const durable = (registry) => registry instanceof FileRegistry || registry instanceof SqliteRegistry;
141
+ const locked = async (root, registry, key, fn) => durable(registry) ? withHistoryLock(root, key, fn) : fn();
142
+ const owner = async (registry, source, url) => assertWireOwner(await registry.listResources(), source, dependencies.catalog.find(s => s.matches(new URL(url))));
143
+ const historyFor = async (root, registry, source) => durable(registry) ? DocumentHistory.load(root, resourceId(source), dependencies.now) : null;
144
+ const removeDetached = (registry) => async (before) => {
145
+ const current = (await registry.listResources()).find(r => r.id === before.id);
146
+ if (!current)
147
+ return;
148
+ if (stableJsonCompact(current) !== stableJsonCompact(before))
149
+ throw new Error("Registration changed during detach. The newer registration was kept.");
150
+ await registry.delete(before.id);
151
+ };
152
+ const restore = async (root, registry, source, path) => {
153
+ const history = await historyFor(root, registry, source);
154
+ await history?.recover(path, r => registry.put(r), removeDetached(registry));
155
+ return history;
156
+ };
157
+ const checkReceiptLink = (resource, h) => {
158
+ if (resource && (primaryLink(resource).data["editor_receipts"] === true) !== !!h?.refs.editorReceipts)
159
+ throw new Error("Missing Wire editor receipt history or link registration. Restore the link and its private history before syncing.");
160
+ };
161
+ const store = async (url, path, fetched, previousMarkdown, action, fixedOutputPath, summaryMarkdown, summaryAfterMarkdown, history, enableReceipts = false, expectedRaw) => {
135
162
  const source = parseSourceUrl(url, dependencies.catalog);
136
163
  const root = await wireRoot(dependencies, path);
137
164
  const registry = await dependencies.workspace.openRegistry(root, dependencies.home);
@@ -147,34 +174,46 @@ export function composeWire(dependencies) {
147
174
  outputPath = await availableMarkdownPath(path, fetched.title, source.service, source.identifier, async (candidate) => await dependencies.filesystem.exists(candidate) || (await registry.findByPath(dependencies.workspace.relativePath(candidate, root))).length > 0);
148
175
  }
149
176
  const relativePath = dependencies.workspace.relativePath(outputPath, root);
150
- const onDisk = await dependencies.filesystem.exists(outputPath) ? await dependencies.filesystem.readText(outputPath) : null;
177
+ checkReceiptLink(current, history);
178
+ plainMarkdown(fetched.markdown);
179
+ const raw = history ? await working(outputPath) : await dependencies.filesystem.exists(outputPath) ? await dependencies.filesystem.readText(outputPath) : null;
180
+ const view = raw === null ? null : history ? history.view(raw) : editorView(raw);
181
+ const onDisk = view?.markdown ?? null;
182
+ if (expectedRaw !== undefined && raw !== expectedRaw && (enableReceipts || history?.refs.editorReceipts))
183
+ throw new Error("Local file changed during sync; run wire sync again.");
184
+ if (!current && fixedOutputPath === undefined && onDisk !== null)
185
+ throw new Error("Another file appeared at the proposed attachment path; retry attach.");
151
186
  const previous = (previousMarkdown === undefined ? onDisk : previousMarkdown) ?? "";
152
187
  const concurrentEdit = previousMarkdown !== undefined && onDisk !== previousMarkdown && onDisk !== fetched.markdown;
153
188
  const retry = `Local file changed during sync: ${relativePath}. Local changes were preserved. Run wire sync again.`;
154
189
  // Only advance the common base if the editor saw that version. Otherwise a retry
155
190
  // could mistake remote additions that never reached disk for local deletions.
156
- if (concurrentEdit && current !== null && fetched.markdown !== previousMarkdown)
191
+ if (concurrentEdit && current !== null && fetched.markdown !== previousMarkdown) {
192
+ if (history) {
193
+ await history.observe(fetched);
194
+ await history.save();
195
+ }
157
196
  throw new Error(retry);
197
+ }
158
198
  if (action === "attached" && current !== null) {
159
199
  const snapshot = current.data.find((item) => item.namespace === source.service && item.key === "snapshot").value;
160
- const baseMarkdown = markdownSnapshot(syncBase(source.service, snapshot, current.data));
200
+ const baseMarkdown = markdownSnapshot(syncBase(source.service, snapshot, current.data)) ?? (history?.refs.base ? await history.text(history.refs.base) : null);
161
201
  if (baseMarkdown !== null && previous !== baseMarkdown)
162
202
  throw new Error(`Local edits exist for ${primaryLink(current).path}. Run \`wire sync ${primaryLink(current).path}\` before attaching this URL again.`);
163
203
  }
164
- if (!concurrentEdit && onDisk !== fetched.markdown)
165
- await dependencies.filesystem.writeText(outputPath, fetched.markdown);
166
204
  const id = resourceId(source);
167
205
  const primary = current?.filesystem_links.find((link) => link.path === relativePath && link.role === "primary");
206
+ const link = { path: relativePath, role: "primary", data: { ...(primary?.data ?? { format: "markdown" }), ...(enableReceipts ? { editor_receipts: true } : {}) } };
168
207
  const resource = {
169
208
  id,
170
209
  type: source.type,
171
210
  identifiers: [{ service: source.service, identifier: source.identifier }],
172
211
  urls: [url],
173
212
  filesystem_links: current === null
174
- ? [{ path: relativePath, role: "primary", data: { format: "markdown" } }]
213
+ ? [link]
175
214
  : [
176
215
  ...current.filesystem_links.filter((link) => !(link.path === relativePath && link.role === "primary")),
177
- primary ?? { path: relativePath, role: "primary", data: { format: "markdown" } },
216
+ link,
178
217
  ],
179
218
  data: [
180
219
  ...(current?.data.filter((item) => item.namespace !== "wire" && !(item.namespace === source.service && item.key === "snapshot")) ?? []),
@@ -184,16 +223,96 @@ export function composeWire(dependencies) {
184
223
  ],
185
224
  relationships: extractRelationships(fetched.markdown, id, dependencies.catalog),
186
225
  };
187
- const stored = await registry.put(resource);
226
+ let stored;
227
+ if (history) {
228
+ if (history.refs.conflict)
229
+ throw new Error("Unresolved Wire conflict. Review the saved revisions and use wire resolve.");
230
+ const currentBase = history.refs.base;
231
+ if (onDisk !== null && currentBase !== null && onDisk !== await history.text(currentBase) && (previousMarkdown === undefined || previousMarkdown === onDisk))
232
+ await history.captureLocal(onDisk, view?.shown ?? undefined);
233
+ const draft = history.refs.draft;
234
+ let next;
235
+ if (currentBase === null) {
236
+ const input = previousMarkdown === undefined || previousMarkdown === null || previousMarkdown === fetched.markdown ? null : await history.revision("local", previousMarkdown, []);
237
+ next = await history.revision("attach", fetched.markdown, [input]);
238
+ }
239
+ else if (draft !== null && draft !== currentBase && action !== "downloaded") {
240
+ const remote = history.refs.remote;
241
+ const merged = remote !== null && (remote !== currentBase || (view?.base != null && view.base !== currentBase));
242
+ next = await history.revision(merged ? "merge" : "local", fetched.markdown, merged ? [draft, remote] : [draft]);
243
+ }
244
+ else
245
+ next = await history.observe(fetched);
246
+ const refs = { ...history.refs, base: next, remote: next, draft: null, strict: false, resolution: null, resolutionParent: null, conflict: null };
247
+ delete refs.editorDraft;
248
+ // A confirmed push of the exact draft the editor already saw is safe to
249
+ // acknowledge even if another save arrived while it was in flight.
250
+ if (concurrentEdit && previousMarkdown === fetched.markdown) {
251
+ await history.publish(outputPath, onDisk ?? "", onDisk ?? "", refs, resource, r => registry.put(r), true);
252
+ stored = await registry.get(resource.id);
253
+ }
254
+ else if (concurrentEdit) {
255
+ if (current !== null)
256
+ throw new Error(retry);
257
+ refs.base = previousMarkdown == null ? next : await history.revision("local", previousMarkdown, []);
258
+ refs.resolution = fetched;
259
+ refs.resolutionParent = next;
260
+ await history.publish(outputPath, onDisk ?? "", onDisk ?? "", refs, resource, r => registry.put(r), true);
261
+ stored = await registry.get(resource.id);
262
+ }
263
+ else {
264
+ if (enableReceipts || refs.editorReceipts)
265
+ refs.editorReceipts = { ...refs.editorReceipts };
266
+ const materialized = refs.editorReceipts ? editorFile(fetched.markdown, refs.editorReceipts, next, next) : fetched.markdown;
267
+ await history.publish(outputPath, raw, materialized, refs, resource, r => registry.put(r));
268
+ stored = await registry.get(resource.id);
269
+ }
270
+ }
271
+ else {
272
+ if (!concurrentEdit && onDisk !== fetched.markdown)
273
+ await dependencies.filesystem.writeText(outputPath, fetched.markdown);
274
+ stored = await registry.put(resource);
275
+ }
188
276
  if (concurrentEdit)
189
277
  throw new Error(retry);
190
278
  const changes = changeSummary(summaryMarkdown ?? previous, summaryAfterMarkdown);
191
279
  const resolvedAction = action === "attached" && current !== null && previous !== "" ? changes.added === 0 && changes.modified === 0 && changes.removed === 0 ? "synced" : "downloaded" : action;
192
280
  return { resource: stored, path: outputPath, markdown: fetched.markdown, summary: { action: resolvedAction, ...changes, remote: url, local: outputPath } };
193
281
  };
194
- const attach = async (url, path) => {
195
- const fetched = await fetchSource(dependencies.fetchInput, url, dependencies.catalog);
196
- return store(url, path, fetched, undefined, "attached", undefined, undefined, fetched.markdown);
282
+ const attach = async (url, path, editorReceipts = false) => {
283
+ return attachAt(url, path, undefined, editorReceipts);
284
+ };
285
+ const attachAt = async (url, path, fixed, editorReceipts = false) => {
286
+ const root = await wireRoot(dependencies, path), initial = await dependencies.workspace.openRegistry(root, dependencies.home);
287
+ const source = parseSourceUrl(url, dependencies.catalog);
288
+ return locked(root, initial, sourceLock(source), async () => {
289
+ const registry = await dependencies.workspace.openRegistry(root, dependencies.home);
290
+ await owner(registry, source, url);
291
+ const h = await restore(root, registry, source);
292
+ const current = findResource(await registry.listResources(), source, dependencies.catalog);
293
+ checkReceiptLink(current, h);
294
+ if (editorReceipts && (!h || source.service !== "google-docs" || source.type !== "document" || dependencies.catalog.find(s => s.matches(new URL(url)))?.owner !== undefined))
295
+ throw new Error("Editor receipts require a generic Google Docs Markdown link with durable history.");
296
+ if (current && fixed !== undefined && join(dirname(root), primaryLink(current).path) !== fixed)
297
+ throw new Error("This URL is already attached at another path.");
298
+ if (fixed !== undefined && (await registry.findByPath(dependencies.workspace.relativePath(fixed, root))).some(r => r.id !== resourceId(source)))
299
+ throw new Error("This file already has another registration.");
300
+ if (h && current)
301
+ await h.seed(markdownSnapshot(current.data.find(i => i.namespace === source.service && i.key === "snapshot")?.value ?? null));
302
+ if (h?.refs.conflict)
303
+ throw new Error("Unresolved Wire conflict. Use wire resolve.");
304
+ if (h?.refs.strict)
305
+ throw new Error("Sync the pending Wire draft before attaching again.");
306
+ const trackedPath = current ? join(dirname(root), primaryLink(current).path) : fixed;
307
+ if (h)
308
+ await requireHistoryVolume(h.dir, trackedPath ? dirname(trackedPath) : path);
309
+ const raw = trackedPath && h ? await working(trackedPath) : undefined;
310
+ const existing = raw == null ? raw : h.view(raw).markdown;
311
+ const fetched = await fetchSource(dependencies.fetchInput, url, dependencies.catalog);
312
+ if (fixed !== undefined && (h ? existing : await dependencies.filesystem.readText(fixed)) !== fetched.markdown)
313
+ throw new Error("Cannot adopt: the existing file differs from the remote document.");
314
+ return store(url, path, fetched, fixed === undefined ? undefined : fetched.markdown, "attached", fixed, undefined, fetched.markdown, h, editorReceipts, raw);
315
+ });
197
316
  };
198
317
  const create = attach;
199
318
  const view = (url) => fetchSource(dependencies.fetchInput, url, dependencies.catalog);
@@ -283,31 +402,79 @@ export function composeWire(dependencies) {
283
402
  throw new Error(`Resource path not found: ${value}`);
284
403
  return registry.get(value);
285
404
  };
286
- const sync = async (value, path) => {
405
+ const syncInner = async (value, path) => {
287
406
  const candidatePath = resolve(path, value);
288
407
  const root = await wireRoot(dependencies, await dependencies.filesystem.exists(candidatePath) ? candidatePath : path);
289
408
  const registry = await dependencies.workspace.openRegistry(root, dependencies.home);
290
409
  const relativePath = dependencies.workspace.relativePath(candidatePath, root);
291
410
  const pathResources = await registry.findByPath(relativePath);
292
411
  if (pathResources.length === 0 && await dependencies.filesystem.exists(candidatePath)) {
293
- const markdown = await dependencies.filesystem.readText(candidatePath);
294
- const uploaded = await uploadSource(dependencies.fetchInput, dependencies.catalog, markdown, candidatePath);
295
- return store(uploaded.url, dirname(candidatePath), uploaded, markdown, "uploaded", candidatePath, undefined, uploaded.markdown);
412
+ if (durable(registry))
413
+ await requireHistoryVolume(join(root, "history"), dirname(candidatePath));
414
+ const markdown = durable(registry) ? await working(candidatePath) : await dependencies.filesystem.readText(candidatePath);
415
+ if (markdown === null)
416
+ throw new Error("Cannot upload a missing Markdown file.");
417
+ const uploaded = await uploadSource(dependencies.fetchInput, dependencies.catalog, plainMarkdown(markdown), candidatePath);
418
+ const source = parseSourceUrl(uploaded.url, dependencies.catalog);
419
+ return locked(root, registry, sourceLock(source), async () => store(uploaded.url, dirname(candidatePath), uploaded, markdown, "uploaded", candidatePath, undefined, uploaded.markdown, await restore(root, registry, source)));
296
420
  }
297
- const resource = await resolveResource(registry, value, root, path);
421
+ let resource = await resolveResource(registry, value, root, path);
298
422
  const outputPath = join(dirname(root), primaryLink(resource).path);
299
423
  const outputDirectory = dirname(outputPath);
300
424
  const source = legacyDefaultTab(resource, dependencies.catalog) ?? parseSourceUrl(resource.urls[0], dependencies.catalog);
425
+ await owner(registry, source, resource.urls[0]);
426
+ const history = await restore(root, registry, source, outputPath);
427
+ resource = await registry.get(resource.id);
428
+ if (history)
429
+ await requireHistoryVolume(history.dir, outputDirectory);
430
+ if (history?.refs.conflict && !("editor" in history.refs.conflict))
431
+ throw new Error("Unresolved Wire conflict. Inspect wire conflicts and use wire resolve.");
301
432
  const snapshot = resource.data.find((item) => item.namespace === source.service && item.key === "snapshot")?.value;
302
433
  if (snapshot === undefined)
303
434
  throw new Error(`Missing saved snapshot for ${primaryLink(resource).path}. Keep the local file and download a separate copy to reconcile before syncing.`);
304
435
  if (!(await dependencies.filesystem.exists(outputPath)))
305
436
  throw new Error(`Linked file missing: ${primaryLink(resource).path} - restore it or run wire detach`);
306
- const markdown = await dependencies.filesystem.readText(outputPath);
307
- const base = syncBase(source.service, snapshot, resource.data);
308
- const baseMarkdown = markdownSnapshot(base);
437
+ checkReceiptLink(resource, history);
438
+ let raw = history ? await working(outputPath) : await dependencies.filesystem.readText(outputPath);
439
+ if (raw === null)
440
+ throw new Error("Linked file missing: " + outputPath);
441
+ let view = history ? history.view(raw) : editorView(raw);
442
+ await history?.checkPendingDraft(view);
443
+ if (history?.refs.conflict && "editor" in history.refs.conflict) {
444
+ const c = history.refs.conflict;
445
+ const merge = dependencies.catalog.find(s => s.matches(new URL(resource.urls[0])))?.mergeDrafts;
446
+ const base = c.editorBase === c.shellBase ? history.commonAncestor(c.editor, c.shell) : null;
447
+ let merged;
448
+ // A user may already be reconciling the file. Never overwrite edits
449
+ // that arrived after the two local versions were captured.
450
+ const editor = await history.text(c.editor);
451
+ if (merge && base && view.markdown === editor && view.base === c.editorBase) {
452
+ const before = await history.text(base), shell = await history.text(c.shell);
453
+ try {
454
+ merged = merge(before, editor, shell);
455
+ }
456
+ catch { /* retain the saved conflict */ }
457
+ }
458
+ if (merged === undefined)
459
+ throw new Error("Unresolved Wire conflict. The editor save and shell draft are both local. Compare them with wire diff <resource> --from editor --to shell, then use wire resolve <resource> <choice>.");
460
+ const draft = await history.revision("merge", merged, [c.editor, c.shell]);
461
+ const receipts = { ...history.refs.editorReceipts };
462
+ const next = editorFile(merged, receipts, draft, c.editorBase);
463
+ await history.publish(outputPath, raw, next, { ...history.refs, conflict: null, editorReceipts: receipts, editorDraft: draft, draft, strict: true }, null, r => registry.put(r));
464
+ raw = next;
465
+ view = history.view(raw);
466
+ }
467
+ const markdown = view.markdown;
468
+ // A stale receipt proves Markdown ancestry, not native paragraph positions.
469
+ // Never attach a newer snapshot's verified revision or IDs to older bytes.
470
+ const base = view.base && history && view.base !== history.refs.base && view.base !== history.refs.resolutionParent
471
+ ? { markdown: await history.text(view.base) }
472
+ : history?.refs.resolution && (!view.base || view.base === history.refs.resolutionParent) ? storedSnapshot(history.refs.resolution) : syncBase(source.service, snapshot, resource.data);
473
+ if (history)
474
+ await history.seed(markdownSnapshot(snapshot));
475
+ const baseMarkdown = markdownSnapshot(base) ?? (history?.refs.base ? await history.text(history.refs.base) : null);
309
476
  const localChanged = baseMarkdown !== null && markdown !== baseMarkdown;
310
- if (localChanged && !serviceCanSynchronize(resource.urls[0], dependencies.catalog))
477
+ if (localChanged && !history?.refs.strict && !serviceCanSynchronize(resource.urls[0], dependencies.catalog))
311
478
  throw new Error(`${source.service} is download-only and the local file has edits. Run \`wire download ${primaryLink(resource).path}\` to discard them.`);
312
479
  if (source.service === "google-docs" && source["document_tab"] === "t.0") {
313
480
  const registered = findResource(await registry.listResources(), source, dependencies.catalog);
@@ -321,33 +488,123 @@ export function composeWire(dependencies) {
321
488
  await registry.rekey(registered, { service: source.service, identifier: source.identifier });
322
489
  }
323
490
  }
324
- const fetched = await synchronizeSource(dependencies.fetchInput, resource.urls[0], dependencies.catalog, base, markdown, outputPath);
491
+ if (history && (localChanged || history.refs.draft !== null))
492
+ await history.captureLocal(markdown, view.shown ?? undefined);
493
+ const strict = (history?.refs.strict === true || view.base !== null) && localChanged;
494
+ if (history && strict && source.service !== "notion" && !(source.service === "google-docs" && source.type === "document")) {
495
+ const remote = await fetchSource(dependencies.fetchInput, resource.urls[0], dependencies.catalog);
496
+ await history.observe(remote);
497
+ await history.save();
498
+ if (remote.markdown !== markdown)
499
+ throw new Error("This provider cannot conditionally publish a Wire draft. The local revision was kept. Apply it in the provider, then sync to verify.");
500
+ return store(resource.urls[0], outputDirectory, remote, markdown, "synced", undefined, undefined, remote.markdown, history);
501
+ }
502
+ const observed = {};
503
+ let observations = Promise.resolve();
504
+ const fork = view.base ?? (history?.refs.resolution ? history.refs.resolutionParent : history?.refs.base);
505
+ let fetched;
506
+ try {
507
+ fetched = await synchronizeSource(dependencies.fetchInput, resource.urls[0], dependencies.catalog, base, markdown, outputPath, remote => {
508
+ plainMarkdown(remote.markdown);
509
+ observed.remote = remote;
510
+ observations = observations.then(async () => { if (history) {
511
+ await history.observe(remote);
512
+ await history.save();
513
+ } });
514
+ return observations;
515
+ }, strict);
516
+ await observations;
517
+ }
518
+ catch (error) {
519
+ await observations;
520
+ if (history && error instanceof WireMergeConflict && observed.remote && history.refs.draft && history.refs.remote) {
521
+ if (fork) {
522
+ history.refs.conflict = { base: fork, local: history.refs.draft, remote: history.refs.remote };
523
+ history.refs.resolution = observed.remote;
524
+ history.refs.resolutionParent = history.refs.remote;
525
+ await history.save();
526
+ throw new Error("Unresolved Wire conflict. " + error.message + " Inspect wire conflicts and use wire resolve.", { cause: error });
527
+ }
528
+ }
529
+ throw error;
530
+ }
531
+ if (history && !observed.remote && fetched.markdown !== markdown) {
532
+ await history.observe(fetched);
533
+ await history.save();
534
+ }
325
535
  const uploaded = fetched.wroteRemote ?? (localChanged && fetched.markdown !== baseMarkdown);
326
536
  const action = uploaded ? "uploaded" : fetched.markdown === markdown || (localChanged && fetched.markdown === baseMarkdown) ? "synced" : "downloaded";
327
- return store(resource.urls[0], outputDirectory, fetched, markdown, action, undefined, action === "uploaded" && baseMarkdown !== null ? baseMarkdown : undefined, action === "uploaded" ? markdown : fetched.markdown);
537
+ return store(resource.urls[0], outputDirectory, fetched, markdown, action, undefined, action === "uploaded" && baseMarkdown !== null ? baseMarkdown : undefined, action === "uploaded" ? markdown : fetched.markdown, history, false, raw);
538
+ };
539
+ const underResourceLock = async (value, path, fn) => {
540
+ const candidate = resolve(path, value);
541
+ const root = await wireRoot(dependencies, await dependencies.filesystem.exists(candidate) ? candidate : path), registry = await dependencies.workspace.openRegistry(root, dependencies.home);
542
+ const ids = await registry.findByPath(dependencies.workspace.relativePath(candidate, root));
543
+ const key = !ids.length && await dependencies.filesystem.exists(candidate) ? "path:" + dependencies.workspace.relativePath(candidate, root) : sourceLock(parseSourceUrl((await resolveResource(registry, value, root, path)).urls[0], dependencies.catalog));
544
+ return locked(root, registry, key, fn);
328
545
  };
329
- const download = async (value, path) => {
546
+ const sync = (v, p) => underResourceLock(v, p, () => syncInner(v, p));
547
+ const downloadInner = async (value, path) => {
330
548
  const candidatePath = resolve(path, value);
331
549
  const root = await wireRoot(dependencies, await dependencies.filesystem.exists(candidatePath) ? candidatePath : path);
332
550
  const registry = await dependencies.workspace.openRegistry(root, dependencies.home);
333
551
  const resource = await resolveResource(registry, value, root, path);
334
552
  const outputPath = join(dirname(root), primaryLink(resource).path);
335
- const markdown = await dependencies.filesystem.exists(outputPath) ? await dependencies.filesystem.readText(outputPath) : null;
553
+ const source = parseSourceUrl(resource.urls[0], dependencies.catalog);
554
+ await owner(registry, source, resource.urls[0]);
555
+ const h = await restore(root, registry, source, outputPath);
556
+ await h?.seed(markdownSnapshot(resource.data.find(i => i.namespace === source.service && i.key === "snapshot")?.value ?? null));
557
+ if (h?.refs.conflict)
558
+ throw new Error("Unresolved Wire conflict. Use wire resolve.");
559
+ checkReceiptLink(resource, h);
560
+ const raw = h ? await working(outputPath) : await dependencies.filesystem.exists(outputPath) ? await dependencies.filesystem.readText(outputPath) : null;
561
+ const markdown = raw === null ? null : (h ? h.view(raw) : editorView(raw)).markdown;
562
+ if (h?.refs.strict && h.refs.draft)
563
+ throw new Error("Sync the pending Wire draft before downloading over it.");
336
564
  const fetched = await fetchSource(dependencies.fetchInput, resource.urls[0], dependencies.catalog);
337
- return store(resource.urls[0], dirname(outputPath), fetched, markdown, "downloaded", undefined, undefined, fetched.markdown);
565
+ return store(resource.urls[0], dirname(outputPath), fetched, markdown, "downloaded", undefined, undefined, fetched.markdown, h, false, raw);
338
566
  };
339
- const detach = async (value, path) => {
567
+ const download = (v, p) => underResourceLock(v, p, () => downloadInner(v, p));
568
+ const detachInner = async (value, path) => {
340
569
  const candidatePath = resolve(path, value);
341
570
  const root = await wireRoot(dependencies, await dependencies.filesystem.exists(candidatePath) ? candidatePath : path);
342
571
  const registry = await dependencies.workspace.openRegistry(root, dependencies.home);
343
572
  const resource = await resolveResource(registry, value, root, path);
344
573
  const outputPath = join(dirname(root), primaryLink(resource).path);
345
- const previous = await dependencies.filesystem.exists(outputPath) ? await dependencies.filesystem.readText(outputPath) : "";
574
+ const source = parseSourceUrl(resource.urls[0], dependencies.catalog);
575
+ await owner(registry, source, resource.urls[0]);
576
+ const h = await historyFor(root, registry, source);
577
+ const recovered = await h?.recover(outputPath, r => registry.put(r), removeDetached(registry));
578
+ if (recovered) {
579
+ const markdown = await h.text(h.refs.base);
580
+ return { resource: recovered, path: outputPath, markdown, summary: { action: "detached", added: 0, modified: 0, removed: 0, remote: recovered.urls[0], local: outputPath } };
581
+ }
582
+ checkReceiptLink(resource, h);
583
+ const initialRaw = h ? await working(outputPath) : await dependencies.filesystem.exists(outputPath) ? await dependencies.filesystem.readText(outputPath) : null;
584
+ const previousView = initialRaw === null ? null : (h ? h.view(initialRaw) : editorView(initialRaw));
585
+ const previous = previousView?.markdown ?? "";
586
+ if (h?.refs.conflict || h?.refs.strict)
587
+ throw new Error("Resolve and sync the Wire draft before detaching.");
346
588
  const fetched = await fetchSource(dependencies.fetchInput, resource.urls[0], dependencies.catalog);
347
- await dependencies.filesystem.writeText(outputPath, fetched.markdown);
348
- await registry.delete(resource.id);
589
+ if (h) {
590
+ const onDisk = await working(outputPath);
591
+ if (onDisk !== initialRaw)
592
+ throw new Error("Local file changed during detach; retry.");
593
+ if (previousView)
594
+ await h.captureLocal(previousView.markdown, previousView.shown ?? undefined);
595
+ const next = await h.observe(fetched);
596
+ const { editorReceipts, ...plainRefs } = h.refs;
597
+ if (editorReceipts)
598
+ plainRefs.retiredEditorReceipts = { ...plainRefs.retiredEditorReceipts, ...editorReceipts };
599
+ await h.detach(outputPath, onDisk, fetched.markdown, { ...plainRefs, base: next, remote: next, draft: null }, resource, removeDetached(registry));
600
+ }
601
+ else {
602
+ await dependencies.filesystem.writeText(outputPath, fetched.markdown);
603
+ await registry.delete(resource.id);
604
+ }
349
605
  return { resource, path: outputPath, markdown: fetched.markdown, summary: { action: "detached", ...changeSummary(previous, fetched.markdown), remote: resource.urls[0], local: outputPath } };
350
606
  };
607
+ const detach = (v, p) => underResourceLock(v, p, () => detachInner(v, p));
351
608
  const unlink = detach;
352
609
  const runWatchHooks = async (hooks, command, result) => {
353
610
  let current = result;
@@ -386,6 +643,12 @@ export function composeWire(dependencies) {
386
643
  continue;
387
644
  const result = config.mode === "download" ? await runWatchHooks(hooks, "download", await download(value, path)) : await runWatchHooks(hooks, "sync", await sync(value, path));
388
645
  lastSyncedMarkdown = result.markdown;
646
+ if (primaryLink(result.resource).data["editor_receipts"] === true) {
647
+ const h = await historyFor(root, registry, parseSourceUrl(result.resource.urls[0], dependencies.catalog));
648
+ if (h?.refs.editorReceipts && h.refs.base && await h.text(h.refs.base) === result.markdown) {
649
+ lastSyncedMarkdown = editorFile(result.markdown, h.refs.editorReceipts, h.refs.base, h.refs.base);
650
+ }
651
+ }
389
652
  }
390
653
  catch (error) {
391
654
  console.warn(`Wire watch: ${errorMessage(error)}`);
@@ -466,8 +729,113 @@ export function composeWire(dependencies) {
466
729
  const registry = await dependencies.workspace.openRegistry(root, dependencies.home);
467
730
  return resolveResource(registry, value, root, path);
468
731
  };
732
+ const withDocument = async (v, p, run) => underResourceLock(v, p, async () => {
733
+ const candidate = resolve(p, v), root = await wireRoot(dependencies, await dependencies.filesystem.exists(candidate) ? candidate : p);
734
+ const registry = await dependencies.workspace.openRegistry(root, dependencies.home);
735
+ let r = await resolveResource(registry, v, root, p);
736
+ const path = join(dirname(root), primaryLink(r).path);
737
+ const source = parseSourceUrl(r.urls[0], dependencies.catalog);
738
+ const h = await restore(root, registry, source, path);
739
+ if (!h)
740
+ throw new Error("This registry does not provide durable document history.");
741
+ r = await registry.get(r.id);
742
+ checkReceiptLink(r, h);
743
+ await h.seed(markdownSnapshot(r.data.find(i => i.namespace === source.service && i.key === "snapshot")?.value ?? null));
744
+ return run(h, path, registry, r);
745
+ });
746
+ const historyStatus = (v, p) => withDocument(v, p, async (h, path) => {
747
+ const raw = await working(path);
748
+ if (raw !== null)
749
+ await h.checkPendingDraft(h.view(raw));
750
+ return h.status(path);
751
+ });
752
+ const historyLog = (v, p) => withDocument(v, p, h => h.log());
753
+ const historyDiff = (v, p, from = "base", to = "working") => withDocument(v, p, async (h, path) => {
754
+ const raw = await working(path);
755
+ const current = raw === null ? null : h.view(raw).markdown;
756
+ const text = async (ref) => {
757
+ if (ref === "working") {
758
+ if (current === null)
759
+ throw new Error("Linked Markdown is missing.");
760
+ return current;
761
+ }
762
+ const c = h.refs.conflict;
763
+ const id = c && "editor" in c && (ref === "editor" || ref === "shell") ? c[ref]
764
+ : ref === "base" ? (c && "base" in c ? c.base : h.refs.base)
765
+ : ref === "remote" ? h.refs.remote : ref === "local" ? (c && "local" in c ? c.local : h.refs.draft ?? h.refs.base) : ref;
766
+ if (!id)
767
+ throw new Error("No saved " + ref + " revision.");
768
+ return h.text(id);
769
+ };
770
+ return { from, to, before: await text(from), after: await text(to), token: h.token(raw) };
771
+ });
772
+ const checkpoint = (v, p, expected, markdown, token) => withDocument(v, p, async (h, path, reg) => {
773
+ const raw = await working(path);
774
+ const view = raw === null ? null : h.view(raw);
775
+ if (!view || view.markdown !== expected || token !== h.token(raw))
776
+ throw new Error("Stale shell edit. The document changed; rerun the command.");
777
+ if (expected !== markdown) {
778
+ await h.checkPendingDraft(view);
779
+ if (h.refs.conflict && "editor" in h.refs.conflict)
780
+ throw new Error("Unresolved Wire conflict. Edit the working file and run wire resolve <resource> working, or choose editor or shell before using wire shell.");
781
+ plainMarkdown(markdown);
782
+ const prior = await h.captureLocal(expected, view.shown ?? undefined);
783
+ const draft = await h.revision("local", markdown, [prior]);
784
+ const refs = { ...h.refs, draft, strict: true, ...(view.base ? { editorDraft: draft } : {}) };
785
+ if (refs.editorReceipts)
786
+ refs.editorReceipts = { ...refs.editorReceipts };
787
+ const next = refs.editorReceipts && view.base ? editorFile(markdown, refs.editorReceipts, draft, view.base) : markdown;
788
+ await h.publish(path, raw, next, refs, null, r => reg.put(r));
789
+ }
790
+ return h.status(path);
791
+ });
792
+ const resolveConflict = (v, p, choice) => withDocument(v, p, async (h, path, reg) => {
793
+ const raw = await working(path);
794
+ if (raw === null)
795
+ throw new Error("Linked Markdown is missing.");
796
+ const view = h.view(raw), current = view.markdown;
797
+ await h.checkPendingDraft(view);
798
+ const conflict = h.refs.conflict;
799
+ if (!conflict)
800
+ throw new Error("No saved conflict for this document.");
801
+ let next, basis, parents;
802
+ if ("editor" in conflict) {
803
+ if (!["working", "editor", "shell"].includes(choice))
804
+ throw new Error("Both drafts are local. Choose editor, shell or working.");
805
+ if (choice !== "working" && current !== await h.text(conflict.editor))
806
+ throw new Error("Working file changed since the conflict. Choose working to retain those edits.");
807
+ // The file being reconciled is the editor branch. Keep its remote basis
808
+ // for an edited working resolution; never silently adopt a later base.
809
+ basis = choice === "shell" ? conflict.shellBase : conflict.editorBase;
810
+ if (choice === "working" && view.base !== conflict.editorBase)
811
+ throw new Error("The working file has a different receipt. Restore the conflicted editor receipt before resolving.");
812
+ next = choice === "working" ? current : await h.text(choice === "shell" ? conflict.shell : conflict.editor);
813
+ parents = [conflict.editor, conflict.shell];
814
+ }
815
+ else {
816
+ if (!h.refs.resolution)
817
+ throw new Error("Missing saved provider conflict snapshot.");
818
+ if (!["working", "local", "remote"].includes(choice))
819
+ throw new Error("Choose local, remote or working.");
820
+ const local = await h.text(conflict.local);
821
+ if (choice !== "working" && current !== local)
822
+ throw new Error("Working file changed since the conflict. Choose working to retain those edits.");
823
+ next = choice === "working" ? current : choice === "local" ? local : await h.text(conflict.remote);
824
+ basis = conflict.remote;
825
+ parents = [conflict.local, conflict.remote];
826
+ }
827
+ const draft = await h.revision("resolve", next, parents);
828
+ const refs = { ...h.refs, draft, strict: true, conflict: null, ...(h.refs.editorReceipts ? { editorDraft: draft } : {}) };
829
+ if (refs.editorReceipts)
830
+ refs.editorReceipts = { ...refs.editorReceipts };
831
+ const materialized = refs.editorReceipts ? editorFile(next, refs.editorReceipts, draft, basis) : next;
832
+ await h.publish(path, raw, materialized, refs, null, r => reg.put(r));
833
+ return h.status(path);
834
+ });
469
835
  return Object.freeze({
470
836
  attach,
837
+ adopt: (url, path, editorReceipts = false) => attachAt(url, dirname(resolve(path)), resolve(path), editorReceipts),
838
+ historyStatus, historyDiff, historyLog, checkpoint, resolveConflict,
471
839
  create,
472
840
  view,
473
841
  downloadSource,