@r_masseater/oxlint-plugin-decision 0.8.0 → 0.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -0
- package/dist/{app-UakaWKAT.mjs → app-D2bguKZ_.mjs} +137 -27
- package/dist/app-D2bguKZ_.mjs.map +1 -0
- package/dist/claim-rule-B0LCcxxc.mjs +36 -0
- package/dist/claim-rule-B0LCcxxc.mjs.map +1 -0
- package/dist/cloudflare-worker.mjs +111 -2
- package/dist/cloudflare-worker.mjs.map +1 -1
- package/dist/{index-HOwrGbIA.d.mts → index-B4wX62VC.d.mts} +2 -2
- package/dist/{index-C0Twu0w7.d.mts → index-CK88FBE5.d.mts} +666 -319
- package/dist/index.d.mts +1 -1
- package/dist/index.mjs +1 -1
- package/dist/{define-presets-yflVt8vT.mjs → preset-plugin-MKdvpXxa.mjs} +11 -214
- package/dist/preset-plugin-MKdvpXxa.mjs.map +1 -0
- package/dist/presets/ai-slop.d.mts +2 -2
- package/dist/presets/ai-slop.mjs +179 -2
- package/dist/presets/ai-slop.mjs.map +1 -1
- package/dist/presets/index.d.mts +1 -1
- package/dist/presets/index.mjs +1 -1
- package/dist/presets/recommended.d.mts +1 -1
- package/dist/presets/recommended.mjs +1 -2
- package/dist/presets/recommended.mjs.map +1 -1
- package/dist/presets/review-only.d.mts +1 -1
- package/dist/presets/review-only.mjs +1 -2
- package/dist/presets/review-only.mjs.map +1 -1
- package/dist/presets/strict.d.mts +1 -1
- package/dist/presets/strict.mjs +1 -2
- package/dist/presets/strict.mjs.map +1 -1
- package/dist/serve-decisions-D6M-l2uy.mjs +232 -0
- package/dist/serve-decisions-D6M-l2uy.mjs.map +1 -0
- package/dist/typesafe-worker.mjs +20 -2
- package/dist/typesafe-worker.mjs.map +1 -1
- package/dist/{decision-B7hahWHz.mjs → wire-CKpt_MBX.mjs} +11 -134
- package/dist/wire-CKpt_MBX.mjs.map +1 -0
- package/package.json +23 -21
- package/skills/write-decision-rules/SKILL.md +0 -1
- package/skills/write-decision-rules/references/tuning.md +2 -2
- package/dist/app-UakaWKAT.mjs.map +0 -1
- package/dist/decision-B7hahWHz.mjs.map +0 -1
- package/dist/define-presets-yflVt8vT.mjs.map +0 -1
- package/dist/preset-plugin-ClpEFUN5.mjs +0 -10
- package/dist/preset-plugin-ClpEFUN5.mjs.map +0 -1
- package/dist/serve-decisions-DYGwLMft.mjs +0 -287
- package/dist/serve-decisions-DYGwLMft.mjs.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"decision-B7hahWHz.mjs","names":["Arr","Rec","DATA_FIRST_ARITY","Rec","Fn","DATA_FIRST_ARITY","DATA_FIRST_ARITY_3","FIRST_LINE","Str","Num","Bool","Arr","Fn","Rec","FIRST_LINE","Rec","Str","DATA_FIRST_ARITY_3","FIRST_LINE","Arr","Str","Fn","DATA_FIRST_ARITY_3","Str","Fn","DATA_FIRST_ARITY","Arr","Str","Fn","Rec","DATA_FIRST_ARITY","Bool","Str","Num","Fn","Arr","Rec","Fn","Str","Arr","Rec"],"sources":["../src/entities/decision/model/schema.ts","../src/entities/decision/model/answer.ts","../src/entities/decision/model/location.ts","../src/entities/decision/model/nodes.ts","../src/entities/decision/model/context.ts","../src/entities/decision/model/name.ts","../src/entities/decision/model/models.ts","../src/entities/decision/model/options.ts","../src/entities/decision/model/request.ts","../src/entities/decision/model/runtime.ts","../src/entities/decision/model/wire.ts"],"sourcesContent":["import { Schema, Array as Arr, Record as Rec, pipe } from \"effect\";\n\nconst NONE = 0;\nconst MINIMUM_LABELS = 2;\n\nconst NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(NONE));\n\nexport const Probability = Schema.Finite.check(Schema.isBetween({ minimum: 0, maximum: 1 }));\n\nexport const CONFIDENT = 0.8;\n\nexport const Cutoff = Schema.Finite.check(\n Schema.isBetween(\n { minimum: CONFIDENT, maximum: 1 },\n { message: `cutoff must be between ${CONFIDENT} and 1` },\n ),\n);\n\nexport const TargetSchema = Schema.Literals([\"function\", \"call\", \"jsx\", \"file\"]);\n\nexport const CiBehaviorSchema = Schema.Literals([\"skip\", \"fail\"]);\n\nexport const ExplainSettingSchema = Schema.Union([\n Schema.Boolean,\n Schema.Literals([\"text\", \"json\"]),\n]);\n\nexport const EnclosingKindSchema = Schema.Literals([\"function\", \"class\", \"block\"]);\n\nexport const RuleContextSchema = Schema.Union([\n Schema.Struct({ scope: Schema.Literals([\"node\", \"file\", \"comment\"]) }),\n Schema.Struct({\n scope: Schema.Literal(\"lines\"),\n before: Schema.optionalKey(NonNegativeInt),\n after: Schema.optionalKey(NonNegativeInt),\n }),\n Schema.Struct({ scope: Schema.Literal(\"enclosing\"), kind: EnclosingKindSchema }),\n]);\n\nexport const SeveritySchema = Schema.Literals([\"info\", \"warn\", \"error\"]);\n\nconst Label = Schema.NonEmptyString;\n\nconst BooleanAnswer = Schema.Struct({ kind: Schema.Literal(\"boolean\") });\n\nconst ClassifyAnswer = Schema.Struct({\n kind: Schema.Literal(\"classify\"),\n labels: Schema.Record(Label, Schema.String).check(Schema.isMinProperties(MINIMUM_LABELS)),\n report: Schema.NonEmptyArray(Label),\n}).check(\n Schema.makeFilter(\n ({ labels, report }) =>\n pipe(\n report,\n Arr.every((label) => Rec.has(labels, label)),\n ),\n {\n message: \"every label in report must be one of labels\",\n },\n ),\n);\n\nconst SeverityAnswer = Schema.Struct({\n kind: Schema.Literal(\"severity\"),\n minimum: Schema.optionalKey(SeveritySchema),\n});\n\nexport const RuleAnswerSchema = Schema.Union([BooleanAnswer, ClassifyAnswer, SeverityAnswer]);\n","import { Option, Result, Schema, Record as Rec, Function as Fn } from \"effect\";\n\nimport { Probability, RuleAnswerSchema } from \"./schema.ts\";\nimport type {\n Answer,\n ChoiceAnswer,\n NoulAnswer,\n Question,\n RuleAnswer,\n Severity,\n Verdict,\n} from \"./types.ts\";\n\nconst DATA_FIRST_ARITY = 2;\n\nconst YES = \"yes\";\nconst DEFAULT_MINIMUM: Severity = \"warn\";\n\nconst SEVERITY_CRITERIA = {\n none: \"No problem\",\n info: \"Worth noting, but not a problem\",\n warn: \"Likely a problem\",\n error: \"Clearly a problem\",\n} as const;\n\nexport const SEVERITY_ORDER: readonly string[] = Rec.keys(SEVERITY_CRITERIA);\n\nexport const BOOLEAN_ANSWER: RuleAnswer = { kind: \"boolean\" };\n\nconst decodeAnswer = Schema.decodeUnknownResult(RuleAnswerSchema);\n\nexport const decodeRuleAnswer = (answer: unknown): Result.Result<RuleAnswer, string> => {\n const decoded = decodeAnswer(answer);\n if (Result.isSuccess(decoded)) {\n return Result.succeed(decoded.success);\n }\n return Result.fail(decoded.failure.message);\n};\n\nconst NoulAnswerSchema = Schema.Struct({ type: Schema.Literal(\"noul\"), noul: Probability });\n\nconst ChoiceAnswerSchema = Schema.Struct({\n type: Schema.Literal(\"choice\"),\n choice: Schema.String,\n probabilities: Schema.optional(Schema.Record(Schema.String, Probability)),\n} satisfies Partial<Record<keyof ChoiceAnswer, Schema.Top>>);\n\nexport const AnswerSchema = Schema.Union([NoulAnswerSchema, ChoiceAnswerSchema]);\n\nconst decodeNoul = Schema.decodeOption(NoulAnswerSchema);\n\nconst decodeChoice = Schema.decodeOption(ChoiceAnswerSchema);\n\nconst isNoul = (answer: Answer): answer is NoulAnswer => answer.type === \"noul\";\n\nconst isChoice = (answer: Answer): answer is ChoiceAnswer => answer.type === \"choice\";\n\nexport const noulOf = (answer: Answer | undefined): Option.Option<NoulAnswer> =>\n Option.fromUndefinedOr(answer).pipe(Option.filter(isNoul), Option.flatMap(decodeNoul));\n\nexport const choiceOf = (answer: Answer | undefined): Option.Option<ChoiceAnswer> =>\n Option.fromUndefinedOr(answer).pipe(Option.filter(isChoice), Option.flatMap(decodeChoice));\n\nexport const probabilityOfChoice = ({\n choice,\n probabilities,\n}: ChoiceAnswer): Option.Option<number> =>\n Option.fromUndefinedOr(probabilities).pipe(\n Option.flatMap((byLabel) => Option.fromUndefinedOr(byLabel[choice])),\n );\n\nexport const questionFor: {\n (instructions: string): (answer: RuleAnswer) => Question;\n (answer: RuleAnswer, instructions: string): Question;\n} = Fn.dual(DATA_FIRST_ARITY, (answer: RuleAnswer, instructions: string): Question => {\n switch (answer.kind) {\n case \"classify\": {\n return {\n type: \"choice\",\n instructions: `${instructions} Select the label that fits best.`,\n criteria: answer.labels,\n };\n }\n case \"severity\": {\n return {\n type: \"choice\",\n instructions: `${instructions} Rate how serious the problem is, and select none if there is no problem.`,\n criteria: SEVERITY_CRITERIA,\n };\n }\n case \"boolean\": {\n return { type: \"noul\", instructions };\n }\n default: {\n return { type: \"noul\", instructions };\n }\n }\n});\n\nconst choiceVerdictOf = (\n criteria: Readonly<Record<string, unknown>>,\n answer: Answer | undefined,\n): Option.Option<Verdict> =>\n choiceOf(answer).pipe(\n Option.filter(({ choice }) => Rec.has(criteria, choice)),\n Option.flatMap((chosen) =>\n Option.map(probabilityOfChoice(chosen), (probability) => ({\n answer: chosen.choice,\n probability,\n })),\n ),\n );\n\nexport const verdictOf: {\n (answer: Answer | undefined): (question: Question) => Option.Option<Verdict>;\n (question: Question, answer: Answer | undefined): Option.Option<Verdict>;\n} = Fn.dual(\n DATA_FIRST_ARITY,\n (question: Question, answer: Answer | undefined): Option.Option<Verdict> => {\n if (question.type === \"choice\") {\n return choiceVerdictOf(question.criteria, answer);\n }\n return noulOf(answer).pipe(Option.map(({ noul }) => ({ answer: YES, probability: noul })));\n },\n);\n\nconst severityMatches = (\n { minimum = DEFAULT_MINIMUM }: { readonly minimum?: Severity },\n label: string,\n): boolean => SEVERITY_ORDER.indexOf(label) >= SEVERITY_ORDER.indexOf(minimum);\n\nconst answerMatches = (answer: RuleAnswer, label: string): boolean => {\n switch (answer.kind) {\n case \"classify\": {\n return answer.report.includes(label);\n }\n case \"severity\": {\n return severityMatches(answer, label);\n }\n case \"boolean\": {\n return label === YES;\n }\n default: {\n return false;\n }\n }\n};\n\nexport const isReported: {\n (verdict: Verdict): (rule: { readonly answer: RuleAnswer; readonly cutoff: number }) => boolean;\n (rule: { readonly answer: RuleAnswer; readonly cutoff: number }, verdict: Verdict): boolean;\n} = Fn.dual(\n DATA_FIRST_ARITY,\n (rule: { readonly answer: RuleAnswer; readonly cutoff: number }, verdict: Verdict): boolean =>\n verdict.probability >= rule.cutoff && answerMatches(rule.answer, verdict.answer),\n);\n","import type { Location } from \"@oxlint/plugins\";\nimport {\n Array as Arr,\n Boolean as Bool,\n Number as Num,\n Option,\n Predicate,\n String as Str,\n Record as Rec,\n pipe,\n Function as Fn,\n} from \"effect\";\n\nimport { choiceOf, probabilityOfChoice } from \"./answer.ts\";\nimport type { Answer, ChoiceQuestion, LineRange, RequestMatch, RuleLocation } from \"./types.ts\";\n\nconst DATA_FIRST_ARITY = 2;\nconst DATA_FIRST_ARITY_3 = 3;\nconst CHOICE_OPTION_LIMIT = 254;\nconst FIRST_LINE = 1;\nconst MINIMUM_WIDTH = 1;\nconst UNKNOWN_CHOICE = \"unknown\";\n\nexport const sourceLines = (text: string): readonly string[] =>\n Str.split(text, /\\r\\n|[\\n\\r\\u2028\\u2029]/u);\n\nexport type LocatedMatch = RequestMatch & {\n readonly rule: { readonly question: string; readonly location: RuleLocation };\n};\n\nexport const locates = (match: RequestMatch): match is LocatedMatch =>\n Predicate.isNotUndefined(match.rule.location) && !match.truncated;\n\nexport interface NumberedLine {\n readonly text: string;\n readonly line: number;\n}\n\nexport const EVERY_LINE: LineRange = { start: FIRST_LINE, end: Number.POSITIVE_INFINITY };\n\nconst isWithin = (line: number, within: LineRange): boolean =>\n Num.between(line, { minimum: within.start, maximum: within.end });\n\nconst rangeKey = ({ start, end }: LineRange): string =>\n Bool.match(start === end, {\n onTrue: () => `L${String(start)}`,\n onFalse: () => `L${String(start)}-L${String(end)}`,\n });\n\nconst rangeLabel = ({ start, end }: LineRange): string =>\n Bool.match(start === end, {\n onTrue: () => `Line ${String(start)}`,\n onFalse: () => `Lines ${String(start)} to ${String(end)}`,\n });\n\nconst rangeOf = (group: Arr.NonEmptyReadonlyArray<NumberedLine>): LineRange => ({\n start: Arr.headNonEmpty(group).line,\n end: Arr.lastNonEmpty(group).line,\n});\n\nexport const numberedLines = (snippet: string): readonly NumberedLine[] =>\n pipe(\n sourceLines(snippet),\n Arr.map((text, index) => ({ text, line: Num.sum(index, FIRST_LINE) })),\n );\n\nexport const locationCandidates: {\n (within: LineRange): (snippet: string) => Readonly<Record<string, LineRange>>;\n (snippet: string, within: LineRange): Readonly<Record<string, LineRange>>;\n} = Fn.dual(\n DATA_FIRST_ARITY,\n (snippet: string, within: LineRange): Readonly<Record<string, LineRange>> => {\n const lines = pipe(\n numberedLines(snippet),\n Arr.filter(({ text, line }) => Str.trim(text).length >= FIRST_LINE && isWithin(line, within)),\n );\n const width = Math.max(MINIMUM_WIDTH, Math.ceil(lines.length / CHOICE_OPTION_LIMIT));\n return Rec.fromEntries(\n pipe(\n Arr.chunksOf(lines, width),\n Arr.map((group) => {\n const range = rangeOf(group);\n return [rangeKey(range), range];\n }),\n ),\n );\n },\n);\n\nexport const locationQuestion: {\n (\n ref: string,\n candidates: Readonly<Record<string, LineRange>>,\n ): (match: LocatedMatch) => ChoiceQuestion;\n (\n match: LocatedMatch,\n ref: string,\n candidates: Readonly<Record<string, LineRange>>,\n ): ChoiceQuestion;\n} = Fn.dual(\n DATA_FIRST_ARITY_3,\n (\n match: LocatedMatch,\n ref: string,\n candidates: Readonly<Record<string, LineRange>>,\n ): ChoiceQuestion => ({\n type: \"choice\",\n instructions: `Consider only the numbered source in state.snippets.${ref}. If it violates this rule, select the line (or range containing that line) to annotate. Rule: ${match.rule.question} Location: ${match.rule.location.question} If multiple violations exist, select the earliest one. Select ${UNKNOWN_CHOICE} if no violation exists or its location is unclear.`,\n criteria: {\n ...Rec.fromEntries(\n pipe(\n Rec.toEntries(candidates),\n Arr.map(([key, range]) => [key, rangeLabel(range)]),\n ),\n ),\n [UNKNOWN_CHOICE]: \"No clear source location for this violation\",\n },\n }),\n);\n\nexport type ChoiceCriteria = ChoiceQuestion[\"criteria\"];\n\nexport const validChoice: {\n (criteria: ChoiceCriteria): (answer: Answer | undefined) => boolean;\n (answer: Answer | undefined, criteria: ChoiceCriteria): boolean;\n} = Fn.dual(DATA_FIRST_ARITY, (answer: Answer | undefined, criteria: ChoiceCriteria): boolean =>\n Option.exists(\n choiceOf(answer),\n (chosen) => Rec.has(criteria, chosen.choice) && Option.isSome(probabilityOfChoice(chosen)),\n ),\n);\n\nexport const selectedLocation: {\n (\n candidates: Readonly<Record<string, LineRange>>,\n cutoff: number,\n ): (answer: Answer | undefined) => Option.Option<LineRange>;\n (\n answer: Answer | undefined,\n candidates: Readonly<Record<string, LineRange>>,\n cutoff: number,\n ): Option.Option<LineRange>;\n} = Fn.dual(\n DATA_FIRST_ARITY_3,\n (\n answer: Answer | undefined,\n candidates: Readonly<Record<string, LineRange>>,\n cutoff: number,\n ): Option.Option<LineRange> =>\n choiceOf(answer).pipe(\n Option.filter((chosen) =>\n Option.exists(probabilityOfChoice(chosen), (probability) =>\n Num.isGreaterThanOrEqualTo(probability, cutoff),\n ),\n ),\n Option.flatMap(({ choice }) => Option.fromUndefinedOr(candidates[choice])),\n ),\n);\n\nexport const locationOfLine: {\n (line: number): (snippet: string) => Location;\n (snippet: string, line: number): Location;\n} = Fn.dual(DATA_FIRST_ARITY, (snippet: string, line: number): Location => {\n const text = Option.getOrElse(Arr.get(sourceLines(snippet), Num.decrement(line)), () => \"\");\n return {\n start: {\n line,\n column: Option.getOrElse(Str.search(/\\S/u)(text), () => Num.decrement(FIRST_LINE)),\n },\n end: { line, column: Str.trimEnd(text).length },\n };\n});\n","import type { Location } from \"@oxlint/plugins\";\nimport { Option, String as Str, Record as Rec } from \"effect\";\n\nimport type { AstNode, Target } from \"./types.ts\";\n\nconst FIRST_LINE = 1;\nconst FIRST_COLUMN = 0;\nexport const TARGET_NODE_TYPES = {\n function: [\"FunctionDeclaration\", \"FunctionExpression\", \"ArrowFunctionExpression\"],\n call: [\"CallExpression\"],\n jsx: [\"JSXElement\"],\n file: [\"Program\"],\n} as const satisfies Readonly<Record<Target, readonly string[]>>;\n\nconst NAMED_PARENTS = {\n VariableDeclarator: \"init\",\n Property: \"value\",\n MethodDefinition: \"value\",\n PropertyDefinition: \"value\",\n} as const;\n\ntype NamedField = (typeof NAMED_PARENTS)[keyof typeof NAMED_PARENTS];\n\nconst NAMED_PARENT_TYPES: ReadonlySet<string> = new Set(Rec.keys(NAMED_PARENTS));\n\nconst isNamedParentType = (type: string): type is keyof typeof NAMED_PARENTS =>\n NAMED_PARENT_TYPES.has(type);\n\nconst ANONYMOUS_FUNCTIONS: ReadonlySet<string> = new Set([\n \"FunctionExpression\",\n \"ArrowFunctionExpression\",\n]);\n\nconst holdsAsName = (parent: AstNode, node: AstNode): boolean => {\n if (!isNamedParentType(parent.type)) {\n return false;\n }\n const field: NamedField = NAMED_PARENTS[parent.type];\n return ANONYMOUS_FUNCTIONS.has(node.type) && parent[field] === node;\n};\n\nexport const snippetNodeFor = (node: AstNode): AstNode =>\n Option.fromNullishOr(node.parent).pipe(\n Option.filter((parent) => holdsAsName(parent, node)),\n Option.getOrElse((): AstNode => node),\n );\nconst headOf = (text: string, line: number, column: number): Location => {\n const [first] = Str.split(text, \"\\n\");\n return { start: { line, column }, end: { line, column: column + first.length } };\n};\n\nexport const REPORT_LOC = {\n function: (node: AstNode, text: string): Location =>\n headOf(text, node.loc.start.line, node.loc.start.column),\n call: (node: AstNode): Location => node.loc,\n jsx: (node: AstNode): Location =>\n Option.getOrElse(Option.fromNullishOr(node.openingElement), () => node).loc,\n file: (_node: AstNode, text: string): Location => headOf(text, FIRST_LINE, FIRST_COLUMN),\n} as const satisfies Readonly<Record<Target, (node: AstNode, text: string) => Location>>;\n","import type { Context } from \"@oxlint/plugins\";\nimport { Array as Arr, Option, Predicate, String as Str, pipe, Function as Fn } from \"effect\";\n\nimport { sourceLines } from \"./location.ts\";\nimport { snippetNodeFor } from \"./nodes.ts\";\nimport type { AstNode, EnclosingKind, ResolvedRule, RuleContext } from \"./types.ts\";\n\nconst DATA_FIRST_ARITY_3 = 3;\n\nconst DEFAULT_LINES = 5;\nconst FIRST_LINE = 1;\nconst LAST = 1;\nconst END = 1;\n\nconst ENCLOSING_TYPES: Readonly<Record<EnclosingKind, readonly string[]>> = {\n function: [\"FunctionDeclaration\", \"FunctionExpression\", \"ArrowFunctionExpression\"],\n class: [\"ClassDeclaration\", \"ClassExpression\"],\n block: [\"BlockStatement\", \"StaticBlock\", \"Program\"],\n};\n\nconst ancestorsOf = (node: AstNode): readonly AstNode[] =>\n Arr.unfold(Option.fromNullishOr(node.parent), (current) =>\n current.pipe(\n Option.map((ancestor) => [ancestor, Option.fromNullishOr(ancestor.parent)] as const),\n ),\n );\n\nconst enclosingText = (context: Context, node: AstNode, kind: EnclosingKind): string =>\n Arr.findFirst(ancestorsOf(node), (ancestor) =>\n ENCLOSING_TYPES[kind].includes(ancestor.type),\n ).pipe(\n Option.match({\n onNone: () => context.sourceCode.text,\n onSome: (ancestor) => context.sourceCode.getText(ancestor),\n }),\n );\n\nconst linesAround = (\n context: Context,\n node: AstNode,\n {\n before = DEFAULT_LINES,\n after = DEFAULT_LINES,\n }: { readonly before?: number; readonly after?: number },\n): string => {\n const lines = sourceLines(context.sourceCode.text);\n const first = Math.max(FIRST_LINE, node.loc.start.line - before);\n const last = Math.min(lines.length, node.loc.end.line + after);\n return pipe(\n lines,\n Arr.drop(first - FIRST_LINE),\n Arr.take(last - first + FIRST_LINE),\n Arr.map((text, index) => `L${String(first + index)}| ${text}`),\n Arr.join(\"\\n\"),\n );\n};\n\nconst DECLARING_PARENTS: ReadonlySet<string> = new Set([\n \"VariableDeclaration\",\n \"ExportNamedDeclaration\",\n \"ExportDefaultDeclaration\",\n]);\n\nconst declarationOf = (node: AstNode): AstNode =>\n Option.fromNullishOr(node.parent).pipe(\n Option.filter((parent) => DECLARING_PARENTS.has(parent.type)),\n Option.match({ onNone: () => node, onSome: declarationOf }),\n );\n\ninterface Span {\n readonly start: number;\n readonly end: number;\n}\n\nconst leadingOf = (text: string, comments: readonly Span[], until: number): readonly Span[] =>\n Option.match(Arr.last(comments), {\n onNone: () => [],\n onSome: (last) => {\n if (Str.isNonEmpty(Str.trim(Str.slice(last.end, until)(text)))) {\n return [];\n }\n return [...leadingOf(text, Arr.dropRight(comments, LAST), last.start), last];\n },\n });\n\nconst commentedTextOf = (context: Context, node: AstNode): Option.Option<string> => {\n const { text } = context.sourceCode;\n const named = snippetNodeFor(node);\n const [start] = declarationOf(named).range;\n const before = pipe(\n context.sourceCode.getAllComments(),\n Arr.filter((comment) => comment.type !== \"Shebang\" && comment.end <= start),\n );\n return Arr.match(leadingOf(text, before, start), {\n onEmpty: () => Option.none(),\n onNonEmpty: ([first]) => Option.some(Str.slice(first.start, named.range[END])(text)),\n });\n};\n\nconst isCommented = ({ context: wanted }: ResolvedRule): boolean =>\n Predicate.isNotUndefined(wanted) && wanted.scope === \"comment\";\n\nexport const commentedSnippetOf: {\n (node: AstNode, rule: ResolvedRule): (context: Context) => Option.Option<string>;\n (context: Context, node: AstNode, rule: ResolvedRule): Option.Option<string>;\n} = Fn.dual(\n DATA_FIRST_ARITY_3,\n (context: Context, node: AstNode, rule: ResolvedRule): Option.Option<string> =>\n Option.flatMap(Option.liftPredicate(rule, isCommented), () => commentedTextOf(context, node)),\n);\n\nexport const lacksComment: {\n (node: AstNode, rule: ResolvedRule): (context: Context) => boolean;\n (context: Context, node: AstNode, rule: ResolvedRule): boolean;\n} = Fn.dual(\n DATA_FIRST_ARITY_3,\n (context: Context, node: AstNode, rule: ResolvedRule): boolean =>\n isCommented(rule) && Option.isNone(commentedTextOf(context, node)),\n);\n\nexport const contextOf: {\n (node: AstNode, rule: RuleContext): (context: Context) => Option.Option<string>;\n (context: Context, node: AstNode, rule: RuleContext): Option.Option<string>;\n} = Fn.dual(\n DATA_FIRST_ARITY_3,\n (context: Context, node: AstNode, rule: RuleContext): Option.Option<string> => {\n if (rule.scope === \"lines\") {\n return Option.some(linesAround(context, node, rule));\n }\n if (rule.scope === \"enclosing\") {\n return Option.some(enclosingText(context, node, rule.kind));\n }\n return Option.liftPredicate(context.sourceCode.text, () => rule.scope === \"file\");\n },\n);\n","import type { Context } from \"@oxlint/plugins\";\nimport { Match, Option, String as Str, Function as Fn } from \"effect\";\n\nimport type { DecisionRule, SelectedNode } from \"./types.ts\";\n\nconst DATA_FIRST_ARITY_3 = 3;\n\nconst heldName = (node: SelectedNode): Option.Option<SelectedNode> =>\n Option.flatMap(Option.fromNullishOr(node.parent), (parent) =>\n Match.value(parent).pipe(\n Match.when({ type: \"VariableDeclarator\" }, (holder) =>\n Option.liftPredicate(holder.id, () => holder.init === node),\n ),\n Match.when(\n { type: Match.is(\"Property\", \"MethodDefinition\", \"PropertyDefinition\") },\n (holder) => Option.liftPredicate(holder.key, () => holder.value === node),\n ),\n Match.orElse(() => Option.none<SelectedNode>()),\n ),\n );\n\nconst nameNodeOf = (node: SelectedNode): Option.Option<SelectedNode> =>\n Match.value(node).pipe(\n Match.when({ type: Match.is(\"FunctionDeclaration\", \"FunctionExpression\") }, (fn) =>\n Option.orElse(Option.fromNullishOr(fn.id), () => heldName(fn)),\n ),\n Match.when({ type: \"ArrowFunctionExpression\" }, heldName),\n Match.when({ type: Match.is(\"CallExpression\", \"NewExpression\") }, (call) =>\n Option.some(call.callee),\n ),\n Match.when({ type: \"JSXElement\" }, (element) => Option.some(element.openingElement.name)),\n Match.orElse(() => Option.none<SelectedNode>()),\n );\n\nconst nameOf = (node: SelectedNode, context: Context): string | undefined =>\n Option.getOrUndefined(\n Option.map(nameNodeOf(node), (name) =>\n Str.slice(name.start, name.end)(context.sourceCode.text),\n ),\n );\n\nexport const isSelected: {\n (node: SelectedNode, rule: DecisionRule): (context: Context) => boolean;\n (context: Context, node: SelectedNode, rule: DecisionRule): boolean;\n} = Fn.dual(\n DATA_FIRST_ARITY_3,\n (context: Context, node: SelectedNode, { select }: DecisionRule): boolean =>\n Option.match(Option.fromUndefinedOr(select), {\n onNone: () => true,\n onSome: (selects) => selects(node, { name: nameOf(node, context), context }),\n }),\n);\n","import { Schema } from \"effect\";\n\nexport type DecisionModel =\n | \"typesafe/jev-latest\"\n | `typesafe/jev-${number}.${number}`\n | \"cloudflare/@cf/cloudflare/clef\"\n | \"cloudflare/@cf/cloudflare/clef-flash\"\n | \"cloudflare/@cf/cloudflare/clef-omni\";\n\nexport const JEV_MODEL = /^jev-(?:latest|\\d+\\.\\d+)$/u;\n\nexport const CLEF_MODEL = /^@cf\\/cloudflare\\/clef(?:-flash|-omni)?$/u;\n\nconst DECISION_MODEL =\n /^(?:typesafe\\/jev-(?:latest|\\d+\\.\\d+)|cloudflare\\/@cf\\/cloudflare\\/clef(?:-flash|-omni)?)$/u;\n\nconst isDecisionModel = (model: string): model is DecisionModel => DECISION_MODEL.test(model);\n\nexport const DecisionModelSchema = Schema.String.pipe(\n Schema.refine(isDecisionModel, {\n message:\n 'model must be a decision model: \"typesafe/jev-latest\", \"typesafe/jev-<major>.<minor>\", or \"cloudflare/@cf/cloudflare/clef\", \"clef-flash\" or \"clef-omni\"',\n }),\n);\n","import {\n Array as Arr,\n Option,\n Predicate,\n Result,\n Schema,\n String as Str,\n Record as Rec,\n pipe,\n Function as Fn,\n} from \"effect\";\n\nimport { BOOLEAN_ANSWER, decodeRuleAnswer } from \"./answer.ts\";\nimport { DecisionModelSchema } from \"./models.ts\";\nimport type { DecisionModel } from \"./models.ts\";\nimport {\n CiBehaviorSchema,\n Cutoff,\n ExplainSettingSchema,\n RuleContextSchema,\n TargetSchema,\n} from \"./schema.ts\";\nimport type {\n DecisionOptions,\n DecisionProvider,\n DecisionRule,\n ModelRef,\n ModelSpec,\n ResolvedOptions,\n ResolvedRule,\n RuleAnswer,\n} from \"./types.ts\";\n\nconst DATA_FIRST_ARITY_3 = 3;\n\nconst DATA_FIRST_ARITY = 2;\n\nexport const PREFIX = \"oxlint-plugin-decision\";\nconst PROVIDER_SEPARATOR = \"/\";\nconst ONE_RULE = 1;\n\nconst DEFAULTS = {\n ci: \"fail\",\n timeoutMs: 10_000,\n maxSnippetChars: 4000,\n model: \"cloudflare/@cf/cloudflare/clef-flash\",\n env: {},\n explain: false,\n} as const satisfies Required<DecisionOptions>;\n\nconst isSelector = (input: unknown): input is DecisionRule[\"select\"] => Predicate.isFunction(input);\n\nconst RULE_ID = /^[a-z0-9]+(?:-[a-z0-9]+)*$/u;\n\nexport const ModelSpecSchema = Schema.Union([\n DecisionModelSchema,\n Schema.NonEmptyArray(DecisionModelSchema),\n]);\n\nconst ONE = 1;\n\nconst PositiveInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(ONE));\n\nconst RuleId = Schema.NonEmptyString.check(\n Schema.isPattern(RULE_ID, { message: \"id must be lowercase words joined by hyphens\" }),\n);\n\nconst OptionsSchema = Schema.Struct({\n ci: Schema.optionalKey(CiBehaviorSchema),\n timeoutMs: Schema.optionalKey(PositiveInt),\n maxSnippetChars: Schema.optionalKey(PositiveInt),\n model: Schema.optionalKey(ModelSpecSchema),\n env: Schema.optionalKey(Schema.Record(Schema.NonEmptyString, Schema.NonEmptyString)),\n explain: Schema.optionalKey(ExplainSettingSchema),\n});\n\nconst RuleSchema = Schema.Struct({\n id: RuleId,\n target: TargetSchema,\n question: Schema.NonEmptyString,\n cutoff: Cutoff,\n message: Schema.optionalKey(Schema.NonEmptyString),\n select: Schema.optionalKey(Schema.declare(isSelector)),\n location: Schema.optionalKey(Schema.Struct({ question: Schema.NonEmptyString, cutoff: Cutoff })),\n model: Schema.optionalKey(ModelSpecSchema),\n context: Schema.optionalKey(RuleContextSchema),\n answer: Schema.optionalKey(Schema.Unknown),\n});\n\nexport const STRICT = { onExcessProperty: \"error\" } as const;\n\nconst decodeOptions = Schema.decodeUnknownResult(OptionsSchema, STRICT);\nconst decodeRule = Schema.decodeUnknownResult(RuleSchema, STRICT);\n\nconst taggedError = Schema.TaggedError;\n\nclass OptionsError extends taggedError<OptionsError, { readonly brand: unique symbol }>()(\n \"OptionsError\",\n { message: Schema.String },\n) {}\n\nexport const optionsError = (message: string): Error =>\n OptionsError.make({ message: `${PREFIX}: ${message}` });\n\nexport const modelIdsOf = (spec: ModelSpec): readonly DecisionModel[] =>\n Arr.dedupe(Arr.ensure(spec));\n\nconst splitModelId = (id: string): Option.Option<readonly [string, string]> => {\n const [provider, ...rest] = Str.split(id, PROVIDER_SEPARATOR);\n const model = pipe(rest, Arr.join(PROVIDER_SEPARATOR));\n return Option.liftPredicate(\n [provider, model] as const,\n ([left, right]) => Str.isNonEmpty(left) && Str.isNonEmpty(right),\n );\n};\n\nconst acceptedModel = (ref: ModelRef): ModelRef => {\n const { models, name } = ref.provider;\n if (!models.test(ref.model)) {\n throw optionsError(\n `model \"${ref.id}\" is not a decision model that the \"${name}\" provider accepts`,\n );\n }\n return ref;\n};\n\nexport const resolveModel: {\n (providers: Readonly<Record<string, DecisionProvider>>): (id: string) => ModelRef;\n (id: string, providers: Readonly<Record<string, DecisionProvider>>): ModelRef;\n} = Fn.dual(\n DATA_FIRST_ARITY,\n (id: string, providers: Readonly<Record<string, DecisionProvider>>): ModelRef =>\n acceptedModel(\n splitModelId(id).pipe(\n Option.flatMap(([name, model]) =>\n Option.map(Option.fromUndefinedOr(providers[name]), (provider) => ({\n id,\n provider,\n model,\n })),\n ),\n\n Option.getOrThrowWith(() =>\n optionsError(\n `model \"${id}\" must be \"<provider>/<model>\" with a provider from: ${pipe(Rec.keys(providers), Arr.join(\", \"))}`,\n ),\n ),\n ),\n ),\n);\n\nconst duplicateIdOf = (rules: readonly DecisionRule[]): Option.Option<string> =>\n Arr.findFirst(\n Rec.toEntries(Arr.groupBy(rules, ({ id }) => id)),\n ([, same]) => same.length > ONE_RULE,\n ).pipe(Option.map(([id]) => id));\n\nconst answerOf = (rule: DecisionRule): RuleAnswer => {\n if (Predicate.isUndefined(rule.answer)) {\n return BOOLEAN_ANSWER;\n }\n return Result.getOrThrowWith(decodeRuleAnswer(rule.answer), (issue) =>\n optionsError(`rule \"${rule.id}\" has an invalid answer: ${issue}`),\n );\n};\n\nexport type Decode<Value> = (input: unknown) => Result.Result<Value, Schema.SchemaError>;\n\nexport const checked: {\n (input: unknown, what: string): <Value>(decode: Decode<Value>) => Value;\n <Value>(decode: Decode<Value>, input: unknown, what: string): Value;\n} = Fn.dual(\n DATA_FIRST_ARITY_3,\n <Value>(decode: Decode<Value>, input: unknown, what: string): Value =>\n Result.getOrThrowWith(decode(input), (issue) =>\n optionsError(`invalid ${what}: ${issue.message}`),\n ),\n);\n\nconst checkRule = (rule: DecisionRule): DecisionRule => {\n checked(decodeRule, rule, `rule \"${rule.id}\"`);\n if (Predicate.isNotUndefined(rule.location) && rule.target !== \"file\") {\n throw optionsError(\"location is supported only for file rules\");\n }\n answerOf(rule);\n return rule;\n};\n\nexport const checkRules = (rules: readonly DecisionRule[]): readonly DecisionRule[] => {\n if (!Arr.isReadonlyArrayNonEmpty(rules)) {\n throw optionsError(\"rules must list at least one rule\");\n }\n Option.map(duplicateIdOf(rules), (duplicate) => {\n throw optionsError(`rule id \"${duplicate}\" is used more than once`);\n });\n return pipe(\n rules,\n Arr.map((rule) => checkRule(rule)),\n );\n};\n\nconst resolveRule =\n (fallback: ModelSpec, providers: Readonly<Record<string, DecisionProvider>>) =>\n (rule: DecisionRule): ResolvedRule => ({\n ...rule,\n answer: answerOf(rule),\n models: pipe(\n modelIdsOf(rule.model ?? fallback),\n Arr.map((id) => resolveModel(id, providers)),\n ),\n });\n\nexport interface Sources {\n readonly options: DecisionOptions;\n readonly settings?: unknown;\n}\n\nconst settingsFrom = (settings: unknown): DecisionOptions => {\n if (Predicate.isUndefined(settings)) {\n return {};\n }\n return checked(decodeOptions, settings, \"settings\");\n};\n\nexport const resolveOptions: {\n (\n rules: readonly DecisionRule[],\n providers: Readonly<Record<string, DecisionProvider>>,\n ): (sources: Sources) => ResolvedOptions;\n (\n sources: Sources,\n rules: readonly DecisionRule[],\n providers: Readonly<Record<string, DecisionProvider>>,\n ): ResolvedOptions;\n} = Fn.dual(\n DATA_FIRST_ARITY_3,\n (\n { options, settings }: Sources,\n rules: readonly DecisionRule[],\n providers: Readonly<Record<string, DecisionProvider>>,\n ): ResolvedOptions => {\n const fromCode = checked(decodeOptions, options, \"createDecisionPlugin options\");\n const { model, ...merged } = { ...DEFAULTS, ...fromCode, ...settingsFrom(settings) };\n return {\n ci: merged.ci,\n timeoutMs: merged.timeoutMs,\n maxSnippetChars: merged.maxSnippetChars,\n env: merged.env,\n explain: merged.explain,\n rules: pipe(\n checkRules(rules),\n Arr.map((rule) => resolveRule(model, providers)(rule)),\n ),\n };\n },\n);\n","import {\n Array as Arr,\n Boolean as Bool,\n Number as Num,\n Option,\n Predicate,\n String as Str,\n Record as Rec,\n pipe,\n Function as Fn,\n} from \"effect\";\n\nimport { questionFor, verdictOf } from \"./answer.ts\";\nimport {\n EVERY_LINE,\n locates,\n locationCandidates,\n locationQuestion,\n numberedLines,\n validChoice,\n} from \"./location.ts\";\nimport type { ChoiceCriteria } from \"./location.ts\";\nimport type {\n Answers,\n DecisionRequest,\n DecisionResponse,\n Question,\n RequestMatch,\n Verdict,\n Verdicts,\n} from \"./types.ts\";\n\nconst DATA_FIRST_ARITY = 2;\n\nconst FIRST_LINE = 1;\nconst LOCATION_SUFFIX = \"_location\";\nconst TRUNCATION_MARKER = \"/* ...truncated */\";\n\nexport const refAt = (index: number): string => `s${String(index)}`;\n\nexport const locationRefOf = (ref: string): string => `${ref}${LOCATION_SUFFIX}`;\n\nexport const snippetRefOf = (questionId: string): string =>\n Bool.match(Str.endsWith(LOCATION_SUFFIX)(questionId), {\n onTrue: () => Str.slice(Num.decrement(FIRST_LINE), -LOCATION_SUFFIX.length)(questionId),\n onFalse: () => questionId,\n });\n\nexport const truncateSnippet: {\n (maxChars: number): (text: string) => string;\n (text: string, maxChars: number): string;\n} = Fn.dual(DATA_FIRST_ARITY, (text: string, maxChars: number): string =>\n Bool.match(text.length <= maxChars, {\n onTrue: () => text,\n onFalse: () => `${Str.slice(Num.decrement(FIRST_LINE), maxChars)(text)}${TRUNCATION_MARKER}`,\n }),\n);\n\nconst numbered = (snippet: string): string =>\n pipe(\n numberedLines(snippet),\n Arr.map(({ text, line }) => `L${String(line)}| ${text}`),\n Arr.join(\"\\n\"),\n );\n\nconst contextNote = (match: RequestMatch, ref: string): string => {\n if (Predicate.isUndefined(match.context)) {\n return \"\";\n }\n return ` state.contexts.${ref} shows the source around it; use it only to understand the snippet.`;\n};\n\nconst mainQuestionFor = (match: RequestMatch, ref: string): readonly [string, Question] => [\n ref,\n questionFor(\n match.rule.answer,\n `Consider only snippet \"${ref}\" in state.snippets.${contextNote(match, ref)} ${match.rule.question}`,\n ),\n];\n\nconst questionsFor = (\n match: RequestMatch,\n ref: string,\n): readonly (readonly [string, Question])[] => {\n if (!locates(match)) {\n return [mainQuestionFor(match, ref)];\n }\n return [\n mainQuestionFor(match, ref),\n [\n locationRefOf(ref),\n locationQuestion(match, ref, locationCandidates(match.snippet, EVERY_LINE)),\n ],\n ];\n};\n\nconst snippetFor = (match: RequestMatch): string => {\n if (locates(match)) {\n return numbered(match.snippet);\n }\n return match.snippet;\n};\n\nconst contextsOf = (\n matches: readonly RequestMatch[],\n): Readonly<{ contexts?: Readonly<Record<string, string>> }> => {\n const contexts = pipe(\n matches,\n Arr.flatMap((match, index) =>\n Option.toArray(\n Option.map(Option.fromUndefinedOr(match.context), (text) => [refAt(index), text] as const),\n ),\n ),\n );\n if (Arr.isReadonlyArrayEmpty(contexts)) {\n return {};\n }\n return { contexts: Rec.fromEntries(contexts) };\n};\n\nexport const buildRequest: {\n (matches: readonly RequestMatch[]): (model: string) => DecisionRequest;\n (model: string, matches: readonly RequestMatch[]): DecisionRequest;\n} = Fn.dual(\n DATA_FIRST_ARITY,\n (model: string, matches: readonly RequestMatch[]): DecisionRequest => ({\n model,\n state: {\n snippets: Rec.fromEntries(\n pipe(\n matches,\n Arr.map((match, index) => [refAt(index), snippetFor(match)]),\n ),\n ),\n ...contextsOf(matches),\n },\n questions: Rec.fromEntries(\n pipe(\n matches,\n Arr.flatMap((match, index) => questionsFor(match, refAt(index))),\n ),\n ),\n }),\n);\n\nconst choiceQuestionsOf = (\n request: DecisionRequest,\n): readonly (readonly [string, ChoiceCriteria])[] =>\n pipe(\n Rec.toEntries(request.questions),\n Arr.flatMap(([id, question]) => {\n if (question.type === \"choice\") {\n return [[id, question.criteria] as const];\n }\n return [];\n }),\n );\n\nconst mainQuestionsOf = (request: DecisionRequest): readonly (readonly [string, Question])[] =>\n pipe(\n Rec.toEntries(request.questions),\n Arr.filter(([id]) => !Str.endsWith(LOCATION_SUFFIX)(id)),\n );\n\nconst resultOf = (\n answers: Answers,\n [ref, question]: readonly [string, Question],\n): readonly [string, Verdict] => [\n ref,\n Option.getOrThrowWith(\n verdictOf(question, answers[ref]),\n () => new Error(`response has no valid answer for \"${ref}\"`),\n ),\n];\n\nexport const parseVerdicts: {\n (request: DecisionRequest): (response: DecisionResponse) => Verdicts;\n (response: DecisionResponse, request: DecisionRequest): Verdicts;\n} = Fn.dual(DATA_FIRST_ARITY, (response: DecisionResponse, request: DecisionRequest): Verdicts => {\n const { model, answers } = Option.getOrThrowWith(\n Option.liftPredicate(response, ({ model: served }) => Str.isNonEmpty(served)),\n () => new Error(\"response has no model id\"),\n );\n const results = Rec.fromEntries(\n pipe(\n mainQuestionsOf(request),\n Arr.map((entry) => resultOf(answers, entry)),\n ),\n );\n const complete = pipe(\n choiceQuestionsOf(request),\n Arr.every(([id, criteria]) => validChoice(answers[id], criteria)),\n );\n return { model, results, answers, complete };\n});\n","import {\n Cause,\n DateTime,\n Config,\n Console,\n Effect,\n Exit,\n Option,\n Schema,\n String as Str,\n Function as Fn,\n} from \"effect\";\n\nimport { PREFIX } from \"./options.ts\";\nimport type { ResolvedOptions } from \"./types.ts\";\n\nconst DATA_FIRST_ARITY = 2;\n\nconst encodeJson = Schema.encodeUnknownOption(Schema.fromJsonString(Schema.Unknown));\n\nexport const toJson = (value: unknown): string =>\n Option.getOrElse(encodeJson(value), () => String(value));\n\nexport const nowMs = (): number => DateTime.toEpochMillis(DateTime.nowUnsafe());\n\nexport const runOrElse: {\n <Value>(\n fallback: (error: unknown) => Value,\n ): <Failure>(effect: Effect.Effect<Value, Failure>) => Value;\n <Value, Failure>(\n effect: Effect.Effect<Value, Failure>,\n fallback: (error: unknown) => Value,\n ): Value;\n} = Fn.dual(\n DATA_FIRST_ARITY,\n <Value, Failure>(\n effect: Effect.Effect<Value, Failure>,\n fallback: (error: unknown) => Value,\n ): Value =>\n Exit.match(Effect.runSyncExit(effect), {\n onSuccess: (value) => value,\n onFailure: (cause) => fallback(Cause.squash(cause)),\n }),\n);\n\nexport const envOf = (name: string): Option.Option<string> =>\n runOrElse(Config.option(Config.NonEmptyString(name)), () => Option.none()).pipe(\n Option.map((value) => Str.trim(value)),\n Option.filter(Str.isNonEmpty),\n );\n\nexport const envNameOf: {\n (name: string): (env: Readonly<Record<string, string>>) => string;\n (env: Readonly<Record<string, string>>, name: string): string;\n} = Fn.dual(\n DATA_FIRST_ARITY,\n (env: Readonly<Record<string, string>>, name: string): string => env[name] ?? name,\n);\n\nexport const failsInCi = (options: ResolvedOptions): boolean =>\n options.ci === \"fail\" && Option.isSome(envOf(\"CI\"));\n\nconst warned = new Set<string>();\n\nexport const warnOnce: {\n (message: string): (reason: string) => void;\n (reason: string, message: string): void;\n} = Fn.dual(DATA_FIRST_ARITY, (reason: string, message: string): void => {\n if (warned.has(reason)) {\n return;\n }\n warned.add(reason);\n Effect.runFork(Console.warn(`${PREFIX}: ${message}`));\n});\n\nexport const messageOf = (error: unknown): string => {\n if (error instanceof Error) {\n return error.message;\n }\n return String(error);\n};\n\nexport const captured: {\n (name: string): (match: Option.Option<RegExpMatchArray>) => Option.Option<string>;\n (match: Option.Option<RegExpMatchArray>, name: string): Option.Option<string>;\n} = Fn.dual(\n DATA_FIRST_ARITY,\n (match: Option.Option<RegExpMatchArray>, name: string): Option.Option<string> =>\n match.pipe(\n Option.flatMap((found) => Option.fromNullishOr(found.groups)),\n Option.flatMap((groups) => Option.fromNullishOr(groups[name])),\n ),\n);\n","import { Array as Arr, Option, Predicate, pipe, Record as Rec } from \"effect\";\n\nimport { snippetRefOf } from \"./request.ts\";\nimport type { DecisionRequest, DecisionResponse, Question } from \"./types.ts\";\n\nconst MAX_QUESTIONS = 64;\n\ntype State = DecisionRequest[\"state\"];\n\nexport interface WireRequest extends Readonly<Pick<DecisionRequest, \"model\" | \"state\">> {\n readonly questions: Readonly<Record<string, Question>>;\n}\n\nconst only = (\n entries: Readonly<Record<string, string>>,\n ref: string,\n): Readonly<Record<string, string>> =>\n Option.match(Option.fromUndefinedOr(entries[ref]), {\n onNone: () => ({}),\n onSome: (text) => ({ [ref]: text }),\n });\n\nconst stateOf = ({ snippets, contexts }: State, ref: string): State => {\n if (Predicate.isUndefined(contexts)) {\n return { snippets: only(snippets, ref) };\n }\n return { snippets: only(snippets, ref), contexts: only(contexts, ref) };\n};\n\nexport const fileRequestsFor = (\n request: DecisionRequest,\n): Arr.NonEmptyReadonlyArray<WireRequest> => {\n const wires = pipe(\n Arr.chunksOf(Rec.toEntries(request.questions), MAX_QUESTIONS),\n Arr.map((chunk): WireRequest => ({ ...request, questions: Rec.fromEntries(chunk) })),\n );\n if (Arr.isReadonlyArrayNonEmpty(wires)) {\n return wires;\n }\n return [request];\n};\n\nexport const snippetRequestsFor = (\n request: DecisionRequest,\n): Arr.NonEmptyReadonlyArray<WireRequest> => {\n const bySnippet = Arr.groupBy(Rec.toEntries(request.questions), ([id]) => snippetRefOf(id));\n const wires = pipe(\n Rec.toEntries(bySnippet),\n Arr.flatMap(([ref, questions]) =>\n pipe(\n Arr.chunksOf(questions, MAX_QUESTIONS),\n Arr.map((chunk): WireRequest => ({\n model: request.model,\n state: stateOf(request.state, ref),\n questions: Rec.fromEntries(chunk),\n })),\n ),\n ),\n );\n if (Arr.isReadonlyArrayNonEmpty(wires)) {\n return wires;\n }\n return [request];\n};\n\nexport const mergeResponses = (\n responses: Arr.NonEmptyReadonlyArray<DecisionResponse>,\n): DecisionResponse => ({\n model: Arr.headNonEmpty(responses).model,\n answers: pipe(\n responses,\n Arr.flatMap(({ answers }) => Rec.toEntries(answers)),\n Rec.fromEntries,\n ),\n});\n"],"mappings":";;AAEA,MAAM,OAAO;AACb,MAAM,iBAAiB;AAEvB,MAAM,iBAAiB,OAAO,IAAI,MAAM,OAAO,uBAAuB,IAAI,CAAC;AAE3E,MAAa,cAAc,OAAO,OAAO,MAAM,OAAO,UAAU;CAAE,SAAS;CAAG,SAAS;AAAE,CAAC,CAAC;AAE3F,MAAa,YAAY;AAEzB,MAAa,SAAS,OAAO,OAAO,MAClC,OAAO,UACL;CAAE,SAAS;CAAW,SAAS;AAAE,GACjC,EAAE,SAAS,0BAA0B,UAAU,QAAQ,CACzD,CACF;AAEA,MAAa,eAAe,OAAO,SAAS;CAAC;CAAY;CAAQ;CAAO;AAAM,CAAC;AAE/E,MAAa,mBAAmB,OAAO,SAAS,CAAC,QAAQ,MAAM,CAAC;AAEhE,MAAa,uBAAuB,OAAO,MAAM,CAC/C,OAAO,SACP,OAAO,SAAS,CAAC,QAAQ,MAAM,CAAC,CAClC,CAAC;AAED,MAAa,sBAAsB,OAAO,SAAS;CAAC;CAAY;CAAS;AAAO,CAAC;AAEjF,MAAa,oBAAoB,OAAO,MAAM;CAC5C,OAAO,OAAO,EAAE,OAAO,OAAO,SAAS;EAAC;EAAQ;EAAQ;CAAS,CAAC,EAAE,CAAC;CACrE,OAAO,OAAO;EACZ,OAAO,OAAO,QAAQ,OAAO;EAC7B,QAAQ,OAAO,YAAY,cAAc;EACzC,OAAO,OAAO,YAAY,cAAc;CAC1C,CAAC;CACD,OAAO,OAAO;EAAE,OAAO,OAAO,QAAQ,WAAW;EAAG,MAAM;CAAoB,CAAC;AACjF,CAAC;AAED,MAAa,iBAAiB,OAAO,SAAS;CAAC;CAAQ;CAAQ;AAAO,CAAC;AAEvE,MAAM,QAAQ,OAAO;AAErB,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WAAWC,OAAI,YAAY,KAAK;CAAE,EAAE,CACrF;CACA,IAAID,MAAI,wBAAwB,KAAK,GACnC,OAAO;CAET,OAAO,CAAC,OAAO;AACjB;AAEA,MAAa,sBACX,YAC2C;CAC3C,MAAM,YAAYA,MAAI,QAAQC,OAAI,UAAU,QAAQ,SAAS,IAAI,CAAC,QAAQ,aAAa,EAAE,CAAC;CAC1F,MAAM,QAAQ,KACZA,OAAI,UAAU,SAAS,GACvBD,MAAI,SAAS,CAAC,KAAK,eACjB,KACEA,MAAI,SAAS,WAAW,aAAa,GACrCA,MAAI,KAAK,WAAwB;EAC/B,OAAO,QAAQ;EACf,OAAO,QAAQ,QAAQ,OAAO,GAAG;EACjC,WAAWC,OAAI,YAAY,KAAK;CAClC,EAAE,CACJ,CACF,CACF;CACA,IAAID,MAAI,wBAAwB,KAAK,GACnC,OAAO;CAET,OAAO,CAAC,OAAO;AACjB;AAEA,MAAa,kBACX,eACsB;CACtB,OAAOA,MAAI,aAAa,SAAS,CAAC,CAAC;CACnC,SAAS,KACP,WACAA,MAAI,SAAS,EAAE,cAAcC,OAAI,UAAU,OAAO,CAAC,GACnDA,OAAI,WACN;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"define-presets-yflVt8vT.mjs","names":["Fn","Rec","Arr","Arr","Arr","Str","Arr","Str","Arr"],"sources":["../src/features/define-presets/lib/select.ts","../src/features/define-presets/lib/ai-slop-select.ts","../src/features/define-presets/lib/comment-select.ts","../src/features/define-presets/model/ai-slop-rules.ts","../src/features/define-presets/lib/claim-rule.ts","../src/features/define-presets/lib/claim-select.ts","../src/features/define-presets/model/code-claims.ts","../src/features/define-presets/model/rules.ts","../src/features/define-presets/model/test-claims.ts","../src/features/define-presets/model/presets.ts"],"sourcesContent":["import {\n Match,\n Option,\n Predicate,\n Array as Arr,\n Record as Rec,\n pipe,\n Function as Fn,\n} from \"effect\";\n\nimport type { DecisionRule, SelectMatch, SelectedNode } from \"#/entities/decision/index.ts\";\n\nconst DATA_FIRST_ARITY = 2;\n\nexport type Select = NonNullable<DecisionRule[\"select\"]>;\n\nexport interface DualSelect {\n (match: SelectMatch): (node: SelectedNode) => boolean;\n (node: SelectedNode, match: SelectMatch): boolean;\n}\n\nexport const dualSelect = (select: Select): DualSelect => Fn.dual(DATA_FIRST_ARITY, select);\n\nexport type NodeTest = Predicate.Predicate<SelectedNode>;\n\nconst childrenOf = (node: SelectedNode): readonly SelectedNode[] =>\n pipe(\n Rec.toEntries<string, unknown>(node),\n Arr.filter(([key]) => key !== \"parent\"),\n Arr.flatMap(([, value]) => Arr.ensure(value)),\n Arr.filter((value): value is SelectedNode => Predicate.hasProperty(value, \"type\")),\n );\n\nconst descendantsOf = (node: SelectedNode): readonly SelectedNode[] => [\n node,\n ...pipe(\n childrenOf(node),\n Arr.flatMap((child) => descendantsOf(child)),\n ),\n];\n\nexport const containing =\n (test: NodeTest): NodeTest =>\n (node) =>\n pipe(\n descendantsOf(node),\n Arr.some((found) => test(found)),\n );\n\nexport const ofType =\n (...types: readonly string[]): NodeTest =>\n (node) =>\n types.includes(node.type);\n\nexport const identifierOf = (node: SelectedNode): Option.Option<string> =>\n Match.value(node).pipe(\n Match.when({ type: \"Identifier\" }, (identifier) => Option.some(identifier.name)),\n Match.orElse(() => Option.none()),\n );\n","import { Array as Arr, Match, Option, Predicate, pipe } from \"effect\";\n\nimport type { SelectedNode } from \"#/entities/decision/index.ts\";\n\nimport { containing, dualSelect, identifierOf, ofType } from \"./select.ts\";\nimport type { DualSelect, NodeTest } from \"./select.ts\";\n\nconst isPlaceholderValue = ofType(\n \"Literal\",\n \"TemplateLiteral\",\n \"ArrayExpression\",\n \"ObjectExpression\",\n);\n\nconst isFallbackOperator: NodeTest = (node) =>\n Match.value(node).pipe(\n Match.when({ type: \"LogicalExpression\", operator: \"??\" }, () => true),\n Match.when({ type: \"LogicalExpression\", operator: \"||\" }, (logical) =>\n isPlaceholderValue(logical.right),\n ),\n Match.when({ type: \"AssignmentExpression\", operator: \"??=\" }, () => true),\n Match.when({ type: \"AssignmentExpression\", operator: \"||=\" }, () => true),\n Match.orElse(() => false),\n );\n\nconst isTypeofCheck: NodeTest = (node) =>\n Match.value(node).pipe(\n Match.when({ type: \"UnaryExpression\", operator: \"typeof\" }, () => true),\n Match.orElse(() => false),\n );\n\nconst isConstAssertion = (annotation: SelectedNode): boolean =>\n Match.value(annotation).pipe(\n Match.when(\n { type: \"TSTypeReference\", typeName: { type: \"Identifier\", name: \"const\" } },\n () => true,\n ),\n Match.orElse(() => false),\n );\n\nconst isCast: NodeTest = (node) =>\n Match.value(node).pipe(\n Match.when({ type: \"TSAsExpression\" }, (cast) => !isConstAssertion(cast.typeAnnotation)),\n Match.when({ type: \"TSTypeAssertion\" }, () => true),\n Match.when({ type: \"TSNonNullExpression\" }, () => true),\n Match.orElse(() => false),\n );\n\nconst bodyOf = (node: SelectedNode): Option.Option<SelectedNode> =>\n Match.value(node).pipe(\n Match.when({ type: \"FunctionDeclaration\" }, (fn) => Option.fromNullishOr(fn.body)),\n Match.when({ type: \"FunctionExpression\" }, (fn) => Option.fromNullishOr(fn.body)),\n Match.when({ type: \"ArrowFunctionExpression\" }, (fn) => Option.some(fn.body)),\n Match.orElse(() => Option.none()),\n );\n\nconst statementsOf = (body: SelectedNode): readonly SelectedNode[] =>\n Match.value(body).pipe(\n Match.when({ type: \"BlockStatement\" }, (block) => block.body),\n Match.orElse((expression) => [expression]),\n );\n\nconst ONE_STATEMENT = 1;\n\nconst isCall = ofType(\"CallExpression\", \"NewExpression\");\n\nconst parentOf = (node: SelectedNode): Option.Option<SelectedNode> =>\n Option.fromNullishOr(node.parent);\n\nconst isArgument = (node: SelectedNode): boolean => Option.exists(parentOf(node), isCall);\n\nconst isOptionOfCall = (node: SelectedNode): boolean =>\n parentOf(node).pipe(\n Option.filter(ofType(\"Property\")),\n Option.flatMap(parentOf),\n Option.filter(ofType(\"ObjectExpression\")),\n Option.exists(isArgument),\n );\n\nconst isCallback: NodeTest = Predicate.or(isArgument, isOptionOfCall);\n\nexport const isDeclared: NodeTest = Predicate.not(isCallback);\n\nconst isShort: NodeTest = (node) =>\n Option.exists(bodyOf(node), (body) => statementsOf(body).length <= ONE_STATEMENT);\n\nconst hasAtMostOneStatement: NodeTest = Predicate.and(isDeclared, isShort);\n\nconst expressionOf = (statement: SelectedNode): Option.Option<SelectedNode> =>\n Match.value(statement).pipe(\n Match.when({ type: \"ReturnStatement\" }, (returned) => Option.fromNullishOr(returned.argument)),\n Match.when({ type: \"ExpressionStatement\" }, (expression) => Option.some(expression.expression)),\n Match.orElse((other) => Option.some(other)),\n );\n\nconst awaitedOf = (expression: SelectedNode): SelectedNode =>\n Match.value(expression).pipe(\n Match.when({ type: \"AwaitExpression\" }, (awaited) => awaited.argument),\n Match.orElse((plain) => plain),\n );\n\nconst isForwardingStatement = (statements: readonly SelectedNode[]): boolean =>\n Option.exists(\n Option.flatMap(Arr.head(statements), expressionOf),\n (expression) => awaitedOf(expression).type === \"CallExpression\",\n );\n\nconst isSingleCall: NodeTest = (node) =>\n Option.exists(bodyOf(node), (body) => isForwardingStatement(statementsOf(body)));\n\nconst paramsOf = (node: SelectedNode): readonly SelectedNode[] =>\n Match.value(node).pipe(\n Match.when({ type: \"FunctionDeclaration\" }, (fn) => fn.params),\n Match.when({ type: \"FunctionExpression\" }, (fn) => fn.params),\n Match.when({ type: \"ArrowFunctionExpression\" }, (fn) => fn.params),\n Match.orElse(() => []),\n );\n\nconst nameOf = (node: SelectedNode): Option.Option<string> =>\n Match.value(node).pipe(\n Match.when({ type: \"SpreadElement\" }, (spread) => identifierOf(spread.argument)),\n Match.when({ type: \"RestElement\" }, (rest) => identifierOf(rest.argument)),\n Match.orElse((plain) => identifierOf(plain)),\n );\n\nconst argumentsOf = (node: SelectedNode): Option.Option<readonly SelectedNode[]> =>\n bodyOf(node).pipe(\n Option.flatMap((body) => Arr.head(statementsOf(body))),\n Option.flatMap(expressionOf),\n Option.map(awaitedOf),\n Option.flatMap((expression) =>\n Match.value(expression).pipe(\n Match.when({ type: \"CallExpression\" }, (call) => Option.some(call.arguments)),\n Match.orElse(() => Option.none()),\n ),\n ),\n );\n\nconst isForwardedArgument =\n (names: readonly string[]) =>\n (argument: SelectedNode): boolean =>\n Match.value(argument).pipe(\n Match.when({ type: \"Literal\" }, () => true),\n Match.orElse((other) => Option.exists(nameOf(other), (name) => names.includes(name))),\n );\n\nconst passesExactly = (names: readonly string[]): Predicate.Predicate<readonly SelectedNode[]> =>\n Predicate.and(\n (passed) =>\n pipe(\n passed,\n Arr.every((argument) => isForwardedArgument(names)(argument)),\n ),\n (passed) => {\n const passedNames = Arr.getSomes(\n pipe(\n passed,\n Arr.map((argument) => nameOf(argument)),\n ),\n );\n return pipe(\n names,\n Arr.every((name) => passedNames.includes(name)),\n );\n },\n );\n\nconst passesParamsUnchanged: NodeTest = (node) =>\n pipe(\n paramsOf(node),\n Arr.map((param) => nameOf(param)),\n Option.all,\n Option.exists((names) => Option.exists(argumentsOf(node), passesExactly(names))),\n );\n\nexport const forwardsOneCall: NodeTest = Predicate.and(\n Predicate.and(hasAtMostOneStatement, isSingleCall),\n passesParamsUnchanged,\n);\n\nconst declaredTypeOf = (param: SelectedNode): Option.Option<SelectedNode> =>\n Match.value(param).pipe(\n Match.when({ type: \"AssignmentPattern\" }, (assigned) => declaredTypeOf(assigned.left)),\n Match.when({ type: \"TSParameterProperty\" }, (property) => declaredTypeOf(property.parameter)),\n Match.when({ typeAnnotation: { type: \"TSTypeAnnotation\" } }, (typed) =>\n Option.some(typed.typeAnnotation.typeAnnotation),\n ),\n Match.orElse(() => Option.none()),\n );\n\nconst isOpenType = ofType(\"TSUnknownKeyword\", \"TSAnyKeyword\");\n\nconst hasNarrowParameter: NodeTest = (node) =>\n pipe(\n paramsOf(node),\n Arr.some((param) => Option.exists(declaredTypeOf(param), Predicate.not(isOpenType))),\n );\n\nconst typeParameterNamesOf = (node: SelectedNode): readonly string[] =>\n Match.value(node).pipe(\n Match.when({ typeParameters: { type: \"TSTypeParameterDeclaration\" } }, (generic) =>\n pipe(\n generic.typeParameters.params,\n Arr.map((parameter) => parameter.name.name),\n ),\n ),\n Match.orElse(() => []),\n );\n\nconst referencedNameOf = (type: SelectedNode): Option.Option<string> =>\n Match.value(type).pipe(\n Match.when({ type: \"TSTypeReference\", typeName: { type: \"Identifier\" } }, (reference) =>\n Option.some(reference.typeName.name),\n ),\n Match.orElse(() => Option.none()),\n );\n\nconst isGenericParameter = (node: SelectedNode, param: SelectedNode): boolean =>\n Option.exists(Option.flatMap(declaredTypeOf(param), referencedNameOf), (name) =>\n typeParameterNamesOf(node).includes(name),\n );\n\nconst returnedOf = (node: SelectedNode): Option.Option<SelectedNode> =>\n Option.flatMap(bodyOf(node), (body) =>\n Option.flatMap(Arr.head(statementsOf(body)), expressionOf),\n );\n\nconst returnedNameOf = (node: SelectedNode): Option.Option<string> =>\n Option.flatMap(returnedOf(node), identifierOf);\n\nconst returnsParameter = (node: SelectedNode, param: SelectedNode): boolean =>\n Option.exists(\n Option.all([returnedNameOf(node), identifierOf(param)]),\n ([returned, given]) => returned === given,\n );\n\nconst ONE_PARAMETER = 1;\n\nconst onlyParameterOf = (node: SelectedNode): Option.Option<SelectedNode> =>\n Option.liftPredicate(paramsOf(node), (params) => params.length === ONE_PARAMETER).pipe(\n Option.flatMap(Arr.head),\n );\n\nconst isGenericIdentity: NodeTest = (node) =>\n onlyParameterOf(node).pipe(\n Option.filter((param) => isGenericParameter(node, param)),\n Option.exists((param) => returnsParameter(node, param)),\n );\n\nexport const mayBePlaceholder: NodeTest = Predicate.and(\n hasAtMostOneStatement,\n Predicate.not(isGenericIdentity),\n);\n\nconst isGuard: NodeTest = Predicate.or(\n ofType(\"IfStatement\", \"ConditionalExpression\", \"ChainExpression\", \"TryStatement\"),\n isTypeofCheck,\n);\n\nexport const hasGuard: NodeTest = Predicate.and(hasNarrowParameter, containing(isGuard));\n\nconst isFallback: NodeTest = Predicate.or(isFallbackOperator, ofType(\"AssignmentPattern\"));\n\nexport const hasFallback: DualSelect = dualSelect(containing(isFallback));\n\nexport const hasCast: DualSelect = dualSelect(containing(isCast));\n","import { Array as Arr, String as Str, pipe } from \"effect\";\n\nimport type { SelectMatch, SelectedNode } from \"#/entities/decision/index.ts\";\n\nimport { dualSelect } from \"./select.ts\";\nimport type { DualSelect } from \"./select.ts\";\n\nconst commentsIn = (node: SelectedNode, { context }: SelectMatch): readonly string[] => {\n const [start, end] = node.range;\n return pipe(\n context.sourceCode.getAllComments(),\n Arr.filter((comment) => comment.start >= start && comment.end <= end),\n Arr.map((comment) => comment.value),\n );\n};\n\nexport const hasCommentInside: DualSelect = dualSelect((node, match) =>\n Arr.isReadonlyArrayNonEmpty(commentsIn(node, match)),\n);\n\nconst SUPPRESSIONS = [\n \"eslint-disable\",\n \"oxlint-disable\",\n \"@ts-ignore\",\n \"@ts-expect-error\",\n \"@ts-nocheck\",\n \"fallow-ignore\",\n];\n\nexport const hasSuppression: DualSelect = dualSelect((node, match) =>\n pipe(\n commentsIn(node, match),\n Arr.some((comment) =>\n pipe(\n SUPPRESSIONS,\n Arr.some((word) => Str.includes(word)(comment)),\n ),\n ),\n ),\n);\n","import { defineDecisionRule } from \"#/entities/decision/index.ts\";\nimport type { DecisionRule } from \"#/entities/decision/index.ts\";\nimport {\n forwardsOneCall,\n isDeclared,\n mayBePlaceholder,\n hasCast,\n hasFallback,\n hasGuard,\n} from \"#/features/define-presets/lib/ai-slop-select.ts\";\nimport { hasCommentInside, hasSuppression } from \"#/features/define-presets/lib/comment-select.ts\";\n\ninterface SlopRule extends Pick<DecisionRule, \"id\" | \"select\" | \"context\"> {\n readonly ask: string;\n readonly flag: string;\n readonly pass: string;\n}\n\nconst CUTOFF = 0.8;\n\nconst slopRule = ({ ask, flag, pass, ...rule }: SlopRule): DecisionRule =>\n defineDecisionRule({\n target: \"function\",\n cutoff: CUTOFF,\n ...rule,\n message: ask,\n question: `${ask}\\n\\nAnswer yes when: ${flag}\\n\\nAnswer no when: ${pass}`,\n });\n\nexport const redundantGuard = slopRule({\n id: \"redundant-guard\",\n select: hasGuard,\n ask: \"This function checks one of its own parameters for a case that the parameter's declared type already rules out, so the check can never change what happens.\",\n flag: \"A parameter whose type annotation is non-optional and non-nullable, such as `user: User` or `name: string`, is compared with null or undefined, has its `typeof` tested against the type it is already declared as, or is read with `?.`.\",\n pass: \"No parameter is checked against its own declared type. Checks on local variables do not count: a local that holds the result of `Map.get`, `find`, `JSON.parse` or any other call, or a value annotated `unknown`, can really be missing or of another type, so checking it is necessary. Parameters of plain JavaScript have no declared type, so any check on them is allowed.\",\n});\n\nexport const defaultMasksMissingValue = slopRule({\n id: \"default-masks-missing-value\",\n select: hasFallback,\n ask: \"This function replaces a value that should always be present with a made-up default, so a missing value is hidden instead of reported.\",\n flag: \"A `??` or `||` default, or a default parameter, stands in for data the rest of the code treats as required, such as an id, a user, a price, a config entry or a response field, with a placeholder like 'unknown', '', 0, [] or {} that later code will use as if it were real; or a chain of two or more fallbacks (`a ?? b ?? c`) picks among sources with no sign of why that order is right.\",\n pass: \"Every default is a value the domain genuinely allows when the input is absent, such as an optional setting with a documented default, an empty list for an optional filter, or a display label for an optional field; or the missing case is reported, thrown or returned to the caller instead of being filled in.\",\n});\n\nexport const passThroughWrapper = slopRule({\n id: \"pass-through-wrapper\",\n select: forwardsOneCall,\n ask: \"This function only forwards its arguments to another function and returns the result, adding no behaviour of its own.\",\n flag: \"The body is a single call that receives every parameter exactly as it came in, in the same order, or with an extra argument that is always the same constant, and returns or awaits the result unchanged, so callers could call the inner function directly.\",\n pass: \"The function changes something on the way: it transforms an argument before passing it on (for example trimming, lower-casing, converting or validating it), transforms the result, binds a dependency, adapts to a different signature a caller requires, or it is an entry point that a framework or another package calls by name.\",\n});\n\nexport const placeholderImplementation = slopRule({\n id: \"placeholder-implementation\",\n select: mayBePlaceholder,\n ask: \"This function is a stand-in that pretends to do its job: it returns a fixed value or does nothing where its name promises real work.\",\n flag: \"The body is empty, only logs, or only holds a TODO while the name promises an action; a validator, checker or permission function always returns true or always returns false; a function named after a computation returns a hard-coded number, string or object; or a branch the name promises to handle silently does nothing.\",\n pass: \"The body does the work its name promises, even simply. An intentional no-op whose name says so (noop, ignore, a default callback), an abstract method meant to be overridden, and a test double inside test code are not placeholders.\",\n});\n\nexport const commentRestatesCode = slopRule({\n id: \"comment-restates-code\",\n select: hasCommentInside,\n ask: \"A comment inside this function only translates the next line of code into words and adds no reason, unit, or constraint.\",\n flag: \"A comment repeats the code in words, such as `// increment the counter` over `count += 1`, `// loop over the items` over a for loop, or `// return the total` over a return; deleting it would leave a reader knowing exactly as much.\",\n pass: \"Every comment says something the code cannot say on its own: why it is done this way (often with `because` or `so`), a fact about the outside world such as a billing rule, an API quirk or a standard, a unit, or an invariant. Lint directive comments such as `eslint-disable` are not judged here.\",\n});\n\nexport const commentNarratesHistory = slopRule({\n id: \"comment-narrates-history\",\n select: hasCommentInside,\n ask: \"A comment inside this function records how the code came to be, or speaks to the person who asked for the change, instead of describing the code as it stands.\",\n flag: \"A comment says what was added, changed, removed, fixed or kept for compatibility (`added X`, `changed to Y`, `previously`, `now uses`, `new:`), marks the code as a stopgap (`temporary`, `for now`, `quick fix`, `hack until`), mentions a date, a ticket in progress, a model or a conversation, or addresses a reader as if replying (`as requested`, `here we`, `note that I`).\",\n pass: \"Every comment describes the code as it is now and would still be true and useful to a reader who never saw the earlier version or the conversation. A TODO that names a concrete missing case is a description of the code, not history.\",\n});\n\nexport const docRestatesSignature = slopRule({\n id: \"doc-restates-signature\",\n context: { scope: \"comment\" },\n ask: \"The comment above this function contains nothing except the function's name and parameter names reworded.\",\n flag: \"Every sentence of the comment can be rebuilt from the signature alone, such as `Gets the order.`, `@param id - the id`, `@returns the order` or `Creates a new instance.`\",\n pass: \"At least one sentence states behaviour the signature does not show, such as what is returned when nothing matches, when it fails, a unit or range, a side effect, or how values are compared.\",\n});\n\nexport const castInsteadOfNarrowing = slopRule({\n id: \"cast-instead-of-narrowing\",\n select: hasCast,\n ask: \"This function uses a type assertion (`as`, `<T>` or a non-null `!`) to silence the type checker where the value is not known to have that type.\",\n flag: \"The asserted type is not established by anything on the path: data from parsing, I/O, `unknown`, `any` or a wider union is cast to a specific shape without a check, a possibly missing value gets `!` without a preceding check or a guarantee from the API, or the cast goes through `unknown` (`as unknown as T`) to force an unrelated type.\",\n pass: \"Each assertion states something the code has just established or the API guarantees, such as a cast after a type guard, a DOM element looked up by a selector that the same module creates, or a literal narrowed for an overload; `as const` is not a cast.\",\n});\n\nexport const suppressionInsteadOfFix = slopRule({\n id: \"suppression-instead-of-fix\",\n select: hasSuppression,\n ask: \"A lint or type-check suppression comment inside this function hides a problem that the code next to it could simply fix.\",\n flag: \"The directive gives no reason after the rule name, or the line it silences has a direct local fix, such as handling a floating promise, typing a value instead of `any`, removing an unused variable, or narrowing instead of `@ts-ignore`.\",\n pass: \"Every directive is followed by `--` or a comment with a reason explaining why the rule does not fit this line, such as output a command-line tool prints on purpose, a wrong third-party type, or generated code.\",\n});\n\nexport const reinventsBuiltin = slopRule({\n id: \"reinvents-builtin\",\n select: isDeclared,\n ask: \"This function contains a hand-written loop or algorithm that re-implements something the JavaScript standard library or the platform already provides.\",\n flag: \"A loop or manual algorithm in the body does what one built-in call does: de-duplicating with an array and includes instead of a Set, deep copying instead of structuredClone, grouping instead of Object.groupBy, building query strings instead of URLSearchParams, formatting numbers or dates instead of Intl, padding instead of padStart, flattening instead of flat, or finding the last match instead of findLast.\",\n pass: \"The function has no such hand-written loop: it already calls the built-in directly (for example `new Set`, `structuredClone`, `reduce` or `Intl`), or its loop does domain work that no single built-in does. A chain of built-in array methods such as `filter`, `map`, `flatMap` and `flat` already uses the built-ins.\",\n});\n\nexport const aiSlopRules = [\n redundantGuard,\n defaultMasksMissingValue,\n passThroughWrapper,\n placeholderImplementation,\n commentRestatesCode,\n commentNarratesHistory,\n docRestatesSignature,\n castInsteadOfNarrowing,\n suppressionInsteadOfFix,\n reinventsBuiltin,\n] as const;\n","import { Predicate, Array as Arr, pipe } from \"effect\";\n\nimport { defineDecisionRule } from \"#/entities/decision/index.ts\";\nimport type { DecisionRule, RuleContext } from \"#/entities/decision/index.ts\";\n\nexport interface Judgement {\n readonly ask: string;\n readonly yes: string;\n readonly no: string;\n readonly note?: string | undefined;\n}\n\nexport interface ClaimRule\n extends Judgement, Pick<DecisionRule, \"id\" | \"cutoff\" | \"select\" | \"context\"> {\n readonly target?: Extract<DecisionRule[\"target\"], \"function\" | \"call\">;\n}\n\nconst questionOf = ({ ask, yes, no, note }: Judgement): string =>\n pipe(\n [ask, `It is true when: ${yes}`, `It is false when: ${no}`, note],\n Arr.filter((part) => Predicate.isNotUndefined(part)),\n Arr.join(\"\\n\\n\"),\n );\n\nexport const claimRule = ({ ask, yes, no, note, ...rule }: ClaimRule): DecisionRule =>\n defineDecisionRule({\n target: \"function\",\n ...rule,\n message: ask,\n question: questionOf({ ask, yes, no, note }),\n });\n\nexport const COMMENT: RuleContext = { scope: \"comment\" };\nexport const ENCLOSING_FUNCTION: RuleContext = { scope: \"enclosing\", kind: \"function\" };\n","import { Array as Arr, Match, Option, Predicate, String as Str, pipe } from \"effect\";\n\nimport type { SelectedNode } from \"#/entities/decision/index.ts\";\n\nimport { containing, dualSelect, identifierOf, ofType } from \"./select.ts\";\nimport type { DualSelect, NodeTest, Select } from \"./select.ts\";\n\nconst WORD_STARTS: ReadonlySet<string> = new Set([\n \"\",\n ...Str.split(\"_0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\", \"\"),\n]);\n\nconst NEXT_CHARACTER = 1;\n\nconst startsWithWord =\n (word: string): Predicate.Predicate<string> =>\n (name) =>\n Predicate.and(\n (text: string) => Str.startsWith(word)(text),\n (text: string) => WORD_STARTS.has(Str.slice(word.length, word.length + NEXT_CHARACTER)(text)),\n )(name);\n\nconst endsWith =\n (word: string): Predicate.Predicate<string> =>\n (name) =>\n Str.endsWith(word)(name);\n\nexport interface NameWords {\n readonly prefixes: readonly string[];\n readonly suffixes?: readonly string[];\n}\n\nexport const namedLike = ({ prefixes, suffixes = [] }: NameWords): Select => {\n const matchers = [\n ...pipe(\n prefixes,\n Arr.map((word) => startsWithWord(word)),\n ),\n ...pipe(\n suffixes,\n Arr.map((word) => endsWith(word)),\n ),\n ];\n return (_node, { name }) =>\n Option.exists(Option.fromUndefinedOr(name), (found) =>\n pipe(\n matchers,\n Arr.some((matches) => matches(found)),\n ),\n );\n};\n\nconst rootOf = (callee: SelectedNode): Option.Option<string> =>\n Match.value(callee).pipe(\n Match.when({ type: \"MemberExpression\", computed: false }, (member) => rootOf(member.object)),\n Match.orElse(identifierOf),\n );\n\nconst calleeOf = (node: SelectedNode): Option.Option<SelectedNode> =>\n Match.value(node).pipe(\n Match.when({ type: \"CallExpression\" }, (call) => Option.some(call.callee)),\n Match.orElse(() => Option.none()),\n );\n\nconst callingAny =\n (roots: readonly string[]): Select =>\n (node) =>\n Option.exists(Option.flatMap(calleeOf(node), rootOf), (root) => roots.includes(root));\n\nconst LOG_LEVELS: ReadonlySet<string> = new Set([\n \"trace\",\n \"debug\",\n \"verbose\",\n \"info\",\n \"log\",\n \"warn\",\n \"warning\",\n \"error\",\n \"fatal\",\n]);\n\nconst lastNameOf = (node: SelectedNode): Option.Option<string> =>\n Match.value(node).pipe(\n Match.when({ type: \"MemberExpression\", computed: false }, (member) =>\n identifierOf(member.property),\n ),\n Match.orElse(identifierOf),\n );\n\nconst isLogger = (name: string): boolean =>\n Arr.some([\"console\", \"log\"], (word) => Str.includes(word)(Str.toLowerCase(name)));\n\ninterface LogCall {\n readonly level: Option.Option<string>;\n readonly logger: Option.Option<string>;\n}\n\nconst logCallOf = (callee: SelectedNode): Option.Option<LogCall> =>\n Match.value(callee).pipe(\n Match.when({ type: \"MemberExpression\", computed: false }, (member) =>\n Option.some({ level: identifierOf(member.property), logger: lastNameOf(member.object) }),\n ),\n Match.orElse(() => Option.none()),\n );\n\nexport const isLogCall: DualSelect = dualSelect((node) =>\n Option.exists(Option.flatMap(calleeOf(node), logCallOf), ({ level, logger }) =>\n Predicate.and(\n () => Option.exists(level, (found) => LOG_LEVELS.has(found)),\n () => Option.exists(logger, isLogger),\n )(node),\n ),\n);\n\nconst isCatchName = (name: SelectedNode): boolean =>\n Match.value(name).pipe(\n Match.when({ type: \"Identifier\" }, (identifier) => Str.startsWith(\"catch\")(identifier.name)),\n Match.orElse(() => false),\n );\n\nconst isCatch: NodeTest = (node) =>\n Match.value(node).pipe(\n Match.when({ type: \"CatchClause\" }, () => true),\n Match.when({ type: \"MemberExpression\", computed: false }, (member) =>\n isCatchName(member.property),\n ),\n Match.when({ type: \"Property\", computed: false }, (property) => isCatchName(property.key)),\n Match.orElse(() => false),\n );\n\nexport const hasCatch: DualSelect = dualSelect(containing(isCatch));\n\nconst hasCallbackArgument: Select = (node) =>\n Match.value(node).pipe(\n Match.when({ type: \"CallExpression\" }, (call) =>\n pipe(\n call.arguments,\n Arr.some((argument) => ofType(\"ArrowFunctionExpression\", \"FunctionExpression\")(argument)),\n ),\n ),\n Match.orElse(() => false),\n );\n\nexport const isTestCall: DualSelect = dualSelect((node, match) =>\n pipe(\n [callingAny([\"it\", \"test\"]), hasCallbackArgument],\n Arr.every((select) => select(node, match)),\n ),\n);\n\nexport const isDescribeCall: DualSelect = dualSelect(callingAny([\"describe\"]));\n","import type { DecisionRule } from \"#/entities/decision/index.ts\";\nimport {\n COMMENT,\n ENCLOSING_FUNCTION,\n claimRule,\n} from \"#/features/define-presets/lib/claim-rule.ts\";\nimport { hasCatch, isLogCall, namedLike } from \"#/features/define-presets/lib/claim-select.ts\";\n\nexport const fnNamePromises = claimRule({\n id: \"fn-name-promises\",\n cutoff: 0.8,\n ask: \"The body of this function does something materially different from what its name promises.\",\n yes: \"Someone who read only the name and the parameter list would be wrong about what this function does: it returns a different kind of thing than the name suggests (a count that is a list, a predicate that is a number), it changes state when the name says it only reads, checks, looks up or serialises, it can fail or return nothing when the name promises a value, it handles only a narrower case than the name claims, it never performs an effect or repetition the name names (a drain or remove that leaves the container as it was, a retry that tries once), it computes something no reading of the name accounts for, or it does substantial work the name does not mention at all, such as writing what it was asked to read.\",\n no: \"The name and parameter list describe what the body actually does. Someone who read only them would not be surprised by the body, even if a longer or more specific name could be imagined. A terse or conventional name (run, handle, take, len, fmt, toString, a getter) that the body fits is not a violation, and a comment inside the body that is wrong about the body is a wrong comment, not a wrong name.\",\n});\n\nexport const pureNameIsPure = claimRule({\n id: \"pure-name-is-pure\",\n cutoff: 0.8,\n select: namedLike({ prefixes: [\"compute\", \"calculate\", \"derive\", \"format\", \"to\", \"parse\"] }),\n ask: \"This function's name presents it as a computation of a result from its inputs, but its body changes state outside itself or performs I/O.\",\n yes: \"The body mutates an argument or something reachable through one, assigns to a module-level binding, a field of `this` or an object it did not create, stores something it computed into a cache, Map, Set or other store that outlives the call, logs, emits or increments a metric, or reads or writes a file, network, database, environment, clock or random source, directly or through a call whose name or arguments show it does so (fetch, a path, a URL, a query, send, save). One such read or write on any path is enough.\",\n no: \"The body derives its result from its parameters, from `this`, from module-level values it only reads, and from dependencies it obtains, and returns it. A mutable local accumulator, a copy of an argument that is then modified, and a local object built up and returned are not effects outside the function.\",\n note: \"Obtaining a dependency (a module, a client, a parser handed back by a loader) is not an effect; using an acquired client to fetch, read, write or send is. A body that puts its own result into a cache that outlives the call is an effect even when it is only memoisation.\",\n});\n\nexport const safeNameIsSafe = claimRule({\n id: \"safe-name-is-safe\",\n cutoff: 0.8,\n select: namedLike({\n prefixes: [\"safe\", \"try\"],\n suffixes: [\"OrNull\", \"OrDefault\", \"OrUndefined\"],\n }),\n ask: \"This function's name says that failure is absorbed and reported as a value, but its body has a path on which a failure escapes as a throw or a rejection.\",\n yes: \"A failure of the kind the name promises to absorb can reach the caller as an exception or a rejected promise: the operation that can fail is outside any try, the catch rethrows or throws a new error, a failing case is detected and answered with a throw instead of the null, undefined, default, false or result value the name promises, or the fallback itself is computed by something that can fail.\",\n no: \"Every failure of the kind the name refers to is turned into the value the name promises: null, undefined, a default, a boolean, or a result object the caller can inspect. A body that cannot fail at all, and so has nothing to catch, honours the name.\",\n note: \"A throw on a programmer error, such as an argument of the wrong type, is not the failure such a name promises to absorb. Logging before returning the fallback is fine.\",\n});\n\nexport const idempotentName = claimRule({\n id: \"idempotent-name\",\n cutoff: 0.8,\n select: namedLike({ prefixes: [\"ensure\", \"upsert\", \"setup\", \"install\", \"register\"] }),\n ask: \"This function's name says a repeated call is harmless, but calling it a second time with the same arguments leaves a different result from calling it once.\",\n yes: \"The body performs its effect without finding out whether it is already in place, and repeating the effect accumulates or fails: it appends to a list or adds a listener, creates a record, index, table, column or resource that would then exist twice or make the second creation fail, inserts where a matching row may already be, or runs a step that is not itself safe to repeat, with no existence check, no keyed overwrite and no guard that makes the second call a no-op.\",\n no: \"A second call finds the effect already in place and leaves the state as the first call left it: the body checks for existence before acting, writes by key so a repeat overwrites the same entry, assigns rather than appends, uses an operation that is inherently repeatable (put, set, mkdir with recursive, CREATE IF NOT EXISTS, ON CONFLICT), returns early on a flag it sets, or has no effect at all beyond its return value.\",\n note: \"A helper whose own name says it is repeat-safe (ensure*, upsert*, put*, set*) is assumed to be. Logging on each call, or returning a fresh object each call, is not a different result.\",\n});\n\nexport const catchHidesFailure = claimRule({\n id: \"catch-hides-failure\",\n cutoff: 0.8,\n select: hasCatch,\n ask: \"A catch block in this function hides a failure the function's caller needed to know about.\",\n yes: \"The catch block neither rethrows, returns an error value the signature admits, nor reports through a channel the function is documented to use; it returns a default, an empty value, a made-up value or nothing, or only logs, and the function's name or return type promises a real result: a value that was fetched, parsed or computed, or an operation such as a save or a send that the caller will assume happened.\",\n no: \"The function has no catch block; or the failure is propagated (rethrown, wrapped, or logged and then rethrown); converted into a value the caller can distinguish from success, such as a Result or null when the return type admits it; or absorbed where absorbing is the point: a cleanup or best-effort step after the real result is in hand, a fallback to the next attempt or source, a catch that swallows only the case in which the goal already holds, or a top-level entry point that reports and exits with a non-zero status. A function named safe*, try* or *OrNull has promised to absorb failure.\",\n});\n\nexport const errorMessageMatchesCondition = claimRule({\n id: \"error-message-matches-condition\",\n cutoff: 0.8,\n ask: \"The message given to an error thrown in this function misdescribes the condition that leads to the throw.\",\n yes: \"The message names a different cause, value, operation or expectation than the condition guarding the throw actually checks: it says a thing is missing when the check is about its permission, form or range; it names one field or operand when the condition tests another; it names one failure (a timeout, an expiry) when the status or state tested is a different one; it states a bound or direction the condition does not test; or it is a copy of another throw's message in the same function and describes that throw's condition rather than this one.\",\n no: \"The function throws nothing with a message; or every message describes the condition that leads to its throw, whether it states the failed requirement, its consequence, or the intent the check serves. A message that is short, generic or lacks detail is not wrong, only unhelpful. A message that quotes the offending input, names what cannot proceed, or wraps a caught error with the name of the operation that failed, is a match.\",\n});\n\nexport const logLevelMatchesEvent = claimRule({\n id: \"log-level-matches-event\",\n target: \"call\",\n cutoff: 0.8,\n select: isLogCall,\n context: ENCLOSING_FUNCTION,\n ask: \"The level of this log call misstates the severity of what the surrounding code is handling at that point.\",\n yes: \"The call is at info, debug or trace but sits on a path where the operation has failed and the function gives up, rethrows, exits, discards data or returns a failure the caller must act on; the call is at debug or trace for an outcome the function reports to its caller, such as a refusal; the call is at error or fatal but sits on the ordinary success path or on a routine, expected branch such as a cache miss or a validation failure; or the call is at warn but the code immediately exits or throws with no recovery.\",\n no: \"The level fits what the code around the call shows: error or warn where something went wrong that an operator should see, even if the function recovers from it; info for routine outcomes; debug or trace for per-item progress and chatter; warn for a degraded or transient condition the code goes on to handle. Whether the message text is well written is not the question.\",\n});\n\nexport const logMessageMatchesEvent = claimRule({\n id: \"log-message-matches-event\",\n target: \"call\",\n cutoff: 0.8,\n select: isLogCall,\n context: ENCLOSING_FUNCTION,\n ask: \"The message of this log call misdescribes the event at the point in the code where the call sits.\",\n yes: \"What the message says happened is not what the code path shows at that point: it reports an outcome as done before the operation that produces it runs, or on the branch where that operation failed or was skipped; it names an action (a retry, a deletion, a cache hit, a send) that the path does not perform; it reports a count of what was selected or attempted as the count of what was deleted, sent or written; it interpolates a value that is not what the message calls it; or it names a kind of thing other than the one the surrounding code acts on.\",\n no: \"The message is true of the point where it sits: an intent phrased before the operation, a completion phrased after it, a failure on the branch that fails, a templated message whose values are what it calls them, or a terse message on the path it describes. A message that is vague or could say more is not wrong. Whether the level fits is not the question.\",\n});\n\nexport const commentDescribesBlock = claimRule({\n id: \"comment-describes-block\",\n cutoff: 0.8,\n ask: \"A comment inside this function makes a claim about the code beneath it that the code contradicts.\",\n yes: \"The comment says what the code beneath it does, and the code does something else: a count, limit, number of attempts or delay that differs from the code's; a direction, order, sign, rounding or unit that is not the one the code uses; a condition the code tests the other way round; or a step the comment says happens here that the code beneath it does not perform.\",\n no: \"The function has no comment inside its body; or every specific claim in each comment holds for the code beneath it, meaning the run of statements down to the next comment or the end of the block. A comment that gives a reason outside the code, says what the whole function is for, is vague, or summarises the code loosely but not wrongly, makes no claim the code can contradict. A comment at the end of a line belongs to that line.\",\n});\n\nexport const commentDescribesDeclaration = claimRule({\n id: \"comment-describes-declaration\",\n cutoff: 0.8,\n context: COMMENT,\n ask: \"The comment directly above this function claims something that is not true of the code.\",\n yes: \"A specific claim the comment makes is contradicted by the code: it names a different operation, direction, rounding, ordering or unit than the code uses, it states a return value or guarantee the code does not provide, it describes a side effect the code does not perform or omits one it does, it gives a count, limit or default that differs from the code's, or it refers to a parameter, field or function that the code no longer has.\",\n no: \"Every specific claim the comment makes holds for the code below it. A comment that is vague, redundant or says less than it could is not a false comment. A section heading or divider names the part of the file that starts there and makes no claim about the function.\",\n note: \"Only a comment that ends on the line just before the function, or just before the export or declaration that holds it, is directly above it; a comment followed by other code belongs to that code. Judge only claims the code can confirm or contradict. A comment about a caller's obligations, about performance, or about history is not checkable here.\",\n});\n\nexport const docErrorsMatchBody = claimRule({\n id: \"doc-errors-match-body\",\n cutoff: 0.8,\n context: COMMENT,\n ask: \"The failure contract stated in the documentation right above this function (what it says the function throws, rejects with, or returns in place of a result when something goes wrong, and under what condition) is contradicted by the body.\",\n yes: \"The documentation names a failure the body cannot produce: it says the function throws a named error and the body returns null, a default or a success value on that condition instead. Or it names the wrong failure: a different error type or a different condition than the one the body checks before failing. Or the body explicitly fails on its own (a throw, an assert, or a null or default returned in place of a result) under a condition the documentation says nothing about. Or the documentation says the function never throws and the body has a throw.\",\n no: \"The documentation states no failure contract; or every failure the documentation names is one the body produces under the condition named, and every explicit failure the body writes is covered somewhere in the documentation. A failure described at the level of intent is honoured by whatever mechanism the body uses. A fallback the documentation describes, such as a default when a file is absent, is a documented outcome.\",\n note: \"The snippet starts with the documentation directly above the function, and that documentation is what is judged. An error that merely passes through unchanged from a callee is the callee's failure, not a clause this body owes, unless the documentation says the function cannot fail.\",\n});\n\nexport const varNameDescribesValue = claimRule({\n id: \"var-name-describes-value\",\n cutoff: 0.8,\n ask: \"A binding declared in this function has a name that misdescribes the value it is bound to.\",\n yes: \"The name states a type, unit, shape, quantity or meaning that the initializer does not produce: a plural name bound to a single item or a singular name bound to a collection, a name that reads as a boolean bound to something that is not one, a name naming one unit while the value is in another, a name saying it holds a value while it holds a function or a promise, or a name describing a different thing entirely from what the initializer computes.\",\n no: \"Every name is an accurate description of what its initializer produces, even if it is terse or a clearer name could be imagined. Being short or generic is not a mismatch. A plural name on a number names the count of those things; an accumulator, index or buffer name is a convention, not a claim.\",\n});\n\nexport const codeClaims = [\n fnNamePromises,\n pureNameIsPure,\n safeNameIsSafe,\n idempotentName,\n catchHidesFailure,\n errorMessageMatchesCondition,\n logLevelMatchesEvent,\n logMessageMatchesEvent,\n commentDescribesBlock,\n commentDescribesDeclaration,\n docErrorsMatchBody,\n varNameDescribesValue,\n] as const satisfies readonly DecisionRule[];\n","import { defineDecisionRule } from \"#/entities/decision/index.ts\";\nimport { namedLike } from \"#/features/define-presets/lib/claim-select.ts\";\n\nexport const noPiiInLogs = defineDecisionRule({\n id: \"no-pii-in-logs\",\n target: \"call\",\n question:\n \"Does this call write personal data, such as an email or phone number, to a log or console?\",\n cutoff: 0.8,\n});\n\nexport const noPromptInjection = defineDecisionRule({\n id: \"no-prompt-injection\",\n target: \"function\",\n question:\n \"Does this function build a language model prompt by concatenating untrusted user input into the instructions?\",\n cutoff: 0.8,\n});\n\nexport const noHardcodedSecrets = defineDecisionRule({\n id: \"no-hardcoded-secrets\",\n target: \"file\",\n question:\n \"Does this file contain a hard-coded secret, such as an API key, password, or private token, as a literal value?\",\n cutoff: 0.8,\n});\n\nexport const nameMatchesBehavior = defineDecisionRule({\n id: \"name-matches-behavior\",\n target: \"function\",\n select: namedLike({\n prefixes: [\"get\", \"find\", \"load\", \"fetch\", \"read\", \"lookup\", \"query\", \"list\", \"search\"],\n }),\n question:\n \"Does this function's name describe only reading or fetching data (for example get, find, load or fetch), while its body also changes or announces something on the side, such as writing to a database or file, logging, or sending a message? Sending the request that fetches the data, such as calling an API or a model and reading its answer, is the fetching itself and does not count.\",\n cutoff: 0.8,\n});\n\nexport const untrustedInputRisk = defineDecisionRule({\n id: \"untrusted-input-risk\",\n target: \"function\",\n question:\n \"Does this function splice untrusted input, such as a user message or request parameter, into the same string as a SQL query, shell command, eval code, HTML, or language model instructions, instead of passing it as a separate parameter or field? Count input as untrusted only when it comes from outside the program, such as a request, a user message, a form, or a file or response the program does not control; a parameter whose origin is not shown counts when its name or type marks it as user or request data. Text taken from the program's own rule definitions, settings, constants or cache is not untrusted, and JSON.parse is not eval.\",\n cutoff: 0.8,\n answer: { kind: \"severity\", minimum: \"warn\" },\n});\n\nexport const domainNaming = defineDecisionRule({\n id: \"domain-naming\",\n target: \"function\",\n question:\n \"Is this function named after a mechanism word such as Manager, Processor, Handler, Helper, Data, Info, handle, process, or do, while its body works on one specific business concept, such as an invoice, an order, or a refund, that the name should call by its domain name instead? Code whose subject is a generic mechanism, such as HTTP, files, the command line, or framework glue, does not count.\",\n cutoff: 0.8,\n});\n\nexport const preferSchemaValidation = defineDecisionRule({\n id: \"prefer-schema-validation\",\n target: \"function\",\n question:\n \"Does this function check the shape or values of untyped data, such as parsed JSON, a request body, config, or an API response, with a long hand-written chain of typeof, instanceof, in, or field checks joined by && or ||, where a schema from a validation library would state the same rules more simply? A single simple check does not count.\",\n cutoff: 0.8,\n});\n","import type { DecisionRule } from \"#/entities/decision/index.ts\";\nimport { claimRule } from \"#/features/define-presets/lib/claim-rule.ts\";\nimport { isDescribeCall, isTestCall } from \"#/features/define-presets/lib/claim-select.ts\";\n\nexport const describeNamesSubject = claimRule({\n id: \"describe-names-subject\",\n cutoff: 0.8,\n target: \"call\",\n select: isDescribeCall,\n ask: \"The tests inside this describe block exercise something other than what its title names.\",\n yes: \"The title names a specific function, method, class or module and no test in the block calls, constructs or otherwise reaches it: every test calls a differently named sibling instead; or the title names a behaviour and no test makes that behaviour happen or observes it.\",\n no: \"What the title names is what the tests exercise, directly or through something that reaches it: a feature tested through a public function of another name, a class tested through its factory or an instance created in beforeEach, a title that is a file name, a scenario or a sentence when the tests are about it, or an abbreviation or synonym of what the tests call.\",\n});\n\nexport const testNameDescribesCode = claimRule({\n id: \"test-name-describes-code\",\n cutoff: 0.8,\n target: \"call\",\n select: isTestCall,\n ask: \"The operation, input or outcome this test exercises is not the one the test's name names.\",\n yes: \"The operation the code calls is not the one the name says; the input or case the code sets up is not the one the name states (three units where the name says above ten); the outcome the code expects is the opposite of the one the name implies; the name promises a throw or a rejection where the code expects an ordinary value; or the name refers to something that the code never calls and never checks.\",\n no: \"The code calls the operation the name says, on the input the name says, and expects the kind of outcome the name says, however weak the assertion is. A one-word title, a synonym for the operation's name, and setup that calls other operations before the named one are all fine.\",\n});\n\nexport const testNameVerifiesClaim = claimRule({\n id: \"test-name-verifies-claim\",\n cutoff: 0.8,\n target: \"call\",\n select: isTestCall,\n ask: \"This test would still pass if the behaviour its name claims were broken.\",\n yes: \"The body does not establish what the name claims: it asserts nothing at all, it asserts something that would hold whether or not the named behaviour worked, it checks an incidental property such as a length or a type instead of the named behaviour itself, or it never sets up the case the name is about.\",\n no: \"The body contains at least one assertion that would fail if the named behaviour were broken. A name that claims only that something renders or matches a snapshot is established by the snapshot; a name that claims an interaction with a collaborator is established by an assertion on that call; a name that claims only that something does not throw is established by calling it.\",\n});\n\nexport const snapshotOnlyBehaviourClaim = claimRule({\n id: \"snapshot-only-behaviour-claim\",\n cutoff: 0.8,\n target: \"call\",\n select: isTestCall,\n ask: \"This test's name claims a specific behaviour, but the body only compares a snapshot.\",\n yes: \"The title asserts a property of the output (an ordering, an element hidden or shown, a state rendered under a condition, a format applied) and the only assertions are toMatchSnapshot, toMatchInlineSnapshot or toMatchFileSnapshot over a whole rendering, so nothing isolates the named property.\",\n no: \"The body uses no snapshot; or the title claims only that the output matches a snapshot or renders, or only names the input; or at least one assertion targets the named behaviour directly; or the inline snapshot is a short literal that is itself the named outcome.\",\n});\n\nexport const testMocksSubject = claimRule({\n id: \"test-mocks-subject\",\n cutoff: 0.8,\n target: \"call\",\n select: isTestCall,\n ask: \"The behaviour this test's name attributes to the code under test is performed by a mock or stub whose canned value the assertion reads back unchanged.\",\n yes: \"The title says the code under test computes, derives or returns something, but the function or module that would do it is replaced (vi.mock or jest.mock with a fake, mockReturnValue or mockResolvedValue, a stubbed global) and the value the assertion checks can be traced to that stub's configuration with none of the subject's own logic in between. The assertion then checks the test's own setup.\",\n no: \"The body mocks nothing; or the stub stands in for a collaborator the code under test calls (the network, the clock, a repository, a mailer) and the assertion checks what the real code did with the stub's output; or the title is itself about the collaborator; or the spy has no replacement value and the real method runs.\",\n});\n\nexport const testClaims = [\n describeNamesSubject,\n testNameDescribesCode,\n testNameVerifiesClaim,\n snapshotOnlyBehaviourClaim,\n testMocksSubject,\n] as const satisfies readonly DecisionRule[];\n","import type { DecisionRule } from \"#/entities/decision/index.ts\";\n\nimport {\n catchHidesFailure,\n commentDescribesBlock,\n commentDescribesDeclaration,\n docErrorsMatchBody,\n errorMessageMatchesCondition,\n fnNamePromises,\n idempotentName,\n logLevelMatchesEvent,\n logMessageMatchesEvent,\n pureNameIsPure,\n safeNameIsSafe,\n varNameDescribesValue,\n} from \"./code-claims.ts\";\nimport {\n domainNaming,\n nameMatchesBehavior,\n noHardcodedSecrets,\n noPiiInLogs,\n noPromptInjection,\n preferSchemaValidation,\n untrustedInputRisk,\n} from \"./rules.ts\";\nimport {\n describeNamesSubject,\n snapshotOnlyBehaviourClaim,\n testMocksSubject,\n testNameDescribesCode,\n testNameVerifiesClaim,\n} from \"./test-claims.ts\";\n\nexport type Preset = readonly [DecisionRule, ...DecisionRule[]];\n\nexport const recommended: Preset = [noPiiInLogs, noPromptInjection, noHardcodedSecrets];\n\nexport const strict: Preset = [\n ...recommended,\n nameMatchesBehavior,\n untrustedInputRisk,\n pureNameIsPure,\n safeNameIsSafe,\n idempotentName,\n catchHidesFailure,\n testNameVerifiesClaim,\n testMocksSubject,\n];\n\nexport const reviewOnly: Preset = [\n domainNaming,\n preferSchemaValidation,\n fnNamePromises,\n commentDescribesDeclaration,\n commentDescribesBlock,\n docErrorsMatchBody,\n errorMessageMatchesCondition,\n logLevelMatchesEvent,\n logMessageMatchesEvent,\n varNameDescribesValue,\n describeNamesSubject,\n testNameDescribesCode,\n snapshotOnlyBehaviourClaim,\n];\n\nexport const presets = { recommended, strict, reviewOnly } as const satisfies Readonly<\n Record<string, Preset>\n>;\n"],"mappings":";;;;AAYA,MAAM,mBAAmB;AASzB,MAAa,cAAc,WAA+BA,SAAG,KAAK,kBAAkB,MAAM;AAI1F,MAAM,cAAc,SAClB,KACEC,OAAI,UAA2B,IAAI,GACnCC,MAAI,QAAQ,CAAC,SAAS,QAAQ,QAAQ,GACtCA,MAAI,SAAS,GAAG,WAAWA,MAAI,OAAO,KAAK,CAAC,GAC5CA,MAAI,QAAQ,UAAiC,UAAU,YAAY,OAAO,MAAM,CAAC,CACnF;AAEF,MAAM,iBAAiB,SAAgD,CACrE,MACA,GAAG,KACD,WAAW,IAAI,GACfA,MAAI,SAAS,UAAU,cAAc,KAAK,CAAC,CAC7C,CACF;AAEA,MAAa,cACV,UACA,SACC,KACE,cAAc,IAAI,GAClBA,MAAI,MAAM,UAAU,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;CAClD,IAAI;CACJ,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,KAAK;CACL,KAAK;CACL,IAAI;AACN,CAAC;AAED,MAAa,mBAAmB,UAAU;CACxC,IAAI;CACJ,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,KAAK;CACL,KAAK;CACL,IAAI;AACN,CAAC;AAED,MAAa,aAAa;CACxB;CACA;CACA;CACA;CACA;AACF;;ACzBA,MAAa,cAAsB;CAAC;CAAa;CAAmB;AAAkB;AAEtF,MAAa,SAAiB;CAC5B,GAAG;CACH;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,MAAa,aAAqB;CAChC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,MAAa,UAAU;CAAE;CAAa;CAAQ;AAAW"}
|
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
import { t as createDecisionPlugin } from "./app-UakaWKAT.mjs";
|
|
2
|
-
// src/app/preset-plugin.ts
|
|
3
|
-
const PLUGIN_NAME = "decision-presets";
|
|
4
|
-
const presetPlugin = (rules) => createDecisionPlugin({
|
|
5
|
-
name: PLUGIN_NAME,
|
|
6
|
-
rules
|
|
7
|
-
});
|
|
8
|
-
export { presetPlugin as t };
|
|
9
|
-
|
|
10
|
-
//# sourceMappingURL=preset-plugin-ClpEFUN5.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"preset-plugin-ClpEFUN5.mjs","names":[],"sources":["../src/app/preset-plugin.ts"],"sourcesContent":["import { createDecisionPlugin } from \"@r_masseater/oxlint-plugin-decision\";\nimport type { DecisionPlugin } from \"@r_masseater/oxlint-plugin-decision\";\n\nimport type { Preset } from \"#/features/define-presets/index.ts\";\n\nconst PLUGIN_NAME = \"decision-presets\";\n\nexport const presetPlugin = (rules: Preset): DecisionPlugin =>\n createDecisionPlugin({ name: PLUGIN_NAME, rules });\n"],"mappings":";;AAKA,MAAM,cAAc;AAEpB,MAAa,gBAAgB,UAC3B,qBAAqB;CAAE,MAAM;CAAa;AAAM,CAAC"}
|
|
@@ -1,287 +0,0 @@
|
|
|
1
|
-
import { H as AnswerSchema, a as envNameOf, c as messageOf, d as toJson, h as parseVerdicts, i as captured, n as mergeResponses, y as PREFIX } from "./decision-B7hahWHz.mjs";
|
|
2
|
-
import { Array, Clock, Config, Effect, FileSystem, Function, Layer, Option, Path, Schedule, Schema, String as String$1, pipe } from "effect";
|
|
3
|
-
import { runAsWorker } from "synckit";
|
|
4
|
-
import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
|
|
5
|
-
import { Digest } from "effect/crypto";
|
|
6
|
-
import { layerDigest } from "@effect/platform-node-shared/NodeCrypto";
|
|
7
|
-
import { layer } from "@effect/platform-node-shared/NodeFileSystem";
|
|
8
|
-
import { layer as layer$1 } from "@effect/platform-node-shared/NodePath";
|
|
9
|
-
import { OtlpSerialization, OtlpTracer } from "effect/observability";
|
|
10
|
-
// src/features/serve-decisions/model/app-context.ts
|
|
11
|
-
const SELF = "masseater/masseater.dev";
|
|
12
|
-
const GIT_SUFFIX = /\.git\/?$/u;
|
|
13
|
-
const SEPARATORS = /[/:]/u;
|
|
14
|
-
const SLUG_PARTS = 2;
|
|
15
|
-
const GITDIR = /^gitdir:\s*(?<dir>.+)$/mu;
|
|
16
|
-
const ORIGIN_URL = /\[remote "origin"\][^[]*?\burl\s*=\s*(?<url>\S+)/u;
|
|
17
|
-
const isSet = (name) => Config.option(Config.NonEmptyString(name)).pipe(Effect.map(Option.isSome), Effect.orElseSucceed(() => false));
|
|
18
|
-
const contextOf = Effect.gen(function* contextOf() {
|
|
19
|
-
if (yield* isSet("GITHUB_ACTIONS")) return "github-actions";
|
|
20
|
-
if (yield* isSet("CLAUDE_CODE_REMOTE")) return "claude-code-cloud";
|
|
21
|
-
if (yield* isSet("CLAUDECODE")) return "claude-code";
|
|
22
|
-
return "local";
|
|
23
|
-
});
|
|
24
|
-
const slugOf = (url) => {
|
|
25
|
-
const parts = pipe(url, String$1.trim, String$1.replace(GIT_SUFFIX, ""), String$1.split(SEPARATORS), Array.filter((part) => String$1.isNonEmpty(part)));
|
|
26
|
-
if (parts.length < SLUG_PARTS) return Option.none();
|
|
27
|
-
return Option.some(pipe(Array.takeRight(parts, SLUG_PARTS), Array.join("/")));
|
|
28
|
-
};
|
|
29
|
-
const linkedGitDir = Effect.fn("linkedGitDir")(function* linkedGitDir(dir, dotGit) {
|
|
30
|
-
const fs = yield* FileSystem.FileSystem;
|
|
31
|
-
const path = yield* Path.Path;
|
|
32
|
-
const text = yield* fs.readFileString(dotGit);
|
|
33
|
-
return captured(String$1.match(GITDIR)(text), "dir").pipe(Option.map((found) => path.resolve(dir, String$1.trim(found))));
|
|
34
|
-
});
|
|
35
|
-
const gitDirAt = Effect.fn("gitDirAt")(function* gitDirAt(dir) {
|
|
36
|
-
const fs = yield* FileSystem.FileSystem;
|
|
37
|
-
const dotGit = (yield* Path.Path).join(dir, ".git");
|
|
38
|
-
const info = yield* fs.stat(dotGit).pipe(Effect.option);
|
|
39
|
-
if (Option.isNone(info)) return Option.none();
|
|
40
|
-
if (info.value.type === "Directory") return Option.some(dotGit);
|
|
41
|
-
return yield* linkedGitDir(dir, dotGit);
|
|
42
|
-
});
|
|
43
|
-
const gitDirFrom = (dir) => Effect.gen(function* walk() {
|
|
44
|
-
const path = yield* Path.Path;
|
|
45
|
-
const here = yield* gitDirAt(dir);
|
|
46
|
-
const parent = path.dirname(dir);
|
|
47
|
-
if (Option.isSome(here) || parent === dir) return here;
|
|
48
|
-
return yield* gitDirFrom(parent);
|
|
49
|
-
});
|
|
50
|
-
const commonDirOf = Effect.fn("commonDirOf")(function* commonDirOf(gitDir) {
|
|
51
|
-
const fs = yield* FileSystem.FileSystem;
|
|
52
|
-
const path = yield* Path.Path;
|
|
53
|
-
const common = yield* fs.readFileString(path.join(gitDir, "commondir")).pipe(Effect.option);
|
|
54
|
-
return Option.match(common, {
|
|
55
|
-
onNone: () => gitDir,
|
|
56
|
-
onSome: (relative) => path.resolve(gitDir, String$1.trim(relative))
|
|
57
|
-
});
|
|
58
|
-
});
|
|
59
|
-
const remoteSlug = Effect.gen(function* remoteSlug() {
|
|
60
|
-
const fs = yield* FileSystem.FileSystem;
|
|
61
|
-
const path = yield* Path.Path;
|
|
62
|
-
const gitDir = yield* gitDirFrom(path.resolve("."));
|
|
63
|
-
if (Option.isNone(gitDir)) return Option.none();
|
|
64
|
-
const commonDir = yield* commonDirOf(gitDir.value);
|
|
65
|
-
const config = yield* fs.readFileString(path.join(commonDir, "config"));
|
|
66
|
-
return captured(String$1.match(ORIGIN_URL)(config), "url").pipe(Option.flatMap(slugOf));
|
|
67
|
-
}).pipe(Effect.orElseSucceed(() => Option.none()));
|
|
68
|
-
const repoOf = Effect.gen(function* repoOf() {
|
|
69
|
-
const fromActions = yield* Config.option(Config.NonEmptyString("GITHUB_REPOSITORY")).pipe(Effect.orElseSucceed(() => Option.none()));
|
|
70
|
-
if (Option.isSome(fromActions)) return fromActions;
|
|
71
|
-
return yield* remoteSlug;
|
|
72
|
-
});
|
|
73
|
-
/** @internal */
|
|
74
|
-
const appContext = Effect.gen(function* app() {
|
|
75
|
-
const context = yield* contextOf;
|
|
76
|
-
const repo = yield* repoOf;
|
|
77
|
-
return {
|
|
78
|
-
repo: Option.getOrElse(repo, () => SELF),
|
|
79
|
-
context
|
|
80
|
-
};
|
|
81
|
-
});
|
|
82
|
-
// src/features/serve-decisions/model/system-one.ts
|
|
83
|
-
const FIRST_REDIRECT = 300;
|
|
84
|
-
const RETRY_INITIAL_MS = 10;
|
|
85
|
-
const RETRY_EXPONENT = 2;
|
|
86
|
-
const Decisions = Schema.Struct({
|
|
87
|
-
model: Schema.String,
|
|
88
|
-
answers: Schema.Record(Schema.String, AnswerSchema)
|
|
89
|
-
});
|
|
90
|
-
const Envelope = Schema.Struct({ result: Decisions });
|
|
91
|
-
const ErrorMessage = Schema.Struct({ message: Schema.String });
|
|
92
|
-
const ErrorBody = Schema.Union([Schema.Struct({ errors: Schema.NonEmptyArray(ErrorMessage) }), Schema.Struct({ detail: ErrorMessage })]);
|
|
93
|
-
const decodeErrorBody = Schema.decodeUnknownOption(ErrorBody);
|
|
94
|
-
const messageOfBody = (body) => Option.match(decodeErrorBody(body), {
|
|
95
|
-
onNone: () => "request failed",
|
|
96
|
-
onSome: (decoded) => {
|
|
97
|
-
if ("detail" in decoded) return decoded.detail.message;
|
|
98
|
-
return pipe(decoded.errors, Array.map(({ message }) => message), Array.join("; "));
|
|
99
|
-
}
|
|
100
|
-
});
|
|
101
|
-
const failureOf = (response) => response.json.pipe(Effect.option, Effect.flatMap((body) => Effect.fail(`http ${String(response.status)}: ${messageOfBody(Option.getOrUndefined(body))}`)));
|
|
102
|
-
const decodeEnvelope = HttpClientResponse.schemaBodyJson(Envelope);
|
|
103
|
-
const decodeDecisions = HttpClientResponse.schemaBodyJson(Decisions);
|
|
104
|
-
const invalid = ({ message }) => `invalid response: ${message}`;
|
|
105
|
-
const decisionsOf = (response, envelope) => {
|
|
106
|
-
if (envelope) return decodeEnvelope(response).pipe(Effect.mapBoth({
|
|
107
|
-
onSuccess: ({ result }) => result,
|
|
108
|
-
onFailure: invalid
|
|
109
|
-
}));
|
|
110
|
-
return decodeDecisions(response).pipe(Effect.mapError(invalid));
|
|
111
|
-
};
|
|
112
|
-
/** @internal */
|
|
113
|
-
const sendSystemOne = Effect.fn("sendSystemOne")(function* sendSystemOne(call, wire) {
|
|
114
|
-
const client = (yield* HttpClient.HttpClient).pipe(HttpClient.retryTransient({
|
|
115
|
-
retryOn: "response-only",
|
|
116
|
-
schedule: Schedule.exponential(RETRY_INITIAL_MS, RETRY_EXPONENT)
|
|
117
|
-
}));
|
|
118
|
-
const response = yield* HttpClientRequest.post(call.url).pipe(HttpClientRequest.bearerToken(call.token), HttpClientRequest.setHeaders(call.headers), HttpClientRequest.bodyJsonUnsafe({
|
|
119
|
-
model: call.model,
|
|
120
|
-
state: wire.state,
|
|
121
|
-
questions: wire.questions
|
|
122
|
-
}), client.execute, Effect.mapError(({ message }) => `network: ${message}`));
|
|
123
|
-
if (response.status >= FIRST_REDIRECT) return yield* failureOf(response);
|
|
124
|
-
const decisions = yield* decisionsOf(response, call.envelope);
|
|
125
|
-
return {
|
|
126
|
-
model: decisions.model,
|
|
127
|
-
answers: decisions.answers
|
|
128
|
-
};
|
|
129
|
-
});
|
|
130
|
-
// src/features/serve-decisions/model/workers-ai.ts
|
|
131
|
-
const DEFAULT_GATEWAY = "default";
|
|
132
|
-
const DEFAULT_API_URL = "https://api.cloudflare.com/client/v4";
|
|
133
|
-
const RUN_PATH = "/ai/run";
|
|
134
|
-
const TRAILING_SLASHES$1 = /\/+$/u;
|
|
135
|
-
const MODEL_NAME = /(?<name>[^/]+)$/u;
|
|
136
|
-
const accountUrl = ({ api, account }) => `${String$1.replace(TRAILING_SLASHES$1, "")(String$1.trim(api))}/accounts/${String$1.trim(account)}`;
|
|
137
|
-
/** @internal */
|
|
138
|
-
const endpointOf = (env) => Config.all({
|
|
139
|
-
api: Config.String(envNameOf(env, "CLOUDFLARE_API_BASE_URL")).pipe(Config.withDefault(DEFAULT_API_URL)),
|
|
140
|
-
account: Config.NonEmptyString(envNameOf(env, "CLOUDFLARE_ACCOUNT_ID"))
|
|
141
|
-
}).pipe(Config.map(accountUrl));
|
|
142
|
-
const modelNameOf = (model) => Option.getOrElse(captured(String$1.match(MODEL_NAME)(model), "name"), () => model);
|
|
143
|
-
/** @internal */
|
|
144
|
-
const sendWorkersAi = Effect.fn("sendWorkersAi")(function* sendWorkersAi(endpoint, wire, { env }) {
|
|
145
|
-
const token = yield* Config.Redacted(envNameOf(env, "CLOUDFLARE_API_TOKEN"));
|
|
146
|
-
const gateway = yield* Config.NonEmptyString(envNameOf(env, "CLOUDFLARE_AI_GATEWAY_ID")).pipe(Config.withDefault(DEFAULT_GATEWAY));
|
|
147
|
-
const app = yield* appContext;
|
|
148
|
-
const decided = yield* sendSystemOne({
|
|
149
|
-
url: `${endpoint}${RUN_PATH}/${wire.model}`,
|
|
150
|
-
model: modelNameOf(wire.model),
|
|
151
|
-
token,
|
|
152
|
-
headers: {
|
|
153
|
-
"cf-aig-gateway-id": gateway,
|
|
154
|
-
"cf-aig-metadata": toJson({
|
|
155
|
-
tool: PREFIX,
|
|
156
|
-
...app
|
|
157
|
-
})
|
|
158
|
-
},
|
|
159
|
-
envelope: true
|
|
160
|
-
}, wire);
|
|
161
|
-
return {
|
|
162
|
-
model: wire.model,
|
|
163
|
-
answers: decided.answers
|
|
164
|
-
};
|
|
165
|
-
});
|
|
166
|
-
// src/features/serve-decisions/model/typesafe.ts
|
|
167
|
-
const DEFAULT_BASE_URL = "https://api.typesafe.ai";
|
|
168
|
-
const SYSTEM_ONE_PATH = "/v1/systemone";
|
|
169
|
-
const TRAILING_SLASHES = /\/+$/u;
|
|
170
|
-
/** @internal */
|
|
171
|
-
const typesafeEndpointOf = (env) => Config.String(envNameOf(env, "TYPESAFE_BASE_URL")).pipe(Config.withDefault(DEFAULT_BASE_URL), Config.map((url) => String$1.replace(TRAILING_SLASHES, "")(String$1.trim(url))));
|
|
172
|
-
/** @internal */
|
|
173
|
-
const sendTypesafe = Effect.fn("sendTypesafe")(function* sendTypesafe(endpoint, wire, { env }) {
|
|
174
|
-
const token = yield* Config.Redacted(envNameOf(env, "TYPESAFE_API_KEY"));
|
|
175
|
-
return yield* sendSystemOne({
|
|
176
|
-
url: `${endpoint}${SYSTEM_ONE_PATH}`,
|
|
177
|
-
model: wire.model,
|
|
178
|
-
token,
|
|
179
|
-
headers: {},
|
|
180
|
-
envelope: false
|
|
181
|
-
}, wire);
|
|
182
|
-
});
|
|
183
|
-
// src/features/serve-decisions/model/cache.ts
|
|
184
|
-
const DATA_FIRST_ARITY = 2;
|
|
185
|
-
const CACHE_VERSION = 7;
|
|
186
|
-
/** @internal */
|
|
187
|
-
const CACHE_DIR = `node_modules/.cache/${PREFIX}`;
|
|
188
|
-
const encodeJson = (value) => Schema.encodeUnknownEffect(Schema.fromJsonString(Schema.Unknown))(value).pipe(Effect.orDie);
|
|
189
|
-
/** @internal */
|
|
190
|
-
const cacheFile = Effect.fn("cacheFile")(function* cacheFile(endpoint, request) {
|
|
191
|
-
const digest = yield* Digest.Digest;
|
|
192
|
-
const path = yield* Path.Path;
|
|
193
|
-
const json = yield* encodeJson({
|
|
194
|
-
version: CACHE_VERSION,
|
|
195
|
-
endpoint,
|
|
196
|
-
request
|
|
197
|
-
});
|
|
198
|
-
const payload = new TextEncoder().encode(json);
|
|
199
|
-
const hash = yield* digest.digestHex(Digest.sha256, payload);
|
|
200
|
-
return path.resolve(CACHE_DIR, `${hash}.json`);
|
|
201
|
-
});
|
|
202
|
-
const CachedResponse = Schema.Struct({
|
|
203
|
-
model: Schema.NonEmptyString,
|
|
204
|
-
answers: Schema.Record(Schema.String, AnswerSchema)
|
|
205
|
-
});
|
|
206
|
-
const decodeCached = Schema.decodeOption(Schema.fromJsonString(CachedResponse));
|
|
207
|
-
/** @internal */
|
|
208
|
-
const isComplete = Function.dual(DATA_FIRST_ARITY, (response, request) => Option.liftThrowable(() => parseVerdicts(response, request).complete)().pipe(Option.getOrElse(() => false)));
|
|
209
|
-
/** @internal */
|
|
210
|
-
const readCache = Effect.fn("readCache")(function* readCache(file, request) {
|
|
211
|
-
return (yield* (yield* FileSystem.FileSystem).readFileString(file).pipe(Effect.option)).pipe(Option.flatMap((raw) => decodeCached(raw)), Option.filter((response) => isComplete(response, request)));
|
|
212
|
-
});
|
|
213
|
-
/** @internal */
|
|
214
|
-
const writeCache = Effect.fn("writeCache")(function* writeCache(file, response) {
|
|
215
|
-
const fs = yield* FileSystem.FileSystem;
|
|
216
|
-
const path = yield* Path.Path;
|
|
217
|
-
const now = yield* Clock.currentTimeMillis;
|
|
218
|
-
const temp = `${file}.tmp-${String(now)}`;
|
|
219
|
-
const json = yield* encodeJson(response);
|
|
220
|
-
yield* fs.makeDirectory(path.dirname(file), { recursive: true });
|
|
221
|
-
yield* fs.writeFileString(temp, json);
|
|
222
|
-
yield* fs.rename(temp, file);
|
|
223
|
-
});
|
|
224
|
-
// src/features/serve-decisions/model/services.ts
|
|
225
|
-
const tracing = OtlpTracer.layerFromConfig({ resource: { serviceName: "oxlint-plugin-decision" } }).pipe(Layer.provide(OtlpSerialization.layerJson), Layer.provide(FetchHttpClient.layer));
|
|
226
|
-
/** @internal */
|
|
227
|
-
const workerServices = [
|
|
228
|
-
layer,
|
|
229
|
-
layer$1,
|
|
230
|
-
layerDigest,
|
|
231
|
-
FetchHttpClient.layer,
|
|
232
|
-
tracing
|
|
233
|
-
];
|
|
234
|
-
// src/features/serve-decisions/model/serve-decisions.ts
|
|
235
|
-
const ask = Effect.fn("ask")(function* ask(transport, endpoint, { request, timeoutMs, env }) {
|
|
236
|
-
const responses = yield* Effect.forEach(transport.wires(request), (wire) => transport.send(endpoint, wire, { env }), { concurrency: "unbounded" }).pipe(Effect.timeoutOrElse({
|
|
237
|
-
duration: timeoutMs,
|
|
238
|
-
orElse: () => Effect.fail("timeout")
|
|
239
|
-
}));
|
|
240
|
-
return mergeResponses(responses);
|
|
241
|
-
});
|
|
242
|
-
const askAndStore = Effect.fn("askAndStore")(function* askAndStore(transport, { endpoint, file }, input) {
|
|
243
|
-
const response = yield* ask(transport, endpoint, input);
|
|
244
|
-
if (isComplete(response, input.request)) yield* writeCache(file, response).pipe(Effect.ignore);
|
|
245
|
-
return response;
|
|
246
|
-
});
|
|
247
|
-
const decide = Effect.fn("decide")(function* decide(transport, input) {
|
|
248
|
-
yield* Effect.annotateCurrentSpan({ model: input.request.model });
|
|
249
|
-
const endpoint = yield* transport.endpoint(input.env);
|
|
250
|
-
const file = yield* cacheFile(endpoint, input.request);
|
|
251
|
-
const cached = yield* readCache(file, input.request);
|
|
252
|
-
yield* Effect.annotateCurrentSpan({ cached: Option.isSome(cached) });
|
|
253
|
-
if (Option.isSome(cached)) return {
|
|
254
|
-
response: cached.value,
|
|
255
|
-
cached: true
|
|
256
|
-
};
|
|
257
|
-
return {
|
|
258
|
-
response: yield* askAndStore(transport, {
|
|
259
|
-
endpoint,
|
|
260
|
-
file
|
|
261
|
-
}, input),
|
|
262
|
-
cached: false
|
|
263
|
-
};
|
|
264
|
-
});
|
|
265
|
-
const reasonOf = (error) => {
|
|
266
|
-
if (typeof error === "string") return error;
|
|
267
|
-
return messageOf(error);
|
|
268
|
-
};
|
|
269
|
-
const decideOne = (transport, input) => decide(transport, input).pipe(Effect.match({
|
|
270
|
-
onSuccess: ({ response, cached }) => ({
|
|
271
|
-
ok: true,
|
|
272
|
-
response,
|
|
273
|
-
cached
|
|
274
|
-
}),
|
|
275
|
-
onFailure: (error) => ({
|
|
276
|
-
ok: false,
|
|
277
|
-
reason: reasonOf(error)
|
|
278
|
-
})
|
|
279
|
-
}));
|
|
280
|
-
const decideEach = (transport, inputs) => Effect.all(pipe(inputs, Array.map((input) => decideOne(transport, input))), { concurrency: "unbounded" }).pipe(Effect.provide(workerServices));
|
|
281
|
-
/** @internal */
|
|
282
|
-
const serveDecisions = (transport) => {
|
|
283
|
-
runAsWorker((inputs) => Effect.runPromise(decideEach(transport, inputs)));
|
|
284
|
-
};
|
|
285
|
-
export { sendWorkersAi as a, endpointOf as i, sendTypesafe as n, typesafeEndpointOf as r, serveDecisions as t };
|
|
286
|
-
|
|
287
|
-
//# sourceMappingURL=serve-decisions-DYGwLMft.mjs.map
|