@rivetkit/engine-api-full 25.5.3

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 (192) hide show
  1. package/dist/browser/cjs/core.js +2297 -0
  2. package/dist/browser/cjs/index.js +3752 -0
  3. package/dist/browser/cjs/serialization.js +1744 -0
  4. package/dist/browser/esm/core.js +2271 -0
  5. package/dist/browser/esm/index.js +3726 -0
  6. package/dist/browser/esm/serialization.js +1717 -0
  7. package/dist/node/core.js +2310 -0
  8. package/dist/node/index.js +3765 -0
  9. package/dist/node/serialization.js +1782 -0
  10. package/package.json +59 -0
  11. package/types/Client.d.ts +241 -0
  12. package/types/api/client/index.d.ts +1 -0
  13. package/types/api/client/requests/ActorsCreateRequest.d.ts +22 -0
  14. package/types/api/client/requests/ActorsDeleteRequest.d.ts +10 -0
  15. package/types/api/client/requests/ActorsGetByIdRequest.d.ts +16 -0
  16. package/types/api/client/requests/ActorsGetOrCreateByIdRequest.d.ts +23 -0
  17. package/types/api/client/requests/ActorsGetOrCreateRequest.d.ts +23 -0
  18. package/types/api/client/requests/ActorsGetRequest.d.ts +10 -0
  19. package/types/api/client/requests/ActorsListNamesRequest.d.ts +14 -0
  20. package/types/api/client/requests/ActorsListRequest.d.ts +18 -0
  21. package/types/api/client/requests/index.d.ts +8 -0
  22. package/types/api/index.d.ts +3 -0
  23. package/types/api/resources/datacenters/client/Client.d.ts +34 -0
  24. package/types/api/resources/datacenters/client/index.d.ts +1 -0
  25. package/types/api/resources/datacenters/index.d.ts +1 -0
  26. package/types/api/resources/index.d.ts +5 -0
  27. package/types/api/resources/namespaces/client/Client.d.ts +54 -0
  28. package/types/api/resources/namespaces/client/index.d.ts +1 -0
  29. package/types/api/resources/namespaces/client/requests/NamespacesCreateRequest.d.ts +14 -0
  30. package/types/api/resources/namespaces/client/requests/NamespacesListRequest.d.ts +12 -0
  31. package/types/api/resources/namespaces/client/requests/index.d.ts +2 -0
  32. package/types/api/resources/namespaces/index.d.ts +1 -0
  33. package/types/api/resources/runners/client/Client.d.ts +61 -0
  34. package/types/api/resources/runners/client/index.d.ts +1 -0
  35. package/types/api/resources/runners/client/requests/RunnersGetRequest.d.ts +10 -0
  36. package/types/api/resources/runners/client/requests/RunnersListNamesRequest.d.ts +14 -0
  37. package/types/api/resources/runners/client/requests/RunnersListRequest.d.ts +16 -0
  38. package/types/api/resources/runners/client/requests/index.d.ts +3 -0
  39. package/types/api/resources/runners/index.d.ts +1 -0
  40. package/types/api/types/Actor.d.ts +19 -0
  41. package/types/api/types/ActorName.d.ts +6 -0
  42. package/types/api/types/ActorsCreateResponse.d.ts +7 -0
  43. package/types/api/types/ActorsDeleteResponse.d.ts +4 -0
  44. package/types/api/types/ActorsGetByIdResponse.d.ts +7 -0
  45. package/types/api/types/ActorsGetOrCreateByIdResponse.d.ts +8 -0
  46. package/types/api/types/ActorsGetOrCreateResponse.d.ts +8 -0
  47. package/types/api/types/ActorsGetResponse.d.ts +7 -0
  48. package/types/api/types/ActorsListNamesResponse.d.ts +8 -0
  49. package/types/api/types/ActorsListResponse.d.ts +8 -0
  50. package/types/api/types/CrashPolicy.d.ts +9 -0
  51. package/types/api/types/Datacenter.d.ts +8 -0
  52. package/types/api/types/DatacentersListResponse.d.ts +8 -0
  53. package/types/api/types/Namespace.d.ts +10 -0
  54. package/types/api/types/NamespacesCreateResponse.d.ts +7 -0
  55. package/types/api/types/NamespacesGetResponse.d.ts +7 -0
  56. package/types/api/types/NamespacesListResponse.d.ts +8 -0
  57. package/types/api/types/Pagination.d.ts +6 -0
  58. package/types/api/types/RivetId.d.ts +4 -0
  59. package/types/api/types/Runner.d.ts +24 -0
  60. package/types/api/types/RunnersGetResponse.d.ts +7 -0
  61. package/types/api/types/RunnersListNamesResponse.d.ts +8 -0
  62. package/types/api/types/RunnersListResponse.d.ts +8 -0
  63. package/types/api/types/StringHttpAddressHashableMap.d.ts +5 -0
  64. package/types/api/types/StringHttpAddressHashableMapValue.d.ts +7 -0
  65. package/types/api/types/StringTcpAddressHashableMap.d.ts +5 -0
  66. package/types/api/types/StringTcpAddressHashableMapValue.d.ts +7 -0
  67. package/types/api/types/StringUdpAddressHashableMap.d.ts +5 -0
  68. package/types/api/types/StringUdpAddressHashableMapValue.d.ts +7 -0
  69. package/types/api/types/index.d.ts +29 -0
  70. package/types/core/fetcher/APIResponse.d.ts +10 -0
  71. package/types/core/fetcher/Fetcher.d.ts +39 -0
  72. package/types/core/fetcher/Supplier.d.ts +4 -0
  73. package/types/core/fetcher/createRequestUrl.d.ts +1 -0
  74. package/types/core/fetcher/getFetchFn.d.ts +4 -0
  75. package/types/core/fetcher/getHeader.d.ts +1 -0
  76. package/types/core/fetcher/getRequestBody.d.ts +7 -0
  77. package/types/core/fetcher/getResponseBody.d.ts +1 -0
  78. package/types/core/fetcher/index.d.ts +5 -0
  79. package/types/core/fetcher/makeRequest.d.ts +1 -0
  80. package/types/core/fetcher/requestWithRetries.d.ts +1 -0
  81. package/types/core/fetcher/signals.d.ts +11 -0
  82. package/types/core/fetcher/stream-wrappers/Node18UniversalStreamWrapper.d.ts +30 -0
  83. package/types/core/fetcher/stream-wrappers/NodePre18StreamWrapper.d.ts +21 -0
  84. package/types/core/fetcher/stream-wrappers/UndiciStreamWrapper.d.ts +31 -0
  85. package/types/core/fetcher/stream-wrappers/chooseStreamWrapper.d.ts +18 -0
  86. package/types/core/index.d.ts +3 -0
  87. package/types/core/json.d.ts +15 -0
  88. package/types/core/runtime/index.d.ts +1 -0
  89. package/types/core/runtime/runtime.d.ts +9 -0
  90. package/types/core/schemas/Schema.d.ts +87 -0
  91. package/types/core/schemas/builders/bigint/bigint.d.ts +2 -0
  92. package/types/core/schemas/builders/bigint/index.d.ts +1 -0
  93. package/types/core/schemas/builders/date/date.d.ts +2 -0
  94. package/types/core/schemas/builders/date/index.d.ts +1 -0
  95. package/types/core/schemas/builders/enum/enum.d.ts +2 -0
  96. package/types/core/schemas/builders/enum/index.d.ts +1 -0
  97. package/types/core/schemas/builders/index.d.ts +14 -0
  98. package/types/core/schemas/builders/lazy/index.d.ts +3 -0
  99. package/types/core/schemas/builders/lazy/lazy.d.ts +5 -0
  100. package/types/core/schemas/builders/lazy/lazyObject.d.ts +3 -0
  101. package/types/core/schemas/builders/list/index.d.ts +1 -0
  102. package/types/core/schemas/builders/list/list.d.ts +2 -0
  103. package/types/core/schemas/builders/literals/booleanLiteral.d.ts +2 -0
  104. package/types/core/schemas/builders/literals/index.d.ts +2 -0
  105. package/types/core/schemas/builders/literals/stringLiteral.d.ts +2 -0
  106. package/types/core/schemas/builders/object/index.d.ts +6 -0
  107. package/types/core/schemas/builders/object/object.d.ts +3 -0
  108. package/types/core/schemas/builders/object/objectWithoutOptionalProperties.d.ts +6 -0
  109. package/types/core/schemas/builders/object/property.d.ts +8 -0
  110. package/types/core/schemas/builders/object/types.d.ts +31 -0
  111. package/types/core/schemas/builders/object-like/getObjectLikeUtils.d.ts +9 -0
  112. package/types/core/schemas/builders/object-like/index.d.ts +2 -0
  113. package/types/core/schemas/builders/object-like/types.d.ts +7 -0
  114. package/types/core/schemas/builders/primitives/any.d.ts +1 -0
  115. package/types/core/schemas/builders/primitives/boolean.d.ts +1 -0
  116. package/types/core/schemas/builders/primitives/index.d.ts +5 -0
  117. package/types/core/schemas/builders/primitives/number.d.ts +1 -0
  118. package/types/core/schemas/builders/primitives/string.d.ts +1 -0
  119. package/types/core/schemas/builders/primitives/unknown.d.ts +1 -0
  120. package/types/core/schemas/builders/record/index.d.ts +2 -0
  121. package/types/core/schemas/builders/record/record.d.ts +3 -0
  122. package/types/core/schemas/builders/record/types.d.ts +4 -0
  123. package/types/core/schemas/builders/schema-utils/JsonError.d.ts +5 -0
  124. package/types/core/schemas/builders/schema-utils/ParseError.d.ts +5 -0
  125. package/types/core/schemas/builders/schema-utils/getSchemaUtils.d.ts +21 -0
  126. package/types/core/schemas/builders/schema-utils/index.d.ts +4 -0
  127. package/types/core/schemas/builders/schema-utils/stringifyValidationErrors.d.ts +2 -0
  128. package/types/core/schemas/builders/set/index.d.ts +1 -0
  129. package/types/core/schemas/builders/set/set.d.ts +2 -0
  130. package/types/core/schemas/builders/undiscriminated-union/index.d.ts +2 -0
  131. package/types/core/schemas/builders/undiscriminated-union/types.d.ts +4 -0
  132. package/types/core/schemas/builders/undiscriminated-union/undiscriminatedUnion.d.ts +3 -0
  133. package/types/core/schemas/builders/union/discriminant.d.ts +5 -0
  134. package/types/core/schemas/builders/union/index.d.ts +4 -0
  135. package/types/core/schemas/builders/union/types.d.ts +13 -0
  136. package/types/core/schemas/builders/union/union.d.ts +4 -0
  137. package/types/core/schemas/index.d.ts +2 -0
  138. package/types/core/schemas/utils/MaybePromise.d.ts +1 -0
  139. package/types/core/schemas/utils/addQuestionMarksToNullableProperties.d.ts +7 -0
  140. package/types/core/schemas/utils/createIdentitySchemaCreator.d.ts +2 -0
  141. package/types/core/schemas/utils/entries.d.ts +1 -0
  142. package/types/core/schemas/utils/filterObject.d.ts +1 -0
  143. package/types/core/schemas/utils/getErrorMessageForIncorrectType.d.ts +1 -0
  144. package/types/core/schemas/utils/isPlainObject.d.ts +1 -0
  145. package/types/core/schemas/utils/keys.d.ts +1 -0
  146. package/types/core/schemas/utils/maybeSkipValidation.d.ts +2 -0
  147. package/types/core/schemas/utils/partition.d.ts +1 -0
  148. package/types/errors/RivetError.d.ts +12 -0
  149. package/types/errors/RivetTimeoutError.d.ts +6 -0
  150. package/types/errors/index.d.ts +2 -0
  151. package/types/index.d.ts +4 -0
  152. package/types/serialization/client/index.d.ts +1 -0
  153. package/types/serialization/client/requests/ActorsCreateRequest.d.ts +17 -0
  154. package/types/serialization/client/requests/ActorsGetOrCreateByIdRequest.d.ts +17 -0
  155. package/types/serialization/client/requests/ActorsGetOrCreateRequest.d.ts +17 -0
  156. package/types/serialization/client/requests/index.d.ts +3 -0
  157. package/types/serialization/index.d.ts +3 -0
  158. package/types/serialization/resources/index.d.ts +2 -0
  159. package/types/serialization/resources/namespaces/client/index.d.ts +1 -0
  160. package/types/serialization/resources/namespaces/client/requests/NamespacesCreateRequest.d.ts +13 -0
  161. package/types/serialization/resources/namespaces/client/requests/index.d.ts +1 -0
  162. package/types/serialization/resources/namespaces/index.d.ts +1 -0
  163. package/types/serialization/types/Actor.d.ts +26 -0
  164. package/types/serialization/types/ActorName.d.ts +12 -0
  165. package/types/serialization/types/ActorsCreateResponse.d.ts +13 -0
  166. package/types/serialization/types/ActorsDeleteResponse.d.ts +10 -0
  167. package/types/serialization/types/ActorsGetByIdResponse.d.ts +13 -0
  168. package/types/serialization/types/ActorsGetOrCreateByIdResponse.d.ts +14 -0
  169. package/types/serialization/types/ActorsGetOrCreateResponse.d.ts +14 -0
  170. package/types/serialization/types/ActorsGetResponse.d.ts +13 -0
  171. package/types/serialization/types/ActorsListNamesResponse.d.ts +15 -0
  172. package/types/serialization/types/ActorsListResponse.d.ts +15 -0
  173. package/types/serialization/types/CrashPolicy.d.ts +10 -0
  174. package/types/serialization/types/Datacenter.d.ts +14 -0
  175. package/types/serialization/types/DatacentersListResponse.d.ts +15 -0
  176. package/types/serialization/types/Namespace.d.ts +16 -0
  177. package/types/serialization/types/NamespacesCreateResponse.d.ts +13 -0
  178. package/types/serialization/types/NamespacesGetResponse.d.ts +13 -0
  179. package/types/serialization/types/NamespacesListResponse.d.ts +15 -0
  180. package/types/serialization/types/Pagination.d.ts +12 -0
  181. package/types/serialization/types/RivetId.d.ts +10 -0
  182. package/types/serialization/types/Runner.d.ts +33 -0
  183. package/types/serialization/types/RunnersGetResponse.d.ts +13 -0
  184. package/types/serialization/types/RunnersListNamesResponse.d.ts +14 -0
  185. package/types/serialization/types/RunnersListResponse.d.ts +15 -0
  186. package/types/serialization/types/StringHttpAddressHashableMap.d.ts +11 -0
  187. package/types/serialization/types/StringHttpAddressHashableMapValue.d.ts +13 -0
  188. package/types/serialization/types/StringTcpAddressHashableMap.d.ts +11 -0
  189. package/types/serialization/types/StringTcpAddressHashableMapValue.d.ts +13 -0
  190. package/types/serialization/types/StringUdpAddressHashableMap.d.ts +11 -0
  191. package/types/serialization/types/StringUdpAddressHashableMapValue.d.ts +13 -0
  192. package/types/serialization/types/index.d.ts +29 -0
@@ -0,0 +1,3765 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __esm = (fn, res) => function __init() {
9
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
10
+ };
11
+ var __export = (target, all) => {
12
+ for (var name in all)
13
+ __defProp(target, name, { get: all[name], enumerable: true });
14
+ };
15
+ var __copyProps = (to, from, except, desc) => {
16
+ if (from && typeof from === "object" || typeof from === "function") {
17
+ for (let key of __getOwnPropNames(from))
18
+ if (!__hasOwnProp.call(to, key) && key !== except)
19
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
20
+ }
21
+ return to;
22
+ };
23
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
24
+ // If the importer is in node compatibility mode or this is not an ESM
25
+ // file that has been converted to a CommonJS file using a Babel-
26
+ // compatible transform (i.e. "__esModule" has not been set), then set
27
+ // "default" to the CommonJS "module.exports" for node compatibility.
28
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
29
+ mod
30
+ ));
31
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
32
+
33
+ // src/core/fetcher/stream-wrappers/Node18UniversalStreamWrapper.ts
34
+ var Node18UniversalStreamWrapper_exports = {};
35
+ __export(Node18UniversalStreamWrapper_exports, {
36
+ Node18UniversalStreamWrapper: () => Node18UniversalStreamWrapper
37
+ });
38
+ var Node18UniversalStreamWrapper;
39
+ var init_Node18UniversalStreamWrapper = __esm({
40
+ "src/core/fetcher/stream-wrappers/Node18UniversalStreamWrapper.ts"() {
41
+ "use strict";
42
+ Node18UniversalStreamWrapper = class _Node18UniversalStreamWrapper {
43
+ readableStream;
44
+ reader;
45
+ events;
46
+ paused;
47
+ resumeCallback;
48
+ encoding;
49
+ constructor(readableStream) {
50
+ this.readableStream = readableStream;
51
+ this.reader = this.readableStream.getReader();
52
+ this.events = {
53
+ data: [],
54
+ end: [],
55
+ error: [],
56
+ readable: [],
57
+ close: [],
58
+ pause: [],
59
+ resume: []
60
+ };
61
+ this.paused = false;
62
+ this.resumeCallback = null;
63
+ this.encoding = null;
64
+ }
65
+ on(event, callback) {
66
+ var _a;
67
+ (_a = this.events[event]) == null ? void 0 : _a.push(callback);
68
+ }
69
+ off(event, callback) {
70
+ var _a;
71
+ this.events[event] = (_a = this.events[event]) == null ? void 0 : _a.filter((cb) => cb !== callback);
72
+ }
73
+ pipe(dest) {
74
+ this.on("data", async (chunk) => {
75
+ if (dest instanceof _Node18UniversalStreamWrapper) {
76
+ dest._write(chunk);
77
+ } else if (dest instanceof WritableStream) {
78
+ const writer = dest.getWriter();
79
+ writer.write(chunk).then(() => writer.releaseLock());
80
+ } else {
81
+ dest.write(chunk);
82
+ }
83
+ });
84
+ this.on("end", async () => {
85
+ if (dest instanceof _Node18UniversalStreamWrapper) {
86
+ dest._end();
87
+ } else if (dest instanceof WritableStream) {
88
+ const writer = dest.getWriter();
89
+ writer.close();
90
+ } else {
91
+ dest.end();
92
+ }
93
+ });
94
+ this.on("error", async (error) => {
95
+ if (dest instanceof _Node18UniversalStreamWrapper) {
96
+ dest._error(error);
97
+ } else if (dest instanceof WritableStream) {
98
+ const writer = dest.getWriter();
99
+ writer.abort(error);
100
+ } else {
101
+ dest.destroy(error);
102
+ }
103
+ });
104
+ this._startReading();
105
+ return dest;
106
+ }
107
+ pipeTo(dest) {
108
+ return this.pipe(dest);
109
+ }
110
+ unpipe(dest) {
111
+ this.off("data", async (chunk) => {
112
+ if (dest instanceof _Node18UniversalStreamWrapper) {
113
+ dest._write(chunk);
114
+ } else if (dest instanceof WritableStream) {
115
+ const writer = dest.getWriter();
116
+ writer.write(chunk).then(() => writer.releaseLock());
117
+ } else {
118
+ dest.write(chunk);
119
+ }
120
+ });
121
+ this.off("end", async () => {
122
+ if (dest instanceof _Node18UniversalStreamWrapper) {
123
+ dest._end();
124
+ } else if (dest instanceof WritableStream) {
125
+ const writer = dest.getWriter();
126
+ writer.close();
127
+ } else {
128
+ dest.end();
129
+ }
130
+ });
131
+ this.off("error", async (error) => {
132
+ if (dest instanceof _Node18UniversalStreamWrapper) {
133
+ dest._error(error);
134
+ } else if (dest instanceof WritableStream) {
135
+ const writer = dest.getWriter();
136
+ writer.abort(error);
137
+ } else {
138
+ dest.destroy(error);
139
+ }
140
+ });
141
+ }
142
+ destroy(error) {
143
+ this.reader.cancel(error).then(() => {
144
+ this._emit("close");
145
+ }).catch((err) => {
146
+ this._emit("error", err);
147
+ });
148
+ }
149
+ pause() {
150
+ this.paused = true;
151
+ this._emit("pause");
152
+ }
153
+ resume() {
154
+ if (this.paused) {
155
+ this.paused = false;
156
+ this._emit("resume");
157
+ if (this.resumeCallback) {
158
+ this.resumeCallback();
159
+ this.resumeCallback = null;
160
+ }
161
+ }
162
+ }
163
+ get isPaused() {
164
+ return this.paused;
165
+ }
166
+ async read() {
167
+ if (this.paused) {
168
+ await new Promise((resolve) => {
169
+ this.resumeCallback = resolve;
170
+ });
171
+ }
172
+ const { done, value } = await this.reader.read();
173
+ if (done) {
174
+ return void 0;
175
+ }
176
+ return value;
177
+ }
178
+ setEncoding(encoding) {
179
+ this.encoding = encoding;
180
+ }
181
+ async text() {
182
+ const chunks = [];
183
+ while (true) {
184
+ const { done, value } = await this.reader.read();
185
+ if (done) {
186
+ break;
187
+ }
188
+ if (value) {
189
+ chunks.push(value);
190
+ }
191
+ }
192
+ const decoder = new TextDecoder(this.encoding || "utf-8");
193
+ return decoder.decode(await new Blob(chunks).arrayBuffer());
194
+ }
195
+ async json() {
196
+ const text = await this.text();
197
+ return JSON.parse(text);
198
+ }
199
+ _write(chunk) {
200
+ this._emit("data", chunk);
201
+ }
202
+ _end() {
203
+ this._emit("end");
204
+ }
205
+ _error(error) {
206
+ this._emit("error", error);
207
+ }
208
+ _emit(event, data) {
209
+ if (this.events[event]) {
210
+ for (const callback of this.events[event] || []) {
211
+ callback(data);
212
+ }
213
+ }
214
+ }
215
+ async _startReading() {
216
+ try {
217
+ this._emit("readable");
218
+ while (true) {
219
+ if (this.paused) {
220
+ await new Promise((resolve) => {
221
+ this.resumeCallback = resolve;
222
+ });
223
+ }
224
+ const { done, value } = await this.reader.read();
225
+ if (done) {
226
+ this._emit("end");
227
+ this._emit("close");
228
+ break;
229
+ }
230
+ if (value) {
231
+ this._emit("data", value);
232
+ }
233
+ }
234
+ } catch (error) {
235
+ this._emit("error", error);
236
+ }
237
+ }
238
+ [Symbol.asyncIterator]() {
239
+ return {
240
+ next: async () => {
241
+ if (this.paused) {
242
+ await new Promise((resolve) => {
243
+ this.resumeCallback = resolve;
244
+ });
245
+ }
246
+ const { done, value } = await this.reader.read();
247
+ if (done) {
248
+ return { done: true, value: void 0 };
249
+ }
250
+ return { done: false, value };
251
+ },
252
+ [Symbol.asyncIterator]() {
253
+ return this;
254
+ }
255
+ };
256
+ }
257
+ };
258
+ }
259
+ });
260
+
261
+ // src/core/fetcher/stream-wrappers/UndiciStreamWrapper.ts
262
+ var UndiciStreamWrapper_exports = {};
263
+ __export(UndiciStreamWrapper_exports, {
264
+ UndiciStreamWrapper: () => UndiciStreamWrapper
265
+ });
266
+ var UndiciStreamWrapper;
267
+ var init_UndiciStreamWrapper = __esm({
268
+ "src/core/fetcher/stream-wrappers/UndiciStreamWrapper.ts"() {
269
+ "use strict";
270
+ UndiciStreamWrapper = class _UndiciStreamWrapper {
271
+ readableStream;
272
+ reader;
273
+ events;
274
+ paused;
275
+ resumeCallback;
276
+ encoding;
277
+ constructor(readableStream) {
278
+ this.readableStream = readableStream;
279
+ this.reader = this.readableStream.getReader();
280
+ this.events = {
281
+ data: [],
282
+ end: [],
283
+ error: [],
284
+ readable: [],
285
+ close: [],
286
+ pause: [],
287
+ resume: []
288
+ };
289
+ this.paused = false;
290
+ this.resumeCallback = null;
291
+ this.encoding = null;
292
+ }
293
+ on(event, callback) {
294
+ var _a;
295
+ (_a = this.events[event]) == null ? void 0 : _a.push(callback);
296
+ }
297
+ off(event, callback) {
298
+ var _a;
299
+ this.events[event] = (_a = this.events[event]) == null ? void 0 : _a.filter((cb) => cb !== callback);
300
+ }
301
+ pipe(dest) {
302
+ this.on("data", (chunk) => {
303
+ if (dest instanceof _UndiciStreamWrapper) {
304
+ dest._write(chunk);
305
+ } else {
306
+ const writer = dest.getWriter();
307
+ writer.write(chunk).then(() => writer.releaseLock());
308
+ }
309
+ });
310
+ this.on("end", () => {
311
+ if (dest instanceof _UndiciStreamWrapper) {
312
+ dest._end();
313
+ } else {
314
+ const writer = dest.getWriter();
315
+ writer.close();
316
+ }
317
+ });
318
+ this.on("error", (error) => {
319
+ if (dest instanceof _UndiciStreamWrapper) {
320
+ dest._error(error);
321
+ } else {
322
+ const writer = dest.getWriter();
323
+ writer.abort(error);
324
+ }
325
+ });
326
+ this._startReading();
327
+ return dest;
328
+ }
329
+ pipeTo(dest) {
330
+ return this.pipe(dest);
331
+ }
332
+ unpipe(dest) {
333
+ this.off("data", (chunk) => {
334
+ if (dest instanceof _UndiciStreamWrapper) {
335
+ dest._write(chunk);
336
+ } else {
337
+ const writer = dest.getWriter();
338
+ writer.write(chunk).then(() => writer.releaseLock());
339
+ }
340
+ });
341
+ this.off("end", () => {
342
+ if (dest instanceof _UndiciStreamWrapper) {
343
+ dest._end();
344
+ } else {
345
+ const writer = dest.getWriter();
346
+ writer.close();
347
+ }
348
+ });
349
+ this.off("error", (error) => {
350
+ if (dest instanceof _UndiciStreamWrapper) {
351
+ dest._error(error);
352
+ } else {
353
+ const writer = dest.getWriter();
354
+ writer.abort(error);
355
+ }
356
+ });
357
+ }
358
+ destroy(error) {
359
+ this.reader.cancel(error).then(() => {
360
+ this._emit("close");
361
+ }).catch((err) => {
362
+ this._emit("error", err);
363
+ });
364
+ }
365
+ pause() {
366
+ this.paused = true;
367
+ this._emit("pause");
368
+ }
369
+ resume() {
370
+ if (this.paused) {
371
+ this.paused = false;
372
+ this._emit("resume");
373
+ if (this.resumeCallback) {
374
+ this.resumeCallback();
375
+ this.resumeCallback = null;
376
+ }
377
+ }
378
+ }
379
+ get isPaused() {
380
+ return this.paused;
381
+ }
382
+ async read() {
383
+ if (this.paused) {
384
+ await new Promise((resolve) => {
385
+ this.resumeCallback = resolve;
386
+ });
387
+ }
388
+ const { done, value } = await this.reader.read();
389
+ if (done) {
390
+ return void 0;
391
+ }
392
+ return value;
393
+ }
394
+ setEncoding(encoding) {
395
+ this.encoding = encoding;
396
+ }
397
+ async text() {
398
+ const chunks = [];
399
+ while (true) {
400
+ const { done, value } = await this.reader.read();
401
+ if (done) {
402
+ break;
403
+ }
404
+ if (value) {
405
+ chunks.push(value);
406
+ }
407
+ }
408
+ const decoder = new TextDecoder(this.encoding || "utf-8");
409
+ return decoder.decode(await new Blob(chunks).arrayBuffer());
410
+ }
411
+ async json() {
412
+ const text = await this.text();
413
+ return JSON.parse(text);
414
+ }
415
+ _write(chunk) {
416
+ this._emit("data", chunk);
417
+ }
418
+ _end() {
419
+ this._emit("end");
420
+ }
421
+ _error(error) {
422
+ this._emit("error", error);
423
+ }
424
+ _emit(event, data) {
425
+ if (this.events[event]) {
426
+ for (const callback of this.events[event] || []) {
427
+ callback(data);
428
+ }
429
+ }
430
+ }
431
+ async _startReading() {
432
+ try {
433
+ this._emit("readable");
434
+ while (true) {
435
+ if (this.paused) {
436
+ await new Promise((resolve) => {
437
+ this.resumeCallback = resolve;
438
+ });
439
+ }
440
+ const { done, value } = await this.reader.read();
441
+ if (done) {
442
+ this._emit("end");
443
+ this._emit("close");
444
+ break;
445
+ }
446
+ if (value) {
447
+ this._emit("data", value);
448
+ }
449
+ }
450
+ } catch (error) {
451
+ this._emit("error", error);
452
+ }
453
+ }
454
+ [Symbol.asyncIterator]() {
455
+ return {
456
+ next: async () => {
457
+ if (this.paused) {
458
+ await new Promise((resolve) => {
459
+ this.resumeCallback = resolve;
460
+ });
461
+ }
462
+ const { done, value } = await this.reader.read();
463
+ if (done) {
464
+ return { done: true, value: void 0 };
465
+ }
466
+ return { done: false, value };
467
+ },
468
+ [Symbol.asyncIterator]() {
469
+ return this;
470
+ }
471
+ };
472
+ }
473
+ };
474
+ }
475
+ });
476
+
477
+ // src/core/fetcher/stream-wrappers/NodePre18StreamWrapper.ts
478
+ var NodePre18StreamWrapper_exports = {};
479
+ __export(NodePre18StreamWrapper_exports, {
480
+ NodePre18StreamWrapper: () => NodePre18StreamWrapper
481
+ });
482
+ var NodePre18StreamWrapper;
483
+ var init_NodePre18StreamWrapper = __esm({
484
+ "src/core/fetcher/stream-wrappers/NodePre18StreamWrapper.ts"() {
485
+ "use strict";
486
+ NodePre18StreamWrapper = class {
487
+ readableStream;
488
+ encoding;
489
+ constructor(readableStream) {
490
+ this.readableStream = readableStream;
491
+ }
492
+ on(event, callback) {
493
+ this.readableStream.on(event, callback);
494
+ }
495
+ off(event, callback) {
496
+ this.readableStream.off(event, callback);
497
+ }
498
+ pipe(dest) {
499
+ this.readableStream.pipe(dest);
500
+ return dest;
501
+ }
502
+ pipeTo(dest) {
503
+ return this.pipe(dest);
504
+ }
505
+ unpipe(dest) {
506
+ if (dest) {
507
+ this.readableStream.unpipe(dest);
508
+ } else {
509
+ this.readableStream.unpipe();
510
+ }
511
+ }
512
+ destroy(error) {
513
+ this.readableStream.destroy(error);
514
+ }
515
+ pause() {
516
+ this.readableStream.pause();
517
+ }
518
+ resume() {
519
+ this.readableStream.resume();
520
+ }
521
+ get isPaused() {
522
+ return this.readableStream.isPaused();
523
+ }
524
+ async read() {
525
+ return new Promise((resolve, reject) => {
526
+ const chunk = this.readableStream.read();
527
+ if (chunk) {
528
+ resolve(chunk);
529
+ } else {
530
+ this.readableStream.once("readable", () => {
531
+ const chunk2 = this.readableStream.read();
532
+ resolve(chunk2);
533
+ });
534
+ this.readableStream.once("error", reject);
535
+ }
536
+ });
537
+ }
538
+ setEncoding(encoding) {
539
+ this.readableStream.setEncoding(encoding);
540
+ this.encoding = encoding;
541
+ }
542
+ async text() {
543
+ const chunks = [];
544
+ const encoder = new TextEncoder();
545
+ this.readableStream.setEncoding(this.encoding || "utf-8");
546
+ for await (const chunk of this.readableStream) {
547
+ chunks.push(encoder.encode(chunk));
548
+ }
549
+ const decoder = new TextDecoder(this.encoding || "utf-8");
550
+ return decoder.decode(Buffer.concat(chunks));
551
+ }
552
+ async json() {
553
+ const text = await this.text();
554
+ return JSON.parse(text);
555
+ }
556
+ [Symbol.asyncIterator]() {
557
+ const readableStream = this.readableStream;
558
+ const iterator = readableStream[Symbol.asyncIterator]();
559
+ return {
560
+ async next() {
561
+ const { value, done } = await iterator.next();
562
+ return { value, done };
563
+ },
564
+ [Symbol.asyncIterator]() {
565
+ return this;
566
+ }
567
+ };
568
+ }
569
+ };
570
+ }
571
+ });
572
+
573
+ // src/index.ts
574
+ var src_exports = {};
575
+ __export(src_exports, {
576
+ Rivet: () => api_exports,
577
+ RivetClient: () => RivetClient,
578
+ RivetError: () => RivetError,
579
+ RivetTimeoutError: () => RivetTimeoutError,
580
+ serialization: () => serialization_exports
581
+ });
582
+ module.exports = __toCommonJS(src_exports);
583
+
584
+ // src/api/index.ts
585
+ var api_exports = {};
586
+ __export(api_exports, {
587
+ CrashPolicy: () => CrashPolicy,
588
+ datacenters: () => datacenters_exports,
589
+ namespaces: () => namespaces_exports,
590
+ runners: () => runners_exports
591
+ });
592
+
593
+ // src/api/types/CrashPolicy.ts
594
+ var CrashPolicy = {
595
+ Restart: "restart",
596
+ Sleep: "sleep",
597
+ Destroy: "destroy"
598
+ };
599
+
600
+ // src/api/resources/datacenters/index.ts
601
+ var datacenters_exports = {};
602
+
603
+ // src/api/resources/namespaces/index.ts
604
+ var namespaces_exports = {};
605
+
606
+ // src/api/resources/runners/index.ts
607
+ var runners_exports = {};
608
+
609
+ // src/core/json.ts
610
+ var toJson = (value, replacer, space) => {
611
+ return JSON.stringify(value, replacer, space);
612
+ };
613
+
614
+ // src/core/fetcher/createRequestUrl.ts
615
+ var import_qs = __toESM(require("qs"));
616
+ function createRequestUrl(baseUrl, queryParameters) {
617
+ return Object.keys(queryParameters ?? {}).length > 0 ? `${baseUrl}?${import_qs.default.stringify(queryParameters, { arrayFormat: "repeat" })}` : baseUrl;
618
+ }
619
+
620
+ // src/core/runtime/runtime.ts
621
+ var RUNTIME = evaluateRuntime();
622
+ function evaluateRuntime() {
623
+ var _a, _b, _c, _d, _e;
624
+ const isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined";
625
+ if (isBrowser) {
626
+ return {
627
+ type: "browser",
628
+ version: window.navigator.userAgent
629
+ };
630
+ }
631
+ const isCloudflare = typeof globalThis !== "undefined" && ((_a = globalThis == null ? void 0 : globalThis.navigator) == null ? void 0 : _a.userAgent) === "Cloudflare-Workers";
632
+ if (isCloudflare) {
633
+ return {
634
+ type: "workerd"
635
+ };
636
+ }
637
+ const isEdgeRuntime = typeof EdgeRuntime === "string";
638
+ if (isEdgeRuntime) {
639
+ return {
640
+ type: "edge-runtime"
641
+ };
642
+ }
643
+ const isWebWorker = typeof self === "object" && // @ts-ignore
644
+ typeof (self == null ? void 0 : self.importScripts) === "function" && (((_b = self.constructor) == null ? void 0 : _b.name) === "DedicatedWorkerGlobalScope" || ((_c = self.constructor) == null ? void 0 : _c.name) === "ServiceWorkerGlobalScope" || ((_d = self.constructor) == null ? void 0 : _d.name) === "SharedWorkerGlobalScope");
645
+ if (isWebWorker) {
646
+ return {
647
+ type: "web-worker"
648
+ };
649
+ }
650
+ const isDeno = typeof Deno !== "undefined" && typeof Deno.version !== "undefined" && typeof Deno.version.deno !== "undefined";
651
+ if (isDeno) {
652
+ return {
653
+ type: "deno",
654
+ version: Deno.version.deno
655
+ };
656
+ }
657
+ const isBun = typeof Bun !== "undefined" && typeof Bun.version !== "undefined";
658
+ if (isBun) {
659
+ return {
660
+ type: "bun",
661
+ version: Bun.version
662
+ };
663
+ }
664
+ const isNode = typeof process !== "undefined" && "version" in process && !!process.version && "versions" in process && !!((_e = process.versions) == null ? void 0 : _e.node);
665
+ if (isNode) {
666
+ return {
667
+ type: "node",
668
+ version: process.versions.node,
669
+ parsedVersion: Number(process.versions.node.split(".")[0])
670
+ };
671
+ }
672
+ const isReactNative = typeof navigator !== "undefined" && (navigator == null ? void 0 : navigator.product) === "ReactNative";
673
+ if (isReactNative) {
674
+ return {
675
+ type: "react-native"
676
+ };
677
+ }
678
+ return {
679
+ type: "unknown"
680
+ };
681
+ }
682
+
683
+ // src/core/fetcher/getFetchFn.ts
684
+ async function getFetchFn() {
685
+ if (RUNTIME.type === "node" && RUNTIME.parsedVersion != null && RUNTIME.parsedVersion >= 18) {
686
+ return fetch;
687
+ }
688
+ if (RUNTIME.type === "node") {
689
+ return (await import("node-fetch")).default;
690
+ }
691
+ if (typeof fetch == "function") {
692
+ return fetch;
693
+ }
694
+ return (await import("node-fetch")).default;
695
+ }
696
+
697
+ // src/core/fetcher/getRequestBody.ts
698
+ async function getRequestBody({ body, type }) {
699
+ if (type.includes("json")) {
700
+ return toJson(body);
701
+ } else {
702
+ return body;
703
+ }
704
+ }
705
+
706
+ // src/core/fetcher/stream-wrappers/chooseStreamWrapper.ts
707
+ async function chooseStreamWrapper(responseBody) {
708
+ if (RUNTIME.type === "node" && RUNTIME.parsedVersion != null && RUNTIME.parsedVersion >= 18) {
709
+ return new (await Promise.resolve().then(() => (init_Node18UniversalStreamWrapper(), Node18UniversalStreamWrapper_exports))).Node18UniversalStreamWrapper(
710
+ responseBody
711
+ );
712
+ } else if (RUNTIME.type !== "node" && typeof fetch === "function") {
713
+ return new (await Promise.resolve().then(() => (init_UndiciStreamWrapper(), UndiciStreamWrapper_exports))).UndiciStreamWrapper(responseBody);
714
+ } else {
715
+ return new (await Promise.resolve().then(() => (init_NodePre18StreamWrapper(), NodePre18StreamWrapper_exports))).NodePre18StreamWrapper(responseBody);
716
+ }
717
+ }
718
+
719
+ // src/core/fetcher/getResponseBody.ts
720
+ async function getResponseBody(response, responseType) {
721
+ if (response.body != null && responseType === "blob") {
722
+ return await response.blob();
723
+ } else if (response.body != null && responseType === "arrayBuffer") {
724
+ return await response.arrayBuffer();
725
+ } else if (response.body != null && responseType === "sse") {
726
+ return response.body;
727
+ } else if (response.body != null && responseType === "streaming") {
728
+ return chooseStreamWrapper(response.body);
729
+ } else if (response.body != null && responseType === "text") {
730
+ return await response.text();
731
+ } else {
732
+ const text = await response.text();
733
+ if (text.length > 0) {
734
+ try {
735
+ let responseBody = JSON.parse(text);
736
+ return responseBody;
737
+ } catch (err) {
738
+ return {
739
+ ok: false,
740
+ error: {
741
+ reason: "non-json",
742
+ statusCode: response.status,
743
+ rawBody: text
744
+ }
745
+ };
746
+ }
747
+ } else {
748
+ return void 0;
749
+ }
750
+ }
751
+ }
752
+
753
+ // src/core/fetcher/signals.ts
754
+ var TIMEOUT = "timeout";
755
+ function getTimeoutSignal(timeoutMs) {
756
+ const controller = new AbortController();
757
+ const abortId = setTimeout(() => controller.abort(TIMEOUT), timeoutMs);
758
+ return { signal: controller.signal, abortId };
759
+ }
760
+ function anySignal(...args) {
761
+ const signals = args.length === 1 && Array.isArray(args[0]) ? args[0] : args;
762
+ const controller = new AbortController();
763
+ for (const signal of signals) {
764
+ if (signal.aborted) {
765
+ controller.abort(signal == null ? void 0 : signal.reason);
766
+ break;
767
+ }
768
+ signal.addEventListener("abort", () => controller.abort(signal == null ? void 0 : signal.reason), {
769
+ signal: controller.signal
770
+ });
771
+ }
772
+ return controller.signal;
773
+ }
774
+
775
+ // src/core/fetcher/makeRequest.ts
776
+ var makeRequest = async (fetchFn, url, method, headers, requestBody, timeoutMs, abortSignal, withCredentials, duplex) => {
777
+ const signals = [];
778
+ let timeoutAbortId = void 0;
779
+ if (timeoutMs != null) {
780
+ const { signal, abortId } = getTimeoutSignal(timeoutMs);
781
+ timeoutAbortId = abortId;
782
+ signals.push(signal);
783
+ }
784
+ if (abortSignal != null) {
785
+ signals.push(abortSignal);
786
+ }
787
+ let newSignals = anySignal(signals);
788
+ const response = await fetchFn(url, {
789
+ method,
790
+ headers,
791
+ body: requestBody,
792
+ signal: newSignals,
793
+ credentials: withCredentials ? "include" : void 0,
794
+ // @ts-ignore
795
+ duplex
796
+ });
797
+ if (timeoutAbortId != null) {
798
+ clearTimeout(timeoutAbortId);
799
+ }
800
+ return response;
801
+ };
802
+
803
+ // src/core/fetcher/requestWithRetries.ts
804
+ var INITIAL_RETRY_DELAY = 1e3;
805
+ var MAX_RETRY_DELAY = 6e4;
806
+ var DEFAULT_MAX_RETRIES = 2;
807
+ var JITTER_FACTOR = 0.2;
808
+ function addJitter(delay) {
809
+ const jitterMultiplier = 1 + (Math.random() * 2 - 1) * JITTER_FACTOR;
810
+ return delay * jitterMultiplier;
811
+ }
812
+ async function requestWithRetries(requestFn, maxRetries = DEFAULT_MAX_RETRIES) {
813
+ let response = await requestFn();
814
+ for (let i = 0; i < maxRetries; ++i) {
815
+ if ([408, 429].includes(response.status) || response.status >= 500) {
816
+ const baseDelay = Math.min(INITIAL_RETRY_DELAY * Math.pow(2, i), MAX_RETRY_DELAY);
817
+ const delayWithJitter = addJitter(baseDelay);
818
+ await new Promise((resolve) => setTimeout(resolve, delayWithJitter));
819
+ response = await requestFn();
820
+ } else {
821
+ break;
822
+ }
823
+ }
824
+ return response;
825
+ }
826
+
827
+ // src/core/fetcher/Fetcher.ts
828
+ async function fetcherImpl(args) {
829
+ const headers = {};
830
+ if (args.body !== void 0 && args.contentType != null) {
831
+ headers["Content-Type"] = args.contentType;
832
+ }
833
+ if (args.headers != null) {
834
+ for (const [key, value] of Object.entries(args.headers)) {
835
+ if (value != null) {
836
+ headers[key] = value;
837
+ }
838
+ }
839
+ }
840
+ const url = createRequestUrl(args.url, args.queryParameters);
841
+ const requestBody = await getRequestBody({
842
+ body: args.body,
843
+ type: args.requestType === "json" ? "json" : "other"
844
+ });
845
+ const fetchFn = await getFetchFn();
846
+ try {
847
+ const response = await requestWithRetries(
848
+ async () => makeRequest(
849
+ fetchFn,
850
+ url,
851
+ args.method,
852
+ headers,
853
+ requestBody,
854
+ args.timeoutMs,
855
+ args.abortSignal,
856
+ args.withCredentials,
857
+ args.duplex
858
+ ),
859
+ args.maxRetries
860
+ );
861
+ const responseBody = await getResponseBody(response, args.responseType);
862
+ if (response.status >= 200 && response.status < 400) {
863
+ return {
864
+ ok: true,
865
+ body: responseBody,
866
+ headers: response.headers
867
+ };
868
+ } else {
869
+ return {
870
+ ok: false,
871
+ error: {
872
+ reason: "status-code",
873
+ statusCode: response.status,
874
+ body: responseBody
875
+ }
876
+ };
877
+ }
878
+ } catch (error) {
879
+ if (args.abortSignal != null && args.abortSignal.aborted) {
880
+ return {
881
+ ok: false,
882
+ error: {
883
+ reason: "unknown",
884
+ errorMessage: "The user aborted a request"
885
+ }
886
+ };
887
+ } else if (error instanceof Error && error.name === "AbortError") {
888
+ return {
889
+ ok: false,
890
+ error: {
891
+ reason: "timeout"
892
+ }
893
+ };
894
+ } else if (error instanceof Error) {
895
+ return {
896
+ ok: false,
897
+ error: {
898
+ reason: "unknown",
899
+ errorMessage: error.message
900
+ }
901
+ };
902
+ }
903
+ return {
904
+ ok: false,
905
+ error: {
906
+ reason: "unknown",
907
+ errorMessage: toJson(error)
908
+ }
909
+ };
910
+ }
911
+ }
912
+ var fetcher = fetcherImpl;
913
+
914
+ // src/core/fetcher/Supplier.ts
915
+ var Supplier = {
916
+ get: async (supplier) => {
917
+ if (typeof supplier === "function") {
918
+ return supplier();
919
+ } else {
920
+ return supplier;
921
+ }
922
+ }
923
+ };
924
+
925
+ // src/core/schemas/index.ts
926
+ var schemas_exports = {};
927
+ __export(schemas_exports, {
928
+ JsonError: () => JsonError,
929
+ ParseError: () => ParseError,
930
+ any: () => any,
931
+ bigint: () => bigint,
932
+ boolean: () => boolean,
933
+ booleanLiteral: () => booleanLiteral,
934
+ date: () => date,
935
+ discriminant: () => discriminant,
936
+ enum_: () => enum_,
937
+ getObjectLikeUtils: () => getObjectLikeUtils,
938
+ getObjectUtils: () => getObjectUtils,
939
+ getSchemaUtils: () => getSchemaUtils,
940
+ isProperty: () => isProperty,
941
+ lazy: () => lazy,
942
+ lazyObject: () => lazyObject,
943
+ list: () => list,
944
+ number: () => number,
945
+ object: () => object,
946
+ objectWithoutOptionalProperties: () => objectWithoutOptionalProperties,
947
+ optional: () => optional,
948
+ property: () => property,
949
+ record: () => record,
950
+ set: () => set,
951
+ string: () => string,
952
+ stringLiteral: () => stringLiteral,
953
+ transform: () => transform,
954
+ undiscriminatedUnion: () => undiscriminatedUnion,
955
+ union: () => union,
956
+ unknown: () => unknown,
957
+ withParsedProperties: () => withParsedProperties
958
+ });
959
+
960
+ // src/core/schemas/Schema.ts
961
+ var SchemaType = {
962
+ BIGINT: "bigint",
963
+ DATE: "date",
964
+ ENUM: "enum",
965
+ LIST: "list",
966
+ STRING_LITERAL: "stringLiteral",
967
+ BOOLEAN_LITERAL: "booleanLiteral",
968
+ OBJECT: "object",
969
+ ANY: "any",
970
+ BOOLEAN: "boolean",
971
+ NUMBER: "number",
972
+ STRING: "string",
973
+ UNKNOWN: "unknown",
974
+ RECORD: "record",
975
+ SET: "set",
976
+ UNION: "union",
977
+ UNDISCRIMINATED_UNION: "undiscriminatedUnion",
978
+ NULLABLE: "nullable",
979
+ OPTIONAL: "optional",
980
+ OPTIONAL_NULLABLE: "optionalNullable"
981
+ };
982
+
983
+ // src/core/schemas/utils/getErrorMessageForIncorrectType.ts
984
+ function getErrorMessageForIncorrectType(value, expectedType) {
985
+ return `Expected ${expectedType}. Received ${getTypeAsString(value)}.`;
986
+ }
987
+ function getTypeAsString(value) {
988
+ if (Array.isArray(value)) {
989
+ return "list";
990
+ }
991
+ if (value === null) {
992
+ return "null";
993
+ }
994
+ if (value instanceof BigInt) {
995
+ return "BigInt";
996
+ }
997
+ switch (typeof value) {
998
+ case "string":
999
+ return `"${value}"`;
1000
+ case "bigint":
1001
+ case "number":
1002
+ case "boolean":
1003
+ case "undefined":
1004
+ return `${value}`;
1005
+ }
1006
+ return typeof value;
1007
+ }
1008
+
1009
+ // src/core/schemas/utils/maybeSkipValidation.ts
1010
+ function maybeSkipValidation(schema) {
1011
+ return {
1012
+ ...schema,
1013
+ json: transformAndMaybeSkipValidation(schema.json),
1014
+ parse: transformAndMaybeSkipValidation(schema.parse)
1015
+ };
1016
+ }
1017
+ function transformAndMaybeSkipValidation(transform2) {
1018
+ return (value, opts) => {
1019
+ const transformed = transform2(value, opts);
1020
+ const { skipValidation = false } = opts ?? {};
1021
+ if (!transformed.ok && skipValidation) {
1022
+ console.warn(
1023
+ [
1024
+ "Failed to validate.",
1025
+ ...transformed.errors.map(
1026
+ (error) => " - " + (error.path.length > 0 ? `${error.path.join(".")}: ${error.message}` : error.message)
1027
+ )
1028
+ ].join("\n")
1029
+ );
1030
+ return {
1031
+ ok: true,
1032
+ value
1033
+ };
1034
+ } else {
1035
+ return transformed;
1036
+ }
1037
+ };
1038
+ }
1039
+
1040
+ // src/core/schemas/builders/schema-utils/stringifyValidationErrors.ts
1041
+ function stringifyValidationError(error) {
1042
+ if (error.path.length === 0) {
1043
+ return error.message;
1044
+ }
1045
+ return `${error.path.join(" -> ")}: ${error.message}`;
1046
+ }
1047
+
1048
+ // src/core/schemas/builders/schema-utils/JsonError.ts
1049
+ var JsonError = class _JsonError extends Error {
1050
+ constructor(errors) {
1051
+ super(errors.map(stringifyValidationError).join("; "));
1052
+ this.errors = errors;
1053
+ Object.setPrototypeOf(this, _JsonError.prototype);
1054
+ }
1055
+ };
1056
+
1057
+ // src/core/schemas/builders/schema-utils/ParseError.ts
1058
+ var ParseError = class _ParseError extends Error {
1059
+ constructor(errors) {
1060
+ super(errors.map(stringifyValidationError).join("; "));
1061
+ this.errors = errors;
1062
+ Object.setPrototypeOf(this, _ParseError.prototype);
1063
+ }
1064
+ };
1065
+
1066
+ // src/core/schemas/builders/schema-utils/getSchemaUtils.ts
1067
+ function getSchemaUtils(schema) {
1068
+ return {
1069
+ nullable: () => nullable(schema),
1070
+ optional: () => optional(schema),
1071
+ optionalNullable: () => optionalNullable(schema),
1072
+ transform: (transformer) => transform(schema, transformer),
1073
+ parseOrThrow: (raw, opts) => {
1074
+ const parsed = schema.parse(raw, opts);
1075
+ if (parsed.ok) {
1076
+ return parsed.value;
1077
+ }
1078
+ throw new ParseError(parsed.errors);
1079
+ },
1080
+ jsonOrThrow: (parsed, opts) => {
1081
+ const raw = schema.json(parsed, opts);
1082
+ if (raw.ok) {
1083
+ return raw.value;
1084
+ }
1085
+ throw new JsonError(raw.errors);
1086
+ }
1087
+ };
1088
+ }
1089
+ function nullable(schema) {
1090
+ const baseSchema = {
1091
+ parse: (raw, opts) => {
1092
+ if (raw == null) {
1093
+ return {
1094
+ ok: true,
1095
+ value: null
1096
+ };
1097
+ }
1098
+ return schema.parse(raw, opts);
1099
+ },
1100
+ json: (parsed, opts) => {
1101
+ if (parsed == null) {
1102
+ return {
1103
+ ok: true,
1104
+ value: null
1105
+ };
1106
+ }
1107
+ return schema.json(parsed, opts);
1108
+ },
1109
+ getType: () => SchemaType.NULLABLE
1110
+ };
1111
+ return {
1112
+ ...baseSchema,
1113
+ ...getSchemaUtils(baseSchema)
1114
+ };
1115
+ }
1116
+ function optional(schema) {
1117
+ const baseSchema = {
1118
+ parse: (raw, opts) => {
1119
+ if (raw == null) {
1120
+ return {
1121
+ ok: true,
1122
+ value: void 0
1123
+ };
1124
+ }
1125
+ return schema.parse(raw, opts);
1126
+ },
1127
+ json: (parsed, opts) => {
1128
+ if ((opts == null ? void 0 : opts.omitUndefined) && parsed === void 0) {
1129
+ return {
1130
+ ok: true,
1131
+ value: void 0
1132
+ };
1133
+ }
1134
+ if (parsed == null) {
1135
+ return {
1136
+ ok: true,
1137
+ value: null
1138
+ };
1139
+ }
1140
+ return schema.json(parsed, opts);
1141
+ },
1142
+ getType: () => SchemaType.OPTIONAL
1143
+ };
1144
+ return {
1145
+ ...baseSchema,
1146
+ ...getSchemaUtils(baseSchema)
1147
+ };
1148
+ }
1149
+ function optionalNullable(schema) {
1150
+ const baseSchema = {
1151
+ parse: (raw, opts) => {
1152
+ if (raw === void 0) {
1153
+ return {
1154
+ ok: true,
1155
+ value: void 0
1156
+ };
1157
+ }
1158
+ if (raw === null) {
1159
+ return {
1160
+ ok: true,
1161
+ value: null
1162
+ };
1163
+ }
1164
+ return schema.parse(raw, opts);
1165
+ },
1166
+ json: (parsed, opts) => {
1167
+ if (parsed === void 0) {
1168
+ return {
1169
+ ok: true,
1170
+ value: void 0
1171
+ };
1172
+ }
1173
+ if (parsed === null) {
1174
+ return {
1175
+ ok: true,
1176
+ value: null
1177
+ };
1178
+ }
1179
+ return schema.json(parsed, opts);
1180
+ },
1181
+ getType: () => SchemaType.OPTIONAL_NULLABLE
1182
+ };
1183
+ return {
1184
+ ...baseSchema,
1185
+ ...getSchemaUtils(baseSchema)
1186
+ };
1187
+ }
1188
+ function transform(schema, transformer) {
1189
+ const baseSchema = {
1190
+ parse: (raw, opts) => {
1191
+ const parsed = schema.parse(raw, opts);
1192
+ if (!parsed.ok) {
1193
+ return parsed;
1194
+ }
1195
+ return {
1196
+ ok: true,
1197
+ value: transformer.transform(parsed.value)
1198
+ };
1199
+ },
1200
+ json: (transformed, opts) => {
1201
+ const parsed = transformer.untransform(transformed);
1202
+ return schema.json(parsed, opts);
1203
+ },
1204
+ getType: () => schema.getType()
1205
+ };
1206
+ return {
1207
+ ...baseSchema,
1208
+ ...getSchemaUtils(baseSchema)
1209
+ };
1210
+ }
1211
+
1212
+ // src/core/schemas/builders/bigint/bigint.ts
1213
+ function bigint() {
1214
+ const baseSchema = {
1215
+ parse: (raw, { breadcrumbsPrefix = [] } = {}) => {
1216
+ if (typeof raw === "bigint") {
1217
+ return {
1218
+ ok: true,
1219
+ value: raw
1220
+ };
1221
+ }
1222
+ if (typeof raw === "number") {
1223
+ return {
1224
+ ok: true,
1225
+ value: BigInt(raw)
1226
+ };
1227
+ }
1228
+ return {
1229
+ ok: false,
1230
+ errors: [
1231
+ {
1232
+ path: breadcrumbsPrefix,
1233
+ message: getErrorMessageForIncorrectType(raw, "bigint | number")
1234
+ }
1235
+ ]
1236
+ };
1237
+ },
1238
+ json: (bigint2, { breadcrumbsPrefix = [] } = {}) => {
1239
+ if (typeof bigint2 !== "bigint") {
1240
+ return {
1241
+ ok: false,
1242
+ errors: [
1243
+ {
1244
+ path: breadcrumbsPrefix,
1245
+ message: getErrorMessageForIncorrectType(bigint2, "bigint")
1246
+ }
1247
+ ]
1248
+ };
1249
+ }
1250
+ return {
1251
+ ok: true,
1252
+ value: bigint2
1253
+ };
1254
+ },
1255
+ getType: () => SchemaType.BIGINT
1256
+ };
1257
+ return {
1258
+ ...maybeSkipValidation(baseSchema),
1259
+ ...getSchemaUtils(baseSchema)
1260
+ };
1261
+ }
1262
+
1263
+ // src/core/schemas/builders/date/date.ts
1264
+ var ISO_8601_REGEX = /^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([.,]\d+(?!:))?)?(\17[0-5]\d([.,]\d+)?)?([zZ]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;
1265
+ function date() {
1266
+ const baseSchema = {
1267
+ parse: (raw, { breadcrumbsPrefix = [] } = {}) => {
1268
+ if (typeof raw !== "string") {
1269
+ return {
1270
+ ok: false,
1271
+ errors: [
1272
+ {
1273
+ path: breadcrumbsPrefix,
1274
+ message: getErrorMessageForIncorrectType(raw, "string")
1275
+ }
1276
+ ]
1277
+ };
1278
+ }
1279
+ if (!ISO_8601_REGEX.test(raw)) {
1280
+ return {
1281
+ ok: false,
1282
+ errors: [
1283
+ {
1284
+ path: breadcrumbsPrefix,
1285
+ message: getErrorMessageForIncorrectType(raw, "ISO 8601 date string")
1286
+ }
1287
+ ]
1288
+ };
1289
+ }
1290
+ return {
1291
+ ok: true,
1292
+ value: new Date(raw)
1293
+ };
1294
+ },
1295
+ json: (date2, { breadcrumbsPrefix = [] } = {}) => {
1296
+ if (date2 instanceof Date) {
1297
+ return {
1298
+ ok: true,
1299
+ value: date2.toISOString()
1300
+ };
1301
+ } else {
1302
+ return {
1303
+ ok: false,
1304
+ errors: [
1305
+ {
1306
+ path: breadcrumbsPrefix,
1307
+ message: getErrorMessageForIncorrectType(date2, "Date object")
1308
+ }
1309
+ ]
1310
+ };
1311
+ }
1312
+ },
1313
+ getType: () => SchemaType.DATE
1314
+ };
1315
+ return {
1316
+ ...maybeSkipValidation(baseSchema),
1317
+ ...getSchemaUtils(baseSchema)
1318
+ };
1319
+ }
1320
+
1321
+ // src/core/schemas/utils/createIdentitySchemaCreator.ts
1322
+ function createIdentitySchemaCreator(schemaType, validate) {
1323
+ return () => {
1324
+ const baseSchema = {
1325
+ parse: validate,
1326
+ json: validate,
1327
+ getType: () => schemaType
1328
+ };
1329
+ return {
1330
+ ...maybeSkipValidation(baseSchema),
1331
+ ...getSchemaUtils(baseSchema)
1332
+ };
1333
+ };
1334
+ }
1335
+
1336
+ // src/core/schemas/builders/enum/enum.ts
1337
+ function enum_(values) {
1338
+ const validValues = new Set(values);
1339
+ const schemaCreator = createIdentitySchemaCreator(
1340
+ SchemaType.ENUM,
1341
+ (value, { allowUnrecognizedEnumValues, breadcrumbsPrefix = [] } = {}) => {
1342
+ if (typeof value !== "string") {
1343
+ return {
1344
+ ok: false,
1345
+ errors: [
1346
+ {
1347
+ path: breadcrumbsPrefix,
1348
+ message: getErrorMessageForIncorrectType(value, "string")
1349
+ }
1350
+ ]
1351
+ };
1352
+ }
1353
+ if (!validValues.has(value) && !allowUnrecognizedEnumValues) {
1354
+ return {
1355
+ ok: false,
1356
+ errors: [
1357
+ {
1358
+ path: breadcrumbsPrefix,
1359
+ message: getErrorMessageForIncorrectType(value, "enum")
1360
+ }
1361
+ ]
1362
+ };
1363
+ }
1364
+ return {
1365
+ ok: true,
1366
+ value
1367
+ };
1368
+ }
1369
+ );
1370
+ return schemaCreator();
1371
+ }
1372
+
1373
+ // src/core/schemas/builders/lazy/lazy.ts
1374
+ function lazy(getter) {
1375
+ const baseSchema = constructLazyBaseSchema(getter);
1376
+ return {
1377
+ ...baseSchema,
1378
+ ...getSchemaUtils(baseSchema)
1379
+ };
1380
+ }
1381
+ function constructLazyBaseSchema(getter) {
1382
+ return {
1383
+ parse: (raw, opts) => getMemoizedSchema(getter).parse(raw, opts),
1384
+ json: (parsed, opts) => getMemoizedSchema(getter).json(parsed, opts),
1385
+ getType: () => getMemoizedSchema(getter).getType()
1386
+ };
1387
+ }
1388
+ function getMemoizedSchema(getter) {
1389
+ const castedGetter = getter;
1390
+ if (castedGetter.__zurg_memoized == null) {
1391
+ castedGetter.__zurg_memoized = getter();
1392
+ }
1393
+ return castedGetter.__zurg_memoized;
1394
+ }
1395
+
1396
+ // src/core/schemas/utils/entries.ts
1397
+ function entries(object2) {
1398
+ return Object.entries(object2);
1399
+ }
1400
+
1401
+ // src/core/schemas/utils/filterObject.ts
1402
+ function filterObject(obj, keysToInclude) {
1403
+ const keysToIncludeSet = new Set(keysToInclude);
1404
+ return Object.entries(obj).reduce(
1405
+ (acc, [key, value]) => {
1406
+ if (keysToIncludeSet.has(key)) {
1407
+ acc[key] = value;
1408
+ }
1409
+ return acc;
1410
+ },
1411
+ {}
1412
+ );
1413
+ }
1414
+
1415
+ // src/core/schemas/utils/isPlainObject.ts
1416
+ function isPlainObject(value) {
1417
+ if (typeof value !== "object" || value === null) {
1418
+ return false;
1419
+ }
1420
+ if (Object.getPrototypeOf(value) === null) {
1421
+ return true;
1422
+ }
1423
+ let proto = value;
1424
+ while (Object.getPrototypeOf(proto) !== null) {
1425
+ proto = Object.getPrototypeOf(proto);
1426
+ }
1427
+ return Object.getPrototypeOf(value) === proto;
1428
+ }
1429
+
1430
+ // src/core/schemas/utils/keys.ts
1431
+ function keys(object2) {
1432
+ return Object.keys(object2);
1433
+ }
1434
+
1435
+ // src/core/schemas/utils/partition.ts
1436
+ function partition(items, predicate) {
1437
+ const trueItems = [], falseItems = [];
1438
+ for (const item of items) {
1439
+ if (predicate(item)) {
1440
+ trueItems.push(item);
1441
+ } else {
1442
+ falseItems.push(item);
1443
+ }
1444
+ }
1445
+ return [trueItems, falseItems];
1446
+ }
1447
+
1448
+ // src/core/schemas/builders/object-like/getObjectLikeUtils.ts
1449
+ function getObjectLikeUtils(schema) {
1450
+ return {
1451
+ withParsedProperties: (properties) => withParsedProperties(schema, properties)
1452
+ };
1453
+ }
1454
+ function withParsedProperties(objectLike, properties) {
1455
+ const objectSchema = {
1456
+ parse: (raw, opts) => {
1457
+ const parsedObject = objectLike.parse(raw, opts);
1458
+ if (!parsedObject.ok) {
1459
+ return parsedObject;
1460
+ }
1461
+ const additionalProperties = Object.entries(properties).reduce(
1462
+ (processed, [key, value]) => {
1463
+ return {
1464
+ ...processed,
1465
+ [key]: typeof value === "function" ? value(parsedObject.value) : value
1466
+ };
1467
+ },
1468
+ {}
1469
+ );
1470
+ return {
1471
+ ok: true,
1472
+ value: {
1473
+ ...parsedObject.value,
1474
+ ...additionalProperties
1475
+ }
1476
+ };
1477
+ },
1478
+ json: (parsed, opts) => {
1479
+ if (!isPlainObject(parsed)) {
1480
+ return {
1481
+ ok: false,
1482
+ errors: [
1483
+ {
1484
+ path: (opts == null ? void 0 : opts.breadcrumbsPrefix) ?? [],
1485
+ message: getErrorMessageForIncorrectType(parsed, "object")
1486
+ }
1487
+ ]
1488
+ };
1489
+ }
1490
+ const addedPropertyKeys = new Set(Object.keys(properties));
1491
+ const parsedWithoutAddedProperties = filterObject(
1492
+ parsed,
1493
+ Object.keys(parsed).filter((key) => !addedPropertyKeys.has(key))
1494
+ );
1495
+ return objectLike.json(parsedWithoutAddedProperties, opts);
1496
+ },
1497
+ getType: () => objectLike.getType()
1498
+ };
1499
+ return {
1500
+ ...objectSchema,
1501
+ ...getSchemaUtils(objectSchema),
1502
+ ...getObjectLikeUtils(objectSchema)
1503
+ };
1504
+ }
1505
+
1506
+ // src/core/schemas/builders/object/property.ts
1507
+ function property(rawKey, valueSchema) {
1508
+ return {
1509
+ rawKey,
1510
+ valueSchema,
1511
+ isProperty: true
1512
+ };
1513
+ }
1514
+ function isProperty(maybeProperty) {
1515
+ return maybeProperty.isProperty;
1516
+ }
1517
+
1518
+ // src/core/schemas/builders/object/object.ts
1519
+ function object(schemas) {
1520
+ const baseSchema = {
1521
+ _getRawProperties: () => Object.entries(schemas).map(
1522
+ ([parsedKey, propertySchema]) => isProperty(propertySchema) ? propertySchema.rawKey : parsedKey
1523
+ ),
1524
+ _getParsedProperties: () => keys(schemas),
1525
+ parse: (raw, opts) => {
1526
+ const rawKeyToProperty = {};
1527
+ const requiredKeys = [];
1528
+ for (const [parsedKey, schemaOrObjectProperty] of entries(schemas)) {
1529
+ const rawKey = isProperty(schemaOrObjectProperty) ? schemaOrObjectProperty.rawKey : parsedKey;
1530
+ const valueSchema = isProperty(schemaOrObjectProperty) ? schemaOrObjectProperty.valueSchema : schemaOrObjectProperty;
1531
+ const property2 = {
1532
+ rawKey,
1533
+ parsedKey,
1534
+ valueSchema
1535
+ };
1536
+ rawKeyToProperty[rawKey] = property2;
1537
+ if (isSchemaRequired(valueSchema)) {
1538
+ requiredKeys.push(rawKey);
1539
+ }
1540
+ }
1541
+ return validateAndTransformObject({
1542
+ value: raw,
1543
+ requiredKeys,
1544
+ getProperty: (rawKey) => {
1545
+ const property2 = rawKeyToProperty[rawKey];
1546
+ if (property2 == null) {
1547
+ return void 0;
1548
+ }
1549
+ return {
1550
+ transformedKey: property2.parsedKey,
1551
+ transform: (propertyValue) => property2.valueSchema.parse(propertyValue, {
1552
+ ...opts,
1553
+ breadcrumbsPrefix: [...(opts == null ? void 0 : opts.breadcrumbsPrefix) ?? [], rawKey]
1554
+ })
1555
+ };
1556
+ },
1557
+ unrecognizedObjectKeys: opts == null ? void 0 : opts.unrecognizedObjectKeys,
1558
+ skipValidation: opts == null ? void 0 : opts.skipValidation,
1559
+ breadcrumbsPrefix: opts == null ? void 0 : opts.breadcrumbsPrefix,
1560
+ omitUndefined: opts == null ? void 0 : opts.omitUndefined
1561
+ });
1562
+ },
1563
+ json: (parsed, opts) => {
1564
+ const requiredKeys = [];
1565
+ for (const [parsedKey, schemaOrObjectProperty] of entries(schemas)) {
1566
+ const valueSchema = isProperty(schemaOrObjectProperty) ? schemaOrObjectProperty.valueSchema : schemaOrObjectProperty;
1567
+ if (isSchemaRequired(valueSchema)) {
1568
+ requiredKeys.push(parsedKey);
1569
+ }
1570
+ }
1571
+ return validateAndTransformObject({
1572
+ value: parsed,
1573
+ requiredKeys,
1574
+ getProperty: (parsedKey) => {
1575
+ const property2 = schemas[parsedKey];
1576
+ if (property2 == null) {
1577
+ return void 0;
1578
+ }
1579
+ if (isProperty(property2)) {
1580
+ return {
1581
+ transformedKey: property2.rawKey,
1582
+ transform: (propertyValue) => property2.valueSchema.json(propertyValue, {
1583
+ ...opts,
1584
+ breadcrumbsPrefix: [...(opts == null ? void 0 : opts.breadcrumbsPrefix) ?? [], parsedKey]
1585
+ })
1586
+ };
1587
+ } else {
1588
+ return {
1589
+ transformedKey: parsedKey,
1590
+ transform: (propertyValue) => property2.json(propertyValue, {
1591
+ ...opts,
1592
+ breadcrumbsPrefix: [...(opts == null ? void 0 : opts.breadcrumbsPrefix) ?? [], parsedKey]
1593
+ })
1594
+ };
1595
+ }
1596
+ },
1597
+ unrecognizedObjectKeys: opts == null ? void 0 : opts.unrecognizedObjectKeys,
1598
+ skipValidation: opts == null ? void 0 : opts.skipValidation,
1599
+ breadcrumbsPrefix: opts == null ? void 0 : opts.breadcrumbsPrefix,
1600
+ omitUndefined: opts == null ? void 0 : opts.omitUndefined
1601
+ });
1602
+ },
1603
+ getType: () => SchemaType.OBJECT
1604
+ };
1605
+ return {
1606
+ ...maybeSkipValidation(baseSchema),
1607
+ ...getSchemaUtils(baseSchema),
1608
+ ...getObjectLikeUtils(baseSchema),
1609
+ ...getObjectUtils(baseSchema)
1610
+ };
1611
+ }
1612
+ function validateAndTransformObject({
1613
+ value,
1614
+ requiredKeys,
1615
+ getProperty,
1616
+ unrecognizedObjectKeys = "fail",
1617
+ skipValidation = false,
1618
+ breadcrumbsPrefix = []
1619
+ }) {
1620
+ if (!isPlainObject(value)) {
1621
+ return {
1622
+ ok: false,
1623
+ errors: [
1624
+ {
1625
+ path: breadcrumbsPrefix,
1626
+ message: getErrorMessageForIncorrectType(value, "object")
1627
+ }
1628
+ ]
1629
+ };
1630
+ }
1631
+ const missingRequiredKeys = new Set(requiredKeys);
1632
+ const errors = [];
1633
+ const transformed = {};
1634
+ for (const [preTransformedKey, preTransformedItemValue] of Object.entries(value)) {
1635
+ const property2 = getProperty(preTransformedKey);
1636
+ if (property2 != null) {
1637
+ missingRequiredKeys.delete(preTransformedKey);
1638
+ const value2 = property2.transform(preTransformedItemValue);
1639
+ if (value2.ok) {
1640
+ transformed[property2.transformedKey] = value2.value;
1641
+ } else {
1642
+ transformed[preTransformedKey] = preTransformedItemValue;
1643
+ errors.push(...value2.errors);
1644
+ }
1645
+ } else {
1646
+ switch (unrecognizedObjectKeys) {
1647
+ case "fail":
1648
+ errors.push({
1649
+ path: [...breadcrumbsPrefix, preTransformedKey],
1650
+ message: `Unexpected key "${preTransformedKey}"`
1651
+ });
1652
+ break;
1653
+ case "strip":
1654
+ break;
1655
+ case "passthrough":
1656
+ transformed[preTransformedKey] = preTransformedItemValue;
1657
+ break;
1658
+ }
1659
+ }
1660
+ }
1661
+ errors.push(
1662
+ ...requiredKeys.filter((key) => missingRequiredKeys.has(key)).map((key) => ({
1663
+ path: breadcrumbsPrefix,
1664
+ message: `Missing required key "${key}"`
1665
+ }))
1666
+ );
1667
+ if (errors.length === 0 || skipValidation) {
1668
+ return {
1669
+ ok: true,
1670
+ value: transformed
1671
+ };
1672
+ } else {
1673
+ return {
1674
+ ok: false,
1675
+ errors
1676
+ };
1677
+ }
1678
+ }
1679
+ function getObjectUtils(schema) {
1680
+ return {
1681
+ extend: (extension) => {
1682
+ const baseSchema = {
1683
+ _getParsedProperties: () => [...schema._getParsedProperties(), ...extension._getParsedProperties()],
1684
+ _getRawProperties: () => [...schema._getRawProperties(), ...extension._getRawProperties()],
1685
+ parse: (raw, opts) => {
1686
+ return validateAndTransformExtendedObject({
1687
+ extensionKeys: extension._getRawProperties(),
1688
+ value: raw,
1689
+ transformBase: (rawBase) => schema.parse(rawBase, opts),
1690
+ transformExtension: (rawExtension) => extension.parse(rawExtension, opts)
1691
+ });
1692
+ },
1693
+ json: (parsed, opts) => {
1694
+ return validateAndTransformExtendedObject({
1695
+ extensionKeys: extension._getParsedProperties(),
1696
+ value: parsed,
1697
+ transformBase: (parsedBase) => schema.json(parsedBase, opts),
1698
+ transformExtension: (parsedExtension) => extension.json(parsedExtension, opts)
1699
+ });
1700
+ },
1701
+ getType: () => SchemaType.OBJECT
1702
+ };
1703
+ return {
1704
+ ...baseSchema,
1705
+ ...getSchemaUtils(baseSchema),
1706
+ ...getObjectLikeUtils(baseSchema),
1707
+ ...getObjectUtils(baseSchema)
1708
+ };
1709
+ },
1710
+ passthrough: () => {
1711
+ const baseSchema = {
1712
+ _getParsedProperties: () => schema._getParsedProperties(),
1713
+ _getRawProperties: () => schema._getRawProperties(),
1714
+ parse: (raw, opts) => {
1715
+ const transformed = schema.parse(raw, { ...opts, unrecognizedObjectKeys: "passthrough" });
1716
+ if (!transformed.ok) {
1717
+ return transformed;
1718
+ }
1719
+ return {
1720
+ ok: true,
1721
+ value: {
1722
+ ...raw,
1723
+ ...transformed.value
1724
+ }
1725
+ };
1726
+ },
1727
+ json: (parsed, opts) => {
1728
+ const transformed = schema.json(parsed, { ...opts, unrecognizedObjectKeys: "passthrough" });
1729
+ if (!transformed.ok) {
1730
+ return transformed;
1731
+ }
1732
+ return {
1733
+ ok: true,
1734
+ value: {
1735
+ ...parsed,
1736
+ ...transformed.value
1737
+ }
1738
+ };
1739
+ },
1740
+ getType: () => SchemaType.OBJECT
1741
+ };
1742
+ return {
1743
+ ...baseSchema,
1744
+ ...getSchemaUtils(baseSchema),
1745
+ ...getObjectLikeUtils(baseSchema),
1746
+ ...getObjectUtils(baseSchema)
1747
+ };
1748
+ }
1749
+ };
1750
+ }
1751
+ function validateAndTransformExtendedObject({
1752
+ extensionKeys,
1753
+ value,
1754
+ transformBase,
1755
+ transformExtension
1756
+ }) {
1757
+ const extensionPropertiesSet = new Set(extensionKeys);
1758
+ const [extensionProperties, baseProperties] = partition(
1759
+ keys(value),
1760
+ (key) => extensionPropertiesSet.has(key)
1761
+ );
1762
+ const transformedBase = transformBase(filterObject(value, baseProperties));
1763
+ const transformedExtension = transformExtension(filterObject(value, extensionProperties));
1764
+ if (transformedBase.ok && transformedExtension.ok) {
1765
+ return {
1766
+ ok: true,
1767
+ value: {
1768
+ ...transformedBase.value,
1769
+ ...transformedExtension.value
1770
+ }
1771
+ };
1772
+ } else {
1773
+ return {
1774
+ ok: false,
1775
+ errors: [
1776
+ ...transformedBase.ok ? [] : transformedBase.errors,
1777
+ ...transformedExtension.ok ? [] : transformedExtension.errors
1778
+ ]
1779
+ };
1780
+ }
1781
+ }
1782
+ function isSchemaRequired(schema) {
1783
+ return !isSchemaOptional(schema);
1784
+ }
1785
+ function isSchemaOptional(schema) {
1786
+ switch (schema.getType()) {
1787
+ case SchemaType.ANY:
1788
+ case SchemaType.UNKNOWN:
1789
+ case SchemaType.OPTIONAL:
1790
+ case SchemaType.OPTIONAL_NULLABLE:
1791
+ return true;
1792
+ default:
1793
+ return false;
1794
+ }
1795
+ }
1796
+
1797
+ // src/core/schemas/builders/object/objectWithoutOptionalProperties.ts
1798
+ function objectWithoutOptionalProperties(schemas) {
1799
+ return object(schemas);
1800
+ }
1801
+
1802
+ // src/core/schemas/builders/lazy/lazyObject.ts
1803
+ function lazyObject(getter) {
1804
+ const baseSchema = {
1805
+ ...constructLazyBaseSchema(getter),
1806
+ _getRawProperties: () => getMemoizedSchema(getter)._getRawProperties(),
1807
+ _getParsedProperties: () => getMemoizedSchema(getter)._getParsedProperties()
1808
+ };
1809
+ return {
1810
+ ...baseSchema,
1811
+ ...getSchemaUtils(baseSchema),
1812
+ ...getObjectLikeUtils(baseSchema),
1813
+ ...getObjectUtils(baseSchema)
1814
+ };
1815
+ }
1816
+
1817
+ // src/core/schemas/builders/list/list.ts
1818
+ function list(schema) {
1819
+ const baseSchema = {
1820
+ parse: (raw, opts) => validateAndTransformArray(
1821
+ raw,
1822
+ (item, index) => schema.parse(item, {
1823
+ ...opts,
1824
+ breadcrumbsPrefix: [...(opts == null ? void 0 : opts.breadcrumbsPrefix) ?? [], `[${index}]`]
1825
+ })
1826
+ ),
1827
+ json: (parsed, opts) => validateAndTransformArray(
1828
+ parsed,
1829
+ (item, index) => schema.json(item, {
1830
+ ...opts,
1831
+ breadcrumbsPrefix: [...(opts == null ? void 0 : opts.breadcrumbsPrefix) ?? [], `[${index}]`]
1832
+ })
1833
+ ),
1834
+ getType: () => SchemaType.LIST
1835
+ };
1836
+ return {
1837
+ ...maybeSkipValidation(baseSchema),
1838
+ ...getSchemaUtils(baseSchema)
1839
+ };
1840
+ }
1841
+ function validateAndTransformArray(value, transformItem) {
1842
+ if (!Array.isArray(value)) {
1843
+ return {
1844
+ ok: false,
1845
+ errors: [
1846
+ {
1847
+ message: getErrorMessageForIncorrectType(value, "list"),
1848
+ path: []
1849
+ }
1850
+ ]
1851
+ };
1852
+ }
1853
+ const maybeValidItems = value.map((item, index) => transformItem(item, index));
1854
+ return maybeValidItems.reduce(
1855
+ (acc, item) => {
1856
+ if (acc.ok && item.ok) {
1857
+ return {
1858
+ ok: true,
1859
+ value: [...acc.value, item.value]
1860
+ };
1861
+ }
1862
+ const errors = [];
1863
+ if (!acc.ok) {
1864
+ errors.push(...acc.errors);
1865
+ }
1866
+ if (!item.ok) {
1867
+ errors.push(...item.errors);
1868
+ }
1869
+ return {
1870
+ ok: false,
1871
+ errors
1872
+ };
1873
+ },
1874
+ { ok: true, value: [] }
1875
+ );
1876
+ }
1877
+
1878
+ // src/core/schemas/builders/literals/stringLiteral.ts
1879
+ function stringLiteral(literal) {
1880
+ const schemaCreator = createIdentitySchemaCreator(
1881
+ SchemaType.STRING_LITERAL,
1882
+ (value, { breadcrumbsPrefix = [] } = {}) => {
1883
+ if (value === literal) {
1884
+ return {
1885
+ ok: true,
1886
+ value: literal
1887
+ };
1888
+ } else {
1889
+ return {
1890
+ ok: false,
1891
+ errors: [
1892
+ {
1893
+ path: breadcrumbsPrefix,
1894
+ message: getErrorMessageForIncorrectType(value, `"${literal}"`)
1895
+ }
1896
+ ]
1897
+ };
1898
+ }
1899
+ }
1900
+ );
1901
+ return schemaCreator();
1902
+ }
1903
+
1904
+ // src/core/schemas/builders/literals/booleanLiteral.ts
1905
+ function booleanLiteral(literal) {
1906
+ const schemaCreator = createIdentitySchemaCreator(
1907
+ SchemaType.BOOLEAN_LITERAL,
1908
+ (value, { breadcrumbsPrefix = [] } = {}) => {
1909
+ if (value === literal) {
1910
+ return {
1911
+ ok: true,
1912
+ value: literal
1913
+ };
1914
+ } else {
1915
+ return {
1916
+ ok: false,
1917
+ errors: [
1918
+ {
1919
+ path: breadcrumbsPrefix,
1920
+ message: getErrorMessageForIncorrectType(value, `${literal.toString()}`)
1921
+ }
1922
+ ]
1923
+ };
1924
+ }
1925
+ }
1926
+ );
1927
+ return schemaCreator();
1928
+ }
1929
+
1930
+ // src/core/schemas/builders/primitives/any.ts
1931
+ var any = createIdentitySchemaCreator(SchemaType.ANY, (value) => ({ ok: true, value }));
1932
+
1933
+ // src/core/schemas/builders/primitives/boolean.ts
1934
+ var boolean = createIdentitySchemaCreator(
1935
+ SchemaType.BOOLEAN,
1936
+ (value, { breadcrumbsPrefix = [] } = {}) => {
1937
+ if (typeof value === "boolean") {
1938
+ return {
1939
+ ok: true,
1940
+ value
1941
+ };
1942
+ } else {
1943
+ return {
1944
+ ok: false,
1945
+ errors: [
1946
+ {
1947
+ path: breadcrumbsPrefix,
1948
+ message: getErrorMessageForIncorrectType(value, "boolean")
1949
+ }
1950
+ ]
1951
+ };
1952
+ }
1953
+ }
1954
+ );
1955
+
1956
+ // src/core/schemas/builders/primitives/number.ts
1957
+ var number = createIdentitySchemaCreator(
1958
+ SchemaType.NUMBER,
1959
+ (value, { breadcrumbsPrefix = [] } = {}) => {
1960
+ if (typeof value === "number") {
1961
+ return {
1962
+ ok: true,
1963
+ value
1964
+ };
1965
+ } else {
1966
+ return {
1967
+ ok: false,
1968
+ errors: [
1969
+ {
1970
+ path: breadcrumbsPrefix,
1971
+ message: getErrorMessageForIncorrectType(value, "number")
1972
+ }
1973
+ ]
1974
+ };
1975
+ }
1976
+ }
1977
+ );
1978
+
1979
+ // src/core/schemas/builders/primitives/string.ts
1980
+ var string = createIdentitySchemaCreator(
1981
+ SchemaType.STRING,
1982
+ (value, { breadcrumbsPrefix = [] } = {}) => {
1983
+ if (typeof value === "string") {
1984
+ return {
1985
+ ok: true,
1986
+ value
1987
+ };
1988
+ } else {
1989
+ return {
1990
+ ok: false,
1991
+ errors: [
1992
+ {
1993
+ path: breadcrumbsPrefix,
1994
+ message: getErrorMessageForIncorrectType(value, "string")
1995
+ }
1996
+ ]
1997
+ };
1998
+ }
1999
+ }
2000
+ );
2001
+
2002
+ // src/core/schemas/builders/primitives/unknown.ts
2003
+ var unknown = createIdentitySchemaCreator(SchemaType.UNKNOWN, (value) => ({ ok: true, value }));
2004
+
2005
+ // src/core/schemas/builders/record/record.ts
2006
+ function record(keySchema, valueSchema) {
2007
+ const baseSchema = {
2008
+ parse: (raw, opts) => {
2009
+ return validateAndTransformRecord({
2010
+ value: raw,
2011
+ isKeyNumeric: keySchema.getType() === SchemaType.NUMBER,
2012
+ transformKey: (key) => keySchema.parse(key, {
2013
+ ...opts,
2014
+ breadcrumbsPrefix: [...(opts == null ? void 0 : opts.breadcrumbsPrefix) ?? [], `${key} (key)`]
2015
+ }),
2016
+ transformValue: (value, key) => valueSchema.parse(value, {
2017
+ ...opts,
2018
+ breadcrumbsPrefix: [...(opts == null ? void 0 : opts.breadcrumbsPrefix) ?? [], `${key}`]
2019
+ }),
2020
+ breadcrumbsPrefix: opts == null ? void 0 : opts.breadcrumbsPrefix
2021
+ });
2022
+ },
2023
+ json: (parsed, opts) => {
2024
+ return validateAndTransformRecord({
2025
+ value: parsed,
2026
+ isKeyNumeric: keySchema.getType() === SchemaType.NUMBER,
2027
+ transformKey: (key) => keySchema.json(key, {
2028
+ ...opts,
2029
+ breadcrumbsPrefix: [...(opts == null ? void 0 : opts.breadcrumbsPrefix) ?? [], `${key} (key)`]
2030
+ }),
2031
+ transformValue: (value, key) => valueSchema.json(value, {
2032
+ ...opts,
2033
+ breadcrumbsPrefix: [...(opts == null ? void 0 : opts.breadcrumbsPrefix) ?? [], `${key}`]
2034
+ }),
2035
+ breadcrumbsPrefix: opts == null ? void 0 : opts.breadcrumbsPrefix
2036
+ });
2037
+ },
2038
+ getType: () => SchemaType.RECORD
2039
+ };
2040
+ return {
2041
+ ...maybeSkipValidation(baseSchema),
2042
+ ...getSchemaUtils(baseSchema)
2043
+ };
2044
+ }
2045
+ function validateAndTransformRecord({
2046
+ value,
2047
+ isKeyNumeric,
2048
+ transformKey,
2049
+ transformValue,
2050
+ breadcrumbsPrefix = []
2051
+ }) {
2052
+ if (!isPlainObject(value)) {
2053
+ return {
2054
+ ok: false,
2055
+ errors: [
2056
+ {
2057
+ path: breadcrumbsPrefix,
2058
+ message: getErrorMessageForIncorrectType(value, "object")
2059
+ }
2060
+ ]
2061
+ };
2062
+ }
2063
+ return entries(value).reduce(
2064
+ (accPromise, [stringKey, value2]) => {
2065
+ if (value2 === void 0) {
2066
+ return accPromise;
2067
+ }
2068
+ const acc = accPromise;
2069
+ let key = stringKey;
2070
+ if (isKeyNumeric) {
2071
+ const numberKey = stringKey.length > 0 ? Number(stringKey) : NaN;
2072
+ if (!isNaN(numberKey)) {
2073
+ key = numberKey;
2074
+ }
2075
+ }
2076
+ const transformedKey = transformKey(key);
2077
+ const transformedValue = transformValue(value2, key);
2078
+ if (acc.ok && transformedKey.ok && transformedValue.ok) {
2079
+ return {
2080
+ ok: true,
2081
+ value: {
2082
+ ...acc.value,
2083
+ [transformedKey.value]: transformedValue.value
2084
+ }
2085
+ };
2086
+ }
2087
+ const errors = [];
2088
+ if (!acc.ok) {
2089
+ errors.push(...acc.errors);
2090
+ }
2091
+ if (!transformedKey.ok) {
2092
+ errors.push(...transformedKey.errors);
2093
+ }
2094
+ if (!transformedValue.ok) {
2095
+ errors.push(...transformedValue.errors);
2096
+ }
2097
+ return {
2098
+ ok: false,
2099
+ errors
2100
+ };
2101
+ },
2102
+ { ok: true, value: {} }
2103
+ );
2104
+ }
2105
+
2106
+ // src/core/schemas/builders/set/set.ts
2107
+ function set(schema) {
2108
+ const listSchema = list(schema);
2109
+ const baseSchema = {
2110
+ parse: (raw, opts) => {
2111
+ const parsedList = listSchema.parse(raw, opts);
2112
+ if (parsedList.ok) {
2113
+ return {
2114
+ ok: true,
2115
+ value: new Set(parsedList.value)
2116
+ };
2117
+ } else {
2118
+ return parsedList;
2119
+ }
2120
+ },
2121
+ json: (parsed, opts) => {
2122
+ if (!(parsed instanceof Set)) {
2123
+ return {
2124
+ ok: false,
2125
+ errors: [
2126
+ {
2127
+ path: (opts == null ? void 0 : opts.breadcrumbsPrefix) ?? [],
2128
+ message: getErrorMessageForIncorrectType(parsed, "Set")
2129
+ }
2130
+ ]
2131
+ };
2132
+ }
2133
+ const jsonList = listSchema.json([...parsed], opts);
2134
+ return jsonList;
2135
+ },
2136
+ getType: () => SchemaType.SET
2137
+ };
2138
+ return {
2139
+ ...maybeSkipValidation(baseSchema),
2140
+ ...getSchemaUtils(baseSchema)
2141
+ };
2142
+ }
2143
+
2144
+ // src/core/schemas/builders/undiscriminated-union/undiscriminatedUnion.ts
2145
+ function undiscriminatedUnion(schemas) {
2146
+ const baseSchema = {
2147
+ parse: (raw, opts) => {
2148
+ return validateAndTransformUndiscriminatedUnion(
2149
+ (schema, opts2) => schema.parse(raw, opts2),
2150
+ schemas,
2151
+ opts
2152
+ );
2153
+ },
2154
+ json: (parsed, opts) => {
2155
+ return validateAndTransformUndiscriminatedUnion(
2156
+ (schema, opts2) => schema.json(parsed, opts2),
2157
+ schemas,
2158
+ opts
2159
+ );
2160
+ },
2161
+ getType: () => SchemaType.UNDISCRIMINATED_UNION
2162
+ };
2163
+ return {
2164
+ ...maybeSkipValidation(baseSchema),
2165
+ ...getSchemaUtils(baseSchema)
2166
+ };
2167
+ }
2168
+ function validateAndTransformUndiscriminatedUnion(transform2, schemas, opts) {
2169
+ const errors = [];
2170
+ for (const [index, schema] of schemas.entries()) {
2171
+ const transformed = transform2(schema, { ...opts, skipValidation: false });
2172
+ if (transformed.ok) {
2173
+ return transformed;
2174
+ } else {
2175
+ for (const error of transformed.errors) {
2176
+ errors.push({
2177
+ path: error.path,
2178
+ message: `[Variant ${index}] ${error.message}`
2179
+ });
2180
+ }
2181
+ }
2182
+ }
2183
+ return {
2184
+ ok: false,
2185
+ errors
2186
+ };
2187
+ }
2188
+
2189
+ // src/core/schemas/builders/union/discriminant.ts
2190
+ function discriminant(parsedDiscriminant, rawDiscriminant) {
2191
+ return {
2192
+ parsedDiscriminant,
2193
+ rawDiscriminant
2194
+ };
2195
+ }
2196
+
2197
+ // src/core/schemas/builders/union/union.ts
2198
+ function union(discriminant2, union2) {
2199
+ const rawDiscriminant = typeof discriminant2 === "string" ? discriminant2 : discriminant2.rawDiscriminant;
2200
+ const parsedDiscriminant = typeof discriminant2 === "string" ? discriminant2 : discriminant2.parsedDiscriminant;
2201
+ const discriminantValueSchema = enum_(keys(union2));
2202
+ const baseSchema = {
2203
+ parse: (raw, opts) => {
2204
+ return transformAndValidateUnion({
2205
+ value: raw,
2206
+ discriminant: rawDiscriminant,
2207
+ transformedDiscriminant: parsedDiscriminant,
2208
+ transformDiscriminantValue: (discriminantValue) => discriminantValueSchema.parse(discriminantValue, {
2209
+ allowUnrecognizedEnumValues: opts == null ? void 0 : opts.allowUnrecognizedUnionMembers,
2210
+ breadcrumbsPrefix: [...(opts == null ? void 0 : opts.breadcrumbsPrefix) ?? [], rawDiscriminant]
2211
+ }),
2212
+ getAdditionalPropertiesSchema: (discriminantValue) => union2[discriminantValue],
2213
+ allowUnrecognizedUnionMembers: opts == null ? void 0 : opts.allowUnrecognizedUnionMembers,
2214
+ transformAdditionalProperties: (additionalProperties, additionalPropertiesSchema) => additionalPropertiesSchema.parse(additionalProperties, opts),
2215
+ breadcrumbsPrefix: opts == null ? void 0 : opts.breadcrumbsPrefix
2216
+ });
2217
+ },
2218
+ json: (parsed, opts) => {
2219
+ return transformAndValidateUnion({
2220
+ value: parsed,
2221
+ discriminant: parsedDiscriminant,
2222
+ transformedDiscriminant: rawDiscriminant,
2223
+ transformDiscriminantValue: (discriminantValue) => discriminantValueSchema.json(discriminantValue, {
2224
+ allowUnrecognizedEnumValues: opts == null ? void 0 : opts.allowUnrecognizedUnionMembers,
2225
+ breadcrumbsPrefix: [...(opts == null ? void 0 : opts.breadcrumbsPrefix) ?? [], parsedDiscriminant]
2226
+ }),
2227
+ getAdditionalPropertiesSchema: (discriminantValue) => union2[discriminantValue],
2228
+ allowUnrecognizedUnionMembers: opts == null ? void 0 : opts.allowUnrecognizedUnionMembers,
2229
+ transformAdditionalProperties: (additionalProperties, additionalPropertiesSchema) => additionalPropertiesSchema.json(additionalProperties, opts),
2230
+ breadcrumbsPrefix: opts == null ? void 0 : opts.breadcrumbsPrefix
2231
+ });
2232
+ },
2233
+ getType: () => SchemaType.UNION
2234
+ };
2235
+ return {
2236
+ ...maybeSkipValidation(baseSchema),
2237
+ ...getSchemaUtils(baseSchema),
2238
+ ...getObjectLikeUtils(baseSchema)
2239
+ };
2240
+ }
2241
+ function transformAndValidateUnion({
2242
+ value,
2243
+ discriminant: discriminant2,
2244
+ transformedDiscriminant,
2245
+ transformDiscriminantValue,
2246
+ getAdditionalPropertiesSchema,
2247
+ allowUnrecognizedUnionMembers = false,
2248
+ transformAdditionalProperties,
2249
+ breadcrumbsPrefix = []
2250
+ }) {
2251
+ if (!isPlainObject(value)) {
2252
+ return {
2253
+ ok: false,
2254
+ errors: [
2255
+ {
2256
+ path: breadcrumbsPrefix,
2257
+ message: getErrorMessageForIncorrectType(value, "object")
2258
+ }
2259
+ ]
2260
+ };
2261
+ }
2262
+ const { [discriminant2]: discriminantValue, ...additionalProperties } = value;
2263
+ if (discriminantValue == null) {
2264
+ return {
2265
+ ok: false,
2266
+ errors: [
2267
+ {
2268
+ path: breadcrumbsPrefix,
2269
+ message: `Missing discriminant ("${discriminant2}")`
2270
+ }
2271
+ ]
2272
+ };
2273
+ }
2274
+ const transformedDiscriminantValue = transformDiscriminantValue(discriminantValue);
2275
+ if (!transformedDiscriminantValue.ok) {
2276
+ return {
2277
+ ok: false,
2278
+ errors: transformedDiscriminantValue.errors
2279
+ };
2280
+ }
2281
+ const additionalPropertiesSchema = getAdditionalPropertiesSchema(transformedDiscriminantValue.value);
2282
+ if (additionalPropertiesSchema == null) {
2283
+ if (allowUnrecognizedUnionMembers) {
2284
+ return {
2285
+ ok: true,
2286
+ value: {
2287
+ [transformedDiscriminant]: transformedDiscriminantValue.value,
2288
+ ...additionalProperties
2289
+ }
2290
+ };
2291
+ } else {
2292
+ return {
2293
+ ok: false,
2294
+ errors: [
2295
+ {
2296
+ path: [...breadcrumbsPrefix, discriminant2],
2297
+ message: "Unexpected discriminant value"
2298
+ }
2299
+ ]
2300
+ };
2301
+ }
2302
+ }
2303
+ const transformedAdditionalProperties = transformAdditionalProperties(
2304
+ additionalProperties,
2305
+ additionalPropertiesSchema
2306
+ );
2307
+ if (!transformedAdditionalProperties.ok) {
2308
+ return transformedAdditionalProperties;
2309
+ }
2310
+ return {
2311
+ ok: true,
2312
+ value: {
2313
+ [transformedDiscriminant]: discriminantValue,
2314
+ ...transformedAdditionalProperties.value
2315
+ }
2316
+ };
2317
+ }
2318
+
2319
+ // src/Client.ts
2320
+ var import_url_join4 = __toESM(require("url-join"));
2321
+
2322
+ // src/serialization/index.ts
2323
+ var serialization_exports = {};
2324
+ __export(serialization_exports, {
2325
+ Actor: () => Actor,
2326
+ ActorName: () => ActorName,
2327
+ ActorsCreateRequest: () => ActorsCreateRequest,
2328
+ ActorsCreateResponse: () => ActorsCreateResponse,
2329
+ ActorsDeleteResponse: () => ActorsDeleteResponse,
2330
+ ActorsGetByIdResponse: () => ActorsGetByIdResponse,
2331
+ ActorsGetOrCreateByIdRequest: () => ActorsGetOrCreateByIdRequest,
2332
+ ActorsGetOrCreateByIdResponse: () => ActorsGetOrCreateByIdResponse,
2333
+ ActorsGetOrCreateRequest: () => ActorsGetOrCreateRequest,
2334
+ ActorsGetOrCreateResponse: () => ActorsGetOrCreateResponse,
2335
+ ActorsGetResponse: () => ActorsGetResponse,
2336
+ ActorsListNamesResponse: () => ActorsListNamesResponse,
2337
+ ActorsListResponse: () => ActorsListResponse,
2338
+ CrashPolicy: () => CrashPolicy2,
2339
+ Datacenter: () => Datacenter,
2340
+ DatacentersListResponse: () => DatacentersListResponse,
2341
+ Namespace: () => Namespace,
2342
+ NamespacesCreateRequest: () => NamespacesCreateRequest,
2343
+ NamespacesCreateResponse: () => NamespacesCreateResponse,
2344
+ NamespacesGetResponse: () => NamespacesGetResponse,
2345
+ NamespacesListResponse: () => NamespacesListResponse,
2346
+ Pagination: () => Pagination,
2347
+ RivetId: () => RivetId,
2348
+ Runner: () => Runner,
2349
+ RunnersGetResponse: () => RunnersGetResponse,
2350
+ RunnersListNamesResponse: () => RunnersListNamesResponse,
2351
+ RunnersListResponse: () => RunnersListResponse,
2352
+ StringHttpAddressHashableMap: () => StringHttpAddressHashableMap,
2353
+ StringHttpAddressHashableMapValue: () => StringHttpAddressHashableMapValue,
2354
+ StringTcpAddressHashableMap: () => StringTcpAddressHashableMap,
2355
+ StringTcpAddressHashableMapValue: () => StringTcpAddressHashableMapValue,
2356
+ StringUdpAddressHashableMap: () => StringUdpAddressHashableMap,
2357
+ StringUdpAddressHashableMapValue: () => StringUdpAddressHashableMapValue,
2358
+ namespaces: () => namespaces_exports2
2359
+ });
2360
+
2361
+ // src/serialization/types/RivetId.ts
2362
+ var RivetId = schemas_exports.string();
2363
+
2364
+ // src/serialization/types/CrashPolicy.ts
2365
+ var CrashPolicy2 = schemas_exports.enum_(["restart", "sleep", "destroy"]);
2366
+
2367
+ // src/serialization/types/Actor.ts
2368
+ var Actor = schemas_exports.object({
2369
+ actorId: schemas_exports.property("actor_id", RivetId),
2370
+ connectableTs: schemas_exports.property("connectable_ts", schemas_exports.number().optional()),
2371
+ crashPolicy: schemas_exports.property("crash_policy", CrashPolicy2),
2372
+ createTs: schemas_exports.property("create_ts", schemas_exports.number()),
2373
+ datacenter: schemas_exports.string(),
2374
+ destroyTs: schemas_exports.property("destroy_ts", schemas_exports.number().optional()),
2375
+ key: schemas_exports.string().optional(),
2376
+ name: schemas_exports.string(),
2377
+ namespaceId: schemas_exports.property("namespace_id", RivetId),
2378
+ pendingAllocationTs: schemas_exports.property("pending_allocation_ts", schemas_exports.number().optional()),
2379
+ runnerNameSelector: schemas_exports.property("runner_name_selector", schemas_exports.string()),
2380
+ sleepTs: schemas_exports.property("sleep_ts", schemas_exports.number().optional()),
2381
+ startTs: schemas_exports.property("start_ts", schemas_exports.number().optional())
2382
+ });
2383
+
2384
+ // src/serialization/types/ActorName.ts
2385
+ var ActorName = schemas_exports.object({
2386
+ metadata: schemas_exports.record(schemas_exports.string(), schemas_exports.unknown())
2387
+ });
2388
+
2389
+ // src/serialization/types/ActorsCreateResponse.ts
2390
+ var ActorsCreateResponse = schemas_exports.object({
2391
+ actor: Actor
2392
+ });
2393
+
2394
+ // src/serialization/types/ActorsDeleteResponse.ts
2395
+ var ActorsDeleteResponse = schemas_exports.record(schemas_exports.string(), schemas_exports.unknown());
2396
+
2397
+ // src/serialization/types/ActorsGetByIdResponse.ts
2398
+ var ActorsGetByIdResponse = schemas_exports.object({
2399
+ actorId: schemas_exports.property("actor_id", RivetId.optional())
2400
+ });
2401
+
2402
+ // src/serialization/types/ActorsGetOrCreateByIdResponse.ts
2403
+ var ActorsGetOrCreateByIdResponse = schemas_exports.object({
2404
+ actorId: schemas_exports.property("actor_id", RivetId),
2405
+ created: schemas_exports.boolean()
2406
+ });
2407
+
2408
+ // src/serialization/types/ActorsGetOrCreateResponse.ts
2409
+ var ActorsGetOrCreateResponse = schemas_exports.object({
2410
+ actor: Actor,
2411
+ created: schemas_exports.boolean()
2412
+ });
2413
+
2414
+ // src/serialization/types/ActorsGetResponse.ts
2415
+ var ActorsGetResponse = schemas_exports.object({
2416
+ actor: Actor
2417
+ });
2418
+
2419
+ // src/serialization/types/Pagination.ts
2420
+ var Pagination = schemas_exports.object({
2421
+ cursor: schemas_exports.string().optional()
2422
+ });
2423
+
2424
+ // src/serialization/types/ActorsListNamesResponse.ts
2425
+ var ActorsListNamesResponse = schemas_exports.object({
2426
+ names: schemas_exports.record(schemas_exports.string(), ActorName),
2427
+ pagination: Pagination
2428
+ });
2429
+
2430
+ // src/serialization/types/ActorsListResponse.ts
2431
+ var ActorsListResponse = schemas_exports.object({
2432
+ actors: schemas_exports.list(Actor),
2433
+ pagination: Pagination
2434
+ });
2435
+
2436
+ // src/serialization/types/Datacenter.ts
2437
+ var Datacenter = schemas_exports.object({
2438
+ datacenterLabel: schemas_exports.property("datacenter_label", schemas_exports.number()),
2439
+ name: schemas_exports.string(),
2440
+ url: schemas_exports.string()
2441
+ });
2442
+
2443
+ // src/serialization/types/DatacentersListResponse.ts
2444
+ var DatacentersListResponse = schemas_exports.object({
2445
+ datacenters: schemas_exports.list(Datacenter),
2446
+ pagination: Pagination
2447
+ });
2448
+
2449
+ // src/serialization/types/Namespace.ts
2450
+ var Namespace = schemas_exports.object({
2451
+ createTs: schemas_exports.property("create_ts", schemas_exports.number()),
2452
+ displayName: schemas_exports.property("display_name", schemas_exports.string()),
2453
+ name: schemas_exports.string(),
2454
+ namespaceId: schemas_exports.property("namespace_id", RivetId)
2455
+ });
2456
+
2457
+ // src/serialization/types/NamespacesCreateResponse.ts
2458
+ var NamespacesCreateResponse = schemas_exports.object({
2459
+ namespace: Namespace
2460
+ });
2461
+
2462
+ // src/serialization/types/NamespacesGetResponse.ts
2463
+ var NamespacesGetResponse = schemas_exports.object({
2464
+ namespace: Namespace
2465
+ });
2466
+
2467
+ // src/serialization/types/NamespacesListResponse.ts
2468
+ var NamespacesListResponse = schemas_exports.object({
2469
+ namespaces: schemas_exports.list(Namespace),
2470
+ pagination: Pagination
2471
+ });
2472
+
2473
+ // src/serialization/types/StringHttpAddressHashableMapValue.ts
2474
+ var StringHttpAddressHashableMapValue = schemas_exports.object({
2475
+ hostname: schemas_exports.string(),
2476
+ port: schemas_exports.number()
2477
+ });
2478
+
2479
+ // src/serialization/types/StringHttpAddressHashableMap.ts
2480
+ var StringHttpAddressHashableMap = schemas_exports.record(schemas_exports.string(), StringHttpAddressHashableMapValue);
2481
+
2482
+ // src/serialization/types/StringTcpAddressHashableMapValue.ts
2483
+ var StringTcpAddressHashableMapValue = schemas_exports.object({
2484
+ hostname: schemas_exports.string(),
2485
+ port: schemas_exports.number()
2486
+ });
2487
+
2488
+ // src/serialization/types/StringTcpAddressHashableMap.ts
2489
+ var StringTcpAddressHashableMap = schemas_exports.record(schemas_exports.string(), StringTcpAddressHashableMapValue);
2490
+
2491
+ // src/serialization/types/StringUdpAddressHashableMapValue.ts
2492
+ var StringUdpAddressHashableMapValue = schemas_exports.object({
2493
+ hostname: schemas_exports.string(),
2494
+ port: schemas_exports.number()
2495
+ });
2496
+
2497
+ // src/serialization/types/StringUdpAddressHashableMap.ts
2498
+ var StringUdpAddressHashableMap = schemas_exports.record(schemas_exports.string(), StringUdpAddressHashableMapValue);
2499
+
2500
+ // src/serialization/types/Runner.ts
2501
+ var Runner = schemas_exports.object({
2502
+ addressesHttp: schemas_exports.property("addresses_http", StringHttpAddressHashableMap),
2503
+ addressesTcp: schemas_exports.property("addresses_tcp", StringTcpAddressHashableMap),
2504
+ addressesUdp: schemas_exports.property("addresses_udp", StringUdpAddressHashableMap),
2505
+ createTs: schemas_exports.property("create_ts", schemas_exports.number()),
2506
+ datacenter: schemas_exports.string(),
2507
+ drainTs: schemas_exports.property("drain_ts", schemas_exports.number().optional()),
2508
+ key: schemas_exports.string(),
2509
+ lastConnectedTs: schemas_exports.property("last_connected_ts", schemas_exports.number().optional()),
2510
+ lastPingTs: schemas_exports.property("last_ping_ts", schemas_exports.number()),
2511
+ lastRtt: schemas_exports.property("last_rtt", schemas_exports.number()),
2512
+ metadata: schemas_exports.record(schemas_exports.string(), schemas_exports.unknown()).optional(),
2513
+ name: schemas_exports.string(),
2514
+ namespaceId: schemas_exports.property("namespace_id", RivetId),
2515
+ remainingSlots: schemas_exports.property("remaining_slots", schemas_exports.number()),
2516
+ runnerId: schemas_exports.property("runner_id", RivetId),
2517
+ stopTs: schemas_exports.property("stop_ts", schemas_exports.number().optional()),
2518
+ totalSlots: schemas_exports.property("total_slots", schemas_exports.number()),
2519
+ version: schemas_exports.number()
2520
+ });
2521
+
2522
+ // src/serialization/types/RunnersGetResponse.ts
2523
+ var RunnersGetResponse = schemas_exports.object({
2524
+ runner: Runner
2525
+ });
2526
+
2527
+ // src/serialization/types/RunnersListNamesResponse.ts
2528
+ var RunnersListNamesResponse = schemas_exports.object({
2529
+ names: schemas_exports.list(schemas_exports.string()),
2530
+ pagination: Pagination
2531
+ });
2532
+
2533
+ // src/serialization/types/RunnersListResponse.ts
2534
+ var RunnersListResponse = schemas_exports.object({
2535
+ pagination: Pagination,
2536
+ runners: schemas_exports.list(Runner)
2537
+ });
2538
+
2539
+ // src/serialization/client/requests/ActorsCreateRequest.ts
2540
+ var ActorsCreateRequest = schemas_exports.object({
2541
+ crashPolicy: schemas_exports.property("crash_policy", CrashPolicy2),
2542
+ input: schemas_exports.string().optional(),
2543
+ key: schemas_exports.string().optional(),
2544
+ name: schemas_exports.string(),
2545
+ runnerNameSelector: schemas_exports.property("runner_name_selector", schemas_exports.string())
2546
+ });
2547
+
2548
+ // src/serialization/client/requests/ActorsGetOrCreateRequest.ts
2549
+ var ActorsGetOrCreateRequest = schemas_exports.object({
2550
+ crashPolicy: schemas_exports.property("crash_policy", CrashPolicy2),
2551
+ input: schemas_exports.string().optional(),
2552
+ key: schemas_exports.string(),
2553
+ name: schemas_exports.string(),
2554
+ runnerNameSelector: schemas_exports.property("runner_name_selector", schemas_exports.string())
2555
+ });
2556
+
2557
+ // src/serialization/client/requests/ActorsGetOrCreateByIdRequest.ts
2558
+ var ActorsGetOrCreateByIdRequest = schemas_exports.object({
2559
+ crashPolicy: schemas_exports.property("crash_policy", CrashPolicy2),
2560
+ input: schemas_exports.string().optional(),
2561
+ key: schemas_exports.string(),
2562
+ name: schemas_exports.string(),
2563
+ runnerNameSelector: schemas_exports.property("runner_name_selector", schemas_exports.string())
2564
+ });
2565
+
2566
+ // src/serialization/resources/namespaces/index.ts
2567
+ var namespaces_exports2 = {};
2568
+ __export(namespaces_exports2, {
2569
+ NamespacesCreateRequest: () => NamespacesCreateRequest
2570
+ });
2571
+
2572
+ // src/serialization/resources/namespaces/client/requests/NamespacesCreateRequest.ts
2573
+ var NamespacesCreateRequest = schemas_exports.object({
2574
+ displayName: schemas_exports.property("display_name", schemas_exports.string()),
2575
+ name: schemas_exports.string()
2576
+ });
2577
+
2578
+ // src/errors/RivetError.ts
2579
+ var RivetError = class _RivetError extends Error {
2580
+ statusCode;
2581
+ body;
2582
+ constructor({ message, statusCode, body }) {
2583
+ super(buildMessage({ message, statusCode, body }));
2584
+ Object.setPrototypeOf(this, _RivetError.prototype);
2585
+ if (statusCode != null) {
2586
+ this.statusCode = statusCode;
2587
+ }
2588
+ if (body !== void 0) {
2589
+ this.body = body;
2590
+ }
2591
+ }
2592
+ };
2593
+ function buildMessage({
2594
+ message,
2595
+ statusCode,
2596
+ body
2597
+ }) {
2598
+ let lines = [];
2599
+ if (message != null) {
2600
+ lines.push(message);
2601
+ }
2602
+ if (statusCode != null) {
2603
+ lines.push(`Status code: ${statusCode.toString()}`);
2604
+ }
2605
+ if (body != null) {
2606
+ lines.push(`Body: ${toJson(body, void 0, 2)}`);
2607
+ }
2608
+ return lines.join("\n");
2609
+ }
2610
+
2611
+ // src/errors/RivetTimeoutError.ts
2612
+ var RivetTimeoutError = class _RivetTimeoutError extends Error {
2613
+ constructor(message) {
2614
+ super(message);
2615
+ Object.setPrototypeOf(this, _RivetTimeoutError.prototype);
2616
+ }
2617
+ };
2618
+
2619
+ // src/api/resources/datacenters/client/Client.ts
2620
+ var import_url_join = __toESM(require("url-join"));
2621
+ var Datacenters = class {
2622
+ constructor(_options) {
2623
+ this._options = _options;
2624
+ }
2625
+ /**
2626
+ * @param {Datacenters.RequestOptions} requestOptions - Request-specific configuration.
2627
+ *
2628
+ * @example
2629
+ * await client.datacenters.list()
2630
+ */
2631
+ async list(requestOptions) {
2632
+ const _response = await (this._options.fetcher ?? fetcher)({
2633
+ url: (0, import_url_join.default)(
2634
+ await Supplier.get(this._options.baseUrl) ?? await Supplier.get(this._options.environment),
2635
+ "datacenters"
2636
+ ),
2637
+ method: "GET",
2638
+ headers: {
2639
+ "X-Fern-Language": "JavaScript",
2640
+ "X-Fern-Runtime": RUNTIME.type,
2641
+ "X-Fern-Runtime-Version": RUNTIME.version,
2642
+ ...requestOptions == null ? void 0 : requestOptions.headers
2643
+ },
2644
+ contentType: "application/json",
2645
+ requestType: "json",
2646
+ timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 18e4,
2647
+ maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries,
2648
+ abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal
2649
+ });
2650
+ if (_response.ok) {
2651
+ return DatacentersListResponse.parseOrThrow(_response.body, {
2652
+ unrecognizedObjectKeys: "passthrough",
2653
+ allowUnrecognizedUnionMembers: true,
2654
+ allowUnrecognizedEnumValues: true,
2655
+ skipValidation: true,
2656
+ breadcrumbsPrefix: ["response"]
2657
+ });
2658
+ }
2659
+ if (_response.error.reason === "status-code") {
2660
+ throw new RivetError({
2661
+ statusCode: _response.error.statusCode,
2662
+ body: _response.error.body
2663
+ });
2664
+ }
2665
+ switch (_response.error.reason) {
2666
+ case "non-json":
2667
+ throw new RivetError({
2668
+ statusCode: _response.error.statusCode,
2669
+ body: _response.error.rawBody
2670
+ });
2671
+ case "timeout":
2672
+ throw new RivetTimeoutError("Timeout exceeded when calling GET /datacenters.");
2673
+ case "unknown":
2674
+ throw new RivetError({
2675
+ message: _response.error.errorMessage
2676
+ });
2677
+ }
2678
+ }
2679
+ };
2680
+
2681
+ // src/api/resources/namespaces/client/Client.ts
2682
+ var import_url_join2 = __toESM(require("url-join"));
2683
+ var Namespaces = class {
2684
+ constructor(_options) {
2685
+ this._options = _options;
2686
+ }
2687
+ /**
2688
+ * @param {Rivet.NamespacesListRequest} request
2689
+ * @param {Namespaces.RequestOptions} requestOptions - Request-specific configuration.
2690
+ *
2691
+ * @example
2692
+ * await client.namespaces.list()
2693
+ */
2694
+ async list(request = {}, requestOptions) {
2695
+ const { limit, cursor, name } = request;
2696
+ const _queryParams = {};
2697
+ if (limit != null) {
2698
+ _queryParams["limit"] = limit.toString();
2699
+ }
2700
+ if (cursor != null) {
2701
+ _queryParams["cursor"] = cursor;
2702
+ }
2703
+ if (name != null) {
2704
+ _queryParams["name"] = name;
2705
+ }
2706
+ const _response = await (this._options.fetcher ?? fetcher)({
2707
+ url: (0, import_url_join2.default)(
2708
+ await Supplier.get(this._options.baseUrl) ?? await Supplier.get(this._options.environment),
2709
+ "namespaces"
2710
+ ),
2711
+ method: "GET",
2712
+ headers: {
2713
+ "X-Fern-Language": "JavaScript",
2714
+ "X-Fern-Runtime": RUNTIME.type,
2715
+ "X-Fern-Runtime-Version": RUNTIME.version,
2716
+ ...requestOptions == null ? void 0 : requestOptions.headers
2717
+ },
2718
+ contentType: "application/json",
2719
+ queryParameters: _queryParams,
2720
+ requestType: "json",
2721
+ timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 18e4,
2722
+ maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries,
2723
+ abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal
2724
+ });
2725
+ if (_response.ok) {
2726
+ return NamespacesListResponse.parseOrThrow(_response.body, {
2727
+ unrecognizedObjectKeys: "passthrough",
2728
+ allowUnrecognizedUnionMembers: true,
2729
+ allowUnrecognizedEnumValues: true,
2730
+ skipValidation: true,
2731
+ breadcrumbsPrefix: ["response"]
2732
+ });
2733
+ }
2734
+ if (_response.error.reason === "status-code") {
2735
+ throw new RivetError({
2736
+ statusCode: _response.error.statusCode,
2737
+ body: _response.error.body
2738
+ });
2739
+ }
2740
+ switch (_response.error.reason) {
2741
+ case "non-json":
2742
+ throw new RivetError({
2743
+ statusCode: _response.error.statusCode,
2744
+ body: _response.error.rawBody
2745
+ });
2746
+ case "timeout":
2747
+ throw new RivetTimeoutError("Timeout exceeded when calling GET /namespaces.");
2748
+ case "unknown":
2749
+ throw new RivetError({
2750
+ message: _response.error.errorMessage
2751
+ });
2752
+ }
2753
+ }
2754
+ /**
2755
+ * @param {Rivet.NamespacesCreateRequest} request
2756
+ * @param {Namespaces.RequestOptions} requestOptions - Request-specific configuration.
2757
+ *
2758
+ * @example
2759
+ * await client.namespaces.create({
2760
+ * displayName: "display_name",
2761
+ * name: "name"
2762
+ * })
2763
+ */
2764
+ async create(request, requestOptions) {
2765
+ const _response = await (this._options.fetcher ?? fetcher)({
2766
+ url: (0, import_url_join2.default)(
2767
+ await Supplier.get(this._options.baseUrl) ?? await Supplier.get(this._options.environment),
2768
+ "namespaces"
2769
+ ),
2770
+ method: "POST",
2771
+ headers: {
2772
+ "X-Fern-Language": "JavaScript",
2773
+ "X-Fern-Runtime": RUNTIME.type,
2774
+ "X-Fern-Runtime-Version": RUNTIME.version,
2775
+ ...requestOptions == null ? void 0 : requestOptions.headers
2776
+ },
2777
+ contentType: "application/json",
2778
+ requestType: "json",
2779
+ body: NamespacesCreateRequest.jsonOrThrow(request, { unrecognizedObjectKeys: "strip" }),
2780
+ timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 18e4,
2781
+ maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries,
2782
+ abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal
2783
+ });
2784
+ if (_response.ok) {
2785
+ return NamespacesCreateResponse.parseOrThrow(_response.body, {
2786
+ unrecognizedObjectKeys: "passthrough",
2787
+ allowUnrecognizedUnionMembers: true,
2788
+ allowUnrecognizedEnumValues: true,
2789
+ skipValidation: true,
2790
+ breadcrumbsPrefix: ["response"]
2791
+ });
2792
+ }
2793
+ if (_response.error.reason === "status-code") {
2794
+ throw new RivetError({
2795
+ statusCode: _response.error.statusCode,
2796
+ body: _response.error.body
2797
+ });
2798
+ }
2799
+ switch (_response.error.reason) {
2800
+ case "non-json":
2801
+ throw new RivetError({
2802
+ statusCode: _response.error.statusCode,
2803
+ body: _response.error.rawBody
2804
+ });
2805
+ case "timeout":
2806
+ throw new RivetTimeoutError("Timeout exceeded when calling POST /namespaces.");
2807
+ case "unknown":
2808
+ throw new RivetError({
2809
+ message: _response.error.errorMessage
2810
+ });
2811
+ }
2812
+ }
2813
+ /**
2814
+ * @param {Rivet.RivetId} namespaceId
2815
+ * @param {Namespaces.RequestOptions} requestOptions - Request-specific configuration.
2816
+ *
2817
+ * @example
2818
+ * await client.namespaces.get("namespace_id")
2819
+ */
2820
+ async get(namespaceId, requestOptions) {
2821
+ const _response = await (this._options.fetcher ?? fetcher)({
2822
+ url: (0, import_url_join2.default)(
2823
+ await Supplier.get(this._options.baseUrl) ?? await Supplier.get(this._options.environment),
2824
+ `namespaces/${encodeURIComponent(RivetId.jsonOrThrow(namespaceId))}`
2825
+ ),
2826
+ method: "GET",
2827
+ headers: {
2828
+ "X-Fern-Language": "JavaScript",
2829
+ "X-Fern-Runtime": RUNTIME.type,
2830
+ "X-Fern-Runtime-Version": RUNTIME.version,
2831
+ ...requestOptions == null ? void 0 : requestOptions.headers
2832
+ },
2833
+ contentType: "application/json",
2834
+ requestType: "json",
2835
+ timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 18e4,
2836
+ maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries,
2837
+ abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal
2838
+ });
2839
+ if (_response.ok) {
2840
+ return NamespacesGetResponse.parseOrThrow(_response.body, {
2841
+ unrecognizedObjectKeys: "passthrough",
2842
+ allowUnrecognizedUnionMembers: true,
2843
+ allowUnrecognizedEnumValues: true,
2844
+ skipValidation: true,
2845
+ breadcrumbsPrefix: ["response"]
2846
+ });
2847
+ }
2848
+ if (_response.error.reason === "status-code") {
2849
+ throw new RivetError({
2850
+ statusCode: _response.error.statusCode,
2851
+ body: _response.error.body
2852
+ });
2853
+ }
2854
+ switch (_response.error.reason) {
2855
+ case "non-json":
2856
+ throw new RivetError({
2857
+ statusCode: _response.error.statusCode,
2858
+ body: _response.error.rawBody
2859
+ });
2860
+ case "timeout":
2861
+ throw new RivetTimeoutError("Timeout exceeded when calling GET /namespaces/{namespace_id}.");
2862
+ case "unknown":
2863
+ throw new RivetError({
2864
+ message: _response.error.errorMessage
2865
+ });
2866
+ }
2867
+ }
2868
+ };
2869
+
2870
+ // src/api/resources/runners/client/Client.ts
2871
+ var import_url_join3 = __toESM(require("url-join"));
2872
+ var Runners = class {
2873
+ constructor(_options) {
2874
+ this._options = _options;
2875
+ }
2876
+ /**
2877
+ * @param {Rivet.RunnersListRequest} request
2878
+ * @param {Runners.RequestOptions} requestOptions - Request-specific configuration.
2879
+ *
2880
+ * @example
2881
+ * await client.runners.list({
2882
+ * namespace: "namespace"
2883
+ * })
2884
+ */
2885
+ async list(request, requestOptions) {
2886
+ const { namespace, name, includeStopped, limit, cursor } = request;
2887
+ const _queryParams = {};
2888
+ _queryParams["namespace"] = namespace;
2889
+ if (name != null) {
2890
+ _queryParams["name"] = name;
2891
+ }
2892
+ if (includeStopped != null) {
2893
+ _queryParams["include_stopped"] = includeStopped.toString();
2894
+ }
2895
+ if (limit != null) {
2896
+ _queryParams["limit"] = limit.toString();
2897
+ }
2898
+ if (cursor != null) {
2899
+ _queryParams["cursor"] = cursor;
2900
+ }
2901
+ const _response = await (this._options.fetcher ?? fetcher)({
2902
+ url: (0, import_url_join3.default)(
2903
+ await Supplier.get(this._options.baseUrl) ?? await Supplier.get(this._options.environment),
2904
+ "runners"
2905
+ ),
2906
+ method: "GET",
2907
+ headers: {
2908
+ "X-Fern-Language": "JavaScript",
2909
+ "X-Fern-Runtime": RUNTIME.type,
2910
+ "X-Fern-Runtime-Version": RUNTIME.version,
2911
+ ...requestOptions == null ? void 0 : requestOptions.headers
2912
+ },
2913
+ contentType: "application/json",
2914
+ queryParameters: _queryParams,
2915
+ requestType: "json",
2916
+ timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 18e4,
2917
+ maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries,
2918
+ abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal
2919
+ });
2920
+ if (_response.ok) {
2921
+ return RunnersListResponse.parseOrThrow(_response.body, {
2922
+ unrecognizedObjectKeys: "passthrough",
2923
+ allowUnrecognizedUnionMembers: true,
2924
+ allowUnrecognizedEnumValues: true,
2925
+ skipValidation: true,
2926
+ breadcrumbsPrefix: ["response"]
2927
+ });
2928
+ }
2929
+ if (_response.error.reason === "status-code") {
2930
+ throw new RivetError({
2931
+ statusCode: _response.error.statusCode,
2932
+ body: _response.error.body
2933
+ });
2934
+ }
2935
+ switch (_response.error.reason) {
2936
+ case "non-json":
2937
+ throw new RivetError({
2938
+ statusCode: _response.error.statusCode,
2939
+ body: _response.error.rawBody
2940
+ });
2941
+ case "timeout":
2942
+ throw new RivetTimeoutError("Timeout exceeded when calling GET /runners.");
2943
+ case "unknown":
2944
+ throw new RivetError({
2945
+ message: _response.error.errorMessage
2946
+ });
2947
+ }
2948
+ }
2949
+ /**
2950
+ * 2 round trips:
2951
+ *
2952
+ * - GET /runners/names (fanout)
2953
+ * - [api-peer] namespace::ops::resolve_for_name_global
2954
+ *
2955
+ * @param {Rivet.RunnersListNamesRequest} request
2956
+ * @param {Runners.RequestOptions} requestOptions - Request-specific configuration.
2957
+ *
2958
+ * @example
2959
+ * await client.runners.listNames({
2960
+ * namespace: "namespace"
2961
+ * })
2962
+ */
2963
+ async listNames(request, requestOptions) {
2964
+ const { namespace, limit, cursor } = request;
2965
+ const _queryParams = {};
2966
+ _queryParams["namespace"] = namespace;
2967
+ if (limit != null) {
2968
+ _queryParams["limit"] = limit.toString();
2969
+ }
2970
+ if (cursor != null) {
2971
+ _queryParams["cursor"] = cursor;
2972
+ }
2973
+ const _response = await (this._options.fetcher ?? fetcher)({
2974
+ url: (0, import_url_join3.default)(
2975
+ await Supplier.get(this._options.baseUrl) ?? await Supplier.get(this._options.environment),
2976
+ "runners/names"
2977
+ ),
2978
+ method: "GET",
2979
+ headers: {
2980
+ "X-Fern-Language": "JavaScript",
2981
+ "X-Fern-Runtime": RUNTIME.type,
2982
+ "X-Fern-Runtime-Version": RUNTIME.version,
2983
+ ...requestOptions == null ? void 0 : requestOptions.headers
2984
+ },
2985
+ contentType: "application/json",
2986
+ queryParameters: _queryParams,
2987
+ requestType: "json",
2988
+ timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 18e4,
2989
+ maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries,
2990
+ abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal
2991
+ });
2992
+ if (_response.ok) {
2993
+ return RunnersListNamesResponse.parseOrThrow(_response.body, {
2994
+ unrecognizedObjectKeys: "passthrough",
2995
+ allowUnrecognizedUnionMembers: true,
2996
+ allowUnrecognizedEnumValues: true,
2997
+ skipValidation: true,
2998
+ breadcrumbsPrefix: ["response"]
2999
+ });
3000
+ }
3001
+ if (_response.error.reason === "status-code") {
3002
+ throw new RivetError({
3003
+ statusCode: _response.error.statusCode,
3004
+ body: _response.error.body
3005
+ });
3006
+ }
3007
+ switch (_response.error.reason) {
3008
+ case "non-json":
3009
+ throw new RivetError({
3010
+ statusCode: _response.error.statusCode,
3011
+ body: _response.error.rawBody
3012
+ });
3013
+ case "timeout":
3014
+ throw new RivetTimeoutError("Timeout exceeded when calling GET /runners/names.");
3015
+ case "unknown":
3016
+ throw new RivetError({
3017
+ message: _response.error.errorMessage
3018
+ });
3019
+ }
3020
+ }
3021
+ /**
3022
+ * @param {Rivet.RivetId} runnerId
3023
+ * @param {Rivet.RunnersGetRequest} request
3024
+ * @param {Runners.RequestOptions} requestOptions - Request-specific configuration.
3025
+ *
3026
+ * @example
3027
+ * await client.runners.get("runner_id")
3028
+ */
3029
+ async get(runnerId, request = {}, requestOptions) {
3030
+ const { namespace } = request;
3031
+ const _queryParams = {};
3032
+ if (namespace != null) {
3033
+ _queryParams["namespace"] = namespace;
3034
+ }
3035
+ const _response = await (this._options.fetcher ?? fetcher)({
3036
+ url: (0, import_url_join3.default)(
3037
+ await Supplier.get(this._options.baseUrl) ?? await Supplier.get(this._options.environment),
3038
+ `runners/${encodeURIComponent(RivetId.jsonOrThrow(runnerId))}`
3039
+ ),
3040
+ method: "GET",
3041
+ headers: {
3042
+ "X-Fern-Language": "JavaScript",
3043
+ "X-Fern-Runtime": RUNTIME.type,
3044
+ "X-Fern-Runtime-Version": RUNTIME.version,
3045
+ ...requestOptions == null ? void 0 : requestOptions.headers
3046
+ },
3047
+ contentType: "application/json",
3048
+ queryParameters: _queryParams,
3049
+ requestType: "json",
3050
+ timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 18e4,
3051
+ maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries,
3052
+ abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal
3053
+ });
3054
+ if (_response.ok) {
3055
+ return RunnersGetResponse.parseOrThrow(_response.body, {
3056
+ unrecognizedObjectKeys: "passthrough",
3057
+ allowUnrecognizedUnionMembers: true,
3058
+ allowUnrecognizedEnumValues: true,
3059
+ skipValidation: true,
3060
+ breadcrumbsPrefix: ["response"]
3061
+ });
3062
+ }
3063
+ if (_response.error.reason === "status-code") {
3064
+ throw new RivetError({
3065
+ statusCode: _response.error.statusCode,
3066
+ body: _response.error.body
3067
+ });
3068
+ }
3069
+ switch (_response.error.reason) {
3070
+ case "non-json":
3071
+ throw new RivetError({
3072
+ statusCode: _response.error.statusCode,
3073
+ body: _response.error.rawBody
3074
+ });
3075
+ case "timeout":
3076
+ throw new RivetTimeoutError("Timeout exceeded when calling GET /runners/{runner_id}.");
3077
+ case "unknown":
3078
+ throw new RivetError({
3079
+ message: _response.error.errorMessage
3080
+ });
3081
+ }
3082
+ }
3083
+ };
3084
+
3085
+ // src/Client.ts
3086
+ var RivetClient = class {
3087
+ constructor(_options) {
3088
+ this._options = _options;
3089
+ }
3090
+ _datacenters;
3091
+ _namespaces;
3092
+ _runners;
3093
+ get datacenters() {
3094
+ return this._datacenters ?? (this._datacenters = new Datacenters(this._options));
3095
+ }
3096
+ get namespaces() {
3097
+ return this._namespaces ?? (this._namespaces = new Namespaces(this._options));
3098
+ }
3099
+ get runners() {
3100
+ return this._runners ?? (this._runners = new Runners(this._options));
3101
+ }
3102
+ /**
3103
+ * **If key is some & `include_destroyed` is false**
3104
+ *
3105
+ * 2 round trips:
3106
+ *
3107
+ * - namespace::ops::resolve_for_name_global
3108
+ * - GET /actors/{} (multiple DCs based on actor IDs)
3109
+ *
3110
+ * This path is optimized because we can read the actor IDs fro the key directly from Epoxy with
3111
+ * stale consistency to determine which datacenter the actor lives in. Under most circumstances,
3112
+ * this means we don't need to fan out to all datacenters (like normal list does).
3113
+ *
3114
+ * The reason `include_destroyed` has to be false is Epoxy only stores currently active actors. If
3115
+ * `include_destroyed` is true, we show all previous iterations of actors with the same key.
3116
+ *
3117
+ * **Otherwise**
3118
+ *
3119
+ * 2 round trips:
3120
+ *
3121
+ * - namespace::ops::resolve_for_name_global
3122
+ * - GET /actors (fanout)
3123
+ *
3124
+ * ## Optimized Alternative Routes
3125
+ *
3126
+ * For minimal round trips to check if an actor exists for a key, use `GET /actors/by-id`. This
3127
+ * does not require fetching the actor's state, so it returns immediately.
3128
+ *
3129
+ * @param {Rivet.ActorsListRequest} request
3130
+ * @param {RivetClient.RequestOptions} requestOptions - Request-specific configuration.
3131
+ *
3132
+ * @example
3133
+ * await client.actorsList({
3134
+ * namespace: "namespace"
3135
+ * })
3136
+ */
3137
+ async actorsList(request, requestOptions) {
3138
+ const { namespace, name, key, actorIds, includeDestroyed, limit, cursor } = request;
3139
+ const _queryParams = {};
3140
+ _queryParams["namespace"] = namespace;
3141
+ if (name != null) {
3142
+ _queryParams["name"] = name;
3143
+ }
3144
+ if (key != null) {
3145
+ _queryParams["key"] = key;
3146
+ }
3147
+ if (actorIds != null) {
3148
+ _queryParams["actor_ids"] = actorIds;
3149
+ }
3150
+ if (includeDestroyed != null) {
3151
+ _queryParams["include_destroyed"] = includeDestroyed.toString();
3152
+ }
3153
+ if (limit != null) {
3154
+ _queryParams["limit"] = limit.toString();
3155
+ }
3156
+ if (cursor != null) {
3157
+ _queryParams["cursor"] = cursor;
3158
+ }
3159
+ const _response = await (this._options.fetcher ?? fetcher)({
3160
+ url: (0, import_url_join4.default)(
3161
+ await Supplier.get(this._options.baseUrl) ?? await Supplier.get(this._options.environment),
3162
+ "actors"
3163
+ ),
3164
+ method: "GET",
3165
+ headers: {
3166
+ "X-Fern-Language": "JavaScript",
3167
+ "X-Fern-Runtime": RUNTIME.type,
3168
+ "X-Fern-Runtime-Version": RUNTIME.version,
3169
+ ...requestOptions == null ? void 0 : requestOptions.headers
3170
+ },
3171
+ contentType: "application/json",
3172
+ queryParameters: _queryParams,
3173
+ requestType: "json",
3174
+ timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 18e4,
3175
+ maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries,
3176
+ abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal
3177
+ });
3178
+ if (_response.ok) {
3179
+ return ActorsListResponse.parseOrThrow(_response.body, {
3180
+ unrecognizedObjectKeys: "passthrough",
3181
+ allowUnrecognizedUnionMembers: true,
3182
+ allowUnrecognizedEnumValues: true,
3183
+ skipValidation: true,
3184
+ breadcrumbsPrefix: ["response"]
3185
+ });
3186
+ }
3187
+ if (_response.error.reason === "status-code") {
3188
+ throw new RivetError({
3189
+ statusCode: _response.error.statusCode,
3190
+ body: _response.error.body
3191
+ });
3192
+ }
3193
+ switch (_response.error.reason) {
3194
+ case "non-json":
3195
+ throw new RivetError({
3196
+ statusCode: _response.error.statusCode,
3197
+ body: _response.error.rawBody
3198
+ });
3199
+ case "timeout":
3200
+ throw new RivetTimeoutError("Timeout exceeded when calling GET /actors.");
3201
+ case "unknown":
3202
+ throw new RivetError({
3203
+ message: _response.error.errorMessage
3204
+ });
3205
+ }
3206
+ }
3207
+ /**
3208
+ * **If actor is created in the current datacenter:**
3209
+ *
3210
+ * 2 round trips:
3211
+ *
3212
+ * - namespace::ops::resolve_for_name_global
3213
+ * - [pegboard::workflows::actor] Create actor workflow (includes Epoxy key allocation)
3214
+ *
3215
+ * **If actor is created in a different datacenter:**
3216
+ *
3217
+ * 3 round trips:
3218
+ *
3219
+ * - namespace::ops::resolve_for_name_global
3220
+ * - POST /actors to remote datacenter
3221
+ * - [pegboard::workflows::actor] Create actor workflow (includes Epoxy key allocation)
3222
+ *
3223
+ * actor::get will always be in the same datacenter.
3224
+ *
3225
+ * @param {Rivet.ActorsCreateRequest} request
3226
+ * @param {RivetClient.RequestOptions} requestOptions - Request-specific configuration.
3227
+ *
3228
+ * @example
3229
+ * await client.actorsCreate({
3230
+ * namespace: "namespace",
3231
+ * crashPolicy: "restart",
3232
+ * name: "name",
3233
+ * runnerNameSelector: "runner_name_selector"
3234
+ * })
3235
+ */
3236
+ async actorsCreate(request, requestOptions) {
3237
+ const { namespace, datacenter, ..._body } = request;
3238
+ const _queryParams = {};
3239
+ _queryParams["namespace"] = namespace;
3240
+ if (datacenter != null) {
3241
+ _queryParams["datacenter"] = datacenter;
3242
+ }
3243
+ const _response = await (this._options.fetcher ?? fetcher)({
3244
+ url: (0, import_url_join4.default)(
3245
+ await Supplier.get(this._options.baseUrl) ?? await Supplier.get(this._options.environment),
3246
+ "actors"
3247
+ ),
3248
+ method: "POST",
3249
+ headers: {
3250
+ "X-Fern-Language": "JavaScript",
3251
+ "X-Fern-Runtime": RUNTIME.type,
3252
+ "X-Fern-Runtime-Version": RUNTIME.version,
3253
+ ...requestOptions == null ? void 0 : requestOptions.headers
3254
+ },
3255
+ contentType: "application/json",
3256
+ queryParameters: _queryParams,
3257
+ requestType: "json",
3258
+ body: ActorsCreateRequest.jsonOrThrow(_body, { unrecognizedObjectKeys: "strip" }),
3259
+ timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 18e4,
3260
+ maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries,
3261
+ abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal
3262
+ });
3263
+ if (_response.ok) {
3264
+ return ActorsCreateResponse.parseOrThrow(_response.body, {
3265
+ unrecognizedObjectKeys: "passthrough",
3266
+ allowUnrecognizedUnionMembers: true,
3267
+ allowUnrecognizedEnumValues: true,
3268
+ skipValidation: true,
3269
+ breadcrumbsPrefix: ["response"]
3270
+ });
3271
+ }
3272
+ if (_response.error.reason === "status-code") {
3273
+ throw new RivetError({
3274
+ statusCode: _response.error.statusCode,
3275
+ body: _response.error.body
3276
+ });
3277
+ }
3278
+ switch (_response.error.reason) {
3279
+ case "non-json":
3280
+ throw new RivetError({
3281
+ statusCode: _response.error.statusCode,
3282
+ body: _response.error.rawBody
3283
+ });
3284
+ case "timeout":
3285
+ throw new RivetTimeoutError("Timeout exceeded when calling POST /actors.");
3286
+ case "unknown":
3287
+ throw new RivetError({
3288
+ message: _response.error.errorMessage
3289
+ });
3290
+ }
3291
+ }
3292
+ /**
3293
+ * **If actor exists**
3294
+ *
3295
+ * 2 round trips:
3296
+ *
3297
+ * - namespace::ops::resolve_for_name_global
3298
+ * - GET /actors/{}
3299
+ *
3300
+ * **If actor does not exist and is created in the current datacenter:**
3301
+ *
3302
+ * 2 round trips:
3303
+ *
3304
+ * - namespace::ops::resolve_for_name_global
3305
+ * - [pegboard::workflows::actor] Create actor workflow (includes Epoxy key allocation)
3306
+ *
3307
+ * **If actor does not exist and is created in a different datacenter:**
3308
+ *
3309
+ * 3 round trips:
3310
+ *
3311
+ * - namespace::ops::resolve_for_name_global
3312
+ * - POST /actors to remote datacenter
3313
+ * - [pegboard::workflows::actor] Create actor workflow (includes Epoxy key allocation)
3314
+ *
3315
+ * actor::get will always be in the same datacenter.
3316
+ *
3317
+ * ## Optimized Alternative Routes
3318
+ *
3319
+ * For minimal round trips to get or create an actor, use `PUT /actors/by-id`. This doesn't
3320
+ * require fetching the actor's state from the other datacenter.
3321
+ *
3322
+ * @param {Rivet.ActorsGetOrCreateRequest} request
3323
+ * @param {RivetClient.RequestOptions} requestOptions - Request-specific configuration.
3324
+ *
3325
+ * @example
3326
+ * await client.actorsGetOrCreate({
3327
+ * namespace: "namespace",
3328
+ * crashPolicy: "restart",
3329
+ * key: "key",
3330
+ * name: "name",
3331
+ * runnerNameSelector: "runner_name_selector"
3332
+ * })
3333
+ */
3334
+ async actorsGetOrCreate(request, requestOptions) {
3335
+ const { namespace, datacenter, ..._body } = request;
3336
+ const _queryParams = {};
3337
+ _queryParams["namespace"] = namespace;
3338
+ if (datacenter != null) {
3339
+ _queryParams["datacenter"] = datacenter;
3340
+ }
3341
+ const _response = await (this._options.fetcher ?? fetcher)({
3342
+ url: (0, import_url_join4.default)(
3343
+ await Supplier.get(this._options.baseUrl) ?? await Supplier.get(this._options.environment),
3344
+ "actors"
3345
+ ),
3346
+ method: "PUT",
3347
+ headers: {
3348
+ "X-Fern-Language": "JavaScript",
3349
+ "X-Fern-Runtime": RUNTIME.type,
3350
+ "X-Fern-Runtime-Version": RUNTIME.version,
3351
+ ...requestOptions == null ? void 0 : requestOptions.headers
3352
+ },
3353
+ contentType: "application/json",
3354
+ queryParameters: _queryParams,
3355
+ requestType: "json",
3356
+ body: ActorsGetOrCreateRequest.jsonOrThrow(_body, { unrecognizedObjectKeys: "strip" }),
3357
+ timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 18e4,
3358
+ maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries,
3359
+ abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal
3360
+ });
3361
+ if (_response.ok) {
3362
+ return ActorsGetOrCreateResponse.parseOrThrow(_response.body, {
3363
+ unrecognizedObjectKeys: "passthrough",
3364
+ allowUnrecognizedUnionMembers: true,
3365
+ allowUnrecognizedEnumValues: true,
3366
+ skipValidation: true,
3367
+ breadcrumbsPrefix: ["response"]
3368
+ });
3369
+ }
3370
+ if (_response.error.reason === "status-code") {
3371
+ throw new RivetError({
3372
+ statusCode: _response.error.statusCode,
3373
+ body: _response.error.body
3374
+ });
3375
+ }
3376
+ switch (_response.error.reason) {
3377
+ case "non-json":
3378
+ throw new RivetError({
3379
+ statusCode: _response.error.statusCode,
3380
+ body: _response.error.rawBody
3381
+ });
3382
+ case "timeout":
3383
+ throw new RivetTimeoutError("Timeout exceeded when calling PUT /actors.");
3384
+ case "unknown":
3385
+ throw new RivetError({
3386
+ message: _response.error.errorMessage
3387
+ });
3388
+ }
3389
+ }
3390
+ /**
3391
+ * 1 round trip:
3392
+ *
3393
+ * - namespace::ops::resolve_for_name_global
3394
+ *
3395
+ * This does not require another round trip since we use stale consistency for the get_id_for_key.
3396
+ *
3397
+ * @param {Rivet.ActorsGetByIdRequest} request
3398
+ * @param {RivetClient.RequestOptions} requestOptions - Request-specific configuration.
3399
+ *
3400
+ * @example
3401
+ * await client.actorsGetById({
3402
+ * namespace: "namespace",
3403
+ * name: "name",
3404
+ * key: "key"
3405
+ * })
3406
+ */
3407
+ async actorsGetById(request, requestOptions) {
3408
+ const { namespace, name, key } = request;
3409
+ const _queryParams = {};
3410
+ _queryParams["namespace"] = namespace;
3411
+ _queryParams["name"] = name;
3412
+ _queryParams["key"] = key;
3413
+ const _response = await (this._options.fetcher ?? fetcher)({
3414
+ url: (0, import_url_join4.default)(
3415
+ await Supplier.get(this._options.baseUrl) ?? await Supplier.get(this._options.environment),
3416
+ "actors/by-id"
3417
+ ),
3418
+ method: "GET",
3419
+ headers: {
3420
+ "X-Fern-Language": "JavaScript",
3421
+ "X-Fern-Runtime": RUNTIME.type,
3422
+ "X-Fern-Runtime-Version": RUNTIME.version,
3423
+ ...requestOptions == null ? void 0 : requestOptions.headers
3424
+ },
3425
+ contentType: "application/json",
3426
+ queryParameters: _queryParams,
3427
+ requestType: "json",
3428
+ timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 18e4,
3429
+ maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries,
3430
+ abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal
3431
+ });
3432
+ if (_response.ok) {
3433
+ return ActorsGetByIdResponse.parseOrThrow(_response.body, {
3434
+ unrecognizedObjectKeys: "passthrough",
3435
+ allowUnrecognizedUnionMembers: true,
3436
+ allowUnrecognizedEnumValues: true,
3437
+ skipValidation: true,
3438
+ breadcrumbsPrefix: ["response"]
3439
+ });
3440
+ }
3441
+ if (_response.error.reason === "status-code") {
3442
+ throw new RivetError({
3443
+ statusCode: _response.error.statusCode,
3444
+ body: _response.error.body
3445
+ });
3446
+ }
3447
+ switch (_response.error.reason) {
3448
+ case "non-json":
3449
+ throw new RivetError({
3450
+ statusCode: _response.error.statusCode,
3451
+ body: _response.error.rawBody
3452
+ });
3453
+ case "timeout":
3454
+ throw new RivetTimeoutError("Timeout exceeded when calling GET /actors/by-id.");
3455
+ case "unknown":
3456
+ throw new RivetError({
3457
+ message: _response.error.errorMessage
3458
+ });
3459
+ }
3460
+ }
3461
+ /**
3462
+ * **If actor exists**
3463
+ *
3464
+ * 1 round trip:
3465
+ *
3466
+ * - namespace::ops::resolve_for_name_global
3467
+ *
3468
+ * **If actor does not exist and is created in the current datacenter:**
3469
+ *
3470
+ * 2 round trips:
3471
+ *
3472
+ * - namespace::ops::resolve_for_name_global
3473
+ * - [pegboard::workflows::actors::keys::allocate_key] Reserve Epoxy key
3474
+ *
3475
+ * **If actor does not exist and is created in a different datacenter:**
3476
+ *
3477
+ * 3 round trips:
3478
+ *
3479
+ * - namespace::ops::resolve_for_name_global
3480
+ * - namespace::ops::get (to get namespace name for remote call)
3481
+ * - POST /actors to remote datacenter
3482
+ *
3483
+ * @param {Rivet.ActorsGetOrCreateByIdRequest} request
3484
+ * @param {RivetClient.RequestOptions} requestOptions - Request-specific configuration.
3485
+ *
3486
+ * @example
3487
+ * await client.actorsGetOrCreateById({
3488
+ * namespace: "namespace",
3489
+ * crashPolicy: "restart",
3490
+ * key: "key",
3491
+ * name: "name",
3492
+ * runnerNameSelector: "runner_name_selector"
3493
+ * })
3494
+ */
3495
+ async actorsGetOrCreateById(request, requestOptions) {
3496
+ const { namespace, datacenter, ..._body } = request;
3497
+ const _queryParams = {};
3498
+ _queryParams["namespace"] = namespace;
3499
+ if (datacenter != null) {
3500
+ _queryParams["datacenter"] = datacenter;
3501
+ }
3502
+ const _response = await (this._options.fetcher ?? fetcher)({
3503
+ url: (0, import_url_join4.default)(
3504
+ await Supplier.get(this._options.baseUrl) ?? await Supplier.get(this._options.environment),
3505
+ "actors/by-id"
3506
+ ),
3507
+ method: "PUT",
3508
+ headers: {
3509
+ "X-Fern-Language": "JavaScript",
3510
+ "X-Fern-Runtime": RUNTIME.type,
3511
+ "X-Fern-Runtime-Version": RUNTIME.version,
3512
+ ...requestOptions == null ? void 0 : requestOptions.headers
3513
+ },
3514
+ contentType: "application/json",
3515
+ queryParameters: _queryParams,
3516
+ requestType: "json",
3517
+ body: ActorsGetOrCreateByIdRequest.jsonOrThrow(_body, { unrecognizedObjectKeys: "strip" }),
3518
+ timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 18e4,
3519
+ maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries,
3520
+ abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal
3521
+ });
3522
+ if (_response.ok) {
3523
+ return ActorsGetOrCreateByIdResponse.parseOrThrow(_response.body, {
3524
+ unrecognizedObjectKeys: "passthrough",
3525
+ allowUnrecognizedUnionMembers: true,
3526
+ allowUnrecognizedEnumValues: true,
3527
+ skipValidation: true,
3528
+ breadcrumbsPrefix: ["response"]
3529
+ });
3530
+ }
3531
+ if (_response.error.reason === "status-code") {
3532
+ throw new RivetError({
3533
+ statusCode: _response.error.statusCode,
3534
+ body: _response.error.body
3535
+ });
3536
+ }
3537
+ switch (_response.error.reason) {
3538
+ case "non-json":
3539
+ throw new RivetError({
3540
+ statusCode: _response.error.statusCode,
3541
+ body: _response.error.rawBody
3542
+ });
3543
+ case "timeout":
3544
+ throw new RivetTimeoutError("Timeout exceeded when calling PUT /actors/by-id.");
3545
+ case "unknown":
3546
+ throw new RivetError({
3547
+ message: _response.error.errorMessage
3548
+ });
3549
+ }
3550
+ }
3551
+ /**
3552
+ * 2 round trips:
3553
+ *
3554
+ * - GET /actors/names (fanout)
3555
+ * - [api-peer] namespace::ops::resolve_for_name_global
3556
+ *
3557
+ * @param {Rivet.ActorsListNamesRequest} request
3558
+ * @param {RivetClient.RequestOptions} requestOptions - Request-specific configuration.
3559
+ *
3560
+ * @example
3561
+ * await client.actorsListNames({
3562
+ * namespace: "namespace"
3563
+ * })
3564
+ */
3565
+ async actorsListNames(request, requestOptions) {
3566
+ const { namespace, limit, cursor } = request;
3567
+ const _queryParams = {};
3568
+ _queryParams["namespace"] = namespace;
3569
+ if (limit != null) {
3570
+ _queryParams["limit"] = limit.toString();
3571
+ }
3572
+ if (cursor != null) {
3573
+ _queryParams["cursor"] = cursor;
3574
+ }
3575
+ const _response = await (this._options.fetcher ?? fetcher)({
3576
+ url: (0, import_url_join4.default)(
3577
+ await Supplier.get(this._options.baseUrl) ?? await Supplier.get(this._options.environment),
3578
+ "actors/names"
3579
+ ),
3580
+ method: "GET",
3581
+ headers: {
3582
+ "X-Fern-Language": "JavaScript",
3583
+ "X-Fern-Runtime": RUNTIME.type,
3584
+ "X-Fern-Runtime-Version": RUNTIME.version,
3585
+ ...requestOptions == null ? void 0 : requestOptions.headers
3586
+ },
3587
+ contentType: "application/json",
3588
+ queryParameters: _queryParams,
3589
+ requestType: "json",
3590
+ timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 18e4,
3591
+ maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries,
3592
+ abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal
3593
+ });
3594
+ if (_response.ok) {
3595
+ return ActorsListNamesResponse.parseOrThrow(_response.body, {
3596
+ unrecognizedObjectKeys: "passthrough",
3597
+ allowUnrecognizedUnionMembers: true,
3598
+ allowUnrecognizedEnumValues: true,
3599
+ skipValidation: true,
3600
+ breadcrumbsPrefix: ["response"]
3601
+ });
3602
+ }
3603
+ if (_response.error.reason === "status-code") {
3604
+ throw new RivetError({
3605
+ statusCode: _response.error.statusCode,
3606
+ body: _response.error.body
3607
+ });
3608
+ }
3609
+ switch (_response.error.reason) {
3610
+ case "non-json":
3611
+ throw new RivetError({
3612
+ statusCode: _response.error.statusCode,
3613
+ body: _response.error.rawBody
3614
+ });
3615
+ case "timeout":
3616
+ throw new RivetTimeoutError("Timeout exceeded when calling GET /actors/names.");
3617
+ case "unknown":
3618
+ throw new RivetError({
3619
+ message: _response.error.errorMessage
3620
+ });
3621
+ }
3622
+ }
3623
+ /**
3624
+ * 2 round trip:
3625
+ *
3626
+ * - GET /actors/{}
3627
+ * - [api-peer] namespace::ops::resolve_for_name_global
3628
+ *
3629
+ * @param {Rivet.RivetId} actorId
3630
+ * @param {Rivet.ActorsGetRequest} request
3631
+ * @param {RivetClient.RequestOptions} requestOptions - Request-specific configuration.
3632
+ *
3633
+ * @example
3634
+ * await client.actorsGet("actor_id")
3635
+ */
3636
+ async actorsGet(actorId, request = {}, requestOptions) {
3637
+ const { namespace } = request;
3638
+ const _queryParams = {};
3639
+ if (namespace != null) {
3640
+ _queryParams["namespace"] = namespace;
3641
+ }
3642
+ const _response = await (this._options.fetcher ?? fetcher)({
3643
+ url: (0, import_url_join4.default)(
3644
+ await Supplier.get(this._options.baseUrl) ?? await Supplier.get(this._options.environment),
3645
+ `actors/${encodeURIComponent(RivetId.jsonOrThrow(actorId))}`
3646
+ ),
3647
+ method: "GET",
3648
+ headers: {
3649
+ "X-Fern-Language": "JavaScript",
3650
+ "X-Fern-Runtime": RUNTIME.type,
3651
+ "X-Fern-Runtime-Version": RUNTIME.version,
3652
+ ...requestOptions == null ? void 0 : requestOptions.headers
3653
+ },
3654
+ contentType: "application/json",
3655
+ queryParameters: _queryParams,
3656
+ requestType: "json",
3657
+ timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 18e4,
3658
+ maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries,
3659
+ abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal
3660
+ });
3661
+ if (_response.ok) {
3662
+ return ActorsGetResponse.parseOrThrow(_response.body, {
3663
+ unrecognizedObjectKeys: "passthrough",
3664
+ allowUnrecognizedUnionMembers: true,
3665
+ allowUnrecognizedEnumValues: true,
3666
+ skipValidation: true,
3667
+ breadcrumbsPrefix: ["response"]
3668
+ });
3669
+ }
3670
+ if (_response.error.reason === "status-code") {
3671
+ throw new RivetError({
3672
+ statusCode: _response.error.statusCode,
3673
+ body: _response.error.body
3674
+ });
3675
+ }
3676
+ switch (_response.error.reason) {
3677
+ case "non-json":
3678
+ throw new RivetError({
3679
+ statusCode: _response.error.statusCode,
3680
+ body: _response.error.rawBody
3681
+ });
3682
+ case "timeout":
3683
+ throw new RivetTimeoutError("Timeout exceeded when calling GET /actors/{actor_id}.");
3684
+ case "unknown":
3685
+ throw new RivetError({
3686
+ message: _response.error.errorMessage
3687
+ });
3688
+ }
3689
+ }
3690
+ /**
3691
+ * 2 round trip:
3692
+ *
3693
+ * - DELETE /actors/{}
3694
+ * - [api-peer] namespace::ops::resolve_for_name_global
3695
+ *
3696
+ * @param {Rivet.RivetId} actorId
3697
+ * @param {Rivet.ActorsDeleteRequest} request
3698
+ * @param {RivetClient.RequestOptions} requestOptions - Request-specific configuration.
3699
+ *
3700
+ * @example
3701
+ * await client.actorsDelete("actor_id")
3702
+ */
3703
+ async actorsDelete(actorId, request = {}, requestOptions) {
3704
+ const { namespace } = request;
3705
+ const _queryParams = {};
3706
+ if (namespace != null) {
3707
+ _queryParams["namespace"] = namespace;
3708
+ }
3709
+ const _response = await (this._options.fetcher ?? fetcher)({
3710
+ url: (0, import_url_join4.default)(
3711
+ await Supplier.get(this._options.baseUrl) ?? await Supplier.get(this._options.environment),
3712
+ `actors/${encodeURIComponent(RivetId.jsonOrThrow(actorId))}`
3713
+ ),
3714
+ method: "DELETE",
3715
+ headers: {
3716
+ "X-Fern-Language": "JavaScript",
3717
+ "X-Fern-Runtime": RUNTIME.type,
3718
+ "X-Fern-Runtime-Version": RUNTIME.version,
3719
+ ...requestOptions == null ? void 0 : requestOptions.headers
3720
+ },
3721
+ contentType: "application/json",
3722
+ queryParameters: _queryParams,
3723
+ requestType: "json",
3724
+ timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 18e4,
3725
+ maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries,
3726
+ abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal
3727
+ });
3728
+ if (_response.ok) {
3729
+ return ActorsDeleteResponse.parseOrThrow(_response.body, {
3730
+ unrecognizedObjectKeys: "passthrough",
3731
+ allowUnrecognizedUnionMembers: true,
3732
+ allowUnrecognizedEnumValues: true,
3733
+ skipValidation: true,
3734
+ breadcrumbsPrefix: ["response"]
3735
+ });
3736
+ }
3737
+ if (_response.error.reason === "status-code") {
3738
+ throw new RivetError({
3739
+ statusCode: _response.error.statusCode,
3740
+ body: _response.error.body
3741
+ });
3742
+ }
3743
+ switch (_response.error.reason) {
3744
+ case "non-json":
3745
+ throw new RivetError({
3746
+ statusCode: _response.error.statusCode,
3747
+ body: _response.error.rawBody
3748
+ });
3749
+ case "timeout":
3750
+ throw new RivetTimeoutError("Timeout exceeded when calling DELETE /actors/{actor_id}.");
3751
+ case "unknown":
3752
+ throw new RivetError({
3753
+ message: _response.error.errorMessage
3754
+ });
3755
+ }
3756
+ }
3757
+ };
3758
+ // Annotate the CommonJS export names for ESM import in node:
3759
+ 0 && (module.exports = {
3760
+ Rivet,
3761
+ RivetClient,
3762
+ RivetError,
3763
+ RivetTimeoutError,
3764
+ serialization
3765
+ });