@r_masseater/oxlint-plugin-decision 0.8.3 → 0.9.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.
Files changed (30) hide show
  1. package/README.md +2 -0
  2. package/dist/{app-D2bguKZ_.mjs → app-BO1xNTFk.mjs} +80 -10
  3. package/dist/app-BO1xNTFk.mjs.map +1 -0
  4. package/dist/{claim-rule-B0LCcxxc.mjs → claim-rule-BtckE1OP.mjs} +2 -2
  5. package/dist/{claim-rule-B0LCcxxc.mjs.map → claim-rule-BtckE1OP.mjs.map} +1 -1
  6. package/dist/cloudflare-worker.mjs +2 -2
  7. package/dist/{index-CK88FBE5.d.mts → index-B2bdY9ax.d.mts} +28 -2
  8. package/dist/{index-B4wX62VC.d.mts → index-YYrIqZKY.d.mts} +2 -2
  9. package/dist/index.d.mts +2 -2
  10. package/dist/index.mjs +1 -1
  11. package/dist/{preset-plugin-MKdvpXxa.mjs → preset-plugin-DlO5OR3z.mjs} +3 -3
  12. package/dist/{preset-plugin-MKdvpXxa.mjs.map → preset-plugin-DlO5OR3z.mjs.map} +1 -1
  13. package/dist/presets/ai-slop.d.mts +2 -2
  14. package/dist/presets/ai-slop.mjs +2 -2
  15. package/dist/presets/index.d.mts +1 -1
  16. package/dist/presets/index.mjs +1 -1
  17. package/dist/presets/recommended.d.mts +1 -1
  18. package/dist/presets/recommended.mjs +1 -1
  19. package/dist/presets/review-only.d.mts +1 -1
  20. package/dist/presets/review-only.mjs +1 -1
  21. package/dist/presets/strict.d.mts +1 -1
  22. package/dist/presets/strict.mjs +1 -1
  23. package/dist/{serve-decisions-D6M-l2uy.mjs → serve-decisions-vZr4L2TM.mjs} +2 -2
  24. package/dist/{serve-decisions-D6M-l2uy.mjs.map → serve-decisions-vZr4L2TM.mjs.map} +1 -1
  25. package/dist/typesafe-worker.mjs +2 -2
  26. package/dist/{wire-CKpt_MBX.mjs → wire-D0YSbfBG.mjs} +3 -2
  27. package/dist/wire-D0YSbfBG.mjs.map +1 -0
  28. package/package.json +6 -6
  29. package/dist/app-D2bguKZ_.mjs.map +0 -1
  30. package/dist/wire-CKpt_MBX.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"preset-plugin-MKdvpXxa.mjs","names":["Str","Arr"],"sources":["../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","../src/app/preset-plugin.ts"],"sourcesContent":["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","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":";;;;AAOA,MAAM,8BAAmC,IAAI,IAAI,CAC/C,IACA,GAAGA,OAAI,MAAM,yCAAyC,EAAE,CAC1D,CAAC;AAED,MAAM,iBAAiB;AAEvB,MAAM,kBACH,UACA,SACC,UAAU,KACP,SAAiBA,OAAI,WAAW,IAAI,CAAC,CAAC,IAAI,IAC1C,SAAiB,YAAY,IAAIA,OAAI,MAAM,KAAK,QAAQ,KAAK,SAAS,cAAc,CAAC,CAAC,IAAI,CAAC,CAC9F,CAAC,CAAC,IAAI;AAEV,MAAM,YACH,UACA,SACCA,OAAI,SAAS,IAAI,CAAC,CAAC,IAAI;AAO3B,MAAa,aAAa,EAAE,UAAU,WAAW,CAAC,QAA2B;CAC3E,MAAM,WAAW,CACf,GAAG,KACD,UACAC,MAAI,KAAK,SAAS,eAAe,IAAI,CAAC,CACxC,GACA,GAAG,KACD,UACAA,MAAI,KAAK,SAAS,SAAS,IAAI,CAAC,CAClC,CACF;CACA,QAA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,KAAK;CACL,IAAI;AACN,CAAC;AAED,MAAa,wBAAwB,UAAU;CAC7C,IAAI;CACJ,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,KAAK;CACL,KAAK;CACL,IAAI;AACN,CAAC;AAED,MAAa,wBAAwB,UAAU;CAC7C,IAAI;CACJ,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,KAAK;CACL,KAAK;CACL,IAAI;AACN,CAAC;AAED,MAAa,6BAA6B,UAAU;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;;AC5DzD,MAAM,cAAc;AAEpB,MAAa,gBAAgB,UAC3B,qBAAqB;CAAE,MAAM;CAAa;AAAM,CAAC"}
1
+ {"version":3,"file":"preset-plugin-DlO5OR3z.mjs","names":["Str","Arr"],"sources":["../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","../src/app/preset-plugin.ts"],"sourcesContent":["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","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":";;;;AAOA,MAAM,8BAAmC,IAAI,IAAI,CAC/C,IACA,GAAGA,OAAI,MAAM,yCAAyC,EAAE,CAC1D,CAAC;AAED,MAAM,iBAAiB;AAEvB,MAAM,kBACH,UACA,SACC,UAAU,KACP,SAAiBA,OAAI,WAAW,IAAI,CAAC,CAAC,IAAI,IAC1C,SAAiB,YAAY,IAAIA,OAAI,MAAM,KAAK,QAAQ,KAAK,SAAS,cAAc,CAAC,CAAC,IAAI,CAAC,CAC9F,CAAC,CAAC,IAAI;AAEV,MAAM,YACH,UACA,SACCA,OAAI,SAAS,IAAI,CAAC,CAAC,IAAI;AAO3B,MAAa,aAAa,EAAE,UAAU,WAAW,CAAC,QAA2B;CAC3E,MAAM,WAAW,CACf,GAAG,KACD,UACAC,MAAI,KAAK,SAAS,eAAe,IAAI,CAAC,CACxC,GACA,GAAG,KACD,UACAA,MAAI,KAAK,SAAS,SAAS,IAAI,CAAC,CAClC,CACF;CACA,QAAQ,OAAO,EAAE,WACf,OAAO,OAAO,OAAO,gBAAgB,IAAI,IAAI,UAC3C,KACE,UACAA,MAAI,MAAM,YAAY,QAAQ,KAAK,CAAC,CACtC,CACF;AACJ;AAEA,MAAM,UAAU,WACd,MAAM,MAAM,MAAM,CAAC,CAAC,KAClB,MAAM,KAAK;CAAE,MAAM;CAAoB,UAAU;AAAM,IAAI,WAAW,OAAO,OAAO,MAAM,CAAC,GAC3F,MAAM,OAAO,YAAY,CAC3B;AAEF,MAAM,YAAY,SAChB,MAAM,MAAM,IAAI,CAAC,CAAC,KAChB,MAAM,KAAK,EAAE,MAAM,iBAAiB,IAAI,SAAS,OAAO,KAAK,KAAK,MAAM,CAAC,GACzE,MAAM,aAAa,OAA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;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;;AC5DzD,MAAM,cAAc;AAEpB,MAAa,gBAAgB,UAC3B,qBAAqB;CAAE,MAAM;CAAa;AAAM,CAAC"}
@@ -1,5 +1,5 @@
1
- import { o as DecisionPlugin } from "../index-CK88FBE5.mjs";
2
- import { B as redundantGuard, F as commentRestatesCode, H as suppressionInsteadOfFix, I as defaultMasksMissingValue, L as docRestatesSignature, M as aiSlopRules, N as castInsteadOfNarrowing, P as commentNarratesHistory, R as passThroughWrapper, V as reinventsBuiltin, z as placeholderImplementation } from "../index-B4wX62VC.mjs";
1
+ import { u as DecisionPlugin } from "../index-B2bdY9ax.mjs";
2
+ import { B as redundantGuard, F as commentRestatesCode, H as suppressionInsteadOfFix, I as defaultMasksMissingValue, L as docRestatesSignature, M as aiSlopRules, N as castInsteadOfNarrowing, P as commentNarratesHistory, R as passThroughWrapper, V as reinventsBuiltin, z as placeholderImplementation } from "../index-YYrIqZKY.mjs";
3
3
  declare const plugin: DecisionPlugin;
4
4
  export { aiSlopRules, castInsteadOfNarrowing, commentNarratesHistory, commentRestatesCode, plugin as default, defaultMasksMissingValue, docRestatesSignature, passThroughWrapper, placeholderImplementation, redundantGuard, reinventsBuiltin, suppressionInsteadOfFix };
5
5
  //# sourceMappingURL=ai-slop.d.mts.map
@@ -1,5 +1,5 @@
1
- import { t as createDecisionPlugin } from "../app-D2bguKZ_.mjs";
2
- import { a as dualSelect, i as containing, o as identifierOf, r as claimRule, s as ofType } from "../claim-rule-B0LCcxxc.mjs";
1
+ import { t as createDecisionPlugin } from "../app-BO1xNTFk.mjs";
2
+ import { a as dualSelect, i as containing, o as identifierOf, r as claimRule, s as ofType } from "../claim-rule-BtckE1OP.mjs";
3
3
  import { Array, Match, Option, Predicate, String, pipe } from "effect";
4
4
  // src/features/define-presets/lib/ai-slop-select.ts
5
5
  const isPlaceholderValue = ofType("Literal", "TemplateLiteral", "ArrayExpression", "ObjectExpression");
@@ -1,3 +1,3 @@
1
1
  import plugin from "./recommended.mjs";
2
- import { A as safeNameIsSafe, C as docErrorsMatchBody, D as logLevelMatchesEvent, E as idempotentName, O as logMessageMatchesEvent, S as commentDescribesDeclaration, T as fnNamePromises, _ as reviewOnly, a as testNameDescribesCode, b as codeClaims, c as nameMatchesBehavior, d as noPromptInjection, f as preferSchemaValidation, g as recommended, h as presets, i as testMocksSubject, j as varNameDescribesValue, k as pureNameIsPure, l as noHardcodedSecrets, m as Preset, n as snapshotOnlyBehaviourClaim, o as testNameVerifiesClaim, p as untrustedInputRisk, r as testClaims, s as domainNaming, t as describeNamesSubject, u as noPiiInLogs, v as strict, w as errorMessageMatchesCondition, x as commentDescribesBlock, y as catchHidesFailure } from "../index-B4wX62VC.mjs";
2
+ import { A as safeNameIsSafe, C as docErrorsMatchBody, D as logLevelMatchesEvent, E as idempotentName, O as logMessageMatchesEvent, S as commentDescribesDeclaration, T as fnNamePromises, _ as reviewOnly, a as testNameDescribesCode, b as codeClaims, c as nameMatchesBehavior, d as noPromptInjection, f as preferSchemaValidation, g as recommended, h as presets, i as testMocksSubject, j as varNameDescribesValue, k as pureNameIsPure, l as noHardcodedSecrets, m as Preset, n as snapshotOnlyBehaviourClaim, o as testNameVerifiesClaim, p as untrustedInputRisk, r as testClaims, s as domainNaming, t as describeNamesSubject, u as noPiiInLogs, v as strict, w as errorMessageMatchesCondition, x as commentDescribesBlock, y as catchHidesFailure } from "../index-YYrIqZKY.mjs";
3
3
  export { type Preset, catchHidesFailure, codeClaims, commentDescribesBlock, commentDescribesDeclaration, plugin as default, describeNamesSubject, docErrorsMatchBody, domainNaming, errorMessageMatchesCondition, fnNamePromises, idempotentName, logLevelMatchesEvent, logMessageMatchesEvent, nameMatchesBehavior, noHardcodedSecrets, noPiiInLogs, noPromptInjection, preferSchemaValidation, presets, pureNameIsPure, recommended, reviewOnly, safeNameIsSafe, snapshotOnlyBehaviourClaim, strict, testClaims, testMocksSubject, testNameDescribesCode, testNameVerifiesClaim, untrustedInputRisk, varNameDescribesValue };
@@ -1,3 +1,3 @@
1
1
  import plugin from "./recommended.mjs";
2
- import { A as safeNameIsSafe, C as docErrorsMatchBody, D as logLevelMatchesEvent, E as idempotentName, O as logMessageMatchesEvent, S as commentDescribesDeclaration, T as fnNamePromises, _ as preferSchemaValidation, a as strict, b as codeClaims, c as testClaims, d as testNameVerifiesClaim, f as domainNaming, g as noPromptInjection, h as noPiiInLogs, i as reviewOnly, j as varNameDescribesValue, k as pureNameIsPure, l as testMocksSubject, m as noHardcodedSecrets, n as presets, o as describeNamesSubject, p as nameMatchesBehavior, r as recommended, s as snapshotOnlyBehaviourClaim, u as testNameDescribesCode, v as untrustedInputRisk, w as errorMessageMatchesCondition, x as commentDescribesBlock, y as catchHidesFailure } from "../preset-plugin-MKdvpXxa.mjs";
2
+ import { A as safeNameIsSafe, C as docErrorsMatchBody, D as logLevelMatchesEvent, E as idempotentName, O as logMessageMatchesEvent, S as commentDescribesDeclaration, T as fnNamePromises, _ as preferSchemaValidation, a as strict, b as codeClaims, c as testClaims, d as testNameVerifiesClaim, f as domainNaming, g as noPromptInjection, h as noPiiInLogs, i as reviewOnly, j as varNameDescribesValue, k as pureNameIsPure, l as testMocksSubject, m as noHardcodedSecrets, n as presets, o as describeNamesSubject, p as nameMatchesBehavior, r as recommended, s as snapshotOnlyBehaviourClaim, u as testNameDescribesCode, v as untrustedInputRisk, w as errorMessageMatchesCondition, x as commentDescribesBlock, y as catchHidesFailure } from "../preset-plugin-DlO5OR3z.mjs";
3
3
  export { catchHidesFailure, codeClaims, commentDescribesBlock, commentDescribesDeclaration, plugin as default, describeNamesSubject, docErrorsMatchBody, domainNaming, errorMessageMatchesCondition, fnNamePromises, idempotentName, logLevelMatchesEvent, logMessageMatchesEvent, nameMatchesBehavior, noHardcodedSecrets, noPiiInLogs, noPromptInjection, preferSchemaValidation, presets, pureNameIsPure, recommended, reviewOnly, safeNameIsSafe, snapshotOnlyBehaviourClaim, strict, testClaims, testMocksSubject, testNameDescribesCode, testNameVerifiesClaim, untrustedInputRisk, varNameDescribesValue };
@@ -1,4 +1,4 @@
1
- import { o as DecisionPlugin } from "../index-CK88FBE5.mjs";
1
+ import { u as DecisionPlugin } from "../index-B2bdY9ax.mjs";
2
2
  declare const plugin: DecisionPlugin;
3
3
  export { plugin as default };
4
4
  //# sourceMappingURL=recommended.d.mts.map
@@ -1,4 +1,4 @@
1
- import { r as recommended, t as presetPlugin } from "../preset-plugin-MKdvpXxa.mjs";
1
+ import { r as recommended, t as presetPlugin } from "../preset-plugin-DlO5OR3z.mjs";
2
2
  // src/app/recommended.ts
3
3
  const plugin = presetPlugin(recommended);
4
4
  export { plugin as default };
@@ -1,4 +1,4 @@
1
- import { o as DecisionPlugin } from "../index-CK88FBE5.mjs";
1
+ import { u as DecisionPlugin } from "../index-B2bdY9ax.mjs";
2
2
  declare const plugin: DecisionPlugin;
3
3
  export { plugin as default };
4
4
  //# sourceMappingURL=review-only.d.mts.map
@@ -1,4 +1,4 @@
1
- import { i as reviewOnly, t as presetPlugin } from "../preset-plugin-MKdvpXxa.mjs";
1
+ import { i as reviewOnly, t as presetPlugin } from "../preset-plugin-DlO5OR3z.mjs";
2
2
  // src/app/review-only.ts
3
3
  const plugin = presetPlugin(reviewOnly);
4
4
  export { plugin as default };
@@ -1,4 +1,4 @@
1
- import { o as DecisionPlugin } from "../index-CK88FBE5.mjs";
1
+ import { u as DecisionPlugin } from "../index-B2bdY9ax.mjs";
2
2
  declare const plugin: DecisionPlugin;
3
3
  export { plugin as default };
4
4
  //# sourceMappingURL=strict.d.mts.map
@@ -1,4 +1,4 @@
1
- import { a as strict, t as presetPlugin } from "../preset-plugin-MKdvpXxa.mjs";
1
+ import { a as strict, t as presetPlugin } from "../preset-plugin-DlO5OR3z.mjs";
2
2
  // src/app/strict.ts
3
3
  const plugin = presetPlugin(strict);
4
4
  export { plugin as default };
@@ -1,4 +1,4 @@
1
- import { L as AnswerSchema, _ as snippetRefOf, b as PREFIX, c as messageOf, h as parseVerdicts, n as mergeResponses } from "./wire-CKpt_MBX.mjs";
1
+ import { R as AnswerSchema, c as messageOf, g as parseVerdicts, n as mergeResponses, v as snippetRefOf, x as PREFIX } from "./wire-D0YSbfBG.mjs";
2
2
  import { Array, Clock, Effect, FileSystem, Function, Layer, Option, Path, Record, Schedule, Schema, pipe } from "effect";
3
3
  import { runAsWorker } from "synckit";
4
4
  import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
@@ -229,4 +229,4 @@ const serveDecisions = (transport) => {
229
229
  };
230
230
  export { sendSystemOne as n, serveDecisions as t };
231
231
 
232
- //# sourceMappingURL=serve-decisions-D6M-l2uy.mjs.map
232
+ //# sourceMappingURL=serve-decisions-vZr4L2TM.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"serve-decisions-D6M-l2uy.mjs","names":["Arr","Rec","Fn","Arr","fileSystem","path","Arr"],"sources":["../src/features/serve-decisions/model/system-one.ts","../src/features/serve-decisions/model/cache.ts","../src/features/serve-decisions/model/services.ts","../src/features/serve-decisions/model/serve-decisions.ts"],"sourcesContent":["import { Array as Arr, Effect, Option, Schedule, Schema, pipe } from \"effect\";\nimport type { Redacted } from \"effect\";\nimport { HttpClient, HttpClientRequest, HttpClientResponse } from \"effect/http\";\n\nimport { AnswerSchema } from \"#/entities/decision/index.ts\";\nimport type { DecisionResponse, WireRequest } from \"#/entities/decision/index.ts\";\n\nconst FIRST_REDIRECT = 300;\nconst RETRY_INITIAL_MS = 10;\nconst RETRY_EXPONENT = 2;\n\nconst Decisions = Schema.Struct({\n model: Schema.String,\n answers: Schema.Record(Schema.String, AnswerSchema),\n});\n\nconst Envelope = Schema.Struct({ result: Decisions });\n\nconst ErrorMessage = Schema.Struct({ message: Schema.String });\n\nconst ErrorBody = Schema.Union([\n Schema.Struct({ errors: Schema.NonEmptyArray(ErrorMessage) }),\n Schema.Struct({ detail: ErrorMessage }),\n]);\n\nconst decodeErrorBody = Schema.decodeUnknownOption(ErrorBody);\n\nconst messageOfBody = (body: unknown): string =>\n Option.match(decodeErrorBody(body), {\n onNone: () => \"request failed\",\n onSome: (decoded) => {\n if (\"detail\" in decoded) {\n return decoded.detail.message;\n }\n return pipe(\n decoded.errors,\n Arr.map(({ message }) => message),\n Arr.join(\"; \"),\n );\n },\n });\n\nconst failureOf = (response: HttpClientResponse.HttpClientResponse): Effect.Effect<never, string> =>\n response.json.pipe(\n Effect.option,\n Effect.flatMap((body) =>\n Effect.fail(\n `http ${String(response.status)}: ${body.pipe(Option.getOrUndefined, messageOfBody)}`,\n ),\n ),\n );\n\n/** @internal */\nexport interface SystemOneCall {\n readonly url: string;\n readonly model: string;\n readonly token: Redacted.Redacted;\n readonly headers: Readonly<Record<string, string>>;\n readonly envelope: boolean;\n}\n\nconst decodeEnvelope = HttpClientResponse.schemaBodyJson(Envelope);\n\nconst decodeDecisions = HttpClientResponse.schemaBodyJson(Decisions);\n\nconst invalid = ({ message }: Readonly<{ message: string }>): string =>\n `invalid response: ${message}`;\n\nconst decisionsOf = (\n response: HttpClientResponse.HttpClientResponse,\n envelope: boolean,\n): Effect.Effect<typeof Decisions.Type, string> => {\n if (envelope) {\n return decodeEnvelope(response).pipe(\n Effect.mapBoth({ onSuccess: ({ result }) => result, onFailure: invalid }),\n );\n }\n return decodeDecisions(response).pipe(Effect.mapError(invalid));\n};\n\n/** @internal */\nexport const sendSystemOne = Effect.fn(\"sendSystemOne\")(function* sendSystemOne(\n call: SystemOneCall,\n wire: WireRequest,\n) {\n const client = (yield* HttpClient.HttpClient).pipe(\n HttpClient.retryTransient({\n retryOn: \"response-only\",\n schedule: Schedule.exponential(RETRY_INITIAL_MS, RETRY_EXPONENT),\n }),\n );\n const response = yield* HttpClientRequest.post(call.url).pipe(\n HttpClientRequest.bearerToken(call.token),\n HttpClientRequest.setHeaders(call.headers),\n HttpClientRequest.bodyJsonUnsafe({\n model: call.model,\n state: wire.state,\n questions: wire.questions,\n }),\n client.execute,\n Effect.mapError(({ message }) => `network: ${message}`),\n );\n if (response.status >= FIRST_REDIRECT) {\n return yield* failureOf(response);\n }\n const decisions = yield* decisionsOf(response, call.envelope);\n return { model: decisions.model, answers: decisions.answers } satisfies DecisionResponse;\n});\n","import {\n Array as Arr,\n Clock,\n Effect,\n FileSystem,\n Function as Fn,\n Option,\n Path,\n Record as Rec,\n Schema,\n pipe,\n} from \"effect\";\nimport { Digest } from \"effect/crypto\";\n\nimport { AnswerSchema, PREFIX, parseVerdicts, snippetRefOf } from \"#/entities/decision/index.ts\";\nimport type { Answer, DecisionRequest, DecisionResponse } from \"#/entities/decision/index.ts\";\n\nconst DATA_FIRST_ARITY = 2;\n\nconst CACHE_VERSION = 8;\n/** @internal */\nexport const CACHE_DIR = `node_modules/.cache/${PREFIX}`;\n\nconst encodeJson = (value: unknown): Effect.Effect<string> =>\n Schema.encodeUnknownEffect(Schema.fromJsonString(Schema.Unknown))(value).pipe(Effect.orDie);\n\nconst contextOf = (request: DecisionRequest, ref: string): Option.Option<string> =>\n pipe(Option.fromUndefinedOr(request.state.contexts), Option.flatMap(Rec.get(ref)));\n\nconst keyOf = (endpoint: string, request: DecisionRequest, id: string): unknown => {\n const ref = snippetRefOf(id);\n return {\n version: CACHE_VERSION,\n endpoint,\n model: request.model,\n snippet: request.state.snippets[ref],\n context: Option.getOrNull(contextOf(request, ref)),\n question: request.questions[id],\n };\n};\n\nconst cacheFile = Effect.fn(\"cacheFile\")(function* cacheFile(key: unknown) {\n const digest = yield* Digest.Digest;\n const path = yield* Path.Path;\n const json = yield* encodeJson(key);\n const hash = yield* digest.digestHex(Digest.sha256, new TextEncoder().encode(json));\n return path.resolve(CACHE_DIR, `${hash}.json`);\n});\n\nconst CachedAnswerSchema = Schema.Struct({ model: Schema.NonEmptyString, answer: AnswerSchema });\n\n/** @internal */\nexport interface CachedAnswer {\n readonly model: string;\n readonly answer: Answer;\n}\n\nconst decodeCached = Schema.decodeOption(Schema.fromJsonString(CachedAnswerSchema));\n\n/** @internal */\nexport interface QuestionCache {\n readonly id: string;\n readonly file: string;\n readonly cached: Option.Option<CachedAnswer>;\n}\n\n/** @internal */\nexport const isComplete: {\n (request: DecisionRequest): (response: DecisionResponse) => boolean;\n (response: DecisionResponse, request: DecisionRequest): boolean;\n} = Fn.dual(DATA_FIRST_ARITY, (response: DecisionResponse, request: DecisionRequest): boolean =>\n Option.liftThrowable(() => parseVerdicts(response, request).complete)().pipe(\n Option.getOrElse(() => false),\n ),\n);\n\nconst keptFor =\n (refs: readonly string[]) =>\n <Value>(record: Readonly<Record<string, Value>>): Record<string, Value> =>\n pipe(\n record,\n Rec.filter((_value, ref) => refs.includes(ref)),\n );\n\n/** @internal */\nexport const missingRequest: {\n (missing: readonly string[]): (request: DecisionRequest) => DecisionRequest;\n (request: DecisionRequest, missing: readonly string[]): DecisionRequest;\n} = Fn.dual(\n DATA_FIRST_ARITY,\n (request: DecisionRequest, missing: readonly string[]): DecisionRequest => {\n const refs = pipe(missing, Arr.map(snippetRefOf));\n const kept = keptFor(refs);\n return {\n ...request,\n state: {\n ...request.state,\n snippets: kept(request.state.snippets),\n ...pipe(\n Option.fromUndefinedOr(request.state.contexts),\n Option.match({\n onNone: () => ({}),\n onSome: (contexts) => ({ contexts: kept(contexts) }),\n }),\n ),\n },\n questions: pipe(\n request.questions,\n Rec.filter((_question, id) => missing.includes(id)),\n ),\n };\n },\n);\n\nconst validFor =\n (request: DecisionRequest, id: string) =>\n ({ model, answer }: CachedAnswer): boolean =>\n isComplete({ model, answers: { [id]: answer } }, pipe(request, missingRequest([id])));\n\nconst readOne = Effect.fn(\"readOne\")(function* readOne(\n endpoint: string,\n request: DecisionRequest,\n id: string,\n) {\n const fs = yield* FileSystem.FileSystem;\n const file = yield* cacheFile(keyOf(endpoint, request, id));\n const text = yield* fs.readFileString(file).pipe(Effect.option);\n const cached: Option.Option<CachedAnswer> = pipe(\n text,\n Option.flatMap(decodeCached),\n Option.filter(validFor(request, id)),\n );\n return { id, file, cached } satisfies QuestionCache;\n});\n\n/** @internal */\nexport const readCache = Effect.fn(\"readCache\")(function* readCache(\n endpoint: string,\n request: DecisionRequest,\n) {\n return yield* Effect.forEach(\n Rec.keys(request.questions),\n (id) => readOne(endpoint, request, id),\n {\n concurrency: \"unbounded\",\n },\n );\n});\n\n/** @internal */\nexport const cachedAnswers = (\n entries: readonly QuestionCache[],\n): Readonly<Record<string, Answer>> =>\n Rec.fromEntries(\n pipe(\n entries,\n Arr.flatMap(({ id, cached }) =>\n pipe(\n cached,\n Option.map(({ answer }) => [id, answer] as const),\n Option.toArray,\n ),\n ),\n ),\n );\n\n/** @internal */\nexport const writeCache = Effect.fn(\"writeCache\")(function* writeCache(\n file: string,\n cached: CachedAnswer,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const now = yield* Clock.currentTimeMillis;\n const temp = `${file}.tmp-${String(now)}`;\n const json = yield* encodeJson(cached);\n yield* fs.makeDirectory(path.dirname(file), { recursive: true });\n yield* fs.writeFileString(temp, json);\n yield* fs.rename(temp, file);\n});\n\n/** @internal */\nexport type CacheServices = Digest.Digest | FileSystem.FileSystem | Path.Path;\n","import { layerDigest } from \"@effect/platform-node-shared/NodeCrypto\";\nimport { layer as fileSystem } from \"@effect/platform-node-shared/NodeFileSystem\";\nimport { layer as path } from \"@effect/platform-node-shared/NodePath\";\nimport { Layer } from \"effect\";\nimport { FetchHttpClient } from \"effect/http\";\nimport { OtlpSerialization, OtlpTracer } from \"effect/observability\";\n\nconst tracing = OtlpTracer.layerFromConfig({\n resource: { serviceName: \"oxlint-plugin-decision\" },\n}).pipe(Layer.provide(OtlpSerialization.layerJson), Layer.provide(FetchHttpClient.layer));\n\n/** @internal */\nexport const workerServices: [\n typeof fileSystem,\n typeof path,\n typeof layerDigest,\n typeof FetchHttpClient.layer,\n typeof tracing,\n] = [fileSystem, path, layerDigest, FetchHttpClient.layer, tracing];\n","import { Array as Arr, Effect, Option, pipe } from \"effect\";\nimport type { Config } from \"effect\";\nimport type { HttpClient } from \"effect/http\";\nimport { runAsWorker } from \"synckit\";\n\nimport { mergeResponses, messageOf } from \"#/entities/decision/index.ts\";\nimport type {\n DecideInput,\n DecideResult,\n DecisionRequest,\n DecisionResponse,\n WireRequest,\n} from \"#/entities/decision/index.ts\";\n\nimport type { AppServices } from \"./app-context.ts\";\nimport { cachedAnswers, isComplete, missingRequest, readCache, writeCache } from \"./cache.ts\";\nimport type { CacheServices, QuestionCache } from \"./cache.ts\";\nimport { workerServices } from \"./services.ts\";\n\n/** @internal */\nexport type Services = AppServices | CacheServices | HttpClient.HttpClient;\n\ntype Inputs = Arr.NonEmptyReadonlyArray<DecideInput>;\n\n/** @internal */\nexport interface Transport {\n readonly endpoint: (env: DecideInput[\"env\"]) => Config.Config<string>;\n readonly wires: (request: DecisionRequest) => Arr.NonEmptyReadonlyArray<WireRequest>;\n readonly send: (\n endpoint: string,\n wire: WireRequest,\n input: Pick<DecideInput, \"env\">,\n ) => Effect.Effect<DecisionResponse, Config.ConfigError | string, Services>;\n}\n\nconst ask = Effect.fn(\"ask\")(function* ask(\n transport: Transport,\n endpoint: string,\n { request, timeoutMs, env }: DecideInput,\n) {\n const responses = yield* Effect.forEach(\n transport.wires(request),\n (wire) => transport.send(endpoint, wire, { env }),\n { concurrency: \"unbounded\" },\n ).pipe(\n Effect.timeoutOrElse({\n duration: timeoutMs,\n orElse: () => Effect.fail(\"timeout\"),\n }),\n );\n return mergeResponses(responses);\n});\n\nconst store = Effect.fn(\"store\")(function* store(\n entries: readonly QuestionCache[],\n response: DecisionResponse,\n) {\n yield* Effect.forEach(\n entries,\n ({ id, file }: QuestionCache) =>\n Option.match(Option.fromUndefinedOr(response.answers[id]), {\n onNone: () => Effect.void,\n onSome: (answer) => writeCache(file, { model: response.model, answer }).pipe(Effect.ignore),\n }),\n { concurrency: \"unbounded\", discard: true },\n );\n});\n\nconst servedModel = (entries: readonly QuestionCache[]): Option.Option<string> =>\n pipe(\n entries,\n Arr.findFirst(({ cached }) => cached),\n Option.map(({ model }) => model),\n );\n\nconst idsOf = (entries: readonly QuestionCache[]): readonly string[] =>\n pipe(\n entries,\n Arr.map(({ id }) => id),\n );\n\nconst askMissing = Effect.fn(\"askMissing\")(function* askMissing(\n transport: Transport,\n { endpoint, entries }: Readonly<{ endpoint: string; entries: readonly QuestionCache[] }>,\n input: DecideInput,\n) {\n const missing = pipe(\n entries,\n Arr.filter(({ cached }) => Option.isNone(cached)),\n );\n yield* Effect.annotateCurrentSpan({ askedQuestions: missing.length });\n const request = pipe(input.request, missingRequest(idsOf(missing)));\n const asked = yield* ask(transport, endpoint, { ...input, request });\n const response = { model: asked.model, answers: { ...cachedAnswers(entries), ...asked.answers } };\n if (isComplete(response, input.request)) {\n yield* store(missing, asked);\n }\n return response;\n});\n\nconst decide = Effect.fn(\"decide\")(function* decide(transport: Transport, input: DecideInput) {\n yield* Effect.annotateCurrentSpan({ model: input.request.model });\n const endpoint = yield* transport.endpoint(input.env);\n const entries = yield* readCache(endpoint, input.request);\n const hit = pipe(\n entries,\n Arr.every(({ cached }) => Option.isSome(cached)),\n );\n yield* Effect.annotateCurrentSpan({ cached: hit });\n if (hit) {\n const model = Option.getOrElse(servedModel(entries), () => input.request.model);\n return { response: { model, answers: cachedAnswers(entries) }, cached: true };\n }\n return { response: yield* askMissing(transport, { endpoint, entries }, input), cached: false };\n});\n\nconst reasonOf = (error: unknown): string => {\n if (typeof error === \"string\") {\n return error;\n }\n return messageOf(error);\n};\n\nconst decideOne = (\n transport: Transport,\n input: DecideInput,\n): Effect.Effect<DecideResult, never, Services> =>\n decide(transport, input).pipe(\n Effect.match({\n onSuccess: ({ response, cached }): DecideResult => ({ ok: true, response, cached }),\n onFailure: (error): DecideResult => ({ ok: false, reason: reasonOf(error) }),\n }),\n );\n\nconst decideEach = (\n transport: Transport,\n inputs: Inputs,\n): Effect.Effect<Arr.NonEmptyReadonlyArray<DecideResult>> =>\n Effect.all(\n pipe(\n inputs,\n Arr.map((input) => decideOne(transport, input)),\n ),\n { concurrency: \"unbounded\" },\n ).pipe(Effect.provide(workerServices));\n\n/** @internal */\nexport const serveDecisions = (transport: Transport): void => {\n runAsWorker((inputs: Inputs): Promise<Arr.NonEmptyReadonlyArray<DecideResult>> =>\n Effect.runPromise(decideEach(transport, inputs)),\n );\n};\n"],"mappings":";;;;;;;;;;AAOA,MAAM,iBAAiB;AACvB,MAAM,mBAAmB;AACzB,MAAM,iBAAiB;AAEvB,MAAM,YAAY,OAAO,OAAO;CAC9B,OAAO,OAAO;CACd,SAAS,OAAO,OAAO,OAAO,QAAQ,YAAY;AACpD,CAAC;AAED,MAAM,WAAW,OAAO,OAAO,EAAE,QAAQ,UAAU,CAAC;AAEpD,MAAM,eAAe,OAAO,OAAO,EAAE,SAAS,OAAO,OAAO,CAAC;AAE7D,MAAM,YAAY,OAAO,MAAM,CAC7B,OAAO,OAAO,EAAE,QAAQ,OAAO,cAAc,YAAY,EAAE,CAAC,GAC5D,OAAO,OAAO,EAAE,QAAQ,aAAa,CAAC,CACxC,CAAC;AAED,MAAM,kBAAkB,OAAO,oBAAoB,SAAS;AAE5D,MAAM,iBAAiB,SACrB,OAAO,MAAM,gBAAgB,IAAI,GAAG;CAClC,cAAc;CACd,SAAS,YAAY;EACnB,IAAI,YAAY,SACd,OAAO,QAAQ,OAAO;EAExB,OAAO,KACL,QAAQ,QACRA,MAAI,KAAK,EAAE,cAAc,OAAO,GAChCA,MAAI,KAAK,IAAI,CACf;CACF;AACF,CAAC;AAEH,MAAM,aAAa,aACjB,SAAS,KAAK,KACZ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O,MAAM,CAAC,CACjD;CACA,OAAO,OAAO,oBAAoB,EAAE,QAAQ,IAAI,CAAC;CACjD,IAAI,KAEF,OAAO;EAAE,UAAU;GAAE,OADP,OAAO,UAAU,YAAY,OAAO,SAAS,MAAM,QAAQ,KAChD;GAAG,SAAS,cAAc,OAAO;EAAE;EAAG,QAAQ;CAAK;CAE9E,OAAO;EAAE,UAAU,OAAO,WAAW,WAAW;GAAE;GAAU;EAAQ,GAAG,KAAK;EAAG,QAAQ;CAAM;AAC/F,CAAC;AAED,MAAM,YAAY,UAA2B;CAC3C,IAAI,OAAO,UAAU,UACnB,OAAO;CAET,OAAO,UAAU,KAAK;AACxB;AAEA,MAAM,aACJ,WACA,UAEA,OAAO,WAAW,KAAK,CAAC,CAAC,KACvB,OAAO,MAAM;CACX,YAAY,EAAE,UAAU,cAA4B;EAAE,IAAI;EAAM;EAAU;CAAO;CACjF,YAAY,WAAyB;EAAE,IAAI;EAAO,QAAQ,SAAS,KAAK;CAAE;AAC5E,CAAC,CACH;AAEF,MAAM,cACJ,WACA,WAEA,OAAO,IACL,KACE,QACAA,MAAI,KAAK,UAAU,UAAU,WAAW,KAAK,CAAC,CAChD,GACA,EAAE,aAAa,YAAY,CAC7B,CAAC,CAAC,KAAK,OAAO,QAAQ,cAAc,CAAC;;AAGvC,MAAa,kBAAkB,cAA+B;CAC5D,aAAa,WACX,OAAO,WAAW,WAAW,WAAW,MAAM,CAAC,CACjD;AACF"}
1
+ {"version":3,"file":"serve-decisions-vZr4L2TM.mjs","names":["Arr","Rec","Fn","Arr","fileSystem","path","Arr"],"sources":["../src/features/serve-decisions/model/system-one.ts","../src/features/serve-decisions/model/cache.ts","../src/features/serve-decisions/model/services.ts","../src/features/serve-decisions/model/serve-decisions.ts"],"sourcesContent":["import { Array as Arr, Effect, Option, Schedule, Schema, pipe } from \"effect\";\nimport type { Redacted } from \"effect\";\nimport { HttpClient, HttpClientRequest, HttpClientResponse } from \"effect/http\";\n\nimport { AnswerSchema } from \"#/entities/decision/index.ts\";\nimport type { DecisionResponse, WireRequest } from \"#/entities/decision/index.ts\";\n\nconst FIRST_REDIRECT = 300;\nconst RETRY_INITIAL_MS = 10;\nconst RETRY_EXPONENT = 2;\n\nconst Decisions = Schema.Struct({\n model: Schema.String,\n answers: Schema.Record(Schema.String, AnswerSchema),\n});\n\nconst Envelope = Schema.Struct({ result: Decisions });\n\nconst ErrorMessage = Schema.Struct({ message: Schema.String });\n\nconst ErrorBody = Schema.Union([\n Schema.Struct({ errors: Schema.NonEmptyArray(ErrorMessage) }),\n Schema.Struct({ detail: ErrorMessage }),\n]);\n\nconst decodeErrorBody = Schema.decodeUnknownOption(ErrorBody);\n\nconst messageOfBody = (body: unknown): string =>\n Option.match(decodeErrorBody(body), {\n onNone: () => \"request failed\",\n onSome: (decoded) => {\n if (\"detail\" in decoded) {\n return decoded.detail.message;\n }\n return pipe(\n decoded.errors,\n Arr.map(({ message }) => message),\n Arr.join(\"; \"),\n );\n },\n });\n\nconst failureOf = (response: HttpClientResponse.HttpClientResponse): Effect.Effect<never, string> =>\n response.json.pipe(\n Effect.option,\n Effect.flatMap((body) =>\n Effect.fail(\n `http ${String(response.status)}: ${body.pipe(Option.getOrUndefined, messageOfBody)}`,\n ),\n ),\n );\n\n/** @internal */\nexport interface SystemOneCall {\n readonly url: string;\n readonly model: string;\n readonly token: Redacted.Redacted;\n readonly headers: Readonly<Record<string, string>>;\n readonly envelope: boolean;\n}\n\nconst decodeEnvelope = HttpClientResponse.schemaBodyJson(Envelope);\n\nconst decodeDecisions = HttpClientResponse.schemaBodyJson(Decisions);\n\nconst invalid = ({ message }: Readonly<{ message: string }>): string =>\n `invalid response: ${message}`;\n\nconst decisionsOf = (\n response: HttpClientResponse.HttpClientResponse,\n envelope: boolean,\n): Effect.Effect<typeof Decisions.Type, string> => {\n if (envelope) {\n return decodeEnvelope(response).pipe(\n Effect.mapBoth({ onSuccess: ({ result }) => result, onFailure: invalid }),\n );\n }\n return decodeDecisions(response).pipe(Effect.mapError(invalid));\n};\n\n/** @internal */\nexport const sendSystemOne = Effect.fn(\"sendSystemOne\")(function* sendSystemOne(\n call: SystemOneCall,\n wire: WireRequest,\n) {\n const client = (yield* HttpClient.HttpClient).pipe(\n HttpClient.retryTransient({\n retryOn: \"response-only\",\n schedule: Schedule.exponential(RETRY_INITIAL_MS, RETRY_EXPONENT),\n }),\n );\n const response = yield* HttpClientRequest.post(call.url).pipe(\n HttpClientRequest.bearerToken(call.token),\n HttpClientRequest.setHeaders(call.headers),\n HttpClientRequest.bodyJsonUnsafe({\n model: call.model,\n state: wire.state,\n questions: wire.questions,\n }),\n client.execute,\n Effect.mapError(({ message }) => `network: ${message}`),\n );\n if (response.status >= FIRST_REDIRECT) {\n return yield* failureOf(response);\n }\n const decisions = yield* decisionsOf(response, call.envelope);\n return { model: decisions.model, answers: decisions.answers } satisfies DecisionResponse;\n});\n","import {\n Array as Arr,\n Clock,\n Effect,\n FileSystem,\n Function as Fn,\n Option,\n Path,\n Record as Rec,\n Schema,\n pipe,\n} from \"effect\";\nimport { Digest } from \"effect/crypto\";\n\nimport { AnswerSchema, PREFIX, parseVerdicts, snippetRefOf } from \"#/entities/decision/index.ts\";\nimport type { Answer, DecisionRequest, DecisionResponse } from \"#/entities/decision/index.ts\";\n\nconst DATA_FIRST_ARITY = 2;\n\nconst CACHE_VERSION = 8;\n/** @internal */\nexport const CACHE_DIR = `node_modules/.cache/${PREFIX}`;\n\nconst encodeJson = (value: unknown): Effect.Effect<string> =>\n Schema.encodeUnknownEffect(Schema.fromJsonString(Schema.Unknown))(value).pipe(Effect.orDie);\n\nconst contextOf = (request: DecisionRequest, ref: string): Option.Option<string> =>\n pipe(Option.fromUndefinedOr(request.state.contexts), Option.flatMap(Rec.get(ref)));\n\nconst keyOf = (endpoint: string, request: DecisionRequest, id: string): unknown => {\n const ref = snippetRefOf(id);\n return {\n version: CACHE_VERSION,\n endpoint,\n model: request.model,\n snippet: request.state.snippets[ref],\n context: Option.getOrNull(contextOf(request, ref)),\n question: request.questions[id],\n };\n};\n\nconst cacheFile = Effect.fn(\"cacheFile\")(function* cacheFile(key: unknown) {\n const digest = yield* Digest.Digest;\n const path = yield* Path.Path;\n const json = yield* encodeJson(key);\n const hash = yield* digest.digestHex(Digest.sha256, new TextEncoder().encode(json));\n return path.resolve(CACHE_DIR, `${hash}.json`);\n});\n\nconst CachedAnswerSchema = Schema.Struct({ model: Schema.NonEmptyString, answer: AnswerSchema });\n\n/** @internal */\nexport interface CachedAnswer {\n readonly model: string;\n readonly answer: Answer;\n}\n\nconst decodeCached = Schema.decodeOption(Schema.fromJsonString(CachedAnswerSchema));\n\n/** @internal */\nexport interface QuestionCache {\n readonly id: string;\n readonly file: string;\n readonly cached: Option.Option<CachedAnswer>;\n}\n\n/** @internal */\nexport const isComplete: {\n (request: DecisionRequest): (response: DecisionResponse) => boolean;\n (response: DecisionResponse, request: DecisionRequest): boolean;\n} = Fn.dual(DATA_FIRST_ARITY, (response: DecisionResponse, request: DecisionRequest): boolean =>\n Option.liftThrowable(() => parseVerdicts(response, request).complete)().pipe(\n Option.getOrElse(() => false),\n ),\n);\n\nconst keptFor =\n (refs: readonly string[]) =>\n <Value>(record: Readonly<Record<string, Value>>): Record<string, Value> =>\n pipe(\n record,\n Rec.filter((_value, ref) => refs.includes(ref)),\n );\n\n/** @internal */\nexport const missingRequest: {\n (missing: readonly string[]): (request: DecisionRequest) => DecisionRequest;\n (request: DecisionRequest, missing: readonly string[]): DecisionRequest;\n} = Fn.dual(\n DATA_FIRST_ARITY,\n (request: DecisionRequest, missing: readonly string[]): DecisionRequest => {\n const refs = pipe(missing, Arr.map(snippetRefOf));\n const kept = keptFor(refs);\n return {\n ...request,\n state: {\n ...request.state,\n snippets: kept(request.state.snippets),\n ...pipe(\n Option.fromUndefinedOr(request.state.contexts),\n Option.match({\n onNone: () => ({}),\n onSome: (contexts) => ({ contexts: kept(contexts) }),\n }),\n ),\n },\n questions: pipe(\n request.questions,\n Rec.filter((_question, id) => missing.includes(id)),\n ),\n };\n },\n);\n\nconst validFor =\n (request: DecisionRequest, id: string) =>\n ({ model, answer }: CachedAnswer): boolean =>\n isComplete({ model, answers: { [id]: answer } }, pipe(request, missingRequest([id])));\n\nconst readOne = Effect.fn(\"readOne\")(function* readOne(\n endpoint: string,\n request: DecisionRequest,\n id: string,\n) {\n const fs = yield* FileSystem.FileSystem;\n const file = yield* cacheFile(keyOf(endpoint, request, id));\n const text = yield* fs.readFileString(file).pipe(Effect.option);\n const cached: Option.Option<CachedAnswer> = pipe(\n text,\n Option.flatMap(decodeCached),\n Option.filter(validFor(request, id)),\n );\n return { id, file, cached } satisfies QuestionCache;\n});\n\n/** @internal */\nexport const readCache = Effect.fn(\"readCache\")(function* readCache(\n endpoint: string,\n request: DecisionRequest,\n) {\n return yield* Effect.forEach(\n Rec.keys(request.questions),\n (id) => readOne(endpoint, request, id),\n {\n concurrency: \"unbounded\",\n },\n );\n});\n\n/** @internal */\nexport const cachedAnswers = (\n entries: readonly QuestionCache[],\n): Readonly<Record<string, Answer>> =>\n Rec.fromEntries(\n pipe(\n entries,\n Arr.flatMap(({ id, cached }) =>\n pipe(\n cached,\n Option.map(({ answer }) => [id, answer] as const),\n Option.toArray,\n ),\n ),\n ),\n );\n\n/** @internal */\nexport const writeCache = Effect.fn(\"writeCache\")(function* writeCache(\n file: string,\n cached: CachedAnswer,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const now = yield* Clock.currentTimeMillis;\n const temp = `${file}.tmp-${String(now)}`;\n const json = yield* encodeJson(cached);\n yield* fs.makeDirectory(path.dirname(file), { recursive: true });\n yield* fs.writeFileString(temp, json);\n yield* fs.rename(temp, file);\n});\n\n/** @internal */\nexport type CacheServices = Digest.Digest | FileSystem.FileSystem | Path.Path;\n","import { layerDigest } from \"@effect/platform-node-shared/NodeCrypto\";\nimport { layer as fileSystem } from \"@effect/platform-node-shared/NodeFileSystem\";\nimport { layer as path } from \"@effect/platform-node-shared/NodePath\";\nimport { Layer } from \"effect\";\nimport { FetchHttpClient } from \"effect/http\";\nimport { OtlpSerialization, OtlpTracer } from \"effect/observability\";\n\nconst tracing = OtlpTracer.layerFromConfig({\n resource: { serviceName: \"oxlint-plugin-decision\" },\n}).pipe(Layer.provide(OtlpSerialization.layerJson), Layer.provide(FetchHttpClient.layer));\n\n/** @internal */\nexport const workerServices: [\n typeof fileSystem,\n typeof path,\n typeof layerDigest,\n typeof FetchHttpClient.layer,\n typeof tracing,\n] = [fileSystem, path, layerDigest, FetchHttpClient.layer, tracing];\n","import { Array as Arr, Effect, Option, pipe } from \"effect\";\nimport type { Config } from \"effect\";\nimport type { HttpClient } from \"effect/http\";\nimport { runAsWorker } from \"synckit\";\n\nimport { mergeResponses, messageOf } from \"#/entities/decision/index.ts\";\nimport type {\n DecideInput,\n DecideResult,\n DecisionRequest,\n DecisionResponse,\n WireRequest,\n} from \"#/entities/decision/index.ts\";\n\nimport type { AppServices } from \"./app-context.ts\";\nimport { cachedAnswers, isComplete, missingRequest, readCache, writeCache } from \"./cache.ts\";\nimport type { CacheServices, QuestionCache } from \"./cache.ts\";\nimport { workerServices } from \"./services.ts\";\n\n/** @internal */\nexport type Services = AppServices | CacheServices | HttpClient.HttpClient;\n\ntype Inputs = Arr.NonEmptyReadonlyArray<DecideInput>;\n\n/** @internal */\nexport interface Transport {\n readonly endpoint: (env: DecideInput[\"env\"]) => Config.Config<string>;\n readonly wires: (request: DecisionRequest) => Arr.NonEmptyReadonlyArray<WireRequest>;\n readonly send: (\n endpoint: string,\n wire: WireRequest,\n input: Pick<DecideInput, \"env\">,\n ) => Effect.Effect<DecisionResponse, Config.ConfigError | string, Services>;\n}\n\nconst ask = Effect.fn(\"ask\")(function* ask(\n transport: Transport,\n endpoint: string,\n { request, timeoutMs, env }: DecideInput,\n) {\n const responses = yield* Effect.forEach(\n transport.wires(request),\n (wire) => transport.send(endpoint, wire, { env }),\n { concurrency: \"unbounded\" },\n ).pipe(\n Effect.timeoutOrElse({\n duration: timeoutMs,\n orElse: () => Effect.fail(\"timeout\"),\n }),\n );\n return mergeResponses(responses);\n});\n\nconst store = Effect.fn(\"store\")(function* store(\n entries: readonly QuestionCache[],\n response: DecisionResponse,\n) {\n yield* Effect.forEach(\n entries,\n ({ id, file }: QuestionCache) =>\n Option.match(Option.fromUndefinedOr(response.answers[id]), {\n onNone: () => Effect.void,\n onSome: (answer) => writeCache(file, { model: response.model, answer }).pipe(Effect.ignore),\n }),\n { concurrency: \"unbounded\", discard: true },\n );\n});\n\nconst servedModel = (entries: readonly QuestionCache[]): Option.Option<string> =>\n pipe(\n entries,\n Arr.findFirst(({ cached }) => cached),\n Option.map(({ model }) => model),\n );\n\nconst idsOf = (entries: readonly QuestionCache[]): readonly string[] =>\n pipe(\n entries,\n Arr.map(({ id }) => id),\n );\n\nconst askMissing = Effect.fn(\"askMissing\")(function* askMissing(\n transport: Transport,\n { endpoint, entries }: Readonly<{ endpoint: string; entries: readonly QuestionCache[] }>,\n input: DecideInput,\n) {\n const missing = pipe(\n entries,\n Arr.filter(({ cached }) => Option.isNone(cached)),\n );\n yield* Effect.annotateCurrentSpan({ askedQuestions: missing.length });\n const request = pipe(input.request, missingRequest(idsOf(missing)));\n const asked = yield* ask(transport, endpoint, { ...input, request });\n const response = { model: asked.model, answers: { ...cachedAnswers(entries), ...asked.answers } };\n if (isComplete(response, input.request)) {\n yield* store(missing, asked);\n }\n return response;\n});\n\nconst decide = Effect.fn(\"decide\")(function* decide(transport: Transport, input: DecideInput) {\n yield* Effect.annotateCurrentSpan({ model: input.request.model });\n const endpoint = yield* transport.endpoint(input.env);\n const entries = yield* readCache(endpoint, input.request);\n const hit = pipe(\n entries,\n Arr.every(({ cached }) => Option.isSome(cached)),\n );\n yield* Effect.annotateCurrentSpan({ cached: hit });\n if (hit) {\n const model = Option.getOrElse(servedModel(entries), () => input.request.model);\n return { response: { model, answers: cachedAnswers(entries) }, cached: true };\n }\n return { response: yield* askMissing(transport, { endpoint, entries }, input), cached: false };\n});\n\nconst reasonOf = (error: unknown): string => {\n if (typeof error === \"string\") {\n return error;\n }\n return messageOf(error);\n};\n\nconst decideOne = (\n transport: Transport,\n input: DecideInput,\n): Effect.Effect<DecideResult, never, Services> =>\n decide(transport, input).pipe(\n Effect.match({\n onSuccess: ({ response, cached }): DecideResult => ({ ok: true, response, cached }),\n onFailure: (error): DecideResult => ({ ok: false, reason: reasonOf(error) }),\n }),\n );\n\nconst decideEach = (\n transport: Transport,\n inputs: Inputs,\n): Effect.Effect<Arr.NonEmptyReadonlyArray<DecideResult>> =>\n Effect.all(\n pipe(\n inputs,\n Arr.map((input) => decideOne(transport, input)),\n ),\n { concurrency: \"unbounded\" },\n ).pipe(Effect.provide(workerServices));\n\n/** @internal */\nexport const serveDecisions = (transport: Transport): void => {\n runAsWorker((inputs: Inputs): Promise<Arr.NonEmptyReadonlyArray<DecideResult>> =>\n Effect.runPromise(decideEach(transport, inputs)),\n );\n};\n"],"mappings":";;;;;;;;;;AAOA,MAAM,iBAAiB;AACvB,MAAM,mBAAmB;AACzB,MAAM,iBAAiB;AAEvB,MAAM,YAAY,OAAO,OAAO;CAC9B,OAAO,OAAO;CACd,SAAS,OAAO,OAAO,OAAO,QAAQ,YAAY;AACpD,CAAC;AAED,MAAM,WAAW,OAAO,OAAO,EAAE,QAAQ,UAAU,CAAC;AAEpD,MAAM,eAAe,OAAO,OAAO,EAAE,SAAS,OAAO,OAAO,CAAC;AAE7D,MAAM,YAAY,OAAO,MAAM,CAC7B,OAAO,OAAO,EAAE,QAAQ,OAAO,cAAc,YAAY,EAAE,CAAC,GAC5D,OAAO,OAAO,EAAE,QAAQ,aAAa,CAAC,CACxC,CAAC;AAED,MAAM,kBAAkB,OAAO,oBAAoB,SAAS;AAE5D,MAAM,iBAAiB,SACrB,OAAO,MAAM,gBAAgB,IAAI,GAAG;CAClC,cAAc;CACd,SAAS,YAAY;EACnB,IAAI,YAAY,SACd,OAAO,QAAQ,OAAO;EAExB,OAAO,KACL,QAAQ,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MAAM,GAAG;CACpD,MAAM,UAAU,OAAO,UAAU,UAAU,MAAM,OAAO;CACxD,MAAM,MAAM,KACV,SACAA,MAAI,OAAO,EAAE,aAAa,OAAO,OAAO,MAAM,CAAC,CACjD;CACA,OAAO,OAAO,oBAAoB,EAAE,QAAQ,IAAI,CAAC;CACjD,IAAI,KAEF,OAAO;EAAE,UAAU;GAAE,OADP,OAAO,UAAU,YAAY,OAAO,SAAS,MAAM,QAAQ,KAChD;GAAG,SAAS,cAAc,OAAO;EAAE;EAAG,QAAQ;CAAK;CAE9E,OAAO;EAAE,UAAU,OAAO,WAAW,WAAW;GAAE;GAAU;EAAQ,GAAG,KAAK;EAAG,QAAQ;CAAM;AAC/F,CAAC;AAED,MAAM,YAAY,UAA2B;CAC3C,IAAI,OAAO,UAAU,UACnB,OAAO;CAET,OAAO,UAAU,KAAK;AACxB;AAEA,MAAM,aACJ,WACA,UAEA,OAAO,WAAW,KAAK,CAAC,CAAC,KACvB,OAAO,MAAM;CACX,YAAY,EAAE,UAAU,cAA4B;EAAE,IAAI;EAAM;EAAU;CAAO;CACjF,YAAY,WAAyB;EAAE,IAAI;EAAO,QAAQ,SAAS,KAAK;CAAE;AAC5E,CAAC,CACH;AAEF,MAAM,cACJ,WACA,WAEA,OAAO,IACL,KACE,QACAA,MAAI,KAAK,UAAU,UAAU,WAAW,KAAK,CAAC,CAChD,GACA,EAAE,aAAa,YAAY,CAC7B,CAAC,CAAC,KAAK,OAAO,QAAQ,cAAc,CAAC;;AAGvC,MAAa,kBAAkB,cAA+B;CAC5D,aAAa,WACX,OAAO,WAAW,WAAW,WAAW,MAAM,CAAC,CACjD;AACF"}
@@ -1,5 +1,5 @@
1
- import { a as envNameOf, t as fileRequestsFor } from "./wire-CKpt_MBX.mjs";
2
- import { n as sendSystemOne, t as serveDecisions } from "./serve-decisions-D6M-l2uy.mjs";
1
+ import { a as envNameOf, t as fileRequestsFor } from "./wire-D0YSbfBG.mjs";
2
+ import { n as sendSystemOne, t as serveDecisions } from "./serve-decisions-vZr4L2TM.mjs";
3
3
  import { Config, Effect, String } from "effect";
4
4
  // src/features/serve-decisions/model/typesafe.ts
5
5
  const DEFAULT_BASE_URL = "https://api.typesafe.ai";
@@ -386,6 +386,7 @@ const runOrElse = Function.dual(DATA_FIRST_ARITY, (effect, fallback) => Exit.mat
386
386
  }));
387
387
  const envOf = (name) => runOrElse(Config.option(Config.NonEmptyString(name)), () => Option.none()).pipe(Option.map((value) => String$1.trim(value)), Option.filter(String$1.isNonEmpty));
388
388
  const envNameOf = Function.dual(DATA_FIRST_ARITY, (env, name) => env[name] ?? name);
389
+ const missingEnvOf = Function.dual(DATA_FIRST_ARITY, (env, provider) => pipe(provider.requiredEnv, Array.map((name) => envNameOf(env, name)), Array.filter((name) => Option.isNone(envOf(name)))));
389
390
  const failsInCi = (options) => options.ci === "fail" && Option.isSome(envOf("CI"));
390
391
  const warned = /* @__PURE__ */ new Set();
391
392
  const warnOnce = Function.dual(DATA_FIRST_ARITY, (reason, message) => {
@@ -433,6 +434,6 @@ const mergeResponses = (responses) => ({
433
434
  model: Array.headNonEmpty(responses).model,
434
435
  answers: pipe(responses, Array.flatMap(({ answers }) => Record.toEntries(answers)), Record.fromEntries)
435
436
  });
436
- export { EVERY_LINE as A, checked as C, resolveOptions as D, resolveModel as E, selectedLocation as F, sourceLines as I, AnswerSchema as L, locationCandidates as M, locationOfLine as N, CLEF_MODEL as O, locationQuestion as P, isReported as R, checkRules as S, optionsError as T, snippetRefOf as _, envNameOf as a, PREFIX as b, messageOf as c, toJson as d, warnOnce as f, refAt as g, parseVerdicts as h, captured as i, locates as j, JEV_MODEL as k, nowMs as l, locationRefOf as m, mergeResponses as n, envOf as o, buildRequest as p, snippetRequestsFor as r, failsInCi as s, fileRequestsFor as t, runOrElse as u, truncateSnippet as v, modelIdsOf as w, STRICT as x, ModelSpecSchema as y };
437
+ export { JEV_MODEL as A, isReported as B, checkRules as C, resolveModel as D, optionsError as E, locationQuestion as F, selectedLocation as I, sourceLines as L, locates as M, locationCandidates as N, resolveOptions as O, locationOfLine as P, AnswerSchema as R, STRICT as S, modelIdsOf as T, refAt as _, envNameOf as a, ModelSpecSchema as b, messageOf as c, runOrElse as d, toJson as f, parseVerdicts as g, locationRefOf as h, captured as i, EVERY_LINE as j, CLEF_MODEL as k, missingEnvOf as l, buildRequest as m, mergeResponses as n, envOf as o, warnOnce as p, snippetRequestsFor as r, failsInCi as s, fileRequestsFor as t, nowMs as u, snippetRefOf as v, checked as w, PREFIX as x, truncateSnippet as y, BOOLEAN_ANSWER as z };
437
438
 
438
- //# sourceMappingURL=wire-CKpt_MBX.mjs.map
439
+ //# sourceMappingURL=wire-D0YSbfBG.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wire-D0YSbfBG.mjs","names":["Arr","Rec","DATA_FIRST_ARITY","Rec","Fn","DATA_FIRST_ARITY","DATA_FIRST_ARITY_3","FIRST_LINE","Str","Num","Bool","Arr","Fn","Rec","DATA_FIRST_ARITY","Arr","Str","Fn","Rec","DATA_FIRST_ARITY","Bool","Str","Num","Fn","Arr","Rec","Fn","Str","Arr","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/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 { 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 Array as Arr,\n Cause,\n DateTime,\n Config,\n Console,\n Effect,\n Exit,\n Option,\n Schema,\n String as Str,\n pipe,\n Function as Fn,\n} from \"effect\";\n\nimport { PREFIX } from \"./options.ts\";\nimport type { DecisionProvider, 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 missingEnvOf: {\n (provider: DecisionProvider): (env: Readonly<Record<string, string>>) => readonly string[];\n (env: Readonly<Record<string, string>>, provider: DecisionProvider): readonly string[];\n} = Fn.dual(\n DATA_FIRST_ARITY,\n (env: Readonly<Record<string, string>>, provider: DecisionProvider): readonly string[] =>\n pipe(\n provider.requiredEnv,\n Arr.map((name) => envNameOf(env, name)),\n Arr.filter((name) => Option.isNone(envOf(name))),\n ),\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,MAAM,gBAAgB,OAAO,OAAO,E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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"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@r_masseater/oxlint-plugin-decision",
3
- "version": "0.8.3",
3
+ "version": "0.9.1",
4
4
  "description": "Oxlint JS plugin that lints code with plain-English rules answered by decision models: Clef on Workers AI or Jev on the Typesafe System One API.",
5
5
  "keywords": [
6
6
  "ai-gateway",
@@ -68,14 +68,14 @@
68
68
  "synckit": "^0.12.3"
69
69
  },
70
70
  "devDependencies": {
71
- "@effect/platform-node": "4.1.5",
72
- "@effect/platform-node-shared": "4.1.5",
71
+ "@effect/platform-node": "4.1.7",
72
+ "@effect/platform-node-shared": "4.1.7",
73
73
  "@effect/tsgo": "0.73.7",
74
- "@effect/vitest": "4.1.5",
74
+ "@effect/vitest": "4.1.7",
75
75
  "@masseater.dev/lint-host": "0.0.0",
76
76
  "@oxlint/plugins": "1.95.0",
77
- "@types/node": "26.6.10",
78
- "effect": "4.1.5",
77
+ "@types/node": "26.6.11",
78
+ "effect": "4.1.7",
79
79
  "oxlint": "1.95.0",
80
80
  "vite-plus": "1.8.0"
81
81
  },