@chainlink/cre-sdk 1.1.2 → 1.1.3-alpha.2

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.
@@ -0,0 +1,573 @@
1
+ /**
2
+ * Workflow Runtime Compatibility Validator
3
+ *
4
+ * CRE (Compute Runtime Environment) workflows are compiled from TypeScript to
5
+ * WebAssembly and executed inside a Javy/QuickJS sandbox — NOT a full Node.js
6
+ * runtime. This means many APIs that developers take for granted (filesystem,
7
+ * network sockets, crypto, child processes, etc.) are simply not available at
8
+ * runtime and will silently fail or crash.
9
+ *
10
+ * This module performs **static analysis** on workflow source code to catch
11
+ * these issues at build time, before the workflow is compiled to WASM. It
12
+ * operates in two passes:
13
+ *
14
+ * 1. **Module import analysis** — walks the AST of every reachable source file
15
+ * (starting from the workflow entry point) and flags imports from restricted
16
+ * Node.js built-in modules (e.g. `node:fs`, `node:crypto`, `node:http`).
17
+ * This catches `import`, `export ... from`, `require()`, and dynamic
18
+ * `import()` syntax.
19
+ *
20
+ * 2. **Global API analysis** — uses the TypeScript type-checker to detect
21
+ * references to browser/Node globals that don't exist in QuickJS (e.g.
22
+ * `fetch`, `setTimeout`, `window`, `document`). Only flags identifiers
23
+ * that resolve to non-local declarations, so user-defined variables with
24
+ * the same name (e.g. `const fetch = cre.capabilities.HTTPClient`) are
25
+ * not flagged.
26
+ *
27
+ * The validator follows relative imports transitively so that violations in
28
+ * helper files reachable from the entry point are also caught.
29
+ *
30
+ * ## How it's used
31
+ *
32
+ * This validator runs automatically as part of the `cre-compile` build pipeline:
33
+ *
34
+ * ```
35
+ * cre-compile <path/to/workflow.ts> [path/to/output.wasm]
36
+ * ```
37
+ *
38
+ * The pipeline is: `cre-compile` (CLI) -> `compile-workflow` -> `compile-to-js`
39
+ * -> **`assertWorkflowRuntimeCompatibility()`** -> bundle -> compile to WASM.
40
+ *
41
+ * The validation happens before any bundling or WASM compilation, so developers
42
+ * get fast, actionable error messages pointing to exact file:line:column
43
+ * locations instead of cryptic WASM runtime failures.
44
+ *
45
+ * ## Layers of protection
46
+ *
47
+ * This validator is one of two complementary mechanisms that prevent usage of
48
+ * unavailable APIs:
49
+ *
50
+ * 1. **Compile-time types** (`restricted-apis.d.ts` and `restricted-node-modules.d.ts`)
51
+ * — mark restricted APIs as `never` so the TypeScript compiler flags them
52
+ * with red squiggles in the IDE. This gives instant feedback while coding.
53
+ *
54
+ * 2. **Build-time validation** (this module) — performs AST-level static
55
+ * analysis during `cre-compile`. This catches cases that type-level
56
+ * restrictions can't cover, such as `require()` calls, dynamic `import()`,
57
+ * and usage inside plain `.js` files that don't go through `tsc`.
58
+ *
59
+ * @example
60
+ * ```ts
61
+ * import { assertWorkflowRuntimeCompatibility } from './validate-workflow-runtime-compat'
62
+ *
63
+ * // Throws WorkflowRuntimeCompatibilityError if violations are found
64
+ * assertWorkflowRuntimeCompatibility('./src/workflow.ts')
65
+ * ```
66
+ *
67
+ * @see https://docs.chain.link/cre/concepts/typescript-wasm-runtime
68
+ */
69
+
70
+ import { existsSync, readFileSync, statSync } from 'node:fs'
71
+ import path from 'node:path'
72
+ import * as ts from 'typescript'
73
+
74
+ /**
75
+ * A single detected violation: a location in the source code where a
76
+ * restricted API is referenced.
77
+ */
78
+ type Violation = {
79
+ /** Absolute path to the file containing the violation. */
80
+ filePath: string
81
+ /** 1-based line number. */
82
+ line: number
83
+ /** 1-based column number. */
84
+ column: number
85
+ /** Human-readable description of the violation. */
86
+ message: string
87
+ }
88
+
89
+ /**
90
+ * Node.js built-in module specifiers that are not available in the QuickJS
91
+ * runtime. Both bare (`fs`) and prefixed (`node:fs`) forms are included
92
+ * because TypeScript/bundlers accept either.
93
+ */
94
+ const restrictedModuleSpecifiers = new Set([
95
+ 'crypto',
96
+ 'node:crypto',
97
+ 'fs',
98
+ 'node:fs',
99
+ 'fs/promises',
100
+ 'node:fs/promises',
101
+ 'net',
102
+ 'node:net',
103
+ 'http',
104
+ 'node:http',
105
+ 'https',
106
+ 'node:https',
107
+ 'child_process',
108
+ 'node:child_process',
109
+ 'os',
110
+ 'node:os',
111
+ 'stream',
112
+ 'node:stream',
113
+ 'worker_threads',
114
+ 'node:worker_threads',
115
+ 'dns',
116
+ 'node:dns',
117
+ 'zlib',
118
+ 'node:zlib',
119
+ ])
120
+
121
+ /**
122
+ * Global identifiers (browser and Node.js) that do not exist in the QuickJS
123
+ * runtime. For network requests, workflows should use `cre.capabilities.HTTPClient`;
124
+ * for scheduling, `cre.capabilities.CronCapability`.
125
+ */
126
+ const restrictedGlobalApis = new Set([
127
+ 'fetch',
128
+ 'window',
129
+ 'document',
130
+ 'XMLHttpRequest',
131
+ 'localStorage',
132
+ 'sessionStorage',
133
+ 'setTimeout',
134
+ 'setInterval',
135
+ ])
136
+
137
+ /** File extensions treated as scannable source code. */
138
+ const sourceExtensions = ['.ts', '.tsx', '.mts', '.cts', '.js', '.jsx', '.mjs', '.cjs']
139
+
140
+ /**
141
+ * Error thrown when one or more runtime-incompatible API usages are detected.
142
+ * The message includes a docs link and a formatted list of every violation
143
+ * with file path, line, column, and description.
144
+ */
145
+ class WorkflowRuntimeCompatibilityError extends Error {
146
+ constructor(violations: Violation[]) {
147
+ const sortedViolations = [...violations].sort((a, b) => {
148
+ if (a.filePath !== b.filePath) return a.filePath.localeCompare(b.filePath)
149
+ if (a.line !== b.line) return a.line - b.line
150
+ return a.column - b.column
151
+ })
152
+
153
+ const formattedViolations = sortedViolations
154
+ .map((violation) => {
155
+ const relativePath = path.relative(process.cwd(), violation.filePath)
156
+ return `- ${relativePath}:${violation.line}:${violation.column} ${violation.message}`
157
+ })
158
+ .join('\n')
159
+
160
+ super(
161
+ `Unsupported API usage found in workflow source.
162
+ CRE workflows run on Javy (QuickJS), not full Node.js.
163
+ Use CRE capabilities instead (for example, HTTPClient instead of fetch/node:http).
164
+ See https://docs.chain.link/cre/concepts/typescript-wasm-runtime
165
+
166
+ ${formattedViolations}`,
167
+ )
168
+ this.name = 'WorkflowRuntimeCompatibilityError'
169
+ }
170
+ }
171
+
172
+ /** Resolves a file path to an absolute path using the current working directory. */
173
+ const toAbsolutePath = (filePath: string) => path.resolve(filePath)
174
+
175
+ /**
176
+ * Maps a file extension to the appropriate TypeScript {@link ts.ScriptKind}
177
+ * so the parser handles JSX, CommonJS, and ESM files correctly.
178
+ */
179
+ const getScriptKind = (filePath: string): ts.ScriptKind => {
180
+ switch (path.extname(filePath).toLowerCase()) {
181
+ case '.js':
182
+ return ts.ScriptKind.JS
183
+ case '.jsx':
184
+ return ts.ScriptKind.JSX
185
+ case '.mjs':
186
+ return ts.ScriptKind.JS
187
+ case '.cjs':
188
+ return ts.ScriptKind.JS
189
+ case '.tsx':
190
+ return ts.ScriptKind.TSX
191
+ case '.mts':
192
+ return ts.ScriptKind.TS
193
+ case '.cts':
194
+ return ts.ScriptKind.TS
195
+ default:
196
+ return ts.ScriptKind.TS
197
+ }
198
+ }
199
+
200
+ /**
201
+ * Creates a {@link Violation} with 1-based line and column numbers derived
202
+ * from a character position in the source file.
203
+ */
204
+ const createViolation = (
205
+ filePath: string,
206
+ pos: number,
207
+ sourceFile: ts.SourceFile,
208
+ message: string,
209
+ ): Violation => {
210
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(pos)
211
+ return {
212
+ filePath: toAbsolutePath(filePath),
213
+ line: line + 1,
214
+ column: character + 1,
215
+ message,
216
+ }
217
+ }
218
+
219
+ /** Returns `true` if the specifier looks like a relative or absolute file path. */
220
+ const isRelativeImport = (specifier: string) => {
221
+ return specifier.startsWith('./') || specifier.startsWith('../') || specifier.startsWith('/')
222
+ }
223
+
224
+ /**
225
+ * Attempts to resolve a relative import specifier to an absolute file path.
226
+ * Tries the path as-is first, then appends each known source extension, then
227
+ * looks for an index file inside the directory. Returns `null` if nothing is
228
+ * found on disk.
229
+ */
230
+ const resolveRelativeImport = (fromFilePath: string, specifier: string): string | null => {
231
+ const basePath = specifier.startsWith('/')
232
+ ? path.resolve(specifier)
233
+ : path.resolve(path.dirname(fromFilePath), specifier)
234
+
235
+ if (existsSync(basePath) && statSync(basePath).isFile()) {
236
+ return toAbsolutePath(basePath)
237
+ }
238
+
239
+ for (const extension of sourceExtensions) {
240
+ const withExtension = `${basePath}${extension}`
241
+ if (existsSync(withExtension)) {
242
+ return toAbsolutePath(withExtension)
243
+ }
244
+ }
245
+
246
+ for (const extension of sourceExtensions) {
247
+ const asIndex = path.join(basePath, `index${extension}`)
248
+ if (existsSync(asIndex)) {
249
+ return toAbsolutePath(asIndex)
250
+ }
251
+ }
252
+
253
+ return null
254
+ }
255
+
256
+ /**
257
+ * Extracts a string literal from the first argument of a call expression.
258
+ * Used for `require('node:fs')` and `import('node:fs')` patterns.
259
+ * Returns `null` if the first argument is not a static string literal.
260
+ */
261
+ const getStringLiteralFromCall = (node: ts.CallExpression): string | null => {
262
+ const [firstArg] = node.arguments
263
+ if (!firstArg || !ts.isStringLiteral(firstArg)) return null
264
+ return firstArg.text
265
+ }
266
+
267
+ /**
268
+ * **Pass 1 — Module import analysis.**
269
+ *
270
+ * Walks the AST of a single source file and:
271
+ * - Flags any import/export/require/dynamic-import of a restricted module.
272
+ * - Enqueues relative imports for recursive scanning so the validator
273
+ * transitively covers the entire local dependency graph.
274
+ *
275
+ * Handles all module import syntaxes:
276
+ * - `import ... from 'node:fs'`
277
+ * - `export ... from 'node:fs'`
278
+ * - `import fs = require('node:fs')`
279
+ * - `require('node:fs')`
280
+ * - `import('node:fs')`
281
+ */
282
+ const collectModuleUsage = (
283
+ sourceFile: ts.SourceFile,
284
+ filePath: string,
285
+ violations: Violation[],
286
+ enqueueFile: (nextFile: string) => void,
287
+ ) => {
288
+ const checkModuleSpecifier = (specifier: string, pos: number) => {
289
+ if (restrictedModuleSpecifiers.has(specifier)) {
290
+ violations.push(
291
+ createViolation(
292
+ filePath,
293
+ pos,
294
+ sourceFile,
295
+ `'${specifier}' is not available in CRE workflow runtime.`,
296
+ ),
297
+ )
298
+ }
299
+
300
+ if (!isRelativeImport(specifier)) return
301
+ const resolved = resolveRelativeImport(filePath, specifier)
302
+ if (resolved) {
303
+ enqueueFile(resolved)
304
+ }
305
+ }
306
+
307
+ const visit = (node: ts.Node) => {
308
+ // import ... from 'specifier'
309
+ if (ts.isImportDeclaration(node) && ts.isStringLiteral(node.moduleSpecifier)) {
310
+ checkModuleSpecifier(node.moduleSpecifier.text, node.moduleSpecifier.getStart(sourceFile))
311
+ }
312
+
313
+ // export ... from 'specifier'
314
+ if (
315
+ ts.isExportDeclaration(node) &&
316
+ node.moduleSpecifier &&
317
+ ts.isStringLiteral(node.moduleSpecifier)
318
+ ) {
319
+ checkModuleSpecifier(node.moduleSpecifier.text, node.moduleSpecifier.getStart(sourceFile))
320
+ }
321
+
322
+ // import fs = require('specifier')
323
+ if (
324
+ ts.isImportEqualsDeclaration(node) &&
325
+ ts.isExternalModuleReference(node.moduleReference) &&
326
+ node.moduleReference.expression &&
327
+ ts.isStringLiteral(node.moduleReference.expression)
328
+ ) {
329
+ checkModuleSpecifier(
330
+ node.moduleReference.expression.text,
331
+ node.moduleReference.expression.getStart(sourceFile),
332
+ )
333
+ }
334
+
335
+ if (ts.isCallExpression(node)) {
336
+ // require('specifier')
337
+ if (ts.isIdentifier(node.expression) && node.expression.text === 'require') {
338
+ const requiredModule = getStringLiteralFromCall(node)
339
+ if (requiredModule) {
340
+ checkModuleSpecifier(requiredModule, node.arguments[0].getStart(sourceFile))
341
+ }
342
+ }
343
+
344
+ // import('specifier')
345
+ if (node.expression.kind === ts.SyntaxKind.ImportKeyword) {
346
+ const importedModule = getStringLiteralFromCall(node)
347
+ if (importedModule) {
348
+ checkModuleSpecifier(importedModule, node.arguments[0].getStart(sourceFile))
349
+ }
350
+ }
351
+ }
352
+
353
+ ts.forEachChild(node, visit)
354
+ }
355
+
356
+ visit(sourceFile)
357
+ }
358
+
359
+ /**
360
+ * Checks whether an identifier AST node is the **name being declared** (as
361
+ * opposed to a reference/usage). For example, in `const fetch = ...` the
362
+ * `fetch` token is a declaration name, while in `fetch(url)` it is a usage.
363
+ *
364
+ * This distinction is critical so that user-defined variables that shadow
365
+ * restricted global names are not flagged as violations.
366
+ */
367
+ const isDeclarationName = (identifier: ts.Identifier): boolean => {
368
+ const parent = identifier.parent
369
+
370
+ // Variable, function, class, interface, type alias, enum, module,
371
+ // type parameter, parameter, binding element, import names, enum member,
372
+ // property/method declarations, property assignments, and labels.
373
+ if (
374
+ (ts.isFunctionDeclaration(parent) && parent.name === identifier) ||
375
+ (ts.isFunctionExpression(parent) && parent.name === identifier) ||
376
+ (ts.isClassDeclaration(parent) && parent.name === identifier) ||
377
+ (ts.isClassExpression(parent) && parent.name === identifier) ||
378
+ (ts.isInterfaceDeclaration(parent) && parent.name === identifier) ||
379
+ (ts.isTypeAliasDeclaration(parent) && parent.name === identifier) ||
380
+ (ts.isEnumDeclaration(parent) && parent.name === identifier) ||
381
+ (ts.isModuleDeclaration(parent) && parent.name === identifier) ||
382
+ (ts.isTypeParameterDeclaration(parent) && parent.name === identifier) ||
383
+ (ts.isVariableDeclaration(parent) && parent.name === identifier) ||
384
+ (ts.isParameter(parent) && parent.name === identifier) ||
385
+ (ts.isBindingElement(parent) && parent.name === identifier) ||
386
+ (ts.isImportClause(parent) && parent.name === identifier) ||
387
+ (ts.isImportSpecifier(parent) && parent.name === identifier) ||
388
+ (ts.isNamespaceImport(parent) && parent.name === identifier) ||
389
+ (ts.isImportEqualsDeclaration(parent) && parent.name === identifier) ||
390
+ (ts.isNamespaceExport(parent) && parent.name === identifier) ||
391
+ (ts.isEnumMember(parent) && parent.name === identifier) ||
392
+ (ts.isPropertyDeclaration(parent) && parent.name === identifier) ||
393
+ (ts.isPropertySignature(parent) && parent.name === identifier) ||
394
+ (ts.isMethodDeclaration(parent) && parent.name === identifier) ||
395
+ (ts.isMethodSignature(parent) && parent.name === identifier) ||
396
+ (ts.isGetAccessorDeclaration(parent) && parent.name === identifier) ||
397
+ (ts.isSetAccessorDeclaration(parent) && parent.name === identifier) ||
398
+ (ts.isPropertyAssignment(parent) && parent.name === identifier) ||
399
+ (ts.isShorthandPropertyAssignment(parent) && parent.name === identifier) ||
400
+ (ts.isLabeledStatement(parent) && parent.label === identifier)
401
+ ) {
402
+ return true
403
+ }
404
+
405
+ // Property access (obj.fetch), qualified names (Ns.fetch), and type
406
+ // references (SomeType) — the right-hand identifier is not a standalone
407
+ // usage of the global name.
408
+ if (
409
+ (ts.isPropertyAccessExpression(parent) && parent.name === identifier) ||
410
+ (ts.isQualifiedName(parent) && parent.right === identifier) ||
411
+ (ts.isTypeReferenceNode(parent) && parent.typeName === identifier)
412
+ ) {
413
+ return true
414
+ }
415
+
416
+ return false
417
+ }
418
+
419
+ /**
420
+ * **Pass 2 — Global API analysis.**
421
+ *
422
+ * Uses the TypeScript type-checker to find references to restricted global
423
+ * identifiers (e.g. `fetch`, `setTimeout`, `window`). An identifier is only
424
+ * flagged if:
425
+ * - It matches a name in {@link restrictedGlobalApis}.
426
+ * - It is **not** a declaration name (see {@link isDeclarationName}).
427
+ * - Its symbol resolves to a declaration outside the local source files,
428
+ * meaning it comes from the global scope rather than user code.
429
+ *
430
+ * This also catches `globalThis.fetch`-style access patterns.
431
+ */
432
+ const collectGlobalApiUsage = (
433
+ program: ts.Program,
434
+ localSourceFiles: Set<string>,
435
+ violations: Violation[],
436
+ ) => {
437
+ const checker = program.getTypeChecker()
438
+
439
+ for (const sourceFile of program.getSourceFiles()) {
440
+ const resolvedSourcePath = toAbsolutePath(sourceFile.fileName)
441
+ if (!localSourceFiles.has(resolvedSourcePath)) continue
442
+
443
+ const visit = (node: ts.Node) => {
444
+ // Direct usage: fetch(...), setTimeout(...)
445
+ if (
446
+ ts.isIdentifier(node) &&
447
+ restrictedGlobalApis.has(node.text) &&
448
+ !isDeclarationName(node)
449
+ ) {
450
+ const symbol = checker.getSymbolAtLocation(node)
451
+ const hasLocalDeclaration =
452
+ symbol?.declarations?.some((declaration) =>
453
+ localSourceFiles.has(toAbsolutePath(declaration.getSourceFile().fileName)),
454
+ ) ?? false
455
+
456
+ if (!hasLocalDeclaration) {
457
+ violations.push(
458
+ createViolation(
459
+ resolvedSourcePath,
460
+ node.getStart(sourceFile),
461
+ sourceFile,
462
+ `'${node.text}' is not available in CRE workflow runtime.`,
463
+ ),
464
+ )
465
+ }
466
+ }
467
+
468
+ // Property access on globalThis: globalThis.fetch(...)
469
+ if (
470
+ ts.isPropertyAccessExpression(node) &&
471
+ ts.isIdentifier(node.expression) &&
472
+ node.expression.text === 'globalThis' &&
473
+ restrictedGlobalApis.has(node.name.text)
474
+ ) {
475
+ violations.push(
476
+ createViolation(
477
+ resolvedSourcePath,
478
+ node.name.getStart(sourceFile),
479
+ sourceFile,
480
+ `'globalThis.${node.name.text}' is not available in CRE workflow runtime.`,
481
+ ),
482
+ )
483
+ }
484
+
485
+ ts.forEachChild(node, visit)
486
+ }
487
+
488
+ visit(sourceFile)
489
+ }
490
+ }
491
+
492
+ /**
493
+ * Validates that a workflow entry file (and all local files it transitively
494
+ * imports) only uses APIs available in the CRE QuickJS/WASM runtime.
495
+ *
496
+ * The check runs in two passes:
497
+ *
498
+ * 1. **Module import scan** — starting from `entryFilePath`, recursively
499
+ * parses every reachable local source file and flags imports from
500
+ * restricted Node.js built-in modules.
501
+ *
502
+ * 2. **Global API scan** — creates a TypeScript program from the collected
503
+ * source files and uses the type-checker to flag references to restricted
504
+ * global identifiers that resolve to non-local (i.e. global) declarations.
505
+ *
506
+ * @param entryFilePath - Path to the workflow entry file (absolute or relative).
507
+ * @throws {WorkflowRuntimeCompatibilityError} If any violations are found.
508
+ * The error message includes a link to the CRE runtime docs and a formatted
509
+ * list of every violation with file:line:column and description.
510
+ *
511
+ * @example
512
+ * ```ts
513
+ * // During the cre-compile build step:
514
+ * assertWorkflowRuntimeCompatibility('./src/workflow.ts')
515
+ * // Throws if the workflow (or any file it imports) uses fetch, node:fs, etc.
516
+ * ```
517
+ *
518
+ * @see https://docs.chain.link/cre/concepts/typescript-wasm-runtime
519
+ */
520
+ export const assertWorkflowRuntimeCompatibility = (entryFilePath: string) => {
521
+ const rootFile = toAbsolutePath(entryFilePath)
522
+ const filesToScan = [rootFile]
523
+ const scannedFiles = new Set<string>()
524
+ const localSourceFiles = new Set<string>()
525
+ const violations: Violation[] = []
526
+
527
+ // Pass 1: Walk the local import graph and collect module-level violations.
528
+ while (filesToScan.length > 0) {
529
+ const currentFile = filesToScan.pop()
530
+ if (!currentFile || scannedFiles.has(currentFile)) continue
531
+ scannedFiles.add(currentFile)
532
+
533
+ if (!existsSync(currentFile)) continue
534
+ localSourceFiles.add(currentFile)
535
+
536
+ const fileContents = readFileSync(currentFile, 'utf-8')
537
+ const sourceFile = ts.createSourceFile(
538
+ currentFile,
539
+ fileContents,
540
+ ts.ScriptTarget.Latest,
541
+ true,
542
+ getScriptKind(currentFile),
543
+ )
544
+
545
+ collectModuleUsage(sourceFile, currentFile, violations, (nextFile) => {
546
+ if (!scannedFiles.has(nextFile)) {
547
+ filesToScan.push(nextFile)
548
+ }
549
+ })
550
+ }
551
+
552
+ // Pass 2: Use the type-checker to detect restricted global API usage.
553
+ const program = ts.createProgram({
554
+ rootNames: [...localSourceFiles],
555
+ options: {
556
+ allowJs: true,
557
+ checkJs: true,
558
+ noEmit: true,
559
+ skipLibCheck: true,
560
+ target: ts.ScriptTarget.ESNext,
561
+ module: ts.ModuleKind.ESNext,
562
+ moduleResolution: ts.ModuleResolutionKind.Bundler,
563
+ },
564
+ })
565
+
566
+ collectGlobalApiUsage(program, localSourceFiles, violations)
567
+
568
+ if (violations.length > 0) {
569
+ throw new WorkflowRuntimeCompatibilityError(violations)
570
+ }
571
+ }
572
+
573
+ export { WorkflowRuntimeCompatibilityError }