@antelopejs/tooling-configs 0.7.4 → 0.7.5-next.356.g0d472b3

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 (44) hide show
  1. package/README.md +32 -77
  2. package/dist/bin/api-diff.mjs +16 -36
  3. package/dist/bin/capture.mjs +4 -4
  4. package/dist/bin/check-size.mjs +12 -3
  5. package/dist/bin/checks.mjs +2 -2
  6. package/dist/bin/comment-proof.mjs +3 -4
  7. package/dist/bin/garden.mjs +45 -170
  8. package/dist/bin/readme-strip.mjs +2 -2
  9. package/dist/bin/suppressions.mjs +212 -9
  10. package/dist/bin/sync.mjs +284 -189
  11. package/dist/bin/tsc.mjs +1 -1
  12. package/dist/bin/verify.mjs +33 -613
  13. package/dist/{checks-BTFf0Evy.mjs → checks-C60vMFin.mjs} +130 -283
  14. package/dist/{docs-compat-BmczGA1d.mjs → docs-compat-CdgBviGf.mjs} +2 -2
  15. package/dist/eslint.mjs +1 -1
  16. package/dist/{files-C-JJhExM.mjs → files-BbzJEk-L.mjs} +5 -4
  17. package/dist/formal/index.mjs +1 -1
  18. package/dist/{guardrails-CNmSFSxO.mjs → guardrails-Dron1AbR.mjs} +5 -611
  19. package/dist/{map-BYkmnvNw.mjs → map-CbNbypUa.mjs} +2 -2
  20. package/dist/oxc/anti-slop/index.mjs +22 -964
  21. package/dist/oxc/guardrails/index.d.mts +1 -1
  22. package/dist/oxc/guardrails/index.mjs +1 -1
  23. package/dist/oxc/lint.d.mts +2 -14
  24. package/dist/oxc/lint.mjs +3 -20
  25. package/dist/{package-1pH5I0TF.mjs → package-7oylgBeT.mjs} +3 -12
  26. package/dist/{workflow-C-oBwL2H.mjs → renovate-D0su_v9p.mjs} +191 -91
  27. package/dist/{suppression-budget-BeJIgSTO.mjs → suppression-budget-De9nUzlD.mjs} +33 -13
  28. package/dist/{suppressions-BvWGA463.mjs → suppressions-CfJwL0fN.mjs} +1 -1
  29. package/dist/{templates-Df6SlGLA.mjs → templates-DLW0Ubfk.mjs} +26 -29
  30. package/dist/typescript-C7eU-cig.mjs +581 -0
  31. package/dist/verify/index.d.mts +5 -24
  32. package/package.json +1 -3
  33. package/dist/bin/body-check.d.mts +0 -1
  34. package/dist/bin/body-check.mjs +0 -350
  35. package/dist/bin/ratchet.d.mts +0 -1
  36. package/dist/bin/ratchet.mjs +0 -375
  37. package/dist/ceilings-B7KayYIG.mjs +0 -76
  38. package/dist/oxlint-CIeonWMB.mjs +0 -133
  39. package/dist/proof-stamp-Bg4ULLvr.mjs +0 -342
  40. package/dist/ratchet-CPpvIU6Y.mjs +0 -453
  41. package/dist/renames-L2owF5GD.mjs +0 -59
  42. package/dist/size-CCGLY4Ke.mjs +0 -18
  43. package/dist/suppression-base-CDiFJse2.mjs +0 -120
  44. package/dist/typescript-B0df00nl.mjs +0 -292
@@ -664,7 +664,7 @@ function typePredicateSubjectIndex(sourceCode, owner, parameters) {
664
664
  function annotationTarget(annotation, environment) {
665
665
  return annotation === null || annotation === void 0 ? null : classifyWideningTarget(annotation.typeAnnotation, environment);
666
666
  }
667
- function enclosingFunction$1(node) {
667
+ function enclosingFunction(node) {
668
668
  let current = node.parent;
669
669
  while (current !== null && current.type !== "Program") {
670
670
  if (current.type === "ArrowFunctionExpression" || current.type === "FunctionDeclaration" || current.type === "FunctionExpression") return current;
@@ -766,7 +766,7 @@ const noKnownValueWideningRule = defineRule({
766
766
  },
767
767
  ReturnStatement(node) {
768
768
  if (node.argument === null) return;
769
- const owner = enclosingFunction$1(node);
769
+ const owner = enclosingFunction(node);
770
770
  reportFlow(node.argument, targetFromAnnotation(owner?.returnType), `return value of \`${functionName(context.sourceCode, owner)}\``);
771
771
  },
772
772
  ArrowFunctionExpression(node) {
@@ -1073,864 +1073,6 @@ const noForbiddenTermInSymbolNamesRule = defineRule({
1073
1073
  }
1074
1074
  });
1075
1075
  //#endregion
1076
- //#region src/oxc/anti-slop/shared/binding-origin.ts
1077
- /** Return the variable an identifier refers to, searching outward from its scope, or null for an unresolved global. */
1078
- function variableOf(identifier, sourceCode) {
1079
- let scope = sourceCode.getScope(identifier);
1080
- while (scope !== null) {
1081
- const variable = scope.set.get(identifier.name);
1082
- if (variable !== void 0) return variable;
1083
- scope = scope.upper;
1084
- }
1085
- return null;
1086
- }
1087
- /**
1088
- * Return whether a name has no definition in this file: a name no scope binds, or a global the environment declares (`Array`,
1089
- * `Error`), which oxlint binds to a variable with no definition.
1090
- */
1091
- function isGlobalName(identifier, sourceCode) {
1092
- const variable = variableOf(identifier, sourceCode);
1093
- return variable === null || variable.defs.length === 0;
1094
- }
1095
- //#endregion
1096
- //#region src/oxc/anti-slop/shared/brand-probe.ts
1097
- /** Primitive types a probe may hand back: a derived value, never an object shape the function claims to know. */
1098
- const PRIMITIVE_TYPES = /* @__PURE__ */ new Set([
1099
- "TSBigIntKeyword",
1100
- "TSBooleanKeyword",
1101
- "TSNullKeyword",
1102
- "TSNumberKeyword",
1103
- "TSStringKeyword",
1104
- "TSSymbolKeyword",
1105
- "TSUndefinedKeyword",
1106
- "TSVoidKeyword"
1107
- ]);
1108
- function isPrimitiveType(type) {
1109
- if (type.type === "TSUnionType") return type.types.every(isPrimitiveType);
1110
- if (type.type === "TSParenthesizedType") return isPrimitiveType(type.typeAnnotation);
1111
- return PRIMITIVE_TYPES.has(type.type) || type.type === "TSLiteralType";
1112
- }
1113
- /** Return whether a call creates a symbol: `Symbol(...)` or `Symbol.for(...)` on the global `Symbol`. */
1114
- function createsSymbol(node, sourceCode) {
1115
- if (node === null || node === void 0 || node.type !== "CallExpression") return false;
1116
- const { callee } = node;
1117
- const root = callee.type === "MemberExpression" && !callee.computed && callee.property.type === "Identifier" && callee.property.name === "for" ? callee.object : callee;
1118
- return root.type === "Identifier" && root.name === "Symbol" && isGlobalName(root, sourceCode);
1119
- }
1120
- /** Return whether an expression is a symbol this file creates: a `const` bound to `Symbol(...)` or `Symbol.for(...)`, or such a call. */
1121
- function isOwnSymbol(node, sourceCode) {
1122
- if (node.type !== "Identifier") return createsSymbol(node, sourceCode);
1123
- const definition = variableOf(node, sourceCode)?.defs[0];
1124
- const declarator = definition?.node;
1125
- return definition?.type === "Variable" && declarator?.type === "VariableDeclarator" && declarator.parent.type === "VariableDeclaration" && declarator.parent.kind === "const" && createsSymbol(declarator.init, sourceCode);
1126
- }
1127
- /** Return whether a reference reads a symbol-keyed member of the value (`value[BRAND]`) or asks `BRAND in value`. */
1128
- function isProbe(reference, sourceCode) {
1129
- const user = reference.parent;
1130
- if (user.type === "MemberExpression") return user.object === reference && user.computed && isOwnSymbol(user.property, sourceCode);
1131
- return user.type === "BinaryExpression" && user.operator === "in" && user.right === reference && isOwnSymbol(user.left, sourceCode);
1132
- }
1133
- /** Return the function a callee names when this file declares it: a function declaration, or a `const` bound to an arrow or function expression. */
1134
- function declaredFunctionOf(callee, sourceCode) {
1135
- if (callee.type !== "Identifier") return null;
1136
- const definition = variableOf(callee, sourceCode)?.defs[0];
1137
- if (definition?.type === "FunctionName" && isRuntimeFunction(definition.node)) return definition.node;
1138
- const declarator = definition?.node;
1139
- if (definition?.type === "Variable" && declarator?.type === "VariableDeclarator" && declarator.parent.type === "VariableDeclaration" && declarator.parent.kind === "const" && declarator.init !== null && declarator.init !== void 0 && isRuntimeFunction(declarator.init)) return declarator.init;
1140
- return null;
1141
- }
1142
- function parameterAt(owner, position, sourceCode) {
1143
- const parameter = argumentParameters(owner)[position];
1144
- if (parameter?.type !== "Identifier") return null;
1145
- return sourceCode.getDeclaredVariables(owner).find((variable) => variable.name === parameter.name && variable.defs[0]?.type === "Parameter") ?? null;
1146
- }
1147
- /** Return whether a function declared in this file is a type guard on the parameter at `position`. */
1148
- function guardsParameterAt(owner, position) {
1149
- const predicate = owner.returnType?.typeAnnotation;
1150
- const parameter = argumentParameters(owner)[position];
1151
- return predicate?.type === "TSTypePredicate" && !predicate.asserts && predicate.parameterName.type === "Identifier" && parameter?.type === "Identifier" && predicate.parameterName.name === parameter.name;
1152
- }
1153
- /** Operators whose result is a boolean about the operands, which a probe may hand back. */
1154
- const COMPARISONS = /* @__PURE__ */ new Set([
1155
- "===",
1156
- "!==",
1157
- "==",
1158
- "!=",
1159
- "<",
1160
- ">",
1161
- "<=",
1162
- ">="
1163
- ]);
1164
- /** Return whether a function declares a primitive return type, so what it hands back is a derived value. */
1165
- function returnsPrimitive(fn) {
1166
- const returned = fn.returnType?.typeAnnotation;
1167
- return returned !== void 0 && isPrimitiveType(returned);
1168
- }
1169
- /** Return the function a node is written in. */
1170
- function enclosingFunction(node) {
1171
- for (let at = node.parent; at !== null; at = at.parent) if (isRuntimeFunction(at)) return at;
1172
- return null;
1173
- }
1174
- /** Return whether every reference of a `const` or function binding is a use that `reaches` accepts. */
1175
- function everyUseReaches(variable, reaches) {
1176
- if (variable === null || variable === void 0) return false;
1177
- const reads = variable.references.filter((reference) => !reference.init);
1178
- return reads.length > 0 && variable.references.every((reference) => reference.init || !reference.isWrite()) && reads.every((reference) => reaches(reference.identifier));
1179
- }
1180
- /**
1181
- * Return whether the value an expression yields reaches nothing but the result of the probe. The value may be tested,
1182
- * compared, negated, read further (`.identity`), pass through `Boolean(...)`, a type wrapper, a `&&`, `||`, `??` or a
1183
- * conditional branch, be held in a `const` whose uses obey the same rule, or be returned. Only the probe ends the walk. A function that is not the
1184
- * probe may return it when it is declared in this file and every use of it is a call whose value obeys the same rule, or when it
1185
- * declares a primitive return type and nothing in the file refers to it (an exported sibling probe).
1186
- * An assignment, a `delete`, an update, a call of the value, an argument to any other call, a store or a spread refuses.
1187
- */
1188
- function resultReachesOnlyReturn(node, owner, sourceCode, seen) {
1189
- if (seen.has(node)) return true;
1190
- seen.add(node);
1191
- const user = node.parent;
1192
- if (user === null) return false;
1193
- const next = (target) => resultReachesOnlyReturn(target, owner, sourceCode, seen);
1194
- switch (user.type) {
1195
- case "ChainExpression":
1196
- case "TSAsExpression":
1197
- case "TSNonNullExpression":
1198
- case "TSSatisfiesExpression":
1199
- case "TSTypeAssertion": return next(user);
1200
- case "MemberExpression": return user.object === node && next(user);
1201
- case "UnaryExpression": return (user.operator === "!" || user.operator === "typeof") && next(user);
1202
- case "BinaryExpression": return COMPARISONS.has(user.operator) && next(user);
1203
- case "LogicalExpression": return next(user);
1204
- case "ConditionalExpression": return user.test === node || next(user);
1205
- case "IfStatement": return user.test === node;
1206
- case "ExpressionStatement": return true;
1207
- case "CallExpression": return user.callee.type === "Identifier" && user.callee.name === "Boolean" && isGlobalName(user.callee, sourceCode) && user.arguments[0] === node && next(user);
1208
- case "VariableDeclarator":
1209
- if (user.id.type !== "Identifier" || user.parent.type !== "VariableDeclaration" || user.parent.kind !== "const") return false;
1210
- return everyUseReaches(sourceCode.getDeclaredVariables(user).find((each) => each.name === user.id.name), next);
1211
- case "ReturnStatement":
1212
- case "ArrowFunctionExpression": {
1213
- if (user.type === "ArrowFunctionExpression" && user.body !== node) return false;
1214
- const returner = user.type === "ArrowFunctionExpression" ? user : enclosingFunction(user);
1215
- if (returner === null) return false;
1216
- if (returner === owner) return true;
1217
- const bound = readerVariable(returner, sourceCode);
1218
- if (returnsPrimitive(returner) && bound !== null && bound.references.length === 0) return true;
1219
- return everyUseReaches(bound, (use) => use.parent.type === "CallExpression" && use.parent.callee === use && next(use.parent));
1220
- }
1221
- default: return false;
1222
- }
1223
- }
1224
- /** Return the variable a function declared in this file is bound to. */
1225
- function readerVariable(reader, sourceCode) {
1226
- if (reader.type === "FunctionDeclaration") return reader.id === null ? null : sourceCode.getDeclaredVariables(reader).find((variable) => variable.name === reader.id?.name && variable.defs[0]?.type === "FunctionName") ?? null;
1227
- const declarator = reader.parent;
1228
- if (declarator.type !== "VariableDeclarator" || declarator.init !== reader || declarator.id.type !== "Identifier") return null;
1229
- return sourceCode.getDeclaredVariables(declarator).find((variable) => variable.name === declarator.id.name) ?? null;
1230
- }
1231
- const REFUSED = {
1232
- allowed: false,
1233
- probed: false
1234
- };
1235
- function combine(uses) {
1236
- return {
1237
- allowed: uses.every((use) => use.allowed),
1238
- probed: uses.some((use) => use.probed)
1239
- };
1240
- }
1241
- /**
1242
- * Walk every use of a value. A use is allowed when it is a symbol-keyed probe, an argument to a type guard declared in this
1243
- * file, the initializer of a `const` alias whose own uses are allowed, or an argument to a function declared in this file whose
1244
- * matching parameter's uses are allowed. Any other use (a store, a return, a call elsewhere, a cast, an assignment) refuses.
1245
- */
1246
- function usesOf(variable, owner, sourceCode, seen) {
1247
- if (seen.has(variable)) return {
1248
- allowed: true,
1249
- probed: false
1250
- };
1251
- seen.add(variable);
1252
- const reads = variable.references.filter((reference) => !reference.init);
1253
- if (variable.references.some((reference) => reference.isWrite() && !reference.init) || reads.length === 0) return REFUSED;
1254
- return combine(reads.map((reference) => {
1255
- const { identifier } = reference;
1256
- if (isProbe(identifier, sourceCode)) return resultReachesOnlyReturn(identifier.parent, owner, sourceCode, /* @__PURE__ */ new Set()) ? {
1257
- allowed: true,
1258
- probed: true
1259
- } : REFUSED;
1260
- const user = identifier.parent;
1261
- if (user.type === "VariableDeclarator" && user.init === identifier && user.id.type === "Identifier" && user.parent.type === "VariableDeclaration" && user.parent.kind === "const") {
1262
- const alias = sourceCode.getDeclaredVariables(user).find((each) => each.name === user.id.name);
1263
- return alias === void 0 ? REFUSED : usesOf(alias, owner, sourceCode, seen);
1264
- }
1265
- if (user.type !== "CallExpression") return REFUSED;
1266
- const position = user.arguments.findIndex((argument) => argument === identifier);
1267
- const callee = declaredFunctionOf(user.callee, sourceCode);
1268
- if (position < 0 || callee === null) return REFUSED;
1269
- if (guardsParameterAt(callee, position)) return {
1270
- allowed: true,
1271
- probed: false
1272
- };
1273
- const parameter = parameterAt(callee, position, sourceCode);
1274
- return parameter === null ? REFUSED : usesOf(parameter, owner, sourceCode, seen);
1275
- }));
1276
- }
1277
- /**
1278
- * Return whether a function is a brand probe on a parameter typed `unknown`: it declares a primitive return type, so the
1279
- * value it hands back is derived, and the only things it does with the parameter are to read a symbol-keyed member that this
1280
- * file creates (or ask `in` with one), through guards and readers declared in this file, and at least one such read happens.
1281
- * Storing, forwarding, casting or returning the parameter, reading it by a string key, or a reader imported from elsewhere
1282
- * is not one.
1283
- */
1284
- function isBrandProbe(owner, parameter, sourceCode) {
1285
- const returned = owner.returnType?.typeAnnotation;
1286
- if (parameter === void 0 || returned === void 0 || !isPrimitiveType(returned)) return false;
1287
- const uses = usesOf(parameter, owner, sourceCode, /* @__PURE__ */ new Set());
1288
- return uses.allowed && uses.probed;
1289
- }
1290
- //#endregion
1291
- //#region src/oxc/anti-slop/shared/caught-callback.ts
1292
- /** Return whether an identifier is a catch clause's own binding, never reassigned, so it holds exactly what was thrown. */
1293
- function isCaughtValue(node, sourceCode) {
1294
- if (node.type !== "Identifier") return false;
1295
- const definition = variableOf(node, sourceCode)?.defs[0];
1296
- if (definition?.type !== "CatchClause" || definition.node.type !== "CatchClause") return false;
1297
- return definition.node.param?.type === "Identifier" && definition.node.param.name === node.name && variableOf(node, sourceCode)?.references.every((reference) => !reference.isWrite()) === true;
1298
- }
1299
- /** Return whether a use of a callback leaves it unable to run with anything but what a call site passes: a plain test of whether it exists. */
1300
- function isExistenceTest(reference) {
1301
- const user = reference.parent;
1302
- return user.type === "ConditionalExpression" && user.test === reference || user.type === "IfStatement" && user.test === reference || user.type === "LogicalExpression" && user.operator === "&&" && user.left === reference;
1303
- }
1304
- /** Return whether a call hands a caught value to every parameter of the callback type that is `unknown`. */
1305
- function passesCaughtValues(call, unknownPositions, sourceCode) {
1306
- return unknownPositions.every((position) => {
1307
- const argument = call.arguments[position];
1308
- return argument !== void 0 && isCaughtValue(argument, sourceCode);
1309
- });
1310
- }
1311
- function parameterVariable(owner, parameter, sourceCode) {
1312
- return sourceCode.getDeclaredVariables(owner).find((variable) => variable.name === parameter.name && variable.defs[0]?.type === "Parameter");
1313
- }
1314
- /**
1315
- * Return whether a function type is the type of a callback parameter that the function only calls with a caught value.
1316
- * The callback parameter is a plain identifier of a function that has a body, its type is written directly as a function
1317
- * type, it is called at least once, and every use of it is such a call (with a caught value in each `unknown` position of
1318
- * the type) or a test of whether it exists. A callback that is stored, passed on, never called, or called with any other
1319
- * value is not one: the thrown value has no type JavaScript promises, so `unknown` is the true type only there.
1320
- */
1321
- function isCaughtValueCallbackType(owner, sourceCode) {
1322
- const annotation = owner.parent;
1323
- if (annotation.type !== "TSTypeAnnotation") return false;
1324
- const callback = annotation.parent;
1325
- if (callback.type !== "Identifier") return false;
1326
- const holder = callback.parent;
1327
- if (!isRuntimeFunction(holder) || holder.body === null || holder.body === void 0) return false;
1328
- const unknownPositions = argumentParameters(owner).flatMap((parameter, position) => {
1329
- const type = functionParameterTypeAnnotation(parameter)?.typeAnnotation;
1330
- return type !== void 0 && containsUnknownType(type) ? [position] : [];
1331
- });
1332
- const reads = parameterVariable(holder, callback, sourceCode)?.references.filter((reference) => !reference.init);
1333
- if (reads === void 0) return false;
1334
- const calls = reads.filter((reference) => !isExistenceTest(reference.identifier));
1335
- return calls.length > 0 && calls.every((reference) => {
1336
- const call = reference.identifier.parent;
1337
- return call.type === "CallExpression" && call.callee === reference.identifier && passesCaughtValues(call, unknownPositions, sourceCode);
1338
- });
1339
- }
1340
- //#endregion
1341
- //#region src/oxc/anti-slop/shared/parse-boundary.ts
1342
- /** Callee names that read as a decoder: `parse`, `safeParse` and their `Async` forms, `decode`, and `parseX` and `decodeX` in either case. */
1343
- const DECODER_NAME = /^(?:safeParse(?:Async)?|[Pp]arse(?:[A-Z]\w*)?|[Dd]ecode(?:[A-Z]\w*)?)$/;
1344
- /** Packages whose exports are schemas or decoders. A subpath such as `zod/v4` counts as its package. */
1345
- const SCHEMA_LIBRARIES = [
1346
- "zod",
1347
- "valibot",
1348
- "yup",
1349
- "joi",
1350
- "superstruct",
1351
- "io-ts",
1352
- "@sinclair/typebox",
1353
- "arktype",
1354
- "effect",
1355
- "@effect/schema"
1356
- ];
1357
- /** Calls that write properties of the object they are handed first. */
1358
- const PROPERTY_WRITERS = /* @__PURE__ */ new Set([
1359
- "Object.assign",
1360
- "Object.defineProperty",
1361
- "Object.defineProperties",
1362
- "Object.setPrototypeOf",
1363
- "Reflect.set",
1364
- "Reflect.defineProperty",
1365
- "Reflect.setPrototypeOf"
1366
- ]);
1367
- const PROMISE_TYPES = /* @__PURE__ */ new Set(["Promise", "PromiseLike"]);
1368
- /** Return the name a call is made by: an identifier callee's name, or a non-computed member callee's property name. */
1369
- function calleeName(call) {
1370
- const { callee } = call;
1371
- if (callee.type === "Identifier") return callee.name;
1372
- return callee.type === "MemberExpression" && !callee.computed && callee.property.type === "Identifier" ? callee.property.name : null;
1373
- }
1374
- /** Return the initializer of the single-name `const` a variable declares. */
1375
- function constInitializerOf(variable) {
1376
- const declarator = variable?.defs[0]?.node;
1377
- return declarator?.type === "VariableDeclarator" && declarator.id.type === "Identifier" && declarator.parent.type === "VariableDeclaration" && declarator.parent.kind === "const" ? declarator.init : null;
1378
- }
1379
- function isSchemaLibrary(source) {
1380
- return SCHEMA_LIBRARIES.some((library) => source === library || source.startsWith(`${library}/`));
1381
- }
1382
- /** Return the `a.b` name of a non-computed member callee, or null. */
1383
- function dottedName(node) {
1384
- return node.type === "MemberExpression" && !node.computed && node.object.type === "Identifier" && node.property.type === "Identifier" ? `${node.object.name}.${node.property.name}` : null;
1385
- }
1386
- /** Return whether a call is one of `PROPERTY_WRITERS`, such as `Object.assign`, which write properties of the object they are handed first. */
1387
- function writesProperties(call) {
1388
- return PROPERTY_WRITERS.has(dottedName(call.callee) ?? "");
1389
- }
1390
- /** Return the outermost member expression a reference is the object of, or the reference itself. */
1391
- function memberChainTop(identifier) {
1392
- let current = identifier;
1393
- while (current.parent?.type === "MemberExpression" && current.parent.object === current) current = current.parent;
1394
- return current;
1395
- }
1396
- /**
1397
- * Return whether this file writes a property of a variable's value: an assignment, update or `delete` on a member read from it,
1398
- * or a call such as `Object.assign` handed it first. A write through another name is not seen.
1399
- */
1400
- function hasPropertyWrites(variable) {
1401
- return variable.references.some(({ identifier }) => {
1402
- const top = memberChainTop(identifier);
1403
- const holder = top.parent;
1404
- if (holder === null) return false;
1405
- if (top !== identifier) {
1406
- if (holder.type === "AssignmentExpression" && holder.left === top) return true;
1407
- if (holder.type === "UpdateExpression") return true;
1408
- if (holder.type === "UnaryExpression" && holder.operator === "delete") return true;
1409
- }
1410
- return holder.type === "CallExpression" && holder.arguments[0] === top && writesProperties(holder);
1411
- });
1412
- }
1413
- /** Return whether a variable is an import from a schema library, or a `const` whose initializer is rooted at one. */
1414
- function isSchemaVariable(variable, sourceCode, seen) {
1415
- const [definition, ...others] = variable.defs;
1416
- if (definition === void 0 || others.length > 0 || seen.has(variable) || hasPropertyWrites(variable)) return false;
1417
- if (variable.references.some((reference) => reference.isWrite() && !reference.init)) return false;
1418
- if (definition.type === "ImportBinding") {
1419
- const declaration = definition.parent;
1420
- return declaration?.type === "ImportDeclaration" && isSchemaLibrary(declaration.source.value);
1421
- }
1422
- const initializer = constInitializerOf(variable);
1423
- return initializer !== null && isRootedAtSchemaLibrary(initializer, sourceCode, /* @__PURE__ */ new Set([...seen, variable]));
1424
- }
1425
- /** Return whether a value is read, through members, calls, type wrappers and `const` aliases, from a schema library's import. */
1426
- function isRootedAtSchemaLibrary(node, sourceCode, seen) {
1427
- switch (node.type) {
1428
- case "TSAsExpression":
1429
- case "TSSatisfiesExpression":
1430
- case "TSNonNullExpression":
1431
- case "TSTypeAssertion":
1432
- case "ChainExpression": return isRootedAtSchemaLibrary(node.expression, sourceCode, seen);
1433
- case "MemberExpression": return isRootedAtSchemaLibrary(node.object, sourceCode, seen);
1434
- case "CallExpression": return isRootedAtSchemaLibrary(node.callee, sourceCode, seen);
1435
- case "Identifier": {
1436
- const variable = variableOf(node, sourceCode);
1437
- return variable !== null && isSchemaVariable(variable, sourceCode, seen);
1438
- }
1439
- default: return false;
1440
- }
1441
- }
1442
- /**
1443
- * Return the decoder call whose direct argument a reference is: a call of a decoder name read from a schema library's import.
1444
- * An `unknown` value is not callable, so it is never the callee. A decoder of any other origin can do anything with the value.
1445
- */
1446
- function decoderCallOf(identifier, sourceCode) {
1447
- const call = identifier.parent;
1448
- return call.type === "CallExpression" && DECODER_NAME.test(calleeName(call) ?? "") && isRootedAtSchemaLibrary(call.callee, sourceCode, /* @__PURE__ */ new Set()) ? call : null;
1449
- }
1450
- /** Return the type a declared return type hands back, read through `Promise<T>` and `PromiseLike<T>`. */
1451
- function promisedType(annotation) {
1452
- const type = annotation?.typeAnnotation;
1453
- if (type === void 0) return void 0;
1454
- return type.type === "TSTypeReference" && type.typeName.type === "Identifier" && PROMISE_TYPES.has(type.typeName.name) ? type.typeArguments?.params[0] : type;
1455
- }
1456
- /** Return whether a declared return type states a value, not `unknown` or `any`, promised or not. */
1457
- function declaresParsedType(annotation) {
1458
- const promised = promisedType(annotation);
1459
- return promised !== void 0 && promised.type !== "TSAnyKeyword" && !containsUnknownType(promised);
1460
- }
1461
- /** Strip what leaves a decoder's result the parsed value: `await` and the `.data` of a safe parse. */
1462
- function parsedSource(node) {
1463
- if (node.type === "AwaitExpression") return parsedSource(node.argument);
1464
- return node.type === "MemberExpression" && !node.computed && node.property.type === "Identifier" && node.property.name === "data" ? parsedSource(node.object) : node;
1465
- }
1466
- /** Names that read a parameter without a reference to it: the `arguments` object, and a direct `eval` that can name it in a string. */
1467
- const IMPLICIT_READERS = /* @__PURE__ */ new Set(["arguments", "eval"]);
1468
- /** Return the expressions a function hands back: an arrow's expression body, or what its `return` statements return. */
1469
- function returnedExpressions(owner, returns) {
1470
- if (owner.body === null || owner.body === void 0) return [];
1471
- return owner.body.type === "BlockStatement" ? returns.map((statement) => statement.argument) : [owner.body];
1472
- }
1473
- /**
1474
- * Return whether a parameter typed exactly `unknown` is a parse boundary: every read of it is a direct argument
1475
- * to a decoder read from a schema library, every value the function returns is such a call's result,
1476
- * and the function declares a return type that states what it parsed. A function that stores, forwards, reads
1477
- * by hand (through `arguments` or `eval` too) or discards the parsed value is not one.
1478
- */
1479
- function decodesParameterIntoResult(owner, name, annotated, facts, sourceCode) {
1480
- if (annotated.type !== "TSUnknownKeyword" || facts.readsImplicitly || !declaresParsedType(owner.returnType)) return false;
1481
- const reads = sourceCode.getDeclaredVariables(owner).find((variable) => variable.name === name && variable.defs[0]?.type === "Parameter")?.references.filter((reference) => !reference.init);
1482
- const decoders = new Set(reads?.map((reference) => decoderCallOf(reference.identifier, sourceCode)));
1483
- if (decoders.has(null)) return false;
1484
- const results = returnedExpressions(owner, facts.returns);
1485
- return results.length > 0 && results.every((result) => {
1486
- if (result === null) return false;
1487
- const source = parsedSource(result);
1488
- if (source.type !== "Identifier") return decoders.has(source);
1489
- const initializer = constInitializerOf(variableOf(source, sourceCode));
1490
- return initializer !== null && decoders.has(parsedSource(initializer));
1491
- });
1492
- }
1493
- //#endregion
1494
- //#region src/oxc/anti-slop/shared/guarded-reads.ts
1495
- /** No type test on the parameter holds. */
1496
- const UNTESTED = 0;
1497
- /** A type test holds that leaves a type TypeScript lets into a narrower one unchecked: `any[]`, a class with `any` type arguments, `object`, `Function`. */
1498
- const LOOSE = 1;
1499
- /** A type test holds that leaves a primitive, or the type a predicate names. */
1500
- const PRECISE = 2;
1501
- /** Return what holds where two tests both hold: the narrower of the two. */
1502
- function narrower(first, second) {
1503
- return first > second ? first : second;
1504
- }
1505
- /** Return what holds where one of two tests holds: the looser of the two. */
1506
- function looser(first, second) {
1507
- return first < second ? first : second;
1508
- }
1509
- const NONE = {
1510
- truthy: UNTESTED,
1511
- falsy: UNTESTED
1512
- };
1513
- /** Names an imported function is trusted as a type guard by: `isX` or `IsX`, called with one argument. TypeScript rejects a narrowed read after one that is not a predicate. */
1514
- const IMPORTED_GUARD_NAME = /^[Ii]s[A-Z0-9_$]/;
1515
- /** What `typeof` answers for a primitive, which a test against it narrows to precisely. `"object"` and `"function"` leave `object` and `Function`. */
1516
- const PRIMITIVE_TYPEOF = /* @__PURE__ */ new Set([
1517
- "bigint",
1518
- "boolean",
1519
- "number",
1520
- "string",
1521
- "symbol",
1522
- "undefined"
1523
- ]);
1524
- const EQUALITY = /* @__PURE__ */ new Set([
1525
- "===",
1526
- "!==",
1527
- "==",
1528
- "!="
1529
- ]);
1530
- const POSITIVE_EQUALITY = /* @__PURE__ */ new Set(["===", "=="]);
1531
- /** Nodes a test outside does not narrow inside: a function declaration, hoisted above the test, and a class body with its methods, accessors and property initializers. */
1532
- const NARROWING_BARRIERS = /* @__PURE__ */ new Set(["FunctionDeclaration", "ClassBody"]);
1533
- /** Parents that change the type a read is seen at. A read under one of them is never accepted. */
1534
- const CASTS = /* @__PURE__ */ new Set([
1535
- "TSAsExpression",
1536
- "TSTypeAssertion",
1537
- "TSSatisfiesExpression",
1538
- "TSNonNullExpression"
1539
- ]);
1540
- /** Return whether a node is the non-computed member `object.property` of a global `object` no binding of the file shadows. */
1541
- function isGlobalMember(node, object, property, sourceCode) {
1542
- return node.type === "MemberExpression" && !node.computed && node.object.type === "Identifier" && node.object.name === object && isGlobalName(node.object, sourceCode) && node.property.type === "Identifier" && node.property.name === property;
1543
- }
1544
- /**
1545
- * Return how a call narrows its argument at `position`: loosely for `Array.isArray`, which leaves `any[]`; precisely for a
1546
- * function declared in this file whose type predicate names the parameter at that position, and for an `isX` imported from
1547
- * another module called with that argument alone.
1548
- */
1549
- function guardPrecision(call, position, sourceCode) {
1550
- const { callee } = call;
1551
- if (isGlobalMember(callee, "Array", "isArray", sourceCode)) return position === 0 ? LOOSE : UNTESTED;
1552
- if (callee.type !== "Identifier") return UNTESTED;
1553
- const declared = declaredFunctionOf(callee, sourceCode);
1554
- if (declared !== null) return guardsParameterAt(declared, position) ? PRECISE : UNTESTED;
1555
- return variableOf(callee, sourceCode)?.defs[0]?.type === "ImportBinding" && position === 0 && call.arguments.length === 1 && IMPORTED_GUARD_NAME.test(callee.name) ? PRECISE : UNTESTED;
1556
- }
1557
- /** Return whether a call is a type guard on its argument at `position`, see `guardPrecision`. */
1558
- function guardsArgument(call, position, sourceCode) {
1559
- return guardPrecision(call, position, sourceCode) !== UNTESTED;
1560
- }
1561
- /** Return how a comparison of `typeof` of the parameter with a string literal narrows it: precisely to a primitive, loosely otherwise. */
1562
- function typeofPrecision(test, reads) {
1563
- const sides = [test.left, test.right];
1564
- if (!sides.some((side) => side.type === "UnaryExpression" && side.operator === "typeof" && reads.references.has(side.argument))) return UNTESTED;
1565
- const named = sides.flatMap((side) => side.type === "Literal" && typeof side.value === "string" ? [side.value] : []);
1566
- if (named.length === 0) return UNTESTED;
1567
- return named.every((each) => PRIMITIVE_TYPEOF.has(each)) ? PRECISE : LOOSE;
1568
- }
1569
- function binaryNarrowing(test, reads) {
1570
- if (test.operator === "instanceof") return reads.references.has(test.left) ? {
1571
- truthy: LOOSE,
1572
- falsy: UNTESTED
1573
- } : NONE;
1574
- if (!EQUALITY.has(test.operator)) return NONE;
1575
- const precision = typeofPrecision(test, reads);
1576
- return POSITIVE_EQUALITY.has(test.operator) ? {
1577
- truthy: precision,
1578
- falsy: UNTESTED
1579
- } : {
1580
- truthy: UNTESTED,
1581
- falsy: precision
1582
- };
1583
- }
1584
- /**
1585
- * Return how a test narrows the parameter. A guard call, `instanceof` and `typeof p === "lit"` narrow where they hold;
1586
- * `!`, `typeof p !== "lit"` and the `&&` and `||` that join tests carry that through. A comparison with `null` narrows nowhere.
1587
- */
1588
- function narrowingOf(test, reads) {
1589
- switch (test.type) {
1590
- case "UnaryExpression": {
1591
- if (test.operator !== "!") return NONE;
1592
- const inner = narrowingOf(test.argument, reads);
1593
- return {
1594
- truthy: inner.falsy,
1595
- falsy: inner.truthy
1596
- };
1597
- }
1598
- case "LogicalExpression": {
1599
- const left = narrowingOf(test.left, reads);
1600
- const right = narrowingOf(test.right, reads);
1601
- if (test.operator === "&&") return {
1602
- truthy: narrower(left.truthy, right.truthy),
1603
- falsy: looser(left.falsy, right.falsy)
1604
- };
1605
- if (test.operator === "||") return {
1606
- truthy: looser(left.truthy, right.truthy),
1607
- falsy: narrower(left.falsy, right.falsy)
1608
- };
1609
- return NONE;
1610
- }
1611
- case "CallExpression": return {
1612
- truthy: test.arguments.reduce((found, argument, position) => reads.references.has(argument) ? narrower(found, guardPrecision(test, position, reads.sourceCode)) : found, UNTESTED),
1613
- falsy: UNTESTED
1614
- };
1615
- case "BinaryExpression": return binaryNarrowing(test, reads);
1616
- default: return NONE;
1617
- }
1618
- }
1619
- /** Return whether a statement always leaves its function: a `return` or `throw`, or a block that ends in one. */
1620
- function exits(statement) {
1621
- if (statement?.type === "BlockStatement") return exits(statement.body.at(-1));
1622
- return statement?.type === "ReturnStatement" || statement?.type === "ThrowStatement";
1623
- }
1624
- /** Return how the `if`s with no `else` before a statement of a block, which leave the function unless a test holds, narrow the parameter there. */
1625
- function exitingGuardNarrowing(block, statement, reads) {
1626
- const index = block.body.findIndex((each) => each === statement);
1627
- return block.body.slice(0, index).reduce((found, earlier) => earlier.type === "IfStatement" && earlier.alternate === null && exits(earlier.consequent) ? narrower(found, narrowingOf(earlier.test, reads).falsy) : found, UNTESTED);
1628
- }
1629
- /** Return how `parent` narrows the parameter for its part `child`: a branch, the right of `&&` or `||`, or a statement after an exiting guard. */
1630
- function partNarrowing(parent, child, reads) {
1631
- switch (parent.type) {
1632
- case "IfStatement":
1633
- case "ConditionalExpression":
1634
- if (child === parent.consequent) return narrowingOf(parent.test, reads).truthy;
1635
- return child === parent.alternate ? narrowingOf(parent.test, reads).falsy : UNTESTED;
1636
- case "LogicalExpression":
1637
- if (child !== parent.right) return UNTESTED;
1638
- if (parent.operator === "&&") return narrowingOf(parent.left, reads).truthy;
1639
- return parent.operator === "||" ? narrowingOf(parent.left, reads).falsy : UNTESTED;
1640
- case "BlockStatement": return exitingGuardNarrowing(parent, child, reads);
1641
- default: return UNTESTED;
1642
- }
1643
- }
1644
- /** Return how the tests that hold at a read narrow the parameter, in the owner or an arrow, function expression or object method inside it. */
1645
- function narrowingAt(read, reads) {
1646
- let found = UNTESTED;
1647
- for (let child = read; child !== reads.owner && child.parent !== null && !NARROWING_BARRIERS.has(child.type); child = child.parent) found = narrower(found, partNarrowing(child.parent, child, reads));
1648
- return found;
1649
- }
1650
- /** Return the expression a read's value leaves by: the read, or the `?:` branch, `&&`, `||`, `??` or `await` it flows out through. */
1651
- function outflowOf(read) {
1652
- let value = read;
1653
- while (value.parent !== null && (value.parent.type === "LogicalExpression" || value.parent.type === "AwaitExpression" || value.parent.type === "ConditionalExpression" && value.parent.test !== value)) value = value.parent;
1654
- return value;
1655
- }
1656
- /**
1657
- * Return whether a read hands its value on where TypeScript lets a loose type in unchecked: returned, yielded, called,
1658
- * constructed, assigned, or held in a `const` with no annotation.
1659
- */
1660
- function handsOnLooseValue(read) {
1661
- const value = outflowOf(read);
1662
- const holder = value.parent;
1663
- switch (holder?.type) {
1664
- case "ReturnStatement":
1665
- case "YieldExpression": return true;
1666
- case "ArrowFunctionExpression": return holder.body === value;
1667
- case "CallExpression":
1668
- case "NewExpression": return holder.callee === value;
1669
- case "TaggedTemplateExpression": return holder.tag === value;
1670
- case "AssignmentExpression":
1671
- case "AssignmentPattern": return holder.right === value;
1672
- case "VariableDeclarator": return holder.init === value && holder.id.typeAnnotation?.typeAnnotation === void 0;
1673
- default: return false;
1674
- }
1675
- }
1676
- /**
1677
- * A read that sits where a type test on the parameter holds, in the owner or a closure inside it. Under a precise test any use
1678
- * is accepted there; under a loose one, any use that does not hand the value on as is.
1679
- */
1680
- function isNarrowedRead(read, reads) {
1681
- const precision = narrowingAt(read, reads);
1682
- return precision === PRECISE || precision === LOOSE && !handsOnLooseValue(read);
1683
- }
1684
- /** A read a type test is made of: a guard's argument, the left of `instanceof`, or the operand of `typeof`. */
1685
- function isTypeTestOperand(read, reads) {
1686
- const user = read.parent;
1687
- switch (user.type) {
1688
- case "CallExpression": return guardsArgument(user, user.arguments.findIndex((argument) => argument === read), reads.sourceCode);
1689
- case "BinaryExpression": return user.operator === "instanceof" && user.left === read;
1690
- case "UnaryExpression": return user.operator === "typeof";
1691
- default: return false;
1692
- }
1693
- }
1694
- /** A read compared with `===`, `!==`, `==` or `!=`, which answers a boolean and narrows nothing this rule follows. */
1695
- function isEqualityOperand(read) {
1696
- return read.parent.type === "BinaryExpression" && EQUALITY.has(read.parent.operator);
1697
- }
1698
- /** A read passed back to the function itself at the parameter's own position, with no spread before it, so the same check judges it there. */
1699
- function isRecursiveArgument(read, reads) {
1700
- const user = read.parent;
1701
- return user.type === "CallExpression" && user.arguments[reads.position] === read && user.arguments.slice(0, reads.position).every((argument) => argument.type !== "SpreadElement") && declaredFunctionOf(user.callee, reads.sourceCode) === reads.owner;
1702
- }
1703
- /** Return whether a callee is the global `String` or `JSON.stringify`, which take any value and return text. */
1704
- function convertsToText(callee, sourceCode) {
1705
- return callee.type === "Identifier" && callee.name === "String" && isGlobalName(callee, sourceCode) || isGlobalMember(callee, "JSON", "stringify", sourceCode);
1706
- }
1707
- /** A read handed as is, as the first argument, to the global `String(...)` or `JSON.stringify(...)`. */
1708
- function isTotalStringConversion(read, reads) {
1709
- const user = read.parent;
1710
- return user.type === "CallExpression" && user.arguments[0] === read && convertsToText(user.callee, reads.sourceCode);
1711
- }
1712
- /** The positions a read of an unknown parameter may take without leaving it unparsed. */
1713
- const ALLOWED_READS = [
1714
- isTypeTestOperand,
1715
- isEqualityOperand,
1716
- isRecursiveArgument,
1717
- isTotalStringConversion,
1718
- isNarrowedRead,
1719
- (read, reads) => reads.forwards(read)
1720
- ];
1721
- /** Return the declarator a read's value initializes, through the branches of `?:`, the operands of `&&`, `||` and `??`, and `await`. */
1722
- function declaratorHolding(read) {
1723
- const value = outflowOf(read);
1724
- const holder = value.parent;
1725
- return holder?.type === "VariableDeclarator" && holder.init === value ? holder : null;
1726
- }
1727
- /** Return whether a type states only that a value is an array, claiming nothing of its items: `unknown[]` or `readonly unknown[]`. */
1728
- function isUnknownArray(type) {
1729
- if (type.type === "TSTypeOperator" && type.operator === "readonly") return isUnknownArray(type.typeAnnotation);
1730
- return type.type === "TSArrayType" && type.elementType.type === "TSUnknownKeyword";
1731
- }
1732
- /**
1733
- * Return whether a read is recast: wrapped in `as`, `<T>`, `satisfies` or `!`, directly or around the `?:`, `&&`, `||`,
1734
- * `??` or `await` it flows out through, or held in a `let`, a `var`, or a `const` annotated with a type other than
1735
- * `unknown[]`. TypeScript lets an `object` into a type whose members are all optional without checking one of them, so such
1736
- * an annotation is a cast.
1737
- */
1738
- function isRecast(read) {
1739
- if (CASTS.has(read.parent.type) || CASTS.has(outflowOf(read).parent?.type ?? "")) return true;
1740
- const declarator = declaratorHolding(read);
1741
- if (declarator === null) return false;
1742
- const declared = declarator.id.typeAnnotation?.typeAnnotation;
1743
- const declaration = declarator.parent;
1744
- return declaration.type !== "VariableDeclaration" || declaration.kind !== "const" || declared !== void 0 && !isUnknownArray(declared);
1745
- }
1746
- /** Union members that leave a verdict a verdict: `boolean | undefined` still answers yes, no or nothing. */
1747
- const NO_ANSWER_TYPES = /* @__PURE__ */ new Set([
1748
- "TSUndefinedKeyword",
1749
- "TSNullKeyword",
1750
- "TSVoidKeyword"
1751
- ]);
1752
- /**
1753
- * Return whether a declared return type answers yes or no about the input rather than hand back a value parsed from it:
1754
- * `boolean`, `true` or `false`, a type predicate or `asserts` clause on any parameter, or a union of them, also with
1755
- * `undefined`, `null` or `void`.
1756
- */
1757
- function answersVerdict(type) {
1758
- switch (type.type) {
1759
- case "TSBooleanKeyword":
1760
- case "TSTypePredicate": return true;
1761
- case "TSLiteralType": return type.literal.type === "Literal" && typeof type.literal.value === "boolean";
1762
- case "TSUnionType": return type.types.some(answersVerdict) && type.types.every((member) => answersVerdict(member) || NO_ANSWER_TYPES.has(member.type));
1763
- case "TSParenthesizedType": return answersVerdict(type.typeAnnotation);
1764
- default: return false;
1765
- }
1766
- }
1767
- /** Return whether a function declares that it hands back a value parsed from its input: not `unknown`, `any`, `void` or a verdict, promised or not. */
1768
- function handsBackParsedValue(owner) {
1769
- const handed = promisedType(owner.returnType);
1770
- return handed !== void 0 && handed.type !== "TSVoidKeyword" && !answersVerdict(handed) && declaresParsedType(owner.returnType);
1771
- }
1772
- /**
1773
- * Return the reads of a parameter typed exactly `unknown` of a function with a body, when the function never reassigns it and
1774
- * never mentions `arguments` or `eval`, and reads it at least once. Return null otherwise.
1775
- */
1776
- function unknownParameterReads(owner, name, annotated, facts, sourceCode) {
1777
- if (annotated.type !== "TSUnknownKeyword" || facts.readsImplicitly || owner.body === null || owner.body === void 0) return null;
1778
- const parameter = sourceCode.getDeclaredVariables(owner).find((variable) => variable.name === name && variable.defs[0]?.type === "Parameter");
1779
- if (parameter === void 0 || parameter.references.some((reference) => reference.isWrite() && !reference.init)) return null;
1780
- const identifiers = parameter.references.filter((reference) => !reference.init).map((reference) => reference.identifier);
1781
- return identifiers.length > 0 ? identifiers : null;
1782
- }
1783
- /**
1784
- * Return whether a parameter typed exactly `unknown` is only classified: the function declares a return type other than
1785
- * `unknown`, `any`, `void` or a verdict, never reassigns the parameter, never mentions `arguments` or `eval`, tests the
1786
- * parameter's type or converts it to text at least once, and reads it each time as a type test's operand, a side of an
1787
- * equality, an argument to itself at its own position, the first argument of `String` or `JSON.stringify`, or where a type
1788
- * test on it holds, short of handing the value on as is where only a loose test holds. A recast of it anywhere, or a property
1789
- * read, a call argument or a store where no type test holds, is not one.
1790
- */
1791
- function readsOnlyThroughGuards(owner, name, annotated, facts, { sourceCode, forwards }) {
1792
- const identifiers = handsBackParsedValue(owner) ? unknownParameterReads(owner, name, annotated, facts, sourceCode) : null;
1793
- if (identifiers === null) return false;
1794
- const reads = {
1795
- owner,
1796
- position: argumentParameters(owner).findIndex((parameter) => functionParameterBindingName(parameter, sourceCode) === name),
1797
- references: new Set(identifiers),
1798
- sourceCode,
1799
- forwards
1800
- };
1801
- const tested = identifiers.some((read) => isTypeTestOperand(read, reads));
1802
- const converted = identifiers.some((read) => isTotalStringConversion(read, reads));
1803
- return (tested || converted && !identifiers.some(forwards)) && identifiers.every((read) => !isRecast(read) && ALLOWED_READS.some((allowed) => allowed(read, reads)));
1804
- }
1805
- //#endregion
1806
- //#region src/oxc/anti-slop/shared/forward-only.ts
1807
- /** Callee names that read as a validator: `assert` and `validate`, and `assertX` and `validateX`. */
1808
- const VALIDATOR_NAME = /^(?:[Aa]ssert|[Vv]alidate)(?:[A-Z]\w*)?$/;
1809
- /** Methods that keep a value in a collection. A call of one stores the value instead of handing it on. */
1810
- const STORE_METHODS = /* @__PURE__ */ new Set([
1811
- "add",
1812
- "push",
1813
- "set",
1814
- "splice",
1815
- "unshift"
1816
- ]);
1817
- /** Return the object a member callee is read from, through further members, calls and type wrappers: `this` for `this.a?.b`, `p` for `p.a().b`. */
1818
- function rootOf(node) {
1819
- switch (node.type) {
1820
- case "MemberExpression": return rootOf(node.object);
1821
- case "CallExpression": return rootOf(node.callee);
1822
- case "ChainExpression":
1823
- case "TSAsExpression":
1824
- case "TSNonNullExpression":
1825
- case "TSSatisfiesExpression":
1826
- case "TSTypeAssertion": return rootOf(node.expression);
1827
- default: return node;
1828
- }
1829
- }
1830
- /**
1831
- * Return whether a value is rooted at a parameter, which would make a member of it a callee the caller hands in: read from a
1832
- * parameter, or from a variable whose initializer, destructuring source or assigned value is rooted at one, transitively, through
1833
- * either operand of `&&`, `||` and `??`, either branch of `?:`, and `await`.
1834
- */
1835
- function isRootedAtParameter(node, sourceCode, seen) {
1836
- const root = rootOf(node);
1837
- const rooted = (each) => isRootedAtParameter(each, sourceCode, seen);
1838
- if (root.type === "LogicalExpression") return rooted(root.left) || rooted(root.right);
1839
- if (root.type === "ConditionalExpression") return rooted(root.consequent) || rooted(root.alternate);
1840
- if (root.type === "AwaitExpression") return rooted(root.argument);
1841
- const variable = root.type === "Identifier" ? variableOf(root, sourceCode) : null;
1842
- if (variable === null || seen.has(variable)) return false;
1843
- if (variable.defs[0]?.type === "Parameter") return true;
1844
- const traced = /* @__PURE__ */ new Set([...seen, variable]);
1845
- return writtenValues(variable).some((value) => isRootedAtParameter(value, sourceCode, traced));
1846
- }
1847
- /** Return the values a variable is initialized, destructured or assigned from. oxlint leaves `writeExpr` undefined on a read, so only writes are asked. */
1848
- function writtenValues(variable) {
1849
- return variable.references.flatMap((reference) => reference.isWrite() && reference.writeExpr ? [reference.writeExpr] : []);
1850
- }
1851
- /** Return whether a function declared in this file declares its parameter at `position` exactly `unknown`. */
1852
- function takesUnknownAt(callee, position) {
1853
- const parameter = argumentParameters(callee)[position];
1854
- return parameter !== void 0 && parameter.type !== "RestElement" && functionParameterTypeAnnotation(parameter)?.typeAnnotation.type === "TSUnknownKeyword";
1855
- }
1856
- /**
1857
- * Return whether a call may take a forward at `position`: a member call that is not a collection store, not a property writer
1858
- * such as `Object.assign`, and not rooted at a parameter, which would be a callee the caller hands in; an imported function; or
1859
- * a function this file declares whose parameter there is exactly `unknown` and exempt from this rule. A forward back to a
1860
- * parameter still under judgment is not exempt.
1861
- */
1862
- function reachesTrustedCallee(call, position, targets) {
1863
- const { callee } = call;
1864
- const { sourceCode } = targets;
1865
- if (callee.type === "MemberExpression") {
1866
- if (STORE_METHODS.has(calleeName(call) ?? "") || writesProperties(call)) return false;
1867
- return !isRootedAtParameter(callee, sourceCode, /* @__PURE__ */ new Set());
1868
- }
1869
- if (callee.type !== "Identifier") return false;
1870
- const declared = declaredFunctionOf(callee, sourceCode);
1871
- if (declared !== null) return takesUnknownAt(declared, position) && targets.accepts(declared, position);
1872
- const variable = variableOf(callee, sourceCode);
1873
- if (variable?.defs[0]?.type === "ImportBinding") return true;
1874
- return variable !== null && holdsBuiltFunction(variable, sourceCode) && !isRootedAtParameter(callee, sourceCode, /* @__PURE__ */ new Set());
1875
- }
1876
- /** Return the expression under `await` and the type wrappers `as`, `<T>`, `satisfies` and `!`. */
1877
- function unwrapped(node) {
1878
- switch (node.type) {
1879
- case "AwaitExpression": return unwrapped(node.argument);
1880
- case "TSAsExpression":
1881
- case "TSNonNullExpression":
1882
- case "TSSatisfiesExpression":
1883
- case "TSTypeAssertion": return unwrapped(node.expression);
1884
- default: return node;
1885
- }
1886
- }
1887
- /** Return whether a value is `null` or the global `undefined`, which a lazily built callee starts as. */
1888
- function isNothing(node, sourceCode) {
1889
- return node.type === "Literal" && node.value === null || node.type === "Identifier" && node.name === "undefined" && isGlobalName(node, sourceCode);
1890
- }
1891
- /** Return whether a variable is bound by the head of a `for...of` or `for...in` loop, which writes it an element of what it iterates. */
1892
- function isLoopBinding(variable) {
1893
- return variable.defs.some(({ node }) => node.type === "VariableDeclarator" && (node.parent.parent?.type === "ForOfStatement" || node.parent.parent?.type === "ForInStatement"));
1894
- }
1895
- /**
1896
- * Return whether a variable holds a function another owner built and this file does not write: every value it is initialized,
1897
- * destructured or assigned from is a call's result, or `null` or `undefined` before one, and at least one is a call. A function
1898
- * literal, an alias or any other value is not one.
1899
- */
1900
- function holdsBuiltFunction(variable, sourceCode) {
1901
- if (isLoopBinding(variable)) return false;
1902
- const values = writtenValues(variable).map(unwrapped);
1903
- return values.some((value) => value.type === "CallExpression") && values.every((value) => value.type === "CallExpression" || isNothing(value, sourceCode));
1904
- }
1905
- /**
1906
- * Return whether a read is handed on unread: a direct argument, not the callee, of a call that reaches a trusted callee and is
1907
- * not a type guard, the global `String` or `JSON.stringify`, or a decoder or validator by name, which the parse-boundary
1908
- * exemption judges.
1909
- */
1910
- function isForward(read, targets) {
1911
- const call = read.parent;
1912
- if (call.type !== "CallExpression") return false;
1913
- const position = call.arguments.findIndex((argument) => argument === read);
1914
- if (position < 0 || convertsToText(call.callee, targets.sourceCode) || guardsArgument(call, position, targets.sourceCode)) return false;
1915
- const name = calleeName(call) ?? "";
1916
- if (DECODER_NAME.test(name) || VALIDATOR_NAME.test(name)) return false;
1917
- return reachesTrustedCallee(call, position, targets);
1918
- }
1919
- /**
1920
- * Return whether a parameter typed exactly `unknown` is only forwarded: every read of it is a direct argument of a call that
1921
- * takes `unknown` there, the function never reassigns it and never mentions `arguments` or `eval`, and it declares a return
1922
- * type other than `unknown`, `any` or a verdict (see `answersVerdict`), promised or not. A callee this file declares must
1923
- * declare that parameter exactly `unknown` and have it exempt. A member call or an imported callee is trusted unseen:
1924
- * TypeScript rejects an `unknown` argument to any parameter narrower than `unknown` or `any`. One whose parameter is `any` is
1925
- * not caught.
1926
- */
1927
- function forwardsOnly(owner, name, annotated, facts, targets) {
1928
- const handed = promisedType(owner.returnType);
1929
- if (handed === void 0 || answersVerdict(handed) || !declaresParsedType(owner.returnType)) return false;
1930
- const reads = unknownParameterReads(owner, name, annotated, facts, targets.sourceCode);
1931
- return reads !== null && reads.every((read) => isForward(read, targets));
1932
- }
1933
- //#endregion
1934
1076
  //#region src/oxc/anti-slop/rules/no-unknown-parameters.ts
1935
1077
  function isTypePredicateSubject(owner, parameterName) {
1936
1078
  const predicate = owner.returnType?.typeAnnotation;
@@ -1976,129 +1118,45 @@ function isRejectFunctionType(owner) {
1976
1118
  return holder.type === "Identifier" && (holder.name === "reject" || isPromiseExecutorReject(holder));
1977
1119
  }
1978
1120
  /** Return whether a parameter is exempt whatever its name: `this`, a boundary-decorated request value, or a promise rejection reason. */
1979
- function isExemptPosition(owner, parameter, sourceCode) {
1121
+ function isExemptPosition(owner, parameter) {
1980
1122
  if (isThisParameter(parameter) || hasBoundaryDecorator(parameter)) return true;
1981
1123
  if (argumentParameters(owner)[0] === parameter && isRejectionCallback(owner)) return true;
1982
- return isRejectFunctionType(owner) || owner.type === "TSFunctionType" && isCaughtValueCallbackType(owner, sourceCode);
1983
- }
1984
- /** Return whether a parameter typed exactly `unknown` is only probed for a symbol-keyed brand this file creates, see `isBrandProbe`. */
1985
- function probesBrand(owner, name, annotated, facts, sourceCode) {
1986
- if (annotated.type !== "TSUnknownKeyword" || facts.readsImplicitly) return false;
1987
- return isBrandProbe(owner, sourceCode.getDeclaredVariables(owner).find((variable) => variable.name === name && variable.defs[0]?.type === "Parameter"), sourceCode);
1988
- }
1989
- /** The facts of a function the rule did not walk: a signature with no body. */
1990
- const NO_FACTS = {
1991
- returns: [],
1992
- readsImplicitly: false
1993
- };
1124
+ return isRejectFunctionType(owner);
1125
+ }
1994
1126
  /** Disallow unknown inputs except explicitly named error-cause enrichment. */
1995
1127
  const noUnknownParametersRule = defineRule({
1996
1128
  meta: {
1997
1129
  type: "problem",
1998
- docs: { description: "Disallow explicitly unknown function parameters except `cause`, type-predicate subjects, `this`, request values injected by `@JSONBody`, `@JsonBody` or `@Parameter`, promise rejection reasons, the parameter of a callback type that the function only calls with a caught value, a symbol-keyed brand probe, a parameter a function only decodes through a schema or decoder into the value it returns, a parameter a function only reads through type guards, where they hold and short of handing on as is a value only a loose guard narrowed, and through `String` or `JSON.stringify`, to classify it into a declared value other than a yes-or-no verdict or `void`, also beside forwards once one of them is a type test, and a parameter a function only forwards, unread, to member calls not rooted at another parameter, imports, callees a variable holds from another call's result, or exempt same-file parameters that take `unknown`; decode unknown input at its I/O boundary instead." },
1999
- messages: { unknownParameter: "Parameter `{{parameter}}` leaves input unparsed. Accept a named domain type and run the expected schema or parser at the I/O boundary before calling this function, or make this function that parser: pass the parameter only to the schema and return its result under a declared type." }
1130
+ docs: { description: "Disallow explicitly unknown function parameters except `cause`, type-predicate subjects, `this`, request values injected by `@JSONBody`, `@JsonBody` or `@Parameter`, and promise rejection reasons; decode unknown input at its I/O boundary instead." },
1131
+ messages: { unknownParameter: "Parameter `{{parameter}}` leaves input unparsed. Accept a named domain type; run the expected schema or parser at the I/O boundary before calling this function." }
2000
1132
  },
2001
1133
  createOnce(context) {
2002
- const open = [];
2003
- /** The checks of one file, in the order they were met. They run at its end, so a forward is judged by a function declared after it. */
2004
- const pending = [];
2005
- const walked = /* @__PURE__ */ new Map();
2006
- /** The parameters a forward is being judged into. A forward back to one of them is not exempt. */
2007
- const judging = /* @__PURE__ */ new Set();
2008
- /** The verdicts on parameters a forward landed on, so a chain of forwarders judges each parameter once. */
2009
- const verdicts = /* @__PURE__ */ new Map();
2010
- const isExempt = (node, parameter, annotated, facts) => {
2011
- const { sourceCode } = context;
2012
- if (isExemptPosition(node, parameter, sourceCode)) return true;
2013
- const name = functionParameterBindingName(parameter, sourceCode);
2014
- if (name === "cause" || isTypePredicateSubject(node, name)) return true;
2015
- if (!isRuntimeFunction(node)) return false;
2016
- const targets = {
2017
- sourceCode,
2018
- accepts: acceptsForward
2019
- };
2020
- return decodesParameterIntoResult(node, name, annotated, facts, sourceCode) || probesBrand(node, name, annotated, facts, sourceCode) || readsOnlyThroughGuards(node, name, annotated, facts, {
2021
- sourceCode,
2022
- forwards: (read) => isForward(read, targets)
2023
- }) || forwardsOnly(node, name, annotated, facts, targets);
2024
- };
2025
- /** Return whether this rule exempts the parameter at `position` of a function the file declares, so a forward to it hands the value to a parser. */
2026
- const acceptsForward = (callee, position) => {
2027
- const parameter = argumentParameters(callee)[position];
2028
- if (parameter === void 0 || judging.has(parameter)) return false;
2029
- const known = verdicts.get(parameter);
2030
- if (known !== void 0) return known;
2031
- const annotation = functionParameterTypeAnnotation(parameter);
2032
- const facts = walked.get(callee);
2033
- if (annotation === null || annotation === void 0 || facts === void 0) return false;
2034
- judging.add(parameter);
2035
- const exempt = isExempt(callee, parameter, annotation.typeAnnotation, facts);
2036
- judging.delete(parameter);
2037
- verdicts.set(parameter, exempt);
2038
- return exempt;
2039
- };
2040
- const checkParameters = (node, facts) => {
1134
+ const checkParameters = (node) => {
2041
1135
  for (const parameter of node.params) {
2042
1136
  const annotation = functionParameterTypeAnnotation(parameter);
2043
1137
  if (annotation === null || annotation === void 0) continue;
2044
1138
  if (!containsUnknownType(annotation.typeAnnotation)) continue;
2045
- if (isExempt(node, parameter, annotation.typeAnnotation, facts)) continue;
1139
+ if (isExemptPosition(node, parameter)) continue;
1140
+ const name = functionParameterBindingName(parameter, context.sourceCode);
1141
+ if (name === "cause" || isTypePredicateSubject(node, name)) continue;
2046
1142
  context.report({
2047
1143
  node: annotation.typeAnnotation,
2048
1144
  messageId: "unknownParameter",
2049
- data: { parameter: functionParameterBindingName(parameter, context.sourceCode) }
1145
+ data: { parameter: name }
2050
1146
  });
2051
1147
  }
2052
1148
  };
2053
- const checkSignature = (node) => {
2054
- pending.push({
2055
- node,
2056
- facts: NO_FACTS
2057
- });
2058
- };
2059
- const enterFunction = () => {
2060
- open.push({
2061
- returns: [],
2062
- readsImplicitly: false
2063
- });
2064
- };
2065
- const leaveFunction = (node) => {
2066
- const facts = open.pop() ?? NO_FACTS;
2067
- walked.set(node, facts);
2068
- pending.push({
2069
- node,
2070
- facts
2071
- });
2072
- };
2073
1149
  return {
2074
- Program() {
2075
- pending.length = 0;
2076
- walked.clear();
2077
- verdicts.clear();
2078
- },
2079
- "Program:exit"() {
2080
- for (const { node, facts } of pending) checkParameters(node, facts);
2081
- },
2082
- ArrowFunctionExpression: enterFunction,
2083
- FunctionDeclaration: enterFunction,
2084
- FunctionExpression: enterFunction,
2085
- "ArrowFunctionExpression:exit": leaveFunction,
2086
- "FunctionDeclaration:exit": leaveFunction,
2087
- "FunctionExpression:exit": leaveFunction,
2088
- ReturnStatement(node) {
2089
- open.at(-1)?.returns.push(node);
2090
- },
2091
- Identifier(node) {
2092
- if (!IMPLICIT_READERS.has(node.name)) return;
2093
- for (const frame of open) frame.readsImplicitly = true;
2094
- },
2095
- TSCallSignatureDeclaration: checkSignature,
2096
- TSConstructSignatureDeclaration: checkSignature,
2097
- TSConstructorType: checkSignature,
2098
- TSDeclareFunction: checkSignature,
2099
- TSEmptyBodyFunctionExpression: checkSignature,
2100
- TSFunctionType: checkSignature,
2101
- TSMethodSignature: checkSignature
1150
+ ArrowFunctionExpression: checkParameters,
1151
+ FunctionDeclaration: checkParameters,
1152
+ FunctionExpression: checkParameters,
1153
+ TSCallSignatureDeclaration: checkParameters,
1154
+ TSConstructSignatureDeclaration: checkParameters,
1155
+ TSConstructorType: checkParameters,
1156
+ TSDeclareFunction: checkParameters,
1157
+ TSEmptyBodyFunctionExpression: checkParameters,
1158
+ TSFunctionType: checkParameters,
1159
+ TSMethodSignature: checkParameters
2102
1160
  };
2103
1161
  }
2104
1162
  });