@ingram-tech/nk-dev 0.15.0 → 0.16.1

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
@@ -113,7 +113,13 @@ tsc), so versions stay under your control. nk only orchestrates.
113
113
  - **`nk check`** — `oxlint` + `oxfmt --check` + `knip` (only when the repo has a
114
114
  knip config) + the agent-guide import gate + the migration seal. The CI gate;
115
115
  runs every checker and reports them all before failing.
116
- - **`nk type-check`** — `next typegen && tsc --noEmit`.
116
+ - **`nk type-check`** — `next typegen && tsc --noEmit`, with recovery: when
117
+ every error sits inside generated types (`.next/types`, `.next/dev/types` —
118
+ a deleted route or a killed dev server leaves them stale, and `next typegen`
119
+ does not rewrite the dev copy), it removes them, regenerates and retries once.
120
+ Starts cold when the lockfile is newer than `tsconfig.tsbuildinfo`; `--cold`
121
+ forces it.
122
+ - **`nk clean`** — remove the regenerable artifacts above by hand.
117
123
  - **`nk test [...]`** — `vitest run`, extra args passed through.
118
124
  - **`nk build [...]`** — `next build`, extra args passed through.
119
125
 
package/guide.md CHANGED
@@ -18,12 +18,21 @@ package. Stay a thin, standard Next.js app (bun · oxlint + oxfmt · strict TS).
18
18
  - **Never trust an external request body's shape — validate it with Zod, never
19
19
  `as`-cast it.** Every `/api` route and webhook handler takes untrusted input;
20
20
  an `as` cast is a lie the type-checker can't catch at runtime.
21
+ `nextkit/no-unvalidated-request-body` enforces this in `app/**/route.ts`:
22
+ cast the parsed body to `unknown` on the way into a schema, never to a shape.
21
23
  - Format/lint with **oxlint + oxfmt** via `nk` (`@ingram-tech/nk-dev`); don't
22
24
  reintroduce ESLint or Prettier (SQL isn't formatted — it's generated). nk-dev
23
25
  owns the toolchain: don't re-declare `oxfmt`/`oxlint`/`typescript` or the
24
26
  retired `@ingram-tech/{oxlint,typescript}-config` — `nk doctor` flags the drift.
25
27
  `nk` is optional convenience that only orchestrates the standard tools — the
26
28
  site must stay buildable with plain `next build` / `next dev`.
29
+ - **Type-check with `nk type-check`, not bare `tsc`.** A `tsc` error that
30
+ points inside `.next/` (typically `.next/dev/types/validator.ts` after a
31
+ route was deleted or `next dev` was killed mid-write) is stale generated
32
+ output, not a source defect: `next typegen` does not rewrite the dev
33
+ server's copy. `nk type-check` detects that case, removes the artifacts and
34
+ retries; `nk clean` does the removal on its own. Don't hunt for the error in
35
+ `src/`, and don't `rm -rf .next/types` by hand.
27
36
 
28
37
  ## Route & URL conventions
29
38
 
package/lib/doctor.js CHANGED
@@ -24,9 +24,26 @@ const CANONICAL_SCRIPTS = {
24
24
  };
25
25
 
26
26
  const GUIDE_IMPORT = "@./node_modules/@ingram-tech/nk-dev/guide.md";
27
- const OXLINTRC_EXTENDS = "./node_modules/@ingram-tech/nk-dev/oxlintrc.json";
27
+ const OXLINTRC_FILE = "node_modules/@ingram-tech/nk-dev/oxlintrc.json";
28
+ /** Matches any `extends` entry that reaches nk-dev's oxlintrc, whatever the prefix. */
29
+ const OXLINTRC_EXTENDS_RE = /(^|\/)node_modules\/@ingram-tech\/nk-dev\/oxlintrc\.json$/;
28
30
  const TSCONFIG_EXTENDS = "@ingram-tech/nk-dev/tsconfig/nextjs.json";
29
31
 
32
+ /**
33
+ * The `extends` entry that reaches nk-dev's oxlintrc from `cwd`. oxlint resolves
34
+ * `extends` relative to the config file, not through node resolution, so a
35
+ * hoisted-workspace member (whose node_modules sits at the repo root) needs
36
+ * `../node_modules/…`, not `./node_modules/…`. Walk up until the file exists;
37
+ * fall back to the standalone-site form.
38
+ */
39
+ function oxlintrcExtendsFor(cwd) {
40
+ for (const prefix of ["./", "../", "../../", "../../../"]) {
41
+ const entry = `${prefix}${OXLINTRC_FILE}`;
42
+ if (existsSync(resolve(cwd, entry))) return entry;
43
+ }
44
+ return `./${OXLINTRC_FILE}`;
45
+ }
46
+
30
47
  /** Read + parse a JSON file, or null if absent/unparseable. */
31
48
  function readJson(file) {
32
49
  try {
@@ -117,7 +134,7 @@ export function findings(cwd) {
117
134
  const ox = readJson(oxPath);
118
135
  if (ox) {
119
136
  const ext = [].concat(ox.extends ?? []);
120
- if (!ext.includes(OXLINTRC_EXTENDS)) {
137
+ if (!ext.some((e) => OXLINTRC_EXTENDS_RE.test(String(e)))) {
121
138
  out.push({
122
139
  id: "oxlintrc:extends",
123
140
  level: "error",
@@ -132,9 +149,9 @@ export function findings(cwd) {
132
149
  .filter(
133
150
  (e) =>
134
151
  !String(e).includes("oxlint-config") &&
135
- e !== OXLINTRC_EXTENDS,
152
+ !OXLINTRC_EXTENDS_RE.test(String(e)),
136
153
  );
137
- j.extends = [OXLINTRC_EXTENDS, ...kept];
154
+ j.extends = [oxlintrcExtendsFor(dir), ...kept];
138
155
  j.$schema ??= "./node_modules/oxlint/configuration_schema.json";
139
156
  writeJson(p, j);
140
157
  return "repointed .oxlintrc.json extends → nk-dev";
@@ -0,0 +1,141 @@
1
+ // nextkit oxlint JS plugin rule: a Base UI (@base-ui/react) button-like
2
+ // component that renders something other than a <button> must say so with
3
+ // `nativeButton={false}`.
4
+ //
5
+ // Base UI builds every button-like part on `useButton`, whose `nativeButton`
6
+ // prop defaults to true. Render a non-<button> element through `render` and
7
+ // leave the default in place and Base UI logs at runtime:
8
+ //
9
+ // Base UI: A component that acts as a button expected a native <button>
10
+ // because the `nativeButton` prop is true. Rendering a non-<button> removes
11
+ // native button semantics, which can impact forms and accessibility.
12
+ //
13
+ // It is not only console noise: Base UI skips the keyboard, role and
14
+ // form-participation shims the non-native element needs, so the control is
15
+ // reachable but not operable the way a button is. The type-checker cannot see
16
+ // it (`nativeButton` is optional and the render element is just a ReactElement),
17
+ // so it needs a rule.
18
+ //
19
+ // Scope is structural and deliberately narrow:
20
+ //
21
+ // * Only a JSX element literal in `render` is inspected, which is the
22
+ // convention on these sites (`render={<Link href={...} />}`). A variable,
23
+ // call or conditional is not followed: the unusual cases fall out for free
24
+ // instead of needing an allowlist of innocents.
25
+ // * `render={<button />}` is correct as-is, and so is a component named
26
+ // `*Button`: that is Base UI's own button primitive or a wrapper on it,
27
+ // which renders a native <button>.
28
+ // * `nativeButton={false}` anywhere on the element clears it. Any other
29
+ // value, or a spread that might carry one, still reports: a spread is not
30
+ // an explicit `nativeButton={false}`.
31
+ //
32
+ // Which components count: only the ones that actually accept `nativeButton`.
33
+ // In @base-ui/react 1.8.0 that is Button, PopoverTrigger, Switch and the menu
34
+ // items; every other *Trigger builds on useButton internally but does not
35
+ // expose the prop, so demanding it there produces code that does not compile.
36
+ // An earlier revision keyed on the `Button`/`Trigger` name suffixes and was
37
+ // wrong on both counts: it reported design-system Buttons (which render a
38
+ // native <button>) and Triggers that have no such prop.
39
+ //
40
+ // The host must also be Base UI's own component. A locally defined
41
+ // `SidebarMenuButton` shares the name and takes no such prop, so the name list
42
+ // below is deliberately short and exact rather than suffix-matched.
43
+
44
+ import { fileUsesBaseUi } from "./base-ui-project.js";
45
+
46
+ const NATIVE_BUTTON_PROP_COMPONENTS = new Set([
47
+ "Button",
48
+ "PopoverTrigger",
49
+ "Switch",
50
+ "MenuItem",
51
+ ]);
52
+
53
+ /** `<Foo>` -> "Foo", `<Menu.Trigger>` -> "Trigger", otherwise null. */
54
+ const componentNameOf = (opening) => {
55
+ const name = opening.name;
56
+ if (name.type === "JSXIdentifier") return name.name;
57
+ if (name.type === "JSXMemberExpression" && name.property.type === "JSXIdentifier") {
58
+ return name.property.name;
59
+ }
60
+ return null;
61
+ };
62
+
63
+ /**
64
+ * A render target that is itself a button. The lowercase intrinsic is the
65
+ * obvious one; a component named `*Button` is Base UI's own primitive or a
66
+ * wrapper around it, and renders a native <button> too, so requiring
67
+ * `nativeButton={false}` there would be wrong twice over: the element is
68
+ * native, and Base UI logs the inverse warning when the prop lies about it.
69
+ *
70
+ * The known gap is a `*Button` wrapper that renders an anchor (a LinkButton).
71
+ * Those set `nativeButton={false}` on their own inner button, so the mistake
72
+ * is contained in the wrapper rather than at every call site.
73
+ */
74
+ const rendersNativeButton = (name) =>
75
+ name === "button" || (/^[A-Z]/.test(name) && name.endsWith("Button"));
76
+
77
+ const isButtonLike = (name) => name !== null && NATIVE_BUTTON_PROP_COMPONENTS.has(name);
78
+
79
+ /** The JSX element literal passed to `render`, or null. */
80
+ const renderedElement = (attribute) => {
81
+ const value = attribute.value;
82
+ if (!value || value.type !== "JSXExpressionContainer") return null;
83
+ const expression = value.expression;
84
+ return expression.type === "JSXElement" ? expression : null;
85
+ };
86
+
87
+ const isNativeButtonFalse = (attribute) => {
88
+ const value = attribute.value;
89
+ if (!value || value.type !== "JSXExpressionContainer") return false;
90
+ const expression = value.expression;
91
+ return expression.type === "Literal" && expression.value === false;
92
+ };
93
+
94
+ const baseUiNativeButton = {
95
+ meta: {
96
+ type: "problem",
97
+ docs: {
98
+ description:
99
+ "Require nativeButton={false} on a Base UI button-like component rendered as a non-<button>",
100
+ },
101
+ messages: {
102
+ missingNativeButtonFalse:
103
+ "`{{component}}` renders <{{rendered}}> but leaves `nativeButton` at its default of true, so Base UI drops the native button semantics it would otherwise shim and logs an error at runtime. Add `nativeButton={false}`, or render a real <button>.",
104
+ },
105
+ },
106
+ create(context) {
107
+ if (!fileUsesBaseUi(context)) return {};
108
+ return {
109
+ JSXOpeningElement(node) {
110
+ const component = componentNameOf(node);
111
+ if (!isButtonLike(component)) return;
112
+
113
+ let render = null;
114
+ for (const attribute of node.attributes) {
115
+ if (attribute.type !== "JSXAttribute") continue;
116
+ if (attribute.name.type !== "JSXIdentifier") continue;
117
+ if (attribute.name.name === "nativeButton") {
118
+ if (isNativeButtonFalse(attribute)) return;
119
+ } else if (attribute.name.name === "render") {
120
+ render = renderedElement(attribute);
121
+ }
122
+ }
123
+ if (render === null) return;
124
+
125
+ const rendered = componentNameOf(render.openingElement);
126
+ if (rendered === null || rendersNativeButton(rendered)) return;
127
+
128
+ context.report({
129
+ node: render,
130
+ messageId: "missingNativeButtonFalse",
131
+ data: { component, rendered },
132
+ });
133
+ },
134
+ };
135
+ },
136
+ };
137
+
138
+ export default {
139
+ meta: { name: "nextkit" },
140
+ rules: { "base-ui-native-button": baseUiNativeButton },
141
+ };
@@ -0,0 +1,50 @@
1
+ // Shared gate for the Base UI (@base-ui/react) rules: they only activate for
2
+ // projects that actually depend on the library, so the shared nextkit ruleset
3
+ // can enable them fleet-wide without firing on Radix or UI-less sites.
4
+
5
+ import { existsSync, readFileSync } from "node:fs";
6
+ import { dirname, join } from "node:path";
7
+
8
+ const baseUiCache = new Map();
9
+
10
+ const pkgDeclaresBaseUi = (pkgPath) => {
11
+ try {
12
+ const pkg = JSON.parse(readFileSync(pkgPath, "utf8"));
13
+ return Boolean(
14
+ pkg.dependencies?.["@base-ui/react"] ||
15
+ pkg.devDependencies?.["@base-ui/react"] ||
16
+ pkg.peerDependencies?.["@base-ui/react"],
17
+ );
18
+ } catch {
19
+ return false;
20
+ }
21
+ };
22
+
23
+ // Walk up to the nearest package.json and report whether it declares
24
+ // @base-ui/react, memoizing every directory visited so a lint run pays the fs
25
+ // cost once per project subtree.
26
+ export const projectUsesBaseUi = (fromDir) => {
27
+ const seen = [];
28
+ let dir = fromDir;
29
+ let result = null;
30
+ while (result === null) {
31
+ if (baseUiCache.has(dir)) {
32
+ result = baseUiCache.get(dir);
33
+ } else {
34
+ seen.push(dir);
35
+ const pkgPath = join(dir, "package.json");
36
+ const parent = dirname(dir);
37
+ if (existsSync(pkgPath)) result = pkgDeclaresBaseUi(pkgPath);
38
+ else if (parent === dir) result = false;
39
+ else dir = parent;
40
+ }
41
+ }
42
+ for (const d of seen) baseUiCache.set(d, result);
43
+ return result;
44
+ };
45
+
46
+ /** Whether the rule should run for this file's project. */
47
+ export const fileUsesBaseUi = (context) => {
48
+ const filename = context.physicalFilename || context.filename || "";
49
+ return Boolean(filename) && projectUsesBaseUi(dirname(filename));
50
+ };
@@ -26,46 +26,7 @@
26
26
  // @base-ui/react; on Radix (or UI-less) sites it is inert. This lets the shared
27
27
  // nextkit ruleset enable it as an error fleet-wide without false positives.
28
28
 
29
- import { existsSync, readFileSync } from "node:fs";
30
- import { dirname, join } from "node:path";
31
-
32
- const baseUiCache = new Map();
33
-
34
- const pkgDeclaresBaseUi = (pkgPath) => {
35
- try {
36
- const pkg = JSON.parse(readFileSync(pkgPath, "utf8"));
37
- return Boolean(
38
- pkg.dependencies?.["@base-ui/react"] ||
39
- pkg.devDependencies?.["@base-ui/react"] ||
40
- pkg.peerDependencies?.["@base-ui/react"],
41
- );
42
- } catch {
43
- return false;
44
- }
45
- };
46
-
47
- // Walk up to the nearest package.json and report whether it declares
48
- // @base-ui/react, memoizing every directory visited so a lint run pays the fs
49
- // cost once per project subtree.
50
- const projectUsesBaseUi = (fromDir) => {
51
- const seen = [];
52
- let dir = fromDir;
53
- let result = null;
54
- while (result === null) {
55
- if (baseUiCache.has(dir)) {
56
- result = baseUiCache.get(dir);
57
- } else {
58
- seen.push(dir);
59
- const pkgPath = join(dir, "package.json");
60
- const parent = dirname(dir);
61
- if (existsSync(pkgPath)) result = pkgDeclaresBaseUi(pkgPath);
62
- else if (parent === dir) result = false;
63
- else dir = parent;
64
- }
65
- }
66
- for (const d of seen) baseUiCache.set(d, result);
67
- return result;
68
- };
29
+ import { fileUsesBaseUi } from "./base-ui-project.js";
69
30
 
70
31
  // component name -> { bannedProp: replacementProp }
71
32
  const BANNED = {
@@ -97,8 +58,7 @@ const noRadixPropsOnBaseUi = {
97
58
  },
98
59
  },
99
60
  create(context) {
100
- const filename = context.physicalFilename || context.filename || "";
101
- if (!filename || !projectUsesBaseUi(dirname(filename))) return {};
61
+ if (!fileUsesBaseUi(context)) return {};
102
62
  return {
103
63
  JSXAttribute(node) {
104
64
  if (!node.name || node.name.type !== "JSXIdentifier") return;
@@ -3,12 +3,16 @@
3
3
  // oxlintrc.json loads via `jsPlugins`.
4
4
 
5
5
  import baseUi from "./base-ui.js";
6
+ import baseUiNativeButton from "./base-ui-native-button.js";
6
7
  import deferredCurrentTarget from "./deferred-current-target.js";
7
8
  import lucideIconSuffix from "./lucide-icon-suffix.js";
8
9
  import noCryptoRandomUuid from "./no-crypto-random-uuid.js";
9
10
  import noIdCodecInAppCode from "./no-id-codec-in-app-code.js";
10
11
  import noRedirectOnlyPage from "./no-redirect-only-page.js";
11
12
  import noRedundantNodeCrypto from "./no-redundant-node-crypto.js";
13
+ import noServerEnvInClient from "./no-server-env-in-client.js";
14
+ import noSqlArrayCast from "./no-sql-array-cast.js";
15
+ import noUnvalidatedRequestBody from "./no-unvalidated-request-body.js";
12
16
  import redundantUseStateType from "./redundant-usestate-type.js";
13
17
  import satoriCss from "./satori-css.js";
14
18
  import tNoPositionalArgs from "./t-no-positional-args.js";
@@ -18,12 +22,16 @@ export default {
18
22
  meta: { name: "nextkit" },
19
23
  rules: {
20
24
  ...baseUi.rules,
25
+ ...baseUiNativeButton.rules,
21
26
  ...deferredCurrentTarget.rules,
22
27
  ...lucideIconSuffix.rules,
23
28
  ...noCryptoRandomUuid.rules,
24
29
  ...noIdCodecInAppCode.rules,
25
30
  ...noRedirectOnlyPage.rules,
26
31
  ...noRedundantNodeCrypto.rules,
32
+ ...noServerEnvInClient.rules,
33
+ ...noSqlArrayCast.rules,
34
+ ...noUnvalidatedRequestBody.rules,
27
35
  ...redundantUseStateType.rules,
28
36
  ...satoriCss.rules,
29
37
  ...tNoPositionalArgs.rules,
@@ -0,0 +1,88 @@
1
+ // nextkit oxlint JS plugin rule: a client component reads only the env vars
2
+ // Next is willing to give the browser.
3
+ //
4
+ // Next replaces `process.env.FOO` at build time, and only `NEXT_PUBLIC_*`
5
+ // survives into client bundles. Everything else becomes `undefined` there, so
6
+ // a secret read from a `"use client"` file is a feature that silently does
7
+ // nothing in the browser — a key that is never sent, a flag that never turns
8
+ // on — while working perfectly in dev, in tests and in any server render of
9
+ // the same module. And when a var IS public, the value is inlined into the
10
+ // bundle for anyone to read, which is the wrong home for a credential.
11
+ //
12
+ // The rule is an allowlist rather than a list of secret names, because a list
13
+ // of secrets goes stale the moment someone adds an integration and the miss is
14
+ // silent: a client file may read `NEXT_PUBLIC_*` and `NODE_ENV`, nothing else.
15
+ //
16
+ // The fix is almost never to rename the variable to `NEXT_PUBLIC_`. Read it in
17
+ // a server component or route handler and pass the value down as a prop, or
18
+ // call an API route that reads it server-side.
19
+
20
+ const CLIENT_SAFE = /^NEXT_PUBLIC_/;
21
+
22
+ /** Whether the file opens with the "use client" directive. */
23
+ const isClientFile = (program) => {
24
+ for (const statement of program.body) {
25
+ if (statement.type !== "ExpressionStatement") break;
26
+ const value = statement.directive ?? statement.expression.value;
27
+ if (typeof value !== "string") break;
28
+ if (value === "use client") return true;
29
+ }
30
+ return false;
31
+ };
32
+
33
+ /** The variable name in `process.env.FOO` / `process.env["FOO"]`, or null. */
34
+ const envVarName = (node) => {
35
+ const object = node.object;
36
+ if (object.type !== "MemberExpression" || object.computed) return null;
37
+ if (object.object.type !== "Identifier" || object.object.name !== "process") {
38
+ return null;
39
+ }
40
+ if (object.property.type !== "Identifier" || object.property.name !== "env") {
41
+ return null;
42
+ }
43
+ if (!node.computed && node.property.type === "Identifier") {
44
+ return node.property.name;
45
+ }
46
+ if (node.computed && node.property.type === "Literal") {
47
+ return typeof node.property.value === "string" ? node.property.value : null;
48
+ }
49
+ return null;
50
+ };
51
+
52
+ const noServerEnvInClient = {
53
+ meta: {
54
+ type: "problem",
55
+ docs: {
56
+ description:
57
+ 'Disallow reading non-public env vars from a "use client" file',
58
+ },
59
+ messages: {
60
+ serverEnvInClient:
61
+ "`process.env.{{name}}` is not available in the browser: Next only inlines `NEXT_PUBLIC_*` into client bundles, so this reads `undefined` there while working on the server. Read it in a server component or route handler and pass the value in. Renaming it to `NEXT_PUBLIC_{{name}}` publishes it to every visitor, so do that only for values that are already public.",
62
+ },
63
+ },
64
+ create(context) {
65
+ let client = false;
66
+ return {
67
+ Program(node) {
68
+ client = isClientFile(node);
69
+ },
70
+ MemberExpression(node) {
71
+ if (!client) return;
72
+ const name = envVarName(node);
73
+ if (name === null) return;
74
+ if (name === "NODE_ENV" || CLIENT_SAFE.test(name)) return;
75
+ context.report({
76
+ node,
77
+ messageId: "serverEnvInClient",
78
+ data: { name },
79
+ });
80
+ },
81
+ };
82
+ },
83
+ };
84
+
85
+ export default {
86
+ meta: { name: "nextkit" },
87
+ rules: { "no-server-env-in-client": noServerEnvInClient },
88
+ };
@@ -0,0 +1,55 @@
1
+ // nextkit oxlint JS plugin rule: no `${jsArray}::type[]` in a drizzle `sql`
2
+ // template.
3
+ //
4
+ // A template interpolation is one bound parameter, and drizzle expands a JS
5
+ // array into a comma-separated list of them. So `sql`${ids}::uuid[]`` sends
6
+ // `($1, $2, $3)::uuid[]` — Postgres parses that as a record and fails at run
7
+ // time with "cannot cast type record to uuid[]". Nothing catches it earlier:
8
+ // the types are happy, and the query is a string until it reaches the server.
9
+ //
10
+ // Build the array explicitly instead:
11
+ //
12
+ // sql`array[${sql.join(ids.map((id) => sql`${id}`), sql`, `)}]::uuid[]`
13
+ //
14
+ // Casting a *column* to an array type is legitimate and indistinguishable
15
+ // syntactically, so that case takes a justified disable comment.
16
+
17
+ const ARRAY_CAST = /^::\s*"?[A-Za-z_][\w."]*"?\s*\[\s*\]/;
18
+
19
+ const noSqlArrayCast = {
20
+ meta: {
21
+ type: "problem",
22
+ docs: {
23
+ description:
24
+ "Disallow casting an interpolated value to an array type in a drizzle sql template",
25
+ },
26
+ messages: {
27
+ sqlArrayCast:
28
+ 'An interpolated array is expanded into separate bound parameters, so `::{{type}}` casts a record and fails at run time ("cannot cast type record to {{type}}"). Build the array with `array[...]` and `sql.join`. If this interpolation is a column rather than a JS array, add `// oxlint-disable-next-line nextkit/no-sql-array-cast -- <reason>`.',
29
+ },
30
+ },
31
+ create(context) {
32
+ return {
33
+ TaggedTemplateExpression(node) {
34
+ if (node.tag.type !== "Identifier" || node.tag.name !== "sql") return;
35
+ const quasis = node.quasi.quasis;
36
+ // quasis[i] for i > 0 is the text right after expressions[i - 1].
37
+ for (let i = 1; i < quasis.length; i++) {
38
+ const text = quasis[i].value.raw;
39
+ const match = ARRAY_CAST.exec(text);
40
+ if (match === null) continue;
41
+ context.report({
42
+ node: node.quasi.expressions[i - 1] ?? node,
43
+ messageId: "sqlArrayCast",
44
+ data: { type: match[0].slice(2).trim() },
45
+ });
46
+ }
47
+ },
48
+ };
49
+ },
50
+ };
51
+
52
+ export default {
53
+ meta: { name: "nextkit" },
54
+ rules: { "no-sql-array-cast": noSqlArrayCast },
55
+ };
@@ -0,0 +1,85 @@
1
+ // nextkit oxlint JS plugin rule: a route handler never `as`-casts the request
2
+ // body it just parsed.
3
+ //
4
+ // `Request.json()` is typed `Promise<any>`, so `(await req.json()) as Invoice`
5
+ // and `const body: Invoice = await req.json()` both type-check while asserting
6
+ // something about a payload the caller controls. The cast is a lie the type
7
+ // checker cannot catch: the handler then reads fields that may be absent, of
8
+ // the wrong type, or attacker-chosen, and the first symptom is a 500 or a row
9
+ // written from a body nobody validated.
10
+ //
11
+ // Parse it instead — `schema.parse(await req.json())` (or `safeParse` where the
12
+ // handler answers the failure itself), which produces the same static type
13
+ // from a run-time check. Casting to `unknown` is fine and is how you hand the
14
+ // value to a parser.
15
+ //
16
+ // Scoped to route handlers (`app/**/route.ts`), where the body is by
17
+ // definition external. Casting a *response* you fetched is a different (and
18
+ // weaker) claim, and this rule says nothing about it.
19
+
20
+ const ROUTE_FILE = /(^|[\\/])app[\\/].*[\\/]route\.[cm]?[jt]sx?$/;
21
+ const SAFE_TARGETS = new Set(["TSUnknownKeyword", "TSAnyKeyword"]);
22
+
23
+ /** Unwrap parentheses and `as`-chains down to the inner expression. */
24
+ const inner = (node) => {
25
+ let current = node;
26
+ while (
27
+ current.type === "TSAsExpression" ||
28
+ current.type === "TSNonNullExpression" ||
29
+ current.type === "ParenthesizedExpression"
30
+ ) {
31
+ current = current.expression;
32
+ }
33
+ return current;
34
+ };
35
+
36
+ /** Whether `node` is `await <something>.json()`. */
37
+ const isAwaitedJson = (node) => {
38
+ if (node.type !== "AwaitExpression") return false;
39
+ const call = inner(node.argument);
40
+ if (call.type !== "CallExpression" || call.arguments.length > 0) return false;
41
+ const callee = call.callee;
42
+ return (
43
+ callee.type === "MemberExpression" &&
44
+ !callee.computed &&
45
+ callee.property.type === "Identifier" &&
46
+ callee.property.name === "json"
47
+ );
48
+ };
49
+
50
+ const noUnvalidatedRequestBody = {
51
+ meta: {
52
+ type: "problem",
53
+ docs: {
54
+ description:
55
+ "Disallow asserting a type on a request body instead of parsing it",
56
+ },
57
+ messages: {
58
+ castBody:
59
+ "`json()` returns `any`, so this asserts a shape the caller controls and nothing checks it. Parse the body with a schema instead — `schema.parse(await req.json())` — which gives the same static type from a run-time check. `as unknown` is fine on the way into a parser.",
60
+ },
61
+ },
62
+ create(context) {
63
+ if (!ROUTE_FILE.test(context.filename ?? "")) return {};
64
+ return {
65
+ // `(await req.json()) as Body`
66
+ TSAsExpression(node) {
67
+ if (SAFE_TARGETS.has(node.typeAnnotation?.type)) return;
68
+ if (!isAwaitedJson(inner(node.expression))) return;
69
+ context.report({ node, messageId: "castBody" });
70
+ },
71
+ // `const body: Body = await req.json()` — no cast, same assertion.
72
+ VariableDeclarator(node) {
73
+ const annotation = node.id.typeAnnotation?.typeAnnotation;
74
+ if (!annotation || SAFE_TARGETS.has(annotation.type)) return;
75
+ if (!node.init || !isAwaitedJson(inner(node.init))) return;
76
+ context.report({ node, messageId: "castBody" });
77
+ },
78
+ };
79
+ },
80
+ };
81
+
82
+ export default {
83
+ meta: { name: "nextkit" },
84
+ rules: { "no-unvalidated-request-body": noUnvalidatedRequestBody },
85
+ };
@@ -9,6 +9,10 @@ import { FORMATTER } from "./formatter.js";
9
9
  import { hasKnipConfig, runKnip } from "./knip.js";
10
10
  import { checkSeal } from "./migrations.js";
11
11
  import { run, runCapture, writeThrough } from "./run.js";
12
+ import {
13
+ tailwindCoverageFindings,
14
+ tailwindSourceFindings,
15
+ } from "./tailwind-sources.js";
12
16
  import { readdirSync, rmSync } from "node:fs";
13
17
 
14
18
  /** `nk lint [...]` — oxlint, with extra args passed through (e.g. `--fix`). */
@@ -20,7 +24,9 @@ export function lint(extraArgs = []) {
20
24
  * `nk check` — the CI gate. Runs every fast checker and reports them all before
21
25
  * failing: oxlint, oxfmt (format), knip (when configured), and the agent-guide
22
26
  * import gate. Tooling drift (superseded deps) is reported as a non-fatal
23
- * warning — `nk doctor --fix` resolves it.
27
+ * warning — `nk doctor --fix` resolves it. Tailwind `@source` paths that
28
+ * resolve to nothing, and workspace packages no stylesheet scans, fail the
29
+ * gate: no other checker reads CSS.
24
30
  */
25
31
  export function check() {
26
32
  // Run every gate before deciding (no short-circuit), so one failure doesn't
@@ -48,9 +54,39 @@ export function check() {
48
54
  " → restore the file and add a new migration, or run `nk migrations` to seal a newly generated one.",
49
55
  );
50
56
  }
57
+ // A tailwind @source that matches nothing drops every class only those
58
+ // files use, and no other gate reads CSS. A no-op on sites without one.
59
+ const sources = tailwindSourceFindings();
60
+ for (const { file, source, resolved } of sources) {
61
+ console.error(
62
+ `nk check: ${file} scans \`${source}\`, which does not exist (${resolved})`,
63
+ );
64
+ console.error(
65
+ " → tailwind resolves @source against the stylesheet and silently scans nothing; fix the path.",
66
+ );
67
+ }
68
+ // The same failure from the other side: a workspace package whose classes
69
+ // no stylesheet scans. Automatic detection never reaches a sibling package.
70
+ const uncovered = tailwindCoverageFindings();
71
+ for (const { name, dir } of uncovered) {
72
+ console.error(
73
+ `nk check: no @source scans \`${name}\` (${dir}), whose components write class names`,
74
+ );
75
+ console.error(
76
+ " → tailwind only scans the site; add `@source` for the package or its classes are dropped.",
77
+ );
78
+ }
51
79
  warnToolDrift();
52
80
  process.exit(
53
- lintFailed || fmtFailed || knipFailed || !guide.ok || !seal.ok ? 1 : 0,
81
+ lintFailed ||
82
+ fmtFailed ||
83
+ knipFailed ||
84
+ !guide.ok ||
85
+ !seal.ok ||
86
+ sources.length > 0 ||
87
+ uncovered.length > 0
88
+ ? 1
89
+ : 0,
54
90
  );
55
91
  }
56
92
 
@@ -0,0 +1,201 @@
1
+ import { existsSync, readdirSync, readFileSync, realpathSync } from "node:fs";
2
+ import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
3
+
4
+ // Two ways a stylesheet ends up scanning the wrong thing, both silent.
5
+ //
6
+ // Tailwind v4 declares what to scan for classes in CSS: `@source "<path>"`,
7
+ // resolved against the stylesheet that carries it. A path that matches nothing
8
+ // is not an error — the scan simply yields no files, so every utility only
9
+ // those files use is dropped from the build. Nothing else notices: oxlint and
10
+ // tsc do not read CSS, knip walks imports, and `next build` exits 0 with a
11
+ // smaller stylesheet. The page just renders unstyled. So resolve them here.
12
+ //
13
+ // The same failure has a second shape in a workspace: automatic detection
14
+ // scans from the site, never a sibling package, so a component library linked
15
+ // in as a workspace dependency is invisible unless some `@source` names it. A
16
+ // stylesheet that never mentions it is as broken as one that misspells the
17
+ // path, and has even less to notice. So check coverage as well as resolution.
18
+
19
+ const SKIP_DIRS = new Set([
20
+ "node_modules",
21
+ ".next",
22
+ ".git",
23
+ "dist",
24
+ "build",
25
+ "coverage",
26
+ ".turbo",
27
+ ".vercel",
28
+ ]);
29
+
30
+ // `@source "x"`, `@source not "x"`. `@source inline(...)` names class names
31
+ // rather than files, and has no quote in that position, so it never matches.
32
+ const SOURCE_RE = /@source\s+(?:not\s+)?(?:"([^"]+)"|'([^']+)')/g;
33
+ const GLOB = /[*?[\]{}]/;
34
+
35
+ /** Every .css file under `dir`, skipping generated and vendored trees. */
36
+ function cssFiles(dir, out = []) {
37
+ let entries;
38
+ try {
39
+ entries = readdirSync(dir, { withFileTypes: true });
40
+ } catch {
41
+ return out;
42
+ }
43
+ for (const entry of entries) {
44
+ const full = join(dir, entry.name);
45
+ if (entry.isDirectory()) {
46
+ if (SKIP_DIRS.has(entry.name)) continue;
47
+ cssFiles(full, out);
48
+ } else if (entry.name.endsWith(".css")) out.push(full);
49
+ }
50
+ return out;
51
+ }
52
+
53
+ /**
54
+ * The part of a source path that must exist on disk: everything before the
55
+ * first globbed segment, so `../ui/src/**\/*.tsx` is checked as `../ui/src`.
56
+ */
57
+ function literalPrefix(path) {
58
+ const segments = path.split("/");
59
+ const stop = segments.findIndex((s) => GLOB.test(s));
60
+ return (stop === -1 ? segments : segments.slice(0, stop)).join("/");
61
+ }
62
+
63
+ /**
64
+ * Findings for the repo at `cwd`: one per `@source` that resolves to nothing.
65
+ * Each is `{ file, source, resolved }`, `file` relative to `cwd`.
66
+ */
67
+ export function tailwindSourceFindings(cwd = process.cwd()) {
68
+ const out = [];
69
+ for (const file of cssFiles(cwd)) {
70
+ let css;
71
+ try {
72
+ css = readFileSync(file, "utf8");
73
+ } catch {
74
+ continue;
75
+ }
76
+ if (!css.includes("@source")) continue;
77
+ for (const match of css.matchAll(SOURCE_RE)) {
78
+ const source = match[1] ?? match[2];
79
+ const prefix = literalPrefix(source);
80
+ // A wholly globbed path (`**/*.tsx`) names no directory to check.
81
+ if (prefix === "") continue;
82
+ const resolved = isAbsolute(prefix)
83
+ ? prefix
84
+ : resolve(dirname(file), prefix);
85
+ if (existsSync(resolved)) continue;
86
+ out.push({
87
+ file: relative(cwd, file).split(sep).join("/"),
88
+ source,
89
+ resolved,
90
+ });
91
+ }
92
+ }
93
+ return out;
94
+ }
95
+
96
+ const CLASS_EXT = /\.(tsx|jsx|ts|js|mjs|cjs)$/;
97
+ const TAILWIND_IMPORT = /@import\s+["']tailwindcss/;
98
+
99
+ /** The site's dependencies that resolve to a package inside the repo. */
100
+ function workspacePackages(cwd) {
101
+ let pkg;
102
+ try {
103
+ pkg = JSON.parse(readFileSync(resolve(cwd, "package.json"), "utf8"));
104
+ } catch {
105
+ return [];
106
+ }
107
+ const names = Object.keys({
108
+ ...pkg.dependencies,
109
+ ...pkg.devDependencies,
110
+ });
111
+ const out = [];
112
+ for (const name of names) {
113
+ // Walk up for the install that serves this site: bun and npm hoist to
114
+ // the workspace root, so the link is rarely in the site's own tree.
115
+ let dir = cwd;
116
+ for (;;) {
117
+ const candidate = join(dir, "node_modules", name);
118
+ if (existsSync(candidate)) {
119
+ let real;
120
+ try {
121
+ real = realpathSync(candidate);
122
+ } catch {
123
+ break;
124
+ }
125
+ // A linked workspace member resolves outside node_modules; a
126
+ // published dependency stays inside it.
127
+ if (!real.split(sep).includes("node_modules")) {
128
+ out.push({ name, dir: real });
129
+ }
130
+ break;
131
+ }
132
+ const parent = dirname(dir);
133
+ if (parent === dir) break;
134
+ dir = parent;
135
+ }
136
+ }
137
+ return out;
138
+ }
139
+
140
+ /** Whether any source file under `dir` writes a `className`. */
141
+ function writesClassNames(dir) {
142
+ let entries;
143
+ try {
144
+ entries = readdirSync(dir, { withFileTypes: true });
145
+ } catch {
146
+ return false;
147
+ }
148
+ for (const entry of entries) {
149
+ const full = join(dir, entry.name);
150
+ if (entry.isDirectory()) {
151
+ if (SKIP_DIRS.has(entry.name)) continue;
152
+ if (writesClassNames(full)) return true;
153
+ continue;
154
+ }
155
+ if (!CLASS_EXT.test(entry.name)) continue;
156
+ try {
157
+ if (readFileSync(full, "utf8").includes("className")) return true;
158
+ } catch {
159
+ /* unreadable file: not evidence either way */
160
+ }
161
+ }
162
+ return false;
163
+ }
164
+
165
+ /** Whether `a` is `b`, contains it, or sits inside it. */
166
+ function overlaps(a, b) {
167
+ return a === b || a.startsWith(b + sep) || b.startsWith(a + sep);
168
+ }
169
+
170
+ /**
171
+ * Findings for the repo at `cwd`: one per workspace dependency that writes
172
+ * class names and no tailwind stylesheet scans. Each is `{ name, dir }`, `dir`
173
+ * relative to `cwd`. Empty when the site has no tailwind entry stylesheet.
174
+ */
175
+ export function tailwindCoverageFindings(cwd = process.cwd()) {
176
+ const scanned = [];
177
+ let hasEntry = false;
178
+ for (const file of cssFiles(cwd)) {
179
+ let css;
180
+ try {
181
+ css = readFileSync(file, "utf8");
182
+ } catch {
183
+ continue;
184
+ }
185
+ if (!TAILWIND_IMPORT.test(css)) continue;
186
+ hasEntry = true;
187
+ for (const match of css.matchAll(SOURCE_RE)) {
188
+ const prefix = literalPrefix(match[1] ?? match[2]);
189
+ if (prefix === "") continue;
190
+ scanned.push(isAbsolute(prefix) ? prefix : resolve(dirname(file), prefix));
191
+ }
192
+ }
193
+ if (!hasEntry) return [];
194
+ const out = [];
195
+ for (const { name, dir } of workspacePackages(cwd)) {
196
+ if (scanned.some((source) => overlaps(dir, source))) continue;
197
+ if (!writesClassNames(dir)) continue;
198
+ out.push({ name, dir: relative(cwd, dir).split(sep).join("/") });
199
+ }
200
+ return out;
201
+ }
package/oxlintrc.json CHANGED
@@ -6,6 +6,7 @@
6
6
  },
7
7
  "rules": {
8
8
  "nextkit/no-radix-props-on-base-ui": "error",
9
+ "nextkit/base-ui-native-button": "error",
9
10
  "nextkit/no-deferred-current-target": "error",
10
11
  "nextkit/no-redundant-usestate-type": "warn",
11
12
  "nextkit/lucide-icon-suffix": "warn",
@@ -16,6 +17,9 @@
16
17
  "nextkit/no-id-codec-in-app-code": "warn",
17
18
  "nextkit/no-redundant-node-crypto": "warn",
18
19
  "nextkit/satori-css": "warn",
20
+ "nextkit/no-server-env-in-client": "error",
21
+ "nextkit/no-sql-array-cast": "error",
22
+ "nextkit/no-unvalidated-request-body": "error",
19
23
  "no-unused-vars": "warn",
20
24
  "typescript/no-non-null-assertion": "error",
21
25
  "typescript/no-explicit-any": "error",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ingram-tech/nk-dev",
3
- "version": "0.15.0",
3
+ "version": "0.16.1",
4
4
  "description": "The nextkit dev toolchain in one package: the `nk` CLI plus shared oxlint/oxfmt, TypeScript, and Vitest config, the format-on-commit hook, and the AI agent guide. `nk init` scaffolds a site to use it.",
5
5
  "license": "MIT",
6
6
  "type": "module",