var H=Object.defineProperty;var j=(e,t)=>H(e,"name",{value:t,configurable:!0});import{createRequire as K}from"node:module";import{b as V,E as A,d as Y}from"./config.js";import{B as X,K as D,z as T,M as C}from"../packem_shared/readFileSync-DseCu8sg-DEq4Fn3a.js";import{o as Z}from"../packem_shared/index-DH-5hsrC.js";import{aO as G,C as ee,aP as te,a5 as oe}from"./bin.js";import{r as re}from"../packem_shared/glob-D_7bct6p-D8itOHsr.js";import{n as ne}from"../packem_shared/manifests-BzWpKW8F.js";const z=K(import.meta.url),O=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,Q=j(e=>{if(typeof O<"u"&&O.versions&&O.versions.node){const[t,o]=O.versions.node.split(".").map(Number);if(t>22||t===22&&o>=3||t===20&&o>=16)return O.getBuiltinModule(e)}return z(e)},"__cjs_getBuiltinModule"),{readFileSync:F}=Q("node:fs");var se=Object.defineProperty,y=j((e,t)=>se(e,"name",{value:t,configurable:!0}),"c");const ie=y((e,t)=>{const o=t.replace(/^\.?\//,"");return o===""||o==="."?`/${e}/`:e===""||e==="."?`/${o}`:`/${e}/${o}`},"toWorkspacePath"),_=y((e,t,o=[])=>{const s=[],r=new Set;for(const[i,n]of Object.entries(t?.globalPaths??{}))s.push({owners:n,path:i,source:"project-json"}),r.add(i);for(const[i,n]of Object.entries(e.projects)){const a=n.owners??[];for(const c of a){const l=ie(n.root??i,c.path);s.push({channel:c.channel,owners:c.owners,path:l,projectId:i,source:"project-json"}),r.add(l)}}for(const i of o)r.has(i.path)||(s.push(i),r.add(i.path));return(t?.orderBy??"file-source")==="project-id"?s.sort((i,n)=>(i.projectId??"").localeCompare(n.projectId??"")||i.path.localeCompare(n.path)):s.sort((i,n)=>i.path.localeCompare(n.path)),s},"buildCodeownersLines"),ae="Update each project's project.json `owners` field and re-run the command.",ce=y(e=>["# CODEOWNERS — generated by `vis sync codeowners`. Do not edit by hand.",e?`# Re-run with: ${e}`:`# ${ae}`,""],"buildHeader"),M=y(e=>{const t=[];for(const o of e){const s=o.owners.join(" "),r=o.channel?`    # notify: ${o.channel}`:"";t.push(`${o.path} ${s}${r}`)}return t},"renderEntries"),de=y((e,t={})=>[...ce(t.regenerationCommand),...M(e),""].join(`
`),"renderCodeowners"),S={begin:"# BEGIN vis-codeowners",end:"# END vis-codeowners"},le=y((e,t=S,o={})=>{const s=o.regenerationCommand?`# Generated by vis sync codeowners — re-run with: ${o.regenerationCommand}`:"# Generated by `vis sync codeowners` — do not edit by hand.";return[t.begin,s,...M(e),t.end].join(`
`)},"renderCodeownersBlock"),ue=y((e,t,o=S)=>{const s=e.indexOf(o.begin),r=e.indexOf(o.end);if(s!==-1&&r!==-1&&r>s){const n=e.slice(0,s),a=r+o.end.length,c=e.slice(a);return`${n}${t}${c}`}const i=e.replace(/\s+$/u,"");return`${i.length===0?"":`${i}

`}${t}
`},"mergeIntoExisting");var fe=Object.defineProperty,N=j((e,t)=>fe(e,"name",{value:t,configurable:!0}),"f$1");const pe=["**/CODEOWNERS"],he=["**/node_modules/**","**/dist/**","**/build/**","**/coverage/**","**/.git/**","**/.next/**","**/.nuxt/**"],ge=N(e=>{const t=[];for(const o of e.split(/\r?\n/u)){const s=o.indexOf("#"),r=(s===-1?o:o.slice(0,s)).trim();if(r.length===0)continue;const i=r.split(/\s+/u);if(i.length<2)continue;const[n,...a]=i,c=a.filter(l=>l.length>0);!n||c.length===0||t.push({owners:c,path:n})}return t},"parseCodeownersFile"),me=N((e,t)=>{const o=t.replace(/^\.\/?/,"").replace(/\/$/,"");return e.startsWith("/")?o===""?e:`/${o}${e}`:o===""?`/${e}`:`/${o}/${e}`},"rewriteNestedPath"),we=N(async(e,t,o)=>{const s=t&&t.length>0?[...t]:[...pe],r=[...he];if(o){const a=o.replace(/^\.\/?/,"").replace(/^\/+/,"");a.length>0&&r.push(a)}const i=await re(s,{absolute:!0,cwd:e,ignore:r}),n=[];for(const a of i){let c;try{c=X(a)}catch{continue}const l=D(a),p=T(e,l);for(const m of ge(c))n.push({owners:m.owners,path:me(m.path,p)})}return n},"collectNestedCodeownersLines"),be=/^(?:https?:\/\/)?(?:www\.)?github\.com\/([^/?#]+)/iu,$e=N(e=>{if(!e)return;const t=e.match(be);if(!t?.[1])return;const o=t[1].trim();if(!(o===""||o.includes(" ")))return`@${o.replace(/^@/,"")}`},"extractGitHubHandle"),je=N((e,t)=>{const o=[];for(const[s,r]of Object.entries(e.projects)){if(r.owners&&r.owners.length>0)continue;const i=r.root??s,n=C(t,i,"package.json"),a=G(n);if(!a)continue;const c=ne(a.maintainers);if(!c||c.length===0)continue;const l=[],p=new Set;for(const m of c){const w=$e(m.url);w&&!p.has(w)&&(p.add(w),l.push(w))}l.length!==0&&o.push({owners:l,path:i===""||i==="."?"/":`/${i}/`,projectId:s})}return o},"collectMaintainerLines");var ye=Object.defineProperty,v=j((e,t)=>ye(e,"name",{value:t,configurable:!0}),"s");const ke=["author","bugs","homepage","license","repository","engines"],I=v(e=>typeof e=="object"&&e!==null&&!Array.isArray(e),"isPlainObject"),R=v((e,t)=>{if(e===t)return!0;if(typeof e!=typeof t||e===null||t===null)return!1;if(Array.isArray(e)){if(!Array.isArray(t)||e.length!==t.length)return!1;for(const[o,s]of e.entries())if(!R(s,t[o]))return!1;return!0}if(typeof e=="object"&&typeof t=="object"){const o=Object.keys(e),s=Object.keys(t);if(o.length!==s.length)return!1;for(const r of o)if(!R(e[r],t[r]))return!1;return!0}return!1},"deepEqual"),x=v(e=>e===void 0?e:structuredClone(e),"cloneJson"),Ce=v((e,t,o)=>{if(e==="repository"&&I(t)&&I(o)){const s={};for(const[r,i]of Object.entries(t))r!=="directory"&&(s[r]=x(i));return typeof o.directory=="string"&&(s.directory=o.directory),s}return x(t)},"buildTargetValue"),ve=v((e,t,o)=>{const s=[];for(const r of o.fields){if(!Object.hasOwn(e,r))continue;const i=e[r],n=t[r],a=Ce(r,i,n);R(a,n)||s.push({after:a,before:n,field:r,packageJsonPath:""})}return s},"computeFieldChanges"),Ee=v((e,t)=>{for(const o of t)e[o.field]=o.after},"applyFieldChanges");var Oe=Object.defineProperty,P=j((e,t)=>Oe(e,"name",{value:t,configurable:!0}),"n");const U="Generated by `vis sync codeowners --write-guard`. Do not edit by hand.",Ne=P(e=>{const t=e.replace(/^\.?\/+/u,"").replace(/\/+$/u,"");return t===""||t==="."?"**":`${t}/**`},"toPathGlob"),q=P(e=>{const t=new Set,o=[];for(const s of[...e].sort((r,i)=>r.name.localeCompare(i.name))){const r=Ne(s.root);t.has(r)||(t.add(r),o.push(r))}return o},"resolveGlobs"),Pe=P(e=>{const t=q(e),o=t.map(r=>`      - "${r}"`).join(`
`),s=t.map(r=>`            ${r}`).join(`
`);return`# ${U}
name: Write Guard

on:
  pull_request:
    paths:
${o}

permissions:
  contents: read
  pull-requests: read

jobs:
  write-guard:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
      - uses: geritol/write-guard@v1
        with:
          codeowners: CODEOWNERS
          paths: |
${s}
`},"renderGithubWriteGuard"),Ge=P(e=>{const t=q(e).map(o=>`        - "${o}/*"`).join(`
`);return`# ${U}
#
# SOFT GUARD ONLY — this job does NOT block a merge by itself.
# It verifies the generated CODEOWNERS is in sync and flags that a
# restricted path changed. GitLab CI cannot portably gate a merge on
# code-owner *approval* from a job, so REAL ENFORCEMENT REQUIRES the
# native GitLab setting:
#   Settings -> Repository -> Protected branches ->
#   "Require approval from Code Owners"  (GitLab Premium / Ultimate)
#   https://docs.gitlab.com/ee/user/project/codeowners/
# Without that setting enabled, this job is advisory only.
write-guard:
  stage: test
  image: node:22-alpine
  rules:
    - if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
      changes:
${t}
  script:
    - corepack enable
    - pnpm install --frozen-lockfile
    - pnpm vis sync codeowners --check
    - >-
      echo "SOFT GUARD: a restricted path changed. This job does NOT enforce
      code-owner approval. Enable 'Require approval from Code Owners' on the
      protected branch (GitLab Premium/Ultimate) for a real merge gate:
      https://docs.gitlab.com/ee/user/project/codeowners/"
`},"renderGitlabWriteGuard"),Re=P(e=>e.length===0?[]:[{content:Pe(e),path:".github/workflows/write-guard.yml"},{content:Ge(e),path:".gitlab/write-guard.gitlab-ci.yml"}],"buildWriteGuardArtifacts");var Se=Object.defineProperty,k=j((e,t)=>Se(e,"name",{value:t,configurable:!0}),"m");const B=new Set(["nested-codeowners","package-json-maintainers","project-json"]),J=k((e,t,o)=>{const s=new Set,r=[];for(const i of e??[])for(const n of i.split(",")){const a=n.trim();if(a.length===0)continue;if(o&&!o(a))throw new Error(`Unknown codeowners source: "${a}". Known: ${[...B].join(", ")}.`);const c=a;s.has(c)||(s.add(c),r.push(c))}return r.length>0?r:[...t]},"parseCsvOption"),We=k(e=>B.has(e),"isCodeownersSource"),L=["codeowners","package-json-fields"],_e=k((e,t)=>t.some(o=>Z(o,e)),"matchesAnyGlob"),Ie=k((e,t,o,s)=>{const r=Object.entries(o.projects).filter(([,n])=>n.restricted===!0).map(([n,a])=>({name:n,root:a.root??n})),i=Re(r);if(i.length===0){e.info("No projects flagged `restricted: true` in project.json. Skipping Write Guard.");return}if(s){let n=!1;for(const a of i){const c=C(t,a.path);let l="";try{l=F(c,"utf8")}catch(p){if(p.code!=="ENOENT")throw p}l.trim()!==a.content.trim()&&(e.error(`${a.path} is out of date. Run \`vis sync codeowners --write-guard\` to update it.`),n=!0)}n?process.exitCode=1:e.info(`Write Guard CI is up to date (${i.length} files, ${r.length} restricted projects).`);return}for(const n of i){const a=C(t,n.path);V(D(a)),A(a,n.content),e.info(`Wrote ${n.path}`)}e.info(`Write Guard CI scoped to ${r.length} restricted project${r.length===1?"":"s"}.`)},"handleWriteGuard"),xe=k(async({logger:e,options:t,visConfig:o,workspaceRoot:s})=>{const r=s,{workspace:i}=ee(r,o),n=o?.codeowners;t.writeGuard===!0&&Ie(e,r,i,t.check===!0);const a=J(t.from,n?.sources??["project-json"],We),c=t.regenerationCommand??n?.regenerationCommand,l=t.preserveBlock===!0||n?.preserveBlock===!0,p=n?.blockMarker??S,m=t.nestedIncludes??n?.nestedIncludes,w=t.out??"CODEOWNERS",f=[];if(a.includes("nested-codeowners")){const g=await we(r,m,w);for(const $ of g)f.push({...$,source:"nested"})}if(a.includes("package-json-maintainers")){const g=je(i,r);for(const $ of g)f.push({...$,source:"maintainers"})}const b=a.includes("project-json")?_(i,n,f):_({projects:{}},n,f);if(b.length===0){e.info("No `owners` entries found in any source. Nothing to sync.");return}const u=C(r,w);let E="";try{E=F(u,"utf8")}catch(g){if(g.code!=="ENOENT")throw g}const d={regenerationCommand:c},h=l?ue(E,le(b,p,d),p):de(b,d);if(t.check){if(E.trim()!==h.trim()){e.error(`${u} is out of date. Run \`vis sync codeowners\` to update it.`),process.exitCode=1;return}e.info(`${u} is up to date.`);return}A(u,h),e.info(`Wrote ${b.length} entries to ${u}`)},"runCodeowners"),Le=k(({logger:e,options:t,visConfig:o,workspaceRoot:s})=>{const r=s,i=o?.editorconfig??!0,n=G(C(r,"package.json"));if(!n){e.error("Could not read root package.json. Nothing to sync."),process.exitCode=1;return}const a=J(t.fields,ke),c=t.ignorePackageName??[],l=t.check===!0,p=(t.format??"human").toLowerCase(),m=t.quiet===!0,w=te(r).filter(d=>d!=="."),f=[];let b=0;for(const d of w){const h=C(r,d,"package.json"),g=G(h);if(!g)continue;const $=typeof g.name=="string"?g.name:void 0;if($!==void 0&&c.length>0&&_e($,c))continue;b+=1;const W=ve(n,g,{fields:a});W.length!==0&&f.push({filePath:h,packageJsonPath:T(r,h),packageName:$,pkg:g,pkgChanges:W})}if(!l)for(const d of f)Ee(d.pkg,d.pkgChanges),Y(d.filePath,d.pkg,{indent:oe(d.filePath,{useEditorconfig:i}),overwrite:!0});const u=f.flatMap(d=>d.pkgChanges.map(h=>({after:h.after,before:h.before,field:h.field,packageJsonPath:d.packageJsonPath,packageName:d.packageName}))),E={changes:u,fields:a,kind:"package-json-fields",mode:l?"check":"write",totalChanges:u.length,totalPackages:b};if(p==="json")process.stdout.write(`${JSON.stringify(E,null,4)}
`);else if(u.length===0)e.info(`All ${b} package${b===1?"":"s"} in sync (fields: ${a.join(", ")}).`);else if(l){if(!m)for(const d of u)e.error(`${d.packageJsonPath}: ${d.field} drifts from root`);e.error(`Found ${u.length} field drift${u.length===1?"":"s"} across ${f.length} package${f.length===1?"":"s"}. Run \`vis sync package-json-fields\` to fix.`)}else{if(!m)for(const d of f)e.info(`${d.packageJsonPath}: synced ${d.pkgChanges.map(h=>h.field).join(", ")}`);e.info(`Synced ${u.length} field${u.length===1?"":"s"} across ${f.length} package${f.length===1?"":"s"}.`)}l&&u.length>0&&(process.exitCode=1)},"runPackageJsonFields"),Je=k(async e=>{const t=e.argument[0];if(!t)throw new Error(`Missing sync kind. Usage: vis sync <kind> (known kinds: ${L.join(", ")})`);if(!e.workspaceRoot)throw new Error("Could not determine workspace root. Run inside a monorepo.");if(t==="codeowners"){await xe(e);return}if(t==="package-json-fields"){Le(e);return}throw new Error(`Unknown sync kind: "${t}". Known kinds: ${L.join(", ")}.`)},"execute");export{Je as default};
