mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-15 15:02:04 +00:00
release: v1.32.0 — hardening and scalability (#580)
* release: prepare v1.32.0 * test: stabilize water capture re-entry
This commit is contained in:
1 parent
b01822be48
commit
62eb431d66
372 files changed
+25178
-8561
No files matched your search
@@ -0,0 +1,72 @@
|
||||
import { describe, it } from "vitest";
|
||||
import { RuleTester } from "eslint";
|
||||
import rule from "../api-fetch-required.js";
|
||||
|
||||
RuleTester.describe = describe;
|
||||
RuleTester.it = it;
|
||||
RuleTester.itOnly = it.only;
|
||||
|
||||
const ruleTester = new RuleTester({
|
||||
languageOptions: {
|
||||
ecmaVersion: 2023,
|
||||
sourceType: "module",
|
||||
parserOptions: { ecmaFeatures: { jsx: true } },
|
||||
},
|
||||
});
|
||||
|
||||
ruleTester.run("api-fetch-required", rule, {
|
||||
valid: [
|
||||
{
|
||||
code: "apiGet(endpoint); apiFetchRaw(externalUrl);",
|
||||
filename: "/repo/src/components/example.tsx",
|
||||
},
|
||||
{
|
||||
code: 'fetch("/api/server-prefetch");',
|
||||
filename: "/repo/src/app/server-page.tsx",
|
||||
},
|
||||
{
|
||||
code: 'fetch("https://example.test/data");',
|
||||
filename: "/repo/src/lib/server-only.ts",
|
||||
},
|
||||
{
|
||||
code: "fetch(path, init);",
|
||||
filename: "/repo/src/lib/api/api-fetch.ts",
|
||||
},
|
||||
{
|
||||
code: 'fetch("/api/mock");',
|
||||
filename: "/repo/src/components/__tests__/example.test.tsx",
|
||||
},
|
||||
],
|
||||
invalid: [
|
||||
{
|
||||
code: "fetch(endpoint);",
|
||||
filename: "/repo/src/components/example.tsx",
|
||||
errors: [{ messageId: "rawApiFetch" }],
|
||||
},
|
||||
{
|
||||
code: "window.fetch(`/api/${id}`);",
|
||||
filename: "/repo/src/components/example.tsx",
|
||||
errors: [{ messageId: "rawApiFetch" }],
|
||||
},
|
||||
{
|
||||
code: 'globalThis.fetch("https://example.test/data");',
|
||||
filename: "/repo/src/hooks/use-example.ts",
|
||||
errors: [{ messageId: "rawApiFetch" }],
|
||||
},
|
||||
{
|
||||
code: '"use client"; self.fetch(url);',
|
||||
filename: "/repo/src/app/client-page.tsx",
|
||||
errors: [{ messageId: "rawApiFetch" }],
|
||||
},
|
||||
{
|
||||
code: '"use client"; fetch(endpoint);',
|
||||
filename: "/repo/src/lib/i18n/context.tsx",
|
||||
errors: [{ messageId: "rawApiFetch" }],
|
||||
},
|
||||
{
|
||||
code: 'window["fetch"](endpoint);',
|
||||
filename: "/repo/src/components/example.tsx",
|
||||
errors: [{ messageId: "rawApiFetch" }],
|
||||
},
|
||||
],
|
||||
});
|
||||
@@ -0,0 +1,64 @@
|
||||
import { describe, it } from "vitest";
|
||||
import { RuleTester } from "eslint";
|
||||
import plugin from "../queryKey-factory.js";
|
||||
|
||||
RuleTester.describe = describe;
|
||||
RuleTester.it = it;
|
||||
RuleTester.itOnly = it.only;
|
||||
|
||||
const ruleTester = new RuleTester({
|
||||
languageOptions: {
|
||||
ecmaVersion: 2023,
|
||||
sourceType: "module",
|
||||
parserOptions: { ecmaFeatures: { jsx: true } },
|
||||
},
|
||||
});
|
||||
|
||||
const rule = plugin.rules["queryKey-factory"];
|
||||
|
||||
ruleTester.run("queryKey-factory", rule, {
|
||||
valid: [
|
||||
{
|
||||
code: "useQuery({ queryKey: queryKeys.example(id) });",
|
||||
filename: "/repo/src/components/example.tsx",
|
||||
},
|
||||
{
|
||||
code: "const key = queryKeys.example(id); useQuery({ queryKey: key });",
|
||||
filename: "/repo/src/hooks/use-example.ts",
|
||||
},
|
||||
{
|
||||
code: 'export const example = () => ["example"];',
|
||||
filename: "/repo/src/lib/query-keys/example.ts",
|
||||
},
|
||||
{
|
||||
code: 'useQuery({ queryKey: ["fixture"] });',
|
||||
filename: "/repo/src/components/__tests__/example.test.tsx",
|
||||
},
|
||||
{
|
||||
code: 'useQuery({ queryKey: ["server-prefetch"] });',
|
||||
filename: "/repo/src/app/server-page.tsx",
|
||||
},
|
||||
],
|
||||
invalid: [
|
||||
{
|
||||
code: 'useQuery({ queryKey: ["unguarded-component"] });',
|
||||
filename: "/repo/src/components/custom-metrics/example.tsx",
|
||||
errors: [{ messageId: "bareArray" }],
|
||||
},
|
||||
{
|
||||
code: 'useMutation({ mutationKey: ["unguarded-hook"] });',
|
||||
filename: "/repo/src/hooks/use-example.ts",
|
||||
errors: [{ messageId: "bareArray" }],
|
||||
},
|
||||
{
|
||||
code: '"use client"; useQuery({ queryKey: ["client-app"] });',
|
||||
filename: "/repo/src/app/previously-unguarded/page.tsx",
|
||||
errors: [{ messageId: "bareArray" }],
|
||||
},
|
||||
{
|
||||
code: '"use client"; useQuery({ queryKey: ["client-lib"] });',
|
||||
filename: "/repo/src/lib/client-state.tsx",
|
||||
errors: [{ messageId: "bareArray" }],
|
||||
},
|
||||
],
|
||||
});
|
||||
@@ -1,35 +1,24 @@
|
||||
/**
|
||||
* @fileoverview ESLint rule — client-side `/api/...` calls must route
|
||||
* through the typed `apiFetch` wrapper.
|
||||
* @fileoverview ESLint rule — client-side requests must route through the
|
||||
* typed API-fetch entry points.
|
||||
*
|
||||
* `src/lib/api/api-fetch.ts` owns the `.ok` check, the
|
||||
* `{ data, error, meta? }` envelope unwrap, and the `ApiError` shape
|
||||
* (message via `readError`, `status`, error-side `meta`). A raw
|
||||
* `fetch("/api/…")` in a component re-implements that contract by hand
|
||||
* — the exact drift this wrapper retired — so this rule flags it at
|
||||
* authoring time and in CI.
|
||||
* A raw `fetch(...)` in a client module can hide a same-origin API request
|
||||
* behind a variable, endpoint map, or conditional. Checking only literal
|
||||
* `/api/...` arguments therefore leaves the envelope and error contract open
|
||||
* to bypass. This rule rejects every bare Fetch API call in the client surface,
|
||||
* regardless of argument shape.
|
||||
*
|
||||
* Complements `healthlog/safe-fetch-required`: that rule covers
|
||||
* OUTBOUND egress (absolute / variable-sourced URLs) and exempts
|
||||
* same-origin relative paths; this rule covers exactly those same-origin
|
||||
* `/api/...` paths inside the client surface.
|
||||
* Use `apiGet` / `apiPost` / `apiPut` / `apiPatch` / `apiDelete` for envelope
|
||||
* JSON. Use `apiFetchEnvelope` when success metadata is required, and
|
||||
* `apiFetchRaw` for deliberate Response-level work such as external requests,
|
||||
* downloads, streams, beacons, or manual status branching.
|
||||
*
|
||||
* Allowed:
|
||||
* - `apiFetch` / verb helpers / `apiFetchEnvelope` / `apiFetchRaw` —
|
||||
* distinct identifiers, never match.
|
||||
* - calls inside `src/lib/api/api-fetch.ts` — the wrapper's own `fetch`.
|
||||
* - test files (`*.test.ts(x)`, `__tests__/`, `__mocks__/`) — they
|
||||
* mock or assert against `fetch` directly.
|
||||
*
|
||||
* The check is a syntactic `CallExpression` match against a bare
|
||||
* `fetch(` callee (Identifier `fetch`) and `globalThis.fetch(` /
|
||||
* `window.fetch(` / `self.fetch(` member forms, where the first
|
||||
* argument is a string literal or template literal whose head starts
|
||||
* with `/api/`. Variable-sourced or absolute URLs are the
|
||||
* safe-fetch-required rule's territory and stay out of scope here.
|
||||
* Components and hooks are client-facing by convention. Other `src/` modules
|
||||
* are guarded when they declare top-level `"use client"`; `src/lib/queries/`
|
||||
* remains an explicit client-transitive root. Server-only modules, tests,
|
||||
* mocks, and the wrapper implementation are exempt.
|
||||
*
|
||||
* @see src/lib/api/api-fetch.ts
|
||||
* @see eslint-plugins/healthlog/safe-fetch-required.js
|
||||
*/
|
||||
|
||||
"use strict";
|
||||
@@ -39,20 +28,9 @@
|
||||
// `String#includes`, mirroring the safe-fetch-required convention.
|
||||
const EXEMPT_FILES = ["src/lib/api/api-fetch.ts"];
|
||||
|
||||
// Enforce across the client-facing source roots. `src/lib/` stays out:
|
||||
// server-side lib code never self-calls `/api/` routes, and the
|
||||
// safe-fetch rule already covers its outbound calls. `src/hooks/` is
|
||||
// client-only by construction (v1.16.4) — its `/api/` reads route
|
||||
// through the wrapper like every component. `src/lib/queries/` is the
|
||||
// one `src/lib/` exception: it holds client-only TanStack-Query hooks
|
||||
// (every file is `"use client"`), so its `/api/` reads route through the
|
||||
// wrapper too.
|
||||
const ENFORCED_ROOTS = [
|
||||
"src/components/",
|
||||
"src/app/",
|
||||
"src/hooks/",
|
||||
"src/lib/queries/",
|
||||
];
|
||||
// Components and hooks are client-facing by convention. Query modules are
|
||||
// client-transitive even if a future refactor moves the directive to a barrel.
|
||||
const CLIENT_ROOTS = ["src/components/", "src/hooks/", "src/lib/queries/"];
|
||||
|
||||
function toPosix(filename) {
|
||||
return filename.replace(/\\/g, "/");
|
||||
@@ -67,12 +45,17 @@ function isTestFile(posix) {
|
||||
);
|
||||
}
|
||||
|
||||
function isEnforced(filename) {
|
||||
function isEnforced(filename, sourceCode) {
|
||||
const posix = toPosix(filename);
|
||||
if (!ENFORCED_ROOTS.some((root) => posix.includes(root))) return false;
|
||||
if (!posix.startsWith("src/") && !posix.includes("/src/")) return false;
|
||||
if (EXEMPT_FILES.some((f) => posix.includes(f))) return false;
|
||||
if (isTestFile(posix)) return false;
|
||||
return true;
|
||||
if (CLIENT_ROOTS.some((root) => posix.includes(root))) return true;
|
||||
return sourceCode.ast.body.some(
|
||||
(statement) =>
|
||||
statement.type === "ExpressionStatement" &&
|
||||
statement.directive === "use client",
|
||||
);
|
||||
}
|
||||
|
||||
/** @type {import("eslint").Rule.RuleModule} */
|
||||
@@ -81,49 +64,40 @@ const apiFetchRequiredRule = {
|
||||
type: "problem",
|
||||
docs: {
|
||||
description:
|
||||
"Same-origin /api/ calls must route through the apiFetch wrapper (src/lib/api/api-fetch.ts).",
|
||||
"Client-side requests must route through the apiFetch wrapper family (src/lib/api/api-fetch.ts).",
|
||||
},
|
||||
schema: [],
|
||||
messages: {
|
||||
rawApiFetch:
|
||||
'Raw fetch("/api/…") re-implements the envelope unwrap + error contract by hand. Import { apiFetch } (or a verb helper / apiFetchRaw) from "@/lib/api/api-fetch" and call it instead.',
|
||||
"Raw fetch() bypasses the client request contract. Use an apiFetch envelope helper, or apiFetchRaw for deliberate Response-level/external requests.",
|
||||
},
|
||||
},
|
||||
create(context) {
|
||||
const filename = context.filename ?? context.getFilename?.();
|
||||
if (!filename || !isEnforced(filename)) {
|
||||
const sourceCode = context.sourceCode ?? context.getSourceCode();
|
||||
if (!filename || !isEnforced(filename, sourceCode)) {
|
||||
return {};
|
||||
}
|
||||
|
||||
function isFetchCallee(callee) {
|
||||
// Bare `fetch(...)`.
|
||||
if (callee.type === "Identifier" && callee.name === "fetch") return true;
|
||||
// `globalThis.fetch(...)` / `window.fetch(...)` / `self.fetch(...)`.
|
||||
// `globalThis.fetch(...)` / `window.fetch(...)` / `self.fetch(...)`,
|
||||
// including their static computed forms (`window["fetch"](...)`).
|
||||
if (
|
||||
callee.type === "MemberExpression" &&
|
||||
!callee.computed &&
|
||||
callee.property.type === "Identifier" &&
|
||||
callee.property.name === "fetch" &&
|
||||
callee.object.type === "Identifier" &&
|
||||
(callee.object.name === "globalThis" ||
|
||||
callee.object.name === "window" ||
|
||||
callee.object.name === "self")
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function isApiPath(arg) {
|
||||
if (!arg) return false;
|
||||
const isApiHead = (head) => head.startsWith("/api/");
|
||||
// `fetch("/api/…")`
|
||||
if (arg.type === "Literal" && typeof arg.value === "string") {
|
||||
return isApiHead(arg.value);
|
||||
}
|
||||
// `fetch(`/api/${id}`)` — inspect the template's first cooked chunk.
|
||||
if (arg.type === "TemplateLiteral" && arg.quasis.length > 0) {
|
||||
return isApiHead(arg.quasis[0].value.cooked ?? "");
|
||||
const propertyName =
|
||||
!callee.computed && callee.property.type === "Identifier"
|
||||
? callee.property.name
|
||||
: callee.computed && callee.property.type === "Literal"
|
||||
? callee.property.value
|
||||
: null;
|
||||
return propertyName === "fetch";
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -131,7 +105,6 @@ const apiFetchRequiredRule = {
|
||||
return {
|
||||
CallExpression(node) {
|
||||
if (!isFetchCallee(node.callee)) return;
|
||||
if (!isApiPath(node.arguments[0])) return;
|
||||
context.report({ node, messageId: "rawApiFetch" });
|
||||
},
|
||||
};
|
||||
|
||||
@@ -1,96 +1,57 @@
|
||||
/**
|
||||
* @fileoverview ESLint rule — `queryKey` / `mutationKey` literal-array
|
||||
* factory enforcement.
|
||||
* factory enforcement across the complete client tree.
|
||||
*
|
||||
* v1.4.41 W-PROCESS-DOCS — promoted from the test-guard substitute
|
||||
* (`src/lib/__tests__/query-keys.test.ts`, factory-bypass guard added
|
||||
* in v1.4.40 W-RSC) to a real ESLint rule. The test-guard substitute
|
||||
* stays in place as a belt-and-braces safety net for repo-walk
|
||||
* coverage of files the ESLint config might miss; this rule fires at
|
||||
* authoring time inside the IDE and at lint CI time.
|
||||
* Every TanStack key must come from `src/lib/query-keys/`. The rule flags
|
||||
* object-property `queryKey: [ … ]` and `mutationKey: [ … ]` values in
|
||||
* components, hooks, client query modules, and any source module declaring
|
||||
* top-level `"use client"`.
|
||||
*
|
||||
* The rule flags any object-property `queryKey: [ … ]` or
|
||||
* `mutationKey: [ … ]` whose value is a bare ArrayExpression — i.e.
|
||||
* the bypass shape that drove audit-H1 in `.planning/round-v1439-
|
||||
* arch-qa-frontend.md`. Acceptable shapes:
|
||||
* Accepted call-site shapes include direct factory calls, identifiers already
|
||||
* built from the factory, and conditionals selecting factory calls. Tests and
|
||||
* the factory definition directory are exempt because they intentionally
|
||||
* construct literal fixtures and tuples.
|
||||
*
|
||||
* - `queryKey: queryKeys.something(arg)` — factory call
|
||||
* - `queryKey: someLocal` — indirect identifier
|
||||
* - `queryKey: cond ? queryKeys.a() : queryKeys.b()` — conditional via factory
|
||||
*
|
||||
* Files outside `WHITELISTED_FILES` are exempt entirely — the
|
||||
* test-guard substitute holds the "guarded surface" line until a
|
||||
* future wave extends both the guard and this whitelist together.
|
||||
*
|
||||
* @see src/lib/query-keys/ — factory home (do not lint as offender)
|
||||
* @see src/lib/__tests__/query-keys.test.ts — test-guard substitute
|
||||
* @see .planning/phase-W-PROCESS-DOCS-v1441-report.md
|
||||
* @see src/lib/query-keys/
|
||||
* @see src/lib/__tests__/query-keys.test.ts
|
||||
*/
|
||||
|
||||
"use strict";
|
||||
|
||||
// Files that are ALLOWED to declare a literal-array queryKey. Mirrors
|
||||
// the test-guard substitute's `guardedRoots` allowlist inverted: every
|
||||
// file under those roots MUST use the factory, every file outside is
|
||||
// exempt for now. Path matches use `String#includes` semantics against
|
||||
// the absolute filename — keep entries as posix-style suffix paths.
|
||||
const FACTORY_HOME_FILES = [
|
||||
// The factory's own unit-test file constructs literal keys to assert
|
||||
// the factory output shape.
|
||||
"src/lib/__tests__/query-keys.test.ts",
|
||||
];
|
||||
|
||||
// The factory definition files are allowed to declare literal keys —
|
||||
// that's the whole point of the factory. The factory is split into
|
||||
// per-feature files under this directory (barrel at index.ts).
|
||||
const FACTORY_HOME_DIRECTORY = "src/lib/query-keys";
|
||||
|
||||
// Directories under which any `queryKey: [ … ]` literal is an error.
|
||||
// Extend in lockstep with the test-guard substitute's `guardedRoots`.
|
||||
const GUARDED_DIRECTORIES = [
|
||||
"src/components/charts",
|
||||
"src/components/comparison",
|
||||
// v1.4.41 W-FRONTEND-FACTORY — auth + notifications migrated to the
|
||||
// factory. Mirror the test-guard's guardedRoots so IDE/lint CI fail
|
||||
// at the same boundary the unit-test walker does.
|
||||
"src/app/auth",
|
||||
"src/app/notifications",
|
||||
// v1.4.42 W3-QUERYKEY-LONGTAIL — the settings / medications /
|
||||
// admin / hooks surface is now factory-only. Every long-tail
|
||||
// bare-literal flagged by audit-H1 routes through `queryKeys.<entry>()`.
|
||||
"src/components/settings",
|
||||
"src/components/medications",
|
||||
"src/components/admin",
|
||||
"src/hooks",
|
||||
];
|
||||
// Components and hooks are client-facing by convention. Query modules are
|
||||
// client-transitive even if a future refactor moves the directive to a barrel.
|
||||
const CLIENT_ROOTS = ["src/components/", "src/hooks/", "src/lib/queries/"];
|
||||
|
||||
// Individual guarded files outside the directories above.
|
||||
const GUARDED_FILES = [
|
||||
"src/app/page.tsx",
|
||||
"src/hooks/use-auth.ts",
|
||||
// v1.4.41 W-FRONTEND-FACTORY — about-section migrated.
|
||||
"src/components/settings/about-section.tsx",
|
||||
// v1.4.42 W3-QUERYKEY-LONGTAIL — medications + targets pages now
|
||||
// route every read through the factory.
|
||||
"src/app/medications/page.tsx",
|
||||
"src/app/medications/[id]/history/page.tsx",
|
||||
"src/app/targets/page.tsx",
|
||||
];
|
||||
function toPosix(filename) {
|
||||
return filename.replace(/\\/g, "/");
|
||||
}
|
||||
|
||||
function isGuarded(filename) {
|
||||
// Factory home is never an offender even if it shows up under a
|
||||
// guarded directory by accident.
|
||||
for (const home of FACTORY_HOME_FILES) {
|
||||
if (filename.endsWith(home)) return false;
|
||||
function isTestFile(posix) {
|
||||
return (
|
||||
/\.(?:test|spec)\.[cm]?[jt]sx?$/.test(posix) ||
|
||||
posix.includes("/__tests__/") ||
|
||||
posix.includes("/__mocks__/")
|
||||
);
|
||||
}
|
||||
|
||||
function isGuarded(filename, sourceCode) {
|
||||
const posix = toPosix(filename);
|
||||
if (!posix.startsWith("src/") && !posix.includes("/src/")) return false;
|
||||
if (
|
||||
posix.startsWith(`${FACTORY_HOME_DIRECTORY}/`) ||
|
||||
posix.includes(`/${FACTORY_HOME_DIRECTORY}/`)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
if (filename.includes(`/${FACTORY_HOME_DIRECTORY}/`)) return false;
|
||||
for (const dir of GUARDED_DIRECTORIES) {
|
||||
if (filename.includes(`/${dir}/`)) return true;
|
||||
}
|
||||
for (const file of GUARDED_FILES) {
|
||||
if (filename.endsWith(file)) return true;
|
||||
}
|
||||
return false;
|
||||
if (isTestFile(posix)) return false;
|
||||
if (CLIENT_ROOTS.some((root) => posix.includes(root))) return true;
|
||||
return sourceCode.ast.body.some(
|
||||
(statement) =>
|
||||
statement.type === "ExpressionStatement" &&
|
||||
statement.directive === "use client",
|
||||
);
|
||||
}
|
||||
|
||||
/** @type {import('eslint').Rule.RuleModule} */
|
||||
@@ -99,7 +60,7 @@ const queryKeyFactoryRule = {
|
||||
type: "problem",
|
||||
docs: {
|
||||
description:
|
||||
"Disallow literal-array `queryKey` / `mutationKey` declarations in guarded files. Use `queryKeys.<entry>()` from `src/lib/query-keys/` instead.",
|
||||
"Disallow literal-array `queryKey` / `mutationKey` declarations in client modules. Use `queryKeys.<entry>()` from `src/lib/query-keys/` instead.",
|
||||
recommended: false,
|
||||
},
|
||||
messages: {
|
||||
@@ -110,7 +71,8 @@ const queryKeyFactoryRule = {
|
||||
},
|
||||
create(context) {
|
||||
const filename = context.filename ?? context.getFilename?.();
|
||||
if (!filename || !isGuarded(filename)) {
|
||||
const sourceCode = context.sourceCode ?? context.getSourceCode();
|
||||
if (!filename || !isGuarded(filename, sourceCode)) {
|
||||
return {};
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user