@agimon-ai/po-hashline 0.0.0-alpha.2 → 0.0.0-alpha.200

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.
package/LICENSE CHANGED
@@ -1,7 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2026 Vuong Ngo
4
- Copyright (c) 2026 pulseaiclub
3
+ Copyright (c) 2026 Agimon Pty Ltd
5
4
 
6
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
7
6
  of this software and associated documentation files (the "Software"), to deal
package/NOTICE ADDED
@@ -0,0 +1,35 @@
1
+ This package is licensed under the MIT License, see LICENSE.
2
+
3
+ Third-party components
4
+
5
+ The following material in this package was written by third parties. It is
6
+ not covered by this package's LICENSE and remains under its own license,
7
+ reproduced below. Where a file combines third-party material with changes by
8
+ Agimon Pty Ltd, the third-party portions remain under their original license
9
+ and the changes are licensed under this package's LICENSE.
10
+
11
+ 1. Phi writetool (https://github.com/pulseaiclub/phi/tree/main/internal/tools/writetool)
12
+ Used in: hashline protocol and FNV anchor implementation
13
+ License: MIT
14
+
15
+ MIT License
16
+
17
+ Copyright (c) 2026 pulseaiclub
18
+
19
+ Permission is hereby granted, free of charge, to any person obtaining a copy
20
+ of this software and associated documentation files (the "Software"), to deal
21
+ in the Software without restriction, including without limitation the rights
22
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
23
+ copies of the Software, and to permit persons to whom the Software is
24
+ furnished to do so, subject to the following conditions:
25
+
26
+ The above copyright notice and this permission notice shall be included in all
27
+ copies or substantial portions of the Software.
28
+
29
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
30
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
31
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
32
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
33
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
34
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
35
+ SOFTWARE.
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  Shared snapshot-bound file tags and line anchors for Po tools.
4
4
 
5
- This is a foundation library, not a Pi extension. It has no `pi.extensions` entry, Cordis service,
5
+ This is a shared utility library, not a Pi extension. It has no `pi.extensions` entry, Cordis service,
6
6
  or Pi peer dependency. Tool packages use the same protocol implementation without importing one
7
7
  another.
8
8
 
@@ -64,4 +64,4 @@ pnpm lint
64
64
 
65
65
  ## License
66
66
 
67
- MIT
67
+ MIT. See [LICENSE](LICENSE).
package/dist/files.cjs CHANGED
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./services/files/index.cjs");exports.computeFileTag=e.computeFileTag,exports.decodeUtf8=e.decodeUtf8,exports.displayPath=e.displayPath,exports.isWritableFile=e.isWritableFile,exports.resolveInputPath=e.resolveInputPath,exports.resolveReadInputPath=e.resolveReadInputPath;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./services/files/portable.cjs"),t=require("./services/files/index.cjs");exports.computeFileTag=e.computeFileTag,exports.decodeUtf8=e.decodeUtf8,exports.displayPath=e.displayPath,exports.isWritableFile=t.isWritableFile,exports.resolveInputPath=t.resolveInputPath,exports.resolveReadInputPath=t.resolveReadInputPath;
package/dist/files.d.mts CHANGED
@@ -1,2 +1,3 @@
1
- import { computeFileTag, decodeUtf8, displayPath, isWritableFile, resolveInputPath, resolveReadInputPath } from "./services/files/index.mjs";
1
+ import { computeFileTag, decodeUtf8, displayPath } from "./services/files/portable.mjs";
2
+ import { isWritableFile, resolveInputPath, resolveReadInputPath } from "./services/files/index.mjs";
2
3
  export { computeFileTag, decodeUtf8, displayPath, isWritableFile, resolveInputPath, resolveReadInputPath };
package/dist/files.mjs CHANGED
@@ -1 +1 @@
1
- import{computeFileTag as e,decodeUtf8 as t,displayPath as n,isWritableFile as r,resolveInputPath as i,resolveReadInputPath as a}from"./services/files/index.mjs";export{e as computeFileTag,t as decodeUtf8,n as displayPath,r as isWritableFile,i as resolveInputPath,a as resolveReadInputPath};
1
+ import{computeFileTag as e,decodeUtf8 as t,displayPath as n}from"./services/files/portable.mjs";import{isWritableFile as r,resolveInputPath as i,resolveReadInputPath as a}from"./services/files/index.mjs";export{e as computeFileTag,t as decodeUtf8,n as displayPath,r as isWritableFile,i as resolveInputPath,a as resolveReadInputPath};
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{applyHashlineEdits as e,formatFileHeader as t,formatTaggedLine as n,formatTaggedLines as r,hashLine as i,normalizeFileTag as a,normalizeToLf as o,parseFileHeader as s,parseLineAnchor as c,parseTaggedLine as l,splitLines as u,stripBom as d}from"./services/hashline/index.mjs";export{e as applyHashlineEdits,t as formatFileHeader,n as formatTaggedLine,r as formatTaggedLines,i as hashLine,a as normalizeFileTag,o as normalizeToLf,s as parseFileHeader,c as parseLineAnchor,l as parseTaggedLine,u as splitLines,d as stripBom};
1
+ export{applyHashlineEdits,formatFileHeader,formatTaggedLine,formatTaggedLines,hashLine,normalizeFileTag,normalizeToLf,parseFileHeader,parseLineAnchor,parseTaggedLine,splitLines,stripBom}from"./services/hashline/index.mjs";
@@ -0,0 +1 @@
1
+ {"version":1,"platformRequirements":{},"sourceFiles":["NOTICE","package.json","src/exports/files.ts","src/exports/index.ts","src/exports/truncate.ts","src/services/files/index.edge.ts","src/services/files/index.ts","src/services/files/portable.ts","src/services/hashline/index.ts","src/services/truncate/index.ts","src/types/hashline.ts","tsdown.config.ts"],"sourceRevision":"51599e3c8fb08c32bf084aa98639d9b5","manifestRevision":"ec6481137e6c872fe30d3d584ac4a733","outputFiles":["NOTICE","dist/files.cjs","dist/files.mjs","dist/index.cjs","dist/index.mjs","dist/services/files/index.cjs","dist/services/files/index.mjs","dist/services/files/portable.cjs","dist/services/files/portable.mjs","dist/services/hashline/index.cjs","dist/services/hashline/index.mjs","dist/services/truncate/index.cjs","dist/services/truncate/index.mjs","dist/truncate.cjs","dist/truncate.mjs"],"outputRevision":"43606b160d411aa57025ccfc55274d01"}
@@ -1,2 +1,2 @@
1
- let e=require("node:crypto"),t=require("node:fs"),n=require("node:fs/promises"),r=require("node:os"),i=require("node:path"),a=require("node:url");const o=/[\u00A0\u2000-\u200A\u202F\u205F\u3000]/gu;function s(t){return(0,e.createHash)(`sha256`).update(t).digest(`base64url`).slice(0,8)}function c(e,t){try{return new TextDecoder(`utf-8`,{fatal:!0}).decode(e)}catch(e){throw Error(`Cannot use hashline tools on ${t}: the file is not valid UTF-8.`,{cause:e})}}async function l(e){return(0,n.access)(e,t.constants.W_OK).then(()=>!0,()=>!1)}function u(e,t){let n=e.replace(o,` `);return n.startsWith(`@`)&&(n=n.slice(1)),process.platform===`win32`&&(n=m(n)),n===`~`?n=(0,r.homedir)():n.startsWith(`~${i.sep}`)?n=(0,i.resolve)((0,r.homedir)(),n.slice(2)):n.startsWith(`file://`)&&(n=(0,a.fileURLToPath)(n)),(0,i.isAbsolute)(n)?(0,i.resolve)(n):(0,i.resolve)(t,n)}async function d(e,t){let n=u(e,t);if(await p(n))return n;let r=[n.replace(/ (AM|PM)\./giu,` $1.`),n.normalize(`NFD`),n.replaceAll(`'`,`’`),n.normalize(`NFD`).replaceAll(`'`,`’`)];for(let e of r)if(e!==n&&await p(e))return e;return n}function f(e,t){let n=(0,i.relative)(t,e),r=(n!==``&&n!==`..`&&!n.startsWith(`..${i.sep}`)&&!(0,i.isAbsolute)(n)?n:e).split(i.sep).join(`/`);return r===`~`||r.startsWith(`~/`)?`./${r}`:r}async function p(e){return(0,n.access)(e).then(()=>!0,()=>!1)}function m(e){if(!e.startsWith(`/`)||e.startsWith(`//`)||e.includes(`\\`))return e;let t=/^\/(?:mnt\/|cygdrive\/)?([a-z])(?:\/(.*))?$/iu.exec(e);if(!t?.[1])return e;let n=t[2]?.replaceAll(`/`,`\\`);return`${t[1].toUpperCase()}:\\${n??``}`}exports.computeFileTag=s,exports.decodeUtf8=c,exports.displayPath=f,exports.isWritableFile=l,exports.resolveInputPath=u,exports.resolveReadInputPath=d;
1
+ const e=require("./portable.cjs");let t=require("node:fs"),n=require("node:fs/promises"),r=require("node:os"),i=require("node:path"),a=require("node:url");async function o(e){return(0,n.access)(e,t.constants.W_OK).then(()=>!0,()=>!1)}function s(t,n){let o=e.normalizeInputPath(t);return process.platform===`win32`&&(o=u(o)),o===`~`?o=(0,r.homedir)():o.startsWith(`~${i.sep}`)?o=(0,i.resolve)((0,r.homedir)(),o.slice(2)):o.startsWith(`file://`)&&(o=(0,a.fileURLToPath)(o)),(0,i.isAbsolute)(o)?(0,i.resolve)(o):(0,i.resolve)(n,o)}async function c(e,t){let n=s(e,t);if(await l(n))return n;let r=[n.replace(/ (AM|PM)\./giu,` $1.`),n.normalize(`NFD`),n.replaceAll(`'`,`’`),n.normalize(`NFD`).replaceAll(`'`,`’`)];for(let e of r)if(e!==n&&await l(e))return e;return n}async function l(e){return(0,n.access)(e).then(()=>!0,()=>!1)}function u(e){if(!e.startsWith(`/`)||e.startsWith(`//`)||e.includes(`\\`))return e;let t=/^\/(?:mnt\/|cygdrive\/)?([a-z])(?:\/(.*))?$/iu.exec(e);if(!t?.[1])return e;let n=t[2]?.replaceAll(`/`,`\\`);return`${t[1].toUpperCase()}:\\${n??``}`}exports.computeFileTag=e.computeFileTag,exports.decodeUtf8=e.decodeUtf8,exports.displayPath=e.displayPath,exports.isWritableFile=o,exports.resolveInputPath=s,exports.resolveReadInputPath=c;
2
2
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["createHash","access","constants","homedir","sep","resolve","fileURLToPath","isAbsolute","relative","node_crypto","node_fs","node_fs_promises","node_os","node_path","node_url","UNICODE_SPACES","computeFileTag","bytes","decodeUtf8","error","path","isWritableFile","resolveInputPath","input","normalizeWindowsShellPath","cwd","resolveReadInputPath","resolved","pathExists","variants","candidate","displayPath","absolutePath","portable","match","suffix"],"sources":["../../../src/services/files/index.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport { constants } from 'node:fs';\nimport { access } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { isAbsolute, relative, resolve, sep } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nconst UNICODE_SPACES = /[\\u00A0\\u2000-\\u200A\\u202F\\u205F\\u3000]/gu;\nconst NARROW_NO_BREAK_SPACE = '\\u202f';\n\nexport function computeFileTag(bytes: Uint8Array): string {\n return createHash('sha256').update(bytes).digest('base64url').slice(0, 8);\n}\n\nexport function decodeUtf8(bytes: Uint8Array, path: string): string {\n try {\n return new TextDecoder('utf-8', { fatal: true }).decode(bytes);\n } catch (error) {\n throw new Error(`Cannot use hashline tools on ${path}: the file is not valid UTF-8.`, { cause: error });\n }\n}\n\n/** Return whether the current process can edit an existing file. */\nexport async function isWritableFile(path: string): Promise<boolean> {\n return access(path, constants.W_OK).then(\n () => true,\n () => false,\n );\n}\n\nexport function resolveInputPath(input: string, cwd: string): string {\n let path = input.replace(UNICODE_SPACES, ' ');\n if (path.startsWith('@')) path = path.slice(1);\n if (process.platform === 'win32') path = normalizeWindowsShellPath(path);\n if (path === '~') path = homedir();\n else if (path.startsWith(`~${sep}`)) path = resolve(homedir(), path.slice(2));\n else if (path.startsWith('file://')) path = fileURLToPath(path);\n return isAbsolute(path) ? resolve(path) : resolve(cwd, path);\n}\n\n/** Resolve the same existing-file variants as Pi's native read tool. */\nexport async function resolveReadInputPath(input: string, cwd: string): Promise<string> {\n const resolved = resolveInputPath(input, cwd);\n if (await pathExists(resolved)) return resolved;\n\n const variants = [\n resolved.replace(/ (AM|PM)\\./giu, `${NARROW_NO_BREAK_SPACE}$1.`),\n resolved.normalize('NFD'),\n resolved.replaceAll(\"'\", '\\u2019'),\n resolved.normalize('NFD').replaceAll(\"'\", '\\u2019'),\n ];\n for (const candidate of variants) {\n if (candidate !== resolved && (await pathExists(candidate))) return candidate;\n }\n return resolved;\n}\n\nexport function displayPath(absolutePath: string, cwd: string): string {\n const path = relative(cwd, absolutePath);\n const display =\n path !== '' && path !== '..' && !path.startsWith(`..${sep}`) && !isAbsolute(path) ? path : absolutePath;\n const portable = display.split(sep).join('/');\n return portable === '~' || portable.startsWith('~/') ? `./${portable}` : portable;\n}\n\nasync function pathExists(path: string): Promise<boolean> {\n return access(path).then(\n () => true,\n () => false,\n );\n}\n\nfunction normalizeWindowsShellPath(path: string): string {\n if (!path.startsWith('/') || path.startsWith('//') || path.includes('\\\\')) return path;\n const match = /^\\/(?:mnt\\/|cygdrive\\/)?([a-z])(?:\\/(.*))?$/iu.exec(path);\n if (!match?.[1]) return path;\n const suffix = match[2]?.replaceAll('/', '\\\\');\n return `${match[1].toUpperCase()}:\\\\${suffix ?? ''}`;\n}\n"],"mappings":"kJAOA,MAAMe,EAAiB,4CAGvB,SAAgBC,EAAe,EAA2B,CACxD,OAAA,EAAOhB,EAAAA,WAAAA,CAAW,QAAQ,CAAC,CAAC,OAAOiB,CAAK,CAAC,CAAC,OAAO,WAAW,CAAC,CAAC,MAAM,EAAG,CAAC,CAC1E,CAEA,SAAgBC,EAAW,EAAmB,EAAsB,CAClE,GAAI,CACF,OAAO,IAAI,YAAY,QAAS,CAAE,MAAO,EAAK,CAAC,CAAC,CAAC,OAAOD,CAAK,CAC/D,OAASE,EAAO,CACd,MAAU,MAAM,gCAAgCC,EAAK,gCAAiC,CAAE,MAAOD,CAAM,CAAC,CACxG,CACF,CAGA,eAAsBE,EAAe,EAAgC,CACnE,OAAA,EAAOpB,EAAAA,OAAAA,CAAOmB,EAAMlB,EAAAA,UAAU,IAAI,CAAC,CAAC,SAC5B,OACA,EACR,CACF,CAEA,SAAgBoB,EAAiB,EAAe,EAAqB,CACnE,IAAIF,EAAOG,EAAM,QAAQR,EAAgB,GAAG,EAM5C,O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AAa,KAAOA,EAAS,WAAW,IAAI,EAAI,KAAKA,IAAaA,CAC3E,CAEA,eAAeL,EAAW,EAAgC,CACxD,OAAA,EAAO3B,EAAAA,OAAAA,CAAOmB,CAAI,CAAC,CAAC,SACZ,OACA,EACR,CACF,CAEA,SAASI,EAA0B,EAAsB,CACvD,GAAI,CAACJ,EAAK,WAAW,GAAG,GAAKA,EAAK,WAAW,IAAI,GAAKA,EAAK,SAAS,IAAI,EAAG,OAAOA,EAClF,IAAMc,EAAQ,gDAAgD,KAAKd,CAAI,EACvE,GAAI,CAACc,IAAQ,GAAI,OAAOd,EACxB,IAAMe,EAASD,EAAM,EAAE,EAAE,WAAW,IAAK,IAAI,EAC7C,MAAO,GAAGA,EAAM,EAAE,CAAC,YAAY,EAAE,KAAKC,GAAU,IAClD"}
1
+ {"version":3,"file":"index.cjs","names":["access","constants","normalizeInputPath","homedir","sep","resolve","fileURLToPath","isAbsolute","require_portable","node_fs","node_fs_promises","node_os","node_path","node_url","isWritableFile","path","resolveInputPath","input","normalizeWindowsShellPath","cwd","resolveReadInputPath","resolved","pathExists","variants","candidate","match","suffix"],"sources":["../../../src/services/files/index.ts"],"sourcesContent":["import { constants } from 'node:fs';\nimport { access } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { isAbsolute, resolve, sep } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nimport { normalizeInputPath } from './portable';\n\nexport { computeFileTag, decodeUtf8, displayPath } from './portable';\n\nconst NARROW_NO_BREAK_SPACE = '\\u202f';\n\n/** Return whether the current process can edit an existing file. */\nexport async function isWritableFile(path: string): Promise<boolean> {\n return access(path, constants.W_OK).then(\n () => true,\n () => false,\n );\n}\n\nexport function resolveInputPath(input: string, cwd: string): string {\n let path = normalizeInputPath(input);\n if (process.platform === 'win32') path = normalizeWindowsShellPath(path);\n if (path === '~') path = homedir();\n else if (path.startsWith(`~${sep}`)) path = resolve(homedir(), path.slice(2));\n else if (path.startsWith('file://')) path = fileURLToPath(path);\n return isAbsolute(path) ? resolve(path) : resolve(cwd, path);\n}\n\n/** Resolve the same existing-file variants as Pi's native read tool. */\nexport async function resolveReadInputPath(input: string, cwd: string): Promise<string> {\n const resolved = resolveInputPath(input, cwd);\n if (await pathExists(resolved)) return resolved;\n\n const variants = [\n resolved.replace(/ (AM|PM)\\./giu, `${NARROW_NO_BREAK_SPACE}$1.`),\n resolved.normalize('NFD'),\n resolved.replaceAll(\"'\", '\\u2019'),\n resolved.normalize('NFD').replaceAll(\"'\", '\\u2019'),\n ];\n for (const candidate of variants) {\n if (candidate !== resolved && (await pathExists(candidate))) return candidate;\n }\n return resolved;\n}\n\nasync function pathExists(path: string): Promise<boolean> {\n return access(path).then(\n () => true,\n () => false,\n );\n}\n\nfunction normalizeWindowsShellPath(path: string): string {\n if (!path.startsWith('/') || path.startsWith('//') || path.includes('\\\\')) return path;\n const match = /^\\/(?:mnt\\/|cygdrive\\/)?([a-z])(?:\\/(.*))?$/iu.exec(path);\n if (!match?.[1]) return path;\n const suffix = match[2]?.replaceAll('/', '\\\\');\n return `${match[1].toUpperCase()}:\\\\${suffix ?? ''}`;\n}\n"],"mappings":"A,2JAaA,eAAsBc,EAAe,EAAgC,CACnE,OAAA,EAAOd,EAAAA,OAAAA,CAAOe,EAAMd,EAAAA,UAAU,IAAI,CAAC,CAAC,SAC5B,OACA,EACR,CACF,CAEA,SAAgBe,EAAiB,EAAe,EAAqB,CACnE,IAAID,EAAOb,EAAAA,mBAAmBe,CAAK,EAKnC,OAJI,QAAQ,WAAa,UAAS,EAAOC,EAA0BH,CAAI,GACnEA,IAAS,IAAK,GAAA,EAAOZ,EAAAA,QAAAA,CAAQ,EACxBY,EAAK,WAAW,IAAIX,EAAAA,KAAK,EAAG,GAAA,EAAOC,EAAAA,QAAAA,EAAAA,EAAQF,EAAAA,QAAAA,CAAQ,EAAGY,EAAK,MAAM,CAAC,CAAC,EACnEA,EAAK,WAAW,SAAS,IAAG,GAAA,EAAOT,EAAAA,cAAAA,CAAcS,CAAI,IAC9D,EAAOR,EAAAA,WAAAA,CAAWQ,CAAI,GAAA,EAAIV,EAAAA,QAAAA,CAAQU,CAAI,GAAA,EAAIV,EAAAA,QAAAA,CAAQc,EAAKJ,CAAI,CAC7D,CAGA,eAAsBK,EAAqB,EAAe,EAA8B,CACtF,IAAMC,EAAWL,EAAiBC,EAAOE,CAAG,EAC5C,GAAI,MAAMG,EAAWD,CAAQ,EAAG,OAAOA,EAEvC,IAAME,EAAW,CACfF,EAAS,QAAQ,gBAAiB,MAA6B,EAC/DA,EAAS,UAAU,KAAK,EACxBA,EAAS,WAAW,IAAK,GAAQ,EACjCA,EAAS,UAAU,KAAK,CAAC,CAAC,WAAW,IAAK,GAAQ,CACpD,EACA,IAAK,IAAMG,KAAaD,EACtB,GAAIC,IAAcH,GAAa,MAAMC,EAAWE,CAAS,EAAI,OAAOA,EAEtE,OAAOH,CACT,CAEA,eAAeC,EAAW,EAAgC,CACxD,OAAA,EAAOtB,EAAAA,OAAAA,CAAOe,CAAI,CAAC,CAAC,SACZ,OACA,EACR,CACF,CAEA,SAASG,EAA0B,EAAsB,CACvD,GAAI,CAACH,EAAK,WAAW,GAAG,GAAKA,EAAK,WAAW,IAAI,GAAKA,EAAK,SAAS,IAAI,EAAG,OAAOA,EAClF,IAAMU,EAAQ,gDAAgD,KAAKV,CAAI,EACvE,GAAI,CAACU,IAAQ,GAAI,OAAOV,EACxB,IAAMW,EAASD,EAAM,EAAE,EAAE,WAAW,IAAK,IAAI,EAC7C,MAAO,GAAGA,EAAM,EAAE,CAAC,YAAY,EAAE,KAAKC,GAAU,IAClD,C"}
@@ -1,11 +1,10 @@
1
+ import { computeFileTag, decodeUtf8, displayPath } from "./portable.mjs";
1
2
  //#region src/services/files/index.d.ts
2
- export declare function computeFileTag(bytes: Uint8Array): string;
3
- export declare function decodeUtf8(bytes: Uint8Array, path: string): string;
4
3
  /** Return whether the current process can edit an existing file. */
5
4
  export declare function isWritableFile(path: string): Promise<boolean>;
6
5
  export declare function resolveInputPath(input: string, cwd: string): string;
7
6
  /** Resolve the same existing-file variants as Pi's native read tool. */
8
7
  export declare function resolveReadInputPath(input: string, cwd: string): Promise<string>;
9
- export declare function displayPath(absolutePath: string, cwd: string): string;
10
8
  //#endregion
9
+ export { computeFileTag, decodeUtf8, displayPath };
11
10
  //# sourceMappingURL=index.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../../../src/services/files/index.ts"],"mappings":";wBAUgB,eAAe,OAAO;wBAItB,WAAW,OAAO,YAAY;;wBASxB,eAAe,eAAe;wBAOpC,iBAAiB,eAAe;;wBAW1B,qBAAqB,eAAe,cAAc;wBAgBxD,YAAY,sBAAsB"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../../../src/services/files/index.ts"],"mappings":";;;wBAasB,eAAe,eAAe;wBAOpC,iBAAiB,eAAe;;wBAU1B,qBAAqB,eAAe,cAAc"}
@@ -1,2 +1,2 @@
1
- import{createHash as e}from"node:crypto";import{constants as t}from"node:fs";import{access as n}from"node:fs/promises";import{homedir as r}from"node:os";import{isAbsolute as i,relative as a,resolve as o,sep as s}from"node:path";import{fileURLToPath as c}from"node:url";const l=/[\u00A0\u2000-\u200A\u202F\u205F\u3000]/gu;function u(t){return e(`sha256`).update(t).digest(`base64url`).slice(0,8)}function d(e,t){try{return new TextDecoder(`utf-8`,{fatal:!0}).decode(e)}catch(e){throw Error(`Cannot use hashline tools on ${t}: the file is not valid UTF-8.`,{cause:e})}}async function f(e){return n(e,t.W_OK).then(()=>!0,()=>!1)}function p(e,t){let n=e.replace(l,` `);return n.startsWith(`@`)&&(n=n.slice(1)),process.platform===`win32`&&(n=_(n)),n===`~`?n=r():n.startsWith(`~${s}`)?n=o(r(),n.slice(2)):n.startsWith(`file://`)&&(n=c(n)),i(n)?o(n):o(t,n)}async function m(e,t){let n=p(e,t);if(await g(n))return n;let r=[n.replace(/ (AM|PM)\./giu,` $1.`),n.normalize(`NFD`),n.replaceAll(`'`,`’`),n.normalize(`NFD`).replaceAll(`'`,`’`)];for(let e of r)if(e!==n&&await g(e))return e;return n}function h(e,t){let n=a(t,e),r=(n!==``&&n!==`..`&&!n.startsWith(`..${s}`)&&!i(n)?n:e).split(s).join(`/`);return r===`~`||r.startsWith(`~/`)?`./${r}`:r}async function g(e){return n(e).then(()=>!0,()=>!1)}function _(e){if(!e.startsWith(`/`)||e.startsWith(`//`)||e.includes(`\\`))return e;let t=/^\/(?:mnt\/|cygdrive\/)?([a-z])(?:\/(.*))?$/iu.exec(e);if(!t?.[1])return e;let n=t[2]?.replaceAll(`/`,`\\`);return`${t[1].toUpperCase()}:\\${n??``}`}export{u as computeFileTag,d as decodeUtf8,h as displayPath,f as isWritableFile,p as resolveInputPath,m as resolveReadInputPath};
1
+ import{computeFileTag as e,decodeUtf8 as t,displayPath as n,normalizeInputPath as r}from"./portable.mjs";import{constants as i}from"node:fs";import{access as a}from"node:fs/promises";import{homedir as o}from"node:os";import{isAbsolute as s,resolve as c,sep as l}from"node:path";import{fileURLToPath as u}from"node:url";async function d(e){return a(e,i.W_OK).then(()=>!0,()=>!1)}function f(e,t){let n=r(e);return process.platform===`win32`&&(n=h(n)),n===`~`?n=o():n.startsWith(`~${l}`)?n=c(o(),n.slice(2)):n.startsWith(`file://`)&&(n=u(n)),s(n)?c(n):c(t,n)}async function p(e,t){let n=f(e,t);if(await m(n))return n;let r=[n.replace(/ (AM|PM)\./giu,` $1.`),n.normalize(`NFD`),n.replaceAll(`'`,`’`),n.normalize(`NFD`).replaceAll(`'`,`’`)];for(let e of r)if(e!==n&&await m(e))return e;return n}async function m(e){return a(e).then(()=>!0,()=>!1)}function h(e){if(!e.startsWith(`/`)||e.startsWith(`//`)||e.includes(`\\`))return e;let t=/^\/(?:mnt\/|cygdrive\/)?([a-z])(?:\/(.*))?$/iu.exec(e);if(!t?.[1])return e;let n=t[2]?.replaceAll(`/`,`\\`);return`${t[1].toUpperCase()}:\\${n??``}`}export{e as computeFileTag,t as decodeUtf8,n as displayPath,d as isWritableFile,f as resolveInputPath,p as resolveReadInputPath};
2
2
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["UNICODE_SPACES","computeFileTag","createHash","bytes","decodeUtf8","error","path","isWritableFile","access","constants","resolveInputPath","input","normalizeWindowsShellPath","homedir","sep","resolve","fileURLToPath","isAbsolute","cwd","resolveReadInputPath","resolved","pathExists","variants","candidate","displayPath","relative","absolutePath","portable","match","suffix"],"sources":["../../../src/services/files/index.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport { constants } from 'node:fs';\nimport { access } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { isAbsolute, relative, resolve, sep } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nconst UNICODE_SPACES = /[\\u00A0\\u2000-\\u200A\\u202F\\u205F\\u3000]/gu;\nconst NARROW_NO_BREAK_SPACE = '\\u202f';\n\nexport function computeFileTag(bytes: Uint8Array): string {\n return createHash('sha256').update(bytes).digest('base64url').slice(0, 8);\n}\n\nexport function decodeUtf8(bytes: Uint8Array, path: string): string {\n try {\n return new TextDecoder('utf-8', { fatal: true }).decode(bytes);\n } catch (error) {\n throw new Error(`Cannot use hashline tools on ${path}: the file is not valid UTF-8.`, { cause: error });\n }\n}\n\n/** Return whether the current process can edit an existing file. */\nexport async function isWritableFile(path: string): Promise<boolean> {\n return access(path, constants.W_OK).then(\n () => true,\n () => false,\n );\n}\n\nexport function resolveInputPath(input: string, cwd: string): string {\n let path = input.replace(UNICODE_SPACES, ' ');\n if (path.startsWith('@')) path = path.slice(1);\n if (process.platform === 'win32') path = normalizeWindowsShellPath(path);\n if (path === '~') path = homedir();\n else if (path.startsWith(`~${sep}`)) path = resolve(homedir(), path.slice(2));\n else if (path.startsWith('file://')) path = fileURLToPath(path);\n return isAbsolute(path) ? resolve(path) : resolve(cwd, path);\n}\n\n/** Resolve the same existing-file variants as Pi's native read tool. */\nexport async function resolveReadInputPath(input: string, cwd: string): Promise<string> {\n const resolved = resolveInputPath(input, cwd);\n if (await pathExists(resolved)) return resolved;\n\n const variants = [\n resolved.replace(/ (AM|PM)\\./giu, `${NARROW_NO_BREAK_SPACE}$1.`),\n resolved.normalize('NFD'),\n resolved.replaceAll(\"'\", '\\u2019'),\n resolved.normalize('NFD').replaceAll(\"'\", '\\u2019'),\n ];\n for (const candidate of variants) {\n if (candidate !== resolved && (await pathExists(candidate))) return candidate;\n }\n return resolved;\n}\n\nexport function displayPath(absolutePath: string, cwd: string): string {\n const path = relative(cwd, absolutePath);\n const display =\n path !== '' && path !== '..' && !path.startsWith(`..${sep}`) && !isAbsolute(path) ? path : absolutePath;\n const portable = display.split(sep).join('/');\n return portable === '~' || portable.startsWith('~/') ? `./${portable}` : portable;\n}\n\nasync function pathExists(path: string): Promise<boolean> {\n return access(path).then(\n () => true,\n () => false,\n );\n}\n\nfunction normalizeWindowsShellPath(path: string): string {\n if (!path.startsWith('/') || path.startsWith('//') || path.includes('\\\\')) return path;\n const match = /^\\/(?:mnt\\/|cygdrive\\/)?([a-z])(?:\\/(.*))?$/iu.exec(path);\n if (!match?.[1]) return path;\n const suffix = match[2]?.replaceAll('/', '\\\\');\n return `${match[1].toUpperCase()}:\\\\${suffix ?? ''}`;\n}\n"],"mappings":"6QAOA,MAAMA,EAAiB,4CAGvB,SAAgBC,EAAe,EAA2B,CACxD,OAAOC,EAAW,QAAQ,CAAC,CAAC,OAAOC,CAAK,CAAC,CAAC,OAAO,WAAW,CAAC,CAAC,MAAM,EAAG,CAAC,CAC1E,CAEA,SAAgBC,EAAW,EAAmB,EAAsB,CAClE,GAAI,CACF,OAAO,IAAI,YAAY,QAAS,CAAE,MAAO,EAAK,CAAC,CAAC,CAAC,OAAOD,CAAK,CAC/D,OAASE,EAAO,CACd,MAAU,MAAM,gCAAgCC,EAAK,gCAAiC,CAAE,MAAOD,CAAM,CAAC,CACxG,CACF,CAGA,eAAsBE,EAAe,EAAgC,CACnE,OAAOC,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AEA,eAAeN,EAAW,EAAgC,CACxD,OAAOb,EAAOF,CAAI,CAAC,CAAC,SACZ,OACA,EACR,CACF,CAEA,SAASM,EAA0B,EAAsB,CACvD,GAAI,CAACN,EAAK,WAAW,GAAG,GAAKA,EAAK,WAAW,IAAI,GAAKA,EAAK,SAAS,IAAI,EAAG,OAAOA,EAClF,IAAMsB,EAAQ,gDAAgD,KAAKtB,CAAI,EACvE,GAAI,CAACsB,IAAQ,GAAI,OAAOtB,EACxB,IAAMuB,EAASD,EAAM,EAAE,EAAE,WAAW,IAAK,IAAI,EAC7C,MAAO,GAAGA,EAAM,EAAE,CAAC,YAAY,EAAE,KAAKC,GAAU,IAClD"}
1
+ {"version":3,"file":"index.mjs","names":["isWritableFile","access","path","constants","resolveInputPath","normalizeInputPath","input","normalizeWindowsShellPath","homedir","sep","resolve","fileURLToPath","isAbsolute","cwd","resolveReadInputPath","resolved","pathExists","variants","candidate","match","suffix","computeFileTag","decodeUtf8","displayPath"],"sources":["../../../src/services/files/index.ts"],"sourcesContent":["import { constants } from 'node:fs';\nimport { access } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { isAbsolute, resolve, sep } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nimport { normalizeInputPath } from './portable';\n\nexport { computeFileTag, decodeUtf8, displayPath } from './portable';\n\nconst NARROW_NO_BREAK_SPACE = '\\u202f';\n\n/** Return whether the current process can edit an existing file. */\nexport async function isWritableFile(path: string): Promise<boolean> {\n return access(path, constants.W_OK).then(\n () => true,\n () => false,\n );\n}\n\nexport function resolveInputPath(input: string, cwd: string): string {\n let path = normalizeInputPath(input);\n if (process.platform === 'win32') path = normalizeWindowsShellPath(path);\n if (path === '~') path = homedir();\n else if (path.startsWith(`~${sep}`)) path = resolve(homedir(), path.slice(2));\n else if (path.startsWith('file://')) path = fileURLToPath(path);\n return isAbsolute(path) ? resolve(path) : resolve(cwd, path);\n}\n\n/** Resolve the same existing-file variants as Pi's native read tool. */\nexport async function resolveReadInputPath(input: string, cwd: string): Promise<string> {\n const resolved = resolveInputPath(input, cwd);\n if (await pathExists(resolved)) return resolved;\n\n const variants = [\n resolved.replace(/ (AM|PM)\\./giu, `${NARROW_NO_BREAK_SPACE}$1.`),\n resolved.normalize('NFD'),\n resolved.replaceAll(\"'\", '\\u2019'),\n resolved.normalize('NFD').replaceAll(\"'\", '\\u2019'),\n ];\n for (const candidate of variants) {\n if (candidate !== resolved && (await pathExists(candidate))) return candidate;\n }\n return resolved;\n}\n\nasync function pathExists(path: string): Promise<boolean> {\n return access(path).then(\n () => true,\n () => false,\n );\n}\n\nfunction normalizeWindowsShellPath(path: string): string {\n if (!path.startsWith('/') || path.startsWith('//') || path.includes('\\\\')) return path;\n const match = /^\\/(?:mnt\\/|cygdrive\\/)?([a-z])(?:\\/(.*))?$/iu.exec(path);\n if (!match?.[1]) return path;\n const suffix = match[2]?.replaceAll('/', '\\\\');\n return `${match[1].toUpperCase()}:\\\\${suffix ?? ''}`;\n}\n"],"mappings":"A,+TAaA,eAAsBA,EAAe,EAAgC,CACnE,OAAOC,EAAOC,EAAMC,EAAU,IAAI,CAAC,CAAC,SAC5B,OACA,EACR,CACF,CAEA,SAAgBC,EAAiB,EAAe,EAAqB,CACnE,IAAIF,EAAOG,EAAmBC,CAAK,EAKnC,OAJI,QAAQ,WAAa,UAAS,EAAOC,EAA0BL,CAAI,GACnEA,IAAS,IAAK,EAAOM,EAAQ,EACxBN,EAAK,WAAW,IAAIO,GAAK,EAAG,EAAOC,EAAQF,EAAQ,EAAGN,EAAK,MAAM,CAAC,CAAC,EACnEA,EAAK,WAAW,SAAS,IAAG,EAAOS,EAAcT,CAAI,GACvDU,EAAWV,CAAI,EAAIQ,EAAQR,CAAI,EAAIQ,EAAQG,EAAKX,CAAI,CAC7D,CAGA,eAAsBY,EAAqB,EAAe,EAA8B,CACtF,IAAMC,EAAWX,EAAiBE,EAAOO,CAAG,EAC5C,GAAI,MAAMG,EAAWD,CAAQ,EAAG,OAAOA,EAEvC,IAAME,EAAW,CACfF,EAAS,QAAQ,gBAAiB,MAA6B,EAC/DA,EAAS,UAAU,KAAK,EACxBA,EAAS,WAAW,IAAK,GAAQ,EACjCA,EAAS,UAAU,KAAK,CAAC,CAAC,WAAW,IAAK,GAAQ,CACpD,EACA,IAAK,IAAMG,KAAaD,EACtB,GAAIC,IAAcH,GAAa,MAAMC,EAAWE,CAAS,EAAI,OAAOA,EAEtE,OAAOH,CACT,CAEA,eAAeC,EAAW,EAAgC,CACxD,OAAOf,EAAOC,CAAI,CAAC,CAAC,SACZ,OACA,EACR,CACF,CAEA,SAASK,EAA0B,EAAsB,CACvD,GAAI,CAACL,EAAK,WAAW,GAAG,GAAKA,EAAK,WAAW,IAAI,GAAKA,EAAK,SAAS,IAAI,EAAG,OAAOA,EAClF,IAAMiB,EAAQ,gDAAgD,KAAKjB,CAAI,EACvE,GAAI,CAACiB,IAAQ,GAAI,OAAOjB,EACxB,IAAMkB,EAASD,EAAM,EAAE,EAAE,WAAW,IAAK,IAAI,EAC7C,MAAO,GAAGA,EAAM,EAAE,CAAC,YAAY,EAAE,KAAKC,GAAU,IAClD,C"}
@@ -0,0 +1,2 @@
1
+ let e=require("node:path"),t=require("node:crypto");const n=/[\u00A0\u2000-\u200A\u202F\u205F\u3000]/gu;function r(e){return(0,t.createHash)(`sha256`).update(e).digest(`base64url`).slice(0,8)}function i(e,t){try{return new TextDecoder(`utf-8`,{fatal:!0}).decode(e)}catch(e){throw Error(`Cannot use hashline tools on ${t}: the file is not valid UTF-8.`,{cause:e})}}function a(e){let t=e.replace(n,` `);return t.startsWith(`@`)?t.slice(1):t}function o(t,n){let r=(0,e.relative)(n,t),i=(r!==``&&r!==`..`&&!r.startsWith(`..${e.sep}`)&&!(0,e.isAbsolute)(r)?r:t).split(e.sep).join(`/`);return i===`~`||i.startsWith(`~/`)?`./${i}`:i}exports.computeFileTag=r,exports.decodeUtf8=i,exports.displayPath=o,exports.normalizeInputPath=a;
2
+ //# sourceMappingURL=portable.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"portable.cjs","names":["createHash","relative","sep","isAbsolute","node_path","node_crypto","UNICODE_SPACES","computeFileTag","bytes","decodeUtf8","error","path","normalizeInputPath","input","displayPath","cwd","absolutePath","portable"],"sources":["../../../src/services/files/portable.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport { isAbsolute, relative, sep } from 'node:path';\n\n// The parts of the file helpers that behave the same on every host, so the Node and edge modules cannot drift.\nconst UNICODE_SPACES = /[\\u00A0\\u2000-\\u200A\\u202F\\u205F\\u3000]/gu;\n\nexport function computeFileTag(bytes: Uint8Array): string {\n return createHash('sha256').update(bytes).digest('base64url').slice(0, 8);\n}\n\nexport function decodeUtf8(bytes: Uint8Array, path: string): string {\n try {\n return new TextDecoder('utf-8', { fatal: true }).decode(bytes);\n } catch (error) {\n throw new Error(`Cannot use hashline tools on ${path}: the file is not valid UTF-8.`, { cause: error });\n }\n}\n\n/** Normalize an input path the way Pi's tools do: Unicode spaces become spaces and one leading `@` is dropped. */\nexport function normalizeInputPath(input: string): string {\n const path = input.replace(UNICODE_SPACES, ' ');\n return path.startsWith('@') ? path.slice(1) : path;\n}\n\nexport function displayPath(absolutePath: string, cwd: string): string {\n const path = relative(cwd, absolutePath);\n const display =\n path !== '' && path !== '..' && !path.startsWith(`..${sep}`) && !isAbsolute(path) ? path : absolutePath;\n const portable = display.split(sep).join('/');\n return portable === '~' || portable.startsWith('~/') ? `./${portable}` : portable;\n}\n"],"mappings":"A,oDAIA,MAAMM,EAAiB,4CAEvB,SAAgBC,EAAe,EAA2B,CACxD,OAAA,EAAOP,EAAAA,WAAAA,CAAW,QAAQ,CAAC,CAAC,OAAOQ,CAAK,CAAC,CAAC,OAAO,WAAW,CAAC,CAAC,MAAM,EAAG,CAAC,CAC1E,CAEA,SAAgBC,EAAW,EAAmB,EAAsB,CAClE,GAAI,CACF,OAAO,IAAI,YAAY,QAAS,CAAE,MAAO,EAAK,CAAC,CAAC,CAAC,OAAOD,CAAK,CAC/D,OAASE,EAAO,CACd,MAAU,MAAM,gCAAgCC,EAAK,gCAAiC,CAAE,MAAOD,CAAM,CAAC,CACxG,CACF,CAGA,SAAgBE,EAAmB,EAAuB,CACxD,IAAMD,EAAOE,EAAM,QAAQP,EAAgB,GAAG,EAC9C,OAAOK,EAAK,WAAW,GAAG,EAAIA,EAAK,MAAM,CAAC,EAAIA,CAChD,CAEA,SAAgBG,EAAY,EAAsB,EAAqB,CACrE,IAAMH,GAAA,EAAOV,EAAAA,SAAAA,CAASc,EAAKC,CAAY,EAGjCC,GADJN,IAAS,IAAMA,IAAS,MAAQ,CAACA,EAAK,WAAW,KAAKT,EAAAA,KAAK,GAAK,EAAA,EAACC,EAAAA,WAAAA,CAAWQ,CAAI,EAAIA,EAAOK,EAAA,CACpE,MAAMd,EAAAA,GAAG,CAAC,CAAC,KAAK,GAAG,EAC5C,OAAOe,IAAa,KAAOA,EAAS,WAAW,IAAI,EAAI,KAAKA,IAAaA,CAC3E,C"}
@@ -0,0 +1,6 @@
1
+ //#region src/services/files/portable.d.ts
2
+ export declare function computeFileTag(bytes: Uint8Array): string;
3
+ export declare function decodeUtf8(bytes: Uint8Array, path: string): string;
4
+ export declare function displayPath(absolutePath: string, cwd: string): string;
5
+ //#endregion
6
+ //# sourceMappingURL=portable.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"portable.d.mts","names":[],"sources":["../../../src/services/files/portable.ts"],"mappings":";wBAMgB,eAAe,OAAO;wBAItB,WAAW,OAAO,YAAY;wBAc9B,YAAY,sBAAsB"}
@@ -0,0 +1,2 @@
1
+ import{isAbsolute as e,relative as t,sep as n}from"node:path";import{createHash as r}from"node:crypto";const i=/[\u00A0\u2000-\u200A\u202F\u205F\u3000]/gu;function a(e){return r(`sha256`).update(e).digest(`base64url`).slice(0,8)}function o(e,t){try{return new TextDecoder(`utf-8`,{fatal:!0}).decode(e)}catch(e){throw Error(`Cannot use hashline tools on ${t}: the file is not valid UTF-8.`,{cause:e})}}function s(e){let t=e.replace(i,` `);return t.startsWith(`@`)?t.slice(1):t}function c(r,i){let a=t(i,r),o=(a!==``&&a!==`..`&&!a.startsWith(`..${n}`)&&!e(a)?a:r).split(n).join(`/`);return o===`~`||o.startsWith(`~/`)?`./${o}`:o}export{a as computeFileTag,o as decodeUtf8,c as displayPath,s as normalizeInputPath};
2
+ //# sourceMappingURL=portable.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"portable.mjs","names":["UNICODE_SPACES","computeFileTag","createHash","bytes","decodeUtf8","error","path","normalizeInputPath","input","displayPath","relative","cwd","absolutePath","portable","sep","isAbsolute"],"sources":["../../../src/services/files/portable.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport { isAbsolute, relative, sep } from 'node:path';\n\n// The parts of the file helpers that behave the same on every host, so the Node and edge modules cannot drift.\nconst UNICODE_SPACES = /[\\u00A0\\u2000-\\u200A\\u202F\\u205F\\u3000]/gu;\n\nexport function computeFileTag(bytes: Uint8Array): string {\n return createHash('sha256').update(bytes).digest('base64url').slice(0, 8);\n}\n\nexport function decodeUtf8(bytes: Uint8Array, path: string): string {\n try {\n return new TextDecoder('utf-8', { fatal: true }).decode(bytes);\n } catch (error) {\n throw new Error(`Cannot use hashline tools on ${path}: the file is not valid UTF-8.`, { cause: error });\n }\n}\n\n/** Normalize an input path the way Pi's tools do: Unicode spaces become spaces and one leading `@` is dropped. */\nexport function normalizeInputPath(input: string): string {\n const path = input.replace(UNICODE_SPACES, ' ');\n return path.startsWith('@') ? path.slice(1) : path;\n}\n\nexport function displayPath(absolutePath: string, cwd: string): string {\n const path = relative(cwd, absolutePath);\n const display =\n path !== '' && path !== '..' && !path.startsWith(`..${sep}`) && !isAbsolute(path) ? path : absolutePath;\n const portable = display.split(sep).join('/');\n return portable === '~' || portable.startsWith('~/') ? `./${portable}` : portable;\n}\n"],"mappings":"A,uGAIA,MAAMA,EAAiB,4CAEvB,SAAgBC,EAAe,EAA2B,CACxD,OAAOC,EAAW,QAAQ,CAAC,CAAC,OAAOC,CAAK,CAAC,CAAC,OAAO,WAAW,CAAC,CAAC,MAAM,EAAG,CAAC,CAC1E,CAEA,SAAgBC,EAAW,EAAmB,EAAsB,CAClE,GAAI,CACF,OAAO,IAAI,YAAY,QAAS,CAAE,MAAO,EAAK,CAAC,CAAC,CAAC,OAAOD,CAAK,CAC/D,OAASE,EAAO,CACd,MAAU,MAAM,gCAAgCC,EAAK,gCAAiC,CAAE,MAAOD,CAAM,CAAC,CACxG,CACF,CAGA,SAAgBE,EAAmB,EAAuB,CACxD,IAAMD,EAAOE,EAAM,QAAQR,EAAgB,GAAG,EAC9C,OAAOM,EAAK,WAAW,GAAG,EAAIA,EAAK,MAAM,CAAC,EAAIA,CAChD,CAEA,SAAgBG,EAAY,EAAsB,EAAqB,CACrE,IAAMH,EAAOI,EAASC,EAAKC,CAAY,EAGjCC,GADJP,IAAS,IAAMA,IAAS,MAAQ,CAACA,EAAK,WAAW,KAAKQ,GAAK,GAAK,CAACC,EAAWT,CAAI,EAAIA,EAAOM,EAAA,CACpE,MAAME,CAAG,CAAC,CAAC,KAAK,GAAG,EAC5C,OAAOD,IAAa,KAAOA,EAAS,WAAW,IAAI,EAAI,KAAKA,IAAaA,CAC3E,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["ANCHOR_SPACE","FILE_TAG_PATTERN","FILE_HEADER_PATTERN","TAGGED_LINE_PATTERN","ANCHOR_PATTERN","ASCII_WHITESPACE","hashLine","bytes","line","hash","byte","value","letters","index","normalizeToLf","text","stripBom","splitLines","normalizeFileTag","trimmed","hashIndex","tag","formatFileHeader","path","parseFileHeader","match","formatTaggedLine","assertLineNumber","lineNumber","prefix","anchorSource","formatTaggedLines","lines","firstLine","parseTaggedLine","lineText","content","marker","taggedLineMarker","parseLineAnchor","applyHashlineEdits","originalContent","edits","deduplicateEdits","requestedEdits","validateEdit","edit","compareEdits","validateNoOverlaps","result","deleteCount","replacements","splitReplacement","from","to","validateAnchor","anchor","currentHash","unique","key","left","right","previous","current","normalized"],"sources":["../../../src/services/hashline/index.ts"],"sourcesContent":["import type {\n AppliedHashlineEdits,\n FileHeader,\n HashlineRangeInput,\n LineAnchor,\n ParsedTaggedLine,\n PreparedHashlineEdit,\n TaggedLineMarker,\n TaggedLinePrefix,\n} from '../../types/hashline';\n\nconst FNV_OFFSET_BASIS = 0xcbf29ce484222325n;\nconst FNV_PRIME = 0x100000001b3n;\nconst ANCHOR_SPACE = 26n * 26n * 26n;\nconst ASCII_A = 97;\nconst FILE_TAG_PATTERN = /^[A-Za-z0-9_-]{8}$/u;\nconst FILE_HEADER_PATTERN = /^@file (.+)#([A-Za-z0-9_-]{8})$/u;\nconst TAGGED_LINE_PATTERN = /^(>> | {3})?(\\d+)#[a-z]{3}\\|(.*)$/u;\nconst ANCHOR_PATTERN = /^\\s*[>+-]*\\s*(\\d+)\\s*[:#]\\s*([a-zA-Z]{3})(?:\\s*\\|.*)?\\s*$/u;\nconst ASCII_WHITESPACE = /[ \\t\\n\\r\\v\\f]/gu;\n\n/**\n * Return Phi's three-letter whitespace-insensitive FNV-1a64 line anchor.\n * Adapted from pulseaiclub/phi writetool under the MIT license.\n */\nexport function hashLine(line: string): string {\n const bytes = new TextEncoder().encode(line.replace(ASCII_WHITESPACE, ''));\n let hash = FNV_OFFSET_BASIS;\n for (const byte of bytes) {\n hash ^= BigInt(byte);\n hash = BigInt.asUintN(64, hash * FNV_PRIME);\n }\n\n let value = hash % ANCHOR_SPACE;\n const letters = Array.from({ length: 3 }, () => '');\n for (let index = letters.length - 1; index >= 0; index -= 1) {\n letters[index] = String.fromCharCode(ASCII_A + Number(value % 26n));\n value /= 26n;\n }\n return letters.join('');\n}\n\nexport function normalizeToLf(text: string): string {\n return text.replace(/\\r\\n/gu, '\\n').replace(/\\r/gu, '\\n');\n}\n\nexport function stripBom(text: string): string {\n return text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;\n}\n\nexport function splitLines(text: string): string[] {\n return normalizeToLf(stripBom(text)).split('\\n');\n}\n\nexport function normalizeFileTag(value: string): string {\n const trimmed = value.trim();\n const hashIndex = trimmed.lastIndexOf('#');\n const tag = hashIndex === -1 ? trimmed : trimmed.slice(hashIndex + 1);\n if (!FILE_TAG_PATTERN.test(tag)) {\n throw new Error(`Invalid file hash: ${value}. Expected the eight-character tag from @file path#HASH.`);\n }\n return tag;\n}\n\nexport function formatFileHeader(path: string, tag: string): string {\n if (path.length === 0 || path.includes('\\n') || path.includes('\\r')) {\n throw new Error('Invalid file header path. Expected one non-empty path without line breaks.');\n }\n return `@file ${path}#${normalizeFileTag(tag)}`;\n}\n\nexport function parseFileHeader(value: string): FileHeader | undefined {\n const match = FILE_HEADER_PATTERN.exec(value);\n const path = match?.[1];\n const tag = match?.[2];\n return path === undefined || tag === undefined ? undefined : { path, tag };\n}\n\nexport function formatTaggedLine(\n line: string,\n lineNumber: number,\n prefix: TaggedLinePrefix = '',\n anchorSource = line,\n): string {\n assertLineNumber(lineNumber);\n return `${prefix}${lineNumber}#${hashLine(anchorSource)}|${line}`;\n}\n\nexport function formatTaggedLines(lines: readonly string[], firstLine = 1): string {\n return lines.map((line, index) => formatTaggedLine(line, firstLine + index)).join('\\n');\n}\n\nexport function parseTaggedLine(value: string): ParsedTaggedLine | undefined {\n const match = TAGGED_LINE_PATTERN.exec(value);\n const lineText = match?.[2];\n const content = match?.[3];\n if (lineText === undefined || content === undefined) return undefined;\n\n const line = Number.parseInt(lineText, 10);\n if (!Number.isSafeInteger(line) || line < 1) return undefined;\n\n const marker = taggedLineMarker(match?.[1]);\n return marker === undefined ? { content, line } : { content, line, marker };\n}\n\nexport function parseLineAnchor(value: string): LineAnchor {\n if (value.includes('\\n') || value.includes('\\r')) {\n throw new Error(`Invalid line anchor: ${value}. Expected one anchor such as 5#abc, not a pasted multiline block.`);\n }\n\n const match = ANCHOR_PATTERN.exec(value);\n if (!match) {\n throw new Error(\n `Invalid line anchor: ${value}. Expected one anchor such as 5#abc from the latest read or grep result.`,\n );\n }\n\n const line = Number.parseInt(match[1] ?? '', 10);\n const hash = match[2]?.toLowerCase();\n if (!Number.isSafeInteger(line) || line < 1 || hash === undefined) {\n throw new Error(`Invalid line anchor: ${value}. Expected a positive line number and three letters, such as 5#abc.`);\n }\n return { line, hash };\n}\n\nexport function applyHashlineEdits(\n originalContent: string,\n requestedEdits: readonly HashlineRangeInput[],\n): AppliedHashlineEdits {\n const lines = splitLines(originalContent);\n const validated = requestedEdits.map((edit) => validateEdit(edit, lines));\n const edits = deduplicateEdits(validated).sort(compareEdits);\n validateNoOverlaps(edits);\n\n const result = [...lines];\n for (const edit of [...edits].reverse()) {\n const deleteCount = edit.to.line - edit.from.line + 1;\n const replacements = edit.content === null || edit.content === '' ? [] : splitReplacement(edit.content);\n result.splice(edit.from.line - 1, deleteCount, ...replacements);\n }\n return { content: result.join('\\n'), edits };\n}\n\nfunction taggedLineMarker(prefix: string | undefined): TaggedLineMarker | undefined {\n if (prefix === '>> ') return 'match';\n if (prefix === ' ') return 'context';\n return undefined;\n}\n\nfunction assertLineNumber(line: number): void {\n if (!Number.isSafeInteger(line) || line < 1) {\n throw new Error(`Invalid tagged line number: ${String(line)}. Expected a positive safe integer.`);\n }\n}\n\nfunction validateEdit(edit: HashlineRangeInput, lines: readonly string[]): PreparedHashlineEdit {\n const from = parseLineAnchor(edit.from);\n const to = parseLineAnchor(edit.to);\n if (from.line > to.line) {\n throw new Error(`Invalid edit range ${edit.from} to ${edit.to}: the starting line follows the ending line.`);\n }\n if (to.line > lines.length) {\n throw new Error(`Invalid edit range ${edit.from} to ${edit.to}: the file has ${lines.length} lines.`);\n }\n\n validateAnchor(from, lines);\n validateAnchor(to, lines);\n return { from, to, content: edit.content ?? null, source: edit };\n}\n\nfunction validateAnchor(anchor: LineAnchor, lines: readonly string[]): void {\n const line = lines[anchor.line - 1];\n if (line === undefined) throw new Error(`Line ${anchor.line} is outside the current file.`);\n const currentHash = hashLine(line);\n if (currentHash !== anchor.hash) {\n throw new Error(\n `Stale line anchor ${anchor.line}#${anchor.hash}. Current anchor is ${anchor.line}#${currentHash}. Re-read the file and retry.`,\n );\n }\n}\n\nfunction deduplicateEdits(edits: readonly PreparedHashlineEdit[]): PreparedHashlineEdit[] {\n const unique = new Map<string, PreparedHashlineEdit>();\n for (const edit of edits) {\n const key = JSON.stringify([edit.from.line, edit.from.hash, edit.to.line, edit.to.hash, edit.content]);\n if (!unique.has(key)) unique.set(key, edit);\n }\n return [...unique.values()];\n}\n\nfunction compareEdits(left: PreparedHashlineEdit, right: PreparedHashlineEdit): number {\n return left.from.line - right.from.line || left.to.line - right.to.line;\n}\n\nfunction validateNoOverlaps(edits: readonly PreparedHashlineEdit[]): void {\n for (let index = 1; index < edits.length; index += 1) {\n const previous = edits[index - 1];\n const current = edits[index];\n if (previous !== undefined && current !== undefined && current.from.line <= previous.to.line) {\n throw new Error(\n `Overlapping edit ranges ${previous.from.line}-${previous.to.line} and ${current.from.line}-${current.to.line}. Merge them and retry.`,\n );\n }\n }\n}\n\nfunction splitReplacement(content: string): string[] {\n const normalized = normalizeToLf(content);\n const trimmed = normalized.endsWith('\\n') ? normalized.slice(0, -1) : normalized;\n return trimmed === '' ? [] : trimmed.split('\\n');\n}\n"],"mappings":"AAWA,MAEMA,EAAe,IAAM,IAAM,IAE3BC,EAAmB,sBACnBC,EAAsB,mCACtBC,EAAsB,qCACtBC,EAAiB,6DACjBC,EAAmB,kBAMzB,SAAgBC,EAAS,EAAsB,CAC7C,IAAMC,EAAQ,IAAI,YAAY,CAAC,CAAC,OAAOC,EAAK,QAAQH,EAAkB,EAAE,CAAC,EACrEI,EAAO,sBACX,IAAK,IAAMC,KAAQH,EACjB,GAAQ,OAAOG,CAAI,EACnB,EAAO,OAAO,QAAQ,GAAID,EAAO,cAAS,EAG5C,IAAIE,EAAQF,EAAOT,EACbY,EAAU,MAAM,KAAK,CAAE,OAAQ,CAAE,MAAS,EAAE,EAClD,IAAK,IAAIC,EAAQD,EAAQ,OAA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"}
1
+ {"version":3,"file":"index.cjs","names":["ANCHOR_SPACE","FILE_TAG_PATTERN","FILE_HEADER_PATTERN","TAGGED_LINE_PATTERN","ANCHOR_PATTERN","ASCII_WHITESPACE","hashLine","bytes","line","hash","byte","value","letters","index","normalizeToLf","text","stripBom","splitLines","normalizeFileTag","trimmed","hashIndex","tag","formatFileHeader","path","parseFileHeader","match","formatTaggedLine","assertLineNumber","lineNumber","prefix","anchorSource","formatTaggedLines","lines","firstLine","parseTaggedLine","lineText","content","marker","taggedLineMarker","parseLineAnchor","applyHashlineEdits","originalContent","edits","deduplicateEdits","requestedEdits","validateEdit","edit","compareEdits","validateNoOverlaps","result","deleteCount","replacements","splitReplacement","from","to","validateAnchor","anchor","currentHash","unique","key","left","right","previous","current","normalized"],"sources":["../../../src/services/hashline/index.ts"],"sourcesContent":["import type {\n AppliedHashlineEdits,\n FileHeader,\n HashlineRangeInput,\n LineAnchor,\n ParsedTaggedLine,\n PreparedHashlineEdit,\n TaggedLineMarker,\n TaggedLinePrefix,\n} from '../../types/hashline';\n\nconst FNV_OFFSET_BASIS = 0xcbf29ce484222325n;\nconst FNV_PRIME = 0x100000001b3n;\nconst ANCHOR_SPACE = 26n * 26n * 26n;\nconst ASCII_A = 97;\nconst FILE_TAG_PATTERN = /^[A-Za-z0-9_-]{8}$/u;\nconst FILE_HEADER_PATTERN = /^@file (.+)#([A-Za-z0-9_-]{8})$/u;\nconst TAGGED_LINE_PATTERN = /^(>> | {3})?(\\d+)#[a-z]{3}\\|(.*)$/u;\nconst ANCHOR_PATTERN = /^\\s*[>+-]*\\s*(\\d+)\\s*[:#]\\s*([a-zA-Z]{3})(?:\\s*\\|.*)?\\s*$/u;\nconst ASCII_WHITESPACE = /[ \\t\\n\\r\\v\\f]/gu;\n\n/**\n * Return Phi's three-letter whitespace-insensitive FNV-1a64 line anchor.\n * Adapted from pulseaiclub/phi writetool under the MIT license.\n */\nexport function hashLine(line: string): string {\n const bytes = new TextEncoder().encode(line.replace(ASCII_WHITESPACE, ''));\n let hash = FNV_OFFSET_BASIS;\n for (const byte of bytes) {\n hash ^= BigInt(byte);\n hash = BigInt.asUintN(64, hash * FNV_PRIME);\n }\n\n let value = hash % ANCHOR_SPACE;\n const letters = Array.from({ length: 3 }, () => '');\n for (let index = letters.length - 1; index >= 0; index -= 1) {\n letters[index] = String.fromCharCode(ASCII_A + Number(value % 26n));\n value /= 26n;\n }\n return letters.join('');\n}\n\nexport function normalizeToLf(text: string): string {\n return text.replace(/\\r\\n/gu, '\\n').replace(/\\r/gu, '\\n');\n}\n\nexport function stripBom(text: string): string {\n return text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;\n}\n\nexport function splitLines(text: string): string[] {\n return normalizeToLf(stripBom(text)).split('\\n');\n}\n\nexport function normalizeFileTag(value: string): string {\n const trimmed = value.trim();\n const hashIndex = trimmed.lastIndexOf('#');\n const tag = hashIndex === -1 ? trimmed : trimmed.slice(hashIndex + 1);\n if (!FILE_TAG_PATTERN.test(tag)) {\n throw new Error(`Invalid file hash: ${value}. Expected the eight-character tag from @file path#HASH.`);\n }\n return tag;\n}\n\nexport function formatFileHeader(path: string, tag: string): string {\n if (path.length === 0 || path.includes('\\n') || path.includes('\\r')) {\n throw new Error('Invalid file header path. Expected one non-empty path without line breaks.');\n }\n return `@file ${path}#${normalizeFileTag(tag)}`;\n}\n\nexport function parseFileHeader(value: string): FileHeader | undefined {\n const match = FILE_HEADER_PATTERN.exec(value);\n const path = match?.[1];\n const tag = match?.[2];\n return path === undefined || tag === undefined ? undefined : { path, tag };\n}\n\nexport function formatTaggedLine(\n line: string,\n lineNumber: number,\n prefix: TaggedLinePrefix = '',\n anchorSource = line,\n): string {\n assertLineNumber(lineNumber);\n return `${prefix}${lineNumber}#${hashLine(anchorSource)}|${line}`;\n}\n\nexport function formatTaggedLines(lines: readonly string[], firstLine = 1): string {\n return lines.map((line, index) => formatTaggedLine(line, firstLine + index)).join('\\n');\n}\n\nexport function parseTaggedLine(value: string): ParsedTaggedLine | undefined {\n const match = TAGGED_LINE_PATTERN.exec(value);\n const lineText = match?.[2];\n const content = match?.[3];\n if (lineText === undefined || content === undefined) return undefined;\n\n const line = Number.parseInt(lineText, 10);\n if (!Number.isSafeInteger(line) || line < 1) return undefined;\n\n const marker = taggedLineMarker(match?.[1]);\n return marker === undefined ? { content, line } : { content, line, marker };\n}\n\nexport function parseLineAnchor(value: string): LineAnchor {\n if (value.includes('\\n') || value.includes('\\r')) {\n throw new Error(`Invalid line anchor: ${value}. Expected one anchor such as 5#abc, not a pasted multiline block.`);\n }\n\n const match = ANCHOR_PATTERN.exec(value);\n if (!match) {\n throw new Error(\n `Invalid line anchor: ${value}. Expected one anchor such as 5#abc from the latest read or grep result.`,\n );\n }\n\n const line = Number.parseInt(match[1] ?? '', 10);\n const hash = match[2]?.toLowerCase();\n if (!Number.isSafeInteger(line) || line < 1 || hash === undefined) {\n throw new Error(`Invalid line anchor: ${value}. Expected a positive line number and three letters, such as 5#abc.`);\n }\n return { line, hash };\n}\n\nexport function applyHashlineEdits(\n originalContent: string,\n requestedEdits: readonly HashlineRangeInput[],\n): AppliedHashlineEdits {\n const lines = splitLines(originalContent);\n const validated = requestedEdits.map((edit) => validateEdit(edit, lines));\n const edits = deduplicateEdits(validated).sort(compareEdits);\n validateNoOverlaps(edits);\n\n const result = [...lines];\n for (const edit of [...edits].reverse()) {\n const deleteCount = edit.to.line - edit.from.line + 1;\n const replacements = edit.content === null || edit.content === '' ? [] : splitReplacement(edit.content);\n result.splice(edit.from.line - 1, deleteCount, ...replacements);\n }\n return { content: result.join('\\n'), edits };\n}\n\nfunction taggedLineMarker(prefix: string | undefined): TaggedLineMarker | undefined {\n if (prefix === '>> ') return 'match';\n if (prefix === ' ') return 'context';\n return undefined;\n}\n\nfunction assertLineNumber(line: number): void {\n if (!Number.isSafeInteger(line) || line < 1) {\n throw new Error(`Invalid tagged line number: ${String(line)}. Expected a positive safe integer.`);\n }\n}\n\nfunction validateEdit(edit: HashlineRangeInput, lines: readonly string[]): PreparedHashlineEdit {\n const from = parseLineAnchor(edit.from);\n const to = parseLineAnchor(edit.to);\n if (from.line > to.line) {\n throw new Error(`Invalid edit range ${edit.from} to ${edit.to}: the starting line follows the ending line.`);\n }\n if (to.line > lines.length) {\n throw new Error(`Invalid edit range ${edit.from} to ${edit.to}: the file has ${lines.length} lines.`);\n }\n\n validateAnchor(from, lines);\n validateAnchor(to, lines);\n return { from, to, content: edit.content ?? null, source: edit };\n}\n\nfunction validateAnchor(anchor: LineAnchor, lines: readonly string[]): void {\n const line = lines[anchor.line - 1];\n if (line === undefined) throw new Error(`Line ${anchor.line} is outside the current file.`);\n const currentHash = hashLine(line);\n if (currentHash !== anchor.hash) {\n throw new Error(\n `Stale line anchor ${anchor.line}#${anchor.hash}. Current anchor is ${anchor.line}#${currentHash}. Re-read the file and retry.`,\n );\n }\n}\n\nfunction deduplicateEdits(edits: readonly PreparedHashlineEdit[]): PreparedHashlineEdit[] {\n const unique = new Map<string, PreparedHashlineEdit>();\n for (const edit of edits) {\n const key = JSON.stringify([edit.from.line, edit.from.hash, edit.to.line, edit.to.hash, edit.content]);\n if (!unique.has(key)) unique.set(key, edit);\n }\n return [...unique.values()];\n}\n\nfunction compareEdits(left: PreparedHashlineEdit, right: PreparedHashlineEdit): number {\n return left.from.line - right.from.line || left.to.line - right.to.line;\n}\n\nfunction validateNoOverlaps(edits: readonly PreparedHashlineEdit[]): void {\n for (let index = 1; index < edits.length; index += 1) {\n const previous = edits[index - 1];\n const current = edits[index];\n if (previous !== undefined && current !== undefined && current.from.line <= previous.to.line) {\n throw new Error(\n `Overlapping edit ranges ${previous.from.line}-${previous.to.line} and ${current.from.line}-${current.to.line}. Merge them and retry.`,\n );\n }\n }\n}\n\nfunction splitReplacement(content: string): string[] {\n const normalized = normalizeToLf(content);\n const trimmed = normalized.endsWith('\\n') ? normalized.slice(0, -1) : normalized;\n return trimmed === '' ? [] : trimmed.split('\\n');\n}\n"],"mappings":"AAWA,MAEMA,EAAe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rB,EAAM7B,GACtB,GAAIiD,IAAa,IAAA,IAAaC,IAAY,IAAA,IAAaA,EAAQ,KAAK,MAAQD,EAAS,GAAG,KACtF,MAAU,MACR,2BAA2BA,EAAS,KAAK,KAAK,GAAGA,EAAS,GAAG,KAAK,OAAOC,EAAQ,KAAK,KAAK,GAAGA,EAAQ,GAAG,KAAK,wBAChH,CAEJ,CACF,CAEA,SAASX,EAAiB,EAA2B,CACnD,IAAMY,EAAalD,EAAcsB,CAAO,EAClCjB,EAAU6C,EAAW,SAAS;CAAI,EAAIA,EAAW,MAAM,EAAG,EAAE,EAAIA,EACtE,OAAO7C,IAAY,GAAK,CAAC,EAAIA,EAAQ,MAAM;CAAI,CACjD,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["ANCHOR_SPACE","FILE_TAG_PATTERN","FILE_HEADER_PATTERN","TAGGED_LINE_PATTERN","ANCHOR_PATTERN","ASCII_WHITESPACE","hashLine","bytes","line","hash","byte","value","letters","index","normalizeToLf","text","stripBom","splitLines","normalizeFileTag","trimmed","hashIndex","tag","formatFileHeader","path","parseFileHeader","match","formatTaggedLine","assertLineNumber","lineNumber","prefix","anchorSource","formatTaggedLines","lines","firstLine","parseTaggedLine","lineText","content","marker","taggedLineMarker","parseLineAnchor","applyHashlineEdits","originalContent","edits","deduplicateEdits","requestedEdits","validateEdit","edit","compareEdits","validateNoOverlaps","result","deleteCount","replacements","splitReplacement","from","to","validateAnchor","anchor","currentHash","unique","key","left","right","previous","current","normalized"],"sources":["../../../src/services/hashline/index.ts"],"sourcesContent":["import type {\n AppliedHashlineEdits,\n FileHeader,\n HashlineRangeInput,\n LineAnchor,\n ParsedTaggedLine,\n PreparedHashlineEdit,\n TaggedLineMarker,\n TaggedLinePrefix,\n} from '../../types/hashline';\n\nconst FNV_OFFSET_BASIS = 0xcbf29ce484222325n;\nconst FNV_PRIME = 0x100000001b3n;\nconst ANCHOR_SPACE = 26n * 26n * 26n;\nconst ASCII_A = 97;\nconst FILE_TAG_PATTERN = /^[A-Za-z0-9_-]{8}$/u;\nconst FILE_HEADER_PATTERN = /^@file (.+)#([A-Za-z0-9_-]{8})$/u;\nconst TAGGED_LINE_PATTERN = /^(>> | {3})?(\\d+)#[a-z]{3}\\|(.*)$/u;\nconst ANCHOR_PATTERN = /^\\s*[>+-]*\\s*(\\d+)\\s*[:#]\\s*([a-zA-Z]{3})(?:\\s*\\|.*)?\\s*$/u;\nconst ASCII_WHITESPACE = /[ \\t\\n\\r\\v\\f]/gu;\n\n/**\n * Return Phi's three-letter whitespace-insensitive FNV-1a64 line anchor.\n * Adapted from pulseaiclub/phi writetool under the MIT license.\n */\nexport function hashLine(line: string): string {\n const bytes = new TextEncoder().encode(line.replace(ASCII_WHITESPACE, ''));\n let hash = FNV_OFFSET_BASIS;\n for (const byte of bytes) {\n hash ^= BigInt(byte);\n hash = BigInt.asUintN(64, hash * FNV_PRIME);\n }\n\n let value = hash % ANCHOR_SPACE;\n const letters = Array.from({ length: 3 }, () => '');\n for (let index = letters.length - 1; index >= 0; index -= 1) {\n letters[index] = String.fromCharCode(ASCII_A + Number(value % 26n));\n value /= 26n;\n }\n return letters.join('');\n}\n\nexport function normalizeToLf(text: string): string {\n return text.replace(/\\r\\n/gu, '\\n').replace(/\\r/gu, '\\n');\n}\n\nexport function stripBom(text: string): string {\n return text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;\n}\n\nexport function splitLines(text: string): string[] {\n return normalizeToLf(stripBom(text)).split('\\n');\n}\n\nexport function normalizeFileTag(value: string): string {\n const trimmed = value.trim();\n const hashIndex = trimmed.lastIndexOf('#');\n const tag = hashIndex === -1 ? trimmed : trimmed.slice(hashIndex + 1);\n if (!FILE_TAG_PATTERN.test(tag)) {\n throw new Error(`Invalid file hash: ${value}. Expected the eight-character tag from @file path#HASH.`);\n }\n return tag;\n}\n\nexport function formatFileHeader(path: string, tag: string): string {\n if (path.length === 0 || path.includes('\\n') || path.includes('\\r')) {\n throw new Error('Invalid file header path. Expected one non-empty path without line breaks.');\n }\n return `@file ${path}#${normalizeFileTag(tag)}`;\n}\n\nexport function parseFileHeader(value: string): FileHeader | undefined {\n const match = FILE_HEADER_PATTERN.exec(value);\n const path = match?.[1];\n const tag = match?.[2];\n return path === undefined || tag === undefined ? undefined : { path, tag };\n}\n\nexport function formatTaggedLine(\n line: string,\n lineNumber: number,\n prefix: TaggedLinePrefix = '',\n anchorSource = line,\n): string {\n assertLineNumber(lineNumber);\n return `${prefix}${lineNumber}#${hashLine(anchorSource)}|${line}`;\n}\n\nexport function formatTaggedLines(lines: readonly string[], firstLine = 1): string {\n return lines.map((line, index) => formatTaggedLine(line, firstLine + index)).join('\\n');\n}\n\nexport function parseTaggedLine(value: string): ParsedTaggedLine | undefined {\n const match = TAGGED_LINE_PATTERN.exec(value);\n const lineText = match?.[2];\n const content = match?.[3];\n if (lineText === undefined || content === undefined) return undefined;\n\n const line = Number.parseInt(lineText, 10);\n if (!Number.isSafeInteger(line) || line < 1) return undefined;\n\n const marker = taggedLineMarker(match?.[1]);\n return marker === undefined ? { content, line } : { content, line, marker };\n}\n\nexport function parseLineAnchor(value: string): LineAnchor {\n if (value.includes('\\n') || value.includes('\\r')) {\n throw new Error(`Invalid line anchor: ${value}. Expected one anchor such as 5#abc, not a pasted multiline block.`);\n }\n\n const match = ANCHOR_PATTERN.exec(value);\n if (!match) {\n throw new Error(\n `Invalid line anchor: ${value}. Expected one anchor such as 5#abc from the latest read or grep result.`,\n );\n }\n\n const line = Number.parseInt(match[1] ?? '', 10);\n const hash = match[2]?.toLowerCase();\n if (!Number.isSafeInteger(line) || line < 1 || hash === undefined) {\n throw new Error(`Invalid line anchor: ${value}. Expected a positive line number and three letters, such as 5#abc.`);\n }\n return { line, hash };\n}\n\nexport function applyHashlineEdits(\n originalContent: string,\n requestedEdits: readonly HashlineRangeInput[],\n): AppliedHashlineEdits {\n const lines = splitLines(originalContent);\n const validated = requestedEdits.map((edit) => validateEdit(edit, lines));\n const edits = deduplicateEdits(validated).sort(compareEdits);\n validateNoOverlaps(edits);\n\n const result = [...lines];\n for (const edit of [...edits].reverse()) {\n const deleteCount = edit.to.line - edit.from.line + 1;\n const replacements = edit.content === null || edit.content === '' ? [] : splitReplacement(edit.content);\n result.splice(edit.from.line - 1, deleteCount, ...replacements);\n }\n return { content: result.join('\\n'), edits };\n}\n\nfunction taggedLineMarker(prefix: string | undefined): TaggedLineMarker | undefined {\n if (prefix === '>> ') return 'match';\n if (prefix === ' ') return 'context';\n return undefined;\n}\n\nfunction assertLineNumber(line: number): void {\n if (!Number.isSafeInteger(line) || line < 1) {\n throw new Error(`Invalid tagged line number: ${String(line)}. Expected a positive safe integer.`);\n }\n}\n\nfunction validateEdit(edit: HashlineRangeInput, lines: readonly string[]): PreparedHashlineEdit {\n const from = parseLineAnchor(edit.from);\n const to = parseLineAnchor(edit.to);\n if (from.line > to.line) {\n throw new Error(`Invalid edit range ${edit.from} to ${edit.to}: the starting line follows the ending line.`);\n }\n if (to.line > lines.length) {\n throw new Error(`Invalid edit range ${edit.from} to ${edit.to}: the file has ${lines.length} lines.`);\n }\n\n validateAnchor(from, lines);\n validateAnchor(to, lines);\n return { from, to, content: edit.content ?? null, source: edit };\n}\n\nfunction validateAnchor(anchor: LineAnchor, lines: readonly string[]): void {\n const line = lines[anchor.line - 1];\n if (line === undefined) throw new Error(`Line ${anchor.line} is outside the current file.`);\n const currentHash = hashLine(line);\n if (currentHash !== anchor.hash) {\n throw new Error(\n `Stale line anchor ${anchor.line}#${anchor.hash}. Current anchor is ${anchor.line}#${currentHash}. Re-read the file and retry.`,\n );\n }\n}\n\nfunction deduplicateEdits(edits: readonly PreparedHashlineEdit[]): PreparedHashlineEdit[] {\n const unique = new Map<string, PreparedHashlineEdit>();\n for (const edit of edits) {\n const key = JSON.stringify([edit.from.line, edit.from.hash, edit.to.line, edit.to.hash, edit.content]);\n if (!unique.has(key)) unique.set(key, edit);\n }\n return [...unique.values()];\n}\n\nfunction compareEdits(left: PreparedHashlineEdit, right: PreparedHashlineEdit): number {\n return left.from.line - right.from.line || left.to.line - right.to.line;\n}\n\nfunction validateNoOverlaps(edits: readonly PreparedHashlineEdit[]): void {\n for (let index = 1; index < edits.length; index += 1) {\n const previous = edits[index - 1];\n const current = edits[index];\n if (previous !== undefined && current !== undefined && current.from.line <= previous.to.line) {\n throw new Error(\n `Overlapping edit ranges ${previous.from.line}-${previous.to.line} and ${current.from.line}-${current.to.line}. Merge them and retry.`,\n );\n }\n }\n}\n\nfunction splitReplacement(content: string): string[] {\n const normalized = normalizeToLf(content);\n const trimmed = normalized.endsWith('\\n') ? normalized.slice(0, -1) : normalized;\n return trimmed === '' ? [] : trimmed.split('\\n');\n}\n"],"mappings":"AAWA,MAEMA,EAAe,IAAM,IAAM,IAE3BC,EAAmB,sBACnBC,EAAsB,mCACtBC,EAAsB,qCACtBC,EAAiB,6DACjBC,EAAmB,kBAMzB,SAAgBC,EAAS,EAAsB,CAC7C,IAAMC,EAAQ,IAAI,YAAY,CAAC,CAAC,OAAOC,EAAK,QAAQH,EAAkB,EAAE,CAAC,EACrEI,EAAO,sBACX,IAAK,IAAMC,KAAQH,EACjB,GAAQ,OAAOG,CAAI,EACnB,EAAO,OAAO,QAAQ,GAAID,EAAO,cAAS,EAG5C,IAAIE,EAAQF,EAAOT,EACbY,EAAU,MAAM,KAAK,CAAE,OAAQ,CAAE,MAAS,EAAE,EAClD,IAAK,IAAIC,EAAQD,EAAQ,OAAS,EAAGC,GAAS,EAAG,IAC/C,EAAQA,GAAS,OAAO,aAAa,GAAU,OAAOF,EAAQ,GAAG,CAAC,EAClE,GAAS,IAEX,OAAOC,EAAQ,KAAK,EAAE,CACxB,CAEA,SAAgBE,EAAc,EAAsB,CAClD,OAAOC,EAAK,QAAQ,SAAU;CAAI,CAAC,CAAC,QAAQ,OAAQ;CAAI,CAC1D,CAEA,SAAgBC,EAAS,EAAsB,CAC7C,OAAOD,EAAK,WAAW,CAAC,IAAM,MAASA,EAAK,MAAM,CAAC,EAAIA,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AAK,KAAMA,EAAK,GAAG,KAAMA,EAAK,GAAG,KAAMA,EAAK,OAAO,CAAC,EAChGY,EAAO,IAAIC,CAAG,GAAGD,EAAO,IAAIC,EAAKb,CAAI,CAC5C,CACA,MAAO,CAAC,GAAGY,EAAO,OAAO,CAAC,CAC5B,CAEA,SAASX,EAAa,EAA4B,EAAqC,CACrF,OAAOa,EAAK,KAAK,KAAOC,EAAM,KAAK,MAAQD,EAAK,GAAG,KAAOC,EAAM,GAAG,IACrE,CAEA,SAASb,EAAmB,EAA8C,CACxE,IAAK,IAAInC,EAAQ,EAAGA,EAAQ6B,EAAM,OAAQ,GAAS,EAAG,CACpD,IAAMoB,EAAWpB,EAAM7B,EAAQ,GACzBkD,EAAUrB,EAAM7B,GACtB,GAAIiD,IAAa,IAAA,IAAaC,IAAY,IAAA,IAAaA,EAAQ,KAAK,MAAQD,EAAS,GAAG,KACtF,MAAU,MACR,2BAA2BA,EAAS,KAAK,KAAK,GAAGA,EAAS,GAAG,KAAK,OAAOC,EAAQ,KAAK,KAAK,GAAGA,EAAQ,GAAG,KAAK,wBAChH,CAEJ,CACF,CAEA,SAASX,EAAiB,EAA2B,CACnD,IAAMY,EAAalD,EAAcsB,CAAO,EAClCjB,EAAU6C,EAAW,SAAS;CAAI,EAAIA,EAAW,MAAM,EAAG,EAAE,EAAIA,EACtE,OAAO7C,IAAY,GAAK,CAAC,EAAIA,EAAQ,MAAM;CAAI,CACjD"}
1
+ {"version":3,"file":"index.mjs","names":["ANCHOR_SPACE","FILE_TAG_PATTERN","FILE_HEADER_PATTERN","TAGGED_LINE_PATTERN","ANCHOR_PATTERN","ASCII_WHITESPACE","hashLine","bytes","line","hash","byte","value","letters","index","normalizeToLf","text","stripBom","splitLines","normalizeFileTag","trimmed","hashIndex","tag","formatFileHeader","path","parseFileHeader","match","formatTaggedLine","assertLineNumber","lineNumber","prefix","anchorSource","formatTaggedLines","lines","firstLine","parseTaggedLine","lineText","content","marker","taggedLineMarker","parseLineAnchor","applyHashlineEdits","originalContent","edits","deduplicateEdits","requestedEdits","validateEdit","edit","compareEdits","validateNoOverlaps","result","deleteCount","replacements","splitReplacement","from","to","validateAnchor","anchor","currentHash","unique","key","left","right","previous","current","normalized"],"sources":["../../../src/services/hashline/index.ts"],"sourcesContent":["import type {\n AppliedHashlineEdits,\n FileHeader,\n HashlineRangeInput,\n LineAnchor,\n ParsedTaggedLine,\n PreparedHashlineEdit,\n TaggedLineMarker,\n TaggedLinePrefix,\n} from '../../types/hashline';\n\nconst FNV_OFFSET_BASIS = 0xcbf29ce484222325n;\nconst FNV_PRIME = 0x100000001b3n;\nconst ANCHOR_SPACE = 26n * 26n * 26n;\nconst ASCII_A = 97;\nconst FILE_TAG_PATTERN = /^[A-Za-z0-9_-]{8}$/u;\nconst FILE_HEADER_PATTERN = /^@file (.+)#([A-Za-z0-9_-]{8})$/u;\nconst TAGGED_LINE_PATTERN = /^(>> | {3})?(\\d+)#[a-z]{3}\\|(.*)$/u;\nconst ANCHOR_PATTERN = /^\\s*[>+-]*\\s*(\\d+)\\s*[:#]\\s*([a-zA-Z]{3})(?:\\s*\\|.*)?\\s*$/u;\nconst ASCII_WHITESPACE = /[ \\t\\n\\r\\v\\f]/gu;\n\n/**\n * Return Phi's three-letter whitespace-insensitive FNV-1a64 line anchor.\n * Adapted from pulseaiclub/phi writetool under the MIT license.\n */\nexport function hashLine(line: string): string {\n const bytes = new TextEncoder().encode(line.replace(ASCII_WHITESPACE, ''));\n let hash = FNV_OFFSET_BASIS;\n for (const byte of bytes) {\n hash ^= BigInt(byte);\n hash = BigInt.asUintN(64, hash * FNV_PRIME);\n }\n\n let value = hash % ANCHOR_SPACE;\n const letters = Array.from({ length: 3 }, () => '');\n for (let index = letters.length - 1; index >= 0; index -= 1) {\n letters[index] = String.fromCharCode(ASCII_A + Number(value % 26n));\n value /= 26n;\n }\n return letters.join('');\n}\n\nexport function normalizeToLf(text: string): string {\n return text.replace(/\\r\\n/gu, '\\n').replace(/\\r/gu, '\\n');\n}\n\nexport function stripBom(text: string): string {\n return text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;\n}\n\nexport function splitLines(text: string): string[] {\n return normalizeToLf(stripBom(text)).split('\\n');\n}\n\nexport function normalizeFileTag(value: string): string {\n const trimmed = value.trim();\n const hashIndex = trimmed.lastIndexOf('#');\n const tag = hashIndex === -1 ? trimmed : trimmed.slice(hashIndex + 1);\n if (!FILE_TAG_PATTERN.test(tag)) {\n throw new Error(`Invalid file hash: ${value}. Expected the eight-character tag from @file path#HASH.`);\n }\n return tag;\n}\n\nexport function formatFileHeader(path: string, tag: string): string {\n if (path.length === 0 || path.includes('\\n') || path.includes('\\r')) {\n throw new Error('Invalid file header path. Expected one non-empty path without line breaks.');\n }\n return `@file ${path}#${normalizeFileTag(tag)}`;\n}\n\nexport function parseFileHeader(value: string): FileHeader | undefined {\n const match = FILE_HEADER_PATTERN.exec(value);\n const path = match?.[1];\n const tag = match?.[2];\n return path === undefined || tag === undefined ? undefined : { path, tag };\n}\n\nexport function formatTaggedLine(\n line: string,\n lineNumber: number,\n prefix: TaggedLinePrefix = '',\n anchorSource = line,\n): string {\n assertLineNumber(lineNumber);\n return `${prefix}${lineNumber}#${hashLine(anchorSource)}|${line}`;\n}\n\nexport function formatTaggedLines(lines: readonly string[], firstLine = 1): string {\n return lines.map((line, index) => formatTaggedLine(line, firstLine + index)).join('\\n');\n}\n\nexport function parseTaggedLine(value: string): ParsedTaggedLine | undefined {\n const match = TAGGED_LINE_PATTERN.exec(value);\n const lineText = match?.[2];\n const content = match?.[3];\n if (lineText === undefined || content === undefined) return undefined;\n\n const line = Number.parseInt(lineText, 10);\n if (!Number.isSafeInteger(line) || line < 1) return undefined;\n\n const marker = taggedLineMarker(match?.[1]);\n return marker === undefined ? { content, line } : { content, line, marker };\n}\n\nexport function parseLineAnchor(value: string): LineAnchor {\n if (value.includes('\\n') || value.includes('\\r')) {\n throw new Error(`Invalid line anchor: ${value}. Expected one anchor such as 5#abc, not a pasted multiline block.`);\n }\n\n const match = ANCHOR_PATTERN.exec(value);\n if (!match) {\n throw new Error(\n `Invalid line anchor: ${value}. Expected one anchor such as 5#abc from the latest read or grep result.`,\n );\n }\n\n const line = Number.parseInt(match[1] ?? '', 10);\n const hash = match[2]?.toLowerCase();\n if (!Number.isSafeInteger(line) || line < 1 || hash === undefined) {\n throw new Error(`Invalid line anchor: ${value}. Expected a positive line number and three letters, such as 5#abc.`);\n }\n return { line, hash };\n}\n\nexport function applyHashlineEdits(\n originalContent: string,\n requestedEdits: readonly HashlineRangeInput[],\n): AppliedHashlineEdits {\n const lines = splitLines(originalContent);\n const validated = requestedEdits.map((edit) => validateEdit(edit, lines));\n const edits = deduplicateEdits(validated).sort(compareEdits);\n validateNoOverlaps(edits);\n\n const result = [...lines];\n for (const edit of [...edits].reverse()) {\n const deleteCount = edit.to.line - edit.from.line + 1;\n const replacements = edit.content === null || edit.content === '' ? [] : splitReplacement(edit.content);\n result.splice(edit.from.line - 1, deleteCount, ...replacements);\n }\n return { content: result.join('\\n'), edits };\n}\n\nfunction taggedLineMarker(prefix: string | undefined): TaggedLineMarker | undefined {\n if (prefix === '>> ') return 'match';\n if (prefix === ' ') return 'context';\n return undefined;\n}\n\nfunction assertLineNumber(line: number): void {\n if (!Number.isSafeInteger(line) || line < 1) {\n throw new Error(`Invalid tagged line number: ${String(line)}. Expected a positive safe integer.`);\n }\n}\n\nfunction validateEdit(edit: HashlineRangeInput, lines: readonly string[]): PreparedHashlineEdit {\n const from = parseLineAnchor(edit.from);\n const to = parseLineAnchor(edit.to);\n if (from.line > to.line) {\n throw new Error(`Invalid edit range ${edit.from} to ${edit.to}: the starting line follows the ending line.`);\n }\n if (to.line > lines.length) {\n throw new Error(`Invalid edit range ${edit.from} to ${edit.to}: the file has ${lines.length} lines.`);\n }\n\n validateAnchor(from, lines);\n validateAnchor(to, lines);\n return { from, to, content: edit.content ?? null, source: edit };\n}\n\nfunction validateAnchor(anchor: LineAnchor, lines: readonly string[]): void {\n const line = lines[anchor.line - 1];\n if (line === undefined) throw new Error(`Line ${anchor.line} is outside the current file.`);\n const currentHash = hashLine(line);\n if (currentHash !== anchor.hash) {\n throw new Error(\n `Stale line anchor ${anchor.line}#${anchor.hash}. Current anchor is ${anchor.line}#${currentHash}. Re-read the file and retry.`,\n );\n }\n}\n\nfunction deduplicateEdits(edits: readonly PreparedHashlineEdit[]): PreparedHashlineEdit[] {\n const unique = new Map<string, PreparedHashlineEdit>();\n for (const edit of edits) {\n const key = JSON.stringify([edit.from.line, edit.from.hash, edit.to.line, edit.to.hash, edit.content]);\n if (!unique.has(key)) unique.set(key, edit);\n }\n return [...unique.values()];\n}\n\nfunction compareEdits(left: PreparedHashlineEdit, right: PreparedHashlineEdit): number {\n return left.from.line - right.from.line || left.to.line - right.to.line;\n}\n\nfunction validateNoOverlaps(edits: readonly PreparedHashlineEdit[]): void {\n for (let index = 1; index < edits.length; index += 1) {\n const previous = edits[index - 1];\n const current = edits[index];\n if (previous !== undefined && current !== undefined && current.from.line <= previous.to.line) {\n throw new Error(\n `Overlapping edit ranges ${previous.from.line}-${previous.to.line} and ${current.from.line}-${current.to.line}. Merge them and retry.`,\n );\n }\n }\n}\n\nfunction splitReplacement(content: string): string[] {\n const normalized = normalizeToLf(content);\n const trimmed = normalized.endsWith('\\n') ? normalized.slice(0, -1) : normalized;\n return trimmed === '' ? [] : trimmed.split('\\n');\n}\n"],"mappings":"AAWA,MAEMA,EAAe,IAAM,IAAM,IAE3BC,EAAmB,sBACnBC,EAAsB,mCACtBC,EAAsB,qCACtBC,EAAiB,6DACjBC,EAAmB,kBAMzB,SAAgBC,EAAS,EAAsB,CAC7C,IAAMC,EAAQ,IAAI,YAAY,CAAC,CAAC,OAAOC,EAAK,QAAQH,EAAkB,EAAE,CAAC,EACrEI,EAAO,sBACX,IAAK,IAAMC,KAAQH,EACjB,GAAQ,OAAOG,CAAI,EACnB,EAAO,OAAO,QAAQ,GAAID,EAAO,cAAS,EAG5C,IAAIE,EAAQF,EA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A,EAAW,MAAM,EAAG,EAAE,EAAIA,EACtE,OAAO7C,IAAY,GAAK,CAAC,EAAIA,EAAQ,MAAM;CAAI,CACjD,C"}
@@ -0,0 +1,5 @@
1
+ function e(e){if(e.length===0)return[];let t=e.split(`
2
+ `);return e.endsWith(`
3
+ `)&&t.pop(),t}function t(e){return e<1024?`${e}B`:e<1048576?`${(e/1024).toFixed(1)}KB`:`${(e/1048576).toFixed(1)}MB`}function n(e,t=500){return e.length<=t?{text:e,wasTruncated:!1}:{text:`${e.slice(0,t)}... [truncated]`,wasTruncated:!0}}function r(t,n={}){let r=n.maxLines??2e3,i=n.maxBytes??51200,a=Buffer.byteLength(t,`utf-8`),o=e(t),s=o.length;if(s<=r&&a<=i)return{content:t,truncated:!1,truncatedBy:null,totalLines:s,totalBytes:a,outputLines:s,outputBytes:a,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines:r,maxBytes:i};let c=o[0]??``;if(Buffer.byteLength(c,`utf-8`)>i)return{content:``,truncated:!0,truncatedBy:`bytes`,totalLines:s,totalBytes:a,outputLines:0,outputBytes:0,lastLinePartial:!1,firstLineExceedsLimit:!0,maxLines:r,maxBytes:i};let l=[],u=0,d=`lines`;for(let e=0;e<o.length&&e<r;e+=1){let t=o[e]??``,n=Buffer.byteLength(t,`utf-8`)+ +(e>0);if(u+n>i){d=`bytes`;break}l.push(t),u+=n}l.length>=r&&u<=i&&(d=`lines`);let f=l.join(`
4
+ `);return{content:f,truncated:!0,truncatedBy:d,totalLines:s,totalBytes:a,outputLines:l.length,outputBytes:Buffer.byteLength(f,`utf-8`),lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines:r,maxBytes:i}}exports.DEFAULT_MAX_BYTES=51200,exports.DEFAULT_MAX_LINES=2e3,exports.GREP_MAX_LINE_LENGTH=500,exports.formatSize=t,exports.truncateHead=r,exports.truncateLine=n;
5
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","names":["splitLinesForCounting","content","lines","formatSize","bytes","truncateLine","line","maxChars","truncateHead","maxLines","options","maxBytes","totalBytes","totalLines","firstLine","kept","keptBytes","truncatedBy","index","lineBytes","output"],"sources":["../../../src/services/truncate/index.ts"],"sourcesContent":["/**\n * Host-neutral output limits for tool results: the head truncation, line truncation and size\n * formatting Pi's coding tools use, for hosts that cannot load Pi (the Worker). Whichever of the\n * line and byte limits is hit first wins, and a line is never returned in part.\n */\nexport const DEFAULT_MAX_LINES = 2000;\nexport const DEFAULT_MAX_BYTES = 50 * 1024;\n/** Longest grep match line shown before it is cut. */\nexport const GREP_MAX_LINE_LENGTH = 500;\n\nexport interface TruncationOptions {\n /** Maximum number of lines (default 2000). */\n readonly maxLines?: number;\n /** Maximum number of UTF-8 bytes (default 50 KiB). */\n readonly maxBytes?: number;\n}\n\nexport interface TruncationResult {\n /** The kept content. */\n readonly content: string;\n readonly truncated: boolean;\n /** Which limit was hit, or null when nothing was cut. */\n readonly truncatedBy: 'lines' | 'bytes' | null;\n readonly totalLines: number;\n readonly totalBytes: number;\n /** Complete lines kept. */\n readonly outputLines: number;\n readonly outputBytes: number;\n /** Always false for head truncation; kept so the shape matches Pi's. */\n readonly lastLinePartial: boolean;\n /** The first line alone was over the byte limit, so nothing is kept. */\n readonly firstLineExceedsLimit: boolean;\n readonly maxLines: number;\n readonly maxBytes: number;\n}\n\n/** A trailing newline ends the last line rather than starting another. */\nfunction splitLinesForCounting(content: string): string[] {\n if (content.length === 0) return [];\n const lines = content.split('\\n');\n if (content.endsWith('\\n')) lines.pop();\n return lines;\n}\n\nexport function formatSize(bytes: number): string {\n if (bytes < 1024) return `${bytes}B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)}KB`;\n return `${(bytes / (1024 * 1024)).toFixed(1)}MB`;\n}\n\n/** Cut one line to `maxChars` characters and mark it. */\nexport function truncateLine(\n line: string,\n maxChars: number = GREP_MAX_LINE_LENGTH,\n): { readonly text: string; readonly wasTruncated: boolean } {\n if (line.length <= maxChars) return { text: line, wasTruncated: false };\n return { text: `${line.slice(0, maxChars)}... [truncated]`, wasTruncated: true };\n}\n\n/** Keep the first lines of `content` that fit both limits. */\nexport function truncateHead(content: string, options: TruncationOptions = {}): TruncationResult {\n const maxLines = options.maxLines ?? DEFAULT_MAX_LINES;\n const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;\n const totalBytes = Buffer.byteLength(content, 'utf-8');\n const lines = splitLinesForCounting(content);\n const totalLines = lines.length;\n\n if (totalLines <= maxLines && totalBytes <= maxBytes) {\n return {\n content,\n truncated: false,\n truncatedBy: null,\n totalLines,\n totalBytes,\n outputLines: totalLines,\n outputBytes: totalBytes,\n lastLinePartial: false,\n firstLineExceedsLimit: false,\n maxLines,\n maxBytes,\n };\n }\n\n const firstLine = lines[0] ?? '';\n if (Buffer.byteLength(firstLine, 'utf-8') > maxBytes) {\n return {\n content: '',\n truncated: true,\n truncatedBy: 'bytes',\n totalLines,\n totalBytes,\n outputLines: 0,\n outputBytes: 0,\n lastLinePartial: false,\n firstLineExceedsLimit: true,\n maxLines,\n maxBytes,\n };\n }\n\n const kept: string[] = [];\n let keptBytes = 0;\n let truncatedBy: 'lines' | 'bytes' = 'lines';\n for (let index = 0; index < lines.length && index < maxLines; index += 1) {\n const line = lines[index] ?? '';\n // Every line after the first carries the newline that joins it to the previous one.\n const lineBytes = Buffer.byteLength(line, 'utf-8') + (index > 0 ? 1 : 0);\n if (keptBytes + lineBytes > maxBytes) {\n truncatedBy = 'bytes';\n break;\n }\n kept.push(line);\n keptBytes += lineBytes;\n }\n if (kept.length >= maxLines && keptBytes <= maxBytes) truncatedBy = 'lines';\n\n const output = kept.join('\\n');\n return {\n content: output,\n truncated: true,\n truncatedBy,\n totalLines,\n totalBytes,\n outputLines: kept.length,\n outputBytes: Buffer.byteLength(output, 'utf-8'),\n lastLinePartial: false,\n firstLineExceedsLimit: false,\n maxLines,\n maxBytes,\n };\n}\n"],"mappings":"AAqCA,SAASA,EAAsB,EAA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MH,EAAOJ,EAAMgB,IAAU,GAEvBC,EAAY,OAAO,WAAWb,EAAM,OAAO,GAAK,IAAQ,GAC9D,GAAIU,EAAYG,EAAYR,EAAU,CACpC,EAAc,QACd,KACF,CACAI,EAAK,KAAKT,CAAI,EACd,GAAaa,CACf,CACIJ,EAAK,QAAUN,GAAYO,GAAaL,IAAU,EAAc,SAEpE,IAAMS,EAASL,EAAK,KAAK;CAAI,EAC7B,MAAO,CACL,QAASK,EACT,UAAW,GACX,cACA,aACA,aACA,YAAaL,EAAK,OAClB,YAAa,OAAO,WAAWK,EAAQ,OAAO,EAC9C,gBAAiB,GACjB,sBAAuB,GACvB,WACA,UACF,CACF,C"}
@@ -0,0 +1,44 @@
1
+ //#region src/services/truncate/index.d.ts
2
+ /**
3
+ * Host-neutral output limits for tool results: the head truncation, line truncation and size
4
+ * formatting Pi's coding tools use, for hosts that cannot load Pi (the Worker). Whichever of the
5
+ * line and byte limits is hit first wins, and a line is never returned in part.
6
+ */
7
+ export declare const DEFAULT_MAX_LINES = 2000;
8
+ export declare const DEFAULT_MAX_BYTES: number;
9
+ /** Longest grep match line shown before it is cut. */
10
+ export declare const GREP_MAX_LINE_LENGTH = 500;
11
+ export interface TruncationOptions {
12
+ /** Maximum number of lines (default 2000). */
13
+ readonly maxLines?: number;
14
+ /** Maximum number of UTF-8 bytes (default 50 KiB). */
15
+ readonly maxBytes?: number;
16
+ }
17
+ export interface TruncationResult {
18
+ /** The kept content. */
19
+ readonly content: string;
20
+ readonly truncated: boolean;
21
+ /** Which limit was hit, or null when nothing was cut. */
22
+ readonly truncatedBy: 'lines' | 'bytes' | null;
23
+ readonly totalLines: number;
24
+ readonly totalBytes: number;
25
+ /** Complete lines kept. */
26
+ readonly outputLines: number;
27
+ readonly outputBytes: number;
28
+ /** Always false for head truncation; kept so the shape matches Pi's. */
29
+ readonly lastLinePartial: boolean;
30
+ /** The first line alone was over the byte limit, so nothing is kept. */
31
+ readonly firstLineExceedsLimit: boolean;
32
+ readonly maxLines: number;
33
+ readonly maxBytes: number;
34
+ }
35
+ export declare function formatSize(bytes: number): string;
36
+ /** Cut one line to `maxChars` characters and mark it. */
37
+ export declare function truncateLine(line: string, maxChars?: number): {
38
+ readonly text: string;
39
+ readonly wasTruncated: boolean;
40
+ };
41
+ /** Keep the first lines of `content` that fit both limits. */
42
+ export declare function truncateHead(content: string, options?: TruncationOptions): TruncationResult;
43
+ //#endregion
44
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../../../src/services/truncate/index.ts"],"mappings":";;;;;;qBAKa;qBACA;;qBAEA;iBAEI;;WAEN;;WAEA;;iBAGM;;WAEN;WACA;;WAEA;WACA;WACA;;WAEA;WACA;;WAEA;;WAEA;WACA;WACA;;wBAWK,WAAW;;wBAOX,aACd,cACA;WACY;WAAuB;;;wBAMrB,aAAa,iBAAiB,UAAS,oBAAyB"}
@@ -0,0 +1,5 @@
1
+ const e=2e3,t=51200,n=500;function r(e){if(e.length===0)return[];let t=e.split(`
2
+ `);return e.endsWith(`
3
+ `)&&t.pop(),t}function i(e){return e<1024?`${e}B`:e<1048576?`${(e/1024).toFixed(1)}KB`:`${(e/1048576).toFixed(1)}MB`}function a(e,t=500){return e.length<=t?{text:e,wasTruncated:!1}:{text:`${e.slice(0,t)}... [truncated]`,wasTruncated:!0}}function o(e,t={}){let n=t.maxLines??2e3,i=t.maxBytes??51200,a=Buffer.byteLength(e,`utf-8`),o=r(e),s=o.length;if(s<=n&&a<=i)return{content:e,truncated:!1,truncatedBy:null,totalLines:s,totalBytes:a,outputLines:s,outputBytes:a,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines:n,maxBytes:i};let c=o[0]??``;if(Buffer.byteLength(c,`utf-8`)>i)return{content:``,truncated:!0,truncatedBy:`bytes`,totalLines:s,totalBytes:a,outputLines:0,outputBytes:0,lastLinePartial:!1,firstLineExceedsLimit:!0,maxLines:n,maxBytes:i};let l=[],u=0,d=`lines`;for(let e=0;e<o.length&&e<n;e+=1){let t=o[e]??``,n=Buffer.byteLength(t,`utf-8`)+ +(e>0);if(u+n>i){d=`bytes`;break}l.push(t),u+=n}l.length>=n&&u<=i&&(d=`lines`);let f=l.join(`
4
+ `);return{content:f,truncated:!0,truncatedBy:d,totalLines:s,totalBytes:a,outputLines:l.length,outputBytes:Buffer.byteLength(f,`utf-8`),lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines:n,maxBytes:i}}export{t as DEFAULT_MAX_BYTES,e as DEFAULT_MAX_LINES,n as GREP_MAX_LINE_LENGTH,i as formatSize,o as truncateHead,a as truncateLine};
5
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":["DEFAULT_MAX_LINES","DEFAULT_MAX_BYTES","GREP_MAX_LINE_LENGTH","splitLinesForCounting","content","lines","formatSize","bytes","truncateLine","line","maxChars","truncateHead","maxLines","options","maxBytes","totalBytes","totalLines","firstLine","kept","keptBytes","truncatedBy","index","lineBytes","output"],"sources":["../../../src/services/truncate/index.ts"],"sourcesContent":["/**\n * Host-neutral output limits for tool results: the head truncation, line truncation and size\n * formatting Pi's coding tools use, for hosts that cannot load Pi (the Worker). Whichever of the\n * line and byte limits is hit first wins, and a line is never returned in part.\n */\nexport const DEFAULT_MAX_LINES = 2000;\nexport const DEFAULT_MAX_BYTES = 50 * 1024;\n/** Longest grep match line shown before it is cut. */\nexport const GREP_MAX_LINE_LENGTH = 500;\n\nexport interface TruncationOptions {\n /** Maximum number of lines (default 2000). */\n readonly maxLines?: number;\n /** Maximum number of UTF-8 bytes (default 50 KiB). */\n readonly maxBytes?: number;\n}\n\nexport interface TruncationResult {\n /** The kept content. */\n readonly content: string;\n readonly truncated: boolean;\n /** Which limit was hit, or null when nothing was cut. */\n readonly truncatedBy: 'lines' | 'bytes' | null;\n readonly totalLines: number;\n readonly totalBytes: number;\n /** Complete lines kept. */\n readonly outputLines: number;\n readonly outputBytes: number;\n /** Always false for head truncation; kept so the shape matches Pi's. */\n readonly lastLinePartial: boolean;\n /** The first line alone was over the byte limit, so nothing is kept. */\n readonly firstLineExceedsLimit: boolean;\n readonly maxLines: number;\n readonly maxBytes: number;\n}\n\n/** A trailing newline ends the last line rather than starting another. */\nfunction splitLinesForCounting(content: string): string[] {\n if (content.length === 0) return [];\n const lines = content.split('\\n');\n if (content.endsWith('\\n')) lines.pop();\n return lines;\n}\n\nexport function formatSize(bytes: number): string {\n if (bytes < 1024) return `${bytes}B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)}KB`;\n return `${(bytes / (1024 * 1024)).toFixed(1)}MB`;\n}\n\n/** Cut one line to `maxChars` characters and mark it. */\nexport function truncateLine(\n line: string,\n maxChars: number = GREP_MAX_LINE_LENGTH,\n): { readonly text: string; readonly wasTruncated: boolean } {\n if (line.length <= maxChars) return { text: line, wasTruncated: false };\n return { text: `${line.slice(0, maxChars)}... [truncated]`, wasTruncated: true };\n}\n\n/** Keep the first lines of `content` that fit both limits. */\nexport function truncateHead(content: string, options: TruncationOptions = {}): TruncationResult {\n const maxLines = options.maxLines ?? DEFAULT_MAX_LINES;\n const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;\n const totalBytes = Buffer.byteLength(content, 'utf-8');\n const lines = splitLinesForCounting(content);\n const totalLines = lines.length;\n\n if (totalLines <= maxLines && totalBytes <= maxBytes) {\n return {\n content,\n truncated: false,\n truncatedBy: null,\n totalLines,\n totalBytes,\n outputLines: totalLines,\n outputBytes: totalBytes,\n lastLinePartial: false,\n firstLineExceedsLimit: false,\n maxLines,\n maxBytes,\n };\n }\n\n const firstLine = lines[0] ?? '';\n if (Buffer.byteLength(firstLine, 'utf-8') > maxBytes) {\n return {\n content: '',\n truncated: true,\n truncatedBy: 'bytes',\n totalLines,\n totalBytes,\n outputLines: 0,\n outputBytes: 0,\n lastLinePartial: false,\n firstLineExceedsLimit: true,\n maxLines,\n maxBytes,\n };\n }\n\n const kept: string[] = [];\n let keptBytes = 0;\n let truncatedBy: 'lines' | 'bytes' = 'lines';\n for (let index = 0; index < lines.length && index < maxLines; index += 1) {\n const line = lines[index] ?? '';\n // Every line after the first carries the newline that joins it to the previous one.\n const lineBytes = Buffer.byteLength(line, 'utf-8') + (index > 0 ? 1 : 0);\n if (keptBytes + lineBytes > maxBytes) {\n truncatedBy = 'bytes';\n break;\n }\n kept.push(line);\n keptBytes += lineBytes;\n }\n if (kept.length >= maxLines && keptBytes <= maxBytes) truncatedBy = 'lines';\n\n const output = kept.join('\\n');\n return {\n content: output,\n truncated: true,\n truncatedBy,\n totalLines,\n totalBytes,\n outputLines: kept.length,\n outputBytes: Buffer.byteLength(output, 'utf-8'),\n lastLinePartial: false,\n firstLineExceedsLimit: false,\n maxLines,\n maxBytes,\n };\n}\n"],"mappings":"AAKA,MAAaA,EAAoB,IACpBC,EAAoB,MAEpBC,EAAuB,IA6BpC,SAASC,EAAsB,EAA2B,CACxD,GAAIC,EAAQ,SAAW,EAAG,MAAO,CAAC,EAClC,IAAMC,EAAQD,EAAQ,MAAM;CAAI,EAEhC,OADIA,EAAQ,SAAS;CAAI,GAAGC,EAAM,IAAI,EAC/BA,CACT,CAEA,SAAgBC,EAAW,EAAuB,CAGhD,OAFIC,EAAQ,KAAa,GAAGA,EAAM,GAC9BA,EAAQ,QAAoB,IAAIA,EAAQ,KAAA,CAAM,QAAQ,CAAC,EAAE,IACtD,IAAIA,EAAS,QAAA,CAAc,QAAQ,CAAC,EAAE,GAC/C,CAGA,SAAgBC,EACd,EACA,EAAA,IAC2D,CAE3D,OADIC,EAAK,QAAUC,EAAiB,CAAE,KAAMD,EAAM,aAAc,EAAM,EAC/D,CAAE,KAAM,GAAGA,EAAK,MAAM,EAAGC,CAAQ,EAAE,iBAAkB,aAAc,EAAK,CACjF,CAGA,SAAgBC,EAAa,EAAiB,EAA6B,CAAC,EAAqB,CAC/F,IAAMC,EAAWC,EAAQ,UAAA,IACnBC,EAAWD,EAAQ,UAAA,MACnBE,EAAa,OAAO,WAAWX,EAAS,OAAO,EAC/CC,EAAQF,EAAsBC,CAAO,EACrCY,EAAaX,EAAM,OAEzB,GAAIW,GAAcJ,GAAYG,GAAcD,EAC1C,MAAO,CACL,UACA,UAAW,GACX,YAAa,KACb,aACA,aACA,YAAaE,EACb,YAAaD,EACb,gBAAiB,GACjB,sBAAuB,GACvB,WACA,UACF,EAGF,IAAME,EAAYZ,EAAM,IAAM,GAC9B,GAAI,OAAO,WAAWY,EAAW,OAAO,EAAIH,EAC1C,MAAO,CACL,QAAS,GACT,UAAW,GACX,YAAa,QACb,aACA,aACA,YAAa,EACb,YAAa,EACb,gBAAiB,GACjB,sBAAuB,GACvB,WACA,UACF,EAGF,IAAMI,EAAiB,CAAC,EACpBC,EAAY,EACZC,EAAiC,QACrC,IAAK,IAAIC,EAAQ,EAAGA,EAAQhB,EAAM,QAAUgB,EAAQT,EAAU,GAAS,EAAG,CACxE,IAAMH,EAAOJ,EAAMgB,IAAU,GAEvBC,EAAY,OAAO,WAAWb,EAAM,OAAO,GAAK,IAAQ,GAC9D,GAAIU,EAAYG,EAAYR,EAAU,CACpC,EAAc,QACd,KACF,CACAI,EAAK,KAAKT,CAAI,EACd,GAAaa,CACf,CACIJ,EAAK,QAAUN,GAAYO,GAAaL,IAAU,EAAc,SAEpE,IAAMS,EAASL,EAAK,KAAK;CAAI,EAC7B,MAAO,CACL,QAASK,EACT,UAAW,GACX,cACA,aACA,aACA,YAAaL,EAAK,OAClB,YAAa,OAAO,WAAWK,EAAQ,OAAO,EAC9C,gBAAiB,GACjB,sBAAuB,GACvB,WACA,UACF,CACF,C"}
@@ -0,0 +1 @@
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./services/truncate/index.cjs");exports.DEFAULT_MAX_BYTES=e.DEFAULT_MAX_BYTES,exports.DEFAULT_MAX_LINES=e.DEFAULT_MAX_LINES,exports.GREP_MAX_LINE_LENGTH=e.GREP_MAX_LINE_LENGTH,exports.formatSize=e.formatSize,exports.truncateHead=e.truncateHead,exports.truncateLine=e.truncateLine;
@@ -0,0 +1,2 @@
1
+ import { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, GREP_MAX_LINE_LENGTH, TruncationOptions, TruncationResult, formatSize, truncateHead, truncateLine } from "./services/truncate/index.mjs";
2
+ export { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, GREP_MAX_LINE_LENGTH, type TruncationOptions, type TruncationResult, formatSize, truncateHead, truncateLine };
@@ -0,0 +1 @@
1
+ export{DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,GREP_MAX_LINE_LENGTH,formatSize,truncateHead,truncateLine}from"./services/truncate/index.mjs";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agimon-ai/po-hashline",
3
- "version": "0.0.0-alpha.2",
3
+ "version": "0.0.0-alpha.200",
4
4
  "description": "Shared snapshot-bound file tags and line anchors for Po tools.",
5
5
  "keywords": [
6
6
  "ai",
@@ -24,6 +24,7 @@
24
24
  "directory": "packages/utils/po-hashline"
25
25
  },
26
26
  "files": [
27
+ "NOTICE",
27
28
  "dist"
28
29
  ],
29
30
  "type": "module",
@@ -41,17 +42,22 @@
41
42
  "import": "./dist/files.mjs",
42
43
  "require": "./dist/files.cjs"
43
44
  },
45
+ "./truncate": {
46
+ "types": "./dist/truncate.d.mts",
47
+ "import": "./dist/truncate.mjs",
48
+ "require": "./dist/truncate.cjs"
49
+ },
44
50
  "./package.json": "./package.json"
45
51
  },
46
52
  "publishConfig": {
47
53
  "access": "public"
48
54
  },
49
55
  "devDependencies": {
50
- "@types/node": "26.6.4",
51
- "@vitest/coverage-v8": "5.0.3",
52
- "tsdown": "0.23.0",
56
+ "@types/node": "26.6.5",
57
+ "@vitest/coverage-v8": "5.0.4",
58
+ "tsdown": "0.23.1",
53
59
  "typescript": "7.0.2",
54
- "vitest": "5.0.3"
60
+ "vitest": "5.0.4"
55
61
  },
56
62
  "engines": {
57
63
  "node": ">=24"
@@ -59,7 +65,7 @@
59
65
  "scripts": {
60
66
  "build": "tsdown",
61
67
  "test": "vitest --run",
62
- "typecheck": "tsc --noEmit",
68
+ "typecheck": "tsrs --noEmit",
63
69
  "lint": "oxlint . && oxfmt . --check",
64
70
  "fixcode": "oxlint . --fix && oxfmt ."
65
71
  }