Repository navigation
Expand file tree
/
Copy pathprepareBuild.js
More file actions
312 lines (289 loc) · 10.5 KB
/
Copy pathprepareBuild.js
File metadata and controls
312 lines (289 loc) · 10.5 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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
const path = require("path");
const fs = require("fs");
const extensionFolder = path.join(__dirname);
const distNodeModules = path.join(extensionFolder, "dist", "node_modules");
function getVsceTarget() {
// Possible values include the platforms supported by `vsce package --target`, see
// https://code.visualstudio.com/api/working-with-extensions/publishing-extension#platformspecific-extensions
return process.env.VSC_VSCE_TARGET || process.env.VSCE_TARGET;
}
/** Every file below `dir`, as absolute paths. */
function listFiles(dir) {
return fs.readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
const child = path.join(dir, entry.name);
return entry.isDirectory() ? listFiles(child) : [child];
});
}
/** Delete the directories below `dir` that are left empty, deepest first. */
function removeEmptyDirs(dir) {
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
if (entry.isDirectory()) {
const child = path.join(dir, entry.name);
removeEmptyDirs(child);
if (fs.readdirSync(child).length === 0) {
fs.rmdirSync(child);
}
}
}
}
/**
* Platforms with no VSIX of their own, whose users install the nearest one by
* hand: Windows on Arm takes the win32-x64 VSIX, and Alpine the linux VSIX of
* its arch. Those VSIXes also ship these addons, so notebooks load there too.
*/
const ZEROMQ_EXTRA_RUNTIMES = {
"win32-x64": ["win32/arm64/msvc"],
"linux-x64": ["linux/x64/musl"],
"linux-arm64": ["linux/arm64/musl"],
};
/**
* The zeromq addon runtimes a VS Code target ships, as "os/arch/libc" in the
* terms of the `build/manifest.json` that zeromq's cmake-ts loader filters on.
*/
function getZeromqRuntimes(vsceTarget) {
const match = /^(win32|linux|alpine|darwin)-(x64|arm64|armhf|ia32)$/.exec(
vsceTarget,
);
if (!match) {
throw new Error(`Unsupported VSCE_TARGET '${vsceTarget}' for zeromq`);
}
const [, platform, arch] = match;
const os = platform === "alpine" ? "linux" : platform;
const libc = {
win32: "msvc",
linux: "glibc",
alpine: "musl",
darwin: "libc",
}[platform];
const runtime = `${os}/${arch === "armhf" ? "arm" : arch}/${libc}`;
return [runtime, ...(ZEROMQ_EXTRA_RUNTIMES[vsceTarget] || [])];
}
/**
* Keep only the zeromq addons the target ships. zeromq loads its addon
* through cmake-ts `loadAddon(build/)`, which reads build/manifest.json, keeps
* the entries matching the running os, arch and libc, and tries them from the
* newest ABI down. The manifest is rewritten to list only the addons kept, so
* the loader never tries a file that isn't shipped.
*/
function pruneZeromqAddons(zeromqDir, vsceTarget) {
const buildDir = path.join(zeromqDir, "build");
const manifestPath = path.join(buildDir, "manifest.json");
const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8"));
const runtimes = getZeromqRuntimes(vsceTarget);
const kept = {};
const found = new Set();
for (const [key, addonPath] of Object.entries(manifest)) {
const config = JSON.parse(key);
const runtime = `${config.os}/${config.arch}/${config.libc}`;
if (runtimes.includes(runtime)) {
kept[key] = addonPath;
found.add(runtime);
}
}
// Windows entries use backslashes; packaging may run on Linux.
const keptFiles = new Set(
Object.values(kept).map((addonPath) =>
path.resolve(buildDir, addonPath.replace(/\\/g, "/")),
),
);
const absent = runtimes.filter((runtime) => !found.has(runtime));
const missing = [...keptFiles].filter((file) => !fs.existsSync(file));
if (absent.length > 0 || missing.length > 0) {
throw new Error(
`Missing zeromq addons for VSCE_TARGET '${vsceTarget}' in ${buildDir}: ${[
...absent,
...missing,
].join(", ")}`,
);
}
for (const file of listFiles(buildDir)) {
if (file !== manifestPath && !keptFiles.has(file)) {
fs.rmSync(file);
}
}
removeEmptyDirs(buildDir);
fs.writeFileSync(manifestPath, JSON.stringify(kept));
console.log(
`kept zeromq addons for ${vsceTarget}:`,
Object.values(kept).join(", "),
);
}
/** Delete every file below `dir` except `keep` (paths relative to `dir`). */
function keepOnly(dir, keep) {
const kept = new Set(keep.map((file) => path.join(dir, file)));
for (const file of listFiles(dir)) {
if (!kept.has(file)) {
fs.rmSync(file);
}
}
removeEmptyDirs(dir);
const missing = [...kept].filter((file) => !fs.existsSync(file));
if (missing.length > 0) {
throw new Error(`Required asset missing: ${missing.join(", ")}`);
}
}
/**
* Strip zeromq and cmake-ts down to what loads at runtime: zeromq's lib/ and
* entry points plus its target addon, and cmake-ts' build/loader.js. Sources,
* install scripts, node-addon-api headers, type declarations and build configs
* are only used when compiling the addon. `prebuilds/` is never read by
* zeromq 6, whose loader looks only in `build/`.
*/
function pruneZeromq() {
const zeromqDir = path.join(distNodeModules, "zeromq");
const cmakeTsDir = path.join(distNodeModules, "cmake-ts");
for (const dir of [zeromqDir, cmakeTsDir]) {
if (!fs.existsSync(dir)) {
throw new Error(`Required asset missing: ${dir}`);
}
}
for (const entry of [
"src",
"script",
"node_modules",
"prebuilds",
"CMakeLists.txt",
"vcpkg.json",
"tsconfig.json",
".mocharc.js",
path.join("lib", "tsconfig.tsbuildinfo"),
]) {
fs.rmSync(path.join(zeromqDir, entry), { recursive: true, force: true });
}
listFiles(zeromqDir)
.filter((file) => file.endsWith(".d.ts"))
.forEach((file) => fs.rmSync(file));
removeEmptyDirs(zeromqDir);
keepOnly(cmakeTsDir, ["package.json", path.join("build", "loader.js")]);
const vsceTarget = getVsceTarget();
if (!vsceTarget) {
// Keep every platform's addon, as we're not building a platform-specific bundle.
console.log("vsceTarget is not set, keeping all zeromq addons");
return;
}
pruneZeromqAddons(zeromqDir, vsceTarget);
}
/**
* Map VSC_VSCE_TARGET to the altimate-core platform package suffix to keep.
* Returns empty array if no target is set (keep all).
*/
function getAltimateCorePackagesToKeep() {
const vsceTarget = getVsceTarget();
if (!vsceTarget) {
return [];
}
if (vsceTarget.includes("darwin")) {
if (vsceTarget.includes("arm64")) return ["darwin-arm64"];
if (vsceTarget.includes("x64")) return ["darwin-x64"];
return ["darwin-arm64", "darwin-x64"];
}
if (vsceTarget.includes("linux") || vsceTarget.includes("alpine")) {
if (vsceTarget.includes("arm64")) return ["linux-arm64-gnu"];
if (vsceTarget.includes("x64")) return ["linux-x64-gnu"];
return ["linux-arm64-gnu", "linux-x64-gnu"];
}
if (vsceTarget.includes("win32")) {
return ["win32-x64-msvc"];
}
return [];
}
function deleteUnnecessaryAltimateCorePackages() {
const vsceTarget = getVsceTarget();
if (!vsceTarget) {
console.log(
"vsceTarget is not set, keeping all altimate-core platform packages",
);
return;
}
console.log(
"pruning altimate-core platform packages for target:",
vsceTarget,
);
const keepSuffixes = getAltimateCorePackagesToKeep();
const altimateCoreDir = path.join(
extensionFolder,
"dist",
"node_modules",
"@altimateai",
);
if (!fs.existsSync(altimateCoreDir)) {
console.log("altimate-core dist directory not found, skipping");
return;
}
const entries = fs.readdirSync(altimateCoreDir);
for (const entry of entries) {
// Only prune platform-specific packages (altimate-core-<platform>)
if (!entry.startsWith("altimate-core-")) continue;
const suffix = entry.replace("altimate-core-", "");
if (!keepSuffixes.includes(suffix)) {
const fullPath = path.join(altimateCoreDir, entry);
console.log("deleting", fullPath);
fs.rmSync(fullPath, { recursive: true });
}
}
// Also prune .node files from the altimate-core/ directory that don't
// match the target platform (these are copied by webpack for direct resolution)
const coreDir = path.join(altimateCoreDir, "altimate-core");
if (fs.existsSync(coreDir)) {
const coreEntries = fs.readdirSync(coreDir);
for (const file of coreEntries) {
if (!file.endsWith(".node")) continue;
// e.g. "altimate-core.darwin-arm64.node" → check if "darwin-arm64" is kept
const match = file.match(/^altimate-core\.(.+)\.node$/);
if (match && !keepSuffixes.includes(match[1])) {
const fullPath = path.join(coreDir, file);
console.log("deleting .node file", fullPath);
fs.rmSync(fullPath);
}
}
}
console.log("pruned altimate-core platform packages");
}
/**
* The Python bridge must be spawned hidden: the extension host has no console,
* so on Windows a bridge spawned without `windowsHide` gets its own visible
* console window (issue 2016). The flag lives in @altimateai/dbt-integration's
* vendored bridge and reaches users only through this bundle, so assert it on
* the built artifact instead of trusting the dependency graph. Exactly one
* bridge copy is required as well: a second copy breaks
* `instanceof PythonException` across the bundle.
*/
function assertPythonBridgeSpawnHidden() {
const bundlePath = path.join(extensionFolder, "dist", "extension.js");
const bundle = fs.readFileSync(bundlePath, "utf8");
const marker = "node_python_bridge.py";
const copies = bundle.split(marker).length - 1;
if (copies !== 1) {
throw new Error(
`Expected exactly one Python bridge in dist/extension.js, found ${copies}`,
);
}
const start = bundle.indexOf(marker);
const region = bundle.slice(start, start + 4000);
// The spawn options are located by the channel's env key: the bridge talks
// newline-JSON over a plain fd-3 pipe named by NODE_CHANNEL_FD (the
// IPC-era anchor was the literal 'ipc' stdio entry).
const anchor = region.search(/NODE_CHANNEL_FD/);
if (anchor === -1) {
throw new Error(
"Could not locate the Python bridge spawn options in dist/extension.js",
);
}
const options = region.slice(anchor, anchor + 200);
if (!/stdio:\s*\[[^\]]*["']pipe["']\]/.test(options)) {
throw new Error(
`Python bridge spawn options lack the fd-3 "pipe" channel in dist/extension.js: ${options}`,
);
}
if (!/windowsHide:\s*(true|!0)/.test(options)) {
throw new Error(
`Python bridge spawn options lack windowsHide in dist/extension.js: ${options}`,
);
}
console.log(
"python bridge spawn is hidden (windowsHide) in dist/extension.js",
);
}
pruneZeromq();
deleteUnnecessaryAltimateCorePackages();
assertPythonBridgeSpawnHidden();