@better-fs-tools/write 0.0.0-stage → 0.1.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 (196) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +442 -2
  3. package/dist/authorize/ask-before-write.d.ts +11 -0
  4. package/dist/authorize/ask-before-write.js +49 -0
  5. package/dist/authorize/index.d.ts +3 -0
  6. package/dist/authorize/index.js +3 -0
  7. package/dist/authorize/protect-paths.d.ts +12 -0
  8. package/dist/authorize/protect-paths.js +74 -0
  9. package/dist/authorize/write-authorizers.d.ts +9 -0
  10. package/dist/authorize/write-authorizers.js +48 -0
  11. package/dist/bundle/create-fs-tools.d.ts +71 -0
  12. package/dist/bundle/create-fs-tools.js +125 -0
  13. package/dist/codecs/index.d.ts +1 -0
  14. package/dist/codecs/index.js +1 -0
  15. package/dist/codecs/utf8.d.ts +7 -0
  16. package/dist/codecs/utf8.js +61 -0
  17. package/dist/contract/codec.d.ts +26 -0
  18. package/dist/contract/codec.js +0 -0
  19. package/dist/contract/context.d.ts +14 -0
  20. package/dist/contract/context.js +0 -0
  21. package/dist/contract/deps.d.ts +55 -0
  22. package/dist/contract/deps.js +0 -0
  23. package/dist/contract/extensions.d.ts +103 -0
  24. package/dist/contract/extensions.js +0 -0
  25. package/dist/contract/format.d.ts +15 -0
  26. package/dist/contract/format.js +0 -0
  27. package/dist/contract/input.d.ts +35 -0
  28. package/dist/contract/input.js +0 -0
  29. package/dist/contract/limits.d.ts +26 -0
  30. package/dist/contract/limits.js +0 -0
  31. package/dist/contract/locks.d.ts +14 -0
  32. package/dist/contract/locks.js +0 -0
  33. package/dist/contract/matcher.d.ts +30 -0
  34. package/dist/contract/matcher.js +0 -0
  35. package/dist/contract/messages.d.ts +211 -0
  36. package/dist/contract/messages.js +0 -0
  37. package/dist/contract/patch.d.ts +50 -0
  38. package/dist/contract/patch.js +0 -0
  39. package/dist/contract/preconditions.d.ts +9 -0
  40. package/dist/contract/preconditions.js +5 -0
  41. package/dist/contract/result.d.ts +102 -0
  42. package/dist/contract/result.js +0 -0
  43. package/dist/core/abort.d.ts +4 -0
  44. package/dist/core/abort.js +23 -0
  45. package/dist/core/authorize.d.ts +9 -0
  46. package/dist/core/authorize.js +87 -0
  47. package/dist/core/bytes.d.ts +3 -0
  48. package/dist/core/bytes.js +14 -0
  49. package/dist/core/commit-patch.d.ts +20 -0
  50. package/dist/core/commit-patch.js +224 -0
  51. package/dist/core/commit.d.ts +9 -0
  52. package/dist/core/commit.js +111 -0
  53. package/dist/core/create-tools.d.ts +23 -0
  54. package/dist/core/create-tools.js +54 -0
  55. package/dist/core/deps.d.ts +11 -0
  56. package/dist/core/deps.js +207 -0
  57. package/dist/core/diff.d.ts +10 -0
  58. package/dist/core/diff.js +221 -0
  59. package/dist/core/encode.d.ts +3 -0
  60. package/dist/core/encode.js +26 -0
  61. package/dist/core/extension-error.d.ts +8 -0
  62. package/dist/core/extension-error.js +17 -0
  63. package/dist/core/format.d.ts +4 -0
  64. package/dist/core/format.js +36 -0
  65. package/dist/core/guards.d.ts +3 -0
  66. package/dist/core/guards.js +45 -0
  67. package/dist/core/hints.d.ts +14 -0
  68. package/dist/core/hints.js +75 -0
  69. package/dist/core/hooks.d.ts +15 -0
  70. package/dist/core/hooks.js +115 -0
  71. package/dist/core/input.d.ts +20 -0
  72. package/dist/core/input.js +91 -0
  73. package/dist/core/limits.d.ts +10 -0
  74. package/dist/core/limits.js +48 -0
  75. package/dist/core/line-index.d.ts +10 -0
  76. package/dist/core/line-index.js +38 -0
  77. package/dist/core/load.d.ts +14 -0
  78. package/dist/core/load.js +221 -0
  79. package/dist/core/lock.d.ts +2 -0
  80. package/dist/core/lock.js +56 -0
  81. package/dist/core/match.d.ts +15 -0
  82. package/dist/core/match.js +66 -0
  83. package/dist/core/messages.d.ts +8 -0
  84. package/dist/core/messages.js +147 -0
  85. package/dist/core/outcomes.d.ts +21 -0
  86. package/dist/core/outcomes.js +127 -0
  87. package/dist/core/parse-patch.d.ts +3 -0
  88. package/dist/core/parse-patch.js +64 -0
  89. package/dist/core/patch-hunks.d.ts +25 -0
  90. package/dist/core/patch-hunks.js +177 -0
  91. package/dist/core/patch-pipeline.d.ts +4 -0
  92. package/dist/core/patch-pipeline.js +285 -0
  93. package/dist/core/pipeline.d.ts +22 -0
  94. package/dist/core/pipeline.js +153 -0
  95. package/dist/core/plan-edit.d.ts +13 -0
  96. package/dist/core/plan-edit.js +215 -0
  97. package/dist/core/plan-patch.d.ts +29 -0
  98. package/dist/core/plan-patch.js +169 -0
  99. package/dist/core/plan-write.d.ts +6 -0
  100. package/dist/core/plan-write.js +27 -0
  101. package/dist/core/planned.d.ts +35 -0
  102. package/dist/core/planned.js +36 -0
  103. package/dist/core/precondition.d.ts +10 -0
  104. package/dist/core/precondition.js +76 -0
  105. package/dist/core/record.d.ts +3 -0
  106. package/dist/core/record.js +58 -0
  107. package/dist/core/resolve.d.ts +3 -0
  108. package/dist/core/resolve.js +65 -0
  109. package/dist/core/scope.d.ts +33 -0
  110. package/dist/core/scope.js +109 -0
  111. package/dist/core/snippet.d.ts +4 -0
  112. package/dist/core/snippet.js +36 -0
  113. package/dist/core/splice.d.ts +10 -0
  114. package/dist/core/splice.js +19 -0
  115. package/dist/core/target.d.ts +10 -0
  116. package/dist/core/target.js +46 -0
  117. package/dist/formatters/default.d.ts +16 -0
  118. package/dist/formatters/default.js +122 -0
  119. package/dist/formatters/index.d.ts +2 -0
  120. package/dist/formatters/index.js +1 -0
  121. package/dist/guards/generated-file.d.ts +10 -0
  122. package/dist/guards/generated-file.js +39 -0
  123. package/dist/guards/index.d.ts +13 -0
  124. package/dist/guards/index.js +25 -0
  125. package/dist/guards/non-text.d.ts +3 -0
  126. package/dist/guards/non-text.js +46 -0
  127. package/dist/guards/omission.d.ts +9 -0
  128. package/dist/guards/omission.js +48 -0
  129. package/dist/guards/read-prefix.d.ts +12 -0
  130. package/dist/guards/read-prefix.js +87 -0
  131. package/dist/guards/shared.d.ts +11 -0
  132. package/dist/guards/shared.js +46 -0
  133. package/dist/guards/syntax.d.ts +10 -0
  134. package/dist/guards/syntax.js +54 -0
  135. package/dist/guards/truncation-notice.d.ts +8 -0
  136. package/dist/guards/truncation-notice.js +32 -0
  137. package/dist/hooks/executable-shebang.d.ts +9 -0
  138. package/dist/hooks/executable-shebang.js +46 -0
  139. package/dist/hooks/index.d.ts +2 -0
  140. package/dist/hooks/index.js +2 -0
  141. package/dist/hooks/verify-write.d.ts +9 -0
  142. package/dist/hooks/verify-write.js +63 -0
  143. package/dist/index.d.ts +30 -0
  144. package/dist/index.js +15 -0
  145. package/dist/locks/index.d.ts +1 -0
  146. package/dist/locks/index.js +1 -0
  147. package/dist/locks/memory-locks.d.ts +9 -0
  148. package/dist/locks/memory-locks.js +94 -0
  149. package/dist/matchers/block-anchor.d.ts +9 -0
  150. package/dist/matchers/block-anchor.js +69 -0
  151. package/dist/matchers/escape.d.ts +6 -0
  152. package/dist/matchers/escape.js +32 -0
  153. package/dist/matchers/exact.d.ts +4 -0
  154. package/dist/matchers/exact.js +29 -0
  155. package/dist/matchers/fold.d.ts +11 -0
  156. package/dist/matchers/fold.js +144 -0
  157. package/dist/matchers/indentation.d.ts +3 -0
  158. package/dist/matchers/indentation.js +81 -0
  159. package/dist/matchers/index.d.ts +11 -0
  160. package/dist/matchers/index.js +18 -0
  161. package/dist/matchers/line-trimmed.d.ts +3 -0
  162. package/dist/matchers/line-trimmed.js +32 -0
  163. package/dist/matchers/lines.d.ts +24 -0
  164. package/dist/matchers/lines.js +74 -0
  165. package/dist/matchers/normalized.d.ts +7 -0
  166. package/dist/matchers/normalized.js +69 -0
  167. package/dist/patch/grammar.d.ts +5 -0
  168. package/dist/patch/grammar.js +24 -0
  169. package/dist/patch/index.d.ts +4 -0
  170. package/dist/patch/index.js +3 -0
  171. package/dist/patch/parse.d.ts +11 -0
  172. package/dist/patch/parse.js +209 -0
  173. package/dist/signature/contract.d.ts +8 -0
  174. package/dist/signature/contract.js +0 -0
  175. package/dist/signature/edit.d.ts +19 -0
  176. package/dist/signature/edit.js +158 -0
  177. package/dist/signature/index.d.ts +6 -0
  178. package/dist/signature/index.js +4 -0
  179. package/dist/signature/matching.d.ts +3 -0
  180. package/dist/signature/matching.js +25 -0
  181. package/dist/signature/messages.d.ts +4 -0
  182. package/dist/signature/messages.js +9 -0
  183. package/dist/signature/patch.d.ts +6 -0
  184. package/dist/signature/patch.js +55 -0
  185. package/dist/signature/schema.d.ts +19 -0
  186. package/dist/signature/schema.js +117 -0
  187. package/dist/signature/write.d.ts +9 -0
  188. package/dist/signature/write.js +52 -0
  189. package/dist/state/index.d.ts +2 -0
  190. package/dist/state/index.js +1 -0
  191. package/dist/state/invalidate.d.ts +29 -0
  192. package/dist/state/invalidate.js +37 -0
  193. package/docs/architecture.md +221 -0
  194. package/docs/hosts.md +95 -0
  195. package/docs/result-schema.md +268 -0
  196. package/package.json +54 -4
@@ -0,0 +1,54 @@
1
+ import { isRecord } from "../core/input.js";
2
+ import { ALLOW, extensionOf, newTextParam, refuse } from "./shared.js";
3
+ const DEFAULT_PARSERS = Object.freeze({
4
+ json: (text) => {
5
+ JSON.parse(text);
6
+ },
7
+ });
8
+ /**
9
+ * Refuses an update that makes a file fail to parse when it parsed before.
10
+ * `.json` uses JSON.parse by default. `parsers` adds or replaces parsers by
11
+ * extension, with or without the dot, and each must throw on bad text.
12
+ * Creates and files that already failed to parse are not checked.
13
+ */
14
+ export function syntaxGuard(options = {}) {
15
+ const parsers = new Map(Object.entries(DEFAULT_PARSERS));
16
+ if (options.parsers !== undefined) {
17
+ if (!isRecord(options.parsers))
18
+ throw new TypeError("parsers must be an object");
19
+ for (const [key, parser] of Object.entries(options.parsers)) {
20
+ if (typeof parser !== "function")
21
+ throw new TypeError(`parser ${key} must be a function`);
22
+ parsers.set(key.replace(/^\./u, "").toLowerCase(), parser);
23
+ }
24
+ }
25
+ return Object.freeze({
26
+ id: "syntax",
27
+ check(change, ctx) {
28
+ if (change.before === null || change.after === null)
29
+ return ALLOW;
30
+ const extension = extensionOf(change.resolvedPath);
31
+ const parser = extension === null ? undefined : parsers.get(extension);
32
+ if (extension === null || parser === undefined)
33
+ return ALLOW;
34
+ if (parseError(parser, change.before.text) !== null)
35
+ return ALLOW;
36
+ const error = parseError(parser, change.after.text);
37
+ if (error === null)
38
+ return ALLOW;
39
+ const language = extension.toUpperCase();
40
+ return refuse("syntax", `The change would make ${change.displayPath} invalid ${language}, and it was valid before. Fix the ${newTextParam(change, ctx)} and retry. The parser said: ${error}`, { language, detail: error });
41
+ },
42
+ });
43
+ }
44
+ function parseError(parser, text) {
45
+ try {
46
+ parser(text);
47
+ return null;
48
+ }
49
+ catch (error) {
50
+ const message = error instanceof Error ? error.message : String(error);
51
+ const line = message.split("\n")[0] ?? "";
52
+ return line.length > 200 ? `${line.slice(0, 200)}…` : line || "parse error";
53
+ }
54
+ }
@@ -0,0 +1,8 @@
1
+ import type { Guard } from "../contract/extensions.ts";
2
+ /**
3
+ * Refuses new text that holds a read tool note or truncation marker. A line
4
+ * that is already in the file is allowed.
5
+ */
6
+ export declare function truncationNoticeGuard(options?: {
7
+ readonly patterns?: readonly RegExp[];
8
+ }): Guard<unknown>;
@@ -0,0 +1,32 @@
1
+ import { ALLOW, existingLines, linesOf, newTextParam, quoted, refuse, regExpList, } from "./shared.js";
2
+ // Notes and truncation markers that read tools add around file text.
3
+ const DEFAULT_PATTERNS = [
4
+ /^\[read:(?:continue|line-clamped|scan-limit)\] /u,
5
+ /… \[line truncated at \d+ chars\]$/u,
6
+ /\.\.\. \[truncated\]$/u,
7
+ /^\(End of file - total \d+ lines\)$/u,
8
+ /^@@ (?:lines \d+-\d+|no lines)(?: of \d+)?(?: \| next offset \d+)? @@$/u,
9
+ ];
10
+ /**
11
+ * Refuses new text that holds a read tool note or truncation marker. A line
12
+ * that is already in the file is allowed.
13
+ */
14
+ export function truncationNoticeGuard(options = {}) {
15
+ const patterns = options.patterns === undefined ? DEFAULT_PATTERNS : regExpList(options.patterns, "patterns");
16
+ return Object.freeze({
17
+ id: "truncation-notice",
18
+ check(change, ctx) {
19
+ if (change.after === null)
20
+ return ALLOW;
21
+ const known = existingLines(change);
22
+ for (const fragment of change.fragments) {
23
+ for (const line of linesOf(fragment.newText)) {
24
+ if (!patterns.some((pattern) => pattern.test(line)) || known(line))
25
+ continue;
26
+ return refuse("truncation-notice", `The ${newTextParam(change, ctx)} for ${change.displayPath} holds read tool output, not file text: "${quoted(line)}". Remove that line. If the file was cut off, read the missing lines first, then send the full text.`, { line: quoted(line) });
27
+ }
28
+ }
29
+ return ALLOW;
30
+ },
31
+ });
32
+ }
@@ -0,0 +1,9 @@
1
+ import type { WriteHook } from "../contract/extensions.ts";
2
+ /**
3
+ * Creates a new file that starts with `#!` as executable, with `mode`
4
+ * (default 0o755), and adds an info note when it worked. An existing file
5
+ * keeps its mode, and a file with a BOM is left alone.
6
+ */
7
+ export declare function executableShebang(options?: {
8
+ readonly mode?: number;
9
+ }): WriteHook<unknown>;
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Creates a new file that starts with `#!` as executable, with `mode`
3
+ * (default 0o755), and adds an info note when it worked. An existing file
4
+ * keeps its mode, and a file with a BOM is left alone.
5
+ */
6
+ export function executableShebang(options = {}) {
7
+ const { mode = 0o755 } = options;
8
+ if (!Number.isInteger(mode) || mode < 0 || mode > 0o7777) {
9
+ throw new TypeError("mode must be an integer from 0 to 0o7777");
10
+ }
11
+ const asked = new WeakMap();
12
+ return Object.freeze({
13
+ id: "executable-shebang",
14
+ newFileMode(change, ctx) {
15
+ const after = change.after;
16
+ if (change.kind !== "create" || after === null || after.style.bom)
17
+ return null;
18
+ if (!after.text.startsWith("#!"))
19
+ return null;
20
+ const paths = asked.get(ctx.call) ?? new Set();
21
+ paths.add(change.resolvedPath);
22
+ asked.set(ctx.call, paths);
23
+ return mode;
24
+ },
25
+ async afterWrite(change, ctx) {
26
+ if (change.kind !== "create" || !asked.get(ctx.call)?.has(change.resolvedPath))
27
+ return {};
28
+ const outcome = await ctx.fs.stat(change.resolvedPath, {});
29
+ if (!outcome.ok || !outcome.stat.exists)
30
+ return {};
31
+ const actual = outcome.stat.mode;
32
+ if (actual === null || (actual & 0o111) === 0)
33
+ return {};
34
+ return {
35
+ notes: [
36
+ {
37
+ code: "executable",
38
+ severity: "info",
39
+ message: `Made ${change.path} executable (mode ${actual.toString(8)}) because it starts with "#!".`,
40
+ data: { mode: actual },
41
+ },
42
+ ],
43
+ };
44
+ },
45
+ });
46
+ }
@@ -0,0 +1,2 @@
1
+ export { executableShebang } from "./executable-shebang.ts";
2
+ export { verifyWrite } from "./verify-write.ts";
@@ -0,0 +1,2 @@
1
+ export { executableShebang } from "./executable-shebang.js";
2
+ export { verifyWrite } from "./verify-write.js";
@@ -0,0 +1,9 @@
1
+ import type { WriteHook } from "../contract/extensions.ts";
2
+ /**
3
+ * Reads each committed file back and checks it against what was written: by
4
+ * hash when the call has a digest, else by size. A removed file must be gone.
5
+ * A mismatch, or a file that cannot be read back, adds a warning note. Put it
6
+ * before any hook that rewrites files, or it reports their rewrite as a
7
+ * mismatch.
8
+ */
9
+ export declare function verifyWrite(): WriteHook<unknown>;
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Reads each committed file back and checks it against what was written: by
3
+ * hash when the call has a digest, else by size. A removed file must be gone.
4
+ * A mismatch, or a file that cannot be read back, adds a warning note. Put it
5
+ * before any hook that rewrites files, or it reports their rewrite as a
6
+ * mismatch.
7
+ */
8
+ export function verifyWrite() {
9
+ return Object.freeze({
10
+ id: "verify-write",
11
+ async afterWrite(change, ctx) {
12
+ const outcome = change.after === null
13
+ ? await checkRemoved(change, ctx)
14
+ : await checkWritten(change, change.after, ctx);
15
+ return outcome === "ok" ? {} : { notes: [warning(change, outcome)] };
16
+ },
17
+ });
18
+ }
19
+ async function checkRemoved(change, ctx) {
20
+ const outcome = await ctx.fs.stat(change.resolvedPath, {});
21
+ if (!outcome.ok)
22
+ return "unreadable";
23
+ return outcome.stat.exists ? "mismatch" : "ok";
24
+ }
25
+ async function checkWritten(change, after, ctx) {
26
+ const opened = await ctx.fs.open(change.resolvedPath, {});
27
+ if (!opened.ok)
28
+ return "unreadable";
29
+ const handle = opened.file;
30
+ const digest = after.contentId === null ? null : ctx.digest;
31
+ const stream = digest?.create() ?? null;
32
+ let size = 0;
33
+ try {
34
+ for await (const chunk of handle.bytes()) {
35
+ size += chunk.byteLength;
36
+ if (size > after.bytes)
37
+ return "mismatch";
38
+ stream?.update(chunk);
39
+ }
40
+ }
41
+ catch {
42
+ return "unreadable";
43
+ }
44
+ finally {
45
+ await handle.close().catch(() => { });
46
+ }
47
+ if (size !== after.bytes)
48
+ return "mismatch";
49
+ return stream === null || stream.digest() === after.contentId ? "ok" : "mismatch";
50
+ }
51
+ function warning(change, outcome) {
52
+ const path = change.path;
53
+ const message = outcome === "unreadable"
54
+ ? `${path} could not be read back to check the write. Read it before you change it again.`
55
+ : change.after === null
56
+ ? `${path} still exists after it was removed. Check the file before you continue.`
57
+ : `${path} does not hold the bytes that were written. Read it again before you change it.`;
58
+ return {
59
+ code: outcome === "unreadable" ? "verify-failed" : "verify-mismatch",
60
+ severity: "warning",
61
+ message,
62
+ };
63
+ }
@@ -0,0 +1,30 @@
1
+ export type { ApplyPatchInput, ApplyPatchRequest, EditInput, EditPair, EditRequest, MutationRequest, WriteInput, WriteRequest, } from "./contract/input.ts";
2
+ export type { ApplyPatchTool, EditTool, MutationTool, WriteTool, WriteToolName, } from "./contract/context.ts";
3
+ export type { CommitFileState, CommitReport, FileChange, FileVersion, MatchInfo, MutationFailure, MutationNoChange, MutationOk, MutationReport, MutationResult, Snippet, WriteError, WriteErrorCode, WritePhase, } from "./contract/result.ts";
4
+ export type { ApplyPatchDependencies, ApplyPatchToolDeps, EditDependencies, EditToolDeps, WriteDependencies, WriteToolDeps, } from "./contract/deps.ts";
5
+ export type { AfterWriteContext, ChangeFragment, Guard, GuardContext, GuardDecision, PlannedChange, PlannedText, WriteAuthorizeDecision, WriteAuthorizer, WriteAuthorizeTarget, WriteHook, WriteHookContext, WriteHookResult, } from "./contract/extensions.ts";
6
+ export type { Codec, DecodeOutcome, TextStyle } from "./contract/codec.ts";
7
+ export type { Matcher, MatchContext, MatchRange } from "./contract/matcher.ts";
8
+ export type { LockManager, LockOutcome } from "./contract/locks.ts";
9
+ export type { PreconditionPolicy } from "./contract/preconditions.ts";
10
+ export type { WriteFormatContext, WriteFormatter } from "./contract/format.ts";
11
+ export type { WriteLimits } from "./contract/limits.ts";
12
+ export type { WriteCanonicalParam, WriteMessageCatalog } from "./contract/messages.ts";
13
+ export { createApplyPatchTool, createEditTool, createWriteTool } from "./core/create-tools.ts";
14
+ export { parseApplyPatchInput, parseEditInput, parseWriteInput } from "./core/input.ts";
15
+ export { defaultWriteLimits, resolveWriteLimits } from "./core/limits.ts";
16
+ export { defaultWriteMessages, resolveWriteMessages } from "./core/messages.ts";
17
+ export { defaultPreconditions } from "./contract/preconditions.ts";
18
+ export { blockAnchorMatcher, defaultEditMatchers, defaultPatchMatchers, escapeMatcher, exactMatcher, indentationMatcher, lineTrimmedMatcher, normalizedMatcher, } from "./matchers/index.ts";
19
+ export { utf8Codec } from "./codecs/index.ts";
20
+ export { memoryLocks } from "./locks/index.ts";
21
+ export { defaultGuards, generatedFileGuard, nonTextGuard, omissionGuard, readPrefixGuard, syntaxGuard, truncationNoticeGuard, } from "./guards/index.ts";
22
+ export { askBeforeWrite, protectPaths, writeAuthorizers } from "./authorize/index.ts";
23
+ export { executableShebang, verifyWrite } from "./hooks/index.ts";
24
+ export { defaultWriteFormatter } from "./formatters/index.ts";
25
+ export type { WriteFormatterOptions } from "./formatters/index.ts";
26
+ export { createFsTools } from "./bundle/create-fs-tools.ts";
27
+ export type { CreateFsToolsOptions, FsTools, FsToolsBashOptions, FsToolsSharedKey, FsToolsWithBash, } from "./bundle/create-fs-tools.ts";
28
+ export { createInvalidator } from "./state/index.ts";
29
+ export type { Invalidate, InvalidateOutcome } from "./state/index.ts";
30
+ export { textOf } from "@better-fs-tools/read";
package/dist/index.js ADDED
@@ -0,0 +1,15 @@
1
+ export { createApplyPatchTool, createEditTool, createWriteTool } from "./core/create-tools.js";
2
+ export { parseApplyPatchInput, parseEditInput, parseWriteInput } from "./core/input.js";
3
+ export { defaultWriteLimits, resolveWriteLimits } from "./core/limits.js";
4
+ export { defaultWriteMessages, resolveWriteMessages } from "./core/messages.js";
5
+ export { defaultPreconditions } from "./contract/preconditions.js";
6
+ export { blockAnchorMatcher, defaultEditMatchers, defaultPatchMatchers, escapeMatcher, exactMatcher, indentationMatcher, lineTrimmedMatcher, normalizedMatcher, } from "./matchers/index.js";
7
+ export { utf8Codec } from "./codecs/index.js";
8
+ export { memoryLocks } from "./locks/index.js";
9
+ export { defaultGuards, generatedFileGuard, nonTextGuard, omissionGuard, readPrefixGuard, syntaxGuard, truncationNoticeGuard, } from "./guards/index.js";
10
+ export { askBeforeWrite, protectPaths, writeAuthorizers } from "./authorize/index.js";
11
+ export { executableShebang, verifyWrite } from "./hooks/index.js";
12
+ export { defaultWriteFormatter } from "./formatters/index.js";
13
+ export { createFsTools } from "./bundle/create-fs-tools.js";
14
+ export { createInvalidator } from "./state/index.js";
15
+ export { textOf } from "@better-fs-tools/read";
@@ -0,0 +1 @@
1
+ export { memoryLocks } from "./memory-locks.ts";
@@ -0,0 +1 @@
1
+ export { memoryLocks } from "./memory-locks.js";
@@ -0,0 +1,9 @@
1
+ import type { LockManager } from "../contract/locks.ts";
2
+ /**
3
+ * In-process locks keyed by resolved path. A caller holds every key or none:
4
+ * on a timeout or an abort it gives back every key it took. `timeoutMs`
5
+ * defaults to 30 000.
6
+ */
7
+ export declare function memoryLocks(options?: {
8
+ readonly timeoutMs?: number;
9
+ }): LockManager;
@@ -0,0 +1,94 @@
1
+ const DEFAULT_TIMEOUT_MS = 30_000;
2
+ /**
3
+ * In-process locks keyed by resolved path. A caller holds every key or none:
4
+ * on a timeout or an abort it gives back every key it took. `timeoutMs`
5
+ * defaults to 30 000.
6
+ */
7
+ export function memoryLocks(options = {}) {
8
+ if (options === null || typeof options !== "object" || Array.isArray(options)) {
9
+ throw new TypeError("memoryLocks options must be an object");
10
+ }
11
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
12
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0) {
13
+ throw new TypeError("timeoutMs must be a positive safe integer");
14
+ }
15
+ const waitersByHeldKey = new Map();
16
+ const release = (key) => {
17
+ const waiting = waitersByHeldKey.get(key);
18
+ if (waiting === undefined)
19
+ return;
20
+ const next = waiting.shift();
21
+ if (next === undefined)
22
+ waitersByHeldKey.delete(key);
23
+ else
24
+ next.grant();
25
+ };
26
+ const waitForKey = (key, ended) => {
27
+ const waiting = waitersByHeldKey.get(key);
28
+ if (waiting === undefined) {
29
+ waitersByHeldKey.set(key, []);
30
+ return Promise.resolve(true);
31
+ }
32
+ return new Promise((resolve) => {
33
+ const waiter = { grant: () => resolve(true) };
34
+ waiting.push(waiter);
35
+ void ended.then(() => {
36
+ const index = waiting.indexOf(waiter);
37
+ const alreadyGranted = index === -1;
38
+ if (alreadyGranted)
39
+ return;
40
+ waiting.splice(index, 1);
41
+ resolve(false);
42
+ });
43
+ });
44
+ };
45
+ return Object.freeze({
46
+ id: "memory",
47
+ async acquire(keys, { signal } = {}) {
48
+ if (signal?.aborted)
49
+ return { ok: false, reason: "aborted" };
50
+ let reason = null;
51
+ let end = () => { };
52
+ const ended = new Promise((resolve) => {
53
+ end = resolve;
54
+ });
55
+ const timer = setTimeout(() => {
56
+ reason ??= "timeout";
57
+ end();
58
+ }, timeoutMs);
59
+ const onAbort = () => {
60
+ reason ??= "aborted";
61
+ end();
62
+ };
63
+ signal?.addEventListener("abort", onAbort, { once: true });
64
+ const held = [];
65
+ try {
66
+ for (const key of keys) {
67
+ const taken = await waitForKey(key, ended);
68
+ if (taken)
69
+ held.push(key);
70
+ if (!taken || reason !== null) {
71
+ for (const key of held.reverse())
72
+ release(key);
73
+ return { ok: false, reason: reason ?? "timeout" };
74
+ }
75
+ }
76
+ }
77
+ finally {
78
+ clearTimeout(timer);
79
+ signal?.removeEventListener("abort", onAbort);
80
+ }
81
+ let released = false;
82
+ return {
83
+ ok: true,
84
+ release() {
85
+ if (released)
86
+ return;
87
+ released = true;
88
+ for (const key of [...held].reverse())
89
+ release(key);
90
+ },
91
+ };
92
+ },
93
+ });
94
+ }
@@ -0,0 +1,9 @@
1
+ import type { Matcher } from "../contract/matcher.ts";
2
+ /**
3
+ * Matches old text of 3 or more lines by its first and last lines, when at
4
+ * least half of its middle lines also appear between them. A match spans at
5
+ * most `maxSpanRatio` (default 3) times the old text's line count.
6
+ */
7
+ export declare function blockAnchorMatcher(options?: {
8
+ readonly maxSpanRatio?: number;
9
+ }): Matcher;
@@ -0,0 +1,69 @@
1
+ import { LineTable, memoizeLast, needleLines } from "./lines.js";
2
+ /**
3
+ * Matches old text of 3 or more lines by its first and last lines, when at
4
+ * least half of its middle lines also appear between them. A match spans at
5
+ * most `maxSpanRatio` (default 3) times the old text's line count.
6
+ */
7
+ export function blockAnchorMatcher(options = {}) {
8
+ if (options === null || typeof options !== "object" || Array.isArray(options)) {
9
+ throw new TypeError("blockAnchorMatcher options must be an object");
10
+ }
11
+ const { maxSpanRatio = 3 } = options;
12
+ if (typeof maxSpanRatio !== "number" || !Number.isFinite(maxSpanRatio) || maxSpanRatio < 1) {
13
+ throw new TypeError("maxSpanRatio must be a finite number of at least 1");
14
+ }
15
+ const table = memoizeLast((text) => new LineTable(text));
16
+ return Object.freeze({
17
+ id: "block-anchor",
18
+ fuzzy: true,
19
+ describe: "lines between matching first and last lines",
20
+ find(haystack, needle, ctx) {
21
+ const { lines, withBreak } = needleLines(needle);
22
+ const wanted = lines.map((line) => line.trim());
23
+ const head = wanted[0] ?? "";
24
+ const tail = wanted.at(-1) ?? "";
25
+ if (wanted.length < 3 || head === "" || tail === "")
26
+ return [];
27
+ const middle = wanted.slice(1, -1);
28
+ const needed = Math.ceil(middle.length / 2);
29
+ const span = Math.floor(maxSpanRatio * wanted.length);
30
+ const hay = table(haystack);
31
+ const trimmed = hay.trimmed;
32
+ const ranges = [];
33
+ for (let first = hay.firstLineAtOrAfter(ctx.from); first < hay.count; first += 1) {
34
+ if (ranges.length >= ctx.maxMatches)
35
+ break;
36
+ if (trimmed[first] !== head)
37
+ continue;
38
+ const limit = Math.min(hay.count - 1, first + span - 1);
39
+ for (let last = first + 2; last <= limit; last += 1) {
40
+ if (trimmed[last] !== tail)
41
+ continue;
42
+ if (sharedLineCount(middle, trimmed.slice(first + 1, last)) < needed)
43
+ continue;
44
+ const range = hay.range(first, last, withBreak);
45
+ if (range === null)
46
+ continue;
47
+ ranges.push(range);
48
+ first = last;
49
+ break;
50
+ }
51
+ }
52
+ return ranges;
53
+ },
54
+ });
55
+ }
56
+ function sharedLineCount(needle, window) {
57
+ const counts = new Map();
58
+ for (const line of window)
59
+ counts.set(line, (counts.get(line) ?? 0) + 1);
60
+ let found = 0;
61
+ for (const line of needle) {
62
+ const left = counts.get(line) ?? 0;
63
+ if (left === 0)
64
+ continue;
65
+ counts.set(line, left - 1);
66
+ found += 1;
67
+ }
68
+ return found;
69
+ }
@@ -0,0 +1,6 @@
1
+ import type { Matcher } from "../contract/matcher.ts";
2
+ /**
3
+ * Matches old text that was escaped once too often, with `\n`, `\t`, `\"`,
4
+ * `\\`, or `\uXXXX` written out. The new text is unescaped the same way.
5
+ */
6
+ export declare function escapeMatcher(): Matcher;
@@ -0,0 +1,32 @@
1
+ import { findExact } from "./exact.js";
2
+ const ESCAPED = /\\(?:u[0-9a-fA-F]{4}|[nt"\\])/u;
3
+ const ESCAPES = /\\(?:u([0-9a-fA-F]{4})|([nt"\\]))/gu;
4
+ /**
5
+ * Matches old text that was escaped once too often, with `\n`, `\t`, `\"`,
6
+ * `\\`, or `\uXXXX` written out. The new text is unescaped the same way.
7
+ */
8
+ export function escapeMatcher() {
9
+ return Object.freeze({
10
+ id: "escape",
11
+ fuzzy: true,
12
+ describe: 'escape sequences such as \\n, \\t, and \\" written out in the old text',
13
+ find(haystack, needle, ctx) {
14
+ if (!ESCAPED.test(needle))
15
+ return [];
16
+ const plain = unescapeText(needle);
17
+ return plain === needle ? [] : findExact(haystack, plain, ctx);
18
+ },
19
+ adapt: (newText) => unescapeText(newText),
20
+ });
21
+ }
22
+ function unescapeText(text) {
23
+ return text.replace(ESCAPES, (_match, hex, char) => {
24
+ if (hex !== undefined)
25
+ return String.fromCharCode(Number.parseInt(hex, 16));
26
+ if (char === "n")
27
+ return "\n";
28
+ if (char === "t")
29
+ return "\t";
30
+ return char ?? "";
31
+ });
32
+ }
@@ -0,0 +1,4 @@
1
+ import type { Matcher, MatchContext, MatchRange } from "../contract/matcher.ts";
2
+ /** Matches the old text exactly. */
3
+ export declare function exactMatcher(): Matcher;
4
+ export declare function findExact(haystack: string, needle: string, ctx: MatchContext): MatchRange[];
@@ -0,0 +1,29 @@
1
+ import { fitsMode } from "./lines.js";
2
+ /** Matches the old text exactly. */
3
+ export function exactMatcher() {
4
+ return Object.freeze({
5
+ id: "exact",
6
+ fuzzy: false,
7
+ describe: "nothing: the text must match exactly",
8
+ find: findExact,
9
+ });
10
+ }
11
+ export function findExact(haystack, needle, ctx) {
12
+ const ranges = [];
13
+ if (needle === "")
14
+ return ranges;
15
+ let from = Math.max(0, ctx.from);
16
+ while (ranges.length < ctx.maxMatches) {
17
+ const start = haystack.indexOf(needle, from);
18
+ if (start === -1)
19
+ break;
20
+ const end = start + needle.length;
21
+ if (!fitsMode(haystack, start, end, ctx)) {
22
+ from = start + 1;
23
+ continue;
24
+ }
25
+ ranges.push({ start, end });
26
+ from = end;
27
+ }
28
+ return ranges;
29
+ }
@@ -0,0 +1,11 @@
1
+ export interface Folded {
2
+ readonly text: string;
3
+ readonly sourceStart: Int32Array;
4
+ readonly sourceEnd: Int32Array;
5
+ /** FIRST: the unit starts its source span's output. LAST: it ends it. */
6
+ readonly edges: Uint8Array;
7
+ readonly trimmedEnd: boolean;
8
+ }
9
+ export declare const FIRST = 1;
10
+ export declare const LAST = 2;
11
+ export declare function fold(text: string): Folded;