-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathbundle-validation.test.mts
More file actions
224 lines (194 loc) · 6.85 KB
/
bundle-validation.test.mts
File metadata and controls
224 lines (194 loc) · 6.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
/**
* @fileoverview Bundle validation tests to ensure build output quality.
* Verifies that dist files don't contain absolute paths or external dependencies.
*/
import { promises as fs } from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import { parse } from '@babel/parser'
import _traverse from '@babel/traverse'
import { describe, expect, it } from 'vitest'
// CJS/ESM interop: @babel/traverse wraps the function under .default in ESM
const traverse = ((_traverse as any).default ?? _traverse) as typeof _traverse
const __dirname = path.dirname(fileURLToPath(import.meta.url))
const packagePath = path.resolve(__dirname, '../..')
const distPath = path.join(packagePath, 'dist')
/**
* Check if content contains absolute paths.
* Detects paths like /Users/, C:\, /home/, etc.
*/
function hasAbsolutePaths(content: string): {
hasIssue: boolean
matches: string[]
} {
// Match absolute paths but exclude URLs and node: protocol.
const patterns = [
// Match require('/abs/path') or require('C:\\path').
/require\(["'](?:\/[^"'\n]+|[A-Z]:\\[^"'\n]+)["']\)/g,
// Match import from '/abs/path'.
/import\s+.*?from\s+["'](?:\/[^"'\n]+|[A-Z]:\\[^"'\n]+)["']/g,
]
const matches: string[] = []
for (const pattern of patterns) {
const found = content.match(pattern)
if (found) {
matches.push(...found)
}
}
return {
hasIssue: matches.length > 0,
matches,
}
}
/**
* Check if bundle contains inlined dependencies using AST analysis.
* Reads package.json dependencies and ensures they are NOT bundled inline.
*/
async function checkBundledDependencies(content: string): Promise<{
bundledDeps: string[]
hasNoBundledDeps: boolean
}> {
// Read package.json to get runtime dependencies.
const pkgJsonPath = path.join(packagePath, 'package.json')
const pkgJson = JSON.parse(await fs.readFile(pkgJsonPath, 'utf8'))
const dependencies = pkgJson.dependencies || {}
const bundledDeps: string[] = []
// Parse the bundle into an AST.
const file = parse(content, {
sourceType: 'module',
plugins: ['typescript'],
})
// Collect all import sources from the AST.
const importSources = new Set<string>()
traverse(file as any, {
ImportDeclaration(path: any) {
const source = path.node.source.value
importSources.add(source)
},
CallExpression(path: any) {
// Handle require() calls
if (
path.node.callee.name === 'require' &&
path.node.arguments.length > 0 &&
path.node.arguments[0].type === 'StringLiteral'
) {
const source = path.node.arguments[0].value
importSources.add(source)
}
},
})
// Packages that should always be external (never bundled).
const socketPackagePatterns = [
/@socketsecurity\/lib/,
/@socketregistry\/packageurl-js/,
/@socketsecurity\/sdk/,
/@socketsecurity\/registry/,
]
// Check if we have runtime dependencies.
if (Object.keys(dependencies).length === 0) {
// No runtime dependencies - check that Socket packages aren't bundled.
for (const pattern of socketPackagePatterns) {
const hasExternalImport = Array.from(importSources).some(source =>
pattern.test(source),
)
if (!hasExternalImport) {
// Check if this package name appears in the content at all.
// If it's just in string literals (like constants), that's fine.
// Use AST to check if it appears in any meaningful way.
let foundInCode = false
traverse(file as any, {
StringLiteral(path: any) {
// Skip string literals - these are fine
if (pattern.test(path.node.value)) {
// It's in a string literal, which is fine
}
},
Identifier(path: any) {
// Check if the package name appears in identifiers or other code
if (
pattern.test(path.node.name) ||
(path.node.name.includes('socketsecurity') &&
pattern.test(path.node.name))
) {
foundInCode = true
}
},
})
// Only flag if we found it in actual code, not just string literals
if (foundInCode) {
bundledDeps.push(pattern.source)
}
}
}
} else {
// We have runtime dependencies - check that they remain external.
for (const dep of Object.keys(dependencies)) {
// Check for exact match or subpath imports (e.g., '@socketsecurity/lib/path')
const hasExternalImport = Array.from(importSources).some(
source => source === dep || source.startsWith(`${dep}/`),
)
if (!hasExternalImport) {
// Check if dependency appears in actual bundled code (not just package.json metadata)
// The bundle might include package.json as a literal object, which is fine
let foundInBundledCode = false
traverse(file as any, {
// Look for actual code that imports/requires this dependency
CallExpression(path: any) {
if (
path.node.callee.name === 'require' &&
path.node.arguments.length > 0 &&
path.node.arguments[0].type === 'StringLiteral' &&
path.node.arguments[0].value.startsWith(dep)
) {
foundInBundledCode = true
}
},
ImportDeclaration(path: any) {
if (path.node.source.value.startsWith(dep)) {
foundInBundledCode = true
}
},
})
// Only flag if we found actual bundled code, not just metadata
if (foundInBundledCode) {
bundledDeps.push(dep)
}
}
}
}
return {
bundledDeps,
hasNoBundledDeps: bundledDeps.length === 0,
}
}
describe('Bundle validation', () => {
it('should not contain absolute paths in dist/index.js', async () => {
const indexPath = path.join(distPath, 'index.js')
const content = await fs.readFile(indexPath, 'utf8')
const result = hasAbsolutePaths(content)
if (result.hasIssue) {
console.error('Found absolute paths in bundle:')
for (const match of result.matches) {
console.error(` - ${match}`)
}
}
expect(result.hasIssue, 'Bundle should not contain absolute paths').toBe(
false,
)
})
it('should not bundle dependencies inline (validate against package.json dependencies)', async () => {
const indexPath = path.join(distPath, 'index.js')
const content = await fs.readFile(indexPath, 'utf8')
const result = await checkBundledDependencies(content)
if (!result.hasNoBundledDeps) {
console.error('Found bundled dependencies (should be external):')
for (const dep of result.bundledDeps) {
console.error(` - ${dep}`)
}
}
expect(
result.hasNoBundledDeps,
'Dependencies from package.json should be external, not bundled inline',
).toBe(true)
})
})