@r_masseater/oxlint-plugin-decision 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,18 +1,25 @@
1
- import { A as resolveOptions, C as REPORT_LOC, D as checked, E as checkRules, N as isReported, O as modelIdsOf, S as PREFIX, T as TARGET_NODE_TYPES, _ as messageOf, a as locationCandidates, b as ModelSpecSchema, c as locationRefOf, d as selectedLocation, f as sourceLines, g as failsInCi, h as envOf, i as locates, j as snippetNodeFor, k as resolveModel, l as parseVerdicts, m as envNameOf, n as wireRequestsFor, o as locationOfLine, p as truncateSnippet, r as buildRequest, s as locationQuestion, u as refAt, v as runOrElse, w as STRICT, x as OptionsError, y as warnOnce } from "./wire-XOgoBBuu.mjs";
2
- import { Array, Boolean, Console, Effect, Function, Match, Option, Predicate, Schema, String as String$1, pipe } from "effect";
1
+ import { S as isReported, _ as resolveModel, a as messageOf, c as toJson, d as PREFIX, f as STRICT, g as optionsError, h as modelIdsOf, i as failsInCi, l as warnOnce, m as checked, n as envNameOf, o as nowMs, p as checkRules, r as envOf, s as runOrElse, u as ModelSpecSchema, v as resolveOptions } from "./runtime-CICpEidL.mjs";
2
+ import { a as buildRequest, c as refAt, d as locates, f as locationCandidates, g as sourceLines, h as selectedLocation, i as yesNoRequestsFor, l as truncateSnippet, m as locationQuestion, o as locationRefOf, p as locationOfLine, r as wireRequestsFor, s as parseVerdicts, u as EVERY_LINE } from "./wire-BbVK3Q_K.mjs";
3
+ import { Array, Boolean, Console, Effect, Function, Match, Option, Predicate, Record, Schema, String as String$1, Struct, pipe } from "effect";
3
4
  import { createSyncFn } from "synckit";
4
5
  // src/define.ts
5
6
  const defineDecisionRule = (rule) => rule;
6
7
  const defineProvider = (provider) => provider;
7
- // src/openrouter.ts
8
+ // src/sync-provider.ts
8
9
  const BACKSTOP_MS = 6e4;
9
10
  const SYNCKIT_TIMEOUT = "Internal error: Atomics.wait() failed: timed-out";
11
+ const BUILT_EXTENSION = ".mjs";
12
+ const MODULE_EXTENSION = /\.[cm]?[jt]s$/u;
10
13
  const workers = /* @__PURE__ */ new Map();
11
- const workerCall = () => {
12
- const existing = workers.get("openrouter");
13
- if (existing) return existing;
14
- const created = createSyncFn(new URL("openrouter-worker.mjs", import.meta.url), { timeout: BACKSTOP_MS });
15
- workers.set("openrouter", created);
14
+ const workerUrl = (worker) => {
15
+ const extension = pipe(String$1.match(MODULE_EXTENSION)(import.meta.url), Option.flatMap(Array.head), Option.getOrElse(() => BUILT_EXTENSION));
16
+ return new URL(`${worker}${extension}`, import.meta.url);
17
+ };
18
+ const workerCall = (worker) => {
19
+ const existing = workers.get(worker);
20
+ if (Predicate.isNotUndefined(existing)) return existing;
21
+ const created = createSyncFn(workerUrl(worker), { timeout: BACKSTOP_MS });
22
+ workers.set(worker, created);
16
23
  return created;
17
24
  };
18
25
  const reasonOf = (error) => {
@@ -20,20 +27,33 @@ const reasonOf = (error) => {
20
27
  if (message === SYNCKIT_TIMEOUT) return "timeout";
21
28
  return `network: ${message}`;
22
29
  };
23
- const ask = (inputs) => runOrElse(Effect.sync(() => workerCall()(inputs)), (cause) => pipe(inputs, Array.map(() => ({
30
+ const askWorker = (worker, inputs) => runOrElse(Effect.sync(() => workerCall(worker)(inputs)), (cause) => pipe(inputs, Array.map(() => ({
24
31
  ok: false,
25
32
  reason: reasonOf(cause)
26
33
  }))));
27
- const openRouter = {
28
- name: "openrouter",
29
- requiredEnv: ["OPENROUTER_API_KEY"],
30
- decide: (input) => Array.headNonEmpty(ask([input])),
34
+ const syncProvider = ({ worker, ...provider }) => ({
35
+ ...provider,
36
+ decide: (input) => Array.headNonEmpty(askWorker(worker, [input])),
31
37
  decideAll: (inputs) => Array.match(inputs, {
32
38
  onEmpty: () => [],
33
- onNonEmpty: (some) => ask(some)
39
+ onNonEmpty: (some) => askWorker(worker, some)
34
40
  })
35
- };
41
+ });
42
+ // src/cloudflare.ts
43
+ const cloudflare = syncProvider({
44
+ name: "cloudflare",
45
+ worker: "cloudflare-worker",
46
+ requiredEnv: ["CLOUDFLARE_API_TOKEN", "CLOUDFLARE_ACCOUNT_ID"],
47
+ yesNo: true
48
+ });
49
+ // src/openrouter.ts
50
+ const openRouter = syncProvider({
51
+ name: "openrouter",
52
+ worker: "openrouter-worker",
53
+ requiredEnv: ["OPENROUTER_API_KEY"]
54
+ });
36
55
  // src/override.ts
56
+ const DATA_FIRST_ARITY_3$3 = 3;
37
57
  const RuleOverrideSchema = Schema.Struct({ model: Schema.optionalKey(ModelSpecSchema) });
38
58
  const RULE_OPTIONS_SCHEMA = [{
39
59
  type: "object",
@@ -51,18 +71,66 @@ const RULE_OPTIONS_SCHEMA = [{
51
71
  }] } }
52
72
  }];
53
73
  const decodeOverride = Schema.decodeUnknownResult(RuleOverrideSchema, STRICT);
54
- const overrideRule = (rule, raw, providers) => {
74
+ const overrideRule = Function.dual(DATA_FIRST_ARITY_3$3, (rule, raw, providers) => {
55
75
  if (Predicate.isUndefined(raw)) return rule;
56
76
  const { model } = checked(decodeOverride, raw, `options for rule "${rule.id}"`);
57
77
  return {
58
78
  ...rule,
59
79
  models: Option.match(Option.fromUndefinedOr(model), {
60
80
  onNone: () => rule.models,
61
- onSome: (spec) => modelIdsOf(spec).map((id) => resolveModel(id, providers))
81
+ onSome: (spec) => pipe(modelIdsOf(spec), Array.map((id) => resolveModel(id, providers)))
62
82
  })
63
83
  };
84
+ });
85
+ // src/nodes.ts
86
+ const FIRST_LINE$1 = 1;
87
+ const FIRST_COLUMN = 0;
88
+ const TARGET_NODE_TYPES = {
89
+ function: [
90
+ "FunctionDeclaration",
91
+ "FunctionExpression",
92
+ "ArrowFunctionExpression"
93
+ ],
94
+ call: ["CallExpression"],
95
+ jsx: ["JSXElement"],
96
+ file: ["Program"]
97
+ };
98
+ const NAMED_PARENTS = {
99
+ VariableDeclarator: "init",
100
+ Property: "value",
101
+ MethodDefinition: "value",
102
+ PropertyDefinition: "value"
103
+ };
104
+ const NAMED_PARENT_TYPES = new Set(Record.keys(NAMED_PARENTS));
105
+ const isNamedParentType = (type) => NAMED_PARENT_TYPES.has(type);
106
+ const ANONYMOUS_FUNCTIONS = /* @__PURE__ */ new Set(["FunctionExpression", "ArrowFunctionExpression"]);
107
+ const holdsAsName = (parent, node) => {
108
+ if (!isNamedParentType(parent.type)) return false;
109
+ const field = NAMED_PARENTS[parent.type];
110
+ return ANONYMOUS_FUNCTIONS.has(node.type) && parent[field] === node;
111
+ };
112
+ const snippetNodeFor = (node) => Option.fromNullishOr(node.parent).pipe(Option.filter((parent) => holdsAsName(parent, node)), Option.getOrElse(() => node));
113
+ const headOf = (text, line, column) => {
114
+ const [first] = String$1.split(text, "\n");
115
+ return {
116
+ start: {
117
+ line,
118
+ column
119
+ },
120
+ end: {
121
+ line,
122
+ column: column + first.length
123
+ }
124
+ };
125
+ };
126
+ const REPORT_LOC = {
127
+ function: (node, text) => headOf(text, node.loc.start.line, node.loc.start.column),
128
+ call: (node) => node.loc,
129
+ jsx: (node) => Option.getOrElse(Option.fromNullishOr(node.openingElement), () => node).loc,
130
+ file: (_node, text) => headOf(text, FIRST_LINE$1, FIRST_COLUMN)
64
131
  };
65
132
  // src/context.ts
133
+ const DATA_FIRST_ARITY_3$2 = 3;
66
134
  const DEFAULT_LINES = 5;
67
135
  const FIRST_LINE = 1;
68
136
  const LAST = 1;
@@ -89,7 +157,7 @@ const linesAround = (context, node, { before = DEFAULT_LINES, after = DEFAULT_LI
89
157
  const lines = sourceLines(context.sourceCode.text);
90
158
  const first = Math.max(FIRST_LINE, node.loc.start.line - before);
91
159
  const last = Math.min(lines.length, node.loc.end.line + after);
92
- return lines.slice(first - FIRST_LINE, last).map((text, index) => `L${String(first + index)}| ${text}`).join("\n");
160
+ return pipe(lines, Array.drop(first - FIRST_LINE), Array.take(last - first + FIRST_LINE), Array.map((text, index) => `L${String(first + index)}| ${text}`), Array.join("\n"));
93
161
  };
94
162
  const DECLARING_PARENTS = /* @__PURE__ */ new Set([
95
163
  "VariableDeclaration",
@@ -103,7 +171,7 @@ const declarationOf = (node) => Option.fromNullishOr(node.parent).pipe(Option.fi
103
171
  const leadingOf = (text, comments, until) => Option.match(Array.last(comments), {
104
172
  onNone: () => [],
105
173
  onSome: (last) => {
106
- if (String$1.isNonEmpty(text.slice(last.end, until).trim())) return [];
174
+ if (String$1.isNonEmpty(String$1.trim(String$1.slice(last.end, until)(text)))) return [];
107
175
  return [...leadingOf(text, Array.dropRight(comments, LAST), last.start), last];
108
176
  }
109
177
  });
@@ -111,31 +179,74 @@ const commentedTextOf = (context, node) => {
111
179
  const { text } = context.sourceCode;
112
180
  const named = snippetNodeFor(node);
113
181
  const [start] = declarationOf(named).range;
114
- const before = context.sourceCode.getAllComments().filter((comment) => comment.type !== "Shebang" && comment.end <= start);
182
+ const before = pipe(context.sourceCode.getAllComments(), Array.filter((comment) => comment.type !== "Shebang" && comment.end <= start));
115
183
  return Array.match(leadingOf(text, before, start), {
116
184
  onEmpty: () => Option.none(),
117
- onNonEmpty: ([first]) => Option.some(text.slice(first.start, named.range[END]))
185
+ onNonEmpty: ([first]) => Option.some(String$1.slice(first.start, named.range[END])(text))
118
186
  });
119
187
  };
120
188
  const isCommented = ({ context: wanted }) => Predicate.isNotUndefined(wanted) && wanted.scope === "comment";
121
- const commentedSnippetOf = (context, node, rule) => Option.flatMap(Option.liftPredicate(rule, isCommented), () => commentedTextOf(context, node));
122
- const lacksComment = (context, node, rule) => isCommented(rule) && Option.isNone(commentedTextOf(context, node));
123
- const contextOf = (context, node, rule) => {
189
+ const commentedSnippetOf = Function.dual(DATA_FIRST_ARITY_3$2, (context, node, rule) => Option.flatMap(Option.liftPredicate(rule, isCommented), () => commentedTextOf(context, node)));
190
+ const lacksComment = Function.dual(DATA_FIRST_ARITY_3$2, (context, node, rule) => isCommented(rule) && Option.isNone(commentedTextOf(context, node)));
191
+ const contextOf = Function.dual(DATA_FIRST_ARITY_3$2, (context, node, rule) => {
124
192
  if (rule.scope === "lines") return Option.some(linesAround(context, node, rule));
125
193
  if (rule.scope === "enclosing") return Option.some(enclosingText(context, node, rule.kind));
126
194
  return Option.liftPredicate(context.sourceCode.text, () => rule.scope === "file");
127
- };
195
+ });
128
196
  // src/name.ts
197
+ const DATA_FIRST_ARITY_3$1 = 3;
129
198
  const heldName = (node) => Option.flatMap(Option.fromNullishOr(node.parent), (parent) => Match.value(parent).pipe(Match.when({ type: "VariableDeclarator" }, (holder) => Option.liftPredicate(holder.id, () => holder.init === node)), Match.when({ type: Match.is("Property", "MethodDefinition", "PropertyDefinition") }, (holder) => Option.liftPredicate(holder.key, () => holder.value === node)), Match.orElse(() => Option.none())));
130
199
  const nameNodeOf = (node) => Match.value(node).pipe(Match.when({ type: Match.is("FunctionDeclaration", "FunctionExpression") }, (fn) => Option.orElse(Option.fromNullishOr(fn.id), () => heldName(fn))), Match.when({ type: "ArrowFunctionExpression" }, heldName), Match.when({ type: Match.is("CallExpression", "NewExpression") }, (call) => Option.some(call.callee)), Match.when({ type: "JSXElement" }, (element) => Option.some(element.openingElement.name)), Match.orElse(() => Option.none()));
131
- const nameOf = (node, context) => Option.getOrUndefined(Option.map(nameNodeOf(node), (name) => context.sourceCode.text.slice(name.start, name.end)));
132
- const isSelected = (context, node, { select }) => Option.match(Option.fromUndefinedOr(select), {
200
+ const nameOf = (node, context) => Option.getOrUndefined(Option.map(nameNodeOf(node), (name) => String$1.slice(name.start, name.end)(context.sourceCode.text)));
201
+ const isSelected = Function.dual(DATA_FIRST_ARITY_3$1, (context, node, { select }) => Option.match(Option.fromUndefinedOr(select), {
133
202
  onNone: () => true,
134
203
  onSome: (selects) => selects(node, {
135
204
  name: nameOf(node, context),
136
205
  context
137
206
  })
207
+ }));
208
+ // src/budget.ts
209
+ const OUT_OF_BUDGET = /^http (?:402|403): .*(?:credit|budget)/iu;
210
+ const outOfBudget = (reason) => OUT_OF_BUDGET.test(reason);
211
+ // src/explain-text.ts
212
+ const DECIMALS$1 = 2;
213
+ const fixed = (value) => value.toFixed(DECIMALS$1);
214
+ const cachedText = (cached) => Option.match(Option.fromUndefinedOr(cached), {
215
+ onNone: () => "unknown",
216
+ onSome: (hit) => Boolean.match(hit, {
217
+ onTrue: () => "yes",
218
+ onFalse: () => "no"
219
+ })
138
220
  });
221
+ const probabilitiesText = (probabilities) => Option.match(Array.match(Record.toEntries(probabilities), {
222
+ onEmpty: () => Option.none(),
223
+ onNonEmpty: (entries) => Option.some(pipe(entries, Array.map(([label, value]) => `${label}=${fixed(value)}`), Array.join(" ")))
224
+ }), {
225
+ onNone: () => "(no answer)",
226
+ onSome: (text) => text
227
+ });
228
+ const verdictText = (explanation) => {
229
+ if (Predicate.isNotUndefined(explanation.error)) return `error: ${explanation.error}`;
230
+ const outcome = Boolean.match(explanation.reported, {
231
+ onTrue: () => "reported",
232
+ onFalse: () => "not reported"
233
+ });
234
+ const cutoff = `cutoff ${fixed(explanation.cutoff)}`;
235
+ return Option.match(Option.fromUndefinedOr(explanation.verdict), {
236
+ onNone: () => `no verdict, ${cutoff}, ${outcome}`,
237
+ onSome: ({ answer, probability }) => `${answer} ${fixed(probability)}, ${cutoff}, ${outcome}`
238
+ });
239
+ };
240
+ const servedText = (served) => Option.match(Option.fromUndefinedOr(served), {
241
+ onNone: () => "",
242
+ onSome: (id) => ` (served ${id})`
243
+ });
244
+ const asText = (explanation) => pipe([
245
+ `${PREFIX} explain: ${explanation.file}:${String(explanation.line)}:${String(explanation.column)} [${explanation.rule}] ${explanation.model}${servedText(explanation.served)} cached=${cachedText(explanation.cached)} ${String(explanation.durationMs)}ms`,
246
+ ` state: ${String(explanation.state.chars)} chars ${toJson(explanation.state.head)}`,
247
+ ...pipe(explanation.questions, Array.map(({ id, question, probabilities }) => ` ${id}: ${probabilitiesText(probabilities)}\n ${question}`)),
248
+ ` verdict: ${verdictText(explanation)}`
249
+ ], Array.join("\n"));
139
250
  // src/explain.ts
140
251
  const EXPLAIN_ENV = "OXLINT_DECISION_EXPLAIN";
141
252
  const OFF_VALUES = /* @__PURE__ */ new Set([
@@ -145,18 +256,17 @@ const OFF_VALUES = /* @__PURE__ */ new Set([
145
256
  "no"
146
257
  ]);
147
258
  const STATE_HEAD_CHARS = 60;
148
- const DECIMALS$1 = 2;
149
259
  const OPTION_SEPARATOR = "__";
150
260
  const FIRST = 1;
151
261
  const START = 0;
152
262
  const COLUMN_BASE = 1;
153
263
  const SEPARATOR = /^[/\\]/u;
154
- const relativeTo = (root, filename) => Boolean.match(String$1.isNonEmpty(root) && filename.startsWith(root) && SEPARATOR.test(filename.slice(root.length)), {
155
- onTrue: () => filename.slice(root.length + FIRST),
264
+ const relativeTo = (root, filename) => Boolean.match(String$1.isNonEmpty(root) && String$1.startsWith(root)(filename) && SEPARATOR.test(String$1.slice(root.length)(filename)), {
265
+ onTrue: () => String$1.slice(root.length + FIRST)(filename),
156
266
  onFalse: () => filename
157
267
  });
158
268
  const fromSetting = (setting) => Match.value(setting).pipe(Match.when("json", () => "json"), Match.when(true, () => "text"), Match.when("text", () => "text"), Match.orElse(() => "off"));
159
- const fromEnv = (value) => Match.value(value.toLowerCase()).pipe(Match.when("json", () => "json"), Match.when((lower) => OFF_VALUES.has(lower), () => "off"), Match.orElse(() => "text"));
269
+ const fromEnv = (value) => Match.value(String$1.toLowerCase(value)).pipe(Match.when("json", () => "json"), Match.when((lower) => OFF_VALUES.has(lower), () => "off"), Match.orElse(() => "text"));
160
270
  const explainModeOf = (setting) => Option.match(envOf(EXPLAIN_ENV), {
161
271
  onNone: () => fromSetting(setting),
162
272
  onSome: fromEnv
@@ -167,12 +277,12 @@ const probabilitiesIn = (answer) => {
167
277
  return Option.none();
168
278
  };
169
279
  const probabilitiesOf = (answer) => Option.fromUndefinedOr(answer).pipe(Option.flatMap(probabilitiesIn), Option.getOrElse(() => ({})));
170
- const asksAbout = (ref, id) => id.split(OPTION_SEPARATOR, FIRST).includes(ref);
171
- const sentFor = (sent, ref) => sent.flatMap((wire) => Object.entries(wire.questions).filter(([id]) => asksAbout(ref, id)));
172
- const stateTextOf = (sent, ref, snippet) => Array.findFirst(sent, (wire) => Object.keys(wire.questions).some((id) => asksAbout(ref, id))).pipe(Option.map(({ state }) => state), Option.filter(Predicate.isString), Option.getOrElse(() => snippet));
280
+ const asksAbout = (ref, id) => pipe(String$1.split(id, OPTION_SEPARATOR), Array.take(FIRST), Array.contains(ref));
281
+ const sentFor = (sent, ref) => pipe(sent, Array.flatMap((wire) => pipe(Record.toEntries(wire.questions), Array.filter(([id]) => asksAbout(ref, id)))));
282
+ const stateTextOf = (sent, ref, snippet) => Array.findFirst(sent, (wire) => pipe(Record.keys(wire.questions), Array.some((id) => asksAbout(ref, id)))).pipe(Option.map(({ state }) => state), Option.filter(Predicate.isString), Option.getOrElse(() => snippet));
173
283
  const summaryOf = (text) => ({
174
284
  chars: text.length,
175
- head: text.replaceAll(/\s+/gu, " ").trim().slice(START, STATE_HEAD_CHARS)
285
+ head: String$1.slice(START, STATE_HEAD_CHARS)(String$1.trim(String$1.replaceAll(/\s+/gu, " ")(text)))
176
286
  });
177
287
  const baseOf = ({ pass, sent }, match, { ref, loc }) => {
178
288
  const questions = sentFor(sent, ref);
@@ -185,59 +295,25 @@ const baseOf = ({ pass, sent }, match, { ref, loc }) => {
185
295
  cutoff: match.rule.cutoff,
186
296
  durationMs: pass.durationMs,
187
297
  state: summaryOf(stateTextOf(sent, ref, match.snippet)),
188
- questions: questions.map(([id, question]) => ({
298
+ questions: pipe(questions, Array.map(([id, question]) => ({
189
299
  id,
190
300
  question: question.instructions,
191
301
  probabilities: probabilitiesOf(answers[id])
192
- }))
302
+ })))
193
303
  });
194
304
  };
195
- const fixed = (value) => value.toFixed(DECIMALS$1);
196
- const cachedText = (cached) => Option.match(Option.fromUndefinedOr(cached), {
197
- onNone: () => "unknown",
198
- onSome: (hit) => Boolean.match(hit, {
199
- onTrue: () => "yes",
200
- onFalse: () => "no"
201
- })
202
- });
203
- const probabilitiesText = (probabilities) => Option.match(Array.match(Object.entries(probabilities), {
204
- onEmpty: () => Option.none(),
205
- onNonEmpty: (entries) => Option.some(entries.map(([label, value]) => `${label}=${fixed(value)}`).join(" "))
206
- }), {
207
- onNone: () => "(no answer)",
208
- onSome: (text) => text
209
- });
210
- const verdictText = (explanation) => {
211
- if (Predicate.isNotUndefined(explanation.error)) return `error: ${explanation.error}`;
212
- const outcome = Boolean.match(explanation.reported, {
213
- onTrue: () => "reported",
214
- onFalse: () => "not reported"
215
- });
216
- const cutoff = `cutoff ${fixed(explanation.cutoff)}`;
217
- return Option.match(Option.fromUndefinedOr(explanation.verdict), {
218
- onNone: () => `no verdict, ${cutoff}, ${outcome}`,
219
- onSome: ({ answer, probability }) => `${answer} ${fixed(probability)}, ${cutoff}, ${outcome}`
220
- });
221
- };
222
- const servedText = (served) => Option.match(Option.fromUndefinedOr(served), {
223
- onNone: () => "",
224
- onSome: (id) => ` (served ${id})`
225
- });
226
- const asText = (explanation) => [
227
- `${PREFIX} explain: ${explanation.file}:${String(explanation.line)}:${String(explanation.column)} [${explanation.rule}] ${explanation.model}${servedText(explanation.served)} cached=${cachedText(explanation.cached)} ${String(explanation.durationMs)}ms`,
228
- ` state: ${String(explanation.state.chars)} chars ${JSON.stringify(explanation.state.head)}`,
229
- ...explanation.questions.map(({ id, question, probabilities }) => ` ${id}: ${probabilitiesText(probabilities)}\n ${question}`),
230
- ` verdict: ${verdictText(explanation)}`
231
- ].join("\n");
232
305
  const printerFor = (mode) => (explanation) => {
233
306
  const line = Boolean.match(mode === "json", {
234
- onTrue: () => JSON.stringify(explanation),
307
+ onTrue: () => toJson(explanation),
235
308
  onFalse: () => asText(explanation)
236
309
  });
237
310
  Effect.runFork(Console.error(line));
238
311
  };
239
312
  const explaining = (pass, mode) => {
240
- const sent = wireRequestsFor(pass.request);
313
+ const sent = Boolean.match(pass.yesNo, {
314
+ onTrue: () => yesNoRequestsFor(pass.request),
315
+ onFalse: () => wireRequestsFor(pass.request)
316
+ });
241
317
  const print = printerFor(mode);
242
318
  return {
243
319
  outcome: (match, at, { served, answers, cached, verdict, reported }) => {
@@ -282,9 +358,11 @@ const SILENT = {
282
358
  };
283
359
  const explainerFor = (pass) => Match.value(explainModeOf(pass.setting)).pipe(Match.when("off", () => SILENT), Match.orElse((mode) => explaining(pass, mode)));
284
360
  // src/locate.ts
361
+ const DATA_FIRST_ARITY_3 = 3;
362
+ const DATA_FIRST_ARITY$1 = 2;
285
363
  const MINIMUM_TIMEOUT_MS = 1;
286
- const remainingMs = (deadline) => Math.max(MINIMUM_TIMEOUT_MS, deadline - Date.now());
287
- const verdictsOf = (result, request) => {
364
+ const remainingMs = (deadline) => Math.max(MINIMUM_TIMEOUT_MS, deadline - nowMs());
365
+ const verdictsOf = Function.dual(DATA_FIRST_ARITY$1, (result, request) => {
288
366
  if (!result.ok) return result;
289
367
  return runOrElse(Effect.sync(() => ({
290
368
  ok: true,
@@ -294,12 +372,12 @@ const verdictsOf = (result, request) => {
294
372
  ok: false,
295
373
  reason: messageOf(cause)
296
374
  }));
297
- };
298
- const inputOf = (asking, request) => ({
375
+ });
376
+ const inputOf = Function.dual(DATA_FIRST_ARITY$1, (asking, request) => ({
299
377
  request,
300
378
  timeoutMs: remainingMs(asking.deadline),
301
379
  env: asking.env
302
- });
380
+ }));
303
381
  const fetchVerdicts = (asking, request) => verdictsOf(asking.model.provider.decide(inputOf(asking, request)), request);
304
382
  const isRange = (location) => Option.exists(location, ({ start, end }) => start !== end);
305
383
  const refineOnce = ({ asking, match, ref, state }, within) => {
@@ -334,27 +412,28 @@ const refine = (refinement, first) => {
334
412
  failure: Option.none()
335
413
  };
336
414
  };
337
- const locateMatch = (asking, match, { ref, verdicts, request }) => {
415
+ const locateMatch = Function.dual(DATA_FIRST_ARITY_3, (asking, match, { ref, verdicts, request }) => {
338
416
  if (!locates(match)) return {
339
417
  loc: match.loc,
340
418
  failure: Option.none()
341
419
  };
342
- const first = selectedLocation(verdicts.answers[locationRefOf(ref)], locationCandidates(match.snippet), match.rule.location.cutoff);
420
+ const first = selectedLocation(verdicts.answers[locationRefOf(ref)], locationCandidates(match.snippet, EVERY_LINE), match.rule.location.cutoff);
343
421
  return refine({
344
422
  asking,
345
423
  match,
346
424
  ref,
347
425
  state: request.state
348
426
  }, first);
349
- };
427
+ });
350
428
  // src/report.ts
351
429
  const DECIMALS = 2;
430
+ const failsHere = (pass, reason) => failsInCi(pass.options) && !outOfBudget(reason);
352
431
  const degrade = (pass, reason) => {
353
- if (failsInCi(pass.options)) throw new OptionsError(`${reason} (${pass.filename})`);
432
+ if (failsHere(pass, reason)) throw optionsError(`${reason} (${pass.filename})`);
354
433
  warnOnce(reason, `${reason} (${pass.filename})`);
355
434
  };
356
435
  const reportFailure = (pass, failure) => {
357
- if (failsInCi(pass.options)) {
436
+ if (failsHere(pass, failure.reason)) {
358
437
  pass.contextOf(failure.match).report({
359
438
  loc: failure.loc,
360
439
  messageId: "unlocated",
@@ -444,6 +523,7 @@ const explainPassOf = (pass, { request, durationMs }) => ({
444
523
  }),
445
524
  filename: pass.filename,
446
525
  model: pass.model.id,
526
+ yesNo: pass.model.provider.yesNo === true,
447
527
  request,
448
528
  durationMs
449
529
  });
@@ -478,9 +558,9 @@ const reportAnswer = ({ pass, asking, request }, { decided, durationMs }) => {
478
558
  });
479
559
  };
480
560
  const decideWith = (provider, prepared) => {
481
- const inputs = prepared.map(({ asking, request }) => inputOf(asking, request));
561
+ const inputs = pipe(prepared, Array.map(({ asking, request }) => inputOf(asking, request)));
482
562
  return Option.match(Option.fromUndefinedOr(provider.decideAll), {
483
- onNone: () => inputs.map((input) => provider.decide(input)),
563
+ onNone: () => pipe(inputs, Array.map((input) => provider.decide(input))),
484
564
  onSome: (decideAll) => decideAll(inputs)
485
565
  });
486
566
  };
@@ -491,10 +571,10 @@ const reportProvider = (prepared) => {
491
571
  const durationMs = Math.round(performance.now() - started);
492
572
  const answers = Boolean.match(results.length === prepared.length, {
493
573
  onTrue: () => results,
494
- onFalse: () => prepared.map(() => ({
574
+ onFalse: () => pipe(prepared, Array.map(() => ({
495
575
  ok: false,
496
576
  reason: `provider ${provider.name} returned ${String(results.length)} results for ${String(prepared.length)} requests`
497
- }))
577
+ })))
498
578
  });
499
579
  for (const [one, decided] of Array.zip(prepared, answers)) reportAnswer(one, {
500
580
  decided,
@@ -502,24 +582,28 @@ const reportProvider = (prepared) => {
502
582
  });
503
583
  };
504
584
  const reportModels = (passes) => {
505
- const byProvider = Array.groupBy(passes.map((pass) => prepare(pass)), ({ pass }) => pass.model.provider.name);
506
- for (const prepared of Object.values(byProvider)) reportProvider(prepared);
585
+ const byProvider = Array.groupBy(pipe(passes, Array.map((pass) => prepare(pass))), ({ pass }) => pass.model.provider.name);
586
+ for (const prepared of Record.values(byProvider)) reportProvider(prepared);
507
587
  };
508
588
  // src/visitor.ts
589
+ const DATA_FIRST_ARITY = 2;
509
590
  const raisedMissing = /* @__PURE__ */ new Set();
510
- const missingEnvOf = (options, provider) => provider.requiredEnv.map((name) => envNameOf(options.env, name)).filter((name) => Option.isNone(envOf(name)));
591
+ const missingEnvOf = (options, provider) => pipe(provider.requiredEnv, Array.map((name) => envNameOf(options.env, name)), Array.filter((name) => Option.isNone(envOf(name))));
511
592
  const isAvailable = (options, { provider }) => {
512
593
  const missingNames = missingEnvOf(options, provider);
513
594
  if (Array.isReadonlyArrayEmpty(missingNames)) return true;
514
- const missing = missingNames.join(", ");
595
+ const missing = pipe(missingNames, Array.join(", "));
515
596
  if (!failsInCi(options)) warnOnce(`missing:${provider.name}`, `${missing} is not set, skipping ${provider.name} models`);
516
597
  else if (!raisedMissing.has(provider.name)) {
517
598
  raisedMissing.add(provider.name);
518
- throw new OptionsError(`${missing} is not set`);
599
+ throw optionsError(`${missing} is not set`);
519
600
  }
520
601
  return false;
521
602
  };
522
- const availableModels = (batch) => [...new Map(Object.values(batch.rules).flatMap((rule) => rule.models).map((model) => [model.id, model])).values()].filter((model) => isAvailable(batch.options, model));
603
+ const availableModels = (batch) => {
604
+ const models = pipe(Record.values(batch.rules), Array.flatMap((rule) => rule.models), Array.map((model) => [model.id, model]));
605
+ return pipe(Array.fromIterable(new Map(models).values()), Array.filter((model) => isAvailable(batch.options, model)));
606
+ };
523
607
  const snippetOf = (context, node) => {
524
608
  if (node.type === "Program") return context.sourceCode.text;
525
609
  return context.sourceCode.getText(node);
@@ -545,11 +629,11 @@ const matchOf = (context, node, { rule, options }) => {
545
629
  };
546
630
  const contextOfRule = (batch, id) => Option.getOrThrow(Option.fromUndefinedOr(batch.contexts[id]));
547
631
  const finish = (batch) => {
548
- const [first] = Object.values(batch.contexts);
632
+ const [first] = Record.values(batch.contexts);
549
633
  if (Predicate.isUndefined(first)) return;
550
- const deadline = Date.now() + batch.options.timeoutMs;
551
- const passes = availableModels(batch).flatMap((model) => {
552
- const matches = batch.matches.filter(({ rule }) => rule.models.some(({ id }) => id === model.id));
634
+ const deadline = nowMs() + batch.options.timeoutMs;
635
+ const passes = pipe(availableModels(batch), Array.flatMap((model) => {
636
+ const matches = pipe(batch.matches, Array.filter(({ rule }) => pipe(rule.models, Array.some(({ id }) => id === model.id))));
553
637
  return Array.match(matches, {
554
638
  onEmpty: () => [],
555
639
  onNonEmpty: (some) => [{
@@ -561,11 +645,11 @@ const finish = (batch) => {
561
645
  deadline
562
646
  }]
563
647
  });
564
- });
648
+ }));
565
649
  reportModels(passes);
566
650
  };
567
651
  const ruleIn = (batch, id) => Option.getOrThrow(Array.findFirst(batch.options.rules, (rule) => rule.id === id));
568
- const sharedFile = (optionsFor, ruleFor) => {
652
+ const sharedFile = Function.dual(DATA_FIRST_ARITY, (optionsFor, ruleFor) => {
569
653
  let current = Option.none();
570
654
  const start = (context) => {
571
655
  const batch = {
@@ -601,16 +685,16 @@ const sharedFile = (optionsFor, ruleFor) => {
601
685
  if (Option.isNone(current)) return;
602
686
  const batch = current.value;
603
687
  batch.exits += 1;
604
- if (batch.exits >= Object.keys(batch.contexts).length) current = Option.none();
688
+ if (batch.exits >= Record.keys(batch.contexts).length) current = Option.none();
605
689
  if (!batch.exiting) {
606
690
  batch.exiting = true;
607
691
  finish(batch);
608
692
  }
609
693
  }
610
694
  };
611
- };
695
+ });
612
696
  const isSkipped = (context, node, rule) => !isSelected(context, node, rule) || lacksComment(context, node, rule);
613
- const visitorFor = (shared, { id, target }) => (context) => {
697
+ const visitorFor = Function.dual(DATA_FIRST_ARITY, (shared, { id, target }) => (context) => {
614
698
  let file = Option.none();
615
699
  const collect = (node) => {
616
700
  if (Option.isNone(file)) return;
@@ -623,7 +707,7 @@ const visitorFor = (shared, { id, target }) => (context) => {
623
707
  };
624
708
  const nodeTypes = TARGET_NODE_TYPES[target];
625
709
  return {
626
- ...Object.fromEntries(nodeTypes.map((type) => [type, collect])),
710
+ ...Record.fromEntries(pipe(nodeTypes, Array.map((type) => [type, collect]))),
627
711
  Program: (node) => {
628
712
  file = Option.some(shared.join(context, id));
629
713
  if (target === "file") collect(node);
@@ -633,7 +717,7 @@ const visitorFor = (shared, { id, target }) => (context) => {
633
717
  shared.leave();
634
718
  }
635
719
  };
636
- };
720
+ });
637
721
  // src/plugin.ts
638
722
  const DEFAULT_NAME = "decision";
639
723
  const metaOf = (rule) => ({
@@ -645,16 +729,15 @@ const metaOf = (rule) => ({
645
729
  unlocated: `${PREFIX}: {{reason}} while refining the location of [{{id}}]; the finding is reported at the file level`
646
730
  }
647
731
  });
648
- const SETUP_ONLY = /* @__PURE__ */ new Set([
732
+ const optionsOf = (setup) => Struct.omit(setup, [
649
733
  "name",
650
734
  "rules",
651
735
  "providers"
652
736
  ]);
653
- const optionsOf = (setup) => Object.fromEntries(Object.entries(setup).filter(([key]) => !SETUP_ONLY.has(key)));
654
737
  const memoized = (resolve) => {
655
738
  const resolved = /* @__PURE__ */ new Map();
656
739
  return (settings) => {
657
- const key = JSON.stringify([settings]);
740
+ const key = toJson([settings]);
658
741
  const cached = resolved.get(key);
659
742
  if (Predicate.isNotUndefined(cached)) return cached;
660
743
  const fresh = resolve(settings);
@@ -667,7 +750,7 @@ const memoizedRules = (providers) => {
667
750
  return (rule, options) => {
668
751
  const known = resolved.get(rule) ?? /* @__PURE__ */ new Map();
669
752
  resolved.set(rule, known);
670
- const key = JSON.stringify([options]);
753
+ const key = toJson([options]);
671
754
  const cached = known.get(key);
672
755
  if (Predicate.isNotUndefined(cached)) return cached;
673
756
  const fresh = overrideRule(rule, options, providers);
@@ -677,7 +760,11 @@ const memoizedRules = (providers) => {
677
760
  };
678
761
  const createDecisionPlugin = (setup) => {
679
762
  const name = setup.name ?? DEFAULT_NAME;
680
- const providers = Object.fromEntries([openRouter, ...setup.providers ?? []].map((provider) => [provider.name, provider]));
763
+ const providers = Record.fromEntries(pipe([
764
+ cloudflare,
765
+ openRouter,
766
+ ...setup.providers ?? []
767
+ ], Array.map((provider) => [provider.name, provider])));
681
768
  const rules = checkRules(setup.rules);
682
769
  const options = optionsOf(setup);
683
770
  const resolve = memoized((settings) => resolveOptions({
@@ -688,12 +775,12 @@ const createDecisionPlugin = (setup) => {
688
775
  const shared = sharedFile((settings) => resolve(settings[name]), memoizedRules(providers));
689
776
  return {
690
777
  meta: { name },
691
- rules: Object.fromEntries(rules.map((rule) => [rule.id, {
778
+ rules: Record.fromEntries(pipe(rules, Array.map((rule) => [rule.id, {
692
779
  meta: metaOf(rule),
693
780
  createOnce: visitorFor(shared, rule)
694
- }]))
781
+ }])))
695
782
  };
696
783
  };
697
- export { createDecisionPlugin, defineDecisionRule, defineProvider, openRouter };
784
+ export { cloudflare, createDecisionPlugin, defineDecisionRule, defineProvider, openRouter };
698
785
 
699
786
  //# sourceMappingURL=index.mjs.map