"use strict";var ft=Object.create;var j=Object.defineProperty;var mt=Object.getOwnPropertyDescriptor;var pt=Object.getOwnPropertyNames;var dt=Object.getPrototypeOf,yt=Object.prototype.hasOwnProperty;var ht=(t,e)=>{for(var r in e)j(t,r,{get:e[r],enumerable:!0})},W=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of pt(e))!yt.call(t,n)&&n!==r&&j(t,n,{get:()=>e[n],enumerable:!(s=mt(e,n))||s.enumerable});return t};var d=(t,e,r)=>(r=t!=null?ft(dt(t)):{},W(e||!t||!t.__esModule?j(r,"default",{value:t,enumerable:!0}):r,t)),wt=t=>W(j({},"__esModule",{value:!0}),t);var At={};ht(At,{processMerge:()=>gt,resolveGitMergeFiles:()=>jt});module.exports=wt(At);var lt=require("child_process");var F=async(t,e)=>{switch(t){case"json":case"json5":return JSON.stringify(e,null,2);case"yaml":{let{stringify:r}=await import("yaml");return r(e)}case"toml":{let{stringify:r}=await import("smol-toml");return r(e)}case"xml":{let{XMLBuilder:r}=await import("fast-xml-parser");return new r({}).build(e)}default:throw new Error(`Unknown format: ${t}`)}};var K=(t,{rules:e,matcher:r})=>{var i,m,f;let s=(i=e.exact[t])!=null?i:[],n=(f=e.exactFields[(m=t.split(".").pop())!=null?m:""])!=null?f:[],o=Object.entries(e.patterns).filter(([l])=>r.isMatch(t,[l])).flatMap(([,l])=>l),a=[...s.flatMap(l=>l.strategies),...n.flatMap(l=>l.strategies),...o.flatMap(l=>l.strategies),...e.default],g=a.filter(l=>l.important),p=a.filter(l=>!l.important);return[...g,...p].map(l=>l.name)};var L=d(require("fs/promises")),A=d(require("path")),R=Symbol("MERGE_DROP"),St=".merge-backups",y=0,M=1,B=2,_=3;var J=async(t,e=St)=>{let r=A.default.relative(process.cwd(),t),s=A.default.join(e,r);return await L.default.mkdir(A.default.dirname(s),{recursive:!0}),await L.default.copyFile(t,s),s};var v=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),xt={ours:({ours:t})=>({status:y,value:t}),theirs:({theirs:t})=>({status:y,value:t}),base:({base:t})=>({status:y,value:t}),drop:t=>({status:y,value:R}),skip:({path:t})=>({status:_,reason:`Skip strategy applied lt ${t}`}),"non-empty":({ours:t,theirs:e,base:r})=>t!=null&&t!==""?{status:y,value:t}:e!=null&&e!==""?{status:y,value:e}:r!=null&&r!==""?{status:y,value:r}:{status:M},update:({ours:t,theirs:e})=>t!==void 0?{status:y,value:e}:{status:y,value:R},merge:async t=>{let{ours:e,theirs:r,base:s,path:n,filePath:o,ctx:a,conflicts:g}=t;if(v(e)&&v(r)){let p=new Set([...Object.keys(e),...Object.keys(r)]),i={};for(let m of p)i[m]=await z({ours:e[m],theirs:r[m],base:v(s)?s[m]:void 0,path:n?`${n}.${m}`:m,filePath:o,ctx:a,conflicts:g});return{status:y,value:i}}return{status:M,reason:"Unmergeable type"}},concat:({ours:t,theirs:e,path:r})=>Array.isArray(t)&&Array.isArray(e)?{status:y,value:[...t,...e]}:{status:M,reason:`Cannot concat lt ${r}`},unique:({ours:t,theirs:e,path:r})=>Array.isArray(t)&&Array.isArray(e)?{status:y,value:[...new Set([...t,...e])]}:{status:M,reason:`Cannot concat lt ${r}`}},z=async({ours:t,theirs:e,base:r,path:s,filePath:n,ctx:o,conflicts:a})=>{var p;if(t===e)return t;o._strategyCache||(o._strategyCache=new Map);let g=o._strategyCache.get(s);g||(g=K(s,o.config),o._strategyCache.set(s,g));for(let i of g){let m=(p=xt[i])!=null?p:o.strategies[i];if(!m)continue;let f=await m({ours:t,theirs:e,base:r,path:s,filePath:n,ctx:o,conflicts:a});switch(f.status){case y:return f.value;case M:continue;case _:a.push({path:s,reason:f.reason});return;case B:throw a.push({path:s,reason:f.reason}),new Error(`Merge failed lt ${s}: ${f.reason}`)}}a.push({path:s,reason:`All strategies failed (tried: ${g.join(", ")||"none"})`,...o.config.debug?{ours:t,theirs:e,base:r}:{}})};var D=(t,e,r=[])=>{if(t!==R){if(t===void 0){let s=`__CONFLICT_MARKER::${e}__`;return r.push(e),s}if(Array.isArray(t))return t.map((s,n)=>D(s,`${e}[${n}]`,r)).filter(s=>s!==void 0);if(t&&typeof t=="object"){let s={};for(let[n,o]of Object.entries(t)){let a=D(o,e?`${e}.${n}`:n,r);a!==void 0&&(s[n]=a)}return s}return t}},X=async(t,e,r,s)=>{let n=[],o=D(t,"",n),a=await F(s,o);for(let g of n){let p=G(e,g),i=G(r,g),[m,f]=await Promise.all([p,i].map(w=>F(s,w))),l=["<<<<<<< ours",V(m,2),"=======",V(f,2),">>>>>>> theirs"].join(`
`),h=`__CONFLICT_MARKER::${g}__`;a=a.replace(/json/.test(s)?JSON.stringify(h):h,l)}return a},G=(t,e)=>{let r=e.replace(/\[(\d+)\]/g,".$1").split(".").filter(Boolean),s=t;for(let n of r)s=s==null?void 0:s[n];return s},V=(t,e)=>{let r=" ".repeat(e);return t.split(`
`).map(s=>s&&r+s).join(`
`)};var q={isMatch:(t,e)=>{let r=$(t);return e.some(s=>Tt(r,$(s)))}},H=async t=>{if(t==="micromatch"){let e;try{e=await import("micromatch")}catch{throw new Error("micromatch is not installed. Please add it as a dependency if you want to use it.")}return{isMatch:(r,s)=>{try{return e.isMatch($(r),s.map($))}catch(n){throw new Error(`micromatch failed to run isMatch: ${n.message}`)}}}}if(t==="picomatch"){let e;try{e=(await import("picomatch")).default}catch{throw new Error("picomatch is not installed. Please add it as a dependency if you want to use it.")}return{isMatch:(r,s)=>{try{return e(s.map($))($(r))}catch(n){throw new Error(`picomatch failed to run isMatch: ${n.message}`)}}}}throw new Error(`Unknown matcher name: ${t}`)},$=t=>{let e="",r=!1;for(let s of t)r?(e+=s,r=!1):s==="\\"?(r=!0,e+="\\"):s==="."?e+="/":e+=s;return e},Ct=t=>{let e=t.startsWith("!"),r=e?t.slice(1):t,s=[],n="",o=!1;for(let a of r)o?(n+="\\"+a,o=!1):a==="\\"?o=!0:a==="/"?(s.push(n),n=""):n+=a;return o&&(n+="\\"),s.push(n),e&&(s.negated=!0),s},Tt=(t,e)=>{let r=t.split("/"),s=Ct(e),n=s.negated===!0,o=Q(r,s);return n?!o:o},Q=(t,e)=>{let r=0,s=0;for(;r<t.length&&s<e.length;){let n=e[s];if(n==="**"){if(s===e.length-1)return!0;for(let o=0;r+o<=t.length;o++)if(Q(t.slice(r+o),e.slice(s+1)))return!0;return!1}if(!bt(t[r],n))return!1;r++,s++}for(;s<e.length&&e[s]==="**";)s++;return r===t.length&&s===e.length},bt=(t,e)=>{let r=!1,s=!1,n="",o="";for(let p=0;p<e.length;p++){let i=e[p];if(r){o+=i,r=!1;continue}if(i==="\\"){r=!0;continue}if(i==="*"){if(!s){s=!0,n=o,o="";continue}o+="*";continue}o+=i}if(r&&(o+="\\"),!s){let p=o.replace(/\\(.)/g,"$1");return t===p}let a=o.replace(/\\(.)/g,"$1"),g=n.replace(/\\(.)/g,"$1");return t.startsWith(g)&&t.endsWith(a)};var Pt={defaultStrategy:["merge","ours"],include:["**/*.json","**/*.yaml","**/*.yml","**/*.xml","**/*.toml"],exclude:["**/node_modules/**","**/dist/**"],debug:!1,writeConflictSidecar:!1},et=async t=>{let{rules:e,byStrategy:r,defaultStrategy:s,matcher:n,plugins:o,pluginConfig:a,customStrategies:g,...p}={...Pt,...t},i=await $t(o,a),m={...g,...i},f={exact:Object.create(null),exactFields:Object.create(null),patterns:Object.create(null),default:Mt(s)},l=typeof n=="string"?await H(n):n!=null?n:q,h=0;if(r)for(let[w,x]of Object.entries(r)){if(!x)continue;let{name:C,important:b}=Y(w);for(let c of x){let{key:u,important:S}=Z(c);tt(f,u,{strategies:[{name:C,important:b||S}],order:h++,source:u})}}return e&&st(e,[],(w,x)=>{let{key:C,important:b}=Z(w),c=x.map(u=>{let{name:S,important:T}=Y(u);return{name:S,important:T||b}});tt(f,C,{strategies:c,order:h++,source:C})}),{...p,rules:f,matcher:l,customStrategies:m}},Mt=t=>(Array.isArray(t)?t:[t]).map(r=>{let s=r.endsWith("!");return rt(r.slice(0,-1)),{name:s?r.slice(0,-1):r,important:s}}),Y=t=>{let e=t.endsWith("!"),r=e?t.slice(0,-1):t;return rt(r),{name:r,important:e}},rt=t=>{if(t.endsWith("!"))throw new Error(`Strategy name "${t}" must not end with "!". Use "!" on field/glob to mark rule importance.`)},Z=t=>{let e=t.endsWith("!"),r=e?t.slice(0,-1):t;if(!r)throw new Error(`Invalid rule key "${t}".`);return{key:r,important:e}},tt=(t,e,r)=>{if(/^\[.*\]$/.test(e)){let n=e.slice(1,-1);if(n.replace(/\\\./g,"").includes(".")||n.trim()==="")throw new Error(`Invalid bracket form "${e}". Use a single bare key like "[id]".`);let o=`**.${n}.**`;O(t.patterns,o,r);return}if(/[*?[\]]/.test(e)){O(t.patterns,e,r);return}e.includes(".")?O(t.exact,e,r):O(t.exactFields,e,r)},st=(t,e,r)=>{for(let[s,n]of Object.entries(t)){let o=[...e,s];Array.isArray(n)?r(o.join("."),n):st(n,o,r)}},O=(t,e,r)=>{var n;((n=t[e])!=null?n:t[e]=[]).push(r)},$t=async(t,e)=>{if(!(t!=null&&t.length))return{};let r={};for(let s of t)try{let n=await import(s),o=n.default||n;if(!o.strategies)throw new Error(`Plugin "${s}" does not export strategies`);o.init&&(e!=null&&e[s])&&await o.init(e[s]),Object.assign(r,o.strategies)}catch(n){throw new Error(`Failed to load plugin "${s}": ${n}`)}return r};var nt=d(require("fs")),N=require("fs"),E=d(require("path")),ot=async(t={},e)=>{var f,l,h,w,x,C,b;let r=(f=t.mode)!=null?f:"memory",s=(l=t.logDir)!=null?l:".logs",n=(h=t.singleFile)!=null?h:!1,o={stdout:(x=(w=t.levels)==null?void 0:w.stdout)!=null?x:e?["debug","info","warn","error"]:["warn","error"],file:(b=(C=t.levels)==null?void 0:C.file)!=null?b:e?["info","debug","warn","error"]:["error"]};try{await N.promises.mkdir(s,{recursive:!0})}catch(c){console.warn(`Failed to create log directory: ${c}`)}let a=new Map,g=new Map,p=c=>{let u=n?"all":c;if(!g.has(u)){let S=E.default.join(s,n?"combined.log":`${c}.log`);g.set(u,nt.default.createWriteStream(S,{flags:"a"}))}return g.get(u)},i=(c,u,S)=>{let T={timestamp:new Date().toISOString(),level:u,message:S};o.stdout.includes(u)&&(u==="error"?console.error:console.log)(`[${c}] [${T.timestamp}] [${u.toUpperCase()}] ${T.message}`),o.file.includes(u)&&(r==="memory"?(a.has(c)||a.set(c,[]),a.get(c).push(T)):p(c).write(`[${T.timestamp}] [${u.toUpperCase()}] ${T.message}
`))};return{info:(c,u)=>i(c,"info",u),warn:(c,u)=>i(c,"warn",u),error:(c,u)=>i(c,"error",u),debug:(c,u)=>i(c,"debug",u),flush:async()=>{if(r==="memory"){let c=new Date().toISOString().replace(/:/g,"-"),u=Array.from(a.entries()).map(async([S,T])=>{try{let k=E.default.join(s,n?`combined-${c}.log`:`${S}-${c}.log`),ut=T.map(I=>`[${I.timestamp}] [${I.level.toUpperCase()}] ${I.message}`);await N.promises.mkdir(E.default.dirname(k),{recursive:!0}),await N.promises.appendFile(k,ut.join(`
`)+`
`)}catch(k){console.warn(`Failed to write log file for ${S}: ${k}`)}});await Promise.all(u)}for(let c of g.values())try{c.end()}catch(u){console.warn(`Failed to close log stream: ${u}`)}await new Promise(c=>setTimeout(c,10))}}};var P=d(require("fs/promises"));var it=require("util"),Xt=(0,it.promisify)(lt.execFile);var kt={json:"json",json5:"json5",yaml:"yaml",yml:"yaml",toml:"toml",xml:"xml"},ct=t=>{var e,r;if(Array.isArray(t.parsers))return t.parsers;if(t.parsers)return t.parsers==="auto"?["json","json5","yaml","toml","xml"]:[t.parsers];if(t.filename){let s=kt[(r=(e=t.filename.split(".").pop())==null?void 0:e.toLowerCase())!=null?r:""];if(s)return[s]}return["json"]},U=async(t,e)=>{for(let r of e)try{return typeof r!="string"?[r.parser(t),r]:[await Ft(r,t),r]}catch(s){console.debug(`Parser ${typeof r=="string"?r:r.name} failed:`,s)}throw new Error(`Failed to parse content. Tried parsers: ${e.map(r=>typeof r=="string"?r:r.name).join(", ")}`)},Ft=async(t,e)=>{switch(t){case"json":return JSON.parse(e);case"json5":try{let{parse:r}=await import("json5");return r(e)}catch{throw new Error("json5 parser not installed. Please install as peer dependency.")}case"yaml":try{let{parse:r}=await import("yaml");return r(e)}catch{throw new Error("yaml parser not installed. Please install as peer dependency.")}case"toml":try{let{parse:r}=await import("smol-toml");return r(e)}catch{throw new Error("toml parser not installed. Please install as peer dependency.")}case"xml":try{let{XMLParser:r}=await import("fast-xml-parser");return new r().parse(e)}catch{throw new Error("fast-xml-parser not installed. Please install as peer dependency.")}}};var Rt=new Map,gt=async({ours:t,theirs:e,base:r,format:s,filePath:n,config:o,normalizedConfig:a,logger:g,autoStage:p=!1})=>{var f;let i=[],[m]=await Promise.all([z({ours:t,theirs:e,base:r,filePath:n,conflicts:i,path:"",ctx:{config:a,strategies:(f=a.customStrategies)!=null?f:{},_strategyCache:Rt}}),J(n,o.backupDir)]);if(a.debug&&g.debug(n,JSON.stringify({merged:m,conflicts:i},null,2)),i.length===0){let l=await F(s,m);if(await P.default.writeFile(n,l,"utf8"),p)try{(0,lt.execSync)(`git add ${n}`)}catch(h){g.warn(n,`Failed to stage file: ${h}`)}return{success:!0,conflicts:[]}}else{let l=await X(m,t,e,s);return await Promise.all([P.default.writeFile(n,l,"utf8"),o.writeConflictSidecar?P.default.writeFile(`${n}.conflict.json`,JSON.stringify(i,null,2)):null]),{success:!1,conflicts:i}}},jt=async(t,e,r,s={})=>{let n=await ot(s.loggerConfig,s.debug),o=await et(s);o.debug&&n.info("git-merge",`Merging files: ours=${t}, base=${e}, theirs=${r}`);let[a,g,p]=await Promise.all([P.default.readFile(t,"utf8"),P.default.readFile(e,"utf8").catch(()=>"{}"),P.default.readFile(r,"utf8")]),i=ct({...o,filename:""}),[m,f]=await U(a,i),[l,h]=await Promise.all([g,p].map(C=>U(C,[f]).then(([b])=>b))),w=typeof f=="string"?f:f.name,{success:x}=await gt({ours:m,theirs:h,base:l,format:w,filePath:t,config:s,normalizedConfig:o,logger:n,autoStage:!1});await n.flush(),process.exit(x?0:1)};0&&(module.exports={processMerge,resolveGitMergeFiles});
