gaji 0.3.2

Type-safe GitHub Actions workflows in TypeScript
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
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
203
204
205
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
# Writing Workflows

This guide explains how to write type-safe GitHub Actions workflows using gaji.

::: tip Standalone TypeScript Files
Workflow files generated by gaji are completely standalone and self-contained. You can run them directly with any TypeScript runtime (tsx, ts-node, Deno) to output the workflow JSON. This makes debugging and inspection easy!
:::

## Basic Structure

A gaji workflow consists of three main components:

1. **Actions**: Imported using `getAction()`
2. **Jobs**: Created using the `Job` class
3. **Workflows**: Created using the `Workflow` class

```ts twoslash
// @filename: workflows/example.ts
// ---cut---
import { getAction, Job, Workflow } from "../generated/index.js";

// 1. Import actions
const checkout = getAction("actions/checkout@v5");

// 2. Create jobs
const build = new Job("ubuntu-latest")
  .addStep(checkout({}));

// 3. Create workflow
const workflow = new Workflow({
  name: "CI",
  on: { push: { branches: ["main"] } },
}).addJob("build", build);

// 4. Build to YAML
workflow.build("ci");
```

## Using Actions

### Adding Actions

First, add the action and generate types:

```bash
gaji add actions/checkout@v5
```

### Importing Actions

Import actions using `getAction()`:

```typescript
const checkout = getAction("actions/checkout@v5");
const setupNode = getAction("actions/setup-node@v4");
const cache = getAction("actions/cache@v4");
```

### Using Actions with Type Safety

Actions return a function that accepts configuration:

```typescript
const step = checkout({
  name: "Checkout code",
  with: {
    // ✅ Full autocomplete for all inputs!
    repository: "owner/repo",
    ref: "main",
    token: "${{ secrets.GITHUB_TOKEN }}",
    "fetch-depth": 0,
  },
});
```

Your editor will provide:
- ✅ Autocomplete for all action inputs
- ✅ Type checking
- ✅ Documentation from action.yml
- ✅ Default values shown

## Creating Jobs

Jobs are created using the `Job` class:

```typescript
const job = new Job("ubuntu-latest");
```

### Supported Runners

```typescript
// Ubuntu
new Job("ubuntu-latest")
new Job("ubuntu-22.04")
new Job("ubuntu-20.04")

// macOS
new Job("macos-latest")
new Job("macos-13")
new Job("macos-12")

// Windows
new Job("windows-latest")
new Job("windows-2022")
new Job("windows-2019")

// Self-hosted
new Job("self-hosted")
new Job(["self-hosted", "linux", "x64"])
```

### Adding Steps

Steps can be added using `.addStep()`:

```typescript
const job = new Job("ubuntu-latest")
  // Action step
  .addStep(checkout({
    name: "Checkout",
  }))

  // Run command
  .addStep({
    name: "Build",
    run: "npm run build",
  })

  // Multi-line command
  .addStep({
    name: "Install dependencies",
    run: `
      npm ci
      npm run build
      npm test
    `.trim(),
  })

  // With environment variables
  .addStep({
    name: "Deploy",
    run: "npm run deploy",
    env: {
      NODE_ENV: "production",
      API_KEY: "${{ secrets.API_KEY }}",
    },
  })

  // Conditional step
  .addStep({
    name: "Upload artifacts",
    if: "success()",
    run: "npm run upload",
  });
```

## Creating Workflows

### Basic Workflow

```typescript
const workflow = new Workflow({
  name: "CI",
  on: {
    push: {
      branches: ["main"],
    },
  },
}).addJob("build", buildJob);

workflow.build("ci");
```

### Trigger Events

#### Push

```typescript
on: {
  push: {
    branches: ["main", "develop"],
    tags: ["v*"],
    paths: ["src/**", "tests/**"],
  },
}
```

#### Pull Request

```typescript
on: {
  pull_request: {
    branches: ["main"],
    types: ["opened", "synchronize", "reopened"],
  },
}
```

#### Schedule (Cron)

```typescript
on: {
  schedule: [
    { cron: "0 0 * * *" },  // Daily at midnight
  ],
}
```

#### Multiple Triggers

```typescript
on: {
  push: { branches: ["main"] },
  pull_request: { branches: ["main"] },
  workflow_dispatch: {},  // Manual trigger
}
```

### Multiple Jobs

```typescript
const test = new Job("ubuntu-latest")
  .addStep(checkout({}))
  .addStep({ run: "npm test" });

const build = new Job("ubuntu-latest")
  .addStep(checkout({}))
  .addStep({ run: "npm run build" });

const workflow = new Workflow({
  name: "CI",
  on: { push: { branches: ["main"] } },
})
  .addJob("test", test)
  .addJob("build", build);
```

### Job Dependencies

Use `.needs()` to create job dependencies:

```typescript
const test = new Job("ubuntu-latest")
  .addStep({ run: "npm test" });

const deploy = new Job("ubuntu-latest")
  .needs(["test"])  // Wait for test job
  .addStep({ run: "npm run deploy" });

const workflow = new Workflow({
  name: "Deploy",
  on: { push: { branches: ["main"] } },
})
  .addJob("test", test)
  .addJob("deploy", deploy);
```

## Matrix Builds

Create matrix builds for testing across multiple versions:

```typescript
const test = new Job("${{ matrix.os }}")
  .strategy({
    matrix: {
      os: ["ubuntu-latest", "macos-latest", "windows-latest"],
      node: ["18", "20", "22"],
    },
  })
  .addStep(checkout({}))
  .addStep(setupNode({
    with: {
      "node-version": "${{ matrix.node }}",
    },
  }))
  .addStep({ run: "npm test" });
```

## Composite Actions

Create reusable composite actions:

```ts twoslash
// @filename: workflows/example.ts
// ---cut---
import { CompositeAction, getAction } from "../generated/index.js";

const checkout = getAction("actions/checkout@v5");

const myAction = new CompositeAction({
  name: "My Action",
  description: "Reusable action",
  inputs: {
    version: {
      description: "Version to install",
      required: true,
    },
  },
})
  .addStep(checkout({}))
  .addStep({
    run: "echo Installing version ${{ inputs.version }}",
  });

myAction.build("my-action");
```

This generates `action.yml` in your repository.

## Composite Jobs

Create reusable job templates using `CompositeJob`:

```ts twoslash
// @filename: workflows/example.ts
// ---cut---
import { CompositeJob, getAction, Workflow } from "../generated/index.js";

const checkout = getAction("actions/checkout@v5");
const setupNode = getAction("actions/setup-node@v4");

// Define a reusable job class
class NodeTestJob extends CompositeJob {
  constructor(nodeVersion: string) {
    super("ubuntu-latest");

    this
      .addStep(checkout({
        name: "Checkout code",
      }))
      .addStep(setupNode({
        name: `Setup Node.js ${nodeVersion}`,
        with: {
          "node-version": nodeVersion,
          cache: "npm",
        },
      }))
      .addStep({
        name: "Install dependencies",
        run: "npm ci",
      })
      .addStep({
        name: "Run tests",
        run: "npm test",
      });
  }
}

// Use in workflow
const workflow = new Workflow({
  name: "Test Matrix",
  on: { push: { branches: ["main"] } },
})
  .addJob("test-node-18", new NodeTestJob("18"))
  .addJob("test-node-20", new NodeTestJob("20"))
  .addJob("test-node-22", new NodeTestJob("22"));

workflow.build("test-matrix");
```

### Advanced Example: Parameterized Jobs

```typescript
class DeployJob extends CompositeJob {
  constructor(environment: "staging" | "production") {
    super("ubuntu-latest");

    this
      .env({
        ENVIRONMENT: environment,
        API_URL: environment === "production"
          ? "https://api.example.com"
          : "https://staging.api.example.com",
      })
      .addStep(checkout({}))
      .addStep(setupNode({ with: { "node-version": "20" } }))
      .addStep({
        name: "Deploy",
        run: `npm run deploy:${environment}`,
        env: {
          DEPLOY_TOKEN: "${{ secrets.DEPLOY_TOKEN }}",
        },
      });
  }
}

// Use in workflow
const workflow = new Workflow({
  name: "Deploy",
  on: { push: { tags: ["v*"] } },
})
  .addJob("deploy-staging", new DeployJob("staging"))
  .addJob("deploy-production",
    new DeployJob("production").needs(["deploy-staging"])
  );
```

**Benefits:**
- Reuse common job patterns
- Type-safe parameters
- Easier maintenance
- Consistent job structure

## Environment Variables

### Workflow-level

```typescript
const workflow = new Workflow({
  name: "CI",
  on: { push: { branches: ["main"] } },
  env: {
    NODE_ENV: "production",
  },
});
```

### Job-level

```typescript
const job = new Job("ubuntu-latest")
  .env({
    DATABASE_URL: "${{ secrets.DATABASE_URL }}",
  });
```

### Step-level

```typescript
.addStep({
  run: "npm run deploy",
  env: {
    API_KEY: "${{ secrets.API_KEY }}",
  },
})
```

## Outputs

Define and use job outputs:

```typescript
const build = new Job("ubuntu-latest")
  .outputs({
    version: "${{ steps.version.outputs.value }}",
  })
  .addStep({
    id: "version",
    run: 'echo "value=1.0.0" >> $GITHUB_OUTPUT',
  });

const deploy = new Job("ubuntu-latest")
  .needs(["build"])
  .addStep({
    run: "echo Deploying version ${{ needs.build.outputs.version }}",
  });
```

## Tips

### 1. Use Watch Mode

Always use `gaji dev --watch` during development to automatically generate types for new actions.

### 2. Review Generated YAML

Always review the generated YAML before committing to ensure correctness.

### 3. Type Safety

Take advantage of TypeScript's type checking:

```typescript
// ❌ Type error - unknown property key
setupNode({
  with: {
    "node-versoin": "20",  // Typo in key name! ❌
  },
});

// ❌ Type error - wrong type
setupNode({
  with: {
    "node-version": 20,  // Should be string! ❌
  },
});

// ✅ Correct
setupNode({
  with: {
    "node-version": "20",  // ✅ Correct key and type
    cache: "npm",
  },
});
```

**Note**: While gaji provides type safety for property keys and types, it cannot validate string values (e.g., `cache: "npn"` vs `cache: "npm"`) at compile time. Always review generated YAML to catch such typos.

## Known Limitations

### `getAction()` Requires String Literals

gaji statically analyzes your TypeScript files to extract action references **without executing them**. This means `getAction()` only works with string literals:

```typescript
// ✅ Works - string literal
const checkout = getAction("actions/checkout@v5");

// ❌ Does NOT work - variable reference
const ref = "actions/checkout@v5";
const checkout = getAction(ref);

// ❌ Does NOT work - template literal
const checkout = getAction(`actions/checkout@v${version}`);

// ❌ Does NOT work - object property
const checkout = getAction(config.checkoutRef);
```

If gaji cannot detect the action reference, it won't fetch the `action.yml` or generate types for that action. Always pass the full `owner/repo@version` string directly.

### String Escaping in YAML Output

Since gaji converts JavaScript strings to YAML, characters that are already escaped in JavaScript may be double-escaped in the output. For example:

```typescript
// In TypeScript, \n is a newline character
.addStep({ run: "echo \"hello\nworld\"" })
```

The JS string contains a literal newline, which YAML will handle correctly. However, if you actually want the literal `\n` characters in the YAML output (e.g., for multiline `echo`), you need to double-escape:

```typescript
// Double-escape to preserve the literal \n in YAML
.addStep({ run: "echo hello\\nworld" })
```

**Tip**: For multi-line commands, prefer template literals instead of escape sequences:

```typescript
.addStep({
  run: `
    echo hello
    echo world
  `.trim(),
})
```

## Next Steps

- Learn about [Configuration]./configuration.md
- See [Examples]/examples/simple-ci
- Check the [API Reference]/reference/api