@fabrika/check 0.0.0-stage → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/trust.ts ADDED
@@ -0,0 +1,189 @@
1
+ // The platform reads `z`, `defineContract` and `defineTables` by the package they are imported from. That holds only
2
+ // while nothing in the application redirects those packages, so every configuration that can redirect an import is
3
+ // checked here, for the checker and for the reader alike. Plain JavaScript: the reader runs it in a Worker.
4
+
5
+ import type { Finding } from './finding'
6
+ import { parseJsonc } from './jsonc'
7
+ import { isIgnoredSegment, isRelativeSpecifier, isSourceFile, joinRelative } from './layout'
8
+ import { isKey, parseToml } from './toml'
9
+
10
+ /** Packages whose exports the reader trusts by name, and the packages they rely on. */
11
+ export const isTrustedSpecifier = (specifier: string): boolean =>
12
+ specifier === 'zod' || specifier.startsWith('zod/') || specifier === 'bun' || specifier.startsWith('@fabrika/')
13
+
14
+ /** Representatives of every trusted specifier form: a pattern that can match one of these is refused. */
15
+ const TRUSTED_FORMS: readonly { readonly prefix: string; readonly open: boolean }[] = [
16
+ { prefix: 'zod', open: false },
17
+ { prefix: 'zod/', open: true },
18
+ { prefix: 'bun', open: false },
19
+ { prefix: '@fabrika/', open: true },
20
+ ]
21
+
22
+ /** Whether an import-map pattern (`zod/*`, `*`, `@fab*`, `zod`) can match a trusted specifier. */
23
+ export const patternMayMatchTrusted = (pattern: string): boolean => {
24
+ const star = pattern.indexOf('*')
25
+ if (star === -1) {
26
+ return isTrustedSpecifier(pattern)
27
+ }
28
+ const prefix = pattern.slice(0, star)
29
+ const suffix = pattern.slice(star + 1)
30
+ return TRUSTED_FORMS.some((form) => {
31
+ if (form.open) {
32
+ // An open form continues with any text, so the pattern matches once its literal prefix agrees with it.
33
+ return form.prefix.startsWith(prefix) || prefix.startsWith(form.prefix)
34
+ }
35
+ return form.prefix.startsWith(prefix) && form.prefix.slice(prefix.length).endsWith(suffix)
36
+ })
37
+ }
38
+
39
+ const TSCONFIG_NAMES = ['tsconfig.json', 'jsconfig.json']
40
+ export const BUNFIG_FILE = 'bunfig.toml'
41
+
42
+ const baseName = (path: string): string => path.slice(path.lastIndexOf('/') + 1)
43
+
44
+ /** The configuration files `checkTrustedResolution` reads, wherever they lie: Bun reads the nearest one. */
45
+ export const isResolutionConfig = (path: string): boolean =>
46
+ TSCONFIG_NAMES.includes(baseName(path)) || baseName(path) === 'package.json' || path === BUNFIG_FILE
47
+
48
+ const isRecord = (value: unknown): value is Readonly<Record<string, unknown>> => typeof value === 'object' && value !== null && !Array.isArray(value)
49
+
50
+ /** Where `needle` first appears in `text`, as a finding position; the start of the file when it does not. */
51
+ const positionIn = (text: string, needle: string): { readonly line: number; readonly column: number } => {
52
+ const index = text.indexOf(needle)
53
+ if (index === -1) {
54
+ return { line: 1, column: 1 }
55
+ }
56
+ const before = text.slice(0, index)
57
+ const lineStart = before.lastIndexOf('\n') + 1
58
+ return { line: before.split('\n').length, column: index - lineStart + 1 }
59
+ }
60
+
61
+ /**
62
+ * Every configuration among `files` that could make a trusted import load something else: a `paths` or `imports`
63
+ * pattern that can match it, a `baseUrl` (an application file shadows a package under it), an `extends` the check
64
+ * cannot follow, an unparseable `tsconfig.json`, and a runtime `preload` in `bunfig.toml` (a plugin can redirect any
65
+ * import).
66
+ */
67
+ export const checkTrustedResolution = (files: ReadonlyMap<string, string>): Finding[] => {
68
+ const findings: Finding[] = []
69
+ const finding = (file: string, needle: string, message: string, allowed: string): void => {
70
+ findings.push({ file, ...positionIn(files.get(file) ?? '', needle), severity: 'refusal', rule: 'unchecked-import', message, allowed })
71
+ }
72
+ for (const [path, text] of files) {
73
+ if (TSCONFIG_NAMES.includes(baseName(path))) {
74
+ checkTsconfig(path, text, files, finding, new Set([path]))
75
+ } else if (baseName(path) === 'package.json') {
76
+ const manifest = parseJsonc(text)
77
+ const imports = isRecord(manifest) ? manifest['imports'] : undefined
78
+ for (const pattern of isRecord(imports) ? Object.keys(imports) : []) {
79
+ if (patternMayMatchTrusted(pattern)) {
80
+ finding(path, `"${pattern}"`, `the import map entry '${pattern}' can redirect a package the platform trusts by name`, MAP_ALLOWED)
81
+ }
82
+ }
83
+ } else if (path === BUNFIG_FILE) {
84
+ checkBunfig(text, (needle, message, allowed) => finding(path, needle, message, allowed))
85
+ }
86
+ }
87
+ return findings
88
+ }
89
+
90
+ const MAP_ALLOWED = 'mappings only for specifiers other than @fabrika/*, zod, zod/* and bun'
91
+
92
+ type Report = (file: string, needle: string, message: string, allowed: string) => void
93
+
94
+ function checkTsconfig(path: string, text: string, files: ReadonlyMap<string, string>, report: Report, seen: ReadonlySet<string>): void {
95
+ const config = parseJsonc(text)
96
+ if (!isRecord(config)) {
97
+ report(path, '', `${path} is not JSON with comments, so its import mappings cannot be checked`, 'a tsconfig.json that parses')
98
+ return
99
+ }
100
+ const options = config['compilerOptions']
101
+ if (isRecord(options)) {
102
+ if (options['baseUrl'] !== undefined) {
103
+ report(
104
+ path,
105
+ '"baseUrl"',
106
+ 'baseUrl lets an application file shadow a package the platform trusts by name',
107
+ 'paths with relative targets, without baseUrl',
108
+ )
109
+ }
110
+ const paths = options['paths']
111
+ for (const pattern of isRecord(paths) ? Object.keys(paths) : []) {
112
+ if (patternMayMatchTrusted(pattern)) {
113
+ report(path, `"${pattern}"`, `the paths entry '${pattern}' can redirect a package the platform trusts by name`, MAP_ALLOWED)
114
+ }
115
+ }
116
+ }
117
+ const extended = config['extends']
118
+ const targets = typeof extended === 'string' ? [extended] : Array.isArray(extended) ? extended : []
119
+ for (const target of targets) {
120
+ if (typeof target !== 'string' || !isRelativeSpecifier(target)) {
121
+ report(
122
+ path,
123
+ '"extends"',
124
+ `${path} extends '${String(target)}', a configuration outside what the platform reads`,
125
+ 'a relative extends of a file inside the application, or none',
126
+ )
127
+ continue
128
+ }
129
+ const base = joinRelative(path, target)
130
+ const resolved = base === undefined ? undefined : [base, `${base}.json`].find((candidate) => files.has(candidate))
131
+ if (resolved === undefined) {
132
+ report(
133
+ path,
134
+ '"extends"',
135
+ `${path} extends '${target}', which is not a file inside the application`,
136
+ 'a relative extends of a file inside the application, or none',
137
+ )
138
+ } else if (!seen.has(resolved)) {
139
+ checkTsconfig(resolved, files.get(resolved) ?? '', files, report, new Set([...seen, resolved]))
140
+ }
141
+ }
142
+ }
143
+
144
+ /** A test preload must be a checked application file: a skipped or generated one runs unchecked during the build. */
145
+ const isCheckedTestPreload = (target: string): boolean => {
146
+ if (!target.startsWith('./')) return false
147
+ const segments = target.slice(2).split('/')
148
+ return segments[0] !== 'fabrika' && segments.every((segment) => segment !== '' && segment !== '..' && !isIgnoredSegment(segment))
149
+ && isSourceFile(target)
150
+ }
151
+
152
+ /**
153
+ * Bun's runtime `preload` runs before the application and can register a plugin that resolves any import; read with
154
+ * Bun's own key decoding, so `"preload"` is `preload`. A test preload runs during the platform build.
155
+ */
156
+ function checkBunfig(text: string, report: (needle: string, message: string, allowed: string) => void): void {
157
+ const lines = text.split('\n')
158
+ const at = (line: number): string => lines[line - 1]?.trim() ?? ''
159
+ const document = parseToml(text)
160
+ if (!document.ok) {
161
+ report(
162
+ at(document.line),
163
+ `bunfig.toml line ${document.line} is outside the TOML the platform reads (${document.message})`,
164
+ 'single-line keys and values: strings, numbers, booleans and arrays of them',
165
+ )
166
+ return
167
+ }
168
+ for (const entry of document.entries) {
169
+ if (isKey(entry, 'preload')) {
170
+ report(
171
+ at(entry.line),
172
+ 'a runtime preload can register a plugin that redirects any import, trusted packages included',
173
+ 'no top-level preload in bunfig.toml',
174
+ )
175
+ }
176
+ if (isKey(entry, 'test', 'preload')) {
177
+ const targets = entry.value.kind === 'array' ? entry.value.items : [entry.value]
178
+ for (const target of targets) {
179
+ if (target.kind !== 'string' || !isCheckedTestPreload(target.value)) {
180
+ report(
181
+ at(entry.line),
182
+ 'a test preload outside the checked application files runs unchecked in the platform build',
183
+ "'./<path>' of a source file the checker reads, outside fabrika/, dist/, node_modules/ and dot directories",
184
+ )
185
+ }
186
+ }
187
+ }
188
+ }
189
+ }
package/src/version.ts ADDED
@@ -0,0 +1,4 @@
1
+ import checkPackage from '../package.json' with { type: 'json' }
2
+
3
+ /** The version of this checker and reader, recorded with every snapshot Control reads with it. */
4
+ export const CHECKER_VERSION: string = checkPackage.version
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.