@antelopejs/tooling-configs 0.5.8 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +39 -49
- package/dist/{api-CCOiLN3w.mjs → api-BQLrI_S1.mjs} +19 -2
- package/dist/bin/api-diff.mjs +155 -37
- package/dist/bin/body-check.mjs +6 -3
- package/dist/bin/check-size.mjs +1 -1
- package/dist/bin/checks.mjs +1 -1
- package/dist/bin/comment-proof.mjs +3 -5
- package/dist/bin/garden.mjs +86 -34
- package/dist/bin/lease.mjs +314 -26
- package/dist/bin/ratchet.mjs +4 -4
- package/dist/bin/readme-strip.mjs +1 -1
- package/dist/bin/suppressions.mjs +10 -6
- package/dist/bin/sync.mjs +23 -98
- package/dist/bin/triage.mjs +1 -1
- package/dist/bin/verify.mjs +1 -1
- package/dist/{checks-BC-F8bsv.mjs → checks-BefrkjiT.mjs} +729 -25
- package/dist/{docs-compat-Ft1r2sf0.mjs → docs-compat-CSljVi3O.mjs} +13 -8
- package/dist/eslint.d.mts +13 -4
- package/dist/eslint.mjs +48 -6
- package/dist/guardrails-BfGwehVj.mjs +2414 -0
- package/dist/installed-typescript-6MtIWlE4.mjs +84 -0
- package/dist/oxc/anti-slop/index.mjs +541 -34
- package/dist/oxc/guardrails/index.d.mts +1 -1
- package/dist/oxc/guardrails/index.mjs +2 -1854
- package/dist/oxc/lint.d.mts +10 -1
- package/dist/oxc/lint.mjs +13 -5
- package/dist/{oxlint-CCOJqj3d.mjs → oxlint-CkHhK5K_.mjs} +33 -11
- package/dist/{package-DnxZ2CXZ.mjs → package-DDG3YH7W.mjs} +10 -5
- package/dist/{ports-DGP6bPJy.mjs → ports-DAeEJsYh.mjs} +22 -0
- package/dist/{proof-stamp-lyD84zmj.mjs → proof-stamp-BFV7JTZT.mjs} +5 -4
- package/dist/{ratchet-SQ7vTR0i.mjs → ratchet-2FeMs1kh.mjs} +4 -3
- package/dist/{suppression-base-whhvw-IJ.mjs → suppression-base-CYaLZAq7.mjs} +2 -2
- package/dist/{suppression-budget-CtIYSoDO.mjs → suppression-budget-CPDSFg4X.mjs} +1 -1
- package/dist/{suppressions-C79kRvYI.mjs → suppressions-CxPnh4sC.mjs} +2 -2
- package/dist/{templates-Dg188oRC.mjs → templates-HG0fel2S.mjs} +1 -1
- package/dist/{type-aware-rules-DMuN6sHb.mjs → type-aware-rules-Da3769fI.mjs} +9 -1
- package/dist/{typescript--_8og8AM.mjs → typescript-CxfNxyr2.mjs} +59 -98
- package/dist/{workflow-CPcNc8KL.mjs → workflow-C-oBwL2H.mjs} +25 -1
- package/package.json +9 -5
- package/dist/bin/check-interface-ranges.d.mts +0 -1
- package/dist/bin/check-interface-ranges.mjs +0 -44
- package/dist/interface-ranges-CcVSr59f.mjs +0 -116
|
@@ -1,1855 +1,3 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import { dirname, join, relative, resolve } from "node:path";
|
|
4
|
-
import { defineRule, eslintCompatPlugin } from "@oxlint/plugins";
|
|
5
|
-
import ts from "typescript";
|
|
6
|
-
//#region src/oxc/guardrails/rules/no-comments.ts
|
|
7
|
-
const allowedCommentForms = [
|
|
8
|
-
{
|
|
9
|
-
type: "Shebang",
|
|
10
|
-
pattern: /^/u
|
|
11
|
-
},
|
|
12
|
-
{
|
|
13
|
-
type: "Block",
|
|
14
|
-
pattern: /^[*!]/u,
|
|
15
|
-
raw: true
|
|
16
|
-
},
|
|
17
|
-
{
|
|
18
|
-
type: "Line",
|
|
19
|
-
pattern: /^\/\s*<reference\s[^>]*\/\s*>\s*$/u
|
|
20
|
-
},
|
|
21
|
-
{
|
|
22
|
-
type: null,
|
|
23
|
-
pattern: /^(?:oxlint|eslint)-enable(?:\s|$)/u
|
|
24
|
-
},
|
|
25
|
-
{
|
|
26
|
-
type: null,
|
|
27
|
-
pattern: /^(?:oxlint|eslint)-disable(?:-line|-next-line)?\s+(?!-)[\w@/]/u
|
|
28
|
-
},
|
|
29
|
-
{
|
|
30
|
-
type: null,
|
|
31
|
-
pattern: /^@ts-expect-error(?:\s*:\s*|\s+)(?!:)\S/u
|
|
32
|
-
},
|
|
33
|
-
{
|
|
34
|
-
type: null,
|
|
35
|
-
pattern: /^SAFETY:/u,
|
|
36
|
-
safety: true
|
|
37
|
-
},
|
|
38
|
-
{
|
|
39
|
-
type: null,
|
|
40
|
-
pattern: /^(?:#|@)__PURE__\s*$/u
|
|
41
|
-
},
|
|
42
|
-
{
|
|
43
|
-
type: null,
|
|
44
|
-
pattern: /^@vite-ignore\b/u
|
|
45
|
-
},
|
|
46
|
-
{
|
|
47
|
-
type: null,
|
|
48
|
-
pattern: /^webpack(?:ChunkName|Prefetch|Preload|Mode|Ignore|Exports|Include|Exclude)\s*:/u
|
|
49
|
-
},
|
|
50
|
-
{
|
|
51
|
-
type: null,
|
|
52
|
-
pattern: /^(?:prettier|oxfmt)-ignore\s*$/u
|
|
53
|
-
}
|
|
54
|
-
];
|
|
55
|
-
const disableDirective = /^(?:oxlint|eslint)-disable(?:-line|-next-line)?(?:\s|$)/u;
|
|
56
|
-
/** Ordinary comments must become executable constraints or documentation on a public item. */
|
|
57
|
-
const noCommentsRule = defineRule({
|
|
58
|
-
meta: {
|
|
59
|
-
type: "problem",
|
|
60
|
-
docs: { description: "Disallow comments except documentation and explicit compiler or safety directives." },
|
|
61
|
-
messages: {
|
|
62
|
-
comment: "Comments rot. Encode this constraint in a type, a lint rule, or a test, or write TSDoc (`/** */`) on the public item it documents.",
|
|
63
|
-
unnamedDisable: "Name the rule(s) to disable and give a reason, for example: oxlint-disable-next-line no-debugger -- debugging this operation."
|
|
64
|
-
}
|
|
65
|
-
},
|
|
66
|
-
createOnce(context) {
|
|
67
|
-
return { Program() {
|
|
68
|
-
let safetyLine;
|
|
69
|
-
for (const comment of context.sourceCode.getAllComments()) {
|
|
70
|
-
const text = comment.value.replace(/^\s*\*?\s*/u, "").trimEnd();
|
|
71
|
-
const form = allowedCommentForms.find((allowed) => (allowed.type === null || allowed.type === comment.type) && allowed.pattern.test("raw" in allowed ? comment.value : text));
|
|
72
|
-
const continuesSafety = comment.type === "Line" && safetyLine !== void 0 && comment.loc.start.line === safetyLine.loc.end.line + 1 && /^\s*$/u.test(context.sourceCode.text.slice(safetyLine.end, comment.start));
|
|
73
|
-
safetyLine = comment.type === "Line" && (continuesSafety || form !== void 0 && "safety" in form) ? comment : void 0;
|
|
74
|
-
const unnamedDisable = disableDirective.test(text) && form === void 0;
|
|
75
|
-
if (!unnamedDisable && (form !== void 0 || continuesSafety)) continue;
|
|
76
|
-
context.report({
|
|
77
|
-
loc: comment.loc,
|
|
78
|
-
messageId: unnamedDisable ? "unnamedDisable" : "comment"
|
|
79
|
-
});
|
|
80
|
-
}
|
|
81
|
-
} };
|
|
82
|
-
}
|
|
83
|
-
});
|
|
84
|
-
//#endregion
|
|
85
|
-
//#region src/oxc/guardrails/rules/no-constant-value-assertion.ts
|
|
86
|
-
const equalityMatchers = /* @__PURE__ */ new Set([
|
|
87
|
-
"toBe",
|
|
88
|
-
"toEqual",
|
|
89
|
-
"toStrictEqual",
|
|
90
|
-
"to.equal",
|
|
91
|
-
"to.eq",
|
|
92
|
-
"eql",
|
|
93
|
-
"to.eql",
|
|
94
|
-
"to.deep.eq",
|
|
95
|
-
"to.deep.equal",
|
|
96
|
-
"to.be.equal"
|
|
97
|
-
]);
|
|
98
|
-
const constantName = /^[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)*$/u;
|
|
99
|
-
function isConstant(node) {
|
|
100
|
-
if (node?.type === "Identifier") return constantName.test(node.name);
|
|
101
|
-
if (node?.type !== "MemberExpression") return false;
|
|
102
|
-
return isConstant(node.object);
|
|
103
|
-
}
|
|
104
|
-
function isLiteralValue(node) {
|
|
105
|
-
if (node.type === "Literal") return !("regex" in node) && !("bigint" in node);
|
|
106
|
-
if (node.type === "TemplateLiteral") return node.expressions.length === 0;
|
|
107
|
-
if (node.type === "UnaryExpression") return node.operator === "-" && node.argument.type === "Literal" && Number.isFinite(node.argument.value);
|
|
108
|
-
if (node.type === "ArrayExpression") return node.elements.every((element) => element !== null && isLiteralValue(element));
|
|
109
|
-
if (node.type === "ObjectExpression") return node.properties.every((property) => property.type === "Property" && !property.computed && !property.method && !property.shorthand && property.kind === "init" && isLiteralValue(property.value));
|
|
110
|
-
return false;
|
|
111
|
-
}
|
|
112
|
-
/** Constant declarations already specify their values; tests must assert the behavior they drive. */
|
|
113
|
-
const noConstantValueAssertionRule = defineRule({
|
|
114
|
-
meta: {
|
|
115
|
-
type: "problem",
|
|
116
|
-
docs: { description: "Disallow assertions that only restate a constant's literal value." },
|
|
117
|
-
messages: { constant: "A test that restates a constant fails only when someone edits the constant on purpose. Assert the behaviour the constant drives." }
|
|
118
|
-
},
|
|
119
|
-
createOnce(context) {
|
|
120
|
-
return { CallExpression(node) {
|
|
121
|
-
const chain = matcherChain(node);
|
|
122
|
-
const expected = node.arguments[0];
|
|
123
|
-
if (chain !== null && equalityMatchers.has(chain.matcher) && isConstant(chain.expect.arguments[0]) && expected !== void 0 && isLiteralValue(expected)) context.report({
|
|
124
|
-
node,
|
|
125
|
-
messageId: "constant"
|
|
126
|
-
});
|
|
127
|
-
} };
|
|
128
|
-
}
|
|
129
|
-
});
|
|
130
|
-
//#endregion
|
|
131
|
-
//#region src/oxc/guardrails/rules/no-fs-read-in-tests.ts
|
|
132
|
-
const fsModules = /* @__PURE__ */ new Set(["fs", "node:fs"]);
|
|
133
|
-
const readMethods = /* @__PURE__ */ new Set(["readFileSync", "readdirSync"]);
|
|
134
|
-
function isFsRequire(node) {
|
|
135
|
-
return node.type === "CallExpression" && node.callee.type === "Identifier" && node.callee.name === "require" && node.arguments[0]?.type === "Literal" && fsModules.has(String(node.arguments[0].value));
|
|
136
|
-
}
|
|
137
|
-
function isFsNamespace(source, node) {
|
|
138
|
-
if (isFsRequire(node)) return true;
|
|
139
|
-
if (node.type !== "Identifier") return false;
|
|
140
|
-
let scope = source.getScope(node);
|
|
141
|
-
while (scope !== null) {
|
|
142
|
-
const binding = scope.set.get(node.name);
|
|
143
|
-
if (binding !== void 0) return binding.defs.some((definition) => {
|
|
144
|
-
if (definition.node.type === "TSImportEqualsDeclaration") {
|
|
145
|
-
const reference = definition.node.moduleReference;
|
|
146
|
-
return reference.type === "TSExternalModuleReference" && fsModules.has(reference.expression.value);
|
|
147
|
-
}
|
|
148
|
-
if (definition.type === "ImportBinding") return (definition.node.type !== "ImportSpecifier" || definition.node.imported.type === "Identifier" && definition.node.imported.name === "default") && definition.parent?.type === "ImportDeclaration" && fsModules.has(definition.parent.source.value);
|
|
149
|
-
return definition.node.type === "VariableDeclarator" && definition.node.init !== null && isFsRequire(definition.node.init);
|
|
150
|
-
});
|
|
151
|
-
scope = scope.upper;
|
|
152
|
-
}
|
|
153
|
-
return false;
|
|
154
|
-
}
|
|
155
|
-
/** Tests exercise behavior through public interfaces rather than reading implementation text. */
|
|
156
|
-
const noFsReadInTestsRule = defineRule({
|
|
157
|
-
meta: {
|
|
158
|
-
type: "problem",
|
|
159
|
-
docs: { description: "Move synchronous filesystem reads out of tests into fixture helpers." },
|
|
160
|
-
messages: { fsRead: "Tests exercise behaviour through the public interface. A test that reads source files asserts text, not behaviour. Move fixture reads into a helper under fixtures/, helpers/ or locales/." }
|
|
161
|
-
},
|
|
162
|
-
createOnce(context) {
|
|
163
|
-
return {
|
|
164
|
-
ImportDeclaration(node) {
|
|
165
|
-
if (!fsModules.has(node.source.value) || node.importKind === "type") return;
|
|
166
|
-
for (const specifier of node.specifiers) {
|
|
167
|
-
if (specifier.type !== "ImportSpecifier" || specifier.importKind === "type") continue;
|
|
168
|
-
const name = specifier.imported.type === "Identifier" ? specifier.imported.name : specifier.imported.value;
|
|
169
|
-
if (readMethods.has(name)) context.report({
|
|
170
|
-
node: specifier,
|
|
171
|
-
messageId: "fsRead"
|
|
172
|
-
});
|
|
173
|
-
}
|
|
174
|
-
},
|
|
175
|
-
MemberExpression(node) {
|
|
176
|
-
const name = memberName(node);
|
|
177
|
-
if (name !== null && readMethods.has(name) && isFsNamespace(context.sourceCode, node.object)) context.report({
|
|
178
|
-
node,
|
|
179
|
-
messageId: "fsRead"
|
|
180
|
-
});
|
|
181
|
-
},
|
|
182
|
-
VariableDeclarator(node) {
|
|
183
|
-
if (node.id.type !== "ObjectPattern" || node.init === null || !isFsNamespace(context.sourceCode, node.init)) return;
|
|
184
|
-
for (const property of node.id.properties) {
|
|
185
|
-
if (property.type !== "Property") continue;
|
|
186
|
-
const name = property.key.type === "Identifier" && !property.computed ? property.key.name : property.key.type === "Literal" ? String(property.key.value) : null;
|
|
187
|
-
if (name !== null && readMethods.has(name)) context.report({
|
|
188
|
-
node: property,
|
|
189
|
-
messageId: "fsRead"
|
|
190
|
-
});
|
|
191
|
-
}
|
|
192
|
-
}
|
|
193
|
-
};
|
|
194
|
-
}
|
|
195
|
-
});
|
|
196
|
-
//#endregion
|
|
197
|
-
//#region src/oxc/guardrails/local-types.ts
|
|
198
|
-
/** Collects top-level and exported type declarations; local ones inside functions are not resolved. */
|
|
199
|
-
function collectLocalTypes(program) {
|
|
200
|
-
const types = {
|
|
201
|
-
aliases: /* @__PURE__ */ new Map(),
|
|
202
|
-
interfaces: /* @__PURE__ */ new Map()
|
|
203
|
-
};
|
|
204
|
-
for (const statement of program.body) {
|
|
205
|
-
const declaration = statement.type === "ExportNamedDeclaration" ? statement.declaration : statement;
|
|
206
|
-
if (declaration?.type === "TSTypeAliasDeclaration") types.aliases.set(declaration.id.name, declaration.typeAnnotation);
|
|
207
|
-
if (declaration?.type === "TSInterfaceDeclaration") {
|
|
208
|
-
const merged = types.interfaces.get(declaration.id.name) ?? [];
|
|
209
|
-
merged.push(declaration);
|
|
210
|
-
types.interfaces.set(declaration.id.name, merged);
|
|
211
|
-
}
|
|
212
|
-
}
|
|
213
|
-
return types;
|
|
214
|
-
}
|
|
215
|
-
/** The type reference's name when it is a plain identifier, such as `Record` in `Record<string, T>`. */
|
|
216
|
-
function referenceName(type) {
|
|
217
|
-
return type.typeName.type === "Identifier" ? type.typeName.name : null;
|
|
218
|
-
}
|
|
219
|
-
/** Strips parentheses and non-null assertions, which change neither the value nor its prototype. */
|
|
220
|
-
function unwrapExpression(node) {
|
|
221
|
-
let current = node;
|
|
222
|
-
while (current.type === "ParenthesizedExpression" || current.type === "TSNonNullExpression") current = current.expression;
|
|
223
|
-
return current;
|
|
224
|
-
}
|
|
225
|
-
/** The variable an identifier refers to, found by walking out from its scope. */
|
|
226
|
-
function resolveVariable(source, identifier) {
|
|
227
|
-
let scope = source.getScope(identifier);
|
|
228
|
-
while (scope !== null) {
|
|
229
|
-
const variable = scope.set.get(identifier.name);
|
|
230
|
-
if (variable !== void 0) return variable;
|
|
231
|
-
scope = scope.upper;
|
|
232
|
-
}
|
|
233
|
-
return null;
|
|
234
|
-
}
|
|
235
|
-
/** The nearest function around a node, or null at module level. */
|
|
236
|
-
function enclosingFunction(node) {
|
|
237
|
-
let current = node.parent;
|
|
238
|
-
while (current !== null) {
|
|
239
|
-
if (current.type === "ArrowFunctionExpression" || current.type === "FunctionDeclaration" || current.type === "FunctionExpression") return current;
|
|
240
|
-
current = current.parent;
|
|
241
|
-
}
|
|
242
|
-
return null;
|
|
243
|
-
}
|
|
244
|
-
/** The predicate a function's return type declares, when it names a parameter (`x is T`, `asserts x is T`). */
|
|
245
|
-
function parameterPredicate(fn) {
|
|
246
|
-
const predicate = fn.returnType?.typeAnnotation;
|
|
247
|
-
return predicate?.type === "TSTypePredicate" && predicate.parameterName.type === "Identifier" ? predicate : null;
|
|
248
|
-
}
|
|
249
|
-
/** The parameter name a predicate narrows, or null for `this` predicates. */
|
|
250
|
-
function predicateName(predicate) {
|
|
251
|
-
return predicate.parameterName.type === "Identifier" ? predicate.parameterName.name : null;
|
|
252
|
-
}
|
|
253
|
-
/** The field `this.<name>` refers to: a property or constructor parameter property of the class around `node`. */
|
|
254
|
-
function classField(node, name) {
|
|
255
|
-
let current = node.parent;
|
|
256
|
-
while (current !== null && current.type !== "ClassBody") {
|
|
257
|
-
if (current.type === "FunctionDeclaration" || current.type === "FunctionExpression" && current.parent.type !== "MethodDefinition") return null;
|
|
258
|
-
current = current.parent;
|
|
259
|
-
}
|
|
260
|
-
if (current === null) return null;
|
|
261
|
-
for (const member of current.body) {
|
|
262
|
-
if (member.type === "PropertyDefinition" && !member.computed && member.key.type === "Identifier" && member.key.name === name) return {
|
|
263
|
-
typeAnnotation: member.typeAnnotation ?? null,
|
|
264
|
-
value: member.value
|
|
265
|
-
};
|
|
266
|
-
if (member.type === "MethodDefinition" && member.kind === "constructor") {
|
|
267
|
-
for (const parameter of member.value.params) if (parameter.type === "TSParameterProperty" && parameter.parameter.type === "Identifier" && parameter.parameter.name === name) return {
|
|
268
|
-
typeAnnotation: parameter.parameter.typeAnnotation ?? null,
|
|
269
|
-
value: null
|
|
270
|
-
};
|
|
271
|
-
}
|
|
272
|
-
}
|
|
273
|
-
return null;
|
|
274
|
-
}
|
|
275
|
-
//#endregion
|
|
276
|
-
//#region src/oxc/guardrails/key-provenance.ts
|
|
277
|
-
const OWN_KEY_LISTS = /* @__PURE__ */ new Set(["Object.keys", "Object.getOwnPropertyNames"]);
|
|
278
|
-
const KEY_PRESERVING_METHODS = /* @__PURE__ */ new Set([
|
|
279
|
-
"filter",
|
|
280
|
-
"reverse",
|
|
281
|
-
"slice",
|
|
282
|
-
"sort",
|
|
283
|
-
"toReversed",
|
|
284
|
-
"toSorted"
|
|
285
|
-
]);
|
|
286
|
-
const ITERATING_METHODS = /* @__PURE__ */ new Set([
|
|
287
|
-
"every",
|
|
288
|
-
"filter",
|
|
289
|
-
"find",
|
|
290
|
-
"findIndex",
|
|
291
|
-
"flatMap",
|
|
292
|
-
"forEach",
|
|
293
|
-
"map",
|
|
294
|
-
"some"
|
|
295
|
-
]);
|
|
296
|
-
/** A literal, a template without substitutions, or a `typeof` result: never an `Object.prototype` key. */
|
|
297
|
-
function isStaticKey(key) {
|
|
298
|
-
if (key.type === "Literal") return true;
|
|
299
|
-
if (key.type === "UnaryExpression") return key.operator === "typeof";
|
|
300
|
-
return key.type === "TemplateLiteral" && key.expressions.length === 0;
|
|
301
|
-
}
|
|
302
|
-
function constInitializer(identifier, source) {
|
|
303
|
-
const [definition] = resolveVariable(source, identifier)?.defs ?? [];
|
|
304
|
-
if (definition?.type !== "Variable" || definition.parent?.type !== "VariableDeclaration" || definition.parent.kind !== "const" || definition.node.type !== "VariableDeclarator" || definition.node.init === null) return null;
|
|
305
|
-
let init = definition.node.init;
|
|
306
|
-
while (init.type === "TSAsExpression" || init.type === "TSSatisfiesExpression") init = init.expression;
|
|
307
|
-
return unwrapExpression(init);
|
|
308
|
-
}
|
|
309
|
-
function propertyValue(object, name) {
|
|
310
|
-
for (const property of object.properties) if (property.type === "Property" && !property.computed && property.key.type === "Identifier" && property.key.name === name) return property.value;
|
|
311
|
-
return null;
|
|
312
|
-
}
|
|
313
|
-
/** `const KEY = "a"` or `const LABELS = { a: "x" }` read as `LABELS.a`, declared in this file. */
|
|
314
|
-
function isConstantKey(key, source) {
|
|
315
|
-
if (key.type === "Identifier") {
|
|
316
|
-
const init = constInitializer(key, source);
|
|
317
|
-
return init !== null && isStaticKey(init);
|
|
318
|
-
}
|
|
319
|
-
if (key.type !== "MemberExpression" || key.computed || key.object.type !== "Identifier" || key.property.type !== "Identifier") return false;
|
|
320
|
-
const init = constInitializer(key.object, source);
|
|
321
|
-
const value = init?.type === "ObjectExpression" ? propertyValue(init, key.property.name) : null;
|
|
322
|
-
return value !== null && isStaticKey(value);
|
|
323
|
-
}
|
|
324
|
-
function keyList(node, source, depth = 0) {
|
|
325
|
-
if (depth > 8) return null;
|
|
326
|
-
if (node.type === "Identifier") {
|
|
327
|
-
const init = constInitializer(node, source);
|
|
328
|
-
return init === null ? null : keyList(init, source, depth + 1);
|
|
329
|
-
}
|
|
330
|
-
if (node.type === "ArrayExpression") return node.elements.every((element) => element !== null && isStaticKey(element)) ? { kind: "literal" } : null;
|
|
331
|
-
if (node.type !== "CallExpression") return null;
|
|
332
|
-
const name = callName(node.callee);
|
|
333
|
-
const [first] = node.arguments;
|
|
334
|
-
if (first !== void 0 && OWN_KEY_LISTS.has(name ?? "")) return {
|
|
335
|
-
kind: "keys",
|
|
336
|
-
table: source.getText(first)
|
|
337
|
-
};
|
|
338
|
-
if (first !== void 0 && name === "Object.entries") return {
|
|
339
|
-
kind: "entries",
|
|
340
|
-
table: source.getText(first)
|
|
341
|
-
};
|
|
342
|
-
const callee = node.callee;
|
|
343
|
-
return callee.type === "MemberExpression" && !callee.computed && callee.property.type === "Identifier" && KEY_PRESERVING_METHODS.has(callee.property.name) ? keyList(callee.object, source, depth + 1) : null;
|
|
344
|
-
}
|
|
345
|
-
/** The pattern that binds a key: the whole binding, or the first element of `[key, value]`. */
|
|
346
|
-
function keyBinding(pattern, name) {
|
|
347
|
-
if (pattern === name) return "plain";
|
|
348
|
-
return pattern.type === "ArrayPattern" && pattern.elements[0] === name ? "entry" : null;
|
|
349
|
-
}
|
|
350
|
-
/** The list a key is iterated from, with how it is bound, or a `for...in` loop. */
|
|
351
|
-
function keySource(definition) {
|
|
352
|
-
if (definition.type === "Parameter") {
|
|
353
|
-
const fn = definition.node;
|
|
354
|
-
const call = fn.parent;
|
|
355
|
-
if (fn.type !== "ArrowFunctionExpression" && fn.type !== "FunctionExpression" || call?.type !== "CallExpression" || call.arguments[0] !== fn || call.callee.type !== "MemberExpression" || call.callee.computed || call.callee.property.type !== "Identifier" || !ITERATING_METHODS.has(call.callee.property.name) || fn.params[0] === void 0) return null;
|
|
356
|
-
return {
|
|
357
|
-
list: call.callee.object,
|
|
358
|
-
binding: keyBinding(fn.params[0], definition.name)
|
|
359
|
-
};
|
|
360
|
-
}
|
|
361
|
-
const loop = definition.parent?.parent;
|
|
362
|
-
if (definition.node.type !== "VariableDeclarator") return null;
|
|
363
|
-
if (loop?.type === "ForInStatement") return {
|
|
364
|
-
list: loop,
|
|
365
|
-
binding: "plain"
|
|
366
|
-
};
|
|
367
|
-
return loop?.type === "ForOfStatement" ? {
|
|
368
|
-
list: loop.right,
|
|
369
|
-
binding: keyBinding(definition.node.id, definition.name)
|
|
370
|
-
} : null;
|
|
371
|
-
}
|
|
372
|
-
function isOwnKeyBinding(key, table, source) {
|
|
373
|
-
if (key.type !== "Identifier") return false;
|
|
374
|
-
const [definition] = resolveVariable(source, key)?.defs ?? [];
|
|
375
|
-
const found = definition === void 0 ? null : keySource(definition);
|
|
376
|
-
if (found === null || found.binding === null) return false;
|
|
377
|
-
if (found.list.type === "ForInStatement") return source.getText(found.list.right) === table;
|
|
378
|
-
const list = keyList(found.list, source);
|
|
379
|
-
if (list === null) return false;
|
|
380
|
-
if (list.kind === "literal") return found.binding === "plain";
|
|
381
|
-
const binding = list.kind === "keys" ? "plain" : "entry";
|
|
382
|
-
return list.table === table && found.binding === binding;
|
|
383
|
-
}
|
|
384
|
-
/**
|
|
385
|
-
* Keys the rule can prove are not inherited: static keys, same-file constants, and keys iterated
|
|
386
|
-
* from string literals or from `Object.keys`, `Object.entries` or `for...in` of the same table,
|
|
387
|
-
* through `filter`, `sort` and similar key-preserving calls. Imported constants are not resolved.
|
|
388
|
-
*/
|
|
389
|
-
function isKnownKey(key, table, source) {
|
|
390
|
-
return isStaticKey(key) || isConstantKey(key, source) || isOwnKeyBinding(key, table, source);
|
|
391
|
-
}
|
|
392
|
-
/** `Object.prototype.hasOwnProperty.call`, `{}.hasOwnProperty.call` and other `<x>.hasOwnProperty.call` forms. */
|
|
393
|
-
function isHasOwnPropertyCall(callee) {
|
|
394
|
-
return callee.type === "MemberExpression" && !callee.computed && callee.property.type === "Identifier" && callee.property.name === "call" && callee.object.type === "MemberExpression" && !callee.object.computed && callee.object.property.type === "Identifier" && callee.object.property.name === "hasOwnProperty";
|
|
395
|
-
}
|
|
396
|
-
//#endregion
|
|
397
|
-
//#region src/oxc/guardrails/own-key-guard.ts
|
|
398
|
-
const HAS_OWN_CALLS = /* @__PURE__ */ new Set(["Object.hasOwn", "hasOwnProperty.call"]);
|
|
399
|
-
const EXITS = /* @__PURE__ */ new Set([
|
|
400
|
-
"BreakStatement",
|
|
401
|
-
"ContinueStatement",
|
|
402
|
-
"ReturnStatement",
|
|
403
|
-
"ThrowStatement"
|
|
404
|
-
]);
|
|
405
|
-
function checksOwnKey(node, read) {
|
|
406
|
-
const [first, second] = node.arguments;
|
|
407
|
-
if (first === void 0) return false;
|
|
408
|
-
const text = (argument) => read.source.getText(argument);
|
|
409
|
-
if (HAS_OWN_CALLS.has(callName(node.callee) ?? "") || isHasOwnPropertyCall(node.callee)) return second !== void 0 && text(first) === read.table && text(second) === read.key;
|
|
410
|
-
const callee = node.callee;
|
|
411
|
-
return callee.type === "MemberExpression" && !callee.computed && callee.property.type === "Identifier" && callee.property.name === "hasOwnProperty" && text(callee.object) === read.table && text(first) === read.key;
|
|
412
|
-
}
|
|
413
|
-
const EQUALITY = /* @__PURE__ */ new Set(["==", "==="]);
|
|
414
|
-
const INEQUALITY = /* @__PURE__ */ new Set(["!=", "!=="]);
|
|
415
|
-
const MAX_DEPTH$2 = 8;
|
|
416
|
-
const ASSERTS = /* @__PURE__ */ new Set([
|
|
417
|
-
"assert",
|
|
418
|
-
"assert.ok",
|
|
419
|
-
"assert.strict"
|
|
420
|
-
]);
|
|
421
|
-
/** The initializer of a `const` the identifier names, such as `has` in `const has = Object.hasOwn(t, k)`. */
|
|
422
|
-
function constValue(node, read) {
|
|
423
|
-
const [definition] = resolveVariable(read.source, node)?.defs ?? [];
|
|
424
|
-
if (definition?.type !== "Variable" || definition.parent?.type !== "VariableDeclaration" || definition.parent.kind !== "const" || definition.node.type !== "VariableDeclarator") return null;
|
|
425
|
-
return definition.node.init;
|
|
426
|
-
}
|
|
427
|
-
/** `x === true`, `x !== false` and their mirrors: the outcome `x` has when the comparison has `outcome`. */
|
|
428
|
-
function comparedOutcome(node, outcome) {
|
|
429
|
-
const equal = EQUALITY.has(node.operator);
|
|
430
|
-
if (!equal && !INEQUALITY.has(node.operator)) return null;
|
|
431
|
-
const [literal, operand] = node.right.type === "Literal" ? [node.right, node.left] : [node.left, node.right];
|
|
432
|
-
if (literal.type !== "Literal") return null;
|
|
433
|
-
const value = literal.value;
|
|
434
|
-
if (value !== true && value !== false) return null;
|
|
435
|
-
return {
|
|
436
|
-
operand,
|
|
437
|
-
outcome: outcome === equal === value
|
|
438
|
-
};
|
|
439
|
-
}
|
|
440
|
-
/** A value that is `true` or `false`, so comparing it with a boolean literal tests its truth: a call, a `!`, or a `const` of one. */
|
|
441
|
-
function isBooleanValued(node, read, depth) {
|
|
442
|
-
if (depth > MAX_DEPTH$2) return false;
|
|
443
|
-
if (node.type === "ParenthesizedExpression") return isBooleanValued(node.expression, read, depth);
|
|
444
|
-
if (node.type === "Identifier") {
|
|
445
|
-
const value = constValue(node, read);
|
|
446
|
-
return value !== null && isBooleanValued(value, read, depth + 1);
|
|
447
|
-
}
|
|
448
|
-
return node.type === "CallExpression" || node.type === "UnaryExpression" && node.operator === "!";
|
|
449
|
-
}
|
|
450
|
-
/** `Object.getOwnPropertyDescriptor(Object.prototype, key)?.value` or `Object.prototype[key]`: the value `Object.prototype` itself holds under the key. */
|
|
451
|
-
function isRootValue(node, read) {
|
|
452
|
-
const value = node.type === "ChainExpression" ? node.expression : node;
|
|
453
|
-
if (value.type !== "MemberExpression") return false;
|
|
454
|
-
const text = (part) => read.source.getText(part);
|
|
455
|
-
if (value.computed) return text(value.object) === "Object.prototype" && text(value.property) === read.key;
|
|
456
|
-
const call = value.object;
|
|
457
|
-
return value.property.type === "Identifier" && value.property.name === "value" && call.type === "CallExpression" && callName(call.callee) === "Object.getOwnPropertyDescriptor" && call.arguments.length === 2 && text(call.arguments[0]) === "Object.prototype" && text(call.arguments[1]) === read.key;
|
|
458
|
-
}
|
|
459
|
-
/** The outcome of `table[key] === <root value>` (or `!==`, either order) under which the read differs from `Object.prototype`'s own value, or `null` for another comparison. */
|
|
460
|
-
function differsFromRootWhen(node, read) {
|
|
461
|
-
const equal = EQUALITY.has(node.operator);
|
|
462
|
-
if (!equal && !INEQUALITY.has(node.operator)) return null;
|
|
463
|
-
const reads = (side) => side.type === "MemberExpression" && side.computed && read.source.getText(side.object) === read.table && read.source.getText(side.property) === read.key;
|
|
464
|
-
return reads(node.left) && isRootValue(node.right, read) || reads(node.right) && isRootValue(node.left, read) ? !equal : null;
|
|
465
|
-
}
|
|
466
|
-
/** `a && b` that is true, or `a || b` that is false, needs one operand to hold; `a || b` that is true, or `a && b` that is false, needs both. */
|
|
467
|
-
function combinedHolds(node, outcome, read, depth) {
|
|
468
|
-
const left = holds(node.left, outcome, read, depth);
|
|
469
|
-
const right = holds(node.right, outcome, read, depth);
|
|
470
|
-
if (node.operator === (outcome ? "&&" : "||")) return left || right;
|
|
471
|
-
return node.operator === (outcome ? "||" : "&&") && left && right;
|
|
472
|
-
}
|
|
473
|
-
/**
|
|
474
|
-
* Whether the key is safe to read whenever `node` evaluates to `outcome`: the table owns the key,
|
|
475
|
-
* the key is no `Object.prototype` name, or the table answers it with something other than
|
|
476
|
-
* `Object.prototype`'s own value.
|
|
477
|
-
*/
|
|
478
|
-
function holds(node, outcome, read, depth = 0) {
|
|
479
|
-
if (depth > MAX_DEPTH$2) return false;
|
|
480
|
-
switch (node.type) {
|
|
481
|
-
case "ParenthesizedExpression": return holds(node.expression, outcome, read, depth);
|
|
482
|
-
case "CallExpression": return outcome ? checksOwnKey(node, read) : checksOwnKey(node, {
|
|
483
|
-
...read,
|
|
484
|
-
table: "Object.prototype"
|
|
485
|
-
});
|
|
486
|
-
case "Identifier": {
|
|
487
|
-
const value = constValue(node, read);
|
|
488
|
-
return value !== null && holds(value, outcome, read, depth + 1);
|
|
489
|
-
}
|
|
490
|
-
case "UnaryExpression": return node.operator === "!" && holds(node.argument, !outcome, read, depth);
|
|
491
|
-
case "BinaryExpression": {
|
|
492
|
-
if (differsFromRootWhen(node, read) === outcome) return true;
|
|
493
|
-
const compared = comparedOutcome(node, outcome);
|
|
494
|
-
return compared !== null && isBooleanValued(compared.operand, read, depth) && holds(compared.operand, compared.outcome, read, depth);
|
|
495
|
-
}
|
|
496
|
-
case "LogicalExpression": return combinedHolds(node, outcome, read, depth);
|
|
497
|
-
default: return false;
|
|
498
|
-
}
|
|
499
|
-
}
|
|
500
|
-
function exits(statement) {
|
|
501
|
-
if (statement.type === "BlockStatement") {
|
|
502
|
-
const last = statement.body.at(-1);
|
|
503
|
-
return last !== void 0 && exits(last);
|
|
504
|
-
}
|
|
505
|
-
if (statement.type === "IfStatement") return statement.alternate !== null && exits(statement.consequent) && exits(statement.alternate);
|
|
506
|
-
return EXITS.has(statement.type);
|
|
507
|
-
}
|
|
508
|
-
/** Whether a statement ends by storing `table[key]`, which makes the key own. */
|
|
509
|
-
function storesKey(statement, read) {
|
|
510
|
-
if (statement.type === "BlockStatement") {
|
|
511
|
-
const last = statement.body.at(-1);
|
|
512
|
-
return last !== void 0 && storesKey(last, read);
|
|
513
|
-
}
|
|
514
|
-
if (statement.type !== "ExpressionStatement") return false;
|
|
515
|
-
const assignment = statement.expression;
|
|
516
|
-
return assignment.type === "AssignmentExpression" && assignment.operator === "=" && assignment.left.type === "MemberExpression" && assignment.left.computed && read.source.getText(assignment.left.object) === read.table && read.source.getText(assignment.left.property) === read.key;
|
|
517
|
-
}
|
|
518
|
-
function settles(statement, read) {
|
|
519
|
-
return exits(statement) || storesKey(statement, read);
|
|
520
|
-
}
|
|
521
|
-
/**
|
|
522
|
-
* A statement after which the key is own: an `assert` of the check, or an `if` whose branch where
|
|
523
|
-
* the check fails leaves the block or stores the key.
|
|
524
|
-
*/
|
|
525
|
-
function establishes(statement, read) {
|
|
526
|
-
if (statement.type === "ExpressionStatement" && statement.expression.type === "CallExpression") {
|
|
527
|
-
const [condition] = statement.expression.arguments;
|
|
528
|
-
return ASSERTS.has(callName(statement.expression.callee) ?? "") && condition !== void 0 && holds(condition, true, read);
|
|
529
|
-
}
|
|
530
|
-
if (statement.type !== "IfStatement") return false;
|
|
531
|
-
if (settles(statement.consequent, read) && holds(statement.test, false, read)) return true;
|
|
532
|
-
return statement.alternate !== null && settles(statement.alternate, read) && holds(statement.test, true, read);
|
|
533
|
-
}
|
|
534
|
-
function statementsOf(node) {
|
|
535
|
-
if (node.type === "BlockStatement" || node.type === "Program" || node.type === "StaticBlock") return node.body;
|
|
536
|
-
return node.type === "SwitchCase" ? node.consequent : null;
|
|
537
|
-
}
|
|
538
|
-
function guardsChild(parent, child, read) {
|
|
539
|
-
if (parent.type === "ConditionalExpression" || parent.type === "IfStatement") {
|
|
540
|
-
if (child === parent.consequent) return holds(parent.test, true, read);
|
|
541
|
-
return child === parent.alternate && holds(parent.test, false, read);
|
|
542
|
-
}
|
|
543
|
-
if (parent.type === "LogicalExpression" && child === parent.right) return (parent.operator === "&&" || parent.operator === "||") && holds(parent.left, parent.operator === "&&", read);
|
|
544
|
-
if (parent.type === "WhileStatement") return child === parent.body && holds(parent.test, true, read);
|
|
545
|
-
if (parent.type === "ForStatement") return (child === parent.body || child === parent.update) && parent.test !== null && holds(parent.test, true, read);
|
|
546
|
-
const statements = statementsOf(parent);
|
|
547
|
-
if (statements === null) return false;
|
|
548
|
-
const index = statements.indexOf(child);
|
|
549
|
-
return statements.slice(0, Math.max(index, 0)).some((statement) => establishes(statement, read));
|
|
550
|
-
}
|
|
551
|
-
/**
|
|
552
|
-
* Whether `node`, a read of `table[key]`, cannot answer a key only `Object.prototype` holds. It is
|
|
553
|
-
* compared with `Object.prototype`'s own value of the key, or a check guards it: an own-key check of
|
|
554
|
-
* `table` and `key` (`Object.hasOwn`, `hasOwnProperty.call`, `table.hasOwnProperty`), a failed
|
|
555
|
-
* `Object.prototype` membership check of `key`, or the read differing from `Object.prototype`'s
|
|
556
|
-
* value, directly, negated, combined with `&&`/`||`, compared with a boolean or held in a `const`.
|
|
557
|
-
* The check guards it when it holds in the branch of a conditional, `if`, `&&`/`||`, `while` or
|
|
558
|
-
* `for` that holds `node`, or an earlier statement asserts it, or leaves the block or stores the
|
|
559
|
-
* key where it fails.
|
|
560
|
-
*/
|
|
561
|
-
function isOwnKeyGuarded(node, table, key, source) {
|
|
562
|
-
const read = {
|
|
563
|
-
table,
|
|
564
|
-
key,
|
|
565
|
-
source
|
|
566
|
-
};
|
|
567
|
-
if (node.parent?.type === "BinaryExpression" && differsFromRootWhen(node.parent, read) !== null) return true;
|
|
568
|
-
let child = node;
|
|
569
|
-
let parent = node.parent;
|
|
570
|
-
while (parent !== null) {
|
|
571
|
-
if (guardsChild(parent, child, read)) return true;
|
|
572
|
-
child = parent;
|
|
573
|
-
parent = parent.parent;
|
|
574
|
-
}
|
|
575
|
-
return false;
|
|
576
|
-
}
|
|
577
|
-
//#endregion
|
|
578
|
-
//#region src/oxc/guardrails/rules/no-inherited-key-lookup.ts
|
|
579
|
-
const WRAPPER_TYPES = /* @__PURE__ */ new Set([
|
|
580
|
-
"Readonly",
|
|
581
|
-
"Partial",
|
|
582
|
-
"Required"
|
|
583
|
-
]);
|
|
584
|
-
const MAX_ALIAS_DEPTH$1 = 8;
|
|
585
|
-
function isStringKey(type) {
|
|
586
|
-
if (type.type === "TSStringKeyword") return true;
|
|
587
|
-
if (type.type === "TSUnionType") return type.types.some(isStringKey);
|
|
588
|
-
return type.type === "TSTypeReference" && referenceName(type) === "PropertyKey";
|
|
589
|
-
}
|
|
590
|
-
function hasStringIndex(members) {
|
|
591
|
-
return members.some((member) => member.type === "TSIndexSignature" && member.parameters.some((parameter) => isStringKey(parameter.typeAnnotation.typeAnnotation)));
|
|
592
|
-
}
|
|
593
|
-
function isStringKeyedReference(type, environment, depth) {
|
|
594
|
-
const name = referenceName(type);
|
|
595
|
-
if (name === null) return false;
|
|
596
|
-
const alias = environment.types.aliases.get(name);
|
|
597
|
-
if (alias !== void 0) return isStringKeyedType(alias, environment, depth + 1);
|
|
598
|
-
const declarations = environment.types.interfaces.get(name);
|
|
599
|
-
if (declarations !== void 0) return declarations.some((declaration) => hasStringIndex(declaration.body.body));
|
|
600
|
-
const [first] = type.typeArguments?.params ?? [];
|
|
601
|
-
if (first === void 0) return false;
|
|
602
|
-
if (name === "Record") return isStringKey(first);
|
|
603
|
-
return WRAPPER_TYPES.has(name) && isStringKeyedType(first, environment, depth + 1);
|
|
604
|
-
}
|
|
605
|
-
function isStringKeyedType(type, environment, depth = 0) {
|
|
606
|
-
if (depth > MAX_ALIAS_DEPTH$1) return false;
|
|
607
|
-
switch (type.type) {
|
|
608
|
-
case "TSParenthesizedType": return isStringKeyedType(type.typeAnnotation, environment, depth);
|
|
609
|
-
case "TSTypeLiteral": return hasStringIndex(type.members);
|
|
610
|
-
case "TSMappedType": return isStringKey(type.constraint);
|
|
611
|
-
case "TSIntersectionType":
|
|
612
|
-
case "TSUnionType": return type.types.some((part) => isStringKeyedType(part, environment, depth));
|
|
613
|
-
case "TSTypeReference": return isStringKeyedReference(type, environment, depth);
|
|
614
|
-
case "TSTypeQuery": return type.exprName.type === "Identifier" && tableKind(type.exprName, environment, depth + 1) === "dictionary";
|
|
615
|
-
default: return false;
|
|
616
|
-
}
|
|
617
|
-
}
|
|
618
|
-
function isProtoKey(key) {
|
|
619
|
-
return key.type === "Identifier" && key.name === "__proto__" || key.type === "Literal" && key.value === "__proto__";
|
|
620
|
-
}
|
|
621
|
-
function isNullPrototype(init) {
|
|
622
|
-
const value = unwrapExpression(init.type === "TSAsExpression" || init.type === "TSSatisfiesExpression" ? init.expression : init);
|
|
623
|
-
if (value.type === "CallExpression") return callName(value.callee) === "Object.create" && value.arguments[0]?.type === "Literal" && value.arguments[0].value === null;
|
|
624
|
-
return value.type === "ObjectExpression" && value.properties.some((property) => property.type === "Property" && !property.computed && isProtoKey(property.key) && property.value.type === "Literal" && property.value.value === null);
|
|
625
|
-
}
|
|
626
|
-
function initializerKind(init, environment, depth) {
|
|
627
|
-
if (init.type === "TSSatisfiesExpression") return isStringKeyedType(init.typeAnnotation, environment, depth) ? "dictionary" : initializerKind(init.expression, environment, depth);
|
|
628
|
-
if (init.type === "TSAsExpression") {
|
|
629
|
-
if (init.typeAnnotation.type === "TSTypeReference" && referenceName(init.typeAnnotation) === "const") return initializerKind(init.expression, environment, depth);
|
|
630
|
-
return isStringKeyedType(init.typeAnnotation, environment, depth) ? "dictionary" : null;
|
|
631
|
-
}
|
|
632
|
-
return unwrapExpression(init).type === "ObjectExpression" ? "literal" : null;
|
|
633
|
-
}
|
|
634
|
-
function annotationOf(definition) {
|
|
635
|
-
const name = definition.name;
|
|
636
|
-
return name.type === "Identifier" && "typeAnnotation" in name ? name.typeAnnotation?.typeAnnotation ?? void 0 : void 0;
|
|
637
|
-
}
|
|
638
|
-
function variableKind(variable, environment, depth) {
|
|
639
|
-
const [definition] = variable.defs;
|
|
640
|
-
if (definition === void 0) return null;
|
|
641
|
-
const annotation = annotationOf(definition);
|
|
642
|
-
if (definition.type === "Parameter") return annotation !== void 0 && isStringKeyedType(annotation, environment, depth) ? "dictionary" : null;
|
|
643
|
-
if (definition.type !== "Variable" || definition.node.type !== "VariableDeclarator") return null;
|
|
644
|
-
const declared = declaredKind(annotation, definition.node.init, environment, depth);
|
|
645
|
-
if (declared !== null || depth >= MAX_ALIAS_DEPTH$1 || definition.parent?.type !== "VariableDeclaration" || definition.parent.kind !== "const" || definition.node.init === null || !isOpaqueAnnotation(annotation)) return declared;
|
|
646
|
-
return tableKind(widened(definition.node.init), environment, depth + 1);
|
|
647
|
-
}
|
|
648
|
-
/** The value under `as unknown` and `as any` casts, which widen the type without changing the value. */
|
|
649
|
-
function widened(init) {
|
|
650
|
-
let value = init;
|
|
651
|
-
while (value.type === "TSAsExpression" && isOpaqueAnnotation(value.typeAnnotation)) value = value.expression;
|
|
652
|
-
return value;
|
|
653
|
-
}
|
|
654
|
-
/** No annotation, `unknown` or `any`: the alias holds whatever its initializer holds. */
|
|
655
|
-
function isOpaqueAnnotation(annotation) {
|
|
656
|
-
return annotation === void 0 || annotation.type === "TSUnknownKeyword" || annotation.type === "TSAnyKeyword";
|
|
657
|
-
}
|
|
658
|
-
/** The table a field declares, given its type annotation and initializer. */
|
|
659
|
-
function declaredKind(annotation, init, environment, depth) {
|
|
660
|
-
if (init !== null && isNullPrototype(init)) return null;
|
|
661
|
-
if (annotation !== void 0) return isStringKeyedType(annotation, environment, depth) ? "dictionary" : null;
|
|
662
|
-
return init === null ? null : initializerKind(init, environment, depth);
|
|
663
|
-
}
|
|
664
|
-
function fieldKind(node, environment, depth) {
|
|
665
|
-
if (node.computed || node.object.type !== "ThisExpression" || node.property.type !== "Identifier") return null;
|
|
666
|
-
const field = classField(node, node.property.name);
|
|
667
|
-
if (field === null) return null;
|
|
668
|
-
return declaredKind(field.typeAnnotation?.typeAnnotation ?? void 0, field.value, environment, depth);
|
|
669
|
-
}
|
|
670
|
-
function tableKind(node, environment, depth = 0) {
|
|
671
|
-
const value = node.type === "Identifier" ? node : unwrapExpression(node);
|
|
672
|
-
if (value.type === "ConditionalExpression") {
|
|
673
|
-
const kinds = [value.consequent, value.alternate].map((branch) => tableKind(branch, environment, depth));
|
|
674
|
-
if (kinds.includes("dictionary")) return "dictionary";
|
|
675
|
-
return kinds.includes("literal") ? "literal" : null;
|
|
676
|
-
}
|
|
677
|
-
if (value.type === "MemberExpression") return fieldKind(value, environment, depth);
|
|
678
|
-
if (value.type !== "Identifier") return null;
|
|
679
|
-
const variable = resolveVariable(environment.source, value);
|
|
680
|
-
return variable === null ? null : variableKind(variable, environment, depth);
|
|
681
|
-
}
|
|
682
|
-
function isWrite(node) {
|
|
683
|
-
const parent = node.parent;
|
|
684
|
-
if (parent.type === "AssignmentExpression") return parent.left === node && parent.operator === "=";
|
|
685
|
-
if (parent.type === "UnaryExpression") return parent.operator === "delete";
|
|
686
|
-
return (parent.type === "ForInStatement" || parent.type === "ForOfStatement") && parent.left === node;
|
|
687
|
-
}
|
|
688
|
-
function isPredicateKey(node) {
|
|
689
|
-
const fn = enclosingFunction(node);
|
|
690
|
-
const predicate = fn === null ? null : parameterPredicate(fn);
|
|
691
|
-
return predicate !== null && node.left.type === "Identifier" && predicateName(predicate) === node.left.name;
|
|
692
|
-
}
|
|
693
|
-
/** The value a `const { [key]: x } = value` declaration or `({ [key]: x } = value)` assignment reads. */
|
|
694
|
-
function destructuredValue(pattern) {
|
|
695
|
-
const parent = pattern.parent;
|
|
696
|
-
if (parent.type === "VariableDeclarator") return parent.id === pattern ? parent.init : null;
|
|
697
|
-
return parent.type === "AssignmentExpression" && parent.left === pattern ? parent.right : null;
|
|
698
|
-
}
|
|
699
|
-
/** A destructured binding nothing reads or exports, such as `_removed` in `const { [key]: _removed, ...rest } = table`. */
|
|
700
|
-
function isDiscarded(value, source) {
|
|
701
|
-
if (value.type !== "Identifier") return false;
|
|
702
|
-
const variable = resolveVariable(source, value);
|
|
703
|
-
return variable !== null && variable.defs.every((definition) => definition.parent?.parent?.type !== "ExportNamedDeclaration") && !variable.references.some((reference) => reference.isRead());
|
|
704
|
-
}
|
|
705
|
-
/** Lookups into string-keyed object tables must not answer inherited `Object.prototype` keys. */
|
|
706
|
-
const noInheritedKeyLookupRule = defineRule({
|
|
707
|
-
meta: {
|
|
708
|
-
type: "problem",
|
|
709
|
-
docs: { description: "Disallow reading a string-keyed object table with a computed key, or testing it with `in`, without an own-key check." },
|
|
710
|
-
messages: {
|
|
711
|
-
lookup: "`{{ table }}` is a string-keyed object table, so `{{ table }}[{{ key }}]` also answers keys inherited from `Object.prototype` such as `constructor` and `toString`. Store the table in a `Map` and call `.get({{ key }})`, check `Object.hasOwn({{ table }}, {{ key }})` before the read, or build the table with a null prototype (`Object.create(null)` or `{ __proto__: null, ... }`).",
|
|
712
|
-
inOperator: "`{{ key }} in {{ table }}` is also true for keys inherited from `Object.prototype` such as `constructor` and `toString`. Use `Object.hasOwn({{ table }}, {{ key }})`, or store the table in a `Map` and call `.has({{ key }})`."
|
|
713
|
-
}
|
|
714
|
-
},
|
|
715
|
-
createOnce(context) {
|
|
716
|
-
let environment = null;
|
|
717
|
-
const report = (candidate) => {
|
|
718
|
-
if (!isOwnKeyGuarded(candidate.node, candidate.table, candidate.key, context.sourceCode)) context.report({
|
|
719
|
-
node: candidate.node,
|
|
720
|
-
messageId: candidate.messageId,
|
|
721
|
-
data: {
|
|
722
|
-
table: candidate.table,
|
|
723
|
-
key: candidate.key
|
|
724
|
-
}
|
|
725
|
-
});
|
|
726
|
-
};
|
|
727
|
-
const lookup = (node, object, key) => {
|
|
728
|
-
if (environment === null) return;
|
|
729
|
-
const kind = tableKind(object, environment);
|
|
730
|
-
if (kind === null || kind === "literal" && key.type !== "TSAsExpression") return;
|
|
731
|
-
const table = context.sourceCode.getText(object);
|
|
732
|
-
if (isKnownKey(key, table, context.sourceCode)) return;
|
|
733
|
-
report({
|
|
734
|
-
node,
|
|
735
|
-
messageId: "lookup",
|
|
736
|
-
table,
|
|
737
|
-
key: context.sourceCode.getText(key)
|
|
738
|
-
});
|
|
739
|
-
};
|
|
740
|
-
return {
|
|
741
|
-
Program(node) {
|
|
742
|
-
environment = {
|
|
743
|
-
source: context.sourceCode,
|
|
744
|
-
types: collectLocalTypes(node)
|
|
745
|
-
};
|
|
746
|
-
},
|
|
747
|
-
MemberExpression(node) {
|
|
748
|
-
if (node.computed && !isWrite(node)) lookup(node, node.object, node.property);
|
|
749
|
-
},
|
|
750
|
-
ObjectPattern(node) {
|
|
751
|
-
const object = destructuredValue(node);
|
|
752
|
-
if (object === null) return;
|
|
753
|
-
for (const property of node.properties) if (property.type === "Property" && property.computed && !isDiscarded(property.value, context.sourceCode)) lookup(property, object, property.key);
|
|
754
|
-
},
|
|
755
|
-
BinaryExpression(node) {
|
|
756
|
-
if (environment === null || node.operator !== "in" || isStaticKey(node.left) || isPredicateKey(node) || tableKind(node.right, environment) === null) return;
|
|
757
|
-
report({
|
|
758
|
-
node,
|
|
759
|
-
messageId: "inOperator",
|
|
760
|
-
table: context.sourceCode.getText(node.right),
|
|
761
|
-
key: context.sourceCode.getText(node.left)
|
|
762
|
-
});
|
|
763
|
-
}
|
|
764
|
-
};
|
|
765
|
-
}
|
|
766
|
-
});
|
|
767
|
-
//#endregion
|
|
768
|
-
//#region src/oxc/guardrails/rules/no-presence-only-type-guard.ts
|
|
769
|
-
const MAX_ALIAS_DEPTH = 8;
|
|
770
|
-
const OBJECT_PROTOTYPE_KEYS = Object.getOwnPropertyNames(Object.prototype);
|
|
771
|
-
const OPEN_TYPES = /* @__PURE__ */ new Set(["TSUnknownKeyword", "TSAnyKeyword"]);
|
|
772
|
-
const WIDE_TYPES = /* @__PURE__ */ new Set([...OPEN_TYPES, "TSObjectKeyword"]);
|
|
773
|
-
function signatureName(member) {
|
|
774
|
-
if (member.type !== "TSPropertySignature" && member.type !== "TSMethodSignature" || member.computed) return null;
|
|
775
|
-
if (member.key.type === "Identifier") return member.key.name;
|
|
776
|
-
return member.key.type === "Literal" ? String(member.key.value) : null;
|
|
777
|
-
}
|
|
778
|
-
function addSignatures(members, body) {
|
|
779
|
-
for (const member of body) {
|
|
780
|
-
const name = signatureName(member);
|
|
781
|
-
if (name === null) continue;
|
|
782
|
-
members.set(name, member.type === "TSPropertySignature" ? member.typeAnnotation?.typeAnnotation ?? null : null);
|
|
783
|
-
}
|
|
784
|
-
}
|
|
785
|
-
function referenceMembers(type, types, depth) {
|
|
786
|
-
const name = referenceName(type);
|
|
787
|
-
if (name === null) return null;
|
|
788
|
-
const alias = types.aliases.get(name);
|
|
789
|
-
if (alias !== void 0) return declaredMembers(alias, types, depth + 1);
|
|
790
|
-
const declarations = types.interfaces.get(name);
|
|
791
|
-
if (declarations === void 0) return null;
|
|
792
|
-
const members = /* @__PURE__ */ new Map();
|
|
793
|
-
for (const declaration of declarations) addSignatures(members, declaration.body.body);
|
|
794
|
-
return members;
|
|
795
|
-
}
|
|
796
|
-
/** The members a narrowed type declares in this file, or null when the file does not declare them. */
|
|
797
|
-
function declaredMembers(type, types, depth = 0) {
|
|
798
|
-
if (depth > MAX_ALIAS_DEPTH) return null;
|
|
799
|
-
switch (type.type) {
|
|
800
|
-
case "TSParenthesizedType": return declaredMembers(type.typeAnnotation, types, depth);
|
|
801
|
-
case "TSTypeLiteral": {
|
|
802
|
-
const members = /* @__PURE__ */ new Map();
|
|
803
|
-
addSignatures(members, type.members);
|
|
804
|
-
return members;
|
|
805
|
-
}
|
|
806
|
-
case "TSTypeReference": return referenceMembers(type, types, depth);
|
|
807
|
-
case "TSIntersectionType": {
|
|
808
|
-
const parts = type.types.map((part) => declaredMembers(part, types, depth)).filter((part) => part !== null);
|
|
809
|
-
return parts.length === 0 ? null : new Map(parts.flatMap((part) => [...part]));
|
|
810
|
-
}
|
|
811
|
-
default: return null;
|
|
812
|
-
}
|
|
813
|
-
}
|
|
814
|
-
function parameterType(fn, name) {
|
|
815
|
-
for (const parameter of fn.params) {
|
|
816
|
-
const binding = parameter.type === "AssignmentPattern" ? parameter.left : parameter;
|
|
817
|
-
if (binding.type === "Identifier" && binding.name === name) return binding.typeAnnotation?.typeAnnotation ?? void 0;
|
|
818
|
-
}
|
|
819
|
-
}
|
|
820
|
-
/**
|
|
821
|
-
* A key typed `prefix${string}` cannot name an inherited member when no `Object.prototype` member starts with that prefix.
|
|
822
|
-
* The prefix is the cooked text TypeScript reads, so `\x63onstructor` is `constructor`. A prefix with no cooked text is open.
|
|
823
|
-
*/
|
|
824
|
-
function excludesPrototypeKeys(type) {
|
|
825
|
-
if (type?.type !== "TSTemplateLiteralType") return false;
|
|
826
|
-
const prefix = type.quasis[0]?.value.cooked;
|
|
827
|
-
return prefix !== void 0 && prefix !== null && !OBJECT_PROTOTYPE_KEYS.some((key) => key.startsWith(prefix));
|
|
828
|
-
}
|
|
829
|
-
function isOpenRecord(type) {
|
|
830
|
-
const value = type.typeArguments?.params[1];
|
|
831
|
-
return referenceName(type) === "Record" && value !== void 0 && OPEN_TYPES.has(value.type);
|
|
832
|
-
}
|
|
833
|
-
/**
|
|
834
|
-
* A parameter typed `unknown`, `object`, `{}` or an open record carries no member types, so the guard
|
|
835
|
-
* alone vouches for them. A named or inferred parameter type already declares what a discriminant leaves out.
|
|
836
|
-
*/
|
|
837
|
-
function isWide(type) {
|
|
838
|
-
if (type === void 0) return false;
|
|
839
|
-
if (WIDE_TYPES.has(type.type)) return true;
|
|
840
|
-
if (type.type === "TSTypeLiteral") return type.members.length === 0;
|
|
841
|
-
if (type.type === "TSTypeReference") return isOpenRecord(type);
|
|
842
|
-
return type.type === "TSUnionType" && type.types.some(isWide);
|
|
843
|
-
}
|
|
844
|
-
function frameFor(fn) {
|
|
845
|
-
const predicate = parameterPredicate(fn);
|
|
846
|
-
const name = predicate === null ? null : predicateName(predicate);
|
|
847
|
-
const narrowed = predicate?.typeAnnotation?.typeAnnotation;
|
|
848
|
-
if (predicate === null || name === null || narrowed === void 0) return null;
|
|
849
|
-
return {
|
|
850
|
-
name,
|
|
851
|
-
predicate,
|
|
852
|
-
narrowed,
|
|
853
|
-
parameter: parameterType(fn, name),
|
|
854
|
-
aliases: /* @__PURE__ */ new Set([name]),
|
|
855
|
-
reads: [],
|
|
856
|
-
dynamicReads: [],
|
|
857
|
-
presence: []
|
|
858
|
-
};
|
|
859
|
-
}
|
|
860
|
-
function guardDeclarations(program) {
|
|
861
|
-
const guards = /* @__PURE__ */ new Map();
|
|
862
|
-
const record = (name, fn) => {
|
|
863
|
-
const narrowed = parameterPredicate(fn)?.typeAnnotation?.typeAnnotation;
|
|
864
|
-
if (narrowed !== void 0) guards.set(name, narrowed);
|
|
865
|
-
};
|
|
866
|
-
for (const statement of program.body) {
|
|
867
|
-
const declaration = statement.type === "ExportNamedDeclaration" ? statement.declaration : statement;
|
|
868
|
-
if (declaration?.type === "FunctionDeclaration" && declaration.id !== null) record(declaration.id.name, declaration);
|
|
869
|
-
if (declaration?.type !== "VariableDeclaration") continue;
|
|
870
|
-
for (const declarator of declaration.declarations) {
|
|
871
|
-
const init = declarator.init;
|
|
872
|
-
if (declarator.id.type === "Identifier" && (init?.type === "ArrowFunctionExpression" || init?.type === "FunctionExpression")) record(declarator.id.name, init);
|
|
873
|
-
}
|
|
874
|
-
}
|
|
875
|
-
return guards;
|
|
876
|
-
}
|
|
877
|
-
function unwrapAlias(node) {
|
|
878
|
-
let current = unwrapExpression(node);
|
|
879
|
-
while (current.type === "TSAsExpression" || current.type === "TSSatisfiesExpression" || current.type === "TSTypeAssertion") current = unwrapExpression(current.expression);
|
|
880
|
-
return current;
|
|
881
|
-
}
|
|
882
|
-
const PRESENCE_CALLS = /* @__PURE__ */ new Set([
|
|
883
|
-
"Object.hasOwn",
|
|
884
|
-
"hasOwnProperty.call",
|
|
885
|
-
"Reflect.has"
|
|
886
|
-
]);
|
|
887
|
-
/** `Object.hasOwn(x, "k")`, `hasOwnProperty.call(x, "k")` and `Reflect.has(x, "k")` test presence, as `"k" in x` does. */
|
|
888
|
-
function presenceCall(node) {
|
|
889
|
-
const [first, second] = node.arguments;
|
|
890
|
-
if (!PRESENCE_CALLS.has(callName(node.callee) ?? "") && !isHasOwnPropertyCall(node.callee) || first === void 0 || first.type === "SpreadElement" || second?.type !== "Literal") return null;
|
|
891
|
-
const object = unwrapAlias(first);
|
|
892
|
-
return object.type === "Identifier" ? {
|
|
893
|
-
object: object.name,
|
|
894
|
-
key: String(second.value)
|
|
895
|
-
} : null;
|
|
896
|
-
}
|
|
897
|
-
function callReads(node, environment) {
|
|
898
|
-
const objects = node.arguments.flatMap((argument) => argument.type === "Identifier" ? [argument.name] : []);
|
|
899
|
-
const keys = node.arguments.flatMap((argument) => argument.type === "Literal" ? [String(argument.value)] : []);
|
|
900
|
-
const guard = node.callee.type === "Identifier" ? environment.guards.get(node.callee.name) : void 0;
|
|
901
|
-
if (guard !== void 0) keys.push(...declaredMembers(guard, environment.types)?.keys() ?? []);
|
|
902
|
-
return objects.flatMap((object) => keys.map((key) => [object, key]));
|
|
903
|
-
}
|
|
904
|
-
/** Reports the presence-only checks and unread members of one finished guard. */
|
|
905
|
-
function evaluate(frame, env, context) {
|
|
906
|
-
const wide = isWide(frame.parameter);
|
|
907
|
-
if (!wide && frame.narrowed.type !== "TSIntersectionType") return;
|
|
908
|
-
const members = declaredMembers(frame.narrowed, env.types);
|
|
909
|
-
const isRead = (key) => frame.reads.some(([object, read]) => read === key && frame.aliases.has(object));
|
|
910
|
-
const isOpen = (key) => {
|
|
911
|
-
const type = members?.get(key);
|
|
912
|
-
return type !== void 0 && type !== null && OPEN_TYPES.has(type.type);
|
|
913
|
-
};
|
|
914
|
-
const present = /* @__PURE__ */ new Set();
|
|
915
|
-
for (const presence of frame.presence) {
|
|
916
|
-
if (!frame.aliases.has(presence.object)) continue;
|
|
917
|
-
present.add(presence.key);
|
|
918
|
-
if (isRead(presence.key) || isOpen(presence.key)) continue;
|
|
919
|
-
context.report({
|
|
920
|
-
node: presence.node,
|
|
921
|
-
messageId: "presenceOnly",
|
|
922
|
-
data: {
|
|
923
|
-
key: presence.key,
|
|
924
|
-
param: presence.object
|
|
925
|
-
}
|
|
926
|
-
});
|
|
927
|
-
}
|
|
928
|
-
const dynamic = frame.dynamicReads.some((object) => frame.aliases.has(object));
|
|
929
|
-
if (!wide || dynamic) return;
|
|
930
|
-
for (const member of members?.keys() ?? []) {
|
|
931
|
-
if (isOpen(member) || present.has(member) || isRead(member)) continue;
|
|
932
|
-
context.report({
|
|
933
|
-
node: frame.predicate,
|
|
934
|
-
messageId: "uncheckedMember",
|
|
935
|
-
data: {
|
|
936
|
-
member,
|
|
937
|
-
param: frame.name,
|
|
938
|
-
type: context.sourceCode.getText(frame.narrowed)
|
|
939
|
-
}
|
|
940
|
-
});
|
|
941
|
-
}
|
|
942
|
-
}
|
|
943
|
-
/** A type predicate must check what it narrows to, not only that a key is present. */
|
|
944
|
-
const noPresenceOnlyTypeGuardRule = defineRule({
|
|
945
|
-
meta: {
|
|
946
|
-
type: "problem",
|
|
947
|
-
docs: { description: "Disallow type predicates that narrow on `in` alone: a key answered by the prototype, or a member whose value is never checked." },
|
|
948
|
-
messages: {
|
|
949
|
-
inheritedKey: "`{{ key }} in ...` is also true for keys inherited from `Object.prototype` such as `constructor` and `toString`, so this guard narrows `{{ key }}` to keys the table does not have. Use `Object.hasOwn(table, {{ key }})`, or keep the keys in a `Map` or `Set` and call `.has({{ key }})`.",
|
|
950
|
-
presenceOnly: "`\"{{ key }}\" in {{ param }}` checks only that `{{ key }}` is present, yet the guard narrows `{{ param }}` to a type that declares its value. Check the value too (`typeof {{ param }}.{{ key }} === \"function\"`, `Array.isArray({{ param }}.{{ key }})`, a nested guard), or parse `{{ param }}` with a schema.",
|
|
951
|
-
uncheckedMember: "This guard narrows `{{ param }}` to `{{ type }}` but never reads `{{ param }}.{{ member }}`, so a value with any `{{ member }}` passes. Check it (`typeof`, `Array.isArray`, a nested guard), narrow to a type without it (`Pick<...>`), or parse `{{ param }}` with a schema."
|
|
952
|
-
}
|
|
953
|
-
},
|
|
954
|
-
createOnce(context) {
|
|
955
|
-
let environment = null;
|
|
956
|
-
const stack = [];
|
|
957
|
-
const active = () => stack.filter((frame) => frame !== null);
|
|
958
|
-
const enter = (fn) => {
|
|
959
|
-
stack.push(frameFor(fn));
|
|
960
|
-
};
|
|
961
|
-
const leave = () => {
|
|
962
|
-
const frame = stack.pop();
|
|
963
|
-
if (frame !== null && frame !== void 0 && environment !== null) evaluate(frame, environment, context);
|
|
964
|
-
};
|
|
965
|
-
return {
|
|
966
|
-
Program(node) {
|
|
967
|
-
environment = {
|
|
968
|
-
types: collectLocalTypes(node),
|
|
969
|
-
guards: guardDeclarations(node)
|
|
970
|
-
};
|
|
971
|
-
stack.length = 0;
|
|
972
|
-
},
|
|
973
|
-
FunctionDeclaration: enter,
|
|
974
|
-
FunctionExpression: enter,
|
|
975
|
-
ArrowFunctionExpression: enter,
|
|
976
|
-
"FunctionDeclaration:exit": leave,
|
|
977
|
-
"FunctionExpression:exit": leave,
|
|
978
|
-
"ArrowFunctionExpression:exit": leave,
|
|
979
|
-
MemberExpression(node) {
|
|
980
|
-
const target = unwrapAlias(node.object);
|
|
981
|
-
if (target.type !== "Identifier") return;
|
|
982
|
-
const object = target.name;
|
|
983
|
-
const key = memberName(node);
|
|
984
|
-
for (const frame of active()) if (key === null) frame.dynamicReads.push(object);
|
|
985
|
-
else frame.reads.push([object, key]);
|
|
986
|
-
},
|
|
987
|
-
CallExpression(node) {
|
|
988
|
-
if (environment === null) return;
|
|
989
|
-
const presence = presenceCall(node);
|
|
990
|
-
if (presence !== null) {
|
|
991
|
-
active().at(-1)?.presence.push({
|
|
992
|
-
node,
|
|
993
|
-
...presence
|
|
994
|
-
});
|
|
995
|
-
return;
|
|
996
|
-
}
|
|
997
|
-
const reads = callReads(node, environment);
|
|
998
|
-
for (const frame of active()) frame.reads.push(...reads);
|
|
999
|
-
},
|
|
1000
|
-
VariableDeclarator(node) {
|
|
1001
|
-
if (node.init === null) return;
|
|
1002
|
-
const init = unwrapAlias(node.init);
|
|
1003
|
-
if (init.type !== "Identifier") return;
|
|
1004
|
-
for (const frame of active()) {
|
|
1005
|
-
if (!frame.aliases.has(init.name)) continue;
|
|
1006
|
-
if (node.id.type === "Identifier") frame.aliases.add(node.id.name);
|
|
1007
|
-
if (node.id.type !== "ObjectPattern") continue;
|
|
1008
|
-
for (const property of node.id.properties) if (property.type === "Property" && property.key.type === "Identifier") frame.reads.push([init.name, property.key.name]);
|
|
1009
|
-
}
|
|
1010
|
-
},
|
|
1011
|
-
BinaryExpression(node) {
|
|
1012
|
-
const frame = active().at(-1);
|
|
1013
|
-
if (node.operator !== "in" || frame === void 0) return;
|
|
1014
|
-
if (node.left.type === "Identifier" && node.left.name === frame.name) {
|
|
1015
|
-
if (!excludesPrototypeKeys(frame.parameter)) context.report({
|
|
1016
|
-
node,
|
|
1017
|
-
messageId: "inheritedKey",
|
|
1018
|
-
data: { key: frame.name }
|
|
1019
|
-
});
|
|
1020
|
-
return;
|
|
1021
|
-
}
|
|
1022
|
-
if (node.left.type === "Literal" && node.right.type === "Identifier") frame.presence.push({
|
|
1023
|
-
node,
|
|
1024
|
-
object: node.right.name,
|
|
1025
|
-
key: String(node.left.value)
|
|
1026
|
-
});
|
|
1027
|
-
}
|
|
1028
|
-
};
|
|
1029
|
-
}
|
|
1030
|
-
});
|
|
1031
|
-
//#endregion
|
|
1032
|
-
//#region src/oxc/guardrails/rules/no-read-then-insert.ts
|
|
1033
|
-
const READ_METHODS = /* @__PURE__ */ new Set([
|
|
1034
|
-
"get",
|
|
1035
|
-
"getBy",
|
|
1036
|
-
"getAll",
|
|
1037
|
-
"count",
|
|
1038
|
-
"find",
|
|
1039
|
-
"findOne"
|
|
1040
|
-
]);
|
|
1041
|
-
const INSERT_METHODS = /* @__PURE__ */ new Set([
|
|
1042
|
-
"insert",
|
|
1043
|
-
"insertOne",
|
|
1044
|
-
"insertMany"
|
|
1045
|
-
]);
|
|
1046
|
-
const INLINE_CALLBACK_METHODS = /* @__PURE__ */ new Set([
|
|
1047
|
-
"map",
|
|
1048
|
-
"flatMap",
|
|
1049
|
-
"forEach",
|
|
1050
|
-
"filter",
|
|
1051
|
-
"reduce",
|
|
1052
|
-
"some",
|
|
1053
|
-
"every",
|
|
1054
|
-
"then",
|
|
1055
|
-
"catch",
|
|
1056
|
-
"finally"
|
|
1057
|
-
]);
|
|
1058
|
-
const DUPLICATE_CHECK = /duplicate|unique|conflict|E11000|^11000$|23505|ER_DUP_ENTRY/iu;
|
|
1059
|
-
function contains(outer, inner) {
|
|
1060
|
-
return outer[0] <= inner[0] && inner[1] <= outer[1];
|
|
1061
|
-
}
|
|
1062
|
-
function isScope(node) {
|
|
1063
|
-
return node.type === "Program" || node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression";
|
|
1064
|
-
}
|
|
1065
|
-
function enclosingScope(node) {
|
|
1066
|
-
let current = node.parent;
|
|
1067
|
-
while (current !== null) {
|
|
1068
|
-
if (isScope(current)) return current;
|
|
1069
|
-
current = current.parent;
|
|
1070
|
-
}
|
|
1071
|
-
return null;
|
|
1072
|
-
}
|
|
1073
|
-
/** A callback that runs while its caller waits: handed to `map`, `then` or the like, or to a call whose value the caller awaits or returns. A handler registered by `app.post(...)` or wrapped by `export const POST = withAuth(...)` runs later, on its own. */
|
|
1074
|
-
function isInlineCallback(scope) {
|
|
1075
|
-
const call = scope.parent;
|
|
1076
|
-
if (scope.type === "Program" || scope.type === "FunctionDeclaration" || call?.type !== "CallExpression" || !call.arguments.some((argument) => argument === scope)) return false;
|
|
1077
|
-
const method = call.callee.type === "MemberExpression" ? memberName(call.callee) : null;
|
|
1078
|
-
return method !== null && INLINE_CALLBACK_METHODS.has(method) || isAwaited(call);
|
|
1079
|
-
}
|
|
1080
|
-
/** Whether the call's value reaches an `await` or a `return`, through array elements, call arguments, `?.` or a `.then` chain, or is the body of an inline arrow. */
|
|
1081
|
-
function isAwaited(call) {
|
|
1082
|
-
let node = call;
|
|
1083
|
-
let parent = node.parent;
|
|
1084
|
-
while (parent !== null) {
|
|
1085
|
-
if (parent.type === "AwaitExpression" || parent.type === "ReturnStatement") return true;
|
|
1086
|
-
if (parent.type === "ArrowFunctionExpression" && parent.body === node) return isInlineCallback(parent);
|
|
1087
|
-
if (!(parent.type === "ArrayExpression" || parent.type === "ChainExpression" || parent.type === "SpreadElement" || parent.type === "CallExpression" || parent.type === "MemberExpression" && parent.object === node)) return false;
|
|
1088
|
-
node = parent;
|
|
1089
|
-
parent = node.parent;
|
|
1090
|
-
}
|
|
1091
|
-
return false;
|
|
1092
|
-
}
|
|
1093
|
-
/** The function a read or an insert runs in, seen through inline callbacks such as `withRetry(() => model.getAll())` or `rows.map((row) => model.insert(row))`. */
|
|
1094
|
-
function runningScope(node) {
|
|
1095
|
-
let scope = enclosingScope(node);
|
|
1096
|
-
while (scope !== null && isInlineCallback(scope)) scope = enclosingScope(scope);
|
|
1097
|
-
return scope;
|
|
1098
|
-
}
|
|
1099
|
-
function chainsFrom(node, call) {
|
|
1100
|
-
let current = node;
|
|
1101
|
-
while (current !== call) if (current.type === "CallExpression") current = current.callee;
|
|
1102
|
-
else if (current.type === "MemberExpression") current = current.object;
|
|
1103
|
-
else return false;
|
|
1104
|
-
return true;
|
|
1105
|
-
}
|
|
1106
|
-
function rootName(node) {
|
|
1107
|
-
let current = node;
|
|
1108
|
-
while (current.type === "MemberExpression" || current.type === "CallExpression") current = current.type === "MemberExpression" ? current.object : current.callee;
|
|
1109
|
-
return current.type === "Identifier" ? current.name : null;
|
|
1110
|
-
}
|
|
1111
|
-
function declares(scope, name) {
|
|
1112
|
-
return scope.type !== "Program" && scope.params.some((param) => param.type === "Identifier" && param.name === name);
|
|
1113
|
-
}
|
|
1114
|
-
function calledMember(node, methods) {
|
|
1115
|
-
if (node.callee.type !== "MemberExpression") return null;
|
|
1116
|
-
const name = memberName(node.callee);
|
|
1117
|
-
return name !== null && methods.has(name) ? node.callee : null;
|
|
1118
|
-
}
|
|
1119
|
-
function isUpsert(node) {
|
|
1120
|
-
return node.arguments.slice(1).some((argument) => argument.type === "ObjectExpression" && argument.properties.some((property) => property.type === "Property" && !property.computed && (property.key.type === "Identifier" && property.key.name === "conflict" || property.key.type === "Literal" && property.key.value === "conflict") && !(property.value.type === "Literal" && property.value.value === "error")));
|
|
1121
|
-
}
|
|
1122
|
-
/** `model.get` and `model.insert` touch one table, and so do `model.get` and the model's raw `model.table.insert`, but not `db.table("a")` and `db.table("b")`, nor `this.get` and `this.audit.insert`. */
|
|
1123
|
-
function sameTable(read, insert) {
|
|
1124
|
-
return read.receivers.has(insert.receiver) || insert.receiver === `${read.receiver}.table`;
|
|
1125
|
-
}
|
|
1126
|
-
/** A catch that returns, continues or breaks in its own function without a rejection, or keeps every `throw` inside a branch, can finish without rethrowing. */
|
|
1127
|
-
function canFinish(facts, handler) {
|
|
1128
|
-
const own = handler.type === "BlockStatement" ? enclosingScope(handler) : handler;
|
|
1129
|
-
const block = handler.type === "BlockStatement" ? handler : (handler.type === "ArrowFunctionExpression" || handler.type === "FunctionExpression") && handler.body?.type === "BlockStatement" ? handler.body : null;
|
|
1130
|
-
return facts.exits.some((exit) => contains(handler.range, exit.range) && enclosingScope(exit) === own && !facts.throwRanges.some((thrown) => contains(exit.range, thrown))) || !facts.throwBlocks.some((thrownIn) => thrownIn === block);
|
|
1131
|
-
}
|
|
1132
|
-
/** A catch tolerates the lost race when it rethrows nothing, or when it can finish without rethrowing and either reads the table back or checks for a duplicate outside a `throw`. */
|
|
1133
|
-
function recovers(facts, handler, insert) {
|
|
1134
|
-
if (handler.type !== "BlockStatement" && handler.type !== "ArrowFunctionExpression" && handler.type !== "FunctionExpression") return DUPLICATE_CHECK.test(facts.text(handler));
|
|
1135
|
-
const range = handler.range;
|
|
1136
|
-
if (!facts.throwRanges.some((thrown) => contains(range, thrown))) return true;
|
|
1137
|
-
if (!canFinish(facts, handler)) return false;
|
|
1138
|
-
return facts.reads.some((read) => contains(range, read.range) && sameTable(read, insert)) || facts.duplicateChecks.some((check) => contains(range, check) && !facts.throwRanges.some((thrown) => contains(thrown, check)));
|
|
1139
|
-
}
|
|
1140
|
-
function isHandedToHelper(facts, insert, child, parent) {
|
|
1141
|
-
return (child.type === "ArrowFunctionExpression" || child.type === "FunctionExpression") && parent.type === "CallExpression" && parent.arguments.some((argument) => argument !== child && facts.text(argument) === insert.receiver);
|
|
1142
|
-
}
|
|
1143
|
-
function recoveryOf(insert, child, parent) {
|
|
1144
|
-
if (parent.type === "TryStatement" && parent.block === child) return parent.handler?.body ?? null;
|
|
1145
|
-
if (parent.type === "MemberExpression" && parent.object === child && chainsFrom(child, insert.call) && memberName(parent) === "catch" && parent.parent?.type === "CallExpression" && parent.parent.callee === parent) return parent.parent.arguments[0] ?? null;
|
|
1146
|
-
return null;
|
|
1147
|
-
}
|
|
1148
|
-
function isGuarded(facts, insert, read) {
|
|
1149
|
-
let child = insert.call;
|
|
1150
|
-
let parent = child.parent;
|
|
1151
|
-
while (parent !== null && child !== read.scope) {
|
|
1152
|
-
const between = !contains(child.range, read.range);
|
|
1153
|
-
if (between && insert.root !== null && isScope(child) && declares(child, insert.root)) return true;
|
|
1154
|
-
if (between && isHandedToHelper(facts, insert, child, parent)) return true;
|
|
1155
|
-
const recovery = recoveryOf(insert, child, parent);
|
|
1156
|
-
if (recovery !== null && recovers(facts, recovery, insert)) return true;
|
|
1157
|
-
child = parent;
|
|
1158
|
-
parent = child.parent;
|
|
1159
|
-
}
|
|
1160
|
-
return false;
|
|
1161
|
-
}
|
|
1162
|
-
function isRaced(facts, insert) {
|
|
1163
|
-
const start = insert.call.range[0];
|
|
1164
|
-
return facts.reads.some((read) => sameTable(read, insert) && read.range[1] <= start && read.scope === insert.scope && !isGuarded(facts, insert, read));
|
|
1165
|
-
}
|
|
1166
|
-
/** Writing a row that a startup read found missing races every other replica that read the same. A catch that rethrows nothing, recognises a duplicate in a condition, or reads the row back and branches, tolerates the lost race, and so does an upsert or a helper handed the table. */
|
|
1167
|
-
const noReadThenInsertRule = defineRule({
|
|
1168
|
-
meta: {
|
|
1169
|
-
type: "problem",
|
|
1170
|
-
docs: { description: "Reject an insert that follows a read of the same table unless a catch tolerates losing it." },
|
|
1171
|
-
messages: { readThenInsert: "`{{receiver}}` is read and then inserted into. Two replicas that start on an empty table both read nothing and both insert, so one writes a duplicate row or fails on the key. Key the row by a stable id, wrap the insert in try/catch, read the row back in the catch, and rethrow only when it is still missing, or upsert with `insert(row, { conflict: \"update\" })`." }
|
|
1172
|
-
},
|
|
1173
|
-
createOnce(context) {
|
|
1174
|
-
const inserts = [];
|
|
1175
|
-
const facts = {
|
|
1176
|
-
reads: [],
|
|
1177
|
-
duplicateChecks: [],
|
|
1178
|
-
throwRanges: [],
|
|
1179
|
-
throwBlocks: [],
|
|
1180
|
-
exits: [],
|
|
1181
|
-
text: (node) => context.sourceCode.getText(node)
|
|
1182
|
-
};
|
|
1183
|
-
const { reads, duplicateChecks, throwRanges, exits } = facts;
|
|
1184
|
-
function receiverChain(start) {
|
|
1185
|
-
const texts = /* @__PURE__ */ new Set();
|
|
1186
|
-
let current = start;
|
|
1187
|
-
while (current !== null) {
|
|
1188
|
-
texts.add(facts.text(current));
|
|
1189
|
-
if (current.type === "CallExpression") current = current.callee;
|
|
1190
|
-
else if (current.type === "MemberExpression") current = current.object;
|
|
1191
|
-
else current = null;
|
|
1192
|
-
}
|
|
1193
|
-
return texts;
|
|
1194
|
-
}
|
|
1195
|
-
return {
|
|
1196
|
-
before() {
|
|
1197
|
-
reads.length = 0;
|
|
1198
|
-
inserts.length = 0;
|
|
1199
|
-
duplicateChecks.length = 0;
|
|
1200
|
-
throwRanges.length = 0;
|
|
1201
|
-
facts.throwBlocks.length = 0;
|
|
1202
|
-
exits.length = 0;
|
|
1203
|
-
},
|
|
1204
|
-
ThrowStatement(node) {
|
|
1205
|
-
throwRanges.push(node.range);
|
|
1206
|
-
if (node.parent !== null) facts.throwBlocks.push(node.parent);
|
|
1207
|
-
},
|
|
1208
|
-
ReturnStatement(node) {
|
|
1209
|
-
exits.push(node);
|
|
1210
|
-
},
|
|
1211
|
-
ContinueStatement(node) {
|
|
1212
|
-
exits.push(node);
|
|
1213
|
-
},
|
|
1214
|
-
BreakStatement(node) {
|
|
1215
|
-
exits.push(node);
|
|
1216
|
-
},
|
|
1217
|
-
Identifier(node) {
|
|
1218
|
-
if (DUPLICATE_CHECK.test(node.name)) duplicateChecks.push(node.range);
|
|
1219
|
-
},
|
|
1220
|
-
TemplateLiteral(node) {
|
|
1221
|
-
if (node.quasis.some((quasi) => DUPLICATE_CHECK.test(quasi.value.raw))) duplicateChecks.push(node.range);
|
|
1222
|
-
},
|
|
1223
|
-
Literal(node) {
|
|
1224
|
-
if (DUPLICATE_CHECK.test(String(node.value))) duplicateChecks.push(node.range);
|
|
1225
|
-
},
|
|
1226
|
-
CallExpression(node) {
|
|
1227
|
-
if (facts.text(node.callee) === "Promise.reject") {
|
|
1228
|
-
throwRanges.push(node.range);
|
|
1229
|
-
const statement = node.parent;
|
|
1230
|
-
if (statement?.type === "ReturnStatement" && statement.parent !== null) facts.throwBlocks.push(statement.parent);
|
|
1231
|
-
}
|
|
1232
|
-
const read = calledMember(node, READ_METHODS);
|
|
1233
|
-
const scope = runningScope(node);
|
|
1234
|
-
if (read !== null && scope !== null) reads.push({
|
|
1235
|
-
range: node.range,
|
|
1236
|
-
scope,
|
|
1237
|
-
receiver: facts.text(read.object),
|
|
1238
|
-
receivers: receiverChain(read.object)
|
|
1239
|
-
});
|
|
1240
|
-
const insert = calledMember(node, INSERT_METHODS);
|
|
1241
|
-
if (insert !== null && scope !== null && !isUpsert(node)) inserts.push({
|
|
1242
|
-
call: node,
|
|
1243
|
-
scope,
|
|
1244
|
-
callee: insert,
|
|
1245
|
-
receiver: facts.text(insert.object),
|
|
1246
|
-
root: rootName(insert.object)
|
|
1247
|
-
});
|
|
1248
|
-
},
|
|
1249
|
-
"Program:exit"() {
|
|
1250
|
-
for (const insert of inserts) if (isRaced(facts, insert)) context.report({
|
|
1251
|
-
node: insert.callee,
|
|
1252
|
-
messageId: "readThenInsert",
|
|
1253
|
-
data: { receiver: insert.receiver }
|
|
1254
|
-
});
|
|
1255
|
-
}
|
|
1256
|
-
};
|
|
1257
|
-
}
|
|
1258
|
-
});
|
|
1259
|
-
//#endregion
|
|
1260
|
-
//#region src/oxc/guardrails/self-package.ts
|
|
1261
|
-
function isObject(value) {
|
|
1262
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1263
|
-
}
|
|
1264
|
-
function isText(value) {
|
|
1265
|
-
return typeof value === "string";
|
|
1266
|
-
}
|
|
1267
|
-
function readManifest(directory) {
|
|
1268
|
-
let parsed;
|
|
1269
|
-
try {
|
|
1270
|
-
parsed = JSON.parse(readFileSync(join(directory, "package.json"), "utf8"));
|
|
1271
|
-
} catch {
|
|
1272
|
-
return;
|
|
1273
|
-
}
|
|
1274
|
-
if (!isObject(parsed) || !isText(parsed.name)) return void 0;
|
|
1275
|
-
const { antelopeJs } = parsed;
|
|
1276
|
-
return {
|
|
1277
|
-
name: parsed.name,
|
|
1278
|
-
exports: parsed.exports,
|
|
1279
|
-
testedByAjs: isObject(antelopeJs) && isText(antelopeJs.test)
|
|
1280
|
-
};
|
|
1281
|
-
}
|
|
1282
|
-
/** The nearest enclosing package that has a name, with the directory holding its manifest. */
|
|
1283
|
-
function enclosingPackage(file) {
|
|
1284
|
-
let directory = dirname(file);
|
|
1285
|
-
for (;;) {
|
|
1286
|
-
const manifest = readManifest(directory);
|
|
1287
|
-
if (manifest !== void 0) return {
|
|
1288
|
-
directory,
|
|
1289
|
-
manifest
|
|
1290
|
-
};
|
|
1291
|
-
const parent = dirname(directory);
|
|
1292
|
-
if (parent === directory) return void 0;
|
|
1293
|
-
directory = parent;
|
|
1294
|
-
}
|
|
1295
|
-
}
|
|
1296
|
-
/** The subpath of `specifier` inside package `name` (`.` for the root), or undefined when it names another package. */
|
|
1297
|
-
function selfSubpath(name, specifier) {
|
|
1298
|
-
if (specifier === name) return ".";
|
|
1299
|
-
return specifier.startsWith(`${name}/`) ? `./${specifier.slice(name.length + 1)}` : void 0;
|
|
1300
|
-
}
|
|
1301
|
-
function exportKeys(exportsField) {
|
|
1302
|
-
if (!isObject(exportsField)) return ["."];
|
|
1303
|
-
const keys = Object.keys(exportsField);
|
|
1304
|
-
return keys.some((key) => key.startsWith(".")) ? keys : ["."];
|
|
1305
|
-
}
|
|
1306
|
-
function patternMatches(key, subpath) {
|
|
1307
|
-
const star = key.indexOf("*");
|
|
1308
|
-
if (star === -1) return key === subpath;
|
|
1309
|
-
const prefix = key.slice(0, star);
|
|
1310
|
-
const suffix = key.slice(star + 1);
|
|
1311
|
-
return subpath.length >= key.length - 1 && subpath.startsWith(prefix) && subpath.endsWith(suffix);
|
|
1312
|
-
}
|
|
1313
|
-
/** Whether the package `exports` map publishes `subpath`, so Node can resolve a self-import to it. */
|
|
1314
|
-
function exportsCover(exportsField, subpath) {
|
|
1315
|
-
if (exportsField === void 0 || exportsField === null) return false;
|
|
1316
|
-
return exportKeys(exportsField).some((key) => patternMatches(key, subpath));
|
|
1317
|
-
}
|
|
1318
|
-
/** Whether `node_modules/<name>` is a link back to the package itself, as a workspace self-link makes it. */
|
|
1319
|
-
function isSelfLinked(directory, name) {
|
|
1320
|
-
const installed = join(directory, "node_modules", ...name.split("/"));
|
|
1321
|
-
try {
|
|
1322
|
-
return lstatSync(installed).isSymbolicLink() && realpathSync.native(installed) === realpathSync.native(directory);
|
|
1323
|
-
} catch {
|
|
1324
|
-
return false;
|
|
1325
|
-
}
|
|
1326
|
-
}
|
|
1327
|
-
//#endregion
|
|
1328
|
-
//#region src/oxc/guardrails/rules/no-self-import-in-tests.ts
|
|
1329
|
-
/** A test that imports its own package name must reach local code: the `exports` map publishes the subpath and `node_modules` links the package to itself. Under `ajs module test` no self-link reaches local code, so every self-import is reported. */
|
|
1330
|
-
const noSelfImportInTestsRule = defineRule({
|
|
1331
|
-
meta: {
|
|
1332
|
-
type: "problem",
|
|
1333
|
-
docs: { description: "Tests import the module under test from local source, never their own published package name." },
|
|
1334
|
-
messages: {
|
|
1335
|
-
selfImport: "This test imports its own package `{{ name }}`, which resolves to the installed published copy, so it never exercises the local code. Import the module under test by relative path, or make the self-import local: publish `{{ subpath }}` in package.json `exports` and link the package to itself (`link:.` in devDependencies).",
|
|
1336
|
-
selfImportUnderAjsTest: "This test imports its own package `{{ name }}`, and `ajs module test` resolves that name through its own module resolver, which can bind it to a copy installed with another module instead of this package, even with a `link:.` self-link. Import the module under test by relative path."
|
|
1337
|
-
}
|
|
1338
|
-
},
|
|
1339
|
-
createOnce(context) {
|
|
1340
|
-
function check(node, specifier) {
|
|
1341
|
-
const owner = enclosingPackage(context.filename);
|
|
1342
|
-
if (owner === void 0) return;
|
|
1343
|
-
const { directory, manifest } = owner;
|
|
1344
|
-
const subpath = selfSubpath(manifest.name, specifier);
|
|
1345
|
-
if (subpath === void 0) return;
|
|
1346
|
-
if (manifest.testedByAjs) {
|
|
1347
|
-
context.report({
|
|
1348
|
-
node,
|
|
1349
|
-
messageId: "selfImportUnderAjsTest",
|
|
1350
|
-
data: { name: manifest.name }
|
|
1351
|
-
});
|
|
1352
|
-
return;
|
|
1353
|
-
}
|
|
1354
|
-
if (exportsCover(manifest.exports, subpath) && isSelfLinked(directory, manifest.name)) return;
|
|
1355
|
-
context.report({
|
|
1356
|
-
node,
|
|
1357
|
-
messageId: "selfImport",
|
|
1358
|
-
data: {
|
|
1359
|
-
name: manifest.name,
|
|
1360
|
-
subpath
|
|
1361
|
-
}
|
|
1362
|
-
});
|
|
1363
|
-
}
|
|
1364
|
-
return {
|
|
1365
|
-
ImportDeclaration(node) {
|
|
1366
|
-
if (node.importKind === "type" || node.specifiers.length > 0 && node.specifiers.every((specifier) => specifier.type === "ImportSpecifier" && specifier.importKind === "type")) return;
|
|
1367
|
-
check(node, node.source.value);
|
|
1368
|
-
},
|
|
1369
|
-
ExportNamedDeclaration(node) {
|
|
1370
|
-
if (node.source && node.exportKind !== "type") check(node, node.source.value);
|
|
1371
|
-
},
|
|
1372
|
-
ExportAllDeclaration(node) {
|
|
1373
|
-
if (node.exportKind !== "type") check(node, node.source.value);
|
|
1374
|
-
},
|
|
1375
|
-
ImportExpression(node) {
|
|
1376
|
-
if (node.source.type === "Literal" && !("regex" in node.source)) check(node, String(node.source.value));
|
|
1377
|
-
},
|
|
1378
|
-
TSImportEqualsDeclaration(node) {
|
|
1379
|
-
const reference = node.moduleReference;
|
|
1380
|
-
if (node.importKind !== "type" && reference.type === "TSExternalModuleReference") check(node, reference.expression.value);
|
|
1381
|
-
},
|
|
1382
|
-
CallExpression(node) {
|
|
1383
|
-
const [argument] = node.arguments;
|
|
1384
|
-
if (node.callee.type === "Identifier" && node.callee.name === "require" && argument?.type === "Literal" && !("regex" in argument)) check(node, String(argument.value));
|
|
1385
|
-
}
|
|
1386
|
-
};
|
|
1387
|
-
}
|
|
1388
|
-
});
|
|
1389
|
-
//#endregion
|
|
1390
|
-
//#region src/oxc/guardrails/rules/no-typeof-function-only-test.ts
|
|
1391
|
-
const functionMatchers = /* @__PURE__ */ new Set([
|
|
1392
|
-
"toBeTypeOf",
|
|
1393
|
-
"to.be.a",
|
|
1394
|
-
"to.be.an"
|
|
1395
|
-
]);
|
|
1396
|
-
const typeofMatchers = /* @__PURE__ */ new Set(["toBe", "to.equal"]);
|
|
1397
|
-
const assertTypeofMatchers = /* @__PURE__ */ new Set(["assert.equal", "assert.strictEqual"]);
|
|
1398
|
-
function isTypeof(node) {
|
|
1399
|
-
return node?.type === "UnaryExpression" && node.operator === "typeof";
|
|
1400
|
-
}
|
|
1401
|
-
function isFunctionString(node) {
|
|
1402
|
-
return node?.type === "Literal" && node.value === "function";
|
|
1403
|
-
}
|
|
1404
|
-
function isFunctionCheck(node) {
|
|
1405
|
-
const name = callName(node.callee);
|
|
1406
|
-
if (name === "assert.isFunction") return true;
|
|
1407
|
-
if (name !== null && assertTypeofMatchers.has(name)) return isTypeof(node.arguments[0]) && isFunctionString(node.arguments[1]);
|
|
1408
|
-
let outer = node;
|
|
1409
|
-
while (outer.parent.type === "MemberExpression" && outer.parent.object === outer) {
|
|
1410
|
-
let member = outer.parent;
|
|
1411
|
-
while (member.parent.type === "MemberExpression" && member.parent.object === member) member = member.parent;
|
|
1412
|
-
if (member.parent.type !== "CallExpression" || member.parent.callee !== member) break;
|
|
1413
|
-
outer = member.parent;
|
|
1414
|
-
}
|
|
1415
|
-
const chain = matcherChain(outer);
|
|
1416
|
-
if (chain === null || !isFunctionString(outer.arguments[0])) return false;
|
|
1417
|
-
return functionMatchers.has(chain.matcher) || typeofMatchers.has(chain.matcher) && isTypeof(chain.expect.arguments[0]);
|
|
1418
|
-
}
|
|
1419
|
-
/** Function existence alone is already a type-checker guarantee, not a behavioral test. */
|
|
1420
|
-
const noTypeofFunctionOnlyTestRule = defineRule({
|
|
1421
|
-
meta: {
|
|
1422
|
-
type: "problem",
|
|
1423
|
-
docs: { description: "Require tests to do more than assert that functions exist." },
|
|
1424
|
-
messages: { functionOnly: "The type checker already proves this. Call the function and assert what it returns or does." }
|
|
1425
|
-
},
|
|
1426
|
-
createOnce(context) {
|
|
1427
|
-
const frames = [];
|
|
1428
|
-
function recordAssertion(node) {
|
|
1429
|
-
const frame = frames.at(-1);
|
|
1430
|
-
if (frame === void 0 || node.start < frame.callback.start || node.end > frame.callback.end || !isAssertion(node)) return;
|
|
1431
|
-
frame.assertions.push(node.type === "CallExpression" && isFunctionCheck(node));
|
|
1432
|
-
}
|
|
1433
|
-
return {
|
|
1434
|
-
before() {
|
|
1435
|
-
frames.length = 0;
|
|
1436
|
-
},
|
|
1437
|
-
CallExpression(node) {
|
|
1438
|
-
const callback = testCallback(node);
|
|
1439
|
-
if (callback !== void 0) frames.push({
|
|
1440
|
-
node,
|
|
1441
|
-
callback,
|
|
1442
|
-
assertions: []
|
|
1443
|
-
});
|
|
1444
|
-
else recordAssertion(node);
|
|
1445
|
-
},
|
|
1446
|
-
MemberExpression: recordAssertion,
|
|
1447
|
-
"CallExpression:exit"(node) {
|
|
1448
|
-
const frame = frames.at(-1);
|
|
1449
|
-
if (frame?.node !== node) return;
|
|
1450
|
-
frames.pop();
|
|
1451
|
-
if (frame.assertions.length > 0 && frame.assertions.every(Boolean)) context.report({
|
|
1452
|
-
node,
|
|
1453
|
-
messageId: "functionOnly"
|
|
1454
|
-
});
|
|
1455
|
-
}
|
|
1456
|
-
};
|
|
1457
|
-
}
|
|
1458
|
-
});
|
|
1459
|
-
//#endregion
|
|
1460
|
-
//#region src/oxc/guardrails/literal-fit.ts
|
|
1461
|
-
const MAX_DEPTH$1 = 8;
|
|
1462
|
-
const INDEX = /^\d+$/u;
|
|
1463
|
-
/** The type a written value has: a shorthand property reads its variable, as a direct assignment would. */
|
|
1464
|
-
function valueType(checker, value) {
|
|
1465
|
-
const shorthand = ts.isShorthandPropertyAssignment(value.parent) && value.parent.name === value ? checker.getShorthandAssignmentValueSymbol(value.parent) : void 0;
|
|
1466
|
-
return shorthand === void 0 ? checker.getTypeAtLocation(value) : checker.getTypeOfSymbolAtLocation(shorthand, value);
|
|
1467
|
-
}
|
|
1468
|
-
function propertyName(property) {
|
|
1469
|
-
if (!(ts.isPropertyAssignment(property) || ts.isShorthandPropertyAssignment(property)) || !(ts.isIdentifier(property.name) || ts.isStringLiteral(property.name) || ts.isNumericLiteral(property.name))) return void 0;
|
|
1470
|
-
return {
|
|
1471
|
-
name: property.name.text,
|
|
1472
|
-
value: ts.isPropertyAssignment(property) ? property.initializer : property.name
|
|
1473
|
-
};
|
|
1474
|
-
}
|
|
1475
|
-
function objectFits(checker, literal, type, depth) {
|
|
1476
|
-
const names = /* @__PURE__ */ new Set();
|
|
1477
|
-
for (const property of literal.properties) {
|
|
1478
|
-
const named = propertyName(property);
|
|
1479
|
-
if (named === void 0) return false;
|
|
1480
|
-
names.add(named.name);
|
|
1481
|
-
const field = checker.getPropertyOfType(type, named.name);
|
|
1482
|
-
const fieldType = field === void 0 ? checker.getIndexTypeOfType(type, ts.IndexKind.String) : checker.getTypeOfSymbolAtLocation(field, literal);
|
|
1483
|
-
if (fieldType === void 0 || !literalFits(checker, named.value, fieldType, depth + 1)) return false;
|
|
1484
|
-
}
|
|
1485
|
-
return checker.getPropertiesOfType(type).every((field) => (field.flags & ts.SymbolFlags.Optional) !== 0 || names.has(field.name));
|
|
1486
|
-
}
|
|
1487
|
-
function arrayFits(checker, literal, type, depth) {
|
|
1488
|
-
const { elements } = literal;
|
|
1489
|
-
if (elements.some((element) => ts.isSpreadElement(element) || ts.isOmittedExpression(element))) return false;
|
|
1490
|
-
if (checker.isTupleType(type)) {
|
|
1491
|
-
const slots = checker.getPropertiesOfType(type).filter((slot) => INDEX.test(slot.name));
|
|
1492
|
-
const required = slots.filter((slot) => (slot.flags & ts.SymbolFlags.Optional) === 0);
|
|
1493
|
-
return elements.length >= required.length && elements.length <= slots.length && elements.every((element, index) => literalFits(checker, element, checker.getTypeOfSymbolAtLocation(slots[index], literal), depth + 1));
|
|
1494
|
-
}
|
|
1495
|
-
const element = checker.getIndexTypeOfType(type, ts.IndexKind.Number);
|
|
1496
|
-
return element !== void 0 && elements.every((value) => literalFits(checker, value, element, depth + 1));
|
|
1497
|
-
}
|
|
1498
|
-
/**
|
|
1499
|
-
* Whether `expression` fits `type` the way a direct assignment types it:
|
|
1500
|
-
* literals inside object and array literals keep their literal types, which
|
|
1501
|
-
* `Object.assign`'s inferred source type widens. Object literals need every
|
|
1502
|
-
* required property and no undeclared one, tuples their length. Past the
|
|
1503
|
-
* depth cap a literal fits, so the rule stays silent rather than wrong.
|
|
1504
|
-
*/
|
|
1505
|
-
function literalFits(checker, expression, type, depth = 0) {
|
|
1506
|
-
let value = expression;
|
|
1507
|
-
while (ts.isParenthesizedExpression(value)) value = value.expression;
|
|
1508
|
-
if (checker.isTypeAssignableTo(valueType(checker, value), type)) return true;
|
|
1509
|
-
if (!ts.isObjectLiteralExpression(value) && !ts.isArrayLiteralExpression(value)) return false;
|
|
1510
|
-
if (depth === MAX_DEPTH$1) return true;
|
|
1511
|
-
if (type.isUnion()) return type.types.some((member) => literalFits(checker, value, member, depth));
|
|
1512
|
-
return ts.isObjectLiteralExpression(value) ? objectFits(checker, value, type, depth) : arrayFits(checker, value, type, depth);
|
|
1513
|
-
}
|
|
1514
|
-
//#endregion
|
|
1515
|
-
//#region src/oxc/guardrails/tsconfig-program.ts
|
|
1516
|
-
const CONFIG_NAMES = ["tsconfig.json", "jsconfig.json"];
|
|
1517
|
-
const HOST = {
|
|
1518
|
-
...ts.sys,
|
|
1519
|
-
onUnRecoverableConfigFileDiagnostic: () => void 0
|
|
1520
|
-
};
|
|
1521
|
-
const projects = /* @__PURE__ */ new Map();
|
|
1522
|
-
function configAbove(directory) {
|
|
1523
|
-
for (let current = directory;; current = dirname(current)) {
|
|
1524
|
-
const config = CONFIG_NAMES.map((name) => join(current, name)).find((path) => existsSync(path));
|
|
1525
|
-
if (config !== void 0) return config;
|
|
1526
|
-
if (dirname(current) === current) return void 0;
|
|
1527
|
-
}
|
|
1528
|
-
}
|
|
1529
|
-
/** The files `config` lists, its compiler options and the configs it references, parsed once per lint run. */
|
|
1530
|
-
function project(config) {
|
|
1531
|
-
if (projects.has(config)) return projects.get(config);
|
|
1532
|
-
const parsed = ts.getParsedCommandLineOfConfigFile(config, void 0, HOST);
|
|
1533
|
-
const result = parsed && {
|
|
1534
|
-
files: new Set(parsed.fileNames),
|
|
1535
|
-
options: parsed.options,
|
|
1536
|
-
references: (parsed.projectReferences ?? []).map((reference) => ts.resolveProjectReferencePath(reference)),
|
|
1537
|
-
automaticTypes: parsed.options.types === void 0 ? ts.getAutomaticTypeDirectiveNames(parsed.options, ts.sys) : []
|
|
1538
|
-
};
|
|
1539
|
-
projects.set(config, result);
|
|
1540
|
-
return result;
|
|
1541
|
-
}
|
|
1542
|
-
/** The first config the nearest one or its references reach that lists `file`, skipping configs already visited. */
|
|
1543
|
-
function listing(nearest, file, visited) {
|
|
1544
|
-
const queue = [nearest];
|
|
1545
|
-
for (let config = queue.shift(); config; config = queue.shift()) {
|
|
1546
|
-
if (visited.has(config)) continue;
|
|
1547
|
-
visited.add(config);
|
|
1548
|
-
const parsed = project(config);
|
|
1549
|
-
if (parsed?.files.has(file)) return config;
|
|
1550
|
-
queue.push(...parsed?.references ?? []);
|
|
1551
|
-
}
|
|
1552
|
-
}
|
|
1553
|
-
/**
|
|
1554
|
-
* The tsconfig.json or jsconfig.json whose program type-aware lint gives `file`,
|
|
1555
|
-
* found as oxlint-tsgolint finds it: the nearest config, the configs it references,
|
|
1556
|
-
* then the same search from each config above. Undefined when none lists the file,
|
|
1557
|
-
* where tsgolint reads it in its inferred program.
|
|
1558
|
-
*/
|
|
1559
|
-
function programConfig(file) {
|
|
1560
|
-
const path = resolve(file).replaceAll("\\", "/");
|
|
1561
|
-
const visited = /* @__PURE__ */ new Set();
|
|
1562
|
-
let directory = dirname(path);
|
|
1563
|
-
for (;;) {
|
|
1564
|
-
const nearest = configAbove(directory);
|
|
1565
|
-
if (nearest === void 0) return void 0;
|
|
1566
|
-
const config = listing(nearest, path, visited);
|
|
1567
|
-
if (config !== void 0) return config;
|
|
1568
|
-
const parent = dirname(dirname(nearest));
|
|
1569
|
-
if (parent === dirname(nearest)) return void 0;
|
|
1570
|
-
directory = parent;
|
|
1571
|
-
}
|
|
1572
|
-
}
|
|
1573
|
-
/**
|
|
1574
|
-
* The `@types` packages tsc loads into `config`'s program only because it lists no
|
|
1575
|
-
* `compilerOptions.types`. oxlint-tsgolint runs TypeScript 7, where `types` defaults
|
|
1576
|
-
* to none, so its program loads none of them.
|
|
1577
|
-
*/
|
|
1578
|
-
function automaticTypes(config) {
|
|
1579
|
-
return project(config)?.automaticTypes ?? [];
|
|
1580
|
-
}
|
|
1581
|
-
//#endregion
|
|
1582
|
-
//#region src/oxc/guardrails/type-checker.ts
|
|
1583
|
-
const programs = /* @__PURE__ */ new Map();
|
|
1584
|
-
/** The source files every program of the lint run shares, parsed once per text and per set of compiler options that change a parse. */
|
|
1585
|
-
const documents = ts.createDocumentRegistry(ts.sys.useCaseSensitiveFileNames);
|
|
1586
|
-
function normalize(file) {
|
|
1587
|
-
return resolve(file).replaceAll("\\", "/");
|
|
1588
|
-
}
|
|
1589
|
-
function build(config, path, text) {
|
|
1590
|
-
const parsed = project(config);
|
|
1591
|
-
if (parsed === void 0) return void 0;
|
|
1592
|
-
const host = ts.createCompilerHost(parsed.options, true);
|
|
1593
|
-
host.getSourceFile = (name, language) => {
|
|
1594
|
-
const content = normalize(name) === path ? text : host.readFile(name);
|
|
1595
|
-
return content === void 0 ? void 0 : documents.acquireDocument(name, parsed.options, ts.ScriptSnapshot.fromString(content), content, void 0, language);
|
|
1596
|
-
};
|
|
1597
|
-
const program = ts.createProgram({
|
|
1598
|
-
rootNames: [...parsed.files],
|
|
1599
|
-
options: parsed.options,
|
|
1600
|
-
host,
|
|
1601
|
-
oldProgram: programs.get(config)
|
|
1602
|
-
});
|
|
1603
|
-
programs.set(config, program);
|
|
1604
|
-
return program;
|
|
1605
|
-
}
|
|
1606
|
-
/**
|
|
1607
|
-
* The type checker of the tsconfig program that lists `file`, built once per
|
|
1608
|
-
* lint run and rebuilt from the previous one when `text` differs from what it
|
|
1609
|
-
* read. Undefined when no tsconfig lists the file.
|
|
1610
|
-
*/
|
|
1611
|
-
function typedFile(file, text) {
|
|
1612
|
-
const config = programConfig(file);
|
|
1613
|
-
if (config === void 0) return void 0;
|
|
1614
|
-
const path = normalize(file);
|
|
1615
|
-
const cached = programs.get(config);
|
|
1616
|
-
const program = cached?.getSourceFile(path)?.text === text ? cached : build(config, path, text);
|
|
1617
|
-
const sourceFile = program?.getSourceFile(path);
|
|
1618
|
-
return program && sourceFile ? {
|
|
1619
|
-
checker: program.getTypeChecker(),
|
|
1620
|
-
options: program.getCompilerOptions(),
|
|
1621
|
-
sourceFile
|
|
1622
|
-
} : void 0;
|
|
1623
|
-
}
|
|
1624
|
-
/** The node `test` accepts that spans exactly `start` to `end`, the span oxlint gives the matching ESTree node. */
|
|
1625
|
-
function nodeAt(sourceFile, span, test) {
|
|
1626
|
-
let found;
|
|
1627
|
-
function visit(node) {
|
|
1628
|
-
if (found !== void 0 || node.pos > span.start || node.end < span.end) return;
|
|
1629
|
-
if (test(node) && node.getStart(sourceFile) === span.start && node.end === span.end) found = node;
|
|
1630
|
-
else ts.forEachChild(node, visit);
|
|
1631
|
-
}
|
|
1632
|
-
visit(sourceFile);
|
|
1633
|
-
return found;
|
|
1634
|
-
}
|
|
1635
|
-
//#endregion
|
|
1636
|
-
//#region src/oxc/guardrails/rules/no-unsafe-object-assign.ts
|
|
1637
|
-
const UNTYPED = ts.TypeFlags.Any | ts.TypeFlags.Unknown;
|
|
1638
|
-
const MAX_DEPTH = 4;
|
|
1639
|
-
function members(type) {
|
|
1640
|
-
return type.isUnion() ? type.types : [type];
|
|
1641
|
-
}
|
|
1642
|
-
/** Whether `type` is `any`, or holds `any` in a union, an intersection or the elements of an array or tuple, as in `any[]`. */
|
|
1643
|
-
function holdsAny(checker, type, depth = 0) {
|
|
1644
|
-
if (type.flags & ts.TypeFlags.Any) return true;
|
|
1645
|
-
if (depth === MAX_DEPTH) return false;
|
|
1646
|
-
const element = checker.isArrayType(type) || checker.isTupleType(type) ? checker.getIndexTypeOfType(type, ts.IndexKind.Number) : void 0;
|
|
1647
|
-
return (type.isUnionOrIntersection() ? type.types : element === void 0 ? [] : [element]).some((member) => holdsAny(checker, member, depth + 1));
|
|
1648
|
-
}
|
|
1649
|
-
/** Whether a declaration sits inside a generic class, interface or type alias, whose type parameters the public checker API cannot instantiate for a declaration. */
|
|
1650
|
-
function insideGeneric(declaration) {
|
|
1651
|
-
for (let node = declaration.parent; !ts.isSourceFile(node); node = node.parent) if ((ts.isClassLike(node) || ts.isInterfaceDeclaration(node) || ts.isTypeAliasDeclaration(node)) && node.typeParameters !== void 0) return true;
|
|
1652
|
-
return false;
|
|
1653
|
-
}
|
|
1654
|
-
/** The types a field accepts: its read type, and its setter's parameter type. Undefined when the setter sits inside a generic declaration, whose parameter type this rule cannot instantiate. */
|
|
1655
|
-
function acceptedTypes(checker, field, source) {
|
|
1656
|
-
const setter = field.declarations?.find(ts.isSetAccessorDeclaration);
|
|
1657
|
-
const parameter = setter?.parameters[0];
|
|
1658
|
-
const read = checker.getTypeOfSymbolAtLocation(field, source);
|
|
1659
|
-
if (setter === void 0 || parameter === void 0) return [read];
|
|
1660
|
-
return insideGeneric(setter) ? void 0 : [read, checker.getTypeAtLocation(parameter)];
|
|
1661
|
-
}
|
|
1662
|
-
function untyped(type) {
|
|
1663
|
-
return (type.flags & UNTYPED) !== 0;
|
|
1664
|
-
}
|
|
1665
|
-
function typeVerdict({ checker, exactOptional }, type, accepted, optional) {
|
|
1666
|
-
if (accepted.length === 0 || accepted.some(untyped)) return void 0;
|
|
1667
|
-
if (untyped(type) || holdsAny(checker, type) && !accepted.some((member) => holdsAny(checker, member))) return "untypedField";
|
|
1668
|
-
return (optional && !exactOptional ? members(type).filter((member) => !(member.flags & ts.TypeFlags.Undefined)) : [type]).every((member) => accepted.some((field) => checker.isTypeAssignableTo(member, field))) ? void 0 : "mistypedField";
|
|
1669
|
-
}
|
|
1670
|
-
function fieldWrite(check, property, field, source) {
|
|
1671
|
-
const { checker } = check;
|
|
1672
|
-
const accepted = acceptedTypes(checker, field, source);
|
|
1673
|
-
if (accepted === void 0) return void 0;
|
|
1674
|
-
const declaration = property.valueDeclaration;
|
|
1675
|
-
const written = declaration !== void 0 && declaration.getSourceFile() === source.getSourceFile() && declaration.pos >= source.pos && declaration.end <= source.end && (ts.isPropertyAssignment(declaration) || ts.isShorthandPropertyAssignment(declaration)) ? ts.isPropertyAssignment(declaration) ? declaration.initializer : declaration.name : void 0;
|
|
1676
|
-
const kind = written === void 0 ? typeVerdict(check, checker.getTypeOfSymbolAtLocation(property, source), accepted, (property.flags & ts.SymbolFlags.Optional) !== 0) : typeVerdict(check, valueType(checker, written), accepted, false);
|
|
1677
|
-
if (kind === void 0 || kind === "mistypedField" && written !== void 0 && accepted.some((type) => literalFits(checker, written, type))) return void 0;
|
|
1678
|
-
return {
|
|
1679
|
-
kind,
|
|
1680
|
-
name: property.name
|
|
1681
|
-
};
|
|
1682
|
-
}
|
|
1683
|
-
/** A primitive source member, such as the `false` of `flag && { ... }`, whose apparent members (`valueOf`) `Object.assign` never copies. */
|
|
1684
|
-
const PRIMITIVE = ts.TypeFlags.BooleanLike | ts.TypeFlags.NumberLike | ts.TypeFlags.StringLike | ts.TypeFlags.BigIntLike | ts.TypeFlags.ESSymbolLike | ts.TypeFlags.Null | ts.TypeFlags.Undefined | ts.TypeFlags.Void | ts.TypeFlags.Never;
|
|
1685
|
-
/** Whether the target declares a field that does not take `unknown`, which an untyped string-keyed source could overwrite. */
|
|
1686
|
-
function hasTypedField(checker, target) {
|
|
1687
|
-
return checker.getPropertiesOfType(target).some((field) => !untyped(checker.getTypeOfSymbol(field)));
|
|
1688
|
-
}
|
|
1689
|
-
function untypedKeys(checker, member) {
|
|
1690
|
-
return checker.getIndexInfosOfType(member).some((info) => (info.keyType.flags & ts.TypeFlags.String) !== 0 && untyped(info.type));
|
|
1691
|
-
}
|
|
1692
|
-
function sourceWrites(check, target, source) {
|
|
1693
|
-
const { checker } = check;
|
|
1694
|
-
const writes = /* @__PURE__ */ new Map();
|
|
1695
|
-
for (const member of members(checker.getTypeAtLocation(source))) {
|
|
1696
|
-
if (untyped(member) || untypedKeys(checker, member) && hasTypedField(checker, target)) writes.set("", { kind: "untypedSource" });
|
|
1697
|
-
if (member.flags & PRIMITIVE) continue;
|
|
1698
|
-
for (const property of checker.getPropertiesOfType(member)) {
|
|
1699
|
-
const field = checker.getPropertyOfType(target, property.name);
|
|
1700
|
-
const write = field && fieldWrite(check, property, field, source);
|
|
1701
|
-
if (write !== void 0) writes.set(property.name, write);
|
|
1702
|
-
}
|
|
1703
|
-
}
|
|
1704
|
-
return [...writes.values()];
|
|
1705
|
-
}
|
|
1706
|
-
/** `Object.assign<T, U>` returns `T & U` without comparing `U` with `T`, so a source can write `unknown`, `any` or a wrong type over a field `T` declares. */
|
|
1707
|
-
const noUnsafeObjectAssignRule = defineRule({
|
|
1708
|
-
meta: {
|
|
1709
|
-
type: "problem",
|
|
1710
|
-
docs: { description: "Object.assign writes no unknown, any or unassignable value over a field its target declares." },
|
|
1711
|
-
messages: {
|
|
1712
|
-
untypedSource: "This Object.assign source is typed `unknown` or `any`, or holds such values under an index signature, and it overwrites fields the target declares without a check: `Object.assign<T, U>` returns `T & U`. Parse it into a typed value first.",
|
|
1713
|
-
untypedField: "Object.assign writes an `unknown` or `any` value over `{{name}}`, a field the target declares, and TypeScript never compares the two: `Object.assign<T, U>` returns `T & U`. Parse the value into the field's type first.",
|
|
1714
|
-
mistypedField: "Object.assign writes a value over `{{name}}` that the target's `{{name}}` type does not accept, and TypeScript never compares the two: `Object.assign<T, U>` returns `T & U`. Assign the field directly so the compiler checks it."
|
|
1715
|
-
}
|
|
1716
|
-
},
|
|
1717
|
-
createOnce(context) {
|
|
1718
|
-
return { CallExpression(node) {
|
|
1719
|
-
if (callName(node.callee) !== "Object.assign" || node.arguments.length < 2) return;
|
|
1720
|
-
const typed = typedFile(context.filename, context.sourceCode.text);
|
|
1721
|
-
const call = typed && nodeAt(typed.sourceFile, node, ts.isCallExpression);
|
|
1722
|
-
if (typed === void 0 || call === void 0) return;
|
|
1723
|
-
const declared = typed.checker.getTypeAtLocation(call.arguments[0]);
|
|
1724
|
-
const target = declared.isTypeParameter() ? typed.checker.getBaseConstraintOfType(declared) ?? declared : declared;
|
|
1725
|
-
if (typed.checker.getPropertiesOfType(target).length === 0) return;
|
|
1726
|
-
const check = {
|
|
1727
|
-
checker: typed.checker,
|
|
1728
|
-
exactOptional: typed.options.exactOptionalPropertyTypes === true
|
|
1729
|
-
};
|
|
1730
|
-
call.arguments.slice(1).forEach((source, index) => {
|
|
1731
|
-
if (ts.isSpreadElement(source)) return;
|
|
1732
|
-
for (const write of sourceWrites(check, target, source)) context.report({
|
|
1733
|
-
node: node.arguments[index + 1],
|
|
1734
|
-
messageId: write.kind,
|
|
1735
|
-
data: "name" in write ? { name: write.name } : {}
|
|
1736
|
-
});
|
|
1737
|
-
});
|
|
1738
|
-
} };
|
|
1739
|
-
}
|
|
1740
|
-
});
|
|
1741
|
-
//#endregion
|
|
1742
|
-
//#region src/oxc/guardrails/rules/require-assertion.ts
|
|
1743
|
-
function isInCallback(node, frame) {
|
|
1744
|
-
for (let current = node.parent; current !== null && current !== frame.node; current = current.parent) if (current === frame.callback) return true;
|
|
1745
|
-
return false;
|
|
1746
|
-
}
|
|
1747
|
-
/** Test callbacks must contain an assertion regardless of their framework or filename. */
|
|
1748
|
-
const requireAssertionRule = defineRule({
|
|
1749
|
-
meta: {
|
|
1750
|
-
type: "problem",
|
|
1751
|
-
docs: { description: "Require an assertion in every executable test callback." },
|
|
1752
|
-
messages: { missingAssertion: "Call an assertion in this test to verify its behavior." }
|
|
1753
|
-
},
|
|
1754
|
-
createOnce(context) {
|
|
1755
|
-
const frames = [];
|
|
1756
|
-
function recordAssertion(node) {
|
|
1757
|
-
const frame = frames.at(-1);
|
|
1758
|
-
if (frame !== void 0 && isAssertion(node) && isInCallback(node, frame)) frame.hasAssertion = true;
|
|
1759
|
-
}
|
|
1760
|
-
return {
|
|
1761
|
-
before() {
|
|
1762
|
-
frames.length = 0;
|
|
1763
|
-
},
|
|
1764
|
-
CallExpression(node) {
|
|
1765
|
-
const callback = testCallback(node);
|
|
1766
|
-
if (callback !== void 0) frames.push({
|
|
1767
|
-
node,
|
|
1768
|
-
callback,
|
|
1769
|
-
hasAssertion: false
|
|
1770
|
-
});
|
|
1771
|
-
else recordAssertion(node);
|
|
1772
|
-
},
|
|
1773
|
-
MemberExpression: recordAssertion,
|
|
1774
|
-
"CallExpression:exit"(node) {
|
|
1775
|
-
const frame = frames.at(-1);
|
|
1776
|
-
if (frame?.node !== node) return;
|
|
1777
|
-
frames.pop();
|
|
1778
|
-
if (!frame.hasAssertion) context.report({
|
|
1779
|
-
node,
|
|
1780
|
-
messageId: "missingAssertion"
|
|
1781
|
-
});
|
|
1782
|
-
}
|
|
1783
|
-
};
|
|
1784
|
-
}
|
|
1785
|
-
});
|
|
1786
|
-
//#endregion
|
|
1787
|
-
//#region src/oxc/guardrails/rules/require-tsconfig-include.ts
|
|
1788
|
-
const TYPE_LINTED$1 = /\.[cm]?[jt]sx?$/u;
|
|
1789
|
-
/** A file type-aware lint reads must be listed by a tsconfig, or tsgolint types it without the repository's compiler options and `types`. */
|
|
1790
|
-
const requireTsconfigIncludeRule = defineRule({
|
|
1791
|
-
meta: {
|
|
1792
|
-
type: "problem",
|
|
1793
|
-
docs: { description: "Every file type-aware lint reads is listed by a tsconfig.json, so its findings use the repository's compiler options and types." },
|
|
1794
|
-
messages: { outside: "No tsconfig.json lists this file, so type-aware lint reads it in tsgolint's inferred program, without this repository's compiler options or `types`: Node and test-runner globals are error types, so `typescript/no-unsafe-*` reports here are false and findings that need those types go missing. List the file in a tsconfig.json that names the `types` it uses: one beside it that extends the root tsconfig, or, for a file at the root, a composite tsconfig that the root tsconfig references." }
|
|
1795
|
-
},
|
|
1796
|
-
createOnce(context) {
|
|
1797
|
-
return { Program(node) {
|
|
1798
|
-
if (TYPE_LINTED$1.test(context.filename) && programConfig(context.filename) === void 0) context.report({
|
|
1799
|
-
node,
|
|
1800
|
-
messageId: "outside"
|
|
1801
|
-
});
|
|
1802
|
-
} };
|
|
1803
|
-
}
|
|
1804
|
-
});
|
|
1805
|
-
//#endregion
|
|
1806
|
-
//#region src/oxc/guardrails/rules/require-tsconfig-types.ts
|
|
1807
|
-
const TYPE_LINTED = /\.[cm]?[jt]sx?$/u;
|
|
1808
|
-
/** The tsconfig of a file type-aware lint reads must list `compilerOptions.types`, or tsgolint loads none of the `@types` packages tsc loads. */
|
|
1809
|
-
const requireTsconfigTypesRule = defineRule({
|
|
1810
|
-
meta: {
|
|
1811
|
-
type: "problem",
|
|
1812
|
-
docs: { description: "The tsconfig.json of every file type-aware lint reads lists compilerOptions.types, so tsgolint loads the same @types packages as tsc." },
|
|
1813
|
-
messages: { missing: "{{config}} lists no `compilerOptions.types`, so tsc loads every `@types` package ({{packages}}) but type-aware lint, which runs TypeScript 7, loads none: Node and test-runner globals are error types, so `typescript/no-unsafe-*` reports here are false and findings that need those types go missing. Add `\"types\": [{{list}}]` to its compilerOptions, or to the config that generates it, listing the packages this code uses." }
|
|
1814
|
-
},
|
|
1815
|
-
createOnce(context) {
|
|
1816
|
-
return { Program(node) {
|
|
1817
|
-
if (!TYPE_LINTED.test(context.filename)) return;
|
|
1818
|
-
const config = programConfig(context.filename);
|
|
1819
|
-
if (config === void 0) return;
|
|
1820
|
-
const packages = automaticTypes(config);
|
|
1821
|
-
if (packages.length === 0) return;
|
|
1822
|
-
context.report({
|
|
1823
|
-
node,
|
|
1824
|
-
messageId: "missing",
|
|
1825
|
-
data: {
|
|
1826
|
-
config: relative(context.cwd, config).replaceAll("\\", "/"),
|
|
1827
|
-
packages: packages.join(", "),
|
|
1828
|
-
list: packages.map((name) => JSON.stringify(name)).join(", ")
|
|
1829
|
-
}
|
|
1830
|
-
});
|
|
1831
|
-
} };
|
|
1832
|
-
}
|
|
1833
|
-
});
|
|
1834
|
-
//#endregion
|
|
1835
|
-
//#region src/oxc/guardrails/index.ts
|
|
1836
|
-
/** AntelopeJS rules that reject comments, inherited-key lookups, presence-only type guards, inserts that follow a read of the same table, unchecked Object.assign writes, low-evidence tests, files no tsconfig lists and tsconfigs that list no `types`. */
|
|
1837
|
-
const guardrailsPlugin = eslintCompatPlugin({
|
|
1838
|
-
meta: { name: "antelopejs" },
|
|
1839
|
-
rules: {
|
|
1840
|
-
"no-comments": noCommentsRule,
|
|
1841
|
-
"no-fs-read-in-tests": noFsReadInTestsRule,
|
|
1842
|
-
"no-inherited-key-lookup": noInheritedKeyLookupRule,
|
|
1843
|
-
"no-presence-only-type-guard": noPresenceOnlyTypeGuardRule,
|
|
1844
|
-
"no-read-then-insert": noReadThenInsertRule,
|
|
1845
|
-
"no-constant-value-assertion": noConstantValueAssertionRule,
|
|
1846
|
-
"no-self-import-in-tests": noSelfImportInTestsRule,
|
|
1847
|
-
"no-typeof-function-only-test": noTypeofFunctionOnlyTestRule,
|
|
1848
|
-
"no-unsafe-object-assign": noUnsafeObjectAssignRule,
|
|
1849
|
-
"require-assertion": requireAssertionRule,
|
|
1850
|
-
"require-tsconfig-include": requireTsconfigIncludeRule,
|
|
1851
|
-
"require-tsconfig-types": requireTsconfigTypesRule
|
|
1852
|
-
}
|
|
1853
|
-
});
|
|
1854
|
-
//#endregion
|
|
1
|
+
import { n as TEST_FILE_GLOBS, t as ASSERTION_FUNCTION_NAMES } from "../../shared-WC0z3y9F.mjs";
|
|
2
|
+
import { t as guardrailsPlugin } from "../../guardrails-BfGwehVj.mjs";
|
|
1855
3
|
export { ASSERTION_FUNCTION_NAMES, TEST_FILE_GLOBS, guardrailsPlugin as default };
|