@better-fs-tools/write 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/README.md +122 -106
  2. package/dist/bundle/create-fs-tools.d.ts +83 -21
  3. package/dist/bundle/create-fs-tools.js +61 -22
  4. package/dist/bundle/definitions.d.ts +51 -0
  5. package/dist/bundle/definitions.js +42 -0
  6. package/dist/contract/deps.d.ts +13 -5
  7. package/dist/contract/messages.d.ts +0 -23
  8. package/dist/contract/preconditions.d.ts +5 -1
  9. package/dist/contract/preconditions.js +1 -1
  10. package/dist/core/commit.d.ts +0 -1
  11. package/dist/core/commit.js +1 -35
  12. package/dist/core/create-tools.d.ts +9 -9
  13. package/dist/core/create-tools.js +11 -11
  14. package/dist/core/deps.d.ts +4 -4
  15. package/dist/core/deps.js +10 -7
  16. package/dist/core/format.js +1 -15
  17. package/dist/core/hooks.js +1 -8
  18. package/dist/core/load.js +1 -1
  19. package/dist/core/messages.js +8 -11
  20. package/dist/core/patch-hunks.js +31 -3
  21. package/dist/core/patch-pipeline.js +1 -2
  22. package/dist/core/pipeline.js +2 -2
  23. package/dist/core/plan-edit.d.ts +2 -0
  24. package/dist/core/plan-edit.js +3 -3
  25. package/dist/core/precondition.js +2 -13
  26. package/dist/core/record.js +1 -0
  27. package/dist/formatters/default.d.ts +7 -1
  28. package/dist/formatters/default.js +23 -5
  29. package/dist/guards/index.d.ts +9 -3
  30. package/dist/guards/index.js +11 -3
  31. package/dist/guards/non-text.d.ts +5 -1
  32. package/dist/guards/non-text.js +5 -1
  33. package/dist/index.d.ts +3 -3
  34. package/dist/index.js +1 -1
  35. package/dist/matchers/index.d.ts +4 -1
  36. package/dist/matchers/index.js +5 -3
  37. package/dist/matchers/keep-bytes.d.ts +22 -0
  38. package/dist/matchers/keep-bytes.js +51 -0
  39. package/dist/matchers/line-trimmed.d.ts +4 -1
  40. package/dist/matchers/line-trimmed.js +9 -1
  41. package/dist/matchers/normalized.d.ts +2 -1
  42. package/dist/matchers/normalized.js +7 -1
  43. package/dist/signature/definition.d.ts +41 -0
  44. package/dist/signature/definition.js +66 -0
  45. package/dist/signature/edit.d.ts +4 -5
  46. package/dist/signature/edit.js +5 -13
  47. package/dist/signature/index.d.ts +6 -2
  48. package/dist/signature/index.js +4 -2
  49. package/dist/signature/patch.d.ts +4 -1
  50. package/dist/signature/patch.js +4 -1
  51. package/dist/signature/write.d.ts +1 -6
  52. package/dist/signature/write.js +1 -8
  53. package/docs/architecture.md +14 -11
  54. package/docs/hosts.md +134 -55
  55. package/docs/result-schema.md +20 -26
  56. package/package.json +4 -4
@@ -1,4 +1,4 @@
1
- import { createReadTool, memoryStore, sha256Digest } from "@better-fs-tools/read";
1
+ import { createReadTool, sha256Digest } from "@better-fs-tools/read";
2
2
  import { createBashTool } from "@better-fs-tools/shell";
3
3
  import { createApplyPatchTool, createEditTool, createWriteTool } from "../core/create-tools.js";
4
4
  import { isWritable } from "../core/deps.js";
@@ -30,31 +30,53 @@ const EMPTY_STATE_STORE = Object.freeze({
30
30
  delete: async () => { },
31
31
  });
32
32
  export function createFsTools(options) {
33
- checkFsToolsOptions("createFsTools", options, KNOWN_OPTION_KEYS, SHARED_KEYS_BY_TOOL);
34
- const { fs } = options;
35
- const clock = options.clock ?? (() => new Date());
36
- const state = options.state === undefined ? memoryStore({ clock }) : options.state;
37
- const digest = options.digest ?? sha256Digest();
38
- const locks = options.locks ?? memoryLocks();
33
+ const bundle = resolveBundle("createFsTools", options);
34
+ const { fs, state, digest, locks, clock } = bundle;
39
35
  const shared = { fs, state, digest, clock };
40
- const bash = options.bash === undefined || options.bash === false ? null : options.bash;
41
- if (bash === true) {
42
- throw new TypeError("createFsTools bash must be an object with a runner and an env: the portable bundle has no default runner");
43
- }
44
36
  return Object.freeze({
45
37
  read: createReadTool({ ...options.read, ...shared }),
46
38
  edit: createEditTool({ ...options.edit, ...shared, locks }),
47
39
  write: createWriteTool({ ...options.write, ...shared, locks }),
48
- applyPatch: createApplyPatchTool({ ...options.applyPatch, ...shared, locks }),
49
- bash: bash === null ? null : createBashTool({ ...bash, digest, clock }),
40
+ applyPatch: bundle.applyPatch === null
41
+ ? null
42
+ : createApplyPatchTool({ ...bundle.applyPatch, ...shared, locks }),
43
+ bash: bundle.bash === null ? null : createBashTool({ ...bundle.bash, digest, clock }),
50
44
  fs,
51
45
  state,
52
46
  digest,
53
47
  locks,
54
48
  clock,
55
- invalidate: invalidator(fs, state ?? EMPTY_STATE_STORE),
49
+ invalidate: bundle.invalidate,
56
50
  });
57
51
  }
52
+ /**
53
+ * Checks the bundle options and resolves the shared defaults. Throws TypeError
54
+ * that names `label` on an unknown key, a shared key inside a tool's options,
55
+ * a malformed state, and bash: true.
56
+ */
57
+ export function resolveBundle(label, options) {
58
+ checkFsToolsOptions(label, options, KNOWN_OPTION_KEYS, SHARED_KEYS_BY_TOOL);
59
+ const { fs } = options;
60
+ const state = options.state ?? null;
61
+ const bash = options.bash === undefined || options.bash === false ? null : options.bash;
62
+ if (bash === true) {
63
+ throw new TypeError(`${label} bash must be an object with a runner and an env: the portable bundle has no default runner`);
64
+ }
65
+ return {
66
+ fs,
67
+ state,
68
+ digest: options.digest ?? sha256Digest(),
69
+ locks: options.locks ?? memoryLocks(),
70
+ clock: options.clock ?? (() => new Date()),
71
+ applyPatch: options.applyPatch === true
72
+ ? {}
73
+ : options.applyPatch === false || options.applyPatch === undefined
74
+ ? null
75
+ : options.applyPatch,
76
+ bash,
77
+ invalidate: invalidator(fs, state),
78
+ };
79
+ }
58
80
  function checkFsToolsOptions(label, options, known, sharedKeys) {
59
81
  if (options === null || typeof options !== "object" || Array.isArray(options)) {
60
82
  throw new TypeError(`${label} options must be an object`);
@@ -64,12 +86,14 @@ function checkFsToolsOptions(label, options, known, sharedKeys) {
64
86
  throw new TypeError(`Unknown ${label} option: ${key}`);
65
87
  }
66
88
  const state = options.state;
67
- if (state !== undefined && state !== null && !isStore(state)) {
68
- throw new TypeError(`${label} state must be a read state store or null: a bundle takes one store, not a per-call factory`);
89
+ if (state !== undefined && state !== null && typeof state !== "function" && !isStore(state)) {
90
+ throw new TypeError(`${label} state must be a read state store, a function that returns one, or null`);
69
91
  }
70
92
  for (const [tool, keys] of Object.entries(sharedKeys)) {
71
93
  const part = options[tool];
72
- if (part === undefined || (tool === "bash" && typeof part === "boolean"))
94
+ if (part === undefined)
95
+ continue;
96
+ if ((tool === "bash" || tool === "applyPatch") && typeof part === "boolean")
73
97
  continue;
74
98
  if (part === null || typeof part !== "object" || Array.isArray(part)) {
75
99
  throw new TypeError(`${label} ${tool} options must be an object`);
@@ -82,24 +106,26 @@ function checkFsToolsOptions(label, options, known, sharedKeys) {
82
106
  }
83
107
  }
84
108
  function invalidator(fs, state) {
85
- if (typeof fs !== "function") {
86
- const fixed = createInvalidator({ fs, state });
109
+ if (typeof fs !== "function" && typeof state !== "function") {
110
+ const fixed = createInvalidator({ fs, state: state ?? EMPTY_STATE_STORE });
87
111
  return (path) => fixed(path);
88
112
  }
89
113
  return async (path, call) => {
90
114
  if (call === undefined) {
115
+ const factory = typeof fs === "function" ? "fs" : "state";
91
116
  return {
92
117
  ok: false,
93
118
  phase: "stat",
94
119
  error: {
95
120
  reason: "unsupported",
96
- detail: "fs is a factory: pass the call context to invalidate(path, call)",
121
+ detail: `${factory} is a factory: pass the call context to invalidate(path, call)`,
97
122
  },
98
123
  };
99
124
  }
100
125
  let backend;
126
+ let store;
101
127
  try {
102
- backend = fs(call);
128
+ backend = typeof fs === "function" ? fs(call) : fs;
103
129
  }
104
130
  catch (error) {
105
131
  return { ok: false, phase: "stat", error: { reason: "io", detail: messageOf(error) } };
@@ -114,7 +140,20 @@ function invalidator(fs, state) {
114
140
  },
115
141
  };
116
142
  }
117
- return createInvalidator({ fs: backend, state })(path);
143
+ try {
144
+ store = typeof state === "function" ? state(call) : state;
145
+ }
146
+ catch (error) {
147
+ return { ok: false, phase: "state", detail: messageOf(error) };
148
+ }
149
+ if (store !== null && !isStore(store)) {
150
+ return {
151
+ ok: false,
152
+ phase: "state",
153
+ detail: "the state factory did not return a read state store or null",
154
+ };
155
+ }
156
+ return createInvalidator({ fs: backend, state: store ?? EMPTY_STATE_STORE })(path);
118
157
  };
119
158
  }
120
159
  function isStore(value) {
@@ -0,0 +1,51 @@
1
+ import type { Clock, Digest } from "@better-fs-tools/read";
2
+ import type { ReadSignature, ReadToolDefinition } from "@better-fs-tools/read/signature";
3
+ import type { BashSignature, BashToolDefinition } from "@better-fs-tools/shell/signature";
4
+ import type { LockManager } from "../contract/locks.ts";
5
+ import type { ApplyPatchToolDefinition, EditToolDefinition, WriteToolDefinition } from "../signature/definition.ts";
6
+ import type { EditSignature, PatchSignature, WriteSignature } from "../signature/contract.ts";
7
+ import type { FsTools, FsToolsApplyPatchOptions, FsToolsBashOptions, FsToolsEditOptions, FsToolsOptions, FsToolsReadOptions, FsToolsState, FsToolsWriteOptions } from "./create-fs-tools.ts";
8
+ /** The options of createFsTools(), with a `signature` in each tool's options. */
9
+ export interface FsToolDefinitionsOptions<THost = undefined> extends Omit<FsToolsOptions<THost>, "read" | "edit" | "write" | "applyPatch" | "bash"> {
10
+ readonly read?: FsToolsReadOptions<THost> & {
11
+ readonly signature?: ReadSignature;
12
+ };
13
+ readonly edit?: FsToolsEditOptions<THost> & {
14
+ readonly signature?: EditSignature;
15
+ };
16
+ readonly write?: FsToolsWriteOptions<THost> & {
17
+ readonly signature?: WriteSignature;
18
+ };
19
+ /** Off by default. `true` or an options object adds apply_patch. */
20
+ readonly applyPatch?: boolean | (FsToolsApplyPatchOptions<THost> & {
21
+ readonly signature?: PatchSignature;
22
+ });
23
+ /** Off by default. The bash options, with `runner` and `env` required. */
24
+ readonly bash?: false | (FsToolsBashOptions<THost> & {
25
+ readonly signature?: BashSignature;
26
+ });
27
+ }
28
+ /** The tool definitions of one bundle, and the parts they share. */
29
+ export interface FsToolDefinitions<THost = undefined> {
30
+ readonly read: ReadToolDefinition<THost>;
31
+ readonly edit: EditToolDefinition<THost>;
32
+ readonly write: WriteToolDefinition<THost>;
33
+ /** null unless options.applyPatch is true or an object. */
34
+ readonly applyPatch: ApplyPatchToolDefinition<THost> | null;
35
+ /** null unless options.bash is set. */
36
+ readonly bash: BashToolDefinition<THost> | null;
37
+ readonly fs: FsToolsOptions<THost>["fs"];
38
+ readonly state: FsToolsState<THost>;
39
+ readonly digest: Digest;
40
+ readonly locks: LockManager;
41
+ readonly clock: Clock;
42
+ /** As createFsTools().invalidate. */
43
+ readonly invalidate: FsTools<THost>["invalidate"];
44
+ }
45
+ /**
46
+ * The bundle of createFsTools(), with each tool bound to its signature by
47
+ * readToolDefinition() and the other definition helpers. Every integration
48
+ * bundle builds on it. Throws TypeError where createFsTools() does, and when
49
+ * two tools have the same name. `label` names the caller in each message.
50
+ */
51
+ export declare function fsToolDefinitions<THost = undefined>(options: FsToolDefinitionsOptions<THost>, label?: string): FsToolDefinitions<THost>;
@@ -0,0 +1,42 @@
1
+ import { readToolDefinition } from "@better-fs-tools/read/signature";
2
+ import { bashToolDefinition } from "@better-fs-tools/shell/signature";
3
+ import { applyPatchToolDefinition, editToolDefinition, writeToolDefinition, } from "../signature/definition.js";
4
+ import { resolveBundle } from "./create-fs-tools.js";
5
+ /**
6
+ * The bundle of createFsTools(), with each tool bound to its signature by
7
+ * readToolDefinition() and the other definition helpers. Every integration
8
+ * bundle builds on it. Throws TypeError where createFsTools() does, and when
9
+ * two tools have the same name. `label` names the caller in each message.
10
+ */
11
+ export function fsToolDefinitions(options, label = "fsToolDefinitions") {
12
+ const bundle = resolveBundle(label, options);
13
+ const { fs, state, digest, locks, clock } = bundle;
14
+ const shared = { fs, state, digest, clock };
15
+ const definitions = {
16
+ read: readToolDefinition({ ...options.read, ...shared }),
17
+ edit: editToolDefinition({ ...options.edit, ...shared, locks }),
18
+ write: writeToolDefinition({ ...options.write, ...shared, locks }),
19
+ applyPatch: bundle.applyPatch === null
20
+ ? null
21
+ : applyPatchToolDefinition({ ...bundle.applyPatch, ...shared, locks }),
22
+ bash: bundle.bash === null ? null : bashToolDefinition({ ...bundle.bash, digest, clock }),
23
+ };
24
+ const names = new Set();
25
+ for (const definition of Object.values(definitions)) {
26
+ if (definition === null)
27
+ continue;
28
+ if (names.has(definition.name)) {
29
+ throw new TypeError(`${label} has two tools named ${definition.name}`);
30
+ }
31
+ names.add(definition.name);
32
+ }
33
+ return Object.freeze({
34
+ ...definitions,
35
+ fs,
36
+ state,
37
+ digest,
38
+ locks,
39
+ clock,
40
+ invalidate: bundle.invalidate,
41
+ });
42
+ }
@@ -21,7 +21,7 @@ export interface WriteDependencies<THost = undefined> {
21
21
  readonly preconditions: Readonly<PreconditionPolicy>;
22
22
  /** The read tool's store. A factory runs at most once for each call. null turns read-before-write off. */
23
23
  readonly state: ReadStateStore | ((call: ToolCallContext<THost>) => ReadStateStore | null) | null;
24
- /** Required when state is set. */
24
+ /** Default sha256Digest(). Needed when state is set. null turns it off. */
25
25
  readonly digest: Digest | null;
26
26
  readonly clock: Clock;
27
27
  readonly locks: LockManager;
@@ -29,7 +29,7 @@ export interface WriteDependencies<THost = undefined> {
29
29
  readonly classifiers: readonly Classifier[];
30
30
  /** The first codec that accepts a file decodes it. Non-empty. */
31
31
  readonly codecs: readonly Codec[];
32
- /** Default defaultGuards(). An empty array turns the guards off. */
32
+ /** Default none. recommendedGuards() gives the guards this package recommends. */
33
33
  readonly guards: readonly Guard<THost>[];
34
34
  readonly hooks: readonly WriteHook<THost>[];
35
35
  readonly formatter: WriteFormatter<THost>;
@@ -37,6 +37,14 @@ export interface WriteDependencies<THost = undefined> {
37
37
  export interface EditDependencies<THost = undefined> extends WriteDependencies<THost> {
38
38
  /** Ordered. Non-empty. */
39
39
  readonly matchers: readonly Matcher[];
40
+ /**
41
+ * Help after a miss. true turns on three extras: a pair whose new text is
42
+ * already in the file and whose old text is not is `already-applied`; a
43
+ * NO_MATCH error shows the closest region of the file; and the third miss
44
+ * in a row on one file adds a `repeated-miss` note. Default false: a miss
45
+ * is a plain NO_MATCH.
46
+ */
47
+ readonly recovery: boolean;
40
48
  }
41
49
  export interface ApplyPatchDependencies<THost = undefined> extends WriteDependencies<THost> {
42
50
  /** Ordered. Used to find hunk lines. Non-empty. */
@@ -49,7 +57,7 @@ type ToolDeps<D extends WriteDependencies<never>> = {
49
57
  readonly messages?: Partial<WriteMessageCatalog>;
50
58
  readonly preconditions?: Partial<PreconditionPolicy>;
51
59
  } & Partial<Omit<D, "fs" | "limits" | "messages" | "preconditions">>;
52
- export type WriteToolDeps<THost = undefined> = ToolDeps<WriteDependencies<THost>>;
53
- export type EditToolDeps<THost = undefined> = ToolDeps<EditDependencies<THost>>;
54
- export type ApplyPatchToolDeps<THost = undefined> = ToolDeps<ApplyPatchDependencies<THost>>;
60
+ export type WriteToolOptions<THost = undefined> = ToolDeps<WriteDependencies<THost>>;
61
+ export type EditToolOptions<THost = undefined> = ToolDeps<EditDependencies<THost>>;
62
+ export type ApplyPatchToolOptions<THost = undefined> = ToolDeps<ApplyPatchDependencies<THost>>;
55
63
  export {};
@@ -77,9 +77,6 @@ export interface WriteMessageCatalog extends ToolMessages {
77
77
  staleRematched(c: {
78
78
  path: string;
79
79
  }): string;
80
- readBeforeWriteOff(c: {
81
- tool: WriteToolName;
82
- }): string;
83
80
  /** `existing` is true when `what` is "content" and the file exists. */
84
81
  tooLarge(c: {
85
82
  path: string | null;
@@ -181,18 +178,6 @@ export interface WriteMessageCatalog extends ToolMessages {
181
178
  readonly state: string;
182
179
  }[];
183
180
  }): string;
184
- notAtomic(c: {
185
- backend: string;
186
- }): string;
187
- noCompareAndSwap(c: {
188
- backend: string;
189
- }): string;
190
- modeNotKept(c: {
191
- backend: string;
192
- }): string;
193
- directoriesCreated(c: {
194
- paths: readonly string[];
195
- }): string;
196
181
  userModified(c: {
197
182
  path: string;
198
183
  }): string;
@@ -200,12 +185,4 @@ export interface WriteMessageCatalog extends ToolMessages {
200
185
  hook: string;
201
186
  path: string;
202
187
  }): string;
203
- hookFailed(c: {
204
- hook: string;
205
- path: string;
206
- }): string;
207
- /** The formatter threw or returned neither a string nor an array. */
208
- formatterFailed(c: {
209
- formatter: string;
210
- }): string;
211
188
  }
@@ -3,7 +3,11 @@ export interface PreconditionPolicy {
3
3
  readonly requireRead: "existing" | "off";
4
4
  /** Which tools accept a record with wholeFileVisible false. "edit-only" means edit and apply_patch. Default "edit-only". */
5
5
  readonly partialRead: "edit-only" | "always" | "never";
6
- /** edit and apply_patch on a stale record. write always rejects. Default "rematch". */
6
+ /**
7
+ * edit and apply_patch on a stale record. "reject" fails with STALE.
8
+ * "rematch" tries the old text again on the new content. write always
9
+ * rejects. Default "reject".
10
+ */
7
11
  readonly onStale: "rematch" | "reject";
8
12
  }
9
13
  export declare const defaultPreconditions: Readonly<PreconditionPolicy>;
@@ -1,5 +1,5 @@
1
1
  export const defaultPreconditions = Object.freeze({
2
2
  requireRead: "existing",
3
3
  partialRead: "edit-only",
4
- onStale: "rematch",
4
+ onStale: "reject",
5
5
  });
@@ -4,6 +4,5 @@ import type { Planned, ResolvedTarget } from "./planned.ts";
4
4
  import type { MutationScope } from "./scope.ts";
5
5
  export declare function commitOne<THost>(scope: MutationScope<THost>, fs: WritableFileSystem, planned: Planned, bytes: Uint8Array): Promise<MutatedFile>;
6
6
  export declare function checkBeforeCommit<THost>(scope: MutationScope<THost>, fs: WritableFileSystem, target: ResolvedTarget, precondition: Precondition): Promise<void>;
7
- export declare function addCapabilityNotes<THost>(scope: MutationScope<THost>, fs: WritableFileSystem, planned: Planned, file: MutatedFile): void;
8
7
  export declare function fileChange<THost>(scope: MutationScope<THost>, planned: Planned, bytes: Uint8Array, file: MutatedFile): FileChange;
9
8
  export declare function isMutatedFile(value: unknown): value is MutatedFile;
@@ -29,7 +29,6 @@ export async function commitOne(scope, fs, planned, bytes) {
29
29
  if (!isRecord(outcome) || outcome.ok !== true || !isMutatedFile(outcome.file)) {
30
30
  throw ioFailure(scope, target.requestedPath, "malformed write outcome");
31
31
  }
32
- addCapabilityNotes(scope, fs, planned, outcome.file);
33
32
  return outcome.file;
34
33
  }
35
34
  export async function checkBeforeCommit(scope, fs, target, precondition) {
@@ -43,38 +42,6 @@ export async function checkBeforeCommit(scope, fs, target, precondition) {
43
42
  throw scope.stop("STALE", messages.stale({ tool: scope.tool, path }));
44
43
  }
45
44
  }
46
- export function addCapabilityNotes(scope, fs, planned, file) {
47
- const { messages } = scope.deps;
48
- const capabilities = fs.writeCapabilities;
49
- const backend = fs.id;
50
- const add = (note) => {
51
- if (!scope.notes.some((existing) => existing.code === note.code))
52
- scope.notes.push(note);
53
- };
54
- if (!capabilities.atomic || !file.atomic) {
55
- add({ code: "not-atomic", severity: "warning", message: messages.notAtomic({ backend }) });
56
- }
57
- if (!capabilities.compareAndSwap) {
58
- add({
59
- code: "no-compare-and-swap",
60
- severity: "info",
61
- message: messages.noCompareAndSwap({ backend }),
62
- });
63
- }
64
- const replacesExistingFile = planned.precondition.kind !== "absent";
65
- if (!capabilities.preserveMode && replacesExistingFile) {
66
- add({ code: "mode-not-kept", severity: "info", message: messages.modeNotKept({ backend }) });
67
- }
68
- if (file.createdDirectories.length > 0) {
69
- const paths = file.createdDirectories;
70
- scope.notes.push({
71
- code: "directories-created",
72
- severity: "info",
73
- message: messages.directoriesCreated({ paths }),
74
- data: { paths: [...paths] },
75
- });
76
- }
77
- }
78
45
  export function fileChange(scope, planned, bytes, file) {
79
46
  const { change, loaded, target } = planned;
80
47
  const { digest } = scope.deps;
@@ -106,6 +73,5 @@ export function isMutatedFile(value) {
106
73
  return (isRecord(value) &&
107
74
  typeof value.resolvedPath === "string" &&
108
75
  (value.version === null || typeof value.version === "string") &&
109
- Array.isArray(value.createdDirectories) &&
110
- typeof value.atomic === "boolean");
76
+ Array.isArray(value.createdDirectories));
111
77
  }
@@ -1,23 +1,23 @@
1
1
  import type { ApplyPatchTool, EditTool, WriteTool } from "../contract/context.ts";
2
2
  import type { StateNeedsDigest } from "@better-fs-tools/read";
3
- import type { ApplyPatchToolDeps, EditToolDeps, WriteToolDeps } from "../contract/deps.ts";
3
+ import type { ApplyPatchToolOptions, EditToolOptions, WriteToolOptions } from "../contract/deps.ts";
4
4
  /**
5
- * Creates the edit tool. Takes the same dependencies as createWriteTool, plus
5
+ * Creates the edit tool. Takes the same options as createWriteTool, plus
6
6
  * a non-empty `matchers` list (default defaultEditMatchers()). Throws
7
- * TypeError on invalid dependencies.
7
+ * TypeError on invalid options.
8
8
  */
9
- export declare function createEditTool<THost = undefined>(deps: EditToolDeps<THost> & StateNeedsDigest): EditTool<THost>;
9
+ export declare function createEditTool<THost = undefined>(options: EditToolOptions<THost> & StateNeedsDigest): EditTool<THost>;
10
10
  /**
11
11
  * Creates the write tool. Throws TypeError on an unknown key, a missing fs,
12
12
  * an empty classifier or codec list, state without digest, or a malformed
13
13
  * limit, message, or policy. limits, messages, and preconditions merge with
14
- * the defaults key by key. Every other dependency replaces its default.
14
+ * the defaults key by key. Every other option replaces its default.
15
15
  */
16
- export declare function createWriteTool<THost = undefined>(deps: WriteToolDeps<THost> & StateNeedsDigest): WriteTool<THost>;
16
+ export declare function createWriteTool<THost = undefined>(options: WriteToolOptions<THost> & StateNeedsDigest): WriteTool<THost>;
17
17
  /**
18
- * Creates the apply_patch tool. Takes the same dependencies as
18
+ * Creates the apply_patch tool. Takes the same options as
19
19
  * createWriteTool, plus a non-empty `matchers` list (default
20
20
  * defaultPatchMatchers()) and a `patchParser` (default codexPatchParser()).
21
- * Throws TypeError on invalid dependencies.
21
+ * Throws TypeError on invalid options.
22
22
  */
23
- export declare function createApplyPatchTool<THost = undefined>(deps: ApplyPatchToolDeps<THost> & StateNeedsDigest): ApplyPatchTool<THost>;
23
+ export declare function createApplyPatchTool<THost = undefined>(options: ApplyPatchToolOptions<THost> & StateNeedsDigest): ApplyPatchTool<THost>;
@@ -4,12 +4,12 @@ import { isRecord } from "./input.js";
4
4
  import { runApplyPatch } from "./patch-pipeline.js";
5
5
  import { runEdit, runWrite } from "./pipeline.js";
6
6
  /**
7
- * Creates the edit tool. Takes the same dependencies as createWriteTool, plus
7
+ * Creates the edit tool. Takes the same options as createWriteTool, plus
8
8
  * a non-empty `matchers` list (default defaultEditMatchers()). Throws
9
- * TypeError on invalid dependencies.
9
+ * TypeError on invalid options.
10
10
  */
11
- export function createEditTool(deps) {
12
- const resolved = resolveEditDependencies(deps);
11
+ export function createEditTool(options) {
12
+ const resolved = resolveEditDependencies(options);
13
13
  const misses = new MissCounter();
14
14
  const edit = async (input, ctx) => {
15
15
  if (ctx !== undefined && !isRecord(ctx))
@@ -23,10 +23,10 @@ export function createEditTool(deps) {
23
23
  * Creates the write tool. Throws TypeError on an unknown key, a missing fs,
24
24
  * an empty classifier or codec list, state without digest, or a malformed
25
25
  * limit, message, or policy. limits, messages, and preconditions merge with
26
- * the defaults key by key. Every other dependency replaces its default.
26
+ * the defaults key by key. Every other option replaces its default.
27
27
  */
28
- export function createWriteTool(deps) {
29
- const resolved = resolveWriteDependencies(deps, "write");
28
+ export function createWriteTool(options) {
29
+ const resolved = resolveWriteDependencies(options, "write");
30
30
  const write = async (input, ctx) => {
31
31
  if (ctx !== undefined && !isRecord(ctx))
32
32
  throw new TypeError("write context must be an object");
@@ -36,13 +36,13 @@ export function createWriteTool(deps) {
36
36
  return write;
37
37
  }
38
38
  /**
39
- * Creates the apply_patch tool. Takes the same dependencies as
39
+ * Creates the apply_patch tool. Takes the same options as
40
40
  * createWriteTool, plus a non-empty `matchers` list (default
41
41
  * defaultPatchMatchers()) and a `patchParser` (default codexPatchParser()).
42
- * Throws TypeError on invalid dependencies.
42
+ * Throws TypeError on invalid options.
43
43
  */
44
- export function createApplyPatchTool(deps) {
45
- const resolved = resolveApplyPatchDependencies(deps);
44
+ export function createApplyPatchTool(options) {
45
+ const resolved = resolveApplyPatchDependencies(options);
46
46
  const applyPatch = async (input, ctx) => {
47
47
  if (ctx !== undefined && !isRecord(ctx)) {
48
48
  throw new TypeError("apply_patch context must be an object");
@@ -1,10 +1,10 @@
1
1
  import type { WritableFileSystem } from "@better-fs-tools/fs";
2
2
  import type { ReadStateStore } from "@better-fs-tools/read";
3
- import type { ApplyPatchDependencies, ApplyPatchToolDeps, EditDependencies, EditToolDeps, WriteDependencies, WriteToolDeps } from "../contract/deps.ts";
3
+ import type { ApplyPatchDependencies, ApplyPatchToolOptions, EditDependencies, EditToolOptions, WriteDependencies, WriteToolOptions } from "../contract/deps.ts";
4
4
  import type { PreconditionPolicy } from "../contract/preconditions.ts";
5
- export declare function resolveWriteDependencies<THost>(deps: WriteToolDeps<THost>, tool: string): WriteDependencies<THost>;
6
- export declare function resolveEditDependencies<THost>(deps: EditToolDeps<THost>): EditDependencies<THost>;
7
- export declare function resolveApplyPatchDependencies<THost>(deps: ApplyPatchToolDeps<THost>): ApplyPatchDependencies<THost>;
5
+ export declare function resolveWriteDependencies<THost>(deps: WriteToolOptions<THost>, tool: string): WriteDependencies<THost>;
6
+ export declare function resolveEditDependencies<THost>(deps: EditToolOptions<THost>): EditDependencies<THost>;
7
+ export declare function resolveApplyPatchDependencies<THost>(deps: ApplyPatchToolOptions<THost>): ApplyPatchDependencies<THost>;
8
8
  export declare function resolvePreconditions(overrides?: Partial<PreconditionPolicy>): Readonly<PreconditionPolicy>;
9
9
  export declare function isWritable(value: unknown): value is WritableFileSystem;
10
10
  export declare function isFileSystem(value: unknown): boolean;
package/dist/core/deps.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { isWritableFileSystem } from "@better-fs-tools/fs";
2
- import { defaultClassifiers } from "@better-fs-tools/read";
2
+ import { defaultClassifiers, sha256Digest } from "@better-fs-tools/read";
3
3
  import { utf8Codec } from "../codecs/utf8.js";
4
4
  import { defaultPreconditions } from "../contract/preconditions.js";
5
5
  import { defaultWriteFormatter } from "../formatters/default.js";
@@ -29,10 +29,10 @@ const KNOWN = new Set([
29
29
  ]);
30
30
  export function resolveWriteDependencies(deps, tool) {
31
31
  if (!isRecord(deps))
32
- throw new TypeError(`${tool} tool dependencies must be an object`);
32
+ throw new TypeError(`${tool} tool options must be an object`);
33
33
  for (const key of Object.keys(deps)) {
34
34
  if (!KNOWN.has(key))
35
- throw new TypeError(`Unknown ${tool} tool dependency: ${key}`);
35
+ throw new TypeError(`Unknown ${tool} tool option: ${key}`);
36
36
  }
37
37
  const { fs } = deps;
38
38
  if (typeof fs !== "function" && !isWritable(fs)) {
@@ -52,7 +52,7 @@ export function resolveWriteDependencies(deps, tool) {
52
52
  if (state !== null && typeof state !== "function" && !isStateStore(state)) {
53
53
  throw new TypeError("state must be a store, a function that returns one, or null");
54
54
  }
55
- const digest = deps.digest ?? null;
55
+ const digest = deps.digest === undefined ? sha256Digest() : deps.digest;
56
56
  if (digest !== null && !isDigest(digest)) {
57
57
  throw new TypeError("digest must have an id, create, and hash, or be null");
58
58
  }
@@ -105,19 +105,22 @@ export function resolveWriteDependencies(deps, tool) {
105
105
  }
106
106
  export function resolveEditDependencies(deps) {
107
107
  if (!isRecord(deps))
108
- throw new TypeError("edit tool dependencies must be an object");
109
- const { matchers = defaultEditMatchers(), ...shared } = deps;
108
+ throw new TypeError("edit tool options must be an object");
109
+ const { matchers = defaultEditMatchers(), recovery = false, ...shared } = deps;
110
110
  if (!Array.isArray(matchers) || matchers.length === 0 || !matchers.every(isMatcher)) {
111
111
  throw new TypeError("matchers must be a non-empty array of matchers");
112
112
  }
113
+ if (typeof recovery !== "boolean")
114
+ throw new TypeError("recovery must be a boolean");
113
115
  return Object.freeze({
114
116
  ...resolveWriteDependencies(shared, "edit"),
115
117
  matchers: Object.freeze([...matchers]),
118
+ recovery,
116
119
  });
117
120
  }
118
121
  export function resolveApplyPatchDependencies(deps) {
119
122
  if (!isRecord(deps))
120
- throw new TypeError("apply_patch tool dependencies must be an object");
123
+ throw new TypeError("apply_patch tool options must be an object");
121
124
  const { matchers = defaultPatchMatchers(), patchParser = codexPatchParser(), ...shared } = deps;
122
125
  if (!Array.isArray(matchers) || matchers.length === 0 || !matchers.every(isMatcher)) {
123
126
  throw new TypeError("matchers must be a non-empty array of matchers");
@@ -1,5 +1,4 @@
1
1
  import { defaultWriteFormatter } from "../formatters/default.js";
2
- import { extensionId } from "./extension-error.js";
3
2
  export function formatResult(deps, call, report) {
4
3
  const ctx = {
5
4
  digest: deps.digest,
@@ -14,20 +13,7 @@ export function formatResult(deps, call, report) {
14
13
  catch { }
15
14
  if (content !== null)
16
15
  return { ...report, content };
17
- const id = extensionId(deps.formatter);
18
- const failed = {
19
- ...report,
20
- notes: [
21
- ...report.notes,
22
- {
23
- code: "extension-failed",
24
- severity: "warning",
25
- message: deps.messages.formatterFailed({ formatter: id ?? "formatter" }),
26
- data: id === null ? { extension: "formatter" } : { extension: "formatter", id },
27
- },
28
- ],
29
- };
30
- return { ...failed, content: toContent(defaultWriteFormatter().format(failed, ctx)) ?? [] };
16
+ return { ...report, content: toContent(defaultWriteFormatter().format(report, ctx)) ?? [] };
31
17
  }
32
18
  function toContent(output) {
33
19
  if (typeof output === "string")
@@ -38,15 +38,8 @@ export async function runWriteHooks(scope, fs, committed) {
38
38
  const rewrote = [];
39
39
  for (const hook of hooks) {
40
40
  const result = await runHook(hook, file.change, ctx);
41
- if (result === null) {
42
- scope.notes.push({
43
- code: "hook-failed",
44
- severity: "warning",
45
- message: messages.hookFailed({ hook: hook.id, path }),
46
- data: { hook: hook.id },
47
- });
41
+ if (result === null)
48
42
  continue;
49
- }
50
43
  scope.notes.push(...result.notes);
51
44
  if (result.rewrote)
52
45
  rewrote.push(hook.id);
package/dist/core/load.js CHANGED
@@ -161,7 +161,7 @@ function classify(scope, sample, requested) {
161
161
  }
162
162
  throw scope.extensionFailure("classifiers", extensionId(classifier));
163
163
  }
164
- throw scope.stop("UNSUPPORTED_BACKEND", messages.unsupportedBackend({ path: requested, detail: "no classifier had an opinion" }));
164
+ throw scope.stop("UNSUPPORTED_BACKEND", messages.unsupportedBackend({ path: requested, detail: "its file type is not supported" }));
165
165
  }
166
166
  function decode(scope, sample, bytes, requested) {
167
167
  const { codecs, messages } = scope.deps;