@stapel/eslint-plugin 0.3.0 → 0.4.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 CHANGED
@@ -38,6 +38,34 @@ The `recommended` preset:
38
38
  - **overrides** the content rules off in tests and fixtures (they exercise the
39
39
  anti-patterns on purpose).
40
40
 
41
+ ### `reserved-paths.json`
42
+
43
+ `stapel/no-reserved-backend-route` reads a project-root `reserved-paths.json`
44
+ (no fixed location config beyond `settings.stapel.reservedPathsFile` — see
45
+ below), the same flat projection stapel-tools' project generator emits:
46
+
47
+ ```json
48
+ {
49
+ "reservedPathPrefixes": [
50
+ "/admin",
51
+ "/staticfiles",
52
+ "/media",
53
+ "/calendar/api",
54
+ "/calendar/swagger"
55
+ ]
56
+ }
57
+ ```
58
+
59
+ `reservedPathPrefixes` is a flat array of path prefixes the backend owns. A
60
+ route is flagged when it **equals** a prefix or continues **past a segment
61
+ boundary** beneath one (`/calendar/api/x` matches `/calendar/api`;
62
+ `/calendar-archive` does not). **Never** put a bare module root
63
+ (`/calendar`) in this list — the generator only emits sub-path reservations,
64
+ because a bare root belongs to the frontend SPA by convention. If the file is
65
+ missing, the rule is a no-op — it never fails the lint run.
66
+
67
+
68
+
41
69
  ## Rules
42
70
 
43
71
  | Rule | Catches |
@@ -58,6 +86,7 @@ The `recommended` preset:
58
86
  | `stapel/demo-literal-meta` | `defineDemo()` with non-literal meta (dynamic `id`/`title`/`description`/`covers`) — breaks static extraction into `demos.json`/`manifest.demos` (§4.2) |
59
87
  | `stapel/no-raw-storage` | direct `localStorage`/`sessionStorage`/`indexedDB` (bare or via `window.`/`globalThis.`/`self.`) or importing `idb-keyval` outside `@stapel/core`'s repository layer — raw storage is neither wiped on logout nor encrypted; persist through `createRepository()` (frontend-core-architecture-v2 §43.4). Off in core's `storage.ts`/`repository.ts`/`query.ts` (the one legal home) and in tests. Extend the banned module list via `options.modules` or `settings.stapel.storageModules` |
60
88
  | `stapel/no-adhoc-401` | comparing a status to the literal `401` (`===`/`!==`/`case 401:`) or wiring an axios-style `*.interceptors` chain — ad hoc 401 handling bypasses the single-flight refresh + logout-hook registry; 401s are handled ONCE, in core's `createStapelClient` (`onAuthRefresh` seam) + `SessionManager` (§43.2). Off in core's `client.ts`/`session.ts` and in tests |
89
+ | `stapel/no-reserved-backend-route` | an SPA route (`<Route path="…">`, a `createBrowserRouter`/`createHashRouter`/`createMemoryRouter` array literal, or any `{ path: "…", element/Component/children/index/errorElement/loader/action/lazy: … }` RouteObject) whose path falls INTO a reserved backend sub-path — `/<mod>/api/…`, `/<mod>/swagger…`, or the project-wide `/admin`, `/staticfiles`, `/media` (§57 nginx canon). A **bare module root** (`/calendar`) is legitimate and never flagged — roots belong to the frontend; only sub-paths collide. Data-driven: reads the flat `reservedPathPrefixes` array from `reserved-paths.json` (emitted by stapel-tools' project generator) at the workspace root, or `settings.stapel.reservedPathsFile`/`reservedPaths`. No catalog → no-op (never a crash) |
61
90
 
62
91
  ### Settings
63
92
 
@@ -72,7 +101,8 @@ settings: {
72
101
  rawModules: ["@x/raw"], // extra raw-token entry points
73
102
  storageModules: ["level"], // extra banned storage-backend packages
74
103
  eventsManifests: [manifest],// or eventNames: ["pricing.plan.selected", …]
75
- operationsManifests: [manifest], // or operationPaths: ["/auth/api/me/", …]
104
+ operationsManifests: [manifest], // or operationPaths: ["/auth/api/v1/me/", …]
105
+ reservedPathsFile: "./reserved-paths.json", // or reservedPaths: ["/admin", …]
76
106
  httpVerbs: ["get","post"], // client methods no-string-paths inspects
77
107
  queryHooks: ["useQuery"], // extra react-query hooks to inspect for keys
78
108
  trackedWrappers: ["tracked"],
package/index.js CHANGED
@@ -20,6 +20,7 @@ import noDirectAnalyticsProvider from "./rules/no-direct-analytics-provider.js";
20
20
  import demoLiteralMeta from "./rules/demo-literal-meta.js";
21
21
  import noRawStorage from "./rules/no-raw-storage.js";
22
22
  import noAdhoc401 from "./rules/no-adhoc-401.js";
23
+ import noReservedBackendRoute from "./rules/no-reserved-backend-route.js";
23
24
 
24
25
  const rules = {
25
26
  "no-raw-colors": noRawColors,
@@ -42,6 +43,9 @@ const rules = {
42
43
  // Session-substrate guardrails (frontend-core-architecture-v2 §43).
43
44
  "no-raw-storage": noRawStorage,
44
45
  "no-adhoc-401": noAdhoc401,
46
+ // Front/back path-collision guardrail (owner directive: SPA router must not
47
+ // claim a reserved backend sub-path).
48
+ "no-reserved-backend-route": noReservedBackendRoute,
45
49
  };
46
50
 
47
51
  const plugin = {
@@ -160,6 +164,10 @@ const recommended = [
160
164
  // + SessionManager.
161
165
  "stapel/no-raw-storage": "error",
162
166
  "stapel/no-adhoc-401": "error",
167
+ // Path-collision guardrail: the SPA router must not claim a reserved
168
+ // backend sub-path (/<mod>/api/…, /<mod>/swagger…, /admin, /staticfiles,
169
+ // /media — §57 nginx canon). No-op without reserved-paths.json.
170
+ "stapel/no-reserved-backend-route": "error",
163
171
  },
164
172
  },
165
173
  {
@@ -227,6 +235,9 @@ const recommended = [
227
235
  // contract test greps localStorage directly) and on 401 fixtures.
228
236
  "stapel/no-raw-storage": "off",
229
237
  "stapel/no-adhoc-401": "off",
238
+ // Route fixtures legitimately probe reserved-path collisions on purpose
239
+ // (that's what this rule's own tests do).
240
+ "stapel/no-reserved-backend-route": "off",
230
241
  // require-disable-description stays ON — disable hygiene applies everywhere.
231
242
  },
232
243
  },
package/lib/data.js CHANGED
@@ -333,6 +333,78 @@ export function loadOperationCatalog(settings = {}) {
333
333
  return _operationCatalogDefault;
334
334
  }
335
335
 
336
+ // ── reserved backend-path catalog (reserved-paths.json) ──────────────────────
337
+ //
338
+ // no-reserved-backend-route reads the SAME projection stapel-tools' project
339
+ // generator emits at the workspace root: a flat array of path PREFIXES a
340
+ // backend module reserves under its own slug (`/<mod>/api/…`,
341
+ // `/<mod>/swagger…`), plus the project-wide infra prefixes nginx enforces
342
+ // (`/admin`, `/staticfiles`, `/media` — §57 canon, compose_templates.NGINX_CONF).
343
+ // Schema: `{ "reservedPathPrefixes": string[] }`. A bare module ROOT
344
+ // (`/<mod>`) must never appear in the list — roots belong to the frontend SPA
345
+ // by convention; only sub-path reservations are catalogued. A missing/
346
+ // unreadable file degrades the rule to a no-op (empty catalog, never a
347
+ // crash) — exactly like the token/i18n/events/operation loaders above (§2.1).
348
+
349
+ function discoverReservedPathsFile(from) {
350
+ const root = workspaceRoot(from);
351
+ if (root) {
352
+ const p = join(root, "reserved-paths.json");
353
+ if (existsSync(p)) return p;
354
+ }
355
+ const local = join(from, "reserved-paths.json");
356
+ if (existsSync(local)) return local;
357
+ return null;
358
+ }
359
+
360
+ function buildReservedPathCatalog(prefixes) {
361
+ const list = (prefixes ?? []).filter(
362
+ (p) => typeof p === "string" && p.length > 0
363
+ );
364
+ return {
365
+ prefixes: list,
366
+ loaded: list.length > 0,
367
+ /**
368
+ * The reserved prefix a route path falls INTO — equal to it, or past a
369
+ * segment boundary beneath it — else null. A route that merely shares a
370
+ * prefix's leading segment (a bare module root, e.g. "/calendar" against
371
+ * reserved "/calendar/api") does NOT match: roots are the frontend's by
372
+ * canon, only sub-paths are reserved.
373
+ */
374
+ matches: (route) => {
375
+ if (typeof route !== "string" || !route.startsWith("/")) return null;
376
+ for (const p of list) {
377
+ const boundary = p.endsWith("/") ? p : `${p}/`;
378
+ if (route === p || route.startsWith(boundary)) return p;
379
+ }
380
+ return null;
381
+ },
382
+ };
383
+ }
384
+
385
+ let _reservedPathCatalogDefault;
386
+ export function loadReservedPathCatalog(settings = {}) {
387
+ if (settings.reservedPaths) {
388
+ return buildReservedPathCatalog(settings.reservedPaths);
389
+ }
390
+ if (settings.reservedPathsFile) {
391
+ // Explicit override → never memoized (mirrors the other loaders: only the
392
+ // zero-config discovered default is cached).
393
+ return buildReservedPathCatalog(
394
+ readJson(settings.reservedPathsFile)?.reservedPathPrefixes
395
+ );
396
+ }
397
+ if (!_reservedPathCatalogDefault) {
398
+ const file = discoverReservedPathsFile(
399
+ process.cwd ? process.cwd() : HERE
400
+ );
401
+ _reservedPathCatalogDefault = buildReservedPathCatalog(
402
+ file ? readJson(file)?.reservedPathPrefixes : undefined
403
+ );
404
+ }
405
+ return _reservedPathCatalogDefault;
406
+ }
407
+
336
408
  /** Read `context.settings.stapel` (flat config) with a stable empty default. */
337
409
  export function stapelSettings(context) {
338
410
  return (context.settings && context.settings.stapel) || {};
@@ -344,6 +416,7 @@ export function __resetCaches() {
344
416
  _i18nDefault = undefined;
345
417
  _eventsCatalogDefault = undefined;
346
418
  _operationCatalogDefault = undefined;
419
+ _reservedPathCatalogDefault = undefined;
347
420
  }
348
421
 
349
422
  export { resolve as _resolve };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stapel/eslint-plugin",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "Stapel frontend guardrails as static lint rules (frontend-guardrails §2): no raw colours, no raw fetch, no raw-ramp imports, i18n-key existence, no hardcoded user-facing text — every rule reads the same generated artifacts (tokens manifest, i18n key registries) as the codegen, so lint and code never drift. Ships a flat-config `recommended` preset plus a self-contained stylelint preset for CSS.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -0,0 +1,216 @@
1
+ // stapel/no-reserved-backend-route — path-collision guardrail between the SPA
2
+ // router and the backend's reserved namespace (§57 nginx canon:
3
+ // stapel-tools' _compose_templates.NGINX_CONF / NGINX_LOCAL_CONF_TEMPLATE —
4
+ // "a frontend app must never define a client route starting with
5
+ // /staticfiles/, /media/ or /<backend-slug>/api|swagger…").
6
+ //
7
+ // Canon (owner directive): a BARE module root (`/calendar`) is legitimate —
8
+ // roots belong to the frontend. Only a route that falls INTO a reserved
9
+ // SUB-path (`/calendar/api/…`, `/calendar/swagger…`, and the project-wide
10
+ // `/admin`, `/staticfiles`, `/media`) collides with the backend. The reserved
11
+ // list itself is data-driven — read from `reserved-paths.json` (the same
12
+ // projection stapel-tools' generator emits), never hand-maintained here, so
13
+ // the rule tracks a project's actual module set (§2.1). A missing catalog
14
+ // degrades the rule to a no-op (never a crash) — same policy as every other
15
+ // data-driven rule in this plugin.
16
+ //
17
+ // Two detector shapes, in the spirit of the other route/path guardrails
18
+ // (no-string-paths):
19
+ // 1. JSX — <Route path="…"> (react-router).
20
+ // 2. Object route configs — a `path` property on an object that reads as a
21
+ // RouteObject (has an `element`/`Component`/`children`/`index`/
22
+ // `errorElement`/`loader`/`action`/`lazy` sibling), OR sits inside the
23
+ // array literal passed straight to `createBrowserRouter`/
24
+ // `createHashRouter`/`createMemoryRouter` — covers `useRoutes([...])`
25
+ // configs and router-factory calls alike.
26
+ // Only string literals and the static prefix of a template literal are
27
+ // checked (dynamic segments are unknowable — false-positive policy, same as
28
+ // no-string-paths).
29
+ import { loadReservedPathCatalog, stapelSettings } from "../lib/data.js";
30
+
31
+ const ROUTER_FACTORIES = new Set([
32
+ "createBrowserRouter",
33
+ "createHashRouter",
34
+ "createMemoryRouter",
35
+ "createStaticRouter",
36
+ ]);
37
+
38
+ const ROUTE_SHAPE_KEYS = new Set([
39
+ "element",
40
+ "Component",
41
+ "children",
42
+ "index",
43
+ "errorElement",
44
+ "loader",
45
+ "action",
46
+ "lazy",
47
+ ]);
48
+
49
+ // Prefixes with more than one path segment (e.g. "/calendar/api") are a
50
+ // module's own sub-path reservation — the bare root one segment up
51
+ // ("/calendar") is the frontend's by canon, worth saying explicitly. A
52
+ // single-segment prefix ("/admin", "/staticfiles", "/media") is a
53
+ // project-wide infra reservation with no such carve-out.
54
+ const SUBPATH_HINT =
55
+ "Reserved for the backend (nginx §57 canon). A bare module root (\"/{{mod}}\") stays the frontend's — only this sub-path collides. Route somewhere else, or drop the reservation from reserved-paths.json if this module no longer owns it.";
56
+ const GLOBAL_HINT =
57
+ "Reserved project-wide for the backend/infra (nginx §57 canon: /admin, /staticfiles, /media) — there is no frontend carve-out for this prefix. Route somewhere else.";
58
+
59
+ /** A meaningful path: leading "/" plus at least one segment char. */
60
+ function isPathLike(str) {
61
+ return typeof str === "string" && str.startsWith("/") && /[A-Za-z0-9]/.test(str);
62
+ }
63
+
64
+ function jsxAttr(node, name) {
65
+ return node.attributes.find(
66
+ (a) =>
67
+ a.type === "JSXAttribute" &&
68
+ a.name &&
69
+ a.name.type === "JSXIdentifier" &&
70
+ a.name.name === name
71
+ );
72
+ }
73
+
74
+ /** The literal/template node behind a JSX attribute's value, or null. */
75
+ function jsxAttrValueNode(attr) {
76
+ if (!attr || attr.value == null) return null;
77
+ const v = attr.value;
78
+ if (v.type === "Literal") return v;
79
+ if (v.type === "JSXExpressionContainer") return v.expression;
80
+ return null;
81
+ }
82
+
83
+ /** String literal value, or a template literal's static-prefix, else null. */
84
+ function literalOrTemplatePrefix(node) {
85
+ if (!node) return null;
86
+ if (node.type === "Literal" && typeof node.value === "string") {
87
+ return isPathLike(node.value) ? node.value : null;
88
+ }
89
+ if (node.type === "TemplateLiteral" && node.quasis.length > 0) {
90
+ const head = node.quasis[0].value.cooked ?? node.quasis[0].value.raw ?? "";
91
+ return isPathLike(head) ? head : null;
92
+ }
93
+ return null;
94
+ }
95
+
96
+ function hasRouteShapeSibling(objExpr) {
97
+ return objExpr.properties.some(
98
+ (p) =>
99
+ p.type === "Property" &&
100
+ !p.computed &&
101
+ p.key.type === "Identifier" &&
102
+ ROUTE_SHAPE_KEYS.has(p.key.name)
103
+ );
104
+ }
105
+
106
+ /**
107
+ * True if `objExpr` sits (through any nesting of `children` arrays / plain
108
+ * arrays) inside the argument list of a `createBrowserRouter`-family call.
109
+ */
110
+ function isInRouterFactoryCall(objExpr) {
111
+ let cur = objExpr;
112
+ let parent = objExpr.parent;
113
+ while (parent) {
114
+ if (parent.type === "ArrayExpression") {
115
+ cur = parent;
116
+ parent = parent.parent;
117
+ continue;
118
+ }
119
+ if (
120
+ parent.type === "Property" &&
121
+ parent.value === cur &&
122
+ !parent.computed &&
123
+ parent.key.type === "Identifier" &&
124
+ parent.key.name === "children"
125
+ ) {
126
+ cur = parent.parent; // the enclosing ObjectExpression
127
+ parent = cur.parent;
128
+ continue;
129
+ }
130
+ if (parent.type === "CallExpression") {
131
+ return (
132
+ parent.arguments.includes(cur) &&
133
+ parent.callee.type === "Identifier" &&
134
+ ROUTER_FACTORIES.has(parent.callee.name)
135
+ );
136
+ }
137
+ return false;
138
+ }
139
+ return false;
140
+ }
141
+
142
+ export default {
143
+ meta: {
144
+ type: "problem",
145
+ docs: {
146
+ description:
147
+ "Disallow an SPA route path that falls into a reserved backend sub-path (/<mod>/api/…, /<mod>/swagger…, /admin, /staticfiles, /media). A bare module root is legitimate.",
148
+ },
149
+ schema: [
150
+ {
151
+ type: "object",
152
+ properties: {
153
+ reservedPathPrefixes: { type: "array", items: { type: "string" } },
154
+ },
155
+ additionalProperties: false,
156
+ },
157
+ ],
158
+ messages: {
159
+ reservedSubPath:
160
+ 'Route path "{{path}}" collides with the reserved backend prefix "{{prefix}}". ' +
161
+ SUBPATH_HINT,
162
+ reservedGlobal:
163
+ 'Route path "{{path}}" collides with the reserved backend prefix "{{prefix}}". ' +
164
+ GLOBAL_HINT,
165
+ },
166
+ },
167
+ create(context) {
168
+ const settings = stapelSettings(context);
169
+ const catalog = loadReservedPathCatalog(
170
+ context.options[0]?.reservedPathPrefixes
171
+ ? { reservedPaths: context.options[0].reservedPathPrefixes }
172
+ : settings
173
+ );
174
+ if (!catalog.loaded) return {}; // no reserved-paths.json → no-op, never guess
175
+
176
+ function check(node, path) {
177
+ const prefix = catalog.matches(path);
178
+ if (!prefix) return;
179
+ const segments = prefix.split("/").filter(Boolean);
180
+ const isSubPath = segments.length > 1;
181
+ const mod = segments[0];
182
+ context.report({
183
+ node,
184
+ messageId: isSubPath ? "reservedSubPath" : "reservedGlobal",
185
+ data: { path, prefix, mod },
186
+ });
187
+ }
188
+
189
+ return {
190
+ // Detector 1: <Route path="…">.
191
+ JSXOpeningElement(node) {
192
+ if (!(node.name.type === "JSXIdentifier" && node.name.name === "Route")) return;
193
+ const attr = jsxAttr(node, "path");
194
+ const valueNode = jsxAttrValueNode(attr);
195
+ const path = literalOrTemplatePrefix(valueNode);
196
+ if (path) check(valueNode, path);
197
+ },
198
+ // Detector 2: object route configs (RouteObject shape or a
199
+ // createBrowserRouter-family array literal).
200
+ Property(node) {
201
+ if (
202
+ node.computed ||
203
+ node.key.type !== "Identifier" ||
204
+ node.key.name !== "path" ||
205
+ node.parent.type !== "ObjectExpression"
206
+ )
207
+ return;
208
+ const path = literalOrTemplatePrefix(node.value);
209
+ if (!path) return;
210
+ const objExpr = node.parent;
211
+ if (!hasRouteShapeSibling(objExpr) && !isInRouterFactoryCall(objExpr)) return;
212
+ check(node.value, path);
213
+ },
214
+ };
215
+ },
216
+ };