UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

115 lines • 87.9 kB
import{n as containsAsciiControlCharacter}from"./string-normalization-D_oBUpO3.mjs";import{r as terminalText}from"./safe-text-B_QTgn0s.mjs";import{t as escapeRegExp}from"./regexp-DAJp1ywh.mjs";import"./text-utility-runtime-CDtGqkrl.mjs";import{t as expectDefined}from"./expect-runtime-CQxc2p61.mjs";import{t as MarkdownItCallable}from"./markdown-it-DgxxBv97.mjs";import"./terminal-safe-text-Crgjdu4T.mjs";import{constants,promises}from"node:fs";import{resolve}from"node:path";import{isDeepStrictEqual}from"node:util";import{isUtf8}from"node:buffer";import{LineCounter,isAlias,isCollection,isMap,isNode,isScalar,isSeq,parseDocument,stringify,visit}from"yaml";import{FILE_HEADERS_ONLY,formatPatch,structuredPatch}from"diff";
//!extensions/oc-path/src/oc-path/dispatch.ts
function inferKind(e){const t=e.toLowerCase();if(t.endsWith(`.md`))return`md`;if(t.endsWith(`.jsonl`)||t.endsWith(`.ndjson`))return`jsonl`;if(t.endsWith(`.jsonc`)||t.endsWith(`.json`))return`jsonc`;if(t.endsWith(`.yaml`)||t.endsWith(`.yml`)||t.endsWith(`.lobster`))return`yaml`;return null}
//!extensions/oc-path/src/oc-path/edit-error.ts
var OcPathEditError=class extends Error{constructor(e,t){super(t??e);this.reason=e;this.detail=t;this.name=`OcPathEditError`}};
//!extensions/oc-path/src/oc-path/sentinel.ts
const REDACTED_SENTINEL=`__OPENCLAW_REDACTED__`;var OcEmitSentinelError=class extends Error{constructor(e){super(`emit refused to write "${REDACTED_SENTINEL}" sentinel literal at ${e}`);this.name=`OcEmitSentinelError`}};function guardSentinel(e,t){if(typeof e===`string`&&e.includes(`__OPENCLAW_REDACTED__`))throw new OcEmitSentinelError(typeof t===`function`?t():t)}
//!extensions/oc-path/src/oc-path/oc-path.ts
const OC_SCHEME=`oc://`;const MAX_PATH_LENGTH=4096;const MAX_SUB_SEGMENTS_PER_SLOT=64;const MAX_TRAVERSAL_DEPTH=256;const BOM$1=``;const RESERVED_CHARS_RE=/[?&%]/;const SPECIAL_SEGMENT_RE=/^(?:\$first|\$last|\*\*?|#\d+|\+.*)$/;function printable(e){let t=``;for(let n=0;n<e.length;n++){const r=e.charCodeAt(n);if(r<=31||r===127)t+=`\\x${r.toString(16).padStart(2,`0`)}`;else t+=e[n]}return t}var OcPathError=class extends Error{constructor(e,t){super(e);this.name=`OcPathError`;this.code=t}};function fail(e,t){throw new OcPathError(e,t)}function validateFileSlot(e,t){if(e.startsWith(`/`)||e.startsWith(`\\`)||/^[a-zA-Z]:/.test(e))fail(`Absolute file slot not allowed (oc:// paths are workspace-relative): ${printable(t)}`,`OC_PATH_ABSOLUTE_FILE`);if(e.split(/[\\/]/).some(e=>e===`..`))fail(`Parent-directory segment ('..') not allowed in oc:// file slot: ${printable(t)}`,`OC_PATH_PARENT_TRAVERSAL`);if(containsAsciiControlCharacter(e))fail(`Control character in oc:// file slot: ${printable(t)}`,`OC_PATH_CONTROL_CHAR`)}function validateSessionSlot(e,t){if(containsAsciiControlCharacter(e))fail(`Control character in oc:// session query: ${printable(t)}`,`OC_PATH_CONTROL_CHAR`);if(RESERVED_CHARS_RE.test(e))fail(`Reserved character (\`?\` / \`&\` / \`%\`) in oc:// session query: ${printable(t)}`,`OC_PATH_RESERVED_CHAR`)}function parseOcPath(e){if(typeof e!==`string`)fail(`oc:// path must be a string`,`OC_PATH_NOT_STRING`);const t=Buffer.byteLength(e,`utf8`);if(t>MAX_PATH_LENGTH)fail(`oc:// path exceeds ${MAX_PATH_LENGTH} bytes (length: ${t})`,`OC_PATH_TOO_LONG`);const n=e.startsWith(BOM$1)?e.slice(1):e;if(!n.startsWith(OC_SCHEME))fail(`Missing oc:// scheme: ${printable(e)}`,`OC_PATH_MISSING_SCHEME`);if(containsAsciiControlCharacter(n))fail(`Control character in oc:// path: ${printable(e)}`,`OC_PATH_CONTROL_CHAR`);const r=n.slice(5);const i=indexOfTopLevel(r,`?`);const a=i===-1?r:r.slice(0,i);const o=i===-1?``:r.slice(i+1);if(a.length===0)fail(`Empty oc:// path: ${printable(e)}`,`OC_PATH_EMPTY`);const s=splitRespectingBrackets(a,`/`,e);for(const t of s)if(t.length===0)fail(`Empty segment in oc:// path: ${printable(e)}`,`OC_PATH_EMPTY_SEGMENT`);const c=unquoteSeg(expectDefined(s.at(0),`path split always returns a file segment`));validateFileSlot(c,e);const l=normalizeDeepJsonPathSegments(s,c,e);if(l.length>4)fail(`Too many segments in oc:// path (max 4): ${printable(e)}`,`OC_PATH_TOO_DEEP`);for(const[t,n]of l.entries()){const r=splitRespectingBrackets(n,`.`,e);if(r.length>64)fail(`Sub-segment count exceeds ${64} in segment "${n}": ${printable(e)}`,`OC_PATH_TOO_DEEP`);for(const n of r){if(t===0&&n.length===0&&c!==`.`)continue;validateSubSegment(n,e)}}const u=extractSession(o,e);return{file:c,...l[1]!==void 0?{section:l[1]}:{},...l[2]!==void 0?{item:l[2]}:{},...l[3]!==void 0?{field:l[3]}:{},...u!==void 0?{session:u}:{}}}function isJsonPathFile(e){const t=e.toLowerCase();return t.endsWith(`.json`)||t.endsWith(`.jsonc`)}function normalizeDeepJsonPathSegments(e,t,n){if(e.length<=4||!isJsonPathFile(t))return e;const r=e.slice(1);if(r.length>256)fail(`JSON oc:// path exceeds ${256} nested segments: ${printable(n)}`,`OC_PATH_TOO_DEEP`);const i=r.slice(0,-2).join(`.`);const a=expectDefined(r.at(-2),`deep JSON path has an item segment`);const o=expectDefined(r.at(-1),`deep JSON path has a field segment`);return[expectDefined(e.at(0),`normalized path has a file segment`),i,a,o]}function formatOcPath(e){if(!e.file)fail(`oc:// path requires a file`,`OC_PATH_FILE_REQUIRED`);validateFileSlot(e.file,e.file);if(e.item!==void 0&&e.section===void 0)fail(`Structural nesting violation: item requires section`,`OC_PATH_NESTING`);if(e.field!==void 0&&e.item===void 0)fail(`Structural nesting violation: field requires item`,`OC_PATH_NESTING`);const formatSubSegment=e=>{if(isQuotedSeg(e)||SPECIAL_SEGMENT_RE.test(e)||e.startsWith(`[`)&&e.endsWith(`]`)||e.startsWith(`{`)&&e.endsWith(`}`))return e;return quoteSeg(e)};const validateSubForFormat=(e,t)=>{if(e.length===0)fail(`Empty dotted sub-segment in OcPath.${t}`,`OC_PATH_EMPTY_SUB_SEGMENT`);if(containsAsciiControlCharacter(e))fail(`Control character in OcPath.${t} sub-segment "${printable(e)}"`,`OC_PATH_CONTROL_CHAR`)};const formatSlot=(e,t)=>{const n=splitRespectingBrackets(e,`.`);for(const e of n)validateSubForFormat(e,t);return n.map(formatSubSegment).join(`.`)};const t=/[/[\]{}?&%"\\\s]/.test(e.file)?quoteSeg(e.file):e.file;let n=OC_SCHEME+t;if(e.section!==void 0)n+=`/`+formatSlot(e.section,`section`);if(e.item!==void 0)n+=`/`+formatSlot(e.item,`item`);if(e.field!==void 0)n+=`/`+formatSlot(e.field,`field`);if(e.session!==void 0){validateSessionSlot(e.session,e.file);n+=`?session=`+e.session}const r=Buffer.byteLength(n,`utf8`);if(r>MAX_PATH_LENGTH)fail(`Formatted oc:// exceeds ${MAX_PATH_LENGTH} bytes (length: ${r})`,`OC_PATH_TOO_LONG`);if(n.includes(`__OPENCLAW_REDACTED__`))throw new OcEmitSentinelError(n);return n}const POS_FIRST=`$first`;const POS_LAST=`$last`;function isPositionalSeg(e){return e===`$first`||e===`$last`}function isOrdinalSeg(e){return/^#\d+$/.test(e)}function parseOrdinalSeg(e){const t=/^#(\d+)$/.exec(e);return t===null||t[1]===void 0?null:Number(t[1])}function parseArrayIndexSegment(e,t){if(!/^(0|[1-9]\d*)$/.test(e))return null;const n=Number(e);return Number.isSafeInteger(n)&&n>=0&&n<t?n:null}function resolvePositionalSeg(e,t){if(t.size===0)return null;if(e===`$first`){if(!t.indexable)return t.keys?.[0]??null;return`0`}if(e===`$last`){if(!t.indexable)return t.keys?.[t.keys.length-1]??null;return String(t.size-1)}return null}const WILDCARD_SINGLE=`*`;const WILDCARD_RECURSIVE=`**`;function isPattern(e){for(const t of[e.section,e.item,e.field]){if(t===void 0)continue;for(const e of splitRespectingBrackets(t,`.`))if(e===`*`||e===`**`||isUnionSeg(e)||isPredicateSeg(e))return true}return false}function isUnionSeg(e){return e.length>=2&&e.startsWith(`{`)&&e.endsWith(`}`)}function parseUnionSeg(e){if(!isUnionSeg(e))return null;const t=e.slice(1,-1);if(t.length===0)return null;const n=splitRespectingBrackets(t,`,`);if(n.some(e=>e.length===0))return null;return n}const PREDICATE_OPS=[`!=`,`<=`,`>=`,`<`,`>`,`=`];function isPredicateSeg(e){if(e.length<4||!e.startsWith(`[`)||!e.endsWith(`]`))return false;const t=new Set(e.slice(1,-1));return PREDICATE_OPS.some(e=>t.has(e))}function parsePredicateSeg(e){if(e.length<4||!e.startsWith(`[`)||!e.endsWith(`]`))return null;const t=e.slice(1,-1);for(let e=1;e<t.length;e++)for(const n of PREDICATE_OPS){if(!t.startsWith(n,e))continue;if(e+n.length>=t.length)continue;return{key:t.slice(0,e),op:n,value:t.slice(e+n.length)}}return null}function evaluatePredicate(e,t){if(e===null)return false;switch(t.op){case`=`:return e===t.value;case`!=`:return e!==t.value;case`<`:case`<=`:case`>`:case`>=`:{const n=Number(e);const r=Number(t.value);if(!Number.isFinite(n)||!Number.isFinite(r))return false;if(t.op===`<`)return n<r;if(t.op===`<=`)return n<=r;if(t.op===`>`)return n>r;return n>=r}}return false}function extractSession(e,t){if(e.length===0)return;for(const n of e.split(`&`)){const e=n.indexOf(`=`);if(e===-1)continue;const r=n.slice(0,e);const i=n.slice(e+1);if(r===`session`&&i.length>0){validateSessionSlot(i,t);return i}}}function scanBracketAware(e,t,n){let r=0;let i=0;let a=false;for(let o=0;o<e.length;o++){const s=e.charAt(o);if(a&&s===`\\`){o++;continue}const c=a||s===`"`;if(s===`"`)a=!a;if(!c){if(s===`[`)r++;else if(s===`]`)r--;else if(s===`{`)i++;else if(s===`}`)i--;if(r<0||i<0)n()}if(t(s,o,!c&&r===0&&i===0)===`stop`)return}if(r!==0||i!==0||a)n()}function indexOfTopLevel(e,t){let n=-1;const failLocal=()=>{throw new OcPathError(`Unbalanced bracket/brace in oc:// path: ${e}`,`OC_PATH_UNBALANCED`)};scanBracketAware(e,(e,r,i)=>{if(i&&e===t){n=r;return`stop`}},failLocal);return n}function splitRespectingBrackets(e,t,n){const r=[];let i=0;const a=n??e;const onUnbalanced=()=>{fail(`Unbalanced bracket/brace in oc:// path: ${a}`,`OC_PATH_UNBALANCED`)};scanBracketAware(e,(n,a,o)=>{if(o&&n===t){r.push(e.slice(i,a));i=a+1}},onUnbalanced);r.push(e.slice(i));return r}function splitOcPathSlots(...e){return e.flatMap(e=>e===void 0?[]:splitRespectingBrackets(e,`.`))}function isQuotedSeg(e){return e.length>=2&&e.startsWith(`"`)&&e.endsWith(`"`)}function unquoteSeg(e){return isQuotedSeg(e)?e.slice(1,-1).replace(/\\(["\\])/g,`$1`):e}function quoteSeg(e){return e.length===0||SPECIAL_SEGMENT_RE.test(e)||/[/.[\]{}?&%"\\\s]/.test(e)?JSON.stringify(e):e}function validateSubSegment(e,t){if(e.length===0)fail(`Empty dotted sub-segment in oc:// path: ${printable(t)}`,`OC_PATH_EMPTY_SUB_SEGMENT`);if(containsAsciiControlCharacter(e))fail(`Control character in oc:// segment "${printable(e)}": ${printable(t)}`,`OC_PATH_CONTROL_CHAR`);if(isQuotedSeg(e)){if(!/^(?:[^"\\]|\\["\\])*$/.test(e.slice(1,-1)))fail(`Quoted segment must escape '"' and '\\\\' with a backslash: ${printable(e)}`,`OC_PATH_UNQUOTABLE`);return}if(!e.startsWith(`[`)&&!e.startsWith(`{`)){if(RESERVED_CHARS_RE.test(e))fail(`Reserved character (\`?\` / \`&\` / \`%\`) in oc:// segment "${e}": ${printable(t)}`,`OC_PATH_RESERVED_CHAR`);if(/\s/.test(e))fail(`Whitespace in oc:// segment "${e}": ${printable(t)}`,`OC_PATH_WHITESPACE`)}const n=e.startsWith(`[`);const r=e.endsWith(`]`);if(n!==r)fail(`Mismatched bracket in segment "${e}": ${printable(t)}`,`OC_PATH_MALFORMED_PREDICATE`);if(n&&r){const n=e.slice(1,-1);if(n.length===0)fail(`Empty bracket segment "${e}": ${printable(t)}`,`OC_PATH_MALFORMED_PREDICATE`);if([`!=`,`<=`,`>=`,`<`,`>`,`=`].some(e=>n.includes(e))){if(parsePredicateSeg(e)===null)fail(`Malformed predicate "${e}" — must be \`[key<op>value]\` with non-empty key and value: ${printable(t)}`,`OC_PATH_MALFORMED_PREDICATE`)}}const i=e.startsWith(`{`);const a=e.endsWith(`}`);if(i!==a)fail(`Mismatched brace in segment "${e}": ${printable(t)}`,`OC_PATH_MALFORMED_UNION`);if(i&&a){const n=e.slice(1,-1);if(n.length===0)fail(`Empty union "${e}" — must contain at least one alternative: ${printable(t)}`,`OC_PATH_MALFORMED_UNION`);const r=splitRespectingBrackets(n,`,`);if(r.some(e=>e.length===0))fail(`Empty alternative in union "${e}": ${printable(t)}`,`OC_PATH_MALFORMED_UNION`);for(const e of r)if(isUnionSeg(e))validateSubSegment(e,t)}}
//!extensions/oc-path/src/oc-path/find-md-frontmatter.ts
function walkMdFrontmatter(e,t,n,r){const i=expectDefined(t[n],`Frontmatter sentinel index checked by walker`);const a=JSON.stringify([`frontmatter`,t.slice(n)]);const o=r.visited.get(e)??/* @__PURE__ */ new Set;if(o.has(a))return;r.visited.set(e,o.add(a));let s;for(let i=n+1;i<t.length;i++){const a=expectDefined(t[i],`Frontmatter key index checked above`);if(isUnionSeg(a.value)){for(const o of parseUnionSeg(a.value)??[]){const s=t.slice();s[i]={slot:a.slot,value:o};walkMdFrontmatter(e,s,n,r)}return}if(a.value===`**`)continue;if(s)return;s=a}const c=s??t[n+1];if(c===void 0){r.onMatch([{slot:i.slot,value:i.value}]);return}const l=c.value===`*`||c.value===`**`;const u=unquoteSeg(c.value);for(const t of e.frontmatter){if(!l&&t.key!==u)continue;r.onMatch([{slot:i.slot,value:i.value},{slot:c.slot,value:quoteSeg(t.key)}])}}
//!extensions/oc-path/src/oc-path/jsonc/resolve-value.ts
function resolveJsoncValueOcPath(e,t){let n=e;let r=null;const i=[];for(const e of t){let t=unquoteSeg(e);if(e.length===0)return null;if(isPositionalSeg(e)){const r=resolveJsoncPositionalSegment(n,e);if(r!==null)t=r}if(n.kind===`object`){const e=n.entries.findLast(e=>e.key===t);if(e===void 0)return null;r=e;i.push(t);n=e.value;continue}if(n.kind===`array`){const e=parseArrayIndexSegment(t,n.items.length);if(e===null)return null;r=null;i.push(e);const a=n.items[e];if(a===void 0)return null;n=a;continue}return null}if(r!==null&&n===r.value)return{kind:`object-entry`,node:r,path:i};return{kind:`value`,node:n,path:i}}function resolveJsoncPositionalSegment(e,t){if(e.kind===`object`){const n=e.entries.map(e=>e.key);return resolvePositionalSeg(t,{indexable:false,size:n.length,keys:n})}if(e.kind===`array`)return resolvePositionalSeg(t,{indexable:true,size:e.items.length});return null}
//!extensions/oc-path/src/oc-path/jsonl/line.ts
function pickJsonlLine(e,t){const n=pickJsonlLineIndex(e,t);if(n===-1)return null;return e.lines[n]??null}function pickJsonlLineIndex(e,t){if(t===`$first`)return e.lines.findIndex(e=>e.kind===`value`);if(t===`$last`)return e.lines.findLastIndex(e=>e?.kind===`value`);const n=/^L(\d+)$/.exec(t);if(n===null||n[1]===void 0)return-1;const r=Number(n[1]);return e.lines.findIndex(e=>e.line===r)}function keepOnlyLineAddressInSection(e){const t=e[0];if(t===void 0||t.length<=1)return e;const n=e.slice(1);const[r=[],...i]=n.length<2?[[],...n]:n;return[t.slice(0,1),[...t.slice(1),...r],...i]}
//!extensions/oc-path/src/oc-path/source.ts
function sourceLineOffset(e,t,n=/\r\n?|\n/g){if(t<=1)return 0;let r=1;for(const i of e.matchAll(n)){r+=1;if(r===t)return i.index+i[0].length}return e.length}function sourceLineEnding(e,t=false){const n=(e.match(/\r\n/g)??[]).length;const r=(e.match(/\n/g)??[]).length;const i=t?(e.match(/\r(?!\n)/g)??[]).length:0;if(i>n&&i>r-n)return`\r`;return n>0&&n*2>=r?`\r
`:`
`}
//!extensions/oc-path/src/oc-path/emit.ts
function replaceMdSource(e,t,n,r,i){const a=(e.raw[t-1]===`\r`&&r.startsWith(`
`)?`\r`:``)+r+(r.endsWith(`\r`)&&e.raw[n]===`
`?`
`:``);const o=e.raw.slice(0,n).split(/\r\n?|\n/).length;const s=n===0||/[\r\n]/.test(e.raw[n-1]??``)||n===1&&e.raw[0]===``;const c=a.split(/\r\n?|\n/).length-e.raw.slice(t,n).split(/\r\n?|\n/).length;const shift=e=>e>o||s&&e===o?e+c:e;const l=i({...e,raw:e.raw.slice(0,t)+a+e.raw.slice(n),frontmatterEndLine:e.frontmatterEndLine===void 0?void 0:shift(e.frontmatterEndLine),frontmatter:e.frontmatter.map(e=>({...e,line:shift(e.line)})),blocks:e.blocks.map(e=>({...e,line:shift(e.line),items:e.items.map(e=>({...e,line:shift(e.line),textLine:e.textLine===null?null:shift(e.textLine)}))}))});const u=l.raw.replace(/^\uFEFF/,``).split(/\r\n?|\n/);const d=[];for(const[e,t]of l.blocks.entries()){const n=l.blocks[e+1];const r=u.slice(t.line,n?n.line-1:u.length).join(`
`);d.push(r===t.bodyText?t:{...t,bodyText:r})}return{...l,preamble:u.slice(l.frontmatterEndLine??0,l.blocks[0]?l.blocks[0].line-1:u.length).join(`
`),blocks:d}}function insertMdSource(e,t,n,r){const i=sourceLineEnding(e.raw,true);const a=t>0&&!/[\r\n]/.test(e.raw[t-1]??``)&&!(t===1&&e.raw[0]===``)?i:``;const o=t<e.raw.length||/[\r\n]$/.test(e.raw)?i:``;const s=e.raw.slice(0,t).split(/\r\n?|\n/).length+(a?1:0);return replaceMdSource(e,t,t,a+n.replace(/\r\n?|\n/g,i)+o,e=>r(e,s))}function emitJsoncObjectEntries(e,t,n){return e.map(e=>{return n(e,guardedJsoncKeyPath(e.key,t))})}function guardedJsoncKeyPath(e,t){const n=`${t}/${e}`;guardSentinel(e,n);return n}
//!extensions/oc-path/src/oc-path/frontmatter-format.ts
function readsBackAsString(e){try{const t=parseDocument(`value: ${e}`).get(`value`,true);return isScalar(t)&&typeof t.value===`string`&&t.value===e}catch{return false}}function formatFrontmatterValue(e){if(e.length===0)return`""`;if(e.trim()!==e||/^["']/.test(e)||/[:#&*?|<>=!%@`,[\]{}\r\n]/.test(e)||!readsBackAsString(e))return JSON.stringify(e);return e}
//!extensions/oc-path/src/oc-path/resolve.ts
function resolveMdOcPath(e,t){if(t.section===`[frontmatter]`){if(t.item!==void 0&&t.field!==void 0)return null;const n=t.item??t.field;if(n===void 0)return null;const r=e.frontmatter.find(e=>e.key===unquoteSeg(n));if(r===void 0)return null;return{kind:`frontmatter`,node:r}}if(t.section===void 0)return{kind:`root`,node:e};const n=e.blocks.find(e=>e.slug===unquoteSeg(t.section).toLowerCase());if(n===void 0)return null;if(t.item===void 0)return{kind:`block`,node:n};let r;if(isOrdinalSeg(t.item)){const e=parseOrdinalSeg(t.item);if(e===null||e<0||e>=n.items.length)return null;r=n.items[e]}else if(isPositionalSeg(t.item)){const e=resolvePositionalSeg(t.item,{indexable:true,size:n.items.length});if(e===null)return null;r=n.items[Number(e)]}else r=n.items.find(e=>e.slug===unquoteSeg(t.item).toLowerCase());if(r===void 0)return null;if(t.field===void 0)return{kind:`item`,node:r,block:n};if(r.kv===void 0)return null;if(r.kv.key.toLowerCase()!==unquoteSeg(t.field).toLowerCase())return null;return{kind:`item-field`,node:r,value:r.kv.value}}
//!extensions/oc-path/src/oc-path/edit.ts
function setMdOcPath(e,t,n){guardSentinel(n,formatOcPath(t));if(t.section===`[frontmatter]`){const r=resolveMdOcPath(e,t);if(r?.kind!==`frontmatter`||e.frontmatterEndLine===void 0)throw new OcPathEditError(`unresolved`);const i=r.node;const a=sourceLineOffset(e.raw,i.line);const o=e.raw.slice(a,sourceLineOffset(e.raw,e.frontmatterEndLine));const s=/^[^:\r\n]*:[ \t]*/.exec(o)?.[0];const c=parseDocument(o.replace(/\r(?!\n)/g,`
`),{prettyErrors:false,logLevel:`silent`}).get(i.key,true);if(s===void 0||!isNode(c)||!c.range)throw new OcPathEditError(`unresolved`);const l=c.range[1];const u=o.slice(0,l).match(/(?:\r\n|\r|\n)$/)?.[0]??(o[l]===`#`?` `:``);const d=!isAlias(c)&&c.anchor?`&${c.anchor} `:``;const f=e.frontmatter.indexOf(i);return replaceMdSource(e,a+s.length,a+l,(s.endsWith(`:`)?` `:``)+d+formatFrontmatterValue(n)+u,e=>({...e,frontmatter:e.frontmatter.map((e,t)=>t===f?{...e,value:n}:e)}))}if(t.section===void 0||t.item===void 0||t.field===void 0)throw new OcPathEditError(`not-writable`);const r=resolveMdOcPath(e,{...t,field:void 0});if(r?.kind!==`item`)throw new OcPathEditError(`unresolved`);const{node:i,block:a}=r;if(i.kv===void 0)throw new OcPathEditError(`no-item-kv`);if(i.kv.key.toLowerCase()!==unquoteSeg(t.field).toLowerCase())throw new OcPathEditError(`unresolved`);if(n.trim()===``)throw new OcPathEditError(`parse-error`,`Markdown item fields require a nonblank value`);if(i.textLine===null)throw new OcPathEditError(`not-writable`);const o=i.kv.key;const s=sourceLineOffset(e.raw,i.textLine);const c=new RegExp(`^([\\s\\S]*?${escapeRegExp(i.kv.key)}[ \\t]*:\\s*)`).exec(e.raw.slice(s))?.[1];if(c===void 0)throw new OcPathEditError(`unresolved`);const l=s+c.length;const u=i.textLine+c.split(/\r\n?|\n/).length+i.kv.value.split(/\r\n?|\n/).length-2;const d=sourceLineOffset(e.raw,u+1);const f=e.raw.slice(l,d).match(/(?:\r\n|\r|\n)$/)?.[0]??``;const p=e.blocks.indexOf(a);const m=a.items.indexOf(i);return replaceMdSource(e,l,d-f.length,n.replace(/\r\n?|\n/g,sourceLineEnding(e.raw,true)),e=>({...e,blocks:e.blocks.map((e,t)=>t!==p?e:{...e,items:e.items.map((e,t)=>t!==m?e:{...e,kv:{key:o,value:n}})})}))}
//!node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/scanner.js
function createScanner(e,t=false){const n=e.length;let r=0,i=``,a=0,o=16,s=0,c=0,l=0,u=0,d=0;function scanHexDigits(t,n){let i=0;let a=0;while(i<t||!n){let t=e.charCodeAt(r);if(t>=48&&t<=57)a=a*16+t-48;else if(t>=65&&t<=70)a=a*16+t-65+10;else if(t>=97&&t<=102)a=a*16+t-97+10;else break;r++;i++}if(i<t)a=-1;return a}function setPosition(e){r=e;i=``;a=0;o=16;d=0}function scanNumber(){let t=r;if(e.charCodeAt(r)===48)r++;else{r++;while(r<e.length&&isDigit(e.charCodeAt(r)))r++}if(r<e.length&&e.charCodeAt(r)===46){r++;if(r<e.length&&isDigit(e.charCodeAt(r))){r++;while(r<e.length&&isDigit(e.charCodeAt(r)))r++}else{d=3;return e.substring(t,r)}}let n=r;if(r<e.length&&(e.charCodeAt(r)===69||e.charCodeAt(r)===101)){r++;if(r<e.length&&e.charCodeAt(r)===43||e.charCodeAt(r)===45)r++;if(r<e.length&&isDigit(e.charCodeAt(r))){r++;while(r<e.length&&isDigit(e.charCodeAt(r)))r++;n=r}else d=3}return e.substring(t,n)}function scanString(){let t=``,i=r;while(true){if(r>=n){t+=e.substring(i,r);d=2;break}const a=e.charCodeAt(r);if(a===34){t+=e.substring(i,r);r++;break}if(a===92){t+=e.substring(i,r);r++;if(r>=n){d=2;break}switch(e.charCodeAt(r++)){case 34:t+=`"`;break;case 92:t+=`\\`;break;case 47:t+=`/`;break;case 98:t+=`\b`;break;case 102:t+=`\f`;break;case 110:t+=`
`;break;case 114:t+=`\r`;break;case 116:t+=`	`;break;case 117:const e=scanHexDigits(4,true);if(e>=0)t+=String.fromCharCode(e);else d=4;break;default:d=5}i=r;continue}if(a>=0&&a<=31){if(isLineBreak(a)){t+=e.substring(i,r);d=2;break}else d=6}r++}return t}function scanNext(){i=``;d=0;a=r;c=s;u=l;if(r>=n){a=n;return o=17}let t=e.charCodeAt(r);if(isWhiteSpace(t)){do{r++;i+=String.fromCharCode(t);t=e.charCodeAt(r)}while(isWhiteSpace(t));return o=15}if(isLineBreak(t)){r++;i+=String.fromCharCode(t);if(t===13&&e.charCodeAt(r)===10){r++;i+=`
`}s++;l=r;return o=14}switch(t){case 123:r++;return o=1;case 125:r++;return o=2;case 91:r++;return o=3;case 93:r++;return o=4;case 58:r++;return o=6;case 44:r++;return o=5;case 34:r++;i=scanString();return o=10;case 47:const c=r-1;if(e.charCodeAt(r+1)===47){r+=2;while(r<n){if(isLineBreak(e.charCodeAt(r)))break;r++}i=e.substring(c,r);return o=12}if(e.charCodeAt(r+1)===42){r+=2;const t=n-1;let a=false;while(r<t){const t=e.charCodeAt(r);if(t===42&&e.charCodeAt(r+1)===47){r+=2;a=true;break}r++;if(isLineBreak(t)){if(t===13&&e.charCodeAt(r)===10)r++;s++;l=r}}if(!a){r++;d=1}i=e.substring(c,r);return o=13}i+=String.fromCharCode(t);r++;return o=16;case 45:i+=String.fromCharCode(t);r++;if(r===n||!isDigit(e.charCodeAt(r)))return o=16;case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:i+=scanNumber();return o=11;default:while(r<n&&isUnknownContentCharacter(t)){r++;t=e.charCodeAt(r)}if(a!==r){i=e.substring(a,r);switch(i){case`true`:return o=8;case`false`:return o=9;case`null`:return o=7}return o=16}i+=String.fromCharCode(t);r++;return o=16}}function isUnknownContentCharacter(e){if(isWhiteSpace(e)||isLineBreak(e))return false;switch(e){case 125:case 93:case 123:case 91:case 34:case 58:case 44:case 47:return false}return true}function scanNextNonTrivia(){let e;do e=scanNext();while(e>=12&&e<=15);return e}return{setPosition,getPosition:()=>r,scan:t?scanNextNonTrivia:scanNext,getToken:()=>o,getTokenValue:()=>i,getTokenOffset:()=>a,getTokenLength:()=>r-a,getTokenStartLine:()=>c,getTokenStartCharacter:()=>a-u,getTokenError:()=>d}}function isWhiteSpace(e){return e===32||e===9}function isLineBreak(e){return e===10||e===13}function isDigit(e){return e>=48&&e<=57}var CharacterCodes;(function(e){e[e[`lineFeed`]=10]=`lineFeed`;e[e[`carriageReturn`]=13]=`carriageReturn`;e[e[`space`]=32]=`space`;e[e[`_0`]=48]=`_0`;e[e[`_1`]=49]=`_1`;e[e[`_2`]=50]=`_2`;e[e[`_3`]=51]=`_3`;e[e[`_4`]=52]=`_4`;e[e[`_5`]=53]=`_5`;e[e[`_6`]=54]=`_6`;e[e[`_7`]=55]=`_7`;e[e[`_8`]=56]=`_8`;e[e[`_9`]=57]=`_9`;e[e[`a`]=97]=`a`;e[e[`b`]=98]=`b`;e[e[`c`]=99]=`c`;e[e[`d`]=100]=`d`;e[e[`e`]=101]=`e`;e[e[`f`]=102]=`f`;e[e[`g`]=103]=`g`;e[e[`h`]=104]=`h`;e[e[`i`]=105]=`i`;e[e[`j`]=106]=`j`;e[e[`k`]=107]=`k`;e[e[`l`]=108]=`l`;e[e[`m`]=109]=`m`;e[e[`n`]=110]=`n`;e[e[`o`]=111]=`o`;e[e[`p`]=112]=`p`;e[e[`q`]=113]=`q`;e[e[`r`]=114]=`r`;e[e[`s`]=115]=`s`;e[e[`t`]=116]=`t`;e[e[`u`]=117]=`u`;e[e[`v`]=118]=`v`;e[e[`w`]=119]=`w`;e[e[`x`]=120]=`x`;e[e[`y`]=121]=`y`;e[e[`z`]=122]=`z`;e[e[`A`]=65]=`A`;e[e[`B`]=66]=`B`;e[e[`C`]=67]=`C`;e[e[`D`]=68]=`D`;e[e[`E`]=69]=`E`;e[e[`F`]=70]=`F`;e[e[`G`]=71]=`G`;e[e[`H`]=72]=`H`;e[e[`I`]=73]=`I`;e[e[`J`]=74]=`J`;e[e[`K`]=75]=`K`;e[e[`L`]=76]=`L`;e[e[`M`]=77]=`M`;e[e[`N`]=78]=`N`;e[e[`O`]=79]=`O`;e[e[`P`]=80]=`P`;e[e[`Q`]=81]=`Q`;e[e[`R`]=82]=`R`;e[e[`S`]=83]=`S`;e[e[`T`]=84]=`T`;e[e[`U`]=85]=`U`;e[e[`V`]=86]=`V`;e[e[`W`]=87]=`W`;e[e[`X`]=88]=`X`;e[e[`Y`]=89]=`Y`;e[e[`Z`]=90]=`Z`;e[e[`asterisk`]=42]=`asterisk`;e[e[`backslash`]=92]=`backslash`;e[e[`closeBrace`]=125]=`closeBrace`;e[e[`closeBracket`]=93]=`closeBracket`;e[e[`colon`]=58]=`colon`;e[e[`comma`]=44]=`comma`;e[e[`dot`]=46]=`dot`;e[e[`doubleQuote`]=34]=`doubleQuote`;e[e[`minus`]=45]=`minus`;e[e[`openBrace`]=123]=`openBrace`;e[e[`openBracket`]=91]=`openBracket`;e[e[`plus`]=43]=`plus`;e[e[`slash`]=47]=`slash`;e[e[`formFeed`]=12]=`formFeed`;e[e[`tab`]=9]=`tab`})(CharacterCodes||(CharacterCodes={}));
//!node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/string-intern.js
const cachedSpaces=new Array(20).fill(0).map((e,t)=>{return` `.repeat(t)});const maxCachedValues=200;const cachedBreakLinesWithSpaces={" ":{"\n":new Array(maxCachedValues).fill(0).map((e,t)=>{return`
`+` `.repeat(t)}),"\r":new Array(maxCachedValues).fill(0).map((e,t)=>{return`\r`+` `.repeat(t)}),"\r\n":new Array(maxCachedValues).fill(0).map((e,t)=>{return`\r
`+` `.repeat(t)})},"	":{"\n":new Array(maxCachedValues).fill(0).map((e,t)=>{return`
`+`	`.repeat(t)}),"\r":new Array(maxCachedValues).fill(0).map((e,t)=>{return`\r`+`	`.repeat(t)}),"\r\n":new Array(maxCachedValues).fill(0).map((e,t)=>{return`\r
`+`	`.repeat(t)})}};const supportedEols=[`
`,`\r`,`\r
`];
//!node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/format.js
function format$2(e,t,n){let r;let i;let a;let o;let s;if(t){o=t.offset;s=o+t.length;a=o;while(a>0&&!isEOL(e,a-1))a--;let c=s;while(c<e.length&&!isEOL(e,c))c++;i=e.substring(a,c);r=computeIndentLevel(i,n)}else{i=e;r=0;a=0;o=0;s=e.length}const c=getEOL(n,e);const l=supportedEols.includes(c);let u=0;let d=0;let f;if(n.insertSpaces)f=cachedSpaces[n.tabSize||4]??repeat(cachedSpaces[1],n.tabSize||4);else f=`	`;const p=f===`	`?`	`:` `;let m=createScanner(i,false);let h=false;function newLinesAndIndent(){if(u>1)return repeat(c,u)+repeat(f,r+d);const e=f.length*(r+d);if(!l||e>cachedBreakLinesWithSpaces[p][c].length)return c+repeat(f,r+d);if(e<=0)return c;return cachedBreakLinesWithSpaces[p][c][e]}function scanNext(){let e=m.scan();u=0;while(e===15||e===14){if(e===14&&n.keepLines)u+=1;else if(e===14)u=1;e=m.scan()}h=e===16||m.getTokenError()!==0;return e}const g=[];function addEdit(n,r,i){if(!h&&(!t||r<s&&i>o)&&e.substring(r,i)!==n)g.push({offset:r,length:i-r,content:n})}let _=scanNext();if(n.keepLines&&u>0)addEdit(repeat(c,u),0,0);if(_!==17){let e=m.getTokenOffset()+a;addEdit(f.length*r<20&&n.insertSpaces?cachedSpaces[f.length*r]:repeat(f,r),a,e)}while(_!==17){let e=m.getTokenOffset()+m.getTokenLength()+a;let t=scanNext();let r=``;let i=false;while(u===0&&(t===12||t===13)){let n=m.getTokenOffset()+a;addEdit(cachedSpaces[1],e,n);e=m.getTokenOffset()+m.getTokenLength()+a;i=t===12;r=i?newLinesAndIndent():``;t=scanNext()}if(t===2){if(_!==1)d--;if(n.keepLines&&u>0||!n.keepLines&&_!==1)r=newLinesAndIndent();else if(n.keepLines)r=cachedSpaces[1]}else if(t===4){if(_!==3)d--;if(n.keepLines&&u>0||!n.keepLines&&_!==3)r=newLinesAndIndent();else if(n.keepLines)r=cachedSpaces[1]}else{switch(_){case 3:case 1:d++;if(n.keepLines&&u>0||!n.keepLines)r=newLinesAndIndent();else r=cachedSpaces[1];break;case 5:if(n.keepLines&&u>0||!n.keepLines)r=newLinesAndIndent();else r=cachedSpaces[1];break;case 12:r=newLinesAndIndent();break;case 13:if(u>0)r=newLinesAndIndent();else if(!i)r=cachedSpaces[1];break;case 6:if(n.keepLines&&u>0)r=newLinesAndIndent();else if(!i)r=cachedSpaces[1];break;case 10:if(n.keepLines&&u>0)r=newLinesAndIndent();else if(t===6&&!i)r=``;break;case 7:case 8:case 9:case 11:case 2:case 4:if(n.keepLines&&u>0)r=newLinesAndIndent();else if((t===12||t===13)&&!i)r=cachedSpaces[1];else if(t!==5&&t!==17)h=true;break;case 16:h=true}if(u>0&&(t===12||t===13))r=newLinesAndIndent()}if(t===17){if(n.keepLines&&u>0)r=newLinesAndIndent();else r=n.insertFinalNewline?c:``}const o=m.getTokenOffset()+a;addEdit(r,e,o);_=t}return g}function repeat(e,t){let n=``;for(let r=0;r<t;r++)n+=e;return n}function computeIndentLevel(e,t){let n=0;let r=0;const i=t.tabSize||4;while(n<e.length){let t=e.charAt(n);if(t===cachedSpaces[1])r++;else if(t===`	`)r+=i;else break;n++}return Math.floor(r/i)}function getEOL(e,t){for(let e=0;e<t.length;e++){const n=t.charAt(e);if(n===`\r`){if(e+1<t.length&&t.charAt(e+1)===`
`)return`\r
`;return`\r`}else if(n===`
`)return`
`}return e&&e.eol||`
`}function isEOL(e,t){return`\r
`.indexOf(e.charAt(t))!==-1}
//!node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/parser.js
var ParseOptions;(function(e){e.DEFAULT={allowTrailingComma:false}})(ParseOptions||(ParseOptions={}));function parseTree$1(e,t=[],n=ParseOptions.DEFAULT){let r={type:`array`,offset:-1,length:-1,children:[],parent:void 0};function ensurePropertyComplete(e){if(r.type===`property`){r.length=e-r.offset;r=r.parent}}function onValue(e){r.children.push(e);return e}visit$1(e,{onObjectBegin:e=>{r=onValue({type:`object`,offset:e,length:-1,parent:r,children:[]})},onObjectProperty:(e,t,n)=>{r=onValue({type:`property`,offset:t,length:-1,parent:r,children:[]});r.children.push({type:`string`,value:e,offset:t,length:n,parent:r})},onObjectEnd:(e,t)=>{ensurePropertyComplete(e+t);r.length=e+t-r.offset;r=r.parent;ensurePropertyComplete(e+t)},onArrayBegin:(e,t)=>{r=onValue({type:`array`,offset:e,length:-1,parent:r,children:[]})},onArrayEnd:(e,t)=>{r.length=e+t-r.offset;r=r.parent;ensurePropertyComplete(e+t)},onLiteralValue:(e,t,n)=>{onValue({type:getNodeType(e),offset:t,length:n,parent:r,value:e});ensurePropertyComplete(t+n)},onSeparator:(e,t,n)=>{if(r.type===`property`){if(e===`:`)r.colonOffset=t;else if(e===`,`)ensurePropertyComplete(t)}},onError:(e,n,r)=>{t.push({error:e,offset:n,length:r})}},n);const i=r.children[0];if(i)delete i.parent;return i}function findNodeAtLocation$1(e,t){if(!e)return;let n=e;for(let e of t)if(typeof e===`string`){if(n.type!==`object`||!Array.isArray(n.children))return;let t=false;for(const r of n.children)if(Array.isArray(r.children)&&r.children[0].value===e&&r.children.length===2){n=r.children[1];t=true;break}if(!t)return}else{const t=e;if(n.type!==`array`||t<0||!Array.isArray(n.children)||t>=n.children.length)return;n=n.children[t]}return n}function visit$1(e,t,n=ParseOptions.DEFAULT){const r=createScanner(e,false);const i=[];let a=0;function toNoArgVisit(e){return e?()=>a===0&&e(r.getTokenOffset(),r.getTokenLength(),r.getTokenStartLine(),r.getTokenStartCharacter()):()=>true}function toOneArgVisit(e){return e?t=>a===0&&e(t,r.getTokenOffset(),r.getTokenLength(),r.getTokenStartLine(),r.getTokenStartCharacter()):()=>true}function toOneArgVisitWithPath(e){return e?t=>a===0&&e(t,r.getTokenOffset(),r.getTokenLength(),r.getTokenStartLine(),r.getTokenStartCharacter(),()=>i.slice()):()=>true}function toBeginVisit(e){return e?()=>{if(a>0)a++;else if(e(r.getTokenOffset(),r.getTokenLength(),r.getTokenStartLine(),r.getTokenStartCharacter(),()=>i.slice())===false)a=1}:()=>true}function toEndVisit(e){return e?()=>{if(a>0)a--;if(a===0)e(r.getTokenOffset(),r.getTokenLength(),r.getTokenStartLine(),r.getTokenStartCharacter())}:()=>true}const o=toBeginVisit(t.onObjectBegin),s=toOneArgVisitWithPath(t.onObjectProperty),c=toEndVisit(t.onObjectEnd),l=toBeginVisit(t.onArrayBegin),u=toEndVisit(t.onArrayEnd),d=toOneArgVisitWithPath(t.onLiteralValue),f=toOneArgVisit(t.onSeparator),p=toNoArgVisit(t.onComment),m=toOneArgVisit(t.onError);const h=n&&n.disallowComments;const g=n&&n.allowTrailingComma;function scanNext(){while(true){const e=r.scan();switch(r.getTokenError()){case 4:handleError(14);break;case 5:handleError(15);break;case 3:handleError(13);break;case 1:if(!h)handleError(11);break;case 2:handleError(12);break;case 6:handleError(16)}switch(e){case 12:case 13:if(h)handleError(10);else p();break;case 16:handleError(1);break;case 15:case 14:break;default:return e}}}function handleError(e,t=[],n=[]){m(e);if(t.length+n.length>0){let e=r.getToken();while(e!==17){if(t.indexOf(e)!==-1){scanNext();break}else if(n.indexOf(e)!==-1)break;e=scanNext()}}}function parseString(e){const t=r.getTokenValue();if(e)d(t);else{s(t);i.push(t)}scanNext();return true}function parseLiteral(){switch(r.getToken()){case 11:const e=r.getTokenValue();let t=Number(e);if(isNaN(t)){handleError(2);t=0}d(t);break;case 7:d(null);break;case 8:d(true);break;case 9:d(false);break;default:return false}scanNext();return true}function parseProperty(){if(r.getToken()!==10){handleError(3,[],[2,5]);return false}parseString(false);if(r.getToken()===6){f(`:`);scanNext();if(!parseValue())handleError(4,[],[2,5])}else handleError(5,[],[2,5]);i.pop();return true}function parseObject(){o();scanNext();let e=false;while(r.getToken()!==2&&r.getToken()!==17){if(r.getToken()===5){if(!e)handleError(4,[],[]);f(`,`);scanNext();if(r.getToken()===2&&g)break}else if(e)handleError(6,[],[]);if(!parseProperty())handleError(4,[],[2,5]);e=true}c();if(r.getToken()!==2)handleError(7,[2],[]);else scanNext();return true}function parseArray(){l();scanNext();let e=true;let t=false;while(r.getToken()!==4&&r.getToken()!==17){if(r.getToken()===5){if(!t)handleError(4,[],[]);f(`,`);scanNext();if(r.getToken()===4&&g)break}else if(t)handleError(6,[],[]);if(e){i.push(0);e=false}else i[i.length-1]++;if(!parseValue())handleError(4,[],[4,5]);t=true}u();if(!e)i.pop();if(r.getToken()!==4)handleError(8,[4],[]);else scanNext();return true}function parseValue(){switch(r.getToken()){case 3:return parseArray();case 1:return parseObject();case 10:return parseString(true);default:return parseLiteral()}}scanNext();if(r.getToken()===17){if(n.allowEmptyContent)return true;handleError(4,[],[]);return false}if(!parseValue()){handleError(4,[],[]);return false}if(r.getToken()!==17)handleError(9,[],[]);return true}function getNodeType(e){switch(typeof e){case`boolean`:return`boolean`;case`number`:return`number`;case`string`:return`string`;case`object`:if(!e)return`null`;else if(Array.isArray(e))return`array`;return`object`;default:return`null`}}
//!node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/edit.js
function setProperty(e,t,n,r){const i=t.slice();const a=parseTree$1(e,[]);let o=void 0;let s=void 0;while(i.length>0){s=i.pop();o=findNodeAtLocation$1(a,i);if(o===void 0&&n!==void 0){if(typeof s===`string`)n={[s]:n};else n=[n]}else break}if(!o){if(n===void 0)throw new Error(`Can not delete in empty document`);return withFormatting(e,{offset:a?a.offset:0,length:a?a.length:0,content:JSON.stringify(n)},r)}else if(o.type===`object`&&typeof s===`string`&&Array.isArray(o.children)){const t=findNodeAtLocation$1(o,[s]);if(t!==void 0){if(n===void 0){if(!t.parent)throw new Error(`Malformed AST`);const n=o.children.indexOf(t.parent);let i;let a=t.parent.offset+t.parent.length;if(n>0){let e=o.children[n-1];i=e.offset+e.length}else{i=o.offset+1;if(o.children.length>1)a=o.children[1].offset}return withFormatting(e,{offset:i,length:a-i,content:``},r)}else return withFormatting(e,{offset:t.offset,length:t.length,content:JSON.stringify(n)},r)}else{if(n===void 0)return[];const t=`${JSON.stringify(s)}: ${JSON.stringify(n)}`;const i=r.getInsertionIndex?r.getInsertionIndex(o.children.map(e=>e.children[0].value)):o.children.length;let a;if(i>0){let e=o.children[i-1];a={offset:e.offset+e.length,length:0,content:`,`+t}}else if(o.children.length===0)a={offset:o.offset+1,length:0,content:t};else a={offset:o.offset+1,length:0,content:t+`,`};return withFormatting(e,a,r)}}else if(o.type===`array`&&typeof s===`number`&&Array.isArray(o.children)){const t=s;if(t===-1){const t=`${JSON.stringify(n)}`;let i;if(o.children.length===0)i={offset:o.offset+1,length:0,content:t};else{const e=o.children[o.children.length-1];i={offset:e.offset+e.length,length:0,content:`,`+t}}return withFormatting(e,i,r)}else if(n===void 0&&o.children.length>=0){const t=s;const n=o.children[t];let i;if(o.children.length===1)i={offset:o.offset+1,length:o.length-2,content:``};else if(o.children.length-1===t){let e=o.children[t-1];let n=e.offset+e.length;i={offset:n,length:o.offset+o.length-2-n,content:``}}else i={offset:n.offset,length:o.children[t+1].offset-n.offset,content:``};return withFormatting(e,i,r)}else if(n!==void 0){let t;const i=`${JSON.stringify(n)}`;if(!r.isArrayInsertion&&o.children.length>s){const e=o.children[s];t={offset:e.offset,length:e.length,content:i}}else if(o.children.length===0||s===0)t={offset:o.offset+1,length:0,content:o.children.length===0?i:i+`,`};else{const e=s>o.children.length?o.children.length:s;const n=o.children[e-1];t={offset:n.offset+n.length,length:0,content:`,`+i}}return withFormatting(e,t,r)}else throw new Error(`Can not ${n===void 0?`remove`:r.isArrayInsertion?`insert`:`modify`} Array index ${t} as length is not sufficient`)}else throw new Error(`Can not add ${typeof s!==`number`?`index`:`property`} to parent of type ${o.type}`)}function withFormatting(e,t,n){if(!n.formattingOptions)return[t];let r=applyEdit(e,t);let i=t.offset;let a=t.offset+t.content.length;if(t.length===0||t.content.length===0){while(i>0&&!isEOL(r,i-1))i--;while(a<r.length&&!isEOL(r,a))a++}const o=format$2(r,{offset:i,length:a-i},{...n.formattingOptions,keepLines:false});for(let e=o.length-1;e>=0;e--){const t=o[e];r=applyEdit(r,t);i=Math.min(i,t.offset);a=Math.max(a,t.offset+t.length);a+=t.content.length-t.length}const s=e.length-(r.length-a)-i;return[{offset:i,length:s,content:r.substring(i,a)}]}function applyEdit(e,t){return e.substring(0,t.offset)+t.content+e.substring(t.offset+t.length)}
//!node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/main.js
var ScanError;(function(e){e[e[`None`]=0]=`None`;e[e[`UnexpectedEndOfComment`]=1]=`UnexpectedEndOfComment`;e[e[`UnexpectedEndOfString`]=2]=`UnexpectedEndOfString`;e[e[`UnexpectedEndOfNumber`]=3]=`UnexpectedEndOfNumber`;e[e[`InvalidUnicode`]=4]=`InvalidUnicode`;e[e[`InvalidEscapeCharacter`]=5]=`InvalidEscapeCharacter`;e[e[`InvalidCharacter`]=6]=`InvalidCharacter`})(ScanError||(ScanError={}));var SyntaxKind;(function(e){e[e[`OpenBraceToken`]=1]=`OpenBraceToken`;e[e[`CloseBraceToken`]=2]=`CloseBraceToken`;e[e[`OpenBracketToken`]=3]=`OpenBracketToken`;e[e[`CloseBracketToken`]=4]=`CloseBracketToken`;e[e[`CommaToken`]=5]=`CommaToken`;e[e[`ColonToken`]=6]=`ColonToken`;e[e[`NullKeyword`]=7]=`NullKeyword`;e[e[`TrueKeyword`]=8]=`TrueKeyword`;e[e[`FalseKeyword`]=9]=`FalseKeyword`;e[e[`StringLiteral`]=10]=`StringLiteral`;e[e[`NumericLiteral`]=11]=`NumericLiteral`;e[e[`LineCommentTrivia`]=12]=`LineCommentTrivia`;e[e[`BlockCommentTrivia`]=13]=`BlockCommentTrivia`;e[e[`LineBreakTrivia`]=14]=`LineBreakTrivia`;e[e[`Trivia`]=15]=`Trivia`;e[e[`Unknown`]=16]=`Unknown`;e[e[`EOF`]=17]=`EOF`})(SyntaxKind||(SyntaxKind={}));const parseTree=parseTree$1;const findNodeAtLocation=findNodeAtLocation$1;var ParseErrorCode;(function(e){e[e[`InvalidSymbol`]=1]=`InvalidSymbol`;e[e[`InvalidNumberFormat`]=2]=`InvalidNumberFormat`;e[e[`PropertyNameExpected`]=3]=`PropertyNameExpected`;e[e[`ValueExpected`]=4]=`ValueExpected`;e[e[`ColonExpected`]=5]=`ColonExpected`;e[e[`CommaExpected`]=6]=`CommaExpected`;e[e[`CloseBraceExpected`]=7]=`CloseBraceExpected`;e[e[`CloseBracketExpected`]=8]=`CloseBracketExpected`;e[e[`EndOfFileExpected`]=9]=`EndOfFileExpected`;e[e[`InvalidCommentToken`]=10]=`InvalidCommentToken`;e[e[`UnexpectedEndOfComment`]=11]=`UnexpectedEndOfComment`;e[e[`UnexpectedEndOfString`]=12]=`UnexpectedEndOfString`;e[e[`UnexpectedEndOfNumber`]=13]=`UnexpectedEndOfNumber`;e[e[`InvalidUnicode`]=14]=`InvalidUnicode`;e[e[`InvalidEscapeCharacter`]=15]=`InvalidEscapeCharacter`;e[e[`InvalidCharacter`]=16]=`InvalidCharacter`})(ParseErrorCode||(ParseErrorCode={}));function printParseErrorCode(e){switch(e){case 1:return`InvalidSymbol`;case 2:return`InvalidNumberFormat`;case 3:return`PropertyNameExpected`;case 4:return`ValueExpected`;case 5:return`ColonExpected`;case 6:return`CommaExpected`;case 7:return`CloseBraceExpected`;case 8:return`CloseBracketExpected`;case 9:return`EndOfFileExpected`;case 10:return`InvalidCommentToken`;case 11:return`UnexpectedEndOfComment`;case 12:return`UnexpectedEndOfString`;case 13:return`UnexpectedEndOfNumber`;case 14:return`InvalidUnicode`;case 15:return`InvalidEscapeCharacter`;case 16:return`InvalidCharacter`}return`<unknown ParseErrorCode>`}function format$1(e,t,n){return format$2(e,t,n)}function modify(e,t,n,r){return setProperty(e,t,n,r)}function applyEdits(e,t){let n=t.slice(0).sort((e,t)=>{const n=e.offset-t.offset;if(n===0)return e.length-t.length;return n});let r=e.length;for(let t=n.length-1;t>=0;t--){let i=n[t];if(i.offset+i.length<=r)e=applyEdit(e,i);else throw new Error(`Overlapping edit`);r=i.offset}return e}
//!extensions/oc-path/src/oc-path/jsonc/parse.ts
const MAX_PARSE_DEPTH=256;const MAX_JSONC_INPUT_BYTES=16777216;function findEffectiveJsoncNode(e,t){let n=e;for(const e of t){const t=n?.children??[];if(typeof e===`number`)n=n?.type===`array`?t[e]:void 0;else{const r=t.findLast(t=>t.type===`property`&&t.children?.[0]?.value===e);n=n?.type===`object`?r?.children?.[1]:void 0}}return n}function parseJsonc(e){const t=Buffer.byteLength(e,`utf8`);if(t>16777216)return{kind:`jsonc`,raw:e,root:null,oversizedInputBytes:t};if(e.trim().length===0)return{kind:`jsonc`,raw:e,root:null};const n=e.startsWith(``)?e.slice(1):e;const r=[];const i=parseTree(n,r,{allowTrailingComma:true,disallowComments:false,allowEmptyContent:true});const a=createLineForOffset(n);const o=i?i.offset+i.length:0;let s=null;if(i&&r.every(e=>{const t=printParseErrorCode(e.error);return t===`EndOfFileExpected`||t===`InvalidSymbol`&&e.offset>=o}))try{s=nodeToJsoncValue(i,a,0)}catch{}return{kind:`jsonc`,raw:e,root:s}}function nodeToJsoncValue(e,t,n){if(n>MAX_PARSE_DEPTH)throw new Error(`structural depth exceeded MAX_PARSE_DEPTH (${MAX_PARSE_DEPTH})`);const r=t(e.offset);switch(e.type){case`object`:return{kind:`object`,line:r,entries:(e.children??[]).flatMap(e=>{if(e.type!==`property`)return[];const r=e.children?.[0];const i=e.children?.[1];if(!r||!i)return[];return[{key:String(r.value),line:t(r.offset),value:nodeToJsoncValue(i,t,n+1)}]})};case`array`:return{kind:`array`,line:r,items:(e.children??[]).map(e=>nodeToJsoncValue(e,t,n+1))};case`string`:return{kind:`string`,value:String(e.value),line:r};case`number`:return{kind:`number`,value:Number(e.value),line:r};case`boolean`:return{kind:`boolean`,value:Boolean(e.value),line:r};case`null`:return{kind:`null`,line:r};default:return{kind:`null`,line:r}}}function createLineForOffset(e){const t=[0];for(let n=0;n<e.length;n++)if(e[n]===`
`||e[n]===`\r`&&e[n+1]!==`
`)t.push(n+1);return e=>{let n=0;let r=t.length-1;while(n<=r){const i=Math.floor((n+r)/2);if((t[i]??0)<=e)n=i+1;else r=i-1}return Math.max(1,r+1)}}
//!extensions/oc-path/src/oc-path/jsonc/edit.ts
const FORMATTING={insertSpaces:true,tabSize:2};function setJsoncOcPath(e,t,n){if(e.root===null)throw new OcPathEditError(`no-root`);const r=resolveEditTarget(e.root,splitOcPathSlots(t.section,t.item,t.field));if(r===null)throw new OcPathEditError(`unresolved`);const i=parseTree(e.raw,[],{allowTrailingComma:true});const a=i&&findEffectiveJsoncNode(i,r.path);if(!a)throw new OcPathEditError(`unresolved`);const o=JSON.stringify(jsoncValueToJson(n,`oc://${t.file}/${r.path.join(`/`)}`));const s=applyEdits(e.raw,[{offset:a.offset,length:a.length,content:o}]);const c={offset:a.offset,length:o.length};return reparse(applyEdits(s,format$1(s,c,{...FORMATTING,keepLines:false})))}function insertJsoncOcPath(e,t,n,r){if(e.root===null)throw new OcPathEditError(`no-root`);const i=resolveEditTarget(e.root,splitOcPathSlots(t.section,t.item,t.field));if(i===null)throw new OcPathEditError(`unresolved`);if(typeof n===`string`){if(i.value.kind!==`object`||i.value.entries.some(e=>e.key===n))throw new OcPathEditError(`unresolved`);guardedJsoncKeyPath(n,`oc://${[t.file,...i.path].join(`/`)}`)}else if(i.value.kind!==`array`)throw new OcPathEditError(`unresolved`);const a=parseTree(e.raw,[],{allowTrailingComma:true});if(a&&findNodeAtLocation(a,i.path)!==findEffectiveJsoncNode(a,i.path))throw new OcPathEditError(`not-writable`,`insertion under a duplicated key is ambiguous; merge the duplicate keys into one (keeping the last, effective value), then retry the insertion`);const o=typeof n===`number`&&n<0?-1:n;return applyJsoncEdit(e,[...i.path,o],r,typeof o===`number`,t.file)}function applyJsoncEdit(e,t,n,r,i){const a=modify(e.raw,t,jsoncValueToJson(n,`oc://${i}/${t.join(`/`)}`),{formattingOptions:FORMATTING,isArrayInsertion:r});if(a.length===0)throw new OcPathEditError(`unresolved`);return reparse(applyEdits(e.raw,a))}function reparse(e){const t=parseJsonc(e);if(t.root===null)throw new OcPathEditError(`unresolved`);return t}function resolveEditTarget(e,t){const n=resolveJsoncValueOcPath(e,t);return n&&{path:n.path,value:n.kind===`object-entry`?n.node.value:n.node}}function jsoncValueToJson(e,t){if(e.kind===`null`)return null;if(e.kind===`string`||e.kind===`number`||e.kind===`boolean`){guardSentinel(e.value,t);return e.value}if(e.kind===`array`)return e.items.map((e,n)=>jsoncValueToJson(e,`${t}/${n}`));return Object.fromEntries(emitJsoncObjectEntries(e.entries,t,(e,t)=>[e.key,jsoncValueToJson(e.value,t)]))}
//!extensions/oc-path/src/oc-path/jsonc/resolve.ts
function resolveJsoncOcPath(e,t){if(e.root===null)return null;const n=splitOcPathSlots(t.section,t.item,t.field);if(n.length===0)return{kind:`root`,node:e};return resolveJsoncValueOcPath(e.root,n)}
//!extensions/oc-path/src/oc-path/jsonl/parse.ts
function parseJsonl(e){const t=sourceLineEnding(e);let n=e.endsWith(`\r
`)?e.slice(0,-2):e.endsWith(`
`)?e.slice(0,-1):e;n=n.replace(/\r\n/g,`
`);const r=[];if(e.length===0)return{kind:`jsonl`,raw:e,lines:r,lineEnding:t};n.split(`
`).forEach((e,t)=>{const n=t+1;if(e.trim().length===0){r.push({kind:`blank`,line:n,raw:e});return}const i=parseJsonc(e);if(i.root===null){r.push({kind:`malformed`,line:n,raw:e});return}r.push({kind:`value`,line:n,value:i.root,raw:e})});return{kind:`jsonl`,raw:e,lines:r,lineEnding:t}}
//!extensions/oc-path/src/oc-path/jsonl/edit.ts
function renderJsoncValue(e,t,n=[]){if(e.kind===`null`)return`null`;if(e.kind===`number`||e.kind===`boolean`)return String(e.value);if(e.kind===`string`){if(e.value.includes(`__OPENCLAW_REDACTED__`))throw new OcEmitSentinelError(`${t}/${n.join(`/`)}`);return JSON.stringify(e.value)}if(e.kind===`array`)return`[${e.items.map((e,r)=>renderJsoncValue(e,t,[...n,String(r)])).join(`,`)}]`;const r=n.length?`${t}/${n.join(`/`)}`:t;return`{${emitJsoncObjectEntries(e.entries,r,e=>`${JSON.stringify(e.key)}:${renderJsoncValue(e.value,t,[...n,e.key])}`).join(`,`)}}`}function setJsonlOcPath(e,t,n){const r=t.section;if(r===void 0)throw new OcPathEditError(`unresolved`);const i=pickJsonlLineIndex(e,r);const a=e.lines[i];if(a===void 0)throw new OcPathEditError(`unresolved`);if(a.kind!==`value`)throw new OcPathEditError(`not-a-value-line`);const o=resolveJsoncValueOcPath(a.value,splitOcPathSlots(t.item,t.field));if(o===null)throw new OcPathEditError(`unresolved`);const s=o.path;const c=a.raw.startsWith(``)?1:0;const l=parseTree(a.raw.slice(c),[],{allowTrailingComma:true});const u=l&&findEffectiveJsoncNode(l,s);if(!u)throw new OcPathEditError(`unresolved`);const d=renderJsoncValue(n,`oc://${t.file}/L${a.line}`,s.map(String));const f=sourceLineOffset(e.raw,a.line,/\n/g)+c+u.offset;const p=e.raw.slice(0,f)+d+e.raw.slice(f+u.length);return parseJsonl(p)}function appendJsonlOcPath(e,t){const n=e.raw.endsWith(`\r
`)?`\r
`:e.raw.endsWith(`
`)?`
`:``;const r=e.raw.length>0&&!n?e.lineEnding??`
`:``;const i=renderJsoncValue(t,`oc:///L${e.raw.split(`
`).length+(r?1:0)}`);return parseJsonl(e.raw+r+i+n)}
//!extensions/oc-path/src/oc-path/jsonl/resolve.ts
function resolveJsonlOcPath(e,t){const n=t.section;if(n===void 0)return{kind:`root`,node:e};const r=pickJsonlLine(e,n);if(r===null)return null;if(t.item===void 0&&t.field===void 0)return{kind:`line`,node:r};if(r.kind!==`value`)return null;const i=resolveJsoncValueOcPath(r.value,splitOcPathSlots(t.item,t.field));if(i===null)return null;return{...i,line:r.line}}
//!extensions/oc-path/src/oc-path/slug.ts
const NON_SLUG_CHARS=/[^a-z0-9-]+/g;const COLLAPSE_HYPHENS=/-+/g;const TRIM_HYPHENS=/^-+|-+$/g;function slugify(e){return e.toLowerCase().replace(NON_SLUG_CHARS,`-`).replace(COLLAPSE_HYPHENS,`-`).replace(TRIM_HYPHENS,``)}
//!extensions/oc-path/src/oc-path/parse.ts
const FENCE=`---`;const BOM=``;const md=new MarkdownItCallable({html:true});function parseMdItemKeyValue(e){const t=/^([^:\r\n]+?)[ \t]*:\s*(.+)$/s.exec(e);const n=t===null?``:expectDefined(t[2],`item value capture`).trim();return t===null||n===``?void 0:{key:expectDefined(t[1],`item key capture`).trim(),value:n}}function parseMd(e){const t=(e.startsWith(BOM)?e.slice(1):e).split(/\r\n?|\n/);const n=detectFrontmatter(t);const r=n===null?0:n.endLine+1;const i=t.slice(r);const a=r+1;const{preamble:o,blocks:s}=walkBlocks(md.parse(i.join(`
`),{}),i,a);return{kind:`md`,raw:e,frontmatter:n?.entries??[],...n===null?{}:{frontmatterEndLine:n.endLine+1},preamble:o,blocks:s}}function detectFrontmatter(e){if(e.length<2||e.at(0)!==FENCE)return null;let t=-1;for(const[n,r]of e.slice(1).entries())if(r===FENCE){t=n+1;break}if(t===-1)return null;const n=e.slice(1,t);const r=new LineCounter;const i=n.join(`
`)+`
`;const a=parseDocument(i,{prettyErrors:false,lineCounter:r});const o=[];if(a.errors.length===0&&isMap(a.contents)){for(const{key:e,value:t}of a.contents.items){if(!isScalar(e)||!e.range)continue;const{line:a,col:s}=r.linePos(e.range[0]);const c=expectDefined(n.at(a-1),`frontmatter key source line`);if(s===1&&e.source!==void 0&&/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(e.source)){const n=c.slice(e.range[1]-e.range[0]).replace(/^\s*:/,``).trim();o.push({key:e.source,value:isScalar(t)?scalarText(t):isCollection(t)&&t.flow&&t.range?i.slice(e.range[1],t.range[1]).replace(/^\s*:\s*/,``).trimEnd():n===``?stringify(t,{verifyAliasOrder:false}).trimEnd():unquote(n),line:a+1})}}return{entries:o,endLine:t}}for(const[e,t]of n.entries()){const r=/^([a-zA-Z_][a-zA-Z0-9_-]*)\s*:\s*(.*)$/.exec(t);if(r!==null){const t=expectDefined(r[1],`frontmatter key capture`);const i=expectDefined(r[2],`frontmatter value capture`).trim();const a=i===``||BLOCK_SCALAR_HEADER_RE.test(i)?readIndentedValue(n,e)??unquote(i):unquote(i);o.push({key:t,value:a,line:e+2})}}return{entries:o,endLine:t}}const BLOCK_SCALAR_HEADER_RE=/^[|>](?:[+-]?\d*|\d*[+-]?)\s*(?:#.*)?$/;function readIndentedValue(e,t){const n=e.slice(t+1);const r=n.findIndex(e=>e!==``&&!/^\s/.test(e));const i=r===-1?n:n.slice(0,r);const a=parseDocument(`${e[t]}\n${i.join(`
`)}\n`,{prettyErrors:false});const o=a.errors.length===0&&isMap(a.contents)?a.contents.items[0]?.value:null;if(isScalar(o))return scalarText(o);return o===null||o===void 0?void 0:stringify(o,{verifyAliasOrder:false}).trimEnd()}function scalarText(e){return typeof e.value===`string`?e.value:e.source??``}function unquote(e){const t=parseDocument(e,{prettyErrors:false});if(t.errors.length===0&&isScalar(t.contents))return t.contents.value===null&&t.contents.source===``?e:scalarText(t.contents);if(t.errors.length===0&&t.contents===null&&e.startsWith(`#`))return``;if(e.length>=2){const t=e.charCodeAt(0);const n=e.charCodeAt(e.length-1);if(t===34||t===39)return t===n?e.slice(1,-1):e}return e}function walkBlocks(e,t,n){const r=[];for(const[t,n]of e.entries())if(n.type===`heading_open`&&n.tag===`h2`&&n.markup===`##`&&n.map!==null){const i=e[t+1];r.push({tokenIdx:t,lineIdx:expectDefined(n.map.at(0),`heading token map start`),text:i?.content??``})}if(r.length===0)return{preamble:t.join(`
`),blocks:[]};const i=expectDefined(r.at(0),`non-empty heading list`);const a=t.slice(0,i.lineIdx).join(`
`);const o=[];for(const[i,a]of r.entries()){const s=r.at(i+1);const c=a.lineIdx;const l=s?.lineIdx??t.length;const u=a.tokenIdx+3;const d=s?.tokenIdx??e.length;const f=e.slice(u,d);const p=[];for(const[e,t]of f.entries()){if(t.type!==`list_item_open`||t.map===null)continue;let r=0;let i=``;let a=null;for(let t=e+1;t<f.length;t++){const e=expectDefined(f[t],`item scan index is in bounds`);if(e.type===`list_item_close`&&r===0)break;if(e.type===`bullet_list_open`||e.type===`ordered_list_open`)r++;else if(e.type===`bullet_list_close`||e.type===`ordered_list_close`)r--;else if(e.type===`inline`&&r===0&&i===``){i=e.content;a=e.map===null?null:n+expectDefined(e.map.at(0),`inline source line`)}}const o=parseMdItemKeyValue(i);p.push({text:i,slug:slugify(o?.key??i),line:n+expectDefined(t.map.at(0),`list item token map start`),textLine:a,...o===void 0?{}:{kv:o}})}o.push({heading:a.text,slug:slugify(a.text),line:n+c,bodyText:t.slice(c+1,l).join(`
`),items:p})}return{preamble:a,blocks:o}}
//!extensions/oc-path/src/oc-path/yaml/resolve.ts
function resolveYamlOcPath(e,t){const n=splitOcPathSlots(t.section,t.item,t.field);if(n.length===0)return{kind:`root`,node:e};return walkNode(e.doc,e.doc.contents,n,0,[])}function derefYamlNode(e,t){if(isAlias(t))return e===void 0?null:t.resolve(e)??null;return t??null}function walkNode(e,t,n,r,i){const a=derefYamlNode(e,t);if(a===null)return null;const o=n[r];if(o===void 0){if(isMap(a))return{kind:`map`,node:a,path:i};if(isSeq(a))return{kind:`seq`,node:a,path:i};if(isScalar(a))return{kind:`scalar`,node:a,value:a.value,path:i};return null}let s=unquoteSeg(o);if(o.length===0)return null;if(isPositionalSeg(o)){const e=resolveYamlPositionalSegment(a,o);if(e!==null)s=e}if(isMap(a)){const t=a.items.find(e=>{const t=isScalar(e.key)?e.key.value:e.key;return String(t)===s});if(t===void 0)return null;const o=isScalar(t.key)?t.key.value:s;const c=[...i,o];const l=derefYamlNode(e,t.value);if(r===n.length-1&&isScalar(l))return{kind:`pair`,node:l,value:l.value,path:c};return walkNode(e,l,n,r+1,c)}if(isSeq(a)){const t=parseArrayIndexSegment(s,a.items.length);if(t===null)return null;const o=a.items[t];return walkNode(e,o,n,r+1,[...i,t])}return null}function resolveYamlPositionalSegment(e,t){if(isMap(e)){const n=e.items.map(e=>String(isScalar(e.key)?e.key.value:e.key));return resolvePositionalSeg(t,{indexable:false,size:n.length,keys:n})}if(isSeq(e))return resolvePositionalSeg(t,{indexable:true,size:e.items.length});return null}
//!extensions/oc-path/src/oc-path/yaml/edit.ts
function setYamlOcPath(e,t,n){if(e.doc.errors.length>0)throw new OcPathEditError(`parse-error`);if(e.doc.contents===null)throw new OcPathEditError(`no-root`);guardYamlSentinel(n,formatOcPath(t));const r=resolveYamlOcPath(e,t);if(r===null||r.kind===`root`)throw new OcPathEditError(`unresolved`);const i=r.path;if(i.some(e=>e!==null&&typeof e===`object`))throw new OcPathEditError(`unresolved`);if(!e.doc.hasIn(i))throw new OcPathEditError(`unresolved`);const{doc:a,lineCounter:o,numericSources:s}=cloneDoc(e);const c=a.getIn(i,true);if(isScalar(c))s.delete(c);a.setIn(i,n);return{kind:`yaml`,raw:stringifyDoc(a,e.raw),doc:a,lineCounter:o}}function insertYamlOcPath(e,t,n,r){if(e.doc.errors.length>0)throw new OcPathEditError(`parse-error`);if(e.doc.contents===null)throw new OcPathEditError(`no-root`);guardYamlSentinel(r,`${formatOcPath(t)}/${formatInsertionMarker(n)}`);const i=resolveYamlOcPath(e,t);if(i===null)throw new OcPathEditError(`unresolved`);const a=i.kind===`root`?[]:i.path;const{doc:o,lineCounter:s}=cloneDoc(e);const c=a.length===0?o.contents:o.getIn(a,false);if(c===void 0||c===null)throw new OcPathEditError(`unresolved`);if(isMap(c)){if(typeof n!==`object`||n.kind!==`keyed`)throw new OcPathEditError(`unresolved`);guardSentinel(n.key,`${formatOcPath(t)}/${formatInsertionMarker(n)}`);if(c.items.some(e=>String(isScalar(e.key)?e.key.value:e.key)===n.key))throw new OcPathEditError(`unresolved`);o.setIn([...a,n.key],r);return{kind:`yaml`,raw:stringifyDoc(o,e.raw),doc:o,lineCounter:s}}if(isSeq(c)){if(typeof n===`object`&&n.kind===`keyed`)throw new OcPathEditError(`unresolved`);if(n===`+`)o.addIn(a,r);else if(typeof n===`object`&&n.kind===`indexed`){const e=Math.min(n.index,c.items.length);c.items.splice(e,0,o.createNode(r))}return{kind:`yaml`,raw:stringifyDoc(o,e.raw),doc:o,lineCounter:s}}throw new OcPathEditError(`unresolved`)}function hasSameDocumentValue(e,t){try{const n=parseDocument(e,{prettyErrors:false});const r=parseDocument(t,{prettyErrors:false});if(n.errors.length>0||r.errors.length>0)return false;return isDeepStrictEqual(n.toJS(),r.toJS())}catch{return false}}function stringifyDoc(e,t){const n=t.startsWith(``)?``:``;const r=sourceLineEnding(t);const i=e.toString().replace(/\n/g,r);if(t.endsWith(`
`))return n+i;const a=i.slice(0,-r.length);return n+(hasSameDocumentValue(i,a)?a:i)}function formatInsertionMarker(e){if(e===`+`)return`+`;return e.kind===`keyed`?`+${e.key}`:`+${e.index}`}function guardYamlSentinel(e,t){guardSentinel(e,t);if(Array.isArray(e)){e.forEach((e,n)=>guardYamlSentinel(e,`${t}/${n}`));return}if(e!==null&&typeof e===`object`)for(const[n,r]of Object.entries(e)){guardSentinel(n,`${t}/${n}`);guardYamlSentinel(r,`${t}/${n}`)}}function cloneDoc(e){const t=new LineCounter;const n=/* @__PURE__ */ new WeakMap;const r=parseDocument(e.raw,{keepSourceTokens:true,prettyErrors:false,lineCounter:t,customTags:e=>e.map(e=>{if(typeof e===`string`||e.collection!==void 0||![`tag:yaml.org,2002:int`,`tag:yaml.org,2002:float`].includes(e.tag))return e;const t=e.stringify;if(typeof t!==`function`)return e;const preserveSource=(e,...r)=>{const i=n.get(e);return i&&Object.is(e.value,i.value)?i.source:t(e,...r)};return{...e,stringify:preserveSource}})});visit(r,{Scalar(e,t){if(typeof t.value===`number`&&t.source!==void 0)n.set(t,{value:t.value,source:t.source})}});return{doc:r,lineCounter:t,numericSources:n}}
//!extensions/oc-path/src/oc-path/universal.ts
function detectInsertion(e,t){const n=e.field!==void 0?`field`:e.item!==void 0?`item`:`section`;const r=(t===`jsonc`||t===`yaml`)&&!e[n]?.startsWith(`+`)?splitOcPathSlots(e[n]):[e[n]];const i=r.pop();if(!i?.startsWith(`+`))return null;const a=i.slice(1);const o=a.length===0?`+`:/^\d+$/.test(a)?{kind:`indexed`,index:Number(a)}:{kind:`keyed`,key:a};return{parentPath:{file:e.file,...n!==`section`&&e.section!==void 0?{section:e.section}:{},...n!==`item`&&e.item!==void 0?{item:e.item}:{},...n!==`field`&&e.field!==void 0?{field:e.field}:{},...r.length>0?{[n]:r.join(`.`)}:{},...e.session!==void 0?{session:e.session}:{}},marker:o}}function resolveOcPath(e,t){if(isPattern(t))throw new OcPathError(`resolveOcPath received a wildcard pattern; use findOcPaths instead: ${formatOcPath(t)}`,`OC_PATH_WILDCARD_IN_RESOLVE`);const n=detectInsertion(t,e.kind);if(n!==null){if(e.kind===`md`){const t=n.parentPath;if(t.section===void 0)return{kind:`insertion-point`,container:`md-file`,line:1};if(t.section===`[frontmatter]`&&t.item===void 0&&t.field===void 0)return{kind:`insertion-point`,container:`md-frontmatter`,line:1};if(t.item===void 0&&t.field===void 0){const n=resolveMdOcPath(e,t);if(n===null||n.kind!==`block`)return null;return{kind:`insertion-point`,container:`md-section`,line:n.node.line}}return null}if(e.kind===`jsonc`)return resolveJsoncInsertion(e,n);if(e.kind===`jsonl`){if(n.parentPath.section!==void 0)return null;return{kind:`insertion-point`,container:`jsonl-file`,line:(e.lines.at(-1)?.line??0)+1}}const t=resolveYamlOcPath(e,n.parentPath);if(t===null)return null;if(t.kind===`root`){const t=e.doc.contents;if(isMap(t))return{kind:`insertion-point`,container:`yaml-map`,line:1};if(isSeq(t))return{kind:`insertion-point`,container:`yaml-seq`,line:1};return null}if(t.kind===`pair`||t.kind===`scalar`)return null;return{kind:`insertion-point`,container:`yaml-${t.kind}`,line:yamlLine(e,t.node)}}if(e.kind===`md`){const n=resolveMdOcPath(e,t);if(n===null||n.kind===`root`)return resolveUniversalRoot(e,n);if(n.kind===`frontmatter`)return{kind:`leaf`,valueText:n.node.value,leafType:`string`,line:n.node.line};if(n.kind===`block`||n.kind===`item`)return{kind:`node`,descriptor:`md-${n.kind}`,line:n.node.line};return{kind:`leaf`,valueText:n.value,leafType:`string`,line:n.node.line}}if(e.kind===`jsonc`){const n=resolveJsoncOcPath(e,t);if(n===null||n.kind===`root`)return resolveUniversalRoot(e,n);if(n.kind===`object-entry`)return jsoncValueToMatch(n.node.value,n.node.line);return jsoncValueToMatch(n.node,n.node.line??1)}if(e.kind===`jsonl`){const n=resolveJsonlOcPath(e,t);if(n===null||n.kind===`root`)return resolveUniversalRoot(e,n);if(n.kind===`line`)return{kind:`node`,descriptor:`jsonl-line`,line:n.node.line};if(n.kind===`object-entry`)return jsoncValueToMatch(n.node.value,n.line);return jsoncValueToMatch(n.node,n.line)}const r=resolveYamlOcPath(e,t);if(r===null||r.kind===`root`)return resolveUniversalRoot(e,r);if(r.kind===`scalar`||r.kind===`pair`)return yamlScalarToMatch(r.value,yamlLine(e,r.node));return{kind:`node`,descriptor:`yaml-${r.kind}`,line:yamlLine(e,r.node)}}function resolveUniversalRoot(e,t){return t===null?null:{kind:`root`,ast:e,line:1}}function jsoncValueToMatch(e,t){if(e.kind===`object`||e.kind===`array`)return{kind:`node`,descriptor:`jsonc-${e.kind}`,line:t};return{kind:`leaf`,valueText:e.kind===`null`?`null`:String(e.value),leafType:e.kind,line:t}}function yamlScalarToMatch(e,t){const n=typeof e;if(n===`number`||n===`boolean`)return{kind:`leaf`,valueText:String(e),leafType:n,line:t};if(e===null)return{kind:`leaf`,valueText:`null`,leafType:`null`,line:t};return{kind:`leaf`,valueText:yamlScalarToText$1(e),leafType:`string`,line:t}}function yamlScalarToText$1(e){if(typeof e===`string`)return e;if(typeof e===`bigint`||typeof e===`symbol`)return e.toString();if(e instanceof Date)return e.toISOString();return JSON.stringify(e)??``}function yamlLine(e,t){const n=t.range;return n?e.lineCounter.linePos(n[0]).line:1}function resolveJsoncInsertion(e,t){const n=resolveJsoncOcPath(e,t.parentPath);if(n===null)return null;let r;if(n.kind===`root`){if(e.root===null)return null;r=e.root}else if(n.kind===`object-entry`)r=n.node.value;else r=n.node;const i=r.line??1;if(r.kind===`object`||r.kind===`array`)return{kind:`insertion-point`,container:`jsonc-${r.kind}`,line:i};return null}function setOcPath(e,t,n,r={}){if(r.valueJson===true&&(e.kind===`md`||e.kind===`yaml`))throw new OcPathEditError(`not-writable`,`--value-json only applies to JSON, JSONC and JSONL; pass a plain <value> without --value-json for Markdown or YAML`);if(isPattern(t))throw new OcPathEditError(`wildcard-not-allowed`,`setOcPath requires a concrete path; use findOcPaths to enumerate matches first`);const i=detectInsertion(t,e.kind);if(i!==null){if(e.kind===`md`){guardSentinel(n,()=>formatOcPath(t));return setMdInsertion(e,i,n)}if(e.kind===`jsonc`)return setJsoncInsertion(e,i,n);if(e.kind===`jsonl`){if(i.parentPath.section!==void 0||i.marker!==`+`)throw new OcPathEditError(`not-writable`,`jsonl insertion only supports oc://FILE/+ append`);const t=parseJsonInput(n,`jsonl line append`);return appendJsonlOcPath(e,t)}if(e.doc.errors.length>0)throw new OcPathEditError(`parse-error`);return insertYamlOcPath(e,i.parentPath,i.marker,parseYamlInput(n))}if(e.kind===`md`)return setMdOcPath(e,t,n);if(e.kind===`jsonc`||e.kind===`jsonl`)return setStructuredLeaf(e,t,n,r);return setYamlLeaf(e,t,n)}function setStructuredLeaf(e,t,n,r){const i=e.kind===`jsonc`?resolveJsoncOcPath(e,t):resolveJsonlOcPath(e,t);if(i===null)throw new OcPathEditError(`unresolved`);if(i.kind===`root`)throw new OcPathEditError(`not-writable`,`root replacement is not supported via setOcPath`);const set=n=>e.kind===`jsonc`?setJsoncOcPath(e,t,n):setJsonlOcPath(e,t,n);if(i.kind===`line`)return set(parseJsonInput(n,`line replacement`));const a=i.kind===`object-entry`?i.node.value:i.node;const o=r.valueJson===true?parseJsoncReplacement(n,a):coerceJsoncLeaf(n,a);if(o===null)throw new OcPathEditError(`parse-error`,`cannot coerce "${n}" to ${a.kind}`);return set(o)}function parseJsoncReplacement(e,t){const n=tryParseJson(e);if(n===void 0)return null;const r=jsonToJsoncValue(n);if(r===null)return null;return t.line===void 0?r:{...r,line:t.line}}function setMdInsertion(e,t,n){const r=t.parentPath;if(r.section===void 0){if(t.marker!==`+`)throw new OcPathEditError(`not-writable`,"md file-level insertion uses bare `+`");const r=e.raw.replace(/^\uFEFF/,``).length>0&&!e.raw.replace(/\r\n?/g,`
`).endsWith(`

`)?`
`:``;return insertMdSource(e,e.raw.length,`${r}## ${n}`,(e,t)=>({...e,blocks:[...e.blocks,{heading:n,slug:slugify(n),line:t+r.length,bodyText:``,items:[]}]}))}if(r.section===`[frontmatter]`&&r.item===void 0&&r.field===void 0){if(typeof t.marker!==`object`||t.marker.kind!==`keyed`)throw new OcPathEditError(`not-writable`,`md frontmatter insertion requires +key`);const r=t.marker.key;if(!/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(r))throw new OcPathEditError(`not-writable`,`md frontmatter keys must start with an ASCII letter or underscore and contain only ASCII letters, digits, underscores, or hyphens`);if(e.frontmatter.some(e=>e.key===r))throw new OcPathEditError(`type-mismatch`,`frontmatter key '${r}' already exists; use set, not insert`);const i=e.frontmatterEndLine;const a=i!==void 0;const o=i!==void 0?sourceLineOffset(e.raw,i):e.raw.startsWith(``)?1:0;const s=`${r}: ${formatFrontmatterValue(n)}`;return insertMdSource(e,o,a?s:`---\n${s}\n---`,(e,t)=>({...e,frontmatterEndLine:a?e.frontmatterEndLine:t+2,frontmatter:[...e.frontmatter,{key:r,value:n,line:t+(a?0:1)}]}))}if(r.item===void 0&&r.field===void 0){if(t.marker!==`+`)throw new OcPathEditError(`not-writable`,"md section insertion uses bare `+`");const i=resolveMdOcPath(e,r);if(i?.kind!==`block`)throw new OcPathEditError(`unresolved`);const a=e.blocks.indexOf(i.node);const o=parseMdItemKeyValue(n);const s=`- ${n}`;const c=e.blocks[a+1];const l=c?sourceLineOffset(e.raw,c.line):e.raw.length;return insertMdSource(e,l,s,(e,t)=>({...e,blocks:e.blocks.map((e,r)=>r!==a?e:{...e,items:[...e.items,{text:n,slug:slugify(o?.key??n),line:t,textLine:t,...o===void 0?{}:{kv:o}}]})}))}throw new OcPathEditError(`not-writable`)}function setJsoncInsertion(e,t,n){const r=resolveJsoncInsertion(e,t);if(r===null)throw new OcPathEditError(`unresolved`);const i=parseJsonInput(n,`jsonc insertion`);if(r.container===`jsonc-array`){if(typeof t.marker===`object`&&t.marker.kind===`keyed`)throw new OcPathEditError(`type-mismatch`,`cannot insert by key into array`);const n=t.marker===`+`?-1:t.marker.index;return insertJsoncOcPath(e,t.parentPath,n,i)}if(typeof t.marker!==`object`||t.marker.kind!==`keyed`)throw new OcPathEditError(`type-mismatch`,`jsonc object insertion requires +key`);return insertJsoncOcPath(e,t.parentPath,t.marker.key,i)}function setYamlLeaf(e,t,n){if(e.doc.errors.length>0)throw new OcPathEditError(`parse-error`);const r=resolveYamlOcPath(e,t);if(r===null)throw new OcPathEditError(`unresolved`);if(r.kind===`root`||r.kind===`map`||r.kind===`seq`)throw new OcPathEditError(`not-writable`);const i=r.value;const a=coerceYamlValue(n,i);if(a===void 0)throw new OcPathEditError(`parse-error`,`cannot coerce "${n}" to ${typeof i}`);return setYamlOcPath(e,t,a)}function coerceYamlValue(e,t){if(typeof t===`number`){if(!/^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/.test(e))return;const t=Number(e);return Number.isFinite(t)?t:void 0}if(typeof t===`boolean`){if(e===`true`)return true;if(e===`false`)return false;return}if(t===null)return e===`null`?null:void 0;return e}function parseYamlInput(e){const t=tryParseJson(e);return t===void 0?e:t}function coerceJsoncLeaf(e,t){const n=t.line!==void 0?{line:t.line}:{};if(t.kind===`string`)return{kind:`string`,value:e,...n};if(t.kind===`number`){const t=e.trim()===``?NaN:Number(e);return Number.isFinite(t)?{kind:`number`,value:t,...n}:null}if(t.kind===`boolean`){if(e===`true`)return{kind:`boolean`,value:true,...n};if(e===`false`)return{kind:`boolean`,value:false,...n};return null}if(t.kind===`null`)return e===`null`?{kind:`null`,...n}:null;return null}function tryParseJson(e){try{return JSON.parse(e)}catch{return}}function parseJsonInput(e,t){const n=tryParseJson(e);if(n===void 0)throw new OcPathEditError(`parse-error`,`${t} requires JSON value`);const r=jsonToJsoncValue(n);if(r===null)throw new OcPathEditError(`parse-error`,`${t} requires finite JSON value`);return r}function jsonToJsoncValue(e){if(e===null)return{kind:`null`};if(typeof e===`string`)return{kind:`string`,value:e};if(typeof e===`number`){if(!Number.isFinite(e))return null;return{kind:`number`,value:e}}if(typeof e===`boolean`)return{kind:`boolean`,value:e};if(Array.isArray(e)){const t=e.map(jsonToJsoncValue);if(t.some(e=>e===null))return null;return{kind:`array`,items:t}}if(typeof e===`object`){const t=e;const n=[];for(const[e,r]of Object.entries(t)){const t=jsonToJsoncValue(r);if(t===null)return null;n.push({key:e,value:t,line:0})}return{kind:`object`,entries:n}}throw new Error(`unsupported JSON value type: ${typeof e}`)}
//!extensions/oc-path/src/oc-path/find.ts
function findOcPaths(e,t){const n=patternSubs(t);if(!n.some(e=>e.value===`*`||e.value===`**`||isPositionalSeg(e.value)||isUnionSeg(e.value)||isPredicateSeg(e.value))){const n=resolveOcPath(e,t);return n===null?[]:[{path:t,match:n}]}const r=[];const i=/* @__PURE__ */ new Set;const a=e.kind===`jsonc`||e.kind===`yaml`;const onMatch=n=>{const o=repackSlotSubs(t,n,e.kind);const s=JSON.stringify(a?n.map(({value:e})=>unquoteSeg(e)):e.kind===`jsonl`?[o.section,splitOcPathSlots(o.item,o.field).map(unquoteSeg)]:[o.section,o.item,o.field]);if(!i.has(s)){i.add(s);r.push(o)}};const o={onMatch,visited:/* @__PURE__ */ new WeakMap,kind:e.kind};switch(e.kind){case`jsonc`:if(e.root!==null)jsoncOps.walk(e.root,n,0,[],o);break;case`jsonl`:walkJsonl(e,n,0,[],o);break;case`md`:walkMd({kind:`root`,ast:e},n,0,[],o);break;case`yaml`:if(e.doc.contents!==null){yamlDoc=e.doc;try{yamlOps.walk(e.doc.contents,n,0,[],o)}finally{yamlDoc=void 0}}}const s=[];for(const t of r){const n=resolveOcPath(e,t);if(n!==null)s.push({path:t,match:n})}return s}function patternSubs(e){const t=[];for(const n of[`section`,`item`,`field`]){const r=e[n];if(r!==void 0)for(const e of splitRespectingBrackets(r,`.`))t.push({slot:n,value:e})}return t}function repackSlotSubs(e,t,n){let r=[];let i;for(const{slot:e,value:n}of t){if(e!==i){r.push([]);i=e}r[r.length-1]?.push(n)}r=n===`jsonl`?keepOnlyLineAddressInSection(r):r;if(n!==`md`){const e=n===`jsonl`?1:0;const t=r.slice(e);if(t.some(e=>e.length>64)){const n=t.flat();r=r.slice(0,e);for(let e=0;e<n.length;e+=64){const t=r.length===2;r.push(n.slice(e,t?void 0:e+64));if(t)break}}}const[a,o,s]=r;return{file:e.file,...a!==void 0?{section:a.join(`.`)}:{},...o!==void 0?{item:o.join(`.`)}:{},...s!==void 0?{field:s.join(`.`)}:{},...e.session!==void 0?{session:e.session}:{}}}function checkDepth(e){if(e.length>256)throw new OcPathError(`findOcPaths exceeded MAX_TRAVERSAL_DEPTH (${256}) — likely a pathological pattern`,`OC_PATH_DEPTH_EXCEEDED`)}function dispatchSeg(e,t,n,r,i,a,o=e){if(r>=n.length){a.onMatch(i);return}const s=n.slice(r);let c;if(a.kind===`jsonc`||a.kind===`yaml`)c=JSON.stringify([s.map(({value:e})=>e),i.map(({value:e})=>unquoteSeg(e))]);else if(a.kind===`jsonl`){const e=i[0]?.slot;const t=i.findIndex(({slot:t})=>t!==e);const n=t<0?i.length:t;c=JSON.stringify([s,i.slice(0,n),i.slice(n).map(({value:e})=>unquoteSeg(e))])}else c=JSON.stringify([s,i]);const l=JSON.stringify([`active`,s.map(({value:e})=>e)]);const u=a.visited.get(o)??/* @__PURE__ */ new Set;if(u.has(c)||u.has(l))return;a.visited.set(o,u.add(c));const d=expectDefined(n[r],`dispatch index checked by walker`);if(isUnionSeg(d.value)){const o=parseUnionSeg(d.value);if(o===null)return;for(const s of o){const o=n.slice();o[r]={slot:d.slot,value:s};t.walk(e,o,r,i,a)}return}if(isPredicateSeg(d.value)){const o=parsePredicateSeg(d.value);if(o===null)return;for(const s of t.predicate(e,o))t.walk(s.child,n,r+1,[...i,{slot:d.slot,value:s.keySub}],a);return}if(d.value===`**`){t.walk(e,n,r+1,i,a);u.add(l);for(const o of t.enumerate(e)){const e=[...i,{slot:d.slot,value:o.keySub}];t.walk(o.child,n,r+1,e,a);t.walk(o.child,n,r,e,a)}u.delete(l);return}if(d.value===`*`){for(const o of t.enumerate(e))t.walk(o.child,n,r+1,[...i,{slot:d.slot,value:o.keySub}],a);return}const f=isPositionalSeg(d.value)?t.positional(e,d.value):t.lookup(e,d.value);if(f===null)return;t.walk(f.child,n,r+1,[...i,{slot:d.slot,value:f.keySub}],a)}const jsoncOps={*enumerate(e,t){if(e.kind===`object`){const n=e.entries;const r=new Map(n.map((e,t)=>[e.key,t]));for(const[e,i]of n.entries())if(r.get(i.key)===e&&(!t||t(i.value)))yield{keySub:quoteSeg(i.key),child:i.value}}else if(e.kind===`array`){for(const[n,r]of e.items.entries())if(!t||t(r))yield{keySub:String(n),child:r}}},lookup(e,t){if(e.kind===`object`){const n=unquoteSeg(t);const r=e.entries.findLast(e=>e.key===n);return r===void 0?null:{keySub:t===n?quoteSeg(r.key):t,child:r.value}}if(e.kind===`array`){const n=parseArrayIndexSegment(unquoteSeg(t),e.items.length);if(n===null)return null;return{keySub:t,child:expectDefined(e.items[n],`parsed JSONC array index is in bounds`)}}return null},positional(e,t){const n=resolveJsoncPositionalSegment(e,t);if(n===null)return null;return jsoncOps.lookup(e,e.kind===`object`?quoteSeg(n):n)},*predicate(e,t){yield*jsoncOps.enumerate(e,e=>evaluatePredicate(jsoncChildFieldText(e,t.key,`null`),t))},walk(e,t,n,r,i){checkDepth(r);dispatchSeg(e,jsoncOps,t,n,r,i)}};function walkJsonl(e,t,n,r,i){checkDepth(r);if(n>=t.length){i.onMatch(r);return}if(r.length===0)dispatchSeg(e,jsonlOps,t,n,r,i)}const jsonlOps={*enumerate(e,t){for(const n of e.lines)if(n.kind===`value`&&(!t||t(n)))yield{keySub:`L${n.line}`,child:n}},lookup(e,t){const n=pickJsonlLine(e,t);if(n===null)return null;return{keySub:n.kind===`value`?`L${n.line}`:t,child:n}},positional(e,t){return jsonlOps.lookup(e,t)},*predicate(e,t){yield*jsonlOps.enumerate(e,e=>e.kind===`value`&&evaluatePredicate(jsoncChildFieldText(e.value,t.key,null),t))},walk(e,t,n,r,i){if(e.kind===`jsonl`){walkJsonl(e,t,n,r,i);return}if(n>=t.length){i.onMatch(r);return}if(e.kind!==`value`)return;jsoncOps.walk(e.value,t,n,r,i)}};let yamlDoc;const yamlOps={*enumerate(e,t){if(isMap(e))for(const n of e.items){const e=isScalar(n.key)?n.key.value:n.key;const r=derefYamlNode(yamlDoc,n.value);if(r!==null&&(!t||t(r)))yield{keySub:quoteSeg(String(e)),child:r}}else if(isSeq(e))for(let n=0;n<e.items.length;n++){const r=derefYamlNode(yamlDoc,e.items[n]);if(r!==null&&(!t||t(r)))yield{keySub:String(n),child:r}}},lookup(e,t){if(isMap(e)){const n=unquoteSeg(t);const r=e.items.find(e=>{const t=isScalar(e.key)?e.key.value:e.key;return String(t)===n});const i=derefYamlNode(yamlDoc,r?.value);return i===null?null:{keySub:t===n?quoteSeg(n):t,child:i}}if(isSeq(e)){const n=parseArrayIndexSegment(unquoteSeg(t),e.items.length);if(n===null)return null;const r=derefYamlNode(yamlDoc,e.items[n]);return r===null?null:{keySub:t,child:r}}return null},positional(e,t){const n=resolveYamlPositionalSegment(e,t);if(n===null)return null;return yamlOps.lookup(e,isMap(e)?quoteSeg(n):n)},*predicate(e,t){yield*yamlOps.enumerate(e,e=>evaluatePredicate(yamlChildFieldText(e,t.key),t))},walk(e,t,n,r,i){checkDepth(r);dispatchSeg(e,yamlOps,t,n,r,i)}};function yamlChildFieldText(e,t){if(!isMap(e))return null;const n=e.items.find(e=>{const n=isScalar(e.key)?e.key.value:e.key;return String(n)===t});return n===void 0?null:yamlScalarToText(derefYamlNode(yamlDoc,n.value))}function yamlScalarToText(e){if(!isScalar(e))return null;const t=e.value;if(typeof t===`string`)return t;if(typeof t===`number`||typeof t===`boolean`)return String(t);if(t===null)return`null`;if(typeof t===`bigint`||typeof t===`symbol`)return t.toString();if(t instanceof Date)return t.toISOString();return JSON.stringify(t)??null}function walkMd(e,t,n,r,i){if(n>=t.length){i.onMatch(r);return}const a=expectDefined(t[n],`Markdown walk index checked above`);if(e.kind===`root`&&r.length===0&&a.value===`[frontmatter]`){walkMdFrontmatter(e.ast,t,n,i);return}if(e.kind===`item`){walkMdItemField(e.item,t,n,r,i);return}dispatchSeg(e,mdOps,t,n,r,i,e.kind===`root`?e.ast:e.block)}function walkMdItemField(e,t,n,r,i){if(e.kv===void 0)return;const a=e.kv.key;let o;let s;const c=[];for(let r=n;r<t.length;r++){const n=expectDefined(t[r],`Markdown field index checked above`);c.length=0;c.push(n.value);let i=false;let l=false;for(const t of c)if(isUnionSeg(t))c.push(...parseUnionSeg(t)??[]);else if(t===`**`)i=true;else if(t===`*`)l=true;else if(isPredicateSeg(t)){const n=parsePredicateSeg(t);l||=n!==null&&mdItemMatchesPredicate(e,n)}else l||=a.toLowerCase()===unquoteSeg(t).toLowerCase();if(i)s??=n;else{if(o||!l)return;o=n}}const l=o??s;if(l)i.onMatch([...r,{slot:l.slot,value:quoteSeg(a)}])}function blockSlugCounts(e){const t=/* @__PURE__ */ new Map;for(const n of e)t.set(n.slug,(t.get(n.slug)??0)+1);return t}const mdOps={*enumerate(e,t){if(e.kind===`root`){for(const n of e.ast.blocks){const e={kind:`block`,block:n};if(!t||t(e))yield{keySub:quoteSeg(n.slug),child:e}}return}if(e.kind===`block`){const n=blockSlugCounts(e.block.items);for(const[r,i]of e.block.items.entries()){const e={kind:`item`,item:i};if(!t||t(e))yield{keySub:(n.get(i.slug)??0)>1?`#${r}`:quoteSeg(i.slug),child:e}}}},lookup(e,t){if(e.kind===`root`){const n=unquoteSeg(t).toLowerCase();const r=e.ast.blocks.find(e=>e.slug===n);return r===void 0?null:{keySub:quoteSeg(r.slug),child:{kind:`block`,block:r}}}if(e.kind===`block`){if(isOrdinalSeg(t)){const n=parseOrdinalSeg(t);if(n===null||n<0||n>=e.block.items.length)return null;return{keySub:t,child:{kind:`item`,item:expectDefined(e.block.items[n],`validated Markdown ordinal is in bounds`)}}}const n=unquoteSeg(t).toLowerCase();const r=e.block.items.find(e=>e.slug===n);return r===void 0?null:{keySub:quoteSeg(r.slug),child:{kind:`item`,item:r}}}return null},positional(e,t){if(e.kind!==`block`)return null;const n=resolvePositionalSeg(t,{indexable:true,size:e.block.items.length});if(n===null)return null;return{keySub:t,child:{kind:`item`,item:expectDefined(e.block.items[Number(n)],`resolved Markdown position is in bounds`)}}},*predicate(e,t){yield*mdOps.enumerate(e,e=>e.kind===`block`?e.block.items.some(e=>mdItemMatchesPredicate(e,t)):e.kind===`item`&&mdItemMatchesPredicate(e.item,t))},walk:walkMd};function mdItemMatchesPredicate(e,t){if(e.kv===void 0)return false;if(e.kv.key.toLowerCase()!==t.key.toLowerCase())return false;return evaluatePredicate(e.kv.value,t)}function jsoncChildFieldText(e,t,n){if(e.kind!==`object`)return null;const r=e.entries.findLast(e=>e.key===t);if(r===void 0)return null;const i=r.value;if(i.kind===`string`)return i.value;if(i.kind===`number`||i.kind===`boolean`)return String(i.value);return i.kind===`null`?n:null}
//!extensions/oc-path/src/oc-path/yaml/parse.ts
function parseYaml(e){const t=new LineCounter;return{kind:`yaml`,raw:e,doc:parseDocument(e,{keepSourceTokens:true,prettyErrors:false,lineCounter:t}),lineCounter:t}}
//!extensions/oc-path/src/cli.ts
const MAX_OC_PATH_INPUT_BYTES=MAX_JSONC_INPUT_BYTES;const SCRUB_PLACEHOLDER=`[REDACTED]`;function scrubSentinel(e){return e.replaceAll(REDACTED_SENTINEL,SCRUB_PLACEHOLDER)}function detectMode(e){if(e.json===true)return`json`;if(e.human===true)return`human`;return process.stdout.isTTY?`human`:`json`}function emit(e,t,n){if(e===`json`){process.stdout.write(scrubSentinel(JSON.stringify(t,null,2)));return}process.stdout.write(scrubSentinel(n()))}function emitError(e,t,n=`ERR`){const r=scrubSentinel(t);if(e===`json`){process.stdout.write(`${JSON.stringify({ok:false,error:{type:`cli_error`,code:n,message:r}})}\n`);return}process.stderr.write(terminalText`${n}: ${r}\n`)}function tryParse(e,t){try{return parseOcPath(e)}catch(e){if(e instanceof OcPathError){emitError(t,`parse failed: ${e.message}`,e.code);process.exitCode=2;return null}throw e}}async function loadOcPathFile(e,t,n,r={}){const i=inferKind(t)??inferKind(e);const a=await promises.open(e,constants.O_RDONLY|constants.O_NONBLOCK);let o;try{const t=await a.stat();if(!t.isFile()){emitError(n,`not a regular file: ${e}`,`OC_PATH_FILE_NOT_REGULAR`);process.exitCode=2;return null}const s=t.size>MAX_OC_PATH_INPUT_BYTES?null:Buffer.concat(await a.createReadStream({autoClose:false,end:MAX_OC_PATH_INPUT_BYTES,start:0}).toArray());if(s===null||s.length>MAX_OC_PATH_INPUT_BYTES){emitError(n,`input exceeds ${MAX_OC_PATH_INPUT_BYTES} bytes${t.size>MAX_OC_PATH_INPUT_BYTES?`; got ${t.size}`:``}`,i===`jsonc`?`OC_JSONC_INPUT_TOO_LARGE`:`OC_PATH_INPUT_TOO_LARGE`);process.exitCode=2;return null}if(r.requireUtf8===true&&!isUtf8(s)){emitError(n,`input is not valid UTF-8; the file was left unchanged: ${e}. Convert or repair a backed-up copy as UTF-8, then retry.`,`OC_PATH_INPUT_NOT_UTF8`);process.exitCode=2;return null}o=s.toString(`utf8`)}finally{await a.close()}if(i===`jsonc`){const e=parseJsonc(o);if(e.oversizedInputBytes!==void 0){emitError(n,`input exceeds MAX_JSONC_INPUT_BYTES (${MAX_JSONC_INPUT_BYTES} bytes; got ${e.oversizedInputBytes})`,`OC_JSONC_INPUT_TOO_LARGE`);process.exitCode=2;return null}return e}if(i===`jsonl`)return parseJsonl(o);if(i===`yaml`)return parseYaml(o);return parseMd(o)}function resolveFsPath(e,t){if(t.file!==void 0)return resolve(t.file);return resolve(t.cwd??process.cwd(),e.file)}function formatMatchHuman(e){if(e.kind===`leaf`)return terminalText`leaf @ L${e.line}: ${JSON.stringify(e.valueText)} (${e.leafType})`;if(e.kind===`node`)return terminalText`node @ L${e.line} [${e.descriptor}]`;if(e.kind===`insertion-point`)return terminalText`insertion-point @ L${e.line} [${e.container}]`;return terminalText`root @ L${e.line}`}function formatUnifiedDiff(e,t,n){if(e===t)return``;const r=e.match(/[^\n]*\n|[^\n]+$/g)??[];const i=t.match(/[^\n]*\n|[^\n]+$/g)??[];let a=0;while(a<r.length&&r[a]===i[a])a++;let o=r.length;let s=i.length;while(o>a&&s>a&&r[o-1]===i[s-1]){o--;s--}const c=Math.max(0,a-3);const l=Math.min(3,r.length-o);const formatLines=(e,t)=>(structuredPatch(``,``,``,t.join(``)).hunks[0]?.lines??[]).map(t=>t.startsWith(`+`)?`${e}${t.slice(1)}`:t);const u=structuredPatch(n,n,``,``);u.hunks.push({oldStart:c+1,oldLines:o-c+l,newStart:c+1,newLines:s-c+l,lines:[...formatLines(` `,r.slice(c,a)),...formatLines(`-`,r.slice(a,o)),...formatLines(`+`,i.slice(a,s)),...formatLines(` `,r.slice(o,o+l))]});return formatPatch(u,FILE_HEADERS_ONLY)}function withCommonOpts(e){return e.option(`--json`,`Force JSON output`).option(`--human`,`Force human output`).option(`--cwd <dir>`,`Resolve file slot against this directory`).option(`--file <file>`,`Override the file slot's resolved path`)}function registerPathCli(e){const t=e.command(`path`).description(`Inspect and edit workspace files via the oc:// addressing scheme`).addHelpText(`after`,`
Docs: https://docs.openclaw.ai/cli/path
`);withCommonOpts(t.command(`resolve`).description(`Print the match at an oc:// path`).argument(`<oc-path>`,`oc:// path to resolve`)).action(async(e,t)=>{const n=detectMode(t);const r=tryParse(e,n);if(r===null)return;const i=await loadOcPathFile(resolveFsPath(r,t),r.file,n);if(i===null)return;let a;try{a=resolveOcPath(i,r)}catch(e){if(e instanceof OcPathError){emitError(n,`resolve refused: ${e.message}`,e.code);process.exitCode=2;return}throw e}if(a===null){emit(n,{resolved:false,ocPath:e},()=>terminalText`not found: ${e}`);process.exitCode=1;return}emit(n,{resolved:true,ocPath:e,match:a},()=>formatMatchHuman(a))});withCommonOpts(t.command(`find`).description(`Enumerate matches for a wildcard / predicate oc:// pattern`).argument(`<pattern>`,`oc:// pattern`)).action(async(e,t)=>{const n=detectMode(t);const r=tryParse(e,n);if(r===null)return;if(r.file.includes(`*`)){emitError(n,`find: file-slot wildcards are not supported (got "${r.file}"). Pass a concrete file path; multi-file globbing is a follow-up feature.`,`OC_PATH_FILE_WILDCARD_UNSUPPORTED`);process.exitCode=2;return}const i=await loadOcPathFile(resolveFsPath(r,t),r.file,n);if(i===null)return;const a=findOcPaths(i,r);emit(n,{pattern:e,count:a.length,matches:a.map(e=>({path:formatOcPath(e.path),match:e.match}))},()=>{if(a.length===0)return terminalText`0 matches for ${e}`;const t=a.length===1?``:`es`;const n=[terminalText`${a.length} match${t} for ${e}:`];for(const e of a){const t=terminalText`${formatOcPath(e.path)}`;n.push(`  ${t}  →  ${formatMatchHuman(e.match)}`)}return n.join(`
`)});if(a.length===0)process.exitCode=1});withCommonOpts(t.command(`set`).description(`Write a leaf value at an oc:// path`).argument(`<oc-path>`,`oc:// path to write`).argument(`<value>`,`string value to write`).option(`--value-json`,`Parse <value> as JSON for JSON/JSONC/JSONL leaf replacement`).option(`--dry-run`,`Print bytes without writing`).option(`--diff`,`With --dry-run, print a unified diff instead of full bytes`)).action(async(e,t,n)=>{const r=detectMode(n);if(n.diff===true&&n.dryRun!==true){emit(r,{ok:false,reason:`--diff requires --dry-run`},()=>`set failed: --diff requires --dry-run`);process.exitCode=1;return}const i=tryParse(e,r);if(i===null)return;const a=resolveFsPath(i,n);const o=await loadOcPathFile(a,i.file,r,{requireUtf8:true});if(o===null)return;let s;try{s=setOcPath(o,i,t,{valueJson:n.valueJson===true})}catch(e){if(e instanceof OcPathEditError){const t=e.detail;emit(r,{ok:false,reason:e.reason,detail:t},()=>terminalText`set failed: ${e.reason}${t!==void 0?` — ${t}`:``}`);process.exitCode=1;return}if(e instanceof OcEmitSentinelError){emitError(r,`set refused: ${e.message}`,`OC_EMIT_SENTINEL`);process.exitCode=1;return}throw e}const c=s.raw;const l=Buffer.byteLength(c,`utf8`);if(n.dryRun===true){const e=n.diff===true?formatUnifiedDiff(o.raw,c,a):void 0;emit(r,{ok:true,dryRun:true,bytes:c,...e!==void 0?{diff:e}:{}},()=>e!==void 0?e||terminalText`--dry-run: no byte changes for ${a}`:`${terminalText`--dry-run: would write ${l} bytes to ${a}`}\n${c}`);return}await promises.writeFile(a,c,`utf-8`);emit(r,{ok:true,dryRun:false,bytesWritten:l,fsPath:a},()=>terminalText`wrote ${l} bytes to ${a}`)});t.command(`validate`).description(`Parse an oc:// path and print its slot structure`).argument(`<oc-path>`,`oc:// path to validate`).option(`--json`,`Force JSON output`).option(`--human`,`Force human output`).action((e,t)=>{const n=detectMode(t);try{const t=parseOcPath(e);emit(n,{valid:true,ocPath:e,formatted:formatOcPath(t),structure:t},()=>{const n=[terminalText`valid: ${e}`,terminalText`  file:    ${t.file}`];if(t.section!==void 0)n.push(terminalText`  section: ${t.section}`);if(t.item!==void 0)n.push(terminalText`  item:    ${t.item}`);if(t.field!==void 0)n.push(terminalText`  field:   ${t.field}`);if(t.session!==void 0)n.push(terminalText`  session: ${t.session}`);return n.join(`
`)})}catch(e){if(e instanceof OcPathError){emit(n,{valid:false,code:e.code,message:e.message},()=>terminalText`INVALID: ${e.code}: ${e.message}`);process.exitCode=1;return}throw e}});withCommonOpts(t.command(`emit`).description(`Round-trip a file through parse + emit`).argument(`<file>`,`Path to a workspace file`)).action(async(e,t)=>{const n=detectMode(t);const r=t.file!==void 0?resolve(t.file):resolve(t.cwd??process.cwd(),e);const i=await loadOcPathFile(r,r.split(/[\\/]/).pop()??e,n);if(i===null)return;const a=i.raw;if(n===`json`){process.stdout.write(scrubSentinel(JSON.stringify({ok:true,kind:i.kind,bytes:a})));return}process.stdout.write(a)});t.action(()=>{t.outputHelp();process.exitCode=0})}export{registerPathCli};