@namzu/sdk 69.2.0 → 69.3.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.
Files changed (118) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/constants/plugin/index.d.ts +8 -0
  3. package/dist/constants/plugin/index.d.ts.map +1 -1
  4. package/dist/constants/plugin/index.js +8 -0
  5. package/dist/constants/plugin/index.js.map +1 -1
  6. package/dist/plugin/common-layout/index.d.ts +5 -0
  7. package/dist/plugin/common-layout/index.d.ts.map +1 -0
  8. package/dist/plugin/common-layout/index.js +3 -0
  9. package/dist/plugin/common-layout/index.js.map +1 -0
  10. package/dist/plugin/common-layout/mcp.d.ts +21 -0
  11. package/dist/plugin/common-layout/mcp.d.ts.map +1 -0
  12. package/dist/plugin/common-layout/mcp.js +305 -0
  13. package/dist/plugin/common-layout/mcp.js.map +1 -0
  14. package/dist/plugin/common-layout/paths.d.ts +27 -0
  15. package/dist/plugin/common-layout/paths.d.ts.map +1 -0
  16. package/dist/plugin/common-layout/paths.js +48 -0
  17. package/dist/plugin/common-layout/paths.js.map +1 -0
  18. package/dist/plugin/common-layout/read.d.ts +25 -0
  19. package/dist/plugin/common-layout/read.d.ts.map +1 -0
  20. package/dist/plugin/common-layout/read.js +1155 -0
  21. package/dist/plugin/common-layout/read.js.map +1 -0
  22. package/dist/plugin/common-layout/types.d.ts +66 -0
  23. package/dist/plugin/common-layout/types.d.ts.map +1 -0
  24. package/dist/plugin/common-layout/types.js +2 -0
  25. package/dist/plugin/common-layout/types.js.map +1 -0
  26. package/dist/plugin/common-layout-names.d.ts +65 -0
  27. package/dist/plugin/common-layout-names.d.ts.map +1 -0
  28. package/dist/plugin/common-layout-names.js +94 -0
  29. package/dist/plugin/common-layout-names.js.map +1 -0
  30. package/dist/plugin/hook-module/capabilities.d.ts +41 -0
  31. package/dist/plugin/hook-module/capabilities.d.ts.map +1 -0
  32. package/dist/plugin/hook-module/capabilities.js +438 -0
  33. package/dist/plugin/hook-module/capabilities.js.map +1 -0
  34. package/dist/plugin/hook-module/consent.d.ts +39 -0
  35. package/dist/plugin/hook-module/consent.d.ts.map +1 -0
  36. package/dist/plugin/hook-module/consent.js +59 -0
  37. package/dist/plugin/hook-module/consent.js.map +1 -0
  38. package/dist/plugin/hook-module/events.d.ts +33 -0
  39. package/dist/plugin/hook-module/events.d.ts.map +1 -0
  40. package/dist/plugin/hook-module/events.js +149 -0
  41. package/dist/plugin/hook-module/events.js.map +1 -0
  42. package/dist/plugin/hook-module/host.d.ts +79 -0
  43. package/dist/plugin/hook-module/host.d.ts.map +1 -0
  44. package/dist/plugin/hook-module/host.js +546 -0
  45. package/dist/plugin/hook-module/host.js.map +1 -0
  46. package/dist/plugin/hook-module/index.d.ts +11 -0
  47. package/dist/plugin/hook-module/index.d.ts.map +1 -0
  48. package/dist/plugin/hook-module/index.js +6 -0
  49. package/dist/plugin/hook-module/index.js.map +1 -0
  50. package/dist/plugin/hook-module/scan.d.ts +99 -0
  51. package/dist/plugin/hook-module/scan.d.ts.map +1 -0
  52. package/dist/plugin/hook-module/scan.js +789 -0
  53. package/dist/plugin/hook-module/scan.js.map +1 -0
  54. package/dist/plugin/hook-module/worker-source.d.ts +31 -0
  55. package/dist/plugin/hook-module/worker-source.d.ts.map +1 -0
  56. package/dist/plugin/hook-module/worker-source.js +498 -0
  57. package/dist/plugin/hook-module/worker-source.js.map +1 -0
  58. package/dist/plugin/index.d.ts +5 -2
  59. package/dist/plugin/index.d.ts.map +1 -1
  60. package/dist/plugin/index.js +4 -1
  61. package/dist/plugin/index.js.map +1 -1
  62. package/dist/plugin/lifecycle.d.ts +57 -0
  63. package/dist/plugin/lifecycle.d.ts.map +1 -1
  64. package/dist/plugin/lifecycle.js +92 -11
  65. package/dist/plugin/lifecycle.js.map +1 -1
  66. package/dist/plugin/loader.d.ts +30 -0
  67. package/dist/plugin/loader.d.ts.map +1 -1
  68. package/dist/plugin/loader.js +76 -19
  69. package/dist/plugin/loader.js.map +1 -1
  70. package/dist/plugin/shell-hook-env.d.ts +7 -0
  71. package/dist/plugin/shell-hook-env.d.ts.map +1 -1
  72. package/dist/plugin/shell-hook-env.js.map +1 -1
  73. package/dist/plugin/shell-hook.d.ts +10 -1
  74. package/dist/plugin/shell-hook.d.ts.map +1 -1
  75. package/dist/plugin/shell-hook.js +81 -70
  76. package/dist/plugin/shell-hook.js.map +1 -1
  77. package/dist/public-runtime.d.ts +3 -2
  78. package/dist/public-runtime.d.ts.map +1 -1
  79. package/dist/public-runtime.js +2 -2
  80. package/dist/public-runtime.js.map +1 -1
  81. package/dist/skills/loader.d.ts +8 -2
  82. package/dist/skills/loader.d.ts.map +1 -1
  83. package/dist/skills/loader.js +22 -11
  84. package/dist/skills/loader.js.map +1 -1
  85. package/dist/skills/registry.d.ts.map +1 -1
  86. package/dist/skills/registry.js +9 -1
  87. package/dist/skills/registry.js.map +1 -1
  88. package/dist/types/plugin/index.d.ts +73 -0
  89. package/dist/types/plugin/index.d.ts.map +1 -1
  90. package/dist/types/plugin/index.js +28 -6
  91. package/dist/types/plugin/index.js.map +1 -1
  92. package/dist/types/skills/index.d.ts +6 -0
  93. package/dist/types/skills/index.d.ts.map +1 -1
  94. package/package.json +2 -1
  95. package/src/constants/plugin/index.ts +9 -0
  96. package/src/plugin/common-layout/index.ts +19 -0
  97. package/src/plugin/common-layout/mcp.ts +362 -0
  98. package/src/plugin/common-layout/paths.ts +70 -0
  99. package/src/plugin/common-layout/read.ts +1282 -0
  100. package/src/plugin/common-layout/types.ts +77 -0
  101. package/src/plugin/common-layout-names.ts +108 -0
  102. package/src/plugin/hook-module/capabilities.ts +500 -0
  103. package/src/plugin/hook-module/consent.ts +96 -0
  104. package/src/plugin/hook-module/events.ts +177 -0
  105. package/src/plugin/hook-module/host.ts +649 -0
  106. package/src/plugin/hook-module/index.ts +52 -0
  107. package/src/plugin/hook-module/scan.ts +1004 -0
  108. package/src/plugin/hook-module/worker-source.ts +500 -0
  109. package/src/plugin/index.ts +13 -1
  110. package/src/plugin/lifecycle.ts +179 -17
  111. package/src/plugin/loader.ts +97 -18
  112. package/src/plugin/shell-hook-env.ts +7 -0
  113. package/src/plugin/shell-hook.ts +91 -70
  114. package/src/public-runtime.ts +35 -0
  115. package/src/skills/loader.ts +26 -9
  116. package/src/skills/registry.ts +9 -1
  117. package/src/types/plugin/index.ts +81 -24
  118. package/src/types/skills/index.ts +7 -0
@@ -0,0 +1,1004 @@
1
+ import { lstatSync, readFileSync, realpathSync } from 'node:fs'
2
+ import * as nodeModule from 'node:module'
3
+ import { isAbsolute, join, posix, relative, resolve } from 'node:path'
4
+ import * as acorn from 'acorn'
5
+
6
+ import { COMMON_HOOKS_FILE, COMMON_MODULE_TYPES_SPECIFIER } from '../common-layout-names.js'
7
+ import type { ShellHookEvent } from '../shell-hook.js'
8
+ import { resolvePattern } from './events.js'
9
+
10
+ /** The most one scanned file, and the hooks file, may hold. */
11
+ export const MAX_MODULE_FILE_BYTES = 1024 * 1024
12
+ /** The most all the files of one module may hold together. */
13
+ export const MAX_MODULE_TOTAL_BYTES = 8 * 1024 * 1024
14
+ /** The most files one module may be made of. */
15
+ export const MAX_MODULE_FILES = 64
16
+
17
+ /** The calls on `$` Namzu answers, by noun. Every other call throws where it is made. */
18
+ export const SUPPORTED_CAPABILITY_CALLS: Readonly<Record<string, readonly string[]>> = {
19
+ fs: ['read', 'exists', 'stat', 'list'],
20
+ store: ['get', 'set', 'delete', 'keys'],
21
+ process: ['run'],
22
+ env: ['get'],
23
+ ui: ['log'],
24
+ http: ['fetch'],
25
+ }
26
+
27
+ /** The properties of `$.plugin` a module may read. */
28
+ export const PLUGIN_PROPERTIES: readonly string[] = ['root', 'name']
29
+
30
+ export interface ScanRefusal {
31
+ /** The file, relative to the plugin. */
32
+ readonly file: string
33
+ readonly line: number
34
+ readonly message: string
35
+ }
36
+
37
+ export interface ScannedHook {
38
+ readonly pattern: string
39
+ readonly file: string
40
+ readonly line: number
41
+ /** Registered with a matcher. */
42
+ readonly matcher: boolean
43
+ /** Given a `.catch`. */
44
+ readonly catches: boolean
45
+ /** The Namzu events it runs on; empty when none of what it names exists here. */
46
+ readonly runs: readonly ShellHookEvent[]
47
+ /** Why the pattern runs nowhere, when it does not. */
48
+ readonly notUsed?: string
49
+ }
50
+
51
+ export interface ScannedCall {
52
+ /** `$.fs.read`. */
53
+ readonly call: string
54
+ readonly file: string
55
+ readonly line: number
56
+ /** False when Namzu has no such call; calling it throws. */
57
+ readonly supported: boolean
58
+ /** The call sits only in hooks Namzu does not run, so it is never made. */
59
+ readonly neverRuns?: boolean
60
+ }
61
+
62
+ /** What the worker runs: every file of the module, rewritten to run as a script. */
63
+ export interface HookModuleProgram {
64
+ /** The entry, relative to the plugin. */
65
+ readonly entry: string
66
+ /** Plugin-relative path to rewritten source. */
67
+ readonly files: Readonly<Record<string, string>>
68
+ }
69
+
70
+ export interface HookModuleScan {
71
+ /** The entry, relative to the plugin. */
72
+ readonly entry: string
73
+ /** Every file the module is made of, relative to the plugin. */
74
+ readonly files: readonly string[]
75
+ readonly hooks: readonly ScannedHook[]
76
+ readonly calls: readonly ScannedCall[]
77
+ /** The variables the module reads, by literal name. */
78
+ readonly envNames: readonly string[]
79
+ readonly refusals: readonly ScanRefusal[]
80
+ /** Present when nothing was refused. */
81
+ readonly program?: HookModuleProgram
82
+ }
83
+
84
+ type AnyNode = acorn.Node & { [key: string]: any }
85
+
86
+ type TypeStripper = (code: string, options?: { mode?: 'strip' | 'transform' }) => string
87
+
88
+ /** `stripTypeScriptTypes` where this Node has it, quiet about its experimental status. */
89
+ function typeStripper(): TypeStripper | undefined {
90
+ const stripper = (nodeModule as { stripTypeScriptTypes?: TypeStripper }).stripTypeScriptTypes
91
+ if (typeof stripper !== 'function') return undefined
92
+ return (code, options) => {
93
+ const original = process.emitWarning
94
+ process.emitWarning = ((warning: unknown, ...rest: unknown[]) => {
95
+ const text = typeof warning === 'string' ? warning : String((warning as Error)?.message ?? '')
96
+ if (/type stripping|stripTypeScriptTypes/i.test(text)) return
97
+ return (original as (...args: unknown[]) => void).call(process, warning, ...rest)
98
+ }) as typeof process.emitWarning
99
+ try {
100
+ return stripper(code, options)
101
+ } finally {
102
+ process.emitWarning = original
103
+ }
104
+ }
105
+ }
106
+
107
+ /** The path inside `root`, or `undefined` when it leaves it. */
108
+ function within(root: string, path: string): boolean {
109
+ const rel = relative(root, path)
110
+ return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel))
111
+ }
112
+
113
+ export type PluginFileRead =
114
+ | { readonly text: string; readonly real: string }
115
+ | { readonly problem: string }
116
+
117
+ /**
118
+ * A plugin's file as text: a regular file inside the plugin, not a link, no
119
+ * larger than `cap`. A problem says why it was not read.
120
+ */
121
+ export function readPluginFile(
122
+ root: string,
123
+ rel: string,
124
+ cap: number = MAX_MODULE_FILE_BYTES,
125
+ ): PluginFileRead {
126
+ const path = resolve(root, rel)
127
+ let realRoot: string
128
+ try {
129
+ realRoot = realpathSync(root)
130
+ } catch {
131
+ return { problem: 'the plugin folder cannot be read' }
132
+ }
133
+ if (!within(resolve(root), path)) return { problem: 'is outside the plugin folder' }
134
+ let info: ReturnType<typeof lstatSync>
135
+ try {
136
+ info = lstatSync(path)
137
+ } catch {
138
+ return { problem: 'no such file' }
139
+ }
140
+ if (info.isSymbolicLink()) return { problem: 'is a link, and links are not followed' }
141
+ if (!info.isFile()) return { problem: 'is not a regular file' }
142
+ if (info.size > cap) return { problem: `is larger than ${cap / 1024} KiB` }
143
+ let real: string
144
+ try {
145
+ real = realpathSync(path)
146
+ } catch {
147
+ return { problem: 'no such file' }
148
+ }
149
+ if (!within(realRoot, real)) return { problem: 'leaves the plugin folder through a link' }
150
+ try {
151
+ return { text: readFileSync(real, 'utf8'), real }
152
+ } catch {
153
+ return { problem: 'cannot be read' }
154
+ }
155
+ }
156
+
157
+ export type HookModuleLocation =
158
+ | { readonly kind: 'none' }
159
+ | {
160
+ readonly kind: 'found'
161
+ /** The hooks file that names it, relative to the plugin. */
162
+ readonly hooksFile: string
163
+ /** As the hooks file spells it. */
164
+ readonly specifier: string
165
+ /** Relative to the plugin, with `/`. */
166
+ readonly entry: string
167
+ }
168
+ | { readonly kind: 'refused'; readonly hooksFile: string; readonly message: string }
169
+
170
+ /**
171
+ * Read the hooks file of the common layout for the module it names: `modules`
172
+ * holds one path, relative to the folder the hooks file is in. The file is read
173
+ * as the hook entries are: no link, valid JSON, one mebibyte at most.
174
+ */
175
+ export function locateHookModule(root: string): HookModuleLocation {
176
+ const hooksFile = COMMON_HOOKS_FILE
177
+ const read = readPluginFile(root, hooksFile)
178
+ if ('problem' in read) {
179
+ // A missing file is not a module; any other problem is the hook entries' to say.
180
+ return { kind: 'none' }
181
+ }
182
+ let parsed: unknown
183
+ try {
184
+ parsed = JSON.parse(read.text)
185
+ } catch {
186
+ return { kind: 'none' }
187
+ }
188
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed))
189
+ return { kind: 'none' }
190
+ const modules = (parsed as Record<string, unknown>).modules
191
+ if (modules === undefined) return { kind: 'none' }
192
+ if (!Array.isArray(modules)) {
193
+ return {
194
+ kind: 'refused',
195
+ hooksFile,
196
+ message: `${hooksFile}: "modules" must be a list of one path.`,
197
+ }
198
+ }
199
+ if (modules.length === 0) return { kind: 'none' }
200
+ if (modules.length > 1) {
201
+ return {
202
+ kind: 'refused',
203
+ hooksFile,
204
+ message: `${hooksFile}: \`modules\` names one hooks module per plugin; a second entry is refused.`,
205
+ }
206
+ }
207
+ const specifier = modules[0]
208
+ if (typeof specifier !== 'string' || specifier.trim() === '') {
209
+ return { kind: 'refused', hooksFile, message: `${hooksFile}: \`modules\` must name a file.` }
210
+ }
211
+ if (isAbsolute(specifier) || /^[A-Za-z]:/.test(specifier) || specifier.startsWith('\\')) {
212
+ return {
213
+ kind: 'refused',
214
+ hooksFile,
215
+ message: `${hooksFile}: "${specifier}" is an absolute path; a module is named relative to the hooks file.`,
216
+ }
217
+ }
218
+ const entry = posix.normalize(
219
+ posix.join(posix.dirname(hooksFile), specifier.replaceAll('\\', '/')),
220
+ )
221
+ if (entry === '..' || entry.startsWith('../') || posix.isAbsolute(entry)) {
222
+ return {
223
+ kind: 'refused',
224
+ hooksFile,
225
+ message: `${hooksFile}: "${specifier}" leaves the plugin folder.`,
226
+ }
227
+ }
228
+ return { kind: 'found', hooksFile, specifier, entry }
229
+ }
230
+
231
+ const SCRIPT_EXTENSIONS = ['.js', '.mjs', '.cjs']
232
+ const TYPED_EXTENSIONS = ['.ts', '.mts', '.cts']
233
+
234
+ function extensionOf(path: string): string {
235
+ const index = path.lastIndexOf('.')
236
+ return index < 0 ? '' : path.slice(index).toLowerCase()
237
+ }
238
+
239
+ /** Names a script uses to climb from an object to the constructors behind it. */
240
+ const REACHING_NAMES: ReadonlySet<string> = new Set([
241
+ 'constructor',
242
+ '__proto__',
243
+ '__defineGetter__',
244
+ '__defineSetter__',
245
+ '__lookupGetter__',
246
+ '__lookupSetter__',
247
+ 'getPrototypeOf',
248
+ 'setPrototypeOf',
249
+ ])
250
+
251
+ function walk(
252
+ node: AnyNode,
253
+ enter: (node: AnyNode, parents: AnyNode[]) => void,
254
+ parents: AnyNode[] = [],
255
+ ): void {
256
+ enter(node, parents)
257
+ parents.push(node)
258
+ for (const key of Object.keys(node)) {
259
+ if (key === 'type' || key === 'start' || key === 'end' || key === 'loc') continue
260
+ const value = node[key]
261
+ if (Array.isArray(value)) {
262
+ for (const child of value) {
263
+ if (child !== null && typeof child === 'object' && typeof child.type === 'string') {
264
+ walk(child as AnyNode, enter, parents)
265
+ }
266
+ }
267
+ } else if (value !== null && typeof value === 'object' && typeof value.type === 'string') {
268
+ walk(value as AnyNode, enter, parents)
269
+ }
270
+ }
271
+ parents.pop()
272
+ }
273
+
274
+ function isFunctionNode(node: AnyNode | undefined): boolean {
275
+ return (
276
+ node !== undefined &&
277
+ (node.type === 'FunctionDeclaration' ||
278
+ node.type === 'FunctionExpression' ||
279
+ node.type === 'ArrowFunctionExpression')
280
+ )
281
+ }
282
+
283
+ function stringValue(node: AnyNode | undefined): string | undefined {
284
+ if (node === undefined) return undefined
285
+ if (node.type === 'Literal' && typeof node.value === 'string') return node.value
286
+ if (node.type === 'TemplateLiteral' && node.expressions.length === 0) {
287
+ return node.quasis[0]?.value?.cooked ?? undefined
288
+ }
289
+ return undefined
290
+ }
291
+
292
+ function patternNames(node: AnyNode | null | undefined, into: string[]): void {
293
+ if (node === null || node === undefined) return
294
+ switch (node.type) {
295
+ case 'Identifier':
296
+ into.push(node.name)
297
+ return
298
+ case 'ObjectPattern':
299
+ for (const property of node.properties) {
300
+ patternNames(property.type === 'RestElement' ? property.argument : property.value, into)
301
+ }
302
+ return
303
+ case 'ArrayPattern':
304
+ for (const element of node.elements) patternNames(element, into)
305
+ return
306
+ case 'AssignmentPattern':
307
+ patternNames(node.left, into)
308
+ return
309
+ case 'RestElement':
310
+ patternNames(node.argument, into)
311
+ return
312
+ }
313
+ }
314
+
315
+ /** Blank a stretch of source, keeping its line breaks so line numbers stay true. */
316
+ function blank(text: string): string {
317
+ return text.replace(/[^\n]/g, ' ')
318
+ }
319
+
320
+ interface FileAnalysis {
321
+ readonly rel: string
322
+ readonly ast: AnyNode
323
+ /** Source after the types are stripped. */
324
+ readonly code: string
325
+ /** Relative imports, as written, in order. */
326
+ readonly imports: { readonly specifier: string; readonly line: number }[]
327
+ }
328
+
329
+ interface ScanState {
330
+ readonly root: string
331
+ readonly refusals: ScanRefusal[]
332
+ readonly hooks: ScannedHook[]
333
+ readonly calls: ScannedCall[]
334
+ /** Where each call starts, in the order of `calls`. */
335
+ readonly callStarts: { readonly file: string; readonly start: number }[]
336
+ /** The bodies of the hooks declared in place, and whether Namzu runs the event they hook. */
337
+ readonly hookBodies: {
338
+ readonly file: string
339
+ readonly start: number
340
+ readonly end: number
341
+ readonly runs: boolean
342
+ }[]
343
+ readonly envNames: Set<string>
344
+ readonly analyses: Map<string, FileAnalysis>
345
+ readonly rewritten: Map<string, string>
346
+ total: number
347
+ }
348
+
349
+ function refuse(state: ScanState, file: string, node: AnyNode | number, message: string): void {
350
+ const line = typeof node === 'number' ? node : (node.loc?.start.line ?? 1)
351
+ // The refusal carries its file and line already; a message that opens with the file says it twice.
352
+ const bare = message.startsWith(`${file}: `) ? message.slice(file.length + 2) : message
353
+ state.refusals.push({ file, line, message: bare })
354
+ }
355
+
356
+ function resolveImport(state: ScanState, fromRel: string, specifier: string): string | undefined {
357
+ const base = posix.normalize(posix.join(posix.dirname(fromRel), specifier))
358
+ if (base.startsWith('../') || base === '..' || posix.isAbsolute(base)) return undefined
359
+ const candidates = [base]
360
+ if (/\.m?js$/.test(base)) candidates.push(base.replace(/\.(m?)js$/, '.$1ts'))
361
+ for (const extension of ['.ts', '.js', '.mjs']) candidates.push(`${base}${extension}`)
362
+ for (const candidate of candidates) {
363
+ let info: ReturnType<typeof lstatSync> | undefined
364
+ try {
365
+ info = lstatSync(join(state.root, candidate))
366
+ } catch {
367
+ info = undefined
368
+ }
369
+ if (info !== undefined && (info.isFile() || info.isSymbolicLink())) return candidate
370
+ }
371
+ return undefined
372
+ }
373
+
374
+ /** Which top-level bindings of a file are functions, by name. */
375
+ function topLevelFunctions(ast: AnyNode): Map<string, AnyNode> {
376
+ const found = new Map<string, AnyNode>()
377
+ for (const statement of ast.body as AnyNode[]) {
378
+ const declaration =
379
+ statement.type === 'ExportNamedDeclaration'
380
+ ? (statement.declaration as AnyNode | null)
381
+ : statement
382
+ if (declaration === null || declaration === undefined) continue
383
+ if (declaration.type === 'FunctionDeclaration' && declaration.id !== null) {
384
+ found.set(declaration.id.name, declaration)
385
+ } else if (declaration.type === 'VariableDeclaration') {
386
+ for (const declarator of declaration.declarations as AnyNode[]) {
387
+ if (declarator.id.type === 'Identifier' && isFunctionNode(declarator.init)) {
388
+ found.set(declarator.id.name, declarator.init)
389
+ }
390
+ }
391
+ }
392
+ }
393
+ return found
394
+ }
395
+
396
+ /** The function the entry exports as `register`, or as its default. */
397
+ function findRegister(ast: AnyNode, functions: Map<string, AnyNode>): AnyNode | undefined {
398
+ for (const statement of ast.body as AnyNode[]) {
399
+ if (statement.type === 'ExportNamedDeclaration') {
400
+ const declaration = statement.declaration as AnyNode | null
401
+ if (declaration?.type === 'FunctionDeclaration' && declaration.id?.name === 'register') {
402
+ return declaration
403
+ }
404
+ if (declaration?.type === 'VariableDeclaration') {
405
+ for (const declarator of declaration.declarations as AnyNode[]) {
406
+ if (declarator.id.type === 'Identifier' && declarator.id.name === 'register') {
407
+ return isFunctionNode(declarator.init) ? declarator.init : undefined
408
+ }
409
+ }
410
+ }
411
+ for (const specifier of (statement.specifiers ?? []) as AnyNode[]) {
412
+ if (specifier.exported.name === 'register' && statement.source === null) {
413
+ return functions.get(specifier.local.name)
414
+ }
415
+ }
416
+ } else if (statement.type === 'ExportDefaultDeclaration') {
417
+ const declaration = statement.declaration as AnyNode
418
+ if (isFunctionNode(declaration)) return declaration
419
+ if (declaration.type === 'Identifier') return functions.get(declaration.name)
420
+ }
421
+ }
422
+ return undefined
423
+ }
424
+
425
+ function capabilityUse(state: ScanState, rel: string, node: AnyNode, parents: AnyNode[]): void {
426
+ const parent = parents[parents.length - 1]
427
+ const grand = parents[parents.length - 2]
428
+ const great = parents[parents.length - 3]
429
+ const spelled = '$ is always spelled $.noun.event(...) at the call site'
430
+ if (
431
+ parent?.type !== 'MemberExpression' ||
432
+ parent.object !== node ||
433
+ parent.computed === true ||
434
+ parent.property.type !== 'Identifier'
435
+ ) {
436
+ refuse(state, rel, node, spelled)
437
+ return
438
+ }
439
+ const noun = parent.property.name as string
440
+ if (
441
+ grand?.type !== 'MemberExpression' ||
442
+ grand.object !== parent ||
443
+ grand.computed === true ||
444
+ grand.property.type !== 'Identifier'
445
+ ) {
446
+ refuse(state, rel, node, spelled)
447
+ return
448
+ }
449
+ const member = grand.property.name as string
450
+ const called = great?.type === 'CallExpression' && great.callee === grand
451
+ if (noun === 'plugin' && !called && PLUGIN_PROPERTIES.includes(member)) return
452
+ if (!called) {
453
+ refuse(state, rel, node, spelled)
454
+ return
455
+ }
456
+ const supported = SUPPORTED_CAPABILITY_CALLS[noun]?.includes(member) === true
457
+ state.calls.push({
458
+ call: `$.${noun}.${member}`,
459
+ file: rel,
460
+ line: node.loc?.start.line ?? 1,
461
+ supported,
462
+ })
463
+ state.callStarts.push({ file: rel, start: node.start })
464
+ if (noun === 'env' && member === 'get' && supported) {
465
+ const name = stringValue(great.arguments[0] as AnyNode | undefined)
466
+ if (name === undefined) {
467
+ refuse(
468
+ state,
469
+ rel,
470
+ node,
471
+ '$.env.get takes a string literal: the variables a module reads are listed before it loads',
472
+ )
473
+ } else state.envNames.add(name)
474
+ }
475
+ }
476
+
477
+ /**
478
+ * Read one file: parse it, refuse what is refused, and note what it hooks and
479
+ * calls. The entry file also has its `register` function read for `on` calls.
480
+ */
481
+ function analyseFile(state: ScanState, rel: string, isEntry: boolean, queue: string[]): void {
482
+ const extension = extensionOf(rel)
483
+ if (extension === '.tsx' || extension === '.jsx') {
484
+ refuse(state, rel, 1, `${rel}: JSX is not supported in a hooks module.`)
485
+ return
486
+ }
487
+ if (!SCRIPT_EXTENSIONS.includes(extension) && !TYPED_EXTENSIONS.includes(extension)) {
488
+ refuse(
489
+ state,
490
+ rel,
491
+ 1,
492
+ `${rel}: only .js, .mjs, .cjs, .ts, .mts and .cts files are loaded as a hooks module.`,
493
+ )
494
+ return
495
+ }
496
+ const read = readPluginFile(state.root, rel)
497
+ if ('problem' in read) {
498
+ refuse(state, rel, 1, `${rel}: ${read.problem}.`)
499
+ return
500
+ }
501
+ state.total += read.text.length
502
+ if (state.total > MAX_MODULE_TOTAL_BYTES) {
503
+ refuse(
504
+ state,
505
+ rel,
506
+ 1,
507
+ `${rel}: the module's files together are past ${MAX_MODULE_TOTAL_BYTES / 1024 / 1024} MiB.`,
508
+ )
509
+ return
510
+ }
511
+ let code = read.text
512
+ if (TYPED_EXTENSIONS.includes(extension)) {
513
+ const strip = typeStripper()
514
+ if (strip === undefined) {
515
+ refuse(
516
+ state,
517
+ rel,
518
+ 1,
519
+ `${rel}: a TypeScript module needs Node 22.13 or later; write it as .js or run a newer Node.`,
520
+ )
521
+ return
522
+ }
523
+ try {
524
+ code = strip(code, { mode: 'strip' })
525
+ } catch (error) {
526
+ const message = error instanceof Error ? error.message.split('\n')[0] : String(error)
527
+ refuse(state, rel, 1, `${rel} does not parse as TypeScript: ${message}`)
528
+ return
529
+ }
530
+ }
531
+ let ast: AnyNode
532
+ try {
533
+ ast = acorn.parse(code, {
534
+ ecmaVersion: 'latest',
535
+ sourceType: 'module',
536
+ locations: true,
537
+ allowHashBang: true,
538
+ }) as unknown as AnyNode
539
+ } catch (error) {
540
+ const problem = error as { message?: string; loc?: { line: number; column: number } }
541
+ const text = (problem.message ?? String(error)).replace(/\s*\(\d+:\d+\)$/, '')
542
+ refuse(
543
+ state,
544
+ rel,
545
+ problem.loc?.line ?? 1,
546
+ `${rel} does not parse: ${text} (line ${problem.loc?.line ?? 1}, column ${(problem.loc?.column ?? 0) + 1})`,
547
+ )
548
+ return
549
+ }
550
+
551
+ const imports: FileAnalysis['imports'][number][] = []
552
+ const importedNames = new Map<string, 'function-ok' | 'namespace'>()
553
+ for (const statement of ast.body as AnyNode[]) {
554
+ const isImport = statement.type === 'ImportDeclaration'
555
+ const isReexport =
556
+ (statement.type === 'ExportNamedDeclaration' || statement.type === 'ExportAllDeclaration') &&
557
+ statement.source !== null &&
558
+ statement.source !== undefined
559
+ if (!isImport && !isReexport) continue
560
+ const specifier = String(statement.source.value)
561
+ if (specifier.startsWith('./') || specifier.startsWith('../')) {
562
+ imports.push({ specifier, line: statement.loc?.start.line ?? 1 })
563
+ if (isImport) {
564
+ for (const item of statement.specifiers as AnyNode[]) {
565
+ importedNames.set(
566
+ item.local.name,
567
+ item.type === 'ImportNamespaceSpecifier' ? 'namespace' : 'function-ok',
568
+ )
569
+ }
570
+ }
571
+ } else if (specifier === COMMON_MODULE_TYPES_SPECIFIER) {
572
+ refuse(
573
+ state,
574
+ rel,
575
+ statement,
576
+ `${rel}: cannot import "${specifier}" as a value (from ${rel}): it holds types only, and only import type is read.`,
577
+ )
578
+ } else {
579
+ refuse(
580
+ state,
581
+ rel,
582
+ statement,
583
+ `${rel}: cannot import "${specifier}" (from ${rel}): a hooks module imports its own files by relative path and "${COMMON_MODULE_TYPES_SPECIFIER}", nothing else`,
584
+ )
585
+ }
586
+ }
587
+
588
+ const functions = topLevelFunctions(ast)
589
+ const register = isEntry ? findRegister(ast, functions) : undefined
590
+ if (isEntry && register === undefined) {
591
+ refuse(
592
+ state,
593
+ rel,
594
+ 1,
595
+ `${rel}: the module does not export a function named register (export function register(on) { ... }).`,
596
+ )
597
+ }
598
+ let onName: string | undefined
599
+ if (register !== undefined) {
600
+ const first = (register.params as AnyNode[])[0]
601
+ if (first !== undefined) {
602
+ if (first.type === 'Identifier') onName = first.name
603
+ else refuse(state, rel, register, `${rel}: register takes on as a plain first parameter.`)
604
+ }
605
+ }
606
+ const inRegister = (node: AnyNode): boolean =>
607
+ register !== undefined && node.start >= register.start && node.end <= register.end
608
+
609
+ const patterns = new Map<string, ScannedHook>()
610
+ walk(ast, (node, parents) => {
611
+ const parent = parents[parents.length - 1]
612
+ if (node.type === 'ImportExpression') {
613
+ refuse(
614
+ state,
615
+ rel,
616
+ node,
617
+ `${rel}: a dynamic import(); a hooks module imports its own files with an import declaration, as in import { name } from "./file.js"`,
618
+ )
619
+ return
620
+ }
621
+ if (node.type === 'MetaProperty' && node.meta.name === 'import') {
622
+ refuse(state, rel, node, `${rel}: import.meta is not available in a hooks module.`)
623
+ return
624
+ }
625
+ if (
626
+ (node.type === 'AwaitExpression' ||
627
+ (node.type === 'ForOfStatement' && node.await === true)) &&
628
+ !parents.some(isFunctionNode)
629
+ ) {
630
+ refuse(
631
+ state,
632
+ rel,
633
+ node,
634
+ `${rel}: a top-level await in a file the entry imports; the environment links the entry alone as an async module`,
635
+ )
636
+ return
637
+ }
638
+ if (node.type === 'MemberExpression') {
639
+ const property = node.property as AnyNode
640
+ const written =
641
+ !node.computed && property.type === 'Identifier'
642
+ ? (property.name as string)
643
+ : node.computed && property.type === 'Literal' && typeof property.value === 'string'
644
+ ? (property.value as string)
645
+ : undefined
646
+ if (written !== undefined && REACHING_NAMES.has(written)) {
647
+ refuse(
648
+ state,
649
+ rel,
650
+ node,
651
+ `${rel}: .${written} is how a script reaches the functions behind the objects it is given; a hooks module does not use it`,
652
+ )
653
+ }
654
+ }
655
+ if (node.type !== 'Identifier') {
656
+ if (
657
+ node.type === 'CallExpression' &&
658
+ onName !== undefined &&
659
+ node.callee.type === 'Identifier' &&
660
+ node.callee.name === onName &&
661
+ inRegister(node)
662
+ ) {
663
+ registration(state, rel, node, parents, functions, importedNames, patterns)
664
+ }
665
+ return
666
+ }
667
+ // An identifier that is not a use: a property key or name, a parameter.
668
+ if (parent?.type === 'MemberExpression' && parent.property === node && !parent.computed) return
669
+ if (
670
+ parent?.type === 'Property' &&
671
+ parent.key === node &&
672
+ !parent.computed &&
673
+ !parent.shorthand
674
+ ) {
675
+ return
676
+ }
677
+ if (node.name === '$') {
678
+ const declared = parents.some((ancestor) => {
679
+ if (!isFunctionNode(ancestor)) return false
680
+ return (ancestor.params as AnyNode[]).some((param) => {
681
+ const names: string[] = []
682
+ patternNames(param, names)
683
+ return names.includes('$') && param.start <= node.start && node.end <= param.end
684
+ })
685
+ })
686
+ if (declared) return
687
+ if (parent?.type === 'VariableDeclarator' && parent.id === node) {
688
+ refuse(
689
+ state,
690
+ rel,
691
+ node,
692
+ `${rel}: $ is declared again in this file; it is the capability object and is spelled $.noun.event(...)`,
693
+ )
694
+ return
695
+ }
696
+ capabilityUse(state, rel, node, parents)
697
+ return
698
+ }
699
+ if (onName !== undefined && node.name === onName && inRegister(node)) {
700
+ const isParam = parent === register && (register?.params as AnyNode[]).includes(node)
701
+ const isCallee = parent?.type === 'CallExpression' && parent.callee === node
702
+ if (!isParam && !isCallee) {
703
+ refuse(
704
+ state,
705
+ rel,
706
+ node,
707
+ `${rel}: on is always on("<event>", hook): it is not passed, bound or assigned`,
708
+ )
709
+ }
710
+ }
711
+ })
712
+
713
+ state.analyses.set(rel, { rel, ast, code, imports })
714
+ for (const item of imports) {
715
+ const target = resolveImport(state, rel, item.specifier)
716
+ if (target === undefined) {
717
+ refuse(
718
+ state,
719
+ rel,
720
+ item.line,
721
+ `${rel}: cannot import "${item.specifier}" (from ${rel}): no such file in the plugin`,
722
+ )
723
+ } else if (!state.analyses.has(target) && !queue.includes(target)) {
724
+ if (state.analyses.size + queue.length >= MAX_MODULE_FILES) {
725
+ refuse(
726
+ state,
727
+ rel,
728
+ item.line,
729
+ `${rel}: the module is made of more than ${MAX_MODULE_FILES} files.`,
730
+ )
731
+ } else queue.push(target)
732
+ }
733
+ }
734
+ }
735
+
736
+ function registration(
737
+ state: ScanState,
738
+ rel: string,
739
+ call: AnyNode,
740
+ parents: AnyNode[],
741
+ functions: Map<string, AnyNode>,
742
+ importedNames: Map<string, 'function-ok' | 'namespace'>,
743
+ patterns: Map<string, ScannedHook>,
744
+ ): void {
745
+ const args = call.arguments as AnyNode[]
746
+ if (args.length < 2 || args.length > 3) {
747
+ refuse(state, rel, call, `${rel}: on() takes (pattern, hook) or (pattern, matcher, hook)`)
748
+ return
749
+ }
750
+ const pattern = stringValue(args[0])
751
+ if (pattern === undefined) {
752
+ refuse(state, rel, call, `${rel}: the event name passed to on() is not a string literal`)
753
+ return
754
+ }
755
+ const resolved = resolvePattern(pattern)
756
+ if (!resolved.ok) {
757
+ refuse(state, rel, call, `${rel}: ${resolved.message}`)
758
+ return
759
+ }
760
+ const hook = args[args.length - 1] as AnyNode
761
+ let isFunction = isFunctionNode(hook)
762
+ if (!isFunction && hook.type === 'Identifier') {
763
+ if (importedNames.get(hook.name) === 'namespace') {
764
+ refuse(state, rel, hook, `${rel}: "${hook.name}" is a namespace import, not a function`)
765
+ return
766
+ }
767
+ isFunction = functions.has(hook.name) || importedNames.has(hook.name)
768
+ }
769
+ if (!isFunction) {
770
+ refuse(
771
+ state,
772
+ rel,
773
+ hook,
774
+ `${rel}: the hook passed to on("${pattern}") is not a function declared at the top of this file (a function declaration, or a const bound to a function), nor imported from one of the module's own files`,
775
+ )
776
+ return
777
+ }
778
+ const body = isFunctionNode(hook)
779
+ ? hook
780
+ : hook.type === 'Identifier'
781
+ ? functions.get(hook.name)
782
+ : undefined
783
+ if (body !== undefined) {
784
+ state.hookBodies.push({
785
+ file: rel,
786
+ start: body.start,
787
+ end: body.end,
788
+ runs: resolved.runs.length > 0,
789
+ })
790
+ }
791
+ const matcher = args.length === 3
792
+ if (!matcher) {
793
+ const earlier = patterns.get(pattern)
794
+ if (earlier !== undefined) {
795
+ refuse(
796
+ state,
797
+ rel,
798
+ call,
799
+ `${rel}: on("${pattern}") is registered twice without a matcher; the first is at ${earlier.file}:${earlier.line}`,
800
+ )
801
+ return
802
+ }
803
+ }
804
+ const parent = parents[parents.length - 1]
805
+ const catches =
806
+ parent?.type === 'MemberExpression' &&
807
+ parent.object === call &&
808
+ parent.property.type === 'Identifier' &&
809
+ parent.property.name === 'catch'
810
+ const scanned: ScannedHook = {
811
+ pattern,
812
+ file: rel,
813
+ line: call.loc?.start.line ?? 1,
814
+ matcher,
815
+ catches,
816
+ runs: resolved.runs,
817
+ ...(resolved.notUsed !== undefined ? { notUsed: resolved.notUsed } : {}),
818
+ }
819
+ if (!matcher) patterns.set(pattern, scanned)
820
+ state.hooks.push(scanned)
821
+ }
822
+
823
+ interface Edit {
824
+ readonly start: number
825
+ readonly end: number
826
+ readonly text: string
827
+ }
828
+
829
+ /**
830
+ * Rewrite one file to run as a script: imports become reads of the importing
831
+ * file's neighbours, exports become assignments, and nothing else changes, so a
832
+ * line number in an error is the line in the author's file.
833
+ */
834
+ function rewrite(code: string, ast: AnyNode, resolved: ReadonlyMap<string, string>): string {
835
+ const edits: Edit[] = []
836
+ const prelude: string[] = []
837
+ const tail: string[] = []
838
+ let counter = 0
839
+ const target = (specifier: string): string => JSON.stringify(resolved.get(specifier) ?? specifier)
840
+ for (const statement of ast.body as AnyNode[]) {
841
+ const span = (): Edit => ({
842
+ start: statement.start,
843
+ end: statement.end,
844
+ text: blank(code.slice(statement.start, statement.end)),
845
+ })
846
+ switch (statement.type) {
847
+ case 'ImportDeclaration': {
848
+ const specifier = String(statement.source.value)
849
+ const variable = `__m${counter++}`
850
+ prelude.push(`const ${variable} = __import(${target(specifier)});`)
851
+ for (const item of statement.specifiers as AnyNode[]) {
852
+ if (item.type === 'ImportDefaultSpecifier') {
853
+ prelude.push(`const ${item.local.name} = ${variable}.default;`)
854
+ } else if (item.type === 'ImportNamespaceSpecifier') {
855
+ prelude.push(`const ${item.local.name} = ${variable};`)
856
+ } else {
857
+ prelude.push(
858
+ `const ${item.local.name} = ${variable}[${JSON.stringify(item.imported.name ?? item.imported.value)}];`,
859
+ )
860
+ }
861
+ }
862
+ edits.push(span())
863
+ break
864
+ }
865
+ case 'ExportNamedDeclaration': {
866
+ if (statement.source !== null && statement.source !== undefined) {
867
+ const variable = `__m${counter++}`
868
+ prelude.push(`const ${variable} = __import(${target(String(statement.source.value))});`)
869
+ for (const item of statement.specifiers as AnyNode[]) {
870
+ const exported = item.exported.name ?? item.exported.value
871
+ const local = item.local.name ?? item.local.value
872
+ tail.push(
873
+ `__exports[${JSON.stringify(exported)}] = ${variable}[${JSON.stringify(local)}];`,
874
+ )
875
+ }
876
+ edits.push(span())
877
+ } else if (statement.declaration !== null && statement.declaration !== undefined) {
878
+ const declaration = statement.declaration as AnyNode
879
+ edits.push({
880
+ start: statement.start,
881
+ end: declaration.start,
882
+ text: blank(code.slice(statement.start, declaration.start)),
883
+ })
884
+ const names: string[] = []
885
+ if (declaration.type === 'VariableDeclaration') {
886
+ for (const declarator of declaration.declarations as AnyNode[]) {
887
+ patternNames(declarator.id, names)
888
+ }
889
+ } else if (declaration.id) names.push(declaration.id.name)
890
+ for (const name of names) tail.push(`__exports[${JSON.stringify(name)}] = ${name};`)
891
+ } else {
892
+ for (const item of statement.specifiers as AnyNode[]) {
893
+ tail.push(
894
+ `__exports[${JSON.stringify(item.exported.name ?? item.exported.value)}] = ${item.local.name};`,
895
+ )
896
+ }
897
+ edits.push(span())
898
+ }
899
+ break
900
+ }
901
+ case 'ExportAllDeclaration': {
902
+ const variable = `__m${counter++}`
903
+ prelude.push(`const ${variable} = __import(${target(String(statement.source.value))});`)
904
+ if (statement.exported) {
905
+ tail.push(
906
+ `__exports[${JSON.stringify(statement.exported.name ?? statement.exported.value)}] = ${variable};`,
907
+ )
908
+ } else {
909
+ tail.push(
910
+ `for (const __k of Object.keys(${variable})) { if (__k !== "default") __exports[__k] = ${variable}[__k]; }`,
911
+ )
912
+ }
913
+ edits.push(span())
914
+ break
915
+ }
916
+ case 'ExportDefaultDeclaration': {
917
+ const declaration = statement.declaration as AnyNode
918
+ const named =
919
+ (declaration.type === 'FunctionDeclaration' || declaration.type === 'ClassDeclaration') &&
920
+ declaration.id !== null &&
921
+ declaration.id !== undefined
922
+ if (named) {
923
+ edits.push({
924
+ start: statement.start,
925
+ end: declaration.start,
926
+ text: blank(code.slice(statement.start, declaration.start)),
927
+ })
928
+ tail.push(`__exports.default = ${declaration.id.name};`)
929
+ } else {
930
+ edits.push({
931
+ start: statement.start,
932
+ end: declaration.start,
933
+ text: '__exports.default = ',
934
+ })
935
+ edits.push({ start: statement.end, end: statement.end, text: ';' })
936
+ }
937
+ break
938
+ }
939
+ }
940
+ }
941
+ let out = code
942
+ for (const edit of [...edits].sort((a, b) => b.start - a.start || b.end - a.end)) {
943
+ out = out.slice(0, edit.start) + edit.text + out.slice(edit.end)
944
+ }
945
+ return `${prelude.join(' ')}${out}\n${tail.join('\n')}`
946
+ }
947
+
948
+ /**
949
+ * Read a plugin's hooks module before anything runs it: the files it is made
950
+ * of, what it hooks, what it calls on `$`, and whatever the module is refused
951
+ * for. Nothing here runs the module.
952
+ */
953
+ export function scanHookModule(root: string, entry: string): HookModuleScan {
954
+ const state: ScanState = {
955
+ root: resolve(root),
956
+ refusals: [],
957
+ hooks: [],
958
+ calls: [],
959
+ callStarts: [],
960
+ hookBodies: [],
961
+ envNames: new Set(),
962
+ analyses: new Map(),
963
+ rewritten: new Map(),
964
+ total: 0,
965
+ }
966
+ const queue: string[] = [entry]
967
+ const entryRel = entry
968
+ while (queue.length > 0) {
969
+ const next = queue.shift() as string
970
+ if (state.analyses.has(next)) continue
971
+ analyseFile(state, next, next === entryRel, queue)
972
+ }
973
+ let program: HookModuleProgram | undefined
974
+ if (state.refusals.length === 0) {
975
+ const files: Record<string, string> = {}
976
+ for (const [rel, analysis] of state.analyses) {
977
+ const resolved = new Map<string, string>()
978
+ for (const item of analysis.imports) {
979
+ const target = resolveImport(state, rel, item.specifier)
980
+ if (target !== undefined) resolved.set(item.specifier, target)
981
+ }
982
+ files[rel] = rewrite(analysis.code, analysis.ast, resolved)
983
+ }
984
+ program = { entry: entryRel, files }
985
+ }
986
+ const calls = state.calls.map((call, index) => {
987
+ const at = state.callStarts[index]
988
+ if (at === undefined) return call
989
+ const inside = state.hookBodies.filter(
990
+ (body) => body.file === at.file && body.start <= at.start && at.start < body.end,
991
+ )
992
+ const neverRuns = inside.length > 0 && inside.every((body) => !body.runs)
993
+ return neverRuns ? { ...call, neverRuns } : call
994
+ })
995
+ return {
996
+ entry: entryRel,
997
+ files: [...state.analyses.keys()],
998
+ hooks: state.hooks,
999
+ calls,
1000
+ envNames: [...state.envNames].sort(),
1001
+ refusals: state.refusals,
1002
+ ...(program !== undefined ? { program } : {}),
1003
+ }
1004
+ }