@nifrajs/cli 5.13.0 → 5.15.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/CHANGELOG.md +52 -0
- package/README.md +3 -1
- package/dist/agent-files.js +0 -74
- package/dist/agent-files.js.map +1 -1
- package/dist/app-files.js +0 -19
- package/dist/app-files.js.map +1 -1
- package/dist/assure-hydration.js +0 -23
- package/dist/assure-hydration.js.map +1 -1
- package/dist/assure.js +0 -14
- package/dist/assure.js.map +1 -1
- package/dist/capabilities-tool.js +0 -51
- package/dist/capabilities-tool.js.map +1 -1
- package/dist/cdn-check.js +0 -2
- package/dist/cdn-check.js.map +1 -1
- package/dist/check-diagnostics.d.ts.map +1 -1
- package/dist/check-diagnostics.js +22 -31
- package/dist/check-diagnostics.js.map +1 -1
- package/dist/check-scan.d.ts.map +1 -1
- package/dist/check-scan.js +17 -622
- package/dist/check-scan.js.map +1 -1
- package/dist/check.js +0 -86
- package/dist/check.js.map +1 -1
- package/dist/cli.js +3 -336
- package/dist/cli.js.map +1 -1
- package/dist/client-module.js +0 -13
- package/dist/client-module.js.map +1 -1
- package/dist/command-catalog.js +0 -21
- package/dist/command-catalog.js.map +1 -1
- package/dist/component-check.js +1 -7
- package/dist/component-check.js.map +1 -1
- package/dist/config-target.js +0 -13
- package/dist/config-target.js.map +1 -1
- package/dist/contract-proof.js +0 -1
- package/dist/contract-proof.js.map +1 -1
- package/dist/contracts.js +0 -36
- package/dist/contracts.js.map +1 -1
- package/dist/db-audit.js +0 -15
- package/dist/db-audit.js.map +1 -1
- package/dist/db-child.js +0 -20
- package/dist/db-child.js.map +1 -1
- package/dist/db-config.js +0 -23
- package/dist/db-config.js.map +1 -1
- package/dist/db-tool.js +0 -24
- package/dist/db-tool.js.map +1 -1
- package/dist/deployment-adapters.js +1 -7
- package/dist/deployment-adapters.js.map +1 -1
- package/dist/dev-bun-config.js +0 -102
- package/dist/dev-bun-config.js.map +1 -1
- package/dist/dev-feed-tool.js +0 -32
- package/dist/dev-feed-tool.js.map +1 -1
- package/dist/dev-server-client.js +0 -16
- package/dist/dev-server-client.js.map +1 -1
- package/dist/diagnostics.js +0 -10
- package/dist/diagnostics.js.map +1 -1
- package/dist/diff-tool.js +0 -23
- package/dist/diff-tool.js.map +1 -1
- package/dist/docs-search.js +0 -35
- package/dist/docs-search.js.map +1 -1
- package/dist/doctor.js +3 -161
- package/dist/doctor.js.map +1 -1
- package/dist/env-file.js +0 -66
- package/dist/env-file.js.map +1 -1
- package/dist/examples.js +0 -16
- package/dist/examples.js.map +1 -1
- package/dist/fix-recipes.js +0 -20
- package/dist/fix-recipes.js.map +1 -1
- package/dist/frontend-guidance.js +12 -48
- package/dist/frontend-guidance.js.map +1 -1
- package/dist/hand-built-manifest.js +0 -17
- package/dist/hand-built-manifest.js.map +1 -1
- package/dist/hooks-report.js +0 -4
- package/dist/hooks-report.js.map +1 -1
- package/dist/i18n-check.js +0 -30
- package/dist/i18n-check.js.map +1 -1
- package/dist/init-agents.js +1 -133
- package/dist/init-agents.js.map +1 -1
- package/dist/internal/code-unit-order.js +0 -2
- package/dist/internal/code-unit-order.js.map +1 -1
- package/dist/internal/config-paths.js +0 -12
- package/dist/internal/config-paths.js.map +1 -1
- package/dist/internal/control-character.js +0 -1
- package/dist/internal/control-character.js.map +1 -1
- package/dist/internal/escape-regexp.d.ts +1 -2
- package/dist/internal/escape-regexp.d.ts.map +1 -1
- package/dist/internal/escape-regexp.js +1 -4
- package/dist/internal/escape-regexp.js.map +1 -1
- package/dist/internal/git-ignored.js +0 -11
- package/dist/internal/git-ignored.js.map +1 -1
- package/dist/internal/installed-package.js +0 -2
- package/dist/internal/installed-package.js.map +1 -1
- package/dist/internal/line-at.js +0 -1
- package/dist/internal/line-at.js.map +1 -1
- package/dist/internal/nifra-project.js +0 -31
- package/dist/internal/nifra-project.js.map +1 -1
- package/dist/internal/posix-path.js +0 -1
- package/dist/internal/posix-path.js.map +1 -1
- package/dist/internal/project-specifiers.js +0 -34
- package/dist/internal/project-specifiers.js.map +1 -1
- package/dist/internal/realpath-or-self.js +0 -1
- package/dist/internal/realpath-or-self.js.map +1 -1
- package/dist/internal/record.d.ts +1 -1
- package/dist/internal/record.d.ts.map +1 -1
- package/dist/internal/record.js +1 -4
- package/dist/internal/record.js.map +1 -1
- package/dist/internal/reserved-segment-codemod.js +0 -44
- package/dist/internal/reserved-segment-codemod.js.map +1 -1
- package/dist/internal/script-kind.js +0 -5
- package/dist/internal/script-kind.js.map +1 -1
- package/dist/internal/source-facts.js +3 -37
- package/dist/internal/source-facts.js.map +1 -1
- package/dist/internal/typescript-import.js +0 -49
- package/dist/internal/typescript-import.js.map +1 -1
- package/dist/internal/workspace-packages.js +0 -24
- package/dist/internal/workspace-packages.js.map +1 -1
- package/dist/introspect.js +1 -89
- package/dist/introspect.js.map +1 -1
- package/dist/learn.js +0 -16
- package/dist/learn.js.map +1 -1
- package/dist/levels-tool.js +0 -34
- package/dist/levels-tool.js.map +1 -1
- package/dist/load.js +0 -75
- package/dist/load.js.map +1 -1
- package/dist/local-cli.js +0 -23
- package/dist/local-cli.js.map +1 -1
- package/dist/lock-links.js +0 -20
- package/dist/lock-links.js.map +1 -1
- package/dist/manifest-tool.js +0 -5
- package/dist/manifest-tool.js.map +1 -1
- package/dist/mcp-app-tool.js +0 -9
- package/dist/mcp-app-tool.js.map +1 -1
- package/dist/mcp-context.js +0 -30
- package/dist/mcp-context.js.map +1 -1
- package/dist/mcp-delegate.js +0 -45
- package/dist/mcp-delegate.js.map +1 -1
- package/dist/mcp-docs-tools.js +0 -13
- package/dist/mcp-docs-tools.js.map +1 -1
- package/dist/mcp-exec.js +0 -71
- package/dist/mcp-exec.js.map +1 -1
- package/dist/mcp-http.js +1 -38
- package/dist/mcp-http.js.map +1 -1
- package/dist/mcp-io.d.ts +5 -1
- package/dist/mcp-io.d.ts.map +1 -1
- package/dist/mcp-io.js +3 -68
- package/dist/mcp-io.js.map +1 -1
- package/dist/mcp-isolate.js +0 -28
- package/dist/mcp-isolate.js.map +1 -1
- package/dist/mcp-path.js +0 -8
- package/dist/mcp-path.js.map +1 -1
- package/dist/mcp-project-child.js +0 -19
- package/dist/mcp-project-child.js.map +1 -1
- package/dist/mcp-protocol.js +0 -5
- package/dist/mcp-protocol.js.map +1 -1
- package/dist/mcp-reflect.js +0 -11
- package/dist/mcp-reflect.js.map +1 -1
- package/dist/mcp-relay.d.ts +4 -0
- package/dist/mcp-relay.d.ts.map +1 -1
- package/dist/mcp-relay.js +9 -20
- package/dist/mcp-relay.js.map +1 -1
- package/dist/mcp-render.js +1 -42
- package/dist/mcp-render.js.map +1 -1
- package/dist/mcp-root.js +0 -90
- package/dist/mcp-root.js.map +1 -1
- package/dist/mcp-run.js +1 -38
- package/dist/mcp-run.js.map +1 -1
- package/dist/mcp-tool-meta.js +3 -8
- package/dist/mcp-tool-meta.js.map +1 -1
- package/dist/mcp-ws.js +0 -16
- package/dist/mcp-ws.js.map +1 -1
- package/dist/mcp.js +0 -86
- package/dist/mcp.js.map +1 -1
- package/dist/migrate-layout.js +0 -313
- package/dist/migrate-layout.js.map +1 -1
- package/dist/openapi-tool.js +0 -18
- package/dist/openapi-tool.js.map +1 -1
- package/dist/openapi-types.js +0 -22
- package/dist/openapi-types.js.map +1 -1
- package/dist/output-schemas.js +0 -67
- package/dist/output-schemas.js.map +1 -1
- package/dist/pipeline-guard.js +0 -58
- package/dist/pipeline-guard.js.map +1 -1
- package/dist/pipeline-report.js +0 -71
- package/dist/pipeline-report.js.map +1 -1
- package/dist/port.js +1 -89
- package/dist/port.js.map +1 -1
- package/dist/ppr-read-fix.js +0 -29
- package/dist/ppr-read-fix.js.map +1 -1
- package/dist/project-facts.js +0 -5
- package/dist/project-facts.js.map +1 -1
- package/dist/project-path.js +0 -7
- package/dist/project-path.js.map +1 -1
- package/dist/project-site.js +0 -2
- package/dist/project-site.js.map +1 -1
- package/dist/recipes/1.8.0.js +0 -9
- package/dist/recipes/1.8.0.js.map +1 -1
- package/dist/recipes/2.0.0.js +0 -6
- package/dist/recipes/2.0.0.js.map +1 -1
- package/dist/recipes/3.0.0.js +0 -7
- package/dist/recipes/3.0.0.js.map +1 -1
- package/dist/recipes/4.0.0.js +0 -6
- package/dist/recipes/4.0.0.js.map +1 -1
- package/dist/recipes/5.0.0.js +0 -8
- package/dist/recipes/5.0.0.js.map +1 -1
- package/dist/recipes/5.1.0.js +0 -6
- package/dist/recipes/5.1.0.js.map +1 -1
- package/dist/recipes/5.10.0.js +0 -10
- package/dist/recipes/5.10.0.js.map +1 -1
- package/dist/recipes/5.11.0.js +0 -7
- package/dist/recipes/5.11.0.js.map +1 -1
- package/dist/recipes/5.12.0.js +0 -6
- package/dist/recipes/5.12.0.js.map +1 -1
- package/dist/recipes/5.13.0.js +0 -6
- package/dist/recipes/5.13.0.js.map +1 -1
- package/dist/recipes/5.14.0.d.ts +10 -0
- package/dist/recipes/5.14.0.d.ts.map +1 -0
- package/dist/recipes/5.14.0.js +26 -0
- package/dist/recipes/5.14.0.js.map +1 -0
- package/dist/recipes/5.15.0.d.ts +12 -0
- package/dist/recipes/5.15.0.d.ts.map +1 -0
- package/dist/recipes/5.15.0.js +30 -0
- package/dist/recipes/5.15.0.js.map +1 -0
- package/dist/recipes/5.2.0.js +0 -7
- package/dist/recipes/5.2.0.js.map +1 -1
- package/dist/recipes/5.3.0.js +0 -8
- package/dist/recipes/5.3.0.js.map +1 -1
- package/dist/recipes/5.4.0.js +0 -8
- package/dist/recipes/5.4.0.js.map +1 -1
- package/dist/recipes/5.5.0.js +0 -6
- package/dist/recipes/5.5.0.js.map +1 -1
- package/dist/recipes/5.6.0.js +0 -7
- package/dist/recipes/5.6.0.js.map +1 -1
- package/dist/recipes/5.7.0.js +0 -9
- package/dist/recipes/5.7.0.js.map +1 -1
- package/dist/recipes/5.8.0.js +0 -6
- package/dist/recipes/5.8.0.js.map +1 -1
- package/dist/recipes/5.9.0.js +0 -9
- package/dist/recipes/5.9.0.js.map +1 -1
- package/dist/recipes/index.d.ts.map +1 -1
- package/dist/recipes/index.js +4 -9
- package/dist/recipes/index.js.map +1 -1
- package/dist/release-verification.js +0 -14
- package/dist/release-verification.js.map +1 -1
- package/dist/replay.js +0 -3
- package/dist/replay.js.map +1 -1
- package/dist/review.js +0 -21
- package/dist/review.js.map +1 -1
- package/dist/route-types.js +0 -17
- package/dist/route-types.js.map +1 -1
- package/dist/rule-explain.js +0 -5
- package/dist/rule-explain.js.map +1 -1
- package/dist/rules/codes.js +0 -2
- package/dist/rules/codes.js.map +1 -1
- package/dist/rules/comment-markers.js +0 -25
- package/dist/rules/comment-markers.js.map +1 -1
- package/dist/rules/contract-visibility.js +0 -27
- package/dist/rules/contract-visibility.js.map +1 -1
- package/dist/rules/data-guard.js +1 -52
- package/dist/rules/data-guard.js.map +1 -1
- package/dist/rules/internal-links.js +0 -36
- package/dist/rules/internal-links.js.map +1 -1
- package/dist/rules/islands.js +2 -65
- package/dist/rules/islands.js.map +1 -1
- package/dist/rules/layout.js +0 -1
- package/dist/rules/layout.js.map +1 -1
- package/dist/rules/legacy.js +0 -31
- package/dist/rules/legacy.js.map +1 -1
- package/dist/rules/merge-auth.js +0 -9
- package/dist/rules/merge-auth.js.map +1 -1
- package/dist/rules/pages.js +0 -95
- package/dist/rules/pages.js.map +1 -1
- package/dist/rules/ppr.js +0 -8
- package/dist/rules/ppr.js.map +1 -1
- package/dist/rules/route-statement.js +0 -13
- package/dist/rules/route-statement.js.map +1 -1
- package/dist/rules/routes.js +1 -67
- package/dist/rules/routes.js.map +1 -1
- package/dist/rules/secrets.js +0 -15
- package/dist/rules/secrets.js.map +1 -1
- package/dist/rules/security.js +0 -113
- package/dist/rules/security.js.map +1 -1
- package/dist/rules/server-fn-namespace.js +0 -5
- package/dist/rules/server-fn-namespace.js.map +1 -1
- package/dist/rules/source-scan.js +0 -5
- package/dist/rules/source-scan.js.map +1 -1
- package/dist/rules/swap.js +0 -21
- package/dist/rules/swap.js.map +1 -1
- package/dist/rules/text-slot-boolean.js +0 -5
- package/dist/rules/text-slot-boolean.js.map +1 -1
- package/dist/rules/typescript.js +0 -5
- package/dist/rules/typescript.js.map +1 -1
- package/dist/rules/undeclared-response.js +0 -8
- package/dist/rules/undeclared-response.js.map +1 -1
- package/dist/rules/zones.js +0 -45
- package/dist/rules/zones.js.map +1 -1
- package/dist/runtime-differences.js +0 -20
- package/dist/runtime-differences.js.map +1 -1
- package/dist/scaffold-hole.js +1 -45
- package/dist/scaffold-hole.js.map +1 -1
- package/dist/scaffold.js +3 -60
- package/dist/scaffold.js.map +1 -1
- package/dist/sdk.js +1 -13
- package/dist/sdk.js.map +1 -1
- package/dist/search-terms.js +0 -12
- package/dist/search-terms.js.map +1 -1
- package/dist/shell-files.js +0 -15
- package/dist/shell-files.js.map +1 -1
- package/dist/shell-init.js +0 -15
- package/dist/shell-init.js.map +1 -1
- package/dist/smoke.js +0 -4
- package/dist/smoke.js.map +1 -1
- package/dist/source-rewrites.js +0 -43
- package/dist/source-rewrites.js.map +1 -1
- package/dist/stylex-migrate.js +0 -29
- package/dist/stylex-migrate.js.map +1 -1
- package/dist/symptom-search.js +0 -3
- package/dist/symptom-search.js.map +1 -1
- package/dist/sync-manifest.js +3 -33
- package/dist/sync-manifest.js.map +1 -1
- package/dist/test-tool.js +0 -10
- package/dist/test-tool.js.map +1 -1
- package/dist/typecheck-coverage.js +0 -36
- package/dist/typecheck-coverage.js.map +1 -1
- package/dist/types-search.js +0 -35
- package/dist/types-search.js.map +1 -1
- package/dist/upgrade.js +0 -214
- package/dist/upgrade.js.map +1 -1
- package/dist/verification-plan.js +0 -19
- package/dist/verification-plan.js.map +1 -1
- package/dist/verification.js +0 -23
- package/dist/verification.js.map +1 -1
- package/dist/version-drift.js +0 -8
- package/dist/version-drift.js.map +1 -1
- package/dist/web-app-options.js +0 -16
- package/dist/web-app-options.js.map +1 -1
- package/dist/work-graph.js +0 -21
- package/dist/work-graph.js.map +1 -1
- package/dist/workspace-link.js +0 -31
- package/dist/workspace-link.js.map +1 -1
- package/docs/examples.json +7 -1
- package/docs/llms-full.txt +422 -44
- package/docs/types.json +193 -16
- package/package.json +12 -11
- package/src/assure-hydration.ts +3 -3
- package/src/check-diagnostics.ts +26 -2
- package/src/check-scan.ts +8 -1
- package/src/cli.ts +5 -5
- package/src/frontend-guidance.ts +12 -12
- package/src/internal/escape-regexp.ts +1 -4
- package/src/internal/record.ts +1 -3
- package/src/internal/typescript-import.ts +1 -1
- package/src/mcp-http.ts +1 -1
- package/src/mcp-io.ts +8 -5
- package/src/mcp-relay.ts +19 -7
- package/src/mcp-render.ts +1 -1
- package/src/mcp-tool-meta.ts +3 -3
- package/src/recipes/5.14.0.ts +34 -0
- package/src/recipes/5.15.0.ts +40 -0
- package/src/recipes/index.ts +4 -0
package/dist/check-scan.js
CHANGED
|
@@ -1,9 +1,3 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Pure source scanners for the nifra verification pipeline.
|
|
3
|
-
*
|
|
4
|
-
* This module deliberately has no CLI, policy, or diagnostic-view dependencies. Its interface is
|
|
5
|
-
* source text plus injected module/type resolvers, which keeps the scanner seam independently testable.
|
|
6
|
-
*/
|
|
7
1
|
import { readFileSync, realpathSync } from "node:fs";
|
|
8
2
|
import { dirname, isAbsolute, join, posix, resolve, sep } from "node:path";
|
|
9
3
|
import { isServerPackageSpecifier } from "@nifrajs/web/zones";
|
|
@@ -16,42 +10,26 @@ import { realpathOrSelf } from "./internal/realpath-or-self.js";
|
|
|
16
10
|
import { scriptKindOf } from "./internal/script-kind.js";
|
|
17
11
|
import { loadProjectTypeScript, } from "./internal/typescript-import.js";
|
|
18
12
|
import { commentBlockExpectation } from "./rules/comment-markers.js";
|
|
19
|
-
/** What marks a hand-rolled own-API call as intended: a streamed POST, a foreign handler's endpoint,
|
|
20
|
-
* a static file. Only the code form; a reason after the colon is required. */
|
|
21
13
|
const TYPED_CLIENT_EXPECTATION = ["NF-C002"];
|
|
22
14
|
function typedClientFinding(file, lines, line) {
|
|
23
15
|
const finding = { file, line, snippet: (lines[line - 1] ?? "").trim() };
|
|
24
16
|
const expected = commentBlockExpectation(lines, line, TYPED_CLIENT_EXPECTATION);
|
|
25
17
|
return expected === undefined ? finding : { ...finding, expected };
|
|
26
18
|
}
|
|
27
|
-
// `fetch( <ws> ('|"|`) / (not /)` - a string/template arg starting with a single `/` is a relative URL,
|
|
28
|
-
// i.e. same-origin = this app's own API. `(?<![.\w])` skips `.fetch(` (a method) and `prefetch(`; the
|
|
29
|
-
// `(?!\/)` skips protocol-relative `//host` (an external origin). A variable arg (`fetch(url)`) is left
|
|
30
|
-
// alone on purpose - undecidable from source, and flagging it would punish legitimate external calls.
|
|
31
19
|
const GLOBAL_FETCH_CALL = /(?<![.\w])fetch\s*\(/g;
|
|
32
20
|
const FETCH_CALL = /(?<![.\w])fetch\s*\(/g;
|
|
33
21
|
const HTTP_VERBS = new Set(["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"]);
|
|
34
22
|
const SOCKET_VERB = new Set(["WS"]);
|
|
35
23
|
export const SIMPLE_REWRITE_METHODS = new Set(["GET", "DELETE", "HEAD", "OPTIONS"]);
|
|
36
|
-
// Don't scan deps, build output, or generated client entries. `dist(-<runtime>)?` also covers
|
|
37
|
-
// per-runtime output dirs (dist-bun/dist-node/dist-deno/dist-vercel). Never source, for any scan.
|
|
38
24
|
const IGNORED_DIR = /(^|\/)(node_modules|dist(-[a-z0-9]+)?|build|\.nifra|\.git|\.wrangler|coverage)\//;
|
|
39
|
-
// A test/spec module. Excluded from `nifra check`'s scans, which are about what SHIPS - a test
|
|
40
|
-
// legitimately drives `fetch`, hand-rolls a client, and calls a route directly. It is NOT excluded from
|
|
41
|
-
// `nifra doctor`: tsc typechecks tests, so an import a test declares nowhere is a real broken build.
|
|
42
25
|
const TEST_FILE = /\.(test|spec)\.[cm]?[jt]sx?$/;
|
|
43
26
|
export const IGNORED = new RegExp(`${IGNORED_DIR.source}|${TEST_FILE.source}`);
|
|
44
|
-
/** Paths crossing the scanner boundary are project-relative identifiers, not filesystem paths. Keep
|
|
45
|
-
* them stable across runtimes so rules, diagnostics, ignore globs, and import chains have one shape. */
|
|
46
27
|
const normalizeProjectPath = toPosix;
|
|
47
|
-
// Browser code by path, mirroring `@nifrajs/web/zones`: a suffix decides first, then the folder. A
|
|
48
|
-
// route's backend half (`x.backend.ts`), `backend/` and `*.fn.ts` run on the server only.
|
|
49
28
|
const BACKEND_SUFFIX = /\.backend\.[cm]?[jt]sx?$/;
|
|
50
29
|
const BROWSER_SUFFIX = /\.(?:frontend|shared)\.[^/]+$/;
|
|
51
30
|
const BROWSER_FOLDER = /(^|\/)(?:routes|frontend|shared)\//;
|
|
52
31
|
const BACKEND_FOLDER = /(^|\/)backend\//;
|
|
53
32
|
const SERVER_FN_FILE = /\.fn\.[cm]?[jt]sx?$/;
|
|
54
|
-
/** Whether a project file is browser code: a route's frontend half, `frontend/` or `shared/`. Pure. */
|
|
55
33
|
export function isBrowserSource(file) {
|
|
56
34
|
const path = normalizeProjectPath(file);
|
|
57
35
|
if (BACKEND_SUFFIX.test(path) || SERVER_FN_FILE.test(path))
|
|
@@ -60,8 +38,6 @@ export function isBrowserSource(file) {
|
|
|
60
38
|
return true;
|
|
61
39
|
return BROWSER_FOLDER.test(path) && !BACKEND_FOLDER.test(path);
|
|
62
40
|
}
|
|
63
|
-
/** Whether a resolved module is backend code a browser import may not reach (a `*.fn.ts` module ships
|
|
64
|
-
* as its generated stub, so it is not). A legacy `*.server` module counts: the build refuses it. */
|
|
65
41
|
function isBackendModule(file) {
|
|
66
42
|
const path = normalizeProjectPath(file);
|
|
67
43
|
if (SERVER_FN_FILE.test(path))
|
|
@@ -70,8 +46,6 @@ function isBackendModule(file) {
|
|
|
70
46
|
LEGACY_SERVER_FILE.test(path) ||
|
|
71
47
|
(BACKEND_FOLDER.test(path) && !BROWSER_SUFFIX.test(path)));
|
|
72
48
|
}
|
|
73
|
-
// Node builtins that have no browser counterpart, imported bare. Bare `events`, `buffer`, `path`, `util`
|
|
74
|
-
// and the like stay out: each also names an npm polyfill a browser bundle may legitimately carry.
|
|
75
49
|
const SERVER_BUILTINS = new Set([
|
|
76
50
|
"async_hooks",
|
|
77
51
|
"child_process",
|
|
@@ -102,52 +76,26 @@ const SERVER_BUILTINS = new Set([
|
|
|
102
76
|
"wasi",
|
|
103
77
|
"worker_threads",
|
|
104
78
|
]);
|
|
105
|
-
// The conventional `./db` module the scaffold generates.
|
|
106
79
|
const DB_MODULE = /^(?:\.\.?\/)+db(?:\.[cm]?[jt]sx?)?$/;
|
|
107
|
-
/**
|
|
108
|
-
* Whether a specifier names server-only code by name, so the chain ends there: a `node:`/`bun:`
|
|
109
|
-
* module, a bare builtin with no browser counterpart, or a package the browser build refuses
|
|
110
|
-
* (`SERVER_PACKAGES` and the driver entries of `@nifrajs/web/zones`).
|
|
111
|
-
*/
|
|
112
80
|
export function isServerOnlySink(specifier) {
|
|
113
81
|
return (/^(?:node:|bun:)/.test(specifier) ||
|
|
114
82
|
SERVER_BUILTINS.has(specifier) ||
|
|
115
83
|
isServerPackageSpecifier(specifier));
|
|
116
84
|
}
|
|
117
|
-
/** A specifier no route module may value-import: a {@link isServerOnlySink} name, or the `./db` module. */
|
|
118
85
|
const isServerOnly = (specifier) => isServerOnlySink(specifier) || DB_MODULE.test(specifier);
|
|
119
|
-
// A static, non-type import with a string specifier, or a re-export (`export … from "x"`), which
|
|
120
|
-
// pulls its module into the bundle the same way. `import type …` and `export type …` are erased at
|
|
121
|
-
// build, so they're safe and skipped. Dynamic `import(…)` has `(` right after `import`, so `import\s+`
|
|
122
|
-
// never matches it; it is read by DYNAMIC_IMPORT below.
|
|
123
|
-
// The clause between the keyword and `from` is spelled out (a default binding, then `* as ns` or a
|
|
124
|
-
// `{ … }` list) rather than scanned lazily: a lazy scan restarts at every `export const` line and is
|
|
125
|
-
// quadratic on a long semicolon-free module.
|
|
126
86
|
const STATIC_IMPORT = /\b(?:import\s*(?!type\b)(?:(?:[\w$]+\s*,?\s*)?(?:\*\s*(?:as\b\s*[\w$]+\s*)?|\{[^{}'"]*\}\s*)?from\s*)?|export\s*(?!type\b)(?:\*\s*(?:as\b\s*[\w$]+\s*)?|\{[^{}'"]*\}\s*)from\s*)['"]([^'"]+)['"]/g;
|
|
127
|
-
// A dynamic `import("x")` whose specifier is one string literal. The client build bundles its target
|
|
128
|
-
// as a lazy chunk, so it reaches the browser bundle like a static import does - also from inside a
|
|
129
|
-
// loader, which ships with the route module. A computed specifier cannot be followed and is skipped.
|
|
130
87
|
const DYNAMIC_IMPORT = /(?<![\w$.])import\s*\(\s*(["'`])([^"'`$\\\r\n]+)\1\s*[,)]/g;
|
|
131
|
-
// Without a parser: `typeof import("x")` and `import("x").Name` are type positions, erased at build.
|
|
132
|
-
// A runtime `import("x")` is a promise, so the only members read straight off it are its methods.
|
|
133
88
|
const TYPE_QUERY_BEFORE = /\btypeof\s*$/;
|
|
134
|
-
// `require("x")` and `import x = require("x")` pull a module into a bundle as `import` does; the
|
|
135
|
-
// `import type x = require("x")` form is erased.
|
|
136
89
|
const REQUIRE_CALL = /(?<![\w$.])require\s*\(\s*(["'])([^"'\\\r\n]+)\1\s*\)/g;
|
|
137
90
|
const TYPE_ALIAS_BEFORE = /\bimport\s+type\s+[\w$]+\s*=\s*$/;
|
|
138
91
|
const TYPE_QUALIFIER_AFTER = /^\s*\.\s*(?!(?:then|catch|finally)\b)[A-Za-z_$]/;
|
|
139
92
|
const ROUTE_REGISTRATION_DQ = /\.([A-Za-z]+)\s*\(\s*"((?:\\.|[^"\\])*)"/g;
|
|
140
93
|
const ROUTE_REGISTRATION_SQ = /\.([A-Za-z]+)\s*\(\s*'((?:\\.|[^'\\])*)'/g;
|
|
141
|
-
// `all("/path", ...)` and `method("PURGE", "/path", ...)` / `method(["GET", "PURGE"], "/path", ...)`
|
|
142
|
-
// from `@nifrajs/core/methods`. They are free function calls, so the member-call patterns above do
|
|
143
|
-
// not see them.
|
|
144
94
|
const METHODS_SUBPATH = "@nifrajs/core/methods";
|
|
145
95
|
const ALL_ROUTES = /(?<![\w$.])all\s*\(\s*(?:"((?:\\.|[^"\\])*)"|'((?:\\.|[^'\\])*)')/g;
|
|
146
96
|
const METHOD_ROUTES = /(?<![\w$.])method\s*\(\s*(\[[^\]]*\]|"[^"\\]*"|'[^'\\]*')\s*,\s*(?:"((?:\\.|[^"\\])*)"|'((?:\\.|[^'\\])*)')/g;
|
|
147
97
|
const METHOD_NAME_LITERAL = /(["'])([A-Za-z][A-Za-z0-9-]{0,31})\1/g;
|
|
148
98
|
export const IDENT = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
|
|
149
|
-
// `.get(NAME, …)` or `` .get(`…`, …) ``: a path that is not a quoted literal. The comma is required:
|
|
150
|
-
// a registration always has a handler after its path, while `map.get(key)` has nothing.
|
|
151
99
|
const ROUTE_ARGUMENT = /\.([A-Za-z]+)\s*\(\s*([A-Za-z_$][\w$]*|`(?:\\.|[^`\\])*`)\s*,/g;
|
|
152
100
|
const NAMED_IMPORTS = /(?<![\w$.])import\s*\{([^}]*)\}\s*from\s*(["'])([^"'\r\n]+)\2/g;
|
|
153
101
|
function parseQuotedLiteral(raw) {
|
|
@@ -158,10 +106,6 @@ function parseQuotedLiteral(raw) {
|
|
|
158
106
|
if (!raw.startsWith("'") || !raw.endsWith("'"))
|
|
159
107
|
return undefined;
|
|
160
108
|
try {
|
|
161
|
-
// Convert the single-quoted body to a JSON string body by scan, handling backslash pairs
|
|
162
|
-
// atomically: `\'` becomes `'`, other escapes pass through untouched, and a bare `"` is
|
|
163
|
-
// escaped. A quote-only `replace` mis-handles content with backslashes (double-escaping
|
|
164
|
-
// an already-escaped quote, or letting a trailing backslash swallow the added escape).
|
|
165
109
|
const inner = raw.slice(1, -1);
|
|
166
110
|
let body = "";
|
|
167
111
|
for (let i = 0; i < inner.length; i++) {
|
|
@@ -185,11 +129,6 @@ function parseQuotedLiteral(raw) {
|
|
|
185
129
|
}
|
|
186
130
|
}
|
|
187
131
|
}
|
|
188
|
-
/**
|
|
189
|
-
* Calls `visit` with each index from `from` whose character sits outside a string literal, until it
|
|
190
|
-
* returns true. Returns that index, `src.length` when the scan ran out, or -1 when it ran out inside a
|
|
191
|
-
* literal left open.
|
|
192
|
-
*/
|
|
193
132
|
function scanOutsideStrings(src, from, visit) {
|
|
194
133
|
let quote;
|
|
195
134
|
for (let i = from; i < src.length; i++) {
|
|
@@ -289,7 +228,6 @@ export function parseSimpleFetchCall(snippet) {
|
|
|
289
228
|
return undefined;
|
|
290
229
|
return { path, method, start: match.index, end: close + 1 };
|
|
291
230
|
}
|
|
292
|
-
// `createWebApp(...)` returns the same `Server`, so a route chained onto it is a backend route.
|
|
293
231
|
const NIFRA_SERVER_CONSTRUCTION = /(?<![.\w])(?:server|createWebApp)\s*\(/;
|
|
294
232
|
const SERVER_CONSTRUCTION = /(?<![.\w])(?:server|createWebApp)\s*\(|new\s+Hono(?:<[^>]+>)?\s*\(/;
|
|
295
233
|
function isPotentialBackendSource(code, file, project) {
|
|
@@ -298,13 +236,6 @@ function isPotentialBackendSource(code, file, project) {
|
|
|
298
236
|
/(?:from\s*|import\s*)["']hono["']/.test(code) ||
|
|
299
237
|
(file !== undefined && project !== undefined && callsLocalServerFactory(code, file, project)));
|
|
300
238
|
}
|
|
301
|
-
/**
|
|
302
|
-
* A module that builds its server through a local helper - `newServer().get(...)` with `newServer`
|
|
303
|
-
* imported from a project file that calls `server()` - names neither `@nifrajs/core` nor `server(`
|
|
304
|
-
* itself. One import hop is followed: the imported module must construct a server, so a helper module
|
|
305
|
-
* that merely mentions `@nifrajs/core` (a schema re-export) does not turn every importer into a
|
|
306
|
-
* backend and its `client.get("/x")` calls into routes.
|
|
307
|
-
*/
|
|
308
239
|
function callsLocalServerFactory(code, file, project) {
|
|
309
240
|
for (const [local, binding] of namedImports(code)) {
|
|
310
241
|
if (!new RegExp(`(?<![.\\w$])${local.replaceAll("$", "\\$")}\\s*\\(`).test(code))
|
|
@@ -315,10 +246,6 @@ function callsLocalServerFactory(code, file, project) {
|
|
|
315
246
|
}
|
|
316
247
|
return false;
|
|
317
248
|
}
|
|
318
|
-
/**
|
|
319
|
-
* Literal route registrations in a file the backend-source gate turned away, so a route the scan
|
|
320
|
-
* could not cover can say where it probably lives. Nothing here is treated as a route.
|
|
321
|
-
*/
|
|
322
249
|
export function scanSkippedRouteText(file, content, project) {
|
|
323
250
|
const code = stripComments(content);
|
|
324
251
|
if (isPotentialBackendSource(code, file, project))
|
|
@@ -341,8 +268,6 @@ function scanRoutePattern(file, content, code, pattern, facts, verbs = HTTP_VERB
|
|
|
341
268
|
continue;
|
|
342
269
|
if (facts !== undefined) {
|
|
343
270
|
const source = facts.parse(file, content);
|
|
344
|
-
// A parseable source model is authoritative for candidate locations. If parsing is unavailable
|
|
345
|
-
// or the source is malformed, retain the lexical finding and fail closed.
|
|
346
271
|
if (source !== undefined &&
|
|
347
272
|
facts.isRouteRegistrationAt(source, m.index, method, path) !== true)
|
|
348
273
|
continue;
|
|
@@ -352,9 +277,6 @@ function scanRoutePattern(file, content, code, pattern, facts, verbs = HTTP_VERB
|
|
|
352
277
|
}
|
|
353
278
|
return out;
|
|
354
279
|
}
|
|
355
|
-
// Punctuators after which a `/` opens a regex literal rather than dividing. A `)` `]` or `}` is read
|
|
356
|
-
// as the end of an operand, so `/` after it divides - the rare statement-leading regex after a block
|
|
357
|
-
// is the cost of not tracking parser context.
|
|
358
280
|
const REGEX_AFTER = new Set([
|
|
359
281
|
"(",
|
|
360
282
|
",",
|
|
@@ -393,8 +315,6 @@ const REGEX_AFTER_WORD = new Set([
|
|
|
393
315
|
"instanceof",
|
|
394
316
|
]);
|
|
395
317
|
const isWordChar = (c) => c !== undefined && /[\w$]/.test(c);
|
|
396
|
-
/** Where a regex literal opened by the `/` at `i` ends (after its flags), or `undefined` when the
|
|
397
|
-
* literal does not close on its line - then the slash was division after all. */
|
|
398
318
|
function regexLiteralEnd(src, i) {
|
|
399
319
|
const n = src.length;
|
|
400
320
|
let j = i + 1;
|
|
@@ -426,13 +346,6 @@ function regexLiteralEnd(src, i) {
|
|
|
426
346
|
j++;
|
|
427
347
|
return j;
|
|
428
348
|
}
|
|
429
|
-
/**
|
|
430
|
-
* Blank comments, template-literal contents and regex-literal contents (and, with `quoted: "blank"`,
|
|
431
|
-
* single/double-quoted strings and every delimiter) while preserving every offset and newline.
|
|
432
|
-
* A small lexer, not a parser: a `/` opens a regex where an operand may start - after a punctuator,
|
|
433
|
-
* an operator keyword, or at the start of the file - so a quote inside a regex no longer derails
|
|
434
|
-
* the string state that follows.
|
|
435
|
-
*/
|
|
436
349
|
function maskSource(src, quoted) {
|
|
437
350
|
const out = src.split("");
|
|
438
351
|
const n = src.length;
|
|
@@ -441,7 +354,6 @@ function maskSource(src, quoted) {
|
|
|
441
354
|
if (out[k] !== "\n")
|
|
442
355
|
out[k] = " ";
|
|
443
356
|
};
|
|
444
|
-
// The last significant code token: a punctuator character, or a whole identifier/keyword.
|
|
445
357
|
let previous = "";
|
|
446
358
|
let i = 0;
|
|
447
359
|
while (i < n) {
|
|
@@ -470,7 +382,7 @@ function maskSource(src, quoted) {
|
|
|
470
382
|
j++;
|
|
471
383
|
}
|
|
472
384
|
if (quoted === "keep")
|
|
473
|
-
blank(i + 1, j);
|
|
385
|
+
blank(i + 1, j);
|
|
474
386
|
else
|
|
475
387
|
blank(i, Math.min(j + 1, n));
|
|
476
388
|
i = j + 1;
|
|
@@ -480,7 +392,7 @@ function maskSource(src, quoted) {
|
|
|
480
392
|
let j = i + 1;
|
|
481
393
|
while (j < n && src[j] !== c) {
|
|
482
394
|
if (src[j] === "\\")
|
|
483
|
-
j++;
|
|
395
|
+
j++;
|
|
484
396
|
j++;
|
|
485
397
|
}
|
|
486
398
|
if (quoted === "blank")
|
|
@@ -519,22 +431,9 @@ function maskSource(src, quoted) {
|
|
|
519
431
|
}
|
|
520
432
|
return out.join("");
|
|
521
433
|
}
|
|
522
|
-
/**
|
|
523
|
-
* Blank, with spaces (newlines preserved, so every byte offset - and line number - is unchanged):
|
|
524
|
-
* - `//` line comments and block comments;
|
|
525
|
-
* - the CONTENTS of backtick template literals - code-as-text (doc `CodeBlock` examples, code
|
|
526
|
-
* generators), never a real statement to lint.
|
|
527
|
-
* Single/double-quoted strings are KEPT (a real import/Response specifier lives in one); a regex
|
|
528
|
-
* literal keeps its slashes and loses its contents, so a quote inside one cannot open a string.
|
|
529
|
-
* Shared by the source scanners here and by `nifra doctor` ({@link ./doctor.ts}).
|
|
530
|
-
*/
|
|
531
434
|
export function stripComments(src) {
|
|
532
435
|
return maskSource(src, "keep");
|
|
533
436
|
}
|
|
534
|
-
/** Blank comments and every quoted/template/regex literal while preserving offsets. Unlike
|
|
535
|
-
* {@link stripComments}, this is a code-position mask: scanners use it to find a call expression in
|
|
536
|
-
* executable code, then inspect the original source for the call's literal argument. That prevents
|
|
537
|
-
* documentation strings such as `const example = 'client("/")'` from becoming diagnostics. */
|
|
538
437
|
export function codePositionMask(src) {
|
|
539
438
|
return maskSource(src, "blank");
|
|
540
439
|
}
|
|
@@ -544,10 +443,6 @@ const firstArgumentIndex = (content, callEnd) => {
|
|
|
544
443
|
index++;
|
|
545
444
|
return index;
|
|
546
445
|
};
|
|
547
|
-
// Read the literal URL path of a `fetch("/…")` call starting at `start` (the index of the leading `/`),
|
|
548
|
-
// stopping at the first quote / query / hash / template-expression boundary, and test it against the
|
|
549
|
-
// allowlist. A template like `/auth/${id}` matches on its literal head (`/auth`), so a dynamic sign-in URL
|
|
550
|
-
// is covered too. Match is segment-anchored - `/auth` blesses `/auth` and `/auth/**`, never `/authors`.
|
|
551
446
|
function matchesExternalMount(content, start, mounts) {
|
|
552
447
|
let end = start;
|
|
553
448
|
while (end < content.length) {
|
|
@@ -559,15 +454,11 @@ function matchesExternalMount(content, start, mounts) {
|
|
|
559
454
|
end++;
|
|
560
455
|
}
|
|
561
456
|
const path = content.slice(start, end);
|
|
562
|
-
// A `..` segment means the runtime path escapes the literal prefix (`/auth/../api/admin` resolves to
|
|
563
|
-
// `/api/admin`), so it must NOT be blessed by an `/auth` mount - never let traversal hide a real own-API
|
|
564
|
-
// fetch. Match is otherwise segment-anchored (`/auth` blesses `/auth` and `/auth/**`, never `/authors`).
|
|
565
457
|
try {
|
|
566
458
|
if (path.split("/").some((segment) => decodeURIComponent(segment) === ".."))
|
|
567
459
|
return false;
|
|
568
460
|
}
|
|
569
461
|
catch {
|
|
570
|
-
// A malformed escape is not a prefix we can prove stays inside the external mount.
|
|
571
462
|
return false;
|
|
572
463
|
}
|
|
573
464
|
return mounts.some((prefix) => path === prefix || path.startsWith(`${prefix}/`));
|
|
@@ -598,9 +489,6 @@ function parseStaticPropertyName(raw) {
|
|
|
598
489
|
}
|
|
599
490
|
return undefined;
|
|
600
491
|
}
|
|
601
|
-
/** Return a statically named property from a plain object literal. Deliberately does not follow
|
|
602
|
-
* spreads, identifiers, or helper calls: only an inline literal proves this fetch is Nifra's page-data
|
|
603
|
-
* transport rather than an arbitrary same-origin API request. */
|
|
604
492
|
function staticObjectProperty(raw, name) {
|
|
605
493
|
if (raw === undefined)
|
|
606
494
|
return undefined;
|
|
@@ -628,18 +516,9 @@ function hasLiteralNifraDataHeader(content, openParen) {
|
|
|
628
516
|
const headers = staticObjectProperty(args[1], "headers");
|
|
629
517
|
return staticObjectProperty(headers, "x-nifra-data") !== undefined;
|
|
630
518
|
}
|
|
631
|
-
/** Scan one file's text for hand-rolled own-API `fetch()` calls. Pure + line-accurate. `externalMounts`
|
|
632
|
-
* are intentional non-typed mount prefixes (from `nifra.check.json`, e.g. a mounted better-auth owning
|
|
633
|
-
* `/auth/**`) - a relative fetch into one is deliberate, not drift, so it's skipped. A fetch with an
|
|
634
|
-
* inline literal `x-nifra-data` header is Nifra's page-loader transport, not a backend API call, and is
|
|
635
|
-
* skipped too. */
|
|
636
519
|
export function scanFetchText(file, content, externalMounts = []) {
|
|
637
520
|
return ownPathCalls(file, content, GLOBAL_FETCH_CALL, externalMounts, (m) => hasLiteralNifraDataHeader(content, m.index + m[0].lastIndexOf("(")));
|
|
638
521
|
}
|
|
639
|
-
/**
|
|
640
|
-
* A finding for each `pattern` match in code whose first argument is a literal own-API path (`"/…"`,
|
|
641
|
-
* not `"//…"`), unless it falls under one of `externalMounts` or `skip` passes it.
|
|
642
|
-
*/
|
|
643
522
|
function ownPathCalls(file, content, pattern, externalMounts, skip) {
|
|
644
523
|
const out = [];
|
|
645
524
|
const lines = content.split("\n");
|
|
@@ -660,26 +539,11 @@ function ownPathCalls(file, content, pattern, externalMounts, skip) {
|
|
|
660
539
|
}
|
|
661
540
|
return out;
|
|
662
541
|
}
|
|
663
|
-
// `new EventSource(` / `new WebSocket(` - a hand-rolled subscription to this app's own streaming
|
|
664
|
-
// surface. `new` is required so a local binding named `WebSocket` (a wrapper, a mock) stays quiet;
|
|
665
|
-
// The word boundary excludes member calls and identifiers such as `renew WebSocket(`; `new` keeps
|
|
666
|
-
// local wrapper bindings quiet while still matching the platform constructors.
|
|
667
542
|
const STREAM_CONSTRUCT = /(?<![\w$])new\s+(?:EventSource|WebSocket)\s*\(/g;
|
|
668
|
-
/** Scan one file's text for hand-rolled own-API `EventSource`/`WebSocket` constructions. Pure +
|
|
669
|
-
* line-accurate. Same contract as {@link scanFetchText}: only a relative-path first argument
|
|
670
|
-
* (`"/…"` not `"//…"`, no scheme) is this app's API, so absolute `ws(s)://` / `http(s)://` URLs
|
|
671
|
-
* stay quiet exactly like absolute fetch URLs do. `externalMounts` and the relative-URL rule behave
|
|
672
|
-
* identically. A relative `new WebSocket("/…")` throws in browsers (the WS constructor needs an
|
|
673
|
-
* absolute URL), so a hit is either broken or bypassing `api.*.ws()` - either way the typed call
|
|
674
|
-
* (`api.*.subscribe()` for `app.sse()` routes, `api.*.ws()` for `app.ws()` routes) is the fix, and
|
|
675
|
-
* it keeps the compiler catching drift. */
|
|
676
543
|
export function scanStreamText(file, content, externalMounts = []) {
|
|
677
544
|
return ownPathCalls(file, content, STREAM_CONSTRUCT, externalMounts);
|
|
678
545
|
}
|
|
679
|
-
|
|
680
|
-
export function scanStaticRouteText(file, content, facts,
|
|
681
|
-
/** Project files by forward-slash relative path, to resolve a path constant imported from one. */
|
|
682
|
-
project) {
|
|
546
|
+
export function scanStaticRouteText(file, content, facts, project) {
|
|
683
547
|
const code = stripComments(content);
|
|
684
548
|
if (!isPotentialBackendSource(code, file, project))
|
|
685
549
|
return [];
|
|
@@ -690,7 +554,6 @@ project) {
|
|
|
690
554
|
...scanRouteArguments(file, content, facts, project).routes,
|
|
691
555
|
].sort(bySite);
|
|
692
556
|
}
|
|
693
|
-
/** The end of the quoted literal opening `text`, or -1 when it does not close on this line. */
|
|
694
557
|
function literalEnd(text) {
|
|
695
558
|
const quote = text[0];
|
|
696
559
|
for (let i = 1; i < text.length; i++) {
|
|
@@ -701,18 +564,12 @@ function literalEnd(text) {
|
|
|
701
564
|
}
|
|
702
565
|
return -1;
|
|
703
566
|
}
|
|
704
|
-
/** The index after the whitespace run at `from`. */
|
|
705
567
|
function skipSpace(text, from) {
|
|
706
568
|
let i = from;
|
|
707
569
|
while (i < text.length && (text[i] === " " || text[i] === "\t"))
|
|
708
570
|
i++;
|
|
709
571
|
return i;
|
|
710
572
|
}
|
|
711
|
-
/**
|
|
712
|
-
* Read `[export ]const NAME[: T] = <init>` written at column 0, so a function-local `const`, which is
|
|
713
|
-
* indented, never stands in for a module-level one. The shape is read from the comment-stripped
|
|
714
|
-
* line; the literal itself from the source line, since stripping blanks template contents.
|
|
715
|
-
*/
|
|
716
573
|
function moduleConstantOn(code, source) {
|
|
717
574
|
const exported = code.startsWith("export ");
|
|
718
575
|
let i = exported ? skipSpace(code, 7) : 0;
|
|
@@ -751,7 +608,6 @@ function moduleConstants(code, source) {
|
|
|
751
608
|
});
|
|
752
609
|
return constants;
|
|
753
610
|
}
|
|
754
|
-
/** Local name → the export it imports and from where, for value imports only. */
|
|
755
611
|
function namedImports(code) {
|
|
756
612
|
const imports = new Map();
|
|
757
613
|
NAMED_IMPORTS.lastIndex = 0;
|
|
@@ -769,7 +625,6 @@ function namedImports(code) {
|
|
|
769
625
|
}
|
|
770
626
|
return imports;
|
|
771
627
|
}
|
|
772
|
-
/** The project file a relative import names, tried the way a TypeScript-aware bundler resolves it. */
|
|
773
628
|
function projectModule(project, fromFile, specifier) {
|
|
774
629
|
if (!specifier.startsWith("./") && !specifier.startsWith("../"))
|
|
775
630
|
return undefined;
|
|
@@ -777,13 +632,6 @@ function projectModule(project, fromFile, specifier) {
|
|
|
777
632
|
const stem = base.replace(/\.(?:m?js|jsx)$/, "");
|
|
778
633
|
return [base, `${stem}.ts`, `${stem}.tsx`, `${stem}.mts`, `${base}/index.ts`].find((candidate) => project.has(candidate));
|
|
779
634
|
}
|
|
780
|
-
/**
|
|
781
|
-
* Route registrations whose path is a name or a template rather than a quoted literal. A name bound
|
|
782
|
-
* to a module-level string `const`, here or imported from a project file, and a template with no
|
|
783
|
-
* substitution resolve to routes; any other template, and a module-level or imported name nifra
|
|
784
|
-
* cannot read, is unresolved. A name bound anywhere else (a parameter, a local) is not reported:
|
|
785
|
-
* nothing marks such a call as a route rather than a `map.get(key, fallback)`.
|
|
786
|
-
*/
|
|
787
635
|
function scanRouteArguments(file, content, facts, project, verbs = HTTP_VERBS) {
|
|
788
636
|
const routes = [];
|
|
789
637
|
const unresolved = [];
|
|
@@ -825,7 +673,6 @@ function scanRouteArguments(file, content, facts, project, verbs = HTTP_VERBS) {
|
|
|
825
673
|
continue;
|
|
826
674
|
path = constant?.value;
|
|
827
675
|
}
|
|
828
|
-
// A name that reads as something other than a path (`settings.get(KEY, fallback)`) is no route.
|
|
829
676
|
if (path !== undefined && (!path.startsWith("/") || path.startsWith("//")))
|
|
830
677
|
continue;
|
|
831
678
|
if (facts !== undefined) {
|
|
@@ -843,17 +690,13 @@ function scanRouteArguments(file, content, facts, project, verbs = HTTP_VERBS) {
|
|
|
843
690
|
}
|
|
844
691
|
return { routes, unresolved };
|
|
845
692
|
}
|
|
846
|
-
/** Route registrations whose path the static scan cannot resolve - see {@link scanRouteArguments}. */
|
|
847
693
|
export function scanUnresolvedRoutePaths(file, content, project, facts) {
|
|
848
694
|
return [
|
|
849
695
|
...scanRouteArguments(file, content, facts, project).unresolved,
|
|
850
696
|
...scanRouteArguments(file, content, facts, project, SOCKET_VERB).unresolved,
|
|
851
697
|
].sort(bySite);
|
|
852
698
|
}
|
|
853
|
-
|
|
854
|
-
export function scanStaticSocketText(file, content, facts,
|
|
855
|
-
/** Project files by forward-slash relative path, to resolve a path constant imported from one. */
|
|
856
|
-
project) {
|
|
699
|
+
export function scanStaticSocketText(file, content, facts, project) {
|
|
857
700
|
const code = stripComments(content);
|
|
858
701
|
if (!isPotentialBackendSource(code, file, project))
|
|
859
702
|
return [];
|
|
@@ -863,7 +706,6 @@ project) {
|
|
|
863
706
|
...scanRouteArguments(file, content, facts, project, SOCKET_VERB).routes,
|
|
864
707
|
].sort(bySite);
|
|
865
708
|
}
|
|
866
|
-
/** Routes from `all()` and `method()`, one per literal method name; a computed name is not guessed. */
|
|
867
709
|
function scanMethodRoutes(file, content, code, facts) {
|
|
868
710
|
const out = [];
|
|
869
711
|
const lines = content.split("\n");
|
|
@@ -873,8 +715,6 @@ function scanMethodRoutes(file, content, code, facts) {
|
|
|
873
715
|
return;
|
|
874
716
|
if (facts !== undefined) {
|
|
875
717
|
const source = facts.parse(file, content);
|
|
876
|
-
// Same contract as a member-call registration: a parsed source is authoritative, an
|
|
877
|
-
// unparseable one keeps the lexical finding.
|
|
878
718
|
if (source !== undefined &&
|
|
879
719
|
facts.isFunctionRouteCallAt(source, index, callee, pathIndex, path) !== true)
|
|
880
720
|
return;
|
|
@@ -887,7 +727,6 @@ function scanMethodRoutes(file, content, code, facts) {
|
|
|
887
727
|
ALL_ROUTES.lastIndex = 0;
|
|
888
728
|
for (let m = ALL_ROUTES.exec(code); m !== null; m = ALL_ROUTES.exec(code)) {
|
|
889
729
|
const double = m[1] !== undefined;
|
|
890
|
-
// all() also registers QUERY, which has no builder of its own and so is not in HTTP_VERBS.
|
|
891
730
|
collect(m.index, "all", 0, double ? m[1] : m[2], double ? '"' : "'", [...HTTP_VERBS, "QUERY"]);
|
|
892
731
|
}
|
|
893
732
|
METHOD_ROUTES.lastIndex = 0;
|
|
@@ -902,22 +741,6 @@ function scanMethodRoutes(file, content, code, facts) {
|
|
|
902
741
|
}
|
|
903
742
|
return out;
|
|
904
743
|
}
|
|
905
|
-
/**
|
|
906
|
-
* SQL built by interpolating a value into the statement text. The value is not a parameter, it is
|
|
907
|
-
* STATEMENT, so anything the caller controls can end the literal and continue as SQL.
|
|
908
|
-
*
|
|
909
|
-
* Two things this deliberately does not flag, because both are safe and flagging them would train
|
|
910
|
-
* people to ignore the rule:
|
|
911
|
-
*
|
|
912
|
-
* - A TAGGED template - ``sql`... ${id} ...` `` in postgres.js, drizzle or kysely. The tag receives the
|
|
913
|
-
* substitutions separately and binds them; that is the parameterised form, not a bypass of it.
|
|
914
|
-
* - A literal with no substitution at all. `db.query("SELECT … WHERE id = ?")` is the shape being
|
|
915
|
-
* argued for.
|
|
916
|
-
*
|
|
917
|
-
* A SQL keyword is required in the literal, so `cache.query(`user:${id}`)` stays quiet. The named
|
|
918
|
-
* escape hatches (`$queryRawUnsafe`, `sql.unsafe`) are flagged on the call alone: their whole purpose
|
|
919
|
-
* is to take a statement as text, and a substitution in one is the exact thing the name warns about.
|
|
920
|
-
*/
|
|
921
744
|
const SQL_METHODS = new Set([
|
|
922
745
|
"query",
|
|
923
746
|
"queryRaw",
|
|
@@ -932,9 +755,6 @@ const SQL_METHODS = new Set([
|
|
|
932
755
|
]);
|
|
933
756
|
const SQL_KEYWORD = /\b(select|insert\s+into|update|delete\s+from|drop\s+table|create\s+table|alter\s+table|truncate|from|where|values|set|join|union)\b/i;
|
|
934
757
|
const ALWAYS_UNSAFE = new Set(["unsafe", "$queryRawUnsafe", "$executeRawUnsafe", "raw"]);
|
|
935
|
-
/** Driver calls that take a statement under names that are everyday words elsewhere (`map.get`,
|
|
936
|
-
* `client.get("/users/update")`): node-sqlite3's `all`/`get`/`each` and pg-promise's result-shaping
|
|
937
|
-
* calls. One of these, and any bare call, is judged by whether its text starts like a statement. */
|
|
938
758
|
const DRIVER_READ_METHODS = new Set([
|
|
939
759
|
"all",
|
|
940
760
|
"get",
|
|
@@ -950,9 +770,6 @@ const DRIVER_READ_METHODS = new Set([
|
|
|
950
770
|
"multiResult",
|
|
951
771
|
]);
|
|
952
772
|
const STATEMENT_START = /^\s*\(?\s*(?:select|insert|update|delete|with|replace|merge|create|drop|alter|truncate|pragma)\s/i;
|
|
953
|
-
/** Read one module's top-level `const` bindings and its import/export edges. Pure syntax - no checker,
|
|
954
|
-
* no filesystem. Destructured names, `let`, `var`, and anything nested stay out on purpose: a
|
|
955
|
-
* module-scope `const` is the only form that provably cannot carry request data. */
|
|
956
773
|
function sqlModuleScope(ts, id, source) {
|
|
957
774
|
const consts = new Map();
|
|
958
775
|
const imports = new Map();
|
|
@@ -980,8 +797,6 @@ function sqlModuleScope(ts, id, source) {
|
|
|
980
797
|
if (!ts.isStringLiteral(statement.moduleSpecifier))
|
|
981
798
|
continue;
|
|
982
799
|
const bindings = clause.namedBindings;
|
|
983
|
-
// Only `import { X }` / `import { X as local }`. A default or namespace import binds a value
|
|
984
|
-
// whose contents this scan cannot prove, so it stays unbound and every use of it flags.
|
|
985
800
|
if (bindings === undefined || !ts.isNamedImports(bindings))
|
|
986
801
|
continue;
|
|
987
802
|
for (const element of bindings.elements) {
|
|
@@ -1001,8 +816,6 @@ function sqlModuleScope(ts, id, source) {
|
|
|
1001
816
|
continue;
|
|
1002
817
|
const clause = statement.exportClause;
|
|
1003
818
|
if (clause === undefined) {
|
|
1004
|
-
// No clause and a specifier is `export * from "./m"`. `export * as ns from "./m"` carries a
|
|
1005
|
-
// NamespaceExport clause instead and falls out below, unresolved, which is what we want.
|
|
1006
819
|
if (from !== undefined)
|
|
1007
820
|
starExports.push(from.text);
|
|
1008
821
|
continue;
|
|
@@ -1025,9 +838,6 @@ export const createSqlImports = (load) => ({
|
|
|
1025
838
|
load,
|
|
1026
839
|
scopes: new Map(),
|
|
1027
840
|
});
|
|
1028
|
-
/** Parse a module for the SQL scan, or `undefined` when it does not parse. Malformed source is already
|
|
1029
|
-
* a typecheck failure; parser recovery nodes are not evidence of anything, so a file that fails to
|
|
1030
|
-
* parse contributes no findings and proves no constant. */
|
|
1031
841
|
function parseSqlSource(ts, file, content) {
|
|
1032
842
|
const kind = scriptKindOf(ts, file);
|
|
1033
843
|
let source;
|
|
@@ -1035,18 +845,12 @@ function parseSqlSource(ts, file, content) {
|
|
|
1035
845
|
source = ts.createSourceFile(file, content, ts.ScriptTarget.Latest, true, kind);
|
|
1036
846
|
}
|
|
1037
847
|
catch {
|
|
1038
|
-
// TypeScript 7 parses only the files its session preloaded; an imported module outside that set
|
|
1039
|
-
// proves no constant, like one that does not parse.
|
|
1040
848
|
return undefined;
|
|
1041
849
|
}
|
|
1042
850
|
const parseDiagnostics = source.parseDiagnostics;
|
|
1043
851
|
return parseDiagnostics !== undefined && parseDiagnostics.length > 0 ? undefined : source;
|
|
1044
852
|
}
|
|
1045
|
-
/** Module-boundary hops one name may cross. Barrels are why it is not 1: `route → index → fragments`
|
|
1046
|
-
* already spends two, and the third leaves room for one more layer without letting the scan wander the
|
|
1047
|
-
* module graph. Past the cap the name is unresolved, so the interpolation flags. */
|
|
1048
853
|
const SQL_IMPORT_HOPS = 3;
|
|
1049
|
-
/** Load + parse the module a specifier names, through the run's cache. */
|
|
1050
854
|
function loadSqlModuleScope(ts, imports, fromModule, specifier) {
|
|
1051
855
|
const loaded = imports.load(fromModule, specifier);
|
|
1052
856
|
if (loaded === undefined)
|
|
@@ -1058,17 +862,6 @@ function loadSqlModuleScope(ts, imports, fromModule, specifier) {
|
|
|
1058
862
|
imports.scopes.set(loaded.id, scope);
|
|
1059
863
|
return scope;
|
|
1060
864
|
}
|
|
1061
|
-
/**
|
|
1062
|
-
* Follow an exported name to its `const` initializer, across re-export hops.
|
|
1063
|
-
*
|
|
1064
|
-
* Handles the three forms a fragments module actually uses: `export const NAME = …`, the two-statement
|
|
1065
|
-
* `const NAME = …; export { NAME }` (including the pass-through `import { A } …; export { A }`), and
|
|
1066
|
-
* barrels - `export { X } from "./m"` and `export * from "./m"`. Bounded by {@link SQL_IMPORT_HOPS} and
|
|
1067
|
-
* a per-chain visited set, so a cyclic barrel terminates instead of recursing.
|
|
1068
|
-
*
|
|
1069
|
-
* Two `export *` sources providing the same name is a conflict, and the scan refuses rather than
|
|
1070
|
-
* picking one: guessing here would silence a real finding.
|
|
1071
|
-
*/
|
|
1072
865
|
function resolveExportedConst(ts, imports, scope, name, hops, seen) {
|
|
1073
866
|
if (hops > SQL_IMPORT_HOPS)
|
|
1074
867
|
return undefined;
|
|
@@ -1087,9 +880,6 @@ function resolveExportedConst(ts, imports, scope, name, hops, seen) {
|
|
|
1087
880
|
const initializer = scope.consts.get(local);
|
|
1088
881
|
if (initializer !== undefined)
|
|
1089
882
|
return { expression: initializer, scope };
|
|
1090
|
-
// `import { A } from "./a"; export { A }` - the same pass-through as `export { A } from "./a"`,
|
|
1091
|
-
// written in two statements. Anything else the name could be (a `let`, a function, a class) has no
|
|
1092
|
-
// initializer in `consts` and no import edge, so it lands on `undefined` and flags.
|
|
1093
883
|
const via = scope.imports.get(local);
|
|
1094
884
|
return via === undefined ? undefined : follow(via);
|
|
1095
885
|
}
|
|
@@ -1107,13 +897,6 @@ function resolveExportedConst(ts, imports, scope, name, hops, seen) {
|
|
|
1107
897
|
}
|
|
1108
898
|
return found;
|
|
1109
899
|
}
|
|
1110
|
-
/** Whether `name`, read at `at`, might be re-declared by anything between the read and module scope.
|
|
1111
|
-
* Conservative on purpose: the OUTERMOST enclosing function/block subtree is scanned for ANY binding
|
|
1112
|
-
* of the name (parameter, `var`/`let`/`const`, catch, local function, destructuring element) - so a
|
|
1113
|
-
* hoisted `var` in a sibling block, or a binding in a branch that never runs, still refuses
|
|
1114
|
-
* resolution. Over-refusal flags a safe line (the pre-feature behavior); under-refusal would resolve
|
|
1115
|
-
* the wrong binding, which is why the cheap-and-broad scan wins over scope simulation. A use with no
|
|
1116
|
-
* enclosing function or block reads module scope directly and cannot be shadowed. */
|
|
1117
900
|
function isShadowedAt(ts, at, name) {
|
|
1118
901
|
let scope;
|
|
1119
902
|
for (let node = at.parent; node !== undefined; node = node.parent) {
|
|
@@ -1147,18 +930,6 @@ function isShadowedAt(ts, at, name) {
|
|
|
1147
930
|
return found;
|
|
1148
931
|
}
|
|
1149
932
|
const CONST_RESOLUTION_DEPTH = 5;
|
|
1150
|
-
/**
|
|
1151
|
-
* Resolve an interpolated expression to compile-time text, or `undefined` when it can carry runtime
|
|
1152
|
-
* data. Pure syntax, no type checker - the same honest limit the rule already documents. What
|
|
1153
|
-
* resolves: string/number literals, no-substitution templates, templates whose every span resolves,
|
|
1154
|
-
* ternaries with both branches resolvable (BOTH branch texts are returned, so a hostile keyword in
|
|
1155
|
-
* either still feeds the keyword scan), `as`/`satisfies` wrappers, a `const` whose initializer
|
|
1156
|
-
* resolves (the nearest binding: function or block scope, then module scope; recursively,
|
|
1157
|
-
* depth-capped), `.join(sep?)` over an array {@link staticArrayItems} proves, and - when
|
|
1158
|
-
* `scope.imports` is configured - a module `const` imported by name from another in-project module.
|
|
1159
|
-
* Everything else - `let`, a parameter, any other call, a member access, a shadowed name, a
|
|
1160
|
-
* bare-specifier import - stays unresolved and the interpolation is flagged exactly as before.
|
|
1161
|
-
*/
|
|
1162
933
|
function resolveStaticSqlText(ts, node, scope, depth) {
|
|
1163
934
|
if (depth > CONST_RESOLUTION_DEPTH)
|
|
1164
935
|
return undefined;
|
|
@@ -1200,13 +971,8 @@ function resolveStaticSqlText(ts, node, scope, depth) {
|
|
|
1200
971
|
return resolveStaticSqlText(ts, local, scope, depth + 1);
|
|
1201
972
|
const initializer = scope.module.consts.get(node.text);
|
|
1202
973
|
const edge = initializer === undefined ? scope.module.imports.get(node.text) : undefined;
|
|
1203
|
-
// Membership first: `isShadowedAt` walks a subtree, and most identifiers in a query are neither a
|
|
1204
|
-
// module const nor an import binding.
|
|
1205
974
|
if (initializer === undefined && edge === undefined)
|
|
1206
975
|
return undefined;
|
|
1207
|
-
// Shadowing is a property of where the identifier is WRITTEN, so one check is right on both sides
|
|
1208
|
-
// of an import hop: an initializer in the imported module sits at module scope with nothing above
|
|
1209
|
-
// it to shadow it, while a use inside a function in this file is still refused.
|
|
1210
976
|
if (isShadowedAt(ts, node, node.text))
|
|
1211
977
|
return undefined;
|
|
1212
978
|
if (initializer !== undefined)
|
|
@@ -1219,18 +985,10 @@ function resolveStaticSqlText(ts, node, scope, depth) {
|
|
|
1219
985
|
const exported = resolveExportedConst(ts, scope.imports, target, edge.exported, 1, new Set());
|
|
1220
986
|
if (exported === undefined)
|
|
1221
987
|
return undefined;
|
|
1222
|
-
// The imported initializer's own identifiers read THAT module's consts, never this file's. A
|
|
1223
|
-
// caller that happens to have its own `const DIR` must not silently supply the fragment's `DIR`,
|
|
1224
|
-
// which is the one way cross-module resolution could resolve to text nobody wrote.
|
|
1225
988
|
return resolveStaticSqlText(ts, exported.expression, { module: exported.scope, imports: scope.imports }, depth + 1);
|
|
1226
989
|
}
|
|
1227
990
|
return undefined;
|
|
1228
991
|
}
|
|
1229
|
-
/**
|
|
1230
|
-
* The initializer of the `const` a function or block scope binds `node` to, `"shadow"` when the
|
|
1231
|
-
* nearest such binding is anything else (a parameter, `let`, `var`, destructuring), or `undefined`
|
|
1232
|
-
* when no scope below the module binds it - the module-scope lookup applies then.
|
|
1233
|
-
*/
|
|
1234
992
|
function localConstInitializer(ts, node) {
|
|
1235
993
|
const source = node.getSourceFile();
|
|
1236
994
|
for (let scope = node.parent; scope !== undefined; scope = scope.parent) {
|
|
@@ -1253,7 +1011,6 @@ const unwrapExpression = (ts, node) => {
|
|
|
1253
1011
|
}
|
|
1254
1012
|
return current;
|
|
1255
1013
|
};
|
|
1256
|
-
/** `Object.freeze([...])` with `Object` unshadowed: the one array form no later code can change. */
|
|
1257
1014
|
function frozenArrayLiteral(ts, node) {
|
|
1258
1015
|
const call = unwrapExpression(ts, node);
|
|
1259
1016
|
if (!ts.isCallExpression(call) || call.arguments.length !== 1)
|
|
@@ -1270,13 +1027,6 @@ function frozenArrayLiteral(ts, node) {
|
|
|
1270
1027
|
return ts.isArrayLiteralExpression(array) ? array : undefined;
|
|
1271
1028
|
}
|
|
1272
1029
|
const ARRAY_READS = new Set(["join", "includes", "indexOf"]);
|
|
1273
|
-
/**
|
|
1274
|
-
* Whether every use of `name` in `source` other than its declaration is a call of `.join(`,
|
|
1275
|
-
* `.includes(` or `.indexOf(`, or a `.length` read: then nothing pushes to, sorts, exports or hands
|
|
1276
|
-
* away the array, so it still holds its literal elements. With `pushed`, a `.push(...)` is accepted
|
|
1277
|
-
* too and its arguments collected, for the caller to prove (the `where.push(...)` builder). A
|
|
1278
|
-
* same-named binding elsewhere only adds uses, so the answer can only err toward refusing.
|
|
1279
|
-
*/
|
|
1280
1030
|
function onlyReadsArray(ts, source, name, declaration, pushed) {
|
|
1281
1031
|
let ok = true;
|
|
1282
1032
|
const visit = (node) => {
|
|
@@ -1298,7 +1048,6 @@ function onlyReadsArray(ts, source, name, declaration, pushed) {
|
|
|
1298
1048
|
ok = false;
|
|
1299
1049
|
else
|
|
1300
1050
|
pushed.push(...call.arguments);
|
|
1301
|
-
// An argument can mention the array again; those uses are checked as well.
|
|
1302
1051
|
for (const argument of call.arguments)
|
|
1303
1052
|
visit(argument);
|
|
1304
1053
|
return;
|
|
@@ -1317,7 +1066,6 @@ function onlyReadsArray(ts, source, name, declaration, pushed) {
|
|
|
1317
1066
|
visit(source);
|
|
1318
1067
|
return ok;
|
|
1319
1068
|
}
|
|
1320
|
-
/** `node` as the target of an assignment, `++`/`--`, or `delete`. */
|
|
1321
1069
|
function isWrittenTo(ts, node) {
|
|
1322
1070
|
const parent = node.parent;
|
|
1323
1071
|
if (ts.isBinaryExpression(parent) &&
|
|
@@ -1332,12 +1080,6 @@ function isWrittenTo(ts, node) {
|
|
|
1332
1080
|
}
|
|
1333
1081
|
return ts.isDeleteExpression(parent);
|
|
1334
1082
|
}
|
|
1335
|
-
/**
|
|
1336
|
-
* The element texts of an array `receiver` names, when the array provably still holds them: an
|
|
1337
|
-
* inline literal, `Object.freeze([...])` anywhere it is bound or imported from, or a `const` array
|
|
1338
|
-
* literal bound in this file, not exported, and only ever read ({@link onlyReadsArray}). `as const`
|
|
1339
|
-
* is type-only and proves nothing.
|
|
1340
|
-
*/
|
|
1341
1083
|
function staticArrayItems(ts, receiver, scope, depth) {
|
|
1342
1084
|
const node = unwrapExpression(ts, receiver);
|
|
1343
1085
|
let array = ts.isArrayLiteralExpression(node) ? node : frozenArrayLiteral(ts, node);
|
|
@@ -1360,7 +1102,6 @@ function staticArrayItems(ts, receiver, scope, depth) {
|
|
|
1360
1102
|
: resolveExportedConst(ts, scope.imports, target, edge.exported, 1, new Set());
|
|
1361
1103
|
if (found === undefined)
|
|
1362
1104
|
return undefined;
|
|
1363
|
-
// Another module's array is accepted only frozen: its own file may mutate it.
|
|
1364
1105
|
array = frozenArrayLiteral(ts, found.expression);
|
|
1365
1106
|
itemScope = { module: found.scope, imports: scope.imports };
|
|
1366
1107
|
}
|
|
@@ -1380,7 +1121,6 @@ function staticArrayItems(ts, receiver, scope, depth) {
|
|
|
1380
1121
|
if (array === undefined)
|
|
1381
1122
|
return undefined;
|
|
1382
1123
|
const items = [];
|
|
1383
|
-
// What the array may hold: its literal elements, and anything pushed onto it in any order.
|
|
1384
1124
|
for (const element of [...array.elements, ...pushed]) {
|
|
1385
1125
|
if (ts.isSpreadElement(element) || ts.isOmittedExpression(element))
|
|
1386
1126
|
return undefined;
|
|
@@ -1391,7 +1131,6 @@ function staticArrayItems(ts, receiver, scope, depth) {
|
|
|
1391
1131
|
}
|
|
1392
1132
|
return items;
|
|
1393
1133
|
}
|
|
1394
|
-
/** `items.join(sep?)` over a {@link staticArrayItems} array with a literal or absent separator. */
|
|
1395
1134
|
function resolveStaticJoin(ts, call, scope, depth) {
|
|
1396
1135
|
const callee = call.expression;
|
|
1397
1136
|
if (!ts.isPropertyAccessExpression(callee) ||
|
|
@@ -1412,16 +1151,10 @@ function resolveStaticJoin(ts, call, scope, depth) {
|
|
|
1412
1151
|
mappedItem(ts, callee.expression, scope, depth + 1);
|
|
1413
1152
|
return items?.join(separator);
|
|
1414
1153
|
}
|
|
1415
|
-
/**
|
|
1416
|
-
* `xs.map(fn)`, `xs.flatMap(fn)` or `Array.from(src, fn)` whose callback returns text that resolves
|
|
1417
|
-
* for every element - `(_, i) => \`($${i * 2 + 1}, $${i * 2 + 2})\``, the batch `VALUES` idiom. How
|
|
1418
|
-
* many items there are is runtime data, what each one says is not, so one item stands for all.
|
|
1419
|
-
*/
|
|
1420
1154
|
function mappedItem(ts, receiver, scope, depth) {
|
|
1421
1155
|
const call = unwrapExpression(ts, receiver);
|
|
1422
1156
|
if (!ts.isCallExpression(call) || !ts.isPropertyAccessExpression(call.expression))
|
|
1423
1157
|
return undefined;
|
|
1424
|
-
// Only these return what the callback returns; `filter` and the rest hand back the elements.
|
|
1425
1158
|
const method = call.expression.name.text;
|
|
1426
1159
|
const argument = indexCallbackArgument(ts, call);
|
|
1427
1160
|
if (argument === undefined || !(method === "map" || method === "flatMap" || argument === 1))
|
|
@@ -1438,7 +1171,6 @@ function mappedItem(ts, receiver, scope, depth) {
|
|
|
1438
1171
|
const text = body === undefined ? undefined : resolveStaticSqlText(ts, body, scope, depth + 1);
|
|
1439
1172
|
return text === undefined ? undefined : [text];
|
|
1440
1173
|
}
|
|
1441
|
-
/** Array methods whose callback receives the element's index, and where in the callback it is. */
|
|
1442
1174
|
const INDEX_PARAMETER = new Map([
|
|
1443
1175
|
["map", 1],
|
|
1444
1176
|
["flatMap", 1],
|
|
@@ -1451,8 +1183,6 @@ const INDEX_PARAMETER = new Map([
|
|
|
1451
1183
|
["reduce", 2],
|
|
1452
1184
|
["reduceRight", 2],
|
|
1453
1185
|
]);
|
|
1454
|
-
/** Which argument of `call` is a callback handed an array index: the first for `xs.map(fn)` and its
|
|
1455
|
-
* kin, the second for an unshadowed `Array.from(src, fn)`. */
|
|
1456
1186
|
function indexCallbackArgument(ts, call) {
|
|
1457
1187
|
const callee = call.expression;
|
|
1458
1188
|
if (!ts.isPropertyAccessExpression(callee) || callee.questionDotToken !== undefined)
|
|
@@ -1466,11 +1196,6 @@ function indexCallbackArgument(ts, call) {
|
|
|
1466
1196
|
? 1
|
|
1467
1197
|
: undefined;
|
|
1468
1198
|
}
|
|
1469
|
-
/**
|
|
1470
|
-
* `"1"` for a span written right after a `$` whose expression provably evaluates to a number: a
|
|
1471
|
-
* Postgres placeholder index (`$${i + 1}`), which binds a parameter and can carry no SQL. Any string
|
|
1472
|
-
* there could, so anything not proved numeric stays unresolved.
|
|
1473
|
-
*/
|
|
1474
1199
|
function placeholderNumber(ts, before, node, depth) {
|
|
1475
1200
|
return before.endsWith("$") && isNumericExpression(ts, node, depth) ? "1" : undefined;
|
|
1476
1201
|
}
|
|
@@ -1488,14 +1213,6 @@ const NUMERIC_OPERATORS = (ts) => new Set([
|
|
|
1488
1213
|
ts.SyntaxKind.GreaterThanGreaterThanGreaterThanToken,
|
|
1489
1214
|
]);
|
|
1490
1215
|
const NUMBER_FUNCTIONS = new Set(["Number", "parseInt", "parseFloat"]);
|
|
1491
|
-
/**
|
|
1492
|
-
* Whether an expression evaluates to a number whatever its inputs hold. Every arithmetic operator but
|
|
1493
|
-
* `+` converts its operands, so `i * 2` is a number even if `i` were a string; `+` is one only when
|
|
1494
|
-
* both sides are. A name proves it when it is a callback's array index, or a `const`, never-reassigned
|
|
1495
|
-
* `let` or `for` counter bound to a number and only ever updated by arithmetic. Also `xs.push(...)`
|
|
1496
|
-
* (the new length), `Number`/`parseInt`/`parseFloat`/`Math.*` calls, and `.length` of an array a
|
|
1497
|
-
* nearby binding builds from a literal. A type annotation proves nothing: it does not run.
|
|
1498
|
-
*/
|
|
1499
1216
|
function isNumericExpression(ts, node, depth) {
|
|
1500
1217
|
if (depth > CONST_RESOLUTION_DEPTH)
|
|
1501
1218
|
return false;
|
|
@@ -1550,7 +1267,6 @@ function nameBinding(ts, node) {
|
|
|
1550
1267
|
}
|
|
1551
1268
|
const binding = directBinding(ts, source, scope, node.text);
|
|
1552
1269
|
if (binding === "shadow") {
|
|
1553
|
-
// `for (let i = 0; ...; i++)`: the one reassigned `let` worth reading, checked by the caller.
|
|
1554
1270
|
const list = ts.isForStatement(scope) ? scope.initializer : undefined;
|
|
1555
1271
|
const declaration = list !== undefined && ts.isVariableDeclarationList(list)
|
|
1556
1272
|
? list.declarations.find((d) => ts.isIdentifier(d.name) && d.name.text === node.text)
|
|
@@ -1577,7 +1293,6 @@ function isNumericName(ts, node, depth) {
|
|
|
1577
1293
|
}
|
|
1578
1294
|
if (binding.kind !== "parameter")
|
|
1579
1295
|
return false;
|
|
1580
|
-
// An array callback's index parameter, never reassigned.
|
|
1581
1296
|
const call = binding.fn.parent;
|
|
1582
1297
|
if (!ts.isCallExpression(call) || !ts.isPropertyAccessExpression(call.expression))
|
|
1583
1298
|
return false;
|
|
@@ -1588,7 +1303,6 @@ function isNumericName(ts, node, depth) {
|
|
|
1588
1303
|
binding.position === position &&
|
|
1589
1304
|
!isReassignedInFile(ts, source, node.text));
|
|
1590
1305
|
}
|
|
1591
|
-
/** Compound assignments that always store a number. */
|
|
1592
1306
|
const NUMERIC_ASSIGNMENTS = (ts) => new Set([
|
|
1593
1307
|
ts.SyntaxKind.MinusEqualsToken,
|
|
1594
1308
|
ts.SyntaxKind.AsteriskEqualsToken,
|
|
@@ -1602,7 +1316,6 @@ const NUMERIC_ASSIGNMENTS = (ts) => new Set([
|
|
|
1602
1316
|
ts.SyntaxKind.GreaterThanGreaterThanEqualsToken,
|
|
1603
1317
|
ts.SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken,
|
|
1604
1318
|
]);
|
|
1605
|
-
/** Every write to `name` in the file is `++`/`--`, or an assignment that stores a number. */
|
|
1606
1319
|
function onlyNumericWrites(ts, source, name, depth) {
|
|
1607
1320
|
let ok = true;
|
|
1608
1321
|
const visit = (node) => {
|
|
@@ -1626,8 +1339,6 @@ function onlyNumericWrites(ts, source, name, depth) {
|
|
|
1626
1339
|
visit(source);
|
|
1627
1340
|
return ok;
|
|
1628
1341
|
}
|
|
1629
|
-
/** A template's contribution to the shape: resolved span texts fold into `staticText` (so the
|
|
1630
|
-
* keyword scan still sees what a `const` carries); any unresolvable span keeps it `dynamic`. */
|
|
1631
1342
|
function templateShape(ts, template, scope) {
|
|
1632
1343
|
let staticText = template.head.text;
|
|
1633
1344
|
let dynamic = false;
|
|
@@ -1644,10 +1355,6 @@ function templateShape(ts, template, scope) {
|
|
|
1644
1355
|
}
|
|
1645
1356
|
return { staticText, dynamic };
|
|
1646
1357
|
}
|
|
1647
|
-
/** Whether `name` is written to anywhere in the file - a plain, compound, or `++`/`--` assignment to a
|
|
1648
|
-
* bare identifier of that name. A `let` that is is over-cautiously refused (it might be reassigned from
|
|
1649
|
-
* request data); a `const` never needs this. Over-refusal only ever leaves an interpolation flagged as
|
|
1650
|
-
* before, never the reverse. */
|
|
1651
1358
|
function isReassignedInFile(ts, source, name) {
|
|
1652
1359
|
let found = false;
|
|
1653
1360
|
const visit = (node) => {
|
|
@@ -1674,8 +1381,6 @@ function isReassignedInFile(ts, source, name) {
|
|
|
1674
1381
|
visit(source);
|
|
1675
1382
|
return found;
|
|
1676
1383
|
}
|
|
1677
|
-
/** Does `binding` bind `name` (as a plain identifier or nested inside a destructuring pattern)? Mirrors
|
|
1678
|
-
* the pattern walk in {@link isShadowedAt}. */
|
|
1679
1384
|
function bindingNameCovers(ts, binding, name) {
|
|
1680
1385
|
return ts.isIdentifier(binding)
|
|
1681
1386
|
? binding.text === name
|
|
@@ -1684,10 +1389,6 @@ function bindingNameCovers(ts, binding, name) {
|
|
|
1684
1389
|
? element.name.text === name
|
|
1685
1390
|
: bindingNameCovers(ts, element.name, name)));
|
|
1686
1391
|
}
|
|
1687
|
-
/** Inspect the bindings a single scope node introduces DIRECTLY (not nested) for `name`: parameters and
|
|
1688
|
-
* catch variables of a function/catch, `var`/`let`/`const` and function/class declarations of a
|
|
1689
|
-
* statement list. Returns the readable initializer, `"shadow"` for a form we cannot read through, or
|
|
1690
|
-
* `undefined` when this scope does not bind the name at all. */
|
|
1691
1392
|
function directBinding(ts, source, scope, name) {
|
|
1692
1393
|
if (ts.isFunctionLike(scope)) {
|
|
1693
1394
|
for (const parameter of scope.parameters) {
|
|
@@ -1710,8 +1411,6 @@ function directBinding(ts, source, scope, name) {
|
|
|
1710
1411
|
for (const declaration of list.declarations) {
|
|
1711
1412
|
if (!bindingNameCovers(ts, declaration.name, name))
|
|
1712
1413
|
continue;
|
|
1713
|
-
// A destructured or uninitialized binding, or a `var` (hoisting + reassignment risk), is not a
|
|
1714
|
-
// value we can read one expression out of.
|
|
1715
1414
|
if (!ts.isIdentifier(declaration.name) || declaration.initializer === undefined)
|
|
1716
1415
|
return "shadow";
|
|
1717
1416
|
const isConst = (list.flags & ts.NodeFlags.Const) !== 0;
|
|
@@ -1734,7 +1433,6 @@ function scopeStatements(ts, scope) {
|
|
|
1734
1433
|
? scope.statements
|
|
1735
1434
|
: undefined;
|
|
1736
1435
|
}
|
|
1737
|
-
/** The `var`/`let`/`const` lists a scope node declares directly: its statements' and a `for` head's. */
|
|
1738
1436
|
function scopeDeclarationLists(ts, scope) {
|
|
1739
1437
|
const lists = [];
|
|
1740
1438
|
for (const statement of scopeStatements(ts, scope) ?? []) {
|
|
@@ -1748,7 +1446,6 @@ function scopeDeclarationLists(ts, scope) {
|
|
|
1748
1446
|
}
|
|
1749
1447
|
return lists;
|
|
1750
1448
|
}
|
|
1751
|
-
/** The `var` or `let` a scope declares `name` with by a plain identifier, if any. */
|
|
1752
1449
|
function mutableDeclaration(ts, scope, name) {
|
|
1753
1450
|
for (const list of scopeDeclarationLists(ts, scope)) {
|
|
1754
1451
|
if ((list.flags & ts.NodeFlags.Const) !== 0)
|
|
@@ -1760,22 +1457,6 @@ function mutableDeclaration(ts, scope, name) {
|
|
|
1760
1457
|
}
|
|
1761
1458
|
return undefined;
|
|
1762
1459
|
}
|
|
1763
|
-
/**
|
|
1764
|
-
* Every value a statement variable may hold where the query reads it, so a statement parked in a
|
|
1765
|
-
* variable is scanned as if it had been written inline at the call. This is the counterpart to
|
|
1766
|
-
* {@link resolveStaticSqlText}: that folds a const's text INTO a template's shape; this unfolds the
|
|
1767
|
-
* statement back out of the variable it was lifted into. Without it, ANY interpolated-SQL finding
|
|
1768
|
-
* could be silenced, invisibly, by hoisting the statement to `const q = …` first, or by building it
|
|
1769
|
-
* in steps (`let q = "SELECT …"; q += …`).
|
|
1770
|
-
*
|
|
1771
|
-
* Same-file only. Nearest enclosing declaration wins, so a shadowing local is read and never a
|
|
1772
|
-
* same-named module const. A `const`, or a `let` the file never reassigns, holds its initializer. A
|
|
1773
|
-
* `var` or reassigned `let` holds its initializer and every value assigned to the name anywhere in
|
|
1774
|
-
* the function (or module) that declares it: over-collected rather than scope-simulated, which only
|
|
1775
|
-
* ever adds a value to check. `key` names the binding, so a value that reads the variable it is
|
|
1776
|
-
* assigned to is recognised. A parameter, an imported or destructured binding, or a name with no
|
|
1777
|
-
* same-file declaration returns `undefined` - which leaves the argument scanned as itself.
|
|
1778
|
-
*/
|
|
1779
1460
|
function variableWrites(ts, node) {
|
|
1780
1461
|
const source = node.getSourceFile();
|
|
1781
1462
|
const name = node.text;
|
|
@@ -1804,7 +1485,6 @@ function variableWrites(ts, node) {
|
|
|
1804
1485
|
}
|
|
1805
1486
|
return undefined;
|
|
1806
1487
|
}
|
|
1807
|
-
/** The values assigned to `name` under `root`. A numeric compound assignment stores no text. */
|
|
1808
1488
|
function writesTo(ts, root, name) {
|
|
1809
1489
|
const writes = [];
|
|
1810
1490
|
const visit = (node) => {
|
|
@@ -1829,7 +1509,6 @@ function writesTo(ts, root, name) {
|
|
|
1829
1509
|
return writes;
|
|
1830
1510
|
}
|
|
1831
1511
|
function mentionsName(ts, node, name) {
|
|
1832
|
-
// A member/key named like the variable does not read that variable (`record = client.record()`).
|
|
1833
1512
|
if (ts.isPropertyAccessExpression(node))
|
|
1834
1513
|
return mentionsName(ts, node.expression, name);
|
|
1835
1514
|
if (ts.isPropertyAssignment(node)) {
|
|
@@ -1859,16 +1538,12 @@ function textShape(text) {
|
|
|
1859
1538
|
function joinShapes(shapes) {
|
|
1860
1539
|
return {
|
|
1861
1540
|
staticText: shapes.map((shape) => shape.staticText).join(""),
|
|
1862
|
-
// As with `+`: text glued onto a binding tag's output un-parameterizes it.
|
|
1863
1541
|
dynamic: shapes.some((shape) => shape.dynamic || shape.parameterizedTag),
|
|
1864
1542
|
concatenated: true,
|
|
1865
1543
|
literal: false,
|
|
1866
1544
|
parameterizedTag: false,
|
|
1867
1545
|
};
|
|
1868
1546
|
}
|
|
1869
|
-
/** Orders a variable's candidate statements by how surely {@link scanInterpolatedSql} would flag
|
|
1870
|
-
* them: dynamic SQL text, then dynamic glued text, then any dynamic text; outside a binding tag
|
|
1871
|
-
* before inside one. */
|
|
1872
1547
|
function sqlRisk(shape) {
|
|
1873
1548
|
const dynamic = !shape.dynamic
|
|
1874
1549
|
? 0
|
|
@@ -1879,12 +1554,6 @@ function sqlRisk(shape) {
|
|
|
1879
1554
|
: 1;
|
|
1880
1555
|
return dynamic * 2 + (shape.parameterizedTag ? 0 : 1);
|
|
1881
1556
|
}
|
|
1882
|
-
/**
|
|
1883
|
-
* The riskiest statement a variable may hold. Each value that replaces the text is one candidate.
|
|
1884
|
-
* The values that build on it (`+=`, or `q = q + more`) are glued onto every replacing value at
|
|
1885
|
-
* once, as a builder that takes each branch would, so a static `SELECT … WHERE 1=1` followed by an
|
|
1886
|
-
* interpolated `AND …` reads as the one statement it becomes.
|
|
1887
|
-
*/
|
|
1888
1557
|
function writtenShape(ts, name, writes, scope, trail) {
|
|
1889
1558
|
const replacing = [];
|
|
1890
1559
|
const building = [];
|
|
@@ -1912,7 +1581,6 @@ const TEXT_METHODS = new Set([
|
|
|
1912
1581
|
"toLowerCase",
|
|
1913
1582
|
"toUpperCase",
|
|
1914
1583
|
]);
|
|
1915
|
-
/** The value a text-preserving call returns: `String(x)`, `x.toString()`, `x.trim()`. */
|
|
1916
1584
|
function passedThrough(ts, call) {
|
|
1917
1585
|
const callee = call.expression;
|
|
1918
1586
|
if (ts.isIdentifier(callee) && callee.text === "String" && call.arguments.length === 1) {
|
|
@@ -1925,7 +1593,6 @@ function passedThrough(ts, call) {
|
|
|
1925
1593
|
}
|
|
1926
1594
|
return undefined;
|
|
1927
1595
|
}
|
|
1928
|
-
/** The parts `[a, b].join(sep)` and `a.concat(b)` glue together, a separator as its text. */
|
|
1929
1596
|
function joinedParts(ts, call) {
|
|
1930
1597
|
const callee = call.expression;
|
|
1931
1598
|
if (!ts.isPropertyAccessExpression(callee))
|
|
@@ -1948,9 +1615,6 @@ function joinedParts(ts, call) {
|
|
|
1948
1615
|
});
|
|
1949
1616
|
return parts;
|
|
1950
1617
|
}
|
|
1951
|
-
/** Whether the `sql` a tag names is a function this file defines (`const sql = (s, ...v) => …`),
|
|
1952
|
-
* which is plain interpolation whatever its name. A parameter, an import, or a driver instance
|
|
1953
|
-
* (`const sql = postgres(url)`) keeps the name's trust. */
|
|
1954
1618
|
function definesSqlFunction(ts, tag) {
|
|
1955
1619
|
for (let scope = tag.parent; scope !== undefined; scope = scope.parent) {
|
|
1956
1620
|
if (ts.isFunctionLike(scope) &&
|
|
@@ -1974,8 +1638,6 @@ function definesSqlFunction(ts, tag) {
|
|
|
1974
1638
|
}
|
|
1975
1639
|
return false;
|
|
1976
1640
|
}
|
|
1977
|
-
/** Describe only the statement's syntax; comments/strings elsewhere cannot influence the result.
|
|
1978
|
-
* `trail` holds the variables being read through, innermost last. */
|
|
1979
1641
|
function sqlExpressionShape(ts, expression, scope, trail = []) {
|
|
1980
1642
|
let node = unwrapExpression(ts, expression);
|
|
1981
1643
|
while (ts.isNonNullExpression(node))
|
|
@@ -1998,20 +1660,6 @@ function sqlExpressionShape(ts, expression, scope, trail = []) {
|
|
|
1998
1660
|
? templateShape(ts, template, parameterizedTag ? undefined : scope)
|
|
1999
1661
|
: { staticText: template.text, dynamic: false };
|
|
2000
1662
|
const staticText = templated.staticText;
|
|
2001
|
-
// Only the ecosystem's binding tags are trusted, by NAME - which is the honest limit of a scanner
|
|
2002
|
-
// that reads syntax and runs no type checker. `sql` is what postgres.js, drizzle, slonik and Bun's
|
|
2003
|
-
// own driver all call theirs, and `Prisma.sql` is Prisma's; taking those at their word is a
|
|
2004
|
-
// deliberate trade, and it is worth stating what it costs: a `sql` this file defines as a
|
|
2005
|
-
// function is read as the interpolation it is, but one imported from anywhere is trusted, so
|
|
2006
|
-
// this rule finds mistakes, not an adversary who reads it first.
|
|
2007
|
-
//
|
|
2008
|
-
// Trusting anything else widens that for no gain. This list briefly also held `sqlIdentifiers`,
|
|
2009
|
-
// a name invented for Nifra's own adapters - a second forgeable name that no user has a
|
|
2010
|
-
// convention for, added so Nifra's source would pass its own rule. Names earn their place here by
|
|
2011
|
-
// being what drivers already call the thing, not by being convenient for the framework.
|
|
2012
|
-
//
|
|
2013
|
-
// Everything else - `String.raw`, an identity tag, a member access that merely ends in `.sql` -
|
|
2014
|
-
// is treated as plain interpolation.
|
|
2015
1663
|
return {
|
|
2016
1664
|
staticText,
|
|
2017
1665
|
dynamic: templated.dynamic && !parameterizedTag,
|
|
@@ -2025,7 +1673,6 @@ function sqlExpressionShape(ts, expression, scope, trail = []) {
|
|
|
2025
1673
|
return {
|
|
2026
1674
|
staticText: templated.staticText,
|
|
2027
1675
|
dynamic: templated.dynamic,
|
|
2028
|
-
// `${a} ${b}` writes no text of its own; it only glues values together.
|
|
2029
1676
|
concatenated: [node.head, ...node.templateSpans.map((span) => span.literal)].every((part) => part.text.trim() === ""),
|
|
2030
1677
|
literal: false,
|
|
2031
1678
|
parameterizedTag: false,
|
|
@@ -2036,20 +1683,12 @@ function sqlExpressionShape(ts, expression, scope, trail = []) {
|
|
|
2036
1683
|
const right = sqlExpressionShape(ts, node.right, scope, trail);
|
|
2037
1684
|
return {
|
|
2038
1685
|
staticText: left.staticText + right.staticText,
|
|
2039
|
-
// A resolved const operand is static text, not a dynamic part - so the old `!literal` test
|
|
2040
|
-
// narrows to what it always actually meant: an operand that carries runtime data (dynamic) or
|
|
2041
|
-
// a binding tag being concatenated into plain text (which un-parameterizes it).
|
|
2042
1686
|
dynamic: left.dynamic || right.dynamic || left.parameterizedTag || right.parameterizedTag,
|
|
2043
1687
|
concatenated: true,
|
|
2044
1688
|
literal: left.literal && right.literal,
|
|
2045
1689
|
parameterizedTag: false,
|
|
2046
1690
|
};
|
|
2047
1691
|
}
|
|
2048
|
-
// A resolvable expression (a module-`const` name, a literal ternary) contributes its compile-time
|
|
2049
|
-
// text and stays non-dynamic - this is what lets `"SELECT " + COLS + " FROM t"` and
|
|
2050
|
-
// `db.query(`${COLS} FROM t WHERE id = $1`)` pass while a mutable or unprovable name still flags.
|
|
2051
|
-
// `literal` stays false: the named escape hatches (`unsafe`, `$queryRawUnsafe`) keep flagging a
|
|
2052
|
-
// resolved const, because taking statement text from ANY variable is what their rule warns about.
|
|
2053
1692
|
if (scope !== undefined) {
|
|
2054
1693
|
const resolved = resolveStaticSqlText(ts, node, scope, 0);
|
|
2055
1694
|
if (resolved !== undefined) {
|
|
@@ -2071,15 +1710,8 @@ function sqlExpressionShape(ts, expression, scope, trail = []) {
|
|
|
2071
1710
|
return joinShapes(parts.map((part) => typeof part === "string" ? textShape(part) : sqlExpressionShape(ts, part, scope, trail)));
|
|
2072
1711
|
}
|
|
2073
1712
|
}
|
|
2074
|
-
// A bare name that did not resolve to compile-time text. If it is a same-file binding, scan the
|
|
2075
|
-
// shapes of what it may hold - so a statement hoisted into `const q = …` or built up in a `let` is
|
|
2076
|
-
// read exactly as if it were written inline at the call, closing the "extract a variable to launder
|
|
2077
|
-
// the finding" hole. `literal` is forced false: the value arrived through a variable, which is the
|
|
2078
|
-
// property the `unsafe`/`$queryRawUnsafe` hatch rule keys on.
|
|
2079
1713
|
if (ts.isIdentifier(node)) {
|
|
2080
1714
|
const read = variableWrites(ts, node);
|
|
2081
|
-
// Read inside one of its own writes (`q = q + more`), the variable is the text the other writes
|
|
2082
|
-
// already account for.
|
|
2083
1715
|
if (read !== undefined && trail.includes(read.key))
|
|
2084
1716
|
return { ...textShape(""), literal: false };
|
|
2085
1717
|
if (read !== undefined && trail.length <= CONST_RESOLUTION_DEPTH) {
|
|
@@ -2094,7 +1726,6 @@ function sqlMethod(ts, call) {
|
|
|
2094
1726
|
? { method, receiver: receiver?.getText() }
|
|
2095
1727
|
: undefined;
|
|
2096
1728
|
const callee = call.expression;
|
|
2097
|
-
// Svelte compiles this unbound rune; it is not a driver's raw-statement escape hatch.
|
|
2098
1729
|
if (ts.isPropertyAccessExpression(callee) &&
|
|
2099
1730
|
callee.name.text === "raw" &&
|
|
2100
1731
|
ts.isIdentifier(callee.expression) &&
|
|
@@ -2130,7 +1761,6 @@ function sqlMethod(ts, call) {
|
|
|
2130
1761
|
return undefined;
|
|
2131
1762
|
}
|
|
2132
1763
|
const SQL_RECEIVER = /(?:^|\.)(?:db|sql|prisma|drizzle|database|conn|connection|client|tx)$/i;
|
|
2133
|
-
/** Whether a statement is SQL assembled from runtime values, judged by where it is sent. */
|
|
2134
1764
|
function isAssembledSql(sink, shape) {
|
|
2135
1765
|
if (!shape.dynamic)
|
|
2136
1766
|
return false;
|
|
@@ -2139,8 +1769,6 @@ function isAssembledSql(sink, shape) {
|
|
|
2139
1769
|
}
|
|
2140
1770
|
return (SQL_KEYWORD.test(shape.staticText) || (shape.concatenated && SQL_RECEIVER.test(sink.receiver)));
|
|
2141
1771
|
}
|
|
2142
|
-
/** The statement a call passes: the argument itself, or the `text`/`sql` of a config object
|
|
2143
|
-
* (`{ text, values }` in pg, `{ sql, values }` in mysql2). */
|
|
2144
1772
|
function statementArgument(ts, argument) {
|
|
2145
1773
|
const node = unwrapExpression(ts, argument);
|
|
2146
1774
|
if (!ts.isObjectLiteralExpression(node))
|
|
@@ -2158,9 +1786,6 @@ function statementArgument(ts, argument) {
|
|
|
2158
1786
|
return undefined;
|
|
2159
1787
|
}
|
|
2160
1788
|
const STATEMENT_KEYS = new Set(["text", "sql"]);
|
|
2161
|
-
/** Same-file functions that send one of their parameters as a statement - `run(db, q)` calling
|
|
2162
|
-
* `db.query(q)` - by name, with the parameter's position and the sink it reaches. A call to one is
|
|
2163
|
-
* scanned as a call to that sink. One level deep. */
|
|
2164
1789
|
function statementHelpers(ts, source) {
|
|
2165
1790
|
const helpers = new Map();
|
|
2166
1791
|
const visit = (node) => {
|
|
@@ -2190,7 +1815,6 @@ function functionName(ts, fn) {
|
|
|
2190
1815
|
}
|
|
2191
1816
|
return undefined;
|
|
2192
1817
|
}
|
|
2193
|
-
/** `content` with every string, template and regex literal blanked, line breaks kept. */
|
|
2194
1818
|
function literalsBlanked(ts, source, content) {
|
|
2195
1819
|
const out = content.split("");
|
|
2196
1820
|
const visit = (node) => {
|
|
@@ -2210,35 +1834,18 @@ function literalsBlanked(ts, source, content) {
|
|
|
2210
1834
|
visit(source);
|
|
2211
1835
|
return out.join("");
|
|
2212
1836
|
}
|
|
2213
|
-
/** What silences one interpolated-SQL finding: `// nifra-expect NF-C006: <reason>` (or the
|
|
2214
|
-
* `sql-dynamic` slug) on the flagged line or in the comment block directly above it. The reason after
|
|
2215
|
-
* the colon is mandatory (see {@link commentBlockExpectation}). Scoped to the single statement it sits on. */
|
|
2216
1837
|
const SQL_DYNAMIC_EXPECTATION = ["NF-C006", "sql-dynamic"];
|
|
2217
|
-
/**
|
|
2218
|
-
* Scan one file's text for SQL assembled by interpolation. Pure + line-accurate.
|
|
2219
|
-
*
|
|
2220
|
-
* `imports` opts into following a fragment `const` into another module. Without it the scan is
|
|
2221
|
-
* same-file only, which is what the unit tests exercise and what any caller that has no module graph
|
|
2222
|
-
* to offer gets. With it, only what {@link createProjectSqlImports} will hand back is followed.
|
|
2223
|
-
*/
|
|
2224
1838
|
export function scanInterpolatedSql(file, content, ts, imports) {
|
|
2225
1839
|
return scanSqlSites(file, content, ts, imports).filter((site) => site.expected === undefined);
|
|
2226
1840
|
}
|
|
2227
|
-
/** {@link scanInterpolatedSql}, keeping the sites an expectation comment silences, with its reason. */
|
|
2228
1841
|
export function scanSqlSites(file, content, ts, imports) {
|
|
2229
1842
|
const out = [];
|
|
2230
1843
|
const lines = content.split("\n");
|
|
2231
|
-
// Malformed source is already a typecheck failure. Do not turn parser recovery nodes into a second,
|
|
2232
|
-
// misleading SQL diagnostic (notably an unterminated template recovered as an interpolation).
|
|
2233
1844
|
const source = parseSqlSource(ts, file, content);
|
|
2234
1845
|
if (source === undefined)
|
|
2235
1846
|
return out;
|
|
2236
|
-
// Module-scope bindings, read once per file: an interpolated `const` that resolves to compile-time
|
|
2237
|
-
// text cannot carry request data, so the shared-projection idiom (`const COLS = "id, name"` …
|
|
2238
|
-
// `${COLS}`) stays quiet while mutable, parameter, shadowed, and unprovable names flag as before.
|
|
2239
1847
|
const scope = { module: sqlModuleScope(ts, file, source), imports };
|
|
2240
1848
|
const helpers = statementHelpers(ts, source);
|
|
2241
|
-
// A marker counts only in a comment: one inside a string the call passes is data, not a reason.
|
|
2242
1849
|
let markerLines;
|
|
2243
1850
|
const visit = (node) => {
|
|
2244
1851
|
if (ts.isCallExpression(node)) {
|
|
@@ -2250,7 +1857,6 @@ export function scanSqlSites(file, content, ts, imports) {
|
|
|
2250
1857
|
const argument = passed === undefined ? undefined : statementArgument(ts, passed);
|
|
2251
1858
|
if (sink !== undefined && argument !== undefined) {
|
|
2252
1859
|
const shape = sqlExpressionShape(ts, argument, scope);
|
|
2253
|
-
// A helper's own hatch call already answers for passing it a variable.
|
|
2254
1860
|
const unsafeEscape = helper === undefined &&
|
|
2255
1861
|
sink.receiver !== undefined &&
|
|
2256
1862
|
ALWAYS_UNSAFE.has(sink.method) &&
|
|
@@ -2259,10 +1865,6 @@ export function scanSqlSites(file, content, ts, imports) {
|
|
|
2259
1865
|
if (unsafeEscape || isAssembledSql(sink, shape)) {
|
|
2260
1866
|
const index = node.getStart(source);
|
|
2261
1867
|
const line = source.getLineAndCharacterOfPosition(index).line + 1;
|
|
2262
|
-
// Sanctioned escape hatch for genuinely-dynamic-but-bound SQL (an allowlisted identifier,
|
|
2263
|
-
// placeholders numbered from data the scan cannot prove numeric). The reason is mandatory: a bare `// nifra-expect
|
|
2264
|
-
// NF-C006` with no reason after the colon does NOT silence, so the hatch always leaves a
|
|
2265
|
-
// greppable audit trail instead of becoming a second laundering trick.
|
|
2266
1868
|
markerLines ??= literalsBlanked(ts, source, content).split("\n");
|
|
2267
1869
|
const reason = commentBlockExpectation(markerLines, line, SQL_DYNAMIC_EXPECTATION)?.reason;
|
|
2268
1870
|
const site = { file, line, snippet: (lines[line - 1] ?? "").trim() };
|
|
@@ -2275,14 +1877,6 @@ export function scanSqlSites(file, content, ts, imports) {
|
|
|
2275
1877
|
visit(source);
|
|
2276
1878
|
return out;
|
|
2277
1879
|
}
|
|
2278
|
-
/**
|
|
2279
|
-
* Collect interpolated-SQL findings across the project.
|
|
2280
|
-
*
|
|
2281
|
-
* Returns `undefined` - not an empty array - when TypeScript is not installed. The rule parses source
|
|
2282
|
-
* with the compiler, so without it there is nothing to report and, more to the point, no basis for
|
|
2283
|
-
* reporting nothing. An empty result would read as "no interpolated SQL found", which is the one
|
|
2284
|
-
* answer a security rule must never give when it did not run.
|
|
2285
|
-
*/
|
|
2286
1880
|
export async function scanProjectSql(cwd) {
|
|
2287
1881
|
const sourceFiles = [];
|
|
2288
1882
|
await walkSource(cwd, (file, content) => sourceFiles.push({ file, content }));
|
|
@@ -2306,34 +1900,14 @@ export async function scanProjectSql(cwd) {
|
|
|
2306
1900
|
await loaded.session?.close();
|
|
2307
1901
|
}
|
|
2308
1902
|
}
|
|
2309
|
-
/** A declaration file. Excluded from cross-module resolution: `declare const X: string` has no
|
|
2310
|
-
* initializer to read, so following one could only ever produce a "proved" the source never wrote. */
|
|
2311
1903
|
const SQL_DECLARATION_FILE = /\.d\.[cm]?ts$/;
|
|
2312
|
-
/** The extensions the SQL scan will parse - the same set {@link walkSource} globs. */
|
|
2313
1904
|
const SQL_SOURCE_FILE = /\.[cm]?tsx?$/;
|
|
2314
|
-
/**
|
|
2315
|
-
* The on-disk loader for cross-module `const` resolution, scoped to one project.
|
|
2316
|
-
*
|
|
2317
|
-
* Deliberately narrow, because every widening here is a way for a real finding to go quiet:
|
|
2318
|
-
*
|
|
2319
|
-
* - **Relative specifiers only.** A bare specifier names a dependency whose exports can change without
|
|
2320
|
-
* this project changing, so "provably a `const` string" is not a property the project owns.
|
|
2321
|
-
* - **Inside `cwd`, outside the ignored trees.** The resolved path is realpath'd and must still sit
|
|
2322
|
-
* under the project root: a symlink pointing out of the tree is not source this scan reads. The
|
|
2323
|
-
* `node_modules` / `dist` / build exclusions are the same ones the walk applies.
|
|
2324
|
-
* - **Real source only.** A `.d.ts` carries no initializer, and a non-TS file is not parsed.
|
|
2325
|
-
*
|
|
2326
|
-
* A miss on any of those returns `undefined`, which leaves the name unresolved and the interpolation
|
|
2327
|
-
* flagged - the pre-feature answer.
|
|
2328
|
-
*/
|
|
2329
1905
|
export function createProjectSqlImports(cwd) {
|
|
2330
1906
|
const root = realpathOrSelf(resolve(cwd));
|
|
2331
1907
|
return createSqlImports((fromModule, specifier) => {
|
|
2332
1908
|
if (!isRelativeSpecifier(specifier))
|
|
2333
1909
|
return undefined;
|
|
2334
1910
|
try {
|
|
2335
|
-
// `fromModule` is the cwd-RELATIVE path the walk supplies for an entry file, and ABSOLUTE for
|
|
2336
|
-
// every module reached through a hop (their ids are the resolved paths).
|
|
2337
1911
|
const fromAbs = isAbsolute(fromModule) ? fromModule : join(root, fromModule);
|
|
2338
1912
|
const resolved = realpathSync(Bun.resolveSync(specifier, dirname(fromAbs)));
|
|
2339
1913
|
if (!resolved.startsWith(root + sep))
|
|
@@ -2346,16 +1920,11 @@ export function createProjectSqlImports(cwd) {
|
|
|
2346
1920
|
return { id: resolved, content: readFileSync(resolved, "utf8") };
|
|
2347
1921
|
}
|
|
2348
1922
|
catch {
|
|
2349
|
-
return undefined;
|
|
1923
|
+
return undefined;
|
|
2350
1924
|
}
|
|
2351
1925
|
});
|
|
2352
1926
|
}
|
|
2353
|
-
// `client("` / `client('` / `client(\`` - a URL-first call WITHOUT the `<typeof app>` generic:
|
|
2354
|
-
// the compiler has nothing to derive types from, so the anti-drift guarantee silently vanishes.
|
|
2355
|
-
// `client<typeof app>("…")` has `<…>` between the name and `(` so it never matches; the published-
|
|
2356
|
-
// contract form `client(contract, url)` starts with an identifier, not a quote - also unmatched.
|
|
2357
1927
|
const CLIENT_CALL = /(?<![.\w])client\s*\(/g;
|
|
2358
|
-
/** Scan one file's text for untyped `client("…")` calls. Pure + line-accurate. */
|
|
2359
1928
|
export function scanUntypedClient(file, content) {
|
|
2360
1929
|
const out = [];
|
|
2361
1930
|
const lines = content.split("\n");
|
|
@@ -2371,18 +1940,6 @@ export function scanUntypedClient(file, content) {
|
|
|
2371
1940
|
}
|
|
2372
1941
|
return out;
|
|
2373
1942
|
}
|
|
2374
|
-
/**
|
|
2375
|
-
* Specifiers that no longer exist, and what replaced them.
|
|
2376
|
-
*
|
|
2377
|
-
* These are the breaks a typecheck does not catch and a test suite does not either. `@nifrajs/core/ws`
|
|
2378
|
-
* was a side-effect import removed in 2.0 in favour of `.use(websocket())`; a consuming package kept
|
|
2379
|
-
* the import and a 533-test suite stayed green while the app could not boot. `@nifrajs/budget` folded
|
|
2380
|
-
* into core with no npm deprecation, so `bun install` fails workspace-wide with a resolution error
|
|
2381
|
-
* that names neither the cause nor the replacement.
|
|
2382
|
-
*
|
|
2383
|
-
* A lint is the right shape for this: it runs before boot, names the file and line, and states the
|
|
2384
|
-
* replacement - which is what neither the resolver error nor the runtime failure does.
|
|
2385
|
-
*/
|
|
2386
1943
|
export const REMOVED_IMPORTS = [
|
|
2387
1944
|
{
|
|
2388
1945
|
specifier: "@nifrajs/budget",
|
|
@@ -2406,17 +1963,9 @@ export const REMOVED_IMPORTS = [
|
|
|
2406
1963
|
replacement: 'a bare `import "@nifrajs/core/ws"` no longer installs the runtime - register it explicitly with `.use(websocket())`, importing `websocket` from the same module',
|
|
2407
1964
|
},
|
|
2408
1965
|
];
|
|
2409
|
-
/** Whether the import statement at `index` is the bare side-effect form (`import "x"`), rather than
|
|
2410
|
-
* one with bindings (`import { y } from "x"`). */
|
|
2411
1966
|
function isSideEffectImport(content, index) {
|
|
2412
|
-
// `staticImportEdges` reports the index of the STATEMENT, not of the specifier, so read forward:
|
|
2413
|
-
// a side-effect import is `import` followed directly by the quoted specifier, with no bindings and
|
|
2414
|
-
// no `from` in between.
|
|
2415
1967
|
return /^import\s*["'`]/.test(content.slice(index, index + 32));
|
|
2416
1968
|
}
|
|
2417
|
-
/** Flag an import of a specifier that no longer exists, or of a name that moved to a subpath
|
|
2418
|
-
* ({@link MOVED_EXPORTS}). Pure; matches the exact specifier or a subpath of it, so `@nifrajs/budget/x`
|
|
2419
|
-
* is caught alongside `@nifrajs/budget`. */
|
|
2420
1969
|
export function scanRemovedImports(file, content) {
|
|
2421
1970
|
const out = [];
|
|
2422
1971
|
const lines = content.split("\n");
|
|
@@ -2429,30 +1978,17 @@ export function scanRemovedImports(file, content) {
|
|
|
2429
1978
|
const line = lineAt(content, edge.index);
|
|
2430
1979
|
out.push({ file, line, snippet: (lines[line - 1] ?? "").trim() });
|
|
2431
1980
|
}
|
|
2432
|
-
// A moved name's snippet is the whole statement on one line: the rule re-reads the site from it.
|
|
2433
1981
|
for (const site of movedExportSites(content)) {
|
|
2434
1982
|
const snippet = content.slice(site.index, site.end).replace(/\s+/g, " ");
|
|
2435
1983
|
out.push({ file, line: lineAt(content, site.index), snippet });
|
|
2436
1984
|
}
|
|
2437
1985
|
return out;
|
|
2438
1986
|
}
|
|
2439
|
-
/**
|
|
2440
|
-
* Named exports that left a module for one of its subpaths, and where they went.
|
|
2441
|
-
*
|
|
2442
|
-
* Unlike a removed specifier, a moved name does fail the typecheck - but that error names neither the
|
|
2443
|
-
* new home nor a fix. Listing it here gives the diagnostic both, and `nifra fix --code NF-C005`
|
|
2444
|
-
* rewrites the import ({@link rewriteMovedExports}).
|
|
2445
|
-
*/
|
|
2446
1987
|
export const MOVED_EXPORTS = [
|
|
2447
|
-
// Compiler plugins sit on their own subpath so the adapter root, which every server and edge bundle
|
|
2448
|
-
// links, never pulls in build-time code.
|
|
2449
1988
|
{ from: "@nifrajs/web-solid", names: ["solidBunPlugin"], to: "@nifrajs/web-solid/plugin" },
|
|
2450
1989
|
{ from: "@nifrajs/web-svelte", names: ["svelteBunPlugin"], to: "@nifrajs/web-svelte/plugin" },
|
|
2451
1990
|
];
|
|
2452
|
-
/** `import { a, b as c } from "x"` and `export { a } from "x"` - the forms a moved name is reached by.
|
|
2453
|
-
* `import type` / `export type` never match, so a type-only import is left to tsc as elsewhere here. */
|
|
2454
1991
|
const NAMED_FROM = /\b(import|export)\s*\{([^{}]*)\}\s*from\s*(["'])([^"'\n]+)\3;?/g;
|
|
2455
|
-
/** Every import/re-export statement naming a {@link MOVED_EXPORTS} binding, in source order. Pure. */
|
|
2456
1992
|
export function movedExportSites(content) {
|
|
2457
1993
|
const positions = codePositionMask(content);
|
|
2458
1994
|
const sites = [];
|
|
@@ -2484,8 +2020,6 @@ export function movedExportSites(content) {
|
|
|
2484
2020
|
}
|
|
2485
2021
|
return sites;
|
|
2486
2022
|
}
|
|
2487
|
-
/** Point every moved binding at the module it moved to, leaving the rest of its statement in place.
|
|
2488
|
-
* Returns `content` unchanged when nothing moved, so applying it twice is a no-op. Pure. */
|
|
2489
2023
|
export function rewriteMovedExports(content) {
|
|
2490
2024
|
let out = content;
|
|
2491
2025
|
for (const site of movedExportSites(content).reverse()) {
|
|
@@ -2498,16 +2032,11 @@ export function rewriteMovedExports(content) {
|
|
|
2498
2032
|
}
|
|
2499
2033
|
return out;
|
|
2500
2034
|
}
|
|
2501
|
-
/** Scan a browser module for server-only imports, static or a literal dynamic `import()`. Returns `[]`
|
|
2502
|
-
* for server code ({@link isBrowserSource}), where a server-only import is fine. Each finding carries
|
|
2503
|
-
* the offending `specifier` so the diagnostic can render the `file → specifier` chain. Pure. */
|
|
2504
2035
|
export function scanServerOnlyImports(file, content, facts) {
|
|
2505
2036
|
if (!isBrowserSource(file))
|
|
2506
2037
|
return [];
|
|
2507
2038
|
const out = [];
|
|
2508
2039
|
const lines = content.split("\n");
|
|
2509
|
-
// Inline `import { type X } from "…"` is erased just like `import type` and is not an edge; a parse
|
|
2510
|
-
// failure keeps the lexical edge so the security rule fails closed.
|
|
2511
2040
|
for (const { specifier, index } of importEdges(content, facts, file)) {
|
|
2512
2041
|
if (!isServerOnly(specifier))
|
|
2513
2042
|
continue;
|
|
@@ -2516,22 +2045,8 @@ export function scanServerOnlyImports(file, content, facts) {
|
|
|
2516
2045
|
}
|
|
2517
2046
|
return out;
|
|
2518
2047
|
}
|
|
2519
|
-
// ---------------------------------------------------------------------------------------------------
|
|
2520
|
-
// #4.4 - TRANSITIVE import-chain resolution for `server-only-import`. `scanServerOnlyImports` above is a
|
|
2521
|
-
// pure per-file regex scan: it sees only the route's DIRECT `import` line, so it reports the direct edge
|
|
2522
|
-
// `routes/x → ../db`. The build leak-guard, which has the real module graph, reports the full transitive
|
|
2523
|
-
// `route → ../data → ../db → pg`. These helpers give `nifra check` the same depth via a BOUNDED
|
|
2524
|
-
// import-resolution walk: from a flagged route, resolve its local imports (`Bun.resolveSync`), BFS the
|
|
2525
|
-
// local module graph, and build the shortest chain to a server-only SINK. It's best-effort: an import
|
|
2526
|
-
// that can't be precisely resolved (a bare pkg, a tsconfig path alias) falls back to the direct edge.
|
|
2527
|
-
// ---------------------------------------------------------------------------------------------------
|
|
2528
|
-
// The retired `*.server` convention. Builds refuse such a module in browser code rather than empty it.
|
|
2529
2048
|
const LEGACY_SERVER_FILE = /\.server(\.[cm]?[jt]sx?)?$/;
|
|
2530
|
-
// The explicit poison-import marker (`@nifrajs/web/backend-only`, or its retired `server-only` name) - a
|
|
2531
|
-
// module opting into the client-leak guard. A resolved file carrying this side-effect import is a sink.
|
|
2532
2049
|
const BACKEND_ONLY_MARKER_IMPORT = /import\s+["']@nifrajs\/web\/(?:backend|server)-only["']/g;
|
|
2533
|
-
/** Whether `content` imports the backend-only marker in code. A mention in a comment or a string,
|
|
2534
|
-
* such as a note on how to opt in, marks nothing. */
|
|
2535
2050
|
function hasBackendOnlyMarker(content) {
|
|
2536
2051
|
if (!content.includes("-only"))
|
|
2537
2052
|
return false;
|
|
@@ -2542,17 +2057,8 @@ function hasBackendOnlyMarker(content) {
|
|
|
2542
2057
|
}
|
|
2543
2058
|
return false;
|
|
2544
2059
|
}
|
|
2545
|
-
/** A relative module specifier (`./x`, `../y`) - the only kind the SQL import lookup follows. */
|
|
2546
2060
|
const isRelativeSpecifier = (spec) => spec.startsWith("./") || spec.startsWith("../");
|
|
2547
|
-
// A FRESH copy of the static-import regex per scan. The transitive walk is REENTRANT - the outer
|
|
2548
|
-
// per-route loop and the inner BFS both scan imports - and a single shared global-flag regex carries
|
|
2549
|
-
// `lastIndex` state, so reusing the module-level `STATIC_IMPORT` across nested calls corrupts the outer
|
|
2550
|
-
// loop's position (it restarts forever). A fresh instance per call keeps each scan's state private.
|
|
2551
2061
|
const staticImportRegex = () => new RegExp(STATIC_IMPORT.source, STATIC_IMPORT.flags);
|
|
2552
|
-
/** Extract the static, non-type import specifiers from a module's source (the edges to follow/inspect),
|
|
2553
|
-
* each with the match index (for line attribution). Mirrors {@link STATIC_IMPORT}, so `import type` +
|
|
2554
|
-
* dynamic `import()` are already excluded. Uses a fresh regex instance, so it's safe under the reentrant
|
|
2555
|
-
* transitive walk. Pure. */
|
|
2556
2062
|
function staticImportEdges(content, facts, file, positions = codePositionMask(content)) {
|
|
2557
2063
|
const edges = [];
|
|
2558
2064
|
const re = staticImportRegex();
|
|
@@ -2562,7 +2068,6 @@ function staticImportEdges(content, facts, file, positions = codePositionMask(co
|
|
|
2562
2068
|
continue;
|
|
2563
2069
|
if (m[1] === undefined)
|
|
2564
2070
|
continue;
|
|
2565
|
-
// Only a `type` modifier can erase a clause the pattern matched, so other clauses skip the parse.
|
|
2566
2071
|
if (facts !== undefined && file !== undefined && /\btype\b/.test(m[0])) {
|
|
2567
2072
|
const source = facts.parse(file, content);
|
|
2568
2073
|
if (source !== undefined && facts.isValueImportAt(source, m.index, m[1]) === false)
|
|
@@ -2572,19 +2077,15 @@ function staticImportEdges(content, facts, file, positions = codePositionMask(co
|
|
|
2572
2077
|
}
|
|
2573
2078
|
return edges;
|
|
2574
2079
|
}
|
|
2575
|
-
/** Extract the static, non-type import specifiers from a module's source (the edges to follow/inspect).
|
|
2576
|
-
* Mirrors {@link STATIC_IMPORT}, so `import type` + dynamic `import()` are already excluded. Pure. */
|
|
2577
2080
|
export function parseStaticImports(content, facts, file) {
|
|
2578
2081
|
return staticImportEdges(content, facts, file).map((e) => e.specifier);
|
|
2579
2082
|
}
|
|
2580
|
-
/** The literal dynamic `import("x")` calls in executable code, skipping type positions. With `facts`
|
|
2581
|
-
* the parser decides; without it (or when it cannot tell) the lexical rule does. Pure. */
|
|
2582
2083
|
function dynamicImportEdges(content, facts, file, positions = codePositionMask(content)) {
|
|
2583
2084
|
const edges = [];
|
|
2584
2085
|
const re = new RegExp(DYNAMIC_IMPORT.source, DYNAMIC_IMPORT.flags);
|
|
2585
2086
|
for (let m = re.exec(content); m !== null; m = re.exec(content)) {
|
|
2586
2087
|
if (positions[m.index] === " ")
|
|
2587
|
-
continue;
|
|
2088
|
+
continue;
|
|
2588
2089
|
const specifier = m[2];
|
|
2589
2090
|
if (specifier === undefined)
|
|
2590
2091
|
continue;
|
|
@@ -2605,13 +2106,12 @@ function dynamicImportEdges(content, facts, file, positions = codePositionMask(c
|
|
|
2605
2106
|
}
|
|
2606
2107
|
return edges;
|
|
2607
2108
|
}
|
|
2608
|
-
/** The literal `require("x")` calls in executable code. Pure. */
|
|
2609
2109
|
function requireEdges(content, positions) {
|
|
2610
2110
|
const edges = [];
|
|
2611
2111
|
const re = new RegExp(REQUIRE_CALL.source, REQUIRE_CALL.flags);
|
|
2612
2112
|
for (let m = re.exec(content); m !== null; m = re.exec(content)) {
|
|
2613
2113
|
if (positions[m.index] === " ")
|
|
2614
|
-
continue;
|
|
2114
|
+
continue;
|
|
2615
2115
|
const specifier = m[2];
|
|
2616
2116
|
if (specifier === undefined)
|
|
2617
2117
|
continue;
|
|
@@ -2621,12 +2121,9 @@ function requireEdges(content, positions) {
|
|
|
2621
2121
|
}
|
|
2622
2122
|
return edges;
|
|
2623
2123
|
}
|
|
2624
|
-
/** Every import a module's runtime code makes - static, literal dynamic and `require` - in source
|
|
2625
|
-
* order. Pure. */
|
|
2626
2124
|
function importEdges(content, facts, file) {
|
|
2627
2125
|
const positions = codePositionMask(content);
|
|
2628
2126
|
const edges = staticImportEdges(content, facts, file, positions);
|
|
2629
|
-
// Without an `import(` or a `require` there is nothing for the other passes to find; skip them.
|
|
2630
2127
|
const dynamic = content.includes("import(") || /import\s+\(/.test(content);
|
|
2631
2128
|
const required = content.includes("require");
|
|
2632
2129
|
if (!dynamic && !required)
|
|
@@ -2637,29 +2134,18 @@ function importEdges(content, facts, file) {
|
|
|
2637
2134
|
edges.push(...requireEdges(content, positions));
|
|
2638
2135
|
return edges.sort((a, b) => a.index - b.index);
|
|
2639
2136
|
}
|
|
2640
|
-
/** The runtime imports of a module with the line each sits on, in source order. With `facts`, an
|
|
2641
|
-
* import the compiler erases (`import { type X }`) is none. Pure. */
|
|
2642
2137
|
export function importSites(content, file, facts) {
|
|
2643
2138
|
return importEdges(content, facts, file).map(({ specifier, index }) => ({
|
|
2644
2139
|
specifier,
|
|
2645
2140
|
line: lineAt(content, index),
|
|
2646
2141
|
}));
|
|
2647
2142
|
}
|
|
2648
|
-
/** The specifiers {@link importEdges} finds, static and literal dynamic, in source order. Pure. */
|
|
2649
2143
|
export function parseImports(content, facts, file) {
|
|
2650
2144
|
return importEdges(content, facts, file).map((e) => e.specifier);
|
|
2651
2145
|
}
|
|
2652
|
-
/** The server-only SINK an import specifier names directly (a `node:`/`bun:` builtin or a known
|
|
2653
|
-
* server-only package), or `undefined` if it isn't a by-name sink. Pure - the label is the specifier
|
|
2654
|
-
* itself (it's already the actionable name). */
|
|
2655
2146
|
export function directSinkSpecifier(spec) {
|
|
2656
2147
|
return isServerOnlySink(spec) ? spec : undefined;
|
|
2657
2148
|
}
|
|
2658
|
-
/**
|
|
2659
|
-
* Every module is read, parsed and resolved at most once, and the chain from a module is searched at
|
|
2660
|
-
* most once, however many routes reach it: per-route searches repeated all of that for every route
|
|
2661
|
-
* that shared a module, which made a check quadratic in the size of a shared graph.
|
|
2662
|
-
*/
|
|
2663
2149
|
function chainGraph(source) {
|
|
2664
2150
|
const { facts } = source;
|
|
2665
2151
|
const componentReceipts = source.componentReceipts ?? new Set();
|
|
@@ -2698,13 +2184,6 @@ function chainGraph(source) {
|
|
|
2698
2184
|
}
|
|
2699
2185
|
return found;
|
|
2700
2186
|
};
|
|
2701
|
-
/**
|
|
2702
|
-
* Breadth-first, so the first sink found is the nearest. A node's edges are its static and literal
|
|
2703
|
-
* dynamic imports; an edge is followed only into a project file `resolve` names, an alias included,
|
|
2704
|
-
* never into node_modules. A by-name sink import (`node:fs`, `postgres`), backend code, or a module
|
|
2705
|
-
* importing the `backend-only` marker ends the chain; a `*.fn.ts` module ships as its stub and is not
|
|
2706
|
-
* entered. The visited set keeps it cycle-free; there is no depth or size cap to cut a chain short.
|
|
2707
|
-
*/
|
|
2708
2187
|
const search = (start, startContent) => {
|
|
2709
2188
|
const seen = new Set([start]);
|
|
2710
2189
|
let frontier = [{ abs: start, content: startContent, chain: [start], modules: [start] }];
|
|
@@ -2757,11 +2236,6 @@ function chainGraph(source) {
|
|
|
2757
2236
|
facts,
|
|
2758
2237
|
};
|
|
2759
2238
|
}
|
|
2760
|
-
/**
|
|
2761
|
-
* The shortest import chain from `routeFile` to a server-only sink, `[routeFile, ...as-written
|
|
2762
|
-
* specifiers, sink]`, or `undefined` when none is reachable. Pure given `resolve`/`read`, so a fake
|
|
2763
|
-
* graph tests it.
|
|
2764
|
-
*/
|
|
2765
2239
|
export function walkServerOnlyChain(routeFile, routeContent, resolve, read, facts, componentReceipts = new Set()) {
|
|
2766
2240
|
return chainGraph({
|
|
2767
2241
|
resolve,
|
|
@@ -2770,24 +2244,10 @@ export function walkServerOnlyChain(routeFile, routeContent, resolve, read, fact
|
|
|
2770
2244
|
componentReceipts,
|
|
2771
2245
|
}).walk(routeFile, routeContent)?.chain;
|
|
2772
2246
|
}
|
|
2773
|
-
/**
|
|
2774
|
-
* The server-only chain finder for one check: called per browser module, it returns that module's
|
|
2775
|
-
* findings, reusing every module and chain an earlier call already searched.
|
|
2776
|
-
*/
|
|
2777
2247
|
export function createServerOnlyChains(source) {
|
|
2778
2248
|
const graph = chainGraph(source);
|
|
2779
2249
|
return (file, content, browserRoot = false) => serverOnlyChains(graph, file, content, browserRoot);
|
|
2780
2250
|
}
|
|
2781
|
-
/**
|
|
2782
|
-
* Resolve the FULL transitive server-only chain(s) for a route module, given a real fs-backed resolver +
|
|
2783
|
-
* reader. For each of the route's top-level imports, if a precise transitive walk finds a sink, the
|
|
2784
|
-
* finding carries the full chain; otherwise - when the first hop is itself a direct by-name sink the
|
|
2785
|
-
* regex scan already flags, or when a relative import can't be resolved - it falls back to the DIRECT
|
|
2786
|
-
* edge (`fallback: true`), never a fabricated chain. Returns one finding per offending top-level import,
|
|
2787
|
-
* de-duplicated to the shortest chain per first-hop specifier. A file that is not browser source
|
|
2788
|
-
* yields `[]`, unless `browserRoot` says the browser bundle loads it anyway (an app's `clientModule`).
|
|
2789
|
-
* One check should use {@link createServerOnlyChains}, which shares the work across modules.
|
|
2790
|
-
*/
|
|
2791
2251
|
export function resolveServerOnlyChains(file, content, resolve, read, facts, componentReceipts = new Set(), browserRoot = false) {
|
|
2792
2252
|
return createServerOnlyChains({
|
|
2793
2253
|
resolve,
|
|
@@ -2811,18 +2271,12 @@ function serverOnlyChains(graph, file, content, browserRoot) {
|
|
|
2811
2271
|
flaggedSpecifiers.add(specifier);
|
|
2812
2272
|
out.push({ file, line, snippet, specifier, chain, modules, fallback });
|
|
2813
2273
|
};
|
|
2814
|
-
// (1) A direct by-name sink (`node:fs`, `postgres`): the route imports it itself.
|
|
2815
2274
|
if (directSinkSpecifier(specifier) !== undefined) {
|
|
2816
2275
|
flag([file, specifier], false);
|
|
2817
2276
|
continue;
|
|
2818
2277
|
}
|
|
2819
|
-
// (2) A project import, relative or through an alias: walk from the resolved dependency and, if
|
|
2820
|
-
// it reaches a sink, report the full chain rooted at THIS route's import line.
|
|
2821
2278
|
const abs = graph.resolve(file, specifier);
|
|
2822
2279
|
if (abs === undefined) {
|
|
2823
|
-
// An installed package that declares itself backend is a sink. Any other name no project file
|
|
2824
|
-
// answers to can't be called server-only, except the `../db` convention, reported as the direct
|
|
2825
|
-
// edge with `fallback` saying the resolve was impossible.
|
|
2826
2280
|
if (graph.backendPackage(file, specifier))
|
|
2827
2281
|
flag([file, specifier], false);
|
|
2828
2282
|
else if (isServerOnly(specifier))
|
|
@@ -2831,7 +2285,6 @@ function serverOnlyChains(graph, file, content, browserRoot) {
|
|
|
2831
2285
|
}
|
|
2832
2286
|
if (graph.componentReceipts.has(abs))
|
|
2833
2287
|
continue;
|
|
2834
|
-
// A backend first hop and a marked module are sinks; a `*.fn.ts` hop ships as its stub.
|
|
2835
2288
|
if (isBackendModule(abs)) {
|
|
2836
2289
|
flag([file, specifier], false, [file, abs]);
|
|
2837
2290
|
continue;
|
|
@@ -2847,42 +2300,21 @@ function serverOnlyChains(graph, file, content, browserRoot) {
|
|
|
2847
2300
|
}
|
|
2848
2301
|
const sub = graph.walk(abs, depContent);
|
|
2849
2302
|
if (sub !== undefined) {
|
|
2850
|
-
// `sub` starts at the resolved dependency; the route names it by its as-written specifier.
|
|
2851
2303
|
flag([file, specifier, ...sub.chain.slice(1)], false, [file, ...sub.modules]);
|
|
2852
2304
|
continue;
|
|
2853
2305
|
}
|
|
2854
|
-
// (3) The `../db` convention with no deeper sink found: still surface the direct edge.
|
|
2855
2306
|
if (isServerOnly(specifier))
|
|
2856
2307
|
flag([file, specifier], true);
|
|
2857
2308
|
}
|
|
2858
2309
|
return out;
|
|
2859
2310
|
}
|
|
2860
|
-
// A route handler returning a raw `Response` (`=> new Response(`, `return Response.json(`, …) makes the
|
|
2861
|
-
// typed client infer `data: never` (`Jsonify<Response>` is `never`) - so frontend/backend drift detection
|
|
2862
|
-
// silently vanishes for that route. Advisory, not a failure: a raw Response is sometimes intended
|
|
2863
|
-
// (redirects, files, streams). Fix is to return a plain object, or declare `{ response: t.… }` to type it.
|
|
2864
2311
|
const RESPONSE_RETURN = /(?:=>\s*|return\s+)(?:new\s+Response|Response\s*\.\s*json)\s*\(/g;
|
|
2865
|
-
/**
|
|
2866
|
-
* Scan a backend module (one that calls `server(` or `createWebApp(`) for handlers returning a raw
|
|
2867
|
-
* `Response`, which collapses the typed client's `data` to `never`. Pure + line-accurate; returns `[]`
|
|
2868
|
-
* for any other file. With an AST it also follows what the lexical pattern cannot see: a local holding
|
|
2869
|
-
* the Response, the context's `json()`/`text()`, and - given `project` - a helper imported from a
|
|
2870
|
-
* relative module whose export returns one, reported at each route's return. It skips a handler the
|
|
2871
|
-
* client still types: one that also returns a plain value, or whose route declares `response`.
|
|
2872
|
-
*/
|
|
2873
2312
|
export function scanResponseRoutes(file, content, facts, project) {
|
|
2874
|
-
// Strip comments + template literals first: a commented-out or doc-example `return new Response(`
|
|
2875
|
-
// must not raise a spurious advisory. Lengths are preserved, so lineAt + the raw-line snippet align.
|
|
2876
2313
|
const code = stripComments(content);
|
|
2877
2314
|
if (!NIFRA_SERVER_CONSTRUCTION.test(code))
|
|
2878
2315
|
return [];
|
|
2879
2316
|
const out = [];
|
|
2880
2317
|
const lines = content.split("\n");
|
|
2881
|
-
// A `// nifra-expect NF-C007` comment (or the `raw-response` slug) marks an intentional raw Response
|
|
2882
|
-
// (a file/redirect that can't be a typed route), silencing this advisory with or without a reason.
|
|
2883
|
-
// It counts on the return line or in the comment block directly above, so a TRAILING comment on one
|
|
2884
|
-
// route's return line can't leak down onto the next route. `stripComments` blanks it in `code` (so it
|
|
2885
|
-
// never affects the match); the raw `lines` still carry it.
|
|
2886
2318
|
const report = (line) => {
|
|
2887
2319
|
if (commentBlockExpectation(lines, line, RAW_RESPONSE_EXPECTATION) !== undefined)
|
|
2888
2320
|
return;
|
|
@@ -2909,10 +2341,6 @@ export function scanResponseRoutes(file, content, facts, project) {
|
|
|
2909
2341
|
: facts.untypedResponseRoutes(source, importReturnsResponse);
|
|
2910
2342
|
RESPONSE_RETURN.lastIndex = 0;
|
|
2911
2343
|
for (let m = RESPONSE_RETURN.exec(code); m !== null; m = RESPONSE_RETURN.exec(code)) {
|
|
2912
|
-
// A parseable AST rejects `return new Response(` text that only lives in a normal string, one
|
|
2913
|
-
// outside a route handler (an auth stage's `rejected` helper, say), and one in a handler the client
|
|
2914
|
-
// still types: it returns a plain value too, or its route declares `response`. On malformed
|
|
2915
|
-
// source we keep the lexical candidate; the typecheck gate will report the syntax error.
|
|
2916
2344
|
if (facts !== undefined &&
|
|
2917
2345
|
source !== undefined &&
|
|
2918
2346
|
(facts.isResponseSyntaxAt(source, m.index) !== true || routes?.isUntypedAt(m.index) !== true))
|
|
@@ -2931,26 +2359,15 @@ export function scanResponseRoutes(file, content, facts, project) {
|
|
|
2931
2359
|
}
|
|
2932
2360
|
return out.sort((a, b) => a.line - b.line);
|
|
2933
2361
|
}
|
|
2934
|
-
/** What suppresses the {@link scanResponseRoutes} advisory for an intentional raw Response. */
|
|
2935
2362
|
const RAW_RESPONSE_EXPECTATION = ["NF-C007", "raw-response"];
|
|
2936
|
-
/** Walk the project's `.ts`/`.tsx` source (skipping deps and build output), calling `visit` per file.
|
|
2937
|
-
* Exported so `nifra doctor` ({@link ./doctor.ts}) scans the same source surface as `nifra check`.
|
|
2938
|
-
*
|
|
2939
|
-
* `includeTests` widens the surface to `*.test.ts`/`*.spec.ts`, which the default excludes. It exists
|
|
2940
|
-
* for `nifra doctor`: `tsc` compiles tests, so a test importing a package no manifest declares is a
|
|
2941
|
-
* build that a clean install cannot produce - the exact false confidence doctor is for. */
|
|
2942
2363
|
export async function walkSource(cwd, visit, opts = {}) {
|
|
2943
2364
|
const skip = opts.includeTests === true ? IGNORED_DIR : IGNORED;
|
|
2944
2365
|
const pattern = opts.scripts === true
|
|
2945
2366
|
? "**/*.{ts,tsx,mts,cts,jsx,js,mjs,cjs,svelte,vue}"
|
|
2946
2367
|
: "**/*.{ts,tsx,mts,cts}";
|
|
2947
|
-
// List candidates first (cheap - no reads), drop the built-in ignores, then exclude gitignored paths in
|
|
2948
|
-
// one batch before the (expensive) reads. So a gitignored generated/build tree is never read or scanned.
|
|
2949
2368
|
const rels = [];
|
|
2950
2369
|
for await (const rawRel of new Glob(pattern).scan({ cwd, dot: false })) {
|
|
2951
|
-
// A backslash is a filename character on POSIX; only Windows separators need normalizing.
|
|
2952
2370
|
const rel = sep === "\\" ? normalizeProjectPath(rawRel) : rawRel;
|
|
2953
|
-
// A `.js` file outside a zone is tooling (a bundler config, a script, a vendored asset), not app code.
|
|
2954
2371
|
if (opts.library !== true &&
|
|
2955
2372
|
PLAIN_SCRIPT_FILE.test(rel) &&
|
|
2956
2373
|
!ZONE_DIRECTORY.test(rel) &&
|
|
@@ -2960,7 +2377,6 @@ export async function walkSource(cwd, visit, opts = {}) {
|
|
|
2960
2377
|
rels.push(rel);
|
|
2961
2378
|
}
|
|
2962
2379
|
const ignored = await gitIgnored(cwd, rels);
|
|
2963
|
-
// Glob order is the filesystem's, so findings would come out in a different order on each platform.
|
|
2964
2380
|
for (const rel of rels.sort(codeUnitOrder)) {
|
|
2965
2381
|
if (ignored.has(rel))
|
|
2966
2382
|
continue;
|
|
@@ -2971,13 +2387,7 @@ export async function walkSource(cwd, visit, opts = {}) {
|
|
|
2971
2387
|
const PLAIN_SCRIPT_FILE = /\.[cm]?js$/;
|
|
2972
2388
|
const ZONE_DIRECTORY = /(?:^|\/)(?:routes|frontend|shared|backend)\//;
|
|
2973
2389
|
const ZONE_SUFFIX = /\.(?:frontend|shared|backend|fn)\.[^/]+$/;
|
|
2974
|
-
/** A single-file component: its `<script>` blocks are the code a build compiles. */
|
|
2975
2390
|
export const COMPONENT_FILE = /\.(?:svelte|vue)$/;
|
|
2976
|
-
/**
|
|
2977
|
-
* A `.svelte` or `.vue` file as the source scanners read it: the text of its `<script>` blocks where
|
|
2978
|
-
* they stand, and every other character blanked to a space with line breaks kept, so a finding's line
|
|
2979
|
-
* and column are the file's own. An unclosed `<script>` runs to the end of the file. Pure.
|
|
2980
|
-
*/
|
|
2981
2391
|
export function componentScripts(text) {
|
|
2982
2392
|
const blank = (part) => part.replace(/[^\n]/g, " ");
|
|
2983
2393
|
let out = "";
|
|
@@ -2989,7 +2399,6 @@ export function componentScripts(text) {
|
|
|
2989
2399
|
const close = text.indexOf(">", open);
|
|
2990
2400
|
if (close === -1)
|
|
2991
2401
|
break;
|
|
2992
|
-
// `<scripts>` or `<script-x>` is another element.
|
|
2993
2402
|
if (!/[\s>]/.test(text[open + 7] ?? "")) {
|
|
2994
2403
|
out += blank(text.slice(at, close + 1));
|
|
2995
2404
|
at = close + 1;
|
|
@@ -3005,51 +2414,37 @@ export function componentScripts(text) {
|
|
|
3005
2414
|
return out + blank(text.slice(at));
|
|
3006
2415
|
}
|
|
3007
2416
|
const bySite = (a, b) => codeUnitOrder(a.file, b.file) || a.line - b.line;
|
|
3008
|
-
/** Collect own-API `fetch()` findings across the project. */
|
|
3009
2417
|
export async function scanProject(cwd) {
|
|
3010
2418
|
const out = [];
|
|
3011
2419
|
await walkSource(cwd, (rel, content) => out.push(...scanFetchText(rel, content)));
|
|
3012
2420
|
return out.sort(bySite);
|
|
3013
2421
|
}
|
|
3014
|
-
// #7 - server-manifest drift. `server-manifest.ts` is a COMMITTED generated file (it bakes the route
|
|
3015
|
-
// list + client-entry hash for a disk-less worker). If `routes/` changes but the manifest isn't
|
|
3016
|
-
// regenerated, the worker serves a stale route table - a silent edge break that no other check catches.
|
|
3017
|
-
// We diff each committed manifest's imported route files against the live `routes/` tree.
|
|
3018
|
-
// The marker comment `generateServerManifest` emits at the top of the file - identifies a generated
|
|
3019
|
-
// manifest unambiguously (so a user file merely named `server-manifest.ts` isn't mistaken for one).
|
|
3020
2422
|
const GENERATED_MARKER = "GENERATED by @nifrajs/web generateServerManifest";
|
|
3021
|
-
// The first route-import specifier's prefix up to `routes/` (e.g. `./`, `../`, `./src/`) - used to
|
|
3022
|
-
// locate the routes dir relative to the manifest, and to strip to route-relative keys.
|
|
3023
2423
|
const ROUTES_PREFIX = /["'](\.{1,2}(?:\/[^"'/]+)*?\/routes\/)[^"']+["']/;
|
|
3024
|
-
// The files route discovery collects (mirrors `@nifrajs/web/fs`'s filter): route files by extension,
|
|
3025
|
-
// each route's backend half, and `_middleware` modules.
|
|
3026
2424
|
const ROUTE_FILE_EXT = /\.(tsx|jsx|svelte|vue|mdx)$/;
|
|
3027
2425
|
const ROUTE_BACKEND_HALF = /\.backend\.(?:[cm]?[jt]s)$/;
|
|
3028
2426
|
const MIDDLEWARE_FILE = /(?:^|\/)_middleware\.(?:ts|js)$/;
|
|
3029
|
-
/**
|
|
3030
|
-
* Scan the project for committed, generated `server-manifest.ts` files and report any that have drifted
|
|
3031
|
-
* from the live `routes/` tree. For each, the routes dir is derived from the manifest's own import
|
|
3032
|
-
* prefix (so a manifest that imports `../routes/x` is checked against the sibling `routes/`), its route
|
|
3033
|
-
* imports are parsed (`parseManifestRouteFiles`), and the set is diffed against the actual route files
|
|
3034
|
-
* on disk. A clean manifest yields no finding. Returns one finding per drifted manifest. Never throws on
|
|
3035
|
-
* a per-manifest miss (an unreadable routes dir is simply skipped).
|
|
3036
|
-
*/
|
|
3037
2427
|
export async function scanServerManifestDrift(cwd) {
|
|
3038
2428
|
const { parseManifestRouteFiles, diffManifestRoutes, isManifestInSync } = await import("@nifrajs/web/build");
|
|
3039
2429
|
const findings = [];
|
|
2430
|
+
const manifests = [];
|
|
3040
2431
|
for await (const rawRel of new Glob("**/server-manifest.ts").scan({ cwd, dot: false })) {
|
|
3041
2432
|
const rel = normalizeProjectPath(rawRel);
|
|
3042
|
-
if (IGNORED.test(rel))
|
|
2433
|
+
if (!IGNORED.test(rel))
|
|
2434
|
+
manifests.push(rel);
|
|
2435
|
+
}
|
|
2436
|
+
const ignored = await gitIgnored(cwd, manifests);
|
|
2437
|
+
for (const rel of manifests) {
|
|
2438
|
+
if (ignored.has(rel))
|
|
3043
2439
|
continue;
|
|
3044
2440
|
const source = await Bun.file(join(cwd, rel)).text();
|
|
3045
2441
|
if (!source.includes(GENERATED_MARKER))
|
|
3046
|
-
continue;
|
|
2442
|
+
continue;
|
|
3047
2443
|
const prefixMatch = ROUTES_PREFIX.exec(source);
|
|
3048
2444
|
if (prefixMatch?.[1] === undefined)
|
|
3049
|
-
continue;
|
|
2445
|
+
continue;
|
|
3050
2446
|
const routesPrefix = prefixMatch[1];
|
|
3051
2447
|
const manifestFiles = parseManifestRouteFiles(source, routesPrefix);
|
|
3052
|
-
// The routes dir sits at `<manifest dir>/<prefix>` - resolve it relative to the manifest file.
|
|
3053
2448
|
const manifestDir = rel.includes("/") ? rel.slice(0, rel.lastIndexOf("/")) : "";
|
|
3054
2449
|
const routesDir = join(cwd, manifestDir, routesPrefix);
|
|
3055
2450
|
let discovered;
|
|
@@ -3059,7 +2454,7 @@ export async function scanServerManifestDrift(cwd) {
|
|
|
3059
2454
|
.filter((f) => ROUTE_FILE_EXT.test(f) || ROUTE_BACKEND_HALF.test(f) || MIDDLEWARE_FILE.test(f));
|
|
3060
2455
|
}
|
|
3061
2456
|
catch {
|
|
3062
|
-
continue;
|
|
2457
|
+
continue;
|
|
3063
2458
|
}
|
|
3064
2459
|
const drift = diffManifestRoutes(manifestFiles, discovered);
|
|
3065
2460
|
if (!isManifestInSync(drift)) {
|