@giveitsmaller/sdk 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- export type ErrorCode = "missing_credentials" | "feature_requires_auth" | "undeclared_asset" | "unused_asset" | "per_input_options_not_supported" | "chain_cardinality_mismatch" | "multipart_part_invalid" | "multipart_part_count_exceeded" | "timeout" | "aborted" | "validation_failed" | "auth_failed" | "feature_tier_restricted" | "tier_restriction" | "multipart_session_ownership" | "multipart_session_auth_required" | "multipart_session_not_found" | "workflow_expired" | "balance_exhausted" | "feature_not_available" | "upload_size_exceeds_tier" | "upload_duration_exceeds_tier" | "probe_pending" | "requires_reencode" | "invalid_options" | "invalid_combination" | "missing_dependency" | "unsupported_value" | "type_mismatch" | "upload_failed" | "workflow_failed";
1
+ export type ErrorCode = "missing_credentials" | "feature_requires_auth" | "undeclared_asset" | "unused_asset" | "per_input_options_not_supported" | "chain_cardinality_mismatch" | "multipart_part_invalid" | "multipart_part_count_exceeded" | "timeout" | "aborted" | "validation_failed" | "cyclic_workflow_edges" | "workflow_edge_references_unknown_job" | "reserved_job_id_pattern" | "cyclic_job_output_source_graph" | "auth_failed" | "feature_tier_restricted" | "tier_restriction" | "multipart_session_ownership" | "multipart_session_auth_required" | "multipart_session_not_found" | "workflow_expired" | "balance_exhausted" | "feature_not_available" | "upload_size_exceeds_tier" | "upload_duration_exceeds_tier" | "probe_pending" | "requires_reencode" | "invalid_options" | "invalid_combination" | "missing_dependency" | "unsupported_value" | "type_mismatch" | "upload_failed" | "workflow_failed";
2
2
  export type ErrorCategory = 'api' | 'config' | 'network' | 'auth' | 'validation' | 'chain';
3
3
  export type ErrorStatus = 'wired' | 'planned';
4
4
  export interface ErrorEntry {
@@ -150,6 +150,52 @@ export const ERROR_CODES = Object.freeze({
150
150
  "details": "array",
151
151
  }),
152
152
  }),
153
+ "cyclic_workflow_edges": Object.freeze({
154
+ code: "cyclic_workflow_edges",
155
+ category: "validation",
156
+ source: "ErrorEnvelope.error",
157
+ status: "wired",
158
+ httpStatus: 422,
159
+ retryable: false,
160
+ sdkClass: "GislValidationError",
161
+ description: "422 — cycle/self-edge in the explicit `workflow_edges` DAG. Wire `CYCLIC_WORKFLOW_EDGES` (g8PPkbNu); ValidationErrorEnvelope shape, `details[0].field`=`workflow_edges`.",
162
+ metadataSchema: Object.freeze({
163
+ "details": "array",
164
+ }),
165
+ }),
166
+ "workflow_edge_references_unknown_job": Object.freeze({
167
+ code: "workflow_edge_references_unknown_job",
168
+ category: "validation",
169
+ source: "ErrorEnvelope.error",
170
+ status: "wired",
171
+ httpStatus: 400,
172
+ retryable: false,
173
+ sdkClass: "GislValidationError",
174
+ description: "400 — a `workflow_edges` entry, job-level `source`, or `inputs[].source` references a job not in the request. Wire `WORKFLOW_EDGE_REFERENCES_UNKNOWN_JOB` (g8PPkbNu).",
175
+ metadataSchema: Object.freeze({}),
176
+ }),
177
+ "reserved_job_id_pattern": Object.freeze({
178
+ code: "reserved_job_id_pattern",
179
+ category: "validation",
180
+ source: "ErrorEnvelope.error",
181
+ status: "wired",
182
+ httpStatus: 400,
183
+ retryable: false,
184
+ sdkClass: "GislValidationError",
185
+ description: "400 — user job `id` matches the reserved `^job_\\d+$` pattern as the SOLE failure. Wire `RESERVED_JOB_ID_PATTERN` (g8PPkbNu); mixed violations keep generic `BAD_REQUEST`.",
186
+ metadataSchema: Object.freeze({}),
187
+ }),
188
+ "cyclic_job_output_source_graph": Object.freeze({
189
+ code: "cyclic_job_output_source_graph",
190
+ category: "validation",
191
+ source: "ErrorEnvelope.error",
192
+ status: "wired",
193
+ httpStatus: 400,
194
+ retryable: false,
195
+ sdkClass: "GislValidationError",
196
+ description: "400 — an implicit cycle in the `job_output` source graph, caught during effective-input-MIME resolution on POST /api/workflows. Wire `CYCLIC_JOB_OUTPUT_SOURCE_GRAPH` (g8PPkbNu).",
197
+ metadataSchema: Object.freeze({}),
198
+ }),
153
199
  "auth_failed": Object.freeze({
154
200
  code: "auth_failed",
155
201
  category: "auth",
@@ -458,6 +504,10 @@ export const ERROR_CATEGORIES = Object.freeze({
458
504
  "multipart_part_invalid",
459
505
  "multipart_part_count_exceeded",
460
506
  "validation_failed",
507
+ "cyclic_workflow_edges",
508
+ "workflow_edge_references_unknown_job",
509
+ "reserved_job_id_pattern",
510
+ "cyclic_job_output_source_graph",
461
511
  "invalid_options",
462
512
  "invalid_combination",
463
513
  "missing_dependency",
@@ -1,3 +1,3 @@
1
- export declare const SDK_SPEC_VERSION: "1.1.0";
1
+ export declare const SDK_SPEC_VERSION: "1.2.0";
2
2
  export declare const PRESET_VERSION: "1.0";
3
3
  export declare const PRESET_CONFIG_HASH: "sha256:35aeb0b6b86edd9814ace5b75cfeef8a7b1432ecb8e4d5ee8b38d9187a0b45eb";
@@ -1,6 +1,6 @@
1
1
  // CODE GENERATED — DO NOT EDIT.
2
2
  // Source: compression_contracts/sdk-spec/ (see sdk-spec/README.md).
3
3
  // Regenerate with: scripts/generate.py.
4
- export const SDK_SPEC_VERSION = "1.1.0";
4
+ export const SDK_SPEC_VERSION = "1.2.0";
5
5
  export const PRESET_VERSION = "1.0";
6
6
  export const PRESET_CONFIG_HASH = "sha256:35aeb0b6b86edd9814ace5b75cfeef8a7b1432ecb8e4d5ee8b38d9187a0b45eb";
package/dist/gisl.d.ts CHANGED
@@ -23,6 +23,8 @@ import type { GislClientConfig } from './types.js';
23
23
  import { OperationBuilder } from './builder.js';
24
24
  import { MergeBuilder, type Asset, type MergeOptions } from './merge.js';
25
25
  import { PresetDefaults } from './ergonomic/presets/index.js';
26
+ import { Recipe, FilesRecipe, type FileInput } from './file-first.js';
27
+ import { Handle } from './handle.js';
26
28
  /**
27
29
  * Operations that may be invoked on a `gisl.anonymous()` client without
28
30
  * raising `GislFeatureRequiresAuthError`. Empty until the free-tier launch
@@ -67,6 +69,35 @@ export declare function create(opts?: GislCreateOptions): Promise<ErgonomicClien
67
69
  * ergonomic factory's narrower string-only typing).
68
70
  */
69
71
  export type ErgonomicClient = GislClient & {
72
+ /**
73
+ * File-first entry point (FF2a). Returns an immutable {@link Recipe} you
74
+ * call operations on (`.compress()` / `.convert()` / `.thumbnail()` /
75
+ * `.textWatermark()`), chaining sequentially. A bare string is a filesystem
76
+ * path; pass a {@link FileInput} (e.g. `fileInput.uploadId(...)`) to reuse a
77
+ * pre-uploaded file. `key` is RESULT-addressing only — never input wiring.
78
+ * Execution (`run()`) lands in FF2b.
79
+ */
80
+ file(input: string | Blob | FileInput, key?: string): Recipe;
81
+ /**
82
+ * Homogeneous fan-out entry point (FF3a). Apply ONE recipe (op chain) to
83
+ * MANY input files in ONE workflow. Each element is a filesystem path
84
+ * (string), an in-memory {@link FileInput} via `fileInput.*`, or a Blob/File.
85
+ * Returns an immutable {@link FilesRecipe} you call the same ops on
86
+ * (`.compress()` / `.convert()` / `.thumbnail()` / `.textWatermark()`); the
87
+ * chain applies to every input. `run()` returns a partitioned
88
+ * {@link RunResult} keyed by each input's 0-based index — one bad input does
89
+ * not sink the rest. `submit(webhook?)` is the fire-and-forget arm: it
90
+ * returns a {@link Handle} whose `wait()`/`result()` partition per input.
91
+ */
92
+ files(inputs: ReadonlyArray<string | Blob | FileInput>): FilesRecipe;
93
+ /**
94
+ * Reattach to a previously-created workflow (FF5a). Returns a client-bound
95
+ * {@link Handle} you can `.status()` / `.wait()` / `.result()`. The handle
96
+ * carries no `webhookSecret` and no recipe key, so the {@link RunResult}
97
+ * from `wait()`/`result()` is keyless (`succeeded[].key === null`) — address
98
+ * outputs positionally or via the sinks.
99
+ */
100
+ workflow(id: string): Handle;
70
101
  compress(input: string | Blob, options?: Record<string, unknown>): OperationBuilder;
71
102
  convert(input: string | Blob, options?: Record<string, unknown>): OperationBuilder;
72
103
  thumbnail(input: string | Blob, options?: Record<string, unknown>): OperationBuilder;
package/dist/gisl.js CHANGED
@@ -22,6 +22,8 @@ import { resolveApiKey, resolveEndpoint, } from './credentials.js';
22
22
  import { OperationBuilder } from './builder.js';
23
23
  import { MergeBuilder, asset } from './merge.js';
24
24
  import { PresetDefaults } from './ergonomic/presets/index.js';
25
+ import { Recipe, FilesRecipe, fileInput } from './file-first.js';
26
+ import { Handle } from './handle.js';
25
27
  // ---------------------------------------------------------------------------
26
28
  // Anonymous-capable operation allowlist (internal)
27
29
  // ---------------------------------------------------------------------------
@@ -71,6 +73,51 @@ export async function create(opts = {}) {
71
73
  function wrapErgonomic(client, presetDefaults, scopedPresetDefaults) {
72
74
  return new Proxy(client, {
73
75
  get(target, prop, receiver) {
76
+ if (prop === 'file') {
77
+ // File-first entry point — the subject of the file-first surface.
78
+ // A bare string is a filesystem path, a Blob/File an in-memory input;
79
+ // pass a `FileInput` (e.g. `fileInput.uploadId(...)`) to reuse a
80
+ // pre-uploaded file. `key` is RESULT-addressing only. The Proxy's
81
+ // closure forwards the same preset-defaults references the op builders
82
+ // get, so a file-first `compress()` resolves presets identically.
83
+ return (input, key) => {
84
+ const resolved = typeof input === 'string'
85
+ ? fileInput.path(input)
86
+ : input instanceof Blob
87
+ ? fileInput.blob(input)
88
+ : input;
89
+ return new Recipe(resolved, key, [], presetDefaults, scopedPresetDefaults, target);
90
+ };
91
+ }
92
+ if (prop === 'files') {
93
+ // Homogeneous fan-out entry point (FF3a) — apply ONE recipe (op chain)
94
+ // to MANY input files in ONE workflow. Each element is coerced the same
95
+ // way `file()` coerces its single input: a bare string is a filesystem
96
+ // path, a Blob/File an in-memory input, a `FileInput` passed through.
97
+ // The fan-out's RunResult partitions per input by 0-based index.
98
+ return (inputs) => {
99
+ if (inputs.length === 0) {
100
+ // A zero-input fan-out is a caller error — "one failing input
101
+ // doesn't sink the rest" is meaningless with no inputs, and it
102
+ // would otherwise create an empty-jobs workflow the API 422s.
103
+ throw new GislConfigError('files() requires at least one input file.', {
104
+ reason: 'no_inputs',
105
+ });
106
+ }
107
+ const resolved = inputs.map((input) => typeof input === 'string'
108
+ ? fileInput.path(input)
109
+ : input instanceof Blob
110
+ ? fileInput.blob(input)
111
+ : input);
112
+ return new FilesRecipe(resolved, [], presetDefaults, scopedPresetDefaults, target);
113
+ };
114
+ }
115
+ if (prop === 'workflow') {
116
+ // Reattach to a previously-created workflow (FF5a). Returns a
117
+ // client-bound Handle with no webhookSecret and no recipe key —
118
+ // its RunResult is therefore keyless (succeeded[].key === null).
119
+ return (id) => new Handle(id, undefined, target);
120
+ }
74
121
  if (prop === 'compress' || prop === 'convert' || prop === 'thumbnail') {
75
122
  return (input, options = {}) => {
76
123
  // T4b — pass client-scope presetDefaults into the builder so
@@ -0,0 +1,153 @@
1
+ /**
2
+ * File-first {@link Handle} + {@link StatusSnapshot} value objects (FF5a).
3
+ *
4
+ * A `Handle` is the lightweight return of a fire-and-forget submit
5
+ * (`OperationBuilder.submit()` / `MergeBuilder.submit()`) AND the value
6
+ * `client.workflow(id)` hands back to reattach to a previously-created
7
+ * workflow. When a `Handle` carries a bound client it exposes three
8
+ * accessors:
9
+ *
10
+ * - `status()` — one non-blocking status fetch, projected to a
11
+ * {@link StatusSnapshot}.
12
+ * - `wait(maxWait, onProgress?)` — the ONLY blocking path: await terminal
13
+ * (SSE with poll fallback), then fetch downloads + project to a
14
+ * {@link RunResult}.
15
+ * - `result()` — non-blocking: fetch status once; if terminal, fetch
16
+ * downloads + project to a {@link RunResult}; if NOT terminal, throw
17
+ * {@link GislResultNotReadyError}. Never waits/polls.
18
+ *
19
+ * A `Handle` built WITHOUT a client (the operation-first/merge `submit()`
20
+ * path) keeps its data fields + `toJSON()` byte-identical to the prior
21
+ * `{ workflowId, webhookSecret }` interface; its accessors throw
22
+ * {@link GislConfigError} (reason `no_client`).
23
+ *
24
+ * Module placement: this lives in its OWN module (not `builder.ts` or
25
+ * `file-first.ts`) to keep the ESM import graph acyclic at module-load time.
26
+ * It imports the await-primitives from `builder.ts` and the
27
+ * {@link RunResult} + {@link projectDownloadsToRunResult} projection from
28
+ * `file-first.ts`; `builder.ts`/`merge.ts` import `Handle` back for
29
+ * construction inside their `submit()` methods. That back-edge is
30
+ * DEFERRED-USAGE-ONLY (construction happens at call time, not module-load),
31
+ * which ESM resolves cleanly.
32
+ *
33
+ * Mirrors the PHP `Gisl\Sdk\Ergonomic\Handle` + `Gisl\Sdk\Ergonomic\StatusSnapshot`.
34
+ */
35
+ import type { GislClient } from './client.js';
36
+ import { type ProgressEvent } from './builder.js';
37
+ import { RunResult } from './file-first.js';
38
+ /**
39
+ * A non-blocking snapshot of a workflow's lifecycle state, returned by
40
+ * {@link Handle.status}. `state` is the RAW wire `WorkflowStatus` value,
41
+ * verbatim (`pending` | `in_progress` | `completed` | `failed` |
42
+ * `partially_failed` | `paused_insufficient_credits` | `cancelled` |
43
+ * `expired`). There is NO `phase` field — phase is an SSE-only concept; the
44
+ * status response carries no phase.
45
+ *
46
+ * Mirrors the PHP `Gisl\Sdk\Ergonomic\StatusSnapshot`.
47
+ */
48
+ export declare class StatusSnapshot {
49
+ readonly workflowId: string;
50
+ readonly state: string;
51
+ constructor(workflowId: string, state: string);
52
+ /**
53
+ * True when {@link state} is one of the terminal states (`completed`,
54
+ * `failed`, `partially_failed`, `cancelled`, `expired`,
55
+ * `paused_insufficient_credits`); false for `pending` / `in_progress`.
56
+ */
57
+ isTerminal(): boolean;
58
+ /** Plain-object projection. Mirrors the PHP `toArray()`. */
59
+ toJSON(): {
60
+ workflowId: string;
61
+ state: string;
62
+ };
63
+ }
64
+ /**
65
+ * Handle to a created workflow. Carries `workflowId` + an optional
66
+ * `webhookSecret` (the data the operation-first/merge `submit()` returns)
67
+ * and, when reattached or built by the file-first run path, an optional
68
+ * bound {@link GislClient}.
69
+ *
70
+ * The bound client is OPTIONAL (mirrors how {@link RunResult} binds its
71
+ * {@link Downloader}): the data fields + {@link toJSON} stay byte-identical
72
+ * whether or not a client is present, so the operation-first/merge `submit()`
73
+ * back-compat fixture (`{ workflowId, webhookSecret }` via `toJSON()`) holds.
74
+ * When the client is absent, {@link status}/{@link wait}/{@link result} throw
75
+ * {@link GislConfigError} (reason `no_client`).
76
+ *
77
+ * A handle built via `client.workflow(id)` has NO recipe key, so its
78
+ * {@link RunResult} is keyless (`succeeded[].key === null`) — address its
79
+ * outputs positionally / via the sinks rather than `byKey()`.
80
+ *
81
+ * Mirrors the PHP `Gisl\Sdk\Ergonomic\Handle`.
82
+ */
83
+ export declare class Handle {
84
+ #private;
85
+ readonly workflowId: string;
86
+ readonly webhookSecret?: string | undefined;
87
+ constructor(workflowId: string, webhookSecret?: string | undefined, client?: GislClient, key?: string | null);
88
+ /**
89
+ * Fetch the workflow's current status once (non-blocking) and project it to
90
+ * a {@link StatusSnapshot}.
91
+ * @throws {GislConfigError} reason `no_client` when no client is bound.
92
+ */
93
+ status(): Promise<StatusSnapshot>;
94
+ /**
95
+ * Block until the workflow reaches a terminal state (SSE with poll
96
+ * fallback), then fetch its downloads and project to a {@link RunResult}.
97
+ * This is the ONLY blocking accessor on a `Handle`.
98
+ *
99
+ * @param maxWait Wall-clock deadline for the wait + downloads (string suffix
100
+ * `'2h'`/`'30m'`/`'120s'` or a number of milliseconds). Defaults to 300s,
101
+ * matching `Recipe.run()` / the PHP `Handle::wait()` default.
102
+ * @throws {GislConfigError} reason `no_client` when no client is bound.
103
+ * @throws {GislTimeoutError} when `maxWait` elapses before terminal.
104
+ */
105
+ wait(maxWait?: string | number, onProgress?: (event: ProgressEvent) => void): Promise<RunResult>;
106
+ /**
107
+ * Non-blocking result accessor. Fetches the workflow status once: if the
108
+ * workflow is terminal, fetches its downloads and projects to a
109
+ * {@link RunResult}; if it is NOT terminal, throws
110
+ * {@link GislResultNotReadyError}. Never waits or polls — use {@link wait}
111
+ * to block.
112
+ *
113
+ * @throws {GislConfigError} reason `no_client` when no client is bound.
114
+ * @throws {GislResultNotReadyError} when the workflow is not yet terminal.
115
+ */
116
+ result(): Promise<RunResult>;
117
+ /**
118
+ * Project a terminal status + its per-job downloads into a {@link RunResult},
119
+ * choosing the producer DATA-DRIVEN off the wire (not a construction-time
120
+ * marker, so a fan-out reattached via `client.workflow(id)` — which carries
121
+ * no marker — still partitions per job):
122
+ *
123
+ * - A `files([...])` fan-out (every job ref is `file-{i}`, see
124
+ * {@link isFanoutStatus}) → {@link projectMultiJobToRunResult} with an
125
+ * empty `keyByRef`, so each input's key is recovered from its `file-{i}`
126
+ * ref (`"0"`, `"1"`, …). A submitted/reattached fan-out carries no
127
+ * caller-supplied keys — keyed fan-out is a separate concern.
128
+ * - Anything else (the single-file {@link Recipe} path) →
129
+ * {@link projectDownloadsToRunResult} keyed by this handle's `#key`
130
+ * (the recipe key from a file-first `submit()`, or `null` on reattach).
131
+ */
132
+ private project;
133
+ /**
134
+ * Plain-object projection. Field order (`workflowId`, then `webhookSecret`
135
+ * when present) and the omit-when-undefined behaviour match the PHP
136
+ * `toArray()` so JSON-string parity holds with the prior `Handle` shape.
137
+ * The bound client is NEVER serialised.
138
+ */
139
+ toJSON(): {
140
+ workflowId: string;
141
+ webhookSecret?: string;
142
+ };
143
+ /**
144
+ * Back-compat alias for {@link toJSON} — the prior operation-first/merge
145
+ * `submit()` fixture asserts a plain `{ workflowId, webhookSecret }` shape.
146
+ */
147
+ toArray(): {
148
+ workflowId: string;
149
+ webhookSecret?: string;
150
+ };
151
+ private makeDownloader;
152
+ private requireClient;
153
+ }
package/dist/handle.js ADDED
@@ -0,0 +1,253 @@
1
+ /**
2
+ * File-first {@link Handle} + {@link StatusSnapshot} value objects (FF5a).
3
+ *
4
+ * A `Handle` is the lightweight return of a fire-and-forget submit
5
+ * (`OperationBuilder.submit()` / `MergeBuilder.submit()`) AND the value
6
+ * `client.workflow(id)` hands back to reattach to a previously-created
7
+ * workflow. When a `Handle` carries a bound client it exposes three
8
+ * accessors:
9
+ *
10
+ * - `status()` — one non-blocking status fetch, projected to a
11
+ * {@link StatusSnapshot}.
12
+ * - `wait(maxWait, onProgress?)` — the ONLY blocking path: await terminal
13
+ * (SSE with poll fallback), then fetch downloads + project to a
14
+ * {@link RunResult}.
15
+ * - `result()` — non-blocking: fetch status once; if terminal, fetch
16
+ * downloads + project to a {@link RunResult}; if NOT terminal, throw
17
+ * {@link GislResultNotReadyError}. Never waits/polls.
18
+ *
19
+ * A `Handle` built WITHOUT a client (the operation-first/merge `submit()`
20
+ * path) keeps its data fields + `toJSON()` byte-identical to the prior
21
+ * `{ workflowId, webhookSecret }` interface; its accessors throw
22
+ * {@link GislConfigError} (reason `no_client`).
23
+ *
24
+ * Module placement: this lives in its OWN module (not `builder.ts` or
25
+ * `file-first.ts`) to keep the ESM import graph acyclic at module-load time.
26
+ * It imports the await-primitives from `builder.ts` and the
27
+ * {@link RunResult} + {@link projectDownloadsToRunResult} projection from
28
+ * `file-first.ts`; `builder.ts`/`merge.ts` import `Handle` back for
29
+ * construction inside their `submit()` methods. That back-edge is
30
+ * DEFERRED-USAGE-ONLY (construction happens at call time, not module-load),
31
+ * which ESM resolves cleanly.
32
+ *
33
+ * Mirrors the PHP `Gisl\Sdk\Ergonomic\Handle` + `Gisl\Sdk\Ergonomic\StatusSnapshot`.
34
+ */
35
+ import { GislApiError, GislConfigError, GislResultNotReadyError, GislTimeoutError, } from './errors.js';
36
+ import { _consumeSseToTerminal, _pollToTerminal, _parseMaxWait, } from './builder.js';
37
+ import { projectDownloadsToRunResult, projectMultiJobToRunResult, isFanoutStatus, } from './file-first.js';
38
+ import { HttpDownloader } from './http-downloader.js';
39
+ /**
40
+ * The terminal workflow states. A status response in any of these states
41
+ * will not change without caller action. Mirrors the `TERMINAL_STATUSES`
42
+ * sets in `client.ts` / `WorkflowConstants` (PHP) — `paused_insufficient_credits`
43
+ * is treated as terminal because the workflow only resumes on caller action.
44
+ */
45
+ const TERMINAL_STATES = new Set([
46
+ 'completed',
47
+ 'failed',
48
+ 'partially_failed',
49
+ 'cancelled',
50
+ 'expired',
51
+ 'paused_insufficient_credits',
52
+ ]);
53
+ /**
54
+ * A non-blocking snapshot of a workflow's lifecycle state, returned by
55
+ * {@link Handle.status}. `state` is the RAW wire `WorkflowStatus` value,
56
+ * verbatim (`pending` | `in_progress` | `completed` | `failed` |
57
+ * `partially_failed` | `paused_insufficient_credits` | `cancelled` |
58
+ * `expired`). There is NO `phase` field — phase is an SSE-only concept; the
59
+ * status response carries no phase.
60
+ *
61
+ * Mirrors the PHP `Gisl\Sdk\Ergonomic\StatusSnapshot`.
62
+ */
63
+ export class StatusSnapshot {
64
+ workflowId;
65
+ state;
66
+ constructor(workflowId, state) {
67
+ this.workflowId = workflowId;
68
+ this.state = state;
69
+ }
70
+ /**
71
+ * True when {@link state} is one of the terminal states (`completed`,
72
+ * `failed`, `partially_failed`, `cancelled`, `expired`,
73
+ * `paused_insufficient_credits`); false for `pending` / `in_progress`.
74
+ */
75
+ isTerminal() {
76
+ return TERMINAL_STATES.has(this.state);
77
+ }
78
+ /** Plain-object projection. Mirrors the PHP `toArray()`. */
79
+ toJSON() {
80
+ return { workflowId: this.workflowId, state: this.state };
81
+ }
82
+ }
83
+ /**
84
+ * Handle to a created workflow. Carries `workflowId` + an optional
85
+ * `webhookSecret` (the data the operation-first/merge `submit()` returns)
86
+ * and, when reattached or built by the file-first run path, an optional
87
+ * bound {@link GislClient}.
88
+ *
89
+ * The bound client is OPTIONAL (mirrors how {@link RunResult} binds its
90
+ * {@link Downloader}): the data fields + {@link toJSON} stay byte-identical
91
+ * whether or not a client is present, so the operation-first/merge `submit()`
92
+ * back-compat fixture (`{ workflowId, webhookSecret }` via `toJSON()`) holds.
93
+ * When the client is absent, {@link status}/{@link wait}/{@link result} throw
94
+ * {@link GislConfigError} (reason `no_client`).
95
+ *
96
+ * A handle built via `client.workflow(id)` has NO recipe key, so its
97
+ * {@link RunResult} is keyless (`succeeded[].key === null`) — address its
98
+ * outputs positionally / via the sinks rather than `byKey()`.
99
+ *
100
+ * Mirrors the PHP `Gisl\Sdk\Ergonomic\Handle`.
101
+ */
102
+ export class Handle {
103
+ workflowId;
104
+ webhookSecret;
105
+ // True ES private (`#`), NOT a TS `private` modifier: a `private` constructor
106
+ // parameter property is an enumerable own field, so spreading/logging/Object
107
+ // .assign-ing a bound handle would leak the GislClient (incl. auth headers).
108
+ // `#client` is non-enumerable and inaccessible outside the class (codex high).
109
+ #client;
110
+ // The recipe's result-addressing key, threaded from a file-first `submit()`
111
+ // (`Recipe.submit()`) so the `RunResult` from `wait()`/`result()` is keyed
112
+ // (`succeeded[].key === recipeKey`). A reattached handle
113
+ // (`client.workflow(id)`) passes no key → null → keyless RunResult. It is
114
+ // ES-private (`#`) — like `#client` — NOT just kept out of `toJSON()`: the
115
+ // parity ReturnSerialiser enumerates a Handle's OWN ENUMERABLE properties
116
+ // (it does not call `toJSON()`), so a plain `readonly key` leaked into the
117
+ // operation-first/merge `submit()` back-compat shape ({workflowId,
118
+ // webhookSecret}). `#key` is non-enumerable, so that shape stays byte-identical.
119
+ #key;
120
+ constructor(workflowId, webhookSecret, client, key = null) {
121
+ this.workflowId = workflowId;
122
+ this.webhookSecret = webhookSecret;
123
+ this.#client = client;
124
+ this.#key = key;
125
+ }
126
+ /**
127
+ * Fetch the workflow's current status once (non-blocking) and project it to
128
+ * a {@link StatusSnapshot}.
129
+ * @throws {GislConfigError} reason `no_client` when no client is bound.
130
+ */
131
+ async status() {
132
+ const client = this.requireClient();
133
+ const status = await client.getWorkflowStatus(this.workflowId);
134
+ return new StatusSnapshot(this.workflowId, status.status);
135
+ }
136
+ /**
137
+ * Block until the workflow reaches a terminal state (SSE with poll
138
+ * fallback), then fetch its downloads and project to a {@link RunResult}.
139
+ * This is the ONLY blocking accessor on a `Handle`.
140
+ *
141
+ * @param maxWait Wall-clock deadline for the wait + downloads (string suffix
142
+ * `'2h'`/`'30m'`/`'120s'` or a number of milliseconds). Defaults to 300s,
143
+ * matching `Recipe.run()` / the PHP `Handle::wait()` default.
144
+ * @throws {GislConfigError} reason `no_client` when no client is bound.
145
+ * @throws {GislTimeoutError} when `maxWait` elapses before terminal.
146
+ */
147
+ async wait(maxWait = 300_000, onProgress) {
148
+ const client = this.requireClient();
149
+ const deadline = Date.now() + _parseMaxWait(maxWait);
150
+ let finalStatus;
151
+ try {
152
+ finalStatus = await _consumeSseToTerminal(client, {
153
+ workflowId: this.workflowId,
154
+ deadline,
155
+ signal: undefined,
156
+ onProgress,
157
+ });
158
+ }
159
+ catch (err) {
160
+ // Mirror Recipe.run(): only genuine SSE transport / clean-stream-end
161
+ // failures fall through to poll. Caller-deadline, abort, and API errors
162
+ // MUST propagate — re-issuing the same doomed request via poll would mask
163
+ // them.
164
+ if (err instanceof GislTimeoutError)
165
+ throw err;
166
+ if (err instanceof DOMException && err.name === 'AbortError')
167
+ throw err;
168
+ if (err instanceof GislApiError)
169
+ throw err;
170
+ finalStatus = await _pollToTerminal(client, {
171
+ workflowId: this.workflowId,
172
+ deadline,
173
+ signal: undefined,
174
+ });
175
+ }
176
+ if (Date.now() >= deadline) {
177
+ throw new GislTimeoutError(`Workflow ${this.workflowId} reached terminal status but maxWait elapsed before downloads could be fetched`);
178
+ }
179
+ const downloads = await client.getWorkflowDownloads(this.workflowId);
180
+ return this.project(finalStatus, downloads.downloads);
181
+ }
182
+ /**
183
+ * Non-blocking result accessor. Fetches the workflow status once: if the
184
+ * workflow is terminal, fetches its downloads and projects to a
185
+ * {@link RunResult}; if it is NOT terminal, throws
186
+ * {@link GislResultNotReadyError}. Never waits or polls — use {@link wait}
187
+ * to block.
188
+ *
189
+ * @throws {GislConfigError} reason `no_client` when no client is bound.
190
+ * @throws {GislResultNotReadyError} when the workflow is not yet terminal.
191
+ */
192
+ async result() {
193
+ const client = this.requireClient();
194
+ const status = await client.getWorkflowStatus(this.workflowId);
195
+ if (!TERMINAL_STATES.has(status.status)) {
196
+ throw new GislResultNotReadyError(this.workflowId, status.status);
197
+ }
198
+ const downloads = await client.getWorkflowDownloads(this.workflowId);
199
+ return this.project(status, downloads.downloads);
200
+ }
201
+ /**
202
+ * Project a terminal status + its per-job downloads into a {@link RunResult},
203
+ * choosing the producer DATA-DRIVEN off the wire (not a construction-time
204
+ * marker, so a fan-out reattached via `client.workflow(id)` — which carries
205
+ * no marker — still partitions per job):
206
+ *
207
+ * - A `files([...])` fan-out (every job ref is `file-{i}`, see
208
+ * {@link isFanoutStatus}) → {@link projectMultiJobToRunResult} with an
209
+ * empty `keyByRef`, so each input's key is recovered from its `file-{i}`
210
+ * ref (`"0"`, `"1"`, …). A submitted/reattached fan-out carries no
211
+ * caller-supplied keys — keyed fan-out is a separate concern.
212
+ * - Anything else (the single-file {@link Recipe} path) →
213
+ * {@link projectDownloadsToRunResult} keyed by this handle's `#key`
214
+ * (the recipe key from a file-first `submit()`, or `null` on reattach).
215
+ */
216
+ project(finalStatus, jobDownloads) {
217
+ const downloader = this.makeDownloader();
218
+ if (isFanoutStatus(finalStatus)) {
219
+ return projectMultiJobToRunResult(this.workflowId, finalStatus, jobDownloads, new Map(), downloader);
220
+ }
221
+ return projectDownloadsToRunResult(this.workflowId, finalStatus, jobDownloads, this.#key, downloader);
222
+ }
223
+ /**
224
+ * Plain-object projection. Field order (`workflowId`, then `webhookSecret`
225
+ * when present) and the omit-when-undefined behaviour match the PHP
226
+ * `toArray()` so JSON-string parity holds with the prior `Handle` shape.
227
+ * The bound client is NEVER serialised.
228
+ */
229
+ toJSON() {
230
+ return this.webhookSecret === undefined
231
+ ? { workflowId: this.workflowId }
232
+ : { workflowId: this.workflowId, webhookSecret: this.webhookSecret };
233
+ }
234
+ /**
235
+ * Back-compat alias for {@link toJSON} — the prior operation-first/merge
236
+ * `submit()` fixture asserts a plain `{ workflowId, webhookSecret }` shape.
237
+ */
238
+ toArray() {
239
+ return this.toJSON();
240
+ }
241
+ makeDownloader() {
242
+ // Download URLs from getWorkflowDownloads are pre-signed and require no SDK
243
+ // auth, so the downloader issues a plain unauthenticated fetch.
244
+ return new HttpDownloader();
245
+ }
246
+ requireClient() {
247
+ if (this.#client === undefined) {
248
+ throw new GislConfigError('This handle has no client bound, so it cannot query the workflow. ' +
249
+ 'Use recipe.run() to execute and get a RunResult directly, or reattach via client.workflow(id).', { reason: 'no_client' });
250
+ }
251
+ return this.#client;
252
+ }
253
+ }
@@ -0,0 +1,9 @@
1
+ import type { Downloader } from './file-first.js';
2
+ /**
3
+ * Streams a (typically pre-signed) URL to a local path without buffering the
4
+ * whole body in memory. Pre-signed download URLs require no SDK auth, so this
5
+ * issues a plain unauthenticated `fetch`.
6
+ */
7
+ export declare class HttpDownloader implements Downloader {
8
+ downloadTo(url: string, destPath: string): Promise<void>;
9
+ }
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Node-only streaming {@link Downloader} implementation.
3
+ *
4
+ * Lives in its own module so the framework-free `file-first.ts` stays
5
+ * Node-import-free; the Node `fs`/`stream` imports are isolated here.
6
+ */
7
+ import { createWriteStream } from 'node:fs';
8
+ import { Readable } from 'node:stream';
9
+ import { pipeline } from 'node:stream/promises';
10
+ import { GislNetworkError, GislSinkError } from './errors.js';
11
+ /**
12
+ * Streams a (typically pre-signed) URL to a local path without buffering the
13
+ * whole body in memory. Pre-signed download URLs require no SDK auth, so this
14
+ * issues a plain unauthenticated `fetch`.
15
+ */
16
+ export class HttpDownloader {
17
+ async downloadTo(url, destPath) {
18
+ // Source-read failures surface as GislNetworkError to match the PHP
19
+ // StreamingDownloader (both raise GislNetworkError when the output URL
20
+ // cannot be fetched); a dest-write failure is GislSinkError(write_failed)
21
+ // on the RunResult sink side. Parity-critical: the FF1 sink contract tells
22
+ // callers to narrow with instanceof, so the source-read error type must
23
+ // match across languages.
24
+ let res;
25
+ try {
26
+ res = await fetch(url);
27
+ }
28
+ catch (cause) {
29
+ // A rejected fetch (DNS, TCP, TLS, mid-flight disconnect) must surface as
30
+ // GislNetworkError too — not the raw TypeError — so callers can narrow
31
+ // every download-source failure with `instanceof GislNetworkError`
32
+ // (codex review medium).
33
+ throw new GislNetworkError(`Failed to fetch download source: ${cause instanceof Error ? cause.message : String(cause)}`);
34
+ }
35
+ if (!res.ok) {
36
+ throw new GislNetworkError(`Download failed with status ${res.status}`);
37
+ }
38
+ if (res.body === null) {
39
+ throw new GislNetworkError('Download response had no body');
40
+ }
41
+ // `fetch`'s WHATWG ReadableStream and Node's `stream/web` ReadableStream
42
+ // are structurally the same at runtime but typed in two different lib
43
+ // declarations; the cast bridges them for `Readable.fromWeb`.
44
+ try {
45
+ await pipeline(Readable.fromWeb(res.body), createWriteStream(destPath));
46
+ }
47
+ catch {
48
+ // Destination-write failures (unwritable dir, disk full, …) surface as
49
+ // GislSinkError(write_failed) to match the PHP StreamingDownloader — a
50
+ // raw Node ENOENT would otherwise leak through the parity-critical sink
51
+ // contract. Source-read failures are handled above as GislNetworkError.
52
+ throw new GislSinkError(`Failed to stream download to destination: ${destPath}`, { reason: 'write_failed' });
53
+ }
54
+ }
55
+ }