@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/package.json +48 -5
- package/src/ast.ts +268 -0
- package/src/bun-plugin.ts +63 -0
- package/src/check.ts +183 -0
- package/src/cli.ts +88 -0
- package/src/contract.ts +254 -0
- package/src/endpoint-fixtures.ts +221 -0
- package/src/finding.ts +88 -0
- package/src/graph.ts +206 -0
- package/src/index.ts +15 -0
- package/src/inputs.ts +88 -0
- package/src/jsonc.ts +63 -0
- package/src/layout.ts +115 -0
- package/src/limits.ts +15 -0
- package/src/packed.ts +66 -0
- package/src/reader/problems.ts +11 -0
- package/src/reader/schema.ts +551 -0
- package/src/reader/surface.ts +1087 -0
- package/src/reader/tables.ts +116 -0
- package/src/reader/value.ts +644 -0
- package/src/references.ts +95 -0
- package/src/resolution.ts +178 -0
- package/src/rules/contract.ts +78 -0
- package/src/rules/crontab.ts +147 -0
- package/src/rules/framework.ts +177 -0
- package/src/rules/identity.ts +80 -0
- package/src/rules/isolation.ts +79 -0
- package/src/rules/json.ts +28 -0
- package/src/rules/literal.ts +736 -0
- package/src/rules/migrations.ts +87 -0
- package/src/rules/modules.ts +226 -0
- package/src/rules/packages.ts +168 -0
- package/src/rules/runtime.ts +507 -0
- package/src/rules/structure.ts +299 -0
- package/src/rules/tests.ts +208 -0
- package/src/rules/types.ts +62 -0
- package/src/scaffold-sample.ts +108 -0
- package/src/scaffold.ts +605 -0
- package/src/scope.ts +108 -0
- package/src/slice.ts +339 -0
- package/src/toml.ts +159 -0
- package/src/trust.ts +189 -0
- package/src/version.ts +4 -0
- package/README.md +0 -3
package/src/scope.ts
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { type AstNode, child, children, identifierName, stringField, walk } from './ast'
|
|
2
|
+
|
|
3
|
+
const FUNCTIONS = new Set(['FunctionDeclaration', 'FunctionExpression', 'ArrowFunctionExpression'])
|
|
4
|
+
const LOOPS = new Set(['ForStatement', 'ForInStatement', 'ForOfStatement'])
|
|
5
|
+
|
|
6
|
+
/** The names a binding pattern declares: `x`, `{ a, b: c, ...d }`, `[e = 1]`, a constructor's `private f`. */
|
|
7
|
+
const patternNames = (pattern: AstNode | null | undefined): readonly string[] => {
|
|
8
|
+
if (pattern === null || pattern === undefined) return []
|
|
9
|
+
const name = identifierName(pattern)
|
|
10
|
+
if (name !== undefined) return [name]
|
|
11
|
+
switch (pattern.type) {
|
|
12
|
+
case 'ObjectPattern':
|
|
13
|
+
return children(pattern, 'properties').flatMap((property) =>
|
|
14
|
+
property === null ? [] : patternNames(child(property, property.type === 'RestElement' ? 'argument' : 'value'))
|
|
15
|
+
)
|
|
16
|
+
case 'ArrayPattern':
|
|
17
|
+
return children(pattern, 'elements').flatMap(patternNames)
|
|
18
|
+
case 'AssignmentPattern':
|
|
19
|
+
return patternNames(child(pattern, 'left'))
|
|
20
|
+
case 'RestElement':
|
|
21
|
+
return patternNames(child(pattern, 'argument'))
|
|
22
|
+
case 'TSParameterProperty':
|
|
23
|
+
return patternNames(child(pattern, 'parameter'))
|
|
24
|
+
default:
|
|
25
|
+
return []
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const declaratorNames = (declaration: AstNode | undefined, lexical: boolean): readonly string[] => {
|
|
30
|
+
if (declaration?.type !== 'VariableDeclaration' || (stringField(declaration, 'kind') === 'var') === lexical) return []
|
|
31
|
+
return children(declaration, 'declarations').flatMap((declarator) => (declarator === null ? [] : patternNames(child(declarator, 'id'))))
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* What one statement declares in the block it stands in: `let`/`const` (every kind at the top level), functions,
|
|
36
|
+
* classes, value imports. An ambient `declare` binds nothing at runtime: the name it types stays the global.
|
|
37
|
+
*/
|
|
38
|
+
const statementNames = (statement: AstNode | null, topLevel: boolean): readonly string[] => {
|
|
39
|
+
if (statement === null || statement['declare'] === true) return []
|
|
40
|
+
switch (statement.type) {
|
|
41
|
+
case 'VariableDeclaration':
|
|
42
|
+
return topLevel ? [...declaratorNames(statement, true), ...declaratorNames(statement, false)] : declaratorNames(statement, true)
|
|
43
|
+
case 'FunctionDeclaration':
|
|
44
|
+
case 'ClassDeclaration':
|
|
45
|
+
case 'TSImportEqualsDeclaration':
|
|
46
|
+
return patternNames(child(statement, 'id'))
|
|
47
|
+
case 'ImportDeclaration':
|
|
48
|
+
if (stringField(statement, 'importKind') === 'type') return []
|
|
49
|
+
return children(statement, 'specifiers').flatMap((specifier) =>
|
|
50
|
+
specifier === null || stringField(specifier, 'importKind') === 'type' ? [] : patternNames(child(specifier, 'local'))
|
|
51
|
+
)
|
|
52
|
+
case 'ExportNamedDeclaration':
|
|
53
|
+
case 'ExportDefaultDeclaration':
|
|
54
|
+
return statementNames(child(statement, 'declaration') ?? null, topLevel)
|
|
55
|
+
default:
|
|
56
|
+
return []
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** `var` names a function body declares anywhere, outside the functions nested in it. */
|
|
61
|
+
const varNames = (body: AstNode | undefined): readonly string[] => {
|
|
62
|
+
const names: string[] = []
|
|
63
|
+
if (body === undefined) return names
|
|
64
|
+
walk(body, (node) => {
|
|
65
|
+
if (FUNCTIONS.has(node.type)) return 'skip'
|
|
66
|
+
names.push(...declaratorNames(node, false))
|
|
67
|
+
return undefined
|
|
68
|
+
})
|
|
69
|
+
return names
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** The names `scope` declares for the code inside it; empty for a node that opens no scope. */
|
|
73
|
+
const declaredNames = (scope: AstNode): readonly string[] => {
|
|
74
|
+
if (FUNCTIONS.has(scope.type)) {
|
|
75
|
+
const own = scope.type === 'FunctionExpression' ? patternNames(child(scope, 'id')) : []
|
|
76
|
+
return [...own, ...children(scope, 'params').flatMap(patternNames), ...varNames(child(scope, 'body'))]
|
|
77
|
+
}
|
|
78
|
+
if (LOOPS.has(scope.type)) return declaratorNames(child(scope, scope.type === 'ForStatement' ? 'init' : 'left'), true)
|
|
79
|
+
switch (scope.type) {
|
|
80
|
+
case 'Program':
|
|
81
|
+
return children(scope, 'body').flatMap((statement) => statementNames(statement, true))
|
|
82
|
+
case 'BlockStatement':
|
|
83
|
+
case 'StaticBlock':
|
|
84
|
+
return children(scope, 'body').flatMap((statement) => statementNames(statement, false))
|
|
85
|
+
case 'SwitchStatement':
|
|
86
|
+
return children(scope, 'cases').flatMap((
|
|
87
|
+
item,
|
|
88
|
+
) => (item === null ? [] : children(item, 'consequent').flatMap((statement) => statementNames(statement, false))))
|
|
89
|
+
case 'CatchClause':
|
|
90
|
+
return patternNames(child(scope, 'param'))
|
|
91
|
+
case 'ClassExpression':
|
|
92
|
+
return patternNames(child(scope, 'id'))
|
|
93
|
+
default:
|
|
94
|
+
return []
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* The scope whose declaration `name` denotes at a node with these ancestors: the innermost one that declares it, or
|
|
100
|
+
* `undefined` for a global. A module's imports and top-level declarations belong to its `Program`.
|
|
101
|
+
*/
|
|
102
|
+
export const declaringScope = (name: string, ancestors: readonly AstNode[]): AstNode | undefined => {
|
|
103
|
+
for (let index = ancestors.length - 1; index >= 0; index--) {
|
|
104
|
+
const scope = ancestors[index]
|
|
105
|
+
if (scope !== undefined && declaredNames(scope).includes(name)) return scope
|
|
106
|
+
}
|
|
107
|
+
return undefined
|
|
108
|
+
}
|
package/src/slice.ts
ADDED
|
@@ -0,0 +1,339 @@
|
|
|
1
|
+
// The shell slice of a module: its text without the handlers the staged kit colocates with their endpoints, and
|
|
2
|
+
// without what only those handlers use. The static reader, the literal rule, Control's input discovery and the SPA
|
|
3
|
+
// bundle read slices, so no module only a handler imports is fetched, parsed or loaded. Runtime-neutral: no Node or
|
|
4
|
+
// Bun API.
|
|
5
|
+
//
|
|
6
|
+
// Removed text becomes spaces, newlines kept, so every finding keeps its line and column. `boot`'s digest check backs
|
|
7
|
+
// the slice: it compiles the evaluated modules and refuses to start when they differ from what Control approved.
|
|
8
|
+
|
|
9
|
+
import {
|
|
10
|
+
type AstNode,
|
|
11
|
+
child,
|
|
12
|
+
children,
|
|
13
|
+
identifierName,
|
|
14
|
+
isNode,
|
|
15
|
+
isParenthesized,
|
|
16
|
+
isValueReference,
|
|
17
|
+
type ParsedModule,
|
|
18
|
+
parseModule,
|
|
19
|
+
type ParseResult,
|
|
20
|
+
positionOf,
|
|
21
|
+
staticKey,
|
|
22
|
+
walk,
|
|
23
|
+
} from './ast'
|
|
24
|
+
import type { Finding } from './finding'
|
|
25
|
+
|
|
26
|
+
/** Builders whose result takes `.handle(handler)`: an endpoint of a group, a link or an export, a job and a webhook. */
|
|
27
|
+
const HANDLED_BUILDERS = new Set(['query', 'mutation', 'cron', 'webhook'])
|
|
28
|
+
|
|
29
|
+
interface Range {
|
|
30
|
+
readonly start: number
|
|
31
|
+
readonly end: number
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const isFunction = (node: AstNode | null | undefined): boolean => node?.type === 'ArrowFunctionExpression' || node?.type === 'FunctionExpression'
|
|
35
|
+
|
|
36
|
+
const offsets = (node: AstNode): Range | undefined => {
|
|
37
|
+
const start = node['start']
|
|
38
|
+
const end = node['end']
|
|
39
|
+
return typeof start === 'number' && typeof end === 'number' ? { start, end } : undefined
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const memberName = (node: AstNode | undefined): string | undefined => {
|
|
43
|
+
if (node?.type !== 'MemberExpression' || node['computed'] === true || node['optional'] === true) return undefined
|
|
44
|
+
return identifierName(child(node, 'property'))
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** A `.handle(…)` the slice cannot keep out of the shell, at its `handle`; the reader and the SPA build refuse it. */
|
|
48
|
+
export interface SliceRefusal {
|
|
49
|
+
readonly node: AstNode
|
|
50
|
+
readonly message: string
|
|
51
|
+
readonly allowed: string
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const HANDLER_ALLOWED =
|
|
55
|
+
'.handle(async ({ input, ctx }) => …) written inline on r.query, r.mutation, app.cron or app.webhook; call a named function from inside it'
|
|
56
|
+
|
|
57
|
+
/** Wrappers that leave which member is called unchanged: `x.handle!`, `x.handle as F`, `x satisfies T`, `<F>x.handle`. */
|
|
58
|
+
const EXPRESSION_WRAPPERS = new Set([
|
|
59
|
+
'ChainExpression',
|
|
60
|
+
'TSNonNullExpression',
|
|
61
|
+
'TSAsExpression',
|
|
62
|
+
'TSSatisfiesExpression',
|
|
63
|
+
'TSTypeAssertion',
|
|
64
|
+
'TSInstantiationExpression',
|
|
65
|
+
])
|
|
66
|
+
|
|
67
|
+
const withoutWrappers = (node: AstNode): AstNode => {
|
|
68
|
+
let current = node
|
|
69
|
+
while (EXPRESSION_WRAPPERS.has(current.type)) {
|
|
70
|
+
const inner = child(current, 'expression')
|
|
71
|
+
if (inner === undefined) return current
|
|
72
|
+
current = inner
|
|
73
|
+
}
|
|
74
|
+
return current
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** The type text each wrapper around `node` adds, removable without unbalancing the expression: `as F`, `<F>`, `<T>`. */
|
|
78
|
+
const wrapperTypes = (node: AstNode): Range[] => {
|
|
79
|
+
const ranges: Range[] = []
|
|
80
|
+
let current = node
|
|
81
|
+
while (EXPRESSION_WRAPPERS.has(current.type)) {
|
|
82
|
+
const inner = child(current, 'expression')
|
|
83
|
+
const outer = offsets(current)
|
|
84
|
+
const within = inner === undefined ? undefined : offsets(inner)
|
|
85
|
+
if (inner === undefined || outer === undefined || within === undefined) break
|
|
86
|
+
if (current.type === 'TSTypeAssertion') ranges.push({ start: outer.start, end: within.start })
|
|
87
|
+
else if (current.type !== 'ChainExpression' && current.type !== 'TSNonNullExpression') ranges.push({ start: within.end, end: outer.end })
|
|
88
|
+
current = inner
|
|
89
|
+
}
|
|
90
|
+
return ranges
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
interface HandleSite {
|
|
94
|
+
/** The text the slice removes: the whole `.handle(…)` of a handler, what a refused one names. */
|
|
95
|
+
readonly ranges: readonly Range[]
|
|
96
|
+
/** What `.handle` is called on; it stays in the shell, and the slice reads it for handlers of its own. */
|
|
97
|
+
readonly receiver: AstNode
|
|
98
|
+
readonly refusal?: SliceRefusal
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* A call of a member statically named `handle`. `<x>.<builder>(…).handle(<inline function>)` is a handler, removed from
|
|
103
|
+
* the end of its receiver. Any other spelling, receiver or handler is refused, and its type arguments, arguments and
|
|
104
|
+
* wrapping types are removed all the same, so what it names is never followed into a module the shell does not need.
|
|
105
|
+
*/
|
|
106
|
+
function handleSite(node: AstNode): HandleSite | undefined {
|
|
107
|
+
if (node.type !== 'CallExpression') return undefined
|
|
108
|
+
const callee = child(node, 'callee')
|
|
109
|
+
const member = callee === undefined ? undefined : withoutWrappers(callee)
|
|
110
|
+
if (callee === undefined || member?.type !== 'MemberExpression' || staticKey(member, 'property') !== 'handle') return undefined
|
|
111
|
+
const property = child(member, 'property')
|
|
112
|
+
const receiver = child(member, 'object')
|
|
113
|
+
const call = offsets(node)
|
|
114
|
+
const receiverRange = receiver === undefined ? undefined : offsets(receiver)
|
|
115
|
+
if (property === undefined || receiver === undefined || call === undefined || receiverRange === undefined) return undefined
|
|
116
|
+
const refused = (message: string): HandleSite => {
|
|
117
|
+
const handler = children(node, 'arguments').filter(isNode).flatMap((argument) => offsets(argument) ?? [])
|
|
118
|
+
const first = handler[0]
|
|
119
|
+
const last = handler.at(-1)
|
|
120
|
+
const typeArguments = child(node, 'typeArguments')
|
|
121
|
+
const typeRange = typeArguments === undefined ? undefined : offsets(typeArguments)
|
|
122
|
+
const ranges = [
|
|
123
|
+
...wrapperTypes(callee),
|
|
124
|
+
...wrapperTypes(receiver),
|
|
125
|
+
...(typeRange === undefined ? [] : [typeRange]),
|
|
126
|
+
...(first === undefined || last === undefined ? [] : [{ start: first.start, end: last.end }]),
|
|
127
|
+
]
|
|
128
|
+
return { ranges, receiver, refusal: { node: property, message, allowed: HANDLER_ALLOWED } }
|
|
129
|
+
}
|
|
130
|
+
const plain = member === callee && member['computed'] !== true && withoutWrappers(receiver) === receiver
|
|
131
|
+
if (!plain || isParenthesized(member) || isParenthesized(receiver)) {
|
|
132
|
+
return refused('.handle spelled other than a plain `.handle(…)` called directly on its builder')
|
|
133
|
+
}
|
|
134
|
+
const builder = receiver.type === 'CallExpression' ? memberName(child(receiver, 'callee')) : undefined
|
|
135
|
+
if (builder === undefined || !HANDLED_BUILDERS.has(builder)) return refused('.handle(…) on something other than an endpoint, job or webhook builder')
|
|
136
|
+
const handler = children(node, 'arguments')
|
|
137
|
+
if (node['optional'] === true || member['optional'] === true || handler.length !== 1 || !isFunction(handler[0])) {
|
|
138
|
+
return refused('a handler other than one inline function beside its builder')
|
|
139
|
+
}
|
|
140
|
+
return { ranges: [{ start: receiverRange.end, end: call.end }], receiver }
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** Whether an identifier names a type or a value here, rather than a key, a property or a label. */
|
|
144
|
+
function isReference(node: AstNode, parent: AstNode | undefined): boolean {
|
|
145
|
+
switch (parent?.type) {
|
|
146
|
+
case 'TSTypeReference':
|
|
147
|
+
return parent['typeName'] === node
|
|
148
|
+
case 'TSQualifiedName':
|
|
149
|
+
return parent['left'] === node
|
|
150
|
+
case 'TSTypeQuery':
|
|
151
|
+
return parent['exprName'] === node
|
|
152
|
+
case 'TSInterfaceHeritage':
|
|
153
|
+
case 'TSClassImplements':
|
|
154
|
+
case 'TSExpressionWithTypeArguments':
|
|
155
|
+
return parent['expression'] === node
|
|
156
|
+
default:
|
|
157
|
+
return isValueReference(node, parent)
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
interface Binding {
|
|
162
|
+
readonly name: string
|
|
163
|
+
readonly node: AstNode
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* The names a top-level statement binds, when the slice may drop it: only what runs nothing when the module loads
|
|
168
|
+
* (an import, a function, a const of an inline function, a type). Every other statement stays, because Bun runs it,
|
|
169
|
+
* and the literal rule decides about it. An exported declaration stays too: it is part of the module.
|
|
170
|
+
*/
|
|
171
|
+
function removableBindings(statement: AstNode): readonly Binding[] | undefined {
|
|
172
|
+
const bound = (id: AstNode | undefined): Binding[] => {
|
|
173
|
+
const name = identifierName(id)
|
|
174
|
+
return name === undefined || id === undefined ? [] : [{ name, node: id }]
|
|
175
|
+
}
|
|
176
|
+
switch (statement.type) {
|
|
177
|
+
case 'ImportDeclaration': {
|
|
178
|
+
const specifiers = children(statement, 'specifiers').filter(isNode)
|
|
179
|
+
return specifiers.length === 0 ? undefined : specifiers.flatMap((specifier) => bound(child(specifier, 'local')))
|
|
180
|
+
}
|
|
181
|
+
case 'VariableDeclaration': {
|
|
182
|
+
const declarators = children(statement, 'declarations').filter(isNode)
|
|
183
|
+
const functions = declarators.filter((declarator) => isFunction(child(declarator, 'init')))
|
|
184
|
+
return functions.length === declarators.length ? declarators.flatMap((declarator) => bound(child(declarator, 'id'))) : undefined
|
|
185
|
+
}
|
|
186
|
+
case 'FunctionDeclaration':
|
|
187
|
+
case 'TSTypeAliasDeclaration':
|
|
188
|
+
case 'TSInterfaceDeclaration':
|
|
189
|
+
return bound(child(statement, 'id'))
|
|
190
|
+
default:
|
|
191
|
+
return undefined
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
const blank = (text: string): string => text.replace(/[^\n]/g, ' ')
|
|
196
|
+
|
|
197
|
+
const sliceOf = (text: string, node: AstNode): string => {
|
|
198
|
+
const range = offsets(node)
|
|
199
|
+
return range === undefined ? '' : text.slice(range.start, range.end)
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** The import with only its `kept` specifiers, written on its first line, its other lines left empty. */
|
|
203
|
+
function rewrittenImport(text: string, statement: AstNode, kept: readonly AstNode[]): string {
|
|
204
|
+
const range = offsets(statement)
|
|
205
|
+
const source = child(statement, 'source')
|
|
206
|
+
if (range === undefined || source === undefined) return text
|
|
207
|
+
const original = text.slice(range.start, range.end)
|
|
208
|
+
const typeOnly = statement['importKind'] === 'type' ? 'type ' : ''
|
|
209
|
+
const named = kept.filter((specifier) => specifier.type === 'ImportSpecifier')
|
|
210
|
+
const leading = kept.filter((specifier) => specifier.type !== 'ImportSpecifier')
|
|
211
|
+
const parts = [
|
|
212
|
+
...leading.map((specifier) => sliceOf(text, specifier)),
|
|
213
|
+
...(named.length > 0 ? [`{ ${named.map((specifier) => sliceOf(text, specifier)).join(', ')} }`] : []),
|
|
214
|
+
]
|
|
215
|
+
const head = `import ${typeOnly}${parts.join(', ')} from ${sliceOf(text, source)}`
|
|
216
|
+
const firstLine = original.indexOf('\n')
|
|
217
|
+
return firstLine === -1 ? head.padEnd(original.length) : `${head}${blank(original.slice(firstLine))}`
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** The names `statements` refer to, outside the handlers and outside what is removed. */
|
|
221
|
+
function referencedNames(statements: readonly AstNode[], skipped: (node: AstNode) => boolean, own: ReadonlySet<AstNode>): Set<string> {
|
|
222
|
+
const referenced = new Set<string>()
|
|
223
|
+
for (const statement of statements) {
|
|
224
|
+
walk(statement, (node, ancestors) => {
|
|
225
|
+
if (skipped(node)) return 'skip'
|
|
226
|
+
const name = identifierName(node)
|
|
227
|
+
if (name !== undefined && !own.has(node) && isReference(node, ancestors.at(-1))) referenced.add(name)
|
|
228
|
+
return undefined
|
|
229
|
+
})
|
|
230
|
+
}
|
|
231
|
+
return referenced
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** A module's slice, and the `.handle(…)` forms it refused. */
|
|
235
|
+
export interface ShellSlice {
|
|
236
|
+
readonly text: string
|
|
237
|
+
readonly refusals: readonly SliceRefusal[]
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* The slice of one parsed module: `module`'s text with every `.handle(…)` and everything only the handlers used
|
|
242
|
+
* blanked. A module without a handler comes back unchanged.
|
|
243
|
+
*/
|
|
244
|
+
export function moduleSlice(module: ParsedModule, text: string): ShellSlice {
|
|
245
|
+
const handles: Range[] = []
|
|
246
|
+
const refusals: SliceRefusal[] = []
|
|
247
|
+
const visit = (node: AstNode): 'skip' | undefined => {
|
|
248
|
+
const site = handleSite(node)
|
|
249
|
+
if (site === undefined) return undefined
|
|
250
|
+
handles.push(...site.ranges)
|
|
251
|
+
if (site.refusal !== undefined) refusals.push(site.refusal)
|
|
252
|
+
walk(site.receiver, visit)
|
|
253
|
+
return 'skip'
|
|
254
|
+
}
|
|
255
|
+
walk(module.program, visit)
|
|
256
|
+
if (handles.length === 0) return { text, refusals }
|
|
257
|
+
const inHandle = (node: AstNode): boolean => {
|
|
258
|
+
const range = offsets(node)
|
|
259
|
+
return range !== undefined && handles.some((handle) => range.start >= handle.start && range.end <= handle.end)
|
|
260
|
+
}
|
|
261
|
+
const statements = children(module.program, 'body').filter(isNode)
|
|
262
|
+
const removable = new Map<AstNode, readonly Binding[]>()
|
|
263
|
+
for (const statement of statements) {
|
|
264
|
+
const bindings = removableBindings(statement)
|
|
265
|
+
if (bindings !== undefined) removable.set(statement, bindings)
|
|
266
|
+
}
|
|
267
|
+
const own = new Set([...removable.values()].flatMap((bindings) => bindings.map((binding) => binding.node)))
|
|
268
|
+
// What the module uses with its handlers: a declaration nobody uses at all is not the handlers', so it stays.
|
|
269
|
+
const used = referencedNames(statements, () => false, own)
|
|
270
|
+
const removedStatements = new Set<AstNode>()
|
|
271
|
+
const removedSpecifiers = new Set<AstNode>()
|
|
272
|
+
for (let changed = true; changed;) {
|
|
273
|
+
changed = false
|
|
274
|
+
const kept = statements.filter((statement) => !removedStatements.has(statement))
|
|
275
|
+
const referenced = referencedNames(kept, (node) => inHandle(node) || removedSpecifiers.has(node), own)
|
|
276
|
+
const handlersOnly = (name: string): boolean => used.has(name) && !referenced.has(name)
|
|
277
|
+
for (const [statement, bindings] of removable) {
|
|
278
|
+
if (removedStatements.has(statement)) continue
|
|
279
|
+
if (statement.type === 'ImportDeclaration') {
|
|
280
|
+
const specifiers = children(statement, 'specifiers').filter(isNode)
|
|
281
|
+
for (const specifier of specifiers) {
|
|
282
|
+
const name = identifierName(child(specifier, 'local'))
|
|
283
|
+
if (name !== undefined && !removedSpecifiers.has(specifier) && handlersOnly(name)) {
|
|
284
|
+
removedSpecifiers.add(specifier)
|
|
285
|
+
changed = true
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
if (specifiers.every((specifier) => removedSpecifiers.has(specifier))) removedStatements.add(statement)
|
|
289
|
+
} else if (bindings.every((binding) => handlersOnly(binding.name))) {
|
|
290
|
+
removedStatements.add(statement)
|
|
291
|
+
changed = true
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
const removedRanges = [...removedStatements].flatMap((statement) => offsets(statement) ?? [])
|
|
296
|
+
const edits: { readonly range: Range; readonly replacement: string }[] = handles
|
|
297
|
+
.filter((handle) => !removedRanges.some((range) => handle.start >= range.start && handle.end <= range.end))
|
|
298
|
+
.map((range) => ({ range, replacement: blank(text.slice(range.start, range.end)) }))
|
|
299
|
+
for (const statement of statements) {
|
|
300
|
+
const range = offsets(statement)
|
|
301
|
+
if (range === undefined) continue
|
|
302
|
+
if (removedStatements.has(statement)) {
|
|
303
|
+
edits.push({ range, replacement: blank(text.slice(range.start, range.end)) })
|
|
304
|
+
continue
|
|
305
|
+
}
|
|
306
|
+
const specifiers = statement.type === 'ImportDeclaration' ? children(statement, 'specifiers').filter(isNode) : []
|
|
307
|
+
if (specifiers.some((specifier) => removedSpecifiers.has(specifier))) {
|
|
308
|
+
edits.push({ range, replacement: rewrittenImport(text, statement, specifiers.filter((specifier) => !removedSpecifiers.has(specifier))) })
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
let sliced = text
|
|
312
|
+
for (const edit of edits.sort((left, right) => right.range.start - left.range.start)) {
|
|
313
|
+
sliced = sliced.slice(0, edit.range.start) + edit.replacement + sliced.slice(edit.range.end)
|
|
314
|
+
}
|
|
315
|
+
return { text: sliced, refusals }
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/**
|
|
319
|
+
* The slice of a module's text. Text that does not parse comes back unchanged, so the reader reports the parse error
|
|
320
|
+
* where it is.
|
|
321
|
+
*/
|
|
322
|
+
export function shellSlice(file: string, text: string): ShellSlice {
|
|
323
|
+
const parsed = parseModule(file, text)
|
|
324
|
+
return parsed.ok ? moduleSlice(parsed.module, text) : { text, refusals: [] }
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/** A refused `.handle(…)` as the finding the reader, the checker and the SPA build report. */
|
|
328
|
+
export function sliceFinding(module: ParsedModule, refusal: SliceRefusal): Finding {
|
|
329
|
+
return { file: module.file, ...positionOf(refusal.node), severity: 'refusal', rule: 'literal', message: refusal.message, allowed: refusal.allowed }
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
/** A module parsed as its slice, what the reader and input discovery read, with the `.handle(…)` forms it refused. */
|
|
333
|
+
export function parseShellModule(file: string, text: string): { readonly parsed: ParseResult; readonly refusals: readonly Finding[] } {
|
|
334
|
+
const parsed = parseModule(file, text)
|
|
335
|
+
if (!parsed.ok) return { parsed, refusals: [] }
|
|
336
|
+
const slice = moduleSlice(parsed.module, text)
|
|
337
|
+
const refusals = slice.refusals.map((refusal) => sliceFinding(parsed.module, refusal))
|
|
338
|
+
return { parsed: slice.text === text ? parsed : parseModule(file, slice.text), refusals }
|
|
339
|
+
}
|
package/src/toml.ts
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
// The subset of TOML a `bunfig.toml` is read in, decoded the way Bun decodes it, so a quoted or dotted key is the same
|
|
2
|
+
// key as its bare form. Plain JavaScript: the reader runs it in a Worker, where `Bun.TOML` does not exist. A file
|
|
3
|
+
// outside the subset is not guessed at; the caller refuses it.
|
|
4
|
+
|
|
5
|
+
export type TomlValue =
|
|
6
|
+
| { readonly kind: 'string'; readonly value: string }
|
|
7
|
+
| { readonly kind: 'array'; readonly items: readonly TomlValue[] }
|
|
8
|
+
/** A number, boolean or date, kept as its source text. */
|
|
9
|
+
| { readonly kind: 'scalar'; readonly raw: string }
|
|
10
|
+
|
|
11
|
+
export interface TomlEntry {
|
|
12
|
+
/** The full key: the table's key followed by the entry's own, each decoded. */
|
|
13
|
+
readonly key: readonly string[]
|
|
14
|
+
readonly value: TomlValue
|
|
15
|
+
readonly line: number
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export type TomlDocument =
|
|
19
|
+
| { readonly ok: true; readonly entries: readonly TomlEntry[] }
|
|
20
|
+
| { readonly ok: false; readonly line: number; readonly message: string }
|
|
21
|
+
|
|
22
|
+
class Unsupported extends Error {}
|
|
23
|
+
|
|
24
|
+
const BARE_KEY = /^[A-Za-z0-9_-]+/
|
|
25
|
+
const SCALAR = /^[A-Za-z0-9_.:+-]+/
|
|
26
|
+
const ESCAPES: Readonly<Record<string, string>> = { b: '\b', t: '\t', n: '\n', f: '\f', r: '\r', '"': '"', '\\': '\\' }
|
|
27
|
+
|
|
28
|
+
/** A cursor over one line. */
|
|
29
|
+
class Line {
|
|
30
|
+
index = 0
|
|
31
|
+
constructor(readonly text: string) {}
|
|
32
|
+
|
|
33
|
+
skipSpace(): void {
|
|
34
|
+
while (this.text[this.index] === ' ' || this.text[this.index] === '\t') this.index++
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** True at the end of the line or at a comment. */
|
|
38
|
+
atEnd(): boolean {
|
|
39
|
+
this.skipSpace()
|
|
40
|
+
return this.index >= this.text.length || this.text[this.index] === '#'
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
expect(char: string): void {
|
|
44
|
+
this.skipSpace()
|
|
45
|
+
if (this.text[this.index] !== char) throw new Unsupported(`expected '${char}'`)
|
|
46
|
+
this.index++
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
rest(): string {
|
|
50
|
+
return this.text.slice(this.index)
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
string(): string {
|
|
54
|
+
const quote = this.text[this.index]
|
|
55
|
+
if (this.text.startsWith(quote === '"' ? '"""' : "'''", this.index)) throw new Unsupported('a multi-line string')
|
|
56
|
+
this.index++
|
|
57
|
+
let value = ''
|
|
58
|
+
while (this.index < this.text.length) {
|
|
59
|
+
const char = this.text[this.index] ?? ''
|
|
60
|
+
this.index++
|
|
61
|
+
if (char === quote) return value
|
|
62
|
+
if (quote === '"' && char === '\\') value += this.escape()
|
|
63
|
+
else value += char
|
|
64
|
+
}
|
|
65
|
+
throw new Unsupported('an unterminated string')
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
private escape(): string {
|
|
69
|
+
const code = this.text[this.index] ?? ''
|
|
70
|
+
this.index++
|
|
71
|
+
const simple = ESCAPES[code]
|
|
72
|
+
if (simple !== undefined) return simple
|
|
73
|
+
const length = code === 'u' ? 4 : code === 'U' ? 8 : 0
|
|
74
|
+
const hex = this.text.slice(this.index, this.index + length)
|
|
75
|
+
if (length === 0 || !/^[0-9A-Fa-f]+$/.test(hex) || hex.length !== length) throw new Unsupported('an unknown escape')
|
|
76
|
+
this.index += length
|
|
77
|
+
return String.fromCodePoint(Number.parseInt(hex, 16))
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
key(): string[] {
|
|
81
|
+
const parts: string[] = []
|
|
82
|
+
for (;;) {
|
|
83
|
+
this.skipSpace()
|
|
84
|
+
const char = this.text[this.index]
|
|
85
|
+
if (char === '"' || char === "'") {
|
|
86
|
+
parts.push(this.string())
|
|
87
|
+
} else {
|
|
88
|
+
const bare = BARE_KEY.exec(this.rest())?.[0]
|
|
89
|
+
if (bare === undefined) throw new Unsupported('a key that is neither bare nor quoted')
|
|
90
|
+
parts.push(bare)
|
|
91
|
+
this.index += bare.length
|
|
92
|
+
}
|
|
93
|
+
this.skipSpace()
|
|
94
|
+
if (this.text[this.index] !== '.') return parts
|
|
95
|
+
this.index++
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
value(): TomlValue {
|
|
100
|
+
this.skipSpace()
|
|
101
|
+
const char = this.text[this.index]
|
|
102
|
+
if (char === '"' || char === "'") return { kind: 'string', value: this.string() }
|
|
103
|
+
if (char === '[') return this.array()
|
|
104
|
+
if (char === '{') throw new Unsupported('an inline table')
|
|
105
|
+
const raw = SCALAR.exec(this.rest())?.[0]
|
|
106
|
+
if (raw === undefined) throw new Unsupported('a value outside strings, arrays, numbers and booleans')
|
|
107
|
+
this.index += raw.length
|
|
108
|
+
return { kind: 'scalar', raw }
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
private array(): TomlValue {
|
|
112
|
+
this.index++
|
|
113
|
+
const items: TomlValue[] = []
|
|
114
|
+
for (;;) {
|
|
115
|
+
this.skipSpace()
|
|
116
|
+
if (this.index >= this.text.length || this.text[this.index] === '#') throw new Unsupported('an array over more than one line')
|
|
117
|
+
if (this.text[this.index] === ']') {
|
|
118
|
+
this.index++
|
|
119
|
+
return { kind: 'array', items }
|
|
120
|
+
}
|
|
121
|
+
items.push(this.value())
|
|
122
|
+
this.skipSpace()
|
|
123
|
+
if (this.text[this.index] === ',') this.index++
|
|
124
|
+
else if (this.text[this.index] !== ']') throw new Unsupported("expected ',' or ']'")
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** Decode `text`, or say on which line it leaves the subset. */
|
|
130
|
+
export function parseToml(text: string): TomlDocument {
|
|
131
|
+
const entries: TomlEntry[] = []
|
|
132
|
+
let table: readonly string[] = []
|
|
133
|
+
const lines = text.split('\n')
|
|
134
|
+
for (const [index, raw] of lines.entries()) {
|
|
135
|
+
const line = new Line(raw.endsWith('\r') ? raw.slice(0, -1) : raw)
|
|
136
|
+
try {
|
|
137
|
+
if (line.atEnd()) continue
|
|
138
|
+
if (line.rest().startsWith('[[')) throw new Unsupported('an array of tables')
|
|
139
|
+
if (line.rest().startsWith('[')) {
|
|
140
|
+
line.expect('[')
|
|
141
|
+
table = line.key()
|
|
142
|
+
line.expect(']')
|
|
143
|
+
} else {
|
|
144
|
+
const key = line.key()
|
|
145
|
+
line.expect('=')
|
|
146
|
+
entries.push({ key: [...table, ...key], value: line.value(), line: index + 1 })
|
|
147
|
+
}
|
|
148
|
+
if (!line.atEnd()) throw new Unsupported('text after the value')
|
|
149
|
+
} catch (error) {
|
|
150
|
+
if (!(error instanceof Unsupported)) throw error
|
|
151
|
+
return { ok: false, line: index + 1, message: error.message }
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
return { ok: true, entries }
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** Whether the decoded key is `expected`. */
|
|
158
|
+
export const isKey = (entry: TomlEntry, ...expected: readonly string[]): boolean =>
|
|
159
|
+
entry.key.length === expected.length && entry.key.every((part, index) => part === expected[index])
|