-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpackaging.test.ts
More file actions
280 lines (266 loc) · 9.77 KB
/
packaging.test.ts
File metadata and controls
280 lines (266 loc) · 9.77 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
import { assertEquals } from "jsr:@std/assert@^1.0.0";
import { fromFileUrl } from "jsr:@std/path@^1.0.0/from-file-url";
import { join } from "node:path";
import { pathToFileURL } from "node:url";
import manifest from "./deno.json" with { type: "json" };
const workspaceRoot = new URL(".", import.meta.url);
const workspacePath = fromFileUrl(workspaceRoot);
const expectedSdkVersionFromDenoJson = manifest.imports[
"@modelcontextprotocol/sdk"
].replace("npm:@modelcontextprotocol/sdk@", "");
const packagingRunPermissions = await Promise.all([
Deno.permissions.query({ name: "run", command: "deno" }),
Deno.permissions.query({ name: "run", command: "node" }),
Deno.permissions.query({
name: "run",
command: Deno.build.os === "windows" ? "where" : "which",
}),
Deno.permissions.query({ name: "run", command: "bun" }),
]);
const packagingRunPermissionGranted = packagingRunPermissions.every(
(permission, index) => index === 3 || permission.state === "granted",
);
const bunRunPermissionGranted = packagingRunPermissions[3]?.state === "granted";
const decodeText = (value: Uint8Array): string =>
new TextDecoder().decode(value);
const commandExists = async (command: string): Promise<boolean> => {
const whichCommand = Deno.build.os === "windows" ? "where" : "which";
try {
const output = await new Deno.Command(whichCommand, {
args: [command],
stdout: "null",
stderr: "null",
}).output();
return output.code === 0;
} catch {
return false;
}
};
const run = async (
command: string,
args: string[],
cwd = workspacePath,
): Promise<{ code: number; stdout: string; stderr: string }> => {
const output = await new Deno.Command(command, {
args,
cwd,
stdout: "piped",
stderr: "piped",
}).output();
return {
code: output.code,
stdout: decodeText(output.stdout),
stderr: decodeText(output.stderr),
};
};
Deno.test({
name: "built npm package loads in node through the published ESM entrypoint",
ignore: !packagingRunPermissionGranted,
fn: async () => {
const build = await run("deno", ["task", "build"]);
assertEquals(build.code, 0, build.stderr || build.stdout);
const builtPackage = JSON.parse(
await Deno.readTextFile(join(workspacePath, "dist/package.json")),
) as {
dependencies?: Record<string, string>;
devDependencies?: Record<string, string>;
};
assertEquals(
builtPackage.dependencies?.cosmiconfig,
"^9.0.0",
"generated npm package must declare cosmiconfig for runtime config loading",
);
assertEquals(
builtPackage.dependencies?.["@modelcontextprotocol/sdk"],
expectedSdkVersionFromDenoJson,
"generated npm package must declare the MCP SDK for runtime loading",
);
assertEquals(
typeof builtPackage.devDependencies?.["@types/node"],
"string",
"generated npm package must declare Node typings for dnt typecheck",
);
const tempDir = await Deno.makeTempDir();
try {
let optionalOpenCodePath: string | undefined;
try {
optionalOpenCodePath = Deno.env.get("OPENCODE_BIN") ?? undefined;
} catch {
optionalOpenCodePath = undefined;
}
const installRoot = join(tempDir, "package-install");
const isolatedCwd = join(tempDir, "bare-cwd");
const installNodeModules = join(installRoot, "node_modules");
const packageDir = join(installNodeModules, "opencode-graphiti");
const esmRunnerPath = join(installRoot, "load-esm.mjs");
const configRunnerPath = join(installRoot, "load-config.mjs");
const nodePackageRunnerPath = join(installRoot, "load-node-package.mjs");
const bunRunnerPath = join(installRoot, "load-bun-package.mjs");
const esmEntrypoint =
pathToFileURL(join(workspacePath, "dist/esm/mod.js")).href;
const isolatedHome = join(tempDir, "home");
const isolatedConfig = join(isolatedHome, ".config", "opencode");
const isolatedConfigPackageDir = join(
isolatedConfig,
"node_modules",
"opencode-graphiti",
);
await Deno.mkdir(installNodeModules, { recursive: true });
await Deno.mkdir(isolatedCwd, { recursive: true });
await Deno.mkdir(isolatedConfig, { recursive: true });
await Deno.writeTextFile(
join(isolatedCwd, ".graphitirc"),
`${
JSON.stringify(
{ graphiti: { endpoint: "http://127.0.0.1:8899/mcp" } },
null,
2,
)
}\n`,
);
await Deno.symlink(join(workspacePath, "dist"), packageDir, {
type: "dir",
});
await Deno.mkdir(join(isolatedConfig, "node_modules"), {
recursive: true,
});
await Deno.symlink(
join(workspacePath, "dist"),
isolatedConfigPackageDir,
{
type: "dir",
},
);
await Deno.writeTextFile(
join(isolatedConfig, "opencode.json"),
`${JSON.stringify({ plugin: ["opencode-graphiti"] }, null, 2)}\n`,
);
await Deno.writeTextFile(
esmRunnerPath,
`import * as plugin from ${
JSON.stringify(esmEntrypoint)
};\nconsole.log(JSON.stringify(Object.keys(plugin).sort()));\n`,
);
await Deno.writeTextFile(
configRunnerPath,
'import "opencode-graphiti";\n' +
`const { loadConfig } = await import(${
JSON.stringify(
pathToFileURL(join(packageDir, "esm/src/config.js")).href,
)
});\n` +
"const config = loadConfig(process.cwd());\n" +
"console.log(JSON.stringify({ endpoint: config.endpoint, graphiti: config.graphiti.endpoint, redis: config.redis.endpoint }));\n",
);
await Deno.writeTextFile(
nodePackageRunnerPath,
'import * as plugin from "opencode-graphiti";\n' +
"console.log(JSON.stringify(Object.keys(plugin).sort()));\n" +
"plugin.graphiti({ client: {}, directory: process.cwd() }).then(async () => {\n" +
" await new Promise((resolve) => setTimeout(resolve, 1000));\n" +
' console.log("initialized");\n' +
" process.exit(0);\n" +
"}, (error) => {\n" +
" console.error(error);\n" +
" process.exit(1);\n" +
"});\n",
);
await Deno.writeTextFile(
bunRunnerPath,
'import * as plugin from "opencode-graphiti";\n' +
"console.log(JSON.stringify(Object.keys(plugin).sort()));\n",
);
const esmLoad = await run("node", [esmRunnerPath], isolatedCwd);
assertEquals(esmLoad.code, 0, esmLoad.stderr || esmLoad.stdout);
assertEquals(esmLoad.stdout.trim(), '["graphiti"]');
const configLoad = await run("node", [configRunnerPath], isolatedCwd);
assertEquals(
configLoad.code,
0,
[
"config loader should resolve cosmiconfig from the plugin package instead of process.cwd()",
configLoad.stderr || configLoad.stdout,
].filter(Boolean).join("\n\n"),
);
assertEquals(
configLoad.stdout.trim(),
'{"endpoint":"http://127.0.0.1:8899/mcp","graphiti":"http://127.0.0.1:8899/mcp","redis":"redis://127.0.0.1:6379"}',
);
const nodePackageLoad = await run(
"node",
[nodePackageRunnerPath],
isolatedCwd,
);
assertEquals(
nodePackageLoad.code,
0,
[
"node package-name import from a bare cwd should succeed; this is the primary regression for cwd-sensitive runtime resolution",
nodePackageLoad.stderr || nodePackageLoad.stdout,
].filter(Boolean).join("\n\n"),
);
assertEquals(
nodePackageLoad.stdout.trim(),
'["graphiti"]\ninitialized',
);
assertEquals(
nodePackageLoad.stderr.includes(
"Cannot find module '@modelcontextprotocol/sdk/client/index.js'",
),
false,
[
"node package-name import from a bare cwd should not resolve runtime dependencies through process.cwd()",
nodePackageLoad.stderr || nodePackageLoad.stdout,
].filter(Boolean).join("\n\n"),
);
if (bunRunPermissionGranted && await commandExists("bun")) {
const bunLoad = await run("bun", [bunRunnerPath], isolatedCwd);
assertEquals(bunLoad.code, 0, bunLoad.stderr || bunLoad.stdout);
assertEquals(bunLoad.stdout.trim(), '["graphiti"]');
}
if (optionalOpenCodePath) {
try {
const opencodeInfo = await Deno.stat(optionalOpenCodePath);
if (opencodeInfo.isFile) {
const isolatedOpenCode = await new Deno.Command(
optionalOpenCodePath,
{
args: ["--print-logs", "stats"],
cwd: isolatedCwd,
env: {
HOME: isolatedHome,
XDG_CONFIG_HOME: join(isolatedHome, ".config"),
},
stdout: "piped",
stderr: "piped",
},
).output();
const isolatedOpenCodeOutput = decodeText(isolatedOpenCode.stdout) +
decodeText(isolatedOpenCode.stderr);
assertEquals(
isolatedOpenCode.code,
0,
isolatedOpenCodeOutput,
);
assertEquals(
isolatedOpenCodeOutput.includes("Missing 'default' export"),
false,
isolatedOpenCodeOutput,
);
assertEquals(
isolatedOpenCodeOutput.includes(
"Cannot find module '@modelcontextprotocol/sdk/client/index.js'",
),
false,
isolatedOpenCodeOutput,
);
}
} catch {
// OPENCODE_BIN is optional; keep the portable package checks above.
}
}
} finally {
await Deno.remove(tempDir, { recursive: true }).catch(() => undefined);
}
},
});