@ryuugg/stanza 0.3.0 → 0.3.2

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.
@@ -24,11 +24,84 @@ const javascript: Record<string, ParserOptions> = {
24
24
 
25
25
  const loneCr = /\r(?!\n)/g;
26
26
 
27
+ const RAW_AFTER_LENGTH = 500_000;
28
+ const RAW_MAX_LENGTH = 1_000_000;
29
+ const RAW_COLLECT_EVERY = 1_000_000;
30
+
31
+ let parsedSinceCollect = 0;
32
+
33
+ type Handoff =
34
+ | { kind: "pending"; remaining: number; required: boolean }
35
+ | { kind: "raw"; parseRaw: typeof import("./raw.ts").parseRaw }
36
+ | { kind: "json" }
37
+ | { kind: "unavailable"; error: Error };
38
+
39
+ let handoff: Handoff | undefined;
40
+
27
41
  export function parse(path: string, text: string): Parsed {
28
- const result = parseSync(path, text, javascript[extname(path)]);
42
+ const options = javascript[extname(path)];
43
+ const current = currentHandoff(text.length <= RAW_MAX_LENGTH ? text.length : 0);
44
+ if (current.kind === "unavailable") throw current.error;
45
+
46
+ if (current.kind === "raw") {
47
+ collectWhileRaw(text.length);
48
+
49
+ if (text.length <= RAW_MAX_LENGTH)
50
+ try {
51
+ return current.parseRaw(path, text, options);
52
+ } catch {
53
+ // The raw deserializer recurses and overflows the stack on deep or long inputs that JSON.parse handles.
54
+ }
55
+ }
56
+
57
+ const result = parseSync(path, text, options);
29
58
  return { program: result.program, comments: result.comments, errors: result.errors };
30
59
  }
31
60
 
61
+ function collectWhileRaw(length: number): void {
62
+ parsedSinceCollect += length;
63
+ if (parsedSinceCollect < RAW_COLLECT_EVERY) return;
64
+
65
+ parsedSinceCollect = 0;
66
+ // JSC counts the 4 GiB raw transfer buffer as live heap, so on its own it never collects the ASTs a whole repo run leaves behind.
67
+ Bun.gc(true);
68
+ }
69
+
70
+ function currentHandoff(length: number): Handoff {
71
+ handoff ??= initialHandoff();
72
+ if (handoff.kind === "pending" && (handoff.remaining -= length) <= 0)
73
+ handoff = loadRaw(handoff.required);
74
+
75
+ return handoff;
76
+ }
77
+
78
+ function initialHandoff(): Handoff {
79
+ const mode = process.env.STANZA_RAW_TRANSFER;
80
+ if (mode === "0") return { kind: "json" };
81
+ return {
82
+ kind: "pending",
83
+ remaining: mode === "1" ? 0 : RAW_AFTER_LENGTH,
84
+ required: mode === "1",
85
+ };
86
+ }
87
+
88
+ function loadRaw(required: boolean): Handoff {
89
+ try {
90
+ // A bare require is the one lazy load bun build --compile embeds; createRequire and import.meta.require fail at runtime in the binary.
91
+ const { parseRaw } = require("./raw.ts") as typeof import("./raw.ts");
92
+ parseRaw("probe.js", "", javascript[".js"]);
93
+ return { kind: "raw", parseRaw };
94
+ } catch (cause) {
95
+ if (!required) return { kind: "json" };
96
+
97
+ const error = new Error(`STANZA_RAW_TRANSFER=1 but raw transfer is unavailable: ${cause}`, {
98
+ cause,
99
+ });
100
+
101
+ return { kind: "unavailable", error };
102
+ }
103
+ }
104
+
32
105
  function crLineEnding(text: string, program: Program): number | undefined {
33
106
  if (text.search(loneCr) < 0) return undefined;
34
107
 
@@ -0,0 +1,95 @@
1
+ import type { Comment, OxcError, ParserOptions, Program } from "oxc-parser";
2
+ import { getBufferOffset, parseRawSync, rawTransferSupported } from "oxc-parser/src-js/bindings.js";
3
+ import {
4
+ ACTIVE_SIZE,
5
+ BLOCK_ALIGN,
6
+ BLOCK_SIZE,
7
+ BUFFER_SIZE,
8
+ IS_TS_FLAG_POS,
9
+ } from "oxc-parser/src-js/generated/constants.js";
10
+ import { deserializerFiles } from "./deserializers.ts";
11
+ import type { Parsed } from "./parse.ts";
12
+
13
+ interface RawBuffer extends Uint8Array {
14
+ block: Uint8Array;
15
+ int32: Int32Array;
16
+ float64: Float64Array;
17
+ }
18
+
19
+ interface Deserializer {
20
+ deserialize(
21
+ buffer: RawBuffer,
22
+ text: string,
23
+ sourceStartPos: number,
24
+ sourceByteLen: number,
25
+ ): { program: Program; comments: Comment[]; errors: OxcError[] };
26
+ }
27
+
28
+ const ALLOCATION_ATTEMPTS = 8;
29
+ const MAX_SOURCE_BYTES = 1 << 30;
30
+
31
+ if (!rawTransferSupported()) throw new Error("raw transfer needs a 64-bit little-endian platform");
32
+
33
+ // Required by path, not by literal, so a compiled binary does not parse 330 KB of deserializers on every start.
34
+ const files = deserializerFiles();
35
+ const deserializeJs = (require(files.js) as Deserializer).deserialize;
36
+ const deserializeTs = (require(files.ts) as Deserializer).deserialize;
37
+
38
+ const encoder = new TextEncoder();
39
+
40
+ let shared: RawBuffer | undefined;
41
+ export function parseRaw(path: string, text: string, options?: ParserOptions): Parsed {
42
+ shared ??= createBuffer();
43
+
44
+ const { sourceStartPos, sourceByteLen } = writeSource(shared, text);
45
+ parseRawSync(path, shared.block, sourceStartPos, sourceByteLen, options ?? {});
46
+
47
+ const isJs = shared[IS_TS_FLAG_POS] === 0;
48
+ const deserialize = isJs ? deserializeJs : deserializeTs;
49
+ const { program, comments, errors } = deserialize(shared, text, sourceStartPos, sourceByteLen);
50
+ if (isJs && program.hashbang !== null) {
51
+ const { value, start, end } = program.hashbang;
52
+ comments.unshift({ type: "Line", value, start, end });
53
+ }
54
+
55
+ return { program, comments, errors };
56
+ }
57
+
58
+ function writeSource(
59
+ buffer: RawBuffer,
60
+ text: string,
61
+ ): { sourceStartPos: number; sourceByteLen: number } {
62
+ const maxBytes = text.length * 3;
63
+ if (maxBytes > MAX_SOURCE_BYTES) throw new Error("Source text is too long for raw transfer");
64
+
65
+ const sourceStartPos = ACTIVE_SIZE - maxBytes;
66
+ const target = new Uint8Array(buffer.buffer, buffer.byteOffset + sourceStartPos, maxBytes);
67
+ const { read, written } = encoder.encodeInto(text, target);
68
+ if (read !== text.length) throw new Error("Failed to write source text into the raw buffer");
69
+
70
+ return { sourceStartPos, sourceByteLen: written };
71
+ }
72
+
73
+ function createBuffer(): RawBuffer {
74
+ const { arrayBuffer, offset } = allocate();
75
+
76
+ const buffer = new Uint8Array(arrayBuffer, offset, BUFFER_SIZE) as RawBuffer;
77
+ buffer.int32 = new Int32Array(arrayBuffer, offset, BUFFER_SIZE / 4);
78
+ buffer.float64 = new Float64Array(arrayBuffer, offset, BUFFER_SIZE / 8);
79
+ buffer.block = new Uint8Array(arrayBuffer, offset, BLOCK_SIZE);
80
+ return buffer;
81
+ }
82
+
83
+ // Bun caps an ArrayBuffer at 4 GiB, so the aligned block only fits some starts; the live spacer shifts each retry by 2 GiB.
84
+ function allocate(): { arrayBuffer: ArrayBuffer; offset: number } {
85
+ const spacers: ArrayBuffer[] = [];
86
+ for (let attempt = 0; attempt < ALLOCATION_ATTEMPTS; attempt++) {
87
+ const arrayBuffer = new ArrayBuffer(BLOCK_ALIGN);
88
+ const offset = getBufferOffset(new Uint8Array(arrayBuffer));
89
+ if (offset + BLOCK_SIZE <= BLOCK_ALIGN) return { arrayBuffer, offset };
90
+
91
+ spacers.push(new ArrayBuffer(BLOCK_ALIGN / 2));
92
+ }
93
+
94
+ throw new Error("Failed to allocate a raw transfer buffer aligned on 4 GiB");
95
+ }
package/src/pool.ts ADDED
@@ -0,0 +1,312 @@
1
+ import { availableParallelism } from "node:os";
2
+ import { statSync } from "node:fs";
3
+ import { workerData, type MessagePort } from "node:worker_threads";
4
+ import {
5
+ formatFile,
6
+ mergeOutcomes,
7
+ readText,
8
+ type FileOutcome,
9
+ type FormatRun,
10
+ type Formatted,
11
+ type Input,
12
+ } from "./format.ts";
13
+ import { deepRisk } from "./depth.ts";
14
+ import {
15
+ deserializerFiles,
16
+ embedDeserializers,
17
+ type DeserializerFiles,
18
+ } from "./languages/javascript/deserializers.ts";
19
+
20
+ export const THRESHOLD = 256;
21
+ export const DEFAULT_WORKERS = 3;
22
+ export const CHUNK_SIZE = 64;
23
+
24
+ export interface FileInput extends Omit<Input, "read"> {
25
+ output: string;
26
+ }
27
+
28
+ export interface PoolData<Input, Job> {
29
+ id: number;
30
+ inputs: Input[];
31
+ job: Job;
32
+ chunkSize: number;
33
+ counter: SharedArrayBuffer;
34
+ signal: SharedArrayBuffer;
35
+ claims: SharedArrayBuffer;
36
+ finished: SharedArrayBuffer;
37
+ port: MessagePort;
38
+ addon: string | undefined;
39
+ deserializers: DeserializerFiles;
40
+ }
41
+
42
+ export type ChunkMessage<Result> =
43
+ | (Result & { chunk: number })
44
+ | { chunk: number | undefined; error: string };
45
+
46
+ export interface PoolTask<Input, Outcome, Result extends { outcomes: (Outcome | null)[] }, Job> {
47
+ worker: string | URL;
48
+ job: Job;
49
+ chunkSize?: number;
50
+ chunk(inputs: Input[]): Result;
51
+ merge(result: Result): void;
52
+ item(input: Input): Outcome;
53
+ }
54
+
55
+ export function workerCount(
56
+ fileCount: number,
57
+ env: Readonly<Record<string, string | undefined>>,
58
+ maximum = DEFAULT_WORKERS,
59
+ ): number {
60
+ const override = env.STANZA_WORKERS;
61
+ if (override !== undefined && /^\d+$/.test(override)) {
62
+ const count = Number(override);
63
+ if (count <= 64) return count;
64
+ }
65
+
66
+ if (fileCount < THRESHOLD) return 0;
67
+
68
+ return Math.max(0, Math.min(maximum, availableParallelism() - 1));
69
+ }
70
+
71
+ export function hardLinked(input: FileInput, run: FormatRun): boolean {
72
+ if (run.mode !== "fix" || !run.write) return false;
73
+
74
+ try {
75
+ return statSync(input.path).nlink > 1;
76
+ } catch {
77
+ return false;
78
+ }
79
+ }
80
+
81
+ export function tooDeep(path: string, text: string): boolean {
82
+ return deepRisk(text, !/\.[cm]?ts$/.test(path));
83
+ }
84
+
85
+ export function formatChunk(inputs: FileInput[], run: FormatRun, inWorker: boolean) {
86
+ const warnings = { unread: new Set<string>(), unreadWidth: new Set<string>() };
87
+ const outcomes = inputs.map((input) => {
88
+ if (hardLinked(input, run)) return null;
89
+
90
+ const text = readText(input.path);
91
+ if (inWorker && typeof text === "string" && tooDeep(input.path, text)) return null;
92
+
93
+ return formatFile({ ...input, read: () => text }, run, input.output, warnings);
94
+ });
95
+
96
+ return { outcomes, unread: [...warnings.unread], unreadWidth: [...warnings.unreadWidth] };
97
+ }
98
+
99
+ function acceptChunk<Input, Outcome, Result extends { outcomes: (Outcome | null)[] }, Job>(
100
+ inputCount: number,
101
+ chunkSize: number,
102
+ message: ChunkMessage<Result>,
103
+ chunks: (Outcome | null)[][],
104
+ task: PoolTask<Input, Outcome, Result, Job>,
105
+ errors: string[],
106
+ ): void {
107
+ if ("error" in message) {
108
+ errors.push(message.error);
109
+ if (message.chunk === undefined) return;
110
+
111
+ const size = Math.min(chunkSize, inputCount - message.chunk * chunkSize);
112
+ chunks[message.chunk] = Array<null>(size).fill(null);
113
+ return;
114
+ }
115
+
116
+ chunks[message.chunk] = message.outcomes;
117
+ task.merge(message);
118
+ }
119
+
120
+ function recoverAbandoned<Outcome>(
121
+ inputCount: number,
122
+ chunkSize: number,
123
+ chunks: (Outcome | null)[][],
124
+ claims: Int32Array,
125
+ stopped: boolean[],
126
+ errors: string[],
127
+ ): number {
128
+ let recovered = 0;
129
+ for (let chunk = 0; chunk < claims.length; chunk++) {
130
+ const owner = Atomics.load(claims, chunk);
131
+ if (chunks[chunk] !== undefined || owner === 0 || !stopped[owner - 1]) continue;
132
+
133
+ const size = Math.min(chunkSize, inputCount - chunk * chunkSize);
134
+ chunks[chunk] = Array<null>(size).fill(null);
135
+ errors.push("a worker thread stopped before reporting its files, so main formatted them");
136
+ recovered++;
137
+ }
138
+
139
+ return recovered;
140
+ }
141
+
142
+ export function runPooled<Input, Outcome, Result extends { outcomes: (Outcome | null)[] }, Job>(
143
+ inputs: Input[],
144
+ task: PoolTask<Input, Outcome, Result, Job>,
145
+ count: number,
146
+ ): { outcomes: Outcome[]; errors: string[] } {
147
+ const { Worker, MessageChannel, receiveMessageOnPort } =
148
+ require("node:worker_threads") as typeof import("node:worker_threads");
149
+
150
+ const counter = new Int32Array(new SharedArrayBuffer(4));
151
+ const signal = new Int32Array(new SharedArrayBuffer(4));
152
+
153
+ const chunkSize = task.chunkSize ?? CHUNK_SIZE;
154
+ const chunkCount = Math.ceil(inputs.length / chunkSize);
155
+ const claims = new Int32Array(new SharedArrayBuffer(4 * chunkCount));
156
+ const finished = new Int32Array(new SharedArrayBuffer(4 * Math.max(count, 1)));
157
+ const chunks: (Outcome | null)[][] = Array(chunkCount);
158
+
159
+ const errors: string[] = [];
160
+ const ports: MessagePort[] = [];
161
+ const deserializers = deserializerFiles();
162
+ for (let index = 0; index < count; index++) {
163
+ const { port1, port2 } = new MessageChannel();
164
+ try {
165
+ const workerData: PoolData<Input, Job> = {
166
+ id: index,
167
+ inputs,
168
+ job: task.job,
169
+ chunkSize,
170
+ counter: counter.buffer as SharedArrayBuffer,
171
+ signal: signal.buffer as SharedArrayBuffer,
172
+ claims: claims.buffer as SharedArrayBuffer,
173
+ finished: finished.buffer as SharedArrayBuffer,
174
+ port: port2,
175
+ addon: process.env.NAPI_RS_NATIVE_LIBRARY_PATH,
176
+ deserializers,
177
+ };
178
+
179
+ const worker = new Worker(task.worker, { workerData, transferList: [port2] });
180
+ worker.on("error", (error: Error) => errors.push(error.message));
181
+ worker.unref();
182
+ ports.push(port1);
183
+ } catch (error: unknown) {
184
+ errors.push(error instanceof Error ? error.message : String(error));
185
+ port1.close();
186
+ port2.close();
187
+ }
188
+ }
189
+
190
+ let completed = 0;
191
+ while (completed < chunkCount) {
192
+ const observed = Atomics.load(signal, 0);
193
+ const stopped = Array.from(finished, (_, index) => Atomics.load(finished, index) === 1);
194
+
195
+ for (const port of ports) {
196
+ let received: ReturnType<typeof receiveMessageOnPort>;
197
+ while ((received = receiveMessageOnPort(port)) !== undefined) {
198
+ const message = received.message as ChunkMessage<Result>;
199
+ acceptChunk(inputs.length, chunkSize, message, chunks, task, errors);
200
+ if (message.chunk !== undefined) completed++;
201
+ }
202
+ }
203
+
204
+ const chunk = Atomics.add(counter, 0, 1);
205
+ if (chunk < chunkCount) {
206
+ try {
207
+ const result = task.chunk(inputs.slice(chunk * chunkSize, (chunk + 1) * chunkSize));
208
+ acceptChunk(inputs.length, chunkSize, { chunk, ...result }, chunks, task, errors);
209
+ } catch (error: unknown) {
210
+ acceptChunk(
211
+ inputs.length,
212
+ chunkSize,
213
+ { chunk, error: error instanceof Error ? error.message : String(error) },
214
+ chunks,
215
+ task,
216
+ errors,
217
+ );
218
+ }
219
+
220
+ completed++;
221
+ continue;
222
+ }
223
+
224
+ completed += recoverAbandoned(inputs.length, chunkSize, chunks, claims, stopped, errors);
225
+ if (completed < chunkCount) Atomics.wait(signal, 0, observed, 50);
226
+ }
227
+
228
+ const outcomes: Outcome[] = [];
229
+ for (let chunk = 0; chunk < chunks.length; chunk++)
230
+ for (const [offset, outcome] of chunks[chunk]!.entries()) {
231
+ const input = inputs[chunk * chunkSize + offset]!;
232
+ outcomes.push(outcome ?? task.item(input));
233
+ }
234
+
235
+ for (const port of ports) port.close();
236
+
237
+ return { outcomes, errors };
238
+ }
239
+
240
+ export function serveChunks<Input, Job, Result>(work: (inputs: Input[], job: Job) => Result): void {
241
+ const data = workerData as PoolData<Input, Job>;
242
+ const counter = new Int32Array(data.counter);
243
+ const signal = new Int32Array(data.signal);
244
+ const claims = new Int32Array(data.claims);
245
+ const finished = new Int32Array(data.finished);
246
+ function post(message: ChunkMessage<Result>): void {
247
+ data.port.postMessage(message);
248
+ Atomics.add(signal, 0, 1);
249
+ Atomics.notify(signal, 0);
250
+ }
251
+
252
+ try {
253
+ if (data.addon !== undefined) process.env.NAPI_RS_NATIVE_LIBRARY_PATH = data.addon;
254
+ embedDeserializers(data.deserializers);
255
+
256
+ const chunkCount = Math.ceil(data.inputs.length / data.chunkSize);
257
+ for (
258
+ let chunk = Atomics.add(counter, 0, 1);
259
+ chunk < chunkCount;
260
+ chunk = Atomics.add(counter, 0, 1)
261
+ ) {
262
+ Atomics.store(claims, chunk, data.id + 1);
263
+
264
+ try {
265
+ const result = work(
266
+ data.inputs.slice(chunk * data.chunkSize, (chunk + 1) * data.chunkSize),
267
+ data.job,
268
+ );
269
+
270
+ post({ chunk, ...result });
271
+ } catch (error: unknown) {
272
+ post({ chunk, error: error instanceof Error ? error.message : String(error) });
273
+ }
274
+ }
275
+ } catch (error: unknown) {
276
+ post({ chunk: undefined, error: error instanceof Error ? error.message : String(error) });
277
+ } finally {
278
+ Atomics.store(finished, data.id, 1);
279
+ Atomics.add(signal, 0, 1);
280
+ Atomics.notify(signal, 0);
281
+ }
282
+ }
283
+
284
+ export function formatPooled(
285
+ inputs: FileInput[],
286
+ run: FormatRun,
287
+ count: number,
288
+ ): { formatted: Formatted; errors: string[] } {
289
+ const warnings = { unread: new Set<string>(), unreadWidth: new Set<string>() };
290
+ // A compiled Bun worker resolves a bare specifier inside bunfs, not a file URL.
291
+ const specifier = Bun.main.includes("/$bunfs/")
292
+ ? "./worker.ts"
293
+ : new URL("./worker.ts", import.meta.url);
294
+
295
+ const { outcomes, errors } = runPooled(
296
+ inputs,
297
+ {
298
+ worker: specifier,
299
+ job: run,
300
+ chunk: (inputs) => formatChunk(inputs, run, false),
301
+ merge(result) {
302
+ for (const path of result.unread) warnings.unread.add(path);
303
+ for (const path of result.unreadWidth) warnings.unreadWidth.add(path);
304
+ },
305
+ item: (input): FileOutcome =>
306
+ formatFile({ ...input, read: () => readText(input.path) }, run, input.output, warnings),
307
+ },
308
+ count,
309
+ );
310
+
311
+ return { formatted: mergeOutcomes(outcomes, warnings), errors };
312
+ }
package/src/step.ts CHANGED
@@ -88,7 +88,12 @@ export function formatText(path: string, text: Decoded, options: StepOptions): S
88
88
 
89
89
  const changed = options.mode === "fix" && !result.parseError && result.text !== text;
90
90
  if (changed) {
91
- const error = languageOf(path).parse(path, withoutMark(result.text)).error;
91
+ const body = withoutMark(result.text);
92
+ const error =
93
+ body === result.lastParse.text
94
+ ? result.lastParse.error
95
+ : languageOf(path).parse(path, body).error;
96
+
92
97
  if (error)
93
98
  return failure(
94
99
  path,
package/src/usage.ts CHANGED
@@ -13,11 +13,14 @@ export const flags: (readonly [string, string])[] = [
13
13
  "--stdin <path>",
14
14
  "source on stdin; --fix: fixed text on stdout, findings on stderr; --check: findings on stdout",
15
15
  ],
16
- ["--json", "findings as a JSON array, for hooks"],
16
+ ["--json", "findings as a JSON array"],
17
17
  ["--braces", "turn on the braces rule even when lint config turns it off or cannot be read"],
18
18
  ["--no-braces", "turn off the braces rule, keep the blank line rules"],
19
19
  ["explain <file>:<line>", "which rule decides the gap or braced body at that line, and why"],
20
- ["hook", "the Stop hook and PreToolUse hook on Write, reads JSON on stdin"],
20
+ [
21
+ "hook",
22
+ "Stop and SubagentStop; PostToolUse on Edit, MultiEdit and Codex apply_patch; PreToolUse on Write; reads JSON on stdin",
23
+ ],
21
24
  ["--help", "usage, flags and the rule catalog"],
22
25
  ["--version", "the version, and for a built binary the commit it was built from"],
23
26
  ];
package/src/worker.ts ADDED
@@ -0,0 +1,4 @@
1
+ import { formatChunk, serveChunks, type FileInput } from "./pool.ts";
2
+ import type { FormatRun } from "./format.ts";
3
+
4
+ serveChunks((inputs: FileInput[], run: FormatRun) => formatChunk(inputs, run, true));