@hol-org/cigar 0.9.4

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.
Files changed (78) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +5 -0
  3. package/README.md +68 -0
  4. package/dist/client.d.ts +16 -0
  5. package/dist/client.d.ts.map +1 -0
  6. package/dist/client.js +839 -0
  7. package/dist/client.js.map +1 -0
  8. package/dist/digest.d.ts +21 -0
  9. package/dist/digest.d.ts.map +1 -0
  10. package/dist/digest.js +406 -0
  11. package/dist/digest.js.map +1 -0
  12. package/dist/errors.d.ts +35 -0
  13. package/dist/errors.d.ts.map +1 -0
  14. package/dist/errors.js +54 -0
  15. package/dist/errors.js.map +1 -0
  16. package/dist/examples/quickstart.d.ts +2 -0
  17. package/dist/examples/quickstart.d.ts.map +1 -0
  18. package/dist/examples/quickstart.js +32 -0
  19. package/dist/examples/quickstart.js.map +1 -0
  20. package/dist/examples/two-agent-observer.d.ts +9 -0
  21. package/dist/examples/two-agent-observer.d.ts.map +1 -0
  22. package/dist/examples/two-agent-observer.js +59 -0
  23. package/dist/examples/two-agent-observer.js.map +1 -0
  24. package/dist/examples/verify-shared-bundle.d.ts +2 -0
  25. package/dist/examples/verify-shared-bundle.d.ts.map +1 -0
  26. package/dist/examples/verify-shared-bundle.js +13 -0
  27. package/dist/examples/verify-shared-bundle.js.map +1 -0
  28. package/dist/generated/cigar_service_pb.d.ts +642 -0
  29. package/dist/generated/cigar_service_pb.d.ts.map +1 -0
  30. package/dist/generated/cigar_service_pb.js +55 -0
  31. package/dist/generated/cigar_service_pb.js.map +1 -0
  32. package/dist/generated/context_abi_pb.d.ts +3429 -0
  33. package/dist/generated/context_abi_pb.d.ts.map +1 -0
  34. package/dist/generated/context_abi_pb.js +1386 -0
  35. package/dist/generated/context_abi_pb.js.map +1 -0
  36. package/dist/generated/errors.d.ts +242 -0
  37. package/dist/generated/errors.d.ts.map +1 -0
  38. package/dist/generated/errors.js +38 -0
  39. package/dist/generated/errors.js.map +1 -0
  40. package/dist/generated/generated/error_codes_pb.d.ts +188 -0
  41. package/dist/generated/generated/error_codes_pb.d.ts.map +1 -0
  42. package/dist/generated/generated/error_codes_pb.js +191 -0
  43. package/dist/generated/generated/error_codes_pb.js.map +1 -0
  44. package/dist/generated/models.d.ts +472 -0
  45. package/dist/generated/models.d.ts.map +1 -0
  46. package/dist/generated/models.js +314 -0
  47. package/dist/generated/models.js.map +1 -0
  48. package/dist/generated/operations.d.ts +912 -0
  49. package/dist/generated/operations.d.ts.map +1 -0
  50. package/dist/generated/operations.js +50 -0
  51. package/dist/generated/operations.js.map +1 -0
  52. package/dist/idempotency.d.ts +3 -0
  53. package/dist/idempotency.d.ts.map +1 -0
  54. package/dist/idempotency.js +16 -0
  55. package/dist/idempotency.js.map +1 -0
  56. package/dist/index.d.ts +13 -0
  57. package/dist/index.d.ts.map +1 -0
  58. package/dist/index.js +13 -0
  59. package/dist/index.js.map +1 -0
  60. package/dist/release.json +6 -0
  61. package/dist/types.d.ts +115 -0
  62. package/dist/types.d.ts.map +1 -0
  63. package/dist/types.js +3 -0
  64. package/dist/types.js.map +1 -0
  65. package/dist/verify-replay.d.ts +3 -0
  66. package/dist/verify-replay.d.ts.map +1 -0
  67. package/dist/verify-replay.js +391 -0
  68. package/dist/verify-replay.js.map +1 -0
  69. package/dist/verify-vectors.d.ts +3 -0
  70. package/dist/verify-vectors.d.ts.map +1 -0
  71. package/dist/verify-vectors.js +383 -0
  72. package/dist/verify-vectors.js.map +1 -0
  73. package/dist/workflow-session.d.ts +93 -0
  74. package/dist/workflow-session.d.ts.map +1 -0
  75. package/dist/workflow-session.js +550 -0
  76. package/dist/workflow-session.js.map +1 -0
  77. package/fixtures/semantic-bundle-v1.json +13 -0
  78. package/package.json +60 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ https://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ https://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,5 @@
1
+ CIGAR
2
+ Copyright 2026 CIGAR contributors
3
+
4
+ This product includes software developed by the CIGAR contributors.
5
+
package/README.md ADDED
@@ -0,0 +1,68 @@
1
+ # `@hol-org/cigar`
2
+
3
+ Developer preview for Node.js 24 ESM applications:
4
+
5
+ ```text
6
+ npm install @hol-org/cigar@alpha
7
+ ```
8
+
9
+ The 0.9.4 developer preview is intended for the `alpha` channel. The package intentionally does
10
+ not claim CommonJS or browser-runtime support, and consumers should pin an exact version for
11
+ reproducible workflow execution.
12
+
13
+ The CIGAR v1 ESM client supports all 45 frozen HTTP operations, resumable SSE streams,
14
+ bounded deadlines, abort signals, typed problems, pagination, idempotency-bound retries,
15
+ and local bundle/delta verification. It has no install script and downloads no binaries.
16
+ The exported `CONTEXT_ABI` constant is the exact string `cigar.context.v1`.
17
+
18
+ ```ts
19
+ import { CigarClient, createIdempotencyKey } from "@hol-org/cigar";
20
+
21
+ const client = new CigarClient({
22
+ baseUrl: "https://cigar.example",
23
+ bearerToken: process.env.CIGAR_TOKEN,
24
+ });
25
+
26
+ const result = await client.compileContextBundle({
27
+ payload: { plan_id: planId },
28
+ idempotencyKey: createIdempotencyKey("compile"),
29
+ }, { timeoutMs: 15_000 });
30
+ ```
31
+
32
+ Every mutating method preserves the caller's idempotency key across retry attempts.
33
+ `dispatchEffect` is never retried automatically, even when a larger attempt count is configured.
34
+ Use `for await` or `await using` with `subscribeSpaceEvents`; reconnections send the last
35
+ verified event ID.
36
+
37
+ Bearer providers receive the call's abort signal. Supplying a custom `fetch` requires
38
+ `trustCustomFetch: true`; the SDK still requests `redirect: "error"`. Published source
39
+ maps contain their exact source text, including declaration maps, and the package has no
40
+ postinstall hook.
41
+
42
+ Remote HTTPS construction requires an explicit `bearerToken` value or provider. The SDK never
43
+ discovers credentials from the URL, environment, project configuration, proxy settings, or a
44
+ redirect target. Explicit cleartext loopback mode remains available only for local development.
45
+ Node proxy environment variables are rejected when using the default fetch implementation. A
46
+ caller that intentionally supplies a proxy-aware fetch must inject it and set `trustCustomFetch`;
47
+ that explicit transport becomes the caller's channel-identity and redirect-policy boundary.
48
+
49
+ Run `pnpm qualify:bundle` to verify the packaged cross-SDK fixture and print its semantic
50
+ bundle ID.
51
+
52
+ ## Honey two-agent observer
53
+
54
+ The packaged `dist/examples/two-agent-observer.js` example uses a distinct observer credential and
55
+ only the disclosure-safe `previewHandoff` and `getSpaceLog` reads. It reports counts and authority
56
+ attenuation without printing task text, source material, result claims, credentials, or event
57
+ payload digests:
58
+
59
+ ```text
60
+ CIGAR_URL=http://127.0.0.1:8080 \
61
+ CIGAR_OBSERVER_TOKEN=... \
62
+ CIGAR_HANDOFF_ID=... \
63
+ CIGAR_SPACE_ID=... \
64
+ node dist/examples/two-agent-observer.js
65
+ ```
66
+
67
+ The observer principal must be provisioned independently. This example never accepts, records,
68
+ merges, or revokes a handoff and therefore does not receive Agent A or Agent B mutation authority.
@@ -0,0 +1,16 @@
1
+ import { type GeneratedOperations, type OperationId } from "./generated/operations.js";
2
+ import type { CallOptions, ClientOptions, Compatibility, EventStream, OperationRequest, OperationResponse, TypedEventStream, TypedOperationRequest, TypedOperationResponse } from "./types.js";
3
+ import type { PayloadModel } from "./generated/models.js";
4
+ export declare class CigarClient {
5
+ #private;
6
+ constructor(options: ClientOptions);
7
+ negotiate(options?: CallOptions): Promise<Compatibility>;
8
+ invokeTypedOperation<RequestPayload, ResponsePayload>(operationId: OperationId, request: TypedOperationRequest<RequestPayload>, responseModel: PayloadModel<ResponsePayload>, options?: CallOptions): Promise<TypedOperationResponse<ResponsePayload>>;
9
+ streamTypedOperation<RequestPayload, EventPayload>(operationId: OperationId, request: TypedOperationRequest<RequestPayload>, eventModel: PayloadModel<EventPayload>, options?: CallOptions): TypedEventStream<EventPayload>;
10
+ paginate(operationId: OperationId, request: OperationRequest, options?: CallOptions): AsyncGenerator<OperationResponse>;
11
+ invokeOperation(operationId: OperationId, request: OperationRequest, options?: CallOptions): Promise<OperationResponse>;
12
+ streamOperation(operationId: OperationId, request: OperationRequest, options?: CallOptions): EventStream;
13
+ }
14
+ export interface CigarClient extends GeneratedOperations {
15
+ }
16
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAWA,OAAO,EAAc,KAAK,mBAAmB,EAAE,KAAK,WAAW,EAAE,MAAM,2BAA2B,CAAC;AAKnG,OAAO,KAAK,EACV,WAAW,EACX,aAAa,EACb,aAAa,EACb,WAAW,EAEX,gBAAgB,EAChB,iBAAiB,EAEjB,gBAAgB,EAEhB,qBAAqB,EACrB,sBAAsB,EACvB,MAAM,YAAY,CAAC;AACpB,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAiW1D,qBAAa,WAAW;;IAQtB,YAAY,OAAO,EAAE,aAAa,EA8CjC;IAEK,SAAS,CAAC,OAAO,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,aAAa,CAAC,CAK7D;IAEK,oBAAoB,CAAC,cAAc,EAAE,eAAe,EACxD,WAAW,EAAE,WAAW,EACxB,OAAO,EAAE,qBAAqB,CAAC,cAAc,CAAC,EAC9C,aAAa,EAAE,YAAY,CAAC,eAAe,CAAC,EAC5C,OAAO,CAAC,EAAE,WAAW,GACpB,OAAO,CAAC,sBAAsB,CAAC,eAAe,CAAC,CAAC,CAUlD;IAED,oBAAoB,CAAC,cAAc,EAAE,YAAY,EAC/C,WAAW,EAAE,WAAW,EACxB,OAAO,EAAE,qBAAqB,CAAC,cAAc,CAAC,EAC9C,UAAU,EAAE,YAAY,CAAC,YAAY,CAAC,EACtC,OAAO,CAAC,EAAE,WAAW,GACpB,gBAAgB,CAAC,YAAY,CAAC,CAKhC;IA4BM,QAAQ,CACb,WAAW,EAAE,WAAW,EACxB,OAAO,EAAE,gBAAgB,EACzB,OAAO,CAAC,EAAE,WAAW,GACpB,cAAc,CAAC,iBAAiB,CAAC,CAenC;IAEK,eAAe,CACnB,WAAW,EAAE,WAAW,EACxB,OAAO,EAAE,gBAAgB,EACzB,OAAO,CAAC,EAAE,WAAW,GACpB,OAAO,CAAC,iBAAiB,CAAC,CAqB5B;IAED,eAAe,CAAC,WAAW,EAAE,WAAW,EAAE,OAAO,EAAE,gBAAgB,EAAE,OAAO,CAAC,EAAE,WAAW,GAAG,WAAW,CAMvG;CA0SF;AAED,MAAM,WAAW,WAAY,SAAQ,mBAAmB;CAAG","sourcesContent":["import { setTimeout as delay } from \"node:timers/promises\";\n\nimport {\n CigarApiError,\n CigarTimeoutError,\n CompatibilityError,\n TransportError,\n ValidationError,\n isRetryable,\n type ProblemDetails,\n} from \"./errors.js\";\nimport { OPERATIONS, type GeneratedOperations, type OperationId } from \"./generated/operations.js\";\nimport { ERROR_CATALOG, type ErrorCode } from \"./generated/errors.js\";\nimport * as models from \"./generated/models.js\";\nimport { validateIdempotencyKey } from \"./idempotency.js\";\nimport { decodeOperationPayload, encodeOperationPayload } from \"./digest.js\";\nimport type {\n CallOptions,\n ClientOptions,\n Compatibility,\n EventStream,\n OperationEvent,\n OperationRequest,\n OperationResponse,\n PathParameter,\n TypedEventStream,\n TypedOperationEvent,\n TypedOperationRequest,\n TypedOperationResponse,\n} from \"./types.js\";\nimport type { PayloadModel } from \"./generated/models.js\";\n\nconst MAX_PAYLOAD_BYTES = 16 * 1024 * 1024;\nconst MAX_EVENT_BYTES = 1024 * 1024;\nconst MAX_PROBLEM_BYTES = 64 * 1024;\nconst MAX_TIMEOUT_MS = 300_000;\nconst MAX_CURSOR_BYTES = 4096;\nconst PATH_NAME = /^[a-z][a-z0-9_]{0,63}$/u;\nconst PATH_VALUE = /^[A-Za-z0-9._~-]{1,256}$/u;\n\nfunction exactBase64url(bytes: Uint8Array): string {\n return Buffer.from(bytes).toString(\"base64url\");\n}\n\nfunction decodeBase64url(value: unknown, maximum: number): Uint8Array {\n if (typeof value !== \"string\" || !/^[A-Za-z0-9_-]*$/u.test(value)) {\n throw new TransportError(\"server returned invalid base64url payload\");\n }\n const decoded = Buffer.from(value, \"base64url\");\n if (decoded.length > maximum || decoded.toString(\"base64url\") !== value) {\n throw new TransportError(\"server returned non-canonical or oversized payload\");\n }\n return Uint8Array.from(decoded);\n}\n\nfunction boundedText(value: unknown, maximum: number, field: string, required = false): string | undefined {\n if (value === undefined && !required) return undefined;\n if (typeof value !== \"string\" || (required && value.length === 0) || Buffer.byteLength(value) > maximum) {\n throw new TransportError(`server returned invalid ${field}`);\n }\n return value;\n}\n\nfunction parseResponse(operationId: OperationId, value: unknown, maximum = MAX_PAYLOAD_BYTES): OperationResponse {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new TransportError(\"server returned a non-object response\");\n }\n const record = value as Record<string, unknown>;\n const keys = Object.keys(record).sort().join(\",\");\n const allowed = [\"next_page_cursor\", \"operation_id\", \"payload_cbor\", \"semantic_etag\"];\n if (Object.keys(record).some((key) => !allowed.includes(key))) {\n throw new TransportError(`server returned unknown response fields: ${keys}`);\n }\n if (record.operation_id !== operationId) throw new TransportError(\"server operation identity mismatch\");\n const semanticEtag = boundedText(record.semantic_etag, 256, \"semantic_etag\");\n const nextPageCursor = boundedText(record.next_page_cursor, MAX_CURSOR_BYTES, \"next_page_cursor\");\n return {\n operationId,\n payloadCbor: decodeBase64url(record.payload_cbor, maximum),\n ...(semanticEtag === undefined ? {} : { semanticEtag }),\n ...(nextPageCursor === undefined ? {} : { nextPageCursor }),\n };\n}\n\nasync function boundedBytes(response: Response, maximum: number, field: string): Promise<Uint8Array> {\n const declared = response.headers.get(\"content-length\");\n if (declared !== null && (!/^(?:0|[1-9][0-9]*)$/u.test(declared) || Number(declared) > maximum)) {\n throw new TransportError(`${field} content length exceeds its bound`);\n }\n if (response.body === null) return new Uint8Array();\n const reader = response.body.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n total += value.length;\n if (total > maximum) {\n await reader.cancel();\n throw new TransportError(`${field} exceeds its bound`);\n }\n chunks.push(value);\n }\n const result = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n result.set(chunk, offset);\n offset += chunk.length;\n }\n return result;\n}\n\nfunction parseJson(bytes: Uint8Array, field: string): unknown {\n try {\n const source = new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes);\n assertUniqueJsonKeys(source);\n return JSON.parse(source);\n } catch (cause) {\n throw new TransportError(`${field} is not valid UTF-8 JSON`, { cause });\n }\n}\n\nfunction assertUniqueJsonKeys(source: string): void {\n let position = 0;\n let nodes = 0;\n const whitespace = /[\\u0009\\u000a\\u000d\\u0020]/u;\n const skipWhitespace = (): void => {\n while (position < source.length && whitespace.test(source[position] ?? \"\")) position += 1;\n };\n const stringToken = (): string => {\n if (source[position] !== '\"') throw new Error(\"expected JSON string\");\n const start = position;\n position += 1;\n for (;;) {\n const character = source[position];\n if (character === undefined || character.charCodeAt(0) < 0x20) throw new Error(\"invalid JSON string\");\n position += 1;\n if (character === '\"') return JSON.parse(source.slice(start, position)) as string;\n if (character !== \"\\\\\") continue;\n const escape = source[position];\n if (escape === undefined || !'\"\\\\/bfnrtu'.includes(escape)) throw new Error(\"invalid JSON escape\");\n position += 1;\n if (escape === \"u\") {\n const scalar = source.slice(position, position + 4);\n if (!/^[0-9a-fA-F]{4}$/u.test(scalar)) throw new Error(\"invalid JSON Unicode escape\");\n position += 4;\n }\n }\n };\n const value = (depth: number): void => {\n nodes += 1;\n if (depth > 64 || nodes > 100_000) throw new Error(\"JSON exceeds nesting or node bounds\");\n skipWhitespace();\n const initial = source[position];\n if (initial === '\"') {\n stringToken();\n return;\n }\n if (initial === \"{\") {\n position += 1;\n skipWhitespace();\n const keys = new Set<string>();\n if (source[position] === \"}\") {\n position += 1;\n return;\n }\n for (;;) {\n skipWhitespace();\n const key = stringToken();\n if (keys.has(key)) throw new Error(\"JSON object contains a duplicate key\");\n keys.add(key);\n skipWhitespace();\n if (source[position] !== \":\") throw new Error(\"JSON object lacks a colon\");\n position += 1;\n value(depth + 1);\n skipWhitespace();\n if (source[position] === \"}\") {\n position += 1;\n return;\n }\n if (source[position] !== \",\") throw new Error(\"JSON object lacks a separator\");\n position += 1;\n }\n }\n if (initial === \"[\") {\n position += 1;\n skipWhitespace();\n if (source[position] === \"]\") {\n position += 1;\n return;\n }\n for (;;) {\n value(depth + 1);\n skipWhitespace();\n if (source[position] === \"]\") {\n position += 1;\n return;\n }\n if (source[position] !== \",\") throw new Error(\"JSON array lacks a separator\");\n position += 1;\n }\n }\n const start = position;\n while (position < source.length && !/[\\u0009\\u000a\\u000d\\u0020,\\]}]/u.test(source[position] ?? \"\")) position += 1;\n if (position === start) throw new Error(\"JSON value is missing\");\n JSON.parse(source.slice(start, position));\n };\n value(0);\n skipWhitespace();\n if (position !== source.length) throw new Error(\"JSON contains trailing data\");\n}\n\nasync function problem(response: Response): Promise<CigarApiError> {\n const contentType = response.headers.get(\"content-type\")?.split(\";\", 1)[0]?.trim();\n if (contentType !== \"application/problem+json\") {\n throw new TransportError(`HTTP ${response.status} did not use application/problem+json`);\n }\n const value = parseJson(\n await boundedBytes(response, MAX_PROBLEM_BYTES, `HTTP ${response.status} problem`),\n `HTTP ${response.status} problem`,\n );\n return decodeProblem(response.status, value);\n}\n\nfunction decodeProblem(status: number, value: unknown): CigarApiError {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new TransportError(`HTTP ${status} contained an invalid CIGAR problem`);\n }\n const candidate = value as Record<string, unknown>;\n const expected = [\"code\", \"correlation_id\", \"details\", \"http_status\", \"message\", \"remediation\", \"retry\", \"schema_version\"].sort();\n const actual = Object.keys(candidate).sort();\n if (actual.length !== expected.length || actual.some((key, index) => key !== expected[index])) {\n throw new TransportError(`HTTP ${status} contained unknown or missing problem fields`);\n }\n if (candidate.schema_version !== \"cigar.problem.v1\" || typeof candidate.code !== \"string\" || !(candidate.code in ERROR_CATALOG)) {\n throw new TransportError(`HTTP ${status} contained an unsupported CIGAR problem`);\n }\n const code = candidate.code as ErrorCode;\n const definition = ERROR_CATALOG[code];\n if (candidate.http_status !== status || candidate.http_status !== definition.httpStatus || candidate.retry !== definition.retry) {\n throw new TransportError(`HTTP ${status} problem disagrees with the frozen error catalog`);\n }\n if (\n typeof candidate.message !== \"string\" || candidate.message.length === 0 || Buffer.byteLength(candidate.message) > 4096\n || typeof candidate.remediation !== \"string\" || candidate.remediation.length === 0 || Buffer.byteLength(candidate.remediation) > 4096\n || typeof candidate.correlation_id !== \"string\"\n || !/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u.test(candidate.correlation_id)\n || typeof candidate.details !== \"object\" || candidate.details === null || Array.isArray(candidate.details)\n || Object.keys(candidate.details).length > 256\n ) {\n throw new TransportError(`HTTP ${status} contained an invalid bounded CIGAR problem`);\n }\n return new CigarApiError(status, candidate as unknown as ProblemDetails);\n}\n\nfunction validateTimeout(value: number): number {\n if (!Number.isInteger(value) || value < 1 || value > MAX_TIMEOUT_MS) {\n throw new ValidationError(`timeout must be an integer in 1..${MAX_TIMEOUT_MS} milliseconds`);\n }\n return value;\n}\n\nconst AMBIENT_PROXY_ENVIRONMENT = [\n \"ALL_PROXY\",\n \"HTTPS_PROXY\",\n \"HTTP_PROXY\",\n \"NODE_USE_ENV_PROXY\",\n \"all_proxy\",\n \"https_proxy\",\n \"http_proxy\",\n] as const;\n\nfunction ambientProxyConfigured(): boolean {\n const runtime = globalThis as typeof globalThis & {\n process?: { env?: Readonly<Record<string, string | undefined>> };\n };\n const environment = runtime.process?.env;\n return environment !== undefined && AMBIENT_PROXY_ENVIRONMENT.some((name) => {\n const value = environment[name];\n return value !== undefined && value.trim() !== \"\" && value.trim() !== \"0\";\n });\n}\n\nfunction pathParameters(parameters: readonly PathParameter[] | undefined): readonly PathParameter[] {\n const sorted = [...(parameters ?? [])].sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0);\n if (sorted.length > 8) throw new ValidationError(\"at most eight path parameters are allowed\");\n for (let index = 0; index < sorted.length; index += 1) {\n const item = sorted[index];\n if (item === undefined || !PATH_NAME.test(item.name) || !PATH_VALUE.test(item.value)) {\n throw new ValidationError(\"path parameters must use the frozen name/value alphabets\");\n }\n if (index > 0 && sorted[index - 1]?.name === item.name) {\n throw new ValidationError(\"path parameter names must be unique\");\n }\n }\n return sorted;\n}\n\nfunction bindPath(template: string, parameters: readonly PathParameter[]): string {\n const expected = [...template.matchAll(/\\{([a-z][a-z0-9_]*)\\}/gu)].map((match) => match[1]);\n if (expected.length !== parameters.length || expected.some((name) => !parameters.some((item) => item.name === name))) {\n throw new ValidationError(\"request path parameters do not exactly match the operation path\");\n }\n return parameters.reduce((path, item) => path.replace(`{${item.name}}`, item.value), template);\n}\n\nclass HttpEventStream implements EventStream {\n #closed = false;\n #lastEventId?: string;\n readonly #controller = new AbortController();\n readonly #iterate: () => AsyncGenerator<OperationEvent>;\n #iterator?: AsyncGenerator<OperationEvent>;\n\n constructor(iterate: () => AsyncGenerator<OperationEvent>) {\n this.#iterate = iterate;\n }\n\n get lastEventId(): string | undefined {\n return this.#lastEventId;\n }\n\n remember(eventId: string): void {\n this.#lastEventId = eventId;\n }\n\n get closed(): boolean {\n return this.#closed;\n }\n\n get signal(): AbortSignal {\n return this.#controller.signal;\n }\n\n close(): void {\n if (this.#closed) return;\n this.#closed = true;\n this.#controller.abort(new DOMException(\"CIGAR event stream closed\", \"AbortError\"));\n }\n\n async [Symbol.asyncDispose](): Promise<void> {\n this.close();\n }\n\n [Symbol.asyncIterator](): AsyncIterator<OperationEvent> {\n this.#iterator ??= this.#iterate();\n return this.#iterator;\n }\n}\n\nclass TypedHttpEventStream<T> implements TypedEventStream<T> {\n readonly #raw: EventStream;\n readonly #model: PayloadModel<T>;\n\n constructor(raw: EventStream, model: PayloadModel<T>) {\n this.#raw = raw;\n this.#model = model;\n }\n\n get lastEventId(): string | undefined {\n return this.#raw.lastEventId;\n }\n\n close(): void {\n this.#raw.close();\n }\n\n async [Symbol.asyncDispose](): Promise<void> {\n this.close();\n }\n\n async *[Symbol.asyncIterator](): AsyncIterator<TypedOperationEvent<T>> {\n for await (const event of this.#raw) {\n const decoded = decodeOperationPayload(event.payloadCbor) as T;\n yield {\n operationId: event.operationId,\n eventId: event.eventId,\n payload: this.#model.create(decoded),\n payloadCbor: Uint8Array.from(event.payloadCbor),\n };\n }\n }\n}\n\nexport class CigarClient {\n readonly #baseUrl: URL;\n readonly #token?: ClientOptions[\"bearerToken\"];\n readonly #timeoutMs: number;\n readonly #maxAttempts: number;\n readonly #fetch: typeof globalThis.fetch;\n readonly #apiVersion: \"1\";\n\n constructor(options: ClientOptions) {\n try {\n this.#baseUrl = new URL(options.baseUrl);\n } catch (cause) {\n throw new ValidationError(\"baseUrl must be an absolute HTTP(S) origin\", { cause });\n }\n if (!new Set([\"http:\", \"https:\"]).has(this.#baseUrl.protocol)) {\n throw new ValidationError(\"baseUrl must use HTTP or HTTPS\");\n }\n if (this.#baseUrl.username !== \"\" || this.#baseUrl.password !== \"\" || this.#baseUrl.search !== \"\" || this.#baseUrl.hash !== \"\") {\n throw new ValidationError(\"baseUrl must not contain credentials, query, or fragment\");\n }\n if (this.#baseUrl.pathname !== \"/\" && this.#baseUrl.pathname !== \"\") {\n throw new ValidationError(\"baseUrl must be an origin with no path prefix\");\n }\n const loopback = this.#baseUrl.hostname === \"localhost\"\n || this.#baseUrl.hostname === \"127.0.0.1\"\n || this.#baseUrl.hostname === \"::1\"\n || this.#baseUrl.hostname === \"[::1]\";\n if (this.#baseUrl.protocol === \"http:\" && (!loopback || options.allowInsecureLoopback !== true)) {\n throw new ValidationError(\"cleartext HTTP requires explicit allowInsecureLoopback for a loopback host\");\n }\n if (this.#baseUrl.protocol === \"https:\" && options.bearerToken === undefined) {\n throw new ValidationError(\"remote HTTPS requires an explicit bearer token provider\");\n }\n if (typeof options.bearerToken === \"string\" && !/^[\\x21-\\x7e]{1,8192}$/u.test(options.bearerToken)) {\n throw new ValidationError(\"bearer token must be 1..8192 visible ASCII bytes\");\n }\n this.#baseUrl.pathname = \"\";\n this.#token = options.bearerToken;\n this.#timeoutMs = validateTimeout(options.defaultTimeoutMs ?? 30_000);\n this.#maxAttempts = options.maxAttempts ?? 3;\n if (!Number.isInteger(this.#maxAttempts) || this.#maxAttempts < 1 || this.#maxAttempts > 8) {\n throw new ValidationError(\"maxAttempts must be in 1..8\");\n }\n if (options.fetch !== undefined && options.trustCustomFetch !== true) {\n throw new ValidationError(\"custom fetch requires explicit trustCustomFetch acknowledgement\");\n }\n if (options.fetch === undefined && ambientProxyConfigured()) {\n throw new ValidationError(\"ambient proxy configuration requires an explicitly trusted custom fetch\");\n }\n this.#fetch = options.fetch ?? globalThis.fetch;\n if (options.apiVersion !== undefined && options.apiVersion !== \"1\") {\n throw new ValidationError(\"apiVersion must be the frozen v1 line\");\n }\n this.#apiVersion = options.apiVersion ?? \"1\";\n }\n\n async negotiate(options?: CallOptions): Promise<Compatibility> {\n const empty = { payloadCbor: new Uint8Array() } satisfies OperationRequest;\n const version = await this.invokeOperation(\"getVersion\", empty, options);\n const capabilities = await this.invokeOperation(\"getCapabilities\", empty, options);\n return { apiVersion: this.#apiVersion, version, capabilities };\n }\n\n async invokeTypedOperation<RequestPayload, ResponsePayload>(\n operationId: OperationId,\n request: TypedOperationRequest<RequestPayload>,\n responseModel: PayloadModel<ResponsePayload>,\n options?: CallOptions,\n ): Promise<TypedOperationResponse<ResponsePayload>> {\n const raw = await this.invokeOperation(operationId, this.#typedRequest(operationId, request), options);\n const decoded = decodeOperationPayload(raw.payloadCbor) as ResponsePayload;\n return {\n operationId: raw.operationId,\n payload: responseModel.create(decoded),\n payloadCbor: Uint8Array.from(raw.payloadCbor),\n ...(raw.semanticEtag === undefined ? {} : { semanticEtag: raw.semanticEtag }),\n ...(raw.nextPageCursor === undefined ? {} : { nextPageCursor: raw.nextPageCursor }),\n };\n }\n\n streamTypedOperation<RequestPayload, EventPayload>(\n operationId: OperationId,\n request: TypedOperationRequest<RequestPayload>,\n eventModel: PayloadModel<EventPayload>,\n options?: CallOptions,\n ): TypedEventStream<EventPayload> {\n return new TypedHttpEventStream(\n this.streamOperation(operationId, this.#typedRequest(operationId, request), options),\n eventModel,\n );\n }\n\n #typedRequest<T>(operationId: OperationId, request: TypedOperationRequest<T>): OperationRequest {\n const definition = OPERATIONS[operationId];\n if (definition.stream && request.pageCursor !== undefined) {\n throw new ValidationError(\"SSE resume uses CallOptions.resumeFrom, not a pagination cursor\");\n }\n const validatedPayload = payloadModel(definition.requestType).create(request.payload);\n if (typeof validatedPayload !== \"object\" || validatedPayload === null) {\n throw new ValidationError(`${definition.requestType} payload must be an object`);\n }\n const record = validatedPayload as Record<string, unknown>;\n const pathParameters = definition.pathFields.map((name) => {\n const value = record[name];\n if (typeof value !== \"string\") throw new ValidationError(`${definition.requestType}.${name} must be a path string`);\n return { name, value };\n });\n return {\n payloadCbor: definition.httpMethod === \"GET\" ? new Uint8Array() : encodeOperationPayload(validatedPayload),\n pathParameters,\n ...(request.idempotencyKey === undefined ? {} : { idempotencyKey: request.idempotencyKey }),\n ...(request.expectedRevision === undefined ? {} : { expectedRevision: request.expectedRevision }),\n ...(request.dryRun === undefined ? {} : { dryRun: request.dryRun }),\n ...(request.pageCursor === undefined ? {} : { pageCursor: request.pageCursor }),\n ...(request.pageSize === undefined ? {} : { pageSize: request.pageSize }),\n };\n }\n\n async *paginate(\n operationId: OperationId,\n request: OperationRequest,\n options?: CallOptions,\n ): AsyncGenerator<OperationResponse> {\n if (OPERATIONS[operationId].stream) throw new ValidationError(\"stream operations cannot be paginated\");\n let cursor = request.pageCursor;\n const seen = new Set<string>();\n for (;;) {\n const pageRequest: OperationRequest = cursor === undefined\n ? { ...request }\n : { ...request, pageCursor: cursor };\n const response = await this.invokeOperation(operationId, pageRequest, options);\n yield response;\n if (response.nextPageCursor === undefined) return;\n if (seen.has(response.nextPageCursor)) throw new TransportError(\"pagination cursor cycle detected\");\n seen.add(response.nextPageCursor);\n cursor = response.nextPageCursor;\n }\n }\n\n async invokeOperation(\n operationId: OperationId,\n request: OperationRequest,\n options?: CallOptions,\n ): Promise<OperationResponse> {\n const definition = OPERATIONS[operationId];\n if (definition.stream) throw new ValidationError(\"use streamOperation for streaming operations\");\n const attempts = this.#attempts(operationId, request, options);\n const timeoutMs = validateTimeout(options?.timeoutMs ?? this.#timeoutMs);\n const deadline = Date.now() + timeoutMs;\n let lastError: unknown;\n for (let attempt = 1; attempt <= attempts; attempt += 1) {\n if (deadline <= Date.now()) throw new CigarTimeoutError(\"CIGAR request deadline elapsed\");\n try {\n return await this.#unary(operationId, request, deadline, options);\n } catch (error) {\n lastError = error;\n if (attempt === attempts || !isRetryable(error)) throw error;\n const backoff = Math.min(100 * 2 ** (attempt - 1), 1_000);\n const remaining = deadline - Date.now();\n if (remaining <= backoff) throw new CigarTimeoutError(\"CIGAR request deadline elapsed\", { cause: error });\n await delay(backoff, undefined, { signal: options?.signal });\n }\n }\n throw lastError;\n }\n\n streamOperation(operationId: OperationId, request: OperationRequest, options?: CallOptions): EventStream {\n if (!OPERATIONS[operationId].stream) throw new ValidationError(\"operation is not a stream\");\n if (request.pageCursor !== undefined) throw new ValidationError(\"SSE resume uses CallOptions.resumeFrom, not pageCursor\");\n let stream: HttpEventStream;\n stream = new HttpEventStream(() => this.#events(stream, operationId, request, options));\n return stream;\n }\n\n #attempts(operationId: OperationId, request: OperationRequest, options: CallOptions | undefined): number {\n const requested = options?.maxAttempts ?? this.#maxAttempts;\n if (!Number.isInteger(requested) || requested < 1 || requested > 8) {\n throw new ValidationError(\"maxAttempts must be in 1..8\");\n }\n if (operationId === \"dispatchEffect\") return 1;\n const definition = OPERATIONS[operationId];\n if (!definition.mutation) return requested;\n return request.idempotencyKey === undefined ? 1 : requested;\n }\n\n async #headers(\n operationId: OperationId,\n timeoutMs: number,\n signal?: AbortSignal,\n externalSignal?: AbortSignal,\n ): Promise<Headers> {\n const headers = new Headers({\n accept: \"application/json, application/problem+json\",\n \"x-cigar-api-version\": this.#apiVersion,\n \"x-cigar-operation-id\": operationId,\n \"x-cigar-timeout-ms\": String(timeoutMs),\n });\n if (this.#token !== undefined) {\n let token: string;\n try {\n if (typeof this.#token !== \"function\") token = this.#token;\n else if (signal === undefined) token = await this.#token();\n else {\n const provider = Promise.resolve(this.#token(signal));\n token = await new Promise<string>((resolve, reject) => {\n const aborted = (): void => reject(signal.reason);\n signal.addEventListener(\"abort\", aborted, { once: true });\n provider.then(resolve, reject).finally(() => signal.removeEventListener(\"abort\", aborted)).catch(() => undefined);\n });\n }\n } catch (cause) {\n if (externalSignal?.aborted === true) throw cause;\n if (signal?.aborted === true) throw new CigarTimeoutError(\"CIGAR request deadline elapsed\", { cause });\n throw new TransportError(\"bearer token provider failed\", { cause });\n }\n if (!/^[\\x21-\\x7e]{1,8192}$/u.test(token)) throw new ValidationError(\"bearer token must be 1..8192 visible ASCII bytes\");\n headers.set(\"authorization\", `Bearer ${token}`);\n }\n return headers;\n }\n\n #signal(options: CallOptions | undefined, timeoutMs: number, internal?: AbortSignal): AbortSignal {\n const timeout = AbortSignal.timeout(timeoutMs);\n const signals = [timeout];\n if (options?.signal !== undefined) signals.push(options.signal);\n if (internal !== undefined) signals.push(internal);\n return signals.length === 1 ? timeout : AbortSignal.any(signals);\n }\n\n async #unary(\n operationId: OperationId,\n request: OperationRequest,\n deadline: number,\n options?: CallOptions,\n ): Promise<OperationResponse> {\n const definition = OPERATIONS[operationId];\n const timeoutMs = Math.max(1, deadline - Date.now());\n const parameters = pathParameters(request.pathParameters);\n let path = bindPath(definition.httpPath, parameters);\n const requestSignal = this.#signal(options, timeoutMs);\n const headers = await this.#headers(operationId, timeoutMs, requestSignal, options?.signal);\n const payload = Uint8Array.from(request.payloadCbor ?? []);\n if (payload.length > definition.requestMaxBytes) throw new ValidationError(\"request payload exceeds operation bound\");\n let body: string | undefined;\n if (definition.httpMethod === \"GET\") {\n if (payload.length !== 0 || request.idempotencyKey !== undefined || request.expectedRevision !== undefined || request.dryRun === true) {\n throw new ValidationError(\"GET operations do not carry payload or mutation metadata\");\n }\n const query = new URLSearchParams();\n if (request.pageCursor !== undefined) {\n if (Buffer.byteLength(request.pageCursor) > MAX_CURSOR_BYTES) throw new ValidationError(\"page cursor exceeds bound\");\n query.set(\"page_cursor\", request.pageCursor);\n }\n if (request.pageSize !== undefined) {\n if (!Number.isInteger(request.pageSize) || request.pageSize < 1 || request.pageSize > 1000) throw new ValidationError(\"pageSize must be in 1..1000\");\n query.set(\"page_size\", String(request.pageSize));\n }\n const encoded = query.toString();\n if (encoded !== \"\") path += `?${encoded}`;\n } else {\n if (definition.idempotencyRequired) {\n if (request.idempotencyKey === undefined) throw new ValidationError(`${operationId} requires an idempotency key`);\n headers.set(\"idempotency-key\", validateIdempotencyKey(request.idempotencyKey));\n } else if (request.idempotencyKey !== undefined) {\n throw new ValidationError(`${operationId} does not accept an idempotency key`);\n }\n if (definition.revisionRequired) {\n if (request.expectedRevision === undefined || request.expectedRevision.length === 0 || request.expectedRevision.length > 256) {\n throw new ValidationError(`${operationId} requires a bounded expected revision`);\n }\n headers.set(\"if-match\", request.expectedRevision);\n } else if (request.expectedRevision !== undefined) {\n throw new ValidationError(`${operationId} does not accept an expected revision`);\n }\n headers.set(\"content-type\", \"application/json\");\n body = JSON.stringify({\n operation_id: operationId,\n payload_cbor: exactBase64url(payload),\n dry_run: request.dryRun ?? false,\n ...(request.idempotencyKey === undefined ? {} : { idempotency_key: request.idempotencyKey }),\n ...(request.expectedRevision === undefined ? {} : { expected_revision: request.expectedRevision }),\n ...(request.pageCursor === undefined ? {} : { page_cursor: request.pageCursor }),\n ...(request.pageSize === undefined ? {} : { page_size: request.pageSize }),\n path_parameters: parameters,\n });\n }\n let response: Response;\n try {\n const init: RequestInit = {\n method: definition.httpMethod,\n headers,\n signal: requestSignal,\n redirect: \"error\",\n ...(body === undefined ? {} : { body }),\n };\n response = await this.#fetch(new URL(path, `${this.#baseUrl.toString()}/`), init);\n } catch (cause) {\n if (options?.signal?.aborted === true) throw cause;\n if (cause instanceof DOMException && cause.name === \"TimeoutError\") throw new CigarTimeoutError(\"CIGAR request deadline elapsed\", { cause });\n throw new TransportError(\"CIGAR transport failed\", { cause });\n }\n if (!response.ok) throw await problem(response);\n const serverVersion = response.headers.get(\"x-cigar-api-version\");\n if (serverVersion !== null && serverVersion !== this.#apiVersion) {\n throw new CompatibilityError(`server API version ${serverVersion} is incompatible with ${this.#apiVersion}`);\n }\n const contentType = response.headers.get(\"content-type\")?.split(\";\", 1)[0]?.trim();\n if (contentType === \"application/openmetrics-text\") {\n return {\n operationId,\n payloadCbor: await boundedBytes(response, definition.responseMaxBytes, \"metrics response\"),\n };\n }\n if (contentType !== \"application/json\") {\n throw new TransportError(`unexpected response content type ${contentType}`);\n }\n const wrapperMaximum = Math.ceil(definition.responseMaxBytes * 4 / 3) + 16_384;\n return parseResponse(\n operationId,\n parseJson(await boundedBytes(response, wrapperMaximum, \"operation response\"), \"operation response\"),\n definition.responseMaxBytes,\n );\n }\n\n async *#events(\n stream: HttpEventStream,\n operationId: OperationId,\n request: OperationRequest,\n options?: CallOptions,\n ): AsyncGenerator<OperationEvent> {\n const timeoutMs = validateTimeout(options?.timeoutMs ?? this.#timeoutMs);\n const deadline = Date.now() + timeoutMs;\n const parameters = pathParameters(request.pathParameters);\n const definition = OPERATIONS[operationId];\n const path = bindPath(definition.httpPath, parameters);\n let resume = options?.resumeFrom;\n if (resume !== undefined && !/^[\\x21-\\x7e]{1,256}$/u.test(resume)) {\n throw new ValidationError(\"resumeFrom must be a bounded visible-ASCII event ID\");\n }\n const attempts = options?.maxAttempts ?? this.#maxAttempts;\n if (!Number.isInteger(attempts) || attempts < 1 || attempts > 8) {\n throw new ValidationError(\"maxAttempts must be in 1..8\");\n }\n const seen = new Set<string>(resume === undefined ? [] : [resume]);\n for (let attempt = 1; attempt <= attempts && !stream.closed; attempt += 1) {\n const remaining = deadline - Date.now();\n if (remaining <= 0) throw new CigarTimeoutError(\"CIGAR stream deadline elapsed\");\n const requestSignal = this.#signal(options, remaining, stream.signal);\n let headers: Headers;\n try {\n headers = await this.#headers(operationId, remaining, requestSignal, options?.signal);\n } catch (error) {\n if (stream.closed) return;\n throw error;\n }\n headers.set(\"accept\", \"text/event-stream, application/problem+json\");\n if (resume !== undefined) headers.set(\"last-event-id\", resume);\n let retryCause: unknown = new TransportError(\"CIGAR event stream ended before close\");\n let cleanEnd = false;\n let response: Response | undefined;\n try {\n response = await this.#fetch(new URL(path, `${this.#baseUrl.toString()}/`), {\n method: \"GET\",\n headers,\n signal: requestSignal,\n redirect: \"error\",\n });\n } catch (cause) {\n if (stream.closed || options?.signal?.aborted === true) return;\n retryCause = new TransportError(\"CIGAR event stream failed\", { cause });\n }\n if (response !== undefined) {\n if (!response.ok) {\n retryCause = await problem(response);\n if (!isRetryable(retryCause)) throw retryCause;\n } else {\n const contentType = response.headers.get(\"content-type\")?.split(\";\", 1)[0]?.trim();\n if (contentType !== \"text/event-stream\") throw new TransportError(\"stream response must use text/event-stream\");\n if (response.body === null) throw new TransportError(\"event stream response has no body\");\n const iterator = response.body.pipeThrough(new TextDecoderStream(\"utf-8\", { fatal: true }))[Symbol.asyncIterator]();\n let pending = \"\";\n for (;;) {\n let next: IteratorResult<string>;\n try {\n next = await iterator.next();\n } catch (cause) {\n retryCause = new TransportError(\"event stream body read failed\", { cause });\n break;\n }\n if (next.done) {\n cleanEnd = true;\n break;\n }\n if (stream.closed) return;\n pending += next.value.replace(/\\r\\n/gu, \"\\n\");\n if (Buffer.byteLength(pending) > MAX_EVENT_BYTES * 2) throw new TransportError(\"event frame exceeds bound\");\n let boundary: number;\n while ((boundary = pending.indexOf(\"\\n\\n\")) >= 0) {\n const frame = pending.slice(0, boundary);\n pending = pending.slice(boundary + 2);\n const parsed = this.#event(operationId, frame);\n if (parsed === undefined) continue;\n if (parsed instanceof CigarApiError) throw parsed;\n if (seen.has(parsed.eventId)) continue;\n if (seen.size >= 100_000) throw new TransportError(\"event identity set exceeds its bound\");\n seen.add(parsed.eventId);\n resume = parsed.eventId;\n stream.remember(parsed.eventId);\n yield parsed;\n }\n }\n }\n }\n if (stream.closed) return;\n if (attempt === attempts) {\n if (cleanEnd) return;\n throw retryCause;\n }\n const backoff = Math.min(100 * 2 ** (attempt - 1), 1_000);\n if (deadline - Date.now() <= backoff) {\n throw new CigarTimeoutError(\"CIGAR stream deadline elapsed\", { cause: retryCause });\n }\n await delay(backoff, undefined, { signal: options?.signal });\n }\n }\n\n #event(operationId: OperationId, frame: string): OperationEvent | CigarApiError | undefined {\n let eventType = \"message\";\n let id: string | undefined;\n const data: string[] = [];\n for (const line of frame.split(\"\\n\")) {\n if (line === \"\" || line.startsWith(\":\")) continue;\n const colon = line.indexOf(\":\");\n const field = colon < 0 ? line : line.slice(0, colon);\n const value = colon < 0 ? \"\" : line.slice(colon + 1).replace(/^ /u, \"\");\n if (field === \"event\") eventType = value;\n else if (field === \"id\") id = value;\n else if (field === \"data\") data.push(value);\n }\n if (data.length === 0) return undefined;\n let decoded: unknown;\n try {\n decoded = parseJson(new TextEncoder().encode(data.join(\"\\n\")), \"event data\");\n } catch (cause) {\n throw new TransportError(\"event data is not valid JSON\", { cause });\n }\n if (eventType === \"problem\") {\n if (typeof decoded !== \"object\" || decoded === null || Array.isArray(decoded)) {\n throw new TransportError(\"problem event is not an object\");\n }\n const status = (decoded as Record<string, unknown>).http_status;\n if (!Number.isInteger(status)) throw new TransportError(\"problem event lacks its HTTP status\");\n return decodeProblem(status as number, decoded);\n }\n if (typeof decoded !== \"object\" || decoded === null || Array.isArray(decoded)) throw new TransportError(\"event is not an object\");\n const record = decoded as Record<string, unknown>;\n const eventFields = Object.keys(record).sort();\n if (eventFields.join(\",\") !== \"event_id,operation_id,payload_cbor\") {\n throw new TransportError(\"event contains unknown or missing fields\");\n }\n if (\n record.operation_id !== operationId\n || typeof record.event_id !== \"string\"\n || !/^[\\x21-\\x7e]{1,256}$/u.test(record.event_id)\n || record.event_id !== id\n ) {\n throw new TransportError(\"event identity mismatch\");\n }\n return { operationId, eventId: record.event_id, payloadCbor: decodeBase64url(record.payload_cbor, MAX_EVENT_BYTES) };\n }\n}\n\nexport interface CigarClient extends GeneratedOperations {}\n\nfunction payloadModel(name: string): PayloadModel<unknown> {\n const candidate = (models as unknown as Record<string, unknown>)[name];\n if (typeof candidate !== \"object\" || candidate === null || !(\"create\" in candidate)) {\n throw new Error(`generated payload model ${name} is missing`);\n }\n return candidate as PayloadModel<unknown>;\n}\n\nfor (const operationId of Object.keys(OPERATIONS) as OperationId[]) {\n Object.defineProperty(CigarClient.prototype, operationId, {\n configurable: false,\n enumerable: false,\n value(\n this: CigarClient,\n request: TypedOperationRequest<unknown>,\n options?: CallOptions,\n ): Promise<TypedOperationResponse<unknown>> | TypedEventStream<unknown> {\n return OPERATIONS[operationId].stream\n ? this.streamTypedOperation(operationId, request, payloadModel(OPERATIONS[operationId].eventType ?? \"\"), options)\n : this.invokeTypedOperation(operationId, request, payloadModel(OPERATIONS[operationId].responseType), options);\n },\n writable: false,\n });\n}\n"]}