codemod 2.0.0-alpha.3 → 2.0.0-alpha.4

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.
@@ -1,6 +1,3 @@
1
- // oxlint-disable triple-slash-reference
2
- /// <reference path="./metrics.d.ts" />
3
-
4
1
  /**
5
2
  * In a workflow, as in Node.js: where the workflow file is, also inside its
6
3
  * steps and `forEachFile` callbacks.
@@ -15,203 +12,6 @@ interface ImportMeta {
15
12
  }
16
13
 
17
14
  declare module "codemod:workflow" {
18
- /**
19
- * Workflow Step Outputs Module
20
- *
21
- * This module provides functions to store and retrieve step outputs
22
- * across workflow executions, similar to GitHub Actions.
23
- */
24
-
25
- /**
26
- * Sets a step output value.
27
- *
28
- * Step outputs allow you to share data between steps in a workflow.
29
- * Similar to GitHub Actions, you can reference outputs like:
30
- * ${{ steps.my_step.outputs.my_output }}
31
- *
32
- * In native mode, outputs are appended to the file specified by
33
- * the STEP_OUTPUTS environment variable.
34
- *
35
- * In WASM mode, outputs are stored in memory.
36
- *
37
- * @param stepId - The unique identifier of the step
38
- * @param outputName - The name of the output variable
39
- * @param value - The value to store (as a string)
40
- *
41
- * @deprecated Use `setState` instead for structured state that doesn't require manual JSON serialization.
42
- *
43
- * @example
44
- * ```typescript
45
- * import { setStepOutput } from 'codemod/workflow';
46
- *
47
- * // In a step with id="build"
48
- * setStepOutput('build', 'version', '1.2.3');
49
- * setStepOutput('build', 'artifact_path', '/tmp/build/app.zip');
50
- *
51
- * // Later steps can access these via:
52
- * // ${{ steps.build.outputs.version }}
53
- * // ${{ steps.build.outputs.artifact_path }}
54
- * ```
55
- */
56
- export function setStepOutput(outputName: string, value: string): void;
57
-
58
- /**
59
- * Gets a step output value.
60
- *
61
- * Returns the value as a string if found, or null if the output doesn't exist.
62
- *
63
- * @param stepId - The unique identifier of the step
64
- * @param outputName - The name of the output variable
65
- * @returns The value as a string, or null if not found
66
- *
67
- * @deprecated Use `getState` instead for structured state that doesn't require manual JSON parsing.
68
- *
69
- * @example
70
- * ```typescript
71
- * import { getStepOutput } from 'codemod/workflow';
72
- *
73
- * // Get output from a previous step
74
- * const version = getStepOutput('build', 'version');
75
- * console.log(version); // '1.2.3'
76
- *
77
- * // Check if output exists
78
- * const artifactPath = getStepOutput('build', 'artifact_path');
79
- * if (artifactPath) {
80
- * console.log(`Artifact ready at: ${artifactPath}`);
81
- * }
82
- * ```
83
- */
84
- export function getStepOutput(stepId: string, outputName: string): string | null;
85
-
86
- /**
87
- * Gets a step output value, or sets it if it doesn't exist (atomically).
88
- *
89
- * This function is useful in concurrent scenarios where multiple files are processed
90
- * in parallel. The first thread to call this function will set the value if it doesn't
91
- * exist, and subsequent calls will return the existing value.
92
- *
93
- * This operation is atomic, preventing race conditions when multiple threads try to
94
- * access/set the same output simultaneously.
95
- *
96
- * @param stepId - The unique identifier of the step
97
- * @param outputName - The name of the output variable
98
- * @param defaultValue - The value to set if the output doesn't exist
99
- * @returns The existing value (if found) or the newly set default value
100
- *
101
- * @deprecated Use `setState`/`getState` with `acquireLock` instead for structured state.
102
- *
103
- * @example
104
- * ```typescript
105
- * import { getOrSetStepOutput, setStepOutput } from 'codemod/workflow';
106
- *
107
- * // Multiple files being processed in parallel
108
- * async function transform(root: SgRoot<JS>): Promise<string | null> {
109
- * const source = root.root().text();
110
- * const newFiles = source.split("\n").filter(line => line.trim() !== "");
111
- *
112
- * // Get existing files or initialize with empty array
113
- * const existingFilesStr = getOrSetStepOutput("scan-files", "allFiles", "[]");
114
- * const existingFiles = JSON.parse(existingFilesStr);
115
- *
116
- * // Merge with existing files
117
- * const allFiles = [...existingFiles, ...newFiles];
118
- *
119
- * // Update the output
120
- * setStepOutput("allFiles", JSON.stringify(allFiles));
121
- *
122
- * return null;
123
- * }
124
- * ```
125
- */
126
- export function getOrSetStepOutput(
127
- stepId: string,
128
- outputName: string,
129
- defaultValue: string,
130
- ): string;
131
-
132
- /**
133
- * Sets a named state value that is shared across all parallel file executions.
134
- *
135
- * Values are stored as native JavaScript objects internally (no JSON serialization needed).
136
- * When `persist` is true (the default), the value will be persisted at the end of the
137
- * execution batch and available to subsequent workflow steps.
138
- *
139
- * @param name - The state key
140
- * @param value - Any JSON-serializable value
141
- * @param persist - Whether to persist across workflow steps (default: true)
142
- *
143
- * @example
144
- * ```typescript
145
- * import { setState } from 'codemod/workflow';
146
- *
147
- * setState("migratedFiles", ["src/App.tsx", "src/utils.ts"]);
148
- * setState("stats", { totalFiles: 42, modified: 5 });
149
- * setState("tempCounter", 0, false); // transient, not persisted
150
- * ```
151
- */
152
- export function setState<T>(name: string, value: T, persist?: boolean): void;
153
-
154
- /**
155
- * Gets a named state value, or `undefined` if it doesn't exist.
156
- *
157
- * @param name - The state key
158
- * @returns The stored value, or `undefined` if not found
159
- *
160
- * @example
161
- * ```typescript
162
- * import { getState } from 'codemod/workflow';
163
- *
164
- * const files = getState<string[]>("migratedFiles");
165
- * if (files) {
166
- * console.log(`Already migrated ${files.length} files`);
167
- * }
168
- * ```
169
- */
170
- export function getState<T>(name: string): T | undefined;
171
-
172
- /**
173
- * Removes a named state value.
174
- *
175
- * If the key was previously persisted, a removal diff will be generated
176
- * so the value is also removed from persistent storage.
177
- *
178
- * @param name - The state key to remove
179
- *
180
- * @example
181
- * ```typescript
182
- * import { unsetState } from 'codemod/workflow';
183
- *
184
- * unsetState("tempData");
185
- * ```
186
- */
187
- export function unsetState(name: string): void;
188
-
189
- /**
190
- * Acquires a named mutex lock for coordinating concurrent access to shared state.
191
- *
192
- * Returns a `release` function that must be called when done. The lock blocks other
193
- * threads trying to acquire the same named lock until it is released.
194
- *
195
- * @param name - The lock name
196
- * @returns A function that releases the lock (must be called exactly once)
197
- *
198
- * @example
199
- * ```typescript
200
- * import { acquireLock, getState, setState } from 'codemod/workflow';
201
- *
202
- * // Safely accumulate results from parallel file processing
203
- * const release = acquireLock("results");
204
- * try {
205
- * const results = getState<string[]>("allResults") ?? [];
206
- * results.push(currentFile);
207
- * setState("allResults", results);
208
- * } finally {
209
- * release();
210
- * }
211
- * ```
212
- */
213
- export function acquireLock(name: string): () => void;
214
-
215
15
  // ── Shard function types ────────────────────────────────────────────────
216
16
 
217
17
  /**
@@ -251,9 +51,9 @@ declare module "codemod:workflow" {
251
51
 
252
52
  // ── Workflow authoring (workflow.ts) ───────────────────────────────────
253
53
  //
254
- // Everything below is used from a workflow file. `getState`, `setState`,
255
- // `unsetState` and `acquireLock` above also work inside function steps and
256
- // forEachFile callbacks; the step output functions only in JSSG transforms.
54
+ // Everything below is used from a workflow file. Workflows have no state:
55
+ // a step gets values from the body (a function step's captured variables,
56
+ // jssg `params`, shell `env`) and returns what it found on its result.
257
57
  //
258
58
  // Code inside `step(() => ...)` and `forEachFile(...)` callbacks runs in
259
59
  // its own isolate, with every module the run allows (`fs`, `fetch` and
@@ -262,9 +62,7 @@ declare module "codemod:workflow" {
262
62
  // `crypto.randomUUID` are replay-safe, and modules that read files, the
263
63
  // network, the environment or the clock are build errors.
264
64
 
265
- import type { MetricEntry } from "codemod:metrics";
266
-
267
- /** A JSON value: what step results, captured variables and state may hold. */
65
+ /** A JSON value: what step results and captured variables may hold. */
268
66
  export type JsonValue =
269
67
  | string
270
68
  | number
@@ -535,8 +333,6 @@ declare module "codemod:workflow" {
535
333
  * callback throws on every file, the step fails instead.
536
334
  */
537
335
  failures: FileFailure[];
538
- /** What callbacks recorded with `codemod/metrics`, by metric name. */
539
- metrics: Record<string, MetricEntry[]>;
540
336
  }
541
337
 
542
338
  /**
@@ -545,8 +341,8 @@ declare module "codemod:workflow" {
545
341
  *
546
342
  * Write the callback inline. Variables from outside it arrive as frozen
547
343
  * copies and must be JSON; assigning to them is a build error. Imports
548
- * (`codemod/ast-grep`, `codemod/metrics`, packages, files next to the
549
- * workflow) are available inside.
344
+ * (`codemod/ast-grep`, packages, files next to the workflow) are
345
+ * available inside.
550
346
  *
551
347
  * @example
552
348
  * ```ts
@@ -605,22 +401,178 @@ declare module "codemod:workflow" {
605
401
  * ));
606
402
  * ```
607
403
  */
608
- export function forEachFile(transform: Transform<JssgResult>): Task<JssgResult>;
609
- export function forEachFile(
404
+ export function forEachFile<Data>(transform: Transform<JssgResult<Data>>): Task<JssgResult<Data>>;
405
+ export function forEachFile<Data>(
610
406
  selector: JssgSelector,
611
- transform: Transform<JssgResult>,
612
- ): Task<JssgResult>;
407
+ transform: Transform<JssgResult<Data>>,
408
+ ): Task<JssgResult<Data>>;
613
409
  export function forEachFile(transform: Transform<AstGrepResult>): Task<AstGrepResult>;
614
410
  export function forEachFile(
615
411
  selector: AstGrepSelector,
616
412
  transform: Transform<AstGrepResult>,
617
413
  ): Task<AstGrepResult>;
618
414
 
415
+ // ---------------------------------------------------------- dependencies ---
416
+
417
+ export type Ecosystem = "npm" | "cargo";
418
+ export type DependencyKind = "prod" | "dev" | "peer" | "optional" | "build";
419
+ export type KindsOption = { kinds?: DependencyKind | readonly DependencyKind[] };
420
+
421
+ /** A `name@version` the lockfiles install, or one of the repository's own packages. */
422
+ export interface PackageNode {
423
+ readonly ecosystem: Ecosystem;
424
+ readonly name: string;
425
+ readonly version: string;
426
+ /** Directory of one of the repository's own packages; null for third-party packages. */
427
+ readonly workspace: string | null;
428
+ readonly isWorkspace: boolean;
429
+ /** Edges this node declares. */
430
+ dependencies(options?: KindsOption): DependencyEdge[];
431
+ /** Edges installed onto this exact node. */
432
+ dependents(options?: KindsOption): DependencyEdge[];
433
+ /** Each workspace that reaches this node, with its shortest chain (workspace first, this node last). */
434
+ workspacesReaching(options?: KindsOption): { workspace: PackageNode; chain: PackageNode[] }[];
435
+ /**
436
+ * This package's releases from the registry, oldest first, each with
437
+ * `breaking` relative to this node's version. Yanked releases are dropped.
438
+ */
439
+ releases(options?: {
440
+ /** `{ react: "19.0.0" }` keeps releases whose ranges on react accept 19.0.0. */
441
+ accepting?: Record<string, string>;
442
+ newerThanMine?: boolean;
443
+ prereleases?: boolean;
444
+ }): Promise<(Release & { breaking: boolean })[]>;
445
+ /** `name@version`, which is also what the node becomes in a step's result. */
446
+ toString(): string;
447
+ }
448
+
449
+ /** One declared dependency. */
450
+ export interface DependencyEdge {
451
+ readonly from: PackageNode;
452
+ /** The installed node; null for peer edges and ranges the lockfile does not resolve. */
453
+ readonly to: PackageNode | null;
454
+ readonly name: string;
455
+ /** Declared range; null when the lockfile keeps none (third-party crates in Cargo.lock). */
456
+ readonly range: string | null;
457
+ readonly kind: DependencyKind;
458
+ /** Whether the declared range accepts `version`; null when it cannot tell. */
459
+ accepts(version: string): boolean | null;
460
+ }
461
+
462
+ /** What an edge becomes in a step's result. */
463
+ export interface RecordedEdge {
464
+ from: string;
465
+ /** `name@version`, or the bare name when the edge does not resolve. */
466
+ to: string;
467
+ kind: DependencyKind;
468
+ range: string | null;
469
+ }
470
+
471
+ /** A `dependencyGraph` result as recorded: nodes become `name@version`, edges `RecordedEdge`. */
472
+ export type Recorded<T> = T extends PackageNode
473
+ ? string
474
+ : T extends DependencyEdge
475
+ ? RecordedEdge
476
+ : T extends (...args: never[]) => unknown
477
+ ? T
478
+ : T extends readonly (infer U)[]
479
+ ? Recorded<U>[]
480
+ : T extends object
481
+ ? { [K in keyof T]: Recorded<T[K]> }
482
+ : T;
483
+
484
+ /**
485
+ * The repository's lockfiles as a live graph. It is only valid inside the
486
+ * `dependencyGraph` callback; only what the callback returns is recorded.
487
+ */
488
+ export interface DependencyGraph {
489
+ /** Lockfiles read, relative to the target. */
490
+ readonly lockfiles: readonly string[];
491
+ /**
492
+ * Lockfiles found but not read, with why. Without a `lockfiles` option,
493
+ * one that cannot be read (a Yarn v1 lockfile in an example, say) is
494
+ * left out instead of failing the step.
495
+ */
496
+ readonly skipped: readonly { readonly lockfile: string; readonly error: string }[];
497
+ /** The repository's own packages. */
498
+ workspaces(): PackageNode[];
499
+ /** Every node, or every installed version of `name`. */
500
+ nodes(name?: string): PackageNode[];
501
+ /** One node by name, and by version when several are installed. */
502
+ node(name: string, version?: string): PackageNode | undefined;
503
+ /** Edges that declare a dependency on `name`, resolved or not (peer edges never resolve). */
504
+ dependents(name: string, options?: KindsOption): DependencyEdge[];
505
+ /** Shortest chains from each `from` node (default: every workspace) to any `to` node. */
506
+ chains(options: {
507
+ from?: PackageNode | readonly PackageNode[];
508
+ to: PackageNode | readonly PackageNode[];
509
+ kinds?: DependencyKind | readonly DependencyKind[];
510
+ }): PackageNode[][];
511
+ }
512
+
619
513
  /**
620
- * Returns the whole workflow state as a frozen object.
621
- * (With a key, see the `getState(name)` overload above.)
514
+ * Reads the target's lockfiles (yarn.lock, pnpm-lock.yaml, package-lock.json,
515
+ * Cargo.lock; default: any of them) into a graph and runs `callback` on it in
516
+ * its own isolate, where it may await `registry` lookups. Nodes and edges in
517
+ * the result are recorded as `name@version` text and `RecordedEdge`.
518
+ *
519
+ * @example
520
+ * ```ts
521
+ * const muiUsers = await step(dependencyGraph({ lockfiles: "yarn.lock" }, (g) =>
522
+ * g.dependents("@material-ui/core", { kinds: "prod" })
523
+ * .filter((edge) => edge.from.isWorkspace)
524
+ * .map((edge) => edge.from.workspace),
525
+ * ));
526
+ * ```
622
527
  */
623
- export function getState(): Readonly<Record<string, JsonValue>>;
528
+ export function dependencyGraph<Output>(
529
+ options: { lockfiles?: Globs },
530
+ callback: (graph: DependencyGraph) => Output | PromiseLike<Output>,
531
+ ): Task<Recorded<Awaited<Output>>>;
532
+
533
+ export interface Release {
534
+ version: string;
535
+ yanked: boolean;
536
+ prerelease: boolean;
537
+ dependencies: Record<string, string>;
538
+ peerDependencies: Record<string, string>;
539
+ optionalDependencies: Record<string, string>;
540
+ /** cargo only. */
541
+ buildDependencies?: Record<string, string>;
542
+ /** cargo only. */
543
+ devDependencies?: Record<string, string>;
544
+ }
545
+
546
+ export interface PackageReleases {
547
+ ecosystem: Ecosystem;
548
+ name: string;
549
+ /** Oldest first. Empty when the registry does not know the package. */
550
+ versions: Release[];
551
+ }
552
+
553
+ /**
554
+ * Release metadata from npm and crates.io. Usable inside a function step or
555
+ * a `forEachFile` / `dependencyGraph` callback, so the answer is recorded
556
+ * with the step; in the workflow body it rejects. Lookups are cached for the
557
+ * run and asked once per package.
558
+ */
559
+ export const registry: {
560
+ npm(name: string): Promise<PackageReleases>;
561
+ cargo(name: string): Promise<PackageReleases>;
562
+ };
563
+
564
+ type EcosystemOption = { ecosystem?: Ecosystem };
565
+ /** Version comparison with npm rules, or Cargo's with `{ ecosystem: "cargo" }`. */
566
+ export const semver: {
567
+ /** true, false, or null when the range cannot be read (`workspace:`, `git:` ...). */
568
+ satisfies(version: string, range: string, options?: EcosystemOption): boolean | null;
569
+ compare(a: string, b: string, options?: EcosystemOption): -1 | 0 | 1;
570
+ gt(a: string, b: string, options?: EcosystemOption): boolean;
571
+ lt(a: string, b: string, options?: EcosystemOption): boolean;
572
+ /** Whether `from` to `to` changes the left-most non-zero component (0.29 to 0.30 is breaking). */
573
+ isBreaking(from: string, to: string, options?: EcosystemOption): boolean;
574
+ isPrerelease(version: string, options?: EcosystemOption): boolean;
575
+ };
624
576
 
625
577
  /**
626
578
  * A result for tasks that do nothing in some runs: shell commands, agents
@@ -635,21 +587,32 @@ declare module "codemod:workflow" {
635
587
  env?: Readonly<Record<string, string>>;
636
588
  /** Directory to run in, relative to the target (or absolute). Defaults to the current directory. */
637
589
  cwd?: string;
590
+ /** Return the result of a command that exits with an error, instead of failing the step. */
591
+ allowFailure?: boolean;
592
+ }
593
+
594
+ /** What a command printed, as text (the last 1 MiB of each), and how it exited. */
595
+ export interface ShellResult {
596
+ stdout: string;
597
+ stderr: string;
598
+ /** 0, unless `allowFailure` is set; -1 when a signal ended the command. */
599
+ exitCode: number;
638
600
  }
639
601
 
640
602
  /** A value in a `shell` template: quoted as one word, or one word per item. */
641
603
  export type ShellValue = string | number | boolean | readonly (string | number | boolean)[];
642
604
 
643
- export type ShellTask = Task<Skippable<{ output: string }>>;
605
+ export type ShellTask = Task<Skippable<ShellResult>>;
644
606
 
645
607
  /**
646
- * Runs a shell command. It can read the workflow state from `$CODEMOD_STATE`
647
- * (a JSON file) or `$CODEMOD_STATE_<KEY>`, and set state by writing
648
- * `key=value` (or `key@=value` to append) lines to `$STATE_OUTPUTS`.
608
+ * Runs a shell command. It gets values through `env`; the workflow parses
609
+ * what it needs from what the command prints. A command that exits with
610
+ * an error fails the step, unless `allowFailure` is set.
649
611
  *
650
612
  * @example
651
613
  * await step("Install", shell("npm install"));
652
- * await step("Setup", shell`${import.meta.dirname}/scripts/setup.sh`);
614
+ * const { stdout } = await step("Detect", shell(`echo '{"major":19}'`));
615
+ * JSON.parse(stdout); // { major: 19 }
653
616
  */
654
617
  export function shell(command: string, options?: ShellOptions): ShellTask;
655
618
  /**
@@ -702,10 +665,31 @@ declare module "codemod:workflow" {
702
665
  dryRun?: boolean;
703
666
  }
704
667
 
705
- export interface JssgResult {
668
+ /** One file's `data`, as the transform returned it. */
669
+ export interface JssgData {
670
+ file: string;
671
+ data: JsonValue;
672
+ }
673
+
674
+ export interface JssgResult<Data = readonly JssgData[]> {
706
675
  changes: FileChanges;
707
676
  unmodified: number;
708
677
  failures: FileFailure[];
678
+ /**
679
+ * Each file's `data`, sorted by path, leaving out files that returned
680
+ * none; or, with a reducer, what it folded them into.
681
+ */
682
+ data: Data;
683
+ }
684
+
685
+ /**
686
+ * Folds each file's `data` into one value as the file finishes, so the
687
+ * step never holds every file's data at once. Files arrive in no
688
+ * particular order. Write `reduce` inline so the build can extract it.
689
+ */
690
+ export interface JssgReducer<T> {
691
+ reduce: (result: T, entry: JssgData) => T | Promise<T>;
692
+ initial: T;
709
693
  }
710
694
 
711
695
  /**
@@ -713,6 +697,12 @@ declare module "codemod:workflow" {
713
697
  * with `forEachFile(selector, jssg(path))`, which says which files it is
714
698
  * for. As a step on its own it runs on the files its options select.
715
699
  */
700
+ // `T` is unconstrained so `initial: 0` gives `number`, not `0`; the
701
+ // result is checked to be JSON when the step runs.
702
+ export function jssg<T>(
703
+ path: string,
704
+ options: JssgOptions & JssgReducer<T>,
705
+ ): Transform<JssgResult<T>>;
716
706
  export function jssg(path: string, options?: JssgOptions): Transform<JssgResult>;
717
707
 
718
708
  export interface AstGrepOptions {
@@ -1,9 +0,0 @@
1
- import type { MetricEntry } from "./context.mts";
2
- declare class MetricAtom {
3
- readonly name: string;
4
- constructor(name: string);
5
- increment(cardinality?: Record<string, unknown> | null, amount?: unknown): void;
6
- getEntries(): MetricEntry[];
7
- }
8
- export declare function useMetricAtom(name: string): MetricAtom;
9
- export { MetricAtom };
@@ -1,42 +0,0 @@
1
- // `codemod/metrics` in Node.js and Bun. Metrics belong to the step that
2
- // records them: they go into a `forEachFile` step's result and the run's
3
- // report. The workflow body cannot record them, as in the engine.
4
- import { context } from "./context.mjs";
5
- class MetricAtom {
6
- name;
7
- constructor(name) {
8
- this.name = name;
9
- }
10
- increment(cardinality = {}, amount = 1) {
11
- const scope = context.getStore()?.step;
12
- if (!scope) {
13
- throw new Error(`metric '${this.name}': metrics can only be recorded inside a step or forEachFile callback`);
14
- }
15
- const labels = cardinality ?? {};
16
- const clean = {};
17
- for (const key of Object.keys(labels).sort()) {
18
- const value = labels[key];
19
- if (value !== undefined && value !== null)
20
- clean[key] = String(value);
21
- }
22
- // A whole amount of at least 0; anything that is not a number counts 1.
23
- const count = typeof amount === "number" && Number.isFinite(amount) ? Math.max(0, Math.trunc(amount)) : 1;
24
- const entryKey = JSON.stringify(clean);
25
- let entries = scope.metrics.get(this.name);
26
- if (!entries)
27
- scope.metrics.set(this.name, (entries = new Map()));
28
- const entry = entries.get(entryKey);
29
- if (entry)
30
- entry.count += count;
31
- else
32
- entries.set(entryKey, { cardinality: clean, count });
33
- }
34
- getEntries() {
35
- const entries = context.getStore()?.step?.metrics.get(this.name);
36
- return entries ? [...entries.values()].map((entry) => ({ ...entry })) : [];
37
- }
38
- }
39
- export function useMetricAtom(name) {
40
- return new MetricAtom(name);
41
- }
42
- export { MetricAtom };
@@ -1,5 +0,0 @@
1
- // oxlint-disable triple-slash-reference
2
- /// <reference path="modules/metrics.d.ts" />
3
-
4
- // `codemod/metrics`: the same module as `codemod:metrics`, its older spelling.
5
- export * from "codemod:metrics";
@@ -1,107 +0,0 @@
1
- declare module "codemod:metrics" {
2
- /**
3
- * Cardinality dimensions for a metric entry.
4
- * Keys and values must be strings. Undefined/null values are omitted.
5
- */
6
- export type Cardinality = Record<string, string | undefined | null>;
7
-
8
- /**
9
- * A metric entry with its cardinality dimensions and count.
10
- */
11
- export interface MetricEntry {
12
- cardinality: Record<string, string>;
13
- count: number;
14
- }
15
-
16
- /**
17
- * A metric atom for tracking counts with cardinality dimensions.
18
- *
19
- * MetricAtom provides a way to increment and retrieve counts for different
20
- * cardinality combinations within a named metric. This is useful for tracking
21
- * things like prop usage counts with multiple dimensions (e.g., propName + propValue).
22
- *
23
- * @example
24
- * ```ts
25
- * import { useMetricAtom } from "codemod/metrics";
26
- *
27
- * const propUsage = useMetricAtom("prop-usage");
28
- *
29
- * export function transform(root) {
30
- * root.findAll({ rule: { pattern: "$PROP={$_}" } }).forEach((match) => {
31
- * propUsage.increment({
32
- * propName: match.getMatch("PROP")?.text(),
33
- * });
34
- * });
35
- * return null;
36
- * }
37
- * ```
38
- */
39
- export class MetricAtom {
40
- /**
41
- * The name of this metric.
42
- */
43
- readonly name: string;
44
-
45
- /**
46
- * Increment the count for a given cardinality combination.
47
- *
48
- * @param cardinality - Object with dimension key-value pairs. Undefined/null values are omitted.
49
- * @param amount - The amount to increment by (default: 1)
50
- *
51
- * @example
52
- * ```ts
53
- * // Simple increment with no cardinality
54
- * metric.increment();
55
- *
56
- * // Single dimension
57
- * propUsage.increment({ propName: "title" });
58
- *
59
- * // Multiple dimensions
60
- * propUsage.increment({ propName: "className", propValue: "container" });
61
- *
62
- * // With amount
63
- * propUsage.increment({ propName: "title" }, 5);
64
- *
65
- * // Undefined values are omitted
66
- * propUsage.increment({ propName: "title", propValue: undefined });
67
- * // Results in cardinality: { propName: "title" }
68
- * ```
69
- */
70
- increment(cardinality?: Cardinality, amount?: number): void;
71
-
72
- /**
73
- * Get the current entries for this metric.
74
- *
75
- * @returns An array of entries with their cardinality and count
76
- *
77
- * @example
78
- * ```ts
79
- * const entries = propUsage.getEntries();
80
- * // [
81
- * // { cardinality: { propName: "title" }, count: 10 },
82
- * // { cardinality: { propName: "className", propValue: "container" }, count: 5 }
83
- * // ]
84
- * ```
85
- */
86
- getEntries(): MetricEntry[];
87
- }
88
-
89
- /**
90
- * Create or retrieve a metric atom with the given name.
91
- *
92
- * Multiple calls with the same name will return atoms that share the same
93
- * underlying data, allowing metrics to be collected across multiple files.
94
- *
95
- * @param name - The name of the metric (e.g., "prop-usage", "component-count")
96
- * @returns A MetricAtom instance for tracking counts with cardinality
97
- *
98
- * @example
99
- * ```ts
100
- * import { useMetricAtom } from "codemod/metrics";
101
- *
102
- * const propUsage = useMetricAtom("prop-usage");
103
- * const componentCount = useMetricAtom("component-count");
104
- * ```
105
- */
106
- export function useMetricAtom(name: string): MetricAtom;
107
- }