@kainappsinc/factory 0.0.0-stage → 0.1.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.
@@ -0,0 +1,85 @@
1
+ // Reusable dependency-cruiser rule shapes for a .dependency-cruiser.cjs (CommonJS, plain
2
+ // JavaScript, so the depcruise CLI can load it under Node as well as Bun):
3
+ //
4
+ // const { layerRules, noTestImportsInProduction, noValueCycles } = require('@kainappsinc/factory/depcruise');
5
+ // module.exports = { forbidden: [...layerRules(LAYERS, { tests: TESTS }), noTestImportsInProduction({ … }), noValueCycles({ … })], … };
6
+ //
7
+ // Every rule is severity `error`: the `boundaries` ratchet (factory-depcruise-counts) freezes
8
+ // today's violations per rule name, so a rule at 0 is enforced outright.
9
+
10
+ /**
11
+ * dependency-cruiser's dependency types of an `import type` and of an `import('…').T` type query.
12
+ * @type {import('dependency-cruiser').DependencyType[]}
13
+ */
14
+ const TYPE_EDGES = ['type-only', 'type-import'];
15
+
16
+ /**
17
+ * One rule per layer, named `layer-<name>`: a module may import its own layer and lower ones.
18
+ * `layers` is ordered lowest first; each has `name`, `path` (a regex), `fix` (what to do instead,
19
+ * printed in the rule comment) and optionally `to` (the paths it may not import, in place of the
20
+ * higher layers). With `typeImportsUpTo` (a layer name), `import type` may also reach upward into
21
+ * layers below that one: a layer below it gets a value rule (any higher layer) and a type rule
22
+ * (that layer and above) under the same name. `tests` (a regex) is exempt; `doc` is named in the
23
+ * comment.
24
+ *
25
+ * @param {ReadonlyArray<{ name: string; path: string; fix: string; to?: string | string[] }>} layers
26
+ * @param {{ tests?: string; typeImportsUpTo?: string; doc?: string }} [options]
27
+ * @returns {import('dependency-cruiser').IForbiddenRuleType[]}
28
+ */
29
+ function layerRules(layers, options = {}) {
30
+ const { tests, typeImportsUpTo, doc = 'factory/BOUNDARIES.md' } = options;
31
+ const split = typeImportsUpTo === undefined ? -1 : layers.findIndex((l) => l.name === typeImportsUpTo);
32
+ if (typeImportsUpTo !== undefined && split === -1) throw new Error(`layerRules: no layer named "${typeImportsUpTo}"`);
33
+ const typeForbidden = split === -1 ? [] : layers.slice(split).map((l) => l.path);
34
+ return layers.flatMap((layer, i) => {
35
+ const higher = layers.slice(i + 1).map((l) => l.path);
36
+ if (!higher.length) return [];
37
+ /** @param {import('dependency-cruiser').IToRestriction} to */
38
+ const rule = (to) => ({
39
+ name: `layer-${layer.name}`,
40
+ severity: /** @type {const} */ ('error'),
41
+ comment: `Layer ${layer.name} imports a higher layer (${doc}): ${layer.fix}.`,
42
+ from: { path: layer.path, ...(tests !== undefined && { pathNot: tests }) },
43
+ to,
44
+ });
45
+ if (split === -1 || i >= split) return [rule({ path: layer.to ?? higher })];
46
+ return [
47
+ rule({ path: layer.to ?? higher, dependencyTypesNot: TYPE_EDGES }),
48
+ rule({ path: typeForbidden, dependencyTypes: TYPE_EDGES }),
49
+ ];
50
+ });
51
+ }
52
+
53
+ /**
54
+ * Production code (`from`, minus `tests`) must not import tests or test helpers (`tests`).
55
+ *
56
+ * @param {{ from: string; tests: string; describe?: string }} options `describe` names the test paths in the comment.
57
+ * @returns {import('dependency-cruiser').IForbiddenRuleType}
58
+ */
59
+ function noTestImportsInProduction({ from, tests, describe = 'tests' }) {
60
+ return {
61
+ name: 'no-test-imports-in-production',
62
+ severity: 'error',
63
+ comment: `Production code must not import test files or helpers (${describe}): they are not shipped and pull test-only state into the product. Move the shared helper into a non-test module.`,
64
+ from: { path: from, pathNot: tests },
65
+ to: { path: tests },
66
+ };
67
+ }
68
+
69
+ /**
70
+ * No value-import cycles among `from` (minus `tests`); type-only edges neither close nor carry one.
71
+ *
72
+ * @param {{ from: string; tests?: string }} options
73
+ * @returns {import('dependency-cruiser').IForbiddenRuleType}
74
+ */
75
+ function noValueCycles({ from, tests }) {
76
+ return {
77
+ name: 'no-value-cycles',
78
+ severity: 'error',
79
+ comment: 'A value-import cycle makes load order matter (undefined at import time) and ties modules together. Break it: move the shared piece into a lower module, use `import type`, or inject the dependency. Counted once per edge on a cycle.',
80
+ from: { path: from, ...(tests !== undefined && { pathNot: tests }) },
81
+ to: { circular: true, viaOnly: { dependencyTypesNot: TYPE_EDGES }, dependencyTypesNot: TYPE_EDGES },
82
+ };
83
+ }
84
+
85
+ module.exports = { TYPE_EDGES, layerRules, noTestImportsInProduction, noValueCycles };
@@ -0,0 +1,7 @@
1
+ import type { DependencyType, IForbiddenRuleType } from 'dependency-cruiser';
2
+
3
+ export declare const TYPE_EDGES: DependencyType[];
4
+ export interface Layer { name: string; path: string; fix: string; to?: string | string[] }
5
+ export declare function layerRules(layers: readonly Layer[], options?: { tests?: string; typeImportsUpTo?: string; doc?: string }): IForbiddenRuleType[];
6
+ export declare function noTestImportsInProduction(options: { from: string; tests: string; describe?: string }): IForbiddenRuleType;
7
+ export declare function noValueCycles(options: { from: string; tests?: string }): IForbiddenRuleType;
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Small accessors over AST nodes. Rules see both ESTree nodes and the TypeScript ones
3
+ * @typescript-eslint/parser adds (TSAsExpression, …), which ESTree's types do not know, so the
4
+ * helpers take `unknown` and read fields defensively.
5
+ */
6
+ import type { AST } from 'eslint';
7
+
8
+ /** A field of a node (or undefined). */
9
+ export function get(node: unknown, key: string): unknown {
10
+ return typeof node === 'object' && node !== null ? (node as Record<string, unknown>)[key] : undefined;
11
+ }
12
+
13
+ /** The node's `type`, or undefined when it is not a node. */
14
+ export function typeOf(node: unknown): string | undefined {
15
+ const t = get(node, 'type');
16
+ return typeof t === 'string' ? t : undefined;
17
+ }
18
+
19
+ /** An identifier's name, or undefined when the node is not an identifier. */
20
+ export function identName(node: unknown): string | undefined {
21
+ return typeOf(node) === 'Identifier' ? String(get(node, 'name')) : undefined;
22
+ }
23
+
24
+ /** An identifier, optionally with a given name. */
25
+ export function isIdent(node: unknown, name?: string | RegExp): boolean {
26
+ const n = identName(node);
27
+ if (n === undefined) return false;
28
+ if (name === undefined) return true;
29
+ return typeof name === 'string' ? n === name : name.test(n);
30
+ }
31
+
32
+ /** A node's source location (every ESTree and TypeScript node has one). */
33
+ export function locOf(node: unknown): AST.SourceLocation {
34
+ return get(node, 'loc') as AST.SourceLocation;
35
+ }
36
+
37
+ /** A string literal's value. */
38
+ export function stringValue(node: unknown): string | undefined {
39
+ const v = get(node, 'value');
40
+ return typeOf(node) === 'Literal' && typeof v === 'string' ? v : undefined;
41
+ }
42
+
43
+ /** The property name of `a.b` or `a['b']` (string literal only). */
44
+ export function propertyName(node: unknown): string | undefined {
45
+ if (typeOf(node) !== 'MemberExpression') return undefined;
46
+ const property = get(node, 'property');
47
+ return get(node, 'computed') === true ? stringValue(property) : identName(property);
48
+ }
49
+
50
+ /** `obj.prop(...)` where obj is the identifier `obj` (or any object when obj is undefined). */
51
+ export function isMemberCall(node: unknown, obj: string | undefined, prop: string): boolean {
52
+ if (typeOf(node) !== 'CallExpression') return false;
53
+ const callee = get(node, 'callee');
54
+ return propertyName(callee) === prop && (obj === undefined || isIdent(get(callee, 'object'), obj));
55
+ }
56
+
57
+ /** Skips TypeScript wrappers that do not change the value (`x!`, `x satisfies T`). */
58
+ export function unwrap(node: unknown): unknown {
59
+ let n = node;
60
+ while (typeOf(n) === 'TSNonNullExpression' || typeOf(n) === 'TSSatisfiesExpression') n = get(n, 'expression');
61
+ return n;
62
+ }
@@ -0,0 +1,86 @@
1
+ /**
2
+ * The ESLint flat-config boilerplate a TypeScript-on-Bun repository repeats, for its
3
+ * eslint.config.js (which then runs on Bun only: `bun --bun eslint`):
4
+ *
5
+ * import { baseConfig, testConfig } from '@kainappsinc/factory/eslint/config';
6
+ * import factory from '@kainappsinc/factory/eslint';
7
+ * export default defineConfig([
8
+ * globalIgnores(['dist/', '**\/node_modules/']),
9
+ * await baseConfig({ files: ['src/**\/*.ts'], plugins: { factory }, rules: { 'factory/no-untracked-todo': 'error' } }),
10
+ * testConfig({ files: ['**\/__tests__/**', '**\/*.test.ts'], rules: { 'factory/no-json-parse-cast': 'off' } }),
11
+ * ]);
12
+ *
13
+ * Not type-aware: typed linting costs gigabytes of memory under Bun.
14
+ */
15
+ import type { ESLint, Linter } from 'eslint';
16
+ import { needsClassicTypeScript, useClassicTypeScript } from '../packs/ts-bun/classic-typescript.js';
17
+
18
+ /**
19
+ * typescript-eslint. When the installed `typescript` has no compiler API (7.0), points
20
+ * require('typescript') at the classic compiler (the `typescript-classic` alias) for this process
21
+ * first; that is why typescript-eslint is imported here dynamically: Bun evaluates a static
22
+ * import's CommonJS dependencies before the importing module's body, so it would load the stub.
23
+ */
24
+ export async function loadTypeScriptEslint(): Promise<typeof import('typescript-eslint').default> {
25
+ if (needsClassicTypeScript()) useClassicTypeScript();
26
+ const { default: tseslint } = await import('typescript-eslint');
27
+ return tseslint;
28
+ }
29
+
30
+ /** The rules every factory repository switches off or narrows, and the ones it adds. */
31
+ export const BASE_RULES: Linter.RulesRecord = {
32
+ // Noise: control-character regexes are deliberate input sanitisers; useless escapes are style.
33
+ 'no-control-regex': 'off',
34
+ 'no-useless-escape': 'off',
35
+ // Literal zero-width / bidi characters in a regex are how input gets stripped of them.
36
+ 'no-irregular-whitespace': ['error', { skipRegExps: true }],
37
+ // A leading underscore marks "unused on purpose".
38
+ '@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_', varsIgnorePattern: '^_', caughtErrorsIgnorePattern: '^_', destructuredArrayIgnorePattern: '^_', ignoreRestSiblings: true }],
39
+ // eslint-comments: a directive must say why (`-- reason`).
40
+ '@eslint-community/eslint-comments/require-description': ['error', { ignore: ['eslint-enable'] }],
41
+ };
42
+
43
+ /** What tests may do that production code may not: fakes, fixtures and casts are the point. */
44
+ export const TEST_RULES: Linter.RulesRecord = {
45
+ '@typescript-eslint/no-explicit-any': 'off',
46
+ '@typescript-eslint/no-require-imports': 'off',
47
+ 'require-yield': 'off',
48
+ '@eslint-community/eslint-comments/require-description': 'off',
49
+ };
50
+
51
+ export interface BlockOptions {
52
+ files: string[];
53
+ plugins?: Record<string, ESLint.Plugin>;
54
+ /** Added after (so over) the defaults. */
55
+ rules?: Linter.RulesRecord;
56
+ }
57
+
58
+ /**
59
+ * The main block: eslint recommended, typescript-eslint recommended (not type-aware) and
60
+ * eslint-comments recommended, unused disable directives as errors, BASE_RULES, then `rules`.
61
+ */
62
+ export async function baseConfig({ files, plugins, rules }: BlockOptions): Promise<Linter.Config> {
63
+ const [tseslint, { default: js }, { default: comments }] = await Promise.all([
64
+ loadTypeScriptEslint(),
65
+ import('@eslint/js'),
66
+ import('@eslint-community/eslint-plugin-eslint-comments/configs'),
67
+ ]);
68
+ return {
69
+ files,
70
+ // defineConfig() flattens `extends`.
71
+ extends: [js.configs.recommended, tseslint.configs.recommended, comments.recommended],
72
+ ...(plugins && { plugins }),
73
+ linterOptions: { reportUnusedDisableDirectives: 'error' },
74
+ rules: { ...BASE_RULES, ...rules },
75
+ } as Linter.Config;
76
+ }
77
+
78
+ /** The tests block: unused disable directives allowed, TEST_RULES, then `rules`. */
79
+ export function testConfig({ files, plugins, rules }: BlockOptions): Linter.Config {
80
+ return {
81
+ files,
82
+ ...(plugins && { plugins }),
83
+ linterOptions: { reportUnusedDisableDirectives: 'off' },
84
+ rules: { ...TEST_RULES, ...rules },
85
+ };
86
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * The shared lint rules: each bans one hazard and its message names the replacement. Every rule
3
+ * takes a `messages` option, so a repository can name its own replacement in the text.
4
+ *
5
+ * import factory from '@kainappsinc/factory/eslint'; // plugin, rules under "factory/…"
6
+ * import { rules } from '@kainappsinc/factory/eslint'; // to merge into a repository's own plugin
7
+ *
8
+ * Repository-specific rules stay in the repository; config.ts has the shared config boilerplate.
9
+ */
10
+ import type { ESLint, Rule } from 'eslint';
11
+ import importSuffix from './rules/import-suffix.js';
12
+ import noJsonParseCast from './rules/no-json-parse-cast.js';
13
+ import noRawRequestJson from './rules/no-raw-request-json.js';
14
+ import noUntrackedTodo from './rules/no-untracked-todo.js';
15
+
16
+ export const rules: Record<string, Rule.RuleModule> = {
17
+ 'import-suffix': importSuffix,
18
+ 'no-json-parse-cast': noJsonParseCast,
19
+ 'no-raw-request-json': noRawRequestJson,
20
+ 'no-untracked-todo': noUntrackedTodo,
21
+ };
22
+
23
+ export { importSuffix, noJsonParseCast, noRawRequestJson, noUntrackedTodo };
24
+
25
+ const plugin: ESLint.Plugin = { meta: { name: '@kainappsinc/factory' }, rules };
26
+ export default plugin;
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Configurable report texts for the shared rules. Each rule has fixed message ids (what tests and
3
+ * tooling match on) and a default text per id; a repository replaces a text with the rule's
4
+ * `messages` option, usually to name its own replacement ("use parseBody(req, schema) from …").
5
+ * `{{name}}` placeholders in a text are filled from the report's data.
6
+ */
7
+ import type { Rule } from 'eslint';
8
+
9
+ /** One option object's JSON schema, as ESLint's rule meta takes it. */
10
+ export type OptionSchema = Exclude<NonNullable<Rule.RuleMetaData['schema']>, readonly unknown[] | false>;
11
+
12
+ /** Every id renders the `message` data field, so the text can come from options. */
13
+ export function messageIds<Id extends string>(ids: readonly Id[]): Record<Id, string> {
14
+ return Object.fromEntries(ids.map((id) => [id, '{{message}}'])) as Record<Id, string>;
15
+ }
16
+
17
+ /** The option schema for `messages`: an optional non-empty string per id. */
18
+ export function messagesSchema(ids: readonly string[]): OptionSchema {
19
+ return {
20
+ type: 'object',
21
+ properties: Object.fromEntries(ids.map((id) => [id, { type: 'string', minLength: 1 }])),
22
+ additionalProperties: false,
23
+ };
24
+ }
25
+
26
+ function fill(text: string, data: Record<string, string>): string {
27
+ return text.replace(/\{\{\s*([^{}\s]+)\s*\}\}/g, (whole, key: string) => data[key] ?? whole);
28
+ }
29
+
30
+ /**
31
+ * A report function for `context`: `report(where, id, data)` uses the `messages` option's text for
32
+ * `id` when given, else `defaults[id]`.
33
+ */
34
+ export function reporter<Id extends string>(
35
+ context: Rule.RuleContext,
36
+ defaults: Record<Id, string>,
37
+ overrides: Partial<Record<Id, string>> | undefined,
38
+ ): (where: Rule.ReportDescriptorLocation, messageId: Id, data?: Record<string, string>) => void {
39
+ return (where, messageId, data = {}) => {
40
+ const text = fill(overrides?.[messageId] ?? defaults[messageId], data);
41
+ context.report({ ...where, messageId, data: { ...data, message: text } });
42
+ };
43
+ }
@@ -0,0 +1,79 @@
1
+ import type { Rule } from 'eslint';
2
+ import { get, locOf, stringValue, typeOf } from '../ast.js';
3
+ import { messageIds, messagesSchema, reporter } from '../messages.js';
4
+
5
+ /** What a relative import names: the emitted `.js` file, or the `.ts` source itself. */
6
+ export type Suffix = 'js' | 'ts';
7
+
8
+ /** Per convention: the suffixes a relative specifier may end in, and the one that is the other convention's. */
9
+ const CONVENTIONS: Record<Suffix, { allowed: RegExp; wrong: RegExp }> = {
10
+ // ES/CommonJS modules and JSON always; .ts sources are named by their .js file.
11
+ js: { allowed: /\.(?:js|mjs|cjs|json)$/, wrong: /\.[cm]?tsx?$/ },
12
+ // the TypeScript source by its own name (allowImportingTsExtensions), modules and JSON.
13
+ ts: { allowed: /\.(?:tsx?|mjs|cjs|json)$/, wrong: /\.js$/ },
14
+ };
15
+
16
+ const IDS = ['missing', 'wrong'] as const;
17
+ type Id = (typeof IDS)[number];
18
+ export const DEFAULT_MESSAGES: Record<Suffix, Record<Id, string>> = {
19
+ js: {
20
+ missing: 'Relative import "{{spec}}" has no .js suffix: Bun resolves it, but ESM and Node need the full name. Write the .js name ("./x.js" finds x.ts).',
21
+ wrong: 'Relative import "{{spec}}" names the .ts file; this codebase imports the .js name ("./x.js" finds x.ts).',
22
+ },
23
+ ts: {
24
+ missing: 'Relative import "{{spec}}" has no file suffix: write the source file\'s full name ("./x.ts"), as the rest of this codebase does (allowImportingTsExtensions).',
25
+ wrong: 'Relative import "{{spec}}" names a .js file; this codebase imports the .ts source by its own name ("./x.ts").',
26
+ },
27
+ };
28
+
29
+ export interface Options { suffix?: Suffix; messages?: Partial<Record<Id, string>> }
30
+
31
+ function isRelative(spec: string): boolean {
32
+ return spec === '.' || spec === '..' || spec.startsWith('./') || spec.startsWith('../');
33
+ }
34
+
35
+ /** What is wrong with a relative specifier's suffix, or undefined when it is fine (or not relative). */
36
+ export function suffixProblem(spec: string, suffix: Suffix): Id | undefined {
37
+ const { allowed, wrong } = CONVENTIONS[suffix];
38
+ if (!isRelative(spec) || allowed.test(spec)) return undefined;
39
+ return wrong.test(spec) ? 'wrong' : 'missing';
40
+ }
41
+
42
+ /** Relative imports name the file with one suffix convention (`suffix`: js, the default, or ts). */
43
+ const rule: Rule.RuleModule = {
44
+ meta: {
45
+ type: 'problem',
46
+ docs: { description: 'Relative imports name the file with the codebase\'s suffix (.js or .ts)' },
47
+ schema: [{
48
+ type: 'object',
49
+ properties: { suffix: { enum: ['js', 'ts'] }, messages: messagesSchema(IDS) },
50
+ additionalProperties: false,
51
+ }],
52
+ messages: messageIds(IDS),
53
+ },
54
+ create(context) {
55
+ const options = (context.options[0] ?? {}) as Options;
56
+ const suffix = options.suffix ?? 'js';
57
+ const report = reporter(context, DEFAULT_MESSAGES[suffix], options.messages);
58
+ function check(source: unknown): void {
59
+ const spec = stringValue(source);
60
+ if (spec === undefined) return;
61
+ const messageId = suffixProblem(spec, suffix);
62
+ if (messageId) report({ loc: locOf(source) }, messageId, { spec });
63
+ }
64
+ return {
65
+ ImportDeclaration: (node) => check(node.source),
66
+ ExportNamedDeclaration: (node) => check(node.source),
67
+ ExportAllDeclaration: (node) => check(node.source),
68
+ ImportExpression: (node) => check(node.source),
69
+ // type-only `import('./x.js').T` (`source` since typescript-eslint 8.x; `argument` before)
70
+ TSImportType(node: unknown) {
71
+ const source = get(node, 'source');
72
+ if (source !== undefined) return check(source);
73
+ const argument = get(node, 'argument');
74
+ check(typeOf(argument) === 'TSLiteralType' ? get(argument, 'literal') : argument);
75
+ },
76
+ };
77
+ },
78
+ };
79
+ export default rule;
@@ -0,0 +1,46 @@
1
+ import type { Rule } from 'eslint';
2
+ import { get, isIdent, isMemberCall, locOf, typeOf, unwrap } from '../ast.js';
3
+ import { messageIds, messagesSchema, reporter } from '../messages.js';
4
+
5
+ /** A type other than `unknown` (and not `as const`). */
6
+ function isTrustingType(type: unknown): boolean {
7
+ const t = typeOf(type);
8
+ if (t === undefined || t === 'TSUnknownKeyword') return false;
9
+ return !(t === 'TSTypeReference' && isIdent(get(type, 'typeName'), 'const'));
10
+ }
11
+
12
+ const IDS = ['cast'] as const;
13
+ type Id = (typeof IDS)[number];
14
+ export const DEFAULT_MESSAGES: Record<Id, string> = {
15
+ cast: 'Casts JSON.parse() to a type, so unvalidated input is trusted as that type. Parse as unknown and validate it (a schema), or narrow it by hand.',
16
+ };
17
+
18
+ export interface Options { messages?: Partial<Record<Id, string>> }
19
+
20
+ /** `JSON.parse(s) as T`, `<T>JSON.parse(s)` and `const x: T = JSON.parse(s)` (T not unknown or const). */
21
+ const rule: Rule.RuleModule = {
22
+ meta: {
23
+ type: 'problem',
24
+ docs: { description: 'Parse JSON as unknown and validate it, instead of casting the result' },
25
+ schema: [{ type: 'object', properties: { messages: messagesSchema(IDS) }, additionalProperties: false }],
26
+ messages: messageIds(IDS),
27
+ },
28
+ create(context) {
29
+ const options = (context.options[0] ?? {}) as Options;
30
+ const report = reporter(context, DEFAULT_MESSAGES, options.messages);
31
+ function check(node: unknown, value: unknown, type: unknown): void {
32
+ if (isMemberCall(unwrap(value), 'JSON', 'parse') && isTrustingType(type)) report({ loc: locOf(node) }, 'cast');
33
+ }
34
+ return {
35
+ // a cast of the parse result: `as T` or `<T>`
36
+ 'TSAsExpression, TSTypeAssertion'(node: unknown) {
37
+ check(node, get(node, 'expression'), get(node, 'typeAnnotation'));
38
+ },
39
+ // const x: T = JSON.parse(s)
40
+ VariableDeclarator(node) {
41
+ check(node, node.init, get(get(node.id, 'typeAnnotation'), 'typeAnnotation'));
42
+ },
43
+ };
44
+ },
45
+ };
46
+ export default rule;
@@ -0,0 +1,46 @@
1
+ import type { Rule } from 'eslint';
2
+ import { get, identName, propertyName } from '../ast.js';
3
+ import { messageIds, messagesSchema, reporter } from '../messages.js';
4
+
5
+ /** The variable names a handler's Request goes by, unless `requestNames` says otherwise. */
6
+ export const DEFAULT_REQUEST_NAMES = ['req', 'request'];
7
+
8
+ const IDS = ['raw'] as const;
9
+ type Id = (typeof IDS)[number];
10
+ export const DEFAULT_MESSAGES: Record<Id, string> = {
11
+ raw: 'Reads a request body with req.json(): the body is unvalidated and unbounded, and a malformed one throws. Read it through the codebase\'s body reader, which bounds and validates it.',
12
+ };
13
+
14
+ export interface Options { requestNames?: string[]; messages?: Partial<Record<Id, string>> }
15
+
16
+ /** `req.json()`, `request.json()` and `ctx.req.json()`: a request body read with no argument. */
17
+ const rule: Rule.RuleModule = {
18
+ meta: {
19
+ type: 'problem',
20
+ docs: { description: 'Read request bodies through the codebase\'s validating reader, not req.json()' },
21
+ schema: [{
22
+ type: 'object',
23
+ properties: {
24
+ requestNames: { type: 'array', items: { type: 'string', minLength: 1 }, minItems: 1, uniqueItems: true },
25
+ messages: messagesSchema(IDS),
26
+ },
27
+ additionalProperties: false,
28
+ }],
29
+ messages: messageIds(IDS),
30
+ },
31
+ create(context) {
32
+ const options = (context.options[0] ?? {}) as Options;
33
+ const report = reporter(context, DEFAULT_MESSAGES, options.messages);
34
+ const requestNames = new Set(options.requestNames ?? DEFAULT_REQUEST_NAMES);
35
+ return {
36
+ CallExpression(node) {
37
+ if (node.arguments.length || propertyName(node.callee) !== 'json') return;
38
+ // req.json(), request.json(), ctx.req.json()
39
+ const object = get(node.callee, 'object');
40
+ const name = identName(object) ?? propertyName(object);
41
+ if (name !== undefined && requestNames.has(name)) report({ node }, 'raw');
42
+ },
43
+ };
44
+ },
45
+ };
46
+ export default rule;
@@ -0,0 +1,37 @@
1
+ import type { Rule } from 'eslint';
2
+ import { messageIds, messagesSchema, reporter } from '../messages.js';
3
+
4
+ const MARKER = /\b(TODO|FIXME|HACK|XXX)\b/;
5
+ /** An issue reference: #123, group/repo#123, or a URL. */
6
+ const REFERENCE = /(?<!&)#\d+\b|https?:\/\/\S+/;
7
+
8
+ const IDS = ['untracked'] as const;
9
+ type Id = (typeof IDS)[number];
10
+ export const DEFAULT_MESSAGES: Record<Id, string> = {
11
+ untracked: '{{marker}} without an issue reference is a note nobody tracks. Do it now, or file an issue and reference it ("TODO(#123): …" or a URL).',
12
+ };
13
+
14
+ export interface Options { messages?: Partial<Record<Id, string>> }
15
+
16
+ /** TODO / FIXME / HACK / XXX comments must reference an issue (#123, group/repo#123 or a URL). */
17
+ const rule: Rule.RuleModule = {
18
+ meta: {
19
+ type: 'suggestion',
20
+ docs: { description: 'TODO / FIXME / HACK / XXX comments reference an issue' },
21
+ schema: [{ type: 'object', properties: { messages: messagesSchema(IDS) }, additionalProperties: false }],
22
+ messages: messageIds(IDS),
23
+ },
24
+ create(context) {
25
+ const options = (context.options[0] ?? {}) as Options;
26
+ const report = reporter(context, DEFAULT_MESSAGES, options.messages);
27
+ return {
28
+ Program() {
29
+ for (const comment of context.sourceCode.getAllComments()) {
30
+ const marker = MARKER.exec(comment.value)?.[1];
31
+ if (marker && !REFERENCE.test(comment.value)) report({ loc: comment.loc! }, 'untracked', { marker });
32
+ }
33
+ },
34
+ };
35
+ },
36
+ };
37
+ export default rule;
@@ -0,0 +1,20 @@
1
+ /**
2
+ * A RuleTester that parses TypeScript, wired to bun:test, for testing lint rules with `bun test`:
3
+ *
4
+ * import { ruleTester } from '@kainappsinc/factory/eslint/tester';
5
+ * ruleTester.run('my-rule', rule, { valid: [...], invalid: [...] });
6
+ *
7
+ * When the installed `typescript` has no compiler API (7.0), the parser gets the classic one
8
+ * (classic-typescript.ts, the `typescript-classic` alias).
9
+ */
10
+ import { describe, it } from 'bun:test';
11
+ import { RuleTester } from 'eslint';
12
+ import { needsClassicTypeScript, useClassicTypeScript } from '../packs/ts-bun/classic-typescript.js';
13
+
14
+ if (needsClassicTypeScript()) useClassicTypeScript();
15
+ const { default: parser } = await import('@typescript-eslint/parser');
16
+
17
+ RuleTester.describe = describe;
18
+ RuleTester.it = it;
19
+
20
+ export const ruleTester = new RuleTester({ languageOptions: { parser, ecmaVersion: 'latest', sourceType: 'module' } });