codemod 2.0.0-alpha.2 → 2.0.0-alpha.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +0 -1
- package/package.json +14 -12
- package/register.d.mts +2 -11
- package/register.mjs +53 -46
- package/runtime/addon.d.mts +114 -0
- package/runtime/addon.mjs +36 -40
- package/runtime/ast-grep.d.mts +20 -0
- package/runtime/ast-grep.mjs +50 -61
- package/runtime/context.d.mts +49 -0
- package/runtime/context.mjs +35 -53
- package/runtime/hooks.d.mts +2 -0
- package/runtime/hooks.mjs +4 -6
- package/runtime/host.d.mts +82 -81
- package/runtime/host.mjs +383 -323
- package/runtime/llm.d.mts +2 -0
- package/runtime/llm.mjs +1 -7
- package/runtime/metrics.d.mts +9 -0
- package/runtime/metrics.mjs +31 -34
- package/runtime/modules.d.mts +3 -0
- package/runtime/modules.mjs +8 -10
- package/runtime/orchestrator-version.d.mts +2 -0
- package/runtime/orchestrator-version.mjs +3 -0
- package/runtime/orchestrator.d.mts +261 -0
- package/runtime/orchestrator.mjs +829 -607
- package/runtime/runtime.d.mts +15 -0
- package/runtime/runtime.mjs +18 -26
- package/runtime/workflow.d.mts +19 -0
- package/runtime/workflow.mjs +83 -92
- package/testing/index.d.mts +109 -155
- package/testing/index.mjs +555 -545
- package/types/langs/package.json +3 -0
- package/types/modules/workflow.d.ts +180 -15
- package/vite.d.mts +4 -21
- package/vite.mjs +23 -17
package/runtime/host.mjs
CHANGED
|
@@ -8,383 +8,443 @@
|
|
|
8
8
|
//
|
|
9
9
|
// Code here has whatever Node.js gives it: capabilities are not enforced.
|
|
10
10
|
// The codemod CLI runs workflows in its own sandboxed runtime instead.
|
|
11
|
-
|
|
11
|
+
var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
|
|
12
|
+
if (typeof path === "string" && /^\.\.?\//.test(path)) {
|
|
13
|
+
return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
|
|
14
|
+
return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
return path;
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* Run a workflow in this Node.js or Bun process.
|
|
21
|
+
*
|
|
22
|
+
* ```ts
|
|
23
|
+
* import { runWorkflow } from "codemod/host";
|
|
24
|
+
*
|
|
25
|
+
* const report = await runWorkflow("./my-codemod", { target: "./repo" });
|
|
26
|
+
* if (report.status !== "succeeded") throw new Error(report.error ?? report.status);
|
|
27
|
+
* ```
|
|
28
|
+
*
|
|
29
|
+
* The workflow's body, function steps and `forEachFile` callbacks run here,
|
|
30
|
+
* so they can be debugged, covered and mocked. Host tasks (`jssg`, `shell`,
|
|
31
|
+
* `codemod`, ...) and the run store go through the native addon.
|
|
32
|
+
*
|
|
33
|
+
* Code here has whatever Node.js gives it: the capabilities codemod.yaml
|
|
34
|
+
* declares are not enforced. The codemod CLI runs workflows in its own
|
|
35
|
+
* sandboxed runtime instead; run packages from the registry with the CLI.
|
|
36
|
+
*
|
|
37
|
+
* @module
|
|
38
|
+
*/
|
|
12
39
|
import "../register.mjs";
|
|
13
|
-
|
|
14
|
-
import { readFileSync } from "node:fs";
|
|
15
40
|
import { isAbsolute, resolve } from "node:path";
|
|
16
41
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
17
|
-
|
|
18
42
|
import { addon } from "./addon.mjs";
|
|
19
43
|
import { context, metricsOf, stateChanges, stepScope } from "./context.mjs";
|
|
20
|
-
import {
|
|
21
|
-
|
|
22
|
-
CanceledError,
|
|
23
|
-
checkJson,
|
|
24
|
-
createRuntime,
|
|
25
|
-
describeError,
|
|
26
|
-
fileHandle,
|
|
27
|
-
} from "./orchestrator.mjs";
|
|
44
|
+
import { ORCHESTRATOR_VERSION } from "./orchestrator-version.mjs";
|
|
45
|
+
import { AwaitingApprovalError, CanceledError, checkJson, createRuntime, describeDuration, describeError, fileHandle, } from "./orchestrator.mjs";
|
|
28
46
|
import { callbackId } from "./workflow.mjs";
|
|
29
|
-
|
|
30
47
|
/**
|
|
31
|
-
* Run a workflow
|
|
48
|
+
* Run a workflow (a workflow file, a package directory, or the workflow
|
|
49
|
+
* module itself). Resolves for every outcome; rejects when the workflow
|
|
50
|
+
* cannot be loaded. YAML workflows run only with the CLI.
|
|
32
51
|
*
|
|
33
|
-
*
|
|
34
|
-
*
|
|
35
|
-
* it through their own module system. A module needs `options.path` (or
|
|
52
|
+
* A module (`await import("./workflow.ts")`), for test runners that should
|
|
53
|
+
* load it through their own module system, needs `options.path` (or
|
|
36
54
|
* `options.workflowDir`) so relative task paths resolve.
|
|
37
55
|
*/
|
|
38
56
|
export async function runWorkflow(workflow, options = {}) {
|
|
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
|
-
|
|
57
|
+
const native = addon();
|
|
58
|
+
checkAddon(native);
|
|
59
|
+
const { path, load } = locate(workflow, options);
|
|
60
|
+
// A workflow that cannot be loaded is not a run: reject.
|
|
61
|
+
const module = await load();
|
|
62
|
+
const main = module?.default;
|
|
63
|
+
if (typeof main !== "function") {
|
|
64
|
+
throw new TypeError(`${path} must export a default function`);
|
|
65
|
+
}
|
|
66
|
+
if (options.captureConsole)
|
|
67
|
+
captureConsole();
|
|
68
|
+
const run = native.Run.open({
|
|
69
|
+
workflow: path,
|
|
70
|
+
target: resolve(options.target ?? "."),
|
|
71
|
+
params: options.params ?? {},
|
|
72
|
+
name: options.name,
|
|
73
|
+
dryRun: options.dryRun ?? false,
|
|
74
|
+
until: options.until,
|
|
75
|
+
given: options.given,
|
|
76
|
+
approve: options.approve ?? true,
|
|
77
|
+
capabilities: options.capabilities ?? [],
|
|
78
|
+
store: options.store,
|
|
79
|
+
resume: options.resume,
|
|
80
|
+
});
|
|
81
|
+
const flight = inFlight();
|
|
82
|
+
const runtime = createRuntime(host(run, flight, () => runtime));
|
|
83
|
+
flight.closed = () => runtime.isClosed();
|
|
84
|
+
const scope = { run, runtime, captureConsole: options.captureConsole ?? false };
|
|
85
|
+
const abort = () => run.cancel();
|
|
86
|
+
if (options.signal?.aborted)
|
|
87
|
+
abort();
|
|
88
|
+
options.signal?.addEventListener?.("abort", abort, { once: true });
|
|
89
|
+
let body;
|
|
90
|
+
try {
|
|
91
|
+
const input = { params: run.params, target: run.target, dryRun: run.dryRun };
|
|
92
|
+
const ended = context
|
|
93
|
+
.run(scope, async () => main(input))
|
|
94
|
+
.then((output) => ({ status: "succeeded", detail: toJson(output) }));
|
|
95
|
+
body = await Promise.race([ended, flight.stalled]);
|
|
96
|
+
}
|
|
97
|
+
catch (error) {
|
|
98
|
+
body = endingOf(error);
|
|
99
|
+
}
|
|
100
|
+
// Steps still running finish and are recorded before the run reports;
|
|
101
|
+
// none starts from here on.
|
|
102
|
+
runtime.close();
|
|
103
|
+
await flight.idle();
|
|
104
|
+
options.signal?.removeEventListener?.("abort", abort);
|
|
105
|
+
const report = run.finish(JSON.stringify(body));
|
|
106
|
+
return { ...report, events: run.takeEvents() };
|
|
89
107
|
}
|
|
90
|
-
|
|
91
108
|
let addonChecked = false;
|
|
92
|
-
|
|
93
109
|
/**
|
|
94
110
|
* The addon and this package share the orchestrator: one from another
|
|
95
111
|
* version would record and replay steps differently.
|
|
96
112
|
*/
|
|
97
113
|
function checkAddon(native) {
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
114
|
+
if (addonChecked)
|
|
115
|
+
return;
|
|
116
|
+
// An addon from before the check by version has no `orchestratorVersion`.
|
|
117
|
+
const built = typeof native.orchestratorVersion === "function" ? native.orchestratorVersion() : undefined;
|
|
118
|
+
if (built !== ORCHESTRATOR_VERSION) {
|
|
119
|
+
throw new Error("the codemod native addon is from another version than the codemod package; reinstall codemod so both match (in a checkout, rebuild both: `cargo build -p codemod-node` and `pnpm --filter codemod build`)");
|
|
120
|
+
}
|
|
121
|
+
addonChecked = true;
|
|
106
122
|
}
|
|
107
|
-
|
|
123
|
+
const CONSOLE_METHODS = ["log", "info", "debug", "warn", "error"];
|
|
108
124
|
/**
|
|
109
125
|
* Route `console` output of code that runs in a run started with
|
|
110
126
|
* `captureConsole` to the run's logs, by step. Other code is untouched.
|
|
111
127
|
*/
|
|
112
128
|
function captureConsole() {
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
129
|
+
const key = Symbol.for("codemod.host.console");
|
|
130
|
+
const shared = globalThis;
|
|
131
|
+
if (shared[key])
|
|
132
|
+
return;
|
|
133
|
+
shared[key] = true;
|
|
134
|
+
for (const method of CONSOLE_METHODS) {
|
|
135
|
+
const original = console[method].bind(console);
|
|
136
|
+
console[method] = (...items) => {
|
|
137
|
+
const store = context.getStore();
|
|
138
|
+
if (!store?.captureConsole)
|
|
139
|
+
return original(...items);
|
|
140
|
+
store.run.log(store.step?.position ?? null, items.map(formatLogItem).join(" "));
|
|
141
|
+
};
|
|
142
|
+
}
|
|
124
143
|
}
|
|
125
|
-
|
|
126
144
|
function formatLogItem(value) {
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
145
|
+
if (typeof value === "string")
|
|
146
|
+
return value;
|
|
147
|
+
if (value instanceof Error)
|
|
148
|
+
return value.stack || `${value.name}: ${value.message}`;
|
|
149
|
+
try {
|
|
150
|
+
return JSON.stringify(value) ?? String(value);
|
|
151
|
+
}
|
|
152
|
+
catch {
|
|
153
|
+
return String(value);
|
|
154
|
+
}
|
|
134
155
|
}
|
|
135
|
-
|
|
136
156
|
/** Where the workflow is, and how to load it. */
|
|
137
157
|
function locate(workflow, options) {
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
158
|
+
if (typeof workflow !== "string" && !isUrl(workflow)) {
|
|
159
|
+
if (!options.path && !options.workflowDir) {
|
|
160
|
+
throw new TypeError("runWorkflow(module, { path }): give the workflow file's path, so relative task paths resolve");
|
|
161
|
+
}
|
|
162
|
+
// The file need not exist: only its directory matters here.
|
|
163
|
+
const file = options.path
|
|
164
|
+
? resolve(String(options.path))
|
|
165
|
+
: resolve(String(options.workflowDir), "workflow.ts");
|
|
166
|
+
return { path: file, load: async () => workflow };
|
|
143
167
|
}
|
|
144
|
-
|
|
145
|
-
const
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
options.workflowName ?? null,
|
|
154
|
-
);
|
|
155
|
-
if (!/\.m?ts$|\.m?js$/.test(path)) {
|
|
156
|
-
throw new Error(
|
|
157
|
-
`${path} is not a TypeScript workflow; run YAML workflows with the codemod CLI, or upgrade them with \`codemod workflow upgrade\``,
|
|
158
|
-
);
|
|
159
|
-
}
|
|
160
|
-
return { path, load: () => import(pathToFileURL(path).href) };
|
|
168
|
+
const source = isUrl(workflow) ? fileURLToPath(workflow.href) : String(workflow);
|
|
169
|
+
const path = addon().resolveWorkflow(isAbsolute(source) ? source : resolve(source), options.workflowName ?? null);
|
|
170
|
+
if (!/\.m?ts$|\.m?js$/.test(path)) {
|
|
171
|
+
throw new Error(`${path} is not a TypeScript workflow; run YAML workflows with the codemod CLI, or upgrade them with \`codemod workflow upgrade\``);
|
|
172
|
+
}
|
|
173
|
+
return { path, load: () => import(__rewriteRelativeImportExtension(pathToFileURL(path).href)) };
|
|
174
|
+
}
|
|
175
|
+
function isRecord(value) {
|
|
176
|
+
return value !== null && typeof value === "object";
|
|
161
177
|
}
|
|
162
|
-
|
|
178
|
+
// Not `instanceof URL`: test environments may have their own URL class.
|
|
163
179
|
function isUrl(value) {
|
|
164
|
-
|
|
180
|
+
return isRecord(value) && typeof value.href === "string";
|
|
165
181
|
}
|
|
166
|
-
|
|
167
|
-
/**
|
|
168
|
-
* Tracks steps in flight. `stalled` resolves (with `null`) when the run is
|
|
169
|
-
* closed and nothing is running: the body may be waiting on steps that will
|
|
170
|
-
* never start, as after a test's `until` step. `idle()` resolves once nothing
|
|
171
|
-
* is running.
|
|
172
|
-
*/
|
|
173
182
|
function inFlight() {
|
|
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
|
-
|
|
183
|
+
let count = 0;
|
|
184
|
+
let stall = () => { };
|
|
185
|
+
const waiters = [];
|
|
186
|
+
const flight = {
|
|
187
|
+
closed: () => false,
|
|
188
|
+
stalled: new Promise((resolvePromise) => (stall = resolvePromise)),
|
|
189
|
+
begin() {
|
|
190
|
+
count++;
|
|
191
|
+
},
|
|
192
|
+
end() {
|
|
193
|
+
count--;
|
|
194
|
+
flight.check();
|
|
195
|
+
},
|
|
196
|
+
check() {
|
|
197
|
+
setImmediate(() => {
|
|
198
|
+
if (count !== 0)
|
|
199
|
+
return;
|
|
200
|
+
if (flight.closed())
|
|
201
|
+
stall(null);
|
|
202
|
+
for (const waiter of waiters.splice(0))
|
|
203
|
+
waiter();
|
|
204
|
+
});
|
|
205
|
+
},
|
|
206
|
+
idle() {
|
|
207
|
+
return new Promise((resolvePromise) => {
|
|
208
|
+
waiters.push(resolvePromise);
|
|
209
|
+
flight.check();
|
|
210
|
+
});
|
|
211
|
+
},
|
|
212
|
+
};
|
|
213
|
+
return flight;
|
|
203
214
|
}
|
|
204
|
-
|
|
205
215
|
function host(run, flight, runtime) {
|
|
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
|
-
|
|
216
|
+
// Replayed steps settle one per turn of the event loop, so the body reacts
|
|
217
|
+
// to each before the next.
|
|
218
|
+
let replaying = false;
|
|
219
|
+
const replay = () => {
|
|
220
|
+
replaying = runtime().replayNext();
|
|
221
|
+
if (replaying)
|
|
222
|
+
setImmediate(replay);
|
|
223
|
+
};
|
|
224
|
+
return {
|
|
225
|
+
history: () => run.history(),
|
|
226
|
+
record: (entry, ms) => run.record(JSON.stringify(entry), ms),
|
|
227
|
+
event: (event) => run.event(JSON.stringify(event)),
|
|
228
|
+
canceled: () => run.refusesSteps(),
|
|
229
|
+
now: () => Date.now(),
|
|
230
|
+
advanceClock() { },
|
|
231
|
+
testPlan: () => run.testPlan(),
|
|
232
|
+
stop() {
|
|
233
|
+
run.stop();
|
|
234
|
+
flight.check();
|
|
235
|
+
},
|
|
236
|
+
wake() {
|
|
237
|
+
if (replaying)
|
|
238
|
+
return;
|
|
239
|
+
replaying = true;
|
|
240
|
+
setImmediate(replay);
|
|
241
|
+
},
|
|
242
|
+
evaluate: (kind, expression, scope) => run.evaluate(kind, expression, JSON.stringify(scope)),
|
|
243
|
+
callbackId,
|
|
244
|
+
async start(request) {
|
|
245
|
+
const { fn, ...task } = request;
|
|
246
|
+
flight.begin();
|
|
247
|
+
try {
|
|
248
|
+
if (fn)
|
|
249
|
+
return await within(task.timeoutMs, (limit) => runInPlace(run, task, fn, limit));
|
|
250
|
+
try {
|
|
251
|
+
return await run.runTask(JSON.stringify(task));
|
|
252
|
+
}
|
|
253
|
+
catch (error) {
|
|
254
|
+
throw payloadOf(error);
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
finally {
|
|
258
|
+
flight.end();
|
|
259
|
+
}
|
|
260
|
+
},
|
|
261
|
+
};
|
|
247
262
|
}
|
|
248
|
-
|
|
249
263
|
/** A host task rejected with `{ name, message }` as JSON in the message. */
|
|
250
264
|
function payloadOf(error) {
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
265
|
+
const message = isRecord(error) && typeof error.message === "string" ? error.message : undefined;
|
|
266
|
+
try {
|
|
267
|
+
const payload = JSON.parse(message ?? "");
|
|
268
|
+
if (isRecord(payload) && typeof payload.message === "string") {
|
|
269
|
+
return { name: String(payload.name ?? "Error"), message: payload.message };
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
catch {
|
|
273
|
+
// a plain message
|
|
274
|
+
}
|
|
275
|
+
return { name: "Error", message: message ?? String(error) };
|
|
258
276
|
}
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
const
|
|
266
|
-
|
|
277
|
+
/**
|
|
278
|
+
* Run `work` for at most `ms`. JavaScript that is running cannot be stopped
|
|
279
|
+
* from outside: when the time is up the step fails, `limit.expired` tells
|
|
280
|
+
* the work to stop where it can, and whatever it still does is discarded.
|
|
281
|
+
*/
|
|
282
|
+
async function within(ms, work) {
|
|
283
|
+
const limit = { expired: false };
|
|
284
|
+
if (ms === undefined)
|
|
285
|
+
return work(limit);
|
|
286
|
+
let timer;
|
|
287
|
+
const late = new Promise((_, reject) => {
|
|
288
|
+
timer = setTimeout(() => {
|
|
289
|
+
limit.expired = true;
|
|
290
|
+
reject({ name: "Error", message: `timed out after ${describeDuration(ms)}` });
|
|
291
|
+
}, ms);
|
|
292
|
+
});
|
|
267
293
|
try {
|
|
268
|
-
|
|
269
|
-
}
|
|
270
|
-
|
|
271
|
-
|
|
294
|
+
return await Promise.race([work(limit), late]);
|
|
295
|
+
}
|
|
296
|
+
finally {
|
|
297
|
+
clearTimeout(timer);
|
|
272
298
|
}
|
|
273
|
-
// A failure reported with failStep() stands even if the code caught it.
|
|
274
|
-
if (step.failure !== undefined) throw new Error(step.failure);
|
|
275
|
-
const result = value === undefined ? null : value;
|
|
276
|
-
checkJson(result, "the step's result");
|
|
277
|
-
return outcome(result, step);
|
|
278
|
-
}
|
|
279
|
-
if (task.task.kind === "forEachFile") return forEachFile(run, outer, task, fn);
|
|
280
|
-
throw new Error(`cannot run a ${task.task.kind} task in place`);
|
|
281
299
|
}
|
|
282
|
-
|
|
300
|
+
async function runInPlace(run, task, fn, limit) {
|
|
301
|
+
const outer = context.getStore();
|
|
302
|
+
if (!outer)
|
|
303
|
+
throw new Error("a step started outside its run");
|
|
304
|
+
if (task.task.kind === "function") {
|
|
305
|
+
const step = stepScope(task.position, task.label, task.state);
|
|
306
|
+
let value;
|
|
307
|
+
try {
|
|
308
|
+
value = await context.run({ ...outer, step }, () => fn());
|
|
309
|
+
}
|
|
310
|
+
finally {
|
|
311
|
+
// What the step measured counts even when it then fails.
|
|
312
|
+
flushMetrics(run, step);
|
|
313
|
+
}
|
|
314
|
+
// A failure reported with failStep() stands even if the code caught it.
|
|
315
|
+
if (step.failure !== undefined)
|
|
316
|
+
throw new Error(step.failure);
|
|
317
|
+
const result = value === undefined ? null : value;
|
|
318
|
+
checkJson(result, "the step's result");
|
|
319
|
+
return outcome(result, step);
|
|
320
|
+
}
|
|
321
|
+
if (task.task.kind === "forEachFile")
|
|
322
|
+
return forEachFile(run, outer, task, fn, limit);
|
|
323
|
+
throw new Error(`cannot run a ${task.task.kind} task in place`);
|
|
324
|
+
}
|
|
283
325
|
function outcome(result, step) {
|
|
284
|
-
|
|
285
|
-
|
|
326
|
+
const state = stateChanges(step);
|
|
327
|
+
return Object.keys(state).length ? { result, state } : { result };
|
|
286
328
|
}
|
|
287
|
-
|
|
288
329
|
function flushMetrics(run, step) {
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
330
|
+
const metrics = metricsOf(step);
|
|
331
|
+
if (Object.keys(metrics).length)
|
|
332
|
+
run.addMetrics(JSON.stringify(metrics));
|
|
333
|
+
return metrics;
|
|
292
334
|
}
|
|
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
|
-
|
|
335
|
+
async function forEachFile(run, outer, task, fn, limit) {
|
|
336
|
+
const selector = task.task.selector;
|
|
337
|
+
const { language, files } = await run.selectFiles(JSON.stringify(selector));
|
|
338
|
+
const step = stepScope(task.position, task.label, task.state, language ?? undefined);
|
|
339
|
+
const total = files.length;
|
|
340
|
+
const every = Math.max(1, Math.floor(total / 100));
|
|
341
|
+
let processed = 0;
|
|
342
|
+
const outputs = Array.from({ length: total });
|
|
343
|
+
const failures = [];
|
|
344
|
+
const effects = [];
|
|
345
|
+
const concurrency = selector.concurrency ?? 1;
|
|
346
|
+
const one = async (index, [path, text]) => {
|
|
347
|
+
const { file, effects: done, close } = fileHandle(path, text, step.language);
|
|
348
|
+
try {
|
|
349
|
+
step.failure = undefined;
|
|
350
|
+
const output = await context.run({ ...outer, step }, () => fn(file));
|
|
351
|
+
// A failure reported with failFile() stands even if the callback
|
|
352
|
+
// caught it. With files in flight together it cannot be told whose it
|
|
353
|
+
// was, as in the CLI.
|
|
354
|
+
if (step.failure !== undefined && concurrency === 1) {
|
|
355
|
+
failures.push({ path, error: step.failure });
|
|
356
|
+
return;
|
|
357
|
+
}
|
|
358
|
+
if (output !== undefined) {
|
|
359
|
+
checkJson(output, "return value");
|
|
360
|
+
outputs[index] = { output };
|
|
361
|
+
}
|
|
362
|
+
if (done.length)
|
|
363
|
+
effects.push({ path, original: text, effects: done });
|
|
364
|
+
}
|
|
365
|
+
catch (error) {
|
|
366
|
+
failures.push({ path, error: describeError(error) });
|
|
367
|
+
}
|
|
368
|
+
finally {
|
|
369
|
+
close();
|
|
370
|
+
processed++;
|
|
371
|
+
if (processed === total || processed % every === 0) {
|
|
372
|
+
run.progress(task.position, processed, total);
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
};
|
|
376
|
+
let next = 0;
|
|
377
|
+
let sinceTurn = 0;
|
|
378
|
+
const worker = async () => {
|
|
379
|
+
for (;;) {
|
|
380
|
+
const index = next++;
|
|
381
|
+
const file = files[index];
|
|
382
|
+
if (!file)
|
|
383
|
+
return;
|
|
384
|
+
// Callbacks that never wait would keep the event loop to themselves:
|
|
385
|
+
// give it a turn now and then, so a cancel can arrive.
|
|
386
|
+
if (++sinceTurn >= 64) {
|
|
387
|
+
sinceTurn = 0;
|
|
388
|
+
await new Promise((turn) => setImmediate(turn));
|
|
389
|
+
}
|
|
390
|
+
if (run.refusesSteps())
|
|
391
|
+
throw new CanceledError();
|
|
392
|
+
if (limit.expired)
|
|
393
|
+
return;
|
|
394
|
+
await one(index, file);
|
|
395
|
+
}
|
|
396
|
+
};
|
|
397
|
+
await Promise.all(Array.from({ length: Math.min(concurrency, total) }, worker));
|
|
398
|
+
// Out of time: the step has already failed, and nothing it did is written.
|
|
399
|
+
if (limit.expired)
|
|
400
|
+
throw new CanceledError("the step ran out of time");
|
|
401
|
+
// Before the commit: a commit that fails must not lose what was measured.
|
|
402
|
+
const metrics = flushMetrics(run, step);
|
|
403
|
+
effects.sort((a, b) => (a.path < b.path ? -1 : 1));
|
|
404
|
+
const committed = await run.commitFiles(task.position, task.label, JSON.stringify(effects));
|
|
405
|
+
const allFailures = [...failures, ...committed.failures].sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
|
|
406
|
+
// As the CLI does: each file that failed, then its error.
|
|
407
|
+
for (const { path, error } of allFailures) {
|
|
408
|
+
run.log(task.position, path);
|
|
409
|
+
for (const line of error.split("\n"))
|
|
410
|
+
run.log(task.position, ` ${line}`);
|
|
332
411
|
}
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
while (next < total) {
|
|
339
|
-
// Callbacks that never wait would keep the event loop to themselves:
|
|
340
|
-
// give it a turn now and then, so a cancel can arrive.
|
|
341
|
-
if (++sinceTurn >= 64) {
|
|
342
|
-
sinceTurn = 0;
|
|
343
|
-
await new Promise((turn) => setImmediate(turn));
|
|
344
|
-
}
|
|
345
|
-
if (run.refusesSteps()) throw new CanceledError();
|
|
346
|
-
await one(next++);
|
|
412
|
+
// The step fails when the callback failed on every file, and is partial
|
|
413
|
+
// when it failed on some.
|
|
414
|
+
const [first] = allFailures;
|
|
415
|
+
if (first && allFailures.length === total) {
|
|
416
|
+
throw new Error(`the callback failed on every file; first error: ${first.path}: ${first.error}`);
|
|
347
417
|
}
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
outputs: outputs.filter(Boolean).map((entry) => entry.output),
|
|
361
|
-
changes: committed.changes,
|
|
362
|
-
failures: allFailures,
|
|
363
|
-
metrics,
|
|
364
|
-
},
|
|
365
|
-
step,
|
|
366
|
-
);
|
|
418
|
+
const result = outcome({
|
|
419
|
+
outputs: outputs.flatMap((entry) => (entry ? [entry.output] : [])),
|
|
420
|
+
changes: committed.changes,
|
|
421
|
+
failures: allFailures,
|
|
422
|
+
metrics,
|
|
423
|
+
}, step);
|
|
424
|
+
if (!allFailures.length)
|
|
425
|
+
return result;
|
|
426
|
+
return {
|
|
427
|
+
...result,
|
|
428
|
+
partial: `${allFailures.length} of ${total} ${total === 1 ? "file" : "files"} failed`,
|
|
429
|
+
};
|
|
367
430
|
}
|
|
368
|
-
|
|
369
431
|
// -------------------------------------------------------------- ending ---
|
|
370
|
-
|
|
371
432
|
/** How a body that threw ended. */
|
|
372
433
|
function endingOf(error) {
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
434
|
+
const name = isRecord(error) ? error.name : undefined;
|
|
435
|
+
if (error instanceof CanceledError || name === "CanceledError") {
|
|
436
|
+
return { status: "canceled" };
|
|
437
|
+
}
|
|
438
|
+
if (error instanceof AwaitingApprovalError || name === "AwaitingApprovalError") {
|
|
439
|
+
return { status: "awaiting-approval", detail: String(error.message) };
|
|
440
|
+
}
|
|
441
|
+
const message = isRecord(error) && "message" in error
|
|
442
|
+
? `${String(name ?? "Error")}: ${String(error.message)}`
|
|
443
|
+
: String(error);
|
|
444
|
+
return { status: "failed", detail: message };
|
|
384
445
|
}
|
|
385
|
-
|
|
386
446
|
/** A value as JSON keeps it; what JSON has no form for (a function) is null. */
|
|
387
447
|
function toJson(value) {
|
|
388
|
-
|
|
389
|
-
|
|
448
|
+
const text = JSON.stringify(value);
|
|
449
|
+
return text === undefined ? null : JSON.parse(text);
|
|
390
450
|
}
|