-
Notifications
You must be signed in to change notification settings - Fork 2.6k
Expand file tree
/
Copy pathexecuteAddDependency.ts
More file actions
338 lines (302 loc) Β· 9.2 KB
/
Copy pathexecuteAddDependency.ts
File metadata and controls
338 lines (302 loc) Β· 9.2 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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
import { db } from "../../db";
import { messages } from "../../db/schema";
import { eq } from "drizzle-orm";
import { Message } from "@/ipc/types";
import { readEffectiveSettings } from "@/main/settings";
import { DyadError, DyadErrorKind } from "@/errors/dyad_error";
import {
ADD_DEPENDENCY_INSTALL_TIMEOUT_MS,
buildAddDependencyCommand,
commitPnpmAllowBuildsConfigIfChanged,
ensureSocketFirewallInstalled,
getCommandExecutionDisplayDetails,
getPackageManagerCommandEnv,
getPnpmMinimumReleaseAgeSupport,
readPnpmIgnoredBuilds,
recordDeniedPnpmBuilds,
runCommand,
} from "@/ipc/utils/socket_firewall";
import { sendTelemetryEvent } from "@/ipc/utils/telemetry";
import {
choosePackageManagerFromSignal,
getPackageManagerSignal,
signalPrefersPnpm,
} from "@/ipc/utils/package_manager_selection";
import { shouldShowPnpmMinimumReleaseAgeWarning } from "@/lib/schemas";
import { escapeXmlAttr, escapeXmlContent } from "../../../shared/xmlEscape";
function escapeRegExp(value: string): string {
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function buildPackagesAttrPattern(packages: string[]): string {
const rawPackages = packages.join(" ");
const escapedPackages = escapeXmlAttr(rawPackages);
const packageVariants = new Set([rawPackages, escapedPackages]);
return Array.from(packageVariants).map(escapeRegExp).join("|");
}
export interface ExecuteAddDependencyResult {
installResults: string;
warningMessages: string[];
}
const NPM_PACKAGE_NAME_PATTERN = /^(@[a-z0-9-_.]+\/)?[a-z0-9-_.]+$/;
const DISPLAY_SUMMARY_PATTERNS = [
/\bblocked\b/i,
/\bfailed\b/i,
/\berror\b/i,
/\bdenied\b/i,
/\btimed out\b/i,
/\btimeout\b/i,
/\betimedout\b/i,
/\bnpm err!/i,
/\berr_pnpm_[a-z0-9_]+\b/i,
/\bE[A-Z][A-Z0-9_]{2,}\b/,
];
const DISPLAY_SUMMARY_NOISE_PATTERNS = [
/^progress:/i,
/^packages:\s*[+-]?\d+/i,
/^npm (?:notice|warn)\b/i,
/^npm err!\s*(?:a complete log of this run can be found in:|this is probably not a problem with npm\.)/i,
/^npm err!\s*(?:[A-Za-z]:\\|\/).+/i,
];
function isDisplaySummaryNoise(line: string): boolean {
return DISPLAY_SUMMARY_NOISE_PATTERNS.some((pattern) => pattern.test(line));
}
function getDisplayLines(value: string): string[] {
return value
.split(/\r?\n/)
.map((line) => line.trim())
.filter(Boolean);
}
function getFilteredDisplayDetails(value: string): string | undefined {
const lines = getDisplayLines(value).filter(
(line) => !isDisplaySummaryNoise(line),
);
if (lines.length === 0) {
return undefined;
}
return lines.join("\n");
}
function getDisplaySummary(value: string): string | undefined {
const lines = getDisplayLines(value);
for (let index = lines.length - 1; index >= 0; index -= 1) {
const line = lines[index];
if (
!isDisplaySummaryNoise(line) &&
DISPLAY_SUMMARY_PATTERNS.some((pattern) => pattern.test(line))
) {
return line;
}
}
for (let index = lines.length - 1; index >= 0; index -= 1) {
const line = lines[index];
if (!isDisplaySummaryNoise(line)) {
return line;
}
}
return lines.at(-1);
}
export class ExecuteAddDependencyError extends Error {
warningMessages: string[];
originalError: unknown;
displayDetails: string;
displaySummary: string;
constructor({
error,
warningMessages,
}: {
error: unknown;
warningMessages: string[];
}) {
const message = error instanceof Error ? error.message : String(error);
const commandDisplayDetails = getCommandExecutionDisplayDetails(error);
const displayDetails = commandDisplayDetails
? (getFilteredDisplayDetails(commandDisplayDetails) ?? message)
: message;
super(message);
this.name = "ExecuteAddDependencyError";
this.warningMessages = warningMessages;
this.originalError = error;
this.displayDetails = displayDetails;
this.displaySummary = getDisplaySummary(displayDetails) ?? message;
}
}
async function runAddDependencyCommand(
command: { command: string; args: string[] },
appPath: string,
): Promise<{
succeeded: boolean;
installResults: string;
lastError: unknown;
}> {
try {
const options = {
cwd: appPath,
env: getPackageManagerCommandEnv(),
timeoutMs: ADD_DEPENDENCY_INSTALL_TIMEOUT_MS,
};
const { stdout, stderr } = await runCommand(
command.command,
command.args,
options,
);
return {
succeeded: true,
installResults: stdout + (stderr ? `\n${stderr}` : ""),
lastError: null,
};
} catch (error) {
return {
succeeded: false,
installResults: "",
lastError: error,
};
}
}
function formatDeniedBuildsNote(packageNames: string[]): string {
if (packageNames.length === 0) {
return "";
}
const packageList = packageNames.join(", ");
return `\n\nNote: build scripts for ${packageList} were not run (Dyad security policy).`;
}
async function rebuildPromotedPnpmBuilds(
appPath: string,
packageNames: string[],
): Promise<void> {
if (packageNames.length === 0) {
return;
}
try {
await runCommand("pnpm", ["rebuild", ...packageNames], {
cwd: appPath,
env: getPackageManagerCommandEnv(),
timeoutMs: ADD_DEPENDENCY_INSTALL_TIMEOUT_MS,
});
} catch {
// Best effort: if the build is still broken, the install should not regress.
}
}
export async function installPackages({
packages,
appPath,
dev = false,
}: {
packages: string[];
appPath: string;
dev?: boolean;
}): Promise<ExecuteAddDependencyResult> {
const invalidPackage = packages.find(
(pkg) => !NPM_PACKAGE_NAME_PATTERN.test(pkg),
);
if (invalidPackage) {
throw new ExecuteAddDependencyError({
error: new DyadError(
`Invalid npm package name: ${invalidPackage}`,
DyadErrorKind.Validation,
),
warningMessages: [],
});
}
const settings = await readEffectiveSettings();
const warningMessages: string[] = [];
let useSocketFirewall = settings.blockUnsafeNpmPackages !== false;
if (useSocketFirewall) {
const socketFirewall = await ensureSocketFirewallInstalled();
if (!socketFirewall.available) {
useSocketFirewall = false;
if (socketFirewall.warningMessage) {
warningMessages.push(socketFirewall.warningMessage);
}
}
}
const pnpmSupport = await getPnpmMinimumReleaseAgeSupport();
// Choose from the app's own signals (packageManager field, lockfiles,
// node_modules shape) so add-dependency and the run command agree on the
// package manager β a pnpm add against an npm-shaped app would purge its
// node_modules and write a lockfile the run command ignores.
const signal = getPackageManagerSignal(appPath);
const packageManager = choosePackageManagerFromSignal({
signal,
pnpmAvailable: pnpmSupport.available,
});
if (
signalPrefersPnpm(signal) &&
!pnpmSupport.minimumReleaseAgeSupported &&
pnpmSupport.warningMessage &&
shouldShowPnpmMinimumReleaseAgeWarning(settings)
) {
warningMessages.push(pnpmSupport.warningMessage);
}
const promotedPackages =
packageManager === "pnpm"
? (await commitPnpmAllowBuildsConfigIfChanged(appPath)).promotedPackages
: [];
const { succeeded, installResults, lastError } =
await runAddDependencyCommand(
buildAddDependencyCommand(packages, packageManager, useSocketFirewall, {
dev,
}),
appPath,
);
if (!succeeded && lastError) {
throw new ExecuteAddDependencyError({
error: lastError,
warningMessages,
});
}
await rebuildPromotedPnpmBuilds(appPath, promotedPackages);
let installResultsWithPolicyNotes = installResults;
if (packageManager === "pnpm") {
const ignoredBuilds = await readPnpmIgnoredBuilds(appPath);
const { deniedBuilds } = await recordDeniedPnpmBuilds({
appPath,
ignoredBuilds,
});
if (deniedBuilds.length > 0) {
sendTelemetryEvent("pnpm:build-auto-denied", {
packages: deniedBuilds.map((ignoredBuild) => ignoredBuild.packageSpec),
source: "add-dependency",
});
installResultsWithPolicyNotes += formatDeniedBuildsNote(
Array.from(
new Set(deniedBuilds.map((ignoredBuild) => ignoredBuild.packageName)),
).sort((left, right) => left.localeCompare(right)),
);
}
}
return {
installResults: installResultsWithPolicyNotes,
warningMessages,
};
}
export async function executeAddDependency({
packages,
message,
appPath,
}: {
packages: string[];
message: Message;
appPath: string;
}): Promise<ExecuteAddDependencyResult> {
const { installResults, warningMessages } = await installPackages({
packages,
appPath,
});
// Update the message content with the installation results
const escapedPackages = escapeXmlAttr(packages.join(" "));
const updatedContent = message.content.replace(
new RegExp(
`<dyad-add-dependency packages="(?:${buildPackagesAttrPattern(packages)})">[\\s\\S]*?</dyad-add-dependency>`,
"g",
),
`<dyad-add-dependency packages="${escapedPackages}">${escapeXmlContent(installResults)}</dyad-add-dependency>`,
);
// Save the updated message back to the database
await db
.update(messages)
.set({ content: updatedContent })
.where(eq(messages.id, message.id));
return {
installResults,
warningMessages,
};
}