@zaly/agent 0.2.0 → 0.3.1
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/dist/{agent-DlhEEMPU.mjs → agent-GXRF7DUP.mjs} +7 -11
- package/dist/agent-GXRF7DUP.mjs.map +1 -0
- package/dist/{bash-DSy03sAj.mjs → bash-CB_VXpyd.mjs} +2 -2
- package/dist/{bash-DSy03sAj.mjs.map → bash-CB_VXpyd.mjs.map} +1 -1
- package/dist/{compactions-BpvQk4CG.mjs → compactions-92bMlcxJ.mjs} +3 -3
- package/dist/{compactions-BpvQk4CG.mjs.map → compactions-92bMlcxJ.mjs.map} +1 -1
- package/dist/{edit-DT672zIy.mjs → edit-gkb6MCW-.mjs} +2 -2
- package/dist/{edit-DT672zIy.mjs.map → edit-gkb6MCW-.mjs.map} +1 -1
- package/dist/{fetch-BrtIqrid.mjs → fetch-D_GzL2yy.mjs} +4 -4
- package/dist/{fetch-BrtIqrid.mjs.map → fetch-D_GzL2yy.mjs.map} +1 -1
- package/dist/{find-B-vvdlHu.mjs → find-DlrYUTXT.mjs} +2 -2
- package/dist/{find-B-vvdlHu.mjs.map → find-DlrYUTXT.mjs.map} +1 -1
- package/dist/{grep-rvZ5S319.mjs → grep-BI8Rou2q.mjs} +2 -2
- package/dist/{grep-rvZ5S319.mjs.map → grep-BI8Rou2q.mjs.map} +1 -1
- package/dist/{html-VrAsoGBK.mjs → html-B-Lr-9W6.mjs} +9457 -4826
- package/dist/html-B-Lr-9W6.mjs.map +1 -0
- package/dist/{index-node-esm-BwaOzhXB.mjs → index-node-esm-75XSYyIw.mjs} +16 -13
- package/dist/index-node-esm-75XSYyIw.mjs.map +1 -0
- package/dist/index.d.mts +11 -4
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +2 -2
- package/dist/{manager-1zEE5WiA.mjs → manager-CEociHy_.mjs} +2 -2
- package/dist/{manager-1zEE5WiA.mjs.map → manager-CEociHy_.mjs.map} +1 -1
- package/dist/{masker-B97uwYXG.mjs → masker-DWuL2Fjs.mjs} +16 -5
- package/dist/{masker-B97uwYXG.mjs.map → masker-DWuL2Fjs.mjs.map} +1 -1
- package/dist/{read-C5keKntU.mjs → read-DLtNq4XJ.mjs} +2 -2
- package/dist/{read-C5keKntU.mjs.map → read-DLtNq4XJ.mjs.map} +1 -1
- package/dist/{registry-CntkeXlo.mjs → registry-7mJQhyBA.mjs} +3 -3
- package/dist/{registry-CntkeXlo.mjs.map → registry-7mJQhyBA.mjs.map} +1 -1
- package/dist/{rolldown-runtime-DYf_mQCB.mjs → rolldown-runtime-BVN1G_yT.mjs} +4 -4
- package/dist/{session-CUE48QWX.mjs → session-C5ra-Hi1.mjs} +2 -2
- package/dist/{session-CUE48QWX.mjs.map → session-C5ra-Hi1.mjs.map} +1 -1
- package/dist/{session-DY9mF9Vb.d.mts → session-WtXqtAaq.d.mts} +2 -2
- package/dist/{session-DY9mF9Vb.d.mts.map → session-WtXqtAaq.d.mts.map} +1 -1
- package/dist/session.d.mts +1 -1
- package/dist/session.mjs +1 -1
- package/dist/{src-DJoqT9yP.mjs → src-Di-H3Oya.mjs} +71 -41
- package/dist/src-Di-H3Oya.mjs.map +1 -0
- package/dist/{subagent-D-TYaX38.mjs → subagent-BOK4GFd4.mjs} +3 -3
- package/dist/{subagent-D-TYaX38.mjs.map → subagent-BOK4GFd4.mjs.map} +1 -1
- package/dist/{tasks-Dgsiuh0Q.mjs → tasks-BUFqFoh6.mjs} +2 -2
- package/dist/{tasks-Dgsiuh0Q.mjs.map → tasks-BUFqFoh6.mjs.map} +1 -1
- package/dist/{tasks-D76WXWr2.mjs → tasks-CkDWJk_3.mjs} +4 -4
- package/dist/tasks-CkDWJk_3.mjs.map +1 -0
- package/dist/{tools-DmoUYORG.mjs → tools-Ca7VsMg3.mjs} +2 -2
- package/dist/{tools-DmoUYORG.mjs.map → tools-Ca7VsMg3.mjs.map} +1 -1
- package/dist/{write-BRQFfWAn.mjs → write-y93TC5ng.mjs} +2 -2
- package/dist/{write-BRQFfWAn.mjs.map → write-y93TC5ng.mjs.map} +1 -1
- package/package.json +11 -11
- package/dist/agent-DlhEEMPU.mjs.map +0 -1
- package/dist/html-VrAsoGBK.mjs.map +0 -1
- package/dist/index-node-esm-BwaOzhXB.mjs.map +0 -1
- package/dist/src-DJoqT9yP.mjs.map +0 -1
- package/dist/tasks-D76WXWr2.mjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"registry-CntkeXlo.mjs","names":["resolveRule","ignore","ignore"],"sources":["../src/permissions/handlers/bash.ts","../../../node_modules/.bun/ignore@7.0.14/node_modules/ignore/index.js","../src/permissions/handlers/files.ts","../src/permissions/handlers/tool.ts","../src/permissions/handlers/registry.ts"],"sourcesContent":["import type { Segment } from \"../../utils/bash/parser.ts\"\nimport type { CheckResult, PermissionHandler, Rule, Suggestion, Verdict } from \"../types.ts\"\n\nimport { parseBash } from \"../../utils/bash/parser.ts\"\nimport { TOOLS } from \"../../utils/bash/tools.ts\"\n\n/**\n * Handler for `Rule<\"bash\">` — evaluates a bash command line against\n * pattern rules, then delegates each segment's inferred and explicit\n * file paths to the file handler via `ctx.validate(\"read\"|\"write\", …)`.\n *\n * Composition keeps file-rule logic in one place: the bash handler\n * doesn't know about workspaces, sensitive files, or path-pattern\n * matching — it just asks the registered handler for those scopes.\n *\n * Sources of file paths per segment:\n * - `seg.reads` / `seg.writes` — explicit `<` / `>` / `>>` redirects\n * extracted by the parser.\n * - `TOOLS[cmd].reads/writes(args)` — inferred from built-in tool\n * specs (e.g. `cat foo.txt` reads `foo.txt`, `tee out` writes `out`).\n *\n * Suggestions and reasons from inner `validate` calls bubble up so the\n * prompt UI can offer \"allow `Bash(cat:*)`\" alongside \"add ~/Documents\n * as workspace\" in a single ask.\n */\nexport const bashHandler: PermissionHandler<\"bash\"> = {\n validate(input, ctx): CheckResult {\n const parsed = parseBash(input)\n if (!parsed.ok) {\n if ([\"bash\", \"read\", \"write\"].every((scope) => ctx.allowsAll?.(scope))) {\n return { verdict: \"allow\" }\n }\n return {\n ask: `Allow this bash command? (${parsed.reason})`,\n reason: parsed.reason,\n verdict: \"ask\",\n }\n }\n\n let verdict: Verdict = \"allow\"\n let reason: string | undefined\n const suggestions: Suggestion[] = []\n\n for (const seg of parsed.segments) {\n // Bash rule match for the command itself. Resolve this before the\n // conservative safety checks so explicit allow-all presets like yolo can\n // mean exactly that instead of degrading to an unimplemented ask prompt.\n const cmdVerdict = resolveRules(ctx.rules, seg) ?? \"ask\"\n if (seg.hasCommandSubst && cmdVerdict !== \"allow\") {\n return {\n ask: `Allow command substitution in \\`${seg.cmd}\\`?`,\n reason: \"command substitution not allowed\",\n verdict: \"ask\",\n }\n }\n const spec = TOOLS[seg.cmd]\n if (spec?.unsafe?.(seg.args) && cmdVerdict !== \"allow\") {\n return {\n ask: `Allow invocation of \\`${seg.cmd}\\`? (unsafe)`,\n reason: `${seg.cmd}: invocation mode not safely modelled`,\n verdict: \"ask\",\n }\n }\n\n let segVerdict: Verdict = cmdVerdict\n let segReason: string | undefined =\n cmdVerdict === \"allow\" ? undefined : `segment \"${seg.cmd}\" → ${cmdVerdict}`\n if (cmdVerdict === \"ask\") {\n suggestions.push({\n kind: \"rule\",\n pattern: seg.args.length > 0 ? `${seg.cmd}:*` : seg.cmd,\n scope: \"bash\",\n })\n }\n\n // Delegate file paths to the file handler. Reads first, then\n // writes; both contribute to this segment's verdict via combine.\n const reads = [...(spec?.reads?.(seg.args) ?? []), ...seg.reads]\n const writes = [...(spec?.writes?.(seg.args) ?? []), ...seg.writes.map((w) => w.path)]\n\n for (const path of reads) {\n if (seg.dyn?.has(path) && !ctx.allowsAll?.(\"read\")) {\n segVerdict = combine(segVerdict, \"ask\")\n segReason ??= `${seg.cmd}: read ${path}: dynamic path`\n suggestions.push({\n kind: \"rule\",\n pattern: `${seg.cmd}:*`,\n scope: \"bash\",\n })\n continue\n }\n const r = ctx.validate(\"read\", path)\n segVerdict = combine(segVerdict, r.verdict)\n if (r.verdict !== \"allow\") {\n segReason ??= `${seg.cmd}: read ${path}: ${r.reason}`\n if (r.suggestions) suggestions.push(...r.suggestions)\n }\n if (segVerdict === \"deny\") break\n }\n if (segVerdict !== \"deny\") {\n for (const path of writes) {\n if (seg.dyn?.has(path) && !ctx.allowsAll?.(\"write\")) {\n segVerdict = combine(segVerdict, \"ask\")\n segReason ??= `${seg.cmd}: write ${path}: dynamic path`\n suggestions.push({\n kind: \"rule\",\n pattern: `${seg.cmd}:*`,\n scope: \"bash\",\n })\n continue\n }\n const w = ctx.validate(\"write\", path)\n segVerdict = combine(segVerdict, w.verdict)\n if (w.verdict !== \"allow\") {\n segReason ??= `${seg.cmd}: write ${path}: ${w.reason}`\n if (w.suggestions) suggestions.push(...w.suggestions)\n }\n if (segVerdict === \"deny\") break\n }\n }\n\n verdict = combine(verdict, segVerdict)\n if (verdict !== \"allow\" && reason === undefined) reason = segReason\n if (verdict === \"deny\") break\n }\n\n return verdict === \"allow\"\n ? { verdict: \"allow\" }\n : {\n ask: `Allow this bash command?`,\n reason: reason ?? \"no rule matched\",\n suggestions: suggestions.length > 0 ? suggestions : undefined,\n verdict,\n }\n },\n}\n\n// ── Pattern matching ─────────────────────────────────────────────────────\n\n/** A command-pattern rule.\n *\n * Pattern syntax:\n * \"cmd\" → cmd alone, no args\n * \"cmd:*\" → cmd with any args (trailing wildcard)\n * \"cmd a\" → cmd with arg \"a\", no other args\n * \"cmd a:*\" → cmd with arg \"a\" plus any others\n * \"cmd a b\" → cmd with exact args [a, b]\n * \"cmd --flag*\" → cmd with arg starting with \"--flag\" (per-arg prefix)\n * \"bun test:node:*\" → cmd \"bun\", arg \"test:node\", any others\n *\n * Whitespace separates the cmd from its args, and args from each\n * other. The `:` character is only meaningful as the trailing `:*`\n * wildcard suffix — anywhere else (including inside an arg like\n * `test:node`) it's a literal character. */\n\ninterface ParsedPattern {\n cmd: string\n /** Arg-position match tokens. Each may end with `*` for prefix match. */\n parts: string[]\n /** Set when the pattern ends with `:*`, allowing arbitrary further args. */\n trailingWildcard: boolean\n}\n\n/** Combine two verdicts: deny dominates, ask beats allow. */\nfunction combine(a: Verdict, b: Verdict): Verdict {\n if (a === \"deny\" || b === \"deny\") return \"deny\"\n if (a === \"ask\" || b === \"ask\") return \"ask\"\n return \"allow\"\n}\n\nconst patternCache = new Map<string, ParsedPattern>()\n\nfunction parsePattern(pattern: string): ParsedPattern {\n const cached = patternCache.get(pattern)\n if (cached) return cached\n\n let body = pattern.trim()\n let trailingWildcard = false\n if (body.endsWith(\":*\")) {\n trailingWildcard = true\n body = body.slice(0, -2)\n }\n\n const tokens = body.split(/\\s+/).filter((s) => s.length > 0)\n const cmd = tokens[0] ?? \"\"\n const result: ParsedPattern = {\n cmd,\n parts: tokens.slice(1),\n trailingWildcard,\n }\n patternCache.set(pattern, result)\n return result\n}\n\nfunction matchPart(part: string, value: string): boolean {\n if (part.endsWith(\"*\")) {\n return value.startsWith(part.slice(0, -1))\n }\n return part === value\n}\n\n/** Test whether a parsed segment matches a rule pattern. */\nexport function matchRule(rule: Rule, seg: Segment): boolean {\n const p = parsePattern(rule.pattern)\n // Bare `*` (e.g. from a `Bash` rule with no parens) matches any command.\n if (p.cmd === \"*\" && p.parts.length === 0) return true\n if (p.cmd !== seg.cmd) return false\n if (seg.args.length < p.parts.length) return false\n for (let i = 0; i < p.parts.length; i++) {\n if (!matchPart(p.parts[i], seg.args[i])) return false\n }\n if (p.trailingWildcard) return true\n return seg.args.length === p.parts.length\n}\n\n/** First-match-wins resolution. Returns `undefined` if no rule matches. */\nfunction resolveRules(rules: readonly Rule[], seg: Segment): Verdict | undefined {\n for (const r of rules) {\n if (matchRule(r, seg)) return r.policy\n }\n return undefined\n}\n","// A simple implementation of make-array\nfunction makeArray (subject) {\n return Array.isArray(subject)\n ? subject\n : [subject]\n}\n\nconst UNDEFINED = undefined\nconst EMPTY = ''\nconst SPACE = ' '\nconst ESCAPE = '\\\\'\n\n// The characters that carry a meaning of their own inside a regular\n// expression, so a literal one has to be escaped before it is emitted.\nconst REGEX_LITERAL_SPECIAL = /[.*+?()[\\]{}^$|\\\\/]/\nconst BOM = '\\uFEFF'\nconst REGEX_INVALID_TRAILING_BACKSLASH = /(?:[^\\\\]|^)\\\\$/\n// A run of two or more asterisks is a globstar (#175)\nconst REGEX_ANCHORED_GLOBSTAR = /^\\/\\*{2,}$/\nconst REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\\\!/\nconst REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\\\#/\nconst REGEX_SPLITALL_CRLF = /\\r?\\n/g\n\n// Invalid:\n// - /foo,\n// - ./foo,\n// - ../foo,\n// - .\n// - ..\n// Valid:\n// - .foo\nconst DOUBLE_SLASH = '//'\nconst SLASH_CODE = 47\nconst DOT_CODE = 46\n\n\nconst SLASH = '/'\n\n// Do not use ternary expression here, since \"istanbul ignore next\" is buggy\nlet TMP_KEY_IGNORE = 'node-ignore'\n/* istanbul ignore else */\nif (typeof Symbol !== 'undefined') {\n TMP_KEY_IGNORE = Symbol.for('node-ignore')\n}\nconst KEY_IGNORE = TMP_KEY_IGNORE\n\nconst define = (object, key, value) => {\n Object.defineProperty(object, key, {value})\n return value\n}\n\nconst RETURN_FALSE = () => false\n\n// > The range notation, e.g. [a-zA-Z],\n// > can be used to match one of the characters in a range.\n//\n// gitignore(5) defers to fnmatch(3) for this, and git implements it in\n// `wildmatch.c`. A bracket expression has a sub-grammar of its own, which\n// is neither the surrounding pattern grammar nor the JavaScript one:\n//\n// - a `]` right after `[` or `[!` is a literal member, not the terminator\n// - `[:alpha:]` names one of twelve POSIX classes\n// - `\\` escapes the next member, `]` included\n// - `*`, `?` and `.` are plain literal members\n// - an unterminated expression makes the whole pattern match nothing\n//\n// which means the expression can not be located -- let alone translated -- by\n// a regular expression. It is scanned out of the pattern before the\n// replacers below run, and put back once they are done, so that neither the\n// metacharacter escaper nor the `?` / `*` replacers ever see its body.\n\n// git classifies with its own ASCII-only ctype macros (`wildmatch.c`), never\n// with the C library ones, so these must not be mapped onto `\\d` / `\\w` /\n// `\\s`, which are wider. `/` is left out of every expansion, because a\n// bracket expression never matches a path separator.\nconst POSIX_CLASSES = {\n alnum: '0-9A-Za-z',\n alpha: 'A-Za-z',\n blank: ' \\\\t',\n cntrl: '\\\\x00-\\\\x1f\\\\x7f',\n digit: '0-9',\n graph: '!-.0-~',\n lower: 'a-z',\n print: ' -.0-~',\n punct: '!-.:-@\\\\[-`{-~',\n // git's `sane-ctype.h` classifies \\v and \\f as control, not space,\n // unlike C's `isspace`\n space: ' \\\\t\\\\n\\\\r',\n upper: 'A-Z',\n xdigit: '0-9A-Fa-f'\n}\n\nconst CLASS_MEMBERS_TO_ESCAPE = '\\\\]^-['\n\nconst escapeMember = char => CLASS_MEMBERS_TO_ESCAPE.indexOf(char) < 0\n ? char\n : ESCAPE + char\n\n// > if (matched == negated || ((flags & WM_PATHNAME) && text_ch == '/'))\n// > return WM_ABORT_TO_STARSTAR; (git, `wildmatch.c`)\n// A bracket expression never matches a path separator, whatever its members\n// say, so a negated class gets `/` as one more excluded character, while a\n// plain one -- where a literal member or a range could still let `/` in --\n// is guarded with a lookahead, `/` being impossible to subtract from a\n// JavaScript character class.\nconst NON_SLASH = '(?!\\\\/)'\n\nconst classSource = (negated, body) => {\n if (negated) {\n return `[^\\\\/${body}]`\n }\n\n const source = `[${body}]`\n\n return new RegExp(source).test('/')\n ? NON_SLASH + source\n : source\n}\n\n// Scan the bracket expression that starts at `pattern[start] === '['`,\n// mirroring the member loop of git's `wildmatch.c`.\n// @returns {{end: number, source: string} | null} `null` if the expression is\n// never terminated, which makes the whole pattern match nothing.\nconst scanBracket = (pattern, start) => {\n const {length} = pattern\n let index = start + 1\n let negated = EMPTY\n\n const lead = pattern[index]\n if (lead === '!' || lead === '^') {\n negated = '^'\n index ++\n }\n\n let body = EMPTY\n\n // The member a `-` could start a range from, or EMPTY when the previous\n // member can not open one (start of the body, or a range / POSIX class\n // that has just closed)\n let prev = EMPTY\n\n // git scans the members with a do-while, so the first one is consumed\n // unconditionally. That is the whole reason a leading `]` is a member\n // and not the terminator.\n for (;;) {\n const char = pattern[index]\n\n if (char === UNDEFINED) {\n return null\n }\n\n if (char === ESCAPE) {\n const escaped = pattern[index + 1]\n if (escaped === UNDEFINED) {\n return null\n }\n body += escapeMember(escaped)\n prev = escaped\n index ++\n } else if (\n char === '-'\n && prev\n && index + 1 < length\n && pattern[index + 1] !== ']'\n ) {\n index ++\n let to = pattern[index]\n if (to === ESCAPE) {\n // A pattern can not end on a lone backslash -- `checkPattern` has\n // already thrown it away -- so there is an upper bound to read.\n to = pattern[index += 1]\n }\n // An out-of-order range matches nothing in git but is a syntax error in\n // JavaScript, so it is dropped. Its lower bound stays: git tests it\n // as a plain member before it ever looks at the `-`, so `[c-a]` does\n // match `c`.\n if (prev <= to) {\n body += `-${escapeMember(to)}`\n }\n prev = EMPTY\n } else if (char === '[' && pattern[index + 1] === ':') {\n const nameStart = index + 2\n let end = nameStart\n while (end < length && pattern[end] !== ']') {\n end ++\n }\n\n if (end === length) {\n return null\n }\n\n if (end > nameStart && pattern[end - 1] === ':') {\n const name = pattern.slice(nameStart, end - 1)\n\n // An unknown class name makes the whole pattern match nothing\n if (!Object.prototype.hasOwnProperty.call(POSIX_CLASSES, name)) {\n return null\n }\n\n body += POSIX_CLASSES[name]\n prev = EMPTY\n index = end\n } else {\n // No `:]` to close it, so the `[` is a plain member and scanning\n // resumes right after it.\n body += escapeMember('[')\n prev = '['\n index = nameStart - 2\n }\n } else {\n body += escapeMember(char)\n prev = char\n }\n\n index ++\n\n if (pattern[index] === ']') {\n return {\n end: index,\n source: classSource(negated, body)\n }\n }\n }\n}\n\n// An empty JavaScript class can never match, which is how a pattern that git\n// gives up on (`WM_ABORT_ALL`) is expressed here.\nconst NEVER_MATCH = '[]'\n\n// A NUL can appear in neither a `.gitignore` line nor a path, which makes it\n// the one safe placeholder character. A literal one in the pattern is\n// held aside all the same, so a collision is impossible by construction.\nconst PLACEHOLDER = '\\u0000'\nconst REGEX_RESTORE_PLACEHOLDER = new RegExp(\n `${PLACEHOLDER}(\\\\d+)${PLACEHOLDER}`, 'g'\n)\n\n// The one wildcard the chain does not expand for itself is a trailing `*`. How\n// it expands depends on the mode (`regex` vs `checkRegex`), so `_make` is\n// left to do it, and until then the pending wildcard travels as this marker.\n// That is what keeps it apart from a user-escaped literal `\\*`: the unescape\n// steps collapse the escaped one to the exact `\\*` a wildcard would leave\n// behind, so by the time `_make` runs the two are otherwise the same string\n// and a literal star gets wrongly rewritten into a wildcard. The marker is a\n// private-use character, and `extractBrackets` keeps one that came out of the\n// pattern apart from it, so the only marker `_make` ever turns back into a\n// real wildcard is the one this chain put there itself.\nconst TRAILING_WILDCARD = '\\uE000'\n\n// A trailing \"/**\" is deferred the same way, because `checkRegex` has to tell\n// it apart from a trailing \"/*\" (see `checkSourceOf`). For `.ignores()` it\n// still never matches the folder itself (#21).\nconst TRAILING_DOUBLESTAR = '\\uE001'\n\n// The three characters above mean something to the chain that builds the\n// source rather than to the path, so one that came out of the pattern is\n// held aside like a bracket expression instead of going straight out. Being\n// held is what makes it safe: the restore runs after the step that anchors\n// the source, so the character comes back in the middle of the source and\n// not at its end, which is the one place `_make` and `checkSourceOf` look\n// for a marker. Without it a pattern's own character lands where a pending\n// marker sits, and `_make` turns it into a real trailing wildcard.\n//\n// It is held as a one-member class rather than bare, in both of the branches\n// a reserved character can reach, so that the property can be\n// read off this function alone -- a reserved character never goes out on\n// its own -- rather than depending on where in the chain the restore\n// happens to run. In the expression built here `[x]` matches exactly what\n// `x` matches, none of the three being special to a regular expression or\n// inside a class, so no test can tell the two apart: the class is insurance,\n// and the paragraph above is the reason it is not needed.\nconst isReserved = char =>\n char === PLACEHOLDER\n || char === TRAILING_WILDCARD\n || char === TRAILING_DOUBLESTAR\n\n// Replace every bracket expression with a placeholder the replacers below\n// leave alone, and translate it separately.\nconst extractBrackets = pattern => {\n const sources = []\n const hold = source =>\n `${PLACEHOLDER}${sources.push(source) - 1}${PLACEHOLDER}`\n\n const {length} = pattern\n let out = EMPTY\n let index = 0\n\n while (index < length) {\n const char = pattern[index]\n\n if (char === ESCAPE) {\n // > Put a backslash (\"\\\") in front of ... a character to make it literal.\n // (gitignore(5) -> fnmatch(3))\n // A backslash quotes the next character, whatever it is, so `\\d` is a\n // literal `d`, not the regex digit class, and `\\?` is a literal `?`,\n // not a wildcard. Held aside as its literal here, the escape never\n // reaches the replacers below, which would otherwise let `\\d`, `\\b`,\n // `\\1`, `\\/` keep their regular-expression meaning, and would turn a\n // `\\?` into `[^\\/]`.\n //\n // Three escapes are still left for the chain: `\\*` (a literal star,\n // told apart from a wildcard by `TRAILING_WILDCARD` and the wildcard\n // replacers), `\\[` (a literal bracket, the one `[` the bracket\n // replacer still expects), and `\\ ` (a quoted space, which one pass\n // below rewrites in bulk -- holding each one aside instead costs more\n // on a pattern built out of them). A lone trailing backslash can reach\n // here after line-ending cleanup.\n //\n // A quoted backslash is not among them. The chain doubles every\n // backslash, then takes the doubling back out again, and a quoted one\n // standing next to a character the chain also escapes left the two\n // counts sharing a run, so one of the escapes was lost. Held here as\n // the literal it means, it never joins that run.\n const escaped = pattern[index + 1]\n\n if (\n escaped === UNDEFINED\n || escaped === SLASH && index + 2 === length\n ) {\n // Git removes a final directory slash before matching. An escape\n // without a character after that removal makes the pattern invalid.\n out += hold(NEVER_MATCH)\n } else if (\n escaped === '*'\n || escaped === '['\n || escaped === SPACE\n ) {\n out += pattern.slice(index, index + 2)\n } else {\n out += hold(\n REGEX_LITERAL_SPECIAL.test(escaped)\n ? ESCAPE + escaped\n : isReserved(escaped)\n ? `[${escaped}]`\n : escaped\n )\n }\n\n index += 2\n } else if (isReserved(char)) {\n out += hold(`[${char}]`)\n index ++\n } else if (char === '[') {\n const scanned = scanBracket(pattern, index)\n\n if (scanned === null) {\n // git gives up on the whole pattern (`WM_ABORT_ALL`), so whatever\n // follows can not make it match either.\n out += hold(NEVER_MATCH)\n index = length\n } else {\n out += hold(scanned.source)\n index = scanned.end + 1\n }\n } else {\n out += char\n index ++\n }\n }\n\n return {\n source: out,\n sources\n }\n}\n\n// A step of the chain below is normally a `[matcher, replacer]` pair handed\n// to `String.replace`. `DIRECT` marks the ones that are plain string work\n// instead, and take `(source, pattern)`.\n//\n// Anchoring the two ends is exactly that -- a test of one character and a\n// concatenation -- and putting it through the regular expression engine\n// cost a third of this chain for nothing: 167ns where 10ns does the same\n// job. The two are still steps in the same list, in the same places,\n// because their position in the order is part of what they mean.\nconst DIRECT = null\n\n// A separator at the beginning or in the middle of a pattern, as opposed to\n// one at the very end.\nconst REGEX_INNER_SLASH = /\\/(?!$)/\n\n// > If the pattern ends with a slash,\n// > it is removed for the purpose of the following description,\n// > but it would only find a match with a directory.\n// > In other words, foo/ will match a directory foo and paths underneath it,\n// > but will not match a regular file or a symbolic link foo\n// > (this is consistent with the way how pathspec works in general in Git).\n// '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`'\n// -> ignore-rules will not deal with it, because it costs extra `fs.stat` call\n// you could use option `mark: true` with `glob`\n\n// '`foo/`' should not continue with the '`..`'\n// The chain that turns one gitignore pattern into a regular expression\n// source, in order. A step is either\n//\n// [matcher, replacer] handed to `String.replace`\n// [matcher, replacer, required] the same, but skipped outright unless\n// `required` appears in the string, which\n// the matcher cannot match without\n// [DIRECT, transform] plain string work, taking (source, pattern)\n//\n// The `required` character is only ever a shortcut: finding it does not mean\n// the matcher will match, and not finding it means it cannot. It is there\n// because scanning for one character costs a fraction of running a matcher\n// that then finds nothing -- for the wildcard step, whose `[^\\\\]+`\n// backtracks its way through the whole string before giving up, 11ns\n// against 400ns.\nconst REPLACERS = [\n\n // Replace (\\ ) with ' '\n // Only a space: an escaped tab or other whitespace is already a literal by\n // the time it reaches here, and a bare tab must be left as one, not turned\n // into a space.\n // (\\ ) -> ' '\n // (\\\\ ) -> '\\\\ '\n // (\\\\\\ ) -> '\\\\ '\n [\n // A run of backslashes is taken whole, from its first one, so no match\n // ever starts again inside it -- `(\\\\+?) ` did, which made a long run\n // quadratic.\n /(\\\\+)( ?)/g,\n (_, run, space) => space\n ? run.slice(0, run.length - run.length % 2) + SPACE\n : run,\n ESCAPE + SPACE\n ],\n\n // git's wildmatch() reads a run of two or more asterisks as one globstar\n // whenever the run fills a path segment: it starts the pattern or follows\n // a `/`, and it ends the pattern or comes before a `/`. A run of two is\n // already `**`; a longer one is folded into `**` here, so the steps\n // below only ever have to know `**`.\n // `***/foo` -> `**/foo`, `a/***/b` -> `a/**/b`, `a/***` -> `a/**`\n // git also takes a run beside a literal prefix (`a***/b`) or beside an\n // escaped slash (`***\\/b`) as a globstar, and this does not; the README\n // lists both, under \"A run of asterisks\".\n [\n /(^|\\/)\\*{3,}(?=\\/|$)/g,\n (_, start) => `${start}**`,\n '*'\n ],\n\n // Escape metacharacters\n // which is written down by users but means special for regular expressions.\n\n // > There are 12 characters with special meanings:\n // > - the backslash \\,\n // > - the caret ^,\n // > - the dollar sign $,\n // > - the period or dot .,\n // > - the vertical bar or pipe symbol |,\n // > - the question mark ?,\n // > - the asterisk or star *,\n // > - the plus sign +,\n // > - the opening parenthesis (,\n // > - the closing parenthesis ),\n // > - and the opening square bracket [,\n // > - the opening curly brace {,\n // > These special characters are often called \"metacharacters\".\n [\n /[\\\\$.|*+(){^]/g,\n match => `\\\\${match}`\n ],\n\n [\n // > a question mark (?) matches a single character\n /(?!\\\\)\\?/g,\n () => '[^/]',\n '?'\n ],\n\n // leading slash\n [\n\n // > A leading slash matches the beginning of the pathname.\n // > For example, \"/*.c\" matches \"cat-file.c\" but not \"mozilla-sha1/sha1.c\".\n // A leading slash matches the beginning of the pathname\n /^\\//,\n () => '^',\n SLASH\n ],\n\n // replace special metacharacter slash after the leading slash\n [\n /\\//g,\n () => '\\\\/',\n SLASH\n ],\n\n [\n // > A leading \"**\" followed by a slash means match in all directories.\n // > For example, \"**/foo\" matches file or directory \"foo\" anywhere,\n // > the same as pattern \"foo\".\n // > \"**/foo/bar\" matches file or directory \"bar\" anywhere that is directly\n // > under directory \"foo\".\n // Notice that the '*'s have been replaced as '\\\\*'\n /^\\^*(?:\\\\\\*\\\\\\*\\\\\\/)+/,\n\n // '**/foo' <-> 'foo'\n () => '^(?:.*\\\\/)?',\n '*'\n ],\n\n // starting\n [\n // there will be no leading '/'\n // (which has been replaced by section \"leading slash\")\n // If starts with '**', adding a '^' to the regular expression also works\n DIRECT,\n (source, pattern) => {\n // Nothing to anchor to, or already anchored\n if (!source || source[0] === '^') {\n return source\n }\n\n // If has a slash `/` at the beginning or middle\n const anchor = !REGEX_INNER_SLASH.test(pattern)\n // > Prior to 2.22.1\n // > If the pattern does not contain a slash /,\n // > Git treats it as a shell glob pattern\n // Actually, if there is only a trailing slash,\n // git also treats it as a shell glob pattern\n\n // After 2.22.1 (compatible but clearer)\n // > If there is a separator at the beginning or middle (or both)\n // > of the pattern, then the pattern is relative to the directory\n // > level of the particular .gitignore file itself.\n // > Otherwise the pattern may also match at any level below\n // > the .gitignore level.\n ? '(?:^|\\\\/)'\n\n // > Otherwise, Git treats the pattern as a shell glob suitable for\n // > consumption by fnmatch(3)\n : '^'\n\n return anchor + source\n }\n ],\n\n // two globstars\n [\n // Use lookahead assertions so that we could match more than one `'/**'`\n /\\\\\\/\\\\\\*\\\\\\*(?=\\\\\\/|$)/g,\n\n // Zero, one or several directories\n // should not use '*', or it will be replaced by the next replacer\n\n // Check if it is not the last `'/**'`\n (_, index, str) => index + 6 < str.length\n\n // case: /**/ at the end of the pattern, i.e. a trailing `'/**/'`\n // > A trailing `\"/**/\"` (a trailing `\"/**\"` restricted to directories)\n // > matches everything inside, but it should not match the current\n // > folder itself, so it requires at least one directory segment.\n // 'a/**/' matches 'a/b/', 'a/x/y/' but not 'a/'\n ? str.slice(index + 6) === '\\\\/'\n ? '(?:\\\\/[^\\\\/]+)+'\n\n // case: /**/\n // > A slash followed by two consecutive asterisks then a slash matches\n // > zero or more directories.\n // > For example, \"a/**/b\" matches \"a/b\", \"a/x/b\", \"a/x/y/b\" and so on.\n // '/**/'\n : '(?:\\\\/[^\\\\/]+)*'\n\n // case: /**\n // > A trailing `\"/**\"` matches everything inside.\n\n // #21: everything inside but it should not include the current folder,\n // resolved by `_make`\n : `\\\\/${TRAILING_DOUBLESTAR}`,\n '*'\n ],\n\n // normal intermediate wildcards\n [\n // Never replace escaped '*'\n // ignore rule '\\*' will match the path '*'\n\n // 'abc.*/' -> go\n // 'abc.*' -> skip this rule,\n // coz trailing single wildcard will be handed by [trailing wildcard]\n /(^|[^\\\\]+)(\\\\\\*)+(?=.+)/g,\n\n // '*.js' matches '.js'\n // '*.js' doesn't match 'abc'\n (_, p1, p2) => {\n // 1.\n // > An asterisk \"*\" matches anything except a slash.\n // 2.\n // > Other consecutive asterisks are considered regular asterisks\n // > and will match according to the previous rules.\n const unescaped = p2.replace(/\\\\\\*/g, '[^\\\\/]*')\n return p1 + unescaped\n },\n '*'\n ],\n\n // trailing wildcard, held apart from a literal star\n [\n // The step above leaves a trailing `*` alone, so a single `\\*` is all that\n // can be left at the end here, and what stands in front of it says which\n // kind it is. A wildcard arrives as the escaper wrote it, `\\*` with\n // nothing before it; a literal arrives as the user's own escape, which\n // the escaper doubled, and then the star's own -- `\\\\` and then `\\*`.\n // There is no third case: every backslash still reaching the chain is\n // one `\\*`, `\\[` or `\\ ` carries itself, and each is followed by its\n // own character, so a longer run can never form. This runs while the\n // two are still distinct, before the unescape steps below collapse the\n // literal onto the very `\\*` a wildcard leaves behind.\n /(^|[^\\\\])((?:\\\\\\\\)*)\\\\\\*$/,\n\n (match, p1, p2) =>\n p2 === EMPTY\n // A real wildcard: carry it to `_make` as the marker, so the unescape\n // steps and the trailing-wildcard rewrite can never mistake it for a\n // literal `\\*` (nor the reverse).\n ? p1 + TRAILING_WILDCARD\n // A literal star: leave it exactly as it stands for the unescape steps.\n : match,\n '*'\n ],\n\n [\n // unescape, revert step 3 except for back slash\n // For example, if a user escape a '\\\\*',\n // after step 3, the result will be '\\\\\\\\\\\\*'\n /\\\\\\\\\\\\(?=[$.|*+(){^])/g,\n () => ESCAPE,\n ESCAPE + ESCAPE\n ],\n\n [\n // '\\\\\\\\' -> '\\\\'\n /\\\\\\\\/g,\n () => ESCAPE,\n ESCAPE + ESCAPE\n ],\n\n [\n // Every real bracket expression -- POSIX classes included -- has already\n // been held aside by `extractBrackets`, so the only `[` left in the\n // pattern is an escaped, literal one.\n\n // A backslash could only stand at the end of the range if it quoted the\n // `]`, and `\\]` is held aside long before this.\n /\\\\\\[([^\\]/]*?)($|\\])/g,\n\n // '\\\\[bar]' -> '\\\\\\\\[bar]'\n (match, range, close) => `\\\\[${range}${close}`,\n '['\n ],\n\n // ending\n [\n // 'js' will not match 'js.'\n // 'ab' will not match 'abc'\n DIRECT,\n\n // WTF!\n // https://git-scm.com/docs/gitignore\n // changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1)\n // which re-fixes #24, #38\n\n // > If there is a separator at the end of the pattern then the pattern\n // > will only match directories, otherwise the pattern can match both\n // > files and directories.\n\n // 'js*' will not match 'a.js'\n // 'js/' will not match 'a.js'\n // 'js' will match 'a.js' and 'a.js/'\n source => {\n const last = source[source.length - 1]\n\n // The pattern is empty, or ends in a pending marker `_make` owns --\n // the trailing wildcard, or a trailing \"/**\". A trailing `*` that is\n // not the marker is a literal star, which anchors like any other\n // final character.\n if (!last || last === TRAILING_WILDCARD || last === TRAILING_DOUBLESTAR) {\n return source\n }\n\n return last === SLASH\n // foo/ will not match 'foo'\n ? `${source}$`\n // foo matches 'foo' and 'foo/'\n : `${source}(?=$|\\\\/$)`\n }\n ]\n]\n\nconst REGEX_REPLACE_TRAILING_WILDCARD = /(^|\\\\\\/)?\\uE000$/\nconst MODE_IGNORE = 'regex'\nconst MODE_CHECK_IGNORE = 'checkRegex'\nconst UNDERSCORE = '_'\n\nconst replaceTrailingWildcard = (_, p1) => {\n const prefix = p1\n // '\\^':\n // '/*' does not match EMPTY\n // '/*' does not match everything\n\n // '\\\\\\/':\n // 'abc/*' does not match 'abc/'\n ? `${p1}[^/]+`\n\n // 'a*' matches 'a'\n // 'a*' matches 'aa'\n : '[^/]*'\n\n return `${prefix}(?=$|\\\\/$)`\n}\n\nconst REGEX_REPLACE_TRAILING_DOUBLESTAR = /\\uE001$/\n\n// 'abc/**' matches everything under 'abc', but not 'abc/' itself (#21)\nconst replaceTrailingDoublestar = () => '.+(?=$|\\\\/$)'\n\nconst WILDCARD = '[^\\\\/]*'\n\n// The fixed piece between the wildcard at `at` and the next wildcard of the\n// run: the tokens that separate them, joined as they appear in the source.\n// A run never holds two wildcards in a row, so there is always at least one\n// token.\nconst separatorAfter = (run, at) => {\n let separator = EMPTY\n\n for (let index = at + 1; index < run.length && !run[index].wildcard; index ++) {\n separator += run[index].single\n }\n\n return separator\n}\n\n// Where a run of non-slash wildcards is split by fixed pieces --\n// `[^/]*ab[^/]*cd...` -- the engine has many equivalent ways to lay the\n// input across the wildcards, and on input that does not match it works\n// through all of them, so the time grows with the number of wildcards\n// rather than the length of the path. Every wildcard but the last in such a\n// run can be pinned to stop where the piece after it begins, which leaves\n// one way to lay out the input and no rewinding, without changing which\n// paths match: the fixed pieces still bound the count, and the last\n// wildcard still absorbs the rest.\n//\n// A wildcard is pinned to the whole piece, never to the piece's first\n// character. The pin leaves no way back, so a wildcard that stopped at that\n// first character would hand over wherever the character happens to turn\n// up, including the places the rest of the piece cannot follow -- which is\n// how `f*o/*/*` came to miss `foo/b/c`, the first `o` of `foo` not being\n// the one the `o/` after it needs. Every token of a piece matches exactly\n// one character, so the first place the whole piece fits is the leftmost\n// place it can sit, and whatever is left over goes to the wildcards that\n// follow.\n//\n// The source is read one token at a time -- a wildcard, a single-character\n// piece (a literal, an escape, a class), or a parenthesised group or anchor\n// that ends the run -- so only a genuine wildcard is touched.\nconst pinWildcards = source => {\n if (source.indexOf(WILDCARD) < 0) {\n return source\n }\n\n const tokens = []\n const {length} = source\n let index = 0\n\n while (index < length) {\n const char = source[index]\n\n if (source.startsWith(WILDCARD, index)) {\n tokens.push({wildcard: true})\n index += WILDCARD.length\n } else if (char === '[') {\n let end = index + 1\n\n if (source[end] === '^') {\n end ++\n }\n\n if (source[end] === ']') {\n end ++\n }\n\n while (end < length && source[end] !== ']') {\n end += source[end] === ESCAPE\n ? 2\n : 1\n }\n\n end ++\n tokens.push({single: source.slice(index, end)})\n index = end\n } else if (char === ESCAPE) {\n tokens.push({single: source.slice(index, index + 2)})\n index += 2\n } else if (char === '(') {\n let depth = 0\n let end = index\n\n do {\n if (source[end] === ESCAPE) {\n end ++\n } else if (source[end] === '(') {\n depth ++\n } else if (source[end] === ')') {\n depth --\n }\n\n end ++\n } while (end < length && depth > 0)\n\n if ('*+?'.indexOf(source[end]) >= 0) {\n end ++\n }\n\n tokens.push({boundary: source.slice(index, end)})\n index = end\n } else if (char === '^' || char === '$') {\n tokens.push({boundary: char})\n index ++\n } else {\n tokens.push({single: char})\n index ++\n }\n }\n\n let out = EMPTY\n let run = []\n\n const flush = () => {\n let lastWildcard\n\n run.forEach((token, at) => {\n if (token.wildcard) {\n lastWildcard = at\n }\n })\n\n run.forEach((token, at) => {\n if (!token.wildcard) {\n out += token.single\n return\n }\n\n // Every wildcard but the last is pinned to the whole piece that\n // follows it, for the reason set out above this function. The last\n // one stays as it is and takes up the rest.\n out += at === lastWildcard\n ? WILDCARD\n : `(?:(?!${separatorAfter(run, at)})[^\\\\/])*`\n })\n\n run = []\n }\n\n tokens.forEach(token => {\n if (token.boundary === undefined) {\n run.push(token)\n return\n }\n\n flush()\n out += token.boundary\n })\n\n flush()\n\n return out\n}\n\n// @param {pattern}\nconst makeRegexPrefix = pattern => {\n // `/**` matches every path, as `**` does. The translation below only finds\n // a globstar beside a slash it keeps, and the leading one is turned into\n // an anchor, so `/**` would come out as `/*` and match one level only.\n // Here rather than in `createRule`, so that `checkSourceOf`, which\n // compiles `/**/` again without its trailing slash, gets it too.\n if (REGEX_ANCHORED_GLOBSTAR.test(pattern)) {\n pattern = '**'\n }\n\n const {source, sources} = extractBrackets(pattern)\n\n const replaced = REPLACERS.reduce(\n // A pass whose matcher finds nothing hands back the very string it was\n // given, so asking first costs a search and saves a rewrite. Ten of the\n // fifteen passes never fire for a typical .gitignore line, and between\n // them they were 45% of this chain.\n (prev, [matcher, replacer, required]) => {\n if (matcher === DIRECT) {\n return replacer(prev, pattern)\n }\n\n if (required !== UNDEFINED && prev.indexOf(required) < 0) {\n return prev\n }\n\n // A pass whose matcher finds nothing hands back the very string it was\n // given, so asking first costs a search and saves a rewrite.\n return matcher.test(prev)\n ? prev.replace(matcher, replacer.bind(pattern))\n : prev\n },\n source\n )\n\n // Most patterns hold no bracket expression at all, and then there is\n // nothing to put back.\n return sources.length\n ? replaced.replace(\n REGEX_RESTORE_PLACEHOLDER,\n (match, index) => sources[index]\n )\n : replaced\n}\n\n// `checkRegex` tests a path with a trailing slash, 'abc/', the way\n// `git check-ignore` matches that literal string once the directory itself\n// is known not to be excluded (see `checkIgnore`): a trailing '/' of the\n// pattern is dropped, a basename pattern sees an empty basename, and only a\n// pattern whose last segment is a pending wildcard can match what is left\n// after the final slash -- 'abc/*' and 'abc/**' match 'abc/', and 'abc/**'\n// also matches 'abc/d/' (#77, #169).\nconst checkSourceOf = (body, prefix) => {\n if (body[body.length - 1] === SLASH) {\n prefix = makeRegexPrefix(body.slice(0, - 1))\n }\n\n const head = prefix.slice(0, - 1)\n const last = prefix[prefix.length - 1]\n\n return last === TRAILING_WILDCARD\n ? `${head}$`\n : last === TRAILING_DOUBLESTAR\n ? `${head}.*$`\n : NEVER_MATCH\n}\n\n// A trailing slash does not stop a pattern being basename-only: it restricts\n// the match to a directory, it does not let the pattern reach across one.\n// Everything else a pattern can hold -- a wildcard, a character class, an\n// escape -- stays inside a single path segment too, so a pattern with no\n// separator in it can only ever describe the last one.\nconst matchesBasename = body => {\n const index = body.indexOf(SLASH)\n\n return index < 0 || index === body.length - 1\n}\n\n// The last segment of a path, keeping a trailing slash, because a pattern that\n// ends in one matches only a directory.\n// 'a/b/c.js' -> 'c.js'; 'a/b/' -> 'b/'; 'c.js' -> 'c.js' (no copy made)\nconst basenameOf = path => {\n const end = path.length - 1\n\n const index = path.lastIndexOf(\n SLASH,\n path[end] === SLASH\n ? end - 1\n : end\n )\n\n return index < 0\n ? path\n : path.slice(index + 1)\n}\n\n// The parent directory of a path, with its trailing separator, or EMPTY when\n// the path has none.\n// 'a/b/c' -> 'a/b/'; 'a/b/' -> 'a/'; 'a' -> EMPTY; 'a/' -> EMPTY\n//\n// A path holding an empty segment has to be taken apart, because its\n// ancestors are not prefixes of it: the parent of 'a//b' is 'a/', not\n// 'a//', and the parent of '/a/' is nothing at all. Both shapes reach here\n// -- 'a//b' is accepted outright, and `checkIgnore` does not put the path\n// it is given through the relative-path check.\n//\n// Every other path is a prefix of itself, and cutting one costs a fraction of\n// splitting it into an array and joining that back at every level: 73ns\n// against 207ns.\nconst parentOf = path => {\n if (\n path.charCodeAt(0) === SLASH_CODE\n || path.indexOf(DOUBLE_SLASH) >= 0\n ) {\n const slices = path.split(SLASH).filter(Boolean)\n\n slices.pop()\n\n return slices.length\n ? slices.join(SLASH) + SLASH\n : EMPTY\n }\n\n const end = path.length - 1\n\n // Look back from before a trailing separator, since that one belongs to the\n // path itself.\n //\n // A negative place to start would be a trap here: `lastIndexOf` clamps one\n // to 0 and searches there rather than reporting no match, so '/' would\n // come back as its own parent and the walk would never end. It cannot\n // happen -- that is the only path short enough to produce one, and the\n // test above has already sent it the other way.\n const cut = path.lastIndexOf(\n SLASH,\n path.charCodeAt(end) === SLASH_CODE\n ? end - 1\n : end\n )\n\n return cut < 0\n ? EMPTY\n : path.slice(0, cut + 1)\n}\n\nconst isString = subject => typeof subject === 'string'\n\n// Blank lines and comments are told by `createRule`, once the pattern is\n// normalized.\nconst checkPattern = pattern => pattern\n && isString(pattern)\n && !REGEX_INVALID_TRAILING_BACKSLASH.test(pattern)\n\nconst splitPattern = pattern => pattern\n.split(REGEX_SPLITALL_CRLF)\n.filter(Boolean)\n\nclass IgnoreRule {\n constructor (\n pattern,\n mark,\n body,\n ignoreCase,\n negative,\n prefix\n ) {\n this.pattern = pattern\n this.mark = mark\n this.negative = negative\n\n define(this, 'body', body)\n define(this, 'ignoreCase', ignoreCase)\n define(this, 'regexPrefix', prefix)\n }\n\n // Worked out on first use and kept behind an own property, the way `regex`\n // caches itself in `_regex`. Deciding it in the constructor instead would\n // add a fourth `defineProperty` to every rule ever built, which cost 4% of\n // every compile -- including the compiles of rules that are never matched\n // against anything.\n get _basenameOnly () {\n return define(this, '_basenameOnly', matchesBasename(this.body))\n }\n\n get regex () {\n const key = UNDERSCORE + MODE_IGNORE\n\n if (this[key]) {\n return this[key]\n }\n\n return this._make(MODE_IGNORE, key)\n }\n\n get checkRegex () {\n const key = UNDERSCORE + MODE_CHECK_IGNORE\n\n if (this[key]) {\n return this[key]\n }\n\n return this._make(MODE_CHECK_IGNORE, key)\n }\n\n _make (mode, key) {\n const str = pinWildcards(\n mode === MODE_IGNORE\n ? this.regexPrefix\n .replace(REGEX_REPLACE_TRAILING_WILDCARD, replaceTrailingWildcard)\n .replace(REGEX_REPLACE_TRAILING_DOUBLESTAR, replaceTrailingDoublestar)\n : checkSourceOf(this.body, this.regexPrefix)\n )\n\n const regex = this.ignoreCase\n ? new RegExp(str, 'i')\n : new RegExp(str)\n\n return define(this, key, regex)\n }\n}\n\nconst isLineEnd = char => char === '\\r' || char === '\\n'\n\n// Drop a line terminator, which can remain when patterns are passed as an\n// array, and then the trailing spaces. Git trims spaces only, and a space\n// escaped by an odd run of backslashes stays, unescaped, as the last one.\n// Scanned from the end: a regular expression can only try each start in\n// turn, which is quadratic over a long run of spaces or backslashes.\n// 'a ' -> 'a'; 'a\\ ' -> 'a '; 'a\\\\ ' -> 'a\\\\'; 'a\\t' -> 'a\\t'\nconst trimEnd = body => {\n let end = body.length\n\n while (end && isLineEnd(body[end - 1])) {\n end --\n }\n\n const lineEnd = end\n\n while (end && body[end - 1] === SPACE) {\n end --\n }\n\n if (end === lineEnd) {\n return body.slice(0, end)\n }\n\n let backslashes = 0\n\n while (backslashes < end && body[end - backslashes - 1] === ESCAPE) {\n backslashes ++\n }\n\n return backslashes % 2\n ? body.slice(0, end - 1) + SPACE\n : body.slice(0, end)\n}\n\nconst createRule = ({\n pattern,\n mark\n}, ignoreCase) => {\n // Git drops a BOM before it reads the first line, so before anything else.\n let body = pattern[0] === BOM\n ? pattern.slice(1)\n : pattern\n\n // > A line starting with # serves as a comment.\n if (body[0] === '#') {\n return\n }\n\n let negative = false\n\n // > An optional prefix \"!\" which negates the pattern;\n if (body[0] === '!') {\n negative = true\n body = body.slice(1)\n }\n\n // Normalize the body before checking which slashes anchor the pattern.\n // Otherwise `bar/ ` is mistaken for a pattern containing an inner slash.\n // Only a body ending in a space or a line terminator has anything to trim.\n const last = body[body.length - 1]\n\n if (last === SPACE || last === '\\r' || last === '\\n') {\n body = trimEnd(body)\n }\n\n // > A blank line matches no files, so it can serve as a separator for\n // > readability.\n // Nor does a lone \"!\", or anything else left empty here: an empty pattern\n // would compile to a regex matching every path.\n if (!body) {\n return\n }\n\n body = body\n // > Put a backslash (\"\\\") in front of the first \"!\" for patterns that\n // > begin with a literal \"!\", for example, `\"\\!important!.txt\"`.\n .replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, '!')\n // > Put a backslash (\"\\\") in front of the first hash for patterns that\n // > begin with a hash.\n .replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, '#')\n\n const regexPrefix = makeRegexPrefix(body)\n\n return new IgnoreRule(\n pattern,\n mark,\n body,\n ignoreCase,\n negative,\n regexPrefix\n )\n}\n\nclass RuleManager {\n constructor (ignoreCase) {\n this._ignoreCase = ignoreCase\n this._rules = []\n\n // How many of the rules git would tag `EXC_FLAG_NODIR`.\n //\n // The scan uses it to decide, once for the whole set, whether handing\n // those rules the basename is worth what it costs the others. The\n // shortcut saves a full-path scan on every rule it applies to and costs\n // a check on every rule it does not, so a set where almost nothing is\n // basename-only comes out behind -- a 955 pattern set with 44 of them\n // measured 19% slower with the shortcut always on.\n //\n // Deciding this by measurement rather than by meaning is safe: a\n // basename-only pattern gives the very same answer against the whole\n // path, it just takes longer to say so. The choice can only change how\n // fast the scan runs, never what it returns.\n this._basenameCount = 0\n }\n\n _add (pattern) {\n // #32\n if (pattern && pattern[KEY_IGNORE]) {\n this._rules = this._rules.concat(pattern._rules._rules)\n this._basenameCount += pattern._rules._basenameCount\n this._added = true\n return\n }\n\n if (isString(pattern)) {\n pattern = {\n pattern\n }\n }\n\n const rule = checkPattern(pattern.pattern)\n && createRule(pattern, this._ignoreCase)\n\n if (rule) {\n this._added = true\n this._rules.push(rule)\n\n // Deliberately not `rule._basenameOnly`: reading that would materialise\n // the rule's own copy, and the whole point of leaving it lazy is that\n // a rule which is compiled and never matched never pays for it.\n if (matchesBasename(rule.body)) {\n this._basenameCount ++\n }\n }\n }\n\n // @param {Array<string> | string | Ignore} pattern\n add (pattern) {\n this._added = false\n\n makeArray(\n isString(pattern)\n ? splitPattern(pattern)\n : pattern\n ).forEach(this._add, this)\n\n if (this._added) {\n this._literalRules = UNDEFINED\n }\n\n return this._added\n }\n\n // Match the literal 'abc/' for `checkIgnore`, last rule wins. Only a rule\n // ending in a wildcard can match it (see `checkSourceOf`), so the rest\n // are left out once, rather than tested or compiled for every path.\n testLiteral (path) {\n const rules = this._literalRules || (\n this._literalRules = this._rules.filter(\n ({body}) => body[body.length - (\n body[body.length - 1] === SLASH ? 2 : 1\n )] === '*'\n )\n )\n\n let ignored = false\n let unignored = false\n let matchedRule\n\n for (let index = rules.length - 1; index >= 0; index --) {\n const rule = rules[index]\n\n if (rule.checkRegex.test(path)) {\n ignored = !rule.negative\n unignored = rule.negative\n matchedRule = rule.negative\n ? UNDEFINED\n : rule\n break\n }\n }\n\n const ret = {\n ignored,\n unignored\n }\n\n if (matchedRule) {\n ret.rule = matchedRule\n }\n\n return ret\n }\n\n // Test one single path without recursively checking parent directories\n //\n // - mode `string` either `MODE_IGNORE` or `MODE_CHECK_IGNORE`\n\n // @returns {TestResult}\n test (path, mode) {\n // Most of a .gitignore is patterns with no slash in them, and running\n // those against the whole path makes the regular expression engine walk\n // every directory name on the way to the only segment that could match.\n // Handing them the basename instead is what git does, and it is where\n // the time in a directory walk goes: the rule scan was two thirds of it.\n const rules = this._rules\n const {length} = rules\n\n const shortcut = this._basenameCount * 2 >= length\n\n const basename = shortcut\n ? basenameOf(path)\n : path\n\n // The last rule to match decides, as in git, and it is the rule\n // `git check-ignore -v` reports, so the scan runs from the end and stops\n // at the first match.\n // A plain loop rather than `forEach`, so that `path`, `basename` and\n // `shortcut` are locals. As a callback they became closure variables,\n // and reaching for one of those once per rule cost 10% of a scan over a\n // large rule set -- more than the shortcut they were there to serve.\n for (let index = length - 1; index >= 0; index --) {\n const rule = rules[index]\n\n if (rule[mode].test(\n shortcut && rule._basenameOnly\n ? basename\n : path\n )) {\n const {negative} = rule\n\n const ret = {\n ignored: !negative,\n unignored: negative\n }\n\n if (!negative) {\n ret.rule = rule\n }\n\n return ret\n }\n }\n\n return {\n ignored: false,\n unignored: false\n }\n }\n}\n\nconst throwError = (message, Ctor) => {\n throw new Ctor(message)\n}\n\nconst checkPath = (path, originalPath, doThrow) => {\n if (!isString(path)) {\n return doThrow(\n `path must be a string, but got \\`${originalPath}\\``,\n TypeError\n )\n }\n\n // We don't know if we should ignore EMPTY, so throw\n if (!path) {\n return doThrow(`path must not be empty`, TypeError)\n }\n\n // Check if it is a relative path\n if (checkPath.isNotRelative(path)) {\n const r = '`path.relative()`d'\n return doThrow(\n `path should be a ${r} string, but got \"${originalPath}\"`,\n RangeError\n )\n }\n\n return true\n}\n\n// > pathname should be a `path.relative()`d one\n//\n// The same thing `REGEX_TEST_INVALID_PATH` says, spelled out: a path is not\n// relative if it begins with a separator, or with `./` or `../`, or is\n// nothing but `.` or `..`. Every match is decided by the first three\n// characters, and this runs on every path handed to the library -- where it\n// was 55% of a cached lookup, more than the cache lookup itself.\nconst isNotRelative = path => {\n const first = path.charCodeAt(0)\n\n if (first === SLASH_CODE) {\n return true\n }\n\n if (first !== DOT_CODE) {\n return false\n }\n\n // '.'\n if (path.length === 1) {\n return true\n }\n\n const second = path.charCodeAt(1)\n\n // './'\n if (second === SLASH_CODE) {\n return true\n }\n\n if (second !== DOT_CODE) {\n return false\n }\n\n // '..' or '../'\n return path.length === 2 || path.charCodeAt(2) === SLASH_CODE\n}\n\ncheckPath.isNotRelative = isNotRelative\n\n// On windows, the following function will be replaced\n/* istanbul ignore next */\ncheckPath.convert = p => p\n\n\nclass Ignore {\n constructor ({\n ignorecase = true,\n ignoreCase = ignorecase,\n allowRelativePaths = false\n } = {}) {\n define(this, KEY_IGNORE, true)\n\n this._rules = new RuleManager(ignoreCase)\n this._strictPathCheck = !allowRelativePaths\n this._initCache()\n }\n\n _initCache () {\n // A cache for the result of `.ignores()`\n this._ignoreCache = Object.create(null)\n\n // A cache for the result of `.test()`\n this._testCache = Object.create(null)\n }\n\n add (pattern) {\n if (this._rules.add(pattern)) {\n // Some rules have just added to the ignore,\n // making the behavior changed,\n // so we need to re-initialize the result cache\n this._initCache()\n }\n\n return this\n }\n\n // legacy\n addPattern (pattern) {\n return this.add(pattern)\n }\n\n // @returns {TestResult}\n _test (originalPath, cache) {\n const path = originalPath\n // Supports nullable path\n && checkPath.convert(originalPath)\n\n checkPath(\n path,\n originalPath,\n this._strictPathCheck\n ? throwError\n : RETURN_FALSE\n )\n\n return this._t(path, cache)\n }\n\n checkIgnore (path) {\n // If the path doest not end with a slash, `.ignores()` is much equivalent\n // to `git check-ignore`\n if (path.charCodeAt(path.length - 1) !== SLASH_CODE) {\n return this.test(path)\n }\n\n // Like `git check-ignore`: a directory excluded by itself or by an\n // ancestor settles it, and only then is the literal 'abc/' matched\n // against the rules (see `checkSourceOf`).\n const dir = this._t(path, this._testCache)\n\n if (dir.ignored) {\n return dir\n }\n\n const literal = this._rules.testLiteral(path)\n\n return literal.ignored || literal.unignored\n ? literal\n : dir\n }\n\n _t (\n // The path to be tested\n path,\n\n // The cache for the result of a certain checking\n cache\n ) {\n if (path in cache) {\n return cache[path]\n }\n\n const parentPath = parentOf(path)\n\n // If the path contains a parent directory, check the parent first\n const parent = parentPath\n ? this._t(parentPath, cache)\n : UNDEFINED\n\n return cache[path] = parent && parent.ignored\n // > It is not possible to re-include a file if a parent directory of\n // > that file is excluded.\n ? parent\n : this._rules.test(path, MODE_IGNORE)\n }\n\n ignores (path) {\n return this._test(path, this._ignoreCache).ignored\n }\n\n createFilter () {\n return path => !this.ignores(path)\n }\n\n filter (paths) {\n return makeArray(paths).filter(this.createFilter())\n }\n\n // @returns {TestResult}\n test (path) {\n return this._test(path, this._testCache)\n }\n}\n\nconst factory = options => new Ignore(options)\n\nconst isPathValid = path =>\n checkPath(path && checkPath.convert(path), path, RETURN_FALSE)\n\n/* istanbul ignore next */\nconst setupWindows = () => {\n /* eslint no-control-regex: \"off\" */\n const makePosix = str => /^\\\\\\\\\\?\\\\/.test(str)\n || /[\"<>|\\u0000-\\u001F]+/u.test(str)\n ? str\n : str.replace(/\\\\/g, '/')\n\n checkPath.convert = makePosix\n\n // 'C:\\\\foo' <- 'C:\\\\foo' has been converted to 'C:/'\n // 'd:\\\\foo'\n const REGEX_TEST_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\\//i\n checkPath.isNotRelative = path =>\n REGEX_TEST_WINDOWS_PATH_ABSOLUTE.test(path)\n || isNotRelative(path)\n}\n\n\n// Windows\n// --------------------------------------------------------------\n/* istanbul ignore next */\nif (\n // Detect `process` so that it can run in browsers.\n typeof process !== 'undefined'\n && process.platform === 'win32'\n) {\n setupWindows()\n}\n\n// COMMONJS_EXPORTS ////////////////////////////////////////////////////////////\n\nmodule.exports = factory\n\n// Although it is an anti-pattern,\n// it is still widely misused by a lot of libraries in github\n// Ref: https://github.com/search?q=ignore.default%28%29&type=code\nfactory.default = factory\n\nmodule.exports.isPathValid = isPathValid\n\n// For testing purposes\ndefine(module.exports, Symbol.for('setupWindows'), setupWindows)\n","import type { CheckResult, PermissionHandler, Rule } from \"../types.ts\"\n\nimport { normPath, prettyPath } from \"@zaly/shared\"\nimport ignore from \"ignore\"\nimport { dirname, isAbsolute, relative } from \"pathe\"\n\n/**\n * Handler for `Rule<\"read\" | \"write\">` — one impl serves both scopes\n * because they share the same matcher and the same workspace state.\n *\n * Algorithm:\n * 1. Normalize candidate to an absolute path.\n * 2. Sensitive-file check (env, ssh keys, credentials) → deny.\n * 3. Find the longest-prefix workspace containing the path. None →\n * ask, with a `kind: \"workspace\"` suggestion for the containing\n * directory.\n * 4. Inside a workspace: resolve the first matching rule against the\n * workspace-relative path. Earlier rules win.\n * 5. Default when no rule matches but the path is inside a workspace:\n * `allow` for reads (workspace = trust signal), `ask` for writes\n * (mutating ops escalate by default; users add `Write(...)` rules\n * to whitelist).\n *\n * Pattern grammar (per Claude-Code conventions):\n * //abs/path absolute filesystem path\n * ~/path path under home directory\n * /path or path workspace-relative (passed through to gitignore)\n */\nexport const fileHandler: PermissionHandler<\"read\" | \"write\"> = {\n validate(input, ctx): CheckResult {\n const abs = normPath(ctx.cwd, input)\n\n if (isSensitiveFile(abs)) {\n return { reason: `${abs}: sensitive file`, verdict: \"deny\" }\n }\n\n const ws = longestWorkspace(abs, ctx.workspaces)\n const inWorkspace = ws !== undefined\n\n // Inside-workspace + path === root: the workspace itself (e.g. `find .`\n // resolved to cwd). Workspace containment alone is enough to allow.\n if (inWorkspace && abs === ws) return { verdict: \"allow\" }\n\n // Outside any workspace, fall through to rule matching with `/` as\n // synthetic root. Lets blanket rules like `read(*)` (yolo preset)\n // override the default \"ask outside workspace\" verdict, while\n // narrower presets keep the safer default.\n const base = ws ?? \"/\"\n const rel = relative(base, abs)\n\n const verb = ctx.scope === \"read\" ? \"reading\" : \"writing\"\n\n const rule = resolveRule(base, rel, ctx.rules)\n if (rule?.policy === \"deny\") return { reason: `${abs}: denied by rule`, verdict: \"deny\" }\n if (rule?.policy === \"ask\") {\n return {\n ask: `Allow ${verb} ${prettyPath(abs)}?`,\n reason: `${abs}: rule requires confirmation`,\n suggestions: [{ kind: \"rule\", pattern: `/${rel}`, scope: ctx.scope }],\n verdict: \"ask\",\n }\n }\n if (rule?.policy === \"allow\") return { verdict: \"allow\" }\n\n // No rule matched. Defaults differ by location:\n // - Inside a workspace: reads ride on workspace trust → allow;\n // writes escalate → ask.\n // - Outside any workspace: always ask, and surface a\n // workspace-add suggestion so the user can promote the parent\n // dir without composing a rule by hand.\n if (!inWorkspace) {\n const parent = dirname(abs)\n return {\n ask: `Allow ${verb} ${prettyPath(abs)}? (not in any workspace)`,\n reason: `${abs}: outside any workspace`,\n suggestions: [\n { description: `add ${parent} as workspace`, kind: \"workspace\", path: parent },\n ],\n verdict: \"ask\",\n }\n }\n if (ctx.scope === \"read\") return { verdict: \"allow\" }\n return {\n ask: `Allow ${verb} ${prettyPath(abs)}?`,\n reason: `${abs}: write requires confirmation`,\n suggestions: [{ kind: \"rule\", pattern: `/${rel}`, scope: \"write\" }],\n verdict: \"ask\",\n }\n },\n}\n\n/** True if `path` looks like a credentials/keys file we shouldn't\n * expose to the model by default. Conservative — false positives are\n * fine here, and users can override via `allow` rules. */\nexport function isSensitiveFile(path: string): boolean {\n return SENSITIVE_PATTERNS.some((re) => re.test(path))\n}\n\n/** Common locations for credentials, keys, and other sensitive data.\n * Matched against the path string directly — covers both absolute and\n * relative inputs. Add to this list as new gotchas surface. */\nconst SENSITIVE_PATTERNS: RegExp[] = [\n /(?:^|\\/)\\.env(?:\\.|$)/, // .env, .env.local, .env.production, ...\n /(?:^|\\/)\\.git\\/(?!hooks\\/)/, // .git/* but not hooks (commonly inspected)\n /(?:^|\\/)\\.ssh\\//, // ssh keys + config\n /(?:^|\\/)\\.aws\\/credentials/,\n /(?:^|\\/)\\.netrc$/,\n /(?:^|\\/)id_(?:rsa|dsa|ed25519|ecdsa)(?:\\.pub)?$/,\n /(?:^|\\/)\\.npmrc$/, // can hold auth tokens\n /(?:^|\\/)\\.pypirc$/,\n /(?:^|\\/)secrets?\\//,\n /(?:^|\\/)credentials?(?:\\.|\\/)/,\n]\n\n/** Longest-prefix match against the workspace list — returns the\n * containing workspace's absolute path, or undefined if none contain\n * the candidate. Workspaces arrive pre-normalized from the manager. */\nfunction longestWorkspace(abs: string, workspaces: readonly string[]): string | undefined {\n let best: string | undefined\n for (const root of workspaces) {\n if (abs === root || abs.startsWith(root.endsWith(\"/\") ? root : `${root}/`)) {\n if (best === undefined || root.length > best.length) best = root\n }\n }\n return best\n}\n\n/** Resolve the first matching rule.\n * Patterns get normalized (`//abs`, `~/`, `/rel`, `rel`) into\n * workspace-rooted gitignore syntax; patterns that resolve outside the\n * candidate's workspace are dropped (they don't apply here). */\nfunction resolveRule(\n workspace: string,\n rel: string,\n rules: readonly Rule<\"read\" | \"write\">[]\n): Rule<\"read\" | \"write\"> | undefined {\n if (rel === \"\") return undefined\n for (const rule of rules) {\n const norm = normalizePattern(rule.pattern, workspace)\n if (norm === undefined) continue\n try {\n if (ignore().add(norm).ignores(rel)) return rule\n } catch {\n // Skip invalid rels.\n }\n }\n}\n\nfunction normalizePattern(pattern: string, workspace: string): string | undefined {\n if (pattern.startsWith(\"//\")) {\n return relativizeToWorkspace(pattern.slice(1), workspace)\n }\n if (pattern.startsWith(\"~/\")) {\n return relativizeToWorkspace(normPath(pattern), workspace)\n }\n // /pattern or pattern → already workspace-relative gitignore syntax.\n return pattern\n}\n\nfunction relativizeToWorkspace(absPattern: string, workspace: string): string | undefined {\n const rel = relative(workspace, absPattern)\n if (rel === \"\" || rel.startsWith(\"..\") || isAbsolute(rel)) return undefined\n return `/${rel}`\n}\n","import type { CheckResult, PermissionHandler, Rule } from \"../types.ts\"\n\nimport ignore from \"ignore\"\n\n/**\n * Generic tool-scope handler.\n *\n * Used by `Tasks` to gate every tool dispatch on the tool name, and\n * available to tools themselves for richer checks (e.g. fetch passing\n * `fetch:example.com` so users can ask-for-domain).\n *\n * Pattern grammar is gitignore-style — reuses the `ignore` package so\n * the syntax matches `read` / `write` patterns. Common shapes:\n *\n * \"tool\" → bare scope; matches every input (default-allow)\n * \"tool(bash)\" → exact match for `\"bash\"`\n * \"tool(fetch:*)\" → glob match `\"fetch:...\"`\n * \"tool(task_*)\" → glob match `\"task_...\"`\n *\n * Resolution is first-match-wins. Default verdict when no rule matches is\n * `allow` — an unconfigured `tool` scope should not surprise users by\n * gating ordinary tool calls.\n */\nexport const toolHandler: PermissionHandler<\"tool\"> = {\n validate(input, ctx): CheckResult {\n const rule = resolveRule(input, ctx.rules)\n if (rule?.policy === \"deny\") {\n return { reason: `tool ${input}: denied by rule`, verdict: \"deny\" }\n }\n if (rule?.policy === \"ask\") {\n return {\n ask: `Allow tool ${input}?`,\n reason: `tool ${input}: rule requires confirmation`,\n suggestions: [{ kind: \"rule\", pattern: input, scope: \"tool\" }],\n verdict: \"ask\",\n }\n }\n return { verdict: \"allow\" }\n },\n}\n\nfunction resolveRule(input: string, rules: readonly Rule<\"tool\">[]): Rule<\"tool\"> | undefined {\n for (const rule of rules) {\n if (ignore().add(rule.pattern).ignores(input)) return rule\n }\n}\n","import type { PermissionHandler } from \"../types.ts\"\n\nimport { createRegistry } from \"@zaly/shared/registry\"\nimport { bashHandler } from \"./bash.ts\"\nimport { fileHandler } from \"./files.ts\"\nimport { toolHandler } from \"./tool.ts\"\n\nexport type HandlerLoader = () => PermissionHandler<string>\n\nconst builtin = {\n bash: () => bashHandler,\n read: () => fileHandler,\n tool: () => toolHandler,\n write: () => fileHandler,\n} as const satisfies Record<string, HandlerLoader>\n\n/** Open registry of permission scopes — declaration-merge to add your\n * own. The keys give `ctx.need(\"…\", input)` typed autocomplete and\n * catch typos at compile time. The value carries the *input* type for\n * that scope (almost always `string` — files take paths, bash takes\n * commands, the generic `tool` scope takes the tool name).\n *\n * Built-ins:\n * - `bash` → command string\n * - `read` → absolute path\n * - `write` → absolute path\n * - `tool` → tool name (or richer `name:arg` shape per tool)\n *\n * Add your own scope:\n *\n * ```ts\n * declare module \"@zaly/agent\" {\n * interface PermissionScopes {\n * fetch: string // expects a domain (or \"*\" for any)\n * }\n * }\n * ```\n *\n * Then `ctx.need(\"fetch\", domain)` is typed end-to-end. You still need\n * to register a runtime handler via `handlerRegistry.register(\"fetch\", …)`\n * — this interface is only the type-side declaration.\n */\nexport interface PermissionScopes {\n bash: string\n read: string\n tool: string\n write: string\n}\n\nexport type BuiltinScope = keyof typeof builtin\nexport type PermissionScope = keyof PermissionScopes\nexport type AnyScope = PermissionScope | (string & {})\n\nexport const handlerRegistry = createRegistry<HandlerLoader>(\"scope\").from(builtin)\n"],"ignoreList":[1],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,MAAa,cAAyC,EACpD,SAAS,OAAO,KAAkB;CAChC,MAAM,SAAS,UAAU,KAAK;CAC9B,IAAI,CAAC,OAAO,IAAI;EACd,IAAI;GAAC;GAAQ;GAAQ;EAAO,CAAC,CAAC,OAAO,UAAU,IAAI,YAAY,KAAK,CAAC,GACnE,OAAO,EAAE,SAAS,QAAQ;EAE5B,OAAO;GACL,KAAK,6BAA6B,OAAO,OAAO;GAChD,QAAQ,OAAO;GACf,SAAS;EACX;CACF;CAEA,IAAI,UAAmB;CACvB,IAAI;CACJ,MAAM,cAA4B,CAAC;CAEnC,KAAK,MAAM,OAAO,OAAO,UAAU;EAIjC,MAAM,aAAa,aAAa,IAAI,OAAO,GAAG,KAAK;EACnD,IAAI,IAAI,mBAAmB,eAAe,SACxC,OAAO;GACL,KAAK,mCAAmC,IAAI,IAAI;GAChD,QAAQ;GACR,SAAS;EACX;EAEF,MAAM,OAAO,MAAM,IAAI;EACvB,IAAI,MAAM,SAAS,IAAI,IAAI,KAAK,eAAe,SAC7C,OAAO;GACL,KAAK,yBAAyB,IAAI,IAAI;GACtC,QAAQ,GAAG,IAAI,IAAI;GACnB,SAAS;EACX;EAGF,IAAI,aAAsB;EAC1B,IAAI,YACF,eAAe,UAAU,KAAA,IAAY,YAAY,IAAI,IAAI,MAAM;EACjE,IAAI,eAAe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;;;;;;;;;;;;;;;;;;AC5IA,MAAa,cAAyC,EACpD,SAAS,OAAO,KAAkB;CAChC,MAAM,OAAO,YAAY,OAAO,IAAI,KAAK;CACzC,IAAI,MAAM,WAAW,QACnB,OAAO;EAAE,QAAQ,QAAQ,MAAM;EAAmB,SAAS;CAAO;CAEpE,IAAI,MAAM,WAAW,OACnB,OAAO;EACL,KAAK,cAAc,MAAM;EACzB,QAAQ,QAAQ,MAAM;EACtB,aAAa,CAAC;GAAE,MAAM;GAAQ,SAAS;GAAO,OAAO;EAAO,CAAC;EAC7D,SAAS;CACX;CAEF,OAAO,EAAE,SAAS,QAAQ;AAC5B,EACF;AAEA,SAAS,YAAY,OAAe,OAA0D;CAC5F,KAAK,MAAM,QAAQ,OACjB,KAAA,GAAIC,cAAAA,QAAAA,CAAO,CAAC,CAAC,IAAI,KAAK,OAAO,CAAC,CAAC,QAAQ,KAAK,GAAG,OAAO;AAE1D;ACQA,MAAa,kBAAkB,eAA8B,OAAO,CAAC,CAAC,KAAK;CA3CzE,YAAY;CACZ,YAAY;CACZ,YAAY;CACZ,aAAa;AAwC4D,CAAO"}
|
|
1
|
+
{"version":3,"file":"registry-7mJQhyBA.mjs","names":["resolveRule","ignore","ignore"],"sources":["../src/permissions/handlers/bash.ts","../../../node_modules/.bun/ignore@7.0.14/node_modules/ignore/index.js","../src/permissions/handlers/files.ts","../src/permissions/handlers/tool.ts","../src/permissions/handlers/registry.ts"],"sourcesContent":["import type { Segment } from \"../../utils/bash/parser.ts\"\nimport type { CheckResult, PermissionHandler, Rule, Suggestion, Verdict } from \"../types.ts\"\n\nimport { parseBash } from \"../../utils/bash/parser.ts\"\nimport { TOOLS } from \"../../utils/bash/tools.ts\"\n\n/**\n * Handler for `Rule<\"bash\">` — evaluates a bash command line against\n * pattern rules, then delegates each segment's inferred and explicit\n * file paths to the file handler via `ctx.validate(\"read\"|\"write\", …)`.\n *\n * Composition keeps file-rule logic in one place: the bash handler\n * doesn't know about workspaces, sensitive files, or path-pattern\n * matching — it just asks the registered handler for those scopes.\n *\n * Sources of file paths per segment:\n * - `seg.reads` / `seg.writes` — explicit `<` / `>` / `>>` redirects\n * extracted by the parser.\n * - `TOOLS[cmd].reads/writes(args)` — inferred from built-in tool\n * specs (e.g. `cat foo.txt` reads `foo.txt`, `tee out` writes `out`).\n *\n * Suggestions and reasons from inner `validate` calls bubble up so the\n * prompt UI can offer \"allow `Bash(cat:*)`\" alongside \"add ~/Documents\n * as workspace\" in a single ask.\n */\nexport const bashHandler: PermissionHandler<\"bash\"> = {\n validate(input, ctx): CheckResult {\n const parsed = parseBash(input)\n if (!parsed.ok) {\n if ([\"bash\", \"read\", \"write\"].every((scope) => ctx.allowsAll?.(scope))) {\n return { verdict: \"allow\" }\n }\n return {\n ask: `Allow this bash command? (${parsed.reason})`,\n reason: parsed.reason,\n verdict: \"ask\",\n }\n }\n\n let verdict: Verdict = \"allow\"\n let reason: string | undefined\n const suggestions: Suggestion[] = []\n\n for (const seg of parsed.segments) {\n // Bash rule match for the command itself. Resolve this before the\n // conservative safety checks so explicit allow-all presets like yolo can\n // mean exactly that instead of degrading to an unimplemented ask prompt.\n const cmdVerdict = resolveRules(ctx.rules, seg) ?? \"ask\"\n if (seg.hasCommandSubst && cmdVerdict !== \"allow\") {\n return {\n ask: `Allow command substitution in \\`${seg.cmd}\\`?`,\n reason: \"command substitution not allowed\",\n verdict: \"ask\",\n }\n }\n const spec = TOOLS[seg.cmd]\n if (spec?.unsafe?.(seg.args) && cmdVerdict !== \"allow\") {\n return {\n ask: `Allow invocation of \\`${seg.cmd}\\`? (unsafe)`,\n reason: `${seg.cmd}: invocation mode not safely modelled`,\n verdict: \"ask\",\n }\n }\n\n let segVerdict: Verdict = cmdVerdict\n let segReason: string | undefined =\n cmdVerdict === \"allow\" ? undefined : `segment \"${seg.cmd}\" → ${cmdVerdict}`\n if (cmdVerdict === \"ask\") {\n suggestions.push({\n kind: \"rule\",\n pattern: seg.args.length > 0 ? `${seg.cmd}:*` : seg.cmd,\n scope: \"bash\",\n })\n }\n\n // Delegate file paths to the file handler. Reads first, then\n // writes; both contribute to this segment's verdict via combine.\n const reads = [...(spec?.reads?.(seg.args) ?? []), ...seg.reads]\n const writes = [...(spec?.writes?.(seg.args) ?? []), ...seg.writes.map((w) => w.path)]\n\n for (const path of reads) {\n if (seg.dyn?.has(path) && !ctx.allowsAll?.(\"read\")) {\n segVerdict = combine(segVerdict, \"ask\")\n segReason ??= `${seg.cmd}: read ${path}: dynamic path`\n suggestions.push({\n kind: \"rule\",\n pattern: `${seg.cmd}:*`,\n scope: \"bash\",\n })\n continue\n }\n const r = ctx.validate(\"read\", path)\n segVerdict = combine(segVerdict, r.verdict)\n if (r.verdict !== \"allow\") {\n segReason ??= `${seg.cmd}: read ${path}: ${r.reason}`\n if (r.suggestions) suggestions.push(...r.suggestions)\n }\n if (segVerdict === \"deny\") break\n }\n if (segVerdict !== \"deny\") {\n for (const path of writes) {\n if (seg.dyn?.has(path) && !ctx.allowsAll?.(\"write\")) {\n segVerdict = combine(segVerdict, \"ask\")\n segReason ??= `${seg.cmd}: write ${path}: dynamic path`\n suggestions.push({\n kind: \"rule\",\n pattern: `${seg.cmd}:*`,\n scope: \"bash\",\n })\n continue\n }\n const w = ctx.validate(\"write\", path)\n segVerdict = combine(segVerdict, w.verdict)\n if (w.verdict !== \"allow\") {\n segReason ??= `${seg.cmd}: write ${path}: ${w.reason}`\n if (w.suggestions) suggestions.push(...w.suggestions)\n }\n if (segVerdict === \"deny\") break\n }\n }\n\n verdict = combine(verdict, segVerdict)\n if (verdict !== \"allow\" && reason === undefined) reason = segReason\n if (verdict === \"deny\") break\n }\n\n return verdict === \"allow\"\n ? { verdict: \"allow\" }\n : {\n ask: `Allow this bash command?`,\n reason: reason ?? \"no rule matched\",\n suggestions: suggestions.length > 0 ? suggestions : undefined,\n verdict,\n }\n },\n}\n\n// ── Pattern matching ─────────────────────────────────────────────────────\n\n/** A command-pattern rule.\n *\n * Pattern syntax:\n * \"cmd\" → cmd alone, no args\n * \"cmd:*\" → cmd with any args (trailing wildcard)\n * \"cmd a\" → cmd with arg \"a\", no other args\n * \"cmd a:*\" → cmd with arg \"a\" plus any others\n * \"cmd a b\" → cmd with exact args [a, b]\n * \"cmd --flag*\" → cmd with arg starting with \"--flag\" (per-arg prefix)\n * \"bun test:node:*\" → cmd \"bun\", arg \"test:node\", any others\n *\n * Whitespace separates the cmd from its args, and args from each\n * other. The `:` character is only meaningful as the trailing `:*`\n * wildcard suffix — anywhere else (including inside an arg like\n * `test:node`) it's a literal character. */\n\ninterface ParsedPattern {\n cmd: string\n /** Arg-position match tokens. Each may end with `*` for prefix match. */\n parts: string[]\n /** Set when the pattern ends with `:*`, allowing arbitrary further args. */\n trailingWildcard: boolean\n}\n\n/** Combine two verdicts: deny dominates, ask beats allow. */\nfunction combine(a: Verdict, b: Verdict): Verdict {\n if (a === \"deny\" || b === \"deny\") return \"deny\"\n if (a === \"ask\" || b === \"ask\") return \"ask\"\n return \"allow\"\n}\n\nconst patternCache = new Map<string, ParsedPattern>()\n\nfunction parsePattern(pattern: string): ParsedPattern {\n const cached = patternCache.get(pattern)\n if (cached) return cached\n\n let body = pattern.trim()\n let trailingWildcard = false\n if (body.endsWith(\":*\")) {\n trailingWildcard = true\n body = body.slice(0, -2)\n }\n\n const tokens = body.split(/\\s+/).filter((s) => s.length > 0)\n const cmd = tokens[0] ?? \"\"\n const result: ParsedPattern = {\n cmd,\n parts: tokens.slice(1),\n trailingWildcard,\n }\n patternCache.set(pattern, result)\n return result\n}\n\nfunction matchPart(part: string, value: string): boolean {\n if (part.endsWith(\"*\")) {\n return value.startsWith(part.slice(0, -1))\n }\n return part === value\n}\n\n/** Test whether a parsed segment matches a rule pattern. */\nexport function matchRule(rule: Rule, seg: Segment): boolean {\n const p = parsePattern(rule.pattern)\n // Bare `*` (e.g. from a `Bash` rule with no parens) matches any command.\n if (p.cmd === \"*\" && p.parts.length === 0) return true\n if (p.cmd !== seg.cmd) return false\n if (seg.args.length < p.parts.length) return false\n for (let i = 0; i < p.parts.length; i++) {\n if (!matchPart(p.parts[i], seg.args[i])) return false\n }\n if (p.trailingWildcard) return true\n return seg.args.length === p.parts.length\n}\n\n/** First-match-wins resolution. Returns `undefined` if no rule matches. */\nfunction resolveRules(rules: readonly Rule[], seg: Segment): Verdict | undefined {\n for (const r of rules) {\n if (matchRule(r, seg)) return r.policy\n }\n return undefined\n}\n","// A simple implementation of make-array\nfunction makeArray (subject) {\n return Array.isArray(subject)\n ? subject\n : [subject]\n}\n\nconst UNDEFINED = undefined\nconst EMPTY = ''\nconst SPACE = ' '\nconst ESCAPE = '\\\\'\n\n// The characters that carry a meaning of their own inside a regular\n// expression, so a literal one has to be escaped before it is emitted.\nconst REGEX_LITERAL_SPECIAL = /[.*+?()[\\]{}^$|\\\\/]/\nconst BOM = '\\uFEFF'\nconst REGEX_INVALID_TRAILING_BACKSLASH = /(?:[^\\\\]|^)\\\\$/\n// A run of two or more asterisks is a globstar (#175)\nconst REGEX_ANCHORED_GLOBSTAR = /^\\/\\*{2,}$/\nconst REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\\\!/\nconst REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\\\#/\nconst REGEX_SPLITALL_CRLF = /\\r?\\n/g\n\n// Invalid:\n// - /foo,\n// - ./foo,\n// - ../foo,\n// - .\n// - ..\n// Valid:\n// - .foo\nconst DOUBLE_SLASH = '//'\nconst SLASH_CODE = 47\nconst DOT_CODE = 46\n\n\nconst SLASH = '/'\n\n// Do not use ternary expression here, since \"istanbul ignore next\" is buggy\nlet TMP_KEY_IGNORE = 'node-ignore'\n/* istanbul ignore else */\nif (typeof Symbol !== 'undefined') {\n TMP_KEY_IGNORE = Symbol.for('node-ignore')\n}\nconst KEY_IGNORE = TMP_KEY_IGNORE\n\nconst define = (object, key, value) => {\n Object.defineProperty(object, key, {value})\n return value\n}\n\nconst RETURN_FALSE = () => false\n\n// > The range notation, e.g. [a-zA-Z],\n// > can be used to match one of the characters in a range.\n//\n// gitignore(5) defers to fnmatch(3) for this, and git implements it in\n// `wildmatch.c`. A bracket expression has a sub-grammar of its own, which\n// is neither the surrounding pattern grammar nor the JavaScript one:\n//\n// - a `]` right after `[` or `[!` is a literal member, not the terminator\n// - `[:alpha:]` names one of twelve POSIX classes\n// - `\\` escapes the next member, `]` included\n// - `*`, `?` and `.` are plain literal members\n// - an unterminated expression makes the whole pattern match nothing\n//\n// which means the expression can not be located -- let alone translated -- by\n// a regular expression. It is scanned out of the pattern before the\n// replacers below run, and put back once they are done, so that neither the\n// metacharacter escaper nor the `?` / `*` replacers ever see its body.\n\n// git classifies with its own ASCII-only ctype macros (`wildmatch.c`), never\n// with the C library ones, so these must not be mapped onto `\\d` / `\\w` /\n// `\\s`, which are wider. `/` is left out of every expansion, because a\n// bracket expression never matches a path separator.\nconst POSIX_CLASSES = {\n alnum: '0-9A-Za-z',\n alpha: 'A-Za-z',\n blank: ' \\\\t',\n cntrl: '\\\\x00-\\\\x1f\\\\x7f',\n digit: '0-9',\n graph: '!-.0-~',\n lower: 'a-z',\n print: ' -.0-~',\n punct: '!-.:-@\\\\[-`{-~',\n // git's `sane-ctype.h` classifies \\v and \\f as control, not space,\n // unlike C's `isspace`\n space: ' \\\\t\\\\n\\\\r',\n upper: 'A-Z',\n xdigit: '0-9A-Fa-f'\n}\n\nconst CLASS_MEMBERS_TO_ESCAPE = '\\\\]^-['\n\nconst escapeMember = char => CLASS_MEMBERS_TO_ESCAPE.indexOf(char) < 0\n ? char\n : ESCAPE + char\n\n// > if (matched == negated || ((flags & WM_PATHNAME) && text_ch == '/'))\n// > return WM_ABORT_TO_STARSTAR; (git, `wildmatch.c`)\n// A bracket expression never matches a path separator, whatever its members\n// say, so a negated class gets `/` as one more excluded character, while a\n// plain one -- where a literal member or a range could still let `/` in --\n// is guarded with a lookahead, `/` being impossible to subtract from a\n// JavaScript character class.\nconst NON_SLASH = '(?!\\\\/)'\n\nconst classSource = (negated, body) => {\n if (negated) {\n return `[^\\\\/${body}]`\n }\n\n const source = `[${body}]`\n\n return new RegExp(source).test('/')\n ? NON_SLASH + source\n : source\n}\n\n// Scan the bracket expression that starts at `pattern[start] === '['`,\n// mirroring the member loop of git's `wildmatch.c`.\n// @returns {{end: number, source: string} | null} `null` if the expression is\n// never terminated, which makes the whole pattern match nothing.\nconst scanBracket = (pattern, start) => {\n const {length} = pattern\n let index = start + 1\n let negated = EMPTY\n\n const lead = pattern[index]\n if (lead === '!' || lead === '^') {\n negated = '^'\n index ++\n }\n\n let body = EMPTY\n\n // The member a `-` could start a range from, or EMPTY when the previous\n // member can not open one (start of the body, or a range / POSIX class\n // that has just closed)\n let prev = EMPTY\n\n // git scans the members with a do-while, so the first one is consumed\n // unconditionally. That is the whole reason a leading `]` is a member\n // and not the terminator.\n for (;;) {\n const char = pattern[index]\n\n if (char === UNDEFINED) {\n return null\n }\n\n if (char === ESCAPE) {\n const escaped = pattern[index + 1]\n if (escaped === UNDEFINED) {\n return null\n }\n body += escapeMember(escaped)\n prev = escaped\n index ++\n } else if (\n char === '-'\n && prev\n && index + 1 < length\n && pattern[index + 1] !== ']'\n ) {\n index ++\n let to = pattern[index]\n if (to === ESCAPE) {\n // A pattern can not end on a lone backslash -- `checkPattern` has\n // already thrown it away -- so there is an upper bound to read.\n to = pattern[index += 1]\n }\n // An out-of-order range matches nothing in git but is a syntax error in\n // JavaScript, so it is dropped. Its lower bound stays: git tests it\n // as a plain member before it ever looks at the `-`, so `[c-a]` does\n // match `c`.\n if (prev <= to) {\n body += `-${escapeMember(to)}`\n }\n prev = EMPTY\n } else if (char === '[' && pattern[index + 1] === ':') {\n const nameStart = index + 2\n let end = nameStart\n while (end < length && pattern[end] !== ']') {\n end ++\n }\n\n if (end === length) {\n return null\n }\n\n if (end > nameStart && pattern[end - 1] === ':') {\n const name = pattern.slice(nameStart, end - 1)\n\n // An unknown class name makes the whole pattern match nothing\n if (!Object.prototype.hasOwnProperty.call(POSIX_CLASSES, name)) {\n return null\n }\n\n body += POSIX_CLASSES[name]\n prev = EMPTY\n index = end\n } else {\n // No `:]` to close it, so the `[` is a plain member and scanning\n // resumes right after it.\n body += escapeMember('[')\n prev = '['\n index = nameStart - 2\n }\n } else {\n body += escapeMember(char)\n prev = char\n }\n\n index ++\n\n if (pattern[index] === ']') {\n return {\n end: index,\n source: classSource(negated, body)\n }\n }\n }\n}\n\n// An empty JavaScript class can never match, which is how a pattern that git\n// gives up on (`WM_ABORT_ALL`) is expressed here.\nconst NEVER_MATCH = '[]'\n\n// A NUL can appear in neither a `.gitignore` line nor a path, which makes it\n// the one safe placeholder character. A literal one in the pattern is\n// held aside all the same, so a collision is impossible by construction.\nconst PLACEHOLDER = '\\u0000'\nconst REGEX_RESTORE_PLACEHOLDER = new RegExp(\n `${PLACEHOLDER}(\\\\d+)${PLACEHOLDER}`, 'g'\n)\n\n// The one wildcard the chain does not expand for itself is a trailing `*`. How\n// it expands depends on the mode (`regex` vs `checkRegex`), so `_make` is\n// left to do it, and until then the pending wildcard travels as this marker.\n// That is what keeps it apart from a user-escaped literal `\\*`: the unescape\n// steps collapse the escaped one to the exact `\\*` a wildcard would leave\n// behind, so by the time `_make` runs the two are otherwise the same string\n// and a literal star gets wrongly rewritten into a wildcard. The marker is a\n// private-use character, and `extractBrackets` keeps one that came out of the\n// pattern apart from it, so the only marker `_make` ever turns back into a\n// real wildcard is the one this chain put there itself.\nconst TRAILING_WILDCARD = '\\uE000'\n\n// A trailing \"/**\" is deferred the same way, because `checkRegex` has to tell\n// it apart from a trailing \"/*\" (see `checkSourceOf`). For `.ignores()` it\n// still never matches the folder itself (#21).\nconst TRAILING_DOUBLESTAR = '\\uE001'\n\n// The three characters above mean something to the chain that builds the\n// source rather than to the path, so one that came out of the pattern is\n// held aside like a bracket expression instead of going straight out. Being\n// held is what makes it safe: the restore runs after the step that anchors\n// the source, so the character comes back in the middle of the source and\n// not at its end, which is the one place `_make` and `checkSourceOf` look\n// for a marker. Without it a pattern's own character lands where a pending\n// marker sits, and `_make` turns it into a real trailing wildcard.\n//\n// It is held as a one-member class rather than bare, in both of the branches\n// a reserved character can reach, so that the property can be\n// read off this function alone -- a reserved character never goes out on\n// its own -- rather than depending on where in the chain the restore\n// happens to run. In the expression built here `[x]` matches exactly what\n// `x` matches, none of the three being special to a regular expression or\n// inside a class, so no test can tell the two apart: the class is insurance,\n// and the paragraph above is the reason it is not needed.\nconst isReserved = char =>\n char === PLACEHOLDER\n || char === TRAILING_WILDCARD\n || char === TRAILING_DOUBLESTAR\n\n// Replace every bracket expression with a placeholder the replacers below\n// leave alone, and translate it separately.\nconst extractBrackets = pattern => {\n const sources = []\n const hold = source =>\n `${PLACEHOLDER}${sources.push(source) - 1}${PLACEHOLDER}`\n\n const {length} = pattern\n let out = EMPTY\n let index = 0\n\n while (index < length) {\n const char = pattern[index]\n\n if (char === ESCAPE) {\n // > Put a backslash (\"\\\") in front of ... a character to make it literal.\n // (gitignore(5) -> fnmatch(3))\n // A backslash quotes the next character, whatever it is, so `\\d` is a\n // literal `d`, not the regex digit class, and `\\?` is a literal `?`,\n // not a wildcard. Held aside as its literal here, the escape never\n // reaches the replacers below, which would otherwise let `\\d`, `\\b`,\n // `\\1`, `\\/` keep their regular-expression meaning, and would turn a\n // `\\?` into `[^\\/]`.\n //\n // Three escapes are still left for the chain: `\\*` (a literal star,\n // told apart from a wildcard by `TRAILING_WILDCARD` and the wildcard\n // replacers), `\\[` (a literal bracket, the one `[` the bracket\n // replacer still expects), and `\\ ` (a quoted space, which one pass\n // below rewrites in bulk -- holding each one aside instead costs more\n // on a pattern built out of them). A lone trailing backslash can reach\n // here after line-ending cleanup.\n //\n // A quoted backslash is not among them. The chain doubles every\n // backslash, then takes the doubling back out again, and a quoted one\n // standing next to a character the chain also escapes left the two\n // counts sharing a run, so one of the escapes was lost. Held here as\n // the literal it means, it never joins that run.\n const escaped = pattern[index + 1]\n\n if (\n escaped === UNDEFINED\n || escaped === SLASH && index + 2 === length\n ) {\n // Git removes a final directory slash before matching. An escape\n // without a character after that removal makes the pattern invalid.\n out += hold(NEVER_MATCH)\n } else if (\n escaped === '*'\n || escaped === '['\n || escaped === SPACE\n ) {\n out += pattern.slice(index, index + 2)\n } else {\n out += hold(\n REGEX_LITERAL_SPECIAL.test(escaped)\n ? ESCAPE + escaped\n : isReserved(escaped)\n ? `[${escaped}]`\n : escaped\n )\n }\n\n index += 2\n } else if (isReserved(char)) {\n out += hold(`[${char}]`)\n index ++\n } else if (char === '[') {\n const scanned = scanBracket(pattern, index)\n\n if (scanned === null) {\n // git gives up on the whole pattern (`WM_ABORT_ALL`), so whatever\n // follows can not make it match either.\n out += hold(NEVER_MATCH)\n index = length\n } else {\n out += hold(scanned.source)\n index = scanned.end + 1\n }\n } else {\n out += char\n index ++\n }\n }\n\n return {\n source: out,\n sources\n }\n}\n\n// A step of the chain below is normally a `[matcher, replacer]` pair handed\n// to `String.replace`. `DIRECT` marks the ones that are plain string work\n// instead, and take `(source, pattern)`.\n//\n// Anchoring the two ends is exactly that -- a test of one character and a\n// concatenation -- and putting it through the regular expression engine\n// cost a third of this chain for nothing: 167ns where 10ns does the same\n// job. The two are still steps in the same list, in the same places,\n// because their position in the order is part of what they mean.\nconst DIRECT = null\n\n// A separator at the beginning or in the middle of a pattern, as opposed to\n// one at the very end.\nconst REGEX_INNER_SLASH = /\\/(?!$)/\n\n// > If the pattern ends with a slash,\n// > it is removed for the purpose of the following description,\n// > but it would only find a match with a directory.\n// > In other words, foo/ will match a directory foo and paths underneath it,\n// > but will not match a regular file or a symbolic link foo\n// > (this is consistent with the way how pathspec works in general in Git).\n// '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`'\n// -> ignore-rules will not deal with it, because it costs extra `fs.stat` call\n// you could use option `mark: true` with `glob`\n\n// '`foo/`' should not continue with the '`..`'\n// The chain that turns one gitignore pattern into a regular expression\n// source, in order. A step is either\n//\n// [matcher, replacer] handed to `String.replace`\n// [matcher, replacer, required] the same, but skipped outright unless\n// `required` appears in the string, which\n// the matcher cannot match without\n// [DIRECT, transform] plain string work, taking (source, pattern)\n//\n// The `required` character is only ever a shortcut: finding it does not mean\n// the matcher will match, and not finding it means it cannot. It is there\n// because scanning for one character costs a fraction of running a matcher\n// that then finds nothing -- for the wildcard step, whose `[^\\\\]+`\n// backtracks its way through the whole string before giving up, 11ns\n// against 400ns.\nconst REPLACERS = [\n\n // Replace (\\ ) with ' '\n // Only a space: an escaped tab or other whitespace is already a literal by\n // the time it reaches here, and a bare tab must be left as one, not turned\n // into a space.\n // (\\ ) -> ' '\n // (\\\\ ) -> '\\\\ '\n // (\\\\\\ ) -> '\\\\ '\n [\n // A run of backslashes is taken whole, from its first one, so no match\n // ever starts again inside it -- `(\\\\+?) ` did, which made a long run\n // quadratic.\n /(\\\\+)( ?)/g,\n (_, run, space) => space\n ? run.slice(0, run.length - run.length % 2) + SPACE\n : run,\n ESCAPE + SPACE\n ],\n\n // git's wildmatch() reads a run of two or more asterisks as one globstar\n // whenever the run fills a path segment: it starts the pattern or follows\n // a `/`, and it ends the pattern or comes before a `/`. A run of two is\n // already `**`; a longer one is folded into `**` here, so the steps\n // below only ever have to know `**`.\n // `***/foo` -> `**/foo`, `a/***/b` -> `a/**/b`, `a/***` -> `a/**`\n // git also takes a run beside a literal prefix (`a***/b`) or beside an\n // escaped slash (`***\\/b`) as a globstar, and this does not; the README\n // lists both, under \"A run of asterisks\".\n [\n /(^|\\/)\\*{3,}(?=\\/|$)/g,\n (_, start) => `${start}**`,\n '*'\n ],\n\n // Escape metacharacters\n // which is written down by users but means special for regular expressions.\n\n // > There are 12 characters with special meanings:\n // > - the backslash \\,\n // > - the caret ^,\n // > - the dollar sign $,\n // > - the period or dot .,\n // > - the vertical bar or pipe symbol |,\n // > - the question mark ?,\n // > - the asterisk or star *,\n // > - the plus sign +,\n // > - the opening parenthesis (,\n // > - the closing parenthesis ),\n // > - and the opening square bracket [,\n // > - the opening curly brace {,\n // > These special characters are often called \"metacharacters\".\n [\n /[\\\\$.|*+(){^]/g,\n match => `\\\\${match}`\n ],\n\n [\n // > a question mark (?) matches a single character\n /(?!\\\\)\\?/g,\n () => '[^/]',\n '?'\n ],\n\n // leading slash\n [\n\n // > A leading slash matches the beginning of the pathname.\n // > For example, \"/*.c\" matches \"cat-file.c\" but not \"mozilla-sha1/sha1.c\".\n // A leading slash matches the beginning of the pathname\n /^\\//,\n () => '^',\n SLASH\n ],\n\n // replace special metacharacter slash after the leading slash\n [\n /\\//g,\n () => '\\\\/',\n SLASH\n ],\n\n [\n // > A leading \"**\" followed by a slash means match in all directories.\n // > For example, \"**/foo\" matches file or directory \"foo\" anywhere,\n // > the same as pattern \"foo\".\n // > \"**/foo/bar\" matches file or directory \"bar\" anywhere that is directly\n // > under directory \"foo\".\n // Notice that the '*'s have been replaced as '\\\\*'\n /^\\^*(?:\\\\\\*\\\\\\*\\\\\\/)+/,\n\n // '**/foo' <-> 'foo'\n () => '^(?:.*\\\\/)?',\n '*'\n ],\n\n // starting\n [\n // there will be no leading '/'\n // (which has been replaced by section \"leading slash\")\n // If starts with '**', adding a '^' to the regular expression also works\n DIRECT,\n (source, pattern) => {\n // Nothing to anchor to, or already anchored\n if (!source || source[0] === '^') {\n return source\n }\n\n // If has a slash `/` at the beginning or middle\n const anchor = !REGEX_INNER_SLASH.test(pattern)\n // > Prior to 2.22.1\n // > If the pattern does not contain a slash /,\n // > Git treats it as a shell glob pattern\n // Actually, if there is only a trailing slash,\n // git also treats it as a shell glob pattern\n\n // After 2.22.1 (compatible but clearer)\n // > If there is a separator at the beginning or middle (or both)\n // > of the pattern, then the pattern is relative to the directory\n // > level of the particular .gitignore file itself.\n // > Otherwise the pattern may also match at any level below\n // > the .gitignore level.\n ? '(?:^|\\\\/)'\n\n // > Otherwise, Git treats the pattern as a shell glob suitable for\n // > consumption by fnmatch(3)\n : '^'\n\n return anchor + source\n }\n ],\n\n // two globstars\n [\n // Use lookahead assertions so that we could match more than one `'/**'`\n /\\\\\\/\\\\\\*\\\\\\*(?=\\\\\\/|$)/g,\n\n // Zero, one or several directories\n // should not use '*', or it will be replaced by the next replacer\n\n // Check if it is not the last `'/**'`\n (_, index, str) => index + 6 < str.length\n\n // case: /**/ at the end of the pattern, i.e. a trailing `'/**/'`\n // > A trailing `\"/**/\"` (a trailing `\"/**\"` restricted to directories)\n // > matches everything inside, but it should not match the current\n // > folder itself, so it requires at least one directory segment.\n // 'a/**/' matches 'a/b/', 'a/x/y/' but not 'a/'\n ? str.slice(index + 6) === '\\\\/'\n ? '(?:\\\\/[^\\\\/]+)+'\n\n // case: /**/\n // > A slash followed by two consecutive asterisks then a slash matches\n // > zero or more directories.\n // > For example, \"a/**/b\" matches \"a/b\", \"a/x/b\", \"a/x/y/b\" and so on.\n // '/**/'\n : '(?:\\\\/[^\\\\/]+)*'\n\n // case: /**\n // > A trailing `\"/**\"` matches everything inside.\n\n // #21: everything inside but it should not include the current folder,\n // resolved by `_make`\n : `\\\\/${TRAILING_DOUBLESTAR}`,\n '*'\n ],\n\n // normal intermediate wildcards\n [\n // Never replace escaped '*'\n // ignore rule '\\*' will match the path '*'\n\n // 'abc.*/' -> go\n // 'abc.*' -> skip this rule,\n // coz trailing single wildcard will be handed by [trailing wildcard]\n /(^|[^\\\\]+)(\\\\\\*)+(?=.+)/g,\n\n // '*.js' matches '.js'\n // '*.js' doesn't match 'abc'\n (_, p1, p2) => {\n // 1.\n // > An asterisk \"*\" matches anything except a slash.\n // 2.\n // > Other consecutive asterisks are considered regular asterisks\n // > and will match according to the previous rules.\n const unescaped = p2.replace(/\\\\\\*/g, '[^\\\\/]*')\n return p1 + unescaped\n },\n '*'\n ],\n\n // trailing wildcard, held apart from a literal star\n [\n // The step above leaves a trailing `*` alone, so a single `\\*` is all that\n // can be left at the end here, and what stands in front of it says which\n // kind it is. A wildcard arrives as the escaper wrote it, `\\*` with\n // nothing before it; a literal arrives as the user's own escape, which\n // the escaper doubled, and then the star's own -- `\\\\` and then `\\*`.\n // There is no third case: every backslash still reaching the chain is\n // one `\\*`, `\\[` or `\\ ` carries itself, and each is followed by its\n // own character, so a longer run can never form. This runs while the\n // two are still distinct, before the unescape steps below collapse the\n // literal onto the very `\\*` a wildcard leaves behind.\n /(^|[^\\\\])((?:\\\\\\\\)*)\\\\\\*$/,\n\n (match, p1, p2) =>\n p2 === EMPTY\n // A real wildcard: carry it to `_make` as the marker, so the unescape\n // steps and the trailing-wildcard rewrite can never mistake it for a\n // literal `\\*` (nor the reverse).\n ? p1 + TRAILING_WILDCARD\n // A literal star: leave it exactly as it stands for the unescape steps.\n : match,\n '*'\n ],\n\n [\n // unescape, revert step 3 except for back slash\n // For example, if a user escape a '\\\\*',\n // after step 3, the result will be '\\\\\\\\\\\\*'\n /\\\\\\\\\\\\(?=[$.|*+(){^])/g,\n () => ESCAPE,\n ESCAPE + ESCAPE\n ],\n\n [\n // '\\\\\\\\' -> '\\\\'\n /\\\\\\\\/g,\n () => ESCAPE,\n ESCAPE + ESCAPE\n ],\n\n [\n // Every real bracket expression -- POSIX classes included -- has already\n // been held aside by `extractBrackets`, so the only `[` left in the\n // pattern is an escaped, literal one.\n\n // A backslash could only stand at the end of the range if it quoted the\n // `]`, and `\\]` is held aside long before this.\n /\\\\\\[([^\\]/]*?)($|\\])/g,\n\n // '\\\\[bar]' -> '\\\\\\\\[bar]'\n (match, range, close) => `\\\\[${range}${close}`,\n '['\n ],\n\n // ending\n [\n // 'js' will not match 'js.'\n // 'ab' will not match 'abc'\n DIRECT,\n\n // WTF!\n // https://git-scm.com/docs/gitignore\n // changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1)\n // which re-fixes #24, #38\n\n // > If there is a separator at the end of the pattern then the pattern\n // > will only match directories, otherwise the pattern can match both\n // > files and directories.\n\n // 'js*' will not match 'a.js'\n // 'js/' will not match 'a.js'\n // 'js' will match 'a.js' and 'a.js/'\n source => {\n const last = source[source.length - 1]\n\n // The pattern is empty, or ends in a pending marker `_make` owns --\n // the trailing wildcard, or a trailing \"/**\". A trailing `*` that is\n // not the marker is a literal star, which anchors like any other\n // final character.\n if (!last || last === TRAILING_WILDCARD || last === TRAILING_DOUBLESTAR) {\n return source\n }\n\n return last === SLASH\n // foo/ will not match 'foo'\n ? `${source}$`\n // foo matches 'foo' and 'foo/'\n : `${source}(?=$|\\\\/$)`\n }\n ]\n]\n\nconst REGEX_REPLACE_TRAILING_WILDCARD = /(^|\\\\\\/)?\\uE000$/\nconst MODE_IGNORE = 'regex'\nconst MODE_CHECK_IGNORE = 'checkRegex'\nconst UNDERSCORE = '_'\n\nconst replaceTrailingWildcard = (_, p1) => {\n const prefix = p1\n // '\\^':\n // '/*' does not match EMPTY\n // '/*' does not match everything\n\n // '\\\\\\/':\n // 'abc/*' does not match 'abc/'\n ? `${p1}[^/]+`\n\n // 'a*' matches 'a'\n // 'a*' matches 'aa'\n : '[^/]*'\n\n return `${prefix}(?=$|\\\\/$)`\n}\n\nconst REGEX_REPLACE_TRAILING_DOUBLESTAR = /\\uE001$/\n\n// 'abc/**' matches everything under 'abc', but not 'abc/' itself (#21)\nconst replaceTrailingDoublestar = () => '.+(?=$|\\\\/$)'\n\nconst WILDCARD = '[^\\\\/]*'\n\n// The fixed piece between the wildcard at `at` and the next wildcard of the\n// run: the tokens that separate them, joined as they appear in the source.\n// A run never holds two wildcards in a row, so there is always at least one\n// token.\nconst separatorAfter = (run, at) => {\n let separator = EMPTY\n\n for (let index = at + 1; index < run.length && !run[index].wildcard; index ++) {\n separator += run[index].single\n }\n\n return separator\n}\n\n// Where a run of non-slash wildcards is split by fixed pieces --\n// `[^/]*ab[^/]*cd...` -- the engine has many equivalent ways to lay the\n// input across the wildcards, and on input that does not match it works\n// through all of them, so the time grows with the number of wildcards\n// rather than the length of the path. Every wildcard but the last in such a\n// run can be pinned to stop where the piece after it begins, which leaves\n// one way to lay out the input and no rewinding, without changing which\n// paths match: the fixed pieces still bound the count, and the last\n// wildcard still absorbs the rest.\n//\n// A wildcard is pinned to the whole piece, never to the piece's first\n// character. The pin leaves no way back, so a wildcard that stopped at that\n// first character would hand over wherever the character happens to turn\n// up, including the places the rest of the piece cannot follow -- which is\n// how `f*o/*/*` came to miss `foo/b/c`, the first `o` of `foo` not being\n// the one the `o/` after it needs. Every token of a piece matches exactly\n// one character, so the first place the whole piece fits is the leftmost\n// place it can sit, and whatever is left over goes to the wildcards that\n// follow.\n//\n// The source is read one token at a time -- a wildcard, a single-character\n// piece (a literal, an escape, a class), or a parenthesised group or anchor\n// that ends the run -- so only a genuine wildcard is touched.\nconst pinWildcards = source => {\n if (source.indexOf(WILDCARD) < 0) {\n return source\n }\n\n const tokens = []\n const {length} = source\n let index = 0\n\n while (index < length) {\n const char = source[index]\n\n if (source.startsWith(WILDCARD, index)) {\n tokens.push({wildcard: true})\n index += WILDCARD.length\n } else if (char === '[') {\n let end = index + 1\n\n if (source[end] === '^') {\n end ++\n }\n\n if (source[end] === ']') {\n end ++\n }\n\n while (end < length && source[end] !== ']') {\n end += source[end] === ESCAPE\n ? 2\n : 1\n }\n\n end ++\n tokens.push({single: source.slice(index, end)})\n index = end\n } else if (char === ESCAPE) {\n tokens.push({single: source.slice(index, index + 2)})\n index += 2\n } else if (char === '(') {\n let depth = 0\n let end = index\n\n do {\n if (source[end] === ESCAPE) {\n end ++\n } else if (source[end] === '(') {\n depth ++\n } else if (source[end] === ')') {\n depth --\n }\n\n end ++\n } while (end < length && depth > 0)\n\n if ('*+?'.indexOf(source[end]) >= 0) {\n end ++\n }\n\n tokens.push({boundary: source.slice(index, end)})\n index = end\n } else if (char === '^' || char === '$') {\n tokens.push({boundary: char})\n index ++\n } else {\n tokens.push({single: char})\n index ++\n }\n }\n\n let out = EMPTY\n let run = []\n\n const flush = () => {\n let lastWildcard\n\n run.forEach((token, at) => {\n if (token.wildcard) {\n lastWildcard = at\n }\n })\n\n run.forEach((token, at) => {\n if (!token.wildcard) {\n out += token.single\n return\n }\n\n // Every wildcard but the last is pinned to the whole piece that\n // follows it, for the reason set out above this function. The last\n // one stays as it is and takes up the rest.\n out += at === lastWildcard\n ? WILDCARD\n : `(?:(?!${separatorAfter(run, at)})[^\\\\/])*`\n })\n\n run = []\n }\n\n tokens.forEach(token => {\n if (token.boundary === undefined) {\n run.push(token)\n return\n }\n\n flush()\n out += token.boundary\n })\n\n flush()\n\n return out\n}\n\n// @param {pattern}\nconst makeRegexPrefix = pattern => {\n // `/**` matches every path, as `**` does. The translation below only finds\n // a globstar beside a slash it keeps, and the leading one is turned into\n // an anchor, so `/**` would come out as `/*` and match one level only.\n // Here rather than in `createRule`, so that `checkSourceOf`, which\n // compiles `/**/` again without its trailing slash, gets it too.\n if (REGEX_ANCHORED_GLOBSTAR.test(pattern)) {\n pattern = '**'\n }\n\n const {source, sources} = extractBrackets(pattern)\n\n const replaced = REPLACERS.reduce(\n // A pass whose matcher finds nothing hands back the very string it was\n // given, so asking first costs a search and saves a rewrite. Ten of the\n // fifteen passes never fire for a typical .gitignore line, and between\n // them they were 45% of this chain.\n (prev, [matcher, replacer, required]) => {\n if (matcher === DIRECT) {\n return replacer(prev, pattern)\n }\n\n if (required !== UNDEFINED && prev.indexOf(required) < 0) {\n return prev\n }\n\n // A pass whose matcher finds nothing hands back the very string it was\n // given, so asking first costs a search and saves a rewrite.\n return matcher.test(prev)\n ? prev.replace(matcher, replacer.bind(pattern))\n : prev\n },\n source\n )\n\n // Most patterns hold no bracket expression at all, and then there is\n // nothing to put back.\n return sources.length\n ? replaced.replace(\n REGEX_RESTORE_PLACEHOLDER,\n (match, index) => sources[index]\n )\n : replaced\n}\n\n// `checkRegex` tests a path with a trailing slash, 'abc/', the way\n// `git check-ignore` matches that literal string once the directory itself\n// is known not to be excluded (see `checkIgnore`): a trailing '/' of the\n// pattern is dropped, a basename pattern sees an empty basename, and only a\n// pattern whose last segment is a pending wildcard can match what is left\n// after the final slash -- 'abc/*' and 'abc/**' match 'abc/', and 'abc/**'\n// also matches 'abc/d/' (#77, #169).\nconst checkSourceOf = (body, prefix) => {\n if (body[body.length - 1] === SLASH) {\n prefix = makeRegexPrefix(body.slice(0, - 1))\n }\n\n const head = prefix.slice(0, - 1)\n const last = prefix[prefix.length - 1]\n\n return last === TRAILING_WILDCARD\n ? `${head}$`\n : last === TRAILING_DOUBLESTAR\n ? `${head}.*$`\n : NEVER_MATCH\n}\n\n// A trailing slash does not stop a pattern being basename-only: it restricts\n// the match to a directory, it does not let the pattern reach across one.\n// Everything else a pattern can hold -- a wildcard, a character class, an\n// escape -- stays inside a single path segment too, so a pattern with no\n// separator in it can only ever describe the last one.\nconst matchesBasename = body => {\n const index = body.indexOf(SLASH)\n\n return index < 0 || index === body.length - 1\n}\n\n// The last segment of a path, keeping a trailing slash, because a pattern that\n// ends in one matches only a directory.\n// 'a/b/c.js' -> 'c.js'; 'a/b/' -> 'b/'; 'c.js' -> 'c.js' (no copy made)\nconst basenameOf = path => {\n const end = path.length - 1\n\n const index = path.lastIndexOf(\n SLASH,\n path[end] === SLASH\n ? end - 1\n : end\n )\n\n return index < 0\n ? path\n : path.slice(index + 1)\n}\n\n// The parent directory of a path, with its trailing separator, or EMPTY when\n// the path has none.\n// 'a/b/c' -> 'a/b/'; 'a/b/' -> 'a/'; 'a' -> EMPTY; 'a/' -> EMPTY\n//\n// A path holding an empty segment has to be taken apart, because its\n// ancestors are not prefixes of it: the parent of 'a//b' is 'a/', not\n// 'a//', and the parent of '/a/' is nothing at all. Both shapes reach here\n// -- 'a//b' is accepted outright, and `checkIgnore` does not put the path\n// it is given through the relative-path check.\n//\n// Every other path is a prefix of itself, and cutting one costs a fraction of\n// splitting it into an array and joining that back at every level: 73ns\n// against 207ns.\nconst parentOf = path => {\n if (\n path.charCodeAt(0) === SLASH_CODE\n || path.indexOf(DOUBLE_SLASH) >= 0\n ) {\n const slices = path.split(SLASH).filter(Boolean)\n\n slices.pop()\n\n return slices.length\n ? slices.join(SLASH) + SLASH\n : EMPTY\n }\n\n const end = path.length - 1\n\n // Look back from before a trailing separator, since that one belongs to the\n // path itself.\n //\n // A negative place to start would be a trap here: `lastIndexOf` clamps one\n // to 0 and searches there rather than reporting no match, so '/' would\n // come back as its own parent and the walk would never end. It cannot\n // happen -- that is the only path short enough to produce one, and the\n // test above has already sent it the other way.\n const cut = path.lastIndexOf(\n SLASH,\n path.charCodeAt(end) === SLASH_CODE\n ? end - 1\n : end\n )\n\n return cut < 0\n ? EMPTY\n : path.slice(0, cut + 1)\n}\n\nconst isString = subject => typeof subject === 'string'\n\n// Blank lines and comments are told by `createRule`, once the pattern is\n// normalized.\nconst checkPattern = pattern => pattern\n && isString(pattern)\n && !REGEX_INVALID_TRAILING_BACKSLASH.test(pattern)\n\nconst splitPattern = pattern => pattern\n.split(REGEX_SPLITALL_CRLF)\n.filter(Boolean)\n\nclass IgnoreRule {\n constructor (\n pattern,\n mark,\n body,\n ignoreCase,\n negative,\n prefix\n ) {\n this.pattern = pattern\n this.mark = mark\n this.negative = negative\n\n define(this, 'body', body)\n define(this, 'ignoreCase', ignoreCase)\n define(this, 'regexPrefix', prefix)\n }\n\n // Worked out on first use and kept behind an own property, the way `regex`\n // caches itself in `_regex`. Deciding it in the constructor instead would\n // add a fourth `defineProperty` to every rule ever built, which cost 4% of\n // every compile -- including the compiles of rules that are never matched\n // against anything.\n get _basenameOnly () {\n return define(this, '_basenameOnly', matchesBasename(this.body))\n }\n\n get regex () {\n const key = UNDERSCORE + MODE_IGNORE\n\n if (this[key]) {\n return this[key]\n }\n\n return this._make(MODE_IGNORE, key)\n }\n\n get checkRegex () {\n const key = UNDERSCORE + MODE_CHECK_IGNORE\n\n if (this[key]) {\n return this[key]\n }\n\n return this._make(MODE_CHECK_IGNORE, key)\n }\n\n _make (mode, key) {\n const str = pinWildcards(\n mode === MODE_IGNORE\n ? this.regexPrefix\n .replace(REGEX_REPLACE_TRAILING_WILDCARD, replaceTrailingWildcard)\n .replace(REGEX_REPLACE_TRAILING_DOUBLESTAR, replaceTrailingDoublestar)\n : checkSourceOf(this.body, this.regexPrefix)\n )\n\n const regex = this.ignoreCase\n ? new RegExp(str, 'i')\n : new RegExp(str)\n\n return define(this, key, regex)\n }\n}\n\nconst isLineEnd = char => char === '\\r' || char === '\\n'\n\n// Drop a line terminator, which can remain when patterns are passed as an\n// array, and then the trailing spaces. Git trims spaces only, and a space\n// escaped by an odd run of backslashes stays, unescaped, as the last one.\n// Scanned from the end: a regular expression can only try each start in\n// turn, which is quadratic over a long run of spaces or backslashes.\n// 'a ' -> 'a'; 'a\\ ' -> 'a '; 'a\\\\ ' -> 'a\\\\'; 'a\\t' -> 'a\\t'\nconst trimEnd = body => {\n let end = body.length\n\n while (end && isLineEnd(body[end - 1])) {\n end --\n }\n\n const lineEnd = end\n\n while (end && body[end - 1] === SPACE) {\n end --\n }\n\n if (end === lineEnd) {\n return body.slice(0, end)\n }\n\n let backslashes = 0\n\n while (backslashes < end && body[end - backslashes - 1] === ESCAPE) {\n backslashes ++\n }\n\n return backslashes % 2\n ? body.slice(0, end - 1) + SPACE\n : body.slice(0, end)\n}\n\nconst createRule = ({\n pattern,\n mark\n}, ignoreCase) => {\n // Git drops a BOM before it reads the first line, so before anything else.\n let body = pattern[0] === BOM\n ? pattern.slice(1)\n : pattern\n\n // > A line starting with # serves as a comment.\n if (body[0] === '#') {\n return\n }\n\n let negative = false\n\n // > An optional prefix \"!\" which negates the pattern;\n if (body[0] === '!') {\n negative = true\n body = body.slice(1)\n }\n\n // Normalize the body before checking which slashes anchor the pattern.\n // Otherwise `bar/ ` is mistaken for a pattern containing an inner slash.\n // Only a body ending in a space or a line terminator has anything to trim.\n const last = body[body.length - 1]\n\n if (last === SPACE || last === '\\r' || last === '\\n') {\n body = trimEnd(body)\n }\n\n // > A blank line matches no files, so it can serve as a separator for\n // > readability.\n // Nor does a lone \"!\", or anything else left empty here: an empty pattern\n // would compile to a regex matching every path.\n if (!body) {\n return\n }\n\n body = body\n // > Put a backslash (\"\\\") in front of the first \"!\" for patterns that\n // > begin with a literal \"!\", for example, `\"\\!important!.txt\"`.\n .replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, '!')\n // > Put a backslash (\"\\\") in front of the first hash for patterns that\n // > begin with a hash.\n .replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, '#')\n\n const regexPrefix = makeRegexPrefix(body)\n\n return new IgnoreRule(\n pattern,\n mark,\n body,\n ignoreCase,\n negative,\n regexPrefix\n )\n}\n\nclass RuleManager {\n constructor (ignoreCase) {\n this._ignoreCase = ignoreCase\n this._rules = []\n\n // How many of the rules git would tag `EXC_FLAG_NODIR`.\n //\n // The scan uses it to decide, once for the whole set, whether handing\n // those rules the basename is worth what it costs the others. The\n // shortcut saves a full-path scan on every rule it applies to and costs\n // a check on every rule it does not, so a set where almost nothing is\n // basename-only comes out behind -- a 955 pattern set with 44 of them\n // measured 19% slower with the shortcut always on.\n //\n // Deciding this by measurement rather than by meaning is safe: a\n // basename-only pattern gives the very same answer against the whole\n // path, it just takes longer to say so. The choice can only change how\n // fast the scan runs, never what it returns.\n this._basenameCount = 0\n }\n\n _add (pattern) {\n // #32\n if (pattern && pattern[KEY_IGNORE]) {\n this._rules = this._rules.concat(pattern._rules._rules)\n this._basenameCount += pattern._rules._basenameCount\n this._added = true\n return\n }\n\n if (isString(pattern)) {\n pattern = {\n pattern\n }\n }\n\n const rule = checkPattern(pattern.pattern)\n && createRule(pattern, this._ignoreCase)\n\n if (rule) {\n this._added = true\n this._rules.push(rule)\n\n // Deliberately not `rule._basenameOnly`: reading that would materialise\n // the rule's own copy, and the whole point of leaving it lazy is that\n // a rule which is compiled and never matched never pays for it.\n if (matchesBasename(rule.body)) {\n this._basenameCount ++\n }\n }\n }\n\n // @param {Array<string> | string | Ignore} pattern\n add (pattern) {\n this._added = false\n\n makeArray(\n isString(pattern)\n ? splitPattern(pattern)\n : pattern\n ).forEach(this._add, this)\n\n if (this._added) {\n this._literalRules = UNDEFINED\n }\n\n return this._added\n }\n\n // Match the literal 'abc/' for `checkIgnore`, last rule wins. Only a rule\n // ending in a wildcard can match it (see `checkSourceOf`), so the rest\n // are left out once, rather than tested or compiled for every path.\n testLiteral (path) {\n const rules = this._literalRules || (\n this._literalRules = this._rules.filter(\n ({body}) => body[body.length - (\n body[body.length - 1] === SLASH ? 2 : 1\n )] === '*'\n )\n )\n\n let ignored = false\n let unignored = false\n let matchedRule\n\n for (let index = rules.length - 1; index >= 0; index --) {\n const rule = rules[index]\n\n if (rule.checkRegex.test(path)) {\n ignored = !rule.negative\n unignored = rule.negative\n matchedRule = rule.negative\n ? UNDEFINED\n : rule\n break\n }\n }\n\n const ret = {\n ignored,\n unignored\n }\n\n if (matchedRule) {\n ret.rule = matchedRule\n }\n\n return ret\n }\n\n // Test one single path without recursively checking parent directories\n //\n // - mode `string` either `MODE_IGNORE` or `MODE_CHECK_IGNORE`\n\n // @returns {TestResult}\n test (path, mode) {\n // Most of a .gitignore is patterns with no slash in them, and running\n // those against the whole path makes the regular expression engine walk\n // every directory name on the way to the only segment that could match.\n // Handing them the basename instead is what git does, and it is where\n // the time in a directory walk goes: the rule scan was two thirds of it.\n const rules = this._rules\n const {length} = rules\n\n const shortcut = this._basenameCount * 2 >= length\n\n const basename = shortcut\n ? basenameOf(path)\n : path\n\n // The last rule to match decides, as in git, and it is the rule\n // `git check-ignore -v` reports, so the scan runs from the end and stops\n // at the first match.\n // A plain loop rather than `forEach`, so that `path`, `basename` and\n // `shortcut` are locals. As a callback they became closure variables,\n // and reaching for one of those once per rule cost 10% of a scan over a\n // large rule set -- more than the shortcut they were there to serve.\n for (let index = length - 1; index >= 0; index --) {\n const rule = rules[index]\n\n if (rule[mode].test(\n shortcut && rule._basenameOnly\n ? basename\n : path\n )) {\n const {negative} = rule\n\n const ret = {\n ignored: !negative,\n unignored: negative\n }\n\n if (!negative) {\n ret.rule = rule\n }\n\n return ret\n }\n }\n\n return {\n ignored: false,\n unignored: false\n }\n }\n}\n\nconst throwError = (message, Ctor) => {\n throw new Ctor(message)\n}\n\nconst checkPath = (path, originalPath, doThrow) => {\n if (!isString(path)) {\n return doThrow(\n `path must be a string, but got \\`${originalPath}\\``,\n TypeError\n )\n }\n\n // We don't know if we should ignore EMPTY, so throw\n if (!path) {\n return doThrow(`path must not be empty`, TypeError)\n }\n\n // Check if it is a relative path\n if (checkPath.isNotRelative(path)) {\n const r = '`path.relative()`d'\n return doThrow(\n `path should be a ${r} string, but got \"${originalPath}\"`,\n RangeError\n )\n }\n\n return true\n}\n\n// > pathname should be a `path.relative()`d one\n//\n// The same thing `REGEX_TEST_INVALID_PATH` says, spelled out: a path is not\n// relative if it begins with a separator, or with `./` or `../`, or is\n// nothing but `.` or `..`. Every match is decided by the first three\n// characters, and this runs on every path handed to the library -- where it\n// was 55% of a cached lookup, more than the cache lookup itself.\nconst isNotRelative = path => {\n const first = path.charCodeAt(0)\n\n if (first === SLASH_CODE) {\n return true\n }\n\n if (first !== DOT_CODE) {\n return false\n }\n\n // '.'\n if (path.length === 1) {\n return true\n }\n\n const second = path.charCodeAt(1)\n\n // './'\n if (second === SLASH_CODE) {\n return true\n }\n\n if (second !== DOT_CODE) {\n return false\n }\n\n // '..' or '../'\n return path.length === 2 || path.charCodeAt(2) === SLASH_CODE\n}\n\ncheckPath.isNotRelative = isNotRelative\n\n// On windows, the following function will be replaced\n/* istanbul ignore next */\ncheckPath.convert = p => p\n\n\nclass Ignore {\n constructor ({\n ignorecase = true,\n ignoreCase = ignorecase,\n allowRelativePaths = false\n } = {}) {\n define(this, KEY_IGNORE, true)\n\n this._rules = new RuleManager(ignoreCase)\n this._strictPathCheck = !allowRelativePaths\n this._initCache()\n }\n\n _initCache () {\n // A cache for the result of `.ignores()`\n this._ignoreCache = Object.create(null)\n\n // A cache for the result of `.test()`\n this._testCache = Object.create(null)\n }\n\n add (pattern) {\n if (this._rules.add(pattern)) {\n // Some rules have just added to the ignore,\n // making the behavior changed,\n // so we need to re-initialize the result cache\n this._initCache()\n }\n\n return this\n }\n\n // legacy\n addPattern (pattern) {\n return this.add(pattern)\n }\n\n // @returns {TestResult}\n _test (originalPath, cache) {\n const path = originalPath\n // Supports nullable path\n && checkPath.convert(originalPath)\n\n checkPath(\n path,\n originalPath,\n this._strictPathCheck\n ? throwError\n : RETURN_FALSE\n )\n\n return this._t(path, cache)\n }\n\n checkIgnore (path) {\n // If the path doest not end with a slash, `.ignores()` is much equivalent\n // to `git check-ignore`\n if (path.charCodeAt(path.length - 1) !== SLASH_CODE) {\n return this.test(path)\n }\n\n // Like `git check-ignore`: a directory excluded by itself or by an\n // ancestor settles it, and only then is the literal 'abc/' matched\n // against the rules (see `checkSourceOf`).\n const dir = this._t(path, this._testCache)\n\n if (dir.ignored) {\n return dir\n }\n\n const literal = this._rules.testLiteral(path)\n\n return literal.ignored || literal.unignored\n ? literal\n : dir\n }\n\n _t (\n // The path to be tested\n path,\n\n // The cache for the result of a certain checking\n cache\n ) {\n if (path in cache) {\n return cache[path]\n }\n\n const parentPath = parentOf(path)\n\n // If the path contains a parent directory, check the parent first\n const parent = parentPath\n ? this._t(parentPath, cache)\n : UNDEFINED\n\n return cache[path] = parent && parent.ignored\n // > It is not possible to re-include a file if a parent directory of\n // > that file is excluded.\n ? parent\n : this._rules.test(path, MODE_IGNORE)\n }\n\n ignores (path) {\n return this._test(path, this._ignoreCache).ignored\n }\n\n createFilter () {\n return path => !this.ignores(path)\n }\n\n filter (paths) {\n return makeArray(paths).filter(this.createFilter())\n }\n\n // @returns {TestResult}\n test (path) {\n return this._test(path, this._testCache)\n }\n}\n\nconst factory = options => new Ignore(options)\n\nconst isPathValid = path =>\n checkPath(path && checkPath.convert(path), path, RETURN_FALSE)\n\n/* istanbul ignore next */\nconst setupWindows = () => {\n /* eslint no-control-regex: \"off\" */\n const makePosix = str => /^\\\\\\\\\\?\\\\/.test(str)\n || /[\"<>|\\u0000-\\u001F]+/u.test(str)\n ? str\n : str.replace(/\\\\/g, '/')\n\n checkPath.convert = makePosix\n\n // 'C:\\\\foo' <- 'C:\\\\foo' has been converted to 'C:/'\n // 'd:\\\\foo'\n const REGEX_TEST_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\\//i\n checkPath.isNotRelative = path =>\n REGEX_TEST_WINDOWS_PATH_ABSOLUTE.test(path)\n || isNotRelative(path)\n}\n\n\n// Windows\n// --------------------------------------------------------------\n/* istanbul ignore next */\nif (\n // Detect `process` so that it can run in browsers.\n typeof process !== 'undefined'\n && process.platform === 'win32'\n) {\n setupWindows()\n}\n\n// COMMONJS_EXPORTS ////////////////////////////////////////////////////////////\n\nmodule.exports = factory\n\n// Although it is an anti-pattern,\n// it is still widely misused by a lot of libraries in github\n// Ref: https://github.com/search?q=ignore.default%28%29&type=code\nfactory.default = factory\n\nmodule.exports.isPathValid = isPathValid\n\n// For testing purposes\ndefine(module.exports, Symbol.for('setupWindows'), setupWindows)\n","import type { CheckResult, PermissionHandler, Rule } from \"../types.ts\"\n\nimport { normPath, prettyPath } from \"@zaly/shared\"\nimport ignore from \"ignore\"\nimport { dirname, isAbsolute, relative } from \"pathe\"\n\n/**\n * Handler for `Rule<\"read\" | \"write\">` — one impl serves both scopes\n * because they share the same matcher and the same workspace state.\n *\n * Algorithm:\n * 1. Normalize candidate to an absolute path.\n * 2. Sensitive-file check (env, ssh keys, credentials) → deny.\n * 3. Find the longest-prefix workspace containing the path. None →\n * ask, with a `kind: \"workspace\"` suggestion for the containing\n * directory.\n * 4. Inside a workspace: resolve the first matching rule against the\n * workspace-relative path. Earlier rules win.\n * 5. Default when no rule matches but the path is inside a workspace:\n * `allow` for reads (workspace = trust signal), `ask` for writes\n * (mutating ops escalate by default; users add `Write(...)` rules\n * to whitelist).\n *\n * Pattern grammar (per Claude-Code conventions):\n * //abs/path absolute filesystem path\n * ~/path path under home directory\n * /path or path workspace-relative (passed through to gitignore)\n */\nexport const fileHandler: PermissionHandler<\"read\" | \"write\"> = {\n validate(input, ctx): CheckResult {\n const abs = normPath(ctx.cwd, input)\n\n if (isSensitiveFile(abs)) {\n return { reason: `${abs}: sensitive file`, verdict: \"deny\" }\n }\n\n const ws = longestWorkspace(abs, ctx.workspaces)\n const inWorkspace = ws !== undefined\n\n // Inside-workspace + path === root: the workspace itself (e.g. `find .`\n // resolved to cwd). Workspace containment alone is enough to allow.\n if (inWorkspace && abs === ws) return { verdict: \"allow\" }\n\n // Outside any workspace, fall through to rule matching with `/` as\n // synthetic root. Lets blanket rules like `read(*)` (yolo preset)\n // override the default \"ask outside workspace\" verdict, while\n // narrower presets keep the safer default.\n const base = ws ?? \"/\"\n const rel = relative(base, abs)\n\n const verb = ctx.scope === \"read\" ? \"reading\" : \"writing\"\n\n const rule = resolveRule(base, rel, ctx.rules)\n if (rule?.policy === \"deny\") return { reason: `${abs}: denied by rule`, verdict: \"deny\" }\n if (rule?.policy === \"ask\") {\n return {\n ask: `Allow ${verb} ${prettyPath(abs)}?`,\n reason: `${abs}: rule requires confirmation`,\n suggestions: [{ kind: \"rule\", pattern: `/${rel}`, scope: ctx.scope }],\n verdict: \"ask\",\n }\n }\n if (rule?.policy === \"allow\") return { verdict: \"allow\" }\n\n // No rule matched. Defaults differ by location:\n // - Inside a workspace: reads ride on workspace trust → allow;\n // writes escalate → ask.\n // - Outside any workspace: always ask, and surface a\n // workspace-add suggestion so the user can promote the parent\n // dir without composing a rule by hand.\n if (!inWorkspace) {\n const parent = dirname(abs)\n return {\n ask: `Allow ${verb} ${prettyPath(abs)}? (not in any workspace)`,\n reason: `${abs}: outside any workspace`,\n suggestions: [\n { description: `add ${parent} as workspace`, kind: \"workspace\", path: parent },\n ],\n verdict: \"ask\",\n }\n }\n if (ctx.scope === \"read\") return { verdict: \"allow\" }\n return {\n ask: `Allow ${verb} ${prettyPath(abs)}?`,\n reason: `${abs}: write requires confirmation`,\n suggestions: [{ kind: \"rule\", pattern: `/${rel}`, scope: \"write\" }],\n verdict: \"ask\",\n }\n },\n}\n\n/** True if `path` looks like a credentials/keys file we shouldn't\n * expose to the model by default. Conservative — false positives are\n * fine here, and users can override via `allow` rules. */\nexport function isSensitiveFile(path: string): boolean {\n return SENSITIVE_PATTERNS.some((re) => re.test(path))\n}\n\n/** Common locations for credentials, keys, and other sensitive data.\n * Matched against the path string directly — covers both absolute and\n * relative inputs. Add to this list as new gotchas surface. */\nconst SENSITIVE_PATTERNS: RegExp[] = [\n /(?:^|\\/)\\.env(?:\\.|$)/, // .env, .env.local, .env.production, ...\n /(?:^|\\/)\\.git\\/(?!hooks\\/)/, // .git/* but not hooks (commonly inspected)\n /(?:^|\\/)\\.ssh\\//, // ssh keys + config\n /(?:^|\\/)\\.aws\\/credentials/,\n /(?:^|\\/)\\.netrc$/,\n /(?:^|\\/)id_(?:rsa|dsa|ed25519|ecdsa)(?:\\.pub)?$/,\n /(?:^|\\/)\\.npmrc$/, // can hold auth tokens\n /(?:^|\\/)\\.pypirc$/,\n /(?:^|\\/)secrets?\\//,\n /(?:^|\\/)credentials?(?:\\.|\\/)/,\n]\n\n/** Longest-prefix match against the workspace list — returns the\n * containing workspace's absolute path, or undefined if none contain\n * the candidate. Workspaces arrive pre-normalized from the manager. */\nfunction longestWorkspace(abs: string, workspaces: readonly string[]): string | undefined {\n let best: string | undefined\n for (const root of workspaces) {\n if (abs === root || abs.startsWith(root.endsWith(\"/\") ? root : `${root}/`)) {\n if (best === undefined || root.length > best.length) best = root\n }\n }\n return best\n}\n\n/** Resolve the first matching rule.\n * Patterns get normalized (`//abs`, `~/`, `/rel`, `rel`) into\n * workspace-rooted gitignore syntax; patterns that resolve outside the\n * candidate's workspace are dropped (they don't apply here). */\nfunction resolveRule(\n workspace: string,\n rel: string,\n rules: readonly Rule<\"read\" | \"write\">[]\n): Rule<\"read\" | \"write\"> | undefined {\n if (rel === \"\") return undefined\n for (const rule of rules) {\n const norm = normalizePattern(rule.pattern, workspace)\n if (norm === undefined) continue\n try {\n if (ignore().add(norm).ignores(rel)) return rule\n } catch {\n // Skip invalid rels.\n }\n }\n}\n\nfunction normalizePattern(pattern: string, workspace: string): string | undefined {\n if (pattern.startsWith(\"//\")) {\n return relativizeToWorkspace(pattern.slice(1), workspace)\n }\n if (pattern.startsWith(\"~/\")) {\n return relativizeToWorkspace(normPath(pattern), workspace)\n }\n // /pattern or pattern → already workspace-relative gitignore syntax.\n return pattern\n}\n\nfunction relativizeToWorkspace(absPattern: string, workspace: string): string | undefined {\n const rel = relative(workspace, absPattern)\n if (rel === \"\" || rel.startsWith(\"..\") || isAbsolute(rel)) return undefined\n return `/${rel}`\n}\n","import type { CheckResult, PermissionHandler, Rule } from \"../types.ts\"\n\nimport ignore from \"ignore\"\n\n/**\n * Generic tool-scope handler.\n *\n * Used by `Tasks` to gate every tool dispatch on the tool name, and\n * available to tools themselves for richer checks (e.g. fetch passing\n * `fetch:example.com` so users can ask-for-domain).\n *\n * Pattern grammar is gitignore-style — reuses the `ignore` package so\n * the syntax matches `read` / `write` patterns. Common shapes:\n *\n * \"tool\" → bare scope; matches every input (default-allow)\n * \"tool(bash)\" → exact match for `\"bash\"`\n * \"tool(fetch:*)\" → glob match `\"fetch:...\"`\n * \"tool(task_*)\" → glob match `\"task_...\"`\n *\n * Resolution is first-match-wins. Default verdict when no rule matches is\n * `allow` — an unconfigured `tool` scope should not surprise users by\n * gating ordinary tool calls.\n */\nexport const toolHandler: PermissionHandler<\"tool\"> = {\n validate(input, ctx): CheckResult {\n const rule = resolveRule(input, ctx.rules)\n if (rule?.policy === \"deny\") {\n return { reason: `tool ${input}: denied by rule`, verdict: \"deny\" }\n }\n if (rule?.policy === \"ask\") {\n return {\n ask: `Allow tool ${input}?`,\n reason: `tool ${input}: rule requires confirmation`,\n suggestions: [{ kind: \"rule\", pattern: input, scope: \"tool\" }],\n verdict: \"ask\",\n }\n }\n return { verdict: \"allow\" }\n },\n}\n\nfunction resolveRule(input: string, rules: readonly Rule<\"tool\">[]): Rule<\"tool\"> | undefined {\n for (const rule of rules) {\n if (ignore().add(rule.pattern).ignores(input)) return rule\n }\n}\n","import type { PermissionHandler } from \"../types.ts\"\n\nimport { createRegistry } from \"@zaly/shared/registry\"\nimport { bashHandler } from \"./bash.ts\"\nimport { fileHandler } from \"./files.ts\"\nimport { toolHandler } from \"./tool.ts\"\n\nexport type HandlerLoader = () => PermissionHandler<string>\n\nconst builtin = {\n bash: () => bashHandler,\n read: () => fileHandler,\n tool: () => toolHandler,\n write: () => fileHandler,\n} as const satisfies Record<string, HandlerLoader>\n\n/** Open registry of permission scopes — declaration-merge to add your\n * own. The keys give `ctx.need(\"…\", input)` typed autocomplete and\n * catch typos at compile time. The value carries the *input* type for\n * that scope (almost always `string` — files take paths, bash takes\n * commands, the generic `tool` scope takes the tool name).\n *\n * Built-ins:\n * - `bash` → command string\n * - `read` → absolute path\n * - `write` → absolute path\n * - `tool` → tool name (or richer `name:arg` shape per tool)\n *\n * Add your own scope:\n *\n * ```ts\n * declare module \"@zaly/agent\" {\n * interface PermissionScopes {\n * fetch: string // expects a domain (or \"*\" for any)\n * }\n * }\n * ```\n *\n * Then `ctx.need(\"fetch\", domain)` is typed end-to-end. You still need\n * to register a runtime handler via `handlerRegistry.register(\"fetch\", …)`\n * — this interface is only the type-side declaration.\n */\nexport interface PermissionScopes {\n bash: string\n read: string\n tool: string\n write: string\n}\n\nexport type BuiltinScope = keyof typeof builtin\nexport type PermissionScope = keyof PermissionScopes\nexport type AnyScope = PermissionScope | (string & {})\n\nexport const handlerRegistry = createRegistry<HandlerLoader>(\"scope\").from(builtin)\n"],"ignoreList":[1],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,MAAa,cAAyC,EACpD,SAAS,OAAO,KAAkB;CAChC,MAAM,SAAS,UAAU,KAAK;CAC9B,IAAI,CAAC,OAAO,IAAI;EACd,IAAI;GAAC;GAAQ;GAAQ;EAAO,CAAC,CAAC,OAAO,UAAU,IAAI,YAAY,KAAK,CAAC,GACnE,OAAO,EAAE,SAAS,QAAQ;EAE5B,OAAO;GACL,KAAK,6BAA6B,OAAO,OAAO;GAChD,QAAQ,OAAO;GACf,SAAS;EACX;CACF;CAEA,IAAI,UAAmB;CACvB,IAAI;CACJ,MAAM,cAA4B,CAAC;CAEnC,KAAK,MAAM,OAAO,OAAO,UAAU;EAIjC,M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nProp = Object.prototype.hasOwnProperty;
|
|
9
9
|
var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod, mod.exports), cb = null), mod.exports);
|
|
10
|
-
var __exportAll = (all,
|
|
11
|
-
let target = {};
|
|
10
|
+
var __exportAll = (all, flags) => {
|
|
11
|
+
let target = Object.setPrototypeOf({}, null);
|
|
12
12
|
for (var name in all) __defProp(target, name, {
|
|
13
13
|
get: all[name],
|
|
14
14
|
enumerable: true
|
|
15
15
|
});
|
|
16
|
-
if (!
|
|
17
|
-
return target;
|
|
16
|
+
if (!(flags & 1)) __defProp(target, Symbol.toStringTag, { value: "Module" });
|
|
17
|
+
return flags & 2 ? target : Object.preventExtensions(target);
|
|
18
18
|
};
|
|
19
19
|
var __copyProps = (to, from, except, desc) => {
|
|
20
20
|
if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as __exportAll } from "./rolldown-runtime-
|
|
1
|
+
import { n as __exportAll } from "./rolldown-runtime-BVN1G_yT.mjs";
|
|
2
2
|
import { r as uuidv7 } from "./uuid-rfbQ9ad2.mjs";
|
|
3
3
|
import { n as JsonlStore } from "./jsonl-BGt7eqPK.mjs";
|
|
4
4
|
import { Emitter, normPath } from "@zaly/shared";
|
|
@@ -480,4 +480,4 @@ var Session = class Session extends Emitter {
|
|
|
480
480
|
};
|
|
481
481
|
export { session_exports as n, MemoryStore as r, Session as t };
|
|
482
482
|
|
|
483
|
-
//# sourceMappingURL=session-
|
|
483
|
+
//# sourceMappingURL=session-C5ra-Hi1.mjs.map
|