@timber-js/oxlint-plugin 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.
Files changed (3) hide show
  1. package/README.md +41 -2
  2. package/dist/index.js +936 -0
  3. package/package.json +37 -4
package/README.md CHANGED
@@ -1,3 +1,42 @@
1
- # Temporary Holding Version
1
+ # @timber-js/oxlint-plugin
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ oxlint rules for [timber.js](https://github.com/switz/timber.js) apps. These rules know your route conventions and which code runs on the server, and each one is backed by a bug that shipped in a real timber app.
4
+
5
+ The plugin adds to a general config such as `@switz/lint-config` and does not replace it.
6
+
7
+ ```sh
8
+ pnpm add -D @timber-js/oxlint-plugin
9
+ ```
10
+
11
+ ```json
12
+ {
13
+ "jsPlugins": ["@timber-js/oxlint-plugin"],
14
+ "rules": {
15
+ "timber/no-ignored-nextjs-config": "error",
16
+ "timber/server-fetch-needs-signal": "error",
17
+ "timber/no-manual-param-parsing": "error"
18
+ }
19
+ }
20
+ ```
21
+
22
+ ## Rules
23
+
24
+ - **`no-ignored-nextjs-config`** flags Next.js configuration that timber accepts and never reads:
25
+ - `export const dynamic` / `revalidate` / `runtime` / `fetchCache` / … in pages, layouts and routes
26
+ - `generateStaticParams` (timber reads `generateStaticSegmentParams`)
27
+ - `'use cache'`
28
+ - `fetch(url, { next: { revalidate } })`
29
+ - **`server-fetch-needs-signal`** flags a server-side `fetch` with no `signal`. A stalled upstream holds the response until the render timeout. Fix it with `signal: AbortSignal.timeout(ms)`.
30
+ - **`no-manual-param-parsing`** flags `Number()` / `parseInt()` over raw segment or search params, which accept `1e2`, `""` and out-of-range ids. Give the param a codec in `app/schema.ts` (or `defineSearchParams`), so bad input 404s. A param whose codec already decodes it is not reported.
31
+
32
+ ## Settings
33
+
34
+ The plugin finds your app the way `timber()` does. The root is the nearest directory with a `vite.config.*` or `timber.config.*`, and the app directory is `app/` or `src/app/` under it. You can override either:
35
+
36
+ ```json
37
+ { "settings": { "timber": { "appDir": "src/app", "pageExtensions": ["tsx", "ts", "mdx"] } } }
38
+ ```
39
+
40
+ `server-fetch-needs-signal` uses the module graph when `.timber/graph-cache.json` exists. That file is written by `timber graph --all` and by the dev server. With the graph, a helper in `lib/` that only server code imports counts as server code. Without it, the rule checks only files it can classify on their own: those with a directive, a `server-only` import, or a route convention.
41
+
42
+ Design notes: [design/54-lint-plugin.md](../../design/54-lint-plugin.md).
package/dist/index.js ADDED
@@ -0,0 +1,936 @@
1
+ // src/ast.ts
2
+ function fileDirective(program) {
3
+ for (const stmt of program.body) {
4
+ if (stmt.type !== "ExpressionStatement" || typeof stmt.directive !== "string") break;
5
+ if (stmt.directive === "use client" || stmt.directive === "use server") return stmt.directive;
6
+ }
7
+ return null;
8
+ }
9
+ function unwrap(node) {
10
+ let n = node;
11
+ for (; ; ) {
12
+ switch (n.type) {
13
+ case "TSAsExpression":
14
+ case "TSSatisfiesExpression":
15
+ case "TSNonNullExpression":
16
+ case "TSTypeAssertion":
17
+ case "ParenthesizedExpression":
18
+ case "ChainExpression":
19
+ n = n.expression;
20
+ continue;
21
+ case "AwaitExpression":
22
+ n = n.argument;
23
+ continue;
24
+ default:
25
+ return n;
26
+ }
27
+ }
28
+ }
29
+ function importBindings(program) {
30
+ const out = /* @__PURE__ */ new Map();
31
+ for (const stmt of program.body) {
32
+ if (stmt.type !== "ImportDeclaration" || stmt.importKind === "type") continue;
33
+ const source = stmt.source.value;
34
+ for (const spec of stmt.specifiers) {
35
+ if (spec.type === "ImportSpecifier") {
36
+ if (spec.importKind === "type") continue;
37
+ const imported = spec.imported.type === "Identifier" ? spec.imported.name : spec.imported.value;
38
+ out.set(spec.local.name, { source, imported });
39
+ } else if (spec.type === "ImportDefaultSpecifier") {
40
+ out.set(spec.local.name, { source, imported: "default" });
41
+ } else {
42
+ out.set(spec.local.name, { source, imported: "*" });
43
+ }
44
+ }
45
+ }
46
+ return out;
47
+ }
48
+ function findVariable(context, id) {
49
+ for (let scope = context.sourceCode.getScope(id); scope; scope = scope.upper) {
50
+ const v = scope.set.get(id.name);
51
+ if (v && v.defs.length > 0) return v;
52
+ }
53
+ return null;
54
+ }
55
+ function resolvesToImport(context, id) {
56
+ return findVariable(context, id)?.defs.some((d) => d.type === "ImportBinding") ?? false;
57
+ }
58
+ function isImportedCall(context, callee, imports, sources, name) {
59
+ const c = unwrap(callee);
60
+ if (c.type === "Identifier") {
61
+ const b = imports.get(c.name);
62
+ return b !== void 0 && b.imported === name && sources.includes(b.source) && resolvesToImport(context, c);
63
+ }
64
+ if (c.type === "MemberExpression" && !c.computed && c.object.type === "Identifier" && c.property.type === "Identifier" && c.property.name === name) {
65
+ const b = imports.get(c.object.name);
66
+ return b !== void 0 && b.imported === "*" && sources.includes(b.source) && resolvesToImport(context, c.object);
67
+ }
68
+ return false;
69
+ }
70
+ function isUndeclared(context, id) {
71
+ return findVariable(context, id) === null;
72
+ }
73
+ function isGlobal(context, node, name) {
74
+ const n = unwrap(node);
75
+ if (n.type === "Identifier") {
76
+ return n.name === name && isUndeclared(context, n);
77
+ }
78
+ if (n.type === "MemberExpression" && !n.computed && n.property.type === "Identifier" && n.property.name === name && n.object.type === "Identifier" && (n.object.name === "globalThis" || n.object.name === "window" || n.object.name === "self")) {
79
+ return isUndeclared(context, n.object);
80
+ }
81
+ return false;
82
+ }
83
+ function propertyKeyName(prop) {
84
+ if (prop.key.type === "Identifier" && !prop.computed) return prop.key.name;
85
+ if (prop.key.type === "Literal" && typeof prop.key.value === "string") return prop.key.value;
86
+ return null;
87
+ }
88
+
89
+ // src/file-kind.ts
90
+ import { basename, dirname as dirname2, extname, relative, sep } from "node:path";
91
+
92
+ // ../timber-app/src/routing/types.ts
93
+ var INTERCEPTION_MARKERS = ["(..)(..)", "(.)", "(..)", "(...)"];
94
+ var DEFAULT_PAGE_EXTENSIONS = ["tsx", "ts", "jsx", "js"];
95
+
96
+ // ../timber-app/src/routing/conventions.ts
97
+ var PAGE_EXT_CONVENTIONS = /* @__PURE__ */ new Set([
98
+ "page",
99
+ "layout",
100
+ "default",
101
+ "denied"
102
+ ]);
103
+ var FIXED_CONVENTIONS = /* @__PURE__ */ new Set(["middleware", "access", "route"]);
104
+ var STATUS_CODE_PATTERN = /^(\d{3}|[45]xx)$/;
105
+ function isRouteConventionFile(base, ext, pageExtensions = DEFAULT_PAGE_EXTENSIONS) {
106
+ const isPageExt = pageExtensions.includes(ext);
107
+ const isScriptExt = /^[jt]sx?$/.test(ext);
108
+ if (PAGE_EXT_CONVENTIONS.has(base) && isPageExt) return true;
109
+ if ((base === "error" || base === "global-error") && isScriptExt) return true;
110
+ if ((FIXED_CONVENTIONS.has(base) || base === "proxy") && isScriptExt) return true;
111
+ if (STATUS_CODE_PATTERN.test(base) && (isScriptExt || ext === "json")) return true;
112
+ return false;
113
+ }
114
+
115
+ // ../timber-app/src/routing/segment-classify.ts
116
+ function classifyUrlSegment(token) {
117
+ const len = token.length;
118
+ if (len === 0) return { kind: "static", value: token };
119
+ const bracketStart = token.indexOf("[");
120
+ if (bracketStart === -1) return { kind: "static", value: token };
121
+ const prefix = token.slice(0, bracketStart);
122
+ let i = bracketStart + 1;
123
+ const optional = i < len && token[i] === "[";
124
+ if (optional) i++;
125
+ const catchAll = i + 2 < len && token[i] === "." && token[i + 1] === "." && token[i + 2] === ".";
126
+ if (catchAll) i += 3;
127
+ const nameStart = i;
128
+ while (i < len && token[i] !== "]") i++;
129
+ if (i >= len || i === nameStart) {
130
+ return { kind: "static", value: token };
131
+ }
132
+ const name = token.slice(nameStart, i);
133
+ i++;
134
+ if (optional) {
135
+ if (i >= len || token[i] !== "]") {
136
+ return { kind: "static", value: token };
137
+ }
138
+ i++;
139
+ }
140
+ const suffix = token.slice(i);
141
+ if (suffix.includes("[") || suffix.includes("]")) {
142
+ return { kind: "static", value: token };
143
+ }
144
+ if (prefix.includes("]")) {
145
+ return { kind: "static", value: token };
146
+ }
147
+ const hasAffixes = prefix.length > 0 || suffix.length > 0;
148
+ if (optional && catchAll) {
149
+ if (hasAffixes) return { kind: "static", value: token };
150
+ return { kind: "optional-catch-all", name };
151
+ }
152
+ if (catchAll) {
153
+ if (hasAffixes) return { kind: "static", value: token };
154
+ return { kind: "catch-all", name };
155
+ }
156
+ if (optional) {
157
+ return { kind: "static", value: token };
158
+ }
159
+ if (hasAffixes) {
160
+ return {
161
+ kind: "dynamic",
162
+ name,
163
+ prefix: prefix || void 0,
164
+ suffix: suffix || void 0
165
+ };
166
+ }
167
+ return { kind: "dynamic", name };
168
+ }
169
+ function classifySegment(dirName) {
170
+ if (dirName.startsWith("_")) {
171
+ return { type: "private" };
172
+ }
173
+ if (dirName.startsWith("@")) {
174
+ return { type: "slot" };
175
+ }
176
+ const interception = parseInterceptionMarker(dirName);
177
+ if (interception) {
178
+ return {
179
+ type: "intercepting",
180
+ interceptionMarker: interception.marker,
181
+ interceptedSegmentName: interception.segmentName
182
+ };
183
+ }
184
+ if (dirName.startsWith("(") && dirName.endsWith(")")) {
185
+ return { type: "group" };
186
+ }
187
+ const urlSeg = classifyUrlSegment(dirName);
188
+ if (urlSeg.kind !== "static") {
189
+ const result = { type: urlSeg.kind, paramName: urlSeg.name };
190
+ if (urlSeg.kind === "dynamic") {
191
+ if (urlSeg.prefix) result.paramPrefix = urlSeg.prefix;
192
+ if (urlSeg.suffix) result.paramSuffix = urlSeg.suffix;
193
+ }
194
+ return result;
195
+ }
196
+ return { type: "static" };
197
+ }
198
+ function parseInterceptionMarker(dirName) {
199
+ for (const marker of INTERCEPTION_MARKERS) {
200
+ if (dirName.startsWith(marker)) {
201
+ const rest = dirName.slice(marker.length);
202
+ if (rest.length > 0 && !rest.endsWith(")")) {
203
+ return { marker, segmentName: rest };
204
+ }
205
+ }
206
+ }
207
+ return null;
208
+ }
209
+
210
+ // ../timber-app/src/server/metadata-routes.ts
211
+ var METADATA_ROUTE_CONVENTIONS = {
212
+ "sitemap": {
213
+ type: "sitemap",
214
+ contentType: "application/xml",
215
+ nestable: true,
216
+ staticExtensions: ["xml"],
217
+ dynamicExtensions: ["ts"],
218
+ servePath: "sitemap.xml"
219
+ },
220
+ "robots": {
221
+ type: "robots",
222
+ contentType: "text/plain",
223
+ nestable: false,
224
+ staticExtensions: ["txt"],
225
+ dynamicExtensions: ["ts"],
226
+ servePath: "robots.txt"
227
+ },
228
+ "manifest": {
229
+ type: "manifest",
230
+ contentType: "application/manifest+json",
231
+ nestable: false,
232
+ staticExtensions: ["json"],
233
+ dynamicExtensions: ["ts"],
234
+ servePath: "manifest.webmanifest"
235
+ },
236
+ "favicon": {
237
+ type: "favicon",
238
+ contentType: "image/x-icon",
239
+ nestable: false,
240
+ staticExtensions: ["ico"],
241
+ dynamicExtensions: ["ts", "tsx"],
242
+ servePath: "favicon.ico"
243
+ },
244
+ "icon": {
245
+ type: "icon",
246
+ contentType: "image/*",
247
+ nestable: true,
248
+ staticExtensions: ["png", "jpg", "svg"],
249
+ dynamicExtensions: ["ts", "tsx"],
250
+ servePath: "icon",
251
+ serveExtension: "png"
252
+ },
253
+ "opengraph-image": {
254
+ type: "opengraph-image",
255
+ contentType: "image/*",
256
+ nestable: true,
257
+ staticExtensions: ["png", "jpg"],
258
+ dynamicExtensions: ["ts", "tsx"],
259
+ servePath: "opengraph-image",
260
+ serveExtension: "png"
261
+ },
262
+ "apple-icon": {
263
+ type: "apple-icon",
264
+ contentType: "image/*",
265
+ nestable: true,
266
+ staticExtensions: ["png"],
267
+ dynamicExtensions: ["ts", "tsx"],
268
+ servePath: "apple-icon",
269
+ serveExtension: "png"
270
+ }
271
+ };
272
+ function isDynamicMetadataExtension(baseName, extension) {
273
+ const convention = METADATA_ROUTE_CONVENTIONS[baseName];
274
+ if (!convention) return false;
275
+ return convention.dynamicExtensions.includes(extension);
276
+ }
277
+ var METADATA_SERVE_PATHS = /* @__PURE__ */ new Set();
278
+ for (const convention of Object.values(METADATA_ROUTE_CONVENTIONS)) {
279
+ if (convention.serveExtension) {
280
+ for (const ext of [...convention.staticExtensions, convention.serveExtension]) {
281
+ METADATA_SERVE_PATHS.add(`${convention.servePath}.${ext}`);
282
+ }
283
+ } else {
284
+ METADATA_SERVE_PATHS.add(convention.servePath);
285
+ }
286
+ }
287
+
288
+ // src/settings.ts
289
+ import { existsSync } from "node:fs";
290
+ import { dirname, isAbsolute, join, resolve } from "node:path";
291
+ var ROOT_MARKERS = [
292
+ "vite.config.ts",
293
+ "vite.config.mts",
294
+ "vite.config.js",
295
+ "vite.config.mjs",
296
+ "timber.config.ts",
297
+ "timber.config.js",
298
+ "timber.config.mjs"
299
+ ];
300
+ var rootByDir = /* @__PURE__ */ new Map();
301
+ function findRoot(startDir) {
302
+ const visited = [];
303
+ let dir = startDir;
304
+ let found = null;
305
+ for (; ; ) {
306
+ const cached = rootByDir.get(dir);
307
+ if (cached !== void 0) {
308
+ found = cached;
309
+ break;
310
+ }
311
+ visited.push(dir);
312
+ if (ROOT_MARKERS.some((m) => existsSync(join(dir, m)))) {
313
+ found = dir;
314
+ break;
315
+ }
316
+ const parent = dirname(dir);
317
+ if (parent === dir) break;
318
+ dir = parent;
319
+ }
320
+ for (const d of visited) rootByDir.set(d, found);
321
+ return found;
322
+ }
323
+ function defaultAppDir(root) {
324
+ for (const candidate of ["app", join("src", "app")]) {
325
+ const dir = join(root, candidate);
326
+ if (existsSync(dir)) return dir;
327
+ }
328
+ return null;
329
+ }
330
+ function readTimberSettings(context) {
331
+ const raw = context.settings.timber;
332
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return {};
333
+ const out = {};
334
+ const { root, appDir, pageExtensions } = raw;
335
+ if (typeof root === "string") out.root = root;
336
+ if (typeof appDir === "string") out.appDir = appDir;
337
+ if (Array.isArray(pageExtensions) && pageExtensions.every((e) => typeof e === "string")) {
338
+ out.pageExtensions = pageExtensions;
339
+ }
340
+ return out;
341
+ }
342
+ function resolveSettings(context) {
343
+ const s = readTimberSettings(context);
344
+ const pageExtensions = s.pageExtensions ?? DEFAULT_PAGE_EXTENSIONS;
345
+ const root = s.root ? resolve(context.cwd, s.root) : findRoot(dirname(resolve(context.cwd, context.filename)));
346
+ if (!root) return { root: null, appDir: null, pageExtensions };
347
+ const appDir = s.appDir ? isAbsolute(s.appDir) ? s.appDir : join(root, s.appDir) : defaultAppDir(root);
348
+ return { root, appDir, pageExtensions };
349
+ }
350
+
351
+ // src/file-kind.ts
352
+ var OUTSIDE = { kind: "outside", segments: [], dynamicParams: [], inSlot: false };
353
+ function conventionKind(base) {
354
+ switch (base) {
355
+ case "page":
356
+ case "layout":
357
+ case "default":
358
+ case "denied":
359
+ case "route":
360
+ case "proxy":
361
+ case "middleware":
362
+ case "access":
363
+ return base;
364
+ case "error":
365
+ case "global-error":
366
+ return "error";
367
+ default:
368
+ return "status";
369
+ }
370
+ }
371
+ function fileInfo(context) {
372
+ const { appDir, pageExtensions } = resolveSettings(context);
373
+ if (!appDir) return OUTSIDE;
374
+ return classify(context.physicalFilename || context.filename, appDir, pageExtensions);
375
+ }
376
+ function classify(file, appDir, pageExtensions) {
377
+ const rel = relative(appDir, file);
378
+ if (rel === "" || rel.startsWith("..") || rel.startsWith(sep) || /^[a-zA-Z]:/.test(rel)) {
379
+ return OUTSIDE;
380
+ }
381
+ const dir = dirname2(rel);
382
+ const segments = dir === "." ? [] : dir.split(sep).map(classifySegment);
383
+ const dynamicParams = [];
384
+ let inSlot = false;
385
+ let inPrivate = false;
386
+ for (const seg of segments) {
387
+ if (seg.type === "slot") inSlot = true;
388
+ if (seg.type === "private") inPrivate = true;
389
+ if (seg.paramName) dynamicParams.push(seg.paramName);
390
+ }
391
+ const ext = extname(rel).slice(1);
392
+ const base = basename(rel, `.${ext}`);
393
+ let kind = "app-other";
394
+ if (!inPrivate && isRouteConventionFile(base, ext, pageExtensions)) kind = conventionKind(base);
395
+ else if (!inPrivate && isDynamicMetadataExtension(base, ext)) kind = "metadata-route";
396
+ return { kind, segments, dynamicParams, inSlot };
397
+ }
398
+ function isRouteModule(kind) {
399
+ return kind === "page" || kind === "layout" || kind === "default" || kind === "denied" || kind === "route" || kind === "metadata-route";
400
+ }
401
+
402
+ // src/rules/no-ignored-nextjs-config.ts
403
+ var SEGMENT_CONFIG = /* @__PURE__ */ new Set([
404
+ "dynamic",
405
+ "dynamicParams",
406
+ "revalidate",
407
+ "fetchCache",
408
+ "runtime",
409
+ "preferredRegion",
410
+ "maxDuration",
411
+ "experimental_ppr"
412
+ ]);
413
+ var CACHE_DIRECTIVE = /^use cache(:\s*\w+)?$/;
414
+ function exportedNames(node) {
415
+ const decl = node.declaration;
416
+ if (decl?.type === "VariableDeclaration") {
417
+ return decl.declarations.flatMap((d) => d.id.type === "Identifier" ? [d.id] : []);
418
+ }
419
+ if (decl?.type === "FunctionDeclaration" && decl.id) return [decl.id];
420
+ if (node.exportKind === "type") return [];
421
+ return node.specifiers.flatMap((s) => s.exportKind === "type" ? [] : [s.exported]);
422
+ }
423
+ function nameOf(node) {
424
+ if (node.type === "Identifier") return node.name;
425
+ if (node.type === "Literal" && typeof node.value === "string") return node.value;
426
+ return null;
427
+ }
428
+ function directiveStatements(body) {
429
+ const out = [];
430
+ for (const stmt of body) {
431
+ if (stmt.type !== "ExpressionStatement" || typeof stmt.directive !== "string") break;
432
+ out.push(stmt);
433
+ }
434
+ return out;
435
+ }
436
+ var noIgnoredNextjsConfig = {
437
+ meta: {
438
+ type: "problem",
439
+ docs: {
440
+ description: "Disallow Next.js route config, `use cache`, and `fetch` cache options that timber ignores"
441
+ },
442
+ messages: {
443
+ segmentConfig: "timber ignores Next's `{{name}}` route segment config. Declare route behavior in `pageOptions` / `layoutOptions` (design/53-segment-lifetime.md) and cache with `cache.component` / `cache.data` (design/45-cache-lifetimes.md).",
444
+ staticParams: "timber reads `generateStaticSegmentParams`, not `generateStaticParams` \u2014 this export is never called, so no params are enumerated at build time.",
445
+ cacheDirective: "timber has no `{{directive}}` transform; the directive does nothing. Cache with `cache.data` / `cache.component` from '@timber-js/app/cache'.",
446
+ fetchNext: "timber does not patch `fetch`, so `{ next: \u2026 }` is ignored and nothing is cached or revalidated. Wrap the call in `cache.data` from '@timber-js/app/cache'."
447
+ },
448
+ schema: []
449
+ },
450
+ create(context) {
451
+ const checkDirectives = (body) => {
452
+ for (const stmt of directiveStatements(body)) {
453
+ if (stmt.directive && CACHE_DIRECTIVE.test(stmt.directive)) {
454
+ context.report({
455
+ node: stmt,
456
+ messageId: "cacheDirective",
457
+ data: { directive: `'${stmt.directive}'` }
458
+ });
459
+ }
460
+ }
461
+ };
462
+ const checkFunctionBody = (fn) => {
463
+ if (fn.body?.type === "BlockStatement") checkDirectives(fn.body.body);
464
+ };
465
+ const text = context.sourceCode.text;
466
+ const visitor = {};
467
+ if (text.includes("use cache")) {
468
+ visitor.Program = (node) => checkDirectives(node.body);
469
+ visitor.FunctionDeclaration = checkFunctionBody;
470
+ visitor.FunctionExpression = checkFunctionBody;
471
+ visitor.ArrowFunctionExpression = checkFunctionBody;
472
+ }
473
+ if (isRouteModule(fileInfo(context).kind)) {
474
+ visitor.ExportNamedDeclaration = (node) => {
475
+ for (const id of exportedNames(node)) {
476
+ const name = nameOf(id);
477
+ if (name === "generateStaticParams") {
478
+ context.report({ node: id, messageId: "staticParams" });
479
+ } else if (name && SEGMENT_CONFIG.has(name)) {
480
+ context.report({ node: id, messageId: "segmentConfig", data: { name } });
481
+ }
482
+ }
483
+ };
484
+ }
485
+ if (text.includes("fetch")) {
486
+ visitor.CallExpression = (node) => {
487
+ if (!isGlobal(context, node.callee, "fetch")) return;
488
+ const init = node.arguments[1];
489
+ if (init?.type !== "ObjectExpression") return;
490
+ for (const prop of init.properties) {
491
+ if (prop.type === "Property" && propertyKeyName(prop) === "next") {
492
+ context.report({ node: prop, messageId: "fetchNext" });
493
+ }
494
+ }
495
+ };
496
+ }
497
+ return visitor;
498
+ }
499
+ };
500
+
501
+ // src/rules/no-manual-param-parsing.ts
502
+ import { basename as basename2 } from "node:path";
503
+
504
+ // src/schema.ts
505
+ import { readFileSync } from "node:fs";
506
+
507
+ // ../timber-app/src/routing/schema-keys.ts
508
+ import { existsSync as existsSync2 } from "node:fs";
509
+ import { join as join2 } from "node:path";
510
+ function maskSource(content, maskStrings) {
511
+ const out = content.split("");
512
+ const n = content.length;
513
+ let i = 0;
514
+ const blank = (from, to) => {
515
+ for (let j = from; j < to; j++) {
516
+ if (content[j] !== "\n") out[j] = " ";
517
+ }
518
+ };
519
+ while (i < n) {
520
+ const ch = content[i];
521
+ const next = content[i + 1];
522
+ if (ch === "/" && next === "/") {
523
+ const start = i;
524
+ while (i < n && content[i] !== "\n") i++;
525
+ blank(start, i);
526
+ } else if (ch === "/" && next === "*") {
527
+ const start = i;
528
+ i += 2;
529
+ while (i < n && !(content[i] === "*" && content[i + 1] === "/")) i++;
530
+ i = Math.min(i + 2, n);
531
+ blank(start, i);
532
+ } else if (ch === '"' || ch === "'" || ch === "`") {
533
+ const start = i;
534
+ i++;
535
+ while (i < n && content[i] !== ch) {
536
+ if (content[i] === "\\") i++;
537
+ i++;
538
+ }
539
+ const end = i;
540
+ if (maskStrings && content.slice(start + 1, end) !== "segmentParams") {
541
+ blank(start + 1, end);
542
+ }
543
+ i++;
544
+ } else {
545
+ i++;
546
+ }
547
+ }
548
+ return out.join("");
549
+ }
550
+ function findSegmentParamsBlock(content) {
551
+ const masked = maskSource(content, true);
552
+ const defineCall = /\bdefineSchema\s*\(/.exec(masked);
553
+ const keyRe = /(['"]?)segmentParams\1\s*:\s*\{/g;
554
+ keyRe.lastIndex = defineCall ? defineCall.index + defineCall[0].length : 0;
555
+ const keyMatch = keyRe.exec(masked);
556
+ if (!keyMatch) return null;
557
+ const openBrace = keyMatch.index + keyMatch[0].length - 1;
558
+ let depth = 1;
559
+ let i = openBrace + 1;
560
+ while (i < masked.length && depth > 0) {
561
+ if (masked[i] === "{") depth++;
562
+ else if (masked[i] === "}") depth--;
563
+ i++;
564
+ }
565
+ if (depth > 0) return null;
566
+ return { openBrace, closeBrace: i - 1 };
567
+ }
568
+ var SCHEMA_EXTENSIONS = [".ts", ".tsx", ".js", ".jsx"];
569
+ function findSchemaFile(appDir) {
570
+ for (const ext of SCHEMA_EXTENSIONS) {
571
+ const p = join2(appDir, `schema${ext}`);
572
+ if (existsSync2(p)) return p;
573
+ }
574
+ return void 0;
575
+ }
576
+
577
+ // src/schema.ts
578
+ var STRING_CODEC = /^(codec\.(string|slug|stringArray)\b|z\.string\(\)\s*[,})\n])/;
579
+ var CATCH_ALL_WRAPPER = /^codec\.(catchAll|optionalCatchAll)\(\s*/;
580
+ function isStringCodec(valueText) {
581
+ let text = valueText;
582
+ for (let m = CATCH_ALL_WRAPPER.exec(text); m; m = CATCH_ALL_WRAPPER.exec(text)) {
583
+ text = text.slice(m[0].length);
584
+ }
585
+ return STRING_CODEC.test(text);
586
+ }
587
+ function escapeRegExp(s) {
588
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
589
+ }
590
+ function segmentCodec(appDir, param) {
591
+ const file = findSchemaFile(appDir);
592
+ if (!file) return "none";
593
+ let content;
594
+ try {
595
+ content = readFileSync(file, "utf8");
596
+ } catch {
597
+ return "none";
598
+ }
599
+ const block = findSegmentParamsBlock(content);
600
+ if (!block) return "none";
601
+ const text = maskSource(content, false).slice(block.openBrace + 1, block.closeBrace);
602
+ const name = escapeRegExp(param);
603
+ const key = new RegExp(`['"]\\[{1,2}(?:\\.{3})?${name}\\]{1,2}['"]\\s*:\\s*`, "g");
604
+ const match = key.exec(text);
605
+ if (!match) return "none";
606
+ return isStringCodec(text.slice(match.index + match[0].length)) ? "string" : "typed";
607
+ }
608
+
609
+ // src/rules/no-manual-param-parsing.ts
610
+ var SEGMENT_SOURCES = [
611
+ { name: "getSegmentParams", sources: ["@timber-js/app/server"] },
612
+ { name: "useSegmentParams", sources: ["@timber-js/app/client"] }
613
+ ];
614
+ var SEARCH_OBJECT_SOURCES = [
615
+ { name: "useSearchParams", sources: ["next/navigation"] }
616
+ ];
617
+ var MAX_HOPS = 4;
618
+ var PARAM_SOURCE_TEXT = /[sS]egmentParams|[sS]earchParams/;
619
+ function destructuredKey(pattern, name) {
620
+ if (pattern.type !== "ObjectPattern") return null;
621
+ for (const p of pattern.properties) {
622
+ if (p.type !== "Property") continue;
623
+ const target = p.value.type === "AssignmentPattern" ? p.value.left : p.value;
624
+ if (target.type === "Identifier" && target.name === name) return propertyKeyName(p);
625
+ }
626
+ return null;
627
+ }
628
+ function memberName(e) {
629
+ if (!e.computed && e.property.type === "Identifier") return e.property.name;
630
+ if (e.computed && e.property.type === "Literal" && typeof e.property.value === "string") {
631
+ return e.property.value;
632
+ }
633
+ return null;
634
+ }
635
+ function origin(context, imports, expr, hops = 0) {
636
+ if (hops > MAX_HOPS) return null;
637
+ const e = unwrap(expr);
638
+ const next = (x) => origin(context, imports, x, hops + 1);
639
+ const isCallTo = (call, table) => table.some((t) => isImportedCall(context, call.callee, imports, t.sources, t.name));
640
+ switch (e.type) {
641
+ case "CallExpression": {
642
+ if (isCallTo(e, SEGMENT_SOURCES)) return { kind: "segment-object" };
643
+ if (isCallTo(e, SEARCH_OBJECT_SOURCES)) return { kind: "search-object" };
644
+ const callee = unwrap(e.callee);
645
+ if (callee.type === "MemberExpression" && memberName(callee) === "get" && next(callee.object)?.kind === "search-object") {
646
+ return { kind: "search-value" };
647
+ }
648
+ return null;
649
+ }
650
+ case "NewExpression":
651
+ return isGlobal(context, e.callee, "URLSearchParams") ? { kind: "search-object" } : null;
652
+ case "MemberExpression": {
653
+ if (!e.computed && memberName(e) === "searchParams") return { kind: "search-object" };
654
+ const from = next(e.object);
655
+ if (from?.kind === "segment-object") return { kind: "segment-value", param: memberName(e) };
656
+ if (from?.kind === "segment-value" && e.computed && memberName(e) === null) return from;
657
+ return null;
658
+ }
659
+ case "LogicalExpression":
660
+ return next(e.left);
661
+ case "Identifier": {
662
+ const def = findVariable(context, e)?.defs;
663
+ const only = def?.length === 1 ? def[0] : void 0;
664
+ if (only?.type !== "Variable" || only.node.type !== "VariableDeclarator") return null;
665
+ const declarator = only.node;
666
+ if (declarator.parent.type === "VariableDeclaration" && declarator.parent.kind !== "const") {
667
+ return null;
668
+ }
669
+ if (!declarator.init) return null;
670
+ if (declarator.id.type === "Identifier") return next(declarator.init);
671
+ const key = destructuredKey(declarator.id, e.name);
672
+ if (key === "searchParams") return { kind: "search-object" };
673
+ const from = next(declarator.init);
674
+ if (from?.kind === "segment-object") return { kind: "segment-value", param: key };
675
+ return null;
676
+ }
677
+ default:
678
+ return null;
679
+ }
680
+ }
681
+ function coercion(context, node) {
682
+ const callee = unwrap(node.callee);
683
+ for (const name of ["Number", "parseInt", "parseFloat", "BigInt"]) {
684
+ if (isGlobal(context, callee, name)) return name;
685
+ }
686
+ if (callee.type === "MemberExpression" && (memberName(callee) === "parseInt" || memberName(callee) === "parseFloat") && isGlobal(context, callee.object, "Number")) {
687
+ return `Number.${memberName(callee)}`;
688
+ }
689
+ return null;
690
+ }
691
+ var noManualParamParsing = {
692
+ meta: {
693
+ type: "problem",
694
+ docs: {
695
+ description: "Require codecs for numeric URL params instead of Number()/parseInt()"
696
+ },
697
+ messages: {
698
+ segment: "`{{fn}}()` on the raw `{{param}}` segment param accepts `1e2`, `\"\"` (\u2192 0), `Infinity` and out-of-range ids, so a bad URL loads the wrong record or 500s. Give it a codec in app/schema.ts (e.g. `'[{{param}}]': codec.integer`) and use the decoded value \u2014 bad input then 404s before the page runs (design/41-global-params.md).",
699
+ search: '`{{fn}}()` on a raw search param accepts `1e2`, `""` (\u2192 0) and NaN. Declare the param with a codec in `defineSearchParams` and read the parsed value (design/23-search-params.md).',
700
+ cast: "`getSegmentParams()` is untyped and this cast asserts a shape nothing checks. Pass the segment path (`getSegmentParams(SEGMENT_PATH)` from `./$segment`) for typed params, with codecs in app/schema.ts (design/41-global-params.md)."
701
+ },
702
+ schema: []
703
+ },
704
+ create(context) {
705
+ if (ROOT_MARKERS.includes(basename2(context.physicalFilename || context.filename))) return {};
706
+ if (!PARAM_SOURCE_TEXT.test(context.sourceCode.text)) return {};
707
+ let imports = /* @__PURE__ */ new Map();
708
+ const decodedBySchema = (param) => {
709
+ if (param === null) return false;
710
+ const { appDir } = resolveSettings(context);
711
+ return appDir !== null && segmentCodec(appDir, param) === "typed";
712
+ };
713
+ const check = (node, fn, arg) => {
714
+ const from = origin(context, imports, arg);
715
+ if (from?.kind === "segment-value" && !decodedBySchema(from.param)) {
716
+ context.report({
717
+ node,
718
+ messageId: "segment",
719
+ data: { fn, param: from.param ?? "id" }
720
+ });
721
+ } else if (from?.kind === "search-value") {
722
+ context.report({ node, messageId: "search", data: { fn } });
723
+ }
724
+ };
725
+ return {
726
+ Program(node) {
727
+ imports = importBindings(node);
728
+ },
729
+ CallExpression(node) {
730
+ const fn = coercion(context, node);
731
+ const arg = node.arguments[0];
732
+ if (fn && arg && arg.type !== "SpreadElement") check(node, fn, arg);
733
+ },
734
+ UnaryExpression(node) {
735
+ if (node.operator === "+") check(node, "unary +", node.argument);
736
+ },
737
+ TSAsExpression(node) {
738
+ const inner = unwrap(node.expression);
739
+ if (inner.type === "CallExpression" && isImportedCall(
740
+ context,
741
+ inner.callee,
742
+ imports,
743
+ ["@timber-js/app/server"],
744
+ "getSegmentParams"
745
+ )) {
746
+ context.report({ node, messageId: "cast" });
747
+ }
748
+ }
749
+ };
750
+ }
751
+ };
752
+
753
+ // src/module-env.ts
754
+ import { readFileSync as readFileSync2, realpathSync, statSync } from "node:fs";
755
+ import { isAbsolute as isAbsolute2, join as join3, resolve as resolve2 } from "node:path";
756
+ var graphByRoot = /* @__PURE__ */ new Map();
757
+ function envOfGraphKind(kind) {
758
+ switch (kind) {
759
+ case "server":
760
+ case "server-action":
761
+ return "server";
762
+ case "client-boundary":
763
+ case "client-internal":
764
+ return "client";
765
+ case "shared":
766
+ return "shared";
767
+ default:
768
+ return "unknown";
769
+ }
770
+ }
771
+ function realPath(path) {
772
+ try {
773
+ return realpathSync.native(path);
774
+ } catch {
775
+ return path;
776
+ }
777
+ }
778
+ function field(value, key) {
779
+ if (typeof value !== "object" || value === null) return void 0;
780
+ return Object.getOwnPropertyDescriptor(value, key)?.value;
781
+ }
782
+ function loadGraph(root) {
783
+ const path = join3(root, ".timber", "graph-cache.json");
784
+ const mtimeMs = statSync(path, { throwIfNoEntry: false })?.mtimeMs ?? -1;
785
+ const loaded = graphByRoot.get(root);
786
+ if (loaded && loaded.mtimeMs === mtimeMs) return loaded.kinds;
787
+ let kinds = null;
788
+ try {
789
+ const parsed = mtimeMs === -1 ? void 0 : JSON.parse(readFileSync2(path, "utf8"));
790
+ const modules = field(field(parsed, "report"), "modules");
791
+ if (Array.isArray(modules)) {
792
+ kinds = /* @__PURE__ */ new Map();
793
+ for (const m of modules) {
794
+ const file = field(m, "file");
795
+ if (typeof file !== "string") continue;
796
+ kinds.set(
797
+ realPath(isAbsolute2(file) ? file : join3(root, file)),
798
+ envOfGraphKind(field(m, "kind"))
799
+ );
800
+ }
801
+ }
802
+ } catch {
803
+ }
804
+ graphByRoot.set(root, { mtimeMs, kinds });
805
+ return kinds;
806
+ }
807
+ function importsMarker(program, marker) {
808
+ return program.body.some((s) => s.type === "ImportDeclaration" && s.source.value === marker);
809
+ }
810
+ function provisional(context, program) {
811
+ const directive = fileDirective(program);
812
+ if (directive === "use client") return "client";
813
+ if (directive === "use server") return "server";
814
+ if (importsMarker(program, "server-only")) return "server";
815
+ if (importsMarker(program, "client-only")) return "client";
816
+ const { kind } = fileInfo(context);
817
+ if (kind === "outside" || kind === "app-other" || kind === "error") return "unknown";
818
+ return "server";
819
+ }
820
+ function moduleEnv(context, program) {
821
+ const directive = fileDirective(program);
822
+ if (directive) return { env: directive === "use client" ? "client" : "server", fromGraph: false };
823
+ const { root } = resolveSettings(context);
824
+ if (root) {
825
+ const graph = loadGraph(root);
826
+ const env = graph?.get(
827
+ realPath(resolve2(context.cwd, context.physicalFilename || context.filename))
828
+ );
829
+ if (env && env !== "unknown") return { env, fromGraph: true };
830
+ }
831
+ return { env: provisional(context, program), fromGraph: false };
832
+ }
833
+ function runsOnServer(answer) {
834
+ return answer.env === "server" || answer.env === "shared";
835
+ }
836
+
837
+ // src/rules/server-fetch-needs-signal.ts
838
+ function initLacksSignal(init) {
839
+ if (init === void 0) return true;
840
+ if (init.type === "SpreadElement") return false;
841
+ const value = unwrap(init);
842
+ if (value.type !== "ObjectExpression") return false;
843
+ return value.properties.every(
844
+ (p) => p.type === "Property" && propertyKeyName(p) !== "signal" && propertyKeyName(p) !== null
845
+ );
846
+ }
847
+ var MAX_HOPS2 = 4;
848
+ function annotatedAsUrl(id) {
849
+ const t = id.typeAnnotation?.typeAnnotation;
850
+ if (!t) return false;
851
+ if (t.type === "TSStringKeyword") return true;
852
+ return t.type === "TSTypeReference" && t.typeName.type === "Identifier" && t.typeName.name === "URL";
853
+ }
854
+ function isUrlInput(context, input, hops = 0) {
855
+ if (hops > MAX_HOPS2) return false;
856
+ const e = unwrap(input);
857
+ switch (e.type) {
858
+ case "Literal":
859
+ return typeof e.value === "string";
860
+ case "TemplateLiteral":
861
+ return true;
862
+ case "BinaryExpression":
863
+ return e.operator === "+";
864
+ case "NewExpression":
865
+ return isGlobal(context, e.callee, "URL");
866
+ case "MemberExpression": {
867
+ if (!e.computed && e.property.type === "Identifier" && e.property.name === "href")
868
+ return true;
869
+ const obj = unwrap(e.object);
870
+ return obj.type === "MemberExpression" && !obj.computed && obj.property.type === "Identifier" && obj.property.name === "env" && isGlobal(context, obj.object, "process");
871
+ }
872
+ case "LogicalExpression":
873
+ return isUrlInput(context, e.left, hops + 1) && isUrlInput(context, e.right, hops + 1);
874
+ case "CallExpression": {
875
+ const callee = unwrap(e.callee);
876
+ if (isGlobal(context, callee, "String")) return true;
877
+ return callee.type === "MemberExpression" && !callee.computed && callee.property.type === "Identifier" && callee.property.name === "toString";
878
+ }
879
+ case "Identifier": {
880
+ const defs = findVariable(context, e)?.defs;
881
+ const def = defs?.length === 1 ? defs[0] : void 0;
882
+ if (!def) return false;
883
+ if (def.name.type === "Identifier" && annotatedAsUrl(def.name)) return true;
884
+ if (def.type !== "Variable" || def.node.type !== "VariableDeclarator") return false;
885
+ const decl = def.node;
886
+ if (decl.parent.type === "VariableDeclaration" && decl.parent.kind !== "const") return false;
887
+ return decl.id.type === "Identifier" && decl.init != null && isUrlInput(context, decl.init, hops + 1);
888
+ }
889
+ default:
890
+ return false;
891
+ }
892
+ }
893
+ var serverFetchNeedsSignal = {
894
+ meta: {
895
+ type: "problem",
896
+ docs: {
897
+ description: "Require an abort signal (e.g. `AbortSignal.timeout(ms)`) on server-side fetch"
898
+ },
899
+ messages: {
900
+ missing: "Server-side `fetch` without a `signal` can hang until the render timeout, holding the response. Pass `signal: AbortSignal.timeout(ms)` (or combine it with the request signal via `AbortSignal.any`)."
901
+ },
902
+ schema: []
903
+ },
904
+ create(context) {
905
+ if (!context.sourceCode.text.includes("fetch")) return {};
906
+ let onServer = false;
907
+ return {
908
+ Program(node) {
909
+ onServer = runsOnServer(moduleEnv(context, node));
910
+ },
911
+ CallExpression(node) {
912
+ if (!onServer || !isGlobal(context, node.callee, "fetch")) return;
913
+ const [input, init] = node.arguments;
914
+ if (!input || input.type === "SpreadElement" || !isUrlInput(context, input)) return;
915
+ if (!initLacksSignal(init)) return;
916
+ context.report({ node, messageId: "missing" });
917
+ }
918
+ };
919
+ }
920
+ };
921
+
922
+ // src/index.ts
923
+ var rules = {
924
+ "no-ignored-nextjs-config": noIgnoredNextjsConfig,
925
+ "server-fetch-needs-signal": serverFetchNeedsSignal,
926
+ "no-manual-param-parsing": noManualParamParsing
927
+ };
928
+ var plugin = {
929
+ meta: { name: "timber" },
930
+ rules
931
+ };
932
+ var index_default = plugin;
933
+ export {
934
+ index_default as default,
935
+ rules
936
+ };
package/package.json CHANGED
@@ -1,6 +1,39 @@
1
1
  {
2
2
  "name": "@timber-js/oxlint-plugin",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "oxlint rules for timber.js apps: file conventions, module environments, and the bugs real apps shipped",
5
+ "keywords": [
6
+ "oxlint",
7
+ "oxlint-plugin",
8
+ "timber"
9
+ ],
10
+ "homepage": "https://github.com/switz/timber.js",
11
+ "license": "SEE LICENSE IN LICENSE",
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "git+https://github.com/switz/timber.js.git",
15
+ "directory": "packages/oxlint-plugin"
16
+ },
17
+ "files": [
18
+ "dist",
19
+ "README.md"
20
+ ],
21
+ "type": "module",
22
+ "exports": {
23
+ ".": "./dist/index.js"
24
+ },
25
+ "scripts": {
26
+ "build": "esbuild src/index.ts --bundle --platform=node --format=esm --target=node22 --outfile=dist/index.js",
27
+ "prepublishOnly": "pnpm run build"
28
+ },
29
+ "devDependencies": {
30
+ "@oxlint/plugins": "1.93.0",
31
+ "esbuild": "0.27.4"
32
+ },
33
+ "peerDependencies": {
34
+ "oxlint": ">=1.93.0"
35
+ },
36
+ "engines": {
37
+ "node": ">=22"
38
+ }
39
+ }