@ryuugg/stanza 0.1.2 → 0.3.0

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ryuugg/stanza",
3
- "version": "0.1.2",
3
+ "version": "0.3.0",
4
4
  "description": "An opinionated code formatter for TypeScript.",
5
5
  "keywords": [
6
6
  "formatter",
package/src/cli.ts CHANGED
@@ -32,12 +32,15 @@ import {
32
32
  } from "./files.ts";
33
33
  import { explain } from "./engine/explain.ts";
34
34
  import { languageOf } from "./languages/index.ts";
35
- import { blockReason, claudeCodeHooks, hookInput, rereadLine, writtenFiles } from "./hook.ts";
35
+ import { blockReason, claudeCodeHooks, hookCall, rereadLine, type HookCall } from "./hook.ts";
36
+ import { systemIo, type Io } from "./start.ts";
36
37
  import type { Changed } from "./engine/model.ts";
37
38
  import { RULES } from "./engine/rules.ts";
38
39
  import { decode, type Decoded, formatText, withoutMark } from "./step.ts";
39
40
  import { compareFindings, type Braces, type Finding, type Mode } from "./engine/types.ts";
40
- import { columns, flags, usage } from "./usage.ts";
41
+ import { bothBraces, columns, flags, usage } from "./usage.ts";
42
+
43
+ export type { Io } from "./start.ts";
41
44
 
42
45
  declare const STANZA_COMMIT: string | undefined;
43
46
 
@@ -58,16 +61,6 @@ interface ExplainArguments {
58
61
  noBraces: boolean;
59
62
  }
60
63
 
61
- type Writer = (chunk: string | Uint8Array) => void;
62
-
63
- export interface Io {
64
- cwd: string;
65
- env: Readonly<Record<string, string | undefined>>;
66
- stdin: () => Uint8Array;
67
- stdout: Writer;
68
- stderr: Writer;
69
- }
70
-
71
64
  interface Input {
72
65
  path: string;
73
66
  read: () => Decoded;
@@ -91,32 +84,8 @@ interface Formatted {
91
84
  unreadWidth: Set<string>;
92
85
  }
93
86
 
94
- function ignoreBrokenPipe(error: NodeJS.ErrnoException): void {
95
- if (error.code !== "EPIPE") throw error;
96
- }
97
-
98
- export function systemIo(): Io {
99
- // Under Bun a stream write throws EPIPE into a stack trace and exit 1, where console.log swallowed it.
100
- process.stdout.on("error", ignoreBrokenPipe);
101
- process.stderr.on("error", ignoreBrokenPipe);
102
-
103
- return {
104
- cwd: process.cwd(),
105
- env: process.env,
106
- stdin: () => readFileSync(0),
107
- stdout: (chunk) => {
108
- process.stdout.write(chunk);
109
- },
110
- stderr: (chunk) => {
111
- process.stderr.write(chunk);
112
- },
113
- };
114
- }
115
-
116
87
  const switches = new Set(["--braces", "--changed", "--hunks", "--json", "--no-braces", "--staged"]);
117
88
  const standalone = new Set(["--help", "-h", "--version"]);
118
- const hookSwitches = new Set(["--braces", "--hunks", "--no-braces"]);
119
- const bothBraces = "use one of --braces or --no-braces";
120
89
 
121
90
  function help(): string {
122
91
  const rules = Object.entries(RULES).map(([id, rule]) => [
@@ -725,16 +694,11 @@ function fixChanged(
725
694
  }
726
695
 
727
696
  function runStopHook(
728
- input: { cwd: string; stopHookActive: boolean; transcriptPath: string | undefined },
697
+ input: { cwd: string; written: Set<string> | undefined },
729
698
  args: string[],
730
699
  io: Io,
731
700
  ): number {
732
- if (input.stopHookActive) return 0;
733
-
734
- const written =
735
- input.transcriptPath === undefined ? undefined : writtenFiles(input.transcriptPath);
736
-
737
- const result = fixChanged(input.cwd, written, args, io);
701
+ const result = fixChanged(input.cwd, input.written, args, io);
738
702
  if (typeof result === "number") return result;
739
703
 
740
704
  const reason = blockReason(result.findings, result.rewritten);
@@ -761,32 +725,14 @@ function runEditHook(input: { cwd: string; paths: string[] }, args: string[], io
761
725
  }
762
726
 
763
727
  function runHook(args: string[], io: Io): number {
764
- if (io.env.AGENT_HOOKS === "0") return 0;
765
-
766
- const unexpected = args.find(
767
- (arg, index) => !hookSwitches.has(arg) || args.indexOf(arg) !== index,
768
- );
769
-
770
- if (unexpected !== undefined) {
771
- warn(io, `stanza hook: unexpected argument ${unexpected}\n${usage}`);
772
- return 1;
773
- }
774
-
775
- if (args.includes("--braces") && args.includes("--no-braces")) {
776
- warn(io, `stanza hook: ${bothBraces}\n${usage}`);
777
- return 1;
778
- }
779
-
780
- const input = hookInput(Buffer.from(io.stdin()).toString("utf8"), io.cwd);
781
- if ("error" in input) {
782
- warn(io, `stanza hook: ${input.error}`);
783
- return 1;
784
- }
728
+ const call = hookCall(args, io);
729
+ return typeof call === "number" ? call : runHookCall(call, args, io);
730
+ }
785
731
 
786
- if (input.event === "ignored") return 0;
787
- if (input.event === "write") return runWriteHook(input.cwd, input.toolInput, args, io);
788
- if (input.event === "edit") return runEditHook(input, args, io);
789
- return runStopHook(input, args, io);
732
+ export function runHookCall(call: HookCall, args: string[], io: Io): number {
733
+ if (call.event === "write") return runWriteHook(call.cwd, call.toolInput, args, io);
734
+ if (call.event === "edit") return runEditHook(call, args, io);
735
+ return runStopHook(call, args, io);
790
736
  }
791
737
 
792
738
  export function main(argv: string[], io: Io): number {
package/src/compiled.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  export async function start(addon: string): Promise<void> {
2
2
  // Must precede any oxc-parser import (its loader cannot find the binding in a compiled binary), hence the dynamic import.
3
3
  process.env.NAPI_RS_NATIVE_LIBRARY_PATH = addon;
4
- const { main, systemIo } = await import("./cli.ts");
5
- process.exitCode = main(process.argv.slice(2), systemIo());
4
+ const { start } = await import("./start.ts");
5
+ process.exitCode = await start(process.argv.slice(2));
6
6
  }
@@ -150,5 +150,8 @@ export function freeze(
150
150
  for (const list of lists)
151
151
  for (const stmt of list.stmts) if (within(frozen, stmt.start)) stmt.frozen = true;
152
152
 
153
- return { lists: lists.filter((list) => !within(frozen, list.start)), frozen };
153
+ return {
154
+ lists: lists.filter((list) => list.kind === "module" || !within(frozen, list.start)),
155
+ frozen,
156
+ };
154
157
  }
@@ -29,7 +29,6 @@ interface Traced extends Trace {
29
29
  }
30
30
 
31
31
  const LABEL = 11;
32
-
33
32
  function field(label: string, text: string): string {
34
33
  return `${label ? `${label}:` : ""}`.padEnd(LABEL) + text;
35
34
  }
@@ -51,7 +51,7 @@ function declarationJoin(prev: Stmt, next: Stmt): Ruled | null {
51
51
 
52
52
  function shortBody(list: StatementList): boolean {
53
53
  return (
54
- list.kind !== "switch" &&
54
+ list.kind === "block" &&
55
55
  list.stmts.length >= 2 &&
56
56
  list.stmts.length <= 3 &&
57
57
  list.stmts.every((stmt) => stmt.compact)
@@ -68,7 +68,10 @@ const LADDER: Step[] = [
68
68
  prev.guard && next.guard && prev.compact && next.compact
69
69
  ? { want: "none", rule: "guard-chain" }
70
70
  : null,
71
- (_list, prev) => (prev.multiline ? { want: "at-least-one", rule: "after-multiline" } : null),
71
+ (_list, prev, next) =>
72
+ prev.multiline && (prev.kind !== "import" || next.kind !== "import")
73
+ ? { want: "at-least-one", rule: "after-multiline" }
74
+ : null,
72
75
  (list, prev) =>
73
76
  list.kind === "switch" && prev.kind === "case" && prev.caseBody
74
77
  ? { want: "at-least-one", rule: "switch-clauses" }
@@ -271,7 +274,8 @@ function walls(
271
274
  (gap.decision.want === "keep" && gap.blank > 0)
272
275
  : gap.decision.want === "frozen" || gap.blank > 0);
273
276
 
274
- if (!stmt || stmt.multiline || separated) {
277
+ const counted = stmt && !stmt.multiline && stmt.kind !== "import";
278
+ if (!counted || separated) {
275
279
  if (runStart && length >= 6 && touches(runStart.startLine, list.stmts[index - 1]!.endLine))
276
280
  findings.push(finding(doc, runStart.start, "wall"));
277
281
 
@@ -279,7 +283,7 @@ function walls(
279
283
  length = 0;
280
284
  }
281
285
 
282
- if (!stmt || stmt.multiline) continue;
286
+ if (!counted) continue;
283
287
 
284
288
  runStart ??= stmt;
285
289
  length++;
@@ -51,7 +51,6 @@ function unbracedCode(line: string): string {
51
51
  }
52
52
 
53
53
  const editLimit = 2000;
54
-
55
54
  function shortestEdit(before: number[], after: number[]): [number, number][] | undefined {
56
55
  const offset = editLimit + 1;
57
56
  const reach = new Int32Array(2 * offset + 1);
@@ -148,7 +148,6 @@ export interface Trace {
148
148
  }
149
149
 
150
150
  const NO_BRACES: BracePass = { edits: [], findings: [] };
151
-
152
151
  export function traceFix(
153
152
  language: Language,
154
153
  original: Doc,
@@ -29,6 +29,7 @@ export type Kind =
29
29
  | "break"
30
30
  | "continue"
31
31
  | "expression"
32
+ | "import"
32
33
  | "other";
33
34
 
34
35
  export type Path = [string, ...string[]];
@@ -64,7 +65,7 @@ export interface Stmt<Node = unknown> extends Item<Node> {
64
65
  detached: boolean;
65
66
  }
66
67
 
67
- export type ListKind = "block" | "switch";
68
+ export type ListKind = "block" | "switch" | "module";
68
69
 
69
70
  export interface StatementList<Node = unknown> {
70
71
  kind: ListKind;
package/src/files.ts CHANGED
@@ -12,7 +12,6 @@ export interface Collected {
12
12
  }
13
13
 
14
14
  let gitAvailable: boolean | undefined;
15
-
16
15
  function hasGit(): boolean {
17
16
  return (gitAvailable ??= Bun.which("git") !== null);
18
17
  }
package/src/gitignore.ts CHANGED
@@ -4,6 +4,7 @@ type CharacterSet = {
4
4
  classes: string[];
5
5
  negated: boolean;
6
6
  };
7
+
7
8
  type Token =
8
9
  | { kind: "literal"; value: string }
9
10
  | { kind: "star" | "globstar" | "directories" | "any" }
package/src/hook.ts CHANGED
@@ -1,7 +1,64 @@
1
- import { readFileSync, readdirSync } from "node:fs";
1
+ import { readFileSync, readdirSync, realpathSync } from "node:fs";
2
2
  import { basename, dirname, isAbsolute, join, resolve } from "node:path";
3
- import { RULES } from "./engine/rules.ts";
4
3
  import type { Finding } from "./engine/types.ts";
4
+ import { isCandidate } from "./languages/index.ts";
5
+ import type { Io } from "./start.ts";
6
+ import { bothBraces, usage } from "./usage.ts";
7
+
8
+ export type HookCall =
9
+ | {
10
+ event: "write";
11
+ cwd: string;
12
+ toolInput: { file_path: string; content: string } & Record<string, unknown>;
13
+ }
14
+ | { event: "edit"; cwd: string; paths: string[] }
15
+ | { event: "stop"; cwd: string; written: Set<string> | undefined };
16
+
17
+ const hookSwitches = new Set(["--braces", "--hunks", "--no-braces"]);
18
+
19
+ function isCandidateFile(path: string): boolean {
20
+ try {
21
+ return isCandidate(basename(realpathSync(path)));
22
+ } catch {
23
+ return false;
24
+ }
25
+ }
26
+
27
+ export function hookCall(args: string[], io: Io): HookCall | number {
28
+ if (io.env.AGENT_HOOKS === "0") return 0;
29
+
30
+ const unexpected = args.find(
31
+ (arg, index) => !hookSwitches.has(arg) || args.indexOf(arg) !== index,
32
+ );
33
+
34
+ if (unexpected !== undefined) {
35
+ io.stderr(`stanza hook: unexpected argument ${unexpected}\n${usage}\n`);
36
+ return 1;
37
+ }
38
+
39
+ if (args.includes("--braces") && args.includes("--no-braces")) {
40
+ io.stderr(`stanza hook: ${bothBraces}\n${usage}\n`);
41
+ return 1;
42
+ }
43
+
44
+ const input = hookInput(Buffer.from(io.stdin()).toString("utf8"), io.cwd);
45
+ if ("error" in input) {
46
+ io.stderr(`stanza hook: ${input.error}\n`);
47
+ return 1;
48
+ }
49
+
50
+ if (input.event === "ignored") return 0;
51
+ if (input.event === "write") return isCandidate(basename(input.toolInput.file_path)) ? input : 0;
52
+ if (input.event === "edit") return input.paths.some(isCandidateFile) ? input : 0;
53
+ if (input.stopHookActive) return 0;
54
+
55
+ const written =
56
+ input.transcriptPath === undefined ? undefined : writtenFiles(input.transcriptPath);
57
+
58
+ if (written !== undefined && ![...written].some(isCandidateFile)) return 0;
59
+
60
+ return { event: "stop", cwd: input.cwd, written };
61
+ }
5
62
 
6
63
  export const claudeCodeHooks =
7
64
  '{ "hooks": { "PreToolUse": [{ "matcher": "Write", "hooks": [{ "type": "command", "command": "stanza hook" }] }], "PostToolUse": [{ "matcher": "Edit|MultiEdit", "hooks": [{ "type": "command", "command": "stanza hook" }] }], "Stop": [{ "hooks": [{ "type": "command", "command": "stanza hook" }] }] } }';
@@ -80,7 +137,6 @@ export function hookInput(
80
137
  const events = new Set(["Stop", "SubagentStop", "PreToolUse", "PostToolUse"]);
81
138
  const patchHeader = /^\*\*\* (Add File|Update File|Move to): (.+)$/;
82
139
  const patchApplied = /^Success\. Updated the following files:$/m;
83
-
84
140
  function editedPaths(input: Record<string, unknown>): string[] {
85
141
  const toolInput = input.tool_input;
86
142
  if (!isRecord(toolInput)) return [];
@@ -228,7 +284,6 @@ function writtenFilesInTranscript(text: string): Set<string> | undefined {
228
284
  }
229
285
 
230
286
  const editTools = new Set(["Write", "Edit", "MultiEdit"]);
231
-
232
287
  function editedPath(item: Record<string, unknown>): string | undefined {
233
288
  if (item.type !== "tool_use" || !editTools.has(String(item.name))) return undefined;
234
289
  if (!isRecord(item.input) || typeof item.input.file_path !== "string") return undefined;
@@ -244,6 +299,8 @@ const failures: Partial<Record<Finding["rule"], string>> = {
244
299
  export function blockReason(findings: Finding[], rewritten: string[]): string | undefined {
245
300
  if (findings.length === 0) return undefined;
246
301
 
302
+ const { RULES } = require("./engine/rules.ts") as typeof import("./engine/rules.ts");
303
+
247
304
  const shown = findings.slice(0, 12);
248
305
  const lines = shown.map((finding) => {
249
306
  const failure = failures[finding.rule];
@@ -6,6 +6,7 @@ const entries: Entry[] = [javascript];
6
6
  const byExtension = new Map(
7
7
  entries.flatMap((entry) => entry.extensions.map((extension) => [extension, entry] as const)),
8
8
  );
9
+
9
10
  export const extensions = [...byExtension.keys()];
10
11
 
11
12
  export function entryFor(path: string): Entry | undefined {
@@ -20,7 +20,6 @@ const identities = new WeakMap<string[], Map<boolean, PatternList>>();
20
20
  const allExtensions = [...entry.extensions];
21
21
 
22
22
  const expansionLimit = 256;
23
-
24
23
  function expand(pattern: string, limit = expansionLimit): string[] | undefined {
25
24
  const match = /\{([^{}]+)\}/.exec(pattern);
26
25
  if (!match) return [pattern];
@@ -327,7 +327,6 @@ export function fileLayers(file: string, context: Context): { layers: Layer[]; r
327
327
  }
328
328
 
329
329
  const manifestConfigs = new Map<string, Value>();
330
-
331
330
  export function eslintConfig(manifest: string): Value {
332
331
  if (manifestConfigs.has(manifest)) return manifestConfigs.get(manifest);
333
332
 
@@ -14,6 +14,7 @@ type Editor = {
14
14
  root: boolean;
15
15
  sections: { pattern: string | null; values: Record<string, string> }[];
16
16
  };
17
+
17
18
  type FormatKeys = {
18
19
  width: string;
19
20
  tab: string;
@@ -73,6 +74,7 @@ const parsed = new Map<string, Read>();
73
74
  const directories = new Map<string, Directory>();
74
75
  const dependencies = new Map<string, Formatter[]>();
75
76
  const globs = new Map<string, Bun.Glob>();
77
+
76
78
  const editorGlobs = new Map<string, { regex: RegExp; ranges: [bigint, bigint][] }>();
77
79
  const editors = new Map<string, Editor | null>();
78
80
  const widths = new Map<string, Width>();
@@ -42,7 +42,22 @@ const JUMPS: Record<string, string> = {
42
42
  BreakStatement: "break",
43
43
  };
44
44
 
45
+ function exported(node: Statement | SwitchCase): Statement | SwitchCase {
46
+ if (node.type === "ExportNamedDeclaration" && node.declaration) return node.declaration;
47
+ if (node.type === "ExportDefaultDeclaration" && node.declaration.type === "FunctionDeclaration")
48
+ return node.declaration;
49
+
50
+ return node;
51
+ }
52
+
45
53
  function kindOf(node: Statement | SwitchCase): Kind {
54
+ if (
55
+ node.type === "ImportDeclaration" ||
56
+ node.type === "ExportAllDeclaration" ||
57
+ (node.type === "ExportNamedDeclaration" && node.source)
58
+ )
59
+ return "import";
60
+
46
61
  if (node.type === "ExpressionStatement")
47
62
  return node.expression.type === "AssignmentExpression" ? "assignment" : "expression";
48
63
 
@@ -251,18 +266,19 @@ export function facts(
251
266
  node: Statement | SwitchCase,
252
267
  width: Layout,
253
268
  ): Item<Statement | SwitchCase> {
269
+ const inner = exported(node);
254
270
  const finalizer = node.type === "TryStatement" ? node.finalizer : null;
255
271
  const joined = joinedColumns(doc, node, width);
256
272
  return {
257
273
  node,
258
274
  start: node.start,
259
275
  end: node.end,
260
- kind: kindOf(node),
261
- word: WORDS[node.type] ?? null,
262
- binds: bindsOf(doc, node),
276
+ kind: kindOf(inner),
277
+ word: WORDS[inner.type] ?? null,
278
+ binds: bindsOf(doc, inner),
263
279
  declaration:
264
- node.type === "VariableDeclaration"
265
- ? { keyword: node.kind, letLike: node.kind === "let" }
280
+ inner.type === "VariableDeclaration"
281
+ ? { keyword: inner.kind, letLike: inner.kind === "let" }
266
282
  : null,
267
283
  guard: guardOf(node),
268
284
  compact:
@@ -271,8 +287,8 @@ export function facts(
271
287
  joined,
272
288
  caseBody: node.type === "SwitchCase" && node.consequent.length > 0,
273
289
  operation: operation(doc, node),
274
- references: (names) => references(node, names),
275
- readsPath: (path) => readsPath(doc, node, path),
290
+ references: (names) => references(inner, names),
291
+ readsPath: (path) => readsPath(doc, inner, path),
276
292
  finallyRepeats: (expected) => finalizer !== null && repeatsOperation(doc, finalizer, expected),
277
293
  };
278
294
  }
@@ -8,6 +8,21 @@ import type { Layout } from "../language.ts";
8
8
  export type List = StatementList<Statement | SwitchCase>;
9
9
 
10
10
  export function listAt(doc: Doc, node: Node, width: Layout): List | undefined {
11
+ if (node.type === "Program")
12
+ return {
13
+ kind: "module",
14
+ start: node.start,
15
+ end: node.end,
16
+ openLine: null,
17
+ closeLine: null,
18
+ stmts: attach(
19
+ doc,
20
+ node.body.map((stmt) => facts(doc, stmt, width)),
21
+ node.start,
22
+ node.end,
23
+ ),
24
+ };
25
+
11
26
  if (node.type === "BlockStatement" || node.type === "StaticBlock") {
12
27
  const start =
13
28
  node.type === "StaticBlock" ? nextToken(doc, node.start + "static".length) : node.start;
package/src/launcher CHANGED
@@ -17,5 +17,5 @@ if (!Bun.semver.satisfies(Bun.version, ">=1.4.0")) {
17
17
  process.exit(process.argv[2] === "hook" ? 1 : 2);
18
18
  }
19
19
 
20
- const { main, systemIo } = await import("./cli.ts");
21
- process.exitCode = main(process.argv.slice(2), systemIo());
20
+ const { start } = await import("./start.ts");
21
+ process.exitCode = await start(process.argv.slice(2));
package/src/start.ts ADDED
@@ -0,0 +1,49 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { hookCall } from "./hook.ts";
3
+
4
+ type Writer = (chunk: string | Uint8Array) => void;
5
+
6
+ export interface Io {
7
+ cwd: string;
8
+ env: Readonly<Record<string, string | undefined>>;
9
+ stdin: () => Uint8Array;
10
+ stdout: Writer;
11
+ stderr: Writer;
12
+ }
13
+
14
+ function ignoreBrokenPipe(error: NodeJS.ErrnoException): void {
15
+ if (error.code !== "EPIPE") throw error;
16
+ }
17
+
18
+ export function systemIo(): Io {
19
+ // Under Bun a stream write throws EPIPE into a stack trace and exit 1, where console.log swallowed it.
20
+ process.stdout.on("error", ignoreBrokenPipe);
21
+ process.stderr.on("error", ignoreBrokenPipe);
22
+
23
+ return {
24
+ cwd: process.cwd(),
25
+ env: process.env,
26
+ stdin: () => readFileSync(0),
27
+ stdout: (chunk) => {
28
+ process.stdout.write(chunk);
29
+ },
30
+ stderr: (chunk) => {
31
+ process.stderr.write(chunk);
32
+ },
33
+ };
34
+ }
35
+
36
+ export async function start(argv: string[]): Promise<number> {
37
+ const io = systemIo();
38
+ if (argv[0] === "hook") {
39
+ const args = argv.slice(1);
40
+ const call = hookCall(args, io);
41
+ if (typeof call === "number") return call;
42
+
43
+ const { runHookCall } = await import("./cli.ts");
44
+ return runHookCall(call, args, io);
45
+ }
46
+
47
+ const { main } = await import("./cli.ts");
48
+ return main(argv, io);
49
+ }
package/src/usage.ts CHANGED
@@ -1,3 +1,5 @@
1
+ export const bothBraces = "use one of --braces or --no-braces";
2
+
1
3
  export const usage =
2
4
  "Usage: stanza (--fix | --check) [--changed [--hunks] | --stdin <path> | [--] <paths...>] [--json] [--braces | --no-braces]\n stanza --check --staged [--hunks] [--json] [--braces | --no-braces]\n stanza explain <file>:<line> [--no-braces]\n stanza hook [--braces | --no-braces] [--hunks]";
3
5