type-git 0.3.0-beta.0 → 0.5.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.
@@ -1,850 +0,0 @@
1
- /**
2
- * Environment variable inheritance control (environment variable traversal prevention)
3
- *
4
- * By default, type-git does NOT pass the entire parent process environment to the
5
- * spawned Git subprocess. Leaking the full environment into Git (and from there into
6
- * credential helpers, hooks, and LFS transfer agents) is an environment variable
7
- * traversal risk: secrets such as cloud credentials or API tokens that live in the
8
- * parent process can be exfiltrated by untrusted Git configuration or remote-controlled
9
- * helpers.
10
- *
11
- * Instead, only a curated allowlist of variables that Git genuinely needs to operate is
12
- * inherited. Callers can widen or replace this behavior via the `inheritEnv` option.
13
- */
14
- /**
15
- * Fine-grained adjustment of the default allowlist.
16
- *
17
- * Starts from {@link DEFAULT_ENV_ALLOWLIST}, adds the names in `add`, then removes the
18
- * names in `remove`. `remove` takes precedence, so `{ add: ['X'], remove: ['X'] }`
19
- * excludes `X`. This is the way to drop a single default entry (for example
20
- * `{ remove: ['SSH_AUTH_SOCK', 'SSH_AGENT_PID'] }` for an HTTPS-only application) while
21
- * keeping the rest of the curated defaults.
22
- */
23
- type EnvAllowlistAdjustment = {
24
- /** Variable names to add to the default allowlist. */
25
- add?: string[];
26
- /** Variable names to remove from the (default + add) allowlist. */
27
- remove?: string[];
28
- };
29
- /**
30
- * Predicate deciding, per variable, whether it is inherited from the parent environment.
31
- * Receives each parent environment variable name and returns `true` to inherit it. This
32
- * gives full control and bypasses the default allowlist entirely — reference
33
- * {@link DEFAULT_ENV_ALLOWLIST} explicitly if you want to build on top of it.
34
- *
35
- * Note: on Windows the name is passed through as-is, so handle case-insensitivity yourself
36
- * (e.g. compare against `name.toUpperCase()`).
37
- */
38
- type EnvInheritancePredicate = (name: string) => boolean;
39
- /**
40
- * Controls how the parent process environment is inherited by spawned Git commands.
41
- *
42
- * - `undefined` (default): inherit only {@link DEFAULT_ENV_ALLOWLIST} — the variables
43
- * Git needs to function. Sensitive variables are not passed through.
44
- * - `true`: inherit the entire parent environment (legacy behavior, opt-in).
45
- * - `false`: inherit nothing. The child only receives explicitly provided variables and
46
- * values computed by the library (e.g. `HOME`, `PATH` prefixes). Note that this may
47
- * break Git if `PATH` is not otherwise supplied.
48
- * - `string[]`: inherit {@link DEFAULT_ENV_ALLOWLIST} plus the named variables. Use this
49
- * to explicitly opt specific variables (e.g. an SSH command or a token) back in.
50
- * - `{ add?, remove? }`: inherit {@link DEFAULT_ENV_ALLOWLIST}, plus `add`, minus `remove`.
51
- * Use this to drop a single default entry without rebuilding the whole allowlist.
52
- * - `(name) => boolean`: a predicate that decides each variable individually, bypassing the
53
- * default allowlist entirely.
54
- */
55
- type EnvInheritance = boolean | string[] | EnvAllowlistAdjustment | EnvInheritancePredicate;
56
- /**
57
- * Curated allowlist of environment variables inherited by default.
58
- *
59
- * These are variables Git (and the tools it shells out to, such as ssh and credential
60
- * helpers) commonly needs to operate. The list intentionally excludes arbitrary
61
- * application secrets so they are not silently forwarded to Git subprocesses.
62
- *
63
- * Security notes:
64
- * - The SSH agent vars (`SSH_AUTH_SOCK`, `SSH_AGENT_PID`) and SSH/TLS transport config
65
- * (`GIT_SSH_COMMAND`, `GIT_SSL_CAINFO`, …) are inherited by default so Git-over-SSH and
66
- * fetch/push keep working out of the box. For an HTTPS-only application that does not
67
- * want to expose the SSH agent, drop it with
68
- * `inheritEnv: { remove: ['SSH_AUTH_SOCK', 'SSH_AGENT_PID'] }`.
69
- * - The most credential-prone helpers (`GIT_ASKPASS`, `SSH_ASKPASS`, `GIT_PROXY_COMMAND`)
70
- * are intentionally NOT in the default allowlist; opt them back in explicitly
71
- * (`inheritEnv: ['GIT_ASKPASS']`) only when you trust the value.
72
- *
73
- * Variable names are matched case-insensitively on Windows.
74
- */
75
- declare const DEFAULT_ENV_ALLOWLIST: readonly string[];
76
- /**
77
- * Resolve the set of environment variables to inherit from the parent process.
78
- *
79
- * @param parentEnv - The parent process environment (e.g. `process.env`).
80
- * @param inheritEnv - Inheritance policy. See {@link EnvInheritance}.
81
- * @param platform - The runtime platform (e.g. `process.platform`). When `'win32'`,
82
- * variable names are matched case-insensitively.
83
- * @returns A record containing only the inherited variables (undefined values removed).
84
- */
85
- declare function resolveInheritedEnv(parentEnv: Record<string, string | undefined>, inheritEnv?: EnvInheritance, platform?: string): Record<string, string>;
86
-
87
- /**
88
- * Core type definitions for the type-safe Git wrapper library
89
- *
90
- * This module defines:
91
- * - Progress events (Git and LFS)
92
- * - Execution options and results
93
- * - Error types and handling
94
- * - Runtime capabilities
95
- * - Output contracts for typed parsing
96
- * - Branded types for type safety
97
- */
98
-
99
- /**
100
- * Brand symbol for NonEmptyString
101
- * @internal
102
- */
103
- declare const NonEmptyBrand: unique symbol;
104
- /**
105
- * A string that is guaranteed to be non-empty at the type level.
106
- *
107
- * Use the `nonEmpty()` helper function to create NonEmptyString values,
108
- * or cast string literals directly: `'main' as NonEmptyString`
109
- *
110
- * @example
111
- * ```typescript
112
- * // Using helper function (recommended for variables)
113
- * const branch = nonEmpty(userInput);
114
- * await repo.branch.create(branch);
115
- *
116
- * // Casting literals (safe for known values)
117
- * await repo.checkout('main' as NonEmptyString);
118
- * ```
119
- */
120
- type NonEmptyString = string & {
121
- readonly [NonEmptyBrand]: never;
122
- };
123
- /**
124
- * Validates and converts a string to NonEmptyString.
125
- *
126
- * @param s - The string to validate
127
- * @returns The string as NonEmptyString
128
- * @throws GitArgumentError if the string is empty
129
- *
130
- * @example
131
- * ```typescript
132
- * const branchName = nonEmpty('feature-branch'); // OK
133
- * const invalid = nonEmpty(''); // throws GitArgumentError
134
- * ```
135
- */
136
- declare function nonEmpty(s: string): NonEmptyString;
137
- /**
138
- * Type guard to check if a string is non-empty.
139
- *
140
- * @param s - The string to check
141
- * @returns true if the string is non-empty
142
- *
143
- * @example
144
- * ```typescript
145
- * const input = getUserInput();
146
- * if (isNonEmpty(input)) {
147
- * await repo.branch.create(input); // input is NonEmptyString here
148
- * }
149
- * ```
150
- */
151
- declare function isNonEmpty(s: string): s is NonEmptyString;
152
- /**
153
- * Progress event for Git operations
154
- *
155
- * Parsed from git's stderr progress output like:
156
- * - "Counting objects: 100% (10/10), done."
157
- * - "Compressing objects: 100% (8/8), done."
158
- */
159
- type GitProgress = {
160
- /** The phase of the git operation */
161
- phase: string;
162
- /** Current progress value */
163
- current: number;
164
- /** Total value (null if unknown) */
165
- total: number | null;
166
- /** Percentage (null if unknown) */
167
- percent: number | null;
168
- /** Raw message from stderr */
169
- message?: string;
170
- };
171
- /**
172
- * Progress event for LFS operations (§7.3)
173
- *
174
- * Parsed from LFS stderr output when GIT_LFS_FORCE_PROGRESS=1:
175
- * "Downloading LFS objects: 50% (1/2), 1.2 MB | 500 KB/s"
176
- */
177
- type LfsProgress = {
178
- /** Direction of the transfer */
179
- direction: 'download' | 'upload' | 'checkout';
180
- /** Total bytes transferred so far */
181
- bytesSoFar: number;
182
- /** Total bytes to transfer */
183
- bytesTotal: number;
184
- /** Transfer rate in bytes per second */
185
- bitrate?: number;
186
- /** Number of files completed */
187
- filesCompleted: number;
188
- /** Total number of files */
189
- filesTotal: number;
190
- /** Progress percentage (0-100) */
191
- percent: number;
192
- };
193
- /**
194
- * Execution options common to all Git operations
195
- */
196
- type ExecOpts = {
197
- /** AbortSignal for cancellation */
198
- signal?: AbortSignal;
199
- /** Git progress callback (for operations like fetch, push, clone) */
200
- onProgress?: (progress: GitProgress) => void;
201
- /** LFS progress callback (for LFS transfer operations) */
202
- onLfsProgress?: (progress: LfsProgress) => void;
203
- };
204
- /**
205
- * Result from raw Git command execution
206
- */
207
- type RawResult = {
208
- /** Standard output */
209
- stdout: string;
210
- /** Standard error */
211
- stderr: string;
212
- /** Exit code (0 = success) */
213
- exitCode: number;
214
- /** Whether the command was aborted via AbortSignal */
215
- aborted: boolean;
216
- };
217
- /**
218
- * Git error kinds
219
- */
220
- type GitErrorKind =
221
- /** Failed to spawn the git process */
222
- 'SpawnFailed'
223
- /** Git exited with non-zero exit code */
224
- | 'NonZeroExit'
225
- /** Failed to parse git output */
226
- | 'ParseError'
227
- /** Command was aborted via AbortSignal */
228
- | 'Aborted'
229
- /** Required capability is missing (e.g., Deno permissions) */
230
- | 'CapabilityMissing'
231
- /** Expected a worktree repository but found bare repository */
232
- | 'NotWorktreeRepo'
233
- /** Expected a bare repository but found worktree repository */
234
- | 'NotBareRepo'
235
- /** Git version is below minimum supported version */
236
- | 'UnsupportedGitVersion';
237
- /**
238
- * Git error category for error handling (§13.2)
239
- *
240
- * Categorizes errors by their nature to enable appropriate handling strategies.
241
- */
242
- type GitErrorCategory =
243
- /** Authentication errors (401, credential related) */
244
- 'auth'
245
- /** Network errors (timeout, DNS resolution failure, etc.) */
246
- | 'network'
247
- /** Merge/rebase conflicts */
248
- | 'conflict'
249
- /** LFS-specific errors (storage capacity, transfer failure, etc.) */
250
- | 'lfs'
251
- /** Permission errors (directory access, file lock) */
252
- | 'permission'
253
- /** Repository corruption */
254
- | 'corruption'
255
- /** Unclassifiable */
256
- | 'unknown';
257
- /**
258
- * Git error with detailed context
259
- */
260
- declare class GitError extends Error {
261
- readonly kind: GitErrorKind;
262
- readonly context: {
263
- argv?: string[];
264
- workdir?: string;
265
- gitDir?: string;
266
- exitCode?: number;
267
- stdout?: string;
268
- stderr?: string;
269
- };
270
- readonly category: GitErrorCategory;
271
- constructor(kind: GitErrorKind, message: string, context?: {
272
- argv?: string[];
273
- workdir?: string;
274
- gitDir?: string;
275
- exitCode?: number;
276
- stdout?: string;
277
- stderr?: string;
278
- }, category?: GitErrorCategory);
279
- /**
280
- * Check if the error is retryable (§13.2)
281
- *
282
- * Network errors and some LFS errors are typically retryable.
283
- */
284
- isRetryable(): boolean;
285
- /**
286
- * Check if authentication is needed (§13.2)
287
- */
288
- needsAuthentication(): boolean;
289
- }
290
- /**
291
- * Error thrown when an argument is invalid (e.g., empty string where non-empty is required)
292
- *
293
- * This error is thrown at the API boundary before the git command is executed,
294
- * providing early feedback for invalid arguments.
295
- *
296
- * @example
297
- * ```typescript
298
- * try {
299
- * await repo.branch.create(nonEmpty('')); // throws GitArgumentError
300
- * } catch (e) {
301
- * if (e instanceof GitArgumentError) {
302
- * console.log('Invalid argument:', e.message);
303
- * }
304
- * }
305
- * ```
306
- */
307
- declare class GitArgumentError extends Error {
308
- constructor(message: string);
309
- }
310
- /**
311
- * Runtime identifier
312
- */
313
- type Runtime = 'node' | 'deno' | 'bun';
314
- /**
315
- * Runtime capabilities
316
- *
317
- * Used to determine what features are available in the current runtime.
318
- */
319
- type Capabilities = {
320
- /** Whether process spawning is available */
321
- canSpawnProcess: boolean;
322
- /** Whether environment variables can be read */
323
- canReadEnv: boolean;
324
- /** Whether temporary files can be written (for LFS progress) */
325
- canWriteTemp: boolean;
326
- /** Whether AbortSignal is supported */
327
- supportsAbortSignal: boolean;
328
- /** Whether kill signals can be sent to processes */
329
- supportsKillSignal: boolean;
330
- /** Runtime identifier */
331
- runtime: Runtime;
332
- /** Git version (if detected) */
333
- gitVersion?: string;
334
- /** Git LFS version (if detected) */
335
- lfsVersion?: string;
336
- };
337
- /**
338
- * LFS mode configuration.
339
- *
340
- * - `'enabled'` (default): LFS behaves normally.
341
- * - `'disabled'`: the `repo.lfs.*` / `repo.lfsExtra.*` helpers become no-ops.
342
- * - object form: working-tree-populating operations (`checkout`, `switch`,
343
- * `reset`, `merge`, `pull`, `rebase`, `restore`) run with
344
- * `GIT_LFS_SKIP_SMUDGE=1` so Git leaves LFS pointer files in place instead of
345
- * downloading their contents. The objects can be materialized later via the
346
- * explicit `repo.lfs.pull()` / `repo.lfs.checkout()` helpers.
347
- */
348
- type LfsMode = 'enabled' | 'disabled' | {
349
- /** Skip smudge filter (don't download LFS files on checkout). */
350
- skipSmudge?: boolean;
351
- /** Skip download, keeping pointer files (also implies skip-smudge). */
352
- skipDownload?: boolean;
353
- };
354
- /**
355
- * Output contract types for typed API
356
- *
357
- * Typed API only supports commands with predictable output formats.
358
- */
359
- type OutputContract =
360
- /** Raw output - no parsing */
361
- {
362
- type: 'raw';
363
- }
364
- /** Porcelain format (v1 or v2) */
365
- | {
366
- type: 'porcelain';
367
- version: 1 | 2;
368
- }
369
- /** JSON output */
370
- | {
371
- type: 'json';
372
- }
373
- /** Custom format with a specific delimiter */
374
- | {
375
- type: 'delimited';
376
- delimiter: string;
377
- nullTerminated?: boolean;
378
- }
379
- /** Custom pretty format for git log */
380
- | {
381
- type: 'pretty';
382
- format: string;
383
- };
384
- /**
385
- * Command specification for typed API
386
- */
387
- type CommandSpec<TOptions, TResult> = {
388
- /** Command name (e.g., "status", "log") */
389
- name: string;
390
- /** Subcommands (e.g., ["lfs", "pull"]) */
391
- subcommands?: string[];
392
- /** Build argv from options */
393
- buildArgs: (options: TOptions) => string[];
394
- /** Output contract */
395
- outputContract: OutputContract;
396
- /** Parse stdout/stderr to result */
397
- parse: (stdout: string, stderr: string) => TResult;
398
- };
399
- /**
400
- * Execution context for git commands
401
- *
402
- * Determines how git commands are executed:
403
- * - Worktree: `git -C <workdir> <command>`
404
- * - Bare: `git --git-dir=<gitDir> <command>`
405
- */
406
- type ExecutionContext = {
407
- type: 'global';
408
- } | {
409
- type: 'worktree';
410
- workdir: string;
411
- } | {
412
- type: 'bare';
413
- gitDir: string;
414
- };
415
- /**
416
- * Options for opening a repository with environment isolation (§6.3)
417
- *
418
- * Provides declarative environment configuration for Git operations.
419
- */
420
- type GitOpenOptions = {
421
- /** Custom HOME directory (~/.gitconfig source) */
422
- home?: string;
423
- /** Ignore system config (--config-env=GIT_CONFIG_GLOBAL=/dev/null equivalent) */
424
- ignoreSystemConfig?: boolean;
425
- /** Custom credential helper */
426
- credentialHelper?: string;
427
- /** Additional environment variables */
428
- env?: Record<string, string>;
429
- /**
430
- * Controls how the parent process environment is inherited by spawned Git commands.
431
- *
432
- * By default, only a curated allowlist of variables that Git needs to operate is
433
- * inherited (environment variable traversal prevention). See {@link EnvInheritance} for
434
- * all supported forms:
435
- * - `true` — inherit the full parent environment.
436
- * - `string[]` — inherit the default allowlist plus the named variables.
437
- * - `{ add?, remove? }` — adjust the default allowlist (e.g. drop `SSH_AUTH_SOCK`).
438
- * - `(name) => boolean` — decide each variable individually.
439
- */
440
- inheritEnv?: EnvInheritance;
441
- /** Directories to prepend to PATH */
442
- pathPrefix?: string[];
443
- /** Credential configuration (§6.4) */
444
- credential?: CredentialConfig;
445
- /** LFS mode configuration */
446
- lfs?: LfsMode;
447
- };
448
- /**
449
- * Credential request information
450
- */
451
- type CredentialRequest = {
452
- protocol: 'https' | 'ssh';
453
- host: string;
454
- path?: string;
455
- };
456
- /**
457
- * Credential response
458
- */
459
- type Credential = {
460
- username: string;
461
- password: string;
462
- };
463
- /**
464
- * Credential configuration for Git authentication (§6.4)
465
- *
466
- * Supports multiple authentication methods:
467
- * 1. Built-in helper (store, cache, manager-core)
468
- * 2. Custom helper binary
469
- * 3. Programmatic authentication (recommended)
470
- * 4. Static credentials (dev/test only)
471
- */
472
- type CredentialConfig = {
473
- /** Method 1: Built-in helper name */
474
- helper?: 'store' | 'cache' | 'manager-core' | string;
475
- /** Method 2: Custom helper binary path */
476
- helperPath?: string;
477
- /** Method 3: Programmatic authentication provider (recommended) */
478
- provider?: (request: CredentialRequest) => Promise<Credential>;
479
- /** Method 4: Static credentials (dev/test only) */
480
- username?: string;
481
- password?: string;
482
- token?: string;
483
- /** Fallback credential configuration */
484
- fallback?: CredentialConfig;
485
- /** Callback when authentication fails */
486
- onAuthFailure?: (error: Error, request: CredentialRequest) => void;
487
- };
488
- /**
489
- * Audit event fired when a Git command starts execution
490
- */
491
- type AuditEventStart = {
492
- /** Event type discriminator */
493
- type: 'start';
494
- /** Timestamp in milliseconds since epoch */
495
- timestamp: number;
496
- /** Command arguments (e.g., ['git', '-C', '/path', 'status']) */
497
- argv: string[];
498
- /** Execution context (global, worktree, or bare) */
499
- context: ExecutionContext;
500
- };
501
- /**
502
- * Audit event fired when a Git command completes
503
- */
504
- type AuditEventEnd = {
505
- /** Event type discriminator */
506
- type: 'end';
507
- /** Timestamp in milliseconds since epoch */
508
- timestamp: number;
509
- /** Command arguments (same as start event) */
510
- argv: string[];
511
- /** Execution context (same as start event) */
512
- context: ExecutionContext;
513
- /** Standard output from the command */
514
- stdout: string;
515
- /** Standard error from the command */
516
- stderr: string;
517
- /** Exit code (0 = success) */
518
- exitCode: number;
519
- /** Whether command was aborted via AbortSignal */
520
- aborted: boolean;
521
- /** Duration in milliseconds */
522
- duration: number;
523
- };
524
- /**
525
- * Audit event for Git command execution lifecycle
526
- *
527
- * Discriminated union based on event type.
528
- *
529
- * @example
530
- * ```typescript
531
- * const git = await createGit({
532
- * adapters: createNodeAdapters(),
533
- * audit: {
534
- * onAudit: (event) => {
535
- * if (event.type === 'start') {
536
- * console.log(`→ ${event.argv.join(' ')}`);
537
- * } else {
538
- * console.log(`✓ completed in ${event.duration}ms (exit ${event.exitCode})`);
539
- * }
540
- * }
541
- * }
542
- * });
543
- * ```
544
- */
545
- type AuditEvent = AuditEventStart | AuditEventEnd;
546
- /**
547
- * Trace output from GIT_TRACE environment variable
548
- *
549
- * Captures Git's internal debug output when GIT_TRACE is enabled.
550
- * Automatically enabled when onTrace callback is provided.
551
- *
552
- * @example
553
- * ```typescript
554
- * const git = await createGit({
555
- * adapters: createNodeAdapters(),
556
- * audit: {
557
- * onTrace: (trace) => {
558
- * console.log(`[GIT_TRACE] ${trace.line}`);
559
- * }
560
- * }
561
- * });
562
- * ```
563
- */
564
- type TraceEvent = {
565
- /** Timestamp in milliseconds since epoch */
566
- timestamp: number;
567
- /** Raw trace output line from git stderr */
568
- line: string;
569
- };
570
- /**
571
- * Audit configuration for Git instance
572
- *
573
- * Provides hooks for observing Git command execution lifecycle
574
- * and internal Git trace output.
575
- *
576
- * @example
577
- * ```typescript
578
- * const git = await createGit({
579
- * adapters: createNodeAdapters(),
580
- * audit: {
581
- * onAudit: (event) => {
582
- * if (event.type === 'start') {
583
- * console.log(`[AUDIT] Starting: ${event.argv.join(' ')}`);
584
- * } else {
585
- * console.log(`[AUDIT] Completed: exit ${event.exitCode}, ${event.duration}ms`);
586
- * }
587
- * },
588
- * onTrace: (trace) => {
589
- * console.log(`[TRACE] ${trace.line}`);
590
- * }
591
- * }
592
- * });
593
- * ```
594
- */
595
- type AuditConfig = {
596
- /**
597
- * Callback invoked for each Git command lifecycle event
598
- *
599
- * Receives 'start' event before command execution and 'end' event after.
600
- */
601
- onAudit?: (event: AuditEvent) => void;
602
- /**
603
- * Callback invoked for GIT_TRACE output
604
- *
605
- * When provided, GIT_TRACE=1 is automatically set.
606
- * Trace output is parsed from stderr lines.
607
- */
608
- onTrace?: (trace: TraceEvent) => void;
609
- };
610
-
611
- /**
612
- * Runtime adapter interfaces for cross-platform support (Node/Deno/Bun)
613
- *
614
- * This module defines:
615
- * - ExecAdapter: Process execution abstraction (#15)
616
- * - FsAdapter: Filesystem operations abstraction (#16)
617
- * - Related types and options
618
- */
619
-
620
- /**
621
- * Options for spawning a process
622
- */
623
- type SpawnOptions = {
624
- /** Command and arguments (first element is the command) */
625
- argv: string[];
626
- /** UTF-8 text to write to standard input, then close it. */
627
- stdin?: string;
628
- /** Additional environment variables */
629
- env?: Record<string, string>;
630
- /**
631
- * Whether to merge the parent process environment underneath `env`.
632
- *
633
- * - `true` (default when omitted): the parent environment is merged underneath `env`,
634
- * so the child inherits the full parent environment with `env` overrides on top.
635
- * - `false`: the child receives only the variables in `env` (and nothing from the
636
- * parent process). This prevents implicit environment variable traversal — used by
637
- * {@link CliRunner}, which resolves the inherited variables itself.
638
- */
639
- inheritEnv?: boolean;
640
- /** Working directory */
641
- cwd?: string;
642
- /** AbortSignal for cancellation */
643
- signal?: AbortSignal;
644
- /** Kill signal to use when aborting (default: SIGTERM) */
645
- killSignal?: 'SIGTERM' | 'SIGKILL';
646
- };
647
- /**
648
- * Result from spawning a process
649
- */
650
- type SpawnResult = {
651
- /** Standard output */
652
- stdout: string;
653
- /** Standard error */
654
- stderr: string;
655
- /** Exit code (-1 if unknown) */
656
- exitCode: number;
657
- /** Signal that terminated the process (if any) */
658
- signal?: string;
659
- /** Whether the process was aborted via AbortSignal */
660
- aborted: boolean;
661
- };
662
- /**
663
- * Stream handler for incremental output
664
- *
665
- * Used for progress tracking and real-time output processing.
666
- */
667
- type StreamHandler = {
668
- /** Called when stdout data is received */
669
- onStdout?: (chunk: string) => void;
670
- /** Called when stderr data is received */
671
- onStderr?: (chunk: string) => void;
672
- };
673
- /**
674
- * Handle to a spawned process
675
- *
676
- * Allows streaming output and waiting for completion.
677
- * Implements AsyncDisposable for use with `await using`.
678
- *
679
- * @example
680
- * ```typescript
681
- * // Traditional usage
682
- * const handle = adapter.spawnStreaming({ argv: ['git', 'fetch'] });
683
- * try {
684
- * for await (const line of handle.stdout) { console.log(line); }
685
- * } finally {
686
- * handle.kill();
687
- * }
688
- *
689
- * // With await using (recommended)
690
- * await using handle = adapter.spawnStreaming({ argv: ['git', 'fetch'] });
691
- * for await (const line of handle.stdout) { console.log(line); }
692
- * // Automatically disposed when scope exits
693
- * ```
694
- */
695
- interface SpawnHandle extends AsyncDisposable {
696
- /** Async iterator for stdout lines */
697
- readonly stdout: AsyncIterable<string>;
698
- /** Async iterator for stderr lines */
699
- readonly stderr: AsyncIterable<string>;
700
- /** Wait for process completion */
701
- wait(): Promise<SpawnResult>;
702
- /** Kill the process */
703
- kill(signal?: 'SIGTERM' | 'SIGKILL'): void;
704
- }
705
- /**
706
- * Adapter interface for process execution
707
- *
708
- * Abstracts process spawning across Node.js, Deno, and Bun.
709
- */
710
- interface ExecAdapter {
711
- /**
712
- * Get the capabilities of this runtime
713
- */
714
- getCapabilities(): Capabilities;
715
- /**
716
- * Spawn a process and wait for completion
717
- *
718
- * @param options - Spawn options
719
- * @param handlers - Optional stream handlers for real-time output
720
- * @returns Promise resolving to spawn result
721
- */
722
- spawn(options: SpawnOptions, handlers?: StreamHandler): Promise<SpawnResult>;
723
- /**
724
- * Spawn a process with streaming support
725
- *
726
- * @param options - Spawn options
727
- * @returns Handle to the spawned process
728
- */
729
- spawnStreaming?(options: SpawnOptions): SpawnHandle;
730
- }
731
- /**
732
- * Options for tailing a file
733
- */
734
- type TailOptions = {
735
- /** Path to the file to tail */
736
- filePath: string;
737
- /** AbortSignal for cancellation */
738
- signal?: AbortSignal;
739
- /** Callback for each new line */
740
- onLine: (line: string) => void;
741
- /** Start offset in bytes (default: 0) */
742
- startOffset?: number;
743
- /** Polling interval in milliseconds (default: 100) */
744
- pollInterval?: number;
745
- };
746
- /**
747
- * Handle to a tail operation
748
- *
749
- * Implements AsyncDisposable for use with `await using`.
750
- *
751
- * @example
752
- * ```typescript
753
- * // Traditional usage
754
- * const handle = adapter.tailStreaming('/path/to/file');
755
- * try {
756
- * for await (const line of handle.lines) { console.log(line); }
757
- * } finally {
758
- * handle.stop();
759
- * }
760
- *
761
- * // With await using (recommended)
762
- * await using handle = adapter.tailStreaming('/path/to/file');
763
- * for await (const line of handle.lines) { console.log(line); }
764
- * // Automatically stopped when scope exits
765
- * ```
766
- */
767
- interface TailHandle extends AsyncDisposable {
768
- /** Async iterator for new lines */
769
- readonly lines: AsyncIterable<string>;
770
- /** Stop tailing */
771
- stop(): void;
772
- }
773
- /**
774
- * Adapter interface for filesystem operations
775
- *
776
- * Used primarily for LFS progress tracking via GIT_LFS_PROGRESS.
777
- */
778
- interface FsAdapter {
779
- /**
780
- * Create a temporary file and return its path
781
- *
782
- * @param prefix - Optional prefix for the temp file name
783
- * @returns Path to the created temporary file
784
- */
785
- createTempFile(prefix?: string): Promise<string>;
786
- /**
787
- * Start tailing a file (watching for new lines)
788
- *
789
- * @param options - Tail options
790
- * @returns Promise that resolves when tailing stops
791
- */
792
- tail(options: TailOptions): Promise<void>;
793
- /**
794
- * Start tailing a file with streaming support
795
- *
796
- * @param filePath - Path to the file to tail
797
- * @param options - Optional tail options
798
- * @returns Handle to the tail operation
799
- */
800
- tailStreaming?(filePath: string, options?: {
801
- signal?: AbortSignal;
802
- pollInterval?: number;
803
- }): TailHandle;
804
- /**
805
- * Delete a file
806
- *
807
- * @param filePath - Path to the file to delete
808
- */
809
- deleteFile(filePath: string): Promise<void>;
810
- /**
811
- * Delete a directory recursively
812
- *
813
- * @param dirPath - Path to the directory to delete
814
- */
815
- deleteDirectory(dirPath: string): Promise<void>;
816
- /**
817
- * Check if a file exists
818
- *
819
- * @param filePath - Path to check
820
- * @returns Whether the file exists
821
- */
822
- exists(filePath: string): Promise<boolean>;
823
- /**
824
- * Read a file's contents
825
- *
826
- * @param filePath - Path to the file
827
- * @returns File contents as string
828
- */
829
- readFile?(filePath: string): Promise<string>;
830
- /**
831
- * Write contents to a file
832
- *
833
- * @param filePath - Path to the file
834
- * @param contents - Contents to write
835
- */
836
- writeFile?(filePath: string, contents: string): Promise<void>;
837
- }
838
- /**
839
- * Combined adapters for a runtime
840
- */
841
- interface RuntimeAdapters {
842
- exec: ExecAdapter;
843
- fs: FsAdapter;
844
- }
845
- /**
846
- * Factory function type for creating runtime adapters
847
- */
848
- type AdapterFactory = () => RuntimeAdapters;
849
-
850
- export { type AuditConfig as A, type AuditEventEnd as B, type Capabilities as C, DEFAULT_ENV_ALLOWLIST as D, type ExecAdapter as E, type FsAdapter as F, type GitErrorCategory as G, type AuditEvent as H, type TraceEvent as I, type LfsMode as L, type NonEmptyString as N, type OutputContract as O, type RuntimeAdapters as R, type SpawnOptions as S, type TailOptions as T, type StreamHandler as a, type SpawnResult as b, type SpawnHandle as c, type TailHandle as d, type ExecOpts as e, type RawResult as f, type GitProgress as g, type GitOpenOptions as h, type EnvInheritance as i, type ExecutionContext as j, GitError as k, type AdapterFactory as l, type EnvAllowlistAdjustment as m, type EnvInheritancePredicate as n, nonEmpty as o, isNonEmpty as p, type LfsProgress as q, resolveInheritedEnv as r, type GitErrorKind as s, GitArgumentError as t, type Runtime as u, type CommandSpec as v, type CredentialRequest as w, type Credential as x, type CredentialConfig as y, type AuditEventStart as z };