adamantite 0.45.0 → 0.46.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +368 -122
- package/dist/index.js +638 -57
- package/dist/oxlint.js +1 -0
- package/dist/presets/analyze.js +1 -0
- package/dist/presets/lint/{react-doctor.d.ts → architecture.d.ts} +1 -1
- package/dist/presets/lint/architecture.js +8 -0
- package/dist/presets/lint/core.js +0 -1
- package/dist/presets/lint/effect.js +26 -1
- package/dist/presets/lint/plugin/glob.d.ts +7 -0
- package/dist/presets/lint/plugin/glob.js +48 -0
- package/dist/presets/lint/plugin/imports.d.ts +4 -0
- package/dist/presets/lint/plugin/imports.js +4 -1
- package/dist/presets/lint/plugin/index.d.ts +3 -0
- package/dist/presets/lint/plugin/index.js +14 -8
- package/dist/presets/lint/plugin/options.d.ts +5 -5
- package/dist/presets/lint/plugin/options.js +19 -7
- package/dist/presets/lint/plugin/resolver.d.ts +8 -0
- package/dist/presets/lint/plugin/resolver.js +79 -0
- package/dist/presets/lint/plugin/rules/import-owners.d.ts +67 -0
- package/dist/presets/lint/plugin/rules/import-owners.js +310 -0
- package/dist/presets/lint/plugin/rules/layers.d.ts +136 -0
- package/dist/presets/lint/plugin/rules/layers.js +479 -0
- package/dist/presets/lint/plugin/rules/no-query-data-in-state.js +1 -1
- package/dist/presets/lint/plugin/rules/no-react-state-hooks.d.ts +0 -5
- package/dist/presets/lint/plugin/rules/no-react-state-hooks.js +3 -47
- package/dist/presets/lint/plugin/rules/query-from-loader.js +2 -2
- package/dist/presets/lint/plugin/rules/require-suppression-reason.d.ts +5 -0
- package/dist/presets/lint/plugin/rules/require-suppression-reason.js +32 -0
- package/dist/presets/lint/react-strict.js +22 -2
- package/dist/presets/lint/strict.js +35 -2
- package/dist/presets/lint/{antislop.d.ts → tailwind.d.ts} +1 -1
- package/dist/presets/lint/{shadcn.js → tailwind.js} +1 -1
- package/dist/presets/lint/vendor/antislop/license.md +26 -1
- package/dist/presets/lint/vendor/antislop/plugin.d.mts +3 -0
- package/dist/presets/lint/vendor/antislop/plugin.mjs +940 -31
- package/dist/presets/lint/vendor/antislop-effect/license.md +27 -0
- package/dist/presets/lint/vendor/antislop-effect/plugin.d.mts +17 -0
- package/dist/presets/lint/vendor/antislop-effect/plugin.mjs +579 -0
- package/dist/presets/{lint → rules}/custom.d.ts +3 -20
- package/dist/presets/{lint → rules}/custom.js +50 -46
- package/dist/presets/rules/folder.d.ts +34 -0
- package/dist/presets/rules/folder.js +52 -0
- package/dist/presets/rules/index.d.ts +2 -9
- package/dist/presets/rules/index.js +1 -29
- package/dist/presets/rules/load.d.ts +8 -0
- package/dist/presets/rules/load.js +29 -0
- package/dist/presets/rules/plugin.d.ts +3 -0
- package/dist/presets/rules/plugin.js +1 -0
- package/dist/presets/rules/testing.d.ts +2 -0
- package/dist/presets/rules/testing.js +14 -0
- package/dist/presets/tsconfig.json +3 -0
- package/dist/runtime-CVZPDpfE.js +11 -0
- package/package.json +79 -18
- package/skills/adamantite/SKILL.md +112 -207
- package/skills/adamantite/references/custom-rules.md +120 -0
- package/skills/adamantite/references/lint-rules.md +158 -0
- package/skills/adamantite/references/setup.md +64 -0
- package/dist/presets/lint/antislop.js +0 -28
- package/dist/presets/lint/react-doctor.js +0 -20
- package/dist/presets/lint/shadcn.d.ts +0 -5
package/dist/index.js
CHANGED
|
@@ -1,21 +1,28 @@
|
|
|
1
|
-
import*as e from"@effect/platform-node/NodeRuntime";import*as t from"effect/Effect";import*as n from"effect/Exit";import*as r from"effect/process/ChildProcessSpawner";import*as i from"effect/Runtime";import*as a from"effect/Stdio";import*as o from"@effect/platform-node/NodeServices";import*as s from"effect/Array";import*as c from"effect/cli/Command";import*as l from"effect/Layer";import*as u from"effect/cli/Flag";import*as d from"effect/Option";import f from"node:process";import{stripVTControlCharacters as p,styleText as m}from"node:util";import*as h from"effect/Console";import*as g from"effect/Context";import*as _ from"effect/process/ChildProcess";import*as v from"effect/Result";import*as y from"effect/Data";import{pipe as b}from"effect/Function";import*as x from"effect/Predicate";import*as S from"effect/String";import{applyEdits as ee,findNodeAtLocation as te,modify as ne,parse as re,parseTree as ie,printParseErrorCode as ae,visit as oe}from"jsonc-parser";import*as C from"effect/FileSystem";import*as w from"effect/Path";import*as se from"effect/Record";import{defu as ce}from"defu";import*as le from"effect/Equal";import{Visitor as ue,parseSync as de}from"oxc-parser";import*as T from"effect/cli/Argument";import{addDevDependency as fe,detectPackageManager as pe,runScriptCommand as me}from"nypm";import*as E from"effect/Schema";import*as D from"effect/Order";import{delimiter as he}from"node:path";import*as ge from"effect/Config";import*as O from"@clack/prompts";import*as _e from"effect/Terminal";function ve(e){return x.isError(e)?b(p(e.message),S.split(/\r\n|[\r\n]/),s.map(e=>S.trimEnd(e)),s.filter(e=>S.isNonEmpty(e))):[]}function k(e){return b(ve(e),s.head,d.map(e=>{let t=S.trim(e);return/[.!?]$/.test(t)?` Cause: ${t}`:` Cause: ${t}.`}),d.getOrElse(()=>``))}function ye(e){let t=ve(e);if(!s.isReadonlyArrayNonEmpty(t))return``;let n=s.takeRight(t,20);return`\n${(n.length<t.length?[`…`,...n]:n).join(`
|
|
2
|
-
`)}`}function
|
|
3
|
-
`)}
|
|
4
|
-
`)}},
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
`,
|
|
10
|
-
`,t.offset),c=s===-1?a.length:s+1;return a.slice(o,c).trim()===``?a.slice(0,o)+a.slice(c):a}function nt(e,t){let n=e;for(let e of t.keys()){let r=t.slice(0,e+1);for(let e=et(n,r);e;e=et(n,r))n=tt(n,e)}return n}function rt(e,t,n,r){let i=e=>ee(e,ne(e,t,n,{formattingOptions:r})),a=ie(e),o=t.slice(0,-1),s=a&&te(a,o)?.children?.at(-1),c=s?.children?.[0]?.value;if(n===void 0||a===void 0||te(a,t)!==void 0||s?.type!==`property`||!x.isString(c))return i(e);let l=s.offset+s.length,u=$e.exec(e.slice(l));if(u?.groups?.comment===void 0)return i(e);let d=l+(u.groups.comma?.length??0),f=u.groups.comment,p=i(e.slice(0,d)+e.slice(d+f.length)),m=ie(p),h=m&&te(m,[...o,c])?.parent,g=h?h.offset+h.length:d,_=g+(/^[ \t]*,/u.exec(p.slice(g))?.[0].length??0);return p.slice(0,_)+f+p.slice(_)}function it(e,t){let n=re(e,[],{allowTrailingComma:!0}),r=Xe(e);return Qe(n,t,[]).reduce((e,[t,n])=>rt(nt(e,t),t,n,r),e)}const at=/^workspace:/,ot=/^[\^~]/;function st(e){return e.trim().replace(at,``).replace(ot,``)}const R=(e=f.cwd())=>t.gen(function*(){let t=(yield*w.Path).join(e,`package.json`),n=yield*N(t);return yield*I(n,t)}),ct=(e,n)=>t.gen(function*(){let t=(yield*w.Path).join(e,`package.json`),r=yield*N(t);yield*F(t,it(r,n))});function lt(e){return e===`bun`||e===`deno`||e===`npm`||e===`pnpm`||e===`yarn`}const z={analyze:`adamantite analyze`,check:`adamantite check`,fix:`adamantite fix`};function ut(e){let t=e.scripts??{};return b(se.keys(z),s.filter(e=>t[e]===z[e]))}function dt(e,t){let n=e.scripts??{};return s.filterMap(t,e=>{let t=n[e];return t!==void 0&&t!==``&&t!==z[e]?v.succeed({command:t,script:e}):v.failVoid})}const ft=/^(?:packages|"packages"|'packages')\s*:/u;function pt(e){return e.replace(/(?:^|\s+)#.*$/u,``).trim()}function mt(e){let t=e.replace(/^\uFEFF/u,``).split(/\r?\n/u),n=t.findIndex(e=>ft.test(e));if(n===-1)return!1;let r=pt((t[n]??``).replace(ft,``));if(r===`[`){for(let e of t.slice(n+1)){let t=pt(e);if(t.length!==0)return t!==`]`}return!1}if(r&&!r.startsWith(`#`))return!/^\[\s*\]$/u.test(r);for(let e of t.slice(n+1)){if(/^\s*-\s*[^#\s]/u.test(e))return!0;if(/^\S/u.test(e)&&!e.startsWith(`#`))return!1}return!1}const B=(e=f.cwd())=>t.gen(function*(){let t=yield*w.Path,n=yield*P(t.join(e,`pnpm-workspace.yaml`));if(d.isSome(n)&&mt(n.value))return!0;let r=(yield*R(e)).workspaces;return((s.isArray(r)?r:r?.packages)?.length??0)>0});function ht(e){return e.replace(/^(["'])(.*)\1$/u,`$2`)}function gt(e){let t=e.replace(/^\uFEFF/u,``).split(/\r?\n/u),n=t.findIndex(e=>ft.test(e));if(n===-1)return[];let r=pt((t[n]??``).replace(ft,``));if(r.startsWith(`[`)){let e=[r,...t.slice(n+1).map(e=>pt(e))].join(` `),i=e.indexOf(`]`);return e.slice(1,i===-1?void 0:i).split(`,`).map(e=>ht(e.trim())).filter(e=>e.length>0)}let i=[];for(let e of t.slice(n+1)){let t=/^\s*-\s*(.+)$/u.exec(pt(e))?.[1];if(t!==void 0)i.push(ht(t.trim()));else if(/^\S/u.test(e)&&!e.startsWith(`#`))break}return i}function _t(e){return e.replaceAll(/[$()+.[\\\]^{|}]/gu,String.raw`\$&`)}function vt(e){let t=e.replace(/^\.\//u,``).replace(/\/+$/u,``).split(`/`),n=``;for(let[e,r]of t.entries()){let i=e===0||t[e-1]===`**`?``:`/`;r===`**`?e<t.length-1?n+=`${i}(?:[^/]+/)*`:n+=e===0?`(?:[^/]+(?:/[^/]+)*)?`:`(?:/[^/]+)*`:n+=`${i}${_t(r).replaceAll(`*`,`[^/]*`).replaceAll(`?`,`[^/]`)}`}return RegExp(`^${n}$`,`u`)}function yt(e){let t=e.replace(/^\.\//u,``).replace(/\/+$/u,``).split(`/`),n=t.findIndex(e=>/[*?]/u.test(e));return n===-1?{base:t.join(`/`),depth:0}:{base:t.slice(0,n).join(`/`),depth:t.includes(`**`)?1/0:t.length-n}}const bt=/* @__PURE__ */ new Set([`node_modules`]),xt=(e,n,r)=>t.gen(function*(){let i=yield*w.Path,a=yield*Ge(i.resolve(e,n));return d.isNone(a)?[]:r===0?[n]:[n,...(yield*t.forEach(a.value.filter(e=>!e.startsWith(`.`)&&!bt.has(e)),t=>xt(e,n===``?t:`${n}/${t}`,r-1),{concurrency:`unbounded`})).flat()]}),St=(e=f.cwd())=>t.gen(function*(){let n=yield*w.Path,r=yield*P(n.join(e,`pnpm-workspace.yaml`)),i=(yield*R(e)).workspaces,a=d.match(r,{onNone:()=>s.isArray(i)?i:i?.packages??[],onSome:e=>gt(e)}),o=a.filter(e=>!e.startsWith(`!`)),c=a.filter(e=>e.startsWith(`!`)).map(e=>vt(e.slice(1))),l=yield*t.forEach(o,n=>t.gen(function*(){let{base:t,depth:r}=yt(n),i=vt(n);return(yield*xt(e,t,r)).filter(e=>e!==``&&i.test(e))}),{concurrency:`unbounded`}),u=s.dedupe(l.flat()).filter(e=>!c.some(t=>t.test(e)));return(yield*t.forEach(u,r=>P(n.join(e,r,`package.json`)).pipe(t.map(t=>d.isSome(t)?[n.resolve(e,r)]:[])),{concurrency:`unbounded`})).flat()});function Ct(e){return e.endsWith(`.jsonc`)?`jsonc`:e.endsWith(`.json`)?`json`:`ts`}function wt(e,t){return s.findFirst(e.legacyConfigs,e=>Ct(e)===t)}function Tt(e){let t=wt(e,`json`),n=wt(e,`jsonc`);return b(d.zipWith(t,n,e=>`${e}(c)`),d.orElse(()=>n),d.orElse(()=>t),d.getOrElse(()=>``))}function Et(e,t,n,r){return n===null||r.length===0?[]:n.format===`ts`?[`Found both \`${t.config}\` and \`${Tt(t)}\`. Adamantite will use \`${t.config}\`.`]:b(d.zipWith(wt(t,`json`),wt(t,`jsonc`),(t,n)=>`Found both \`${t}\` and \`${n}\`. Multiple legacy ${e} configs exist; Adamantite will treat \`${n}\` as the source of truth in its findings.`),d.toArray)}const Dt=t.fn(`detectToolingConfig`)(function*(e,n,r){let i=yield*C.FileSystem,a=yield*w.Path,o=[r.config,...r.legacyConfigs].map(t=>({file:t,format:Ct(t),path:a.join(e,t)})),c=yield*t.forEach(o,e=>i.exists(e.path),{concurrency:`unbounded`}),l=o.filter((e,t)=>c[t]),u=b(s.findFirst(l,e=>e.format===`ts`),d.orElse(()=>s.findFirst(l,e=>e.format===`jsonc`)),d.orElse(()=>s.findFirst(l,e=>e.format===`json`)),d.getOrNull),f=l.filter(e=>e!==u&&e.format!==`ts`);return{active:u,legacy:f,warnings:Et(n,r,u,f)}});function Ot(e,t,n){let r=e.devDependencies?.[t.name]??e.dependencies?.[t.name];return r?st(r)===t.version?[]:[{currentVersion:r,description:`Update \`${t.name}\` from \`${r}\` to \`${t.version}\`.`,package:t.name,targetVersion:t.version,type:`update_package`}]:[{description:`Install \`${t.name}@${t.version}\` for ${n}.`,package:t.name,targetVersion:t.version,type:`install_package`}]}function kt(e,t){return e.map(e=>({currentState:e.type===`install_package`?`The required package \`${e.package}\` is not installed.`:`The installed \`${e.package}\` version is \`${e.currentVersion}\`, but Adamantite requires \`${e.targetVersion}\`.`,goal:[`Run \`adamantite update\` so \`${e.package}@${e.targetVersion}\` is installed.`],id:`${e.type===`install_package`?`missing`:`outdated`}-${e.package}`,integration:t,title:e.type===`install_package`?`Missing ${e.package}`:`Outdated ${e.package}`}))}function At(e,t){if(e.active===null)return[{currentState:`The managed \`${t.configFile}\` file is missing.`,goal:[`Create \`${t.configFile}\` with the reference content.`,`Do not create a legacy JSON or JSONC ${t.toolName} config.`],id:`missing-${t.toolName}-config`,integration:t.toolName,reference:{content:t.configContent,language:`ts`},title:`Missing ${t.toolName} configuration`}];if(e.active.format!==`ts`)return[{currentState:`Legacy \`${e.active.file}\` is the active ${t.toolName} configuration.`,goal:[`Port the project settings into \`${t.configFile}\` using the reference content as the base.`,`Delete every legacy ${t.toolName} JSON or JSONC config after its settings are preserved.`],id:`legacy-${t.toolName}-config`,integration:t.toolName,notes:[`Preserve project-specific settings. Do not replace them with the reference defaults.`],reference:{content:t.configContent,language:`ts`},title:`Legacy ${t.toolName} configuration`}];let n=[];return e.legacy.length>0&&n.push({currentState:`Legacy ${t.toolName} config files remain next to \`${t.configFile}\`: ${e.legacy.map(({file:e})=>`\`${e}\``).join(`, `)}.`,goal:[`Delete the legacy files after you confirm that \`${t.configFile}\` preserves their project-specific settings.`],id:`shadowed-legacy-${t.toolName}-config`,integration:t.toolName,title:`Legacy ${t.toolName} files remain`}),t.inspection?.kind===`invalid`&&n.push({currentState:`\`${t.configFile}\` does not meet Adamantite's required shape. ${t.inspection.reason}`,goal:[t.invalidGoal??t.inspection.goal??`Update \`${t.configFile}\` so it includes the required Adamantite preset while preserving project-specific settings.`],id:`invalid-${t.toolName}-config`,integration:t.toolName,notes:[`Treat the reference as a known-good example, not an exact replacement.`],reference:{content:t.configContent,language:`ts`},title:`Invalid ${t.toolName} configuration`}),n}function jt(e,t){let n=ut(e);return t.some(e=>n.includes(e))}function Mt(e){return M({assess:(n,r)=>t.gen(function*(){let t=jt(r,e.scripts)&&(!e.monorepoOnly||(yield*B(n)))&&(e.isRequired===void 0||(yield*e.isRequired(n))),i=e.legacyFindings?.(r)??[];if(!t)return i.length>0?{applicable:!0,findings:[...i],packageActions:[],warnings:[]}:{applicable:!1,warnings:[]};let a=Ot(r,e,e.purpose);return{applicable:!0,findings:[...kt(a,e.name),...i],packageActions:a,warnings:[]}}),kind:`tooling`,name:e.name,version:e.version})}const Nt=t.fn(`detectToolingWorkspace`)(function*(e){return{isMonorepo:yield*B(e)}});function Pt(e){let n=[{path:e.configFiles.config,type:`config`},...e.configFiles.legacyConfigs.map(e=>({path:e,type:`legacy_config`}))],r=t=>Dt(t,e.name,e.configFiles);return M({assess:(n,i)=>t.gen(function*(){let t=e.legacyFindings?.(i)??[];if(!jt(i,e.scripts))return t.length>0?{applicable:!0,findings:t,packageActions:[],warnings:[]}:{applicable:!1,warnings:[]};let a=yield*r(n),o=Ot(i,e,e.purpose),s=yield*e.detectWorkspace(n),c=e.configContent(s),l=a.active?.format===`ts`?e.inspectConfig(yield*N(a.active.path),s):void 0;return{applicable:!0,findings:[...kt(o,e.name),...At(a,{configContent:c,configFile:e.configFiles.config,inspection:l,toolName:e.name}),...t],packageActions:o,warnings:a.warnings}}),config:e.configFiles.config,create:n=>t.gen(function*(){let t=yield*w.Path;yield*F(t.join(n,e.configFiles.config),e.configContent(yield*e.detectWorkspace(n)))}),detect:r,files:n,kind:`tooling`,name:e.name,version:e.version})}const Ft=[`respectEslintDisableDirectives`,`typeAware`,`typeCheck`],It="`oxlint.config.ts` must export an object literal directly, with or without `defineConfig(...)`, for Adamantite to inspect `options`.",Lt="`oxlint.config.ts` has an `options` property, but it is not an object literal that Adamantite can inspect.",Rt=[`react`,`react-strict`,`react-doctor`,`tanstack`,`nextjs`,`vue`,`effect`,`jest`,`vitest`,`node`,`strict`,`antislop`,`shadcn`];function zt(e){return e.replaceAll(/-([a-z])/g,(e,t)=>t.toUpperCase())}function Bt(e=[]){let t=e.includes(`core`)?e:[`core`,...e];return[`import { defineConfig } from "oxlint"`,...t.map(e=>`import ${zt(e)} from "${e===`core`?`adamantite/lint`:`adamantite/lint/${e}`}"`),`import custom from "adamantite/lint/custom"`,``,`export default defineConfig({`,` extends: [${[...t.map(e=>zt(e)),`custom()`].join(`, `)}],`,` ignorePatterns: core.ignorePatterns,`,` options: {`,...Ft.map(e=>` ${e}: true,`),` },`,`})`,``].join(`
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
1
|
+
import{$ as e,A as t,At as n,B as r,C as i,Ct as a,D as o,Dt as s,E as c,Et as l,F as u,G as d,H as f,I as p,J as m,K as h,L as g,M as _,Mt as v,N as ee,O as y,Ot as te,P as b,Q as ne,R as x,S as re,St as ie,T as ae,Tt as oe,U as S,V as C,W as se,X as ce,Y as w,Z as le,_ as ue,_t as de,a as fe,at as pe,bt as me,c as he,ct as ge,d as _e,dt as ve,et as ye,f as be,ft as xe,g as Se,gt as T,h as Ce,ht as we,i as Te,it as Ee,j as De,jt as Oe,k as ke,kt as Ae,l as je,lt as Me,m as Ne,mt as Pe,n as Fe,nt as Ie,ot as Le,p as Re,pt as ze,q as Be,r as Ve,rt as He,s as Ue,st as We,t as Ge,tt as Ke,u as qe,ut as Je,vt as Ye,w as Xe,wt as Ze,x as Qe,xt as $e,y as et,yt as tt,z as nt}from"./runtime-CVZPDpfE.js";import*as rt from"@effect/platform-node/NodeRuntime";import*as E from"effect/Effect";import*as it from"effect/Exit";import*as D from"effect/process/ChildProcessSpawner";import*as at from"effect/Runtime";import*as ot from"effect/Stdio";import*as st from"@effect/platform-node/NodeServices";import*as O from"effect/Array";import*as k from"effect/cli/Command";import*as A from"effect/Layer";import j from"node:process";import*as M from"effect/cli/Flag";import*as N from"effect/Option";import*as ct from"effect/Context";import*as P from"effect/Path";import*as F from"effect/Predicate";import{styleText as lt}from"node:util";import*as ut from"effect/Console";import*as dt from"effect/process/ChildProcess";import*as ft from"effect/Result";import*as I from"effect/Data";import{pipe as L}from"effect/Function";import*as pt from"effect/String";import*as R from"effect/FileSystem";import*as mt from"effect/Equal";import*as z from"effect/Schema";import*as ht from"effect/encoding/Yaml";import*as gt from"effect/SchemaTransformation";import*as _t from"effect/Record";import*as vt from"effect/RegExp";import{Visitor as yt,parseSync as bt}from"oxc-parser";import*as B from"effect/Order";import*as xt from"effect/Config";import*as V from"effect/cli/Argument";import{addDevDependency as St,detectPackageManager as Ct,runScriptCommand as wt}from"nypm";import*as H from"@clack/prompts";import*as Tt from"effect/Cause";import{posix as U,win32 as Et}from"node:path";import*as Dt from"effect/Stream";import*as Ot from"effect/Brand";import*as kt from"effect/Terminal";const At=ct.Reference(`adamantite/ForwardedArguments`,{defaultValue:()=>[]}),jt=(e,t)=>ut.log(`${lt(`bold`,e)} ${lt(`dim`,`· adamantite (${t})`)}`),Mt=()=>[j.env.NODE_OPTIONS,`--disable-warning=MODULE_TYPELESS_PACKAGE_JSON`].filter(Boolean).join(` `),Nt=E.fn(`CommandRunner.exitCode`)(function*(e){let{command:t}=e;return yield*E.scoped(E.gen(function*(){return yield*(yield*dt.make(t,e.args,{cwd:e.cwd,detached:e.stdin!==`inherit`&&void 0,env:{...e.env,NODE_OPTIONS:Mt()},extendEnv:!0,stderr:e.stderr??`inherit`,stdin:e.stdin??`ignore`,stdout:e.stdout??`inherit`})).exitCode})).pipe(E.catchReason(`PlatformError`,`NotFound`,()=>E.fail(new Ke({command:t}))))});var Pt=class e extends ct.Service()(`CommandRunner`){static make(e){let t=E.fn(`CommandRunner.run`)(function*(t){t.title!==void 0&&(yield*jt(t.title,t.name??t.command));let n=yield*e(t);if(n!==D.ExitCode(0))return yield*new Ie({command:t.command,exitCode:n})}),n=e=>e.map((e,n)=>n===0?t(e):E.andThen(ut.log(``),t(e)));return{exitCode:e,run:t,runAll:E.fn(`CommandRunner.runAll`)(function*(e){let t=yield*E.all(n(e),{concurrency:1,mode:`result`});yield*E.fromResult(ft.all(t))}),runUntilFailure:E.fn(`CommandRunner.runUntilFailure`)(function*(e){yield*E.all(n(e),{concurrency:1,discard:!0})})}}static layer=A.effect(this)(E.gen(function*(){let t=yield*D.ChildProcessSpawner;return e.make(e=>Nt(e).pipe(E.provideService(D.ChildProcessSpawner,t)))}))};function W(e){return e}var Ft=class extends I.TaggedClass(`Missing`){},It=class extends I.TaggedClass(`Current`){},Lt=class extends I.TaggedClass(`Legacy`){};function Rt(e){return e.endsWith(`.jsonc`)?`jsonc`:e.endsWith(`.json`)?`json`:`ts`}function zt(e,t){return O.findFirst(e.legacyConfigs,e=>Rt(e)===t)}function Bt(e){let t=zt(e,`json`),n=zt(e,`jsonc`);return L(N.zipWith(t,n,e=>`${e}(c)`),N.orElse(()=>n),N.orElse(()=>t),N.getOrElse(()=>``))}function Vt(e,t,n,r){return n instanceof Ft||r.length===0?[]:n instanceof It?[`Found both \`${t.config}\` and \`${Bt(t)}\`. Adamantite will use \`${t.config}\`.`]:L(N.zipWith(zt(t,`json`),zt(t,`jsonc`),(t,n)=>`Found both \`${t}\` and \`${n}\`. Multiple legacy ${e} configs exist. Doctor uses \`${n}\` when checking the setup.`),N.toArray)}const Ht=E.fn(`detectToolingConfig`)(function*(e,t,n){let r=yield*R.FileSystem,i=yield*P.Path,a=[n.config,...n.legacyConfigs].map(t=>({file:t,format:Rt(t),path:i.join(e,t)})),o=yield*E.forEach(a,e=>r.exists(e.path),{concurrency:`unbounded`}),s=a.filter((e,t)=>o[t]),c=({file:e,path:t})=>({file:e,path:t}),l=L(O.findFirst(s,e=>e.format===`ts`),N.orElse(()=>O.findFirst(s,e=>e.format===`jsonc`)),N.orElse(()=>O.findFirst(s,e=>e.format===`json`))),u=N.match(l,{onNone:()=>new Ft,onSome:e=>e.format===`ts`?new It({file:c(e)}):new Lt({file:c(e)})}),d=s.flatMap(e=>e.format!==`ts`&&!N.exists(l,t=>t===e)?[c(e)]:[]);return{active:u,legacy:d,warnings:Vt(t,n,u,d)}}),Ut={findings:[],packageActions:[],warnings:[]};function Wt({packageJson:e,workspace:{catalogs:t}},n,r,i){let a=e.devDependencies?.[n.name]??e.dependencies?.[n.name];if(!a)return{findings:[{currentState:`The required package \`${n.name}\` is not installed.`,goal:[`Run \`adamantite update\` so \`${n.name}@${n.version}\` is installed.`],id:`missing-${n.name}`,integration:i,title:`Missing ${n.name}`}],packageActions:[{description:`Install \`${n.name}@${n.version}\` for ${r}.`,package:n.name,targetVersion:n.version,type:`install_package`}],warnings:[]};function o(e){return{findings:[],packageActions:[],warnings:[`\`${n.name}\` is declared as \`${e}\`, so Adamantite cannot check it against the required version \`${n.version}\`.`]}}function s(e,t){let r=e==="default"?"the `catalog`":`the \`${e}\` catalog`;return{findings:[{currentState:`${r} of \`pnpm-workspace.yaml\` sets \`${n.name}\` to \`${t}\`, but Adamantite requires \`${n.version}\`.`,goal:[`Set \`${n.name}\` to \`${n.version}\` in ${r} of \`pnpm-workspace.yaml\`, then install the dependencies.`],id:`outdated-${n.name}`,integration:i,notes:["Keep the `catalog:` specifier in `package.json`. `adamantite update` does not change catalogs."],title:`Outdated ${n.name}`}],packageActions:[],warnings:[]}}return ee(b(a),{Catalog:({catalog:e})=>{let r=t[e]?.[n.name];return r===void 0?o(a):ee(b(r),{Catalog:()=>o(a),Unreadable:()=>o(a),Version:({version:t})=>t===n.version?Ut:s(e,r)})},Unreadable:()=>o(a),Version:({version:e})=>e===n.version?Ut:{findings:[{currentState:`The installed \`${n.name}\` version is \`${a}\`, but Adamantite requires \`${n.version}\`.`,goal:[`Run \`adamantite update\` so \`${n.name}@${n.version}\` is installed.`],id:`outdated-${n.name}`,integration:i,title:`Outdated ${n.name}`}],packageActions:[{currentVersion:a,description:`Update \`${n.name}\` from \`${a}\` to \`${n.version}\`.`,package:n.name,targetVersion:n.version,type:`update_package`}],warnings:[]}})}function Gt(e,t){if(e.active instanceof Ft)return[{currentState:`The managed \`${t.configFile}\` file is missing.`,goal:[`Create \`${t.configFile}\` with the reference content.`,`Do not create a legacy JSON or JSONC ${t.toolName} config.`],id:`missing-${t.toolName}-config`,integration:t.toolName,reference:{content:t.configContent,language:`ts`},title:`Missing ${t.toolName} configuration`}];if(e.active instanceof Lt)return[{currentState:`Legacy \`${e.active.file.file}\` is the active ${t.toolName} configuration.`,goal:[`Move the project settings into \`${t.configFile}\` using the reference content as the base.`,`Delete every legacy ${t.toolName} JSON or JSONC config after its settings are preserved.`],id:`legacy-${t.toolName}-config`,integration:t.toolName,notes:[`Preserve project-specific settings. Do not replace them with the reference defaults.`],reference:{content:t.configContent,language:`ts`},title:`Legacy ${t.toolName} configuration`}];let n=[];return e.legacy.length>0&&n.push({currentState:`Legacy ${t.toolName} config files remain next to \`${t.configFile}\`: ${e.legacy.map(({file:e})=>`\`${e}\``).join(`, `)}.`,goal:[`Delete the legacy files after you confirm that \`${t.configFile}\` preserves their project-specific settings.`],id:`shadowed-legacy-${t.toolName}-config`,integration:t.toolName,title:`Legacy ${t.toolName} files remain`}),t.inspection?.kind===`invalid`&&n.push({currentState:`\`${t.configFile}\` does not meet Adamantite's required shape. ${t.inspection.reason}`,goal:[t.inspection.goal],id:`invalid-${t.toolName}-config`,integration:t.toolName,notes:[`Treat the reference as a known-good example, not an exact replacement.`],reference:{content:t.configContent,language:`ts`},title:`Invalid ${t.toolName} configuration`}),n}function Kt(e,n){let r=t(e);return n.some(e=>r.includes(e))}function qt(e){return W({assess:t=>E.sync(()=>{let{packageJson:n}=t,r=Kt(n,e.scripts)&&(!e.monorepoOnly||t.workspace.isMonorepo)&&(e.isRequired===void 0||e.isRequired(t)),i=e.legacyFindings?.(n)??[];if(!r)return i.length>0?{applicable:!0,findings:[...i],packageActions:[],warnings:[]}:{applicable:!1};let a=Wt(t,e,e.purpose,e.name);return{applicable:!0,findings:[...a.findings,...i],packageActions:a.packageActions,warnings:a.warnings}}),kind:`tooling`,name:e.name,version:e.version})}const Jt=E.fn(`readToolingFacts`)(function*(e){let t=yield*P.Path,[n,r]=yield*E.all([Qe(e),C(t.join(e,`oxlint.config.ts`))],{concurrency:`unbounded`});return{isMonorepo:n,lintConfig:r}});function Yt(e){let t=[{path:e.configFiles.config,type:`config`},...e.configFiles.legacyConfigs.map(e=>({path:e,type:`legacy_config`}))],n=t=>Ht(t,e.name,e.configFiles);return W({assess:t=>E.gen(function*(){let{cwd:i,lintConfig:a,packageJson:o,workspace:{isMonorepo:s}}=t;if(!Kt(o,e.scripts))return{applicable:!1};let c=yield*n(i),l=e.workspace({isMonorepo:s,lintConfig:a}),u=Wt(t,e,e.purpose,e.name),d=e.configContent(l),f=c.active instanceof It?e.inspectConfig(yield*r(c.active.file.path),l):void 0;return{applicable:!0,findings:[...u.findings,...Gt(c,{configContent:d,configFile:e.configFiles.config,inspection:f,toolName:e.name})],packageActions:u.packageActions,warnings:[...u.warnings,...c.warnings]}}),config:e.configFiles.config,create:t=>E.gen(function*(){let n=yield*P.Path;yield*S(n.join(t,e.configFiles.config),e.configContent(e.workspace(yield*Jt(t))))}),detect:n,files:t,kind:`tooling`,name:e.name,version:e.version})}function G(e){return`adamantite${e.slice(1)}`}const Xt=G(`./rules`),K=`.adamantite/lint`,Zt=/* @__PURE__ */ new Set([`.js`,`.mjs`,`.mts`,`.ts`]);function Qt(e){let t=/\.[^.]+$/.exec(e)?.[0]??``;return Zt.has(t)&&!e.startsWith(`_`)&&!/\.(?:d\.m?ts|test\.[^.]+)$/.test(e)}function $t(e){return!e.startsWith(`_`)&&/\.test\.(?:js|mjs|mts|ts)$/.test(e)}var en=class extends I.TaggedClass(`Dynamic`){},tn=class extends I.TaggedClass(`Literal`){};const nn=new en;function rn(e,t){return bt(e,t,{preserveParens:!1,sourceType:`module`})}function an(e){return e.body.flatMap(e=>e.type===`ImportDeclaration`&&e.source.value===Xt?e.specifiers:[]).filter(e=>e.type===`ImportDefaultSpecifier`).map(e=>e.local.name)}function on(e,t){let n=rn(e,t);return n.errors.length>0?!1:n.program.body.some(e=>e.type===`ImportDeclaration`?e.source.value===`adamantite/lint/custom`||e.source.value===Xt&&e.specifiers.some(e=>e.type===`ImportSpecifier`&&(e.imported.type===`Identifier`?e.imported.name:e.imported.value)!==`CustomRulesOptions`):e.type===`ExportNamedDeclaration`&&e.source!==null?e.source.value===`adamantite/lint/custom`||e.source.value===Xt&&e.specifiers.some(e=>{let t=e.local.type===`Identifier`?e.local.name:e.local.value;return t!=="default"&&t!==`CustomRulesOptions`}):e.type===`ExportAllDeclaration`&&e.source.value===`adamantite/lint/custom`)}function sn(e){return e.type===`Literal`&&F.isString(e.value)?e.value:e.type===`TemplateLiteral`&&e.expressions.length===0?e.quasis[0]?.value.cooked??null:null}function cn(e){return e.type===`Literal`&&F.isString(e.value)?e.value:null}function ln(e,t,n){let r=L(e,O.findLast(e=>(e.key.type===`Identifier`?e.key.name:cn(e.key))===t));return N.fromNullOr(N.match(r,{onNone:()=>n,onSome:({value:e})=>sn(e)}))}function un(e){let t=e.filter(e=>e.type!==`SpreadElement`&&!e.computed);return t.length<e.length?nn:N.match(ln(t,`dir`,K),{onNone:()=>nn,onSome:e=>new tn({dir:e,name:ln(t,`name`,`project`)})})}function dn(e,t){let n=rn(e,t),r=an(n.program);if(n.errors.length>0||r.length===0)return[];let i=[];return new yt({CallExpression(e){if(e.callee.type!==`Identifier`||!r.includes(e.callee.name))return;let[t]=e.arguments;t===void 0?i.push(un([])):t.type===`ObjectExpression`?i.push(un(t.properties)):i.push(nn)}}).visit(n.program),i}function fn(e,t){return e.slice(0,t).split(`
|
|
2
|
+
`).length}function pn(e){switch(e.type){case`TSInterfaceDeclaration`:case`TSTypeAliasDeclaration`:return!0;case`TSModuleDeclaration`:return mn(e);case`ClassDeclaration`:case`FunctionDeclaration`:case`TSEnumDeclaration`:case`VariableDeclaration`:return e.declare===!0;case`ExportNamedDeclaration`:return e.declaration===null?e.exportKind===`type`:pn(e.declaration);default:return!1}}function mn(e){return e.kind===`global`||e.declare||e.body===null||e.body.body.every(e=>e.type!==`ExpressionStatement`&&pn(e))}function hn(e){return e.body.some(e=>e.type===`ExportDefaultDeclaration`?e.declaration.type!==`TSInterfaceDeclaration`:e.type===`ExportNamedDeclaration`&&e.exportKind!==`type`&&e.specifiers.some(e=>e.exportKind!==`type`&&(e.exported.type===`Literal`?e.exported.value==="default":e.exported.name==="default")))}function gn(e,t){let n=rn(e,t);return n.errors.length>0?[]:n.program.body.flatMap(e=>{switch(e.type){case`ImportDeclaration`:return e.importKind===`type`?[]:[e.source.value];case`ExportAllDeclaration`:case`ExportNamedDeclaration`:return e.source===null||e.exportKind===`type`?[]:[e.source.value];default:return[]}})}function _n(e,t){let n=rn(e,t);if(n.errors.length>0)return n.errors.map(e=>`Syntax error: ${e.message}`);let r=[],i=(e,n)=>{r.push(`Line ${fn(t,e)}: ${n} needs a TypeScript transform, which type stripping does not do.`)};return new yt({TSEnumDeclaration(e){e.declare||i(e.start,"`enum`")},TSExportAssignment(e){i(e.start,"`export =`")},TSImportEqualsDeclaration(e){e.importKind!==`type`&&i(e.start,"`import x = ...`")},TSModuleDeclaration(e){mn(e)||i(e.start,"A `namespace` with values")},TSParameterProperty(e){i(e.start,`A parameter property`)}}).visit(n.program),hn(n.program)||r.push(`The file has no default export. Export the rule as default.`),r}const vn=[`respectEslintDisableDirectives`,`typeAware`,`typeCheck`],yn="`oxlint.config.ts` must export an object literal directly, with or without `defineConfig(...)`, for Adamantite to inspect `options`.",bn="`oxlint.config.ts` has an `options` property, but it is not an object literal that Adamantite can inspect.",xn="Set `respectEslintDisableDirectives`, `typeAware`, and `typeCheck` to `true` in the `options` object. Preserve every other project setting.";function Sn(e){return e.replaceAll(/-([a-z])/g,(e,t)=>t.toUpperCase())}function Cn(e=[]){let t=[`core`,...e];return[`import { defineConfig } from "oxlint"`,...t.map(e=>`import ${Sn(e)} from "${G(e===`core`?`./lint`:`./lint/${e}`)}"`),`import custom from "${G(`./rules`)}"`,``,`export default defineConfig({`,` extends: [${[...t.map(e=>Sn(e)),`custom()`].join(`, `)}],`,` ignorePatterns: core.ignorePatterns,`,` options: {`,...vn.map(e=>` ${e}: true,`),` },`,`})`,``].join(`
|
|
3
|
+
`)}const wn=N.liftThrowable(e=>bt(`oxlint.config.ts`,e,{astType:`ts`,lang:`ts`,sourceType:`module`}));function Tn(e){return wn(e).pipe(N.flatMap(e=>e.errors.length===0?N.fromNullishOr(e.program):N.none()))}const En=`${G(`./lint`)}/`;function Dn(e){return L(Tn(e),N.map(e=>e.body.flatMap(e=>e.type===`ImportDeclaration`&&e.source.value.startsWith(En)&&e.source.value!==`adamantite/lint/custom`?[e.source.value.slice(En.length)]:[])),N.getOrElse(()=>[]))}function On(e,t){return N.exists(e,e=>Dn(e).includes(t))}function kn(e){return e.type===`Identifier`?L(e.name,N.some):e.type===`Literal`&&F.isString(e.value)?L(e.value,N.some):N.none()}function An(e){return e.type===`ObjectExpression`?L(e,N.some):e.type!==`CallExpression`||e.callee.type!==`Identifier`||e.callee.name!==`defineConfig`?N.none():L(e.arguments.length===1?O.head(e.arguments):N.none(),N.filter(e=>e.type===`ObjectExpression`))}function jn(e){return L(e.body,O.filter(e=>e.type===`ExportDefaultDeclaration`),e=>e.length===1?O.head(e):N.none(),N.flatMap(e=>An(e.declaration)))}function Mn(e,t){let n=null;for(let r of e.properties){if(r.type===`SpreadElement`||r.computed)return{status:`invalid`};let e=N.contains(kn(r.key),t);if(r.method||r.kind!==`init`){if(e)return{status:`invalid`}}else if(e){if(n)return{status:`invalid`};n=r}}return n?{property:n,status:`found`}:{status:`missing`}}function Nn(e){for(let t of vn){let n=Mn(e,t);if(n.status===`invalid`)return{goal:xn,kind:`invalid`,reason:"`oxlint.config.ts` has an `options` object Adamantite cannot inspect. Make sure each required option is a plain `key: true | false` property. Avoid spreads (`...rest`), computed keys (`[name]: ...`), duplicate keys, methods/getters/setters, and non-boolean-literal values."};if(n.status===`missing`||n.property.value.type!==`Literal`||n.property.value.value!==!0)return{goal:xn,kind:`invalid`,reason:`The required Oxlint options are missing or are not set to true.`}}return{kind:`configured`}}function Pn(e){let t=Tn(e);if(N.isNone(t))return{goal:"Fix the syntax errors in `oxlint.config.ts`. Preserve every project setting.",kind:`invalid`,reason:yn};let n=jn(t.value);if(N.isNone(n))return{goal:"Export the config object literal directly from `oxlint.config.ts`, with or without `defineConfig(...)`. Preserve every project setting.",kind:`invalid`,reason:yn};let r=Mn(n.value,`options`);return r.status===`invalid`?{goal:xn,kind:`invalid`,reason:bn}:r.status===`missing`?{goal:xn,kind:`invalid`,reason:`The required Oxlint options are missing.`}:r.property.value.type===`ObjectExpression`?Nn(r.property.value):{goal:xn,kind:`invalid`,reason:bn}}function Fn(e,t){for(let n of e.body)if(n.type===`ImportDeclaration`&&n.source.value===t){for(let e of n.specifiers)if(e.type===`ImportDefaultSpecifier`)return e.local.name}return null}function In(e,t){for(let n of e.body)if(n.type===`VariableDeclaration`){for(let e of n.declarations)if(e.id.type===`Identifier`&&e.id.name===t)return e.init}return null}function Ln(e,t,n){let r=!1;return new yt({Identifier:e=>{e.start>=n.start&&e.end<=n.end&&e.name===t&&(r=!0)}}).visit(e),r}function Rn(e,t){let n=e.body.filter(e=>e.type===`ExportDefaultDeclaration`);if(n.length!==1)return!1;let r=n[0]?.declaration;if(!r)return!1;if(r.type!==`Identifier`)return Ln(e,t,r);if(r.name===t)return!0;let i=In(e,r.name);return i!==null&&Ln(e,t,i)}function zn(e,t){let n=`Import the ${t.presetName} preset from \`${t.moduleName}\`, and use it in the exported config. Preserve every project-specific setting.`,r=bt(`config.ts`,e,{astType:`ts`,lang:`ts`,sourceType:`module`});if(r.errors.length>0)return{goal:`Fix the syntax errors in the file. Preserve every project-specific setting.`,kind:`invalid`,reason:`The file is not valid TypeScript.`};let i=Fn(r.program,t.moduleName);return i?Rn(r.program,i)?{kind:`configured`}:{goal:n,kind:`invalid`,reason:`The imported ${t.presetName} preset is not used by the exported configuration.`}:{goal:n,kind:`invalid`,reason:`The file must import the ${t.presetName} preset from \`${t.moduleName}\`.`}}const Bn=[`monorepo`,`effect`],Vn={effect:[`@effect/language-service`],monorepo:[`sherif`]},Hn={effect:e=>e.usesEffectPreset,monorepo:e=>e.isMonorepo},Un={effect:"the `effect` lint preset names the `@effect/language-service` plugin in `tsconfig.json`, and no package has that name",monorepo:"Knip cannot see that `adamantite analyze` runs Sherif in a monorepo"},Wn={isMonorepo:!1,usesEffectPreset:!1};function Gn(e,t){return new RegExp(String.raw`ignoreDependencies\s*:\s*\[[^\]]*?${vt.escape(t)}`,`u`).test(e)}function Kn(e,t){return new RegExp(String.raw`ignoreDependencies\s*:\s*(?:ignoreDependencies\.${t}|\[[^\]]*?ignoreDependencies\.${t})`,`u`).test(e)}const qn=/import\s[^;]*?\{[^}]*\bignoreDependencies\b[^}]*\}\s*from\s*["']adamantite\/analyze["']/u;function Jn(e){return Bn.filter(t=>Hn[t](e))}function Yn(e,t){return Vn[t].every(t=>Gn(e,t))||Kn(e,t)&&qn.test(e)}function Xn(e){let[t]=e;return e.length===1&&t!==void 0?`ignoreDependencies.${t}`:`[${e.map(e=>`...ignoreDependencies.${e}`).join(`, `)}]`}function Zn({isMonorepo:e,lintConfig:t}){return{isMonorepo:e,usesEffectPreset:On(t,`effect`)}}function Qn(e,t){let n=zn(e,{moduleName:G(`./analyze`),presetName:`Adamantite analyze`});if(n.kind!==`configured`)return n;let r=Jn(t),i=r.filter(t=>!Yn(e,t));if(i.length===0)return n;let a=`\`ignoreDependencies: ${Xn(r)}\``;return{goal:`Set ${a} in \`knip.config.ts\`, with the named \`ignoreDependencies\` import from \`adamantite/analyze\`, and keep the other settings.`,kind:`invalid`,reason:`The file must set ${a} from \`adamantite/analyze\`, because ${i.map(e=>Un[e]).join(`, and `)}.`}}function $n(e=Wn){let t=Jn(e);return[`import type { KnipConfig } from "knip"`,t.length>0?`import analyze, { ignoreDependencies } from "${G(`./analyze`)}"`:`import analyze from "${G(`./analyze`)}"`,``,...t.length>0?[`const config: KnipConfig = {`,` ...analyze,`,` ignoreDependencies: ${Xn(t)},`,`}`]:[`const config: KnipConfig = analyze`],``,`export default config`,``].join(`
|
|
4
|
+
`)}function er(e){return{args:[...e.fix?[`--fix`,`--allow-remove-files`]:[],...e.strict?[`--production`,`--strict`]:[],...e.forwardedArguments],command:`knip`,cwd:e.cwd,stdin:`ignore`,title:`🧹 Analyzing unused code`}}var tr={analyze:er,...Yt({configContent:$n,configFiles:{config:`knip.config.ts`,legacyConfigs:[`knip.json`,`knip.jsonc`]},inspectConfig:Qn,name:`knip`,purpose:"the managed `analyze` script",scripts:De(`knip`),version:`6.42.0`,workspace:Zn})};function nr(e){return{args:[`--check`,...e.files,...e.forwardedArguments],command:`oxfmt`,cwd:e.cwd,title:`✨ Checking formatting`}}function rr(e){return{args:[`--write`,...e.files,...e.forwardedArguments],command:`oxfmt`,cwd:e.cwd,title:`✨ Formatting`}}function ir(e){return zn(e,{moduleName:G(`./format`),presetName:`Adamantite format`})}function ar(){return`import { defineConfig } from "oxfmt"
|
|
5
|
+
import format from "adamantite/format"
|
|
6
|
+
|
|
7
|
+
export default defineConfig(format)
|
|
8
|
+
`}var q={check:nr,fix:rr,...Yt({configContent:ar,configFiles:{config:`oxfmt.config.ts`,legacyConfigs:[`.oxfmtrc.json`,`.oxfmtrc.jsonc`]},inspectConfig:ir,name:`oxfmt`,purpose:"the managed `check` and `fix` scripts",scripts:De(`oxfmt`),version:`0.76.0`,workspace:({isMonorepo:e})=>({isMonorepo:e})})};function or(e){let t=et(e.cwd),n=e.forwardedArguments.some(e=>e===`--deny-warnings`||e.startsWith(`--max-warnings`)),r=e.allowWarnings||n?[]:[`--deny-warnings`];return{...t,args:[...t.args,...e.files,...r,...e.forwardedArguments],title:`🔍 Linting`}}const sr={all:[`--fix-suggestions`,`--fix-dangerously`],dangerous:[`--fix-dangerously`],safe:[],suggested:[`--fix-suggestions`]};function cr(e){let t=et(e.cwd);return{...t,args:[...t.args,`--fix`,...sr[e.level],...e.files,...e.forwardedArguments],title:`🔧 Fixing lint issues`}}function lr(e){if(!e.computed)return e.key.type===`Identifier`?e.key.name:e.key.type===`Literal`&&F.isString(e.key.value)?e.key.value:void 0}function ur(e,t){let{file:n,content:r}=e,i=n.endsWith(`.json`),a=bt(i?`${n}.ts`:n,i?`(${r})`:r,{preserveParens:!1,sourceType:`module`});if(a.errors.length>0)return;let o=/* @__PURE__ */ new Map,s=/* @__PURE__ */ new Map,c=new Map(t.filter(e=>e.from===n).map(e=>[e.specifier,e.file]));for(let e of a.program.body){let t=e.type===`ExportNamedDeclaration`?e.declaration:e;if(t?.type===`VariableDeclaration`&&t.kind===`const`){for(let r of t.declarations)if(r.id.type===`Identifier`&&r.init!==null){let t={expression:r.init,file:n,type:`value`};o.set(r.id.name,t),e.type===`ExportNamedDeclaration`&&s.set(r.id.name,t)}}if(e.type===`ImportDeclaration`&&e.importKind!==`type`){let t=c.get(e.source.value);if(t===void 0)continue;for(let n of e.specifiers)if(n.type===`ImportDefaultSpecifier`)o.set(n.local.name,{file:t,name:`default`,type:`export`});else if(n.type===`ImportSpecifier`&&n.importKind!==`type`){let e=n.imported.type===`Identifier`?n.imported.name:n.imported.value;o.set(n.local.name,{file:t,name:e,type:`export`})}}if(e.type===`ExportDefaultDeclaration`){let t=e.declaration;t.type!==`FunctionDeclaration`&&t.type!==`ClassDeclaration`&&t.type!==`TSInterfaceDeclaration`&&s.set(`default`,{expression:t,file:n,type:`value`})}else if(i&&e.type===`ExpressionStatement`)s.set(`default`,{expression:e.expression,file:n,type:`value`});else if(e.type===`ExportNamedDeclaration`)for(let t of e.specifiers){let r=t.exported.type===`Identifier`?t.exported.name:t.exported.value,i=e.source===null?void 0:c.get(e.source.value);i===void 0?t.local.type===`Identifier`&&s.set(r,{expression:t.local,file:n,type:`value`}):s.set(r,{file:i,name:t.local.type===`Identifier`?t.local.name:t.local.value,type:`export`})}}return{bindings:o,exports:s,file:n,program:a.program}}function dr(e,t){let n=e,r=/* @__PURE__ */ new Set;for(;n!==void 0;){let e=n.type===`value`?n.expression:n;if(r.has(e))return;if(r.add(e),n.type===`export`){n=t.get(n.file)?.exports.get(n.name);continue}let i=n.expression;if(i.type===`Identifier`)n=t.get(n.file)?.bindings.get(i.name);else if(i.type===`TSAsExpression`||i.type===`TSSatisfiesExpression`||i.type===`TSNonNullExpression`)n={...n,expression:i.expression};else return n}return n}function fr(e,t,n=/* @__PURE__ */ new Set){let r=e.expression;if(r.type!==`ObjectExpression`||n.has(r))return[];n.add(r);let i=r.properties.find(e=>e.type===`Property`&&lr(e)===`layers`);if(i?.type!==`Property`)return[];let a=dr({...e,expression:i.value},t);return a?.expression.type===`ObjectExpression`?a.expression.properties.flatMap(e=>{if(e.type!==`Property`)return[];let r=dr({...a,expression:e.value},t);return r===void 0?[]:r.expression.type===`ArrayExpression`?[r.file]:fr(r,t,n)}):[]}function pr(e){let t=/* @__PURE__ */ new Set;for(let n of e.values())new yt({ObjectExpression(r){for(let i of r.properties){if(i.type!==`Property`||lr(i)!==`adamantite/layers`)continue;let r=dr({expression:i.value,file:n.file,type:`value`},e);if(r?.expression.type===`ArrayExpression`)for(let n of r.expression.elements){if(n===null||n.type===`SpreadElement`)continue;let i=dr({...r,expression:n},e);if(i!==void 0)for(let n of fr(i,e))t.add(n)}}}}).visit(n.program);return[...t]}const mr=E.fn(`assessLayerMaps`)(function*(e){let t=yield*P.Path,n=/* @__PURE__ */ new Map;for(let t of e.customRules.sources){let r=ur(t,e.customRules.resolvedImports);r!==void 0&&n.set(r.file,r)}let r=pr(n);return r.length===0?[]:[{currentState:r.map(n=>`\`${t.relative(e.cwd,n)}\` uses arrays for layer declarations in \`adamantite/layers\`.`).join(`
|
|
9
|
+
`),goal:['Replace each layer\'s dependency array with an object containing `imports`. For example, `workspace: ["shared"]` becomes `workspace: { imports: ["shared"] }`, and `shared: []` becomes `shared: { imports: [] }`.',`Preserve every dependency and its transitive permissions, rule severity, root, override, entry, ignore, isolation, type-import setting, and resolution condition. Keep independent branches separate. Do not add permissions or exemptions to make the config pass.`,"Put an existing direct child map in its containing layer's `layers` property. Remove that child map's `root` and separate option object. Its folder name derives the child root. Keep the containing layer's `imports` as the parent's dependencies.","Move the child map's `entries`, `ignore`, `isolate`, `ignoreTypes`, and `conditions` beside its nested `layers`. Each setting applies only to that child map. Parent exemptions do not skip child checks, and settings do not inherit.",`Keep separate roots when nesting would require a new intermediate map or change a glob's matched scope. Declare each concrete scope once. A child root uses the parent's actual matched folder, not a concatenated glob.`,`Compare the allowed and forbidden imports before and after the edit. Keep the original config if a permission, scope, or setting cannot be preserved.`,"Run `adamantite check`, verify representative allowed and forbidden imports, then run `adamantite doctor` again."],id:`layers-map-migration`,integration:`oxlint`,reference:{content:`"adamantite/layers": ["error", {
|
|
10
|
+
root: "src",
|
|
11
|
+
layers: {
|
|
12
|
+
lib: {
|
|
13
|
+
imports: [],
|
|
14
|
+
layers: {
|
|
15
|
+
shared: { imports: [] },
|
|
16
|
+
workspace: { imports: ["shared"] },
|
|
17
|
+
},
|
|
18
|
+
},
|
|
19
|
+
terminal: { imports: ["lib"] },
|
|
20
|
+
},
|
|
21
|
+
}]`,language:`ts`},title:`Layer maps need explicit imports and nested declarations`}]}),hr=z.decodeUnknownOption(z.Struct({header:z.Struct({glibcVersionRuntime:z.optional(z.String)}),sharedObjects:z.Array(z.String)}));function gr(e,t){return[{currentState:e,goal:t,id:`unavailable-oxlint-runtime`,integration:`oxlint`,notes:["Verification: run `adamantite check --only lint` after the repair."],title:`Oxlint runtime unavailable`}]}const _r=E.fn(`assessOxlintRuntime`)(function*(e){let t=t=>e.packageJson.devDependencies?.[t]??e.packageJson.dependencies?.[t];return t(`oxlint`)?yield*E.gen(function*(){let n=yield*fe(e.cwd),{backend:r,binding:i}=n;if(t(`tsrs`)&&r instanceof Ge)return gr(`Oxlint cannot resolve the declared tsrs backend or its launcher.`,[`Install the target project's dependencies so that the tsrs-lint launcher is available.`]);for(let n of Ue)if(n.runtime instanceof Se&&t(n.name)){let t=yield*Ce(e.cwd,n.name);if(N.isNone(t))return yield*new ie({packageName:n.name,project:e.cwd})}if(i instanceof Fe&&!(r instanceof Te))return[];let a=yield*R.FileSystem,o=yield*P.Path,s=yield*Ne,c=`${j.platform}-${j.arch}`,l=`gnu`;if(j.platform===`linux`){let e=yield*C(`/usr/bin/ldd`),t=N.isNone(e)?hr(j.report.getReport()):N.none();l=(N.isSome(e)?e.value.includes(`musl`):N.isSome(t)&&!t.value.header.glibcVersionRuntime&&t.value.sharedObjects.some(e=>e.includes(`libc.musl-`)||e.includes(`ld-musl-`)))?`musl`:`gnu`}let u=c+({android:j.arch===`arm`?`-eabi`:``,linux:`-${l}${j.arch===`arm`?`eabihf`:``}`,win32:j.arch===`x64`&&(`shlib_suffix`in j.config.variables&&j.config.variables.shlib_suffix===`dll.a`||`node_target_type`in j.config.variables&&j.config.variables.node_target_type===`shared_library`)?`-gnu`:`-msvc`}[j.platform]??``);if(i instanceof Ve){let e=yield*xt.String(`NAPI_RS_NATIVE_LIBRARY_PATH`).pipe(xt.withDefault(``)),t=j.platform===`darwin`?[`darwin-universal`,u]:[u],r=[...e?[e]:t.flatMap(e=>[`./oxlint.${e}.node`,`@oxlint/binding-${e}`]),`./oxlint.wasi.cjs`,`@oxlint/binding-wasm32-wasi`],i=yield*E.findFirst(r,e=>E.gen(function*(){let t=yield*s.resolve(o.join(n.oxlint,`dist`),e);return N.isNone(t)||!(yield*a.exists(t.value))?!1:e!==`./oxlint.wasi.cjs`||(yield*a.exists(o.join(n.oxlint,`dist`,`oxlint.wasm32-wasi.wasm`)))||(yield*a.exists(o.join(n.oxlint,`dist`,`oxlint.wasm32-wasi.debug.wasm`)))}));if(N.isNone(i))return gr(`Oxlint cannot resolve its installed native binding.`,[`Install the target project's optional dependencies for this platform, or restore its local binding.`])}if(r instanceof Te){let t=yield*Ce(e.cwd,`tsrs`),n=yield*xt.String(`TSRS_BINARY`).pipe(xt.withDefault(``)),i=`${c}${j.platform===`linux`?`-${l}`:``}`,s=N.isSome(t)&&!n?yield*Ce(t.value,`@tsrs/${i}`):N.none(),u=n===``?N.isSome(s)?o.join(s.value,j.platform===`win32`?`tsrs.exe`:`tsrs`):void 0:n;if(!(yield*a.exists(r.launcher))||u===void 0||!(yield*a.exists(u)))return gr(`Oxlint cannot resolve the installed tsrs binary or its launcher.`,[`Install the target project's optional dependencies for this platform, or restore TSRS_BINARY.`])}return[]}).pipe(E.catchTags({EffectBuildMissing:e=>E.succeed(gr(e.message,["Run `adamantite update` to align Oxlint, tsrs, and @effect/tsgo with supported builds."])),EffectPlatformUnsupported:e=>E.succeed(gr(e.message,["Lint on a platform that `@effect/tsgo` has builds for, or remove `@effect/tsgo` and the effect preset."])),NativeRuntimeConflict:e=>E.succeed(gr(e.message,[`Install at most one Oxlint plugin that replaces each native part of the Oxlint runtime.`])),PackageNotInstalled:e=>E.succeed(t(e.packageName)?gr(e.message,[`Install the target project's dependencies, then run Doctor again.`]):[])})):[]}),vr=`oxlint.config.ts`,yr=`.oxlintrc.json`,br=[{path:vr,type:`config`},{path:yr,type:`legacy_config`}],xr={config:vr,legacyConfigs:[yr]},Sr=`1.91.0`,Cr={antislop:{currentState:"`oxlint.config.ts` imports the retired `adamantite/lint/antislop` preset.",goal:["Replace `adamantite/lint/antislop` with `adamantite/lint/strict`. If strict is already imported, remove the antislop import and its `extends` entry.","Keep `anti-slop/*` rule settings, rule severity, rule options, and all other project settings. The rule namespace stays the same.",'strict sets `anti-slop/no-chained-type-assertions`, `anti-slop/no-widen-then-assert`, and `anti-slop/require-safety-comment-for-type-assertion` in an override for test files, which takes priority over top-level `rules`. Move a project setting for these three rules into an `overrides` entry with `files: ["**/*.{test,spec}.{ts,tsx,mts,cts}", "**/__tests__/**"]`.',"The strict preset also bans type assertions outside tests, console calls other than `console.info`, task comments, and deep destructuring, and it requires a reason on each suppression. Follow those reports when updating the code.","Use `--preset strict` in init commands. Run `adamantite check`, then run `adamantite doctor` again."],id:`strict-preset-migration`,integration:`oxlint`,title:`The antislop rules now belong to strict`},"react-doctor":{currentState:"`oxlint.config.ts` imports the retired `adamantite/lint/react-doctor` preset.",goal:["Replace `adamantite/lint/react-doctor` with `adamantite/lint/react-strict`. If react-strict is already imported, use its existing binding and remove the old import.","Keep the `react` preset and exactly one `react-strict` entry in extends. Keep `oxlint-plugin-react-doctor` as a devDependency. Run `adamantite update` if the package is missing or off its managed version.","Preserve project settings, custom rules, rule severity, and rule options, including `react-doctor/*` overrides. The upstream rule namespace stays the same.",`The react-strict preset also reports state, effect, and memoization hooks outside hook modules. Follow those reports when updating feature code.`,"Run `adamantite check`, then run Doctor again."],id:`react-doctor-preset-migration`,integration:`oxlint`,title:`React Doctor rules now belong to react-strict`},shadcn:{currentState:"`oxlint.config.ts` imports the removed `adamantite/lint/shadcn` preset.",goal:["Replace `adamantite/lint/shadcn` with `adamantite/lint/tailwind` in `oxlint.config.ts`. Keep the local import name and its `extends` entry.","Keep the managed `@shadcn/lint` package, `shadcn/*` rule names, `settings.shadcn` keys, rule severity, rule options, and all other project settings.","Use `--preset tailwind` in init commands. Run `adamantite check`, then run `adamantite doctor` again."],id:`tailwind-preset-migration`,integration:`oxlint`,title:`The shadcn preset was renamed to tailwind`}},wr=e=>Ht(e,`oxlint`,xr);var J=W({assess:e=>E.gen(function*(){let{cwd:n,lintConfig:r,packageJson:i}=e,a=t(i),o=yield*mr(e);if(!y(a,`oxlint`))return o.length===0?{applicable:!1}:{applicable:!0,findings:o,packageActions:[],warnings:[]};let s=yield*wr(n),c=yield*_r(e),l=Wt(e,{name:`oxlint`,version:Sr},`the managed lint scripts`,`oxlint`),u=s.active instanceof It?r.pipe(N.map(e=>Pn(e)),N.getOrUndefined):void 0,d=Cn(),f=je.flatMap(e=>On(r,e)?[Cr[e]]:[]);return{applicable:!0,findings:[...l.findings,...c,...f,...o,...Gt(s,{configContent:d,configFile:vr,inspection:u,toolName:`oxlint`})],packageActions:l.packageActions,warnings:[...l.warnings,...s.warnings]}}),check:or,config:vr,create:(e,t=[])=>E.gen(function*(){let n=yield*P.Path,r=Cn(t);yield*S(n.join(e,vr),r)}),detect:wr,files:br,fix:cr,kind:`tooling`,name:`oxlint`,version:Sr});function Tr(e){return{args:[...e.fix?[`--fix`]:[],...e.forwardedArguments],command:`sherif`,cwd:e.cwd,stdin:`inherit`,title:`📦 Analyzing the monorepo`}}var Er={analyze:Tr,...qt({monorepoOnly:!0,name:`sherif`,purpose:"the managed `analyze` script in a monorepo",scripts:De(`sherif`),version:`1.13.0`})};const Dr=E.fn(`Toolchain.check`)(function*({allowWarnings:e=!1,cwd:t,files:n=[],forwardedArguments:r=[],only:i}){if(i===`format`&&e)return yield*new ze({reason:"`--allow-warnings` applies to the lint stage. Remove it or `--only format`."});let a=yield*Pt,o=i??`lint`,s={format:q.check({cwd:t,files:n,forwardedArguments:o===`format`?r:[]}),lint:J.check({allowWarnings:e,cwd:t,files:n,forwardedArguments:o===`lint`?r:[]})};yield*a.runAll(i===void 0?[s.format,s.lint]:[s[i]])}),Or=E.fn(`Toolchain.fix`)(function*({cwd:e,files:t=[],forwardedArguments:n=[],level:r=`safe`,only:i}){if(i===`format`&&r!==`safe`)return yield*new we({reason:"`--suggested`, `--dangerous`, and `--all` apply to the lint stage. Remove them or `--only format`."});let a=yield*Pt,o=O.dedupe(t),s=i??`lint`,c={format:q.fix({cwd:e,files:o,forwardedArguments:s===`format`?n:[]}),lint:J.fix({cwd:e,files:o,forwardedArguments:s===`lint`?n:[],level:r})};yield*a.runAll(i===void 0?[c.lint,c.format]:[c[i]])}),kr=E.fn(`Toolchain.analyze`)(function*({cwd:e,fix:t=!1,forwardedArguments:n=[],only:r,strict:i=!1}){let a=yield*Pt,o=yield*P.Path,s=r!==`unused`&&(yield*g(o.join(e,`package.json`)))&&(yield*Qe(e).pipe(E.catchTags({FailedToParseFile:()=>E.succeed(!1),InvalidPackageJson:()=>E.succeed(!1)})));if(r===`monorepo`){if(i)return yield*new xe({reason:"`--strict` applies to the unused stage. Remove it or `--only monorepo`."});if(!s)return yield*new xe({reason:"`--only monorepo` requires a monorepo. Run from the monorepo root, or use `--only unused` for a single-package project."})}let c=r??`unused`,l={monorepo:Er.analyze({cwd:e,fix:t,forwardedArguments:c===`monorepo`?n:[]}),unused:tr.analyze({cwd:e,fix:t,forwardedArguments:c===`unused`?n:[],strict:i})},u=r===void 0?[...s?[l.monorepo]:[],l.unused]:[l[r]];yield*(t?a.runUntilFailure(u):a.runAll(u)).pipe(E.mapError(e=>F.isTagged(e,`CliNotFound`)&&e.command===Er.name?new Ke({command:e.command,hint:"Run `adamantite update` to install it."}):e))}),Ar=M.Boolean(`fix`).pipe(M.withDefault(!1),M.withDescription(`Apply fixes in each selected stage`)),jr=M.Boolean(`strict`).pipe(M.withDefault(!1),M.withDescription(`Enable Knip's strict mode when checking unused code`)),Mr=M.Literals(`only`,[`monorepo`,`unused`]).pipe(M.optional,M.withDescription(`Run only monorepo (Sherif) or unused (Knip). Pass tool arguments after --`));var Nr=k.make(`analyze`,{fix:Ar,only:Mr,strict:jr}).pipe(k.withDescription(`Check monorepo consistency with Sherif and find unused code with Knip`),k.withExamples([{command:`adamantite analyze -- --directory packages/app`,description:`Run Knip from a specific directory`},{command:`adamantite analyze --only monorepo --fix -- --select highest`,description:`Fix monorepo issues and use the highest version when versions differ`}]),k.withHandler(({fix:e,only:t,strict:n})=>E.gen(function*(){yield*kr({cwd:j.cwd(),fix:e,forwardedArguments:yield*At,only:N.getOrUndefined(t),strict:n})})));const Pr=V.File(`files`,{mustExist:!0}).pipe(V.withDescription(`Files to check. Omit to check the project`),V.variadic()),Fr=M.Literals(`only`,[`format`,`lint`]).pipe(M.optional,M.withDescription(`Run only format (Oxfmt) or lint (Oxlint). Pass tool arguments after --`)),Ir=M.Boolean(`allow-warnings`).pipe(M.withDefault(!1),M.withDescription(`Allow the lint check to pass when Oxlint reports only warnings`));var Lr=k.make(`check`,{allowWarnings:Ir,files:Pr,only:Fr}).pipe(k.withDescription(`Check formatting, lint issues, and TypeScript types`),k.withHandler(({allowWarnings:e,files:t,only:n})=>E.gen(function*(){yield*Dr({allowWarnings:e,cwd:j.cwd(),files:t,forwardedArguments:yield*At,only:N.getOrUndefined(n)})})));function Rr(e,t){return e.replaceAll(/\{\{(\w+)\}\}/g,(e,n)=>Object.hasOwn(t,n)?t[n]??e:e)}function zr(e,t){return i.flatMap(n=>t.includes(n)?[{command:wt(e,n),name:n}]:[])}function Br(){return i.reduce((e,t)=>e.flatMap(e=>[e,[...e,t]]),[[]]).filter(e=>e.length>0)}function Vr(e){return i.some(t=>e.includes(t))}var Hr=class extends ct.Service()(`DependencyInstaller`){static layer=A.succeed(this)({addDevDependencies:E.fn(`DependencyInstaller.addDevDependencies`)((e,t,n)=>E.tryPromise({catch:t=>new Le({cause:t,packages:e}),try:()=>St(e,{...n,cwd:t})}).pipe(E.asVoid)),detectPackageManager:E.fn(`DependencyInstaller.detectPackageManager`)(e=>E.tryPromise({catch:e=>new me({cause:e}),try:()=>Ct(e)}).pipe(E.map(e=>e??null)))})};function Ur(e,t){return t&&e!==`npm`}const Wr=(e,t)=>E.gen(function*(){let n=yield*Hr,r=yield*Ne,[i,a]=yield*E.all([Qe(e),n.detectPackageManager(e)],{concurrency:`unbounded`});yield*n.addDevDependencies(t,e,{silent:!0,workspace:Ur(a?.name,i)}).pipe(E.ensuring(r.clearCache))});var Gr=class extends I.TaggedClass(`File`){},Kr=class extends I.TaggedClass(`Version`){};const qr=[`.node-version`,`.nvmrc`],Jr=z.Struct({volta:z.Struct({node:z.NonEmptyString})}),Yr=z.Struct({engines:z.Struct({node:z.NonEmptyString})}),Xr=z.Struct({name:z.NonEmptyString,version:z.NonEmptyString});function Zr(e){return e.split(`
|
|
22
|
+
`).map(e=>e.split(`#`)[0]?.trim()??``).some(e=>/^node(?:js)?\s+\S/.test(e))}function Qr(e){return z.is(Xr)(e)&&e.name.toLowerCase()===`node`}function $r(e){if(z.is(Jr)(e))return!0;if(F.isObject(e)&&F.isObject(e.devEngines)){let t=e.devEngines.runtime;if((Array.isArray(t)?t:[t]).some(e=>Qr(e)))return!0}return z.is(Yr)(e)}const ei=[...qr.map(e=>new Gr({path:e})),new Gr({path:`.tool-versions`}),new Gr({path:`package.json`}),new Kr({value:`lts/*`})];var ti=class extends ct.Service()(`NodeVersionResolver`){static layer=A.effect(this,E.gen(function*(){let e=yield*R.FileSystem,t=yield*P.Path,n=(n,r)=>C(t.join(n,r)).pipe(E.provideService(R.FileSystem,e));return{resolve:E.fn(`NodeVersionResolver.resolve`)(function*(e){for(let t of qr){let r=yield*n(e,t);if(N.exists(r,e=>pt.isNonEmpty(e.trim())))return new Gr({path:t})}let r=yield*n(e,`.tool-versions`);if(N.exists(r,e=>Zr(e)))return new Gr({path:`.tool-versions`});let i=yield*n(e,`package.json`);return N.isSome(i)&&$r(yield*w(i.value,t.join(e,`package.json`)))?new Gr({path:`package.json`}):new Kr({value:`lts/*`})})}}))};function ni(e){return c.map(t=>{let[n,r]=wt(t,`script`).split(` `);return`${n}(?:\\s+(?!${r}\\b)\\S+)*\\s+${r}\\s+${e}`}).join(`|`)}const ri=new RegExp(String.raw`\b(?:${ni(`check`)})\b`),ii=z.Struct({jobs:z.Record(z.String,z.Struct({steps:z.optionalKey(z.Array(z.Struct({run:z.optionalKey(z.String),with:z.optionalKey(z.Struct({"node-version":z.optionalKey(z.Union([z.String,z.Finite]))}))}))),strategy:z.optionalKey(z.Struct({matrix:z.optionalKey(z.Unknown)}))}))}),ai=z.Struct({include:z.Array(z.Struct({command:z.optionalKey(z.String)}))}),oi=(e,t)=>E.try({catch:e=>new Me({cause:e,path:t}),try:()=>ht.parse(e)}).pipe(E.flatMap(e=>z.decodeUnknownEffect(ii)(e)),E.map(({jobs:e})=>{let t=Object.values(e),n=t.flatMap(e=>e.steps??[]),r=t.flatMap(e=>N.match(z.decodeUnknownOption(ai)(e.strategy?.matrix),{onNone:()=>[],onSome:({include:e})=>e.flatMap(e=>e.command??[])}));return{commands:[...n.flatMap(e=>e.run??[]),...r],nodeVersions:n.flatMap(e=>e.with?.[`node-version`]??[])}}),E.orElseSucceed(()=>({commands:[],nodeVersions:[]})));function si(e){return` - name: Setup Node.js
|
|
16
23
|
uses: actions/setup-node@v7
|
|
17
24
|
with:
|
|
18
|
-
${e
|
|
25
|
+
${e instanceof Gr?`node-version-file: "${e.path}"`:`node-version: "${e.value}"`}`}function ci(e){return{bun:`${si(e)}
|
|
19
26
|
|
|
20
27
|
- name: Setup Bun
|
|
21
28
|
uses: oven-sh/setup-bun@v2
|
|
@@ -35,22 +42,22 @@ import*as e from"@effect/platform-node/NodeRuntime";import*as t from"effect/Effe
|
|
|
35
42
|
uses: denoland/setup-deno@v2
|
|
36
43
|
|
|
37
44
|
- name: Install dependencies
|
|
38
|
-
run: deno install --frozen`,npm:`${
|
|
45
|
+
run: deno install --frozen`,npm:`${si(e)}
|
|
39
46
|
cache: "npm"
|
|
40
47
|
|
|
41
48
|
- name: Install dependencies
|
|
42
49
|
run: npm ci`,pnpm:` - name: Setup pnpm
|
|
43
50
|
uses: pnpm/action-setup@v6
|
|
44
51
|
|
|
45
|
-
${
|
|
52
|
+
${si(e)}
|
|
46
53
|
cache: "pnpm"
|
|
47
54
|
|
|
48
55
|
- name: Install dependencies
|
|
49
|
-
run: pnpm install --frozen-lockfile`,yarn:`${
|
|
56
|
+
run: pnpm install --frozen-lockfile`,yarn:`${si(e)}
|
|
50
57
|
cache: "yarn"
|
|
51
58
|
|
|
52
59
|
- name: Install dependencies
|
|
53
|
-
run: yarn install --frozen-lockfile`}}function
|
|
60
|
+
run: yarn install --frozen-lockfile`}}function li({packageManager:e,scripts:t},n){let r=zr(e,t);return r.length===0?null:Rr(`name: adamantite
|
|
54
61
|
|
|
55
62
|
on:
|
|
56
63
|
push:
|
|
@@ -75,61 +82,635 @@ jobs:
|
|
|
75
82
|
fail-fast: false
|
|
76
83
|
matrix:
|
|
77
84
|
include:
|
|
78
|
-
|
|
79
|
-
`)}
|
|
85
|
+
{{matrix}}
|
|
80
86
|
|
|
81
87
|
steps:
|
|
82
88
|
- name: Checkout
|
|
83
89
|
uses: actions/checkout@v7
|
|
84
90
|
|
|
85
|
-
|
|
91
|
+
{{setup}}
|
|
86
92
|
|
|
87
93
|
- name: Run \${{ matrix.name }}
|
|
88
|
-
run: \${{ matrix.command }}
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
meta: {
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
schema: [],
|
|
96
|
-
type: "problem",
|
|
97
|
-
},
|
|
98
|
-
createOnce(context) {
|
|
99
|
-
return {
|
|
100
|
-
// Run \`adamantite rule ast <file>\` to find the node types to visit.
|
|
101
|
-
DebuggerStatement(node) {
|
|
102
|
-
context.report({ messageId: "unexpected", node })
|
|
103
|
-
},
|
|
104
|
-
}
|
|
105
|
-
},
|
|
106
|
-
})
|
|
107
|
-
`}const Rr=t.fn(`addCustomRule`)(function*(e,n,r=Fr){if(!Ir.test(n))return yield*new Fe({rule:n});let i=yield*C.FileSystem,a=yield*w.Path,o=a.resolve(e,r),s=a.join(o,`${n}.ts`),c=a.join(o,`AGENTS.md`),l=e=>i.exists(e).pipe(t.mapError(t=>new Ae({cause:t,path:e})));return(yield*l(s))?yield*new Ce({path:s}):(yield*We(o),yield*F(s,Lr(n)),(yield*l(c))?{agentsPath:void 0,rulePath:s}:(yield*F(c,'# Custom rules\n\nEach file in the rules folder, `.adamantite/rules/` by default, is an Oxlint rule that this\nproject owns. `custom()` from `adamantite/lint/custom` loads the folder and enables each\nrule as `error` under the `project` plugin: `no-process-env.ts` becomes\n`project/no-process-env`. Add a file to add a rule. Delete the file to remove the rule.\n`adamantite rule add <name>` writes a correct stub.\n\n- A file that starts with `_`, such as `_helpers.ts`, is a helper, not a rule. Subfolders are\n not read.\n- Export the rule as default with `defineRule` from `adamantite/rules`. The same module exports\n the `Context`, `Rule`, `Visitor`, and `ESTree` node types.\n- Use `createOnce`. It runs one time for each lint run, not one time for each file. Reset\n per-file state in `before`, and report collected results in `after`. `context.filename`,\n `context.sourceCode`, and `context.settings` are not available in the body of\n `createOnce`. Read them in `before` or in a visitor.\n- Write erasable TypeScript only. Oxlint loads rule files with Node.js type stripping, so\n `enum`, a `namespace` with values, parameter properties, and `import x = require()` stop\n the lint run.\n- Rules get no type information. Use only the AST and `context.sourceCode`.\n- Report with a `messageId`, and put each message in `meta.messages`. Describe the options in\n `meta.schema`, and read them from `context.options`.\n- A rule that throws prints an error for each file, and the lint run still exits 0. After you\n change a rule, run the lint and read all of its output.\n- To find node names, run `adamantite rule ast <file>` on real code. It prints the same\n ESTree-shaped AST that rules visit.\n- To test a rule, use `RuleTester` from `oxlint/plugins-dev`. Adamantite does not run rule\n tests.\n- Oxlint caches the rules for each run. Restart the editor language server after you change a\n rule.\n- TypeScript does not check `.adamantite/rules/` by default, because its name starts with a dot. Add\n `".adamantite/rules"` to `include` in `tsconfig.json` to check it.\n- In a monorepo, give each rules folder its own plugin name, such as `custom({ name: "web" })`:\n Oxlint rejects two plugins with the same name in one run. A relative `dir` resolves from the\n file that calls `custom()`, so a shared tooling package can own the rules with\n `custom({ dir: "rules", name: "acme" })`. A nested Oxlint config replaces the root config, so\n a package that needs the root rules extends the root config.\n'),{agentsPath:c,rulePath:s}))}),zr=`custom-rules`,Br=[`oxlint.config.ts`,`oxlint.config.mts`,`oxlint.config.js`,`oxlint.config.mjs`],Vr=[`.ts`,`.mts`,`.cts`,`.js`,`.mjs`,`.cjs`],Hr=/* @__PURE__ */ new Set([`default`,`import`,`node`]);function Ur(e){if(e!=null)return x.isString(e)?e:s.isArray(e)?e.map(e=>Ur(e)).find(e=>e!==void 0):Object.entries(e).filter(([e])=>Hr.has(e)).map(([,e])=>Ur(e)).find(e=>e!==void 0)}const Wr=D.combine(D.mapInput(D.flip(D.Number),([e])=>e.indexOf(`*`)),D.mapInput(D.flip(D.Number),([e])=>e.length));function Gr(e,t){let{exports:n}=e;if(n===void 0)return t===``?e.main??`index`:t;let r=t===``?`.`:`./${t}`;if(n===null||x.isString(n)||s.isArray(n))return r===`.`?Ur(n):void 0;let i=Object.keys(n).some(e=>e.startsWith(`.`))?n:{".":n};if(r in i)return Ur(i[r]);let a=s.sort(Object.entries(i),Wr).map(([e,t])=>{let[n,i,...a]=e.split(`*`);return n!==void 0&&i!==void 0&&a.length===0&&r.startsWith(n)&&r.endsWith(i)&&r.length>n.length+i.length?{match:r.slice(n.length,r.length-i.length),target:t}:null}).find(e=>e!==null);return a===void 0?void 0:Ur(a.target)?.replaceAll(`*`,a.match)}const Kr=t.fn(`readWorkspacePackage`)(function*(e){let t=yield*R(e);return t.name===void 0?d.none():d.some({directory:e,exports:t.exports,main:t.main,name:t.name})}),qr=t.fn(`readFirstFile`)(function*(e){for(let n of e){let e=yield*P(n).pipe(t.orElseSucceed(()=>d.none()));if(d.isSome(e))return d.some({content:e.value,file:n})}return d.none()}),Jr=t.fn(`resolveImport`)(function*(e,t,n){let r=yield*w.Path,i;if(t.startsWith(`.`)||r.isAbsolute(t))i=r.resolve(r.dirname(e),t);else{let e=n.find(e=>t===e.name||t.startsWith(`${e.name}/`));if(e===void 0)return{_tag:`external`};let a=Gr(e,t.slice(e.name.length+1));if(a===void 0)return{_tag:`unresolved`};i=r.resolve(e.directory,a)}if(i.split(r.sep).includes(`node_modules`))return{_tag:`external`};let a=i,o=i.replace(/\.[cm]?js$/u,``),s=yield*qr([i,...Vr.map(e=>`${o}${e}`),...Vr.map(e=>r.join(a,`index${e}`))]);return d.match(s,{onNone:()=>({_tag:`unresolved`}),onSome:e=>({_tag:`found`,module:e})})}),Yr=t.fn(`findCustomRulesCalls`)(function*(e){let n=yield*w.Path,r=s.getSomes(yield*t.forEach(e,e=>Kr(e),{concurrency:`unbounded`})),i=s.getSomes(yield*t.forEach(e,e=>qr(Br.map(t=>n.join(e,t))),{concurrency:`unbounded`})),a=/* @__PURE__ */ new Set,o=[],c=[],l=i;for(;l.length>0;){let e=l.filter(e=>!a.has(e.file));for(let t of e)a.add(t.file),t.content.includes(`adamantite/lint/custom`)&&o.push(...Or(t.file,t.content).map(e=>({dir:e.dir===null?null:n.resolve(n.dirname(t.file),e.dir),name:e.name,source:t.file})));let i=e.flatMap(e=>Nr(e.file,e.content).map(t=>({from:e.file,specifier:t}))),s=yield*t.forEach(i,({from:e,specifier:t})=>Jr(e,t,r),{concurrency:`unbounded`});l=[];for(let[e,t]of s.entries()){let n=i[e];t._tag===`found`?l.push(t.module):t._tag===`unresolved`&&n!==void 0&&c.push(n)}}return{calls:o,unresolvedImports:c}}),Xr=t.fn(`readRulesFolder`)(function*(e){return(yield*Ge(e)).pipe(d.map(t=>({dir:e,ruleFiles:t.filter(e=>Sr(e))})))});var Zr=M({assess:e=>t.gen(function*(){let n=yield*w.Path,r=t=>n.relative(e,t)||`.`,i=[e,...(yield*B(e))?yield*St(e):[]],{calls:a,unresolvedImports:o}=yield*Yr(i),c=i.map(e=>n.join(e,Fr)),l=s.dedupe(a.flatMap(e=>e.dir===null?[]:[e.dir])),u=s.getSomes(yield*t.forEach(s.dedupe([...c,...l]),e=>Xr(e),{concurrency:`unbounded`})).filter(e=>e.ruleFiles.length>0);if(a.length===0&&u.length===0&&o.length===0)return{applicable:!1,warnings:[]};let d=a.filter(e=>e.dir===null||e.name===null),f=[...o.map(({from:e,specifier:t})=>`Doctor cannot resolve the import of \`${t}\` in \`${r(e)}\`, so it does not check the \`custom()\` calls and rules folders behind it.`),...d.map(e=>`Doctor cannot read the \`dir\` or \`name\` of a \`custom()\` call in \`${r(e.source)}\`, because it is not a string literal. Doctor does not check that rules folder.`)],p=[];if(d.length===0&&o.length===0)for(let e of u)l.includes(e.dir)||p.push({currentState:`\`${r(e.dir)}\` has ${e.ruleFiles.length} rule file(s), but no \`custom()\` call loads it, so Oxlint does not run them.`,goal:[`Load \`${r(e.dir)}\` with \`custom()\` from \`adamantite/lint/custom\` in the Oxlint config of \`${r(n.dirname(n.dirname(e.dir)))}\`. A relative \`dir\` resolves from the file that calls \`custom()\`.`,"Give each rules folder its own plugin name with the `name` option, because Oxlint rejects two plugins with the same name in one run.",`Preserve every other setting in the Oxlint config.`],id:`custom-rules-not-loaded:${r(e.dir)}`,integration:zr,reference:{content:`import { defineConfig } from "oxlint"
|
|
108
|
-
import core from "adamantite/lint"
|
|
109
|
-
import custom from "adamantite/lint/custom"
|
|
94
|
+
run: \${{ matrix.command }}
|
|
95
|
+
`,{matrix:r.map(e=>` - name: ${e.name}\n command: ${e.command}`).join(`
|
|
96
|
+
`),setup:ci(n)[e]})}function ui(e){return e.replaceAll(`\r
|
|
97
|
+
`,`
|
|
98
|
+
`).trimEnd()}function di(e){let t=ui(e);return ei.some(e=>_t.keys(ci(e)).some(n=>Br().some(r=>ui(li({packageManager:n,scripts:r},e)??``)===t)))}const fi=[{path:`.github/workflows/adamantite.yml`,type:`ci`}],pi=(e,t)=>E.gen(function*(){let n=yield*P.Path,r=yield*ti,i=n.join(e,fi[0].path),a=li(t,yield*r.resolve(e));a&&(yield*S(i,a))});var mi=W({assess:({cwd:e,packageJson:n})=>E.gen(function*(){let r=(yield*P.Path).join(e,fi[0].path),i=yield*C(r);if(N.isNone(i))return{applicable:!1};let a=t(n),s=yield*oi(i.value,r),c=s.nodeVersions.some(e=>/^\d/.test(String(e))),l=a.includes(`check`)&&!s.commands.some(e=>ri.test(e));if(!c&&!l)return{applicable:!0,findings:[],packageActions:[],warnings:[]};if(!Vr(a))return{applicable:!0,findings:[],packageActions:[],warnings:[`No CI-compatible managed scripts were found, so the GitHub Actions workflow cannot be regenerated.`]};let u=yield*(yield*Hr).detectPackageManager(e);return u?o(u.name)?{applicable:!0,findings:[{currentState:[...c?[`The workflow contains a hard-coded Node.js version.`]:[],...l?["The workflow does not run the managed `check` script."]:[]].join(` `),goal:[...a.includes(`check`)?["Make the workflow run the managed `check` script."]:[],`Use the project's Node.js version declaration instead of a hard-coded version.`],id:`outdated-adamantite-workflow`,integration:`github`,notes:[`The detected package manager is \`${u.name}\`. Preserve unrelated workflow jobs and project-specific settings.`],title:`Outdated Adamantite workflow`}],packageActions:[],warnings:[]}:{applicable:!0,findings:[],packageActions:[],warnings:[`\`${u.name}\` is not a supported package manager for CI workflow generation, so the GitHub Actions workflow cannot be regenerated.`]}:{applicable:!0,findings:[],packageActions:[],warnings:[`Could not detect a package manager, so the GitHub Actions workflow cannot be regenerated.`]}}),create:(e,t)=>E.gen(function*(){let n=yield*P.Path;yield*x(n.dirname(n.join(e,fi[0].path))),yield*pi(e,t)}),detect:e=>E.gen(function*(){let t=yield*R.FileSystem,n=yield*P.Path;return yield*t.exists(n.join(e,fi[0].path))}),files:fi,kind:`ci`,name:`github`,update:(e,t)=>E.gen(function*(){let n=yield*P.Path,r=yield*C(n.join(e,fi[0].path));return N.isSome(r)&&!di(r.value)?`kept`:(yield*pi(e,t),`updated`)})});const Y={agents:`agents`,editor:`editor`,nonInteractive:`non-interactive`,preset:`preset`,script:`script`};function hi({agents:e=!1,editors:t=[],presets:n=[],scripts:r}){return[`adamantite init`,`--${Y.nonInteractive}`,...r.map(e=>`--${Y.script} ${e}`),...n.map(e=>`--${Y.preset} ${e}`),...t.map(e=>`--${Y.editor} ${e}`),...e?[`--${Y.agents}`]:[]].join(` `)}const gi=hi({editors:[`vscode`],scripts:[`check`]}),_i=`node_modules/.cache/adamantite/effect`,vi=`adamantite-sdk.json`,yi=z.Struct({gitHead:z.NonEmptyString,version:z.NonEmptyString}),bi=E.fn(`findNativeTypescript`)(function*(e){for(let t of[`typescript`,`@typescript/native`]){let n=yield*Ce(e,t);if(N.isSome(n)){let e=yield*u(n.value);if(Number(e.version?.split(`.`)[0])>=7)return z.decodeUnknownOption(yi)(e)}}return N.none()}),xi=E.fn(`resolveSdkSource`)(function*(e,t,n){let i=yield*P.Path,a=yield*R.FileSystem,o=yield*bi(e);if(N.isNone(o))return yield*new pe({reason:`The Effect editor SDK needs an installed native TypeScript package with its gitHead. Install TypeScript 7 or later, then run \`${gi}\`.`});let{gitHead:s,version:c}=o.value,l=`${j.platform}-${j.arch}`,u=yield*Ce(t,`@effect/tsgo-${l}`);if(N.isNone(u))return yield*new pe({reason:`The Effect editor SDK cannot find \`@effect/tsgo-${l}\`. Install the optional dependencies on a supported platform.`});let d=i.join(u.value,`lib`,`upstream.json`),f=yield*w(yield*r(d),d),p=h(f)&&f.components,m=h(p)&&p.typescript,g=h(f)&&f.tags,_=h(g)&&g.typescript;if(!h(f)||f.schemaVersion!==5||!h(m)||!h(_))return yield*new Pe({path:d});let v=j.platform===`win32`?`tsc.exe`:`tsc`;for(let[e,t]of Object.entries(m)){if(!h(t)||t.gitHead!==s)continue;let r=e===_.latest?i.join(u.value,`lib`):i.join(u.value,`artifacts`,`typescript`,e);if((yield*a.exists(i.join(r,v)))&&(yield*a.exists(i.join(r,`lib.d.ts`))))return{effectVersion:n,executable:v,gitHead:s,platform:l,source:r,typescriptVersion:c}}return yield*new pe({reason:`@effect/tsgo ${n} has no editor compiler matching TypeScript ${c} (${s}). Install a supported TypeScript version, then run \`${gi}\`.`})}),Si=E.fn(`sdkIsCurrent`)(function*(e,t){let n=yield*P.Path,r=yield*R.FileSystem,i=n.join(e,_i),a=n.join(i,vi),o=yield*C(a);if(N.isNone(o))return!1;let s=yield*w(o.value,a).pipe(E.catchTag(`FailedToParseFile`,()=>E.succeed(null)));if(!h(s)||!Object.entries(t).every(([e,t])=>s[e]===t))return!1;let c=yield*r.readDirectory(t.source);return(yield*E.forEach(c.filter(e=>e===t.executable||e.endsWith(`.d.ts`)),e=>r.exists(n.join(i,e)))).every(Boolean)}),Ci=E.fn(`readEffectEditor`)(function*(e){let t=yield*Ce(e,`@effect/tsgo`);if(N.isNone(t))return N.none();let n=yield*P.Path,i=yield*u(t.value),a=n.join(t.value,`oxlint-schema.json`),o=yield*w(yield*r(a),a),s=h(o)&&o.definitions,c=h(s)&&s.DummyRuleMap,l=h(c)&&c.properties;if(!h(l))return yield*new Pe({path:a});let d=Object.fromEntries(Object.keys(l).filter(e=>e.startsWith(`effecttsgo/`)).map(e=>[e,{severity:`off`}])),f=xi(e,t.value,i.version??`unknown`);return N.some({prepareSdk:E.gen(function*(){let t=yield*f;if(yield*Si(e,t))return;let r=yield*R.FileSystem,i=n.join(e,_i);yield*r.remove(i,{force:!0,recursive:!0}),yield*r.makeDirectory(n.dirname(i),{recursive:!0}),yield*r.copy(t.source,i),yield*se(n.join(i,vi),t)}),rulesCustomization:d,sdkIsCurrent:f.pipe(E.flatMap(t=>Si(e,t)))})}),X=[{path:`.vscode/settings.json`,type:`config`}],wi={"[css]":{"editor.defaultFormatter":`oxc.oxc-vscode`},"[graphql]":{"editor.defaultFormatter":`oxc.oxc-vscode`},"[javascript]":{"editor.defaultFormatter":`oxc.oxc-vscode`},"[javascriptreact]":{"editor.defaultFormatter":`oxc.oxc-vscode`},"[json]":{"editor.defaultFormatter":`oxc.oxc-vscode`},"[jsonc]":{"editor.defaultFormatter":`oxc.oxc-vscode`},"[typescript]":{"editor.defaultFormatter":`oxc.oxc-vscode`},"[typescriptreact]":{"editor.defaultFormatter":`oxc.oxc-vscode`},"editor.codeActionsOnSave":{"source.fixAll.oxc":`explicit`},"editor.defaultFormatter":`oxc.oxc-vscode`,"editor.formatOnPaste":!0,"editor.formatOnSave":!0,"oxc.path.oxlint":ue,"oxc.typeAware":!0};var Ti=W({assess:({cwd:e})=>E.gen(function*(){let t=(yield*P.Path).join(e,X[0].path),n=yield*C(t);if(N.isNone(n))return{applicable:!1};let r=yield*w(n.value,t);if(!h(r))return yield*new Pe({path:t});let i=r[`oxc.path.oxlint`],a=wi[`oxc.path.oxlint`],o=i===a?[]:[{currentState:`\`${X[0].path}\` sets \`oxc.path.oxlint\` to ${i===void 0?`no value`:`\`${yield*ce(i)}\``}. VS Code does not start Oxlint through Adamantite's Oxlint entry.`,goal:[`Set \`oxc.path.oxlint\` to \`${a}\` in \`${X[0].path}\`. Preserve every other setting.`],id:`vscode-oxlint-entry`,integration:`vscode`,reference:{content:`${yield*Be({"oxc.path.oxlint":a})}\n`,language:`json`},title:`VS Code does not use the Oxlint entry`}],s=yield*Ci(e);if(N.isSome(s)){let e=r[`oxc.lint.customization`],t=h(e)&&Object.keys(s.value.rulesCustomization).every(t=>{let n=e[t];return h(n)&&n.severity===`off`});(r[`js/ts.tsdk.path`]!==`node_modules/.cache/adamantite/effect`||!t)&&o.push({currentState:`\`${X[0].path}\` does not select the Effect editor SDK with duplicate Oxlint Effect reports hidden.`,goal:[`Set \`js/ts.tsdk.path\` to \`${_i}\` and merge the reference \`oxc.lint.customization\` entries. Preserve other settings and rule customizations.`],id:`vscode-effect-server`,integration:`vscode`,reference:{content:`${yield*Be({"js/ts.tsdk.path":_i,"oxc.lint.customization":s.value.rulesCustomization})}\n`,language:`json`},title:`VS Code does not use the Effect language server`});let n=yield*s.value.sdkIsCurrent.pipe(E.map(e=>e?void 0:`\`${_i}\` is missing or does not match the installed Effect compiler.`),E.catchTag(`EffectEditorUnavailable`,e=>E.succeed(e.message)));n!==void 0&&o.push({currentState:n,goal:[`Install a supported native TypeScript version and the Effect optional dependencies. Run \`${hi({editors:[`vscode`],scripts:[`check`]})}\` to prepare the SDK cache, then restart the TypeScript server.`],id:`vscode-effect-sdk`,integration:`vscode`,title:`The Effect editor SDK needs preparation`})}return{applicable:!0,findings:o,packageActions:[],warnings:[]}}),config:X[0].path,create:e=>E.gen(function*(){let t=yield*P.Path,n=t.join(e,X[0].path),r=yield*Ci(e),i=N.isSome(r)?{...wi,"js/ts.tsdk.path":_i,"oxc.lint.customization":r.value.rulesCustomization}:wi;N.isSome(r)&&(yield*r.value.prepareSdk),yield*x(t.dirname(n)),yield*se(n,i)}),detect:e=>E.gen(function*(){let t=yield*R.FileSystem,n=yield*P.Path;return yield*t.exists(n.join(e,X[0].path))}),extension:(e=[],t=[])=>E.gen(function*(){let n=[];y(e,`oxlint`)&&n.push(`oxc.oxc-vscode`),y(e,`knip`)&&n.push(`webpro.vscode-knip`),t.includes(`effect`)&&n.push(`TypeScriptTeam.native-preview`);for(let e of n)yield*(yield*Pt).run({args:[`--install-extension`,e],command:`code`}).pipe(E.mapError(t=>F.isTagged(t,`CliNotFound`)&&t.command===`code`?new v({cause:t}):new We({cause:F.isTagged(t,`CommandFailed`)?t.exitCode:t,extension:e})))}),files:X,kind:`editor`,name:`vscode`,update:e=>E.gen(function*(){let t=(yield*P.Path).join(e,X[0].path),n=yield*r(t),i=yield*w(n,t);if(!F.isObject(i))return yield*new Pe({path:t});let a=yield*Ci(e),o=yield*m({fallback:wi,preferred:i}),s=N.isSome(a)?[[`js/ts.tsdk.path`,_i],[`oxc.lint.customization`,yield*m({fallback:h(i[`oxc.lint.customization`])?i[`oxc.lint.customization`]:{},preferred:a.value.rulesCustomization})]]:[];N.isSome(a)&&(yield*a.value.prepareSdk);let c=Object.fromEntries([...Object.entries(o),[`oxc.path.oxlint`,wi[`oxc.path.oxlint`]],...s]);yield*S(t,le(n,c))})});const Z=[{path:`.zed/settings.json`,type:`config`}],Ei={languages:{Astro:{format_on_save:`on`,prettier:{allowed:!0,plugins:[`prettier-plugin-astro`]}},CSS:{format_on_save:`on`,formatter:[{language_server:{name:`oxfmt`}}],prettier:{allowed:!1}},HTML:{format_on_save:`on`,formatter:[{language_server:{name:`oxfmt`}}],prettier:{allowed:!1}},JSON:{format_on_save:`on`,formatter:[{language_server:{name:`oxfmt`}}],prettier:{allowed:!1}},JSONC:{format_on_save:`on`,formatter:[{language_server:{name:`oxfmt`}}],prettier:{allowed:!1}},JavaScript:{format_on_save:`on`,formatter:[{language_server:{name:`oxfmt`}},{code_action:`source.fixAll.oxc`}],prettier:{allowed:!1}},MDX:{format_on_save:`on`,formatter:[{language_server:{name:`oxfmt`}}],prettier:{allowed:!1}},Markdown:{format_on_save:`on`,formatter:[{language_server:{name:`oxfmt`}}],prettier:{allowed:!1}},TSX:{format_on_save:`on`,formatter:[{language_server:{name:`oxfmt`}},{code_action:`source.fixAll.oxc`}],prettier:{allowed:!1}},TypeScript:{format_on_save:`on`,formatter:[{language_server:{name:`oxfmt`}},{code_action:`source.fixAll.oxc`}],prettier:{allowed:!1}},YAML:{format_on_save:`on`,formatter:[{language_server:{name:`oxfmt`}}],prettier:{allowed:!1}}},lsp:{oxfmt:{initialization_options:{settings:{"fmt.configPath":null,run:`onSave`}}},oxlint:{binary:{arguments:[ue,`--lsp`],path:`node`},initialization_options:{settings:{configPath:null,fixKind:`safe_fix`,run:`onType`,typeAware:!0,unusedDisableDirectives:`deny`}}}}},Di={configPath:null,"fmt.experimental":!0,typeAware:!1,unusedDisableDirectives:!1},Oi=/* @__PURE__ */ new Set([`typescript-ls`,`tsgo`,`vtsls`,`typescript-language-server`]),ki=E.fn(`resolveEffectCli`)(function*(e){let t=yield*R.FileSystem,n=yield*P.Path,r=n.resolve(e);for(;;){let i=n.join(r,`node_modules`,`@effect`,`tsgo`);if(yield*t.exists(n.join(i,`package.json`)))return n.relative(e,n.join(i,`dist`,`effect-tsgo.cjs`)).replaceAll(`\\`,`/`);let a=n.dirname(r);if(a===r)return yield*new pe({reason:`Zed cannot find the installed Effect CLI in node_modules. Install @effect/tsgo, then run \`${hi({editors:[`zed`],scripts:[`check`]})}\`.`});r=a}}),Ai=E.fn(`setEffectSettings`)(function*(e,t,n){let r={arguments:[yield*ki(e),`tsc`,`--lsp`,`--stdio`],path:`node`},i=h(t.languages)?t.languages:{},a={};for(let e of[`JavaScript`,`JSX`,`TypeScript`,`TSX`]){let t=h(i[e])?i[e]:{},n=(yield*z.decodeUnknownEffect(z.Array(z.String))(t.language_servers??[`...`])).filter(e=>!Oi.has(e.replace(/^!/,``)));a[e]=Object.fromEntries([...Object.entries(t),[`language_servers`,O.dedupe([`typescript-ls`,`!vtsls`,`!typescript-language-server`,...n])]])}let o=h(t.lsp)?t.lsp:{},s=h(o.tsgo)?o.tsgo:{},c=h(o[`typescript-ls`])?o[`typescript-ls`]:{},l=yield*m({fallback:s,preferred:c}),u=h(o.oxlint)?o.oxlint:{},d=h(u.initialization_options)?u.initialization_options:{},f=h(d.settings)?d.settings:{},p=h(f.rulesCustomization)?f.rulesCustomization:{},g=yield*m({fallback:p,preferred:n});return Object.fromEntries([...Object.entries(t),[`languages`,Object.fromEntries([...Object.entries(i),...Object.entries(a)])],[`lsp`,Object.fromEntries([...Object.entries(o).filter(([e])=>e!==`tsgo`),[`typescript-ls`,Object.fromEntries([...Object.entries(l),[`binary`,r]])],[`oxlint`,Object.fromEntries([...Object.entries(u),[`initialization_options`,Object.fromEntries([...Object.entries(d),[`settings`,Object.fromEntries([...Object.entries(f),[`rulesCustomization`,g]])]])]])]])]])});function ji(e){let t=e.lsp,n=h(t)?t.oxfmt:void 0,r=h(n)?n.initialization_options:void 0,i=h(r)?r.settings:void 0;if(!h(i))return[];let a=Object.entries(Di);return Object.entries(i).filter(([e,t])=>a.some(([n,r])=>n===e&&r===t)).map(([e])=>e)}function Mi(e){return!h(e)||!d(e.plugins)?e:Object.fromEntries([...Object.entries(e),[`plugins`,O.dedupe(e.plugins)]])}function Ni(e){let t=e.languages;if(!h(t))return e;let n=Object.fromEntries(Object.entries(t).map(([e,t])=>!(e in Ei.languages)||!h(t)?[e,t]:[e,Object.fromEntries(Object.entries(t).map(([e,t])=>e===`formatter`&&d(t)?[e,O.dedupe(t)]:e===`prettier`?[e,Mi(t)]:[e,t]))]));return Object.fromEntries([...Object.entries(e),[`languages`,n]])}function Pi(e){let t=h(e.lsp)?e.lsp:{},n=h(t.oxlint)?t.oxlint:{};return Object.fromEntries([...Object.entries(e),[`lsp`,Object.fromEntries([...Object.entries(t),[`oxlint`,Object.fromEntries([...Object.entries(n),[`binary`,Ei.lsp.oxlint.binary]])]])]])}var Fi=W({assess:({cwd:e})=>E.gen(function*(){let t=(yield*P.Path).join(e,Z[0].path),n=yield*C(t);if(N.isNone(n))return{applicable:!1};let r=yield*w(n.value,t);if(!h(r))return yield*new Pe({path:t});let i=ji(r),a=h(r.lsp)?r.lsp:void 0,o=(h(a?.oxlint)?a.oxlint:void 0)?.binary,s=Ei.lsp.oxlint.binary,c=h(o)&&o.path===s.path&&mt.equals(o.arguments,s.arguments),l=yield*Ci(e),u=[];if(N.isSome(l)){let t=yield*Ai(e,r,l.value.rulesCustomization);mt.equals(r,t)||u.push({currentState:`\`${Z[0].path}\` does not select the installed Effect language server with duplicate Oxlint Effect reports hidden.`,goal:["Select `typescript-ls` for JavaScript, JSX, TypeScript, and TSX. Use the reference server binary and Oxlint rule customizations. Move old `lsp.tsgo` settings to `lsp.typescript-ls`, and preserve other settings and language servers."],id:`zed-effect-server`,integration:`zed`,reference:{content:`${yield*Be(yield*Ai(e,{},l.value.rulesCustomization))}\n`,language:`json`},title:`Zed does not use the Effect language server`})}return{applicable:!0,findings:[...u,...i.length===0?[]:[{currentState:`\`${Z[0].path}\` contains stale oxfmt settings: ${i.map(e=>`\`${e}\``).join(`, `)}.`,goal:[`Remove only the stale oxfmt entries that still have Adamantite's old default values.`,`Preserve entries that the project changed.`],id:`legacy-zed-oxfmt-settings`,integration:`zed`,title:`Legacy Zed oxfmt settings`}],...c?[]:[{currentState:`\`${Z[0].path}\` sets \`lsp.oxlint.binary\` to ${o===void 0?`no value`:`\`${yield*ce(o)}\``}. Zed does not start Oxlint through Adamantite's Oxlint entry.`,goal:[`Set \`lsp.oxlint.binary\` to \`${yield*ce(s)}\` in \`${Z[0].path}\`. Preserve every other setting.`],id:`zed-oxlint-entry`,integration:`zed`,reference:{content:`${yield*Be({lsp:{oxlint:{binary:s}}})}\n`,language:`json`},title:`Zed does not use the Oxlint entry`}]],packageActions:[],warnings:[]}}),config:Z[0].path,create:e=>E.gen(function*(){let t=yield*P.Path,n=t.join(e,Z[0].path),r=yield*Ci(e),i=N.isSome(r)?yield*Ai(e,Ei,r.value.rulesCustomization):Ei;yield*x(t.dirname(n)),yield*se(n,i)}),detect:e=>E.gen(function*(){let t=yield*R.FileSystem,n=yield*P.Path;return yield*t.exists(n.join(e,Z[0].path))}),files:Z,kind:`editor`,name:`zed`,update:e=>E.gen(function*(){let t=(yield*P.Path).join(e,Z[0].path),n=yield*r(t),i=yield*w(n,t);if(!F.isObject(i))return yield*new Pe({path:t});let a=yield*m({fallback:Ei,preferred:i}),o=yield*Ci(e),s=Pi(Ni(a)),c=N.isSome(o)?yield*Ai(e,s,o.value.rulesCustomization):s;yield*S(t,le(n,c))})});const Ii=[`oxlint.config.ts`,`oxlint.config.mts`,`oxlint.config.js`,`oxlint.config.mjs`];var Li=class extends I.TaggedClass(`external`){},Ri=class extends I.TaggedClass(`found`){},zi=class extends I.TaggedClass(`unresolved`){};const Bi=E.fn(`readPackageName`)(function*(e){let t=yield*u(e);return N.fromUndefinedOr(t.name)}),Vi=E.fn(`readFirstFile`)(function*(e){let t=yield*E.forEach(e,e=>f(e).pipe(E.map(t=>L(t,N.map(t=>({content:t,file:e}))))),{concurrency:`unbounded`});return O.head(O.getSomes(t))}),Hi=E.fn(`resolveImport`)(function*(e,t,n){let r=yield*P.Path,i=yield*Ne,a=t.startsWith(`.`)||t.startsWith(`#`)||r.isAbsolute(t)||[...n].some(e=>t===e||t.startsWith(`${e}/`)),o=yield*i.resolve(r.dirname(e),t);if(N.isNone(o))return a?new zi:new Li;if(o.value.split(r.sep).includes(`node_modules`))return new Li;let s=yield*Vi([o.value]);return N.match(s,{onNone:()=>new zi,onSome:e=>new Ri({module:e})})}),Ui=E.fn(`discoverCustomRules`)(function*(e,t=e){let n=yield*P.Path;yield*(yield*Ne).clearCache;let[r,i]=yield*E.all([E.forEach(e,e=>Bi(e),{concurrency:`unbounded`}),E.forEach(e,e=>Vi(Ii.map(t=>n.join(e,t))),{concurrency:`unbounded`})],{concurrency:`unbounded`}),a=new Set(O.getSomes(r)),o=O.getSomes(i),s=new Set(t.flatMap(e=>O.sort(o.filter(t=>{let r=n.dirname(t.file);return e===r||e.startsWith(r+n.sep)}),B.mapInput(B.flip(B.Number),e=>n.dirname(e.file).length)).slice(0,1))),c=o.filter(e=>s.has(e)),l=/* @__PURE__ */ new Set,u=/* @__PURE__ */ new Map,d=[],f=[],p=[],m=[],h=[],g=c;for(;g.length>0;){let e=g.filter(e=>!l.has(e.file));for(let t of e)if(l.add(t.file),u.set(t.file,t),on(t.file,t.content)&&p.push(t.file),t.content.includes(Xt))for(let e of dn(t.file,t.content))e instanceof en?m.push(t.file):f.push({dir:n.resolve(n.dirname(t.file),e.dir),name:e.name,source:t.file});let t=e.flatMap(e=>gn(e.file,e.content).map(t=>({from:e.file,specifier:t}))),r=yield*E.forEach(t,({from:e,specifier:t})=>Hi(e,t,a),{concurrency:`unbounded`});g=[];for(let[e,n]of r.entries()){let r=t[e];n instanceof Ri&&r!==void 0?(d.push({...r,file:n.module.file}),g.push(n.module)):n instanceof zi&&r!==void 0&&h.push(r)}}return{calls:f,configs:c.map(e=>e.file),legacyImports:p,resolvedImports:d,sources:[...u.values()],unresolvedCalls:m,unresolvedImports:h}});function Wi(e){return e.unresolvedCalls.length===0&&e.unresolvedImports.length===0}const Gi=`oxlint-custom`,Ki=`import { defineConfig } from "oxlint"
|
|
99
|
+
import core from "${G(`./lint`)}"
|
|
100
|
+
import custom from "${G(`./rules`)}"
|
|
110
101
|
|
|
111
102
|
export default defineConfig({
|
|
112
103
|
extends: [core, custom()],
|
|
113
104
|
})
|
|
114
|
-
`,
|
|
115
|
-
`)
|
|
116
|
-
`)}
|
|
105
|
+
`,qi=E.fn(`readRulesFolder`)(function*(e){return(yield*nt(e)).pipe(N.map(t=>({dir:e,ruleFiles:t.filter(e=>Qt(e))})))});var Ji=W({assess:({customRules:e,cwd:t,workspace:n})=>E.gen(function*(){let i=yield*P.Path,a=e=>i.relative(t,e)||`.`,o=[t,...n.packageDirectories],{calls:s,legacyImports:c,unresolvedCalls:l,unresolvedImports:u}=e,d=Wi(e),f=o.map(e=>i.join(e,K)),p=O.dedupe(s.map(e=>e.dir)),m=o.map(e=>i.join(e,`.adamantite/rules`)),h=yield*E.forEach(O.dedupe([...f,...m,...p]),e=>qi(e),{concurrency:`unbounded`}),g=O.getSomes(h),_=g.filter(e=>e.ruleFiles.length>0),v=O.dedupeWith(s.filter(e=>e.dir!==i.join(i.dirname(e.source),`.adamantite/lint`)&&!g.some(t=>t.dir===e.dir)),(e,t)=>e.dir===t.dir),ee=_.filter(e=>d&&m.includes(e.dir)&&!p.includes(e.dir));if(d&&s.length===0&&_.length===0&&c.length===0)return{applicable:!1};let y=s.filter(e=>N.isNone(e.name)),te=[...u.map(({from:e,specifier:t})=>`Doctor cannot resolve the import of \`${t}\` in \`${a(e)}\`, so it does not check the \`custom()\` calls and rules folders behind it. For a workspace package, install the dependencies and run Doctor again.`),...l.map(e=>`Doctor cannot read the \`dir\` of a \`custom()\` call in \`${a(e)}\`, because it is not a string literal. Doctor does not check that rules folder.`),...y.map(e=>`Doctor cannot read the \`name\` of a \`custom()\` call in \`${a(e.source)}\`, because it is not a string literal. Doctor does not check that its plugin name differs from the other rules folders.`)],b=v.map(e=>({currentState:`The \`custom()\` call in \`${a(e.source)}\` loads \`${a(e.dir)}\`, but that folder does not exist, so Oxlint runs none of its rules.`,goal:[`Set \`dir\` to the folder that holds the rules, or move the rules to \`${a(e.dir)}\`. A relative \`dir\` resolves from the file that calls \`custom()\`.`,`Preserve every other setting in the Oxlint config.`],id:`custom-rules-folder-missing:${a(e.dir)}`,integration:Gi,title:`The rules folder \`${a(e.dir)}\` does not exist`}));if(d)for(let e of _)p.includes(e.dir)||ee.includes(e)||b.push({currentState:`No \`custom()\` call loads the rules in \`${a(e.dir)}\`, so Oxlint does not run them.`,goal:[`Load \`${a(e.dir)}\` with \`custom()\` from \`adamantite/rules\` in the Oxlint config of \`${a(i.dirname(i.dirname(e.dir)))}\`. A relative \`dir\` resolves from the file that calls \`custom()\`.`,"Give each rules folder its own plugin name with the `name` option, because Oxlint rejects two plugins with the same name in one run.",`Preserve every other setting in the Oxlint config.`],id:`custom-rules-not-loaded:${a(e.dir)}`,integration:Gi,reference:{content:Ki,language:`ts`},title:`Custom rules in \`${a(e.dir)}\` are not loaded`});let ne=yield*E.forEach(_.flatMap(e=>e.ruleFiles.map(t=>i.join(e.dir,t))),e=>r(e).pipe(E.map(t=>({legacyImports:on(e,t),problems:_n(e,t),rulePath:e}))),{concurrency:`unbounded`}),x=O.dedupe([...c,...ne.filter(e=>e.legacyImports).map(e=>e.rulePath)]);(x.length>0||ee.length>0)&&b.push({currentState:[...x.map(e=>`\`${a(e)}\` imports the old custom-rules API.`),...ee.map(e=>`\`${a(e.dir)}\` is the previous default rules folder, and no current \`custom()\` call loads it.`)].join(`
|
|
106
|
+
`),goal:['Import the rules-folder preset as `import custom from "adamantite/rules"`. Replace `adamantite/lint/custom` imports and keep `custom()` in the Oxlint config extends.',"Import `definePlugin`, `defineRule`, `eslintCompatPlugin`, and the Oxlint authoring types from `adamantite/rules/plugin`. Keep `RuleTester` at `adamantite/rules/testing`.",'Move `.adamantite/rules` to `.adamantite/lint`, or keep its path with `custom({ dir: ".adamantite/rules" })` and `rule add --dir .adamantite/rules`. A relative `dir` resolves from the file that calls `custom()`.',"If you keep `.adamantite/rules` or another explicit rules folder, add its rule and optional test patterns to Knip oxlint.entry. The preset defaults cover only `.adamantite/lint`.",`Update relative imports, tsconfig include paths, and Knip oxlint.entry patterns when a folder moves. Keep explicit rules folders and their options.`,"Keep optional saved tests beside their rules as `<name>.test.ts`, and update their relative imports. For tests saved elsewhere, use `adamantite rule test --path <file>` and keep their Knip entry settings. Add a test only on request with `adamantite rule test add [name]`.",`Saved RuleTester tests use node:test. Exclude them from Vitest/Jest discovery. If TypeScript checks them, enable compilerOptions.allowImportingTsExtensions for .ts rule imports.`,"Agents verify rules with RuleTester from `adamantite/rules/testing`, using stdin or a temporary file, and remove their temporary cases and fixtures. Preserve user-owned optional tests and CI steps. `adamantite rule test` runs saved tests only when explicitly invoked.","Preserve rule behavior, plugin names, rule severity, rule options, and all other config settings. Run `adamantite check`, then run Doctor again."],id:`custom-rules-api-migration`,integration:Gi,reference:{content:Ki,language:`ts`},title:`Custom rules need migration to the current agent workflow`});for(let{problems:e,rulePath:t}of ne)e.length!==0&&b.push({currentState:`\`${a(t)}\` cannot load as a rule, so the whole lint run fails with "Failed to parse oxlint configuration file":\n${e.map(e=>` - ${e}`).join(`
|
|
107
|
+
`)}`,goal:["The file parses, uses only TypeScript that type stripping can erase (no `enum`, `namespace` with values, parameter properties, or `import x = require()`), and exports the rule as default.",`Keep the behavior of the rule.`],id:`custom-rule-cannot-load:${a(t)}`,integration:Gi,notes:["A file that starts with `_` is a helper, not a rule. Rename a helper file so that it starts with `_`."],title:`Custom rule \`${a(t)}\` cannot load`});let re=s.flatMap(({dir:e,name:t,source:n})=>N.isSome(t)&&_.some(t=>t.dir===e)?[{dir:e,name:t.value,source:n}]:[]);for(let[e,t]of Object.entries(O.groupBy(re,e=>e.name))){let n=O.dedupe(t.map(e=>e.dir));n.length<2||b.push({currentState:`${n.length.toLocaleString(`en-US`)} rules folders use the plugin name \`${e}\`: ${n.map(e=>`\`${a(e)}\``).join(`, `)}. Oxlint rejects two plugins with the same name in one run.`,goal:[`Each \`custom()\` call that loads one of these folders passes a \`name\` that no other rules folder uses, such as \`custom({ name: "web" })\`. The calls are in ${O.dedupe(t.map(e=>`\`${a(e.source)}\``)).join(`, `)}.`,"Rule names in `oxlint-disable` comments and `rules` settings use the new plugin name."],id:`custom-rules-duplicate-name:${e}`,integration:Gi,title:`Rules folders share the plugin name \`${e}\``})}return{applicable:!0,findings:b,packageActions:[],warnings:te}}),kind:`tooling`,name:Gi});function Yi(e){let{assess:t,name:n,preset:r,version:i,...a}=e,o=qt({isRequired:({lintConfig:e})=>On(e,r),name:n,purpose:`the \`adamantite/lint/${r}\` preset`,scripts:De(`oxlint`),version:i});return{...a,...o,assess:e=>E.gen(function*(){let n=yield*o.assess(e);if(!n.applicable||t===void 0)return n;let r=yield*t(e);return{...n,findings:[...n.findings,...r.findings],warnings:[...n.warnings,...r.warnings]}}),preset:r}}const Xi={"@effect/tsgo":`0.67.3`,"@shadcn/lint":`0.2.1`,"oxlint-plugin-react-doctor":`0.9.18`},Zi=be.flatMap(e=>`plugin`in e?[Yi({...e.plugin,preset:e.name,version:Xi[e.plugin.name]})]:[]),Qi=`oxlint-tsgolint`;var $i=qt({legacyFindings:e=>e.devDependencies?.[Qi]??e.dependencies?.[Qi]?[{currentState:`\`package.json\` lists \`${Qi}\`, which Adamantite no longer uses.`,goal:[`Remove \`${Qi}\` from \`package.json\`, and install again.`],id:`legacy-${Qi}`,integration:`tsrs`,notes:[`Adamantite runs the type-aware rules on tsrs, so Oxlint does not start oxlint-tsgolint.`],title:`Legacy ${Qi}`}]:[],name:`tsrs`,purpose:`the type-aware rules of the managed lint scripts`,scripts:De(`oxlint`),version:`0.21.0-ts7.1.0-beta`});const ea=[{path:`AGENTS.md`,type:`config`}];var ta=W({assess:({cwd:e,packageJson:n})=>E.gen(function*(){let r=t(n);if(r.length===0)return{applicable:!1};let i=yield*R.FileSystem,a=yield*P.Path;return{applicable:!0,findings:(yield*i.exists(a.join(e,ea[0].path)))?[]:[{currentState:"The project root has no `AGENTS.md`.",goal:["Create `AGENTS.md` at the project root with the instructions that coding agents must follow in this project.","Run `adamantite doctor` again. It must not report this finding."],id:`missing-agents-md`,integration:`agents`,notes:["`AGENTS.md` is where coding agents start. It points to the other documentation of the project.",`To create the file with an Adamantite section that lists the package scripts, run \`${hi({agents:!0,scripts:r})}\`.`],title:`Missing AGENTS.md`}],packageActions:[],warnings:[]}}),files:ea,kind:`workspace`,name:`agents`});const na=[{path:`tsconfig.json`,type:`config`}],Q=G(`./typescript`),ra={extends:Q},ia=["Adamantite leaves the root `tsconfig.json` unchanged in a monorepo.",`To use the TypeScript preset, add \`"extends": "${Q}"\` to each package's \`tsconfig.json\` or to a shared base config.`];function aa(e){return F.isString(e)?e===Q?e:[e,Q]:O.isArray(e)?e.includes(Q)?e:[...e,Q]:Q}var oa=W({assess:({cwd:e,packageJson:n,workspace:r})=>E.gen(function*(){let i=t(n);if(!y(i,`oxlint`))return{applicable:!1};if(r.isMonorepo)return{applicable:!0,findings:[],packageActions:[],warnings:ia};let a=(yield*P.Path).join(e,na[0].path),o=yield*C(a);if(N.isNone(o))return{applicable:!0,findings:[{currentState:"`tsconfig.json` is missing.",goal:["Create `tsconfig.json` and set `extends` to include `adamantite/typescript`."],id:`missing-tsconfig`,integration:`tsconfig`,reference:{content:`${yield*Be(ra)}\n`,language:`json`},title:`Missing TypeScript configuration`}],packageActions:[],warnings:[]};let s=yield*w(o.value,a);return{applicable:!0,findings:F.isObject(s)&&(s.extends===Q||O.isArray(s.extends)&&s.extends.includes(Q))?[]:[{currentState:"`tsconfig.json` does not extend `adamantite/typescript`.",goal:["Add `adamantite/typescript` to `extends`. Preserve every existing TypeScript option and existing base config."],id:`missing-adamantite-tsconfig-extends`,integration:`tsconfig`,reference:{content:`${yield*Be(ra)}\n`,language:`json`},title:`TypeScript preset is not configured`}],packageActions:[],warnings:[]}}),config:na[0].path,create:e=>E.gen(function*(){let t=yield*P.Path;yield*se(t.join(e,na[0].path),ra)}),detect:e=>E.gen(function*(){let t=yield*R.FileSystem,n=yield*P.Path;return yield*t.exists(n.join(e,na[0].path))}),files:na,kind:`workspace`,name:`tsconfig`,update:e=>E.gen(function*(){let t=(yield*P.Path).join(e,na[0].path),n=yield*r(t),i=yield*w(n,t);if(!F.isObject(i))return yield*new Pe({path:t});let a=yield*m({fallback:ra,preferred:i}),o=Object.fromEntries([...Object.entries(a),[`extends`,aa(`extends`in i?i.extends:void 0)]]);yield*S(t,le(n,o))})});const sa=[tr,q,J,Ji,...Zi,Er,$i,oa,ta,mi,Ti,Fi],ca=E.fn(`assessProject`)(function*(e){let t=yield*E.forEach(sa,t=>E.gen(function*(){let n=yield*t.assess(e);return n.applicable?[{assessment:n,name:t.name}]:[]}),{concurrency:`unbounded`}),n=O.flatten(t);return{applicableIntegrations:n.map(({name:e})=>e),findings:n.flatMap(({assessment:e})=>e.findings),packageActions:n.flatMap(({assessment:e})=>e.packageActions),warnings:n.flatMap(({assessment:e})=>e.warnings)}});function la(e,t){return e.findings.length===0?ua(e.warnings,t):da(e.findings,e.warnings,t)}function ua(e,t){return Rr(`# Adamantite doctor warnings
|
|
108
|
+
|
|
109
|
+
Adamantite {{version}} detected no repair findings. The assessment reported these warnings:
|
|
110
|
+
|
|
111
|
+
{{warnings}}
|
|
112
|
+
|
|
113
|
+
Review the affected project state before deciding whether a warning needs a change.
|
|
114
|
+
Report each unresolved warning and the limit it places on verification.
|
|
115
|
+
If a required tool or source was unavailable, name it on the first line and state what you used instead.
|
|
116
|
+
The review is complete when each warning has an observed result or a stated limit.
|
|
117
|
+
|
|
118
|
+
## Check the report
|
|
119
|
+
|
|
120
|
+
- Every warning is accounted for, including missing tools or sources.
|
|
121
|
+
- A successful Doctor exit is not reported as proof that all project checks pass.
|
|
122
|
+
`,{version:t,warnings:e.map(e=>`- ${e}`).join(`
|
|
123
|
+
`)})}function da(e,t,n){let r=e.map((e,t)=>{let n=e.goal.map(e=>` - ${e}`).join(`
|
|
117
124
|
`),r=e.reference?`\n- **Reference:**\n\n\`\`\`${e.reference.language}\n${e.reference.content.trimEnd()}\n\`\`\``:``,i=e.notes&&e.notes.length>0?`\n- **Notes:**\n${e.notes.map(e=>` - ${e}`).join(`
|
|
118
|
-
`)}`:``;return`## ${t+1}. ${e.title}\n\n- **Current state:** ${e.currentState}\n- **Goal:**\n${n}${r}${i}`}),i=t.length>0?[`## Assessment warnings`,``,`
|
|
125
|
+
`)}`:``;return`## ${t+1}. ${e.title}\n\n- **Current state:** ${e.currentState}\n- **Goal:**\n${n}${r}${i}`}),i=t.length>0?[`## Assessment warnings`,``,`Review these warnings before making repairs:`,``,...t.map(e=>`- ${e}`),``,``].join(`
|
|
126
|
+
`):``;return Rr(`# Adamantite doctor findings
|
|
127
|
+
|
|
128
|
+
Repair the findings below for the target project that uses Adamantite {{version}}.
|
|
129
|
+
Total findings: {{findingCount}}.
|
|
119
130
|
|
|
120
|
-
|
|
121
|
-
|
|
131
|
+
1. If the project has \`AGENTS.md\`, read it and the instructions it names. Inspect the current files for each finding.
|
|
132
|
+
Continue when each finding's current state is confirmed, or rerun Doctor if the state has changed.
|
|
133
|
+
2. Meet every finding's goal and preserve the settings its notes protect. Merge reference settings into the existing configuration.
|
|
134
|
+
For example, add a required plugin entry without replacing the project's other plugins.
|
|
135
|
+
Fix the cause of each finding. Do not suppress checks or add workarounds.
|
|
136
|
+
Continue when each goal is met or recorded as blocked with a reason. Keep unrelated project settings and code unchanged.
|
|
137
|
+
|
|
138
|
+
{{warnings}}{{findings}}
|
|
139
|
+
|
|
140
|
+
## Verify
|
|
141
|
+
|
|
142
|
+
1. Run the project's installed \`adamantite doctor\` from the project root through its package runner, such as \`npx\` or \`pnpm exec\`.
|
|
143
|
+
Reread and resolve new findings until Doctor exits with code 0 and reports no findings.
|
|
144
|
+
If a remaining goal is blocked, record the reason and stop the repair loop. Do not claim that the repair is complete.
|
|
145
|
+
Record assessment warnings separately. Warnings alone can exit with code 0.
|
|
146
|
+
2. Run the project checks affected by the repairs and read their output.
|
|
147
|
+
Continue when those checks pass, or record each failed or unavailable check without claiming a verified repair.
|
|
148
|
+
3. Report the repaired findings, changed files, commands, results, and any blocked goals or warnings.
|
|
149
|
+
If a required tool or source was unavailable, name it on the first line and state what you used instead.
|
|
150
|
+
The report is complete when every finding has a verified result or an explicit blocker.
|
|
151
|
+
|
|
152
|
+
## Check the repair
|
|
153
|
+
|
|
154
|
+
- Every finding's goal is met or has a reported blocker.
|
|
155
|
+
- Reference settings were merged, and unrelated project settings remain intact.
|
|
156
|
+
- Doctor reports no findings, or the report names every remaining finding.
|
|
157
|
+
- The report separates findings, warnings, and checks that could not be verified.
|
|
158
|
+
`,{findingCount:e.length.toLocaleString(`en-US`),findings:r.join(`
|
|
159
|
+
|
|
160
|
+
`),version:n,warnings:i})}const fa=E.fn(`readProject`)(function*(e){let t=yield*P.Path,[n,r,i]=yield*E.all([u(e),re(e),C(t.join(e,`oxlint.config.ts`))],{concurrency:`unbounded`});return{customRules:yield*Ui([e,...r.packageDirectories]),cwd:e,lintConfig:i,packageJson:n,workspace:r}});var pa=class extends ct.Service()(`TerminalCapabilities`){static layer=A.succeed(this)({copyToClipboard:e=>E.sync(()=>{let t=Buffer.from(e).toString(`base64`);j.stdout.write(`\u001B]52;c;${t}\u0007`)}),isInteractive:E.sync(()=>j.stdin.isTTY&&j.stdout.isTTY)})},$=class extends ct.Service()(`Prompter`){static layerWithSpinner(e){return A.succeed(this)({cancel:e=>E.sync(()=>{H.cancel(e)}),confirm:e=>E.promise(()=>H.confirm(e)).pipe(E.filterOrFail(e=>!H.isCancel(e),()=>new $e({}))),intro:e=>E.sync(()=>{H.intro(e)}),log:{error:e=>E.sync(()=>{H.log.error(e)}),info:e=>E.sync(()=>{H.log.info(e)}),success:e=>E.sync(()=>{H.log.success(e)}),warning:e=>E.sync(()=>{H.log.warning(e)})},message:e=>E.sync(()=>{H.log.message(e,{spacing:0,withGuide:!1})}),multiselect:e=>E.promise(()=>H.multiselect(e)).pipe(E.filterOrFail(e=>!H.isCancel(e),()=>new $e({}))),note:(e,t)=>E.sync(()=>{H.note(e,t)}),outro:e=>E.sync(()=>{H.outro(e)}),select:e=>E.promise(()=>H.select(e)).pipe(E.filterOrFail(e=>!H.isCancel(e),()=>new $e({}))),withSpinner:(t,n)=>E.acquireUseRelease(E.sync(()=>{let t=e();return t.start(n.start),t}),e=>t({message:t=>E.sync(()=>{e.message(t)})}),(e,t)=>E.sync(()=>{it.match(t,{onFailure:t=>{Tt.hasInterruptsOnly(t)?e.cancel(n.failure):e.error(n.failure)},onSuccess:t=>{e.stop(F.isFunction(n.success)?n.success(t):n.success)}})}))})}static layer=this.layerWithSpinner(H.spinner)};function ma(e){let t=[`Current state\n${e.currentState}`,`Goal\n${e.goal.map(e=>`• ${e}`).join(`
|
|
122
161
|
`)}`];return e.reference&&t.push(`Reference\n${e.reference.content.trimEnd()}`),e.notes&&e.notes.length>0&&t.push(`Notes\n${e.notes.map(e=>`• ${e}`).join(`
|
|
123
162
|
`)}`),t.join(`
|
|
124
163
|
|
|
125
|
-
`)}const Pi=t.fn(`printFindings`)(function*(e){let t=yield*Q;for(let[n,r]of e.entries())yield*t.note(Ni(r),`${n+1}. ${r.title}`)}),Fi=`0.45.0`;var Ii=c.make(`doctor`).pipe(c.withDescription(`Assess Adamantite-managed integrations in the current project`),c.withHandler(()=>t.gen(function*(){let e=f.cwd(),n=yield*ji,i=yield*Q,a=yield*Mi,o=yield*a.isInteractive;o&&(yield*i.intro(`💠 adamantite doctor`));let s=t.gen(function*(){return yield*i.outro(`⚠️ Doctor found issues.`),yield*new Se({command:`doctor`,exitCode:r.ExitCode(1)})}),c=yield*R(e);if(!c.devDependencies?.adamantite&&!c.dependencies?.adamantite){let e="`adamantite` is not installed in this project. Install it before running `adamantite doctor`.";return o?(yield*i.log.warning(e),yield*i.outro(`⚠️ Doctor found issues.`)):yield*i.message(e),yield*new Se({command:`doctor`,exitCode:r.ExitCode(1)})}let l=yield*Ci(e);if(o)for(let e of l.warnings)yield*i.log.warning(e);if(l.applicableIntegrations.length===0){o&&(yield*i.log.success(`No applicable integrations found.`),yield*i.outro(`✅ Doctor completed successfully!`));return}if(l.findings.length===0){o?(yield*i.log.success(`No issues found.`),yield*i.outro(`✅ Doctor completed successfully!`)):l.warnings.length>0&&(yield*i.message(wi(l,Fi)));return}if(!o)return yield*i.message(wi(l,Fi)),yield*new Se({command:`doctor`,exitCode:r.ExitCode(1)});let u=e=>t.gen(function*(){(yield*i.confirm({initialValue:!0,message:`Copy the Markdown prompt for a coding agent?`}))&&(yield*i.message(e),yield*a.copyToClipboard(e),yield*i.log.success(`The Markdown prompt was printed and sent to the terminal clipboard.`))});yield*Pi(l.findings);let d=yield*i.withSpinner(()=>n.detectInstalled(e),{start:`Checking for installed coding agents...`,success:e=>e.length===0?`No supported coding agent CLI was found on PATH.`:`Found ${e.map(e=>e.name).join(`, `)}.`});d.length===0&&(yield*i.log.info(`Doctor can hand findings off when one of these CLIs is installed: ${Di.map(e=>`\`${e.command}\``).join(`, `)}.`));let p=wi(l,Fi),m=yield*i.select({message:`How do you want to resolve these findings?`,options:[...d.map(e=>({label:`Hand off to ${e.name}`,value:e})),{label:`Copy the Markdown prompt for a coding agent`,value:`copy`},{label:`Do nothing`,value:`done`}]});if(m===`done`)return yield*s;if(m===`copy`)return yield*i.message(p),yield*a.copyToClipboard(p),yield*i.log.success(`The Markdown prompt was printed and sent to the terminal clipboard.`),yield*s;let h=m;if(yield*i.log.info(`Handing the terminal to ${h.name}. Exit the agent to return to Doctor.`),!(yield*n.runSession({agent:h,cwd:e,prompt:p}).pipe(t.as(!0),t.catchTag(`AgentSessionFailed`,e=>i.log.error(e.reason===`not-found`?`\`${h.command}\` was not found on PATH. Install ${h.name} or copy the prompt instead.`:`Failed to start ${h.name}: ${e.cause.message}`).pipe(t.as(!1))))))return yield*u(p),yield*s;let g=yield*Ci(e);if(g.findings.length===0)yield*i.log.success(`All findings were resolved by ${h.name}.`),yield*i.outro(`✅ Doctor completed successfully!`);else return yield*i.log.warning(`${g.findings.length} of ${l.findings.length} findings remain after the ${h.name} session.`),yield*Pi(g.findings),yield*u(wi(g,Fi)),yield*s}).pipe(t.catchTag(`OperationCancelled`,()=>t.gen(function*(){return yield*(yield*Q).cancel(`Doctor was cancelled. The findings remain.`),yield*new Se({command:`doctor`,exitCode:r.ExitCode(1)})})))));const Li=T.File(`files`,{mustExist:!0}).pipe(T.withDescription(`Specific files to fix (optional)`),T.variadic()),Ri=u.Boolean(`suggested`).pipe(u.withDefault(!1),u.withDescription(`Apply suggested fixes`)),zi=u.Boolean(`dangerous`).pipe(u.withDefault(!1),u.withDescription(`Apply dangerous fixes`)),Bi=u.Boolean(`all`).pipe(u.withDefault(!1),u.withDescription(`Apply all fixes, including suggested and dangerous fixes`)),Vi=u.Literals(`only`,[`format`,`lint`]).pipe(u.optional,u.withDescription("Run one stage: `format` (oxfmt) or `lint` (oxlint). Arguments after `--` go to that stage"));var Hi=c.make(`fix`,{all:Bi,dangerous:zi,files:Li,only:Vi,suggested:Ri}).pipe(c.withDescription(`Fix lint and formatting issues in code`),c.withHandler(({all:e,dangerous:n,files:r,only:i,suggested:a})=>t.gen(function*(){let t=yield*Ue,o=yield*j,c=d.getOrUndefined(i);if(c===`format`&&(e||n||a))return yield*new Pe({reason:"`--suggested`, `--dangerous`, and `--all` apply to the lint stage. Remove them or `--only format`."});let l=s.dedupe(r),u=c??`lint`,f=[{args:s.dedupe([`--fix`,...a||e?[`--fix-suggestions`]:[],...n||e?[`--fix-dangerously`]:[],...l]),command:W.name,name:`lint`,title:`🔧 Fixing lint issues`},{args:[`--write`,...l],command:U.name,name:`format`,title:`✨ Formatting`}];yield*o.runAll(f.filter(e=>c===void 0||e.name===c).map(e=>({args:[...e.args,...e.name===u?t:[]],command:e.command,title:e.title})))})));const Ui=' .o8 . o8o . \n "888 .o8 `"\' .o8 \n .oooo. .oooo888 .oooo. ooo. .oo. .oo. .oooo. ooo. .oo. .o888oo oooo .o888oo .ooooo. \n`P )88b d88\' `888 `P )88b `888P"Y88bP"Y88b `P )88b `888P"Y88b 888 `888 888 d88\' `88b \n .oP"888 888 888 .oP"888 888 888 888 .oP"888 888 888 888 888 888 888ooo888 \nd8( 888 888 888 d8( 888 888 888 888 d8( 888 888 888 888 . 888 888 . 888 .o \n`Y888""8o `Y8bod88P" `Y888""8o o888o o888o o888o `Y888""8o o888o o888o "888" o888o "888" `Y8bod8P\' \n \n \n ',Wi=t.gen(function*(){let e=yield*(yield*_e.Terminal).columns,t=Ui.split(`
|
|
126
|
-
`).
|
|
127
|
-
`);
|
|
128
|
-
`)}const ua=(e,n)=>t.gen(function*(){let t=(yield*w.Path).join(e,`AGENTS.md`),r=b(yield*P(t),d.getOrElse(()=>``)),i=b(r,S.indexOf(oa)),a=b(r,S.indexOf(sa)),o=b(d.all({end:a,start:i}),d.filter(({end:e,start:t})=>t<e)),s=la(n);if(d.isSome(o)){let{end:e,start:n}=o.value,i=e+23,a=`${r.slice(0,n)}${s.trimEnd()}${r.slice(i)}`;return yield*F(t,a.endsWith(`
|
|
129
|
-
`)
|
|
164
|
+
`)}const ha=E.fn(`printFindings`)(function*(e){let t=yield*$;for(let[n,r]of e.entries())yield*t.note(ma(r),`${n+1}. ${r.title}`)}),ga=[{command:`claude`,name:`Claude Code`,seedArguments:e=>[e],skillsFolder:`.claude/skills`},{command:`codex`,name:`Codex`,seedArguments:e=>[e],skillsFolder:`.agents/skills`},{command:`cursor-agent`,name:`Cursor`,seedArguments:e=>[e],skillsFolder:`.agents/skills`},{command:`gemini`,name:`Gemini CLI`,seedArguments:e=>[`-i`,e],skillsFolder:`.agents/skills`},{command:`grok`,name:`Grok Build`,probeArguments:[`version`],seedArguments:e=>[e],skillsFolder:`.grok/skills`},{command:`opencode`,name:`OpenCode`,seedArguments:e=>[`--prompt`,e],skillsFolder:`.agents/skills`}];var _a=class extends I.TaggedError(`HandoffFailed`){};const va=()=>{},ya=E.acquireRelease(E.sync(()=>{let e=j.listeners(`SIGINT`);return j.removeAllListeners(`SIGINT`),j.on(`SIGINT`,va),e}),e=>E.sync(()=>{j.removeAllListeners(`SIGINT`);for(let t of e)j.on(`SIGINT`,t)}));var ba=class e extends ct.Service()(`CodingAgents`){static layer=A.effect(this,E.gen(function*(){let t=yield*Pt,n=(e,n)=>t.exitCode({args:[...e.probeArguments??[`--version`]],command:e.command,cwd:n,stderr:`ignore`,stdout:`ignore`}).pipe(E.timeout(`10 seconds`),E.isSuccess);return e.of({detectInstalled:E.fn(`CodingAgents.detectInstalled`)(e=>E.filter(ga,t=>n(t,e),{concurrency:`unbounded`})),handoff:E.fn(`CodingAgents.handoff`)(function*({agent:e,cwd:n,prompt:r}){yield*ya,yield*t.exitCode({args:e.seedArguments(r),command:e.command,cwd:n,stderr:`inherit`,stdin:`inherit`,stdout:`inherit`})},E.scoped,E.mapError(e=>new _a({cause:e,reason:F.isTagged(e,`CliNotFound`)?`not-found`:`spawn-failed`})))})}))},xa=class extends I.TaggedClass(`Copied`){},Sa=class extends I.TaggedClass(`Declined`){},Ca=class extends I.TaggedClass(`Ended`){},wa=class extends I.TaggedClass(`Failed`){};const Ta=E.fn(`copyPrompt`)(function*(e){let t=yield*$,n=yield*pa;yield*t.message(e),yield*n.copyToClipboard(e),yield*t.log.success(`The agent prompt is printed above and sent to the terminal clipboard.`)}),Ea=E.fn(`offerPromptCopy`)(function*(e){(yield*(yield*$).confirm({initialValue:!0,message:`Copy the agent prompt?`}))&&(yield*Ta(e))}),Da=E.fn(`chooseResolution`)(function*(e){let t=yield*ba,n=yield*$,r=yield*n.withSpinner(()=>t.detectInstalled(e.cwd),{failure:`Could not check for installed coding agents.`,start:`Checking for installed coding agents...`,success:e=>e.length===0?`No supported coding agent was found on PATH.`:`Found ${e.map(e=>e.name).join(`, `)}.`});r.length===0&&(yield*n.log.info(`${e.command} can hand ${e.subject} off when one of these CLIs is installed: ${ga.map(e=>`\`${e.command}\``).join(`, `)}.`));let i=yield*n.select({message:e.message,options:[...r.map(e=>({label:`Hand off to ${e.name}`,value:e})),{label:`Copy the agent prompt`,value:`copy`},{label:`Finish without an agent`,value:`done`}]});if(i===`done`)return new Sa;if(i===`copy`)return yield*Ta(e.prompt),new xa;let a=i;return yield*n.log.info(`Handing the terminal to ${a.name}. Exit the agent to return to ${e.command}.`),(yield*t.handoff({agent:a,cwd:e.cwd,prompt:e.prompt}).pipe(E.as(!0),E.catchTag(`HandoffFailed`,e=>n.log.error(e.reason===`not-found`?`\`${a.command}\` was not found on PATH. Install ${a.name} or copy the prompt instead.`:`Failed to start ${a.name}: ${e.cause.message}`).pipe(E.as(!1)))))?new Ca({agent:a}):(yield*Ea(e.prompt),new wa({agent:a}))}),Oa=`0.46.0`,ka="`adamantite` is not installed in this project. Install it before running `adamantite doctor`.",{$match:Aa,Converged:ja,NeedsRepair:Ma,NotInstalled:Na,Unmanaged:Pa}=I.taggedEnum();function Fa(e){return e.applicableIntegrations.length===0?Pa():e.findings.length===0?ja({assessment:e}):Ma({assessment:e})}function Ia(){return new Ie({command:`doctor`,exitCode:D.ExitCode(1)})}var La=k.make(`doctor`).pipe(k.withDescription(`Check Adamantite setup and report what needs repair`),k.withHandler(()=>E.gen(function*(){let e=j.cwd(),t=yield*$,n=yield*(yield*pa).isInteractive;n&&(yield*t.intro(`💠 adamantite doctor`));let r=E.gen(function*(){return yield*t.outro(`⚠️ Doctor found issues.`),yield*Ia()}),i=e=>E.gen(function*(){yield*t.log.success(e),yield*t.outro(`✅ Doctor finished.`)}),a=e=>E.forEach(e.warnings,e=>t.log.warning(e),{discard:!0}),o=E.fn(`resolveFindings`)(function*(n){yield*a(n),yield*ha(n.findings);let o=yield*Da({command:`Doctor`,cwd:e,message:`How do you want to resolve these findings?`,prompt:la(n,Oa),subject:`findings`});if(!(o instanceof Ca))return yield*r;let{agent:s}=o,c=yield*ca(yield*fa(e));return c.findings.length===0?yield*i(`All findings were resolved by ${s.name}.`):(yield*t.log.warning(`Doctor still reports ${c.findings.length.toLocaleString(`en-US`)} unresolved ${c.findings.length===1?`finding`:`findings`} after the ${s.name} session.`),yield*ha(c.findings),yield*Ea(la(c,Oa)),yield*r)}),s=Aa({Converged:({assessment:e})=>a(e).pipe(E.andThen(i(`No setup repairs needed.`))),NeedsRepair:({assessment:e})=>o(e),NotInstalled:()=>t.log.warning(ka).pipe(E.andThen(r)),Unmanaged:()=>i("No Adamantite-managed setup found. Run `adamantite init` to configure the project.")}),c=Aa({Converged:({assessment:e})=>e.warnings.length>0?t.message(la(e,Oa)):E.void,NeedsRepair:({assessment:e})=>t.message(la(e,Oa)).pipe(E.andThen(Ia())),NotInstalled:()=>t.message(ka).pipe(E.andThen(Ia())),Unmanaged:()=>E.void}),l=yield*u(e),d=l.devDependencies?.adamantite||l.dependencies?.adamantite?Fa(yield*ca(yield*fa(e))):Na();yield*n?s(d):c(d)}).pipe(E.catchTag(`OperationCancelled`,()=>E.gen(function*(){return yield*(yield*$).cancel(`Doctor was cancelled. The findings remain.`),yield*Ia()})))));const Ra=V.File(`files`,{mustExist:!0}).pipe(V.withDescription(`Files to fix. Omit to fix the project`),V.variadic()),za=M.Boolean(`suggested`).pipe(M.withDefault(!1),M.withDescription(`Apply Oxlint's suggested fixes`)),Ba=M.Boolean(`dangerous`).pipe(M.withDefault(!1),M.withDescription(`Apply Oxlint's dangerous fixes`)),Va=M.Boolean(`all`).pipe(M.withDefault(!1),M.withDescription(`Apply all Oxlint fixes, including suggested and dangerous fixes`)),Ha=M.Literals(`only`,[`format`,`lint`]).pipe(M.optional,M.withDescription(`Run only format (Oxfmt) or lint (Oxlint). Pass tool arguments after --`));function Ua(e){return e.all||e.suggested&&e.dangerous?`all`:e.suggested?`suggested`:e.dangerous?`dangerous`:`safe`}var Wa=k.make(`fix`,{all:Va,dangerous:Ba,files:Ra,only:Ha,suggested:za}).pipe(k.withDescription(`Apply lint fixes and format code`),k.withHandler(({all:e,dangerous:t,files:n,only:r,suggested:i})=>E.gen(function*(){yield*Or({cwd:j.cwd(),files:n,forwardedArguments:yield*At,level:Ua({all:e,dangerous:t,suggested:i}),only:N.getOrUndefined(r)})})));const Ga=/\.(?:md|mdx|mdc)$/u,Ka=/^ {0,3}((`|~)\2{2,})[^\n]*\n[\s\S]*?(?:^ {0,3}\1\2*[\t ]*$|(?![\s\S]))/gmu,qa=/`([^`\n]+)`/gu,Ja=/\]\(\s*<?([^\s)>]+)>?(?:\s[^)]*)?\)/gu,Ya=/^ {0,3}\[[^\]]+\]:\s*<?([^\s>]+)>?/gmu,Xa=/^[a-z][\d+.a-z-]*:/iu;function Za(e){let[t=``]=e.split(/[#?]/u);try{return decodeURI(t)}catch{return t}}function Qa(e,t){return[...e.matchAll(t)].map(e=>e[1]??``)}const $a=E.fn(`readAgentReach`)(function*(e,t,n){let r=yield*R.FileSystem,i=yield*P.Path,a=new Set(t),o=new Map(yield*E.forEach(t,t=>f(i.join(e,t)).pipe(E.map(e=>[t,N.getOrElse(e,()=>``).replaceAll(Ka,``)])),{concurrency:`unbounded`})),s=e=>{let n=e.flatMap(e=>{let t=U.normalize(e);return t!==`.`&&!t.startsWith(`..`)?[t]:[]}),r=n.find(e=>a.has(e));if(r!==void 0)return[r];let i=n.find(e=>t.some(t=>U.dirname(t)===e));return i===void 0?[]:t.filter(e=>U.dirname(e)===i)},c=e=>{let t=(o.get(e)??``).replaceAll(qa,``);return[...Qa(t,Ja),...Qa(t,Ya)].flatMap(t=>{if(Xa.test(t)||t.startsWith(`#`))return[];let n=Za(t);return n.length===0?[]:[U.normalize(n.startsWith(`/`)?n.slice(1):U.join(U.dirname(e),n))]})},l=e=>[...c(e).flatMap(e=>s([e])),...Qa(o.get(e)??``,qa).flatMap(t=>s([U.join(U.dirname(e),t),t]))],u=new Set(n),d=[...n];for(let e=d.shift();e!==void 0;e=d.shift())for(let t of l(e))u.has(t)||(u.add(t),d.push(t));let p=t.flatMap(e=>c(e).filter(e=>Ga.test(e)&&!a.has(e)).map(t=>({file:e,target:t})));return{brokenLinks:yield*E.filter(p,t=>r.exists(i.join(e,t.target)).pipe(E.map(e=>!e),E.orElseSucceed(()=>!0)),{concurrency:`unbounded`}),unreached:t.filter(e=>!u.has(e))}}),eo=/^\{/mu,to=z.String.pipe(z.decodeTo(z.String,gt.transform({decode:e=>e.replaceAll(`\\`,`/`),encode:e=>e}))),no=z.Struct({diagnostics:z.Array(z.Struct({code:z.optional(z.String),filename:to,labels:z.Array(z.Struct({span:z.Struct({column:z.Int,line:z.Int})})),message:z.String})),number_of_files:z.Int}),ro=z.decodeUnknownOption(z.fromJsonString(no)),io=z.Array(z.Struct({scope:z.String,value:z.String})),ao=z.decodeUnknownOption(z.fromJsonString(io)),oo=z.Struct({rules:z.Record(z.String,z.Unknown)}),so=z.decodeUnknownOption(z.fromJsonString(oo)),co=ct.Reference(`adamantite/OxlintCommand`,{defaultValue:()=>et});function lo(e){let t=e.lastIndexOf(`/`);return t===-1?{name:e,plugin:`eslint`}:{name:e.slice(t+1),plugin:e.slice(0,t)}}function uo(e,t){return e===`${t.plugin}(${t.name})`}function fo(){return[j.env.NODE_OPTIONS,`--disable-warning=MODULE_TYPELESS_PACKAGE_JSON`].filter(Boolean).join(` `)}const po=E.fn(`runOxlint`)(function*(e,t,n=e){let r=yield*D.ChildProcessSpawner,i=(yield*co)(n),a=yield*r.spawn(dt.make(i.command,[...i.args,...t],{cwd:e,env:{...i.env,NODE_OPTIONS:fo()},extendEnv:!0,stdin:`ignore`})),[o,s,c]=yield*E.all([Dt.mkString(Dt.decodeText(a.stdout)),Dt.mkString(Dt.decodeText(a.stderr)),a.exitCode],{concurrency:`unbounded`});return{exitCode:c,output:`${o}${s}`.trim(),stdout:o}},E.scoped,E.catchReason(`PlatformError`,`NotFound`,()=>E.fail(new Ke({command:`node`})),(e,t)=>E.fail(new Ae({output:t.message}))));function mo(e){let t=e.search(eo);return t===-1?N.none():ro(e.slice(t))}const ho=E.fn(`lintFiles`)(function*(e,t){let{output:n,stdout:r}=yield*po(e,[`-f`,`json`,...t]),i=mo(r);return N.isNone(i)?yield*new Ae({output:n}):i.value}),go=E.fn(`listLintedFiles`)(function*(e,t=[]){let{exitCode:n,output:r,stdout:i}=yield*po(e,[`--debug=files`,...t]);return n===0?i.split(`
|
|
165
|
+
`).map(e=>e.trim().replaceAll(`\\`,`/`)).filter(e=>e.length>0):yield*new Ae({output:r})}),_o=E.fn(`resolveRule`)(function*(e,t){let n=yield*R.FileSystem,r=yield*P.Path,i=yield*n.makeTempDirectoryScoped({prefix:`adamantite-rules-`}),a=yield*po(i,[`--rules`,`-f`,`json`],t),o=ao(a.stdout);if(N.isNone(o))return yield*new Ae({output:a.output});let s=O.dedupe(o.value.map(e=>e.scope.replaceAll(`_`,`-`))),{name:c,plugin:l}=lo(e);yield*S(r.join(i,`.oxlintrc.json`),yield*ce({categories:{correctness:`off`},plugins:s,rules:{[e]:`error`}}));let u=yield*po(i,[`--print-config`],t),d=so(u.stdout).pipe(N.flatMap(e=>O.findFirst(Object.keys(e.rules),e=>lo(e).name===c)),N.map(e=>lo(e)));return N.match(d,{onNone:()=>({builtIn:!1,name:c,plugin:l}),onSome:e=>({builtIn:!0,name:e.name,plugin:e.plugin.replaceAll(`_`,`-`)})})},E.scoped),vo=Ot.nominal();function yo(e,t,n){return vo((e.relative(t,n)||`.`).split(e.sep).join(`/`))}const bo=E.fn(`listGitFiles`)(function*(e,t){let n=yield*(yield*D.ChildProcessSpawner).spawn(dt.make(`git`,[`ls-files`,`-z`,...t],{cwd:e,stderr:`ignore`,stdin:`ignore`})),[r,i]=yield*E.all([Dt.mkString(Dt.decodeText(n.stdout)),n.exitCode],{concurrency:`unbounded`}),a=L(r,pt.split(`\0`),O.filter(e=>pt.isNonEmpty(e)));return N.liftPredicate(a,()=>i===0)},E.scoped,E.orElseSucceed(()=>N.none()));function xo(e,t=[]){return bo(e,[`--cached`,`--others`,`--exclude-standard`,`--`,...t])}function So(e,t){return bo(e,[`--others`,`--ignored`,`--exclude-standard`,`--`,t,`:(exclude,glob)**/node_modules/**`])}var Co=class extends I.TaggedClass(`Current`){},wo=class extends I.TaggedClass(`Error`){};function To(e,t){let n=e.indexOf(`=`),r=n===-1?e:e.slice(0,n),i=N.liftPredicate(e.slice(n+1),()=>n!==-1),a=U.normalize(r.replaceAll(`\\`,`/`));return r.length===0||N.exists(i,e=>e.length===0)?E.fail(new Ye({reason:"Give a path, or `<path>=<file>`.",value:e})):U.isAbsolute(a)||Et.isAbsolute(a)||a===`..`||a.startsWith(`../`)||a===`.`?E.fail(new Ye({reason:`The path must be a file inside the project, relative to the project root.`,value:e})):E.succeed({expected:t,path:a,source:i})}function Eo(e){let t={files:e.files,...N.match(e.plugin,{onNone:()=>({}),onSome:e=>({plugins:[e]})}),rules:{[e.rule]:[`error`,...e.settingOptions]}};return["// `adamantite rule try` wrote this file in a copy of the project.",`import config from ${JSON.stringify(`./${e.config}`)}`,``,`export default {`,` ...config,`,` overrides: [...(config.overrides ?? []), ${JSON.stringify(t)}],`,`}`,``].join(`
|
|
166
|
+
`)}const Do=Ot.nominal(),Oo=E.fn(`replaceConfigs`)(function*(e,t){let n=yield*R.FileSystem,r=yield*P.Path;for(let[i,a]of t){let t=r.join(e,i),o=`oxlint.trial-base.config${r.extname(i)}`;yield*n.rename(t,r.join(r.dirname(t),o)),yield*S(t,a(o))}});function ko(e){return["// `adamantite harden` wrote this file in a copy of the project.",`import config from ${JSON.stringify(`./${e.config}`)}`,``,`const removals = new Map(${JSON.stringify([...e.removals])})`,``,`export default {`,` ...config,`,` overrides: (config.overrides ?? []).map((override, index) => ({`,` ...override,`,` rules: Object.fromEntries(`,` Object.entries(override.rules ?? {}).filter(`,` ([rule]) => !(removals.get(index) ?? []).includes(rule)`,` )`,` ),`,` })),`,`}`,``].join(`
|
|
167
|
+
`)}const Ao=E.fn(`makeProjectCopy`)(function*(e,t){let r=yield*R.FileSystem,i=yield*P.Path,a=yield*xo(e);if(N.isNone(a))return yield*new n({cwd:e});let o=yield*r.makeTempDirectoryScoped({prefix:`adamantite-trial-`}),s=O.dedupe(a.value.map(e=>i.dirname(i.join(o,e))));yield*E.forEach(s,e=>r.makeDirectory(e,{recursive:!0}),{concurrency:16,discard:!0}),yield*E.forEach(a.value,t=>r.copyFile(i.join(e,t),i.join(o,t)).pipe(E.catchReason(`PlatformError`,`NotFound`,()=>E.void)),{concurrency:16,discard:!0});let c=[e,...t.packageDirectories],l=yield*r.realPath(e),u=e=>{let t=i.relative(l,e);return N.liftPredicate(t,()=>t!==``&&t!==`..`&&!t.startsWith(`..${i.sep}`)&&!i.isAbsolute(t)&&!t.split(i.sep).includes(`node_modules`))},d=E.fnUntraced(function*(e){let t=yield*nt(e),n=yield*E.forEach(N.getOrElse(t,()=>[]).filter(e=>e!==`.cache`),E.fnUntraced(function*(t){let n=t.startsWith(`@`)&&!(yield*r.readLink(i.join(e,t)).pipe(E.as(!0),E.orElseSucceed(()=>!1)))?yield*nt(i.join(e,t)):N.none();return N.match(n,{onNone:()=>[t],onSome:e=>e.map(e=>`${t}/${e}`)})}),{concurrency:`unbounded`});return t.pipe(N.as(n.flat()))}),f=yield*E.forEach(c,E.fnUntraced(function*(t){let n=i.join(t,`node_modules`),a=i.join(o,i.relative(e,t),`node_modules`),s=yield*d(n);return N.isSome(s)&&(yield*r.makeDirectory(a,{recursive:!0})),yield*E.forEach(N.getOrElse(s,()=>[]),E.fnUntraced(function*(e){let t=i.join(n,e),s=(yield*r.realPath(t).pipe(E.option)).pipe(N.flatMap(e=>u(e)));return yield*r.makeDirectory(i.dirname(i.join(a,e)),{recursive:!0}),yield*r.symlink(N.match(s,{onNone:()=>t,onSome:e=>i.join(o,e)}),i.join(a,e)),s}),{concurrency:1})}),{concurrency:1}),p=yield*E.forEach(O.dedupe(O.getSomes(f.flat())),t=>So(e,t.split(i.sep).join(`/`)).pipe(E.map(e=>N.getOrElse(e,()=>[]))),{concurrency:`unbounded`});return yield*E.forEach(O.dedupe(p.flat()),t=>r.makeDirectory(i.dirname(i.join(o,t)),{recursive:!0}).pipe(E.andThen(r.copyFile(i.join(e,t),i.join(o,t)))),{concurrency:16,discard:!0}),Do(o)},E.catchTag(`PlatformError`,e=>E.fail(new Ze({cause:e})))),jo=E.fn(`findConfig`)(function*(e,t){let n=yield*P.Path,r=[];for(let i=n.dirname(n.join(e,t));i===e||i.startsWith(`${e}${n.sep}`);i=n.dirname(i))r.push(...Ii.map(e=>n.join(i,e)));return yield*E.findFirst(r,e=>g(e))});function Mo(e){let t=[];for(let n of e){let e=t.find(e=>e.every(e=>e.case.path!==n.case.path));e===void 0?t.push([n]):e.push(n)}return t}const No=E.fn(`tryRule`)(function*(e){let t=yield*R.FileSystem,n=yield*P.Path,{cases:i,cwd:a,rule:o,setting:c,workspace:u}=e,{name:d,plugin:f}=lo(o),p=yield*_o(o,a),m=yield*Ao(a,u),h=e=>n.relative(m,e).split(n.sep).join(`/`),g=e=>{let t=[`Rule '${d}' not found in plugin '${f}'`,`Plugin '${f}' not found`].find(t=>F.isTagged(e,`TrialLintFailed`)&&e.output.includes(t));return c instanceof wo&&t!==void 0?new Oe({detail:t,rule:o}):e},_=yield*E.forEach(i,E.fnUntraced(function*(e){if(N.isNone(e.source)&&!(yield*t.exists(n.join(m,e.path))))return yield*new Ye({reason:(yield*t.exists(n.join(a,e.path)))?"Git ignores this file, so the copy of the project does not have it. Use `<path>=<file>` to lint its content.":"The project has no such file. Use `<path>=<file>` to lint other content.",value:e.path});let r=yield*jo(m,e.path);return N.isNone(r)?yield*new te({path:e.path}):{case:e,config:r.value,configFile:n.relative(n.dirname(r.value),n.join(m,e.path)).split(n.sep).join(`/`)}}),{concurrency:1});c instanceof wo&&(yield*Oo(m,new Map(O.dedupe(_.map(e=>e.config)).map(e=>[n.relative(m,e),t=>Eo({config:t,files:O.dedupe(_.filter(t=>t.config===e).map(e=>e.configFile)),plugin:N.liftPredicate(p.plugin,e=>p.builtIn&&e!==`eslint`),rule:o,settingOptions:c.options})]))));let v=/* @__PURE__ */ new Map;for(let e of Mo(_)){let i=e.flatMap(e=>N.match(e.case.source,{onNone:()=>[],onSome:t=>[{source:n.resolve(a,t),target:n.join(m,e.case.path)}]})),o=yield*E.forEach(i,({target:e})=>t.readFileString(e).pipe(E.option),{concurrency:`unbounded`});for(let{source:e,target:a}of i)yield*t.makeDirectory(n.dirname(a),{recursive:!0}),yield*S(a,yield*r(e));let c=e.map(e=>e.case.path),u=yield*ho(m,c).pipe(E.mapError(e=>g(e)));if(u.number_of_files<c.length){let e=new Set(yield*go(m,c));return yield*new l({path:c.find(t=>!e.has(t))??c[0]??``})}yield*E.forEach(i,({target:e},n)=>N.match(o[n]??N.none(),{onNone:()=>t.remove(e),onSome:n=>t.writeFileString(e,n)}),{concurrency:1,discard:!0});for(let t of e){let e=u.diagnostics.filter(e=>e.filename===t.case.path),n=e.filter(e=>e.code===void 0);if(n.length>0)return yield*new s({errors:n.map(e=>e.message),path:t.case.path});v.set(t.case,{case:t.case,config:h(t.config),diagnostics:e.filter(e=>e.code!==void 0&&uo(e.code,p)).map(e=>({column:e.labels[0]?.span.column??1,line:e.labels[0]?.span.line??1,message:e.message}))})}}return O.getSomes(i.map(e=>N.fromUndefinedOr(v.get(e))))},E.scoped,E.catchTag(`PlatformError`,e=>E.fail(new Ze({cause:e}))));var Po=class extends I.TaggedClass(`Linted`){},Fo=class extends I.TaggedClass(`Failed`){};const Io=/[!*?[\]{}]/u;function Lo(e){return e===null?null:e.type===`Literal`&&F.isString(e.value)?e.value:e.type===`TemplateLiteral`&&e.expressions.length===0?e.quasis[0]?.value.cooked??null:null}function Ro(e){return e.computed?null:e.key.type===`Identifier`?e.key.name:e.key.type===`Literal`&&F.isString(e.key.value)?e.key.value:null}function zo(e,t){let n=e.properties.find(e=>e.type===`Property`&&Ro(e)===t);return n?.type===`Property`?n.value:void 0}function Bo(e){if(e.type===`ArrayExpression`){let[t]=e.elements;return t!=null&&t.type!==`SpreadElement`&&Bo(t)}return e.type===`Literal`&&(e.value===`off`||e.value===`allow`||e.value===0)}function Vo(e){let[t]=e.body.flatMap(e=>e.type===`ExportDefaultDeclaration`?[e]:[]);if(t===void 0)return;let n=t=>{if(t.type===`ObjectExpression`)return t;if(t.type===`CallExpression`){let[e]=t.arguments;return e!==void 0&&e.type!==`SpreadElement`?n(e):void 0}if(t.type===`Identifier`){let r=e.body.flatMap(e=>e.type===`VariableDeclaration`?e.declarations:e.type===`ExportNamedDeclaration`&&e.declaration?.type===`VariableDeclaration`?e.declaration.declarations:[]).find(e=>e.id.type===`Identifier`&&e.id.name===t.name);return r?.init?n(r.init):void 0}if(t.type===`TSAsExpression`||t.type===`TSSatisfiesExpression`)return n(t.expression)},r=t.declaration;return r.type===`ObjectExpression`||r.type===`CallExpression`||r.type===`Identifier`||r.type===`TSAsExpression`||r.type===`TSSatisfiesExpression`?n(r):void 0}function Ho(e,t){let{errors:n,program:r}=bt(e,t,{sourceType:`module`});if(n.length>0)return[];let i=Vo(r),a=i===void 0?void 0:zo(i,`overrides`);if(a?.type!==`ArrayExpression`)return[];let o=a.elements.findIndex(e=>e?.type===`SpreadElement`);return(o===-1?a.elements:a.elements.slice(0,o)).flatMap((e,t)=>{if(e?.type!==`ObjectExpression`)return[];let n=zo(e,`files`),r=zo(e,`rules`);if(n?.type!==`ArrayExpression`||r?.type!==`ObjectExpression`)return[];let i=n.elements.map(e=>Lo(e)),a=r.properties.flatMap(e=>{let t=e.type===`Property`?Ro(e):null;return e.type===`Property`&&t!==null&&Bo(e.value)?[t]:[]});return i.every(e=>e!==null)&&a.length>0?[{files:i,index:t,rules:a}]:[]})}const Uo=E.fn(`readOverrides`)(function*(e,t,n,i){let a=yield*P.Path,o=e=>i===null||i===`.`||e===i||e.startsWith(`${i}/`),s=(t,n)=>a.relative(e,a.join(e,a.dirname(t),n)).split(a.sep).join(`/`),c=(yield*E.forEach(n,t=>r(a.join(e,t)).pipe(E.map(e=>({config:t,overrides:Ho(t,e)}))),{concurrency:`unbounded`})).flatMap(({config:e,overrides:t})=>t.flatMap(t=>t.rules.map(n=>({config:e,globs:t.files.filter(e=>Io.test(e)),index:t.index,literals:t.files.filter(e=>!Io.test(e)).map(t=>s(e,t)).filter(e=>o(e)),rule:n})))),l=new Set(yield*E.filter(O.dedupe(c.flatMap(e=>e.literals)),t=>g(a.join(e,t)),{concurrency:`unbounded`})),u=c.filter(e=>e.literals.some(e=>l.has(e))),d=/* @__PURE__ */ new Map;if(u.length>0){let n=new Map(yield*E.forEach(O.dedupe(u.map(e=>e.rule)),t=>_o(t,e).pipe(E.map(e=>[t,e])),{concurrency:`unbounded`})),r=yield*Ao(e,t);yield*Oo(r,new Map(O.dedupe(u.map(e=>e.config)).map(e=>{let t=/* @__PURE__ */ new Map;for(let n of u.filter(t=>t.config===e))t.set(n.index,[...t.get(n.index)??[],n.rule]);return[e,e=>ko({config:e,removals:t})]})));let i=O.dedupe(u.flatMap(e=>e.literals)).filter(e=>l.has(e)),a=yield*ho(r,i),o=new Set(a.number_of_files<i.length?yield*go(r,i):i),s=new Set(a.diagnostics.filter(e=>e.code===void 0).map(e=>e.filename));for(let e of u){let t=n.get(e.rule);for(let n of e.literals.filter(e=>l.has(e))){let r=a.diagnostics.some(e=>e.filename===n&&e.code!==void 0&&t!==void 0&&uo(e.code,t)),i=o.has(n)?s.has(n)?`unparsable`:r?`breaks`:`clean`:`ignored`;d.set(`${e.rule}\0${n}`,i)}}}return new Po({rules:c.filter(e=>e.literals.length>0||e.globs.length>0).map(e=>({config:e.config,files:e.literals.map(t=>({file:t,mark:d.get(`${e.rule}\0${t}`)??`missing`})),globs:e.globs,rule:e.rule}))})},E.scoped,E.catch(e=>E.succeed(new Fo({reason:e.message})))),Wo=`Custom rules`,Go=`AGENTS.md`;function Ko(e){let t=e.split(`/`);return!t.includes(`.changeset`)&&t.at(-1)!==`CHANGELOG.md`}function qo(e,t,n,r){let i=(t,n)=>{let r=e.relative(t,n);return r!==`..`&&!r.startsWith(`..${e.sep}`)&&!e.isAbsolute(r)},a=B.mapInput(B.flip(B.Number),e=>e.length),o=[t,...n.packageDirectories],s=o.filter(e=>i(r,e)),c=O.sort(o.filter(e=>i(e,r)),a).slice(0,1),l=s.length>0?s:c;return{contains:i,isSelectedFile:n=>{let[r=t]=O.sort(o.filter(r=>i(r,e.join(t,n))),a);return r===t||l.includes(r)},packageDirectories:o,selectedPackages:l}}const Jo=E.fn(`readScopedDocumentation`)(function*(e,t,n){let r=yield*P.Path,{contains:i,isSelectedFile:a}=qo(r,e,t,n),o=t=>{let a=r.dirname(r.join(e,t));return i(a,n)||i(n,a)},s=yield*E.transposeOption((yield*xo(e,[`*.md`,`*.mdx`,`*.mdc`])).pipe(N.map(t=>E.forEach(t.filter(e=>Ko(e)),t=>g(r.join(e,t)).pipe(E.map(e=>e?[t]:[])),{concurrency:`unbounded`}).pipe(E.map(e=>e.flat())))));return{agentReach:(yield*E.transposeOption(s.pipe(N.map(t=>$a(e,t,t.filter(e=>r.basename(e)===Go&&o(e))))))).pipe(N.map(e=>({brokenLinks:e.brokenLinks.filter(e=>a(e.file)),unreached:e.unreached.filter(e=>a(e))}))),documentationFiles:s.pipe(N.map(e=>e.filter(e=>a(e))))}}),Yo=E.fn(`readHardenReach`)(function*(e,t,n=e){return(yield*Jo(e,t,n)).agentReach}),Xo=E.fn(`readHardenContext`)(function*(e,t,n=e){let r=yield*P.Path,i=t=>r.relative(e,t)||`.`,{packageDirectories:a,selectedPackages:o}=qo(r,e,t,n),s=[.../* @__PURE__ */ new Set([e,...o])].map(e=>r.join(e,Go)),[{calls:c,configs:l,unresolvedCalls:u},d,f]=yield*E.all([Ui(a,o),E.filter(s,e=>g(e),{concurrency:`unbounded`}),Jo(e,t,n)],{concurrency:`unbounded`});return{agentReach:f.agentReach,configs:l.map(t=>yo(r,e,t)),documentationFiles:f.documentationFiles,instructionFiles:d.map(e=>i(e)),rulesFolders:[...new Set(c.map(e=>i(e.dir)))],scope:n===e?null:yo(r,e,n),unresolvedCalls:[...new Set(u.map(e=>i(e)))]}}),Zo=/^[\w./-]+$/u;function Qo(e){return Zo.test(e)?e:`'${e.replaceAll(`'`,`'\\''`)}'`}function $o(e,t){return e.length===0?t:e.map(e=>`- \`${e}\``).join(`
|
|
168
|
+
`)}function es(e){return[e.unreached.length===0?"Links and code spans from each `AGENTS.md` reach each Markdown file.":`No chain of links or code spans from an \`AGENTS.md\` reaches these Markdown files:\n\n${$o(e.unreached,``)}`,...e.brokenLinks.length===0?[]:[`These links go to Markdown files that do not exist:\n\n${e.brokenLinks.map(e=>`- \`${e.file}\` links to \`${e.target}\``).join(`
|
|
169
|
+
`)}`]].join(`
|
|
170
|
+
|
|
171
|
+
`)}function ts(e){return e.rulesFolders.length===0&&e.unresolvedCalls.length===0?`No \`custom()\` call loads a rules folder. Before you write the first custom rule, add \`custom()\` from \`adamantite/rules\` to the \`extends\` of the Oxlint config. It loads \`${K}\` by default.`:[...e.rulesFolders.map(e=>`- \`${e}\``),...e.unresolvedCalls.map(e=>`- A \`custom()\` call in \`${e}\` whose \`dir\` is not a string literal. Read the config to find its rules folder.`)].join(`
|
|
172
|
+
`)}function ns(e){return N.match(e,{onNone:()=>'Adamantite could not count the comments that turn a rule off, because Oxlint could not list the files that it lints. Count them yourself, for example with `rg -n "(oxlint|eslint)-disable"`, and leave out the files that the config ignores.',onSome:e=>e.length===0?"No `oxlint-disable` or `eslint-disable` comment turns a rule off.":["Adamantite counted the `oxlint-disable` and `eslint-disable` comments of each rule in the files that Oxlint lints. Oxlint obeys both. A comment that names no rule turns off all rules.",``,...e.map(({locations:e,rule:t})=>{let n=N.match(t,{onNone:()=>`All rules`,onSome:e=>`\`${e}\``}),r=e.slice(0,5).map(e=>`\`${e}\``).join(`, `),i=e.length>5?`, and ${e.length-5} more`:``;return`- ${n}: ${e.length} ${e.length===1?`comment`:`comments`}, in ${r}${i}`})].join(`
|
|
173
|
+
`)})}const rs={breaks:`still breaks the rule`,clean:`no longer breaks the rule`,ignored:`the config ignores it, so Oxlint did not lint it`,missing:`does not exist`,unparsable:`does not parse, so Oxlint did not lint it`};function is(e){return e instanceof Fo?[`Adamantite could not lint the files of the overrides that turn a rule off:`,``,"```text",e.reason,"```",``,`For each file in an override that turns a rule off, read the file and find the code that the rule reports.`].join(`
|
|
174
|
+
`):e.rules.length===0?`No override in the Oxlint config turns a rule off for files that it names.`:[`Adamantite turned each rule on again in a copy of the project, and linted each file that an override names and turns the rule off for. Paths are relative to the project root. An override that code builds, such as a spread, is not in this list.`,``,...e.rules.map(({config:e,files:t,globs:n,rule:r})=>[`- \`${r}\` in \`${e}\`:`,...t.map(({file:e,mark:t})=>` - \`${e}\`: ${rs[t]}`),...n.map(e=>` - \`${e}\`: a glob, so Adamantite did not lint its files`)].join(`
|
|
175
|
+
`))].join(`
|
|
176
|
+
`)}function as(e,{adamantiteVersion:t,commits:n,overrides:r,suppressions:i}){let a=Qo(e.scope??`.`);return Rr(`# Adamantite harden
|
|
177
|
+
|
|
178
|
+
Find the coding standards that this target project already follows. Propose the highest step of the enforcement ladder that can enforce each standard. The project uses Adamantite {{version}}.
|
|
179
|
+
|
|
180
|
+
Steps 1 to 8 are read-only for the target project. Keep trial case files outside the project and use stdin for RuleTester cases. Change project files only in step 9, for the candidates that the user approves.
|
|
181
|
+
|
|
182
|
+
## Context
|
|
183
|
+
|
|
184
|
+
{{scope}}
|
|
185
|
+
|
|
186
|
+
### Oxlint config
|
|
187
|
+
|
|
188
|
+
{{configs}}
|
|
189
|
+
|
|
190
|
+
### Rules folders
|
|
191
|
+
|
|
192
|
+
{{rulesFolders}}
|
|
193
|
+
|
|
194
|
+
### Instructions
|
|
195
|
+
|
|
196
|
+
{{instructionFiles}}
|
|
197
|
+
|
|
198
|
+
### Documentation
|
|
199
|
+
|
|
200
|
+
These are the Markdown files of the project, without the changesets and the changelogs.
|
|
201
|
+
|
|
202
|
+
{{documentationFiles}}
|
|
203
|
+
|
|
204
|
+
### Agent reach
|
|
205
|
+
|
|
206
|
+
{{agentReach}}
|
|
207
|
+
|
|
208
|
+
### Suppressions
|
|
209
|
+
|
|
210
|
+
{{suppressions}}
|
|
211
|
+
|
|
212
|
+
### Overrides that turn a rule off
|
|
213
|
+
|
|
214
|
+
{{overrides}}
|
|
215
|
+
|
|
216
|
+
## 1. Explore the documentation
|
|
217
|
+
|
|
218
|
+
Start with each \`AGENTS.md\` above, then read each file in the documentation list. Follow the files that the instructions link to or tell agents to read, including files absent from the list. Read the comments in the Oxlint config. Read a linked file outside \`--path\`, but keep the code survey inside the selected scope. Read each file once.
|
|
219
|
+
|
|
220
|
+
Mark each file as "has standards" or "no standards". A file that states a standard, and that the agent reach above lists as not reached, is a **discovery gap**: an agent that starts from \`AGENTS.md\` never finds its standards. Record the file, its standards, and the \`AGENTS.md\` that should point to it. Each link to a Markdown file that does not exist is a discovery gap too. Record the file that the link must go to.
|
|
221
|
+
|
|
222
|
+
This step is done when each file in the documentation list, and each file that the instructions link to, has its mark.
|
|
223
|
+
|
|
224
|
+
## 2. List the written standards
|
|
225
|
+
|
|
226
|
+
List each standard that a file marked "has standards" states, with its file and line. Each written standard is a candidate, and goes on to step 5, also when the code breaks it in many places.
|
|
227
|
+
|
|
228
|
+
Continue when every written standard has a source location and a candidate entry.
|
|
229
|
+
|
|
230
|
+
## 3. Survey the code
|
|
231
|
+
|
|
232
|
+
Survey these areas: file names and placement, import direction, naming, API use, error handling, and test layout. In each area, find the patterns that the code follows and that no instruction states.
|
|
233
|
+
|
|
234
|
+
- A pattern is a candidate when the code follows it in several places and has few counterexamples. List each counterexample with its file and line.
|
|
235
|
+
- Give the scope of each count as globs, and the command that gives the count, such as an \`rg\` command. Count source, tests, and generated code apart.
|
|
236
|
+
- If the GitHub CLI \`gh\` is available and authenticated, read the review comments of recent merged pull requests. A correction that reviewers repeat is evidence of a standard. If reviews are unavailable, record that limit and use the documentation, code, and local history.
|
|
237
|
+
- A construct that the code never uses is not a standard by itself. It needs an instruction, a review comment, or a commit that states it.
|
|
238
|
+
- Read the git history of the Oxlint config, for example with \`git log -p -- oxlint.config.ts\`. A rule that a commit removed is a **decision** that the maintainer already made, not a candidate.
|
|
239
|
+
|
|
240
|
+
This step is done when each area has its candidates or the note "none found".
|
|
241
|
+
|
|
242
|
+
## 4. Read the fix history
|
|
243
|
+
|
|
244
|
+
A mistake that a commit fixed, and that other code repeats, is a standard that a rule can hold. Run this command from the project root, and read the commits that it lists. When the history has fewer commits, read all of them, and say how many you read.
|
|
245
|
+
|
|
246
|
+
{{fixHistoryCommand}}
|
|
247
|
+
|
|
248
|
+
- Find the commits that fix a mistake: a bug fix, a revert, or a correction after a review. Read the diff of each one with \`git show <commit>\`.
|
|
249
|
+
- Name the mistake in one sentence, in terms of the code, such as "an \`await\` in a \`forEach\` callback" or "a date that the code parses without a time zone". Skip the fixes of logic that only one place has.
|
|
250
|
+
- Find the commit that added the mistake, for example with \`git log -L\` or \`git blame <commit>^ -- <file>\`. Record it with the fix.
|
|
251
|
+
- A mistake is a candidate when two or more fixes have it, or when one fix has it and the code still has the same form in other places. List each fix with its commit, and each other place with its file and line.
|
|
252
|
+
- The code before the fix is the case that the rule must report, and the code after the fix is the case that it must accept. Read the code before the fix with \`git show <commit>^:<file>\`.
|
|
253
|
+
|
|
254
|
+
If Git or the required history is unavailable, record the missing source and continue with the documentation and code candidates. Do not infer commit evidence.
|
|
255
|
+
|
|
256
|
+
This step is done when each fix has its mark: "candidate", "one-off", or "not a code mistake", or the missing history is recorded.
|
|
257
|
+
|
|
258
|
+
## 5. Drop what a tool already enforces
|
|
259
|
+
|
|
260
|
+
For each written standard from step 2 and each candidate from steps 3 and 4, find out whether a tool already enforces it. Read the Oxlint config, the presets and plugins that it extends, its overrides, the custom rules, \`tsconfig.json\`, and the checks that the project runs in CI.
|
|
261
|
+
|
|
262
|
+
- To see whether the config reports a case, or to try a rule that is not on, or a rule with other options, run \`adamantite rule try\`. It lints the cases in a copy of the project, so the project stays unchanged.
|
|
263
|
+
- \`adamantite rule try <rule> --current --report <case>\` shows what the config reports now. Use a counterexample from step 3 or 4 as the case.
|
|
264
|
+
- \`adamantite rule try <rule> [--options '<json array>'] --report <case> --accept <case>\` tries a new rule or new options. The options are the items that come after the severity.
|
|
265
|
+
|
|
266
|
+
A case is a project path, such as \`src/cart.ts\`, or \`<path>=<file>\` to lint the content of \`<file>\` at \`<path>\`, such as \`src/cart.ts=/tmp/before.ts\`. Write the case files outside the project. Exit 2 means that the trial is not evidence: read its reason.
|
|
267
|
+
|
|
268
|
+
- A report from a rule that only the trial turns on is not enforcement: the rule is a proposal for step 7.
|
|
269
|
+
- When no counterexample exists, mark the enforcement as not confirmed.
|
|
270
|
+
- Drop each candidate that a tool enforces fully. When a tool enforces only part of a written standard, keep the other part as a candidate.
|
|
271
|
+
|
|
272
|
+
This step is done when each written standard and each candidate is marked as enforced, partly enforced, not enforced, or not confirmed, with the rule or the lint output as evidence.
|
|
273
|
+
|
|
274
|
+
## 6. Find the gaps in the existing rules
|
|
275
|
+
|
|
276
|
+
Step 5 starts from the standards. This step starts from the rules that the project already has: each custom rule, each \`adamantite/layers\` map, each \`adamantite/import-owners\` option, and each \`no-restricted-imports\` setting and its overrides.
|
|
277
|
+
|
|
278
|
+
- **Forms that a rule misses:** list the forms of the same mistake that the rule does not report. For an import rule, check \`require()\`, \`import()\`, \`export … from\`, \`import type\`, and the path aliases of \`tsconfig.json\`. For a custom rule, read its logic and check the other syntax of the same mistake, such as a call through a variable, optional chaining, a computed member, or a re-export. Search the code for each form, and lint a file that has it. When the code does not have the form yet, run \`adamantite rule try <rule> --current --report <control> --report <missed form>\`, with a form that the rule reports as the control. The gap is confirmed when it reports the control and does not report the missed form. When no trial can show it, mark the gap as not confirmed: the temporary regression case of step 9 confirms it.
|
|
279
|
+
- **Files that a rule misses:** for each \`files\` glob of an override, list the files that the standard applies to and that the glob does not match, such as a new folder or another file extension.
|
|
280
|
+
- **Verification cases:** for each existing custom rule, prepare temporary valid and invalid cases for the forms above. Verify them with RuleTester from stdin. Do not write files in this step. Preserve user-owned saved rule tests.
|
|
281
|
+
- **Overrides that can shrink:** each file that the overrides above mark "no longer breaks the rule" or "does not exist" is a candidate: remove it from the override. A file that Oxlint did not lint, because the config ignores it or it does not parse, is not evidence. Check it yourself.
|
|
282
|
+
- **Suppressions:** read the counts in the suppressions above. Many suppressions of one rule are a **decision**: the rule is too wide, or the standard has exceptions that the rule must know.
|
|
283
|
+
|
|
284
|
+
Each gap is a candidate on the step of the rule that it extends: a wider custom rule, a new option, a new test case, a wider glob, or a smaller override. A gap that is not confirmed is a candidate too: show it with the mark "not confirmed". A gap in a rule that a preset or plugin ships, and that no option of the rule can close, is not a candidate: list it under **Decisions** as a report for the maintainers of that package.
|
|
285
|
+
|
|
286
|
+
This step is done when each rule has its gaps or the note "none found".
|
|
287
|
+
|
|
288
|
+
## 7. Place each candidate on the enforcement ladder
|
|
289
|
+
|
|
290
|
+
Put each remaining candidate on the highest step that works:
|
|
291
|
+
|
|
292
|
+
1. **Type or structure:** a type, a schema, a module boundary, or a stricter TypeScript option makes the mistake impossible.
|
|
293
|
+
2. **Preset rule:** a rule in an Oxlint preset or plugin that the project can turn on, or an option of a rule that is already on. A native rule, such as a file-name rule, comes before a custom rule that checks the same thing.
|
|
294
|
+
3. **Import rule:** \`adamantite/layers\` for one-way imports between the folders of a root, \`adamantite/import-owners\` for a package that only one file or folder imports, or \`no-restricted-imports\` with an override for the files that the standard applies to. In Oxlint, a later override replaces the options of a rule that an earlier override set for the same files. Write one combined \`no-restricted-imports\` for each set of files, with the paths of the existing overrides.
|
|
295
|
+
4. **Project check:** a check that the project already runs, such as Turbo boundaries, Knip, or a script that reads \`package.json\`.
|
|
296
|
+
5. **Custom rule:** a rule in the rules folder that checks the AST.
|
|
297
|
+
6. **Instruction:** a line in \`CODING_STANDARDS.md\`, only when no tool can check the standard.
|
|
298
|
+
|
|
299
|
+
For each rule, give one case that the rule must report and one similar case that it must accept. For a candidate from step 4, use the code before and after one of its fixes. Say what the rule guarantees and what it does not, such as "bans named exports, but does not require a default export". When the rule checks only part of the standard, say which part stays an instruction.
|
|
300
|
+
|
|
301
|
+
A candidate that needs a choice from the maintainer before a rule is useful is a decision, not a candidate. Examples are two documents that state a policy differently, and a migration that changes how the code behaves. Put it in the Decisions list of step 8, and propose no rule for it.
|
|
302
|
+
|
|
303
|
+
Continue when every remaining candidate has a proposed step, evidence, limits, and cases, or is recorded as a decision.
|
|
304
|
+
|
|
305
|
+
## 8. Show the candidates and wait for approval
|
|
306
|
+
|
|
307
|
+
If a tool or source was unavailable, name it on the first line of the report and state the fallback you used. Mark unverified evidence before scoring candidates.
|
|
308
|
+
|
|
309
|
+
Score each candidate from 1 to 5:
|
|
310
|
+
|
|
311
|
+
- **5:** a real standard, with correct counts, that no tool enforces, on the right step, with a precise rule. The maintainer can approve it as it is.
|
|
312
|
+
- **4:** real and useful, with one small problem, such as a count that is not exact.
|
|
313
|
+
- **3:** real but of low value.
|
|
314
|
+
- **2:** mostly enforced already, wrong evidence, or many false positives.
|
|
315
|
+
- **1:** not a standard.
|
|
316
|
+
|
|
317
|
+
Show the candidates with a score of 4 or 5, from the highest score to the lowest. Show each one with:
|
|
318
|
+
|
|
319
|
+
- the standard in one sentence
|
|
320
|
+
- its source: the instruction file and line, the code only, or the fix commits
|
|
321
|
+
- the number of places that follow it, its scope, and the counterexamples
|
|
322
|
+
- its step on the ladder, and the rule, option, or instruction that you propose
|
|
323
|
+
- the case that the rule must report, and the case that it must accept
|
|
324
|
+
- the part of the standard that stays an instruction, if a part stays
|
|
325
|
+
- the existing code that the new rule would report
|
|
326
|
+
|
|
327
|
+
Then show three short lists:
|
|
328
|
+
|
|
329
|
+
- **Decisions:** each written standard that the code does not follow, each rule that a commit removed, each choice from step 7, each rule with many suppressions, and each gap in a shipped rule that no option can close. Give the instruction, the code, and the choice that the maintainer must make.
|
|
330
|
+
- **Discovery gaps:** the gaps from step 1. Propose a pointer only for the standards that stay instructions, because a rule replaces the instruction that a pointer would lead to. For a broken link, propose the correct target.
|
|
331
|
+
- **Also considered:** the candidates with a score of 3 or lower, one line for each, with the reason.
|
|
332
|
+
|
|
333
|
+
When no human can approve, for example in CI or in an unattended session, report the candidates and stop after this step.
|
|
334
|
+
|
|
335
|
+
Otherwise, put the approval question last in the report, with no text after it. Ask the user which named candidates to write. Wait until the user names the candidates to write or approves none. If the user approves none, stop without changing project files.
|
|
336
|
+
|
|
337
|
+
## 9. Write the approved standards
|
|
338
|
+
|
|
339
|
+
Write only the approved candidates:
|
|
340
|
+
|
|
341
|
+
- **Type, structure, preset rule, import rule, or project check:** change the types, the Oxlint config, \`tsconfig.json\`, or the check.
|
|
342
|
+
- **Custom rule:** read \`skills/adamantite/SKILL.md\` in the installed \`adamantite\` package. Follow its "{{customRulesSection}}" section and linked guide to write, verify, and clean up the approved rule. Run \`adamantite rule add <name>\`. When the rules folder above is not \`.adamantite/lint\`, pass it with \`--dir\`. A comment at the top of the rule file states the standard and why it exists.
|
|
343
|
+
- **Gap in a custom rule:** create a temporary regression case first, and use RuleTester to see it fail. Follow the custom-rule guide above until all valid and invalid cases pass and cleanup is complete.
|
|
344
|
+
- **Gap in the config of a rule,** such as a layer map, an import-owners option, a \`no-restricted-imports\` path, or an override glob: change the Oxlint config. Then lint a file that has the missed form, and read the report. When no file has the form, tell the user that the change is not verified. Do not change a rule that a preset or plugin ships.
|
|
345
|
+
- **Override that can shrink:** remove only the files that no longer break the rule.
|
|
346
|
+
- **Instruction that became a rule:** delete the instruction of each standard that a rule now checks. The rule is the only source of the standard. When the rule checks only part of the standard, keep the other part as the instruction.
|
|
347
|
+
- **Existing violations:** keep the code that a new rule reports as it is, and list the violations for the user. Keep the rule at \`error\`, and add an \`overrides\` entry to the Oxlint config that turns the rule off only in the files that break it now, such as \`{ files: ["src/legacy/cart.ts"], rules: { "project/no-foo": "off" } }\`. Do not set the rule to \`warn\`: \`adamantite check\` fails on warnings. New files must follow the rule. A separate change fixes the violations and removes each file from the override.
|
|
348
|
+
- **Instruction:** write each approved standard that no tool can check to \`CODING_STANDARDS.md\`, one line for each standard. When no \`AGENTS.md\` points to \`CODING_STANDARDS.md\`, add the pointer to the root \`AGENTS.md\`.
|
|
349
|
+
- **Discovery gap:** add each approved pointer to the \`AGENTS.md\` that the gap names, or to a file that it reaches, as a Markdown link. Fix each approved broken link.
|
|
350
|
+
|
|
351
|
+
Continue when every approved candidate is implemented and each changed custom rule has passed the guide's verification and cleanup checks.
|
|
352
|
+
|
|
353
|
+
## Verify
|
|
354
|
+
|
|
355
|
+
Run \`adamantite check\` and \`adamantite doctor\` in this order, through the project's package runner. Both must exit 0. When you changed a project check, also run that check with the project's own command, from the folder where CI runs it. Read the output of every check.
|
|
356
|
+
|
|
357
|
+
When a new rule makes \`check\` fail, fix the rule or add the file to the override as step 9 says, not a disable comment. Do not add saved rule tests or CI steps unless the user requests them. Preserve user-owned tests and CI steps.
|
|
358
|
+
|
|
359
|
+
When you changed the documentation, run \`adamantite harden\` again without a terminal and read its agent reach. Do not restart this procedure. Each discovery gap that you closed must be gone, and no link that you added may go to a file that does not exist.
|
|
360
|
+
|
|
361
|
+
Continue when the required checks pass, the approved discovery gaps are closed, and no temporary verification cases, fixtures, or verification-only helpers remain. If a check is blocked, record its command and reason instead of claiming completion.
|
|
362
|
+
|
|
363
|
+
## Report the result
|
|
364
|
+
|
|
365
|
+
Use the missing-source report format from step 8. Report the approved candidates implemented, changed files, verification cases and results, commands run, and remaining violations or decisions. State whether temporary verification files were removed. Keep unverified results separate from successful checks.
|
|
366
|
+
|
|
367
|
+
The report is complete when each approved candidate has a verified result or an explicit blocker. Use this report only after approval and implementation. Before approval, use the proposal and closing question in step 8.
|
|
368
|
+
|
|
369
|
+
## Check the result
|
|
370
|
+
|
|
371
|
+
- Every project change implements an approved candidate and stays inside the selected scope.
|
|
372
|
+
- Each new or changed custom rule passed valid and invalid cases, including a regression case for a bug fix.
|
|
373
|
+
- Temporary verification files are removed, and user-owned tests and CI steps remain.
|
|
374
|
+
- Project checks and Doctor pass, or the report names each blocked check and remaining finding.
|
|
375
|
+
- Approved discovery gaps are closed, and added documentation links resolve.
|
|
376
|
+
`,{agentReach:N.match(e.agentReach,{onNone:()=>"Git could not list the files, so agent reach is unavailable. Follow the links from each `AGENTS.md` and record the files you checked. Report this fallback with the missing sources.",onSome:e=>es(e)}),configs:$o(e.configs,"No Oxlint config was found. When you show the candidates, tell the user to run `adamantite init` before step 9."),customRulesSection:Wo,documentationFiles:N.match(e.documentationFiles,{onNone:()=>`Git could not list project files. Find Markdown files with a file search, excluding dependencies, build output, changesets, and changelogs. Record the search scope and report this fallback with the missing sources.`,onSome:e=>$o(e,`The project has no Markdown file.`)}),fixHistoryCommand:`\`git log -n ${n} --no-merges --format="%h %s" -- ${a}\``,instructionFiles:$o(e.instructionFiles,"No `AGENTS.md` was found. Each file that states a standard is a discovery gap, and the root `AGENTS.md` must point to it."),overrides:is(r),rulesFolders:ts(e),scope:e.scope===null?`Adamantite found these files in the project and its workspace packages. Paths are relative to the project root.`:`Adamantite found these files for \`${e.scope}\`, the folder that \`--path\` selects. Survey only the code in this folder. Paths are relative to the project root.`,suppressions:ns(i),version:t})}const os=/\.[cm]?[jt]sx?$/u,ss=/^\s*(?:oxlint|eslint)-disable(?:-next-line|-line)?(?:\s(?<rules>[\s\S]*))?$/u,cs=/\s--[\s\S]*$/u;function ls(e,t){let{comments:n,errors:r}=bt(e,t);return r.length>0?[]:n.flatMap(e=>{let n=ss.exec(e.value);if(n===null)return[];let r=(n.groups?.rules??``).replace(cs,``).split(`,`).map(e=>e.trim()).filter(e=>e.length>0);return[{line:t.slice(0,e.start).split(`
|
|
377
|
+
`).length,rules:r}]})}const us=E.fn(`readSuppressions`)(function*(e,t){let n=yield*P.Path,r=yield*go(e).pipe(E.option),i=e=>t===null||t===`.`||e.startsWith(`${t}/`);return yield*E.transposeOption(r.pipe(N.map(t=>E.gen(function*(){let r=yield*E.forEach(t.filter(e=>os.test(e)&&i(e)),t=>f(n.join(e,t)).pipe(E.map(e=>N.match(e,{onNone:()=>[],onSome:e=>e.includes(`-disable`)?ls(t,e).flatMap(({line:e,rules:n})=>(n.length===0?[void 0]:n).map(n=>({location:`${t}:${e}`,rule:N.fromUndefinedOr(n)}))):[]}))),{concurrency:16}),a=O.groupBy(r.flat(),e=>N.getOrElse(e.rule,()=>``));return O.sort(Object.values(a).map(e=>({locations:e.map(e=>e.location),rule:e[0].rule})),B.combine(B.mapInput(B.flip(B.Number),e=>e.locations.length),B.mapInput(B.String,e=>N.getOrElse(e.rule,()=>``))))}))))}),ds=`0.46.0`,{$match:fs,BrokenLink:ps,CheckFailed:ms,Findings:hs}=I.taggedEnum();function gs(e){return`${e.file}\0${e.target}`}const _s=E.fn(`readInstalledVersion`)(function*(e){let t=yield*P.Path,n=yield*(yield*Ne).resolve(e,G(`./lint`));if(N.isNone(n))return N.none();for(let e=t.dirname(n.value);e!==t.dirname(e);e=t.dirname(e)){let t=yield*u(e).pipe(E.option);if(N.isSome(t)&&t.value.name===`adamantite`)return N.fromUndefinedOr(t.value.version)}return N.none()}),vs=M.Directory(`path`,{mustExist:!0}).pipe(M.optional,M.withDescription(`Limit the session to a project folder or workspace package. The path is relative to the current directory`)),ys=M.Int(`commits`).pipe(M.withSchema(z.Int.pipe(z.check(z.isGreaterThan(0,{message:"`--commits` must be a positive number"})))),M.withDefault(200),M.withDescription(`Set how many recent commits the agent reads to find past fixes`)),bs=E.fn(`preparePrompt`)(function*(e,t,n){let r=yield*re(e),i=yield*Xo(e,r,t),[a,o]=yield*E.all([Uo(e,r,i.configs,i.scope),us(e,i.scope)],{concurrency:`unbounded`});return{agentReach:i.agentReach,prompt:as(i,{adamantiteVersion:ds,commits:n,overrides:a,suppressions:o})}});var xs=k.make(`harden`,{commits:ys,scope:vs}).pipe(k.withDescription(`Ask a coding agent to turn project standards into custom rules and instructions`),k.withHandler(({commits:t,scope:n})=>E.gen(function*(){let r=j.cwd(),i=yield*R.FileSystem,a=yield*P.Path,o=yield*$,s=yield*(yield*pa).isInteractive;s&&(yield*o.intro(`💠 adamantite harden`));let c=yield*u(r),l=c.name===`adamantite`;if(!l&&!c.devDependencies?.adamantite&&!c.dependencies?.adamantite)return yield*new e({command:`harden`});let d=l?N.fromUndefinedOr(c.version):yield*_s(r);if(N.isNone(d))return yield*new ne({command:`harden`});if(d.value!==ds)return yield*new ye({command:`harden`,installed:d.value,running:ds});let f=N.isSome(n)?yield*i.realPath(a.resolve(r,n.value)).pipe(E.mapError(e=>new Je({cause:e,path:n.value}))):void 0;if(f!==void 0){let e=a.relative(r,f);if(e===`..`||e.startsWith(`..${a.sep}`)||a.isAbsolute(e))return yield*new oe({cwd:r,scope:f})}let{agentReach:p,prompt:m}=yield*bs(r,f,t);if(!s){yield*o.message(m);return}let h=yield*Da({command:`Harden`,cwd:r,message:`How do you want to harden this project?`,prompt:m,subject:`the prompt`});if(!(h instanceof Ca)){yield*o.outro(`Harden ended without an agent session.`);return}let{agent:g}=h,_=yield*Dr({cwd:r}).pipe(E.as([]),E.catchTags({CliNotFound:e=>o.log.error(e.message).pipe(E.as([ms()])),CommandFailed:()=>E.succeed([ms()])})),v=yield*fa(r),[ee,y]=yield*E.all([Yo(r,v.workspace,f),ca(v)],{concurrency:`unbounded`}),te=new Set(N.match(p,{onNone:()=>[],onSome:e=>e.brokenLinks.map(e=>gs(e))})),b=N.match(ee,{onNone:()=>[],onSome:e=>e.brokenLinks.filter(e=>!te.has(gs(e)))}),x=[..._,...y.findings.length>0?[hs({findings:y.findings})]:[],...b.map(e=>ps({link:e}))];for(let e of y.warnings)yield*o.log.warning(e);if(yield*E.forEach(x,fs({BrokenLink:({link:e})=>o.log.error(`\`${e.file}\` links to \`${e.target}\`, which does not exist, after the ${g.name} session.`),CheckFailed:()=>o.log.error(`\`adamantite check\` failed after the ${g.name} session.`),Findings:({findings:e})=>o.log.warning(`Doctor found issues after the ${g.name} session.`).pipe(E.andThen(ha(e)))}),{discard:!0}),x.length>0)return yield*o.outro(`⚠️ Harden verification failed.`),yield*new Ie({command:`harden`,exitCode:D.ExitCode(1)});yield*o.log.success(`\`adamantite check\` and Doctor pass after the ${g.name} session.`),yield*o.outro(`✅ Harden checks passed.`)}).pipe(E.catchTag([`AdamantiteNotInstalled`,`AdamantiteNotInNodeModules`,`AdamantiteVersionMismatch`,`ScopeOutsideProject`],e=>E.gen(function*(){let t=yield*$;return(yield*(yield*pa).isInteractive)?(yield*t.log.warning(e.message),yield*t.outro(`⚠️ Harden did not start.`)):yield*t.message(e.message),yield*new Ie({command:`harden`,exitCode:D.ExitCode(1)})})),E.catchTag(`OperationCancelled`,()=>E.gen(function*(){return yield*(yield*$).cancel(`Harden was cancelled.`),yield*new Ie({command:`harden`,exitCode:D.ExitCode(1)})})))));const Ss=' .o8 . o8o . \n "888 .o8 `"\' .o8 \n .oooo. .oooo888 .oooo. ooo. .oo. .oo. .oooo. ooo. .oo. .o888oo oooo .o888oo .ooooo. \n`P )88b d88\' `888 `P )88b `888P"Y88bP"Y88b `P )88b `888P"Y88b 888 `888 888 d88\' `88b \n .oP"888 888 888 .oP"888 888 888 888 .oP"888 888 888 888 888 888 888ooo888 \nd8( 888 888 888 d8( 888 888 888 888 d8( 888 888 888 888 . 888 888 . 888 .o \n`Y888""8o `Y8bod88P" `Y888""8o o888o o888o o888o `Y888""8o o888o o888o "888" o888o "888" `Y8bod8P\' \n \n \n ',Cs=E.gen(function*(){let e=yield*(yield*kt.Terminal).columns,t=Ss.split(`
|
|
378
|
+
`).reduce((e,t)=>Math.max(e,t.trim().length),0);!e||e<t||(yield*ut.info(Ss))}),ws=[`vscode`,`zed`],Ts={vscode:`VS Code / Cursor / Windsurf`,zed:`Zed`},Es=E.fn(`validateInitOptions`)(function*(e,t){let n={agents:e.agents,editors:O.dedupe(e.editors),githubActions:e.githubActions,installExtensions:e.installExtensions,overwriteScripts:e.overwriteScripts,presets:O.dedupe(e.presets),scripts:O.dedupe(e.scripts),typescript:e.typescript};if(n.scripts.length===0)return yield*new T({reason:"Select at least one script with `--script <name>`."});let r=y(n.scripts,`oxlint`);if(n.presets.length>0&&!r)return yield*new T({reason:"`--preset` requires the `check` or `fix` script."});let i=O.head(_e(n.presets));if(N.isSome(i)){let{required:e,requiredBy:t}=i.value;return yield*new T({reason:`\`--preset ${t}\` requires \`--preset ${e}\`.`})}return n.typescript&&!r?yield*new T({reason:"`--typescript` requires the `check` or `fix` script."}):n.installExtensions&&n.editors.length===0?yield*new T({reason:"`--install-extensions` requires at least one `--editor`."}):n.githubActions&&!Vr(n.scripts)?yield*new T({reason:"`--github-actions` requires --script check or --script analyze."}):n.githubActions&&!o(t)?yield*new T({reason:`\`--github-actions\` does not support the detected package manager \`${t}\`. Use ${_(`disjunction`)}.`}):{agents:n.agents,editors:O.isReadonlyArrayNonEmpty(n.editors)?N.some({installExtensions:n.installExtensions,names:n.editors}):N.none(),githubActions:n.githubActions?N.liftPredicate(t,o):N.none(),lint:r?N.some({presets:n.presets,typescript:n.typescript}):N.none(),overwriteScripts:n.overwriteScripts,scripts:n.scripts}}),Ds=M.Boolean(Y.nonInteractive).pipe(M.withDefault(!1),M.withDescription(`Configure without prompts. Select at least one --script`)),Os=M.Literals(Y.script,ae).pipe(M.atMost(ae.length),M.withDescription(`Add a package script. Repeat --script to add more. Required with --non-interactive`)),ks=M.Literals(Y.preset,he).pipe(M.atMost(he.length),M.withDescription(`Select an Oxlint preset. Repeat --preset to add more. Requires --script check or --script fix`)),As=M.Literals(Y.editor,ws).pipe(M.atMost(ws.length),M.withDescription(`Configure an editor. Repeat --editor to add more`)),js=M.Boolean(`typescript`).pipe(M.withDefault(!1),M.withDescription(`Use the TypeScript preset. Requires --script check or --script fix`)),Ms=M.Boolean(`install-extensions`).pipe(M.withDefault(!1),M.withDescription(`Install recommended editor extensions. Select at least one --editor`)),Ns=M.Boolean(`github-actions`).pipe(M.withDefault(!1),M.withDescription(`Add a GitHub Actions workflow. Requires --script check or --script analyze and ${_(`disjunction`)}`)),Ps={agents:M.Boolean(Y.agents).pipe(M.withDefault(!1),M.withDescription(`Add Adamantite guidance to AGENTS.md and the Adamantite skill to the skill folders of your coding agents`)),editors:As,githubActions:Ns,installExtensions:Ms,nonInteractive:Ds,overwriteScripts:M.Boolean(`overwrite-scripts`).pipe(M.withDefault(!1),M.withDescription(`Replace existing package scripts that conflict with Adamantite's managed commands`)),presets:ks,scripts:Os,typescript:js},Fs=e=>`\`${e.script}\` runs \`${e.command}\`. Adamantite would replace it with \`${Xe[e.script]}\`.`,Is=E.gen(function*(){let e=yield*$,t=yield*e.multiselect({message:`Which presets should Adamantite use with the core preset?`,options:be.map(e=>({hint:qe(e),label:e.label,value:e.name})),required:!1}),n=_e(t);for(let{required:t,requiredBy:r}of n)yield*e.log.info(`Added the \`${t}\` preset, which \`${r}\` requires.`);return[...n.map(({required:e})=>e),...t]}),Ls=E.fn(`collectInteractiveInitOptions`)(function*(e,t,n){let r=yield*$,i=yield*r.multiselect({message:"Which scripts should Adamantite add to `package.json`?",options:[{hint:`recommended`,label:`check - find formatting, lint, and type errors`,value:`check`},{hint:`recommended`,label:`fix - apply safe lint fixes and format code`,value:`fix`},{label:t?`analyze - find unused code and check monorepo consistency`:`analyze - find unused dependencies, exports, and files`,value:`analyze`}]}),a=yield*u(e),s=ke(a,i);for(let e of s)yield*r.log.warning(Fs(e));let c=s.length>0?yield*r.confirm({initialValue:!1,message:s.length===1?`Replace this script with Adamantite's command?`:`Replace these scripts with Adamantite's commands?`}):!1,l=y(i,`oxlint`),d=l?yield*Is:[],f=l?yield*r.confirm({initialValue:!0,message:t?`Show how to use the TypeScript preset in each workspace package?`:`Use the Adamantite TypeScript preset?`}):!1,p=yield*r.multiselect({message:`Which editors should Adamantite configure?`,options:ws.map(e=>({label:Ts[e],value:e})),required:!1}),m=p.length>0?yield*r.confirm({initialValue:!0,message:`Install the recommended editor extensions?`}):!1,h=o(n),g=c?[]:s.map(e=>e.script),v=i.filter(e=>!g.includes(e));Vr(v)&&!h&&(yield*r.log.info(`Adamantite cannot generate a GitHub Actions workflow for \`${n}\`. It supports ${_(`conjunction`)}.`));let ee=Vr(v)&&h?yield*r.confirm({message:`Add a GitHub Actions workflow to run the selected checks?`}):!1;return{agents:yield*r.confirm({initialValue:!0,message:`Teach coding agents to use Adamantite? This adds an AGENTS.md section and the Adamantite skill.`}),editors:p,githubActions:ee,installExtensions:m,overwriteScripts:c,presets:d,scripts:i,typescript:f}}),Rs=`adamantite`,zs={"SKILL.md":`---
|
|
379
|
+
name: adamantite
|
|
380
|
+
description: Use when setting up Adamantite, running its checks, repairing Doctor findings, updating managed dependencies, hardening coding standards, or writing and testing custom rules.
|
|
381
|
+
metadata:
|
|
382
|
+
type: core
|
|
383
|
+
library: adamantite
|
|
384
|
+
library_version: "0.45.0"
|
|
385
|
+
sources:
|
|
386
|
+
- "adelrodriguez/adamantite:src/cli.ts"
|
|
387
|
+
- "adelrodriguez/adamantite:src/commands/**/*.ts"
|
|
388
|
+
- "adelrodriguez/adamantite:src/lib/execution/skill.ts"
|
|
389
|
+
- "adelrodriguez/adamantite:src/lib/toolchain/index.ts"
|
|
390
|
+
- "adelrodriguez/adamantite:src/lib/integrations/tooling/oxlint/plugins/**/*.ts"
|
|
391
|
+
- "adelrodriguez/adamantite:src/lib/integrations/tooling/knip/config.ts"
|
|
392
|
+
- "adelrodriguez/adamantite:src/lib/workspace/custom-rules/*"
|
|
393
|
+
- "adelrodriguez/adamantite:presets/lint/*.ts"
|
|
394
|
+
- "adelrodriguez/adamantite:presets/rules/*.ts"
|
|
395
|
+
---
|
|
396
|
+
|
|
397
|
+
# Adamantite
|
|
398
|
+
|
|
399
|
+
Use Adamantite to maintain the code-quality tools of a target project, the project that
|
|
400
|
+
Adamantite configures or checks.
|
|
401
|
+
|
|
402
|
+
## Select the task
|
|
403
|
+
|
|
404
|
+
Read the target project's instructions and package scripts. Run commands from its root
|
|
405
|
+
with its package manager and installed Adamantite version. Use \`adamantite <command> --help\`
|
|
406
|
+
to check options that the task needs.
|
|
407
|
+
|
|
408
|
+
Use the section below that matches the request. Read a linked guide only when that case
|
|
409
|
+
applies. Continue when you have identified the target project, command, and requested scope.
|
|
410
|
+
|
|
411
|
+
## Set up a target project
|
|
412
|
+
|
|
413
|
+
For a new installation, follow [How to set up Adamantite](references/setup.md).
|
|
414
|
+
Use Doctor for drift in an existing installation. A code-quality failure belongs in the
|
|
415
|
+
checks below, rather than another initialization.
|
|
416
|
+
|
|
417
|
+
Setup is complete when the selected scripts run and Doctor reports no findings.
|
|
418
|
+
|
|
419
|
+
## Check and fix code
|
|
420
|
+
|
|
421
|
+
Use the project's managed scripts when they exist. Otherwise, run the CLI through the
|
|
422
|
+
project's package manager:
|
|
423
|
+
|
|
424
|
+
- Run \`adamantite check\` for read-only formatting, lint, and type checks. Fix warnings
|
|
425
|
+
instead of adding \`--allow-warnings\` to pass the check.
|
|
426
|
+
- Run \`adamantite fix\` for safe lint fixes and formatting. Review the effect and get explicit
|
|
427
|
+
permission before using \`--suggested\`, \`--dangerous\`, or \`--all\`.
|
|
428
|
+
- Run \`adamantite analyze\` for unused files, exports, and dependencies. In a monorepo it
|
|
429
|
+
runs Sherif before Knip. Inspect the findings before using \`--fix\`, which can remove files.
|
|
430
|
+
|
|
431
|
+
To repair preset rule reports or change their configuration, follow
|
|
432
|
+
[How to repair preset rule reports](references/lint-rules.md).
|
|
433
|
+
|
|
434
|
+
Pass underlying tool arguments after \`--\`. For \`check\` and \`fix\`, they go to Oxlint unless
|
|
435
|
+
\`--only\` selects another stage. For \`analyze\`, they go to Knip unless \`--only\` selects
|
|
436
|
+
Sherif. For example, use \`adamantite analyze --only monorepo -- --select highest\`.
|
|
437
|
+
When a package manager consumes a separator, add another, as in
|
|
438
|
+
\`npm run analyze -- -- --directory packages/app\`.
|
|
439
|
+
|
|
440
|
+
If Sherif needs a version choice without a terminal, set \`sherif.select\` to \`"highest"\`
|
|
441
|
+
in the root \`package.json\`, or pass \`--select highest\` to the monorepo stage.
|
|
442
|
+
Keep permanent Sherif settings in that \`sherif\` object, with camelCase option names.
|
|
443
|
+
Sherif refuses fixes when \`CI\` is set. Use \`analyze --only unused --fix\` to run only Knip fixes there.
|
|
444
|
+
|
|
445
|
+
The task is complete when the affected checks exit 0 and you have read their output.
|
|
446
|
+
|
|
447
|
+
## Repair managed setup
|
|
448
|
+
|
|
449
|
+
Run \`adamantite doctor\`. It assesses managed integrations without changing files.
|
|
450
|
+
Without a terminal, it prints a Markdown repair prompt and exits 1 when findings remain.
|
|
451
|
+
Follow each finding's current state, goal, reference, and verification command.
|
|
452
|
+
For old layer-map declarations, use the migration step in
|
|
453
|
+
[Configure layer maps and import owners](references/lint-rules.md#configure-layer-maps-and-import-owners).
|
|
454
|
+
For a finding about the previous custom-rules API, use the migration step in
|
|
455
|
+
[How to write and verify custom rules](references/custom-rules.md#repair-an-existing-rules-folder).
|
|
456
|
+
|
|
457
|
+
Run Doctor again after the repair. This step is complete when Doctor exits 0 with no
|
|
458
|
+
findings. Report assessment warnings separately, because warnings alone also exit 0.
|
|
459
|
+
|
|
460
|
+
## Update managed dependencies
|
|
461
|
+
|
|
462
|
+
Run \`adamantite update\`. It updates managed dependencies and refreshes stale skill copies
|
|
463
|
+
that \`init\` installed from the package. It reports remaining setup findings but can exit 0
|
|
464
|
+
with findings still present.
|
|
465
|
+
|
|
466
|
+
Follow the repair step above. The update is complete when Doctor reports no findings and
|
|
467
|
+
the project's checks pass.
|
|
468
|
+
|
|
469
|
+
## Harden coding standards
|
|
470
|
+
|
|
471
|
+
Run \`adamantite harden\` and follow its Markdown prompt. Use \`--path\` to limit the scope
|
|
472
|
+
when the request covers one package or folder. Show the candidate standards and wait for
|
|
473
|
+
the user's approval before writing. If no human can approve, report the candidates and stop.
|
|
474
|
+
|
|
475
|
+
For rule trials that the prompt requests, follow the trial step in
|
|
476
|
+
[How to repair preset rule reports](references/lint-rules.md#try-a-rule-setting).
|
|
477
|
+
For approved custom rules, follow [How to write and verify custom rules](references/custom-rules.md).
|
|
478
|
+
|
|
479
|
+
A non-interactive \`harden\` run only prints the prompt. Its exit code does not verify the
|
|
480
|
+
work. Hardening is complete when the approved standards are enforced, the checks pass,
|
|
481
|
+
and Doctor reports no findings.
|
|
482
|
+
|
|
483
|
+
## Custom rules
|
|
484
|
+
|
|
485
|
+
To add, change, verify, or save tests for a project-owned rule, follow
|
|
486
|
+
[How to write and verify custom rules](references/custom-rules.md).
|
|
487
|
+
|
|
488
|
+
The task is complete when the guide's verification and cleanup checks pass.
|
|
489
|
+
|
|
490
|
+
## Report the result
|
|
491
|
+
|
|
492
|
+
If a required tool or source was unavailable, name it on the first line and state what you
|
|
493
|
+
used instead. Report the changes, commands run, results, and remaining findings or warnings.
|
|
494
|
+
For a custom rule, include the cases tested and whether you removed temporary verification files.
|
|
495
|
+
|
|
496
|
+
The report is complete when every result has command output or an inspected artifact as evidence.
|
|
497
|
+
|
|
498
|
+
## Check the result
|
|
499
|
+
|
|
500
|
+
- The selected command matches the requested task and scope.
|
|
501
|
+
- The affected checks passed, or the report names the checks that remain unverified.
|
|
502
|
+
- Doctor findings and assessment warnings are reported separately.
|
|
503
|
+
- Every new or changed custom rule passed verification, and temporary cases are removed.
|
|
504
|
+
`,"references/custom-rules.md":'# How to write and verify custom rules\n\n## Select the rules folder\n\nUse a custom rule for a recurring project coding standard that existing rules cannot check.\nKeep it in the target project. A first-party preset change is a different task.\n\nFind the `custom()` call imported from `adamantite/rules` in the project\'s Oxlint configuration.\nIt loads `.adamantite/lint` by default, relative to the file that calls it, and enables each\nrule as `error` under `project`. Thus `no-process-env.ts` becomes `project/no-process-env`.\nUse `dir` for another folder. In a monorepo, give each rules folder its own plugin `name`,\nbecause Oxlint rejects duplicate plugin names in one run. A nested Oxlint config replaces\nthe root config. Extend the root config when the package needs its rules.\n\nContinue when you have identified the loaded rules folder and its plugin name.\n\n## Repair an existing rules folder\n\nIf Doctor reports the previous API, replace `adamantite/lint/custom` with the default import\nfrom `adamantite/rules`. Move authoring imports to `adamantite/rules/plugin`.\nMove the old default folder to `.adamantite/lint`, or set its path with `dir`.\nPreserve rule behavior, plugin names, severity, and options.\n\nContinue when Doctor reports no custom-rule wiring findings.\n\n## Write the rule\n\nFor a new rule, run `adamantite rule add <name>`. It writes only a stub.\nUse `adamantite rule ast <file>` on real code to find the node types that visitors receive.\n\nApply these authoring constraints:\n\n- Export the rule as default with `defineRule` from `adamantite/rules/plugin`.\n Import `Context`, `Rule`, `Visitor`, and `ESTree` types from that module when needed.\n- Use `createOnce`, which runs once for the lint run. Reset per-file state in `before` and\n report collected results in `after`. Read `context.filename`, `context.sourceCode`, and\n `context.settings` in `before` or a visitor. They are unavailable in the `createOnce` body.\n- Write erasable TypeScript. Replace an `enum` with a plain object, for example.\n Node.js type stripping cannot load enums, namespaces with values, parameter properties,\n or `import x = require()`.\n- Use the AST and `context.sourceCode`. Custom rules receive no type information.\n- Report with a `messageId` defined in `meta.messages`. State what the author must do\n instead and link the coding standard. Define options in `meta.schema` and read `context.options`.\n- Keep substantial logic in plain functions in a `_<name>.ts` helper when that makes the\n rule clearer. Files that start with `_`, declaration files, and `.test.*` files are not rules.\n Subfolders are not loaded.\n\nContinue when the rule implements the standard and every report gives a repair.\n\n## Verify the rule\n\nUse `RuleTester` from `adamantite/rules/testing` with Node.js, also in a Bun project.\nPut code that must report in `invalid` and similar code that must pass in `valid`.\nCover the syntax forms and file paths to which the standard applies.\nFor a bug fix, first run a regression case and confirm that it fails. Fix the rule and rerun\nall cases. Change a case only when it is wrong, and explain the change.\n\nRun temporary cases from stdin or a temporary file beside the rule. For the generated\n`no-debugger` stub, this command checks the report and an accepted TypeScript declaration:\n\n```sh\nnode --input-type=module <<\'JS\'\nimport { RuleTester } from "adamantite/rules/testing"\nimport rule from "./.adamantite/lint/no-debugger.ts"\n\nnew RuleTester({ languageOptions: { parserOptions: { lang: "ts" } } }).run("no-debugger", rule, {\n invalid: [{ code: "debugger", errors: [{ messageId: "unexpected" }] }],\n valid: ["const value: number = 1"],\n})\nJS\n```\n\nAdapt the cases to the completed rule. Verify a helper directly only when its cases are too\nmany for RuleTester. During harden, use `adamantite rule test add <name>` to prepare temporary\ncases, adapt them, and run `adamantite rule test --path <test-file>`.\nIf a saved test already exists, preserve it and use stdin for additional temporary cases.\n\nRun lint and read all output. A rule that throws can print an error for every file while\nOxlint still exits 0. Restart the editor language server after changing a rule, because\nOxlint caches rules for each run.\n\nContinue when every valid and invalid case passes and lint output contains no rule errors.\n\n## Keep saved tests when requested\n\nIf the user requests new saved tests, run `adamantite rule test add <name>` and adapt its\nvalid and invalid cases. Use `--dir` for another rules folder or `--path` for another test location.\nKeep `.test.ts` for tests beside rules, so the plugin does not load them as rules.\nRun saved tests with `adamantite rule test`, or `adamantite rule test --path <file>` for a test elsewhere.\n\nSaved tests use `node:test`. Exclude them from Vitest `test.exclude` or Jest\n`testPathIgnorePatterns`, while keeping the runner\'s default and existing exclusions.\nInit, CI generation, and harden do not run saved tests by default. Preserve existing test\nfiles and CI steps. Add new CI test steps only when requested.\n\nContinue when the saved tests pass and the project\'s other test runners do not collect them.\n\n## Check project integration\n\nIf TypeScript must check the rules folder, add `.adamantite/lint` to tsconfig `include`.\nTypeScript skips the dot folder by default. Enable `allowImportingTsExtensions` when checking\ntests that import `.ts` rule files.\n\nKnip treats rules and optional `.test.*` files in `.adamantite/lint` as entry files in the\nroot and workspace packages. For another folder, keep the preset\'s entry patterns and add\nthe folder\'s rule and test patterns to `oxlint.entry` in `knip.config.ts`.\nAdd tests saved elsewhere to the Knip entry settings if needed.\n\nRemove temporary cases, fixtures, and verification-only helpers that you created.\nKeep the rule, its runtime helpers, required configuration, and user-owned saved tests.\nRun `adamantite check` and `adamantite doctor`.\n\nContinue when both commands pass and no temporary verification files remain.\n\n## Check the rule\n\n- Every valid and invalid case passes, including the regression case for a bug fix.\n- Lint output contains no rule errors, regardless of its exit code.\n- Doctor reports no findings, and the project\'s checks pass.\n- Temporary verification files are removed, and user-owned tests and CI steps remain.\n',"references/lint-rules.md":`# How to repair preset rule reports
|
|
505
|
+
|
|
506
|
+
## Repair the reported code
|
|
507
|
+
|
|
508
|
+
Read the rule message and apply the section below that matches it.
|
|
509
|
+
|
|
510
|
+
- For \`adamantite/no-react-state-hooks\`, follow the message's replacement for the hook.
|
|
511
|
+
Moving the call into a hook module only to silence the report leaves the problem in place.
|
|
512
|
+
Set \`allow\` only when the project's hook layout differs from the default.
|
|
513
|
+
- For \`adamantite/no-overzealous-destructuring\`, keep the object and read its members, or split
|
|
514
|
+
the pattern. Raising \`maxDepth\` or \`maxProperties\` only to pass the check hides the problem.
|
|
515
|
+
- For \`adamantite/require-suppression-reason\`, first try to fix the code. If a suppression is
|
|
516
|
+
necessary, state why the rule does not apply after \`--\`. Naming the rule or adding a single
|
|
517
|
+
\`-\` gives no reason. For example, use
|
|
518
|
+
\`// oxlint-disable-next-line no-console -- the CLI writes its report to stdout\`.
|
|
519
|
+
- For \`no-warning-comments\`, fix the code or track the work in the project's issue tracker.
|
|
520
|
+
Renaming \`TODO\` to another marker only to pass the check leaves the work untracked.
|
|
521
|
+
- For \`adamantite/query-from-loader\` reports on \`useQuery\` or \`useSuspenseQuery\`, replace a
|
|
522
|
+
plain options object or a local \`queryOptions()\` call with shared options. Define them with
|
|
523
|
+
\`queryOptions()\` at module scope or in an exported factory. Preload them with
|
|
524
|
+
\`ensureQueryData()\` in the loader and pass the same options to the hook. For reports on
|
|
525
|
+
\`useInfiniteQuery\` or \`useSuspenseInfiniteQuery\`, use \`infiniteQueryOptions()\` with
|
|
526
|
+
\`ensureInfiniteQueryData()\`. Wrapping options in a spread or moving the hook out of the route
|
|
527
|
+
only to silence the report leaves the preload problem unresolved.
|
|
528
|
+
- For \`adamantite/no-query-data-in-state\`, read query data from the query result and keep
|
|
529
|
+
only the user's edits in state.
|
|
530
|
+
- For \`effecttsgo/unstable-api-usage\`, add a deliberately accepted module or package to
|
|
531
|
+
\`allowedUnstableApis\` in the \`@effect/language-service\` tsconfig entry. For example, list
|
|
532
|
+
\`"effect/cli"\` to allow that module instead of disabling the rule for every unstable API.
|
|
533
|
+
|
|
534
|
+
Continue when the reported code follows the rule's repair and the affected lint check passes.
|
|
535
|
+
|
|
536
|
+
## Configure layer maps and import owners
|
|
537
|
+
|
|
538
|
+
If the task changes import rules, use the first-party plugin loaded by \`architecture\` or
|
|
539
|
+
\`strict\`. The \`architecture\` preset enables no rules until the project configures them.
|
|
540
|
+
|
|
541
|
+
Set \`adamantite/layers\` with a layer map. Give each layer an \`imports\` list of sibling
|
|
542
|
+
layers. Imports are transitive. Put a child map in the containing layer's \`layers\` property:
|
|
543
|
+
|
|
544
|
+
\`\`\`ts
|
|
545
|
+
import architecture from "adamantite/lint/architecture"
|
|
546
|
+
import { defineConfig } from "oxlint"
|
|
547
|
+
|
|
548
|
+
export default defineConfig({
|
|
549
|
+
extends: [architecture],
|
|
550
|
+
rules: {
|
|
551
|
+
"adamantite/layers": [
|
|
552
|
+
"error",
|
|
553
|
+
{
|
|
554
|
+
root: "src",
|
|
555
|
+
layers: {
|
|
556
|
+
lib: {
|
|
557
|
+
imports: [],
|
|
558
|
+
layers: {
|
|
559
|
+
shared: { imports: [] },
|
|
560
|
+
services: { imports: ["shared"] },
|
|
561
|
+
},
|
|
562
|
+
},
|
|
563
|
+
terminal: { imports: ["lib"] },
|
|
564
|
+
commands: { imports: ["terminal"] },
|
|
565
|
+
},
|
|
566
|
+
},
|
|
567
|
+
],
|
|
568
|
+
},
|
|
569
|
+
})
|
|
570
|
+
\`\`\`
|
|
571
|
+
|
|
572
|
+
Resolve \`root\` from the nearest \`package.json\` folder. The \`lib\` child map has the root
|
|
573
|
+
\`src/lib\`, and its dependency names are local to that map. Every containing map checks a
|
|
574
|
+
file independently. A child permission cannot override a parent prohibition. Declaration
|
|
575
|
+
order does not change permissions.
|
|
576
|
+
|
|
577
|
+
Use \`entries\` for composition files, \`isolate\` for layers whose child folders cannot import
|
|
578
|
+
each other, and \`ignoreTypes\` when type-only imports do not count. Add import \`conditions\`
|
|
579
|
+
explicitly when resolution needs them. The rule does not read tsconfig \`customConditions\`.
|
|
580
|
+
An unresolved import is not checked. A folder missing from the map is reported. Move a
|
|
581
|
+
loose root file into a layer or declare it as an entry.
|
|
582
|
+
|
|
583
|
+
Place child settings beside the child's \`layers\`. Settings do not inherit. A parent's
|
|
584
|
+
\`ignore\`, \`entries\`, or \`ignoreTypes\` does not skip child checks. A child root uses the
|
|
585
|
+
parent's actual matched folder, including when the top root is a glob. Declare each
|
|
586
|
+
concrete scope once. Keep separate option objects for roots that cannot nest without a
|
|
587
|
+
new intermediate map.
|
|
588
|
+
|
|
589
|
+
If the config uses the previous array-valued declarations, run \`adamantite doctor\` and
|
|
590
|
+
follow its migration instructions. Preserve every dependency and map setting. Nest only
|
|
591
|
+
existing compatible child scopes. Verify allowed and forbidden imports with
|
|
592
|
+
\`adamantite check\`, then run Doctor again. Continue when the migrated maps preserve the
|
|
593
|
+
project's intended imports and Doctor reports no layer-map migration finding.
|
|
594
|
+
|
|
595
|
+
For an import that belongs to one file or folder, set \`adamantite/import-owners\`:
|
|
596
|
+
|
|
597
|
+
\`\`\`ts
|
|
598
|
+
import architecture from "adamantite/lint/architecture"
|
|
599
|
+
import { defineConfig } from "oxlint"
|
|
600
|
+
|
|
601
|
+
export default defineConfig({
|
|
602
|
+
extends: [architecture],
|
|
603
|
+
rules: {
|
|
604
|
+
"adamantite/import-owners": [
|
|
605
|
+
"error",
|
|
606
|
+
{ import: "giget", owners: ["src/services/download.ts"] },
|
|
607
|
+
{ import: "react-native", names: ["Alert"], owners: ["src/shared/alerts.ts"] },
|
|
608
|
+
{ import: "#lib/database.ts", owners: ["src/lib/repositories"] },
|
|
609
|
+
],
|
|
610
|
+
},
|
|
611
|
+
})
|
|
612
|
+
\`\`\`
|
|
613
|
+
|
|
614
|
+
Resolve owners from the workspace root, or the \`package.json\` folder outside a workspace.
|
|
615
|
+
An owner folder covers every file below it. A package name covers its subpaths.
|
|
616
|
+
Use \`names\` to restrict selected exports. Namespace imports and \`export *\` are also reported
|
|
617
|
+
when names are restricted. An \`import\` that starts with \`#\`, \`.\`, or \`/\` names a file or folder of
|
|
618
|
+
the project, resolved from the same root as the owners. The rule resolves each import of a linted
|
|
619
|
+
file, so a relative path or another alias to that module counts too. An import that names a \`#\`
|
|
620
|
+
module as the option states it also counts, as for a package. In a monorepo, a \`#\` option restricts
|
|
621
|
+
that alias in every package. To restrict a folder of one package, name its path from the workspace
|
|
622
|
+
root, such as \`./apps/web/src/lib/db\`. Use layer maps for the dependencies between folders.
|
|
623
|
+
|
|
624
|
+
Repair a report by using what the owner exports or moving the code to its layer or owner.
|
|
625
|
+
Adding an owner, layer dependency, or \`ignore\` glob only to pass the check weakens the standard.
|
|
626
|
+
Continue when the configured maps and owners match the project's intended imports.
|
|
627
|
+
|
|
628
|
+
## Change test rule configuration
|
|
629
|
+
|
|
630
|
+
If a Jest or Vitest preset needs different test paths or rule settings, replace its entry in
|
|
631
|
+
\`extends\` with a project override. Use the preset's exported \`testFiles\`, or the project's
|
|
632
|
+
test paths, with its \`plugins\` and \`rules\`. For example:
|
|
633
|
+
|
|
634
|
+
\`\`\`ts
|
|
635
|
+
import vitest, { testFiles } from "adamantite/lint/vitest"
|
|
636
|
+
import { defineConfig } from "oxlint"
|
|
637
|
+
|
|
638
|
+
export default defineConfig({
|
|
639
|
+
overrides: [{ files: testFiles, plugins: vitest.plugins, rules: { ...vitest.rules } }],
|
|
640
|
+
})
|
|
641
|
+
\`\`\`
|
|
642
|
+
|
|
643
|
+
Change test rules in that override. Top-level rules do not replace the preset's test override.
|
|
644
|
+
Keep \`plugins\` in it, because Oxlint ignores \`vitest/*\` rules without the plugin.
|
|
645
|
+
Continue when the intended test files receive the configured rules.
|
|
646
|
+
|
|
647
|
+
## Try a rule setting
|
|
648
|
+
|
|
649
|
+
Before changing a rule setting, run \`adamantite rule try <rule> --report <case> --accept <case>\`
|
|
650
|
+
when the task requires evidence from cases. Use \`--options '<json array>'\` for options after
|
|
651
|
+
the severity, or \`--current\` for the setting in the config. A case is a project path, or
|
|
652
|
+
\`<path>=<file>\` to lint the content of \`<file>\` at \`<path>\` in a copy of the project.
|
|
653
|
+
|
|
654
|
+
Continue when every case gives the expected result. Exit code 1 means a case differs.
|
|
655
|
+
Exit code 2 means the trial could not supply evidence, such as when the rule does not exist.
|
|
656
|
+
|
|
657
|
+
## Check the repair
|
|
658
|
+
|
|
659
|
+
- The changed code or configuration follows the project's coding standard.
|
|
660
|
+
- The affected lint check passes without a broader exception added only to silence it.
|
|
661
|
+
- Each requested trial ran successfully and gave the expected results.
|
|
662
|
+
`,"references/setup.md":"# How to set up Adamantite\n\n## Select the setup\n\nRead `adamantite init --help` for the available scripts, presets, and editors.\nUse explicit `--non-interactive` setup as an agent. Include at least one `--script`.\nFor example, to configure checks, fixes, TypeScript, and agent instructions, run:\n\n```sh\nnpx adamantite init --non-interactive --script check --script fix --typescript --agents\n```\n\nAdapt the selected options to the request. Omitted boolean flags are disabled.\n`--agents` adds instructions to `AGENTS.md` and writes this skill to `.agents/skills`, and\nto `.claude/skills` or `.grok/skills` when the project has `.claude/` or `.grok/`.\n\nBefore selecting `react-strict`, tell the user about its modified MIT license.\nThe installed `oxlint-plugin-react-doctor` license requires written permission for use as\nmachine learning training or evaluation data, and for certain paid or hosted services.\nRead that license for the exact restrictions.\n\nContinue when each selected option serves the requested setup.\n\n## Create the selected setup\n\nRun `init` with those options. It preserves existing package scripts whose commands differ\nfrom its managed commands. Use `--overwrite-scripts` only when the task includes replacing them.\nRead the output for preserved configuration that needs a Doctor repair.\n\nAdamantite requires TypeScript 7 or later in the target project's own `package.json`.\nCheck that declaration if npm cannot install or update a managed plugin.\n\nContinue when the selected dependencies are installed and the generated files match the request.\n\n## Complete managed plugin setup\n\nIf the selected presets include a managed plugin, check its setup:\n\n- For `react-strict`, include the `react` preset and keep `oxlint-plugin-react-doctor`\n installed. Init installs the pinned package, and Doctor and update maintain it.\n Its React Doctor checks also apply in hook modules.\n- For `effect`, run Oxlint through Adamantite. A plain `oxlint` call cannot load the\n `effecttsgo` rules and stops with `Unknown plugin: 'effecttsgo'`. Replace that call with\n `adamantite check --only lint` instead of removing the preset.\n Keep `{ \"name\": \"@effect/language-service\", \"diagnostics\": true }` in\n `compilerOptions.plugins`. In a monorepo, add it to each package's tsconfig or a shared base.\n Use `ignoreDependencies.effect` from `adamantite/analyze` in `knip.config.ts`.\n- For Effect editor support, follow Doctor's editor findings. After a dependency install or\n update, run `adamantite init --non-interactive --script check --editor vscode` to prepare\n or refresh the VS Code SDK cache. Keep the project's other setup options when needed.\n Select the workspace TypeScript version in VS Code. Zed uses the installed Effect CLI.\n- For `tailwind`, check that the project uses Tailwind v4. Init installs `@shadcn/lint`.\n If components are outside the directories that `components.json` identifies, set\n `settings.shadcn.ui` in `oxlint.config.ts`.\n Without `components.json`, the plugin looks in `components/ui` or `src/components/ui`.\n For another component directory, copy the preset's component-owned rule override to that directory.\n\nContinue when Doctor reports no findings for the selected plugins and editors.\n\n## Check the setup\n\n- Each selected managed script runs successfully.\n- Doctor reports no findings, and its assessment warnings are recorded.\n- Existing scripts and configuration are preserved unless the task includes replacing them.\n"},Bs=O.sort(O.dedupe(ga.map(e=>e.skillsFolder)),B.String),Vs=E.fn(`detectSkillFolders`)(function*(e){let t=yield*R.FileSystem,n=yield*P.Path;return yield*E.filter(Bs,r=>{let i=n.join(e,n.dirname(r));return r===`.agents/skills`?E.succeed(!0):t.exists(i).pipe(E.mapError(e=>new Je({cause:e,path:i})))},{concurrency:`unbounded`})}),Hs=E.fn(`readSkillCopy`)(function*(e){let t=yield*R.FileSystem,n=yield*P.Path,i=yield*nt(e,{recursive:!0});if(N.isNone(i))return N.none();let a=yield*E.forEach(i.value,i=>E.gen(function*(){let a=n.join(e,i);return(yield*t.stat(a).pipe(E.mapError(e=>new Je({cause:e,path:a})))).type===`File`?N.some([i.split(n.sep).join(`/`),yield*r(a)]):N.none()}),{concurrency:`unbounded`});return N.some(Object.fromEntries(O.getSomes(a)))});function Us(e){let t=Object.entries(zs);return Object.keys(e).length===t.length&&t.every(([t,n])=>e[t]===n)}const Ws=E.fn(`getSkillDirectory`)(function*(e,t){return(yield*P.Path).join(e,t,Rs)}),Gs=E.fn(`findStaleSkillFolders`)(function*(e){return(yield*E.forEach(Bs,t=>Ws(e,t).pipe(E.flatMap(e=>Hs(e)),E.map(e=>({copy:e,folder:t}))),{concurrency:`unbounded`})).filter(({copy:e})=>N.isSome(e)&&!Us(e.value)).map(({folder:e})=>e)}),Ks=E.fn(`writeSkill`)(function*(e,t){let n=yield*R.FileSystem,r=yield*P.Path;for(let i of t){let t=yield*Ws(e,i),a=yield*Hs(t);if(!(N.isSome(a)&&Us(a.value))){yield*n.remove(t,{force:!0,recursive:!0}).pipe(E.mapError(e=>new ve({cause:e,path:t})));for(let[e,n]of Object.entries(zs)){let i=r.join(t,...e.split(`/`));yield*x(r.dirname(i)),yield*S(i,n)}}}}),qs=E.fn(`removeSkillsLockEntry`)(function*(e){let t=yield*R.FileSystem,n=(yield*P.Path).join(e,`skills-lock.json`),r=yield*C(n);if(N.isNone(r))return!1;let i=yield*w(r.value,n);if(!h(i)||!h(i.skills))return!1;let{[Rs]:a,...o}=i.skills;return F.isUndefined(a)?!1:Object.keys(o).length===0?(yield*t.remove(n).pipe(E.mapError(e=>new ve({cause:e,path:n}))),!0):(yield*se(n,{...i,skills:o}),!0)}),Js=`<!-- ADAMANTITE:START -->`,Ys=`<!-- ADAMANTITE:END -->`;function Xs(e,t,n){let r=wt(e,t);switch(t){case`analyze`:return`- Run \`${r}\` after changing dependencies, imports, or exports.${n?` It also checks monorepo package consistency.`:``}`;case`check`:return`- Run \`${r}\` to catch formatting, lint, and type issues.`;case`fix`:return`- Run \`${r}\` to apply safe lint fixes and format code.`}}function Zs({isMonorepo:e,packageManager:t,scripts:n}){let r=ae.flatMap(r=>n.includes(r)?[Xs(t,r,e)]:[]);return Rr(`{{start}}
|
|
663
|
+
|
|
664
|
+
## Adamantite
|
|
665
|
+
|
|
666
|
+
Use the Adamantite skill for managed setup, Doctor repairs, and hardening. If the skill is not installed, read \`skills/adamantite/SKILL.md\` in the installed \`adamantite\` package.
|
|
667
|
+
|
|
668
|
+
{{scripts}}{{customRules}}- Run \`adamantite doctor\` for managed setup findings. Follow its repair prompt and rerun Doctor to verify the result.
|
|
669
|
+
|
|
670
|
+
### Check the result
|
|
671
|
+
|
|
672
|
+
- Read the output of the affected checks. Report failures or unavailable checks.
|
|
673
|
+
- Report unresolved Doctor findings and assessment warnings separately.
|
|
674
|
+
|
|
675
|
+
{{end}}
|
|
676
|
+
`,{customRules:y(n,`oxlint`)?`- For custom rules, follow the "${Wo}" section and linked guide in the Adamantite skill. Complete its verification and cleanup checks.\n`:``,end:Ys,scripts:r.length>0?[`- Prefer the package scripts Adamantite added for this workspace.`,...r,``].join(`
|
|
677
|
+
`):``,start:Js})}const Qs=(e,t)=>E.gen(function*(){let n=(yield*P.Path).join(e,`AGENTS.md`),r=L(yield*C(n),N.getOrElse(()=>``)),i=L(r,pt.indexOf(Js)),a=L(r,pt.indexOf(Ys)),o=L(N.all({end:a,start:i}),N.filter(({end:e,start:t})=>t<e)),s=Zs(t);if(N.isSome(o)){let{end:e,start:t}=o.value,i=e+23,a=`${r.slice(0,t)}${s.trimEnd()}${r.slice(i)}`;return yield*S(n,a.endsWith(`
|
|
678
|
+
`)?a:`${a}\n`),`updated`}if(N.isSome(i)||N.isSome(a))return`malformed`;let c=r.length===0||r.endsWith(`
|
|
130
679
|
|
|
131
680
|
`)?``:r.endsWith(`
|
|
132
681
|
`)?`
|
|
133
682
|
`:`
|
|
134
683
|
|
|
135
|
-
`;return yield*F(t,`${r}${c}${s}`),`updated`}),da=(e,n)=>t.gen(function*(){yield*(yield*Q).withSpinner(()=>Hn(e,n),{failure:`Failed to install dependencies.`,start:`Installing dependencies...`,success:`Dependencies installed.`})});function fa(e,n,r){return t.gen(function*(){let i=yield*Q,a=yield*i.withSpinner(a=>t.gen(function*(){let t=yield*n.detect(e);for(let e of t.warnings)yield*i.log.warning(e);return t.active===null?(yield*a.message(`\`${n.config}\` not found, creating...`),yield*r,{created:!0,legacyConfig:null}):t.active.format===`ts`?(yield*a.message(`Found \`${n.config}\`, keeping existing config.`),{created:!1,legacyConfig:null}):(yield*a.message(`Found \`${t.active.file}\`, keeping existing config.`),{created:!1,legacyConfig:t.active.file})}),{failure:`Failed to set up ${n.name} config.`,start:`Setting up ${n.name} config...`,success:e=>e.created?`${n.name} config created successfully.`:`${n.name} config is ready.`});a.legacyConfig&&(yield*i.log.info(`Legacy \`${a.legacyConfig}\` was preserved during \`adamantite init\`. Run \`adamantite doctor\` and follow its findings to migrate it to the latest ${n.name} config.`))})}const pa=(e,n,r)=>t.gen(function*(){let i=yield*Q,a=yield*R(e),o=r.overwriteScripts?[]:dt(a,n),s=new Set(o.map(e=>e.script)),c=n.filter(e=>!s.has(e));yield*i.withSpinner(()=>t.gen(function*(){if(c.length!==0){a.scripts??={};for(let e of c)a.scripts[e]=z[e];yield*ct(e,a)}}),{failure:"Failed to add scripts to `package.json`.",start:"Adding scripts to your `package.json`...",success:o.length===0?"Scripts added to your `package.json`":c.length===0?"Kept your existing `package.json` scripts.":"Scripts added to your `package.json`; conflicting scripts were kept."});let l=r.nonInteractive?"Use `--overwrite-scripts` to replace it.":"Re-run `adamantite init` and confirm overwriting to replace it.";for(let e of o)yield*i.log.warning(`Kept existing \`${e.script}\` script (\`${e.command}\`) instead of \`${z[e.script]}\`. ${l}`);return o.length>0&&(yield*i.log.info("Adamantite commands forward extra arguments after `--`, so custom flags can be kept, e.g. `adamantite analyze -- --directory packages/app`.")),c}),ma=(e,n)=>t.gen(function*(){let r=yield*Q;n?yield*b(vi,t.forEach(e=>r.log.info(e))):yield*r.withSpinner(n=>t.gen(function*(){return(yield*Z.detect(e))?(yield*n.message(`\`${Z.config}\` found, updating...`),yield*Z.update(e),!1):(yield*n.message(`\`${Z.config}\` not found, creating...`),yield*Z.create(e),!0)}),{failure:`Failed to set up TypeScript config.`,start:`Setting up TypeScript config...`,success:e=>e?`\`${Z.config}\` created successfully`:`\`${Z.config}\` updated successfully`})}),ha=e=>t.gen(function*(){let t=yield*Q,n=yield*Y.update(e);n.prepare===`merged`&&(yield*t.log.info("Added `adamantite prepare` to the start of your existing `prepare` script.")),n.tsconfig===`monorepo`&&(yield*t.log.info("In a monorepo, add the Effect language service entry to each package's `tsconfig.json` or to a shared base config. Run `adamantite doctor` for the reference entry.")),n.tsconfig===`missing`&&(yield*t.log.warning("No `tsconfig.json` found, so the Effect language service is not configured. Run `adamantite doctor` for the reference entry."))}),ga=e=>t.gen(function*(){let n=yield*Q;(yield*Y.detect(e))&&(yield*n.withSpinner(()=>Y.patch(e,{quiet:!0}),{failure:`Failed to patch Oxlint and TypeScript.`,start:`Patching Oxlint and TypeScript with @effect/tsgo...`,success:`Oxlint and TypeScript patched with @effect/tsgo.`}).pipe(t.catchTag([`CommandFailed`,`CliNotFound`,`PlatformError`],()=>n.log.warning("Run `adamantite prepare` to see why the patch failed. Oxlint cannot load the `effect` preset until it succeeds."))))}),_a=(e,n)=>t.gen(function*(){let r=yield*Q;n.includes(`vscode`)&&(yield*r.withSpinner(n=>t.gen(function*(){let t=yield*$.detect(e);return yield*n.message(`\`${$.config}\` ${t?`found, updating`:`not found, creating`}...`),yield*t?$.update(e):$.create(e),!t}),{failure:`Failed to set up VS Code config.`,start:`Checking for \`${$.config}\`...`,success:e=>`\`${$.config}\` ${e?`created`:`updated`} with Adamantite preset.`})),n.includes(`zed`)&&(yield*r.withSpinner(n=>t.gen(function*(){let t=yield*K.detect(e);return yield*n.message(`\`${K.config}\` ${t?`found, updating`:`not found, creating`}...`),yield*t?K.update(e):K.create(e),!t}),{failure:`Failed to set up Zed config.`,start:`Checking for \`${K.config}\`...`,success:e=>`\`${K.config}\` ${e?`created`:`updated`} with Adamantite preset.`}))}),va=(e,n)=>t.gen(function*(){let r=yield*Q,i=e.includes(`zed`),a=e.includes(`vscode`);yield*r.withSpinner(e=>t.gen(function*(){return a&&(yield*e.message(`Installing VS Code extension...`),yield*$.extension(n)),!0}),{start:`Installing editor extensions...`,success:i&&!a?`Zed extensions require manual install.`:`Editor extensions installed successfully.`}).pipe(t.catchTags({FailedToInstallExtension:e=>t.gen(function*(){return yield*r.log.warning(`⚠️ ${e.message}`),yield*r.log.warning(`Please install it manually after setup completes.`),!1}),VscodeCliNotFound:()=>t.gen(function*(){return yield*r.log.error(`VSCode CLI ('code' command) not found.`),yield*r.log.info(`To install it:`),yield*r.log.info(` 1. Open VS Code`),yield*r.log.info(` 2. Press Cmd+Shift+P (macOS) or Ctrl+Shift+P (Windows/Linux)`),yield*r.log.info(` 3. Run 'Shell Command: Install "code" command in PATH'`),!1})})),i&&(yield*r.log.info("Install the Zed `oxc` extension: zed://extension/oxc"))}),ya=(e,n,r)=>t.gen(function*(){let i=yield*Q,a=pr.files[0].path;yield*i.withSpinner(i=>t.gen(function*(){let t=yield*pr.detect(e);return yield*i.message(t?`\`${a}\` found, updating...`:`Creating \`${a}\`...`),yield*t?pr.update(e,{packageManager:n,scripts:r}):pr.create(e,{packageManager:n,scripts:r}),!t}),{failure:`Failed to set up GitHub Actions workflow.`,start:`Setting up GitHub Actions workflow...`,success:e=>`GitHub Actions workflow ${e?`created`:`updated`} successfully.`})}).pipe(t.catchTag([`FailedToCreateDirectory`,`FailedToParseFile`,`FailedToReadFile`,`FailedToWriteFile`,`PlatformError`],e=>t.gen(function*(){let t=yield*Q;yield*t.log.warning(`Could not set up the GitHub Actions workflow. ${e.message}`),yield*t.log.warning("Fix the reported problem and run `adamantite init` again, or create the workflow manually.")}))),ba=(e,n,r,i)=>t.gen(function*(){let a=yield*Q,o=yield*a.withSpinner(()=>ua(e,{isMonorepo:i,packageManager:n,scripts:r}),{failure:`Failed to update AGENTS.md.`,start:`Updating AGENTS.md...`,success:`AGENTS.md check complete.`}).pipe(t.catchTag([`FailedToReadFile`,`FailedToWriteFile`],e=>t.gen(function*(){return yield*a.log.warning(`Could not update AGENTS.md. ${e.message} Adamantite will continue initialization.`),`failed`})));o!==`failed`&&o===`malformed`&&(yield*a.log.warning(`Could not update AGENTS.md because Adamantite markers are incomplete. Remove the stale ADAMANTITE marker and run adamantite init again.`))});var xa=c.make(`init`,ta).pipe(c.withDescription(`Initialize Adamantite in the current directory. Setup flags require --non-interactive; omitted boolean setup flags are disabled`),c.withExamples([{command:`adamantite init --non-interactive --script check`,description:`Configure linting without prompts`},{command:`adamantite init --non-interactive --script check --preset react --editor vscode --typescript --install-extensions --github-actions --agents`,description:`Configure a React project with VS Code, TypeScript, CI, and agent guidance`},{command:`adamantite init --non-interactive --script analyze`,description:`Configure analysis; in a detected monorepo it includes Sherif`}]),c.withHandler(e=>t.gen(function*(){let t=f.cwd(),n=yield*Q;yield*Wi,yield*n.intro(`💠 adamantite init`);let r=yield*(yield*Bn).detectPackageManager(t);if(!r)return yield*new Ie({});if(r.warnings?.length)for(let e of r.warnings)yield*n.log.warning(e);yield*n.log.info(`Detected package manager: ${r.name}`);let i=yield*B(t);if(i&&(yield*n.log.info(`We've detected a monorepo setup in your project.`)),!e.nonInteractive&&s.some([e.scripts.length>0,e.presets.length>0,e.editors.length>0,e.typescript,e.installExtensions,e.githubActions,e.agents,e.overwriteScripts],x.isTruthy))return yield*new A({reason:"Setup flags require `--non-interactive`."});let a=e.nonInteractive?e:yield*ra(t,i),o=yield*qi(a,{nonInteractive:e.nonInteractive,packageManager:r.name}),c=o.scripts,l=o.presets,u=o.editors,d=o.typescript,p=o.installExtensions,m=o.githubActions,h=o.agents,g=c.includes(`check`)||c.includes(`fix`),_=c.includes(`analyze`),v=_&&i,y=yield*R(t),b=x.isNotUndefined(y.devDependencies?.adamantite??y.dependencies?.adamantite)?[]:[`adamantite`];g&&b.push(`${W.name}@${W.version}`,`${hi.name}@${hi.version}`,`${U.name}@${U.version}`,...mi.filter(e=>l.includes(e.preset)).map(e=>`${e.name}@${e.version}`)),v&&b.push(`${H.name}@${H.version}`),_&&b.push(`${V.name}@${V.version}`),yield*da(t,b),g&&(yield*fa(t,U,U.create(t)),yield*fa(t,W,W.create(t,l))),_&&(yield*fa(t,V,V.create(t)));let S=yield*pa(t,c,{nonInteractive:e.nonInteractive,overwriteScripts:o.overwriteScripts});if(h&&(yield*ba(t,r.name,S,i)),d&&(yield*ma(t,i)),l.includes(`effect`)&&(yield*ha(t)),g&&(yield*ga(t)),yield*_a(t,u),p&&(yield*va(u,c)),m){let e=r.name;lt(e)?yield*ya(t,e,c):yield*n.log.warning(`Skipping GitHub Actions setup: \`${e}\` is not a supported package manager for CI workflow generation.`)}yield*n.log.success(`Your project is now configured`),yield*n.outro(`💠 Adamantite initialized successfully!`)}).pipe(t.catchTags({OperationCancelled:()=>t.gen(function*(){yield*(yield*Q).cancel(`You've cancelled the initialization process.`)})})))),Sa=c.make(`prepare`).pipe(c.withDescription("Patch Oxlint and TypeScript for the effect preset. The `prepare` script runs it after each install"),c.withHandler(()=>t.gen(function*(){let e=f.cwd();(yield*Y.detect(e))&&(yield*Y.patch(e,{quiet:!1}))})));const Ca=T.File(`file`,{mustExist:!0}).pipe(T.withDescription(`The JavaScript or TypeScript file to parse`)),wa=c.make(`ast`,{file:Ca}).pipe(c.withDescription(`Print the ESTree-shaped AST that Oxlint rules visit, to find node names for a custom rule`),c.withHandler(({file:e})=>t.gen(function*(){let t=yield*Q,n=yield*N(e),r=de(e,n,{preserveParens:!1});if(r.errors.length>0)return yield*new ke({errors:r.errors.map(e=>e.message),path:e});yield*t.message(JSON.stringify(r.program,null,2))}))),Ta=T.String(`name`).pipe(T.withDescription(`The rule name in kebab-case, such as no-process-env`)),Ea=u.String(`dir`).pipe(u.optional,u.withDescription(`The rules folder, relative to the current directory. Default: ${Fr}. Pass the folder that \`custom({ dir })\` loads, such as a rules folder in a monorepo tooling package`)),Da=c.make(`add`,{dir:Ea,name:Ta}).pipe(c.withDescription(`Write a custom rule stub, and the authoring guidance when the rules folder has none`),c.withHandler(({dir:e,name:n})=>t.gen(function*(){let t=yield*Q,r=yield*w.Path,i=f.cwd(),a=yield*Rr(i,n,d.getOrUndefined(e));yield*t.log.success(`Wrote ${r.relative(i,a.rulePath)}.`),a.agentsPath!==void 0&&(yield*t.log.success(`Wrote ${r.relative(i,a.agentsPath)}.`)),yield*t.log.info("`custom()` from `adamantite/lint/custom` loads the rule. Run `adamantite doctor` to check the wiring.")})));var Oa=c.make(`rule`).pipe(c.withDescription(`Write and inspect custom Oxlint rules`),c.withSubcommands([Da,wa]));const ka=[W,hi,U,H,V];function Aa(e,t){return s.filterMap(ka,n=>{if(t.has(n.name))return v.failVoid;let r=e.devDependencies?.[n.name]??e.dependencies?.[n.name];return r&&st(r)!==n.version?v.succeed({currentVersion:r,name:n.name,targetVersion:n.version}):v.failVoid})}var ja=c.make(`update`).pipe(c.withDescription(`Update Adamantite-managed dependencies and report setup findings`),c.withHandler(()=>t.gen(function*(){let e=f.cwd(),t=yield*Q;yield*t.intro(`💠 adamantite update`);let n=yield*R(e),r=yield*Ci(e,n),i=r.packageActions,a=new Set(i.map(e=>e.package)),o=[...i.map(e=>({currentVersion:e.type===`install_package`?`not installed`:e.currentVersion,name:e.package,targetVersion:e.targetVersion})),...Aa(n,a)];if(o.length>0){yield*t.log.info(`The following dependencies will be updated:`);for(let e of o)yield*t.log.info(` ${e.name}: ${e.currentVersion} → ${e.targetVersion}`);yield*t.withSpinner(()=>Hn(e,o.map(e=>`${e.name}@${e.targetVersion}`)),{failure:`Failed to update dependencies`,start:`Updating dependencies...`,success:`Dependencies updated successfully`}),yield*t.log.success(`Dependencies updated successfully.`),(yield*Y.detect(e))&&(yield*t.withSpinner(()=>Y.patch(e,{quiet:!0}),{failure:"Failed to patch Oxlint and TypeScript. Run `adamantite prepare` to see why.",start:`Patching Oxlint and TypeScript with @effect/tsgo...`,success:`Oxlint and TypeScript patched with @effect/tsgo.`}))}let s=o.length===0?r:yield*Ci(e);for(let e of s.warnings)yield*t.log.warning(e);let c=s.findings;return c.length>0&&(yield*Pi(c),yield*t.log.info("Run `adamantite doctor` to get the combined Markdown repair prompt.")),o.length===0&&c.length===0?(yield*t.log.success(`No changes needed.`),`no-changes`):`success`}).pipe(t.tapError(()=>t.gen(function*(){yield*(yield*Q).outro(`❌ Update failed`)})),t.tap(e=>t.gen(function*(){yield*(yield*Q).outro(e===`no-changes`?`✅ Adamantite is already up to date.`:`✅ Update completed successfully!`)})))));const Ma=[Tn,In,Hi],Na=[Tn,In,Ii,Hi,xa,Sa,Oa,ja],Pa=new Set(Na.map(e=>e.name)),Fa=new Set(Ma.map(e=>e.name)),Ia=c.make(`adamantite`).pipe(c.withDescription(`Opinionated preset package for modern TypeScript applications`),c.withSubcommands(Na)),La=e=>l.mergeAll(o.layer,Qn.layer.pipe(l.provide(o.layer)),Q.layer,ji.layer.pipe(l.provideMerge(e),l.provide(o.layer)),Bn.layer,Mi.layer),Ra=t.fn(`runCli`)(function*(e,n){let[r,i]=s.splitWhere(e,e=>e===`--`),a=s.drop(i,1),o=r.find(e=>Pa.has(e));if(a.length>0&&o!==void 0&&!Fa.has(o))return yield*new Re({command:o});yield*c.runWith(Ia,{version:n})(r).pipe(t.provideService(Ue,a))}),za=t.gen(function*(){let e=yield*(yield*a.Stdio).args;yield*Ra(e,`0.45.0`)}).pipe(t.as(0),t.catchTag(`CommandFailed`,e=>t.succeed(e.exitCode)),t.catch(e=>t.service(Q).pipe(t.flatMap(t=>t.log.error(e.message)),t.as(r.ExitCode(1)))),t.provide(La(j.layer)));e.runMain(za,{teardown:(e,t)=>{n.isSuccess(e)?t(Number(e.value)):i.defaultTeardown(e,t)}});export{};
|
|
684
|
+
`;return yield*S(n,`${r}${c}${s}`),`updated`}),$s=(e,t)=>E.gen(function*(){yield*(yield*$).withSpinner(()=>Wr(e,t),{failure:`Failed to install dependencies.`,start:`Installing dependencies...`,success:`Dependencies installed.`})});function ec(e,t,n){return E.gen(function*(){let r=yield*$,i=yield*r.withSpinner(i=>E.gen(function*(){let a=yield*t.detect(e);for(let e of a.warnings)yield*r.log.warning(e);return a.active instanceof Ft?(yield*i.message(`\`${t.config}\` not found, creating...`),yield*n):yield*i.message(`Found \`${a.active.file.file}\`, keeping it.`),a.active}),{failure:`Failed to set up ${t.name} config.`,start:`Setting up ${t.name} config...`,success:e=>e instanceof Ft?`${t.name} config created.`:`Existing ${t.name} config kept.`});i instanceof Lt&&(yield*r.log.info(`Legacy \`${i.file.file}\` was kept during \`adamantite init\`. Run \`adamantite doctor\` for instructions to migrate to the current ${t.name} config.`))})}const tc=(e,n,r)=>E.gen(function*(){let i=yield*$,a=yield*u(e),o=r.overwriteScripts?[]:ke(a,n),s=new Set(o.map(e=>e.script)),c=n.filter(e=>!s.has(e));yield*i.withSpinner(()=>E.gen(function*(){if(c.length!==0){a.scripts??={};for(let e of c)a.scripts[e]=Xe[e];yield*p(e,a)}}),{failure:"Failed to add scripts to `package.json`.",start:"Adding scripts to your `package.json`...",success:o.length===0?"Scripts added to `package.json`.":c.length===0?"Existing `package.json` scripts kept.":"Scripts added to `package.json`. Existing conflicting scripts were kept."});let l=r.nonInteractive?"Use `--overwrite-scripts` to replace it.":"Run `adamantite init` again and choose to replace the script.";for(let e of o)yield*i.log.warning(`Kept existing \`${e.script}\` script (\`${e.command}\`) instead of \`${Xe[e.script]}\`. ${l}`);return o.length>0&&(yield*i.log.info("Pass custom tool arguments after `--`, such as `adamantite analyze -- --directory packages/app`.")),t(a)}),nc=(e,t)=>E.gen(function*(){let n=yield*$;t?yield*L(ia,E.forEach(e=>n.log.info(e))):yield*n.withSpinner(t=>E.gen(function*(){return(yield*oa.detect(e))?(yield*t.message(`\`${oa.config}\` found, updating...`),yield*oa.update(e),!1):(yield*t.message(`\`${oa.config}\` not found, creating...`),yield*oa.create(e),!0)}),{failure:`Failed to set up TypeScript config.`,start:`Setting up TypeScript config...`,success:e=>e?`\`${oa.config}\` created.`:`\`${oa.config}\` updated.`})}),rc=e=>E.gen(function*(){let t=yield*$,n=yield*Re.update(e);n===`monorepo`&&(yield*t.log.info("In a monorepo, add the Effect language service entry to each package's `tsconfig.json` or to a shared base config. Run `adamantite doctor` for the reference entry.")),n===`missing`&&(yield*t.log.warning("No `tsconfig.json` found, so the Effect language service is not configured. Run `adamantite doctor` for the reference entry."))}),ic={vscode:{integration:Ti,name:`VS Code`},zed:{integration:Fi,name:`Zed`}},ac=(e,t)=>E.gen(function*(){let n=yield*$;for(let r of ws.filter(e=>t.includes(e))){let{integration:t,name:i}=ic[r];yield*n.withSpinner(n=>E.gen(function*(){let r=yield*t.detect(e);return yield*n.message(`\`${t.config}\` ${r?`found, updating`:`not found, creating`}...`),yield*r?t.update(e):t.create(e),!r}),{failure:`Failed to set up ${i} config.`,start:`Checking for \`${t.config}\`...`,success:e=>`\`${t.config}\` ${e?`created`:`updated`} with Adamantite preset.`})}}),oc=(e,t,n=[])=>E.gen(function*(){let r=yield*$,i=e.includes(`zed`),a=e.includes(`vscode`);yield*r.withSpinner(e=>E.gen(function*(){return a&&(yield*e.message(`Installing VS Code extension...`),yield*Ti.extension(t,n)),!0}),{failure:`Failed to install editor extensions.`,start:`Installing editor extensions...`,success:i&&!a?`Install the Zed extensions using the links below.`:`Editor extensions installed.`}).pipe(E.catchTags({FailedToInstallExtension:e=>E.gen(function*(){return yield*r.log.warning(`⚠️ ${e.message}`),yield*r.log.warning(`Install the extension manually after setup finishes.`),!1}),VscodeCliNotFound:()=>E.gen(function*(){return yield*r.log.error("VS Code's `code` command was not found on PATH."),yield*r.log.info(`Add the code command to PATH:`),yield*r.log.info(` 1. Open VS Code`),yield*r.log.info(` 2. Press Cmd+Shift+P (macOS) or Ctrl+Shift+P (Windows/Linux)`),yield*r.log.info(` 3. Run 'Shell Command: Install "code" command in PATH'`),!1})})),i&&(yield*r.log.info("Install the Zed `oxc` extension: zed://extension/oxc"),n.includes(`effect`)&&(yield*r.log.info(`Install the Zed TypeScript language server extension: zed://extension/tsgo`)))}),sc=(e,t,n)=>E.gen(function*(){let r=yield*$,i=mi.files[0].path;if(!Vr(n))return yield*r.log.warning("No CI script runs an Adamantite command, so `adamantite init` did not set up the GitHub Actions workflow.");(yield*r.withSpinner(r=>E.gen(function*(){let a=yield*mi.detect(e);return yield*r.message(a?`\`${i}\` found, updating...`:`Creating \`${i}\`...`),a?yield*mi.update(e,{packageManager:t,scripts:n}):(yield*mi.create(e,{packageManager:t,scripts:n}),`created`)}),{failure:`Failed to set up GitHub Actions workflow.`,start:`Setting up GitHub Actions workflow...`,success:e=>`GitHub Actions workflow ${e}.`}))===`kept`&&(yield*r.log.info(`\`${i}\` has changes that Adamantite did not make, so \`adamantite init\` kept it. Run \`adamantite doctor\` to see what to update.`))}).pipe(E.catchTag([`FailedToCreateDirectory`,`FailedToParseFile`,`FailedToReadFile`,`FailedToWriteFile`,`PlatformError`],e=>E.gen(function*(){let t=yield*$;yield*t.log.warning(`Could not set up the GitHub Actions workflow. ${e.message}`),yield*t.log.warning("Fix the reported problem and run `adamantite init` again, or create the workflow manually.")}))),cc=(e,t,n,r)=>E.gen(function*(){let i=yield*$,a=yield*i.withSpinner(()=>Qs(e,{isMonorepo:r,packageManager:t,scripts:n}),{failure:`Failed to update AGENTS.md.`,start:`Updating AGENTS.md...`,success:`AGENTS.md check complete.`}).pipe(E.catchTag([`FailedToReadFile`,`FailedToWriteFile`],e=>E.gen(function*(){return yield*i.log.warning(`Could not update AGENTS.md. ${e.message} Adamantite will continue initialization.`),`failed`})));a!==`failed`&&a===`malformed`&&(yield*i.log.warning("AGENTS.md has an incomplete ADAMANTITE marker. Remove the incomplete marker and run `adamantite init` again."))}),lc=new Intl.ListFormat(`en`,{type:`conjunction`}),uc=e=>E.gen(function*(){let t=yield*$;yield*Vs(e).pipe(E.flatMap(n=>t.withSpinner(()=>Ks(e,n),{failure:`Failed to add the Adamantite skill.`,start:`Adding the Adamantite skill...`,success:`Adamantite skill added to ${lc.format(n.map(e=>`\`${e}\``))}.`})),E.catchTag([`FailedToCreateDirectory`,`FailedToReadFile`,`FailedToWriteFile`],e=>t.log.warning(`Could not add the Adamantite skill. ${e.message} Adamantite will continue initialization.`)))});var dc=k.make(`init`,Ps).pipe(k.withDescription(`Configure Adamantite in the current directory. Use --non-interactive with setup flags and select each optional feature explicitly`),k.withExamples([{command:`adamantite init --non-interactive --script check`,description:`Configure linting without prompts`},{command:`adamantite init --non-interactive --script check --preset react --editor vscode --typescript --install-extensions --github-actions --agents`,description:`Configure a React project with VS Code, TypeScript, CI, agent guidance, and the Adamantite skill`},{command:`adamantite init --non-interactive --script analyze`,description:`Configure analysis, including Sherif checks for a monorepo`}]),k.withHandler(e=>E.gen(function*(){let t=j.cwd(),n=yield*$;yield*Cs,yield*n.intro(`💠 adamantite init`);let r=yield*(yield*Hr).detectPackageManager(t);if(!r)return yield*new me({});if(r.warnings?.length)for(let e of r.warnings)yield*n.log.warning(e);yield*n.log.info(`Detected package manager: ${r.name}`);let i=yield*Qe(t);if(i&&(yield*n.log.info(`This project is a monorepo.`)),!e.nonInteractive&&O.some([e.scripts.length>0,e.presets.length>0,e.editors.length>0,e.typescript,e.installExtensions,e.githubActions,e.agents,e.overwriteScripts],F.isTruthy))return yield*new T({reason:"Setup flags require `--non-interactive`."});let a=e.nonInteractive?e:yield*Ls(t,i,r.name),o=yield*Es(a,r.name),s=[...o.scripts],{lint:c}=o,l=N.match(c,{onNone:()=>[],onSome:e=>e.presets}),d=y(s,`knip`),f=y(s,`sherif`)&&i,p=yield*u(t),m=F.isNotUndefined(p.devDependencies?.adamantite??p.dependencies?.adamantite)?[]:[`adamantite`];N.isSome(c)&&m.push(`${J.name}@${J.version}`,`${$i.name}@${$i.version}`,`${q.name}@${q.version}`,...Zi.filter(e=>l.includes(e.preset)).map(e=>`${e.name}@${e.version}`)),f&&m.push(`${Er.name}@${Er.version}`),d&&m.push(`${tr.name}@${tr.version}`),yield*$s(t,m),N.isSome(c)&&(yield*ec(t,q,q.create(t)),yield*ec(t,J,J.create(t,l))),d&&(yield*ec(t,tr,tr.create(t)));let h=yield*tc(t,s,{nonInteractive:e.nonInteractive,overwriteScripts:o.overwriteScripts});if(o.agents&&(yield*cc(t,r.name,h,i),yield*uc(t)),N.exists(c,e=>e.typescript)&&(yield*nc(t,i)),l.includes(`effect`)&&(yield*rc(t)),N.isSome(o.editors)){let{installExtensions:e,names:n}=o.editors.value;yield*ac(t,n),e&&(yield*oc(n,s,l))}N.isSome(o.githubActions)&&(yield*sc(t,o.githubActions.value,h)),yield*n.outro(`💠 Setup finished.`)}).pipe(E.catchTags({OperationCancelled:()=>E.gen(function*(){yield*(yield*$).cancel(`Setup was cancelled.`)})}))));const fc=/^[a-z][\da-z]*(?:-[\da-z]+)*$/;function pc(e){return`import { defineRule } from "adamantite/rules/plugin"
|
|
685
|
+
|
|
686
|
+
export default defineRule({
|
|
687
|
+
createOnce(context) {
|
|
688
|
+
return {
|
|
689
|
+
// Run \`adamantite rule ast <file>\` to find the node types to visit.
|
|
690
|
+
DebuggerStatement(node) {
|
|
691
|
+
context.report({ messageId: "unexpected", node })
|
|
692
|
+
},
|
|
693
|
+
}
|
|
694
|
+
},
|
|
695
|
+
meta: {
|
|
696
|
+
docs: { description: "TODO: describe what {{name}} reports." },
|
|
697
|
+
messages: { unexpected: "TODO: tell the author what to do instead." },
|
|
698
|
+
schema: [],
|
|
699
|
+
type: "problem",
|
|
700
|
+
},
|
|
701
|
+
})
|
|
702
|
+
`.replaceAll(`{{name}}`,e)}const mc=E.fn(`addCustomRule`)(function*(e,t,n=K){if(!fc.test(t))return yield*new de({rule:t});let r=yield*P.Path,i=r.resolve(e,n),a=r.join(i,`${t}.ts`),o=(yield*hc(e,n)).filter(e=>e.slice(0,-r.extname(e).length)===t);return o.length>0?yield*new He({paths:o.map(e=>r.join(i,e))}):(yield*x(i),yield*S(a,pc(t)),a)}),hc=E.fn(`listCustomRules`)(function*(e,t=K){let n=yield*P.Path,r=yield*R.FileSystem,i=n.resolve(e,t),a=yield*nt(i),o=yield*E.filter(N.getOrElse(a,()=>[]).filter(e=>Qt(e)),e=>r.stat(n.join(i,e)).pipe(E.mapBoth({onFailure:t=>new Je({cause:t,path:n.join(i,e)}),onSuccess:e=>e.type===`File`})));return O.sort(o,B.String)}),gc=E.fn(`addCustomRuleTest`)(function*(e,t,n=K,r){if(!fc.test(t))return yield*new de({rule:t});let i=yield*P.Path,a=yield*R.FileSystem,o=i.resolve(e,n),s=(yield*hc(e,n)).find(e=>e.slice(0,-i.extname(e).length)===t);if(s===void 0)return yield*new Ee({directory:o,rule:t});let c=r===void 0?i.join(o,`${t}.test.ts`):i.resolve(e,r);if(yield*a.exists(c).pipe(E.mapError(e=>new Je({cause:e,path:c}))))return yield*new He({paths:[c]});yield*x(i.dirname(c));let l=e=>a.realPath(e).pipe(E.mapError(t=>new Je({cause:t,path:e}))),[u,d]=yield*E.all([l(i.dirname(c)),l(i.join(o,s))]),f=i.relative(u,d).split(i.sep).join(`/`),p=f.startsWith(`../`)?f:`./${f}`,m=yield*ce(p);return yield*S(c,`import { RuleTester } from "adamantite/rules/testing"
|
|
703
|
+
import rule from {{ruleImport}}
|
|
704
|
+
|
|
705
|
+
const tester = new RuleTester({ languageOptions: { parserOptions: { lang: "ts" } } })
|
|
706
|
+
|
|
707
|
+
// Replace these cases with valid and invalid code for this rule.
|
|
708
|
+
// oxlint-disable-next-line vitest/require-hook, jest/require-hook -- RuleTester registers its node:test suites here.
|
|
709
|
+
tester.run("{{name}}", rule, {
|
|
710
|
+
invalid: [{ code: "debugger", errors: [{ messageId: "unexpected" }] }],
|
|
711
|
+
valid: ["const value: number = 1"],
|
|
712
|
+
})
|
|
713
|
+
`.replaceAll(`{{name}}`,t).replace(`{{ruleImport}}`,m)),c}),_c=E.fn(`findCustomRuleTests`)(function*(e){let t=yield*P.Path,n=O.dedupe(e.calls.map(e=>e.dir)),r=yield*E.forEach(n,e=>nt(e).pipe(E.map(n=>N.getOrElse(n,()=>[]).filter(e=>$t(e)).map(n=>t.join(e,n)))),{concurrency:`unbounded`});return O.sort(r.flat(),B.String)}),vc=E.fn(`readCustomRuleTestCommand`)(function*({customRules:e,cwd:t}){let n=yield*P.Path,r=yield*_c(e);return{command:r.length===0?N.none():N.some({args:[`--test`,...r.map(e=>n.relative(t,e))],command:`node`}),unresolvedCalls:O.dedupe(e.unresolvedCalls),unresolvedImports:e.unresolvedImports}}),yc=V.File(`file`,{mustExist:!0}).pipe(V.withDescription(`The JavaScript or TypeScript file to parse`)),bc=k.make(`ast`,{file:yc}).pipe(k.withDescription(`Print the syntax tree Oxlint rules use, with node names for custom rules`),k.withHandler(({file:e})=>E.gen(function*(){let t=yield*$,n=yield*r(e),i=bt(e,n,{preserveParens:!1});if(i.errors.length>0)return yield*new ge({errors:i.errors.map(e=>e.message),path:e});yield*t.message(yield*Be(i.program))}))),xc=V.String(`name`).pipe(V.withDescription(`The rule name in kebab-case, such as no-process-env`)),Sc=M.String(`dir`).pipe(M.optional,M.withDescription(`The rules folder, relative to the current directory. Default: ${K}. Pass the folder that \`custom({ dir })\` loads, such as a rules folder in a monorepo tooling package`)),Cc=M.String(`path`).pipe(M.optional,M.withDescription(`The test file path, relative to the current directory`)),wc=k.make(`add`,{dir:Sc,name:xc}).pipe(k.withDescription(`Create a custom rule file. See the Adamantite skill for authoring instructions`),k.withHandler(({dir:e,name:t})=>E.gen(function*(){let n=yield*$,r=yield*P.Path,i=j.cwd(),a=yield*mc(i,t,N.getOrUndefined(e));yield*n.log.success(`Wrote ${r.relative(i,a)}.`),yield*n.log.info(`\`custom()\` from \`adamantite/rules\` loads the rule. Run \`adamantite doctor\` to check the wiring. The "${Wo}" section of the Adamantite skill tells agents how to verify the rule with temporary cases.`)}))),Tc=k.make(`add`,{dir:Sc,name:xc.pipe(V.optional),path:Cc}).pipe(k.withDescription(`Create a test for an existing rule. Omit the name to choose a rule`),k.withHandler(({dir:e,name:t,path:n})=>E.gen(function*(){let r=yield*$,i=yield*P.Path,a=yield*pa,o=N.getOrElse(e,()=>K),s=j.cwd(),c=N.getOrUndefined(t);if(c===void 0){let e=(yield*hc(s,o)).map(e=>e.slice(0,-i.extname(e).length));if(e.length===0)return yield*r.log.info(`No custom rules were found in \`${o}\`. Run \`adamantite rule add <name>\` first.`);if(!(yield*a.isInteractive))return yield*r.message(e.join(`
|
|
714
|
+
`)),yield*r.log.info("Pass a rule name with `adamantite rule test add <name>`.");c=yield*r.select({message:`Which rule needs a test?`,options:e.map(e=>({label:e,value:e}))})}let l=yield*gc(s,c,o,N.getOrUndefined(n));yield*r.log.success(`Wrote ${i.relative(s,l)}.`),yield*r.log.info(`Adapt the valid and invalid cases to the rule, then run \`adamantite rule test\`${N.isSome(n)?" with `--path` and the test file path.":`.`}`),yield*r.log.info(`RuleTester uses node:test. Exclude this test from Vitest and Jest discovery. See Custom rules in the Adamantite README.`)}))),Ec=k.make(`test`,{path:Cc}).pipe(k.withDescription(`Run custom rule tests with node --test. Use --path for a test outside the rules folder`),k.withHandler(({path:e})=>E.gen(function*(){let t=yield*$,n=yield*P.Path,r=yield*Pt,i=j.cwd();if(N.isSome(e))return yield*r.run({args:[`--test`,n.resolve(i,e.value)],command:`node`,title:`🧪 Testing custom rules`});let{command:a,unresolvedCalls:o,unresolvedImports:s}=yield*vc(yield*fa(i));for(let e of o)yield*t.log.warning(`\`rule test\` cannot read the \`dir\` of a \`custom()\` call in \`${n.relative(i,e)}\`, because it is not a string literal. It does not run the tests of that rules folder.`);for(let{from:e,specifier:r}of s)yield*t.log.warning(`\`rule test\` cannot resolve the import of \`${r}\` in \`${n.relative(i,e)}\`, so it does not run the tests of the rules folders behind it.`);if(N.isNone(a))return yield*t.log.info("No tests were found for loaded custom rules. Run `adamantite doctor` to check rule setup, or `adamantite rule test add` to add a test.");yield*r.run({...a.value,title:`🧪 Testing custom rules`})})),k.withSubcommands([Tc])),Dc=V.String(`rule`).pipe(V.withDescription(`The full rule name, such as no-restricted-imports, typescript/no-explicit-any, or project/no-foo`)),Oc=M.String(`report`).pipe(M.atLeast(1),M.withDescription(`Add a case the rule must report. Use a project path, or <path>=<file> to lint file contents at another path. Repeat --report for more cases`)),kc=M.String(`accept`).pipe(M.atLeast(0),M.withDescription(`Add a case the rule must accept, using the same path format as --report`)),Ac=M.String(`options`).pipe(M.withSchema(z.fromJsonString(z.Array(z.Json))),M.optional,M.withDescription(`The rule options that come after the severity, as a JSON array, such as '[{"paths":["node:fs"]}]'. The trial sets the rule to error`)),jc=M.Boolean(`current`).pipe(M.withDefault(!1),M.withDescription(`Use the project's current rule setting to see what it reports`));function Mc(e,t){return t instanceof Co?`\`${e}\` as the project config sets it`:`\`${e}\` at ${JSON.stringify([`error`,...t.options])}`}function Nc(e){return e.diagnostics.length>0==(e.case.expected===`reported`)}function Pc(e,t,n){let r=[...new Set(n.map(e=>`\`${e.config}\``))].join(`, `),i=n.map(e=>{let t=N.match(e.case.source,{onNone:()=>`\`${e.case.path}\``,onSome:t=>`\`${e.case.path}\` from \`${t}\``}),n=e.diagnostics.length>0?`reported`:`accepted`;return[Nc(e)?`✓ ${t}: ${n}, as expected.`:`✗ ${t}: ${n}, but it must be ${e.case.expected}.`,...e.diagnostics.map(e=>` ${e.line}:${e.column} ${e.message}`)].join(`
|
|
715
|
+
`)}),a=n.filter(e=>!Nc(e)).length,o=a===0?`All cases produced the expected result.`:n.length===1?`The case did not produce the expected result.`:`${a.toLocaleString(`en-US`)} of ${n.length.toLocaleString(`en-US`)} cases ${a===1?`is`:`are`} different from the expected result.`;return[`Trial of ${Mc(e,t)}, in ${r}.`,``,...i,``,o].join(`
|
|
716
|
+
`)}const Fc=k.make(`try`,{accept:kc,current:jc,options:Ac,report:Oc,rule:Dc}).pipe(k.withDescription(`Test a rule against cases in a project copy. Exit codes: 0 for expected results, 1 for a mismatch, and 2 if a case could not be checked. Project files stay unchanged`),k.withHandler(({accept:e,current:t,options:n,report:r,rule:i})=>E.gen(function*(){let a=yield*$,o=t?new Co:new wo({options:N.getOrElse(n,()=>[])}),s=yield*E.gen(function*(){if(t&&N.isSome(n))return yield*new tt({reason:"Give `--options` or `--current`, not both."});let a=yield*E.all([...r.map(e=>To(e,`reported`)),...e.map(e=>To(e,`accepted`))]),s=j.cwd();return yield*No({cases:a,cwd:s,rule:i,setting:o,workspace:yield*re(s)})}).pipe(E.catch(e=>a.log.error(e.message).pipe(E.andThen(E.fail(new Ie({command:`rule try`,exitCode:D.ExitCode(2)}))))));if(yield*a.message(Pc(i,o,s)),!s.every(e=>Nc(e)))return yield*new Ie({command:`rule try`,exitCode:D.ExitCode(1)})})));var Ic=k.make(`rule`).pipe(k.withDescription(`Create and inspect custom Oxlint rules, try them against cases, and run saved tests`),k.withSubcommands([wc,bc,Ec,Fc]));const Lc=[J,$i,q,Er,tr];var Rc=k.make(`update`).pipe(k.withDescription(`Update managed packages and the Adamantite skill, then report setup issues`),k.withHandler(()=>E.gen(function*(){let e=j.cwd(),t=yield*$;yield*t.intro(`💠 adamantite update`);let n=yield*fa(e),r=yield*ca(n),i=r.packageActions,a=new Set(i.map(e=>e.package)),o=Lc.flatMap(e=>a.has(e.name)?[]:[Wt(n,e,`Adamantite`,`adamantite`)]),s=[...i,...o.flatMap(e=>e.packageActions).filter(e=>e.type===`update_package`)],c=o.filter(e=>e.packageActions.length===0);if(s.length>0){yield*t.log.info(`Packages to install or update:`);for(let e of s){let n=e.type===`install_package`?`not installed`:e.currentVersion;yield*t.log.info(` ${e.package}: ${n} → ${e.targetVersion}`)}yield*t.withSpinner(()=>Wr(e,s.map(e=>`${e.package}@${e.targetVersion}`)),{failure:`Failed to update dependencies`,start:`Updating dependencies...`,success:`Dependencies updated.`})}let l=s.length===0?`idle`:`applied`,u=yield*Gs(e).pipe(E.flatMap(n=>n.length===0?E.succeed(`idle`):t.withSpinner(()=>Ks(e,n),{failure:`Failed to refresh the Adamantite skill.`,start:`Refreshing the Adamantite skill...`,success:`Adamantite skill refreshed.`}).pipe(E.as(`applied`),E.catchTag([`FailedToCreateDirectory`,`FailedToReadFile`,`FailedToWriteFile`],e=>t.log.warning(`Could not refresh the Adamantite skill. ${e.message}`).pipe(E.as(`applyFailed`))))),E.catchTag(`FailedToReadFile`,e=>t.log.warning(`Could not check the Adamantite skill. ${e.message}`).pipe(E.as(`checkFailed`)))),d=e=>t.log.warning(`Could not update \`skills-lock.json\`. ${e.message}`),f=yield*qs(e).pipe(E.flatMap(e=>e?t.log.info("Removed the `adamantite` entry from `skills-lock.json`.").pipe(E.as(`applied`)):E.succeed(`idle`)),E.catchTag([`FailedToParseFile`,`FailedToReadFile`],e=>d(e).pipe(E.as(`checkFailed`))),E.catchTag(`FailedToWriteFile`,e=>d(e).pipe(E.as(`applyFailed`)))),p=l===`idle`?r:yield*ca(yield*fa(e)),m=new Set(p.findings.map(e=>e.id)),h=O.dedupe([...p.warnings,...c.flatMap(e=>e.warnings)]);for(let e of h)yield*t.log.warning(e);let g=[...p.findings,...c.flatMap(e=>e.findings).filter(e=>!m.has(e.id))];return g.length>0&&(yield*ha(g),yield*t.log.info("Run `adamantite doctor` for the remaining repairs and an agent prompt.")),![l,u,f].some(e=>e===`applied`||e===`applyFailed`)&&g.length===0?`no-changes`:`success`}).pipe(E.tapError(()=>E.gen(function*(){yield*(yield*$).outro(`❌ Update failed`)})),E.tap(e=>E.gen(function*(){yield*(yield*$).outro(e===`no-changes`?`✅ No managed updates were applied.`:`✅ Update finished.`)})))));const zc=[Nr,Lr,Wa],Bc=[Nr,Lr,La,Wa,xs,dc,Ic,Rc],Vc=new Set(Bc.map(e=>e.name)),Hc=new Set(zc.map(e=>e.name)),Uc=k.make(`adamantite`).pipe(k.withDescription(`Configure code checks for TypeScript projects`),k.withSubcommands(Bc)),Wc=e=>A.mergeAll(st.layer,ti.layer.pipe(A.provide(st.layer)),Ne.layer,$.layer,ba.layer.pipe(A.provideMerge(e),A.provide(st.layer)),Hr.layer,pa.layer),Gc=E.fn(`runCli`)(function*(e,t){let[n,r]=O.splitWhere(e,e=>e===`--`),i=O.drop(r,1),o=n.find(e=>Vc.has(e));if(i.length>0&&o!==void 0&&!Hc.has(o))return yield*new a({command:o});yield*k.runWith(Uc,{version:t})(n).pipe(E.provideService(At,i))}),Kc=E.gen(function*(){let e=yield*(yield*ot.Stdio).args;yield*Gc(e,`0.46.0`)}).pipe(E.as(0),E.catchTag(`CommandFailed`,e=>E.succeed(e.exitCode)),E.catch(e=>E.service($).pipe(E.flatMap(t=>t.log.error(e.message)),E.as(D.ExitCode(1)))),E.provide(Wc(Pt.layer)));rt.runMain(Kc,{teardown:(e,t)=>{it.isSuccess(e)?t(Number(e.value)):at.defaultTeardown(e,t)}});export{};
|