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.
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "module"
3
+ }
@@ -1,6 +1,19 @@
1
1
  // oxlint-disable triple-slash-reference
2
2
  /// <reference path="./metrics.d.ts" />
3
3
 
4
+ /**
5
+ * In a workflow, as in Node.js: where the workflow file is, also inside its
6
+ * steps and `forEachFile` callbacks.
7
+ */
8
+ interface ImportMeta {
9
+ /** The directory the workflow file is in. */
10
+ dirname: string;
11
+ /** The workflow file. */
12
+ filename: string;
13
+ /** The workflow file, as a `file:` URL. */
14
+ url: string;
15
+ }
16
+
4
17
  declare module "codemod:workflow" {
5
18
  /**
6
19
  * Workflow Step Outputs Module
@@ -300,11 +313,21 @@ declare module "codemod:workflow" {
300
313
 
301
314
  const taskResult: unique symbol;
302
315
 
303
- /** Work for `step()` to run, made by `forEachFile` or a task such as `jssg`. */
316
+ /** Work for `step()` to run, made by `forEachFile` or a task such as `shell`. */
304
317
  export interface Task<Result> {
305
318
  readonly [taskResult]: Result;
306
319
  }
307
320
 
321
+ const transformResult: unique symbol;
322
+
323
+ /**
324
+ * A transform for single files, made by `jssg` or `astGrep`. Give it to
325
+ * `forEachFile` to say which files it runs on.
326
+ */
327
+ export interface Transform<Result> extends Task<Result> {
328
+ readonly [transformResult]: Result;
329
+ }
330
+
308
331
  /** What the workflow's default export receives. */
309
332
  export interface WorkflowContext<Params = Record<string, unknown>> {
310
333
  /** `--param key=value` values (JSON when they parse as JSON, otherwise strings). */
@@ -315,6 +338,32 @@ declare module "codemod:workflow" {
315
338
  dryRun: boolean;
316
339
  }
317
340
 
341
+ /**
342
+ * A length of time: a number of milliseconds, or a number with a unit,
343
+ * such as `"500ms"`, `"30s"`, `"10m"`, `"1h"` or `"2d"`.
344
+ */
345
+ export type Duration = number | `${number}${"ms" | "s" | "m" | "h" | "d"}`;
346
+
347
+ /**
348
+ * How a step is run. These do not identify the step: changing them does
349
+ * not make a finished step run again on resume.
350
+ */
351
+ export interface StepOptions {
352
+ /**
353
+ * Runs the step again when it fails, up to this many more times. The
354
+ * run sees only the last failure. Default: 0.
355
+ */
356
+ retries?: number;
357
+ /** How long to wait before each retry. Default: `"1s"`. */
358
+ retryDelay?: Duration;
359
+ /**
360
+ * Stops the step, and fails it, when one attempt takes longer than
361
+ * this: commands are terminated and file changes not yet written are
362
+ * dropped.
363
+ */
364
+ timeout?: Duration;
365
+ }
366
+
318
367
  /**
319
368
  * Runs a task as a durable step and resolves to its frozen result.
320
369
  *
@@ -327,10 +376,15 @@ declare module "codemod:workflow" {
327
376
  * const renamed = await step("Rename stylesheets", forEachFile("src/**\/*.less", (file) => {
328
377
  * file.rename(file.path.replace(/\.less$/, ".css"));
329
378
  * }));
379
+ * await step("Install", shell("pnpm install"), { retries: 2, timeout: "10m" });
330
380
  * ```
331
381
  */
332
- export function step<Result>(task: Task<Result>): Promise<Frozen<Result>>;
333
- export function step<Result>(label: string, task: Task<Result>): Promise<Frozen<Result>>;
382
+ export function step<Result>(task: Task<Result>, options?: StepOptions): Promise<Frozen<Result>>;
383
+ export function step<Result>(
384
+ label: string,
385
+ task: Task<Result>,
386
+ options?: StepOptions,
387
+ ): Promise<Frozen<Result>>;
334
388
  /**
335
389
  * Runs a function once, in its own isolate, and records its result, which
336
390
  * must be JSON. Write it inline: outside variables arrive as frozen copies,
@@ -339,17 +393,54 @@ declare module "codemod:workflow" {
339
393
  */
340
394
  export function step<Result>(
341
395
  run: () => PromiseLike<Checked<Result>>,
396
+ options?: StepOptions,
342
397
  ): Promise<Frozen<StepValue<Result>>>;
343
398
  export function step<Result>(
344
399
  label: string,
345
400
  run: () => PromiseLike<Checked<Result>>,
401
+ options?: StepOptions,
402
+ ): Promise<Frozen<StepValue<Result>>>;
403
+ export function step<Result>(
404
+ run: () => Checked<Result>,
405
+ options?: StepOptions,
346
406
  ): Promise<Frozen<StepValue<Result>>>;
347
- export function step<Result>(run: () => Checked<Result>): Promise<Frozen<StepValue<Result>>>;
348
407
  export function step<Result>(
349
408
  label: string,
350
409
  run: () => Checked<Result>,
410
+ options?: StepOptions,
351
411
  ): Promise<Frozen<StepValue<Result>>>;
352
412
 
413
+ /**
414
+ * Waits, as a step. The wait counts from when it began: a run that is
415
+ * interrupted and resumed waits only for what is left. A dry run does not
416
+ * wait.
417
+ *
418
+ * @example
419
+ * ```ts
420
+ * await sleep("30s");
421
+ * ```
422
+ */
423
+ export function sleep(duration: Duration): Promise<null>;
424
+
425
+ /**
426
+ * Waits, as a step, for an event sent to the run with
427
+ * `codemod workflow send <name> --id <run-id> [--data <json>]`, and
428
+ * resolves to its data (`null` when none was given). An event sent before
429
+ * the workflow gets here is kept for it. With `timeout`, the step fails if
430
+ * no event comes in that time, counted from when the wait began.
431
+ *
432
+ * A dry run is not saved and cannot be sent events, so the step fails there.
433
+ *
434
+ * @example
435
+ * ```ts
436
+ * const ci = await waitForEvent<{ passed: boolean }>("ci-finished", { timeout: "1h" });
437
+ * ```
438
+ */
439
+ export function waitForEvent<Data = JsonValue>(
440
+ name: string,
441
+ options?: { timeout?: Duration },
442
+ ): Promise<Frozen<Data>>;
443
+
353
444
  /**
354
445
  * `T`, checked to be JSON: `Result` is inferred from the value, which must
355
446
  * then also be assignable to its JSON-compatible form.
@@ -439,7 +530,10 @@ declare module "codemod:workflow" {
439
530
  /** What the callback returned, in path order. Files that returned nothing are left out. */
440
531
  outputs: Output[];
441
532
  changes: FileChanges;
442
- /** Files whose callback threw. */
533
+ /**
534
+ * Files whose callback threw. With some, the step is partial; when the
535
+ * callback throws on every file, the step fails instead.
536
+ */
443
537
  failures: FileFailure[];
444
538
  /** What callbacks recorded with `codemod/metrics`, by metric name. */
445
539
  metrics: Record<string, MetricEntry[]>;
@@ -481,6 +575,47 @@ declare module "codemod:workflow" {
481
575
  callback: (file: WorkflowFile) => Checked<Output>,
482
576
  ): Task<ForEachFileResult<Exclude<Output, void | undefined>>>;
483
577
 
578
+ /**
579
+ * Which files `forEachFile` runs a `jssg` transform on: a glob, a list of
580
+ * globs, or an object. `language` is the language the files are parsed as
581
+ * and, without `include`, selects that language's file extensions. Without
582
+ * a `language`, the package's is used (`targets.languages` in codemod.yaml,
583
+ * when it lists one), and otherwise `typescript`.
584
+ */
585
+ export type JssgSelector = Globs | { include?: Globs; exclude?: Globs; language?: string };
586
+
587
+ /**
588
+ * Which files `forEachFile` applies `astGrep` rules to: a glob, a list of
589
+ * globs, or an object. Without `include`, the files of the rules' languages.
590
+ */
591
+ export type AstGrepSelector = Globs | { include?: Globs; exclude?: Globs };
592
+
593
+ /**
594
+ * Runs a JSSG transform, or applies an ast-grep rule file, on every
595
+ * selected file. The selector's fields stand for the same options of
596
+ * `jssg` and `astGrep`, so give each in one place.
597
+ *
598
+ * @example
599
+ * ```ts
600
+ * await step("Migrate imports", forEachFile(jssg("scripts/codemod.ts")));
601
+ * await step("Apply rules", forEachFile("src/**\/*.ts", astGrep("rules/config.yml")));
602
+ * await step("Migrate components", forEachFile(
603
+ * { include: "src/**\/*.tsx", exclude: "**\/*.test.tsx", language: "tsx" },
604
+ * jssg("scripts/components.ts", { params: { strict: true } }),
605
+ * ));
606
+ * ```
607
+ */
608
+ export function forEachFile(transform: Transform<JssgResult>): Task<JssgResult>;
609
+ export function forEachFile(
610
+ selector: JssgSelector,
611
+ transform: Transform<JssgResult>,
612
+ ): Task<JssgResult>;
613
+ export function forEachFile(transform: Transform<AstGrepResult>): Task<AstGrepResult>;
614
+ export function forEachFile(
615
+ selector: AstGrepSelector,
616
+ transform: Transform<AstGrepResult>,
617
+ ): Task<AstGrepResult>;
618
+
484
619
  /**
485
620
  * Returns the whole workflow state as a frozen object.
486
621
  * (With a key, see the `getState(name)` overload above.)
@@ -502,15 +637,39 @@ declare module "codemod:workflow" {
502
637
  cwd?: string;
503
638
  }
504
639
 
640
+ /** A value in a `shell` template: quoted as one word, or one word per item. */
641
+ export type ShellValue = string | number | boolean | readonly (string | number | boolean)[];
642
+
643
+ export type ShellTask = Task<Skippable<{ output: string }>>;
644
+
505
645
  /**
506
646
  * Runs a shell command. It can read the workflow state from `$CODEMOD_STATE`
507
647
  * (a JSON file) or `$CODEMOD_STATE_<KEY>`, and set state by writing
508
648
  * `key=value` (or `key@=value` to append) lines to `$STATE_OUTPUTS`.
649
+ *
650
+ * @example
651
+ * await step("Install", shell("npm install"));
652
+ * await step("Setup", shell`${import.meta.dirname}/scripts/setup.sh`);
653
+ */
654
+ export function shell(command: string, options?: ShellOptions): ShellTask;
655
+ /**
656
+ * Runs a shell command written as a template. Each value is quoted for the
657
+ * shell, so a path with spaces stays one argument; the text around them is
658
+ * taken as written, backslashes included.
659
+ *
660
+ * @example
661
+ * await step("Find uses", shell`grep -rn ${name} src`);
662
+ */
663
+ export function shell(strings: TemplateStringsArray, ...values: ShellValue[]): ShellTask;
664
+ /**
665
+ * Options for a command written as a template.
666
+ *
667
+ * @example
668
+ * await step("Build", shell({ cwd: "packages/app" })`npm run build`);
509
669
  */
510
670
  export function shell(
511
- command: string,
512
- options?: ShellOptions,
513
- ): Task<Skippable<{ output: string }>>;
671
+ options: ShellOptions,
672
+ ): (strings: TemplateStringsArray, ...values: ShellValue[]) => ShellTask;
514
673
 
515
674
  export type Capability = "fs" | "fetch" | "child_process";
516
675
 
@@ -549,8 +708,12 @@ declare module "codemod:workflow" {
549
708
  failures: FileFailure[];
550
709
  }
551
710
 
552
- /** Runs a JSSG transform file. `path` is relative to the workflow file. */
553
- export function jssg(path: string, options?: JssgOptions): Task<JssgResult>;
711
+ /**
712
+ * A JSSG transform file; `path` is relative to the workflow file. Run it
713
+ * with `forEachFile(selector, jssg(path))`, which says which files it is
714
+ * for. As a step on its own it runs on the files its options select.
715
+ */
716
+ export function jssg(path: string, options?: JssgOptions): Transform<JssgResult>;
554
717
 
555
718
  export interface AstGrepOptions {
556
719
  include?: Globs;
@@ -565,8 +728,13 @@ declare module "codemod:workflow" {
565
728
  failures: FileFailure[];
566
729
  }
567
730
 
568
- /** Applies an ast-grep YAML rule file. `path` is relative to the workflow file. */
569
- export function astGrep(path: string, options?: AstGrepOptions): Task<AstGrepResult>;
731
+ /**
732
+ * An ast-grep YAML rule file; `path` is relative to the workflow file.
733
+ * Apply it with `forEachFile(selector, astGrep(path))`, which says which
734
+ * files it is for. As a step on its own it runs on the files its options
735
+ * select.
736
+ */
737
+ export function astGrep(path: string, options?: AstGrepOptions): Transform<AstGrepResult>;
570
738
 
571
739
  export type ShardMethod =
572
740
  | {
@@ -724,9 +892,6 @@ declare module "codemod:workflow" {
724
892
  options: PullRequestOptions,
725
893
  ): Task<Skippable<{ branch: string; url: string | null }>>;
726
894
 
727
- /** A finished step changed since the run was recorded, so resume cannot reuse its result. */
728
- export class NondeterminismError extends Error {}
729
-
730
895
  /** A step failed. */
731
896
  export class StepError extends Error {
732
897
  readonly label: string;
package/vite.d.mts CHANGED
@@ -1,24 +1,7 @@
1
- /**
2
- * A Vite (and Vitest) plugin that resolves the older `codemod:*` spelling of
3
- * the codemod modules (`codemod:workflow`) to the `codemod/*` exports. Code
4
- * that imports `codemod/*` needs no plugin.
5
- *
6
- * ```ts
7
- * // vitest.config.ts
8
- * import { defineConfig } from "vitest/config";
9
- * import codemod from "codemod/vite";
10
- *
11
- * export default defineConfig({ plugins: [codemod()] });
12
- * ```
13
- *
14
- * @module
15
- */
16
-
17
1
  export interface CodemodVitePlugin {
18
- name: "codemod";
19
- enforce: "pre";
20
- resolveId(id: string): string | null;
2
+ name: "codemod";
3
+ enforce: "pre";
4
+ resolveId(id: string): string | null;
21
5
  }
22
-
23
- export function codemod(): CodemodVitePlugin;
6
+ export declare function codemod(): CodemodVitePlugin;
24
7
  export default codemod;
package/vite.mjs CHANGED
@@ -2,25 +2,31 @@
2
2
  // `codemod:workflow`, `codemod:ast-grep`, ... spelling: it resolves those to
3
3
  // this package's `codemod/*` exports. Code that imports `codemod/*` needs no
4
4
  // plugin.
5
- //
6
- // // vitest.config.ts
7
- // import { defineConfig } from "vitest/config";
8
- // import codemod from "codemod/vite";
9
- // export default defineConfig({ plugins: [codemod()] });
10
-
5
+ /**
6
+ * A Vite (and Vitest) plugin that resolves the older `codemod:*` spelling of
7
+ * the codemod modules (`codemod:workflow`) to the `codemod/*` exports. Code
8
+ * that imports `codemod/*` needs no plugin.
9
+ *
10
+ * ```ts
11
+ * // vitest.config.ts
12
+ * import { defineConfig } from "vitest/config";
13
+ * import codemod from "codemod/vite";
14
+ *
15
+ * export default defineConfig({ plugins: [codemod()] });
16
+ * ```
17
+ *
18
+ * @module
19
+ */
11
20
  import { fileURLToPath } from "node:url";
12
-
13
21
  import { resolveCodemodModule } from "./runtime/modules.mjs";
14
-
15
22
  export function codemod() {
16
- return {
17
- name: "codemod",
18
- enforce: "pre",
19
- resolveId(id) {
20
- const url = resolveCodemodModule(id);
21
- return url ? fileURLToPath(url) : null;
22
- },
23
- };
23
+ return {
24
+ name: "codemod",
25
+ enforce: "pre",
26
+ resolveId(id) {
27
+ const url = resolveCodemodModule(id);
28
+ return url ? fileURLToPath(url) : null;
29
+ },
30
+ };
24
31
  }
25
-
26
32
  export default codemod;