@zero-transfer/google-drive 0.1.4 → 0.1.6

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/dist/index.d.ts CHANGED
@@ -1,3 +1,3185 @@
1
- // AUTO-GENERATED. Edit scripts/scope-manifest.mjs and re-run packages:generate.
2
- export { createGoogleDriveProviderFactory } from "@zero-transfer/sdk";
3
- export type { GoogleDriveProviderOptions } from "@zero-transfer/sdk";
1
+ import { EventEmitter } from 'node:events';
2
+ import { SecureVersion, PeerCertificate } from 'node:tls';
3
+ import { Readable } from 'node:stream';
4
+ import { BaseAgent, Algorithms } from 'ssh2';
5
+ import { Buffer } from 'node:buffer';
6
+
7
+ /**
8
+ * Structured logging contracts and helpers for ZeroTransfer.
9
+ *
10
+ * The logger shape is intentionally compatible with popular structured loggers while
11
+ * staying small enough for applications to implement directly.
12
+ *
13
+ * @module logging/Logger
14
+ */
15
+ /** Supported ZeroTransfer log levels. */
16
+ type LogLevel = "trace" | "debug" | "info" | "warn" | "error";
17
+ /**
18
+ * Complete structured log record emitted by ZeroTransfer helpers.
19
+ */
20
+ interface LogRecord {
21
+ /** Severity level for the record. */
22
+ level: LogLevel;
23
+ /** Human-readable summary message. */
24
+ message: string;
25
+ /** SDK component that produced the record. */
26
+ component?: string;
27
+ /** Active protocol for the record. */
28
+ protocol?: string;
29
+ /** Remote host associated with the record. */
30
+ host?: string;
31
+ /** Correlation id for a connection lifecycle. */
32
+ connectionId?: string;
33
+ /** Correlation id for a protocol command. */
34
+ commandId?: string;
35
+ /** Correlation id for a transfer lifecycle. */
36
+ transferId?: string;
37
+ /** Remote or local path associated with the record. */
38
+ path?: string;
39
+ /** Operation duration in milliseconds. */
40
+ durationMs?: number;
41
+ /** Byte count associated with the operation. */
42
+ bytes?: number;
43
+ /** Additional structured fields supplied by adapters or services. */
44
+ [key: string]: unknown;
45
+ }
46
+ /**
47
+ * Log record input accepted by {@link emitLog}; the helper adds the level.
48
+ */
49
+ interface LogRecordInput extends Omit<LogRecord, "level"> {
50
+ /** Human-readable summary message. */
51
+ message: string;
52
+ }
53
+ /**
54
+ * Logger method signature used for each severity level.
55
+ *
56
+ * @param record - Structured log record.
57
+ * @param message - Convenience message argument for console-like loggers.
58
+ */
59
+ type LoggerMethod = (record: LogRecord, message?: string) => void;
60
+ /**
61
+ * Partial structured logger accepted by ZeroTransfer.
62
+ */
63
+ interface ZeroTransferLogger {
64
+ /** Receives highly detailed diagnostic records. */
65
+ trace?: LoggerMethod;
66
+ /** Receives development/debugging records. */
67
+ debug?: LoggerMethod;
68
+ /** Receives normal lifecycle records. */
69
+ info?: LoggerMethod;
70
+ /** Receives recoverable issue records. */
71
+ warn?: LoggerMethod;
72
+ /** Receives failed operation records. */
73
+ error?: LoggerMethod;
74
+ }
75
+ /**
76
+ * Logger implementation that intentionally drops every record.
77
+ */
78
+ declare const noopLogger: Required<ZeroTransferLogger>;
79
+ /**
80
+ * Emits a structured log record if the logger implements the requested level.
81
+ *
82
+ * @param logger - Logger that may contain a method for the requested level.
83
+ * @param level - Severity level to emit.
84
+ * @param record - Log record fields without the level property.
85
+ * @returns Nothing; missing logger methods are ignored.
86
+ */
87
+ declare function emitLog(logger: ZeroTransferLogger, level: LogLevel, record: LogRecordInput): void;
88
+
89
+ /**
90
+ * Provider identifiers used by the provider-neutral ZeroTransfer core.
91
+ *
92
+ * @module core/ProviderId
93
+ */
94
+ /** Classic remote-transfer providers kept compatible with the original protocol field. */
95
+ declare const CLASSIC_PROVIDER_IDS: readonly ["ftp", "ftps", "sftp"];
96
+ /** Provider ids that map directly to the original protocol-focused alpha facade. */
97
+ type ClassicProviderId = (typeof CLASSIC_PROVIDER_IDS)[number];
98
+ /** Provider ids reserved for first-party ZeroTransfer adapters. */
99
+ type BuiltInProviderId = ClassicProviderId | "memory" | "local" | "http" | "https" | "webdav" | "s3" | "azure-blob" | "gcs" | "dropbox" | "google-drive" | "one-drive";
100
+ /** Provider identifier accepted by registries, profiles, and provider factories. */
101
+ type ProviderId = BuiltInProviderId | (string & {});
102
+ /** Minimal shape used to resolve a provider from new and compatibility profile fields. */
103
+ interface ProviderSelection {
104
+ /** Provider id for provider-neutral ZeroTransfer profiles. */
105
+ provider?: ProviderId;
106
+ /** Compatibility protocol field accepted while the provider-neutral API rolls out. */
107
+ protocol?: ClassicProviderId;
108
+ }
109
+ /**
110
+ * Checks whether a provider id belongs to the classic FTP/FTPS/SFTP family.
111
+ *
112
+ * @param providerId - Provider id to inspect.
113
+ * @returns `true` when the id is one of the classic protocol providers.
114
+ */
115
+ declare function isClassicProviderId(providerId: ProviderId | undefined): providerId is ClassicProviderId;
116
+ /**
117
+ * Resolves the provider id from a profile, preferring the new `provider` field.
118
+ *
119
+ * @param selection - Profile-like object containing provider and/or protocol fields.
120
+ * @returns The selected provider id, or `undefined` when neither field is present.
121
+ */
122
+ declare function resolveProviderId(selection: ProviderSelection): ProviderId | undefined;
123
+
124
+ /**
125
+ * Provider capability contracts for the provider-neutral ZeroTransfer core.
126
+ *
127
+ * @module core/CapabilitySet
128
+ */
129
+
130
+ /** Authentication mechanisms a provider can advertise. */
131
+ type AuthenticationCapability = "anonymous" | "password" | "private-key" | "token" | "oauth" | "service-account" | (string & {});
132
+ /** Checksum or integrity mechanisms a provider can advertise. */
133
+ type ChecksumCapability = "crc32" | "crc32c" | "etag" | "md5" | "sha1" | "sha256" | (string & {});
134
+ /** Metadata fields a provider can preserve or report. */
135
+ type MetadataCapability = "accessedAt" | "createdAt" | "group" | "mimeType" | "modifiedAt" | "owner" | "permissions" | "storageClass" | "symlinkTarget" | "tags" | "uniqueId" | (string & {});
136
+ /**
137
+ * Capability snapshot advertised by a provider factory and active session.
138
+ */
139
+ interface CapabilitySet {
140
+ /** Provider this capability set describes. */
141
+ provider: ProviderId;
142
+ /** Authentication mechanisms accepted by the provider. */
143
+ authentication: AuthenticationCapability[];
144
+ /** Whether the provider can list child entries. */
145
+ list: boolean;
146
+ /** Whether the provider can read metadata for a path. */
147
+ stat: boolean;
148
+ /** Whether the provider can produce readable streams. */
149
+ readStream: boolean;
150
+ /** Whether the provider can accept writable streams. */
151
+ writeStream: boolean;
152
+ /** Whether the provider can copy data without routing bytes through the client. */
153
+ serverSideCopy: boolean;
154
+ /** Whether the provider can move data without routing bytes through the client. */
155
+ serverSideMove: boolean;
156
+ /** Whether the provider can resume partial downloads. */
157
+ resumeDownload: boolean;
158
+ /** Whether the provider can resume partial uploads. */
159
+ resumeUpload: boolean;
160
+ /** Checksum or provider hash mechanisms available for verification. */
161
+ checksum: ChecksumCapability[];
162
+ /** Whether rename operations are atomic within the provider. */
163
+ atomicRename: boolean;
164
+ /** Whether chmod-style permission changes are supported. */
165
+ chmod: boolean;
166
+ /** Whether owner changes are supported. */
167
+ chown: boolean;
168
+ /** Whether symbolic links are supported. */
169
+ symlink: boolean;
170
+ /** Metadata fields the provider can preserve or report. */
171
+ metadata: MetadataCapability[];
172
+ /** Recommended maximum concurrent operations for this provider. */
173
+ maxConcurrency?: number;
174
+ /** Human-readable caveats for diagnostics or provider matrices. */
175
+ notes?: string[];
176
+ }
177
+
178
+ /**
179
+ * Secret source contracts and resolution helpers for connection profiles.
180
+ *
181
+ * @module profiles/SecretSource
182
+ */
183
+
184
+ /** Resolved secret value accepted by profile credential fields. */
185
+ type SecretValue = string | Buffer;
186
+ /** Callback source used by applications to integrate vaults or credential brokers. */
187
+ type SecretProvider = () => SecretValue | Promise<SecretValue>;
188
+ /** Inline secret descriptor. Prefer env, path, or callback sources for real applications. */
189
+ interface ValueSecretSource {
190
+ /** Inline secret value. */
191
+ value: SecretValue;
192
+ }
193
+ /** Environment variable descriptor for text secrets. */
194
+ interface EnvSecretSource {
195
+ /** Environment variable containing the secret. */
196
+ env: string;
197
+ }
198
+ /** Environment variable descriptor for base64-encoded binary secrets. */
199
+ interface Base64EnvSecretSource {
200
+ /** Environment variable containing a base64-encoded secret. */
201
+ base64Env: string;
202
+ }
203
+ /** File-backed secret descriptor. */
204
+ interface FileSecretSource {
205
+ /** Path to the file containing the secret. */
206
+ path: string;
207
+ /** Text encoding to use, or `buffer` to return raw bytes. Defaults to `utf8`. */
208
+ encoding?: BufferEncoding | "buffer";
209
+ }
210
+ /** Secret source accepted by profile credential fields. */
211
+ type SecretSource = SecretValue | SecretProvider | ValueSecretSource | EnvSecretSource | Base64EnvSecretSource | FileSecretSource;
212
+ /** Injectable dependencies used by tests or host applications during secret resolution. */
213
+ interface ResolveSecretOptions {
214
+ /** Environment source. Defaults to `process.env`. */
215
+ env?: NodeJS.ProcessEnv;
216
+ /** File reader. Defaults to `fs.promises.readFile`. */
217
+ readFile?: (path: string) => Promise<Buffer> | Buffer;
218
+ }
219
+ /**
220
+ * Resolves a secret source into a string or Buffer without logging the value.
221
+ *
222
+ * @param source - Secret source to resolve.
223
+ * @param options - Optional env and file-reader overrides.
224
+ * @returns Resolved secret value.
225
+ * @throws {@link ConfigurationError} When a descriptor is invalid or unavailable.
226
+ */
227
+ declare function resolveSecret(source: SecretSource, options?: ResolveSecretOptions): Promise<SecretValue>;
228
+ /**
229
+ * Redacts a secret source or resolved secret for safe diagnostics.
230
+ *
231
+ * @param source - Secret source or resolved value to sanitize.
232
+ * @returns Redacted placeholder or descriptor shape.
233
+ */
234
+ declare function redactSecretSource(source: SecretSource | SecretValue): unknown;
235
+
236
+ /**
237
+ * Public data contracts shared by the ZeroTransfer facade, adapters, and services.
238
+ *
239
+ * These types are intentionally protocol-neutral so FTP, FTPS, and SFTP adapters can
240
+ * report the same metadata, transfer, and connection shapes to application code.
241
+ *
242
+ * @module types/public
243
+ */
244
+
245
+ /** Supported remote file-transfer protocols. */
246
+ type RemoteProtocol = ClassicProviderId;
247
+ /** Normalized remote entry kinds returned by listing and metadata operations. */
248
+ type RemoteEntryType = "file" | "directory" | "symlink" | "unknown";
249
+ /**
250
+ * Portable permission metadata for a remote entry.
251
+ */
252
+ interface RemotePermissions {
253
+ /** Raw protocol permission text, such as Unix mode characters or MLSD `perm` facts. */
254
+ raw?: string;
255
+ /** User/owner permission component when the protocol exposes it. */
256
+ user?: string;
257
+ /** Group permission component when the protocol exposes it. */
258
+ group?: string;
259
+ /** Other/world permission component when the protocol exposes it. */
260
+ other?: string;
261
+ }
262
+ /**
263
+ * Normalized remote file-system entry.
264
+ */
265
+ interface RemoteEntry {
266
+ /** Absolute or normalized remote path for the entry. */
267
+ path: string;
268
+ /** Entry basename without parent directory segments. */
269
+ name: string;
270
+ /** Normalized entry kind. */
271
+ type: RemoteEntryType;
272
+ /** Entry size in bytes when known. */
273
+ size?: number;
274
+ /** Last modification time when known. */
275
+ modifiedAt?: Date;
276
+ /** Creation time when the protocol exposes it. */
277
+ createdAt?: Date;
278
+ /** Last access time when the protocol exposes it. */
279
+ accessedAt?: Date;
280
+ /** Portable permission details when known. */
281
+ permissions?: RemotePermissions;
282
+ /** Owner name or id when known. */
283
+ owner?: string;
284
+ /** Group name or id when known. */
285
+ group?: string;
286
+ /** Target path for symbolic links when known. */
287
+ symlinkTarget?: string;
288
+ /** Protocol-specific stable identity when available. */
289
+ uniqueId?: string;
290
+ /** Raw protocol payload retained for diagnostics or advanced callers. */
291
+ raw?: unknown;
292
+ }
293
+ /**
294
+ * Metadata for a remote entry that is known to exist.
295
+ */
296
+ interface RemoteStat extends RemoteEntry {
297
+ /** Existence discriminator for successful stat operations. */
298
+ exists: true;
299
+ }
300
+ /**
301
+ * TLS material source accepted by certificate-aware connection profiles.
302
+ *
303
+ * A single source is used for most fields; `ca` may use an array to preserve an
304
+ * ordered certificate authority bundle.
305
+ */
306
+ type TlsSecretSource = SecretSource | SecretSource[];
307
+ /** Known-hosts material source accepted by SSH connection profiles. */
308
+ type SshKnownHostsSource = SecretSource | SecretSource[];
309
+ /** SSH agent source accepted by SFTP providers. */
310
+ type SshAgentSource = string | BaseAgent;
311
+ /** SSH transport algorithm overrides accepted by SFTP providers. */
312
+ type SshAlgorithms = Algorithms;
313
+ /** Context passed to SSH socket factories before opening an SSH session. */
314
+ interface SshSocketFactoryContext {
315
+ /** Target SSH host from the resolved connection profile. */
316
+ host: string;
317
+ /** Target SSH port from the resolved connection profile. */
318
+ port: number;
319
+ /** Resolved username, when configured on the connection profile. */
320
+ username?: string;
321
+ /** Abort signal from the connection profile, when one is configured. */
322
+ signal?: AbortSignal;
323
+ }
324
+ /**
325
+ * Creates a preconnected socket-like stream for SSH sessions.
326
+ *
327
+ * Use this hook for HTTP CONNECT, SOCKS, bastion, or custom tunnel integrations.
328
+ *
329
+ * @param context - Resolved SSH target information for the socket being opened.
330
+ * @returns Preconnected readable stream, or a promise for one, passed to ssh2's `sock` option.
331
+ */
332
+ type SshSocketFactory = (context: SshSocketFactoryContext) => Readable | Promise<Readable>;
333
+ /** Prompt metadata supplied by an SSH keyboard-interactive server challenge. */
334
+ interface SshKeyboardInteractivePrompt {
335
+ /** Human-readable prompt text supplied by the SSH server. */
336
+ prompt: string;
337
+ /** Whether the answer may be echoed to a terminal or UI. */
338
+ echo?: boolean;
339
+ }
340
+ /** Input passed to SSH keyboard-interactive answer providers. */
341
+ interface SshKeyboardInteractiveChallenge {
342
+ /** Server-provided challenge title. */
343
+ name: string;
344
+ /** Server-provided instructions for the prompt set. */
345
+ instructions: string;
346
+ /** Server-provided language tag, when supplied. */
347
+ language: string;
348
+ /** Ordered prompts that require answers. */
349
+ prompts: readonly SshKeyboardInteractivePrompt[];
350
+ }
351
+ /** Provides ordered answers for an SSH keyboard-interactive authentication challenge. */
352
+ type SshKeyboardInteractiveHandler = (challenge: SshKeyboardInteractiveChallenge) => readonly string[] | Promise<readonly string[]>;
353
+ /**
354
+ * TLS settings shared by certificate-aware providers such as FTPS and future HTTPS/WebDAV adapters.
355
+ *
356
+ * Secret-bearing fields accept inline values, environment-backed values, or file-backed values,
357
+ * and are resolved by providers before opening TLS sockets.
358
+ */
359
+ interface TlsProfile {
360
+ /** Certificate authority bundle used to validate private or self-signed endpoints. */
361
+ ca?: TlsSecretSource;
362
+ /** Client certificate PEM used for mutual TLS when a provider requires it. */
363
+ cert?: SecretSource;
364
+ /** Client private key PEM used with `cert`. */
365
+ key?: SecretSource;
366
+ /** PFX/P12 client certificate bundle. */
367
+ pfx?: SecretSource;
368
+ /** Passphrase for an encrypted private key or PFX/P12 bundle. */
369
+ passphrase?: SecretSource;
370
+ /** Server name used for SNI and certificate identity checks. Defaults to the profile host. */
371
+ servername?: string;
372
+ /** Whether TLS certificate validation is required. Defaults to `true`. */
373
+ rejectUnauthorized?: boolean;
374
+ /** Minimum TLS protocol version accepted by the client. */
375
+ minVersion?: SecureVersion;
376
+ /** Maximum TLS protocol version accepted by the client. */
377
+ maxVersion?: SecureVersion;
378
+ /**
379
+ * Optional. Expected server certificate SHA-256 fingerprint(s) for **certificate pinning**, in
380
+ * hex form with or without colons. When present, the TLS handshake additionally requires the
381
+ * leaf certificate's SHA-256 fingerprint to match one of these values.
382
+ *
383
+ * Not required for normal CA-trusted endpoints — public CAs and `ca` bundles already gate
384
+ * trust via `rejectUnauthorized`. Pinning is **recommended for production** when you control
385
+ * the server and want defence-in-depth against rogue certificates issued by trusted CAs.
386
+ *
387
+ * @example "AA:BB:CC:DD:EE:FF:00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33:44:55:66:77:88:99"
388
+ */
389
+ pinnedFingerprint256?: string | readonly string[];
390
+ /** Optional custom server identity checker for private PKI or certificate pinning. */
391
+ checkServerIdentity?: (host: string, cert: PeerCertificate) => Error | undefined;
392
+ }
393
+ /**
394
+ * SSH authentication material for SFTP-style providers.
395
+ *
396
+ * Secret-bearing fields accept inline values, environment-backed values, or file-backed values,
397
+ * and are resolved by providers before opening SSH sessions.
398
+ */
399
+ interface SshProfile {
400
+ /** SSH agent socket path or agent instance used for agent-based public-key authentication. */
401
+ agent?: SshAgentSource;
402
+ /** Explicit SSH transport algorithm overrides for ciphers, KEX, host keys, MACs, and compression. */
403
+ algorithms?: SshAlgorithms;
404
+ /** Private key material used for public-key authentication. */
405
+ privateKey?: SecretSource;
406
+ /** Passphrase used to decrypt an encrypted private key. */
407
+ passphrase?: SecretSource;
408
+ /**
409
+ * Optional. OpenSSH `known_hosts` content used for **strict SFTP host-key verification**.
410
+ * Mutually exclusive with provider-level `hostHash`/`hostVerifier` options.
411
+ *
412
+ * Not required for the connection to succeed, but **strongly recommended for production**:
413
+ * without `knownHosts` (and without {@link SshProfile.pinnedHostKeySha256 | pinnedHostKeySha256}),
414
+ * the SSH session accepts any host key the server presents, leaving you exposed to MITM.
415
+ */
416
+ knownHosts?: SshKnownHostsSource;
417
+ /**
418
+ * Optional. SSH host-key SHA-256 fingerprint(s) the remote must present, in OpenSSH
419
+ * `SHA256:<base64>` form, raw base64, or hex.
420
+ *
421
+ * Use this as a lighter-weight alternative to a full `known_hosts` file when you only need
422
+ * to pin a single host. Like `knownHosts`, it is **optional but recommended for production**;
423
+ * leaving both unset disables host-key verification entirely.
424
+ *
425
+ * @example "SHA256:abc123basesixfourpinFromKnownHosts="
426
+ */
427
+ pinnedHostKeySha256?: string | readonly string[];
428
+ /** Runtime callback that answers SSH keyboard-interactive authentication prompts. */
429
+ keyboardInteractive?: SshKeyboardInteractiveHandler;
430
+ /** Runtime callback that returns a preconnected stream used instead of opening a direct TCP socket. */
431
+ socketFactory?: SshSocketFactory;
432
+ }
433
+ /**
434
+ * Connection settings accepted by facade and adapter implementations.
435
+ *
436
+ * Every `ConnectionProfile` has a `host` and a `provider` (or `protocol`).
437
+ * Authentication and transport-specific material is layered on via the
438
+ * optional `ssh`, `tls`, `oauth`, and provider-specific blocks (e.g. `s3`,
439
+ * `azure`, `dropbox`).
440
+ *
441
+ * @example SFTP with public-key auth
442
+ * ```ts
443
+ * const profile: ConnectionProfile = {
444
+ * host: "sftp.example.com",
445
+ * provider: "sftp",
446
+ * username: "deploy",
447
+ * ssh: {
448
+ * privateKey: { path: "./keys/id_ed25519" },
449
+ * pinnedHostKeySha256: "SHA256:abc123basesixfourpinFromKnownHosts=",
450
+ * },
451
+ * };
452
+ * ```
453
+ *
454
+ * @example FTPS with username/password and public-CA TLS
455
+ * ```ts
456
+ * const profile: ConnectionProfile = {
457
+ * host: "ftps.example.com",
458
+ * provider: "ftps",
459
+ * username: "deploy",
460
+ * password: { env: "FTPS_PASSWORD" },
461
+ * tls: { minVersion: "TLSv1.2" },
462
+ * };
463
+ * ```
464
+ *
465
+ * @example S3-compatible
466
+ * ```ts
467
+ * const profile: ConnectionProfile = {
468
+ * host: "my-bucket",
469
+ * provider: "s3",
470
+ * username: process.env.AWS_ACCESS_KEY_ID,
471
+ * password: { env: "AWS_SECRET_ACCESS_KEY" },
472
+ * s3: { region: "us-east-1" },
473
+ * };
474
+ * ```
475
+ */
476
+ interface ConnectionProfile {
477
+ /** Provider to use for this connection. Prefer this over the compatibility protocol field. */
478
+ provider?: ProviderId;
479
+ /** Protocol to use for this connection, overriding the client default. */
480
+ protocol?: RemoteProtocol;
481
+ /** Remote hostname or IP address. */
482
+ host: string;
483
+ /** Remote port; adapters should apply protocol defaults when omitted. */
484
+ port?: number;
485
+ /** Username, account identifier, or deferred secret source for authentication. */
486
+ username?: SecretSource;
487
+ /** Password or deferred secret source for password-based authentication. */
488
+ password?: SecretSource;
489
+ /** Whether encrypted transport should be requested for protocols that support it. */
490
+ secure?: boolean;
491
+ /** TLS settings for encrypted providers such as FTPS. */
492
+ tls?: TlsProfile;
493
+ /** SSH settings for SFTP providers. */
494
+ ssh?: SshProfile;
495
+ /** Operation or connection timeout in milliseconds. */
496
+ timeoutMs?: number;
497
+ /** Abort signal used to cancel connection setup or long-running operations. */
498
+ signal?: AbortSignal;
499
+ /** Per-profile logger override. */
500
+ logger?: ZeroTransferLogger;
501
+ }
502
+ /**
503
+ * Options for remote directory listing operations.
504
+ */
505
+ interface ListOptions {
506
+ /** Recursively walk child directories when supported by the adapter. */
507
+ recursive?: boolean;
508
+ /** Include hidden or dot-prefixed entries when the protocol/listing format supports it. */
509
+ includeHidden?: boolean;
510
+ /** Abort signal used to cancel the listing operation. */
511
+ signal?: AbortSignal;
512
+ }
513
+ /**
514
+ * Options for remote metadata lookup operations.
515
+ */
516
+ interface StatOptions {
517
+ /** Abort signal used to cancel the metadata operation. */
518
+ signal?: AbortSignal;
519
+ }
520
+ /**
521
+ * Options for removing a remote file entry.
522
+ */
523
+ interface RemoveOptions {
524
+ /** Abort signal used to cancel the operation. */
525
+ signal?: AbortSignal;
526
+ /** When true, do not throw if the path does not exist. */
527
+ ignoreMissing?: boolean;
528
+ }
529
+ /**
530
+ * Options for renaming or moving a remote entry.
531
+ */
532
+ interface RenameOptions {
533
+ /** Abort signal used to cancel the operation. */
534
+ signal?: AbortSignal;
535
+ /** Allow overwriting an existing destination when the provider supports it. */
536
+ overwrite?: boolean;
537
+ }
538
+ /**
539
+ * Options for creating a remote directory.
540
+ */
541
+ interface MkdirOptions {
542
+ /** Abort signal used to cancel the operation. */
543
+ signal?: AbortSignal;
544
+ /** Create missing parent directories along the way. */
545
+ recursive?: boolean;
546
+ }
547
+ /**
548
+ * Options for removing a remote directory.
549
+ */
550
+ interface RmdirOptions {
551
+ /** Abort signal used to cancel the operation. */
552
+ signal?: AbortSignal;
553
+ /** Recursively remove non-empty directory contents. */
554
+ recursive?: boolean;
555
+ /** When true, do not throw if the path does not exist. */
556
+ ignoreMissing?: boolean;
557
+ }
558
+ /**
559
+ * Progress snapshot emitted while a transfer is running.
560
+ */
561
+ interface TransferProgressEvent {
562
+ /** Stable transfer identifier used to correlate logs and events. */
563
+ transferId: string;
564
+ /** Bytes successfully transferred so far. */
565
+ bytesTransferred: number;
566
+ /** Total expected bytes when the adapter can determine the remote or local size. */
567
+ totalBytes?: number;
568
+ /** Time at which the transfer began. */
569
+ startedAt: Date;
570
+ /** Elapsed transfer time in milliseconds. */
571
+ elapsedMs: number;
572
+ /** Current average throughput in bytes per second. */
573
+ bytesPerSecond: number;
574
+ /** Completion percentage when `totalBytes` is known. */
575
+ percent?: number;
576
+ }
577
+ /**
578
+ * Final summary for a completed transfer.
579
+ */
580
+ interface TransferResult {
581
+ /** Local or remote source path when known for the operation. */
582
+ sourcePath?: string;
583
+ /** Local or remote destination path for the completed transfer. */
584
+ destinationPath: string;
585
+ /** Total bytes transferred. */
586
+ bytesTransferred: number;
587
+ /** Time at which the transfer began. */
588
+ startedAt: Date;
589
+ /** Time at which the transfer completed. */
590
+ completedAt: Date;
591
+ /** Total transfer duration in milliseconds. */
592
+ durationMs: number;
593
+ /** Average throughput in bytes per second. */
594
+ averageBytesPerSecond: number;
595
+ /** Whether the transfer resumed from a prior partial state. */
596
+ resumed: boolean;
597
+ /** Whether post-transfer verification completed successfully. */
598
+ verified: boolean;
599
+ /** Optional checksum value produced or verified by the transfer workflow. */
600
+ checksum?: string;
601
+ }
602
+
603
+ /**
604
+ * Provider-neutral remote file-system contract.
605
+ *
606
+ * @module providers/RemoteFileSystem
607
+ */
608
+
609
+ /** Minimal file-system surface shared by provider sessions. */
610
+ interface RemoteFileSystem {
611
+ /** Lists entries for a provider path. */
612
+ list(path: string, options?: ListOptions): Promise<RemoteEntry[]>;
613
+ /** Reads metadata for a provider path. */
614
+ stat(path: string, options?: StatOptions): Promise<RemoteStat>;
615
+ /** Removes a file entry when supported by the provider. */
616
+ remove?(path: string, options?: RemoveOptions): Promise<void>;
617
+ /** Renames or moves an entry when supported by the provider. */
618
+ rename?(from: string, to: string, options?: RenameOptions): Promise<void>;
619
+ /** Creates a directory when supported by the provider. */
620
+ mkdir?(path: string, options?: MkdirOptions): Promise<void>;
621
+ /** Removes a directory when supported by the provider. */
622
+ rmdir?(path: string, options?: RmdirOptions): Promise<void>;
623
+ }
624
+
625
+ /**
626
+ * Transfer job and receipt contracts used by the transfer engine foundation.
627
+ *
628
+ * @module transfers/TransferJob
629
+ */
630
+
631
+ /** Provider-neutral transfer operation names. */
632
+ type TransferOperation = "copy" | "delete" | "download" | "move" | "sync" | "upload" | (string & {});
633
+ /** Endpoint referenced by a transfer job or receipt. */
634
+ interface TransferEndpoint {
635
+ /** Provider that owns the endpoint when known. */
636
+ provider?: ProviderId;
637
+ /** Provider, remote, or local path for the endpoint. */
638
+ path: string;
639
+ }
640
+ /** Transfer job input consumed by {@link TransferEngine}. */
641
+ interface TransferJob {
642
+ /** Stable job identifier for correlation. */
643
+ id: string;
644
+ /** Operation the job performs. */
645
+ operation: TransferOperation;
646
+ /** Source endpoint for operations that read data. */
647
+ source?: TransferEndpoint;
648
+ /** Destination endpoint for operations that write data. */
649
+ destination?: TransferEndpoint;
650
+ /** Expected total bytes when known before execution. */
651
+ totalBytes?: number;
652
+ /** Whether this job is resuming prior partial work. */
653
+ resumed?: boolean;
654
+ /** Caller-defined metadata retained for diagnostics. */
655
+ metadata?: Record<string, unknown>;
656
+ }
657
+ /** Optional throughput limit shape that concrete transfer executors may honor. */
658
+ interface TransferBandwidthLimit {
659
+ /** Maximum sustained transfer rate in bytes per second. */
660
+ bytesPerSecond: number;
661
+ /** Optional burst allowance in bytes for token-bucket-style implementations. */
662
+ burstBytes?: number;
663
+ }
664
+ /** Timeout policy applied by the transfer engine. */
665
+ interface TransferTimeoutPolicy {
666
+ /** Maximum duration for the full engine execution, including retries, in milliseconds. */
667
+ timeoutMs?: number;
668
+ /** Whether timeout failures are retryable. Defaults to `true`. */
669
+ retryable?: boolean;
670
+ }
671
+ /** Normalized post-transfer verification details. */
672
+ interface TransferVerificationResult {
673
+ /** Whether verification completed successfully. */
674
+ verified: boolean;
675
+ /** Verification method, such as checksum, size, timestamp, or provider-native. */
676
+ method?: string;
677
+ /** Checksum value produced or verified by the operation. */
678
+ checksum?: string;
679
+ /** Expected checksum when a checksum comparison was performed. */
680
+ expectedChecksum?: string;
681
+ /** Actual checksum observed by the operation. */
682
+ actualChecksum?: string;
683
+ /** Caller-defined verification details retained for diagnostics. */
684
+ details?: Record<string, unknown>;
685
+ }
686
+ /** Result returned by a transfer operation implementation. */
687
+ interface TransferExecutionResult {
688
+ /** Bytes transferred by the completed operation. */
689
+ bytesTransferred: number;
690
+ /** Total expected bytes when discovered during execution. */
691
+ totalBytes?: number;
692
+ /** Whether the operation resumed prior partial work. */
693
+ resumed?: boolean;
694
+ /** Whether post-transfer verification completed successfully. */
695
+ verified?: boolean;
696
+ /** Normalized post-transfer verification details. */
697
+ verification?: TransferVerificationResult;
698
+ /** Optional checksum value produced or verified by the operation. */
699
+ checksum?: string;
700
+ /** Non-fatal warnings produced during execution. */
701
+ warnings?: string[];
702
+ }
703
+ /** Serializable error summary retained in failed attempts. */
704
+ interface TransferAttemptError {
705
+ /** Error class or constructor name. */
706
+ name: string;
707
+ /** Human-readable error message. */
708
+ message: string;
709
+ /** Stable SDK error code when available. */
710
+ code?: string;
711
+ /** Whether retry policy may retry the failure. */
712
+ retryable?: boolean;
713
+ }
714
+ /** Execution attempt retained in a transfer receipt. */
715
+ interface TransferAttempt {
716
+ /** One-based attempt number. */
717
+ attempt: number;
718
+ /** Time this attempt began. */
719
+ startedAt: Date;
720
+ /** Time this attempt finished or failed. */
721
+ completedAt: Date;
722
+ /** Attempt duration in milliseconds. */
723
+ durationMs: number;
724
+ /** Bytes reported by the attempt before completion or failure. */
725
+ bytesTransferred: number;
726
+ /** Error summary for failed attempts. */
727
+ error?: TransferAttemptError;
728
+ }
729
+ /** Audit-friendly receipt for a completed transfer job. */
730
+ interface TransferReceipt {
731
+ /** Stable transfer identifier used for progress and log correlation. */
732
+ transferId: string;
733
+ /** Original job identifier. */
734
+ jobId: string;
735
+ /** Operation performed by the job. */
736
+ operation: TransferOperation;
737
+ /** Source endpoint when supplied by the job. */
738
+ source?: TransferEndpoint;
739
+ /** Destination endpoint when supplied by the job. */
740
+ destination?: TransferEndpoint;
741
+ /** Total bytes transferred by the successful operation. */
742
+ bytesTransferred: number;
743
+ /** Expected total bytes when known. */
744
+ totalBytes?: number;
745
+ /** Time the first attempt began. */
746
+ startedAt: Date;
747
+ /** Time the successful attempt completed. */
748
+ completedAt: Date;
749
+ /** Total elapsed time in milliseconds. */
750
+ durationMs: number;
751
+ /** Average throughput in bytes per second. */
752
+ averageBytesPerSecond: number;
753
+ /** Whether the transfer resumed prior partial work. */
754
+ resumed: boolean;
755
+ /** Whether post-transfer verification completed successfully. */
756
+ verified: boolean;
757
+ /** Normalized post-transfer verification details when supplied by the operation. */
758
+ verification?: TransferVerificationResult;
759
+ /** Optional checksum value produced or verified by the operation. */
760
+ checksum?: string;
761
+ /** Attempt history, including retry failures. */
762
+ attempts: TransferAttempt[];
763
+ /** Non-fatal warnings produced during execution. */
764
+ warnings: string[];
765
+ /** Caller-defined metadata retained from the job. */
766
+ metadata?: Record<string, unknown>;
767
+ }
768
+
769
+ /** Context passed to a concrete transfer operation. */
770
+ interface TransferExecutionContext {
771
+ /** Job being executed. */
772
+ job: TransferJob;
773
+ /** One-based attempt number. */
774
+ attempt: number;
775
+ /** Abort signal active for this execution when supplied. */
776
+ signal?: AbortSignal;
777
+ /** Optional throughput limit shape for concrete executors to honor. */
778
+ bandwidthLimit?: TransferBandwidthLimit;
779
+ /** Throws an SDK abort error when the active signal has been cancelled. */
780
+ throwIfAborted(): void;
781
+ /** Emits a normalized progress event through engine options. */
782
+ reportProgress(bytesTransferred: number, totalBytes?: number): TransferProgressEvent;
783
+ }
784
+ /** Concrete transfer operation implementation used by the engine. */
785
+ type TransferExecutor = (context: TransferExecutionContext) => Promise<TransferExecutionResult> | TransferExecutionResult;
786
+ /** Input used by retry policy hooks. */
787
+ interface TransferRetryDecisionInput {
788
+ /** Error thrown by the failed attempt. */
789
+ error: unknown;
790
+ /** One-based attempt number that failed. */
791
+ attempt: number;
792
+ /** Job being executed. */
793
+ job: TransferJob;
794
+ }
795
+ /** Retry policy for transfer execution. */
796
+ interface TransferRetryPolicy {
797
+ /** Maximum total attempts, including the first attempt. Defaults to `1`. */
798
+ maxAttempts?: number;
799
+ /** Decides whether a failed attempt should be retried. Defaults to SDK retryability metadata. */
800
+ shouldRetry?(input: TransferRetryDecisionInput): boolean;
801
+ /** Observes retry decisions before the next attempt starts. */
802
+ onRetry?(input: TransferRetryDecisionInput): void;
803
+ }
804
+ /** Options used by {@link TransferEngine.execute}. */
805
+ interface TransferEngineExecuteOptions {
806
+ /** Abort signal used to cancel the job. */
807
+ signal?: AbortSignal;
808
+ /** Retry policy used for failed attempts. */
809
+ retry?: TransferRetryPolicy;
810
+ /** Progress observer for normalized transfer progress events. */
811
+ onProgress?(event: TransferProgressEvent): void;
812
+ /** Timeout policy enforced by the engine. */
813
+ timeout?: TransferTimeoutPolicy;
814
+ /** Optional throughput limit shape passed through to concrete executors. */
815
+ bandwidthLimit?: TransferBandwidthLimit;
816
+ }
817
+ /** Construction options for deterministic tests and host integration. */
818
+ interface TransferEngineOptions {
819
+ /** Clock used for receipts and progress events. Defaults to `new Date()`. */
820
+ now?: () => Date;
821
+ }
822
+ /** Executes transfer jobs and produces audit-friendly receipts. */
823
+ declare class TransferEngine {
824
+ private readonly now;
825
+ /**
826
+ * Creates a transfer engine.
827
+ *
828
+ * @param options - Optional clock override for deterministic tests.
829
+ */
830
+ constructor(options?: TransferEngineOptions);
831
+ /**
832
+ * Executes a transfer job through a caller-supplied operation.
833
+ *
834
+ * @param job - Job metadata used for correlation and receipts.
835
+ * @param executor - Concrete transfer operation implementation.
836
+ * @param options - Optional abort, retry, and progress hooks.
837
+ * @returns Receipt for the completed transfer.
838
+ * @throws {@link AbortError} When execution is cancelled.
839
+ * @throws {@link TransferError} When all attempts fail.
840
+ */
841
+ execute(job: TransferJob, executor: TransferExecutor, options?: TransferEngineExecuteOptions): Promise<TransferReceipt>;
842
+ private createExecutionContext;
843
+ private throwIfAborted;
844
+ }
845
+
846
+ /**
847
+ * Provider-backed transfer read/write contracts.
848
+ *
849
+ * @module providers/ProviderTransferOperations
850
+ */
851
+
852
+ /** Binary chunk shape used by provider transfer streams. */
853
+ type TransferDataChunk = Uint8Array;
854
+ /** Provider-neutral transfer content source. Node readable streams satisfy this shape. */
855
+ type TransferDataSource = AsyncIterable<TransferDataChunk>;
856
+ /** Byte range requested from a readable provider endpoint. */
857
+ interface TransferByteRange {
858
+ /** Zero-based byte offset where reading should begin. */
859
+ offset: number;
860
+ /** Maximum number of bytes to read when known. */
861
+ length?: number;
862
+ }
863
+ /** Shared provider transfer request fields. */
864
+ interface ProviderTransferRequest extends TransferExecutionContext {
865
+ /** Endpoint owned by the provider handling this request. */
866
+ endpoint: TransferEndpoint;
867
+ }
868
+ /** Request passed to provider read implementations. */
869
+ interface ProviderTransferReadRequest extends ProviderTransferRequest {
870
+ /** Optional byte range for resumed or partial reads. */
871
+ range?: TransferByteRange;
872
+ }
873
+ /** Result returned by provider read implementations. */
874
+ interface ProviderTransferReadResult {
875
+ /** Content stream produced by the provider. */
876
+ content: TransferDataSource;
877
+ /** Bytes already read by the provider before returning the content stream, if any. */
878
+ bytesRead?: number;
879
+ /** Expected total bytes for the content stream when known. */
880
+ totalBytes?: number;
881
+ /** Verification details produced while opening or reading the source. */
882
+ verification?: TransferVerificationResult;
883
+ /** Checksum produced while opening or reading the source. */
884
+ checksum?: string;
885
+ /** Non-fatal warnings produced by the read side. */
886
+ warnings?: string[];
887
+ }
888
+ /** Request passed to provider write implementations. */
889
+ interface ProviderTransferWriteRequest extends ProviderTransferRequest {
890
+ /** Content stream to write to the provider endpoint. */
891
+ content: TransferDataSource;
892
+ /** Expected total bytes for the content stream when known. */
893
+ totalBytes?: number;
894
+ /** Resume offset for partial writes when supported by the provider. */
895
+ offset?: number;
896
+ /** Verification details from the read side that a writer may preserve or compare. */
897
+ verification?: TransferVerificationResult;
898
+ }
899
+ /** Result returned by provider write implementations. */
900
+ type ProviderTransferWriteResult = TransferExecutionResult;
901
+ /** Optional read/write surface exposed by provider sessions that support transfer streaming. */
902
+ interface ProviderTransferOperations {
903
+ /** Opens readable content for a provider endpoint. */
904
+ read(request: ProviderTransferReadRequest): Promise<ProviderTransferReadResult> | ProviderTransferReadResult;
905
+ /** Writes readable content to a provider endpoint. */
906
+ write(request: ProviderTransferWriteRequest): Promise<ProviderTransferWriteResult> | ProviderTransferWriteResult;
907
+ }
908
+
909
+ /**
910
+ * Active provider session contract returned by provider-neutral connections.
911
+ *
912
+ * @module core/TransferSession
913
+ */
914
+
915
+ /**
916
+ * Connected provider session exposed through {@link TransferClient.connect}.
917
+ */
918
+ interface TransferSession<TRaw = unknown> {
919
+ /** Provider backing this session. */
920
+ provider: ProviderId;
921
+ /** Provider capabilities available for this connected session. */
922
+ capabilities: CapabilitySet;
923
+ /** Provider-neutral remote file-system operations. */
924
+ fs: RemoteFileSystem;
925
+ /** Optional provider-backed transfer read/write operations. */
926
+ transfers?: ProviderTransferOperations;
927
+ /** Disconnects and releases provider resources. */
928
+ disconnect(): Promise<void>;
929
+ /** Returns a provider-specific advanced interface when one exists. */
930
+ raw?(): TRaw;
931
+ }
932
+
933
+ /**
934
+ * Provider implementation contracts for ZeroTransfer adapters.
935
+ *
936
+ * @module providers/Provider
937
+ */
938
+
939
+ /** Provider implementation that can open transfer sessions. */
940
+ interface TransferProvider<TSession extends TransferSession = TransferSession> {
941
+ /** Stable provider id. */
942
+ id: ProviderId;
943
+ /** Capabilities advertised by this provider implementation. */
944
+ capabilities: CapabilitySet;
945
+ /** Opens a connected provider session. */
946
+ connect(profile: ConnectionProfile): Promise<TSession>;
947
+ }
948
+
949
+ /**
950
+ * Provider factory contracts used by the provider registry.
951
+ *
952
+ * @module providers/ProviderFactory
953
+ */
954
+
955
+ /** Factory registered with {@link ProviderRegistry} to create providers on demand. */
956
+ interface ProviderFactory<TProvider extends TransferProvider = TransferProvider> {
957
+ /** Provider id created by this factory. */
958
+ id: ProviderId;
959
+ /** Capability snapshot available without opening a network connection. */
960
+ capabilities: CapabilitySet;
961
+ /** Creates an isolated provider instance for a connection attempt. */
962
+ create(): TProvider;
963
+ }
964
+
965
+ /** Mutable registry of provider factories available to a transfer client. */
966
+ declare class ProviderRegistry {
967
+ private readonly factories;
968
+ /**
969
+ * Creates a registry and optionally seeds it with provider factories.
970
+ *
971
+ * @param providers - Provider factories to register immediately.
972
+ */
973
+ constructor(providers?: Iterable<ProviderFactory>);
974
+ /**
975
+ * Registers a provider factory.
976
+ *
977
+ * @param provider - Provider factory to add.
978
+ * @returns This registry for fluent setup.
979
+ * @throws {@link ConfigurationError} When a provider id is registered twice.
980
+ */
981
+ register(provider: ProviderFactory): this;
982
+ /**
983
+ * Removes a provider factory from the registry.
984
+ *
985
+ * @param providerId - Provider id to remove.
986
+ * @returns `true` when a provider was removed.
987
+ */
988
+ unregister(providerId: ProviderId): boolean;
989
+ /**
990
+ * Checks whether a provider id is registered.
991
+ *
992
+ * @param providerId - Provider id to inspect.
993
+ * @returns `true` when a provider factory exists.
994
+ */
995
+ has(providerId: ProviderId): boolean;
996
+ /**
997
+ * Gets a provider factory when registered.
998
+ *
999
+ * @param providerId - Provider id to retrieve.
1000
+ * @returns The provider factory, or `undefined` when missing.
1001
+ */
1002
+ get(providerId: ProviderId): ProviderFactory | undefined;
1003
+ /**
1004
+ * Gets a registered provider factory or throws a typed SDK error.
1005
+ *
1006
+ * @param providerId - Provider id to retrieve.
1007
+ * @returns The registered provider factory.
1008
+ * @throws {@link UnsupportedFeatureError} When no provider has been registered.
1009
+ */
1010
+ require(providerId: ProviderId): ProviderFactory;
1011
+ /**
1012
+ * Gets a provider capability snapshot when registered.
1013
+ *
1014
+ * @param providerId - Provider id to inspect.
1015
+ * @returns Capability snapshot, or `undefined` when missing.
1016
+ */
1017
+ getCapabilities(providerId: ProviderId): CapabilitySet | undefined;
1018
+ /**
1019
+ * Gets a provider capability snapshot or throws a typed SDK error.
1020
+ *
1021
+ * @param providerId - Provider id to inspect.
1022
+ * @returns Capability snapshot for the registered provider.
1023
+ * @throws {@link UnsupportedFeatureError} When no provider has been registered.
1024
+ */
1025
+ requireCapabilities(providerId: ProviderId): CapabilitySet;
1026
+ /**
1027
+ * Lists registered provider factories in insertion order.
1028
+ *
1029
+ * @returns Registered provider factories.
1030
+ */
1031
+ list(): ProviderFactory[];
1032
+ /**
1033
+ * Lists registered provider capabilities in insertion order.
1034
+ *
1035
+ * @returns Capability snapshots for every registered provider.
1036
+ */
1037
+ listCapabilities(): CapabilitySet[];
1038
+ }
1039
+
1040
+ /** Options used to create a provider-neutral transfer client. */
1041
+ interface TransferClientOptions {
1042
+ /** Existing registry to reuse. When omitted, a fresh empty registry is created. */
1043
+ registry?: ProviderRegistry;
1044
+ /** Provider factories to register with the client registry. */
1045
+ providers?: ProviderFactory[];
1046
+ /** Structured logger used for client lifecycle records. */
1047
+ logger?: ZeroTransferLogger;
1048
+ }
1049
+ /** Small provider-neutral client that owns provider lookup and connection setup. */
1050
+ declare class TransferClient {
1051
+ /** Provider registry used by this client. */
1052
+ readonly registry: ProviderRegistry;
1053
+ private readonly logger;
1054
+ /**
1055
+ * Creates a transfer client without opening any provider connections.
1056
+ *
1057
+ * @param options - Optional registry, provider factories, and logger.
1058
+ */
1059
+ constructor(options?: TransferClientOptions);
1060
+ /**
1061
+ * Registers a provider factory with this client's registry.
1062
+ *
1063
+ * @param provider - Provider factory to register.
1064
+ * @returns This client for fluent setup.
1065
+ */
1066
+ registerProvider(provider: ProviderFactory): this;
1067
+ /**
1068
+ * Checks whether this client can create sessions for a provider id.
1069
+ *
1070
+ * @param providerId - Provider id to inspect.
1071
+ * @returns `true` when a provider factory is registered.
1072
+ */
1073
+ hasProvider(providerId: ProviderId): boolean;
1074
+ /** Lists all registered provider capability snapshots. */
1075
+ getCapabilities(): CapabilitySet[];
1076
+ /** Gets a specific provider capability snapshot. */
1077
+ getCapabilities(providerId: ProviderId): CapabilitySet;
1078
+ /**
1079
+ * Opens a provider session using `profile.provider`, with `profile.protocol` as compatibility fallback.
1080
+ *
1081
+ * @param profile - Connection profile containing a provider or legacy protocol field.
1082
+ * @returns A connected provider session.
1083
+ * @throws {@link ConfigurationError} When neither provider nor protocol is present.
1084
+ */
1085
+ connect(profile: ConnectionProfile): Promise<TransferSession>;
1086
+ }
1087
+
1088
+ /**
1089
+ * Factory for provider-neutral ZeroTransfer clients.
1090
+ *
1091
+ * @module core/createTransferClient
1092
+ */
1093
+
1094
+ /**
1095
+ * Creates a provider-neutral transfer client.
1096
+ *
1097
+ * The returned client owns a registry of provider factories and produces
1098
+ * `TransferSession` instances on demand via {@link TransferClient.connect}.
1099
+ * Registering only the providers you actually use keeps bundle size small
1100
+ * (each factory pulls in its own SDK dependencies).
1101
+ *
1102
+ * @param options - Optional registry, provider factories, and logger.
1103
+ * @returns A disconnected {@link TransferClient} instance.
1104
+ *
1105
+ * @example Multi-provider client
1106
+ * ```ts
1107
+ * import {
1108
+ * createS3ProviderFactory,
1109
+ * createSftpProviderFactory,
1110
+ * createTransferClient,
1111
+ * } from "@zero-transfer/sdk";
1112
+ *
1113
+ * const client = createTransferClient({
1114
+ * providers: [createSftpProviderFactory(), createS3ProviderFactory()],
1115
+ * });
1116
+ *
1117
+ * const session = await client.connect({
1118
+ * host: "sftp.example.com",
1119
+ * provider: "sftp",
1120
+ * username: "deploy",
1121
+ * ssh: { privateKey: { path: "./keys/id_ed25519" } },
1122
+ * });
1123
+ * try {
1124
+ * const list = await session.fs.list("/uploads");
1125
+ * console.log(list);
1126
+ * } finally {
1127
+ * await session.disconnect();
1128
+ * }
1129
+ * ```
1130
+ *
1131
+ * @example Friendly one-shot helpers
1132
+ * ```ts
1133
+ * import { uploadFile } from "@zero-transfer/sdk";
1134
+ *
1135
+ * await uploadFile({
1136
+ * client,
1137
+ * destination: { path: "/uploads/report.csv", profile },
1138
+ * localPath: "./out/report.csv",
1139
+ * });
1140
+ * ```
1141
+ */
1142
+ declare function createTransferClient(options?: TransferClientOptions): TransferClient;
1143
+
1144
+ /**
1145
+ * Shared protocol adapter contract used by the ZeroTransfer facade.
1146
+ *
1147
+ * Protocol-specific implementations for FTP, FTPS, and SFTP should conform to this
1148
+ * interface so high-level client code can remain protocol-neutral.
1149
+ *
1150
+ * @module protocols/RemoteFileAdapter
1151
+ */
1152
+
1153
+ /**
1154
+ * Minimal remote-file adapter required by the current alpha facade.
1155
+ */
1156
+ interface RemoteFileAdapter {
1157
+ /**
1158
+ * Opens a remote connection.
1159
+ *
1160
+ * @param profile - Host, authentication, protocol, timeout, signal, and logger settings.
1161
+ * @returns A promise that resolves when the remote session is ready for operations.
1162
+ */
1163
+ connect(profile: ConnectionProfile): Promise<void>;
1164
+ /**
1165
+ * Closes the remote connection and releases protocol resources.
1166
+ *
1167
+ * @returns A promise that resolves when the remote session is fully closed.
1168
+ */
1169
+ disconnect(): Promise<void>;
1170
+ /**
1171
+ * Lists entries for a remote directory.
1172
+ *
1173
+ * @param path - Remote directory path to list.
1174
+ * @param options - Optional listing controls such as recursion and abort signal.
1175
+ * @returns Normalized remote entries contained by the requested path.
1176
+ */
1177
+ list(path: string, options?: ListOptions): Promise<RemoteEntry[]>;
1178
+ /**
1179
+ * Reads metadata for a remote entry.
1180
+ *
1181
+ * @param path - Remote path to inspect.
1182
+ * @param options - Optional stat controls such as abort signal.
1183
+ * @returns Normalized metadata for an existing remote entry.
1184
+ */
1185
+ stat(path: string, options?: StatOptions): Promise<RemoteStat>;
1186
+ }
1187
+
1188
+ /**
1189
+ * Client facade for the ZeroTransfer SDK foundation.
1190
+ *
1191
+ * This module intentionally keeps the top-level API small while protocol-specific
1192
+ * behavior is delegated to injected adapters. The facade owns lifecycle state,
1193
+ * event emission, logging coordination, and common capability discovery.
1194
+ *
1195
+ * @module client/ZeroTransfer
1196
+ */
1197
+
1198
+ /**
1199
+ * Construction options for a {@link ZeroTransfer} instance.
1200
+ *
1201
+ * @remarks
1202
+ * The adapter option is primarily used by protocol implementations and tests. Until
1203
+ * the built-in FTP, FTPS, and SFTP adapters are implemented, callers can inject a
1204
+ * compatible adapter to exercise the facade contract.
1205
+ */
1206
+ interface ZeroTransferOptions {
1207
+ /** Protocol used when the connection profile does not provide one. */
1208
+ protocol?: RemoteProtocol;
1209
+ /** Structured logger used for lifecycle and operation records. */
1210
+ logger?: ZeroTransferLogger;
1211
+ /** Protocol adapter that performs concrete remote file operations. */
1212
+ adapter?: RemoteFileAdapter;
1213
+ }
1214
+ /**
1215
+ * Lightweight capability snapshot for the current client instance.
1216
+ */
1217
+ interface ZeroTransferCapabilities {
1218
+ /** The protocol selected for this client facade. */
1219
+ protocol: RemoteProtocol;
1220
+ /** Whether a concrete protocol adapter has been supplied. */
1221
+ adapterReady: boolean;
1222
+ }
1223
+ /**
1224
+ * SDK entry point for FTP, FTPS, and SFTP workflows.
1225
+ *
1226
+ * @remarks
1227
+ * ZeroTransfer extends Node.js EventEmitter so applications can observe lifecycle
1228
+ * events while still using promise-based APIs for operations. The facade is
1229
+ * deliberately protocol-neutral; concrete behavior lives behind
1230
+ * {@link RemoteFileAdapter}.
1231
+ *
1232
+ */
1233
+ declare class ZeroTransfer extends EventEmitter {
1234
+ /** Creates a provider-neutral transfer client with the built-in provider registry. */
1235
+ static readonly createTransferClient: typeof createTransferClient;
1236
+ /** Protocol selected for this client instance. */
1237
+ readonly protocol: RemoteProtocol;
1238
+ private readonly logger;
1239
+ private readonly adapter;
1240
+ private connected;
1241
+ /**
1242
+ * Creates a client facade without opening a network connection.
1243
+ *
1244
+ * @param options - Optional facade configuration, logger, and protocol adapter.
1245
+ */
1246
+ constructor(options?: ZeroTransferOptions);
1247
+ /**
1248
+ * Creates a new client facade using the provided options.
1249
+ *
1250
+ * @param options - Optional facade configuration, logger, and adapter.
1251
+ * @returns A disconnected {@link ZeroTransfer} instance.
1252
+ */
1253
+ static create(options?: ZeroTransferOptions): ZeroTransfer;
1254
+ /**
1255
+ * Creates a client and connects it in one step.
1256
+ *
1257
+ * @param profile - Remote host, authentication, and protocol connection settings.
1258
+ * @param options - Optional facade settings that can be overridden by the profile.
1259
+ * @returns A connected {@link ZeroTransfer} instance.
1260
+ * @throws {@link UnsupportedFeatureError} When no adapter is available for the protocol.
1261
+ */
1262
+ static connect(profile: ConnectionProfile, options?: ZeroTransferOptions): Promise<ZeroTransfer>;
1263
+ /**
1264
+ * Opens a remote connection through the configured protocol adapter.
1265
+ *
1266
+ * @param profile - Remote host, authentication, timeout, logger, and protocol settings.
1267
+ * @returns A promise that resolves after the adapter reports a successful connection.
1268
+ * @throws {@link UnsupportedFeatureError} When the client does not have an adapter.
1269
+ */
1270
+ connect(profile: ConnectionProfile): Promise<void>;
1271
+ /**
1272
+ * Closes the active remote connection if one exists.
1273
+ *
1274
+ * @returns A promise that resolves after the adapter disconnects or immediately when idle.
1275
+ */
1276
+ disconnect(): Promise<void>;
1277
+ /**
1278
+ * Checks whether the facade currently considers the adapter connected.
1279
+ *
1280
+ * @returns `true` after a successful connection and before disconnection.
1281
+ */
1282
+ isConnected(): boolean;
1283
+ /**
1284
+ * Describes protocol and adapter readiness for feature discovery.
1285
+ *
1286
+ * @returns A capability snapshot for diagnostics and UI state.
1287
+ */
1288
+ getCapabilities(): ZeroTransferCapabilities;
1289
+ /**
1290
+ * Lists remote entries for a path using the configured adapter.
1291
+ *
1292
+ * @param path - Remote directory path to inspect.
1293
+ * @param options - Optional listing controls such as recursion and abort signal.
1294
+ * @returns Normalized remote entries for the requested directory.
1295
+ * @throws {@link UnsupportedFeatureError} When the client does not have an adapter.
1296
+ */
1297
+ list(path: string, options?: ListOptions): Promise<RemoteEntry[]>;
1298
+ /**
1299
+ * Reads metadata for a remote path using the configured adapter.
1300
+ *
1301
+ * @param path - Remote file, directory, or symbolic-link path to inspect.
1302
+ * @param options - Optional stat controls such as abort signal.
1303
+ * @returns Normalized metadata for an existing remote entry.
1304
+ * @throws {@link UnsupportedFeatureError} When the client does not have an adapter.
1305
+ */
1306
+ stat(path: string, options?: StatOptions): Promise<RemoteStat>;
1307
+ /**
1308
+ * Returns the configured adapter or raises the alpha unsupported-feature error.
1309
+ *
1310
+ * @returns A concrete remote file adapter ready to execute operations.
1311
+ * @throws {@link UnsupportedFeatureError} When no adapter has been provided.
1312
+ */
1313
+ private requireAdapter;
1314
+ }
1315
+
1316
+ /**
1317
+ * MFT route definitions.
1318
+ *
1319
+ * Routes are named, declarative source→destination policies that bind a pair
1320
+ * of {@link ConnectionProfile} values, the paths being moved, and optional
1321
+ * filtering metadata. Routes are pure data; the {@link runRoute} executor and
1322
+ * the {@link RouteRegistry} wrap them with execution and lookup behavior.
1323
+ *
1324
+ * @module mft/MftRoute
1325
+ */
1326
+
1327
+ /** Endpoint inside an MFT route. */
1328
+ interface MftRouteEndpoint {
1329
+ /** Connection profile used to open a provider session for the endpoint. */
1330
+ profile: ConnectionProfile;
1331
+ /** Provider, remote, or local path the route operates on. */
1332
+ path: string;
1333
+ }
1334
+ /** Optional filter metadata reserved for tree-aware route execution. */
1335
+ interface MftRouteFilter {
1336
+ /** Glob patterns whose matches should be included. */
1337
+ include?: readonly string[];
1338
+ /** Glob patterns whose matches should be excluded. */
1339
+ exclude?: readonly string[];
1340
+ }
1341
+ /** Transfer operations supported by route executors. */
1342
+ type MftRouteOperation = Extract<TransferOperation, "copy" | "download" | "upload">;
1343
+ /** Declarative source→destination policy bound to provider profiles. */
1344
+ interface MftRoute {
1345
+ /** Stable route identifier. */
1346
+ id: string;
1347
+ /** Optional human-readable route name. */
1348
+ name?: string;
1349
+ /** Optional human-readable description. */
1350
+ description?: string;
1351
+ /** Source endpoint resolved through the transfer client. */
1352
+ source: MftRouteEndpoint;
1353
+ /** Destination endpoint resolved through the transfer client. */
1354
+ destination: MftRouteEndpoint;
1355
+ /** Optional include/exclude filter, reserved for tree-aware executors. */
1356
+ filter?: MftRouteFilter;
1357
+ /** Transfer operation performed by the route. Defaults to `"copy"`. */
1358
+ operation?: MftRouteOperation;
1359
+ /** Whether the route is enabled. Defaults to `true`. */
1360
+ enabled?: boolean;
1361
+ /** Caller-defined metadata retained for diagnostics and audit records. */
1362
+ metadata?: Record<string, unknown>;
1363
+ }
1364
+
1365
+ /**
1366
+ * Route executor that dispatches a single transfer through {@link TransferEngine}.
1367
+ *
1368
+ * `runRoute` opens both endpoints through the supplied {@link TransferClient},
1369
+ * builds a {@link TransferJob} with route correlation metadata, and runs the
1370
+ * provider read/write executor under retry, abort, progress, timeout, and
1371
+ * bandwidth-limit hooks. Sessions are released in `finally` blocks even when
1372
+ * the transfer fails, throws, or is aborted.
1373
+ *
1374
+ * @module mft/runRoute
1375
+ */
1376
+
1377
+ /** Options accepted by {@link runRoute}. */
1378
+ interface RunRouteOptions {
1379
+ /** Transfer client whose registry can resolve both endpoint providers. */
1380
+ client: TransferClient;
1381
+ /** Route to execute. */
1382
+ route: MftRoute;
1383
+ /** Optional transfer engine override. A fresh engine is created when omitted. */
1384
+ engine?: TransferEngine;
1385
+ /** Optional explicit job id. Defaults to a deterministic route-derived id. */
1386
+ jobId?: string;
1387
+ /** Optional clock used to derive the default job id. Defaults to `Date.now`. */
1388
+ now?: () => Date;
1389
+ /** Abort signal used to cancel the route execution. */
1390
+ signal?: AbortSignal;
1391
+ /** Retry policy forwarded to the engine. */
1392
+ retry?: TransferRetryPolicy;
1393
+ /** Progress observer forwarded to the engine. */
1394
+ onProgress?: (event: TransferProgressEvent) => void;
1395
+ /** Timeout policy forwarded to the engine. */
1396
+ timeout?: TransferTimeoutPolicy;
1397
+ /** Optional bandwidth limit forwarded to the engine. */
1398
+ bandwidthLimit?: TransferBandwidthLimit;
1399
+ /** Caller-defined metadata merged into the resulting transfer job. */
1400
+ metadata?: Record<string, unknown>;
1401
+ }
1402
+
1403
+ /** Endpoint shape accepted by the friendly helpers. */
1404
+ interface RemoteFileEndpoint {
1405
+ /** Provider profile used to open the session. */
1406
+ profile: ConnectionProfile;
1407
+ /** Provider, remote, or local path the helper operates on. */
1408
+ path: string;
1409
+ }
1410
+ /** Shared options consumed by {@link uploadFile}, {@link downloadFile}, and {@link copyBetween}. */
1411
+ type FriendlyTransferOptions = Omit<RunRouteOptions, "client" | "route"> & {
1412
+ /** Stable route id assigned to the synthetic route. Defaults to `"upload:..."`, `"download:..."`, or `"copy:..."`. */
1413
+ routeId?: string;
1414
+ /** Optional human-readable route name forwarded to telemetry. */
1415
+ routeName?: string;
1416
+ };
1417
+ /** Options for {@link uploadFile}. */
1418
+ interface UploadFileOptions extends FriendlyTransferOptions {
1419
+ /** Transfer client used to resolve both endpoint providers. */
1420
+ client: TransferClient;
1421
+ /** Local source path. Relative paths are resolved against `process.cwd()`. */
1422
+ localPath: string;
1423
+ /** Remote destination endpoint. */
1424
+ destination: RemoteFileEndpoint;
1425
+ }
1426
+ /**
1427
+ * Uploads a single local file to a remote endpoint.
1428
+ *
1429
+ * The remote provider is resolved from `destination.profile.provider`, so any
1430
+ * provider factory you registered with {@link createTransferClient} can be used
1431
+ * as the destination.
1432
+ *
1433
+ * @param options - Friendly upload options.
1434
+ * @returns Receipt produced by the underlying transfer engine.
1435
+ *
1436
+ * @example Upload to SFTP with public-key auth
1437
+ * ```ts
1438
+ * import {
1439
+ * createSftpProviderFactory,
1440
+ * createTransferClient,
1441
+ * uploadFile,
1442
+ * } from "@zero-transfer/sdk";
1443
+ *
1444
+ * const client = createTransferClient({ providers: [createSftpProviderFactory()] });
1445
+ *
1446
+ * await uploadFile({
1447
+ * client,
1448
+ * destination: {
1449
+ * path: "/uploads/report.csv",
1450
+ * profile: {
1451
+ * host: "sftp.example.com",
1452
+ * provider: "sftp",
1453
+ * username: "deploy",
1454
+ * ssh: { privateKey: { path: "./keys/id_ed25519" } },
1455
+ * },
1456
+ * },
1457
+ * localPath: "./out/report.csv",
1458
+ * });
1459
+ * ```
1460
+ */
1461
+ declare function uploadFile(options: UploadFileOptions): Promise<TransferReceipt>;
1462
+ /** Options for {@link downloadFile}. */
1463
+ interface DownloadFileOptions extends FriendlyTransferOptions {
1464
+ /** Transfer client used to resolve both endpoint providers. */
1465
+ client: TransferClient;
1466
+ /** Remote source endpoint. */
1467
+ source: RemoteFileEndpoint;
1468
+ /** Local destination path. Relative paths are resolved against `process.cwd()`. */
1469
+ localPath: string;
1470
+ }
1471
+ /**
1472
+ * Downloads a single remote file to a local path.
1473
+ *
1474
+ * The remote provider is resolved from `source.profile.provider`. The local
1475
+ * destination path is created (including parent directories) on demand.
1476
+ *
1477
+ * @param options - Friendly download options.
1478
+ * @returns Receipt produced by the underlying transfer engine.
1479
+ *
1480
+ * @example Download from S3
1481
+ * ```ts
1482
+ * import {
1483
+ * createS3ProviderFactory,
1484
+ * createTransferClient,
1485
+ * downloadFile,
1486
+ * } from "@zero-transfer/sdk";
1487
+ *
1488
+ * const client = createTransferClient({ providers: [createS3ProviderFactory()] });
1489
+ *
1490
+ * await downloadFile({
1491
+ * client,
1492
+ * localPath: "./tmp/snapshot.tar.gz",
1493
+ * source: {
1494
+ * path: "snapshots/2026-04-28/snapshot.tar.gz",
1495
+ * profile: {
1496
+ * host: "snapshots", // S3 bucket
1497
+ * provider: "s3",
1498
+ * s3: { region: "us-east-1" },
1499
+ * },
1500
+ * },
1501
+ * });
1502
+ * ```
1503
+ */
1504
+ declare function downloadFile(options: DownloadFileOptions): Promise<TransferReceipt>;
1505
+ /** Options for {@link copyBetween}. */
1506
+ interface CopyBetweenOptions extends FriendlyTransferOptions {
1507
+ /** Transfer client used to resolve both endpoint providers. */
1508
+ client: TransferClient;
1509
+ /** Source remote endpoint. */
1510
+ source: RemoteFileEndpoint;
1511
+ /** Destination remote endpoint. */
1512
+ destination: RemoteFileEndpoint;
1513
+ }
1514
+ /**
1515
+ * Copies a file between two remote endpoints in a single call.
1516
+ *
1517
+ * Both source and destination providers must be registered with the
1518
+ * {@link TransferClient}. Streams are piped end-to-end without staging the file
1519
+ * on the local disk.
1520
+ *
1521
+ * @param options - Friendly copy options.
1522
+ * @returns Receipt produced by the underlying transfer engine.
1523
+ *
1524
+ * @example Copy from SFTP to S3
1525
+ * ```ts
1526
+ * import {
1527
+ * copyBetween,
1528
+ * createS3ProviderFactory,
1529
+ * createSftpProviderFactory,
1530
+ * createTransferClient,
1531
+ * } from "@zero-transfer/sdk";
1532
+ *
1533
+ * const client = createTransferClient({
1534
+ * providers: [createSftpProviderFactory(), createS3ProviderFactory()],
1535
+ * });
1536
+ *
1537
+ * await copyBetween({
1538
+ * client,
1539
+ * source: {
1540
+ * path: "/exports/daily.csv",
1541
+ * profile: { host: "sftp.example.com", provider: "sftp", username: "etl" },
1542
+ * },
1543
+ * destination: {
1544
+ * path: "warehouse/daily.csv",
1545
+ * profile: { host: "warehouse", provider: "s3", s3: { region: "us-east-1" } },
1546
+ * },
1547
+ * });
1548
+ * ```
1549
+ */
1550
+ declare function copyBetween(options: CopyBetweenOptions): Promise<TransferReceipt>;
1551
+
1552
+ /**
1553
+ * Diagnostics helpers for inspecting a {@link TransferClient} and probing connection profiles.
1554
+ *
1555
+ * These helpers are intentionally side-effect-light: they exercise an existing client without
1556
+ * mutating registry state and never log secret material. Use them to render setup screens,
1557
+ * collect bug-report payloads, or verify a profile after an importer run.
1558
+ *
1559
+ * @module diagnostics
1560
+ */
1561
+
1562
+ /** Snapshot of the providers registered with a client. */
1563
+ interface ClientDiagnostics {
1564
+ /** Providers currently registered, keyed by id. */
1565
+ providers: ReadonlyArray<{
1566
+ id: ProviderId;
1567
+ capabilities: CapabilitySet;
1568
+ }>;
1569
+ }
1570
+ /**
1571
+ * Returns a redaction-safe snapshot of the providers registered with a client.
1572
+ *
1573
+ * @param client - Transfer client to inspect.
1574
+ * @returns Provider id and capability snapshot tuples.
1575
+ */
1576
+ declare function summarizeClientDiagnostics(client: TransferClient): ClientDiagnostics;
1577
+ /** Per-step duration measurements collected by {@link runConnectionDiagnostics}. */
1578
+ interface ConnectionDiagnosticTimings {
1579
+ /** Total time spent inside `client.connect`. */
1580
+ connectMs?: number;
1581
+ /** Time spent inside the optional `fs.list` probe. */
1582
+ listMs?: number;
1583
+ /** Time spent inside the optional `session.disconnect`. */
1584
+ disconnectMs?: number;
1585
+ }
1586
+ /** Result returned by {@link runConnectionDiagnostics}. */
1587
+ interface ConnectionDiagnosticsResult {
1588
+ /** Resolved provider id used to open the session. */
1589
+ provider?: ProviderId;
1590
+ /** Profile host (after redaction). */
1591
+ host: string;
1592
+ /** Capability snapshot reported by the connected session. */
1593
+ capabilities?: CapabilitySet;
1594
+ /** Redacted connection profile mirroring {@link redactConnectionProfile}. */
1595
+ redactedProfile: Record<string, unknown>;
1596
+ /** Per-step duration measurements. */
1597
+ timings: ConnectionDiagnosticTimings;
1598
+ /** Sample of entries returned by the optional `fs.list` probe. */
1599
+ sample?: readonly RemoteEntry[];
1600
+ /** Whether all probes ran without throwing. */
1601
+ ok: boolean;
1602
+ /** Captured error summary when the diagnostics could not complete. */
1603
+ error?: {
1604
+ message: string;
1605
+ name?: string;
1606
+ code?: string;
1607
+ };
1608
+ }
1609
+ /** Options accepted by {@link runConnectionDiagnostics}. */
1610
+ interface RunConnectionDiagnosticsOptions {
1611
+ /** Transfer client used to open the session. */
1612
+ client: TransferClient;
1613
+ /** Connection profile to probe. */
1614
+ profile: ConnectionProfile;
1615
+ /** Path passed to the optional `fs.list` probe. Defaults to `"/"`. */
1616
+ listPath?: string;
1617
+ /** When `false`, skips the `fs.list` probe. Defaults to `true`. */
1618
+ probeList?: boolean;
1619
+ /** Maximum number of entries retained in the result sample. Defaults to `5`. */
1620
+ sampleSize?: number;
1621
+ /** Optional clock injected for deterministic test timings. Defaults to `performance.now`. */
1622
+ now?: () => number;
1623
+ }
1624
+ /**
1625
+ * Connects to a profile, captures capability and listing samples, and returns a redaction-safe report.
1626
+ *
1627
+ * @param options - Diagnostic probe options.
1628
+ * @returns Diagnostic report including timings and any captured error.
1629
+ */
1630
+ declare function runConnectionDiagnostics(options: RunConnectionDiagnosticsOptions): Promise<ConnectionDiagnosticsResult>;
1631
+
1632
+ /** Options used to create a local file-system provider factory. */
1633
+ interface LocalProviderOptions {
1634
+ /** Root directory exposed as `/`. When omitted, `profile.host` is treated as the root path. */
1635
+ rootPath?: string;
1636
+ }
1637
+ /**
1638
+ * Creates a provider factory backed by the local filesystem.
1639
+ *
1640
+ * Useful for copying files between two remote endpoints via a local staging
1641
+ * area, or as the destination for `downloadFile`. The friendly `uploadFile`
1642
+ * helper registers a local provider implicitly.
1643
+ *
1644
+ * @param options - Optional local root path exposed through provider sessions.
1645
+ * @returns Provider factory suitable for `createTransferClient({ providers: [...] })`.
1646
+ *
1647
+ * @example Use a fixed root directory
1648
+ * ```ts
1649
+ * import { createLocalProviderFactory, createTransferClient } from "@zero-transfer/sdk";
1650
+ *
1651
+ * const client = createTransferClient({
1652
+ * providers: [createLocalProviderFactory({ rootPath: "/var/lib/zt-staging" })],
1653
+ * });
1654
+ *
1655
+ * const session = await client.connect({ host: "staging", provider: "local" });
1656
+ * const list = await session.fs.list("/");
1657
+ * ```
1658
+ */
1659
+ declare function createLocalProviderFactory(options?: LocalProviderOptions): ProviderFactory;
1660
+
1661
+ /** Fixture entry used to seed a memory provider instance. */
1662
+ interface MemoryProviderEntry extends Omit<RemoteEntry, "name"> {
1663
+ /** Entry basename. When omitted, it is derived from `path`. */
1664
+ name?: string;
1665
+ /** Optional byte content for file entries. Strings are encoded as UTF-8. */
1666
+ content?: string | Uint8Array;
1667
+ }
1668
+ /** Options used to create a deterministic memory provider factory. */
1669
+ interface MemoryProviderOptions {
1670
+ /** Entries available to sessions created by this provider factory. */
1671
+ entries?: Iterable<MemoryProviderEntry>;
1672
+ }
1673
+ /**
1674
+ * Creates a provider factory backed by deterministic in-memory fixture entries.
1675
+ *
1676
+ * @param options - Optional fixture entries to expose through the memory provider.
1677
+ * @returns Provider factory suitable for `createTransferClient({ providers: [...] })`.
1678
+ */
1679
+ declare function createMemoryProviderFactory(options?: MemoryProviderOptions): ProviderFactory;
1680
+
1681
+ /**
1682
+ * Connection profile redaction helpers.
1683
+ *
1684
+ * @module profiles/ProfileRedactor
1685
+ */
1686
+
1687
+ /**
1688
+ * Produces a diagnostics-safe profile copy with credentials and runtime hooks redacted.
1689
+ *
1690
+ * @param profile - Connection profile to sanitize.
1691
+ * @returns Plain object safe to include in logs, traces, or validation reports.
1692
+ */
1693
+ declare function redactConnectionProfile(profile: ConnectionProfile): Record<string, unknown>;
1694
+
1695
+ /**
1696
+ * Validates provider-neutral connection profile fields before provider lookup.
1697
+ *
1698
+ * @param profile - Profile to validate.
1699
+ * @returns The original profile when valid.
1700
+ * @throws {@link ConfigurationError} When required provider, host, or numeric fields are invalid.
1701
+ */
1702
+ declare function validateConnectionProfile(profile: ConnectionProfile): ConnectionProfile;
1703
+
1704
+ /**
1705
+ * Connection profile secret resolution helpers.
1706
+ *
1707
+ * @module profiles/resolveConnectionProfileSecrets
1708
+ */
1709
+
1710
+ /** SSH profile with private-key and known-host material resolved. */
1711
+ interface ResolvedSshProfile extends Omit<SshProfile, "knownHosts" | "passphrase" | "privateKey"> {
1712
+ /** Resolved private key material. */
1713
+ privateKey?: SecretValue;
1714
+ /** Resolved private-key passphrase. */
1715
+ passphrase?: SecretValue;
1716
+ /** Resolved OpenSSH known_hosts material. */
1717
+ knownHosts?: SecretValue | SecretValue[];
1718
+ }
1719
+ /** TLS profile with certificate-bearing secret sources resolved. */
1720
+ interface ResolvedTlsProfile extends Omit<TlsProfile, "ca" | "cert" | "key" | "passphrase" | "pfx"> {
1721
+ /** Resolved certificate authority bundle. */
1722
+ ca?: SecretValue | SecretValue[];
1723
+ /** Resolved client certificate PEM. */
1724
+ cert?: SecretValue;
1725
+ /** Resolved client private key PEM. */
1726
+ key?: SecretValue;
1727
+ /** Resolved encrypted private-key or PFX/P12 passphrase. */
1728
+ passphrase?: SecretValue;
1729
+ /** Resolved PFX/P12 client certificate bundle. */
1730
+ pfx?: SecretValue;
1731
+ }
1732
+ /** Connection profile with username, password, TLS, and SSH material sources resolved. */
1733
+ interface ResolvedConnectionProfile extends Omit<ConnectionProfile, "password" | "ssh" | "tls" | "username"> {
1734
+ /** Resolved username or account identifier. */
1735
+ username?: SecretValue;
1736
+ /** Resolved password or credential bytes. */
1737
+ password?: SecretValue;
1738
+ /** Resolved TLS profile when certificate material is configured. */
1739
+ tls?: ResolvedTlsProfile;
1740
+ /** Resolved SSH profile when private-key material is configured. */
1741
+ ssh?: ResolvedSshProfile;
1742
+ }
1743
+ /**
1744
+ * Resolves credential and TLS material secret sources without mutating the original profile.
1745
+ *
1746
+ * @param profile - Profile containing optional secret sources.
1747
+ * @param options - Optional env and file-reader overrides.
1748
+ * @returns Profile copy with username, password, TLS material, and SSH material resolved when present.
1749
+ */
1750
+ declare function resolveConnectionProfileSecrets(profile: ConnectionProfile, options?: ResolveSecretOptions): Promise<ResolvedConnectionProfile>;
1751
+
1752
+ /** Token material returned by {@link OAuthRefreshCallback}. */
1753
+ interface OAuthAccessToken {
1754
+ /** Access token value. Required. */
1755
+ accessToken: string;
1756
+ /**
1757
+ * Lifetime in seconds (`expires_in`-style). When provided, the helper caches
1758
+ * the token until `now + (expiresInSeconds - skewSeconds)`.
1759
+ */
1760
+ expiresInSeconds?: number;
1761
+ /** Absolute expiry. Wins over `expiresInSeconds` when both are provided. */
1762
+ expiresAt?: Date;
1763
+ }
1764
+ /** Refresh callback invoked when no valid cached token is available. */
1765
+ type OAuthRefreshCallback = () => OAuthAccessToken | Promise<OAuthAccessToken>;
1766
+ /** Options accepted by {@link createOAuthTokenSecretSource}. */
1767
+ interface OAuthTokenSecretSourceOptions {
1768
+ /**
1769
+ * Safety margin (in milliseconds) subtracted from the token's expiry to
1770
+ * trigger a refresh before the wire deadline. Defaults to `60_000` (60s).
1771
+ */
1772
+ skewMs?: number;
1773
+ /** Clock used to evaluate expiry. Defaults to `Date.now`. */
1774
+ now?: () => number;
1775
+ }
1776
+ /**
1777
+ * Builds a {@link SecretProvider} that exchanges a refresh callback for
1778
+ * cached, auto-renewing access tokens.
1779
+ *
1780
+ * The returned function can be passed directly as `profile.password` for any
1781
+ * provider that accepts bearer tokens (Dropbox, Google Drive, OneDrive, GCS,
1782
+ * Azure Blob via AAD).
1783
+ *
1784
+ * @example
1785
+ * ```ts
1786
+ * const password = createOAuthTokenSecretSource(async () => {
1787
+ * const res = await fetch("https://example.com/oauth/token", { ... });
1788
+ * const body = (await res.json()) as { access_token: string; expires_in: number };
1789
+ * return { accessToken: body.access_token, expiresInSeconds: body.expires_in };
1790
+ * });
1791
+ * const session = await factory.create().connect({ host: "", protocol: "ftp", password });
1792
+ * ```
1793
+ */
1794
+ declare function createOAuthTokenSecretSource(refresh: OAuthRefreshCallback, options?: OAuthTokenSecretSourceOptions): SecretProvider;
1795
+
1796
+ /** Marker prefixing a known_hosts line (`@cert-authority` or `@revoked`). */
1797
+ type KnownHostsMarker = "cert-authority" | "revoked";
1798
+ /** Parsed entry from an OpenSSH `known_hosts` file. */
1799
+ interface KnownHostsEntry {
1800
+ /** Optional line marker (`@cert-authority` or `@revoked`). */
1801
+ marker?: KnownHostsMarker;
1802
+ /** Raw, comma-separated host patterns. Negation patterns retain their leading `!`. */
1803
+ hostPatterns: readonly string[];
1804
+ /** Hashed-salt component for `|1|salt|hash` entries. Mutually exclusive with plain patterns. */
1805
+ hashedSalt?: string;
1806
+ /** Hashed-hash component for `|1|salt|hash` entries. Mutually exclusive with plain patterns. */
1807
+ hashedHash?: string;
1808
+ /** SSH key algorithm identifier (e.g. `ssh-ed25519`, `ecdsa-sha2-nistp256`). */
1809
+ keyType: string;
1810
+ /** Base64-encoded public key blob. */
1811
+ keyBase64: string;
1812
+ /** Trailing comment text, if any. */
1813
+ comment?: string;
1814
+ /** Original line text without trailing newline. */
1815
+ raw: string;
1816
+ }
1817
+ /**
1818
+ * Parses OpenSSH `known_hosts` content into structured entries. Comment and blank lines are skipped.
1819
+ * Lines that cannot be parsed are silently dropped so callers can tolerate hand-edited files.
1820
+ *
1821
+ * @param text - Raw `known_hosts` file contents.
1822
+ * @returns Parsed entries in source order.
1823
+ */
1824
+ declare function parseKnownHosts(text: string): KnownHostsEntry[];
1825
+ /**
1826
+ * Returns true when the given host (and optional port) matches the entry's host patterns.
1827
+ * Hashed entries use HMAC-SHA1 verification per OpenSSH semantics.
1828
+ *
1829
+ * @param entry - Parsed `known_hosts` entry to test.
1830
+ * @param host - Hostname or IP literal to match.
1831
+ * @param port - Optional connection port. Defaults to {@link DEFAULT_SSH_PORT}.
1832
+ * @returns Whether the entry matches and is not negated.
1833
+ */
1834
+ declare function matchKnownHostsEntry(entry: KnownHostsEntry, host: string, port?: number): boolean;
1835
+ /**
1836
+ * Filters parsed entries down to those that match the given host/port. Negations are honored.
1837
+ *
1838
+ * @param entries - Entries returned by {@link parseKnownHosts}.
1839
+ * @param host - Hostname or IP literal to match.
1840
+ * @param port - Optional connection port. Defaults to {@link DEFAULT_SSH_PORT}.
1841
+ * @returns Matching entries in source order.
1842
+ */
1843
+ declare function matchKnownHosts(entries: readonly KnownHostsEntry[], host: string, port?: number): KnownHostsEntry[];
1844
+
1845
+ /** Parsed `Host` block from an OpenSSH config file. */
1846
+ interface OpenSshConfigEntry {
1847
+ /** Host patterns declared on the `Host` line. */
1848
+ patterns: readonly string[];
1849
+ /** Lower-cased directive name to ordered values. Multi-valued directives (e.g. `IdentityFile`) preserve order. */
1850
+ options: Readonly<Record<string, readonly string[]>>;
1851
+ }
1852
+ /**
1853
+ * Parses OpenSSH `ssh_config` text into structured `Host` blocks.
1854
+ *
1855
+ * The parser is intentionally permissive: unknown directives are retained and `Match` blocks are skipped.
1856
+ *
1857
+ * @param text - Contents of the `ssh_config` file.
1858
+ * @returns Parsed `Host` entries in source order.
1859
+ */
1860
+ declare function parseOpenSshConfig(text: string): OpenSshConfigEntry[];
1861
+ /**
1862
+ * Resolved set of directives for a given host alias. Values from later-declared blocks are
1863
+ * merged after earlier ones so wildcard fallbacks (e.g. `Host *`) only fill gaps.
1864
+ */
1865
+ interface ResolvedOpenSshHost {
1866
+ /** Host alias the lookup was performed against. */
1867
+ alias: string;
1868
+ /** Per-directive ordered values, keyed by lower-cased directive name. */
1869
+ options: Readonly<Record<string, readonly string[]>>;
1870
+ /** Source entries that contributed to the resolved set, in match order. */
1871
+ matched: readonly OpenSshConfigEntry[];
1872
+ }
1873
+ /**
1874
+ * Resolves the merged option set for an OpenSSH host alias.
1875
+ *
1876
+ * @param entries - Parsed entries from {@link parseOpenSshConfig}.
1877
+ * @param alias - Host alias to resolve.
1878
+ * @returns Merged directive set with the matching entries.
1879
+ */
1880
+ declare function resolveOpenSshHost(entries: readonly OpenSshConfigEntry[], alias: string): ResolvedOpenSshHost;
1881
+ /** Options accepted by {@link importOpenSshConfig}. */
1882
+ interface ImportOpenSshConfigOptions {
1883
+ /** Raw `ssh_config` text. Either this or {@link entries} must be provided. */
1884
+ text?: string;
1885
+ /** Pre-parsed entries from {@link parseOpenSshConfig}. */
1886
+ entries?: readonly OpenSshConfigEntry[];
1887
+ /** Host alias to import. */
1888
+ alias: string;
1889
+ }
1890
+ /** Result of {@link importOpenSshConfig}. */
1891
+ interface ImportOpenSshConfigResult {
1892
+ /** Generated SFTP connection profile. */
1893
+ profile: ConnectionProfile;
1894
+ /** Resolved directive set used to build the profile. */
1895
+ resolved: ResolvedOpenSshHost;
1896
+ /** Identity file paths declared in the config, in declaration order. */
1897
+ identityFiles: readonly string[];
1898
+ /** Optional `ProxyJump` value preserved from the config. */
1899
+ proxyJump?: string;
1900
+ }
1901
+ /**
1902
+ * Builds a {@link ConnectionProfile} for the given SSH alias from `ssh_config` text or pre-parsed entries.
1903
+ *
1904
+ * @param options - Import options.
1905
+ * @returns Importer result with the generated profile and supporting metadata.
1906
+ * @throws {@link ConfigurationError} When neither text nor entries is supplied.
1907
+ */
1908
+ declare function importOpenSshConfig(options: ImportOpenSshConfigOptions): ImportOpenSshConfigResult;
1909
+
1910
+ /** Imported FileZilla site with the folder hierarchy that contained it. */
1911
+ interface FileZillaSite {
1912
+ /** Site display name. */
1913
+ name: string;
1914
+ /** Ordered folder names leading to the site (top-level first). Empty for root sites. */
1915
+ folder: readonly string[];
1916
+ /** Generated connection profile. */
1917
+ profile: ConnectionProfile;
1918
+ /** Encoded password value retained from the file, if any. */
1919
+ password?: string;
1920
+ /** Logon type code preserved from the file (`0`=anonymous, `1`=normal, etc.). */
1921
+ logonType?: number;
1922
+ }
1923
+ /** Result returned by {@link importFileZillaSites}. */
1924
+ interface ImportFileZillaSitesResult {
1925
+ /** Sites successfully mapped to a connection profile. */
1926
+ sites: readonly FileZillaSite[];
1927
+ /** Sites that were skipped because their protocol is not supported. */
1928
+ skipped: readonly {
1929
+ name: string;
1930
+ folder: readonly string[];
1931
+ protocol?: number;
1932
+ }[];
1933
+ }
1934
+ /**
1935
+ * Parses FileZilla `sitemanager.xml` text and returns generated profiles.
1936
+ *
1937
+ * @param xml - Contents of `sitemanager.xml`.
1938
+ * @returns Imported sites and any skipped entries.
1939
+ * @throws {@link ConfigurationError} When the XML root cannot be located.
1940
+ */
1941
+ declare function importFileZillaSites(xml: string): ImportFileZillaSitesResult;
1942
+
1943
+ /** Imported WinSCP session entry. */
1944
+ interface WinScpSession {
1945
+ /** Decoded session name (URL-decoded path under the `Sessions\\` namespace). */
1946
+ name: string;
1947
+ /** Hierarchical path segments derived from the session name (folders separated by `/`). */
1948
+ folder: readonly string[];
1949
+ /** Generated connection profile. */
1950
+ profile: ConnectionProfile;
1951
+ /** Raw FSProtocol code preserved from the file. */
1952
+ fsProtocol?: number;
1953
+ /** Raw Ftps code preserved from the file (`0`=none, `1`=implicit, `2`/`3`=explicit). */
1954
+ ftps?: number;
1955
+ }
1956
+ /** Result of {@link importWinScpSessions}. */
1957
+ interface ImportWinScpSessionsResult {
1958
+ /** Successfully mapped sessions. */
1959
+ sessions: readonly WinScpSession[];
1960
+ /** Sessions skipped because their protocol is not supported. */
1961
+ skipped: readonly {
1962
+ name: string;
1963
+ folder: readonly string[];
1964
+ fsProtocol?: number;
1965
+ }[];
1966
+ }
1967
+ /**
1968
+ * Parses WinSCP `WinSCP.ini` text and returns generated profiles.
1969
+ *
1970
+ * @param ini - Contents of the WinSCP configuration file.
1971
+ * @returns Imported sessions and any skipped entries.
1972
+ * @throws {@link ConfigurationError} When no session sections are found.
1973
+ */
1974
+ declare function importWinScpSessions(ini: string): ImportWinScpSessionsResult;
1975
+
1976
+ /**
1977
+ * Structured ZeroTransfer error hierarchy.
1978
+ *
1979
+ * The classes in this module preserve protocol details, retryability, command/path
1980
+ * context, and machine-readable codes so application code does not need to parse
1981
+ * human error messages.
1982
+ *
1983
+ * @module errors/ZeroTransferError
1984
+ */
1985
+
1986
+ /**
1987
+ * Complete set of fields required to create a ZeroTransfer error.
1988
+ */
1989
+ interface ZeroTransferErrorDetails {
1990
+ /** Stable machine-readable error code. */
1991
+ code: string;
1992
+ /** Human-readable error message safe to show in logs or diagnostics. */
1993
+ message: string;
1994
+ /** Original error or exception that caused this error. */
1995
+ cause?: unknown;
1996
+ /** Protocol active when the error occurred. */
1997
+ protocol?: RemoteProtocol;
1998
+ /** Remote host associated with the failing operation. */
1999
+ host?: string;
2000
+ /** Protocol command associated with the failure, if any. */
2001
+ command?: string;
2002
+ /** FTP response code associated with the failure. */
2003
+ ftpCode?: number;
2004
+ /** SFTP status code associated with the failure. */
2005
+ sftpCode?: number;
2006
+ /** Remote path associated with the failure. */
2007
+ path?: string;
2008
+ /** Whether retry policy may safely retry this failure. */
2009
+ retryable: boolean;
2010
+ /** Additional structured details for diagnostics. */
2011
+ details?: Record<string, unknown>;
2012
+ }
2013
+ /**
2014
+ * Error construction input for subclasses that provide default codes.
2015
+ */
2016
+ type SpecializedErrorDetails = Omit<ZeroTransferErrorDetails, "code"> & {
2017
+ /** Optional override for the subclass default code. */
2018
+ code?: string;
2019
+ };
2020
+ /**
2021
+ * Base class for all typed ZeroTransfer errors.
2022
+ */
2023
+ declare class ZeroTransferError extends Error {
2024
+ /** Stable machine-readable error code. */
2025
+ readonly code: string;
2026
+ /** Protocol active when the error occurred. */
2027
+ readonly protocol?: RemoteProtocol;
2028
+ /** Remote host associated with the failing operation. */
2029
+ readonly host?: string;
2030
+ /** Protocol command associated with the failure, if any. */
2031
+ readonly command?: string;
2032
+ /** FTP response code associated with the failure. */
2033
+ readonly ftpCode?: number;
2034
+ /** SFTP status code associated with the failure. */
2035
+ readonly sftpCode?: number;
2036
+ /** Remote path associated with the failure. */
2037
+ readonly path?: string;
2038
+ /** Whether retry policy may safely retry this failure. */
2039
+ readonly retryable: boolean;
2040
+ /** Additional structured details for diagnostics. */
2041
+ readonly details?: Record<string, unknown>;
2042
+ /**
2043
+ * Creates a structured SDK error.
2044
+ *
2045
+ * @param details - Code, message, retryability, and optional protocol context.
2046
+ */
2047
+ constructor(details: ZeroTransferErrorDetails);
2048
+ /**
2049
+ * Serializes the error into a plain object suitable for logs or API responses.
2050
+ *
2051
+ * @returns A JSON-safe object containing public structured error fields.
2052
+ */
2053
+ toJSON(): Record<string, unknown>;
2054
+ }
2055
+ /** Error raised when a remote connection cannot be opened or is lost unexpectedly. */
2056
+ declare class ConnectionError extends ZeroTransferError {
2057
+ /**
2058
+ * Creates a connection failure.
2059
+ *
2060
+ * @param details - Error context with optional host, protocol, and retryability details.
2061
+ */
2062
+ constructor(details: SpecializedErrorDetails);
2063
+ }
2064
+ /** Error raised when authentication credentials are rejected. */
2065
+ declare class AuthenticationError extends ZeroTransferError {
2066
+ /**
2067
+ * Creates an authentication failure.
2068
+ *
2069
+ * @param details - Error context with optional host, protocol, and command details.
2070
+ */
2071
+ constructor(details: SpecializedErrorDetails);
2072
+ }
2073
+ /** Error raised when authenticated credentials are not authorized for an operation. */
2074
+ declare class AuthorizationError extends ZeroTransferError {
2075
+ /**
2076
+ * Creates an authorization failure.
2077
+ *
2078
+ * @param details - Error context with optional path and protocol details.
2079
+ */
2080
+ constructor(details: SpecializedErrorDetails);
2081
+ }
2082
+ /** Error raised when a requested remote path does not exist. */
2083
+ declare class PathNotFoundError extends ZeroTransferError {
2084
+ /**
2085
+ * Creates a missing-path failure.
2086
+ *
2087
+ * @param details - Error context with optional path and protocol details.
2088
+ */
2089
+ constructor(details: SpecializedErrorDetails);
2090
+ }
2091
+ /** Error raised when a create or rename operation targets an existing path. */
2092
+ declare class PathAlreadyExistsError extends ZeroTransferError {
2093
+ /**
2094
+ * Creates an already-exists failure.
2095
+ *
2096
+ * @param details - Error context with optional path and command details.
2097
+ */
2098
+ constructor(details: SpecializedErrorDetails);
2099
+ }
2100
+ /** Error raised when the remote server denies access to a path or command. */
2101
+ declare class PermissionDeniedError extends ZeroTransferError {
2102
+ /**
2103
+ * Creates a permission failure.
2104
+ *
2105
+ * @param details - Error context with optional path, command, and protocol details.
2106
+ */
2107
+ constructor(details: SpecializedErrorDetails);
2108
+ }
2109
+ /** Error raised when an operation exceeds its configured timeout. */
2110
+ declare class TimeoutError extends ZeroTransferError {
2111
+ /**
2112
+ * Creates a timeout failure.
2113
+ *
2114
+ * @param details - Error context with optional duration and retryability details.
2115
+ */
2116
+ constructor(details: SpecializedErrorDetails);
2117
+ }
2118
+ /** Error raised when an operation is cancelled by an AbortSignal or caller action. */
2119
+ declare class AbortError extends ZeroTransferError {
2120
+ /**
2121
+ * Creates an aborted-operation failure.
2122
+ *
2123
+ * @param details - Error context with optional operation and path details.
2124
+ */
2125
+ constructor(details: SpecializedErrorDetails);
2126
+ }
2127
+ /** Error raised when a server response violates protocol expectations. */
2128
+ declare class ProtocolError extends ZeroTransferError {
2129
+ /**
2130
+ * Creates a protocol failure.
2131
+ *
2132
+ * @param details - Error context with optional response code and command details.
2133
+ */
2134
+ constructor(details: SpecializedErrorDetails);
2135
+ }
2136
+ /** Error raised when protocol text or metadata cannot be parsed safely. */
2137
+ declare class ParseError extends ZeroTransferError {
2138
+ /**
2139
+ * Creates a parser failure.
2140
+ *
2141
+ * @param details - Error context with malformed input details.
2142
+ */
2143
+ constructor(details: SpecializedErrorDetails);
2144
+ }
2145
+ /** Error raised when an upload, download, or stream transfer fails. */
2146
+ declare class TransferError extends ZeroTransferError {
2147
+ /**
2148
+ * Creates a transfer failure.
2149
+ *
2150
+ * @param details - Error context with optional path, bytes, and retryability details.
2151
+ */
2152
+ constructor(details: SpecializedErrorDetails);
2153
+ }
2154
+ /** Error raised when post-transfer verification fails. */
2155
+ declare class VerificationError extends ZeroTransferError {
2156
+ /**
2157
+ * Creates a verification failure.
2158
+ *
2159
+ * @param details - Error context with checksum, size, or timestamp mismatch details.
2160
+ */
2161
+ constructor(details: SpecializedErrorDetails);
2162
+ }
2163
+ /** Error raised when a requested protocol feature is not implemented or unavailable. */
2164
+ declare class UnsupportedFeatureError extends ZeroTransferError {
2165
+ /**
2166
+ * Creates an unsupported-feature failure.
2167
+ *
2168
+ * @param details - Error context describing the missing feature or adapter.
2169
+ */
2170
+ constructor(details: SpecializedErrorDetails);
2171
+ }
2172
+ /** Error raised when user-provided options or paths are invalid before network I/O. */
2173
+ declare class ConfigurationError extends ZeroTransferError {
2174
+ /**
2175
+ * Creates a configuration failure.
2176
+ *
2177
+ * @param details - Error context describing the invalid option or argument.
2178
+ */
2179
+ constructor(details: SpecializedErrorDetails);
2180
+ }
2181
+
2182
+ /**
2183
+ * Protocol error factory helpers.
2184
+ *
2185
+ * This module translates raw FTP status replies into typed ZeroTransfer errors so
2186
+ * adapters can keep protocol parsing separate from application-facing failures.
2187
+ *
2188
+ * @module errors/errorFactory
2189
+ */
2190
+
2191
+ /**
2192
+ * Input used to map an FTP reply into a structured ZeroTransfer error.
2193
+ */
2194
+ interface FtpReplyErrorInput {
2195
+ /** Numeric FTP response code returned by the server. */
2196
+ ftpCode: number;
2197
+ /** Server-provided response message. */
2198
+ message: string;
2199
+ /** FTP command that produced the response, if known. */
2200
+ command?: string;
2201
+ /** Remote path involved in the command, if any. */
2202
+ path?: string;
2203
+ /** Protocol variant used by the adapter. */
2204
+ protocol?: RemoteProtocol;
2205
+ /** Original lower-level failure that accompanied the reply. */
2206
+ cause?: unknown;
2207
+ }
2208
+ /**
2209
+ * Maps an FTP reply into the closest typed ZeroTransfer error.
2210
+ *
2211
+ * @param input - FTP code, message, and optional operation context.
2212
+ * @returns A structured error subclass with stable code and retryability metadata.
2213
+ */
2214
+ declare function errorFromFtpReply(input: FtpReplyErrorInput): ZeroTransferError;
2215
+
2216
+ /**
2217
+ * Secret redaction helpers for logs, events, and diagnostics.
2218
+ *
2219
+ * These functions focus on preserving useful operational context while removing
2220
+ * credentials and command payloads that should not appear in logs.
2221
+ *
2222
+ * @module logging/redaction
2223
+ */
2224
+ /** Placeholder used when sensitive content has been removed. */
2225
+ declare const REDACTED = "[REDACTED]";
2226
+ /**
2227
+ * Checks whether an object key is likely to contain sensitive data.
2228
+ *
2229
+ * @param key - Object key to inspect.
2230
+ * @returns `true` when the key name should be redacted.
2231
+ */
2232
+ declare function isSensitiveKey(key: string): boolean;
2233
+ /**
2234
+ * Redacts sensitive FTP command payloads while preserving the command name.
2235
+ *
2236
+ * @param command - Raw command text such as `PASS secret` or `USER deploy`.
2237
+ * @returns Command text with secret arguments replaced by {@link REDACTED}.
2238
+ */
2239
+ declare function redactCommand(command: string): string;
2240
+ /**
2241
+ * Recursively redacts strings, arrays, and plain object values.
2242
+ *
2243
+ * @param value - Arbitrary value to sanitize for diagnostics.
2244
+ * @returns A redacted copy for arrays and objects, or the original primitive value.
2245
+ */
2246
+ declare function redactValue(value: unknown): unknown;
2247
+ /**
2248
+ * Redacts sensitive keys and nested values in a plain object.
2249
+ *
2250
+ * @param input - Object containing diagnostic fields.
2251
+ * @returns A shallow object copy with sensitive fields and nested secrets redacted.
2252
+ */
2253
+ declare function redactObject(input: Record<string, unknown>): Record<string, unknown>;
2254
+
2255
+ /** Sleep helper signature used by {@link createBandwidthThrottle}. */
2256
+ type BandwidthSleep = (delayMs: number, signal?: AbortSignal) => Promise<void>;
2257
+ /** Construction overrides for deterministic tests. */
2258
+ interface BandwidthThrottleOptions {
2259
+ /** Monotonic clock returning milliseconds since an arbitrary epoch. Defaults to `Date.now`. */
2260
+ now?: () => number;
2261
+ /** Sleep implementation honoring an optional abort signal. Defaults to a `setTimeout` helper. */
2262
+ sleep?: BandwidthSleep;
2263
+ }
2264
+ /** Token-bucket throttle used to pace transfer chunks. */
2265
+ interface BandwidthThrottle {
2266
+ /** Maximum sustained transfer rate in bytes per second. */
2267
+ readonly bytesPerSecond: number;
2268
+ /** Burst capacity in bytes available before throttling kicks in. */
2269
+ readonly burstBytes: number;
2270
+ /**
2271
+ * Consumes `bytes` from the bucket, awaiting refill when not enough tokens are available.
2272
+ *
2273
+ * @param bytes - Non-negative byte count being released by the throttle.
2274
+ * @param signal - Optional abort signal that interrupts pending waits.
2275
+ * @throws {@link AbortError} When the signal is aborted while waiting.
2276
+ */
2277
+ consume(bytes: number, signal?: AbortSignal): Promise<void>;
2278
+ }
2279
+ /**
2280
+ * Creates a token-bucket throttle that paces an asynchronous data pipeline to
2281
+ * a sustained {@link TransferBandwidthLimit}.
2282
+ *
2283
+ * Returns `undefined` when no limit is supplied so callers can omit throttling
2284
+ * without conditional branches at the call site.
2285
+ *
2286
+ * @param limit - Optional throughput limit. Returns `undefined` when omitted.
2287
+ * @param options - Optional clock/sleep overrides for deterministic tests.
2288
+ * @returns Throttle implementation when a limit is supplied, otherwise `undefined`.
2289
+ * @throws {@link ConfigurationError} When the supplied limit shape is invalid.
2290
+ */
2291
+ declare function createBandwidthThrottle(limit: TransferBandwidthLimit | undefined, options?: BandwidthThrottleOptions): BandwidthThrottle | undefined;
2292
+ /**
2293
+ * Wraps an async iterable of byte chunks so each chunk is released only after
2294
+ * the throttle has admitted its byte count.
2295
+ *
2296
+ * When `throttle` is `undefined`, the source iterable is returned unchanged.
2297
+ *
2298
+ * @param source - Async iterable that produces byte chunks.
2299
+ * @param throttle - Optional throttle that paces chunk emission.
2300
+ * @param signal - Optional abort signal interrupting pending waits.
2301
+ * @returns Async generator emitting the original chunks at the throttled rate.
2302
+ */
2303
+ declare function throttleByteIterable(source: AsyncIterable<Uint8Array>, throttle: BandwidthThrottle | undefined, signal?: AbortSignal): AsyncIterable<Uint8Array>;
2304
+
2305
+ /**
2306
+ * Transfer executor bridge for provider-backed read/write sessions.
2307
+ *
2308
+ * @module transfers/createProviderTransferExecutor
2309
+ */
2310
+
2311
+ /** Endpoint role used while resolving provider sessions for a transfer job. */
2312
+ type ProviderTransferEndpointRole = "source" | "destination";
2313
+ /** Input passed to provider transfer session resolvers. */
2314
+ interface ProviderTransferSessionResolverInput {
2315
+ /** Endpoint being resolved. */
2316
+ endpoint: TransferEndpoint;
2317
+ /** Whether the endpoint is the source or destination side of the transfer. */
2318
+ role: ProviderTransferEndpointRole;
2319
+ /** Job currently being executed. */
2320
+ job: TransferJob;
2321
+ }
2322
+ /** Resolves the connected provider session that owns an endpoint. */
2323
+ type ProviderTransferSessionResolver = (input: ProviderTransferSessionResolverInput) => TransferSession | undefined;
2324
+ /** Options for {@link createProviderTransferExecutor}. */
2325
+ interface ProviderTransferExecutorOptions {
2326
+ /** Resolves connected provider sessions for source and destination endpoints. */
2327
+ resolveSession: ProviderTransferSessionResolver;
2328
+ /** Optional clock/sleep overrides for the bandwidth throttle. */
2329
+ throttle?: BandwidthThrottleOptions;
2330
+ }
2331
+ /**
2332
+ * Creates a {@link TransferExecutor} that reads from a source provider and writes to a destination provider.
2333
+ *
2334
+ * The returned executor supports single-object `upload`, `download`, and `copy` jobs. Provider sessions must
2335
+ * expose `session.transfers.read()` and `session.transfers.write()`; concrete providers remain responsible for
2336
+ * the actual streaming implementation.
2337
+ *
2338
+ * @param options - Session resolver used for source and destination endpoints.
2339
+ * @returns Transfer executor suitable for {@link TransferEngine.execute} or {@link TransferQueue}.
2340
+ */
2341
+ declare function createProviderTransferExecutor(options: ProviderTransferExecutorOptions): TransferExecutor;
2342
+
2343
+ /**
2344
+ * Transfer plan and dry-run primitives.
2345
+ *
2346
+ * @module transfers/TransferPlan
2347
+ */
2348
+
2349
+ /** Non-executing plan action used to explain an intentionally skipped step. */
2350
+ type TransferPlanAction = TransferOperation | "skip";
2351
+ /** Step inside a transfer plan. */
2352
+ interface TransferPlanStep {
2353
+ /** Stable step identifier within the plan. */
2354
+ id: string;
2355
+ /** Action the step would perform. */
2356
+ action: TransferPlanAction;
2357
+ /** Source endpoint when the action reads data. */
2358
+ source?: TransferEndpoint;
2359
+ /** Destination endpoint when the action writes data. */
2360
+ destination?: TransferEndpoint;
2361
+ /** Expected bytes affected by the step when known. */
2362
+ expectedBytes?: number;
2363
+ /** Whether this step may remove or replace data. */
2364
+ destructive?: boolean;
2365
+ /** Human-readable reason for planned or skipped work. */
2366
+ reason?: string;
2367
+ /** Caller-defined metadata retained for diagnostics. */
2368
+ metadata?: Record<string, unknown>;
2369
+ }
2370
+ /** Input used to create a transfer plan. */
2371
+ interface TransferPlanInput {
2372
+ /** Stable plan identifier. */
2373
+ id: string;
2374
+ /** Planned steps in execution order. */
2375
+ steps: TransferPlanStep[];
2376
+ /** Whether the plan is informational only. Defaults to `true`. */
2377
+ dryRun?: boolean;
2378
+ /** Clock used for deterministic tests. Defaults to `new Date()`. */
2379
+ now?: () => Date;
2380
+ /** Non-fatal plan warnings. */
2381
+ warnings?: string[];
2382
+ /** Caller-defined metadata retained for diagnostics. */
2383
+ metadata?: Record<string, unknown>;
2384
+ }
2385
+ /** Provider-neutral transfer plan. */
2386
+ interface TransferPlan {
2387
+ /** Stable plan identifier. */
2388
+ id: string;
2389
+ /** Whether this plan should be treated as a dry run. */
2390
+ dryRun: boolean;
2391
+ /** Time the plan was created. */
2392
+ createdAt: Date;
2393
+ /** Planned steps in execution order. */
2394
+ steps: TransferPlanStep[];
2395
+ /** Non-fatal plan warnings. */
2396
+ warnings: string[];
2397
+ /** Caller-defined metadata retained for diagnostics. */
2398
+ metadata?: Record<string, unknown>;
2399
+ }
2400
+ /** Summary of a transfer plan. */
2401
+ interface TransferPlanSummary {
2402
+ /** Total number of steps. */
2403
+ totalSteps: number;
2404
+ /** Number of executable steps. */
2405
+ executableSteps: number;
2406
+ /** Number of skipped steps. */
2407
+ skippedSteps: number;
2408
+ /** Number of destructive steps. */
2409
+ destructiveSteps: number;
2410
+ /** Sum of expected bytes for steps that provide sizes. */
2411
+ totalExpectedBytes: number;
2412
+ /** Counts grouped by action. */
2413
+ actions: Record<string, number>;
2414
+ }
2415
+ /** Creates a transfer plan from dry-run planning input. */
2416
+ declare function createTransferPlan(input: TransferPlanInput): TransferPlan;
2417
+ /** Summarizes a transfer plan for diagnostics, previews, and tests. */
2418
+ declare function summarizeTransferPlan(plan: TransferPlan): TransferPlanSummary;
2419
+ /** Converts executable plan steps into transfer jobs while preserving order. */
2420
+ declare function createTransferJobsFromPlan(plan: TransferPlan): TransferJob[];
2421
+
2422
+ /** Queue item lifecycle state. */
2423
+ type TransferQueueItemStatus = "queued" | "running" | "completed" | "failed" | "canceled";
2424
+ /** Resolver used when jobs do not provide an executor at enqueue time. */
2425
+ type TransferQueueExecutorResolver = (job: TransferJob) => TransferExecutor;
2426
+ /** Options used to create a transfer queue. */
2427
+ interface TransferQueueOptions {
2428
+ /** Transfer engine used to execute queued jobs. Defaults to a new engine. */
2429
+ engine?: TransferEngine;
2430
+ /** Maximum jobs to execute at the same time. Defaults to `1`. */
2431
+ concurrency?: number;
2432
+ /** Default executor used for jobs that do not provide one directly. */
2433
+ executor?: TransferExecutor;
2434
+ /** Dynamic executor resolver used when no per-job executor or default executor exists. */
2435
+ resolveExecutor?: TransferQueueExecutorResolver;
2436
+ /** Retry policy passed to engine executions. */
2437
+ retry?: TransferRetryPolicy;
2438
+ /** Timeout policy passed to engine executions. */
2439
+ timeout?: TransferTimeoutPolicy;
2440
+ /** Optional throughput limit shape passed to transfer executors. */
2441
+ bandwidthLimit?: TransferBandwidthLimit;
2442
+ /** Progress observer shared across queued jobs. */
2443
+ onProgress?: (event: TransferProgressEvent) => void;
2444
+ /** Completion observer for successful jobs. */
2445
+ onReceipt?: (receipt: TransferReceipt) => void;
2446
+ /** Failure observer for failed jobs. */
2447
+ onError?: (item: TransferQueueItem, error: unknown) => void;
2448
+ }
2449
+ /** Options used when draining a queue. */
2450
+ interface TransferQueueRunOptions {
2451
+ /** Abort signal used to cancel running jobs during this drain. */
2452
+ signal?: AbortSignal;
2453
+ /** Retry policy override for this drain. */
2454
+ retry?: TransferRetryPolicy;
2455
+ /** Timeout policy override for this drain. */
2456
+ timeout?: TransferTimeoutPolicy;
2457
+ /** Bandwidth limit override for this drain. */
2458
+ bandwidthLimit?: TransferBandwidthLimit;
2459
+ /** Progress observer override for this drain. */
2460
+ onProgress?: (event: TransferProgressEvent) => void;
2461
+ }
2462
+ /** Enqueued transfer job state. */
2463
+ interface TransferQueueItem {
2464
+ /** Queued job identifier. */
2465
+ id: string;
2466
+ /** Original transfer job. */
2467
+ job: TransferJob;
2468
+ /** Current queue status. */
2469
+ status: TransferQueueItemStatus;
2470
+ /** Successful transfer receipt when completed. */
2471
+ receipt?: TransferReceipt;
2472
+ /** Failure or cancellation reason when available. */
2473
+ error?: unknown;
2474
+ }
2475
+ /** Summary returned after a queue drain. */
2476
+ interface TransferQueueSummary {
2477
+ /** Number of items currently known to the queue. */
2478
+ total: number;
2479
+ /** Number of successfully completed jobs. */
2480
+ completed: number;
2481
+ /** Number of failed jobs. */
2482
+ failed: number;
2483
+ /** Number of canceled jobs. */
2484
+ canceled: number;
2485
+ /** Number of jobs still queued because the queue was paused. */
2486
+ queued: number;
2487
+ /** Number of jobs currently running. */
2488
+ running: number;
2489
+ /** Successful receipts in queue order. */
2490
+ receipts: TransferReceipt[];
2491
+ /** Failed queue items in queue order. */
2492
+ failures: TransferQueueItem[];
2493
+ }
2494
+ /** Minimal transfer queue with concurrency, pause/resume, cancellation, and drain summaries. */
2495
+ declare class TransferQueue {
2496
+ private readonly engine;
2497
+ private readonly items;
2498
+ private readonly defaultExecutor;
2499
+ private readonly resolveExecutor;
2500
+ private readonly retry;
2501
+ private readonly timeout;
2502
+ private readonly bandwidthLimit;
2503
+ private readonly onProgress;
2504
+ private readonly onReceipt;
2505
+ private readonly onError;
2506
+ private concurrency;
2507
+ private paused;
2508
+ /**
2509
+ * Creates a transfer queue.
2510
+ *
2511
+ * @param options - Queue engine, concurrency, executor, and observer options.
2512
+ */
2513
+ constructor(options?: TransferQueueOptions);
2514
+ /** Adds a transfer job to the queue. */
2515
+ add(job: TransferJob, executor?: TransferExecutor): TransferQueueItem;
2516
+ /** Pauses dispatch of new queued jobs. Running jobs are allowed to finish. */
2517
+ pause(): void;
2518
+ /** Resumes dispatch of queued jobs on the next `run()` call. */
2519
+ resume(): void;
2520
+ /** Updates queue concurrency for subsequent drains. */
2521
+ setConcurrency(concurrency: number): void;
2522
+ /** Cancels a queued or running job. */
2523
+ cancel(jobId: string): boolean;
2524
+ /** Returns a queued item snapshot by id. */
2525
+ get(jobId: string): TransferQueueItem | undefined;
2526
+ /** Lists queue item snapshots in insertion order. */
2527
+ list(): TransferQueueItem[];
2528
+ /** Drains currently queued jobs until complete, failed, canceled, or paused. */
2529
+ run(options?: TransferQueueRunOptions): Promise<TransferQueueSummary>;
2530
+ /** Returns a queue summary without executing more work. */
2531
+ summarize(): TransferQueueSummary;
2532
+ private runWorker;
2533
+ private nextQueuedItem;
2534
+ private runItem;
2535
+ private requireExecutor;
2536
+ private countDispatchableItems;
2537
+ }
2538
+
2539
+ /**
2540
+ * Browser-friendly directory navigation helpers for file-manager UIs.
2541
+ *
2542
+ * Wraps a {@link RemoteFileSystem} with stateful current-directory tracking,
2543
+ * breadcrumb generation, and pure sort/filter utilities so consumers can render
2544
+ * directory views without re-implementing common navigation glue.
2545
+ *
2546
+ * @module sync/createRemoteBrowser
2547
+ */
2548
+
2549
+ /** Sort key supported by {@link sortRemoteEntries}. */
2550
+ type RemoteEntrySortKey = "name" | "size" | "modifiedAt" | "type";
2551
+ /** Sort direction supported by {@link sortRemoteEntries}. */
2552
+ type RemoteEntrySortOrder = "asc" | "desc";
2553
+ /** Crumb describing one segment in the current path. */
2554
+ interface RemoteBreadcrumb {
2555
+ /** Display name. `""` is replaced with `"/"` for the root crumb. */
2556
+ name: string;
2557
+ /** Absolute path the crumb resolves to. */
2558
+ path: string;
2559
+ }
2560
+ /** Filter callback applied to a directory listing. */
2561
+ type RemoteBrowserFilter = (entry: RemoteEntry) => boolean;
2562
+ /** Options accepted by {@link createRemoteBrowser}. */
2563
+ interface CreateRemoteBrowserOptions {
2564
+ /** Remote file system to browse. */
2565
+ fs: RemoteFileSystem;
2566
+ /** Initial path. Defaults to `"/"`. */
2567
+ initialPath?: string;
2568
+ /** Sort key applied to listings. Defaults to `"name"`. */
2569
+ sortKey?: RemoteEntrySortKey;
2570
+ /** Sort order applied to listings. Defaults to `"asc"`. */
2571
+ sortOrder?: RemoteEntrySortOrder;
2572
+ /** Whether dotfile entries (names starting with `.`) are included. Defaults to `true`. */
2573
+ showHidden?: boolean;
2574
+ /** Optional filter applied after sort/hidden filtering. */
2575
+ filter?: RemoteBrowserFilter;
2576
+ }
2577
+ /** Snapshot returned by browser navigation methods. */
2578
+ interface RemoteBrowserSnapshot {
2579
+ /** Current absolute path. */
2580
+ path: string;
2581
+ /** Directory entries after sorting and filtering. */
2582
+ entries: RemoteEntry[];
2583
+ /** Breadcrumb trail leading from `/` to {@link path}. */
2584
+ breadcrumbs: RemoteBreadcrumb[];
2585
+ }
2586
+ /** Stateful directory browser returned by {@link createRemoteBrowser}. */
2587
+ interface RemoteBrowser {
2588
+ /** Current absolute path. */
2589
+ readonly path: string;
2590
+ /** Last loaded sorted/filtered entries. */
2591
+ readonly entries: readonly RemoteEntry[];
2592
+ /** Reload the current directory and return the latest snapshot. */
2593
+ refresh(): Promise<RemoteBrowserSnapshot>;
2594
+ /** Navigate to the supplied absolute or relative path. */
2595
+ navigate(target: string): Promise<RemoteBrowserSnapshot>;
2596
+ /** Descend into the supplied directory entry. Throws when the entry is not a directory. */
2597
+ open(entry: RemoteEntry): Promise<RemoteBrowserSnapshot>;
2598
+ /** Move to the parent directory; no-op when already at the root. */
2599
+ up(): Promise<RemoteBrowserSnapshot>;
2600
+ /** Compute breadcrumbs for the current path without re-listing. */
2601
+ breadcrumbs(): RemoteBreadcrumb[];
2602
+ /** Update the sort key. The next refresh re-sorts the cached entries. */
2603
+ setSort(key: RemoteEntrySortKey, order?: RemoteEntrySortOrder): void;
2604
+ /** Toggle hidden-entry visibility. The next refresh re-applies the filter. */
2605
+ setShowHidden(showHidden: boolean): void;
2606
+ }
2607
+ /**
2608
+ * Returns the parent directory of a remote path, or `"/"` for root inputs.
2609
+ *
2610
+ * @param input - Remote path to inspect.
2611
+ * @returns The parent path normalized to an absolute form.
2612
+ */
2613
+ declare function parentRemotePath(input: string): string;
2614
+ /**
2615
+ * Builds breadcrumbs from `/` down to the supplied path.
2616
+ *
2617
+ * @param input - Absolute remote path.
2618
+ * @returns Ordered crumbs starting with the root.
2619
+ */
2620
+ declare function buildRemoteBreadcrumbs(input: string): RemoteBreadcrumb[];
2621
+ /**
2622
+ * Returns a copy of the supplied entries sorted by the requested key. Directories
2623
+ * are grouped before files within ascending sorts, matching common file-manager UX.
2624
+ *
2625
+ * @param entries - Entries to sort.
2626
+ * @param key - Sort key.
2627
+ * @param order - Sort order.
2628
+ * @returns Sorted copy of the entries.
2629
+ */
2630
+ declare function sortRemoteEntries(entries: readonly RemoteEntry[], key?: RemoteEntrySortKey, order?: RemoteEntrySortOrder): RemoteEntry[];
2631
+ /**
2632
+ * Filters entries using the optional predicate plus an optional hidden-file rule.
2633
+ *
2634
+ * @param entries - Entries to filter.
2635
+ * @param options - Filtering controls.
2636
+ * @returns Entries matching the supplied rules.
2637
+ */
2638
+ declare function filterRemoteEntries(entries: readonly RemoteEntry[], options?: {
2639
+ filter?: RemoteBrowserFilter;
2640
+ showHidden?: boolean;
2641
+ }): RemoteEntry[];
2642
+ /**
2643
+ * Creates a stateful directory browser around a remote file system.
2644
+ *
2645
+ * The returned browser caches the most recent listing and applies sort/filter
2646
+ * settings on each refresh. Navigation methods return a snapshot so UI layers can
2647
+ * render synchronously without re-reading state.
2648
+ *
2649
+ * @param options - Browser configuration.
2650
+ * @returns Stateful browser bound to the supplied file system.
2651
+ */
2652
+ declare function createRemoteBrowser(options: CreateRemoteBrowserOptions): RemoteBrowser;
2653
+
2654
+ /** Filter callback applied to each visited entry. Returning `false` skips the entry. */
2655
+ type RemoteTreeFilter = (entry: RemoteEntry) => boolean;
2656
+ /** Options accepted by {@link walkRemoteTree}. */
2657
+ interface WalkRemoteTreeOptions {
2658
+ /** Whether to descend into subdirectories. Defaults to `true`. */
2659
+ recursive?: boolean;
2660
+ /** Maximum traversal depth. `0` walks only the root listing. Unbounded by default. */
2661
+ maxDepth?: number;
2662
+ /** Whether to include directory entries in the output. Defaults to `true`. */
2663
+ includeDirectories?: boolean;
2664
+ /** Whether to include file entries in the output. Defaults to `true`. */
2665
+ includeFiles?: boolean;
2666
+ /** Whether to follow symlinks during traversal. Defaults to `false`. */
2667
+ followSymlinks?: boolean;
2668
+ /** Optional filter applied before yielding and before descending into directories. */
2669
+ filter?: RemoteTreeFilter;
2670
+ /** Optional abort signal that interrupts traversal between listings. */
2671
+ signal?: AbortSignal;
2672
+ }
2673
+ /** Walk record yielded by {@link walkRemoteTree}. */
2674
+ interface RemoteTreeEntry {
2675
+ /** Visited remote entry. */
2676
+ entry: RemoteEntry;
2677
+ /** Zero-based depth relative to the traversal root. */
2678
+ depth: number;
2679
+ /** Normalized parent directory path. */
2680
+ parentPath: string;
2681
+ }
2682
+ /**
2683
+ * Walks a remote file system depth-first, yielding entries in a stable order.
2684
+ *
2685
+ * Listings are sorted by entry path within each directory so output is deterministic
2686
+ * across providers. Errors thrown by `fs.list()` propagate; callers can supply a
2687
+ * filter to skip directories that should not be traversed.
2688
+ *
2689
+ * @param fs - Remote file system used for listings.
2690
+ * @param rootPath - Root directory to walk.
2691
+ * @param options - Optional traversal controls.
2692
+ * @returns Async generator emitting {@link RemoteTreeEntry} records.
2693
+ * @throws {@link AbortError} When the supplied abort signal is cancelled mid-walk.
2694
+ */
2695
+ declare function walkRemoteTree(fs: RemoteFileSystem, rootPath: string, options?: WalkRemoteTreeOptions): AsyncGenerator<RemoteTreeEntry>;
2696
+
2697
+ /**
2698
+ * Directory diffing primitives that compare two remote trees.
2699
+ *
2700
+ * @module sync/diffRemoteTrees
2701
+ */
2702
+
2703
+ /** Outcome category for an entry across the two compared trees. */
2704
+ type RemoteTreeDiffStatus = "added" | "removed" | "modified" | "unchanged";
2705
+ /** Reason an entry is considered modified. */
2706
+ type RemoteTreeDiffReason = "type" | "size" | "modifiedAt" | "checksum";
2707
+ /** Single diff record produced by {@link diffRemoteTrees}. */
2708
+ interface RemoteTreeDiffEntry {
2709
+ /** Path relative to the traversal root, beginning with `/`. */
2710
+ path: string;
2711
+ /** Outcome category for this entry. */
2712
+ status: RemoteTreeDiffStatus;
2713
+ /** Reasons the entry is considered modified. Empty for unchanged/added/removed records. */
2714
+ reasons: RemoteTreeDiffReason[];
2715
+ /** Source-side entry, when present. */
2716
+ source?: RemoteEntry;
2717
+ /** Destination-side entry, when present. */
2718
+ destination?: RemoteEntry;
2719
+ }
2720
+ /** Compact summary of a diff result. */
2721
+ interface RemoteTreeDiffSummary {
2722
+ /** Number of entries present only on the source side. */
2723
+ added: number;
2724
+ /** Number of entries present only on the destination side. */
2725
+ removed: number;
2726
+ /** Number of entries present on both sides whose contents differ. */
2727
+ modified: number;
2728
+ /** Number of entries present on both sides with identical contents. */
2729
+ unchanged: number;
2730
+ /** Total entries inspected across both sides. */
2731
+ total: number;
2732
+ }
2733
+ /** Result returned by {@link diffRemoteTrees}. */
2734
+ interface RemoteTreeDiff {
2735
+ /** Diff records sorted by path. */
2736
+ entries: RemoteTreeDiffEntry[];
2737
+ /** Compact counts for the diff. */
2738
+ summary: RemoteTreeDiffSummary;
2739
+ }
2740
+ /** Options accepted by {@link diffRemoteTrees}. */
2741
+ interface DiffRemoteTreesOptions {
2742
+ /** Optional traversal controls applied to both sides. */
2743
+ walk?: Pick<WalkRemoteTreeOptions, "filter" | "followSymlinks" | "includeDirectories" | "includeFiles" | "maxDepth" | "recursive">;
2744
+ /** Filter applied only to the source side. Overrides `walk.filter` when set. */
2745
+ sourceFilter?: RemoteTreeFilter;
2746
+ /** Filter applied only to the destination side. Overrides `walk.filter` when set. */
2747
+ destinationFilter?: RemoteTreeFilter;
2748
+ /** Whether unchanged entries are included in `entries`. Defaults to `false`. */
2749
+ includeUnchanged?: boolean;
2750
+ /** Tolerance in milliseconds when comparing modification timestamps. Defaults to `1000`. */
2751
+ modifiedAtToleranceMs?: number;
2752
+ /** Whether modification timestamps participate in the comparison. Defaults to `true`. */
2753
+ compareModifiedAt?: boolean;
2754
+ /** Whether sizes participate in the comparison. Defaults to `true`. */
2755
+ compareSize?: boolean;
2756
+ /** Whether to require matching `uniqueId` checksums when both entries expose one. Defaults to `false`. */
2757
+ compareUniqueId?: boolean;
2758
+ /** Optional abort signal threaded through both walks. */
2759
+ signal?: AbortSignal;
2760
+ }
2761
+ /**
2762
+ * Compares two remote subtrees and produces an entry-level diff.
2763
+ *
2764
+ * Source and destination paths are walked independently; entries are then aligned by
2765
+ * the relative path from each tree root. Directory equality is structural — directories
2766
+ * are equal when their relative paths match and the entry types agree.
2767
+ *
2768
+ * @param source - Source-side remote file system.
2769
+ * @param sourcePath - Source-side root path being compared.
2770
+ * @param destination - Destination-side remote file system.
2771
+ * @param destinationPath - Destination-side root path being compared.
2772
+ * @param options - Optional comparison controls.
2773
+ * @returns Diff result containing entries and a summary.
2774
+ */
2775
+ declare function diffRemoteTrees(source: RemoteFileSystem, sourcePath: string, destination: RemoteFileSystem, destinationPath: string, options?: DiffRemoteTreesOptions): Promise<RemoteTreeDiff>;
2776
+
2777
+ /**
2778
+ * Sync planning primitives that build a {@link TransferPlan} from a remote-tree diff.
2779
+ *
2780
+ * @module sync/createSyncPlan
2781
+ */
2782
+
2783
+ /** Sync direction used by {@link createSyncPlan}. */
2784
+ type SyncDirection = "source-to-destination" | "destination-to-source";
2785
+ /** How {@link createSyncPlan} reacts to entries that exist only on the destination. */
2786
+ type SyncDeletePolicy =
2787
+ /** Never delete destination entries that are missing on the source. */
2788
+ "never"
2789
+ /** Plan destination deletions when running source-to-destination sync. */
2790
+ | "mirror"
2791
+ /** Plan destination deletions only when paired with a same-path file on the source. */
2792
+ | "replace-only";
2793
+ /** How {@link createSyncPlan} reacts to entries flagged as modified on both sides. */
2794
+ type SyncConflictPolicy =
2795
+ /** Overwrite the destination with the source. */
2796
+ "overwrite"
2797
+ /** Overwrite the source with the destination. */
2798
+ | "prefer-destination"
2799
+ /** Skip conflicting entries with a `skip` step. */
2800
+ | "skip"
2801
+ /** Fail planning with a {@link ConfigurationError} when a conflict is encountered. */
2802
+ | "error";
2803
+ /** Endpoint shape supplied to {@link createSyncPlan}. */
2804
+ interface SyncEndpointInput {
2805
+ /** Provider that owns the endpoint when known. */
2806
+ provider?: ProviderId;
2807
+ /** Root path on the provider being synced. */
2808
+ rootPath: string;
2809
+ }
2810
+ /** Options accepted by {@link createSyncPlan}. */
2811
+ interface CreateSyncPlanOptions {
2812
+ /** Stable plan identifier. */
2813
+ id: string;
2814
+ /** Diff produced by {@link diffRemoteTrees} or an equivalent source. */
2815
+ diff: RemoteTreeDiff;
2816
+ /** Source-side endpoint that produced the diff. */
2817
+ source: SyncEndpointInput;
2818
+ /** Destination-side endpoint that produced the diff. */
2819
+ destination: SyncEndpointInput;
2820
+ /** Sync direction. Defaults to `"source-to-destination"`. */
2821
+ direction?: SyncDirection;
2822
+ /** Delete policy. Defaults to `"never"`. */
2823
+ deletePolicy?: SyncDeletePolicy;
2824
+ /** Conflict policy. Defaults to `"overwrite"`. */
2825
+ conflictPolicy?: SyncConflictPolicy;
2826
+ /** Whether to plan upload/download steps for directories. Defaults to `false`. */
2827
+ includeDirectoryActions?: boolean;
2828
+ /** Whether the plan is informational only. Defaults to `true`. */
2829
+ dryRun?: boolean;
2830
+ /** Clock used for deterministic tests. Defaults to `new Date()`. */
2831
+ now?: () => Date;
2832
+ /** Caller-defined metadata retained for diagnostics. */
2833
+ metadata?: Record<string, unknown>;
2834
+ }
2835
+ /**
2836
+ * Builds a {@link TransferPlan} that reconciles two remote subtrees.
2837
+ *
2838
+ * Plan steps are derived from a {@link RemoteTreeDiff}; the function does not perform
2839
+ * any I/O. Direction, delete policy, and conflict policy control which entries
2840
+ * become executable transfers and which become `skip` steps.
2841
+ *
2842
+ * @param options - Inputs and policies that shape the plan.
2843
+ * @returns Transfer plan ready for `createTransferJobsFromPlan` or queue execution.
2844
+ * @throws {@link ConfigurationError} When `conflictPolicy: "error"` encounters a conflict.
2845
+ */
2846
+ declare function createSyncPlan(options: CreateSyncPlanOptions): TransferPlan;
2847
+
2848
+ /**
2849
+ * Atomic deploy planning helpers.
2850
+ *
2851
+ * Produces a structured plan that stages a release under `<liveRoot>/<releasesDir>/<releaseId>`,
2852
+ * activates it via rename or symlink swap, and prunes older releases beyond a retain count.
2853
+ *
2854
+ * The plan is provider-neutral and execution-free: callers wire the upload {@link TransferPlan}
2855
+ * through the transfer engine and execute the activate/prune steps using their provider's
2856
+ * filesystem mutation primitives (rename, symlink, delete).
2857
+ *
2858
+ * @module sync/createAtomicDeployPlan
2859
+ */
2860
+
2861
+ /** Activation strategy used to swap a staged release into place. */
2862
+ type AtomicDeployStrategy =
2863
+ /** Rename `<liveRoot>` aside, then rename the staging path to `<liveRoot>`. */
2864
+ "rename"
2865
+ /** Update a symlink at `<liveRoot>` to point at the staging path. */
2866
+ | "symlink";
2867
+ /** Operation kind for an activation step. */
2868
+ type AtomicDeployActivateOperation = "rename" | "symlink" | "delete";
2869
+ /** Kind of activation step described by the plan. */
2870
+ interface AtomicDeployActivateStep {
2871
+ /** Stable identifier within the activation list. */
2872
+ id: string;
2873
+ /** Operation the step would perform. */
2874
+ operation: AtomicDeployActivateOperation;
2875
+ /** Source path the operation reads or moves from. */
2876
+ fromPath?: string;
2877
+ /** Destination path the operation writes to. */
2878
+ toPath: string;
2879
+ /** Provider identifier that owns the affected paths when known. */
2880
+ provider?: ProviderId;
2881
+ /** Whether the step replaces or removes data. */
2882
+ destructive?: boolean;
2883
+ /** Human-readable description for previews and logs. */
2884
+ reason: string;
2885
+ }
2886
+ /** Pruning step describing an old release directory marked for deletion. */
2887
+ interface AtomicDeployPruneStep {
2888
+ /** Stable identifier within the prune list. */
2889
+ id: string;
2890
+ /** Absolute release directory path to delete. */
2891
+ path: string;
2892
+ /** Provider identifier that owns the path when known. */
2893
+ provider?: ProviderId;
2894
+ /** Reason the release was selected for pruning. */
2895
+ reason: string;
2896
+ }
2897
+ /** Result returned by {@link createAtomicDeployPlan}. */
2898
+ interface AtomicDeployPlan {
2899
+ /** Stable plan identifier. */
2900
+ id: string;
2901
+ /** Release identifier embedded into the staging path. */
2902
+ releaseId: string;
2903
+ /** Activation strategy chosen for the swap. */
2904
+ strategy: AtomicDeployStrategy;
2905
+ /** Provider identifier for the live destination when known. */
2906
+ provider?: ProviderId;
2907
+ /** Live target path the release activates onto. */
2908
+ livePath: string;
2909
+ /** Staging directory the upload populates. */
2910
+ stagingPath: string;
2911
+ /** Releases root directory under which staging and prior releases live. */
2912
+ releasesRoot: string;
2913
+ /** Optional backup path used by the rename strategy. */
2914
+ backupPath?: string;
2915
+ /** Upload plan that populates the staging directory. */
2916
+ uploadPlan: TransferPlan;
2917
+ /** Activation steps that swap staging into the live path. */
2918
+ activate: AtomicDeployActivateStep[];
2919
+ /** Prune steps that remove older releases beyond {@link retain}. */
2920
+ prune: AtomicDeployPruneStep[];
2921
+ /** Number of releases to retain (including the new release). */
2922
+ retain: number;
2923
+ /** Time the plan was created. */
2924
+ createdAt: Date;
2925
+ /** Non-fatal plan warnings. */
2926
+ warnings: string[];
2927
+ /** Caller-defined metadata retained for diagnostics. */
2928
+ metadata?: Record<string, unknown>;
2929
+ }
2930
+ /** Options accepted by {@link createAtomicDeployPlan}. */
2931
+ interface CreateAtomicDeployPlanOptions {
2932
+ /** Stable plan identifier. */
2933
+ id: string;
2934
+ /** Diff describing source vs. staging contents (typically diffed against an empty staging directory). */
2935
+ diff: RemoteTreeDiff;
2936
+ /** Source-side endpoint feeding the release. */
2937
+ source: SyncEndpointInput;
2938
+ /** Live destination endpoint the release activates onto. */
2939
+ destination: SyncEndpointInput;
2940
+ /** Activation strategy. Defaults to `"rename"`. */
2941
+ strategy?: AtomicDeployStrategy;
2942
+ /** Release identifier. Defaults to a timestamp derived from {@link now}. */
2943
+ releaseId?: string;
2944
+ /** Releases directory name under the destination root. Defaults to `".releases"`. */
2945
+ releasesDirectory?: string;
2946
+ /** Number of releases to retain after the new release, including the new one. Defaults to `3`. */
2947
+ retain?: number;
2948
+ /** Existing release directory paths under the releases root that may be pruned. */
2949
+ existingReleases?: string[];
2950
+ /** Whether the plan is informational only. Defaults to `true`. */
2951
+ dryRun?: boolean;
2952
+ /** Clock used for deterministic tests. Defaults to `new Date()`. */
2953
+ now?: () => Date;
2954
+ /** Caller-defined metadata retained for diagnostics. */
2955
+ metadata?: Record<string, unknown>;
2956
+ }
2957
+ /**
2958
+ * Builds an {@link AtomicDeployPlan} that stages a release, swaps it live, and prunes old releases.
2959
+ *
2960
+ * @param options - Inputs and policies that shape the deploy.
2961
+ * @returns Structured deploy plan ready for execution by the calling host.
2962
+ * @throws {@link ConfigurationError} When `retain` is less than `1` or the destination root is empty.
2963
+ */
2964
+ declare function createAtomicDeployPlan(options: CreateAtomicDeployPlanOptions): AtomicDeployPlan;
2965
+
2966
+ /** Schema version for the manifest payload. Bumped on incompatible format changes. */
2967
+ declare const REMOTE_MANIFEST_FORMAT_VERSION = 1;
2968
+ /** Manifest entry recorded for each visited remote node. */
2969
+ interface RemoteManifestEntry {
2970
+ /** Path relative to {@link RemoteManifest.root}, beginning with `/`. */
2971
+ path: string;
2972
+ /** Entry kind. */
2973
+ type: RemoteEntryType;
2974
+ /** Entry size in bytes when known. */
2975
+ size?: number;
2976
+ /** Last modification time as an ISO 8601 timestamp when known. */
2977
+ modifiedAt?: string;
2978
+ /** Protocol-specific stable identity when available. */
2979
+ uniqueId?: string;
2980
+ /** Target path for symbolic links when known. */
2981
+ symlinkTarget?: string;
2982
+ }
2983
+ /** Persisted snapshot of a remote subtree. */
2984
+ interface RemoteManifest {
2985
+ /** Schema version. Must equal {@link REMOTE_MANIFEST_FORMAT_VERSION}. */
2986
+ formatVersion: number;
2987
+ /** ISO 8601 timestamp recording when the manifest was generated. */
2988
+ generatedAt: string;
2989
+ /** Normalized absolute root path the manifest snapshot is anchored to. */
2990
+ root: string;
2991
+ /** Optional provider identifier the snapshot was captured from. */
2992
+ provider?: ProviderId;
2993
+ /** Manifest entries sorted by path. */
2994
+ entries: RemoteManifestEntry[];
2995
+ }
2996
+ /** Options accepted by {@link createRemoteManifest}. */
2997
+ interface CreateRemoteManifestOptions {
2998
+ /** Optional traversal controls forwarded to {@link walkRemoteTree}. */
2999
+ walk?: Pick<WalkRemoteTreeOptions, "filter" | "followSymlinks" | "includeDirectories" | "includeFiles" | "maxDepth" | "recursive">;
3000
+ /** Filter applied during traversal. Overrides `walk.filter` when provided. */
3001
+ filter?: RemoteTreeFilter;
3002
+ /** Provider identifier embedded into the manifest header. */
3003
+ provider?: ProviderId;
3004
+ /** Clock used to stamp `generatedAt`. Defaults to `Date.now`. */
3005
+ now?: () => Date;
3006
+ /** Optional abort signal threaded through the walk. */
3007
+ signal?: AbortSignal;
3008
+ }
3009
+ /** Options accepted by {@link compareRemoteManifests}. */
3010
+ interface CompareRemoteManifestsOptions {
3011
+ /** Whether unchanged entries are included in the result. Defaults to `false`. */
3012
+ includeUnchanged?: boolean;
3013
+ /** Tolerance in milliseconds applied to `modifiedAt` comparisons. Defaults to `1000`. */
3014
+ modifiedAtToleranceMs?: number;
3015
+ /** Whether modification timestamps participate in the comparison. Defaults to `true`. */
3016
+ compareModifiedAt?: boolean;
3017
+ /** Whether sizes participate in the comparison. Defaults to `true`. */
3018
+ compareSize?: boolean;
3019
+ /** Whether to require matching `uniqueId` checksums when both entries expose one. Defaults to `false`. */
3020
+ compareUniqueId?: boolean;
3021
+ }
3022
+ /**
3023
+ * Walks a remote subtree and produces a serializable manifest snapshot.
3024
+ *
3025
+ * @param fs - Remote file system to capture.
3026
+ * @param rootPath - Root path the manifest is anchored to.
3027
+ * @param options - Optional capture controls.
3028
+ * @returns Manifest snapshot suitable for serialization or comparison.
3029
+ */
3030
+ declare function createRemoteManifest(fs: RemoteFileSystem, rootPath: string, options?: CreateRemoteManifestOptions): Promise<RemoteManifest>;
3031
+ /**
3032
+ * Serializes a manifest to a JSON string suitable for persistence.
3033
+ *
3034
+ * @param manifest - Manifest snapshot to serialize.
3035
+ * @param indent - Optional indentation passed to `JSON.stringify`. Defaults to `2`.
3036
+ * @returns Stable JSON representation of the manifest.
3037
+ */
3038
+ declare function serializeRemoteManifest(manifest: RemoteManifest, indent?: number): string;
3039
+ /**
3040
+ * Parses a JSON-encoded manifest, validating the schema version and entry shape.
3041
+ *
3042
+ * @param text - JSON payload produced by {@link serializeRemoteManifest}.
3043
+ * @returns Parsed manifest snapshot.
3044
+ * @throws {@link ConfigurationError} When the payload is invalid or has an unsupported version.
3045
+ */
3046
+ declare function parseRemoteManifest(text: string): RemoteManifest;
3047
+ /**
3048
+ * Compares two manifests and produces an entry-level diff.
3049
+ *
3050
+ * The comparison is performed on the relative-path keys recorded inside each manifest;
3051
+ * the absolute roots may differ between snapshots (e.g. captured against `/site` on the
3052
+ * source and `/var/www/site` on the destination).
3053
+ *
3054
+ * @param source - Source-side manifest snapshot.
3055
+ * @param destination - Destination-side manifest snapshot.
3056
+ * @param options - Optional comparison controls.
3057
+ * @returns Diff result mirroring {@link RemoteTreeDiff}.
3058
+ */
3059
+ declare function compareRemoteManifests(source: RemoteManifest, destination: RemoteManifest, options?: CompareRemoteManifestsOptions): RemoteTreeDiff;
3060
+
3061
+ /**
3062
+ * Transfer result and progress calculation helpers.
3063
+ *
3064
+ * These helpers are pure functions so future FTP, FTPS, and SFTP adapters can share
3065
+ * timing, throughput, and progress calculations without coupling to transport code.
3066
+ *
3067
+ * @module services/TransferService
3068
+ */
3069
+
3070
+ /**
3071
+ * Input used to create a final transfer result.
3072
+ */
3073
+ interface TransferResultInput {
3074
+ /** Local or remote source path when known. */
3075
+ sourcePath?: string;
3076
+ /** Local or remote destination path for the transfer. */
3077
+ destinationPath: string;
3078
+ /** Total bytes transferred. */
3079
+ bytesTransferred: number;
3080
+ /** Time the transfer began. */
3081
+ startedAt: Date;
3082
+ /** Time the transfer completed. */
3083
+ completedAt: Date;
3084
+ /** Whether the transfer resumed from an earlier partial state. */
3085
+ resumed?: boolean;
3086
+ /** Whether post-transfer verification succeeded. */
3087
+ verified?: boolean;
3088
+ /** Optional checksum value produced or verified by the transfer. */
3089
+ checksum?: string;
3090
+ }
3091
+ /**
3092
+ * Input used to create a transfer progress event.
3093
+ */
3094
+ interface ProgressEventInput {
3095
+ /** Stable transfer identifier for correlation. */
3096
+ transferId: string;
3097
+ /** Bytes transferred so far. */
3098
+ bytesTransferred: number;
3099
+ /** Time the transfer began. */
3100
+ startedAt: Date;
3101
+ /** Time to use for the progress calculation; defaults to current time. */
3102
+ now?: Date;
3103
+ /** Total expected bytes when known. */
3104
+ totalBytes?: number;
3105
+ }
3106
+ /**
3107
+ * Creates a final transfer result with duration and average throughput.
3108
+ *
3109
+ * @param input - Transfer paths, byte count, timestamps, and optional verification metadata.
3110
+ * @returns A normalized transfer result.
3111
+ */
3112
+ declare function createTransferResult(input: TransferResultInput): TransferResult;
3113
+ /**
3114
+ * Creates a progress event with elapsed time, rate, and optional percentage.
3115
+ *
3116
+ * @param input - Transfer id, byte count, start time, optional current time, and total bytes.
3117
+ * @returns A normalized transfer progress event.
3118
+ */
3119
+ declare function createProgressEvent(input: ProgressEventInput): TransferProgressEvent;
3120
+
3121
+ /**
3122
+ * Validates that an FTP command argument cannot inject additional command lines.
3123
+ *
3124
+ * @param value - Argument value to validate.
3125
+ * @param label - Human-readable argument label used in error messages.
3126
+ * @returns The original value when it is safe.
3127
+ * @throws {@link ConfigurationError} When the value contains CR or LF characters.
3128
+ */
3129
+ declare function assertSafeFtpArgument(value: string, label?: string): string;
3130
+ /**
3131
+ * Normalizes a remote path using POSIX-style separators without escaping absolute roots.
3132
+ *
3133
+ * @param input - Remote path that may contain duplicate separators or dot segments.
3134
+ * @returns A normalized remote path, `/` for absolute root, or `.` for an empty relative path.
3135
+ * @throws {@link ConfigurationError} When the input contains unsafe CR or LF characters.
3136
+ */
3137
+ declare function normalizeRemotePath(input: string): string;
3138
+ /**
3139
+ * Joins remote path segments and normalizes the result.
3140
+ *
3141
+ * @param segments - Remote path segments to concatenate.
3142
+ * @returns A normalized remote path.
3143
+ * @throws {@link ConfigurationError} When any joined segment contains unsafe characters.
3144
+ */
3145
+ declare function joinRemotePath(...segments: string[]): string;
3146
+ /**
3147
+ * Extracts the final name segment from a normalized remote path.
3148
+ *
3149
+ * @param input - Remote path to inspect.
3150
+ * @returns The final path segment, or `/` when the input is the absolute root.
3151
+ * @throws {@link ConfigurationError} When the input contains unsafe characters.
3152
+ */
3153
+ declare function basenameRemotePath(input: string): string;
3154
+
3155
+ /** Fetch implementation accepted by web-family providers. */
3156
+ type HttpFetch = (input: string, init?: RequestInit) => Promise<Response>;
3157
+
3158
+ /** Options accepted by {@link createGoogleDriveProviderFactory}. */
3159
+ interface GoogleDriveProviderOptions {
3160
+ /** Provider id to register. Defaults to `"google-drive"`. */
3161
+ id?: ProviderId;
3162
+ /** Override the API base URL. Defaults to `https://www.googleapis.com/drive/v3`. */
3163
+ apiBaseUrl?: string;
3164
+ /** Override the upload base URL. Defaults to `https://www.googleapis.com/upload/drive/v3`. */
3165
+ uploadBaseUrl?: string;
3166
+ /**
3167
+ * Folder id used as the root for path resolution. Defaults to `"root"` (the
3168
+ * authenticated user's My Drive root). Pass a folder id when the SDK should
3169
+ * scope to a shared drive subtree.
3170
+ */
3171
+ rootFolderId?: string;
3172
+ /** Custom fetch implementation. Defaults to global `fetch`. */
3173
+ fetch?: HttpFetch;
3174
+ /** Default headers applied to every request before bearer auth. */
3175
+ defaultHeaders?: Record<string, string>;
3176
+ }
3177
+ /**
3178
+ * Creates a Google Drive provider factory.
3179
+ *
3180
+ * The bearer token is resolved per-connection from `profile.password`
3181
+ * (typically an OAuth 2 access token). `profile.host` is unused.
3182
+ */
3183
+ declare function createGoogleDriveProviderFactory(options?: GoogleDriveProviderOptions): ProviderFactory;
3184
+
3185
+ export { AbortError, type AtomicDeployActivateOperation, type AtomicDeployActivateStep, type AtomicDeployPlan, type AtomicDeployPruneStep, type AtomicDeployStrategy, type AuthenticationCapability, AuthenticationError, AuthorizationError, type BandwidthSleep, type BandwidthThrottle, type BandwidthThrottleOptions, type Base64EnvSecretSource, type BuiltInProviderId, CLASSIC_PROVIDER_IDS, type CapabilitySet, type ChecksumCapability, type ClassicProviderId, type ClientDiagnostics, type CompareRemoteManifestsOptions, ConfigurationError, type ConnectionDiagnosticTimings, type ConnectionDiagnosticsResult, ConnectionError, type ConnectionProfile, type CopyBetweenOptions, type CreateAtomicDeployPlanOptions, type CreateRemoteBrowserOptions, type CreateRemoteManifestOptions, type CreateSyncPlanOptions, type DiffRemoteTreesOptions, type DownloadFileOptions, type EnvSecretSource, type FileSecretSource, type FileZillaSite, type FriendlyTransferOptions, type FtpReplyErrorInput, type GoogleDriveProviderOptions, type ImportFileZillaSitesResult, type ImportOpenSshConfigOptions, type ImportOpenSshConfigResult, type ImportWinScpSessionsResult, type KnownHostsEntry, type KnownHostsMarker, type ListOptions, type LocalProviderOptions, type LogLevel, type LogRecord, type LogRecordInput, type LoggerMethod, type MemoryProviderEntry, type MemoryProviderOptions, type MetadataCapability, type MkdirOptions, type OAuthAccessToken, type OAuthRefreshCallback, type OAuthTokenSecretSourceOptions, type OpenSshConfigEntry, ParseError, PathAlreadyExistsError, PathNotFoundError, PermissionDeniedError, type ProgressEventInput, ProtocolError, type AuthenticationCapability as ProviderAuthenticationCapability, type CapabilitySet as ProviderCapabilities, type ChecksumCapability as ProviderChecksumCapability, type ProviderFactory, type ProviderId, type MetadataCapability as ProviderMetadataCapability, ProviderRegistry, type ProviderSelection, type ProviderTransferEndpointRole, type ProviderTransferExecutorOptions, type ProviderTransferOperations, type ProviderTransferReadRequest, type ProviderTransferReadResult, type ProviderTransferRequest, type ProviderTransferSessionResolver, type ProviderTransferSessionResolverInput, type ProviderTransferWriteRequest, type ProviderTransferWriteResult, REDACTED, REMOTE_MANIFEST_FORMAT_VERSION, type RemoteBreadcrumb, type RemoteBrowser, type RemoteBrowserFilter, type RemoteBrowserSnapshot, type RemoteEntry, type RemoteEntrySortKey, type RemoteEntrySortOrder, type RemoteEntryType, type RemoteFileAdapter, type RemoteFileEndpoint, type RemoteFileSystem, type RemoteManifest, type RemoteManifestEntry, type RemotePermissions, type RemoteProtocol, type RemoteStat, type RemoteTreeDiff, type RemoteTreeDiffEntry, type RemoteTreeDiffReason, type RemoteTreeDiffStatus, type RemoteTreeDiffSummary, type RemoteTreeEntry, type RemoteTreeFilter, type RemoveOptions, type RenameOptions, type ResolveSecretOptions, type ResolvedConnectionProfile, type ResolvedOpenSshHost, type ResolvedSshProfile, type ResolvedTlsProfile, type RmdirOptions, type RunConnectionDiagnosticsOptions, type SecretProvider, type SecretSource, type SecretValue, type SpecializedErrorDetails, type SshAgentSource, type SshAlgorithms, type SshKeyboardInteractiveChallenge, type SshKeyboardInteractiveHandler, type SshKeyboardInteractivePrompt, type SshKnownHostsSource, type SshProfile, type SshSocketFactory, type SshSocketFactoryContext, type StatOptions, type SyncConflictPolicy, type SyncDeletePolicy, type SyncDirection, type SyncEndpointInput, TimeoutError, type TlsProfile, type TlsSecretSource, type TransferAttempt, type TransferAttemptError, type TransferBandwidthLimit, type TransferByteRange, TransferClient, type TransferClientOptions, type TransferDataChunk, type TransferDataSource, type TransferEndpoint, TransferEngine, type TransferEngineExecuteOptions, type TransferEngineOptions, TransferError, type TransferExecutionContext, type TransferExecutionResult, type TransferExecutor, type TransferJob, type TransferOperation, type TransferPlan, type TransferPlanAction, type TransferPlanInput, type TransferPlanStep, type TransferPlanSummary, type TransferProgressEvent, type TransferProvider, TransferQueue, type TransferQueueExecutorResolver, type TransferQueueItem, type TransferQueueItemStatus, type TransferQueueOptions, type TransferQueueRunOptions, type TransferQueueSummary, type TransferReceipt, type TransferResult, type TransferResultInput, type TransferRetryDecisionInput, type TransferRetryPolicy, type TransferSession, type TransferTimeoutPolicy, type TransferVerificationResult, UnsupportedFeatureError, type UploadFileOptions, type ValueSecretSource, VerificationError, type WalkRemoteTreeOptions, type WinScpSession, ZeroTransfer, type ZeroTransferCapabilities, ZeroTransferError, type ZeroTransferErrorDetails, type ZeroTransferLogger, type ZeroTransferOptions, assertSafeFtpArgument, basenameRemotePath, buildRemoteBreadcrumbs, compareRemoteManifests, copyBetween, createAtomicDeployPlan, createBandwidthThrottle, createGoogleDriveProviderFactory, createLocalProviderFactory, createMemoryProviderFactory, createOAuthTokenSecretSource, createProgressEvent, createProviderTransferExecutor, createRemoteBrowser, createRemoteManifest, createSyncPlan, createTransferClient, createTransferJobsFromPlan, createTransferPlan, createTransferResult, diffRemoteTrees, downloadFile, emitLog, errorFromFtpReply, filterRemoteEntries, importFileZillaSites, importOpenSshConfig, importWinScpSessions, isClassicProviderId, isSensitiveKey, joinRemotePath, matchKnownHosts, matchKnownHostsEntry, noopLogger, normalizeRemotePath, parentRemotePath, parseKnownHosts, parseOpenSshConfig, parseRemoteManifest, redactCommand, redactConnectionProfile, redactObject, redactSecretSource, redactValue, resolveConnectionProfileSecrets, resolveOpenSshHost, resolveProviderId, resolveSecret, runConnectionDiagnostics, serializeRemoteManifest, sortRemoteEntries, summarizeClientDiagnostics, summarizeTransferPlan, throttleByteIterable, uploadFile, validateConnectionProfile, walkRemoteTree };