Repository navigation
Expand file tree
/
Copy pathbuild-plugin.mjs
More file actions
155 lines (146 loc) · 4.38 KB
/
Copy pathbuild-plugin.mjs
File metadata and controls
155 lines (146 loc) · 4.38 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
import { execFileSync } from "node:child_process";
import { isDeepStrictEqual } from "node:util";
import {
chmod,
copyFile,
lstat,
mkdir,
mkdtemp,
readFile,
readdir,
rename,
rm,
} from "node:fs/promises";
import { dirname, join, posix, resolve } from "node:path";
import { isMain } from "./is-main.mjs";
import { pluginContractFiles } from "./plugin-contract.mjs";
const packageRoot = resolve(import.meta.dirname, "..");
const repositoryRoot = resolve(packageRoot, "../..");
function validatePath(path) {
const parts = path.split("/");
if (
path.includes("\\") ||
posix.isAbsolute(path) ||
parts.some((part) => part === "" || part === "." || part === "..")
) {
throw new Error(
`Plugin projection contract contains an unsafe path: ${path}.`,
);
}
}
export async function bundledPluginFiles(root, prefix = "") {
const entries = await readdir(join(root, prefix), {
withFileTypes: true,
});
const files = [];
for (const entry of entries) {
const path = prefix === "" ? entry.name : `${prefix}/${entry.name}`;
if (entry.isDirectory()) {
files.push(...(await bundledPluginFiles(root, path)));
} else if (entry.isFile()) {
files.push(path);
} else {
throw new Error(`Bundled plugin generated an unsafe path: ${path}.`);
}
}
return files.sort();
}
/** @returns {Promise<string[]>} */
export async function buildBundledPlugin({
contractPath = join(
repositoryRoot,
"plugins",
"codex-security",
"plugin-files.json",
),
destination = join(packageRoot, "_bundled_plugin"),
source = join(repositoryRoot, "plugins", "codex-security"),
} = {}) {
const contract = JSON.parse(await readFile(contractPath, "utf8"));
const files = pluginContractFiles(contract);
files.forEach(validatePath);
if (new Set(files).size !== files.length) {
throw new Error("Plugin projection contract contains duplicate paths.");
}
const copiedPaths = files.filter((path) => !path.startsWith("mcp/"));
const sourceFiles = await Promise.all(
copiedPaths.map(async (path) => {
const file = join(source, path);
let metadata;
try {
metadata = await lstat(file);
} catch (error) {
if (error?.code === "ENOENT") {
throw new Error(`Canonical plugin source is missing ${path}.`);
}
throw error;
}
if (!metadata.isFile()) {
throw new Error(
`Canonical plugin source is not a regular file: ${path}.`,
);
}
return { file, mode: metadata.mode & 0o777, path };
}),
);
await mkdir(dirname(destination), { recursive: true });
const staging = await mkdtemp(join(dirname(destination), ".plugin-build-"));
const staged = join(staging, "bundle");
const previous = join(staging, "previous");
let preservePrevious = false;
try {
if (files.some((path) => path.startsWith("mcp/"))) {
const mcpApp = join(source, "mcp-app");
execFileSync(
process.execPath,
[
join(mcpApp, "scripts/build_mcp_app.mjs"),
"--output",
join(staged, "mcp"),
],
{ cwd: mcpApp, stdio: "inherit" },
);
}
for (const { file, mode, path } of sourceFiles) {
const output = join(staged, path);
await mkdir(dirname(output), { recursive: true });
await copyFile(file, output);
await chmod(output, mode);
}
if (
!isDeepStrictEqual(await bundledPluginFiles(staged), [...files].sort())
) {
throw new Error("Bundled plugin generated files outside its contract.");
}
try {
await rename(destination, previous);
preservePrevious = true;
} catch (error) {
if (error.code !== "ENOENT") throw error;
}
try {
await rename(staged, destination);
} catch (error) {
if (preservePrevious) {
await rename(previous, destination);
preservePrevious = false;
}
throw error;
}
preservePrevious = false;
} finally {
// Leave the previous bundle available if restoring it fails.
if (!preservePrevious) await rm(staging, { recursive: true, force: true });
}
return files;
}
if (isMain(import.meta.url)) {
buildBundledPlugin()
.then((files) => {
console.log(`Generated bundled plugin with ${files.length} files.`);
})
.catch((error) => {
console.error(error instanceof Error ? error.message : error);
process.exitCode = 1;
});
}