@nifrajs/cli 5.17.0 → 5.18.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +67 -0
- package/dist/check-diagnostics.d.ts +7 -0
- package/dist/check-diagnostics.d.ts.map +1 -1
- package/dist/check-diagnostics.js +3 -0
- package/dist/check-diagnostics.js.map +1 -1
- package/dist/check-scan-sql.d.ts +95 -0
- package/dist/check-scan-sql.d.ts.map +1 -0
- package/dist/check-scan-sql.js +1190 -0
- package/dist/check-scan-sql.js.map +1 -0
- package/dist/check-scan.d.ts +5 -93
- package/dist/check-scan.d.ts.map +1 -1
- package/dist/check-scan.js +20 -1207
- package/dist/check-scan.js.map +1 -1
- package/dist/check.d.ts.map +1 -1
- package/dist/check.js +9 -0
- package/dist/check.js.map +1 -1
- package/dist/cli.d.ts +2 -6
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +249 -80
- package/dist/cli.js.map +1 -1
- package/dist/command-catalog.d.ts +3 -0
- package/dist/command-catalog.d.ts.map +1 -1
- package/dist/command-catalog.js +18 -4
- package/dist/command-catalog.js.map +1 -1
- package/dist/frontend-guidance.js +1 -1
- package/dist/frontend-guidance.js.map +1 -1
- package/dist/internal/a11y-element.d.ts +33 -0
- package/dist/internal/a11y-element.d.ts.map +1 -0
- package/dist/internal/a11y-element.js +124 -0
- package/dist/internal/a11y-element.js.map +1 -0
- package/dist/internal/a11y-jsx.d.ts +12 -0
- package/dist/internal/a11y-jsx.d.ts.map +1 -0
- package/dist/internal/a11y-jsx.js +42 -0
- package/dist/internal/a11y-jsx.js.map +1 -0
- package/dist/internal/a11y-template.d.ts +11 -0
- package/dist/internal/a11y-template.d.ts.map +1 -0
- package/dist/internal/a11y-template.js +56 -0
- package/dist/internal/a11y-template.js.map +1 -0
- package/dist/internal/aria-data.d.ts +23 -0
- package/dist/internal/aria-data.d.ts.map +1 -0
- package/dist/internal/aria-data.js +220 -0
- package/dist/internal/aria-data.js.map +1 -0
- package/dist/internal/edit-distance.d.ts +3 -0
- package/dist/internal/edit-distance.d.ts.map +1 -0
- package/dist/internal/edit-distance.js +12 -0
- package/dist/internal/edit-distance.js.map +1 -0
- package/dist/internal/imported-as.d.ts +10 -0
- package/dist/internal/imported-as.d.ts.map +1 -0
- package/dist/internal/imported-as.js +23 -0
- package/dist/internal/imported-as.js.map +1 -0
- package/dist/internal/source-facts.d.ts +3 -0
- package/dist/internal/source-facts.d.ts.map +1 -1
- package/dist/internal/source-facts.js +2 -0
- package/dist/internal/source-facts.js.map +1 -1
- package/dist/internal/template-markup.d.ts +58 -0
- package/dist/internal/template-markup.d.ts.map +1 -0
- package/dist/internal/template-markup.js +221 -0
- package/dist/internal/template-markup.js.map +1 -0
- package/dist/internal/typescript-import.d.ts.map +1 -1
- package/dist/internal/typescript-import.js +11 -0
- package/dist/internal/typescript-import.js.map +1 -1
- package/dist/mcp-exec.d.ts.map +1 -1
- package/dist/mcp-exec.js +37 -23
- package/dist/mcp-exec.js.map +1 -1
- package/dist/mcp-http.js +1 -1
- package/dist/mcp-io.d.ts.map +1 -1
- package/dist/mcp-io.js +5 -3
- package/dist/mcp-io.js.map +1 -1
- package/dist/mcp-root.js +1 -1
- package/dist/mcp-root.js.map +1 -1
- package/dist/mcp-ws.d.ts.map +1 -1
- package/dist/mcp-ws.js +3 -2
- package/dist/mcp-ws.js.map +1 -1
- package/dist/migrate-layout-config.d.ts +63 -0
- package/dist/migrate-layout-config.d.ts.map +1 -0
- package/dist/migrate-layout-config.js +507 -0
- package/dist/migrate-layout-config.js.map +1 -0
- package/dist/migrate-layout-split.d.ts +46 -0
- package/dist/migrate-layout-split.d.ts.map +1 -0
- package/dist/migrate-layout-split.js +687 -0
- package/dist/migrate-layout-split.js.map +1 -0
- package/dist/migrate-layout.d.ts +4 -24
- package/dist/migrate-layout.d.ts.map +1 -1
- package/dist/migrate-layout.js +8 -1183
- package/dist/migrate-layout.js.map +1 -1
- package/dist/output-schemas.d.ts.map +1 -1
- package/dist/output-schemas.js +78 -10
- package/dist/output-schemas.js.map +1 -1
- package/dist/recipes/5.18.0.d.ts +9 -0
- package/dist/recipes/5.18.0.d.ts.map +1 -0
- package/dist/recipes/5.18.0.js +56 -0
- package/dist/recipes/5.18.0.js.map +1 -0
- package/dist/recipes/index.d.ts.map +1 -1
- package/dist/recipes/index.js +2 -0
- package/dist/recipes/index.js.map +1 -1
- package/dist/review.d.ts.map +1 -1
- package/dist/review.js +6 -0
- package/dist/review.js.map +1 -1
- package/dist/rules/a11y.d.ts +5 -0
- package/dist/rules/a11y.d.ts.map +1 -0
- package/dist/rules/a11y.js +78 -0
- package/dist/rules/a11y.js.map +1 -0
- package/dist/rules/codes.d.ts +6 -0
- package/dist/rules/codes.d.ts.map +1 -1
- package/dist/rules/codes.js +6 -0
- package/dist/rules/codes.js.map +1 -1
- package/dist/rules/comment-markers.js +1 -1
- package/dist/rules/comment-markers.js.map +1 -1
- package/dist/rules/explanations.d.ts.map +1 -1
- package/dist/rules/explanations.js +30 -0
- package/dist/rules/explanations.js.map +1 -1
- package/dist/rules/host-exposure.d.ts +23 -0
- package/dist/rules/host-exposure.d.ts.map +1 -0
- package/dist/rules/host-exposure.js +380 -0
- package/dist/rules/host-exposure.js.map +1 -0
- package/dist/rules/internal-links.d.ts.map +1 -1
- package/dist/rules/internal-links.js +16 -141
- package/dist/rules/internal-links.js.map +1 -1
- package/dist/rules/islands.d.ts +54 -0
- package/dist/rules/islands.d.ts.map +1 -1
- package/dist/rules/islands.js +577 -80
- package/dist/rules/islands.js.map +1 -1
- package/dist/rules/security.d.ts +1 -0
- package/dist/rules/security.d.ts.map +1 -1
- package/dist/rules/security.js +34 -7
- package/dist/rules/security.js.map +1 -1
- package/dist/runtime-differences.js +3 -3
- package/dist/runtime-differences.js.map +1 -1
- package/dist/scaffold.d.ts +1 -1
- package/dist/scaffold.d.ts.map +1 -1
- package/dist/scaffold.js +2 -2
- package/dist/scaffold.js.map +1 -1
- package/dist/source-rewrites.d.ts.map +1 -1
- package/dist/source-rewrites.js +2 -19
- package/dist/source-rewrites.js.map +1 -1
- package/docs/examples.json +4 -4
- package/docs/llms-full.txt +422 -42
- package/docs/types.json +466 -56
- package/package.json +12 -12
- package/src/check-diagnostics.ts +11 -0
- package/src/check-scan-sql.ts +1746 -0
- package/src/check-scan.ts +34 -1754
- package/src/check.ts +10 -1
- package/src/cli.ts +258 -98
- package/src/command-catalog.ts +21 -4
- package/src/frontend-guidance.ts +1 -1
- package/src/internal/a11y-element.ts +227 -0
- package/src/internal/a11y-jsx.ts +54 -0
- package/src/internal/a11y-template.ts +74 -0
- package/src/internal/aria-data.ts +242 -0
- package/src/internal/edit-distance.ts +16 -0
- package/src/internal/imported-as.ts +30 -0
- package/src/internal/source-facts.ts +4 -0
- package/src/internal/template-markup.ts +270 -0
- package/src/internal/typescript-import.ts +15 -0
- package/src/mcp-exec.ts +43 -22
- package/src/mcp-http.ts +1 -1
- package/src/mcp-io.ts +5 -3
- package/src/mcp-root.ts +1 -1
- package/src/mcp-ws.ts +3 -2
- package/src/migrate-layout-config.ts +615 -0
- package/src/migrate-layout-split.ts +870 -0
- package/src/migrate-layout.ts +37 -1468
- package/src/output-schemas.ts +85 -17
- package/src/recipes/5.18.0.ts +63 -0
- package/src/recipes/index.ts +2 -0
- package/src/review.ts +6 -0
- package/src/rules/a11y.ts +119 -0
- package/src/rules/codes.ts +6 -0
- package/src/rules/comment-markers.ts +2 -2
- package/src/rules/explanations.ts +30 -0
- package/src/rules/host-exposure.ts +531 -0
- package/src/rules/internal-links.ts +21 -154
- package/src/rules/islands.ts +698 -86
- package/src/rules/security.ts +48 -7
- package/src/runtime-differences.ts +3 -3
- package/src/scaffold.ts +3 -3
- package/src/source-rewrites.ts +2 -15
package/src/check-scan.ts
CHANGED
|
@@ -5,23 +5,14 @@
|
|
|
5
5
|
* source text plus injected module/type resolvers, which keeps the scanner seam independently testable.
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
|
-
import {
|
|
9
|
-
import { dirname, isAbsolute, join, posix, resolve, sep } from "node:path"
|
|
8
|
+
import { join, posix, sep } from "node:path"
|
|
10
9
|
import { isServerPackageSpecifier } from "@nifrajs/web/zones"
|
|
11
10
|
import { Glob } from "bun"
|
|
12
|
-
import type * as TSApi from "typescript"
|
|
13
11
|
import { codeUnitOrder } from "./internal/code-unit-order.ts"
|
|
14
12
|
import { gitIgnored } from "./internal/git-ignored.ts"
|
|
15
13
|
import { lineAt } from "./internal/line-at.ts"
|
|
16
14
|
import { toPosix } from "./internal/posix-path.ts"
|
|
17
|
-
import { realpathOrSelf } from "./internal/realpath-or-self.ts"
|
|
18
|
-
import { scriptKindOf } from "./internal/script-kind.ts"
|
|
19
15
|
import type { SourceFacts } from "./internal/source-facts.ts"
|
|
20
|
-
import {
|
|
21
|
-
loadProjectTypeScript,
|
|
22
|
-
type TypeScriptApi,
|
|
23
|
-
type TypeScriptSourceIndex,
|
|
24
|
-
} from "./internal/typescript-import.ts"
|
|
25
16
|
import { commentBlockExpectation } from "./rules/comment-markers.ts"
|
|
26
17
|
|
|
27
18
|
export interface SourceFinding {
|
|
@@ -72,7 +63,7 @@ export const SIMPLE_REWRITE_METHODS = new Set(["GET", "DELETE", "HEAD", "OPTIONS
|
|
|
72
63
|
|
|
73
64
|
// Don't scan deps, build output, or generated client entries. `dist(-<runtime>)?` also covers
|
|
74
65
|
// per-runtime output dirs (dist-bun/dist-node/dist-deno/dist-vercel). Never source, for any scan.
|
|
75
|
-
const IGNORED_DIR =
|
|
66
|
+
export const IGNORED_DIR =
|
|
76
67
|
/(^|\/)(node_modules|dist(-[a-z0-9]+)?|build|\.nifra|\.git|\.wrangler|coverage)\//
|
|
77
68
|
// A test/spec module. Excluded from `nifra check`'s scans, which are about what SHIPS - a test
|
|
78
69
|
// legitimately drives `fetch`, hand-rolls a client, and calls a route directly. It is NOT excluded from
|
|
@@ -223,7 +214,8 @@ interface SimpleFetchCall {
|
|
|
223
214
|
|
|
224
215
|
function parseQuotedLiteral(raw: string): string | undefined {
|
|
225
216
|
try {
|
|
226
|
-
|
|
217
|
+
const value: unknown = JSON.parse(raw)
|
|
218
|
+
return typeof value === "string" ? value : undefined
|
|
227
219
|
} catch {
|
|
228
220
|
if (!raw.startsWith("'") || !raw.endsWith("'")) return undefined
|
|
229
221
|
try {
|
|
@@ -234,9 +226,9 @@ function parseQuotedLiteral(raw: string): string | undefined {
|
|
|
234
226
|
const inner = raw.slice(1, -1)
|
|
235
227
|
let body = ""
|
|
236
228
|
for (let i = 0; i < inner.length; i++) {
|
|
237
|
-
const ch = inner
|
|
229
|
+
const ch = inner.charAt(i)
|
|
238
230
|
if (ch === "\\" && i + 1 < inner.length) {
|
|
239
|
-
const next = inner
|
|
231
|
+
const next = inner.charAt(i + 1)
|
|
240
232
|
body += next === "'" ? "'" : ch + next
|
|
241
233
|
i++
|
|
242
234
|
} else if (ch === '"') {
|
|
@@ -245,7 +237,8 @@ function parseQuotedLiteral(raw: string): string | undefined {
|
|
|
245
237
|
body += ch
|
|
246
238
|
}
|
|
247
239
|
}
|
|
248
|
-
|
|
240
|
+
const value: unknown = JSON.parse(`"${body}"`)
|
|
241
|
+
return typeof value === "string" ? value : undefined
|
|
249
242
|
} catch {
|
|
250
243
|
return undefined
|
|
251
244
|
}
|
|
@@ -753,14 +746,25 @@ export function scanStaticRouteText(
|
|
|
753
746
|
facts?: SourceFacts,
|
|
754
747
|
/** Project files by forward-slash relative path, to resolve a path constant imported from one. */
|
|
755
748
|
project?: ReadonlyMap<string, string>,
|
|
749
|
+
): StaticRouteFinding[] {
|
|
750
|
+
return scanStaticRegistrations(file, content, facts, project)
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
function scanStaticRegistrations(
|
|
754
|
+
file: string,
|
|
755
|
+
content: string,
|
|
756
|
+
facts: SourceFacts | undefined,
|
|
757
|
+
project: ReadonlyMap<string, string> | undefined,
|
|
758
|
+
verbs?: ReadonlySet<string>,
|
|
756
759
|
): StaticRouteFinding[] {
|
|
757
760
|
const code = stripComments(content)
|
|
758
761
|
if (!isPotentialBackendSource(code, file, project)) return []
|
|
762
|
+
const methods = verbs === undefined && code.includes(METHODS_SUBPATH)
|
|
759
763
|
return [
|
|
760
|
-
...scanRoutePattern(file, content, code, ROUTE_REGISTRATION_DQ, facts),
|
|
761
|
-
...scanRoutePattern(file, content, code, ROUTE_REGISTRATION_SQ, facts),
|
|
762
|
-
...(
|
|
763
|
-
...scanRouteArguments(file, content, facts, project).routes,
|
|
764
|
+
...scanRoutePattern(file, content, code, ROUTE_REGISTRATION_DQ, facts, verbs),
|
|
765
|
+
...scanRoutePattern(file, content, code, ROUTE_REGISTRATION_SQ, facts, verbs),
|
|
766
|
+
...(methods ? scanMethodRoutes(file, content, code, facts) : []),
|
|
767
|
+
...scanRouteArguments(file, content, facts, project, verbs).routes,
|
|
764
768
|
].sort(bySite)
|
|
765
769
|
}
|
|
766
770
|
|
|
@@ -951,13 +955,7 @@ export function scanStaticSocketText(
|
|
|
951
955
|
/** Project files by forward-slash relative path, to resolve a path constant imported from one. */
|
|
952
956
|
project?: ReadonlyMap<string, string>,
|
|
953
957
|
): StaticRouteFinding[] {
|
|
954
|
-
|
|
955
|
-
if (!isPotentialBackendSource(code, file, project)) return []
|
|
956
|
-
return [
|
|
957
|
-
...scanRoutePattern(file, content, code, ROUTE_REGISTRATION_DQ, facts, SOCKET_VERB),
|
|
958
|
-
...scanRoutePattern(file, content, code, ROUTE_REGISTRATION_SQ, facts, SOCKET_VERB),
|
|
959
|
-
...scanRouteArguments(file, content, facts, project, SOCKET_VERB).routes,
|
|
960
|
-
].sort(bySite)
|
|
958
|
+
return scanStaticRegistrations(file, content, facts, project, SOCKET_VERB)
|
|
961
959
|
}
|
|
962
960
|
|
|
963
961
|
/** Routes from `all()` and `method()`, one per literal method name; a computed name is not guessed. */
|
|
@@ -1017,1732 +1015,14 @@ function scanMethodRoutes(
|
|
|
1017
1015
|
return out
|
|
1018
1016
|
}
|
|
1019
1017
|
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
* substitutions separately and binds them; that is the parameterised form, not a bypass of it.
|
|
1029
|
-
* - A literal with no substitution at all. `db.query("SELECT … WHERE id = ?")` is the shape being
|
|
1030
|
-
* argued for.
|
|
1031
|
-
*
|
|
1032
|
-
* A SQL keyword is required in the literal, so `cache.query(`user:${id}`)` stays quiet. The named
|
|
1033
|
-
* escape hatches (`$queryRawUnsafe`, `sql.unsafe`) are flagged on the call alone: their whole purpose
|
|
1034
|
-
* is to take a statement as text, and a substitution in one is the exact thing the name warns about.
|
|
1035
|
-
*/
|
|
1036
|
-
const SQL_METHODS = new Set([
|
|
1037
|
-
"query",
|
|
1038
|
-
"queryRaw",
|
|
1039
|
-
"prepare",
|
|
1040
|
-
"exec",
|
|
1041
|
-
"execute",
|
|
1042
|
-
"run",
|
|
1043
|
-
"unsafe",
|
|
1044
|
-
"$queryRawUnsafe",
|
|
1045
|
-
"$executeRawUnsafe",
|
|
1046
|
-
"raw",
|
|
1047
|
-
])
|
|
1048
|
-
const SQL_KEYWORD =
|
|
1049
|
-
/\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
|
|
1050
|
-
const ALWAYS_UNSAFE = new Set(["unsafe", "$queryRawUnsafe", "$executeRawUnsafe", "raw"])
|
|
1051
|
-
/** Driver calls that take a statement under names that are everyday words elsewhere (`map.get`,
|
|
1052
|
-
* `client.get("/users/update")`): node-sqlite3's `all`/`get`/`each` and pg-promise's result-shaping
|
|
1053
|
-
* calls. One of these, and any bare call, is judged by whether its text starts like a statement. */
|
|
1054
|
-
const DRIVER_READ_METHODS = new Set([
|
|
1055
|
-
"all",
|
|
1056
|
-
"get",
|
|
1057
|
-
"each",
|
|
1058
|
-
"any",
|
|
1059
|
-
"one",
|
|
1060
|
-
"none",
|
|
1061
|
-
"many",
|
|
1062
|
-
"oneOrNone",
|
|
1063
|
-
"manyOrNone",
|
|
1064
|
-
"result",
|
|
1065
|
-
"multi",
|
|
1066
|
-
"multiResult",
|
|
1067
|
-
])
|
|
1068
|
-
const STATEMENT_START =
|
|
1069
|
-
/^\s*\(?\s*(?:select|insert|update|delete|with|replace|merge|create|drop|alter|truncate|pragma)\s/i
|
|
1070
|
-
|
|
1071
|
-
interface SqlExpressionShape {
|
|
1072
|
-
readonly staticText: string
|
|
1073
|
-
readonly dynamic: boolean
|
|
1074
|
-
readonly concatenated: boolean
|
|
1075
|
-
readonly literal: boolean
|
|
1076
|
-
readonly parameterizedTag: boolean
|
|
1077
|
-
}
|
|
1078
|
-
|
|
1079
|
-
/** Module-scope `const` initializers by name - the one binding form the SQL scanner resolves. */
|
|
1080
|
-
type ModuleConsts = ReadonlyMap<string, TSApi.Expression>
|
|
1081
|
-
|
|
1082
|
-
/** A name some other module exports, named exactly as the edge that reaches it writes it. */
|
|
1083
|
-
interface ExportEdge {
|
|
1084
|
-
readonly specifier: string
|
|
1085
|
-
readonly exported: string
|
|
1086
|
-
}
|
|
1087
|
-
|
|
1088
|
-
/**
|
|
1089
|
-
* One module's provable module-scope bindings: its top-level `const` initializers plus the exact
|
|
1090
|
-
* import/export edges this scan is allowed to follow.
|
|
1091
|
-
*
|
|
1092
|
-
* Everything absent from these maps stays unresolved, and an unresolved interpolation keeps flagging.
|
|
1093
|
-
* That is the whole safety argument: resolution can only ever make this rule QUIETER, so a form the
|
|
1094
|
-
* scan cannot prove must fall out as "unknown" rather than be guessed at. Deliberately absent:
|
|
1095
|
-
* `export default`, `export let`/`var`, destructured or computed names, default and namespace imports,
|
|
1096
|
-
* `export * as ns`, `require`, and dynamic `import()`.
|
|
1097
|
-
*/
|
|
1098
|
-
interface SqlModuleScope {
|
|
1099
|
-
/** The module's identity - an absolute path from the loader, or the entry file's path as given. Keys
|
|
1100
|
-
* the parsed-scope cache and the cycle guard, and is the base its own specifiers resolve against. */
|
|
1101
|
-
readonly id: string
|
|
1102
|
-
readonly consts: ModuleConsts
|
|
1103
|
-
/** Local name bound by `import { X as local }` → the edge that provides it. */
|
|
1104
|
-
readonly imports: ReadonlyMap<string, ExportEdge>
|
|
1105
|
-
/** Exported name → the local name it reads (`export { a as b }` → `b` → `a`). */
|
|
1106
|
-
readonly localExports: ReadonlyMap<string, string>
|
|
1107
|
-
/** Exported name → another module's export (`export { a as b } from "./m"`). */
|
|
1108
|
-
readonly reExports: ReadonlyMap<string, ExportEdge>
|
|
1109
|
-
/** `export * from "./m"` specifiers, in source order. */
|
|
1110
|
-
readonly starExports: readonly string[]
|
|
1111
|
-
}
|
|
1112
|
-
|
|
1113
|
-
/** Read one module's top-level `const` bindings and its import/export edges. Pure syntax - no checker,
|
|
1114
|
-
* no filesystem. Destructured names, `let`, `var`, and anything nested stay out on purpose: a
|
|
1115
|
-
* module-scope `const` is the only form that provably cannot carry request data. */
|
|
1116
|
-
function sqlModuleScope(ts: TypeScriptApi, id: string, source: TSApi.SourceFile): SqlModuleScope {
|
|
1117
|
-
const consts = new Map<string, TSApi.Expression>()
|
|
1118
|
-
const imports = new Map<string, ExportEdge>()
|
|
1119
|
-
const localExports = new Map<string, string>()
|
|
1120
|
-
const reExports = new Map<string, ExportEdge>()
|
|
1121
|
-
const starExports: string[] = []
|
|
1122
|
-
for (const statement of source.statements) {
|
|
1123
|
-
if (ts.isVariableStatement(statement)) {
|
|
1124
|
-
if ((statement.declarationList.flags & ts.NodeFlags.Const) === 0) continue
|
|
1125
|
-
const exported =
|
|
1126
|
-
statement.modifiers?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword) === true
|
|
1127
|
-
for (const declaration of statement.declarationList.declarations) {
|
|
1128
|
-
if (!ts.isIdentifier(declaration.name) || declaration.initializer === undefined) continue
|
|
1129
|
-
consts.set(declaration.name.text, declaration.initializer)
|
|
1130
|
-
if (exported) localExports.set(declaration.name.text, declaration.name.text)
|
|
1131
|
-
}
|
|
1132
|
-
continue
|
|
1133
|
-
}
|
|
1134
|
-
if (ts.isImportDeclaration(statement)) {
|
|
1135
|
-
const clause = statement.importClause
|
|
1136
|
-
if (clause === undefined || clause.isTypeOnly) continue
|
|
1137
|
-
if (!ts.isStringLiteral(statement.moduleSpecifier)) continue
|
|
1138
|
-
const bindings = clause.namedBindings
|
|
1139
|
-
// Only `import { X }` / `import { X as local }`. A default or namespace import binds a value
|
|
1140
|
-
// whose contents this scan cannot prove, so it stays unbound and every use of it flags.
|
|
1141
|
-
if (bindings === undefined || !ts.isNamedImports(bindings)) continue
|
|
1142
|
-
for (const element of bindings.elements) {
|
|
1143
|
-
if (element.isTypeOnly) continue
|
|
1144
|
-
imports.set(element.name.text, {
|
|
1145
|
-
specifier: statement.moduleSpecifier.text,
|
|
1146
|
-
exported: element.propertyName?.text ?? element.name.text,
|
|
1147
|
-
})
|
|
1148
|
-
}
|
|
1149
|
-
continue
|
|
1150
|
-
}
|
|
1151
|
-
if (!ts.isExportDeclaration(statement) || statement.isTypeOnly) continue
|
|
1152
|
-
const from = statement.moduleSpecifier
|
|
1153
|
-
if (from !== undefined && !ts.isStringLiteral(from)) continue
|
|
1154
|
-
const clause = statement.exportClause
|
|
1155
|
-
if (clause === undefined) {
|
|
1156
|
-
// No clause and a specifier is `export * from "./m"`. `export * as ns from "./m"` carries a
|
|
1157
|
-
// NamespaceExport clause instead and falls out below, unresolved, which is what we want.
|
|
1158
|
-
if (from !== undefined) starExports.push(from.text)
|
|
1159
|
-
continue
|
|
1160
|
-
}
|
|
1161
|
-
if (!ts.isNamedExports(clause)) continue
|
|
1162
|
-
for (const element of clause.elements) {
|
|
1163
|
-
if (element.isTypeOnly) continue
|
|
1164
|
-
const local = element.propertyName?.text ?? element.name.text
|
|
1165
|
-
if (from === undefined) localExports.set(element.name.text, local)
|
|
1166
|
-
else reExports.set(element.name.text, { specifier: from.text, exported: local })
|
|
1167
|
-
}
|
|
1168
|
-
}
|
|
1169
|
-
return { id, consts, imports, localExports, reExports, starExports }
|
|
1170
|
-
}
|
|
1171
|
-
|
|
1172
|
-
/** A module's identity + source, as resolved from a specifier. `id` must be stable and absolute: it
|
|
1173
|
-
* keys the parsed-scope cache, seeds the cycle guard, and is what the module's own relative specifiers
|
|
1174
|
-
* resolve against. */
|
|
1175
|
-
export interface SqlModuleSource {
|
|
1176
|
-
readonly id: string
|
|
1177
|
-
readonly content: string
|
|
1178
|
-
}
|
|
1179
|
-
|
|
1180
|
-
/**
|
|
1181
|
-
* Resolves a specifier written in the module `fromModule` to the target's identity + source, or
|
|
1182
|
-
* `undefined` when it cannot be resolved, read, or proved to be in-project source.
|
|
1183
|
-
*
|
|
1184
|
-
* Injected rather than built in, for the same reason {@link ModuleResolver} is: it keeps
|
|
1185
|
-
* {@link scanInterpolatedSql} pure and filesystem-free, so the resolution rules can be unit-tested
|
|
1186
|
-
* against a virtual module graph. {@link createProjectSqlImports} is the on-disk implementation.
|
|
1187
|
-
*/
|
|
1188
|
-
export type SqlModuleLoader = (fromModule: string, specifier: string) => SqlModuleSource | undefined
|
|
1189
|
-
|
|
1190
|
-
/** Cross-module resolution state for one run: the loader plus a parsed-scope cache, so a fragments
|
|
1191
|
-
* module imported by fifty callers is read and parsed once. A cached `undefined` is a REFUSAL (the
|
|
1192
|
-
* module did not parse), cached so it is not re-attempted. Build with {@link createSqlImports}. */
|
|
1193
|
-
export interface SqlImports {
|
|
1194
|
-
readonly load: SqlModuleLoader
|
|
1195
|
-
readonly scopes: Map<string, SqlModuleScope | undefined>
|
|
1196
|
-
}
|
|
1197
|
-
|
|
1198
|
-
export const createSqlImports = (load: SqlModuleLoader): SqlImports => ({
|
|
1199
|
-
load,
|
|
1200
|
-
scopes: new Map(),
|
|
1201
|
-
})
|
|
1202
|
-
|
|
1203
|
-
/** Where an expression's identifiers are read: the module the expression physically lives in, plus the
|
|
1204
|
-
* run's cross-module state. `imports === undefined` is same-file-only resolution - the behavior before
|
|
1205
|
-
* imported fragments were followed, and still what an unconfigured `scanInterpolatedSql` call does. */
|
|
1206
|
-
interface SqlScope {
|
|
1207
|
-
readonly module: SqlModuleScope
|
|
1208
|
-
readonly imports: SqlImports | undefined
|
|
1209
|
-
}
|
|
1210
|
-
|
|
1211
|
-
/** Parse a module for the SQL scan, or `undefined` when it does not parse. Malformed source is already
|
|
1212
|
-
* a typecheck failure; parser recovery nodes are not evidence of anything, so a file that fails to
|
|
1213
|
-
* parse contributes no findings and proves no constant. */
|
|
1214
|
-
function parseSqlSource(
|
|
1215
|
-
ts: TypeScriptApi,
|
|
1216
|
-
file: string,
|
|
1217
|
-
content: string,
|
|
1218
|
-
): TSApi.SourceFile | undefined {
|
|
1219
|
-
const kind = scriptKindOf(ts, file)
|
|
1220
|
-
let source: TSApi.SourceFile
|
|
1221
|
-
try {
|
|
1222
|
-
source = ts.createSourceFile(file, content, ts.ScriptTarget.Latest, true, kind)
|
|
1223
|
-
} catch {
|
|
1224
|
-
// TypeScript 7 parses only the files its session preloaded; an imported module outside that set
|
|
1225
|
-
// proves no constant, like one that does not parse.
|
|
1226
|
-
return undefined
|
|
1227
|
-
}
|
|
1228
|
-
const parseDiagnostics = (
|
|
1229
|
-
source as TSApi.SourceFile & { readonly parseDiagnostics?: readonly TSApi.Diagnostic[] }
|
|
1230
|
-
).parseDiagnostics
|
|
1231
|
-
return parseDiagnostics !== undefined && parseDiagnostics.length > 0 ? undefined : source
|
|
1232
|
-
}
|
|
1233
|
-
|
|
1234
|
-
/** Module-boundary hops one name may cross. Barrels are why it is not 1: `route → index → fragments`
|
|
1235
|
-
* already spends two, and the third leaves room for one more layer without letting the scan wander the
|
|
1236
|
-
* module graph. Past the cap the name is unresolved, so the interpolation flags. */
|
|
1237
|
-
const SQL_IMPORT_HOPS = 3
|
|
1238
|
-
|
|
1239
|
-
/** Load + parse the module a specifier names, through the run's cache. */
|
|
1240
|
-
function loadSqlModuleScope(
|
|
1241
|
-
ts: TypeScriptApi,
|
|
1242
|
-
imports: SqlImports,
|
|
1243
|
-
fromModule: string,
|
|
1244
|
-
specifier: string,
|
|
1245
|
-
): SqlModuleScope | undefined {
|
|
1246
|
-
const loaded = imports.load(fromModule, specifier)
|
|
1247
|
-
if (loaded === undefined) return undefined
|
|
1248
|
-
if (imports.scopes.has(loaded.id)) return imports.scopes.get(loaded.id)
|
|
1249
|
-
const source = parseSqlSource(ts, loaded.id, loaded.content)
|
|
1250
|
-
const scope = source === undefined ? undefined : sqlModuleScope(ts, loaded.id, source)
|
|
1251
|
-
imports.scopes.set(loaded.id, scope)
|
|
1252
|
-
return scope
|
|
1253
|
-
}
|
|
1254
|
-
|
|
1255
|
-
/** One exported name resolved to the `const` initializer behind it, together with the scope that
|
|
1256
|
-
* initializer's OWN identifiers must be read in. */
|
|
1257
|
-
interface ResolvedExport {
|
|
1258
|
-
readonly expression: TSApi.Expression
|
|
1259
|
-
readonly scope: SqlModuleScope
|
|
1260
|
-
}
|
|
1261
|
-
|
|
1262
|
-
/**
|
|
1263
|
-
* Follow an exported name to its `const` initializer, across re-export hops.
|
|
1264
|
-
*
|
|
1265
|
-
* Handles the three forms a fragments module actually uses: `export const NAME = …`, the two-statement
|
|
1266
|
-
* `const NAME = …; export { NAME }` (including the pass-through `import { A } …; export { A }`), and
|
|
1267
|
-
* barrels - `export { X } from "./m"` and `export * from "./m"`. Bounded by {@link SQL_IMPORT_HOPS} and
|
|
1268
|
-
* a per-chain visited set, so a cyclic barrel terminates instead of recursing.
|
|
1269
|
-
*
|
|
1270
|
-
* Two `export *` sources providing the same name is a conflict, and the scan refuses rather than
|
|
1271
|
-
* picking one: guessing here would silence a real finding.
|
|
1272
|
-
*/
|
|
1273
|
-
function resolveExportedConst(
|
|
1274
|
-
ts: TypeScriptApi,
|
|
1275
|
-
imports: SqlImports,
|
|
1276
|
-
scope: SqlModuleScope,
|
|
1277
|
-
name: string,
|
|
1278
|
-
hops: number,
|
|
1279
|
-
seen: ReadonlySet<string>,
|
|
1280
|
-
): ResolvedExport | undefined {
|
|
1281
|
-
if (hops > SQL_IMPORT_HOPS) return undefined
|
|
1282
|
-
const key = `${scope.id}#${name}`
|
|
1283
|
-
if (seen.has(key)) return undefined
|
|
1284
|
-
const nextSeen = new Set(seen).add(key)
|
|
1285
|
-
const follow = (edge: ExportEdge): ResolvedExport | undefined => {
|
|
1286
|
-
const target = loadSqlModuleScope(ts, imports, scope.id, edge.specifier)
|
|
1287
|
-
return target === undefined
|
|
1288
|
-
? undefined
|
|
1289
|
-
: resolveExportedConst(ts, imports, target, edge.exported, hops + 1, nextSeen)
|
|
1290
|
-
}
|
|
1291
|
-
const local = scope.localExports.get(name)
|
|
1292
|
-
if (local !== undefined) {
|
|
1293
|
-
const initializer = scope.consts.get(local)
|
|
1294
|
-
if (initializer !== undefined) return { expression: initializer, scope }
|
|
1295
|
-
// `import { A } from "./a"; export { A }` - the same pass-through as `export { A } from "./a"`,
|
|
1296
|
-
// written in two statements. Anything else the name could be (a `let`, a function, a class) has no
|
|
1297
|
-
// initializer in `consts` and no import edge, so it lands on `undefined` and flags.
|
|
1298
|
-
const via = scope.imports.get(local)
|
|
1299
|
-
return via === undefined ? undefined : follow(via)
|
|
1300
|
-
}
|
|
1301
|
-
const reExported = scope.reExports.get(name)
|
|
1302
|
-
if (reExported !== undefined) return follow(reExported)
|
|
1303
|
-
let found: ResolvedExport | undefined
|
|
1304
|
-
for (const specifier of scope.starExports) {
|
|
1305
|
-
const hit = follow({ specifier, exported: name })
|
|
1306
|
-
if (hit === undefined) continue
|
|
1307
|
-
if (found !== undefined) return undefined
|
|
1308
|
-
found = hit
|
|
1309
|
-
}
|
|
1310
|
-
return found
|
|
1311
|
-
}
|
|
1312
|
-
|
|
1313
|
-
/** Whether `name`, read at `at`, might be re-declared by anything between the read and module scope.
|
|
1314
|
-
* Conservative on purpose: the OUTERMOST enclosing function/block subtree is scanned for ANY binding
|
|
1315
|
-
* of the name (parameter, `var`/`let`/`const`, catch, local function, destructuring element) - so a
|
|
1316
|
-
* hoisted `var` in a sibling block, or a binding in a branch that never runs, still refuses
|
|
1317
|
-
* resolution. Over-refusal flags a safe line (the pre-feature behavior); under-refusal would resolve
|
|
1318
|
-
* the wrong binding, which is why the cheap-and-broad scan wins over scope simulation. A use with no
|
|
1319
|
-
* enclosing function or block reads module scope directly and cannot be shadowed. */
|
|
1320
|
-
function isShadowedAt(ts: TypeScriptApi, at: TSApi.Node, name: string): boolean {
|
|
1321
|
-
let scope: TSApi.Node | undefined
|
|
1322
|
-
for (let node: TSApi.Node | undefined = at.parent; node !== undefined; node = node.parent) {
|
|
1323
|
-
if (ts.isSourceFile(node)) break
|
|
1324
|
-
if (ts.isFunctionLike(node) || ts.isBlock(node)) scope = node
|
|
1325
|
-
}
|
|
1326
|
-
if (scope === undefined) return false
|
|
1327
|
-
const bindsName = (binding: TSApi.BindingName): boolean =>
|
|
1328
|
-
ts.isIdentifier(binding)
|
|
1329
|
-
? binding.text === name
|
|
1330
|
-
: binding.elements.some(
|
|
1331
|
-
(element) =>
|
|
1332
|
-
!ts.isOmittedExpression(element) &&
|
|
1333
|
-
(ts.isIdentifier(element.name) ? element.name.text === name : bindsName(element.name)),
|
|
1334
|
-
)
|
|
1335
|
-
let found = false
|
|
1336
|
-
const scan = (node: TSApi.Node): void => {
|
|
1337
|
-
if (found) return
|
|
1338
|
-
if (
|
|
1339
|
-
(ts.isVariableDeclaration(node) || ts.isParameter(node)) &&
|
|
1340
|
-
bindsName(node.name as TSApi.BindingName)
|
|
1341
|
-
) {
|
|
1342
|
-
found = true
|
|
1343
|
-
return
|
|
1344
|
-
}
|
|
1345
|
-
if (ts.isFunctionDeclaration(node) && node.name?.text === name) {
|
|
1346
|
-
found = true
|
|
1347
|
-
return
|
|
1348
|
-
}
|
|
1349
|
-
ts.forEachChild(node, scan)
|
|
1350
|
-
}
|
|
1351
|
-
scan(scope)
|
|
1352
|
-
return found
|
|
1353
|
-
}
|
|
1354
|
-
|
|
1355
|
-
const CONST_RESOLUTION_DEPTH = 5
|
|
1356
|
-
|
|
1357
|
-
/**
|
|
1358
|
-
* Resolve an interpolated expression to compile-time text, or `undefined` when it can carry runtime
|
|
1359
|
-
* data. Pure syntax, no type checker - the same honest limit the rule already documents. What
|
|
1360
|
-
* resolves: string/number literals, no-substitution templates, templates whose every span resolves,
|
|
1361
|
-
* ternaries with both branches resolvable (BOTH branch texts are returned, so a hostile keyword in
|
|
1362
|
-
* either still feeds the keyword scan), `as`/`satisfies` wrappers, a `const` whose initializer
|
|
1363
|
-
* resolves (the nearest binding: function or block scope, then module scope; recursively,
|
|
1364
|
-
* depth-capped), `.join(sep?)` over an array {@link staticArrayItems} proves, and - when
|
|
1365
|
-
* `scope.imports` is configured - a module `const` imported by name from another in-project module.
|
|
1366
|
-
* Everything else - `let`, a parameter, any other call, a member access, a shadowed name, a
|
|
1367
|
-
* bare-specifier import - stays unresolved and the interpolation is flagged exactly as before.
|
|
1368
|
-
*/
|
|
1369
|
-
function resolveStaticSqlText(
|
|
1370
|
-
ts: TypeScriptApi,
|
|
1371
|
-
node: TSApi.Expression,
|
|
1372
|
-
scope: SqlScope,
|
|
1373
|
-
depth: number,
|
|
1374
|
-
): string | undefined {
|
|
1375
|
-
if (depth > CONST_RESOLUTION_DEPTH) return undefined
|
|
1376
|
-
if (ts.isParenthesizedExpression(node)) {
|
|
1377
|
-
return resolveStaticSqlText(ts, node.expression, scope, depth)
|
|
1378
|
-
}
|
|
1379
|
-
if (ts.isAsExpression(node) || ts.isSatisfiesExpression(node)) {
|
|
1380
|
-
return resolveStaticSqlText(ts, node.expression, scope, depth)
|
|
1381
|
-
}
|
|
1382
|
-
if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) return node.text
|
|
1383
|
-
if (ts.isNumericLiteral(node)) return node.text
|
|
1384
|
-
if (ts.isTemplateExpression(node)) {
|
|
1385
|
-
let text = node.head.text
|
|
1386
|
-
for (const span of node.templateSpans) {
|
|
1387
|
-
const part =
|
|
1388
|
-
placeholderNumber(ts, text, span.expression, depth) ??
|
|
1389
|
-
resolveStaticSqlText(ts, span.expression, scope, depth + 1)
|
|
1390
|
-
if (part === undefined) return undefined
|
|
1391
|
-
text += part + span.literal.text
|
|
1392
|
-
}
|
|
1393
|
-
return text
|
|
1394
|
-
}
|
|
1395
|
-
if (ts.isConditionalExpression(node)) {
|
|
1396
|
-
const whenTrue = resolveStaticSqlText(ts, node.whenTrue, scope, depth + 1)
|
|
1397
|
-
const whenFalse = resolveStaticSqlText(ts, node.whenFalse, scope, depth + 1)
|
|
1398
|
-
if (whenTrue === undefined || whenFalse === undefined) return undefined
|
|
1399
|
-
return `${whenTrue} ${whenFalse}`
|
|
1400
|
-
}
|
|
1401
|
-
if (ts.isCallExpression(node)) return resolveStaticJoin(ts, node, scope, depth)
|
|
1402
|
-
if (ts.isIdentifier(node)) {
|
|
1403
|
-
const local = localConstInitializer(ts, node)
|
|
1404
|
-
if (local === "shadow") return undefined
|
|
1405
|
-
if (local !== undefined) return resolveStaticSqlText(ts, local, scope, depth + 1)
|
|
1406
|
-
const initializer = scope.module.consts.get(node.text)
|
|
1407
|
-
const edge = initializer === undefined ? scope.module.imports.get(node.text) : undefined
|
|
1408
|
-
// Membership first: `isShadowedAt` walks a subtree, and most identifiers in a query are neither a
|
|
1409
|
-
// module const nor an import binding.
|
|
1410
|
-
if (initializer === undefined && edge === undefined) return undefined
|
|
1411
|
-
// Shadowing is a property of where the identifier is WRITTEN, so one check is right on both sides
|
|
1412
|
-
// of an import hop: an initializer in the imported module sits at module scope with nothing above
|
|
1413
|
-
// it to shadow it, while a use inside a function in this file is still refused.
|
|
1414
|
-
if (isShadowedAt(ts, node, node.text)) return undefined
|
|
1415
|
-
if (initializer !== undefined) return resolveStaticSqlText(ts, initializer, scope, depth + 1)
|
|
1416
|
-
if (edge === undefined || scope.imports === undefined) return undefined
|
|
1417
|
-
const target = loadSqlModuleScope(ts, scope.imports, scope.module.id, edge.specifier)
|
|
1418
|
-
if (target === undefined) return undefined
|
|
1419
|
-
const exported = resolveExportedConst(ts, scope.imports, target, edge.exported, 1, new Set())
|
|
1420
|
-
if (exported === undefined) return undefined
|
|
1421
|
-
// The imported initializer's own identifiers read THAT module's consts, never this file's. A
|
|
1422
|
-
// caller that happens to have its own `const DIR` must not silently supply the fragment's `DIR`,
|
|
1423
|
-
// which is the one way cross-module resolution could resolve to text nobody wrote.
|
|
1424
|
-
return resolveStaticSqlText(
|
|
1425
|
-
ts,
|
|
1426
|
-
exported.expression,
|
|
1427
|
-
{ module: exported.scope, imports: scope.imports },
|
|
1428
|
-
depth + 1,
|
|
1429
|
-
)
|
|
1430
|
-
}
|
|
1431
|
-
return undefined
|
|
1432
|
-
}
|
|
1433
|
-
|
|
1434
|
-
/**
|
|
1435
|
-
* The initializer of the `const` a function or block scope binds `node` to, `"shadow"` when the
|
|
1436
|
-
* nearest such binding is anything else (a parameter, `let`, `var`, destructuring), or `undefined`
|
|
1437
|
-
* when no scope below the module binds it - the module-scope lookup applies then.
|
|
1438
|
-
*/
|
|
1439
|
-
function localConstInitializer(
|
|
1440
|
-
ts: TypeScriptApi,
|
|
1441
|
-
node: TSApi.Identifier,
|
|
1442
|
-
): TSApi.Expression | "shadow" | undefined {
|
|
1443
|
-
const source = node.getSourceFile()
|
|
1444
|
-
for (let scope: TSApi.Node | undefined = node.parent; scope !== undefined; scope = scope.parent) {
|
|
1445
|
-
if (ts.isSourceFile(scope)) return undefined
|
|
1446
|
-
const binding = directBinding(ts, source, scope, node.text)
|
|
1447
|
-
if (binding === "shadow") return "shadow"
|
|
1448
|
-
if (binding !== undefined) return binding.constant ? binding.initializer : "shadow"
|
|
1449
|
-
}
|
|
1450
|
-
return undefined
|
|
1451
|
-
}
|
|
1452
|
-
|
|
1453
|
-
const unwrapExpression = (ts: TypeScriptApi, node: TSApi.Expression): TSApi.Expression => {
|
|
1454
|
-
let current = node
|
|
1455
|
-
while (
|
|
1456
|
-
ts.isParenthesizedExpression(current) ||
|
|
1457
|
-
ts.isAsExpression(current) ||
|
|
1458
|
-
ts.isSatisfiesExpression(current)
|
|
1459
|
-
) {
|
|
1460
|
-
current = current.expression
|
|
1461
|
-
}
|
|
1462
|
-
return current
|
|
1463
|
-
}
|
|
1464
|
-
|
|
1465
|
-
/** `Object.freeze([...])` with `Object` unshadowed: the one array form no later code can change. */
|
|
1466
|
-
function frozenArrayLiteral(
|
|
1467
|
-
ts: TypeScriptApi,
|
|
1468
|
-
node: TSApi.Expression,
|
|
1469
|
-
): TSApi.ArrayLiteralExpression | undefined {
|
|
1470
|
-
const call = unwrapExpression(ts, node)
|
|
1471
|
-
if (!ts.isCallExpression(call) || call.arguments.length !== 1) return undefined
|
|
1472
|
-
const callee = call.expression
|
|
1473
|
-
if (
|
|
1474
|
-
!ts.isPropertyAccessExpression(callee) ||
|
|
1475
|
-
callee.name.text !== "freeze" ||
|
|
1476
|
-
!ts.isIdentifier(callee.expression) ||
|
|
1477
|
-
callee.expression.text !== "Object" ||
|
|
1478
|
-
isShadowedAt(ts, callee.expression, "Object")
|
|
1479
|
-
) {
|
|
1480
|
-
return undefined
|
|
1481
|
-
}
|
|
1482
|
-
const array = unwrapExpression(ts, call.arguments[0]!)
|
|
1483
|
-
return ts.isArrayLiteralExpression(array) ? array : undefined
|
|
1484
|
-
}
|
|
1485
|
-
|
|
1486
|
-
const ARRAY_READS: ReadonlySet<string> = new Set(["join", "includes", "indexOf"])
|
|
1487
|
-
|
|
1488
|
-
/**
|
|
1489
|
-
* Whether every use of `name` in `source` other than its declaration is a call of `.join(`,
|
|
1490
|
-
* `.includes(` or `.indexOf(`, or a `.length` read: then nothing pushes to, sorts, exports or hands
|
|
1491
|
-
* away the array, so it still holds its literal elements. With `pushed`, a `.push(...)` is accepted
|
|
1492
|
-
* too and its arguments collected, for the caller to prove (the `where.push(...)` builder). A
|
|
1493
|
-
* same-named binding elsewhere only adds uses, so the answer can only err toward refusing.
|
|
1494
|
-
*/
|
|
1495
|
-
function onlyReadsArray(
|
|
1496
|
-
ts: TypeScriptApi,
|
|
1497
|
-
source: TSApi.SourceFile,
|
|
1498
|
-
name: string,
|
|
1499
|
-
declaration: TSApi.Node,
|
|
1500
|
-
pushed?: TSApi.Expression[],
|
|
1501
|
-
): boolean {
|
|
1502
|
-
let ok = true
|
|
1503
|
-
const visit = (node: TSApi.Node): void => {
|
|
1504
|
-
if (!ok) return
|
|
1505
|
-
if (ts.isIdentifier(node) && node.text === name && node !== declaration) {
|
|
1506
|
-
const access = node.parent
|
|
1507
|
-
const call =
|
|
1508
|
-
ts.isPropertyAccessExpression(access) &&
|
|
1509
|
-
access.expression === node &&
|
|
1510
|
-
ts.isCallExpression(access.parent) &&
|
|
1511
|
-
access.parent.expression === access
|
|
1512
|
-
? access.parent
|
|
1513
|
-
: undefined
|
|
1514
|
-
if (
|
|
1515
|
-
pushed !== undefined &&
|
|
1516
|
-
call !== undefined &&
|
|
1517
|
-
ts.isPropertyAccessExpression(access) &&
|
|
1518
|
-
access.name.text === "push"
|
|
1519
|
-
) {
|
|
1520
|
-
if (call.arguments.some((argument) => ts.isSpreadElement(argument))) ok = false
|
|
1521
|
-
else pushed.push(...call.arguments)
|
|
1522
|
-
// An argument can mention the array again; those uses are checked as well.
|
|
1523
|
-
for (const argument of call.arguments) visit(argument)
|
|
1524
|
-
return
|
|
1525
|
-
}
|
|
1526
|
-
const read =
|
|
1527
|
-
ts.isPropertyAccessExpression(access) &&
|
|
1528
|
-
access.expression === node &&
|
|
1529
|
-
(access.name.text === "length"
|
|
1530
|
-
? !isWrittenTo(ts, access)
|
|
1531
|
-
: ARRAY_READS.has(access.name.text) && call !== undefined)
|
|
1532
|
-
if (!read) ok = false
|
|
1533
|
-
return
|
|
1534
|
-
}
|
|
1535
|
-
ts.forEachChild(node, visit)
|
|
1536
|
-
}
|
|
1537
|
-
visit(source)
|
|
1538
|
-
return ok
|
|
1539
|
-
}
|
|
1540
|
-
|
|
1541
|
-
/** `node` as the target of an assignment, `++`/`--`, or `delete`. */
|
|
1542
|
-
function isWrittenTo(ts: TypeScriptApi, node: TSApi.Node): boolean {
|
|
1543
|
-
const parent = node.parent
|
|
1544
|
-
if (
|
|
1545
|
-
ts.isBinaryExpression(parent) &&
|
|
1546
|
-
parent.left === node &&
|
|
1547
|
-
parent.operatorToken.kind >= ts.SyntaxKind.FirstAssignment &&
|
|
1548
|
-
parent.operatorToken.kind <= ts.SyntaxKind.LastAssignment
|
|
1549
|
-
) {
|
|
1550
|
-
return true
|
|
1551
|
-
}
|
|
1552
|
-
if (ts.isPrefixUnaryExpression(parent) || ts.isPostfixUnaryExpression(parent)) {
|
|
1553
|
-
return (
|
|
1554
|
-
parent.operator === ts.SyntaxKind.PlusPlusToken ||
|
|
1555
|
-
parent.operator === ts.SyntaxKind.MinusMinusToken
|
|
1556
|
-
)
|
|
1557
|
-
}
|
|
1558
|
-
return ts.isDeleteExpression(parent)
|
|
1559
|
-
}
|
|
1560
|
-
|
|
1561
|
-
/**
|
|
1562
|
-
* The element texts of an array `receiver` names, when the array provably still holds them: an
|
|
1563
|
-
* inline literal, `Object.freeze([...])` anywhere it is bound or imported from, or a `const` array
|
|
1564
|
-
* literal bound in this file, not exported, and only ever read ({@link onlyReadsArray}). `as const`
|
|
1565
|
-
* is type-only and proves nothing.
|
|
1566
|
-
*/
|
|
1567
|
-
function staticArrayItems(
|
|
1568
|
-
ts: TypeScriptApi,
|
|
1569
|
-
receiver: TSApi.Expression,
|
|
1570
|
-
scope: SqlScope,
|
|
1571
|
-
depth: number,
|
|
1572
|
-
): readonly string[] | undefined {
|
|
1573
|
-
const node = unwrapExpression(ts, receiver)
|
|
1574
|
-
let array = ts.isArrayLiteralExpression(node) ? node : frozenArrayLiteral(ts, node)
|
|
1575
|
-
let itemScope = scope
|
|
1576
|
-
const pushed: TSApi.Expression[] = []
|
|
1577
|
-
if (array === undefined && ts.isIdentifier(node)) {
|
|
1578
|
-
const local = localConstInitializer(ts, node)
|
|
1579
|
-
if (local === "shadow") return undefined
|
|
1580
|
-
let initializer = local
|
|
1581
|
-
let exported = false
|
|
1582
|
-
if (initializer === undefined && !isShadowedAt(ts, node, node.text)) {
|
|
1583
|
-
initializer = scope.module.consts.get(node.text)
|
|
1584
|
-
exported = [...scope.module.localExports.values()].includes(node.text)
|
|
1585
|
-
const edge = initializer === undefined ? scope.module.imports.get(node.text) : undefined
|
|
1586
|
-
if (edge !== undefined && scope.imports !== undefined) {
|
|
1587
|
-
const target = loadSqlModuleScope(ts, scope.imports, scope.module.id, edge.specifier)
|
|
1588
|
-
const found =
|
|
1589
|
-
target === undefined
|
|
1590
|
-
? undefined
|
|
1591
|
-
: resolveExportedConst(ts, scope.imports, target, edge.exported, 1, new Set())
|
|
1592
|
-
if (found === undefined) return undefined
|
|
1593
|
-
// Another module's array is accepted only frozen: its own file may mutate it.
|
|
1594
|
-
array = frozenArrayLiteral(ts, found.expression)
|
|
1595
|
-
itemScope = { module: found.scope, imports: scope.imports }
|
|
1596
|
-
}
|
|
1597
|
-
}
|
|
1598
|
-
if (array === undefined && initializer !== undefined) {
|
|
1599
|
-
array = frozenArrayLiteral(ts, initializer)
|
|
1600
|
-
const literal = unwrapExpression(ts, initializer)
|
|
1601
|
-
if (
|
|
1602
|
-
array === undefined &&
|
|
1603
|
-
!exported &&
|
|
1604
|
-
ts.isArrayLiteralExpression(literal) &&
|
|
1605
|
-
ts.isVariableDeclaration(initializer.parent) &&
|
|
1606
|
-
onlyReadsArray(ts, node.getSourceFile(), node.text, initializer.parent.name, pushed)
|
|
1607
|
-
) {
|
|
1608
|
-
array = literal
|
|
1609
|
-
}
|
|
1610
|
-
}
|
|
1611
|
-
}
|
|
1612
|
-
if (array === undefined) return undefined
|
|
1613
|
-
const items: string[] = []
|
|
1614
|
-
// What the array may hold: its literal elements, and anything pushed onto it in any order.
|
|
1615
|
-
for (const element of [...array.elements, ...pushed]) {
|
|
1616
|
-
if (ts.isSpreadElement(element) || ts.isOmittedExpression(element)) return undefined
|
|
1617
|
-
const text = resolveStaticSqlText(ts, element, itemScope, depth + 1)
|
|
1618
|
-
if (text === undefined) return undefined
|
|
1619
|
-
items.push(text)
|
|
1620
|
-
}
|
|
1621
|
-
return items
|
|
1622
|
-
}
|
|
1623
|
-
|
|
1624
|
-
/** `items.join(sep?)` over a {@link staticArrayItems} array with a literal or absent separator. */
|
|
1625
|
-
function resolveStaticJoin(
|
|
1626
|
-
ts: TypeScriptApi,
|
|
1627
|
-
call: TSApi.CallExpression,
|
|
1628
|
-
scope: SqlScope,
|
|
1629
|
-
depth: number,
|
|
1630
|
-
): string | undefined {
|
|
1631
|
-
const callee = call.expression
|
|
1632
|
-
if (
|
|
1633
|
-
!ts.isPropertyAccessExpression(callee) ||
|
|
1634
|
-
callee.questionDotToken !== undefined ||
|
|
1635
|
-
callee.name.text !== "join" ||
|
|
1636
|
-
call.arguments.length > 1
|
|
1637
|
-
) {
|
|
1638
|
-
return undefined
|
|
1639
|
-
}
|
|
1640
|
-
const separatorArg = call.arguments[0]
|
|
1641
|
-
const separator =
|
|
1642
|
-
separatorArg === undefined
|
|
1643
|
-
? ","
|
|
1644
|
-
: ts.isStringLiteral(separatorArg) || ts.isNoSubstitutionTemplateLiteral(separatorArg)
|
|
1645
|
-
? separatorArg.text
|
|
1646
|
-
: undefined
|
|
1647
|
-
if (separator === undefined) return undefined
|
|
1648
|
-
const items =
|
|
1649
|
-
staticArrayItems(ts, callee.expression, scope, depth + 1) ??
|
|
1650
|
-
mappedItem(ts, callee.expression, scope, depth + 1)
|
|
1651
|
-
return items?.join(separator)
|
|
1652
|
-
}
|
|
1653
|
-
|
|
1654
|
-
/**
|
|
1655
|
-
* `xs.map(fn)`, `xs.flatMap(fn)` or `Array.from(src, fn)` whose callback returns text that resolves
|
|
1656
|
-
* for every element - `(_, i) => \`($${i * 2 + 1}, $${i * 2 + 2})\``, the batch `VALUES` idiom. How
|
|
1657
|
-
* many items there are is runtime data, what each one says is not, so one item stands for all.
|
|
1658
|
-
*/
|
|
1659
|
-
function mappedItem(
|
|
1660
|
-
ts: TypeScriptApi,
|
|
1661
|
-
receiver: TSApi.Expression,
|
|
1662
|
-
scope: SqlScope,
|
|
1663
|
-
depth: number,
|
|
1664
|
-
): readonly string[] | undefined {
|
|
1665
|
-
const call = unwrapExpression(ts, receiver)
|
|
1666
|
-
if (!ts.isCallExpression(call) || !ts.isPropertyAccessExpression(call.expression))
|
|
1667
|
-
return undefined
|
|
1668
|
-
// Only these return what the callback returns; `filter` and the rest hand back the elements.
|
|
1669
|
-
const method = call.expression.name.text
|
|
1670
|
-
const argument = indexCallbackArgument(ts, call)
|
|
1671
|
-
if (argument === undefined || !(method === "map" || method === "flatMap" || argument === 1))
|
|
1672
|
-
return undefined
|
|
1673
|
-
const fn = call.arguments[argument]
|
|
1674
|
-
if (fn === undefined || !(ts.isArrowFunction(fn) || ts.isFunctionExpression(fn))) return undefined
|
|
1675
|
-
const only =
|
|
1676
|
-
ts.isBlock(fn.body) && fn.body.statements.length === 1 ? fn.body.statements[0] : undefined
|
|
1677
|
-
const body = ts.isBlock(fn.body)
|
|
1678
|
-
? only !== undefined && ts.isReturnStatement(only)
|
|
1679
|
-
? only.expression
|
|
1680
|
-
: undefined
|
|
1681
|
-
: fn.body
|
|
1682
|
-
const text = body === undefined ? undefined : resolveStaticSqlText(ts, body, scope, depth + 1)
|
|
1683
|
-
return text === undefined ? undefined : [text]
|
|
1684
|
-
}
|
|
1685
|
-
|
|
1686
|
-
/** Array methods whose callback receives the element's index, and where in the callback it is. */
|
|
1687
|
-
const INDEX_PARAMETER: ReadonlyMap<string, number> = new Map([
|
|
1688
|
-
["map", 1],
|
|
1689
|
-
["flatMap", 1],
|
|
1690
|
-
["forEach", 1],
|
|
1691
|
-
["filter", 1],
|
|
1692
|
-
["some", 1],
|
|
1693
|
-
["every", 1],
|
|
1694
|
-
["find", 1],
|
|
1695
|
-
["findIndex", 1],
|
|
1696
|
-
["reduce", 2],
|
|
1697
|
-
["reduceRight", 2],
|
|
1698
|
-
])
|
|
1699
|
-
|
|
1700
|
-
/** Which argument of `call` is a callback handed an array index: the first for `xs.map(fn)` and its
|
|
1701
|
-
* kin, the second for an unshadowed `Array.from(src, fn)`. */
|
|
1702
|
-
function indexCallbackArgument(ts: TypeScriptApi, call: TSApi.CallExpression): number | undefined {
|
|
1703
|
-
const callee = call.expression
|
|
1704
|
-
if (!ts.isPropertyAccessExpression(callee) || callee.questionDotToken !== undefined)
|
|
1705
|
-
return undefined
|
|
1706
|
-
if (INDEX_PARAMETER.has(callee.name.text)) return 0
|
|
1707
|
-
return callee.name.text === "from" &&
|
|
1708
|
-
ts.isIdentifier(callee.expression) &&
|
|
1709
|
-
callee.expression.text === "Array" &&
|
|
1710
|
-
!isShadowedAt(ts, callee.expression, "Array")
|
|
1711
|
-
? 1
|
|
1712
|
-
: undefined
|
|
1713
|
-
}
|
|
1714
|
-
|
|
1715
|
-
/**
|
|
1716
|
-
* `"1"` for a span written right after a `$` whose expression provably evaluates to a number: a
|
|
1717
|
-
* Postgres placeholder index (`$${i + 1}`), which binds a parameter and can carry no SQL. Any string
|
|
1718
|
-
* there could, so anything not proved numeric stays unresolved.
|
|
1719
|
-
*/
|
|
1720
|
-
function placeholderNumber(
|
|
1721
|
-
ts: TypeScriptApi,
|
|
1722
|
-
before: string,
|
|
1723
|
-
node: TSApi.Expression,
|
|
1724
|
-
depth: number,
|
|
1725
|
-
): string | undefined {
|
|
1726
|
-
return before.endsWith("$") && isNumericExpression(ts, node, depth) ? "1" : undefined
|
|
1727
|
-
}
|
|
1728
|
-
|
|
1729
|
-
const NUMERIC_OPERATORS = (ts: TypeScriptApi): ReadonlySet<TSApi.SyntaxKind> =>
|
|
1730
|
-
new Set([
|
|
1731
|
-
ts.SyntaxKind.MinusToken,
|
|
1732
|
-
ts.SyntaxKind.AsteriskToken,
|
|
1733
|
-
ts.SyntaxKind.AsteriskAsteriskToken,
|
|
1734
|
-
ts.SyntaxKind.SlashToken,
|
|
1735
|
-
ts.SyntaxKind.PercentToken,
|
|
1736
|
-
ts.SyntaxKind.AmpersandToken,
|
|
1737
|
-
ts.SyntaxKind.BarToken,
|
|
1738
|
-
ts.SyntaxKind.CaretToken,
|
|
1739
|
-
ts.SyntaxKind.LessThanLessThanToken,
|
|
1740
|
-
ts.SyntaxKind.GreaterThanGreaterThanToken,
|
|
1741
|
-
ts.SyntaxKind.GreaterThanGreaterThanGreaterThanToken,
|
|
1742
|
-
])
|
|
1743
|
-
const NUMBER_FUNCTIONS: ReadonlySet<string> = new Set(["Number", "parseInt", "parseFloat"])
|
|
1744
|
-
|
|
1745
|
-
/**
|
|
1746
|
-
* Whether an expression evaluates to a number whatever its inputs hold. Every arithmetic operator but
|
|
1747
|
-
* `+` converts its operands, so `i * 2` is a number even if `i` were a string; `+` is one only when
|
|
1748
|
-
* both sides are. A name proves it when it is a callback's array index, or a `const`, never-reassigned
|
|
1749
|
-
* `let` or `for` counter bound to a number and only ever updated by arithmetic. Also `xs.push(...)`
|
|
1750
|
-
* (the new length), `Number`/`parseInt`/`parseFloat`/`Math.*` calls, and `.length` of an array a
|
|
1751
|
-
* nearby binding builds from a literal. A type annotation proves nothing: it does not run.
|
|
1752
|
-
*/
|
|
1753
|
-
function isNumericExpression(ts: TypeScriptApi, node: TSApi.Expression, depth: number): boolean {
|
|
1754
|
-
if (depth > CONST_RESOLUTION_DEPTH) return false
|
|
1755
|
-
const expression = unwrapExpression(ts, node)
|
|
1756
|
-
if (ts.isNumericLiteral(expression)) return true
|
|
1757
|
-
if (ts.isPrefixUnaryExpression(expression))
|
|
1758
|
-
return expression.operator !== ts.SyntaxKind.ExclamationToken
|
|
1759
|
-
if (ts.isPostfixUnaryExpression(expression)) return true
|
|
1760
|
-
if (ts.isBinaryExpression(expression)) {
|
|
1761
|
-
const operator = expression.operatorToken.kind
|
|
1762
|
-
if (operator === ts.SyntaxKind.PlusToken) {
|
|
1763
|
-
return (
|
|
1764
|
-
isNumericExpression(ts, expression.left, depth + 1) &&
|
|
1765
|
-
isNumericExpression(ts, expression.right, depth + 1)
|
|
1766
|
-
)
|
|
1767
|
-
}
|
|
1768
|
-
return NUMERIC_OPERATORS(ts).has(operator)
|
|
1769
|
-
}
|
|
1770
|
-
if (ts.isIdentifier(expression)) return isNumericName(ts, expression, depth)
|
|
1771
|
-
if (ts.isCallExpression(expression)) {
|
|
1772
|
-
const callee = expression.expression
|
|
1773
|
-
if (ts.isIdentifier(callee))
|
|
1774
|
-
return NUMBER_FUNCTIONS.has(callee.text) && !isShadowedAt(ts, callee, callee.text)
|
|
1775
|
-
if (!ts.isPropertyAccessExpression(callee) || callee.questionDotToken !== undefined)
|
|
1776
|
-
return false
|
|
1777
|
-
if (callee.name.text === "push") return true
|
|
1778
|
-
return (
|
|
1779
|
-
ts.isIdentifier(callee.expression) &&
|
|
1780
|
-
callee.expression.text === "Math" &&
|
|
1781
|
-
!isShadowedAt(ts, callee.expression, "Math")
|
|
1782
|
-
)
|
|
1783
|
-
}
|
|
1784
|
-
if (
|
|
1785
|
-
ts.isPropertyAccessExpression(expression) &&
|
|
1786
|
-
expression.name.text === "length" &&
|
|
1787
|
-
ts.isIdentifier(expression.expression)
|
|
1788
|
-
) {
|
|
1789
|
-
const binding = nameBinding(ts, expression.expression)
|
|
1790
|
-
return (
|
|
1791
|
-
binding.kind === "value" &&
|
|
1792
|
-
ts.isArrayLiteralExpression(unwrapExpression(ts, binding.initializer))
|
|
1793
|
-
)
|
|
1794
|
-
}
|
|
1795
|
-
return false
|
|
1796
|
-
}
|
|
1797
|
-
|
|
1798
|
-
/** How the nearest scope binds a name: a readable value ({@link directBinding}), a parameter, a `let`
|
|
1799
|
-
* counter a `for` statement declares and updates, or nothing this walk can read. */
|
|
1800
|
-
type NameBinding =
|
|
1801
|
-
| { readonly kind: "value"; readonly initializer: TSApi.Expression }
|
|
1802
|
-
| {
|
|
1803
|
-
readonly kind: "parameter"
|
|
1804
|
-
readonly fn: TSApi.SignatureDeclaration
|
|
1805
|
-
readonly position: number
|
|
1806
|
-
}
|
|
1807
|
-
| { readonly kind: "counter"; readonly initializer: TSApi.Expression }
|
|
1808
|
-
| { readonly kind: "unknown" }
|
|
1809
|
-
|
|
1810
|
-
function nameBinding(ts: TypeScriptApi, node: TSApi.Identifier): NameBinding {
|
|
1811
|
-
const source = node.getSourceFile()
|
|
1812
|
-
for (let scope: TSApi.Node | undefined = node.parent; scope !== undefined; scope = scope.parent) {
|
|
1813
|
-
if (ts.isFunctionLike(scope)) {
|
|
1814
|
-
const position = scope.parameters.findIndex((p) => bindingNameCovers(ts, p.name, node.text))
|
|
1815
|
-
if (position !== -1) {
|
|
1816
|
-
return ts.isIdentifier(scope.parameters[position]?.name ?? node)
|
|
1817
|
-
? { kind: "parameter", fn: scope, position }
|
|
1818
|
-
: { kind: "unknown" }
|
|
1819
|
-
}
|
|
1820
|
-
}
|
|
1821
|
-
const binding = directBinding(ts, source, scope, node.text)
|
|
1822
|
-
if (binding === "shadow") {
|
|
1823
|
-
// `for (let i = 0; ...; i++)`: the one reassigned `let` worth reading, checked by the caller.
|
|
1824
|
-
const list = ts.isForStatement(scope) ? scope.initializer : undefined
|
|
1825
|
-
const declaration =
|
|
1826
|
-
list !== undefined && ts.isVariableDeclarationList(list)
|
|
1827
|
-
? list.declarations.find((d) => ts.isIdentifier(d.name) && d.name.text === node.text)
|
|
1828
|
-
: undefined
|
|
1829
|
-
return declaration?.initializer === undefined
|
|
1830
|
-
? { kind: "unknown" }
|
|
1831
|
-
: { kind: "counter", initializer: declaration.initializer }
|
|
1832
|
-
}
|
|
1833
|
-
if (binding !== undefined) return { kind: "value", initializer: binding.initializer }
|
|
1834
|
-
if (ts.isSourceFile(scope)) break
|
|
1835
|
-
}
|
|
1836
|
-
return { kind: "unknown" }
|
|
1837
|
-
}
|
|
1838
|
-
|
|
1839
|
-
function isNumericName(ts: TypeScriptApi, node: TSApi.Identifier, depth: number): boolean {
|
|
1840
|
-
const source = node.getSourceFile()
|
|
1841
|
-
const binding = nameBinding(ts, node)
|
|
1842
|
-
if (binding.kind === "value") return isNumericExpression(ts, binding.initializer, depth + 1)
|
|
1843
|
-
if (binding.kind === "counter") {
|
|
1844
|
-
return (
|
|
1845
|
-
isNumericExpression(ts, binding.initializer, depth + 1) &&
|
|
1846
|
-
onlyNumericWrites(ts, source, node.text, depth)
|
|
1847
|
-
)
|
|
1848
|
-
}
|
|
1849
|
-
if (binding.kind !== "parameter") return false
|
|
1850
|
-
// An array callback's index parameter, never reassigned.
|
|
1851
|
-
const call = binding.fn.parent
|
|
1852
|
-
if (!ts.isCallExpression(call) || !ts.isPropertyAccessExpression(call.expression)) return false
|
|
1853
|
-
const argument = indexCallbackArgument(ts, call)
|
|
1854
|
-
const position = argument === 1 ? 1 : INDEX_PARAMETER.get(call.expression.name.text)
|
|
1855
|
-
return (
|
|
1856
|
-
argument !== undefined &&
|
|
1857
|
-
call.arguments[argument] === binding.fn &&
|
|
1858
|
-
binding.position === position &&
|
|
1859
|
-
!isReassignedInFile(ts, source, node.text)
|
|
1860
|
-
)
|
|
1861
|
-
}
|
|
1862
|
-
|
|
1863
|
-
/** Compound assignments that always store a number. */
|
|
1864
|
-
const NUMERIC_ASSIGNMENTS = (ts: TypeScriptApi): ReadonlySet<TSApi.SyntaxKind> =>
|
|
1865
|
-
new Set([
|
|
1866
|
-
ts.SyntaxKind.MinusEqualsToken,
|
|
1867
|
-
ts.SyntaxKind.AsteriskEqualsToken,
|
|
1868
|
-
ts.SyntaxKind.AsteriskAsteriskEqualsToken,
|
|
1869
|
-
ts.SyntaxKind.SlashEqualsToken,
|
|
1870
|
-
ts.SyntaxKind.PercentEqualsToken,
|
|
1871
|
-
ts.SyntaxKind.AmpersandEqualsToken,
|
|
1872
|
-
ts.SyntaxKind.BarEqualsToken,
|
|
1873
|
-
ts.SyntaxKind.CaretEqualsToken,
|
|
1874
|
-
ts.SyntaxKind.LessThanLessThanEqualsToken,
|
|
1875
|
-
ts.SyntaxKind.GreaterThanGreaterThanEqualsToken,
|
|
1876
|
-
ts.SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken,
|
|
1877
|
-
])
|
|
1878
|
-
|
|
1879
|
-
/** Every write to `name` in the file is `++`/`--`, or an assignment that stores a number. */
|
|
1880
|
-
function onlyNumericWrites(
|
|
1881
|
-
ts: TypeScriptApi,
|
|
1882
|
-
source: TSApi.SourceFile,
|
|
1883
|
-
name: string,
|
|
1884
|
-
depth: number,
|
|
1885
|
-
): boolean {
|
|
1886
|
-
let ok = true
|
|
1887
|
-
const visit = (node: TSApi.Node): void => {
|
|
1888
|
-
if (!ok) return
|
|
1889
|
-
if (ts.isIdentifier(node) && node.text === name && isWrittenTo(ts, node)) {
|
|
1890
|
-
const parent = node.parent
|
|
1891
|
-
if (ts.isBinaryExpression(parent)) {
|
|
1892
|
-
const operator = parent.operatorToken.kind
|
|
1893
|
-
ok =
|
|
1894
|
-
operator === ts.SyntaxKind.EqualsToken || operator === ts.SyntaxKind.PlusEqualsToken
|
|
1895
|
-
? isNumericExpression(ts, parent.right, depth + 1)
|
|
1896
|
-
: NUMERIC_ASSIGNMENTS(ts).has(operator)
|
|
1897
|
-
} else ok = !ts.isDeleteExpression(parent)
|
|
1898
|
-
return
|
|
1899
|
-
}
|
|
1900
|
-
ts.forEachChild(node, visit)
|
|
1901
|
-
}
|
|
1902
|
-
visit(source)
|
|
1903
|
-
return ok
|
|
1904
|
-
}
|
|
1905
|
-
|
|
1906
|
-
/** A template's contribution to the shape: resolved span texts fold into `staticText` (so the
|
|
1907
|
-
* keyword scan still sees what a `const` carries); any unresolvable span keeps it `dynamic`. */
|
|
1908
|
-
function templateShape(
|
|
1909
|
-
ts: TypeScriptApi,
|
|
1910
|
-
template: TSApi.TemplateExpression,
|
|
1911
|
-
scope: SqlScope | undefined,
|
|
1912
|
-
): { staticText: string; dynamic: boolean } {
|
|
1913
|
-
let staticText = template.head.text
|
|
1914
|
-
let dynamic = false
|
|
1915
|
-
for (const span of template.templateSpans) {
|
|
1916
|
-
const resolved =
|
|
1917
|
-
scope === undefined
|
|
1918
|
-
? undefined
|
|
1919
|
-
: (placeholderNumber(ts, staticText, span.expression, 0) ??
|
|
1920
|
-
resolveStaticSqlText(ts, span.expression, scope, 0))
|
|
1921
|
-
if (resolved === undefined) dynamic = true
|
|
1922
|
-
else staticText += resolved
|
|
1923
|
-
staticText += span.literal.text
|
|
1924
|
-
}
|
|
1925
|
-
return { staticText, dynamic }
|
|
1926
|
-
}
|
|
1927
|
-
|
|
1928
|
-
/** A same-file binding the argument resolver proved holds one expression: a `const`, or a `let` the
|
|
1929
|
-
* whole file never reassigns. `"shadow"` marks a nearer binding of the name we can NOT read through (a
|
|
1930
|
-
* parameter, `var`, destructured, uninitialized, reassigned `let`) - it stops the outward walk so a
|
|
1931
|
-
* farther, resolvable const of the same name is never read in its place. */
|
|
1932
|
-
type ResolvableBinding =
|
|
1933
|
-
| { readonly initializer: TSApi.Expression; readonly constant: boolean }
|
|
1934
|
-
| "shadow"
|
|
1935
|
-
|
|
1936
|
-
/** Whether `name` is written to anywhere in the file - a plain, compound, or `++`/`--` assignment to a
|
|
1937
|
-
* bare identifier of that name. A `let` that is is over-cautiously refused (it might be reassigned from
|
|
1938
|
-
* request data); a `const` never needs this. Over-refusal only ever leaves an interpolation flagged as
|
|
1939
|
-
* before, never the reverse. */
|
|
1940
|
-
function isReassignedInFile(ts: TypeScriptApi, source: TSApi.SourceFile, name: string): boolean {
|
|
1941
|
-
let found = false
|
|
1942
|
-
const visit = (node: TSApi.Node): void => {
|
|
1943
|
-
if (found) return
|
|
1944
|
-
if (
|
|
1945
|
-
ts.isBinaryExpression(node) &&
|
|
1946
|
-
node.operatorToken.kind >= ts.SyntaxKind.FirstAssignment &&
|
|
1947
|
-
node.operatorToken.kind <= ts.SyntaxKind.LastAssignment &&
|
|
1948
|
-
ts.isIdentifier(node.left) &&
|
|
1949
|
-
node.left.text === name
|
|
1950
|
-
) {
|
|
1951
|
-
found = true
|
|
1952
|
-
return
|
|
1953
|
-
}
|
|
1954
|
-
if (
|
|
1955
|
-
(ts.isPrefixUnaryExpression(node) || ts.isPostfixUnaryExpression(node)) &&
|
|
1956
|
-
(node.operator === ts.SyntaxKind.PlusPlusToken ||
|
|
1957
|
-
node.operator === ts.SyntaxKind.MinusMinusToken) &&
|
|
1958
|
-
ts.isIdentifier(node.operand) &&
|
|
1959
|
-
node.operand.text === name
|
|
1960
|
-
) {
|
|
1961
|
-
found = true
|
|
1962
|
-
return
|
|
1963
|
-
}
|
|
1964
|
-
ts.forEachChild(node, visit)
|
|
1965
|
-
}
|
|
1966
|
-
visit(source)
|
|
1967
|
-
return found
|
|
1968
|
-
}
|
|
1969
|
-
|
|
1970
|
-
/** Does `binding` bind `name` (as a plain identifier or nested inside a destructuring pattern)? Mirrors
|
|
1971
|
-
* the pattern walk in {@link isShadowedAt}. */
|
|
1972
|
-
function bindingNameCovers(ts: TypeScriptApi, binding: TSApi.BindingName, name: string): boolean {
|
|
1973
|
-
return ts.isIdentifier(binding)
|
|
1974
|
-
? binding.text === name
|
|
1975
|
-
: binding.elements.some(
|
|
1976
|
-
(element) =>
|
|
1977
|
-
!ts.isOmittedExpression(element) &&
|
|
1978
|
-
(ts.isIdentifier(element.name)
|
|
1979
|
-
? element.name.text === name
|
|
1980
|
-
: bindingNameCovers(ts, element.name, name)),
|
|
1981
|
-
)
|
|
1982
|
-
}
|
|
1983
|
-
|
|
1984
|
-
/** Inspect the bindings a single scope node introduces DIRECTLY (not nested) for `name`: parameters and
|
|
1985
|
-
* catch variables of a function/catch, `var`/`let`/`const` and function/class declarations of a
|
|
1986
|
-
* statement list. Returns the readable initializer, `"shadow"` for a form we cannot read through, or
|
|
1987
|
-
* `undefined` when this scope does not bind the name at all. */
|
|
1988
|
-
function directBinding(
|
|
1989
|
-
ts: TypeScriptApi,
|
|
1990
|
-
source: TSApi.SourceFile,
|
|
1991
|
-
scope: TSApi.Node,
|
|
1992
|
-
name: string,
|
|
1993
|
-
): ResolvableBinding | undefined {
|
|
1994
|
-
if (ts.isFunctionLike(scope)) {
|
|
1995
|
-
for (const parameter of scope.parameters) {
|
|
1996
|
-
if (bindingNameCovers(ts, parameter.name, name)) return "shadow"
|
|
1997
|
-
}
|
|
1998
|
-
}
|
|
1999
|
-
if (ts.isCatchClause(scope)) {
|
|
2000
|
-
const declared = scope.variableDeclaration
|
|
2001
|
-
if (declared !== undefined && bindingNameCovers(ts, declared.name, name)) return "shadow"
|
|
2002
|
-
}
|
|
2003
|
-
for (const statement of scopeStatements(ts, scope) ?? []) {
|
|
2004
|
-
if (
|
|
2005
|
-
(ts.isFunctionDeclaration(statement) || ts.isClassDeclaration(statement)) &&
|
|
2006
|
-
statement.name?.text === name
|
|
2007
|
-
) {
|
|
2008
|
-
return "shadow"
|
|
2009
|
-
}
|
|
2010
|
-
}
|
|
2011
|
-
for (const list of scopeDeclarationLists(ts, scope)) {
|
|
2012
|
-
for (const declaration of list.declarations) {
|
|
2013
|
-
if (!bindingNameCovers(ts, declaration.name, name)) continue
|
|
2014
|
-
// A destructured or uninitialized binding, or a `var` (hoisting + reassignment risk), is not a
|
|
2015
|
-
// value we can read one expression out of.
|
|
2016
|
-
if (!ts.isIdentifier(declaration.name) || declaration.initializer === undefined)
|
|
2017
|
-
return "shadow"
|
|
2018
|
-
const isConst = (list.flags & ts.NodeFlags.Const) !== 0
|
|
2019
|
-
const isLet = (list.flags & ts.NodeFlags.Let) !== 0
|
|
2020
|
-
if (isConst) return { initializer: declaration.initializer, constant: true }
|
|
2021
|
-
if (isLet && !isReassignedInFile(ts, source, name))
|
|
2022
|
-
return { initializer: declaration.initializer, constant: false }
|
|
2023
|
-
return "shadow"
|
|
2024
|
-
}
|
|
2025
|
-
}
|
|
2026
|
-
return undefined
|
|
2027
|
-
}
|
|
2028
|
-
|
|
2029
|
-
function scopeStatements(
|
|
2030
|
-
ts: TypeScriptApi,
|
|
2031
|
-
scope: TSApi.Node,
|
|
2032
|
-
): readonly TSApi.Statement[] | undefined {
|
|
2033
|
-
return ts.isSourceFile(scope) ||
|
|
2034
|
-
ts.isBlock(scope) ||
|
|
2035
|
-
ts.isModuleBlock(scope) ||
|
|
2036
|
-
ts.isCaseClause(scope) ||
|
|
2037
|
-
ts.isDefaultClause(scope)
|
|
2038
|
-
? scope.statements
|
|
2039
|
-
: undefined
|
|
2040
|
-
}
|
|
2041
|
-
|
|
2042
|
-
/** The `var`/`let`/`const` lists a scope node declares directly: its statements' and a `for` head's. */
|
|
2043
|
-
function scopeDeclarationLists(
|
|
2044
|
-
ts: TypeScriptApi,
|
|
2045
|
-
scope: TSApi.Node,
|
|
2046
|
-
): TSApi.VariableDeclarationList[] {
|
|
2047
|
-
const lists: TSApi.VariableDeclarationList[] = []
|
|
2048
|
-
for (const statement of scopeStatements(ts, scope) ?? []) {
|
|
2049
|
-
if (ts.isVariableStatement(statement)) lists.push(statement.declarationList)
|
|
2050
|
-
}
|
|
2051
|
-
if (
|
|
2052
|
-
(ts.isForStatement(scope) || ts.isForInStatement(scope) || ts.isForOfStatement(scope)) &&
|
|
2053
|
-
scope.initializer !== undefined &&
|
|
2054
|
-
ts.isVariableDeclarationList(scope.initializer)
|
|
2055
|
-
) {
|
|
2056
|
-
lists.push(scope.initializer)
|
|
2057
|
-
}
|
|
2058
|
-
return lists
|
|
2059
|
-
}
|
|
2060
|
-
|
|
2061
|
-
/** The `var` or `let` a scope declares `name` with by a plain identifier, if any. */
|
|
2062
|
-
function mutableDeclaration(
|
|
2063
|
-
ts: TypeScriptApi,
|
|
2064
|
-
scope: TSApi.Node,
|
|
2065
|
-
name: string,
|
|
2066
|
-
): TSApi.VariableDeclaration | undefined {
|
|
2067
|
-
for (const list of scopeDeclarationLists(ts, scope)) {
|
|
2068
|
-
if ((list.flags & ts.NodeFlags.Const) !== 0) continue
|
|
2069
|
-
for (const declaration of list.declarations) {
|
|
2070
|
-
if (ts.isIdentifier(declaration.name) && declaration.name.text === name) return declaration
|
|
2071
|
-
}
|
|
2072
|
-
}
|
|
2073
|
-
return undefined
|
|
2074
|
-
}
|
|
2075
|
-
|
|
2076
|
-
interface SqlWrite {
|
|
2077
|
-
readonly value: TSApi.Expression
|
|
2078
|
-
/** `+=`: the value is glued onto what the variable already holds. */
|
|
2079
|
-
readonly appends: boolean
|
|
2080
|
-
}
|
|
2081
|
-
|
|
2082
|
-
/**
|
|
2083
|
-
* Every value a statement variable may hold where the query reads it, so a statement parked in a
|
|
2084
|
-
* variable is scanned as if it had been written inline at the call. This is the counterpart to
|
|
2085
|
-
* {@link resolveStaticSqlText}: that folds a const's text INTO a template's shape; this unfolds the
|
|
2086
|
-
* statement back out of the variable it was lifted into. Without it, ANY interpolated-SQL finding
|
|
2087
|
-
* could be silenced, invisibly, by hoisting the statement to `const q = …` first, or by building it
|
|
2088
|
-
* in steps (`let q = "SELECT …"; q += …`).
|
|
2089
|
-
*
|
|
2090
|
-
* Same-file only. Nearest enclosing declaration wins, so a shadowing local is read and never a
|
|
2091
|
-
* same-named module const. A `const`, or a `let` the file never reassigns, holds its initializer. A
|
|
2092
|
-
* `var` or reassigned `let` holds its initializer and every value assigned to the name anywhere in
|
|
2093
|
-
* the function (or module) that declares it: over-collected rather than scope-simulated, which only
|
|
2094
|
-
* ever adds a value to check. `key` names the binding, so a value that reads the variable it is
|
|
2095
|
-
* assigned to is recognised. A parameter, an imported or destructured binding, or a name with no
|
|
2096
|
-
* same-file declaration returns `undefined` - which leaves the argument scanned as itself.
|
|
2097
|
-
*/
|
|
2098
|
-
function variableWrites(
|
|
2099
|
-
ts: TypeScriptApi,
|
|
2100
|
-
node: TSApi.Identifier,
|
|
2101
|
-
): { readonly key: TSApi.Node; readonly writes: readonly SqlWrite[] } | undefined {
|
|
2102
|
-
const source = node.getSourceFile()
|
|
2103
|
-
const name = node.text
|
|
2104
|
-
for (let scope: TSApi.Node | undefined = node.parent; scope !== undefined; scope = scope.parent) {
|
|
2105
|
-
const binding = directBinding(ts, source, scope, name)
|
|
2106
|
-
if (binding === "shadow") {
|
|
2107
|
-
const declaration = mutableDeclaration(ts, scope, name)
|
|
2108
|
-
if (declaration === undefined) return undefined
|
|
2109
|
-
let owner: TSApi.Node = declaration
|
|
2110
|
-
while (!ts.isFunctionLike(owner) && !ts.isSourceFile(owner)) owner = owner.parent
|
|
2111
|
-
const writes = writesTo(ts, owner, name)
|
|
2112
|
-
return {
|
|
2113
|
-
key: declaration,
|
|
2114
|
-
writes:
|
|
2115
|
-
declaration.initializer === undefined
|
|
2116
|
-
? writes
|
|
2117
|
-
: [{ value: declaration.initializer, appends: false }, ...writes],
|
|
2118
|
-
}
|
|
2119
|
-
}
|
|
2120
|
-
if (binding !== undefined) {
|
|
2121
|
-
return { key: binding.initializer, writes: [{ value: binding.initializer, appends: false }] }
|
|
2122
|
-
}
|
|
2123
|
-
if (ts.isSourceFile(scope)) break
|
|
2124
|
-
}
|
|
2125
|
-
return undefined
|
|
2126
|
-
}
|
|
2127
|
-
|
|
2128
|
-
/** The values assigned to `name` under `root`. A numeric compound assignment stores no text. */
|
|
2129
|
-
function writesTo(ts: TypeScriptApi, root: TSApi.Node, name: string): SqlWrite[] {
|
|
2130
|
-
const writes: SqlWrite[] = []
|
|
2131
|
-
const visit = (node: TSApi.Node): void => {
|
|
2132
|
-
if (ts.isIdentifier(node) && node.text === name) {
|
|
2133
|
-
const parent = node.parent
|
|
2134
|
-
if (ts.isBinaryExpression(parent) && parent.left === node) {
|
|
2135
|
-
const operator = parent.operatorToken.kind
|
|
2136
|
-
if (operator === ts.SyntaxKind.PlusEqualsToken) {
|
|
2137
|
-
writes.push({ value: parent.right, appends: true })
|
|
2138
|
-
} else if (
|
|
2139
|
-
operator === ts.SyntaxKind.EqualsToken ||
|
|
2140
|
-
operator === ts.SyntaxKind.QuestionQuestionEqualsToken ||
|
|
2141
|
-
operator === ts.SyntaxKind.BarBarEqualsToken ||
|
|
2142
|
-
operator === ts.SyntaxKind.AmpersandAmpersandEqualsToken
|
|
2143
|
-
) {
|
|
2144
|
-
writes.push({ value: parent.right, appends: false })
|
|
2145
|
-
}
|
|
2146
|
-
}
|
|
2147
|
-
}
|
|
2148
|
-
ts.forEachChild(node, visit)
|
|
2149
|
-
}
|
|
2150
|
-
visit(root)
|
|
2151
|
-
return writes
|
|
2152
|
-
}
|
|
2153
|
-
|
|
2154
|
-
function mentionsName(ts: TypeScriptApi, node: TSApi.Node, name: string): boolean {
|
|
2155
|
-
// A member/key named like the variable does not read that variable (`record = client.record()`).
|
|
2156
|
-
if (ts.isPropertyAccessExpression(node)) return mentionsName(ts, node.expression, name)
|
|
2157
|
-
if (ts.isPropertyAssignment(node)) {
|
|
2158
|
-
return (
|
|
2159
|
-
mentionsName(ts, node.initializer, name) ||
|
|
2160
|
-
(ts.isComputedPropertyName(node.name) && mentionsName(ts, node.name.expression, name))
|
|
2161
|
-
)
|
|
2162
|
-
}
|
|
2163
|
-
if (ts.isIdentifier(node)) return node.text === name
|
|
2164
|
-
return ts.forEachChild(node, (child) => mentionsName(ts, child, name) || undefined) === true
|
|
2165
|
-
}
|
|
2166
|
-
|
|
2167
|
-
const UNKNOWN_SQL: SqlExpressionShape = {
|
|
2168
|
-
staticText: "",
|
|
2169
|
-
dynamic: true,
|
|
2170
|
-
concatenated: false,
|
|
2171
|
-
literal: false,
|
|
2172
|
-
parameterizedTag: false,
|
|
2173
|
-
}
|
|
2174
|
-
|
|
2175
|
-
function textShape(text: string): SqlExpressionShape {
|
|
2176
|
-
return {
|
|
2177
|
-
staticText: text,
|
|
2178
|
-
dynamic: false,
|
|
2179
|
-
concatenated: false,
|
|
2180
|
-
literal: true,
|
|
2181
|
-
parameterizedTag: false,
|
|
2182
|
-
}
|
|
2183
|
-
}
|
|
2184
|
-
|
|
2185
|
-
function joinShapes(shapes: readonly SqlExpressionShape[]): SqlExpressionShape {
|
|
2186
|
-
return {
|
|
2187
|
-
staticText: shapes.map((shape) => shape.staticText).join(""),
|
|
2188
|
-
// As with `+`: text glued onto a binding tag's output un-parameterizes it.
|
|
2189
|
-
dynamic: shapes.some((shape) => shape.dynamic || shape.parameterizedTag),
|
|
2190
|
-
concatenated: true,
|
|
2191
|
-
literal: false,
|
|
2192
|
-
parameterizedTag: false,
|
|
2193
|
-
}
|
|
2194
|
-
}
|
|
2195
|
-
|
|
2196
|
-
/** Orders a variable's candidate statements by how surely {@link scanInterpolatedSql} would flag
|
|
2197
|
-
* them: dynamic SQL text, then dynamic glued text, then any dynamic text; outside a binding tag
|
|
2198
|
-
* before inside one. */
|
|
2199
|
-
function sqlRisk(shape: SqlExpressionShape): number {
|
|
2200
|
-
const dynamic = !shape.dynamic
|
|
2201
|
-
? 0
|
|
2202
|
-
: SQL_KEYWORD.test(shape.staticText) || STATEMENT_START.test(shape.staticText)
|
|
2203
|
-
? 3
|
|
2204
|
-
: shape.concatenated
|
|
2205
|
-
? 2
|
|
2206
|
-
: 1
|
|
2207
|
-
return dynamic * 2 + (shape.parameterizedTag ? 0 : 1)
|
|
2208
|
-
}
|
|
2209
|
-
|
|
2210
|
-
/**
|
|
2211
|
-
* The riskiest statement a variable may hold. Each value that replaces the text is one candidate.
|
|
2212
|
-
* The values that build on it (`+=`, or `q = q + more`) are glued onto every replacing value at
|
|
2213
|
-
* once, as a builder that takes each branch would, so a static `SELECT … WHERE 1=1` followed by an
|
|
2214
|
-
* interpolated `AND …` reads as the one statement it becomes.
|
|
2215
|
-
*/
|
|
2216
|
-
function writtenShape(
|
|
2217
|
-
ts: TypeScriptApi,
|
|
2218
|
-
name: string,
|
|
2219
|
-
writes: readonly SqlWrite[],
|
|
2220
|
-
scope: SqlScope | undefined,
|
|
2221
|
-
trail: readonly TSApi.Node[],
|
|
2222
|
-
): SqlExpressionShape {
|
|
2223
|
-
const replacing: SqlExpressionShape[] = []
|
|
2224
|
-
const building: SqlExpressionShape[] = []
|
|
2225
|
-
for (const write of writes) {
|
|
2226
|
-
const shape = sqlExpressionShape(ts, write.value, scope, trail)
|
|
2227
|
-
if (write.appends || mentionsName(ts, write.value, name)) building.push(shape)
|
|
2228
|
-
else replacing.push(shape)
|
|
2229
|
-
}
|
|
2230
|
-
const candidates =
|
|
2231
|
-
building.length === 0 ? replacing : [...replacing, joinShapes([...replacing, ...building])]
|
|
2232
|
-
let worst: SqlExpressionShape | undefined
|
|
2233
|
-
for (const candidate of candidates) {
|
|
2234
|
-
if (worst === undefined || sqlRisk(candidate) > sqlRisk(worst)) worst = candidate
|
|
2235
|
-
}
|
|
2236
|
-
return worst ?? UNKNOWN_SQL
|
|
2237
|
-
}
|
|
2238
|
-
|
|
2239
|
-
const TEXT_METHODS = new Set([
|
|
2240
|
-
"toString",
|
|
2241
|
-
"valueOf",
|
|
2242
|
-
"trim",
|
|
2243
|
-
"trimStart",
|
|
2244
|
-
"trimEnd",
|
|
2245
|
-
"toLowerCase",
|
|
2246
|
-
"toUpperCase",
|
|
2247
|
-
])
|
|
2248
|
-
|
|
2249
|
-
/** The value a text-preserving call returns: `String(x)`, `x.toString()`, `x.trim()`. */
|
|
2250
|
-
function passedThrough(
|
|
2251
|
-
ts: TypeScriptApi,
|
|
2252
|
-
call: TSApi.CallExpression,
|
|
2253
|
-
): TSApi.Expression | undefined {
|
|
2254
|
-
const callee = call.expression
|
|
2255
|
-
if (ts.isIdentifier(callee) && callee.text === "String" && call.arguments.length === 1) {
|
|
2256
|
-
return call.arguments[0]
|
|
2257
|
-
}
|
|
2258
|
-
if (
|
|
2259
|
-
ts.isPropertyAccessExpression(callee) &&
|
|
2260
|
-
TEXT_METHODS.has(callee.name.text) &&
|
|
2261
|
-
call.arguments.length === 0
|
|
2262
|
-
) {
|
|
2263
|
-
return callee.expression
|
|
2264
|
-
}
|
|
2265
|
-
return undefined
|
|
2266
|
-
}
|
|
2267
|
-
|
|
2268
|
-
/** The parts `[a, b].join(sep)` and `a.concat(b)` glue together, a separator as its text. */
|
|
2269
|
-
function joinedParts(
|
|
2270
|
-
ts: TypeScriptApi,
|
|
2271
|
-
call: TSApi.CallExpression,
|
|
2272
|
-
): readonly (TSApi.Expression | string)[] | undefined {
|
|
2273
|
-
const callee = call.expression
|
|
2274
|
-
if (!ts.isPropertyAccessExpression(callee)) return undefined
|
|
2275
|
-
if (callee.name.text === "concat") return [callee.expression, ...call.arguments]
|
|
2276
|
-
const items = unwrapExpression(ts, callee.expression)
|
|
2277
|
-
if (callee.name.text !== "join" || !ts.isArrayLiteralExpression(items)) return undefined
|
|
2278
|
-
const separator = call.arguments[0]
|
|
2279
|
-
const glue: TSApi.Expression | string =
|
|
2280
|
-
separator === undefined ? "," : ts.isStringLiteralLike(separator) ? separator.text : separator
|
|
2281
|
-
const parts: (TSApi.Expression | string)[] = []
|
|
2282
|
-
items.elements.forEach((element, index) => {
|
|
2283
|
-
if (index > 0) parts.push(glue)
|
|
2284
|
-
if (ts.isSpreadElement(element)) parts.push(element.expression)
|
|
2285
|
-
else if (!ts.isOmittedExpression(element)) parts.push(element)
|
|
2286
|
-
})
|
|
2287
|
-
return parts
|
|
2288
|
-
}
|
|
2289
|
-
|
|
2290
|
-
/** Whether the `sql` a tag names is a function this file defines (`const sql = (s, ...v) => …`),
|
|
2291
|
-
* which is plain interpolation whatever its name. A parameter, an import, or a driver instance
|
|
2292
|
-
* (`const sql = postgres(url)`) keeps the name's trust. */
|
|
2293
|
-
function definesSqlFunction(ts: TypeScriptApi, tag: TSApi.Identifier): boolean {
|
|
2294
|
-
for (let scope: TSApi.Node | undefined = tag.parent; scope !== undefined; scope = scope.parent) {
|
|
2295
|
-
if (
|
|
2296
|
-
ts.isFunctionLike(scope) &&
|
|
2297
|
-
scope.parameters.some((parameter) => bindingNameCovers(ts, parameter.name, tag.text))
|
|
2298
|
-
) {
|
|
2299
|
-
return false
|
|
2300
|
-
}
|
|
2301
|
-
for (const statement of scopeStatements(ts, scope) ?? []) {
|
|
2302
|
-
if (ts.isFunctionDeclaration(statement) && statement.name?.text === tag.text) return true
|
|
2303
|
-
}
|
|
2304
|
-
for (const list of scopeDeclarationLists(ts, scope)) {
|
|
2305
|
-
for (const declaration of list.declarations) {
|
|
2306
|
-
if (!ts.isIdentifier(declaration.name) || declaration.name.text !== tag.text) continue
|
|
2307
|
-
const value =
|
|
2308
|
-
declaration.initializer === undefined
|
|
2309
|
-
? undefined
|
|
2310
|
-
: unwrapExpression(ts, declaration.initializer)
|
|
2311
|
-
return value !== undefined && (ts.isArrowFunction(value) || ts.isFunctionExpression(value))
|
|
2312
|
-
}
|
|
2313
|
-
}
|
|
2314
|
-
}
|
|
2315
|
-
return false
|
|
2316
|
-
}
|
|
2317
|
-
|
|
2318
|
-
/** Describe only the statement's syntax; comments/strings elsewhere cannot influence the result.
|
|
2319
|
-
* `trail` holds the variables being read through, innermost last. */
|
|
2320
|
-
function sqlExpressionShape(
|
|
2321
|
-
ts: TypeScriptApi,
|
|
2322
|
-
expression: TSApi.Expression,
|
|
2323
|
-
scope?: SqlScope,
|
|
2324
|
-
trail: readonly TSApi.Node[] = [],
|
|
2325
|
-
): SqlExpressionShape {
|
|
2326
|
-
let node = unwrapExpression(ts, expression)
|
|
2327
|
-
while (ts.isNonNullExpression(node)) node = unwrapExpression(ts, node.expression)
|
|
2328
|
-
if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) {
|
|
2329
|
-
return {
|
|
2330
|
-
staticText: node.text,
|
|
2331
|
-
dynamic: false,
|
|
2332
|
-
concatenated: false,
|
|
2333
|
-
literal: true,
|
|
2334
|
-
parameterizedTag: false,
|
|
2335
|
-
}
|
|
2336
|
-
}
|
|
2337
|
-
if (ts.isTaggedTemplateExpression(node)) {
|
|
2338
|
-
const tag = node.tag
|
|
2339
|
-
const parameterizedTag =
|
|
2340
|
-
(ts.isIdentifier(tag) && tag.text === "sql" && !definesSqlFunction(ts, tag)) ||
|
|
2341
|
-
(ts.isPropertyAccessExpression(tag) && tag.getText() === "Prisma.sql")
|
|
2342
|
-
const template = node.template
|
|
2343
|
-
const templated = ts.isTemplateExpression(template)
|
|
2344
|
-
? templateShape(ts, template, parameterizedTag ? undefined : scope)
|
|
2345
|
-
: { staticText: template.text, dynamic: false }
|
|
2346
|
-
const staticText = templated.staticText
|
|
2347
|
-
// Only the ecosystem's binding tags are trusted, by NAME - which is the honest limit of a scanner
|
|
2348
|
-
// that reads syntax and runs no type checker. `sql` is what postgres.js, drizzle, slonik and Bun's
|
|
2349
|
-
// own driver all call theirs, and `Prisma.sql` is Prisma's; taking those at their word is a
|
|
2350
|
-
// deliberate trade, and it is worth stating what it costs: a `sql` this file defines as a
|
|
2351
|
-
// function is read as the interpolation it is, but one imported from anywhere is trusted, so
|
|
2352
|
-
// this rule finds mistakes, not an adversary who reads it first.
|
|
2353
|
-
//
|
|
2354
|
-
// Trusting anything else widens that for no gain. This list briefly also held `sqlIdentifiers`,
|
|
2355
|
-
// a name invented for Nifra's own adapters - a second forgeable name that no user has a
|
|
2356
|
-
// convention for, added so Nifra's source would pass its own rule. Names earn their place here by
|
|
2357
|
-
// being what drivers already call the thing, not by being convenient for the framework.
|
|
2358
|
-
//
|
|
2359
|
-
// Everything else - `String.raw`, an identity tag, a member access that merely ends in `.sql` -
|
|
2360
|
-
// is treated as plain interpolation.
|
|
2361
|
-
return {
|
|
2362
|
-
staticText,
|
|
2363
|
-
dynamic: templated.dynamic && !parameterizedTag,
|
|
2364
|
-
concatenated: false,
|
|
2365
|
-
literal: !ts.isTemplateExpression(template),
|
|
2366
|
-
parameterizedTag,
|
|
2367
|
-
}
|
|
2368
|
-
}
|
|
2369
|
-
if (ts.isTemplateExpression(node)) {
|
|
2370
|
-
const templated = templateShape(ts, node, scope)
|
|
2371
|
-
return {
|
|
2372
|
-
staticText: templated.staticText,
|
|
2373
|
-
dynamic: templated.dynamic,
|
|
2374
|
-
// `${a} ${b}` writes no text of its own; it only glues values together.
|
|
2375
|
-
concatenated: [node.head, ...node.templateSpans.map((span) => span.literal)].every(
|
|
2376
|
-
(part) => part.text.trim() === "",
|
|
2377
|
-
),
|
|
2378
|
-
literal: false,
|
|
2379
|
-
parameterizedTag: false,
|
|
2380
|
-
}
|
|
2381
|
-
}
|
|
2382
|
-
if (ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.PlusToken) {
|
|
2383
|
-
const left = sqlExpressionShape(ts, node.left, scope, trail)
|
|
2384
|
-
const right = sqlExpressionShape(ts, node.right, scope, trail)
|
|
2385
|
-
return {
|
|
2386
|
-
staticText: left.staticText + right.staticText,
|
|
2387
|
-
// A resolved const operand is static text, not a dynamic part - so the old `!literal` test
|
|
2388
|
-
// narrows to what it always actually meant: an operand that carries runtime data (dynamic) or
|
|
2389
|
-
// a binding tag being concatenated into plain text (which un-parameterizes it).
|
|
2390
|
-
dynamic: left.dynamic || right.dynamic || left.parameterizedTag || right.parameterizedTag,
|
|
2391
|
-
concatenated: true,
|
|
2392
|
-
literal: left.literal && right.literal,
|
|
2393
|
-
parameterizedTag: false,
|
|
2394
|
-
}
|
|
2395
|
-
}
|
|
2396
|
-
// A resolvable expression (a module-`const` name, a literal ternary) contributes its compile-time
|
|
2397
|
-
// text and stays non-dynamic - this is what lets `"SELECT " + COLS + " FROM t"` and
|
|
2398
|
-
// `db.query(`${COLS} FROM t WHERE id = $1`)` pass while a mutable or unprovable name still flags.
|
|
2399
|
-
// `literal` stays false: the named escape hatches (`unsafe`, `$queryRawUnsafe`) keep flagging a
|
|
2400
|
-
// resolved const, because taking statement text from ANY variable is what their rule warns about.
|
|
2401
|
-
if (scope !== undefined) {
|
|
2402
|
-
const resolved = resolveStaticSqlText(ts, node, scope, 0)
|
|
2403
|
-
if (resolved !== undefined) {
|
|
2404
|
-
return {
|
|
2405
|
-
staticText: resolved,
|
|
2406
|
-
dynamic: false,
|
|
2407
|
-
concatenated: false,
|
|
2408
|
-
literal: false,
|
|
2409
|
-
parameterizedTag: false,
|
|
2410
|
-
}
|
|
2411
|
-
}
|
|
2412
|
-
}
|
|
2413
|
-
if (ts.isCallExpression(node)) {
|
|
2414
|
-
const inner = passedThrough(ts, node)
|
|
2415
|
-
if (inner !== undefined)
|
|
2416
|
-
return { ...sqlExpressionShape(ts, inner, scope, trail), literal: false }
|
|
2417
|
-
const parts = joinedParts(ts, node)
|
|
2418
|
-
if (parts !== undefined) {
|
|
2419
|
-
return joinShapes(
|
|
2420
|
-
parts.map((part) =>
|
|
2421
|
-
typeof part === "string" ? textShape(part) : sqlExpressionShape(ts, part, scope, trail),
|
|
2422
|
-
),
|
|
2423
|
-
)
|
|
2424
|
-
}
|
|
2425
|
-
}
|
|
2426
|
-
// A bare name that did not resolve to compile-time text. If it is a same-file binding, scan the
|
|
2427
|
-
// shapes of what it may hold - so a statement hoisted into `const q = …` or built up in a `let` is
|
|
2428
|
-
// read exactly as if it were written inline at the call, closing the "extract a variable to launder
|
|
2429
|
-
// the finding" hole. `literal` is forced false: the value arrived through a variable, which is the
|
|
2430
|
-
// property the `unsafe`/`$queryRawUnsafe` hatch rule keys on.
|
|
2431
|
-
if (ts.isIdentifier(node)) {
|
|
2432
|
-
const read = variableWrites(ts, node)
|
|
2433
|
-
// Read inside one of its own writes (`q = q + more`), the variable is the text the other writes
|
|
2434
|
-
// already account for.
|
|
2435
|
-
if (read !== undefined && trail.includes(read.key)) return { ...textShape(""), literal: false }
|
|
2436
|
-
if (read !== undefined && trail.length <= CONST_RESOLUTION_DEPTH) {
|
|
2437
|
-
const written = writtenShape(ts, node.text, read.writes, scope, [...trail, read.key])
|
|
2438
|
-
return { ...written, literal: false }
|
|
2439
|
-
}
|
|
2440
|
-
}
|
|
2441
|
-
return UNKNOWN_SQL
|
|
2442
|
-
}
|
|
2443
|
-
|
|
2444
|
-
interface SqlSink {
|
|
2445
|
-
readonly method: string
|
|
2446
|
-
/** `undefined` for a bare call: `const { query } = db` and then `query(…)`. */
|
|
2447
|
-
readonly receiver: string | undefined
|
|
2448
|
-
}
|
|
2449
|
-
|
|
2450
|
-
function sqlMethod(ts: TypeScriptApi, call: TSApi.CallExpression): SqlSink | undefined {
|
|
2451
|
-
const sink = (method: string, receiver: TSApi.Expression | undefined): SqlSink | undefined =>
|
|
2452
|
-
SQL_METHODS.has(method) || DRIVER_READ_METHODS.has(method)
|
|
2453
|
-
? { method, receiver: receiver?.getText() }
|
|
2454
|
-
: undefined
|
|
2455
|
-
const callee = call.expression
|
|
2456
|
-
// Svelte compiles this unbound rune; it is not a driver's raw-statement escape hatch.
|
|
2457
|
-
if (
|
|
2458
|
-
ts.isPropertyAccessExpression(callee) &&
|
|
2459
|
-
callee.name.text === "raw" &&
|
|
2460
|
-
ts.isIdentifier(callee.expression) &&
|
|
2461
|
-
callee.expression.text === "$state"
|
|
2462
|
-
) {
|
|
2463
|
-
const source = callee.getSourceFile()
|
|
2464
|
-
const imported = source.statements.some((statement) => {
|
|
2465
|
-
if (ts.isImportEqualsDeclaration(statement)) return statement.name.text === "$state"
|
|
2466
|
-
if (!ts.isImportDeclaration(statement)) return false
|
|
2467
|
-
const clause = statement.importClause
|
|
2468
|
-
const bindings = clause?.namedBindings
|
|
2469
|
-
return (
|
|
2470
|
-
clause?.name?.text === "$state" ||
|
|
2471
|
-
(bindings !== undefined &&
|
|
2472
|
-
(ts.isNamespaceImport(bindings)
|
|
2473
|
-
? bindings.name.text === "$state"
|
|
2474
|
-
: bindings.elements.some((binding) => binding.name.text === "$state")))
|
|
2475
|
-
)
|
|
2476
|
-
})
|
|
2477
|
-
let bound = imported || isShadowedAt(ts, callee.expression, "$state")
|
|
2478
|
-
for (
|
|
2479
|
-
let scope: TSApi.Node | undefined = callee.parent;
|
|
2480
|
-
scope !== undefined && !bound;
|
|
2481
|
-
scope = scope.parent
|
|
2482
|
-
) {
|
|
2483
|
-
bound = directBinding(ts, source, scope, "$state") !== undefined
|
|
2484
|
-
}
|
|
2485
|
-
if (/\.svelte(?:\.[jt]s)?$/.test(source.fileName) && !bound) return undefined
|
|
2486
|
-
}
|
|
2487
|
-
if (ts.isIdentifier(callee)) return sink(callee.text, undefined)
|
|
2488
|
-
if (ts.isPropertyAccessExpression(callee)) return sink(callee.name.text, callee.expression)
|
|
2489
|
-
if (ts.isElementAccessExpression(callee) && ts.isStringLiteralLike(callee.argumentExpression)) {
|
|
2490
|
-
return sink(callee.argumentExpression.text, callee.expression)
|
|
2491
|
-
}
|
|
2492
|
-
return undefined
|
|
2493
|
-
}
|
|
2494
|
-
|
|
2495
|
-
const SQL_RECEIVER = /(?:^|\.)(?:db|sql|prisma|drizzle|database|conn|connection|client|tx)$/i
|
|
2496
|
-
|
|
2497
|
-
/** Whether a statement is SQL assembled from runtime values, judged by where it is sent. */
|
|
2498
|
-
function isAssembledSql(sink: SqlSink, shape: SqlExpressionShape): boolean {
|
|
2499
|
-
if (!shape.dynamic) return false
|
|
2500
|
-
if (sink.receiver === undefined || DRIVER_READ_METHODS.has(sink.method)) {
|
|
2501
|
-
return STATEMENT_START.test(shape.staticText)
|
|
2502
|
-
}
|
|
2503
|
-
return (
|
|
2504
|
-
SQL_KEYWORD.test(shape.staticText) || (shape.concatenated && SQL_RECEIVER.test(sink.receiver))
|
|
2505
|
-
)
|
|
2506
|
-
}
|
|
2507
|
-
|
|
2508
|
-
/** The statement a call passes: the argument itself, or the `text`/`sql` of a config object
|
|
2509
|
-
* (`{ text, values }` in pg, `{ sql, values }` in mysql2). */
|
|
2510
|
-
function statementArgument(
|
|
2511
|
-
ts: TypeScriptApi,
|
|
2512
|
-
argument: TSApi.Expression,
|
|
2513
|
-
): TSApi.Expression | undefined {
|
|
2514
|
-
const node = unwrapExpression(ts, argument)
|
|
2515
|
-
if (!ts.isObjectLiteralExpression(node)) return argument
|
|
2516
|
-
for (const property of node.properties) {
|
|
2517
|
-
if (ts.isShorthandPropertyAssignment(property) && STATEMENT_KEYS.has(property.name.text)) {
|
|
2518
|
-
return property.name
|
|
2519
|
-
}
|
|
2520
|
-
if (
|
|
2521
|
-
ts.isPropertyAssignment(property) &&
|
|
2522
|
-
(ts.isIdentifier(property.name) || ts.isStringLiteral(property.name)) &&
|
|
2523
|
-
STATEMENT_KEYS.has(property.name.text)
|
|
2524
|
-
) {
|
|
2525
|
-
return property.initializer
|
|
2526
|
-
}
|
|
2527
|
-
}
|
|
2528
|
-
return undefined
|
|
2529
|
-
}
|
|
2530
|
-
|
|
2531
|
-
const STATEMENT_KEYS = new Set(["text", "sql"])
|
|
2532
|
-
|
|
2533
|
-
interface StatementHelper {
|
|
2534
|
-
readonly position: number
|
|
2535
|
-
readonly sink: SqlSink
|
|
2536
|
-
}
|
|
2537
|
-
|
|
2538
|
-
/** Same-file functions that send one of their parameters as a statement - `run(db, q)` calling
|
|
2539
|
-
* `db.query(q)` - by name, with the parameter's position and the sink it reaches. A call to one is
|
|
2540
|
-
* scanned as a call to that sink. One level deep. */
|
|
2541
|
-
function statementHelpers(
|
|
2542
|
-
ts: TypeScriptApi,
|
|
2543
|
-
source: TSApi.SourceFile,
|
|
2544
|
-
): ReadonlyMap<string, StatementHelper> {
|
|
2545
|
-
const helpers = new Map<string, StatementHelper>()
|
|
2546
|
-
const visit = (node: TSApi.Node): void => {
|
|
2547
|
-
const sink = ts.isCallExpression(node) ? sqlMethod(ts, node) : undefined
|
|
2548
|
-
const passed = sink !== undefined && ts.isCallExpression(node) ? node.arguments[0] : undefined
|
|
2549
|
-
const argument = passed === undefined ? undefined : statementArgument(ts, passed)
|
|
2550
|
-
const statement = argument === undefined ? undefined : unwrapExpression(ts, argument)
|
|
2551
|
-
if (sink !== undefined && statement !== undefined && ts.isIdentifier(statement)) {
|
|
2552
|
-
const binding = nameBinding(ts, statement)
|
|
2553
|
-
const name = binding.kind === "parameter" ? functionName(ts, binding.fn) : undefined
|
|
2554
|
-
if (binding.kind === "parameter" && name !== undefined && !helpers.has(name)) {
|
|
2555
|
-
helpers.set(name, { position: binding.position, sink })
|
|
2556
|
-
}
|
|
2557
|
-
}
|
|
2558
|
-
ts.forEachChild(node, visit)
|
|
2559
|
-
}
|
|
2560
|
-
visit(source)
|
|
2561
|
-
return helpers
|
|
2562
|
-
}
|
|
2563
|
-
|
|
2564
|
-
function functionName(ts: TypeScriptApi, fn: TSApi.SignatureDeclaration): string | undefined {
|
|
2565
|
-
if (ts.isFunctionDeclaration(fn)) return fn.name?.text
|
|
2566
|
-
if (
|
|
2567
|
-
(ts.isArrowFunction(fn) || ts.isFunctionExpression(fn)) &&
|
|
2568
|
-
ts.isVariableDeclaration(fn.parent) &&
|
|
2569
|
-
ts.isIdentifier(fn.parent.name)
|
|
2570
|
-
) {
|
|
2571
|
-
return fn.parent.name.text
|
|
2572
|
-
}
|
|
2573
|
-
return undefined
|
|
2574
|
-
}
|
|
2575
|
-
|
|
2576
|
-
/** `content` with every string, template and regex literal blanked, line breaks kept. */
|
|
2577
|
-
function literalsBlanked(ts: TypeScriptApi, source: TSApi.SourceFile, content: string): string {
|
|
2578
|
-
const out = content.split("")
|
|
2579
|
-
const visit = (node: TSApi.Node): void => {
|
|
2580
|
-
if (
|
|
2581
|
-
ts.isStringLiteralLike(node) ||
|
|
2582
|
-
ts.isTemplateHead(node) ||
|
|
2583
|
-
ts.isTemplateMiddle(node) ||
|
|
2584
|
-
ts.isTemplateTail(node) ||
|
|
2585
|
-
ts.isRegularExpressionLiteral(node) ||
|
|
2586
|
-
ts.isJsxText(node)
|
|
2587
|
-
) {
|
|
2588
|
-
for (let i = node.getStart(source); i < node.end; i++) if (out[i] !== "\n") out[i] = " "
|
|
2589
|
-
return
|
|
2590
|
-
}
|
|
2591
|
-
ts.forEachChild(node, visit)
|
|
2592
|
-
}
|
|
2593
|
-
visit(source)
|
|
2594
|
-
return out.join("")
|
|
2595
|
-
}
|
|
2596
|
-
|
|
2597
|
-
/** What silences one interpolated-SQL finding: `// nifra-expect NF-C006: <reason>` (or the
|
|
2598
|
-
* `sql-dynamic` slug) on the flagged line or in the comment block directly above it. The reason after
|
|
2599
|
-
* the colon is mandatory (see {@link commentBlockExpectation}). Scoped to the single statement it sits on. */
|
|
2600
|
-
const SQL_DYNAMIC_EXPECTATION = ["NF-C006", "sql-dynamic"]
|
|
2601
|
-
|
|
2602
|
-
/**
|
|
2603
|
-
* Scan one file's text for SQL assembled by interpolation. Pure + line-accurate.
|
|
2604
|
-
*
|
|
2605
|
-
* `imports` opts into following a fragment `const` into another module. Without it the scan is
|
|
2606
|
-
* same-file only, which is what the unit tests exercise and what any caller that has no module graph
|
|
2607
|
-
* to offer gets. With it, only what {@link createProjectSqlImports} will hand back is followed.
|
|
2608
|
-
*/
|
|
2609
|
-
export function scanInterpolatedSql(
|
|
2610
|
-
file: string,
|
|
2611
|
-
content: string,
|
|
2612
|
-
ts: TypeScriptApi,
|
|
2613
|
-
imports?: SqlImports,
|
|
2614
|
-
): SourceFinding[] {
|
|
2615
|
-
return scanSqlSites(file, content, ts, imports).filter((site) => site.expected === undefined)
|
|
2616
|
-
}
|
|
2617
|
-
|
|
2618
|
-
/** {@link scanInterpolatedSql}, keeping the sites an expectation comment silences, with its reason. */
|
|
2619
|
-
export function scanSqlSites(
|
|
2620
|
-
file: string,
|
|
2621
|
-
content: string,
|
|
2622
|
-
ts: TypeScriptApi,
|
|
2623
|
-
imports?: SqlImports,
|
|
2624
|
-
parse = (path: string, text: string) => parseSqlSource(ts, path, text),
|
|
2625
|
-
): SqlFinding[] {
|
|
2626
|
-
const out: SqlFinding[] = []
|
|
2627
|
-
const lines = content.split("\n")
|
|
2628
|
-
// Malformed source is already a typecheck failure. Do not turn parser recovery nodes into a second,
|
|
2629
|
-
// misleading SQL diagnostic (notably an unterminated template recovered as an interpolation).
|
|
2630
|
-
const source = parse(file, content)
|
|
2631
|
-
if (source === undefined) return out
|
|
2632
|
-
// Module-scope bindings, read once per file: an interpolated `const` that resolves to compile-time
|
|
2633
|
-
// text cannot carry request data, so the shared-projection idiom (`const COLS = "id, name"` …
|
|
2634
|
-
// `${COLS}`) stays quiet while mutable, parameter, shadowed, and unprovable names flag as before.
|
|
2635
|
-
const scope: SqlScope = { module: sqlModuleScope(ts, file, source), imports }
|
|
2636
|
-
const helpers = statementHelpers(ts, source)
|
|
2637
|
-
// A marker counts only in a comment: one inside a string the call passes is data, not a reason.
|
|
2638
|
-
let markerLines: readonly string[] | undefined
|
|
2639
|
-
const visit = (node: TSApi.Node): void => {
|
|
2640
|
-
if (ts.isCallExpression(node)) {
|
|
2641
|
-
const helper = ts.isIdentifier(node.expression)
|
|
2642
|
-
? helpers.get(node.expression.text)
|
|
2643
|
-
: undefined
|
|
2644
|
-
const sink = helper?.sink ?? sqlMethod(ts, node)
|
|
2645
|
-
const passed = node.arguments[helper?.position ?? 0]
|
|
2646
|
-
const argument = passed === undefined ? undefined : statementArgument(ts, passed)
|
|
2647
|
-
if (sink !== undefined && argument !== undefined) {
|
|
2648
|
-
const shape = sqlExpressionShape(ts, argument, scope)
|
|
2649
|
-
// A helper's own hatch call already answers for passing it a variable.
|
|
2650
|
-
const unsafeEscape =
|
|
2651
|
-
helper === undefined &&
|
|
2652
|
-
sink.receiver !== undefined &&
|
|
2653
|
-
ALWAYS_UNSAFE.has(sink.method) &&
|
|
2654
|
-
!shape.literal &&
|
|
2655
|
-
!shape.parameterizedTag
|
|
2656
|
-
if (unsafeEscape || isAssembledSql(sink, shape)) {
|
|
2657
|
-
const index = node.getStart(source)
|
|
2658
|
-
const line = source.getLineAndCharacterOfPosition(index).line + 1
|
|
2659
|
-
// Sanctioned escape hatch for genuinely-dynamic-but-bound SQL (an allowlisted identifier,
|
|
2660
|
-
// placeholders numbered from data the scan cannot prove numeric). The reason is mandatory: a bare `// nifra-expect
|
|
2661
|
-
// NF-C006` with no reason after the colon does NOT silence, so the hatch always leaves a
|
|
2662
|
-
// greppable audit trail instead of becoming a second laundering trick.
|
|
2663
|
-
markerLines ??= literalsBlanked(ts, source, content).split("\n")
|
|
2664
|
-
const reason = commentBlockExpectation(markerLines, line, SQL_DYNAMIC_EXPECTATION)?.reason
|
|
2665
|
-
const site = { file, line, snippet: (lines[line - 1] ?? "").trim() }
|
|
2666
|
-
out.push(reason === undefined ? site : { ...site, expected: reason })
|
|
2667
|
-
}
|
|
2668
|
-
}
|
|
2669
|
-
}
|
|
2670
|
-
ts.forEachChild(node, visit)
|
|
2671
|
-
}
|
|
2672
|
-
visit(source)
|
|
2673
|
-
return out
|
|
2674
|
-
}
|
|
2675
|
-
|
|
2676
|
-
/**
|
|
2677
|
-
* Collect interpolated-SQL findings across the project.
|
|
2678
|
-
*
|
|
2679
|
-
* Returns `undefined` - not an empty array - when TypeScript is not installed. The rule parses source
|
|
2680
|
-
* with the compiler, so without it there is nothing to report and, more to the point, no basis for
|
|
2681
|
-
* reporting nothing. An empty result would read as "no interpolated SQL found", which is the one
|
|
2682
|
-
* answer a security rule must never give when it did not run.
|
|
2683
|
-
*/
|
|
2684
|
-
export async function scanProjectSql(cwd: string): Promise<SourceFinding[] | undefined> {
|
|
2685
|
-
const sourceFiles: Array<{ readonly file: string; readonly content: string }> = []
|
|
2686
|
-
await walkSource(cwd, (file, content) => sourceFiles.push({ file, content }))
|
|
2687
|
-
const contents = new Map(sourceFiles.map(({ file, content }) => [file, content]))
|
|
2688
|
-
const sourceIndex: TypeScriptSourceIndex = {
|
|
2689
|
-
files: sourceFiles.map(({ file }) => file),
|
|
2690
|
-
read: (file) => contents.get(file),
|
|
2691
|
-
}
|
|
2692
|
-
const loaded = await loadProjectTypeScript(cwd, undefined, sourceIndex)
|
|
2693
|
-
if (loaded.compiler === undefined) return undefined
|
|
2694
|
-
const out: SourceFinding[] = []
|
|
2695
|
-
const imports = createProjectSqlImports(cwd)
|
|
2696
|
-
try {
|
|
2697
|
-
for (const { file, content } of sourceFiles) {
|
|
2698
|
-
out.push(...scanInterpolatedSql(file, content, loaded.compiler, imports))
|
|
2699
|
-
}
|
|
2700
|
-
return out.sort(bySite)
|
|
2701
|
-
} finally {
|
|
2702
|
-
await loaded.session?.close()
|
|
2703
|
-
}
|
|
2704
|
-
}
|
|
2705
|
-
|
|
2706
|
-
/** A declaration file. Excluded from cross-module resolution: `declare const X: string` has no
|
|
2707
|
-
* initializer to read, so following one could only ever produce a "proved" the source never wrote. */
|
|
2708
|
-
const SQL_DECLARATION_FILE = /\.d\.[cm]?ts$/
|
|
2709
|
-
/** The extensions the SQL scan will parse - the same set {@link walkSource} globs. */
|
|
2710
|
-
const SQL_SOURCE_FILE = /\.[cm]?tsx?$/
|
|
2711
|
-
|
|
2712
|
-
/**
|
|
2713
|
-
* The on-disk loader for cross-module `const` resolution, scoped to one project.
|
|
2714
|
-
*
|
|
2715
|
-
* Deliberately narrow, because every widening here is a way for a real finding to go quiet:
|
|
2716
|
-
*
|
|
2717
|
-
* - **Relative specifiers only.** A bare specifier names a dependency whose exports can change without
|
|
2718
|
-
* this project changing, so "provably a `const` string" is not a property the project owns.
|
|
2719
|
-
* - **Inside `cwd`, outside the ignored trees.** The resolved path is realpath'd and must still sit
|
|
2720
|
-
* under the project root: a symlink pointing out of the tree is not source this scan reads. The
|
|
2721
|
-
* `node_modules` / `dist` / build exclusions are the same ones the walk applies.
|
|
2722
|
-
* - **Real source only.** A `.d.ts` carries no initializer, and a non-TS file is not parsed.
|
|
2723
|
-
*
|
|
2724
|
-
* A miss on any of those returns `undefined`, which leaves the name unresolved and the interpolation
|
|
2725
|
-
* flagged - the pre-feature answer.
|
|
2726
|
-
*/
|
|
2727
|
-
export function createProjectSqlImports(cwd: string): SqlImports {
|
|
2728
|
-
const root = realpathOrSelf(resolve(cwd))
|
|
2729
|
-
return createSqlImports((fromModule, specifier) => {
|
|
2730
|
-
if (!isRelativeSpecifier(specifier)) return undefined
|
|
2731
|
-
try {
|
|
2732
|
-
// `fromModule` is the cwd-RELATIVE path the walk supplies for an entry file, and ABSOLUTE for
|
|
2733
|
-
// every module reached through a hop (their ids are the resolved paths).
|
|
2734
|
-
const fromAbs = isAbsolute(fromModule) ? fromModule : join(root, fromModule)
|
|
2735
|
-
const resolved = realpathSync(Bun.resolveSync(specifier, dirname(fromAbs)))
|
|
2736
|
-
if (!resolved.startsWith(root + sep)) return undefined
|
|
2737
|
-
const rel = resolved.slice(root.length + 1)
|
|
2738
|
-
if (IGNORED_DIR.test(rel)) return undefined
|
|
2739
|
-
if (SQL_DECLARATION_FILE.test(resolved) || !SQL_SOURCE_FILE.test(resolved)) return undefined
|
|
2740
|
-
return { id: resolved, content: readFileSync(resolved, "utf8") }
|
|
2741
|
-
} catch {
|
|
2742
|
-
return undefined // unresolvable, unreadable, or outside the project
|
|
2743
|
-
}
|
|
2744
|
-
})
|
|
2745
|
-
}
|
|
1018
|
+
export {
|
|
1019
|
+
createProjectSqlImports,
|
|
1020
|
+
createSqlImports,
|
|
1021
|
+
type SqlImports,
|
|
1022
|
+
scanInterpolatedSql,
|
|
1023
|
+
scanProjectSql,
|
|
1024
|
+
scanSqlSites,
|
|
1025
|
+
} from "./check-scan-sql.ts"
|
|
2746
1026
|
|
|
2747
1027
|
// `client("` / `client('` / `client(\`` - a URL-first call WITHOUT the `<typeof app>` generic:
|
|
2748
1028
|
// the compiler has nothing to derive types from, so the anti-drift guarantee silently vanishes.
|
|
@@ -2979,7 +1259,7 @@ function hasBackendOnlyMarker(content: string): boolean {
|
|
|
2979
1259
|
}
|
|
2980
1260
|
|
|
2981
1261
|
/** A relative module specifier (`./x`, `../y`) - the only kind the SQL import lookup follows. */
|
|
2982
|
-
const isRelativeSpecifier = (spec: string): boolean =>
|
|
1262
|
+
export const isRelativeSpecifier = (spec: string): boolean =>
|
|
2983
1263
|
spec.startsWith("./") || spec.startsWith("../")
|
|
2984
1264
|
|
|
2985
1265
|
// A FRESH copy of the static-import regex per scan. The transitive walk is REENTRANT - the outer
|
|
@@ -3551,7 +1831,7 @@ export function componentScripts(text: string): string {
|
|
|
3551
1831
|
return out + blank(text.slice(at))
|
|
3552
1832
|
}
|
|
3553
1833
|
|
|
3554
|
-
const bySite = (a: SourceFinding, b: SourceFinding): number =>
|
|
1834
|
+
export const bySite = (a: SourceFinding, b: SourceFinding): number =>
|
|
3555
1835
|
codeUnitOrder(a.file, b.file) || a.line - b.line
|
|
3556
1836
|
|
|
3557
1837
|
/** Collect own-API `fetch()` findings across the project. */
|