@nice-code/action 0.0.15

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 (26) hide show
  1. package/build/index.js +3753 -0
  2. package/build/types/ActionDomain/NiceActionDomain.d.ts +67 -0
  3. package/build/types/ActionDomain/NiceActionDomain.types.d.ts +79 -0
  4. package/build/types/ActionDomain/createActionDomain.d.ts +5 -0
  5. package/build/types/ActionRequestResponse/ActionRequester/NiceActionRequester.d.ts +31 -0
  6. package/build/types/ActionRequestResponse/ActionResponder/NiceActionResponder.d.ts +49 -0
  7. package/build/types/ActionRequestResponse/ActionResponder/NiceActionResponder.types.d.ts +7 -0
  8. package/build/types/ActionRequestResponse/ActionResponder/NiceActionResponderEnvironment.d.ts +42 -0
  9. package/build/types/ActionSchema/NiceActionSchema.d.ts +101 -0
  10. package/build/types/ActionSchema/NiceActionSchema.types.d.ts +32 -0
  11. package/build/types/ActionSchema/action.d.ts +2 -0
  12. package/build/types/NiceAction/ActionSchema/NiceActionSchema.d.ts +99 -0
  13. package/build/types/NiceAction/ActionSchema/NiceActionSchema.types.d.ts +31 -0
  14. package/build/types/NiceAction/ActionSchema/NiceActionSchemaBuilder.d.ts +1 -0
  15. package/build/types/NiceAction/ActionSchema/action.d.ts +2 -0
  16. package/build/types/NiceAction/NiceAction.d.ts +64 -0
  17. package/build/types/NiceAction/NiceAction.types.d.ts +81 -0
  18. package/build/types/NiceAction/NiceActionPrimed.d.ts +59 -0
  19. package/build/types/NiceAction/NiceActionPrimed.schema.d.ts +8 -0
  20. package/build/types/NiceAction/NiceActionResponse.d.ts +32 -0
  21. package/build/types/errors/err_nice_action.d.ts +62 -0
  22. package/build/types/index.d.ts +18 -0
  23. package/build/types/test/nice_action_test_schema.d.ts +30 -0
  24. package/build/types/utils/isActionResponseJsonObject.d.ts +2 -0
  25. package/build/types/utils/isPrimedActionJsonObject.d.ts +2 -0
  26. package/package.json +41 -0
package/build/index.js ADDED
@@ -0,0 +1,3753 @@
1
+ // src/ActionRequestResponse/ActionRequester/NiceActionRequester.ts
2
+ class NiceActionRequester {
3
+ cases = [];
4
+ _defaultRequester;
5
+ async handleAction(action) {
6
+ for (const actionCase of this.cases) {
7
+ if (!actionCase._matcher(action))
8
+ continue;
9
+ return await actionCase._requester(action);
10
+ }
11
+ if (this._defaultRequester) {
12
+ return await this._defaultRequester(action);
13
+ }
14
+ throw new Error(`No handler found for action "${action.coreAction.id}" in domain "${action.coreAction.domain}"`);
15
+ }
16
+ forDomain(domain, handler) {
17
+ this.cases.push({
18
+ _matcher: (action) => domain.isExactActionDomain(action),
19
+ _requester: handler
20
+ });
21
+ return this;
22
+ }
23
+ forActionId(domain, id, handler) {
24
+ this.cases.push({
25
+ _matcher: (action) => domain.isExactActionDomain(action) && action.coreAction.id === id,
26
+ _requester: handler
27
+ });
28
+ return this;
29
+ }
30
+ forActionIds(domain, ids, handler) {
31
+ this.cases.push({
32
+ _matcher: (action) => domain.isExactActionDomain(action) && ids.includes(action.coreAction.id),
33
+ _requester: handler
34
+ });
35
+ return this;
36
+ }
37
+ setDefaultHandler(handler) {
38
+ this._defaultRequester = handler;
39
+ return this;
40
+ }
41
+ }
42
+
43
+ // ../../node_modules/.bun/http-status-codes@2.3.0/node_modules/http-status-codes/build/es/legacy.js
44
+ var ACCEPTED = 202;
45
+ var BAD_GATEWAY = 502;
46
+ var BAD_REQUEST = 400;
47
+ var CONFLICT = 409;
48
+ var CONTINUE = 100;
49
+ var CREATED = 201;
50
+ var EXPECTATION_FAILED = 417;
51
+ var FORBIDDEN = 403;
52
+ var GATEWAY_TIMEOUT = 504;
53
+ var GONE = 410;
54
+ var HTTP_VERSION_NOT_SUPPORTED = 505;
55
+ var IM_A_TEAPOT = 418;
56
+ var INSUFFICIENT_SPACE_ON_RESOURCE = 419;
57
+ var INSUFFICIENT_STORAGE = 507;
58
+ var INTERNAL_SERVER_ERROR = 500;
59
+ var LENGTH_REQUIRED = 411;
60
+ var LOCKED = 423;
61
+ var METHOD_FAILURE = 420;
62
+ var METHOD_NOT_ALLOWED = 405;
63
+ var MOVED_PERMANENTLY = 301;
64
+ var MOVED_TEMPORARILY = 302;
65
+ var MULTI_STATUS = 207;
66
+ var MULTIPLE_CHOICES = 300;
67
+ var NETWORK_AUTHENTICATION_REQUIRED = 511;
68
+ var NO_CONTENT = 204;
69
+ var NON_AUTHORITATIVE_INFORMATION = 203;
70
+ var NOT_ACCEPTABLE = 406;
71
+ var NOT_FOUND = 404;
72
+ var NOT_IMPLEMENTED = 501;
73
+ var NOT_MODIFIED = 304;
74
+ var OK = 200;
75
+ var PARTIAL_CONTENT = 206;
76
+ var PAYMENT_REQUIRED = 402;
77
+ var PERMANENT_REDIRECT = 308;
78
+ var PRECONDITION_FAILED = 412;
79
+ var PRECONDITION_REQUIRED = 428;
80
+ var PROCESSING = 102;
81
+ var PROXY_AUTHENTICATION_REQUIRED = 407;
82
+ var REQUEST_HEADER_FIELDS_TOO_LARGE = 431;
83
+ var REQUEST_TIMEOUT = 408;
84
+ var REQUEST_TOO_LONG = 413;
85
+ var REQUEST_URI_TOO_LONG = 414;
86
+ var REQUESTED_RANGE_NOT_SATISFIABLE = 416;
87
+ var RESET_CONTENT = 205;
88
+ var SEE_OTHER = 303;
89
+ var SERVICE_UNAVAILABLE = 503;
90
+ var SWITCHING_PROTOCOLS = 101;
91
+ var TEMPORARY_REDIRECT = 307;
92
+ var TOO_MANY_REQUESTS = 429;
93
+ var UNAUTHORIZED = 401;
94
+ var UNPROCESSABLE_ENTITY = 422;
95
+ var UNSUPPORTED_MEDIA_TYPE = 415;
96
+ var USE_PROXY = 305;
97
+ var legacy_default = {
98
+ ACCEPTED,
99
+ BAD_GATEWAY,
100
+ BAD_REQUEST,
101
+ CONFLICT,
102
+ CONTINUE,
103
+ CREATED,
104
+ EXPECTATION_FAILED,
105
+ FORBIDDEN,
106
+ GATEWAY_TIMEOUT,
107
+ GONE,
108
+ HTTP_VERSION_NOT_SUPPORTED,
109
+ IM_A_TEAPOT,
110
+ INSUFFICIENT_SPACE_ON_RESOURCE,
111
+ INSUFFICIENT_STORAGE,
112
+ INTERNAL_SERVER_ERROR,
113
+ LENGTH_REQUIRED,
114
+ LOCKED,
115
+ METHOD_FAILURE,
116
+ METHOD_NOT_ALLOWED,
117
+ MOVED_PERMANENTLY,
118
+ MOVED_TEMPORARILY,
119
+ MULTI_STATUS,
120
+ MULTIPLE_CHOICES,
121
+ NETWORK_AUTHENTICATION_REQUIRED,
122
+ NO_CONTENT,
123
+ NON_AUTHORITATIVE_INFORMATION,
124
+ NOT_ACCEPTABLE,
125
+ NOT_FOUND,
126
+ NOT_IMPLEMENTED,
127
+ NOT_MODIFIED,
128
+ OK,
129
+ PARTIAL_CONTENT,
130
+ PAYMENT_REQUIRED,
131
+ PERMANENT_REDIRECT,
132
+ PRECONDITION_FAILED,
133
+ PRECONDITION_REQUIRED,
134
+ PROCESSING,
135
+ PROXY_AUTHENTICATION_REQUIRED,
136
+ REQUEST_HEADER_FIELDS_TOO_LARGE,
137
+ REQUEST_TIMEOUT,
138
+ REQUEST_TOO_LONG,
139
+ REQUEST_URI_TOO_LONG,
140
+ REQUESTED_RANGE_NOT_SATISFIABLE,
141
+ RESET_CONTENT,
142
+ SEE_OTHER,
143
+ SERVICE_UNAVAILABLE,
144
+ SWITCHING_PROTOCOLS,
145
+ TEMPORARY_REDIRECT,
146
+ TOO_MANY_REQUESTS,
147
+ UNAUTHORIZED,
148
+ UNPROCESSABLE_ENTITY,
149
+ UNSUPPORTED_MEDIA_TYPE,
150
+ USE_PROXY
151
+ };
152
+
153
+ // ../../node_modules/.bun/http-status-codes@2.3.0/node_modules/http-status-codes/build/es/utils.js
154
+ var statusCodeToReasonPhrase = {
155
+ "202": "Accepted",
156
+ "502": "Bad Gateway",
157
+ "400": "Bad Request",
158
+ "409": "Conflict",
159
+ "100": "Continue",
160
+ "201": "Created",
161
+ "417": "Expectation Failed",
162
+ "424": "Failed Dependency",
163
+ "403": "Forbidden",
164
+ "504": "Gateway Timeout",
165
+ "410": "Gone",
166
+ "505": "HTTP Version Not Supported",
167
+ "418": "I'm a teapot",
168
+ "419": "Insufficient Space on Resource",
169
+ "507": "Insufficient Storage",
170
+ "500": "Internal Server Error",
171
+ "411": "Length Required",
172
+ "423": "Locked",
173
+ "420": "Method Failure",
174
+ "405": "Method Not Allowed",
175
+ "301": "Moved Permanently",
176
+ "302": "Moved Temporarily",
177
+ "207": "Multi-Status",
178
+ "300": "Multiple Choices",
179
+ "511": "Network Authentication Required",
180
+ "204": "No Content",
181
+ "203": "Non Authoritative Information",
182
+ "406": "Not Acceptable",
183
+ "404": "Not Found",
184
+ "501": "Not Implemented",
185
+ "304": "Not Modified",
186
+ "200": "OK",
187
+ "206": "Partial Content",
188
+ "402": "Payment Required",
189
+ "308": "Permanent Redirect",
190
+ "412": "Precondition Failed",
191
+ "428": "Precondition Required",
192
+ "102": "Processing",
193
+ "103": "Early Hints",
194
+ "426": "Upgrade Required",
195
+ "407": "Proxy Authentication Required",
196
+ "431": "Request Header Fields Too Large",
197
+ "408": "Request Timeout",
198
+ "413": "Request Entity Too Large",
199
+ "414": "Request-URI Too Long",
200
+ "416": "Requested Range Not Satisfiable",
201
+ "205": "Reset Content",
202
+ "303": "See Other",
203
+ "503": "Service Unavailable",
204
+ "101": "Switching Protocols",
205
+ "307": "Temporary Redirect",
206
+ "429": "Too Many Requests",
207
+ "401": "Unauthorized",
208
+ "451": "Unavailable For Legal Reasons",
209
+ "422": "Unprocessable Entity",
210
+ "415": "Unsupported Media Type",
211
+ "305": "Use Proxy",
212
+ "421": "Misdirected Request"
213
+ };
214
+ var reasonPhraseToStatusCode = {
215
+ Accepted: 202,
216
+ "Bad Gateway": 502,
217
+ "Bad Request": 400,
218
+ Conflict: 409,
219
+ Continue: 100,
220
+ Created: 201,
221
+ "Expectation Failed": 417,
222
+ "Failed Dependency": 424,
223
+ Forbidden: 403,
224
+ "Gateway Timeout": 504,
225
+ Gone: 410,
226
+ "HTTP Version Not Supported": 505,
227
+ "I'm a teapot": 418,
228
+ "Insufficient Space on Resource": 419,
229
+ "Insufficient Storage": 507,
230
+ "Internal Server Error": 500,
231
+ "Length Required": 411,
232
+ Locked: 423,
233
+ "Method Failure": 420,
234
+ "Method Not Allowed": 405,
235
+ "Moved Permanently": 301,
236
+ "Moved Temporarily": 302,
237
+ "Multi-Status": 207,
238
+ "Multiple Choices": 300,
239
+ "Network Authentication Required": 511,
240
+ "No Content": 204,
241
+ "Non Authoritative Information": 203,
242
+ "Not Acceptable": 406,
243
+ "Not Found": 404,
244
+ "Not Implemented": 501,
245
+ "Not Modified": 304,
246
+ OK: 200,
247
+ "Partial Content": 206,
248
+ "Payment Required": 402,
249
+ "Permanent Redirect": 308,
250
+ "Precondition Failed": 412,
251
+ "Precondition Required": 428,
252
+ Processing: 102,
253
+ "Early Hints": 103,
254
+ "Upgrade Required": 426,
255
+ "Proxy Authentication Required": 407,
256
+ "Request Header Fields Too Large": 431,
257
+ "Request Timeout": 408,
258
+ "Request Entity Too Large": 413,
259
+ "Request-URI Too Long": 414,
260
+ "Requested Range Not Satisfiable": 416,
261
+ "Reset Content": 205,
262
+ "See Other": 303,
263
+ "Service Unavailable": 503,
264
+ "Switching Protocols": 101,
265
+ "Temporary Redirect": 307,
266
+ "Too Many Requests": 429,
267
+ Unauthorized: 401,
268
+ "Unavailable For Legal Reasons": 451,
269
+ "Unprocessable Entity": 422,
270
+ "Unsupported Media Type": 415,
271
+ "Use Proxy": 305,
272
+ "Misdirected Request": 421
273
+ };
274
+
275
+ // ../../node_modules/.bun/http-status-codes@2.3.0/node_modules/http-status-codes/build/es/utils-functions.js
276
+ function getReasonPhrase(statusCode) {
277
+ var result = statusCodeToReasonPhrase[statusCode.toString()];
278
+ if (!result) {
279
+ throw new Error("Status code does not exist: " + statusCode);
280
+ }
281
+ return result;
282
+ }
283
+ function getStatusCode(reasonPhrase) {
284
+ var result = reasonPhraseToStatusCode[reasonPhrase];
285
+ if (!result) {
286
+ throw new Error("Reason phrase does not exist: " + reasonPhrase);
287
+ }
288
+ return result;
289
+ }
290
+ var getStatusText = getReasonPhrase;
291
+
292
+ // ../../node_modules/.bun/http-status-codes@2.3.0/node_modules/http-status-codes/build/es/status-codes.js
293
+ var StatusCodes;
294
+ (function(StatusCodes2) {
295
+ StatusCodes2[StatusCodes2["CONTINUE"] = 100] = "CONTINUE";
296
+ StatusCodes2[StatusCodes2["SWITCHING_PROTOCOLS"] = 101] = "SWITCHING_PROTOCOLS";
297
+ StatusCodes2[StatusCodes2["PROCESSING"] = 102] = "PROCESSING";
298
+ StatusCodes2[StatusCodes2["EARLY_HINTS"] = 103] = "EARLY_HINTS";
299
+ StatusCodes2[StatusCodes2["OK"] = 200] = "OK";
300
+ StatusCodes2[StatusCodes2["CREATED"] = 201] = "CREATED";
301
+ StatusCodes2[StatusCodes2["ACCEPTED"] = 202] = "ACCEPTED";
302
+ StatusCodes2[StatusCodes2["NON_AUTHORITATIVE_INFORMATION"] = 203] = "NON_AUTHORITATIVE_INFORMATION";
303
+ StatusCodes2[StatusCodes2["NO_CONTENT"] = 204] = "NO_CONTENT";
304
+ StatusCodes2[StatusCodes2["RESET_CONTENT"] = 205] = "RESET_CONTENT";
305
+ StatusCodes2[StatusCodes2["PARTIAL_CONTENT"] = 206] = "PARTIAL_CONTENT";
306
+ StatusCodes2[StatusCodes2["MULTI_STATUS"] = 207] = "MULTI_STATUS";
307
+ StatusCodes2[StatusCodes2["MULTIPLE_CHOICES"] = 300] = "MULTIPLE_CHOICES";
308
+ StatusCodes2[StatusCodes2["MOVED_PERMANENTLY"] = 301] = "MOVED_PERMANENTLY";
309
+ StatusCodes2[StatusCodes2["MOVED_TEMPORARILY"] = 302] = "MOVED_TEMPORARILY";
310
+ StatusCodes2[StatusCodes2["SEE_OTHER"] = 303] = "SEE_OTHER";
311
+ StatusCodes2[StatusCodes2["NOT_MODIFIED"] = 304] = "NOT_MODIFIED";
312
+ StatusCodes2[StatusCodes2["USE_PROXY"] = 305] = "USE_PROXY";
313
+ StatusCodes2[StatusCodes2["TEMPORARY_REDIRECT"] = 307] = "TEMPORARY_REDIRECT";
314
+ StatusCodes2[StatusCodes2["PERMANENT_REDIRECT"] = 308] = "PERMANENT_REDIRECT";
315
+ StatusCodes2[StatusCodes2["BAD_REQUEST"] = 400] = "BAD_REQUEST";
316
+ StatusCodes2[StatusCodes2["UNAUTHORIZED"] = 401] = "UNAUTHORIZED";
317
+ StatusCodes2[StatusCodes2["PAYMENT_REQUIRED"] = 402] = "PAYMENT_REQUIRED";
318
+ StatusCodes2[StatusCodes2["FORBIDDEN"] = 403] = "FORBIDDEN";
319
+ StatusCodes2[StatusCodes2["NOT_FOUND"] = 404] = "NOT_FOUND";
320
+ StatusCodes2[StatusCodes2["METHOD_NOT_ALLOWED"] = 405] = "METHOD_NOT_ALLOWED";
321
+ StatusCodes2[StatusCodes2["NOT_ACCEPTABLE"] = 406] = "NOT_ACCEPTABLE";
322
+ StatusCodes2[StatusCodes2["PROXY_AUTHENTICATION_REQUIRED"] = 407] = "PROXY_AUTHENTICATION_REQUIRED";
323
+ StatusCodes2[StatusCodes2["REQUEST_TIMEOUT"] = 408] = "REQUEST_TIMEOUT";
324
+ StatusCodes2[StatusCodes2["CONFLICT"] = 409] = "CONFLICT";
325
+ StatusCodes2[StatusCodes2["GONE"] = 410] = "GONE";
326
+ StatusCodes2[StatusCodes2["LENGTH_REQUIRED"] = 411] = "LENGTH_REQUIRED";
327
+ StatusCodes2[StatusCodes2["PRECONDITION_FAILED"] = 412] = "PRECONDITION_FAILED";
328
+ StatusCodes2[StatusCodes2["REQUEST_TOO_LONG"] = 413] = "REQUEST_TOO_LONG";
329
+ StatusCodes2[StatusCodes2["REQUEST_URI_TOO_LONG"] = 414] = "REQUEST_URI_TOO_LONG";
330
+ StatusCodes2[StatusCodes2["UNSUPPORTED_MEDIA_TYPE"] = 415] = "UNSUPPORTED_MEDIA_TYPE";
331
+ StatusCodes2[StatusCodes2["REQUESTED_RANGE_NOT_SATISFIABLE"] = 416] = "REQUESTED_RANGE_NOT_SATISFIABLE";
332
+ StatusCodes2[StatusCodes2["EXPECTATION_FAILED"] = 417] = "EXPECTATION_FAILED";
333
+ StatusCodes2[StatusCodes2["IM_A_TEAPOT"] = 418] = "IM_A_TEAPOT";
334
+ StatusCodes2[StatusCodes2["INSUFFICIENT_SPACE_ON_RESOURCE"] = 419] = "INSUFFICIENT_SPACE_ON_RESOURCE";
335
+ StatusCodes2[StatusCodes2["METHOD_FAILURE"] = 420] = "METHOD_FAILURE";
336
+ StatusCodes2[StatusCodes2["MISDIRECTED_REQUEST"] = 421] = "MISDIRECTED_REQUEST";
337
+ StatusCodes2[StatusCodes2["UNPROCESSABLE_ENTITY"] = 422] = "UNPROCESSABLE_ENTITY";
338
+ StatusCodes2[StatusCodes2["LOCKED"] = 423] = "LOCKED";
339
+ StatusCodes2[StatusCodes2["FAILED_DEPENDENCY"] = 424] = "FAILED_DEPENDENCY";
340
+ StatusCodes2[StatusCodes2["UPGRADE_REQUIRED"] = 426] = "UPGRADE_REQUIRED";
341
+ StatusCodes2[StatusCodes2["PRECONDITION_REQUIRED"] = 428] = "PRECONDITION_REQUIRED";
342
+ StatusCodes2[StatusCodes2["TOO_MANY_REQUESTS"] = 429] = "TOO_MANY_REQUESTS";
343
+ StatusCodes2[StatusCodes2["REQUEST_HEADER_FIELDS_TOO_LARGE"] = 431] = "REQUEST_HEADER_FIELDS_TOO_LARGE";
344
+ StatusCodes2[StatusCodes2["UNAVAILABLE_FOR_LEGAL_REASONS"] = 451] = "UNAVAILABLE_FOR_LEGAL_REASONS";
345
+ StatusCodes2[StatusCodes2["INTERNAL_SERVER_ERROR"] = 500] = "INTERNAL_SERVER_ERROR";
346
+ StatusCodes2[StatusCodes2["NOT_IMPLEMENTED"] = 501] = "NOT_IMPLEMENTED";
347
+ StatusCodes2[StatusCodes2["BAD_GATEWAY"] = 502] = "BAD_GATEWAY";
348
+ StatusCodes2[StatusCodes2["SERVICE_UNAVAILABLE"] = 503] = "SERVICE_UNAVAILABLE";
349
+ StatusCodes2[StatusCodes2["GATEWAY_TIMEOUT"] = 504] = "GATEWAY_TIMEOUT";
350
+ StatusCodes2[StatusCodes2["HTTP_VERSION_NOT_SUPPORTED"] = 505] = "HTTP_VERSION_NOT_SUPPORTED";
351
+ StatusCodes2[StatusCodes2["INSUFFICIENT_STORAGE"] = 507] = "INSUFFICIENT_STORAGE";
352
+ StatusCodes2[StatusCodes2["NETWORK_AUTHENTICATION_REQUIRED"] = 511] = "NETWORK_AUTHENTICATION_REQUIRED";
353
+ })(StatusCodes || (StatusCodes = {}));
354
+ // ../../node_modules/.bun/http-status-codes@2.3.0/node_modules/http-status-codes/build/es/index.js
355
+ var __assign = function() {
356
+ __assign = Object.assign || function(t) {
357
+ for (var s, i = 1, n = arguments.length;i < n; i++) {
358
+ s = arguments[i];
359
+ for (var p in s)
360
+ if (Object.prototype.hasOwnProperty.call(s, p))
361
+ t[p] = s[p];
362
+ }
363
+ return t;
364
+ };
365
+ return __assign.apply(this, arguments);
366
+ };
367
+ var es_default = __assign(__assign({}, legacy_default), {
368
+ getStatusCode,
369
+ getStatusText
370
+ });
371
+
372
+ // ../nice-error/src/utils/jsErrorOrCastJsError.ts
373
+ function jsErrorOrCastJsError(error, logMessage = true) {
374
+ if (error instanceof Error) {
375
+ return Object.assign(error, {
376
+ message: error.message
377
+ });
378
+ }
379
+ const message = error?.message ?? (typeof error === "string" ? error : "No error message found");
380
+ if (logMessage) {
381
+ console.error(`An unknown and unstructured error was thrown: ${message}`, error);
382
+ }
383
+ return {
384
+ ...new Error(message),
385
+ ...error
386
+ };
387
+ }
388
+
389
+ // ../nice-error/src/NiceError/nice_error.static.ts
390
+ var DUR_OBJ_PACK_PREFIX = "NE_DUROBJ[[";
391
+ var DUR_OBJ_PACK_SUFFIX = "]]NE_DUROBJ";
392
+
393
+ // ../nice-error/src/utils/packError/causePack.ts
394
+ var causePack = (error) => {
395
+ error._packedState = { cause: error.cause, packedAs: "cause_pack" /* cause_pack */ };
396
+ error.cause = `${DUR_OBJ_PACK_PREFIX}${JSON.stringify(error.toJsonObject())}${DUR_OBJ_PACK_SUFFIX}`;
397
+ return error;
398
+ };
399
+
400
+ // ../nice-error/src/utils/packError/msgPack.ts
401
+ var msgPack = (error) => {
402
+ error._packedState = { message: error.message, packedAs: "msg_pack" /* msg_pack */ };
403
+ error.message = `${DUR_OBJ_PACK_PREFIX}${JSON.stringify(error.toJsonObject())}${DUR_OBJ_PACK_SUFFIX}`;
404
+ return error;
405
+ };
406
+
407
+ // ../nice-error/src/utils/packError/packError.ts
408
+ var packError = (error, packType = "msg_pack") => {
409
+ if (packType === "no_pack") {
410
+ return error;
411
+ }
412
+ if (packType === "msg_pack") {
413
+ return msgPack(error);
414
+ }
415
+ return causePack(error);
416
+ };
417
+
418
+ // ../nice-error/src/NiceError/NiceError.ts
419
+ class NiceError extends Error {
420
+ name = "NiceError";
421
+ def;
422
+ ids;
423
+ wasntNice;
424
+ httpStatusCode;
425
+ originError;
426
+ _packedState;
427
+ _errorDataMap;
428
+ constructor(options) {
429
+ super(options.message);
430
+ this.def = options.def;
431
+ this.ids = options.ids;
432
+ this._errorDataMap = options.errorData;
433
+ this.wasntNice = options.wasntNice ?? false;
434
+ this.httpStatusCode = options.httpStatusCode ?? 500;
435
+ if (options.originError != null) {
436
+ this.originError = options.originError;
437
+ }
438
+ }
439
+ hasId(id) {
440
+ return id in this._errorDataMap;
441
+ }
442
+ hasOneOfIds(ids) {
443
+ return ids.some((id) => (id in this._errorDataMap));
444
+ }
445
+ get hasMultiple() {
446
+ return Object.keys(this._errorDataMap).length > 1;
447
+ }
448
+ getIds() {
449
+ return Object.keys(this._errorDataMap);
450
+ }
451
+ getContext(id) {
452
+ const errorData = this._errorDataMap[id];
453
+ const state = errorData?.contextState;
454
+ if (state == null) {
455
+ return;
456
+ }
457
+ if (state.kind === "unhydrated") {
458
+ throw new Error(`[NiceError.getContext] Context for id "${String(id)}" is in the "unhydrated" state. ` + `The error was reconstructed from a serialized payload but has not been deserialized yet. ` + `Call \`niceErrorDefined.hydrate(error)\` to reconstruct the typed context.`);
459
+ }
460
+ return state.value;
461
+ }
462
+ getErrorDataForId(id) {
463
+ return this._errorDataMap[id];
464
+ }
465
+ withOriginError(error) {
466
+ this.originError = jsErrorOrCastJsError(error);
467
+ if (this._packedState?.packedAs !== "cause_pack" /* cause_pack */) {
468
+ this.cause = this.originError;
469
+ }
470
+ return this;
471
+ }
472
+ matches(other) {
473
+ const myDef = this.def;
474
+ const otherDef = other.def;
475
+ if (myDef.domain !== otherDef.domain)
476
+ return false;
477
+ const myIds = this.getIds().map(String).sort();
478
+ const otherIds = other.getIds().map(String).sort();
479
+ if (myIds.length !== otherIds.length)
480
+ return false;
481
+ return myIds.every((id, i) => id === otherIds[i]);
482
+ }
483
+ toJsonObject() {
484
+ const originError = this.originError ? {
485
+ name: this.originError.name,
486
+ message: this.originError.message,
487
+ stack: this.originError.stack,
488
+ cause: this.originError.cause
489
+ } : undefined;
490
+ const def = {
491
+ domain: this.def.domain,
492
+ allDomains: this.def.allDomains
493
+ };
494
+ if (this.def.defaultHttpStatusCode != null) {
495
+ def["defaultHttpStatusCode"] = this.def.defaultHttpStatusCode;
496
+ }
497
+ if (this.def.defaultMessage != null) {
498
+ def["defaultMessage"] = this.def.defaultMessage;
499
+ }
500
+ const errorData = {};
501
+ for (const rawId of Object.keys(this._errorDataMap)) {
502
+ const id = rawId;
503
+ const data = this._errorDataMap[id];
504
+ if (data == null)
505
+ continue;
506
+ let contextState;
507
+ if (data.contextState.kind === "hydrated" /* hydrated */) {
508
+ contextState = {
509
+ kind: "unhydrated" /* unhydrated */,
510
+ serialized: data.contextState.serialized
511
+ };
512
+ } else {
513
+ contextState = data.contextState;
514
+ }
515
+ errorData[id] = { contextState, message: data.message, httpStatusCode: data.httpStatusCode };
516
+ }
517
+ return {
518
+ name: "NiceError",
519
+ def,
520
+ ids: this.ids,
521
+ errorData,
522
+ wasntNice: this.wasntNice,
523
+ message: this.message,
524
+ httpStatusCode: this.httpStatusCode,
525
+ ...this.stack != null ? { stack: this.stack } : {},
526
+ originError
527
+ };
528
+ }
529
+ hydrate(definedNiceError) {
530
+ return definedNiceError.hydrate(this);
531
+ }
532
+ handleWith(cases) {
533
+ for (const c of cases) {
534
+ if (!c._domain.isExact(this))
535
+ continue;
536
+ if (c._ids != null && !this.hasOneOfIds(c._ids))
537
+ continue;
538
+ c._handler(c._domain.hydrate(this));
539
+ return true;
540
+ }
541
+ return false;
542
+ }
543
+ async handleWithAsync(cases) {
544
+ for (const c of cases) {
545
+ if (!c._domain.isExact(this))
546
+ continue;
547
+ if (c._ids != null && !this.hasOneOfIds(c._ids))
548
+ continue;
549
+ await c._handler(c._domain.hydrate(this));
550
+ return true;
551
+ }
552
+ return false;
553
+ }
554
+ get isPacked() {
555
+ return this._packedState != null;
556
+ }
557
+ pack(packType = "msg_pack") {
558
+ if (this.isPacked)
559
+ return this;
560
+ return packError(this, packType);
561
+ }
562
+ unpack() {
563
+ if (this._packedState == null)
564
+ return this;
565
+ if (this._packedState.packedAs === "msg_pack" /* msg_pack */) {
566
+ this.message = this._packedState.message;
567
+ }
568
+ if (this._packedState.packedAs === "cause_pack" /* cause_pack */) {
569
+ this.cause = this._packedState.cause;
570
+ }
571
+ this._packedState = undefined;
572
+ delete this._packedState;
573
+ return this;
574
+ }
575
+ }
576
+
577
+ // ../nice-error/src/NiceError/NiceErrorHydrated.ts
578
+ class NiceErrorHydrated extends NiceError {
579
+ def;
580
+ niceErrorDefined;
581
+ constructor(options) {
582
+ super(options);
583
+ this.def = options.def;
584
+ this.niceErrorDefined = options.niceErrorDefined;
585
+ }
586
+ addContext(context) {
587
+ const newIds = Object.keys(context);
588
+ const newErrorData = {};
589
+ for (const id of newIds) {
590
+ newErrorData[id] = this.niceErrorDefined.reconcileErrorDataForId(id, context[id]);
591
+ }
592
+ const mergedErrorData = {
593
+ ...this._errorDataMap,
594
+ ...newErrorData
595
+ };
596
+ const mergedIds = Array.from(new Set([...this.getIds(), ...Object.keys(context)]));
597
+ return new NiceErrorHydrated({
598
+ def: this.def,
599
+ niceErrorDefined: this.niceErrorDefined,
600
+ ids: mergedIds,
601
+ errorData: mergedErrorData,
602
+ message: this.message,
603
+ wasntNice: this.wasntNice,
604
+ httpStatusCode: this.httpStatusCode,
605
+ originError: this.originError
606
+ });
607
+ }
608
+ addId(...args) {
609
+ const [id, context] = args;
610
+ const reconciledData = this.niceErrorDefined.reconcileErrorDataForId(id, context);
611
+ const errorDataMap = {};
612
+ errorDataMap[id] = reconciledData;
613
+ const mergedContexts = {
614
+ ...this._errorDataMap,
615
+ ...errorDataMap
616
+ };
617
+ const mergedIds = Array.from(new Set([...this.getIds(), id]));
618
+ return new NiceErrorHydrated({
619
+ def: this.def,
620
+ niceErrorDefined: this.niceErrorDefined,
621
+ ids: mergedIds,
622
+ errorData: mergedContexts,
623
+ message: this.message,
624
+ wasntNice: this.wasntNice,
625
+ httpStatusCode: this.httpStatusCode,
626
+ originError: this.originError
627
+ });
628
+ }
629
+ }
630
+
631
+ // ../nice-error/src/NiceErrorDefined/NiceErrorDefined.ts
632
+ class NiceErrorDefined {
633
+ domain;
634
+ allDomains;
635
+ defaultHttpStatusCode;
636
+ defaultMessage;
637
+ _schema;
638
+ _definedChildNiceErrors = [];
639
+ _definedParentNiceError;
640
+ _setPack;
641
+ _packAsFn;
642
+ constructor(definition) {
643
+ this.domain = definition.domain;
644
+ this.allDomains = definition.allDomains;
645
+ this._schema = definition.schema;
646
+ if (definition.packAs != null) {
647
+ this._packAsFn = definition.packAs;
648
+ }
649
+ if (definition.defaultHttpStatusCode != null) {
650
+ this.defaultHttpStatusCode = definition.defaultHttpStatusCode;
651
+ }
652
+ if (definition.defaultMessage != null) {
653
+ this.defaultMessage = definition.defaultMessage;
654
+ }
655
+ }
656
+ createChildDomain(subErrorDef) {
657
+ const child = new NiceErrorDefined({
658
+ domain: subErrorDef.domain,
659
+ allDomains: [subErrorDef.domain, ...this.allDomains],
660
+ schema: subErrorDef.schema,
661
+ defaultHttpStatusCode: subErrorDef.defaultHttpStatusCode,
662
+ defaultMessage: subErrorDef.defaultMessage
663
+ });
664
+ this.addChildNiceErrorDefined(child);
665
+ child.addParentNiceErrorDefined(this);
666
+ if (subErrorDef.packAs != null) {
667
+ child._packAsFn = subErrorDef.packAs;
668
+ } else if (this._setPack) {
669
+ child.packAs(this._setPack);
670
+ } else if (this._packAsFn) {
671
+ child._packAsFn = this._packAsFn;
672
+ }
673
+ return child;
674
+ }
675
+ addParentNiceErrorDefined(parentError) {
676
+ if (this._definedParentNiceError?.domain === parentError.domain) {
677
+ return;
678
+ }
679
+ this._definedParentNiceError = {
680
+ domain: parentError.domain,
681
+ definedError: parentError
682
+ };
683
+ }
684
+ addChildNiceErrorDefined(child) {
685
+ if (this._definedChildNiceErrors.some((linked) => linked.domain === child.domain)) {
686
+ return;
687
+ }
688
+ this._definedChildNiceErrors.push({
689
+ domain: child.domain,
690
+ definedError: child
691
+ });
692
+ if (this._definedParentNiceError) {
693
+ this._definedParentNiceError.definedError.addChildNiceErrorDefined(child);
694
+ }
695
+ }
696
+ packAs(pack) {
697
+ this._setPack = pack;
698
+ return this;
699
+ }
700
+ createError(input) {
701
+ const err = new NiceErrorHydrated(input);
702
+ const packType = this._setPack ?? this._packAsFn?.();
703
+ if (packType != null && packType !== "no_pack") {
704
+ return err.pack(packType);
705
+ }
706
+ return err;
707
+ }
708
+ hydrate(error) {
709
+ const errDef = error.def;
710
+ if (errDef.domain !== this.domain) {
711
+ throw new Error(`[NiceErrorDefined.hydrate] Domain mismatch: this definition is "${this.domain}" ` + `but the error belongs to "${errDef.domain}". ` + `Call \`niceErrorDefined.is(error)\` before hydrating to ensure compatibility.`);
712
+ }
713
+ const reconciledErrorData = {};
714
+ for (const id of error.getIds()) {
715
+ const existingData = error.getErrorDataForId(id);
716
+ if (existingData == null)
717
+ continue;
718
+ let contextState = existingData.contextState;
719
+ if (contextState.kind === "unhydrated") {
720
+ const entry = this._schema[id];
721
+ const deserialize = entry?.context?.serialization?.fromJsonSerializable;
722
+ if (deserialize != null) {
723
+ contextState = {
724
+ kind: "hydrated" /* hydrated */,
725
+ value: deserialize(contextState.serialized),
726
+ serialized: contextState.serialized
727
+ };
728
+ }
729
+ }
730
+ reconciledErrorData[id] = {
731
+ contextState,
732
+ message: existingData.message,
733
+ httpStatusCode: existingData.httpStatusCode
734
+ };
735
+ }
736
+ return new NiceErrorHydrated({
737
+ def: this._buildDef(),
738
+ niceErrorDefined: this,
739
+ ids: error.ids,
740
+ errorData: reconciledErrorData,
741
+ message: error.message,
742
+ httpStatusCode: error.httpStatusCode,
743
+ wasntNice: error.wasntNice,
744
+ originError: error.originError
745
+ });
746
+ }
747
+ fromId(...args) {
748
+ const [id, context] = args;
749
+ const reconciledData = this.reconcileErrorDataForId(id, context);
750
+ const errorData = {};
751
+ errorData[id] = reconciledData;
752
+ return this.createError({
753
+ def: this._buildDef(),
754
+ niceErrorDefined: this,
755
+ ids: [id],
756
+ errorData,
757
+ message: reconciledData.message,
758
+ httpStatusCode: reconciledData.httpStatusCode
759
+ });
760
+ }
761
+ fromContext(context) {
762
+ const ids = Object.keys(context);
763
+ if (ids.length === 0) {
764
+ throw new Error("[NiceErrorDefined.fromContext] context object must contain at least one error id.");
765
+ }
766
+ const errorData = {};
767
+ for (const id of ids) {
768
+ errorData[id] = this.reconcileErrorDataForId(id, context[id]);
769
+ }
770
+ const primaryId = ids[0];
771
+ return this.createError({
772
+ def: this._buildDef(),
773
+ niceErrorDefined: this,
774
+ ids,
775
+ errorData,
776
+ message: errorData[primaryId].message,
777
+ httpStatusCode: errorData[primaryId].httpStatusCode
778
+ });
779
+ }
780
+ isExact(error) {
781
+ if (!(error instanceof NiceError))
782
+ return false;
783
+ const errDef = error.def;
784
+ return errDef.domain === this.domain;
785
+ }
786
+ isThisOrChild(error) {
787
+ if (!(error instanceof NiceError))
788
+ return false;
789
+ const errDef = error.def;
790
+ return errDef.domain === this.domain || this.allDomains.includes(errDef.domain);
791
+ }
792
+ isParentOf(target) {
793
+ const allDomains = target instanceof NiceError ? target.def.allDomains : target.allDomains;
794
+ return Array.isArray(allDomains) && allDomains.includes(this.domain);
795
+ }
796
+ _buildDef() {
797
+ return {
798
+ domain: this.domain,
799
+ allDomains: this.allDomains,
800
+ schema: this._schema
801
+ };
802
+ }
803
+ _resolveMessage(id, context) {
804
+ const entry = this._schema[id];
805
+ if (typeof entry?.message === "function") {
806
+ return entry.message(context);
807
+ }
808
+ if (typeof entry?.message === "string") {
809
+ return entry.message;
810
+ }
811
+ return this.defaultMessage ?? `[${this.domain}::${id}] An error occurred.`;
812
+ }
813
+ _resolveHttpStatusCode(id, context) {
814
+ const entry = this._schema[id];
815
+ let httpStatusCode;
816
+ if (typeof entry?.httpStatusCode === "function") {
817
+ httpStatusCode = entry.httpStatusCode(context);
818
+ }
819
+ if (typeof entry?.httpStatusCode === "number") {
820
+ httpStatusCode = entry.httpStatusCode;
821
+ }
822
+ return typeof httpStatusCode === "number" ? httpStatusCode : this.defaultHttpStatusCode ?? 500;
823
+ }
824
+ reconcileErrorDataForId(id, context) {
825
+ const message = this._resolveMessage(id, context);
826
+ const httpStatusCode = this._resolveHttpStatusCode(id, context);
827
+ const entry = this._schema[id];
828
+ let contextState;
829
+ if (context != null && entry?.context?.serialization != null) {
830
+ const serialized = entry.context.serialization.toJsonSerializable(context);
831
+ contextState = { kind: "hydrated" /* hydrated */, value: context, serialized };
832
+ } else {
833
+ contextState = { kind: "serde_unset" /* serde_unset */, value: context };
834
+ }
835
+ return { contextState, message, httpStatusCode };
836
+ }
837
+ }
838
+
839
+ // ../nice-error/src/NiceErrorDefined/defineNiceError.ts
840
+ var defineNiceError = (definition) => {
841
+ return new NiceErrorDefined({
842
+ domain: definition.domain,
843
+ allDomains: [definition.domain],
844
+ schema: definition.schema,
845
+ ...definition.packAs != null ? { packAs: definition.packAs } : {}
846
+ });
847
+ };
848
+
849
+ // ../nice-error/src/NiceErrorDefined/err.ts
850
+ function err(meta) {
851
+ return meta ?? {};
852
+ }
853
+
854
+ // ../nice-error/src/internal/nice_core_errors.ts
855
+ var err_nice = defineNiceError({
856
+ domain: "err_nice",
857
+ schema: {}
858
+ });
859
+ var err_cast_not_nice = err_nice.createChildDomain({
860
+ domain: "err_cast_not_nice",
861
+ defaultHttpStatusCode: StatusCodes.UNPROCESSABLE_ENTITY,
862
+ schema: {
863
+ ["native_error" /* js_error */]: err({
864
+ context: {
865
+ required: true
866
+ },
867
+ message: ({ jsError }) => `A native JavaScript Error was encountered during casting: ${jsError.message}`,
868
+ httpStatusCode: StatusCodes.INTERNAL_SERVER_ERROR
869
+ }),
870
+ ["js_error_like_object" /* js_error_like_object */]: err({
871
+ context: {
872
+ required: true
873
+ },
874
+ message: ({ jsErrorObject }) => `An object resembling a JavaScript Error was encountered during casting: [${jsErrorObject.name}] ${jsErrorObject.message}`,
875
+ httpStatusCode: StatusCodes.INTERNAL_SERVER_ERROR
876
+ }),
877
+ ["nullish_value" /* nullish_value */]: err({
878
+ context: {
879
+ required: true
880
+ },
881
+ message: ({ value }) => `A nullish value [${value === null ? "null" : "undefined"}] was encountered during casting`
882
+ }),
883
+ ["js_data_type" /* js_data_type */]: err({
884
+ context: {
885
+ required: true
886
+ },
887
+ message: ({ jsDataType, jsDataValue }) => {
888
+ let inspectedValue;
889
+ try {
890
+ inspectedValue = JSON.stringify(jsDataValue);
891
+ } catch {}
892
+ return `A value of type [${jsDataType}] with value [${inspectedValue ?? "UNSERIALIZABLE"}] was encountered during casting, which is not a valid error type`;
893
+ }
894
+ }),
895
+ ["js_other" /* js_other */]: err({
896
+ context: {
897
+ required: true
898
+ },
899
+ message: ({ jsDataValue }) => {
900
+ let inspectedValue;
901
+ try {
902
+ inspectedValue = JSON.stringify(jsDataValue);
903
+ } catch {}
904
+ return `An unhandled type [${typeof jsDataValue}] with value [${inspectedValue ?? "UNSERIALIZABLE"}] was encountered during casting, which is not a valid error type`;
905
+ }
906
+ })
907
+ }
908
+ });
909
+ // ../nice-error/src/utils/isNiceErrorObject.ts
910
+ function isNiceErrorObject(obj) {
911
+ if (typeof obj !== "object" || obj == null)
912
+ return false;
913
+ const o = obj;
914
+ if (o["name"] !== "NiceError" || typeof o["message"] !== "string" || typeof o["wasntNice"] !== "boolean" || typeof o["httpStatusCode"] !== "number") {
915
+ return false;
916
+ }
917
+ const def = o["def"];
918
+ if (typeof def !== "object" || def == null)
919
+ return false;
920
+ const d = def;
921
+ if (typeof d["domain"] !== "string" || !Array.isArray(d["allDomains"]))
922
+ return false;
923
+ const errorData = o["errorData"];
924
+ if (errorData != null) {
925
+ if (typeof errorData !== "object")
926
+ return false;
927
+ for (const entry of Object.values(errorData)) {
928
+ if (entry == null)
929
+ continue;
930
+ if (typeof entry !== "object")
931
+ return false;
932
+ const e = entry;
933
+ const state = e["contextState"];
934
+ if (state == null || typeof state !== "object")
935
+ return false;
936
+ const kind = state["kind"];
937
+ if (kind !== "serde_unset" /* serde_unset */ && kind !== "unhydrated" /* unhydrated */)
938
+ return false;
939
+ }
940
+ }
941
+ return true;
942
+ }
943
+
944
+ // ../nice-error/src/utils/isRegularErrorObject.ts
945
+ function isRegularErrorJsonObject(obj) {
946
+ if (typeof obj !== "object" || obj == null)
947
+ return false;
948
+ const o = obj;
949
+ return typeof o["name"] === "string" && typeof o["message"] === "string";
950
+ }
951
+
952
+ // ../../node_modules/.bun/tslog@4.10.2/node_modules/tslog/esm/urlToObj.js
953
+ function urlToObject(url) {
954
+ return {
955
+ href: url.href,
956
+ protocol: url.protocol,
957
+ username: url.username,
958
+ password: url.password,
959
+ host: url.host,
960
+ hostname: url.hostname,
961
+ port: url.port,
962
+ pathname: url.pathname,
963
+ search: url.search,
964
+ searchParams: [...url.searchParams].map(([key, value]) => ({ key, value })),
965
+ hash: url.hash,
966
+ origin: url.origin
967
+ };
968
+ }
969
+
970
+ // ../../node_modules/.bun/tslog@4.10.2/node_modules/tslog/esm/prettyLogStyles.js
971
+ var prettyLogStyles = {
972
+ reset: [0, 0],
973
+ bold: [1, 22],
974
+ dim: [2, 22],
975
+ italic: [3, 23],
976
+ underline: [4, 24],
977
+ overline: [53, 55],
978
+ inverse: [7, 27],
979
+ hidden: [8, 28],
980
+ strikethrough: [9, 29],
981
+ black: [30, 39],
982
+ red: [31, 39],
983
+ green: [32, 39],
984
+ yellow: [33, 39],
985
+ blue: [34, 39],
986
+ magenta: [35, 39],
987
+ cyan: [36, 39],
988
+ white: [37, 39],
989
+ blackBright: [90, 39],
990
+ redBright: [91, 39],
991
+ greenBright: [92, 39],
992
+ yellowBright: [93, 39],
993
+ blueBright: [94, 39],
994
+ magentaBright: [95, 39],
995
+ cyanBright: [96, 39],
996
+ whiteBright: [97, 39],
997
+ bgBlack: [40, 49],
998
+ bgRed: [41, 49],
999
+ bgGreen: [42, 49],
1000
+ bgYellow: [43, 49],
1001
+ bgBlue: [44, 49],
1002
+ bgMagenta: [45, 49],
1003
+ bgCyan: [46, 49],
1004
+ bgWhite: [47, 49],
1005
+ bgBlackBright: [100, 49],
1006
+ bgRedBright: [101, 49],
1007
+ bgGreenBright: [102, 49],
1008
+ bgYellowBright: [103, 49],
1009
+ bgBlueBright: [104, 49],
1010
+ bgMagentaBright: [105, 49],
1011
+ bgCyanBright: [106, 49],
1012
+ bgWhiteBright: [107, 49]
1013
+ };
1014
+
1015
+ // ../../node_modules/.bun/tslog@4.10.2/node_modules/tslog/esm/formatTemplate.js
1016
+ function formatTemplate(settings, template, values, hideUnsetPlaceholder = false) {
1017
+ const templateString = String(template);
1018
+ const ansiColorWrap = (placeholderValue, code) => `\x1B[${code[0]}m${placeholderValue}\x1B[${code[1]}m`;
1019
+ const styleWrap = (value, style) => {
1020
+ if (style != null && typeof style === "string") {
1021
+ return ansiColorWrap(value, prettyLogStyles[style]);
1022
+ } else if (style != null && Array.isArray(style)) {
1023
+ return style.reduce((prevValue, thisStyle) => styleWrap(prevValue, thisStyle), value);
1024
+ } else {
1025
+ if (style != null && style[value.trim()] != null) {
1026
+ return styleWrap(value, style[value.trim()]);
1027
+ } else if (style != null && style["*"] != null) {
1028
+ return styleWrap(value, style["*"]);
1029
+ } else {
1030
+ return value;
1031
+ }
1032
+ }
1033
+ };
1034
+ const defaultStyle = null;
1035
+ return templateString.replace(/{{(.+?)}}/g, (_, placeholder) => {
1036
+ const value = values[placeholder] != null ? String(values[placeholder]) : hideUnsetPlaceholder ? "" : _;
1037
+ return settings.stylePrettyLogs ? styleWrap(value, settings?.prettyLogStyles?.[placeholder] ?? defaultStyle) + ansiColorWrap("", prettyLogStyles.reset) : value;
1038
+ });
1039
+ }
1040
+
1041
+ // ../../node_modules/.bun/tslog@4.10.2/node_modules/tslog/esm/formatNumberAddZeros.js
1042
+ function formatNumberAddZeros(value, digits = 2, addNumber = 0) {
1043
+ if (value != null && isNaN(value)) {
1044
+ return "";
1045
+ }
1046
+ value = value != null ? value + addNumber : value;
1047
+ return digits === 2 ? value == null ? "--" : value < 10 ? "0" + value : value.toString() : value == null ? "---" : value < 10 ? "00" + value : value < 100 ? "0" + value : value.toString();
1048
+ }
1049
+
1050
+ // ../../node_modules/.bun/tslog@4.10.2/node_modules/tslog/esm/internal/metaFormatting.js
1051
+ function buildPrettyMeta(settings, meta) {
1052
+ if (meta == null) {
1053
+ return {
1054
+ text: "",
1055
+ template: settings.prettyLogTemplate,
1056
+ placeholders: {}
1057
+ };
1058
+ }
1059
+ let template = settings.prettyLogTemplate;
1060
+ const placeholderValues = {};
1061
+ if (template.includes("{{yyyy}}.{{mm}}.{{dd}} {{hh}}:{{MM}}:{{ss}}:{{ms}}")) {
1062
+ template = template.replace("{{yyyy}}.{{mm}}.{{dd}} {{hh}}:{{MM}}:{{ss}}:{{ms}}", "{{dateIsoStr}}");
1063
+ } else {
1064
+ if (settings.prettyLogTimeZone === "UTC") {
1065
+ placeholderValues["yyyy"] = meta.date?.getUTCFullYear() ?? "----";
1066
+ placeholderValues["mm"] = formatNumberAddZeros(meta.date?.getUTCMonth(), 2, 1);
1067
+ placeholderValues["dd"] = formatNumberAddZeros(meta.date?.getUTCDate(), 2);
1068
+ placeholderValues["hh"] = formatNumberAddZeros(meta.date?.getUTCHours(), 2);
1069
+ placeholderValues["MM"] = formatNumberAddZeros(meta.date?.getUTCMinutes(), 2);
1070
+ placeholderValues["ss"] = formatNumberAddZeros(meta.date?.getUTCSeconds(), 2);
1071
+ placeholderValues["ms"] = formatNumberAddZeros(meta.date?.getUTCMilliseconds(), 3);
1072
+ } else {
1073
+ placeholderValues["yyyy"] = meta.date?.getFullYear() ?? "----";
1074
+ placeholderValues["mm"] = formatNumberAddZeros(meta.date?.getMonth(), 2, 1);
1075
+ placeholderValues["dd"] = formatNumberAddZeros(meta.date?.getDate(), 2);
1076
+ placeholderValues["hh"] = formatNumberAddZeros(meta.date?.getHours(), 2);
1077
+ placeholderValues["MM"] = formatNumberAddZeros(meta.date?.getMinutes(), 2);
1078
+ placeholderValues["ss"] = formatNumberAddZeros(meta.date?.getSeconds(), 2);
1079
+ placeholderValues["ms"] = formatNumberAddZeros(meta.date?.getMilliseconds(), 3);
1080
+ }
1081
+ }
1082
+ const dateInSettingsTimeZone = settings.prettyLogTimeZone === "UTC" ? meta.date : meta.date != null ? new Date(meta.date.getTime() - meta.date.getTimezoneOffset() * 60000) : undefined;
1083
+ placeholderValues["rawIsoStr"] = dateInSettingsTimeZone?.toISOString() ?? "";
1084
+ placeholderValues["dateIsoStr"] = dateInSettingsTimeZone?.toISOString().replace("T", " ").replace("Z", "") ?? "";
1085
+ placeholderValues["logLevelName"] = meta.logLevelName;
1086
+ placeholderValues["fileNameWithLine"] = meta.path?.fileNameWithLine ?? "";
1087
+ placeholderValues["filePathWithLine"] = meta.path?.filePathWithLine ?? "";
1088
+ placeholderValues["fullFilePath"] = meta.path?.fullFilePath ?? "";
1089
+ let parentNamesString = settings.parentNames?.join(settings.prettyErrorParentNamesSeparator);
1090
+ parentNamesString = parentNamesString != null && meta.name != null ? parentNamesString + settings.prettyErrorParentNamesSeparator : undefined;
1091
+ const combinedName = meta.name != null || parentNamesString != null ? `${parentNamesString ?? ""}${meta.name ?? ""}` : "";
1092
+ placeholderValues["name"] = combinedName;
1093
+ placeholderValues["nameWithDelimiterPrefix"] = combinedName.length > 0 ? settings.prettyErrorLoggerNameDelimiter + combinedName : "";
1094
+ placeholderValues["nameWithDelimiterSuffix"] = combinedName.length > 0 ? combinedName + settings.prettyErrorLoggerNameDelimiter : "";
1095
+ if (settings.overwrite?.addPlaceholders != null) {
1096
+ settings.overwrite.addPlaceholders(meta, placeholderValues);
1097
+ }
1098
+ return {
1099
+ text: formatTemplate(settings, template, placeholderValues),
1100
+ template,
1101
+ placeholders: placeholderValues
1102
+ };
1103
+ }
1104
+
1105
+ // ../../node_modules/.bun/tslog@4.10.2/node_modules/tslog/esm/internal/stackTrace.js
1106
+ var DEFAULT_IGNORE_PATTERNS = [
1107
+ /(?:^|[\\/])node_modules[\\/].*tslog/i,
1108
+ /(?:^|[\\/])deps[\\/].*tslog/i,
1109
+ /tslog[\\/]+src[\\/]+internal[\\/]/i,
1110
+ /tslog[\\/]+src[\\/]BaseLogger/i,
1111
+ /tslog[\\/]+src[\\/]index/i
1112
+ ];
1113
+ function splitStackLines(error) {
1114
+ const stack = typeof error?.stack === "string" ? error.stack : undefined;
1115
+ if (stack == null || stack.length === 0) {
1116
+ return [];
1117
+ }
1118
+ return stack.split(`
1119
+ `).map((line) => line.trimEnd());
1120
+ }
1121
+ function sanitizeStackLines(lines) {
1122
+ return lines.filter((line) => line.length > 0 && !/^\s*Error\b/.test(line));
1123
+ }
1124
+ function toStackFrames(lines, parseLine) {
1125
+ const frames = [];
1126
+ for (const line of lines) {
1127
+ const frame = parseLine(line);
1128
+ if (frame != null) {
1129
+ frames.push(frame);
1130
+ }
1131
+ }
1132
+ return frames;
1133
+ }
1134
+ function findFirstExternalFrameIndex(frames, ignorePatterns = DEFAULT_IGNORE_PATTERNS) {
1135
+ for (let index = 0;index < frames.length; index += 1) {
1136
+ const frame = frames[index];
1137
+ const filePathCandidate = frame.filePath ?? "";
1138
+ const fullPathCandidate = frame.fullFilePath ?? "";
1139
+ if (!ignorePatterns.some((pattern) => pattern.test(filePathCandidate) || pattern.test(fullPathCandidate))) {
1140
+ return index;
1141
+ }
1142
+ }
1143
+ return 0;
1144
+ }
1145
+ function getCleanStackLines(error) {
1146
+ return sanitizeStackLines(splitStackLines(error));
1147
+ }
1148
+ function buildStackTrace(error, parseLine) {
1149
+ return toStackFrames(getCleanStackLines(error), parseLine);
1150
+ }
1151
+ function clampIndex(index, maxExclusive) {
1152
+ if (index < 0) {
1153
+ return 0;
1154
+ }
1155
+ if (index >= maxExclusive) {
1156
+ return Math.max(0, maxExclusive - 1);
1157
+ }
1158
+ return index;
1159
+ }
1160
+ function getDefaultIgnorePatterns() {
1161
+ return [...DEFAULT_IGNORE_PATTERNS];
1162
+ }
1163
+
1164
+ // ../../node_modules/.bun/tslog@4.10.2/node_modules/tslog/esm/internal/errorUtils.js
1165
+ var DEFAULT_CAUSE_DEPTH = 5;
1166
+ function collectErrorCauses(error, options = {}) {
1167
+ const maxDepth = options.maxDepth ?? DEFAULT_CAUSE_DEPTH;
1168
+ const causes = [];
1169
+ const visited = new Set;
1170
+ let current = error;
1171
+ let depth = 0;
1172
+ while (current != null && depth < maxDepth) {
1173
+ const cause = current?.cause;
1174
+ if (cause == null || visited.has(cause)) {
1175
+ break;
1176
+ }
1177
+ visited.add(cause);
1178
+ causes.push(toError(cause));
1179
+ current = cause;
1180
+ depth += 1;
1181
+ }
1182
+ return causes;
1183
+ }
1184
+ function toError(value) {
1185
+ if (value instanceof Error) {
1186
+ return value;
1187
+ }
1188
+ const error = new Error(typeof value === "string" ? value : JSON.stringify(value));
1189
+ if (typeof value === "object" && value != null) {
1190
+ Object.assign(error, value);
1191
+ }
1192
+ return error;
1193
+ }
1194
+
1195
+ // ../../node_modules/.bun/tslog@4.10.2/node_modules/tslog/esm/internal/jsonStringifyRecursive.js
1196
+ function jsonStringifyRecursive(obj) {
1197
+ const cache = new Set;
1198
+ return JSON.stringify(obj, (key, value) => {
1199
+ if (typeof value === "object" && value !== null) {
1200
+ if (cache.has(value)) {
1201
+ return "[Circular]";
1202
+ }
1203
+ cache.add(value);
1204
+ }
1205
+ if (typeof value === "bigint") {
1206
+ return `${value}`;
1207
+ }
1208
+ if (typeof value === "undefined") {
1209
+ return "[undefined]";
1210
+ }
1211
+ return value;
1212
+ });
1213
+ }
1214
+
1215
+ // ../../node_modules/.bun/tslog@4.10.2/node_modules/tslog/esm/internal/util.inspect.polyfill.js
1216
+ function inspect(obj, opts) {
1217
+ const ctx = {
1218
+ seen: [],
1219
+ stylize: stylizeNoColor
1220
+ };
1221
+ if (opts != null) {
1222
+ _extend(ctx, opts);
1223
+ }
1224
+ if (isUndefined(ctx.showHidden))
1225
+ ctx.showHidden = false;
1226
+ if (isUndefined(ctx.depth))
1227
+ ctx.depth = 2;
1228
+ if (isUndefined(ctx.colors))
1229
+ ctx.colors = true;
1230
+ if (isUndefined(ctx.customInspect))
1231
+ ctx.customInspect = true;
1232
+ if (ctx.colors)
1233
+ ctx.stylize = stylizeWithColor;
1234
+ return formatValue(ctx, obj, ctx.depth);
1235
+ }
1236
+ inspect.colors = prettyLogStyles;
1237
+ inspect.styles = {
1238
+ special: "cyan",
1239
+ number: "yellow",
1240
+ boolean: "yellow",
1241
+ undefined: "grey",
1242
+ null: "bold",
1243
+ string: "green",
1244
+ date: "magenta",
1245
+ regexp: "red"
1246
+ };
1247
+ function isBoolean(arg) {
1248
+ return typeof arg === "boolean";
1249
+ }
1250
+ function isUndefined(arg) {
1251
+ return arg === undefined;
1252
+ }
1253
+ function stylizeNoColor(str) {
1254
+ return str;
1255
+ }
1256
+ function stylizeWithColor(str, styleType) {
1257
+ const style = inspect.styles[styleType];
1258
+ if (style != null && inspect?.colors?.[style]?.[0] != null && inspect?.colors?.[style]?.[1] != null) {
1259
+ return "\x1B[" + inspect.colors[style][0] + "m" + str + "\x1B[" + inspect.colors[style][1] + "m";
1260
+ } else {
1261
+ return str;
1262
+ }
1263
+ }
1264
+ function isFunction(arg) {
1265
+ return typeof arg === "function";
1266
+ }
1267
+ function isString(arg) {
1268
+ return typeof arg === "string";
1269
+ }
1270
+ function isNumber(arg) {
1271
+ return typeof arg === "number";
1272
+ }
1273
+ function isNull(arg) {
1274
+ return arg === null;
1275
+ }
1276
+ function hasOwn(obj, prop) {
1277
+ return Object.prototype.hasOwnProperty.call(obj, prop);
1278
+ }
1279
+ function isRegExp(re) {
1280
+ return isObject(re) && objectToString(re) === "[object RegExp]";
1281
+ }
1282
+ function isObject(arg) {
1283
+ return typeof arg === "object" && arg !== null;
1284
+ }
1285
+ function isError(e) {
1286
+ return isObject(e) && (objectToString(e) === "[object Error]" || e instanceof Error);
1287
+ }
1288
+ function isDate(d) {
1289
+ return isObject(d) && objectToString(d) === "[object Date]";
1290
+ }
1291
+ function objectToString(o) {
1292
+ return Object.prototype.toString.call(o);
1293
+ }
1294
+ function arrayToHash(array) {
1295
+ const hash = {};
1296
+ array.forEach((val) => {
1297
+ hash[val] = true;
1298
+ });
1299
+ return hash;
1300
+ }
1301
+ function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
1302
+ const output = [];
1303
+ for (let i = 0, l = value.length;i < l; ++i) {
1304
+ if (hasOwn(value, String(i))) {
1305
+ output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true));
1306
+ } else {
1307
+ output.push("");
1308
+ }
1309
+ }
1310
+ keys.forEach((key) => {
1311
+ if (!key.match(/^\d+$/)) {
1312
+ output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true));
1313
+ }
1314
+ });
1315
+ return output;
1316
+ }
1317
+ function formatError(value) {
1318
+ return "[" + Error.prototype.toString.call(value) + "]";
1319
+ }
1320
+ function formatValue(ctx, value, recurseTimes = 0) {
1321
+ if (ctx.customInspect && value != null && isFunction(value) && value?.inspect !== inspect && !(value?.constructor && value?.constructor.prototype === value)) {
1322
+ if (typeof value.inspect !== "function" && value.toString != null) {
1323
+ return value.toString();
1324
+ }
1325
+ let ret = value?.inspect(recurseTimes, ctx);
1326
+ if (!isString(ret)) {
1327
+ ret = formatValue(ctx, ret, recurseTimes);
1328
+ }
1329
+ return ret;
1330
+ }
1331
+ const primitive = formatPrimitive(ctx, value);
1332
+ if (primitive) {
1333
+ return primitive;
1334
+ }
1335
+ let keys = Object.keys(value);
1336
+ const visibleKeys = arrayToHash(keys);
1337
+ try {
1338
+ if (ctx.showHidden && Object.getOwnPropertyNames) {
1339
+ keys = Object.getOwnPropertyNames(value);
1340
+ }
1341
+ } catch {}
1342
+ if (isError(value) && (keys.indexOf("message") >= 0 || keys.indexOf("description") >= 0)) {
1343
+ return formatError(value);
1344
+ }
1345
+ if (keys.length === 0) {
1346
+ if (isFunction(ctx.stylize)) {
1347
+ if (isFunction(value)) {
1348
+ const name = value.name ? ": " + value.name : "";
1349
+ return ctx.stylize("[Function" + name + "]", "special");
1350
+ }
1351
+ if (isRegExp(value)) {
1352
+ return ctx.stylize(RegExp.prototype.toString.call(value), "regexp");
1353
+ }
1354
+ if (isDate(value)) {
1355
+ return ctx.stylize(Date.prototype.toISOString.call(value), "date");
1356
+ }
1357
+ if (isError(value)) {
1358
+ return formatError(value);
1359
+ }
1360
+ } else {
1361
+ return value;
1362
+ }
1363
+ }
1364
+ let base = "";
1365
+ let array = false;
1366
+ let braces = [`{
1367
+ `, `
1368
+ }`];
1369
+ if (Array.isArray(value)) {
1370
+ array = true;
1371
+ braces = [`[
1372
+ `, `
1373
+ ]`];
1374
+ }
1375
+ if (isFunction(value)) {
1376
+ const n = value.name ? ": " + value.name : "";
1377
+ base = " [Function" + n + "]";
1378
+ }
1379
+ if (isRegExp(value)) {
1380
+ base = " " + RegExp.prototype.toString.call(value);
1381
+ }
1382
+ if (isDate(value)) {
1383
+ base = " " + Date.prototype.toUTCString.call(value);
1384
+ }
1385
+ if (isError(value)) {
1386
+ base = " " + formatError(value);
1387
+ }
1388
+ if (keys.length === 0 && (!array || value.length == 0)) {
1389
+ return braces[0] + base + braces[1];
1390
+ }
1391
+ if (recurseTimes < 0) {
1392
+ if (isRegExp(value)) {
1393
+ return ctx.stylize(RegExp.prototype.toString.call(value), "regexp");
1394
+ } else {
1395
+ return ctx.stylize("[Object]", "special");
1396
+ }
1397
+ }
1398
+ ctx.seen.push(value);
1399
+ let output;
1400
+ if (array) {
1401
+ output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
1402
+ } else {
1403
+ output = keys.map((key) => {
1404
+ return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
1405
+ });
1406
+ }
1407
+ ctx.seen.pop();
1408
+ return reduceToSingleString(output, base, braces);
1409
+ }
1410
+ function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
1411
+ let name, str;
1412
+ let desc = { value: undefined };
1413
+ try {
1414
+ desc.value = value[key];
1415
+ } catch {}
1416
+ try {
1417
+ if (Object.getOwnPropertyDescriptor) {
1418
+ desc = Object.getOwnPropertyDescriptor(value, key) || desc;
1419
+ }
1420
+ } catch {}
1421
+ if (desc.get) {
1422
+ if (desc.set) {
1423
+ str = ctx.stylize("[Getter/Setter]", "special");
1424
+ } else {
1425
+ str = ctx.stylize("[Getter]", "special");
1426
+ }
1427
+ } else {
1428
+ if (desc.set) {
1429
+ str = ctx.stylize("[Setter]", "special");
1430
+ }
1431
+ }
1432
+ if (!hasOwn(visibleKeys, key)) {
1433
+ name = "[" + key + "]";
1434
+ }
1435
+ if (!str) {
1436
+ if (ctx.seen.indexOf(desc.value) < 0) {
1437
+ if (isNull(recurseTimes)) {
1438
+ str = formatValue(ctx, desc.value, undefined);
1439
+ } else {
1440
+ str = formatValue(ctx, desc.value, recurseTimes - 1);
1441
+ }
1442
+ if (str.indexOf(`
1443
+ `) > -1) {
1444
+ if (array) {
1445
+ str = str.split(`
1446
+ `).map((line) => {
1447
+ return " " + line;
1448
+ }).join(`
1449
+ `).substr(2);
1450
+ } else {
1451
+ str = `
1452
+ ` + str.split(`
1453
+ `).map((line) => {
1454
+ return " " + line;
1455
+ }).join(`
1456
+ `);
1457
+ }
1458
+ }
1459
+ } else {
1460
+ str = ctx.stylize("[Circular]", "special");
1461
+ }
1462
+ }
1463
+ if (isUndefined(name)) {
1464
+ if (array && key.match(/^\d+$/)) {
1465
+ return str;
1466
+ }
1467
+ name = JSON.stringify("" + key);
1468
+ if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
1469
+ name = name.substr(1, name.length - 2);
1470
+ name = ctx.stylize(name, "name");
1471
+ } else {
1472
+ name = name.replace(/'/g, "\\'").replace(/\\"/g, "\\'").replace(/(^"|"$)/g, "'");
1473
+ name = ctx.stylize(name, "string");
1474
+ }
1475
+ }
1476
+ return name + ": " + str;
1477
+ }
1478
+ function formatPrimitive(ctx, value) {
1479
+ if (isUndefined(value))
1480
+ return ctx.stylize("undefined", "undefined");
1481
+ if (isString(value)) {
1482
+ const simple = "'" + JSON.stringify(value).replace(/^"|"$/g, "").replace(/'/g, "\\'").replace(/\\"/g, "\\'") + "'";
1483
+ return ctx.stylize(simple, "string");
1484
+ }
1485
+ if (isNumber(value))
1486
+ return ctx.stylize("" + value, "number");
1487
+ if (isBoolean(value))
1488
+ return ctx.stylize("" + value, "boolean");
1489
+ if (isNull(value))
1490
+ return ctx.stylize("null", "null");
1491
+ }
1492
+ function reduceToSingleString(output, base, braces) {
1493
+ return braces[0] + (base === "" ? "" : base + `
1494
+ `) + " " + output.join(`,
1495
+ `) + " " + braces[1];
1496
+ }
1497
+ function _extend(origin, add) {
1498
+ const typedOrigin = { ...origin };
1499
+ if (!add || !isObject(add))
1500
+ return origin;
1501
+ const clonedAdd = { ...add };
1502
+ const keys = Object.keys(add);
1503
+ let i = keys.length;
1504
+ while (i--) {
1505
+ typedOrigin[keys[i]] = clonedAdd[keys[i]];
1506
+ }
1507
+ return typedOrigin;
1508
+ }
1509
+ function formatWithOptions(inspectOptions, ...args) {
1510
+ const ctx = {
1511
+ seen: [],
1512
+ stylize: stylizeNoColor
1513
+ };
1514
+ if (inspectOptions != null) {
1515
+ _extend(ctx, inspectOptions);
1516
+ }
1517
+ const first = args[0];
1518
+ let a = 0;
1519
+ let str = "";
1520
+ let join = "";
1521
+ if (typeof first === "string") {
1522
+ if (args.length === 1) {
1523
+ return first;
1524
+ }
1525
+ let tempStr;
1526
+ let lastPos = 0;
1527
+ for (let i = 0;i < first.length - 1; i++) {
1528
+ if (first.charCodeAt(i) === 37) {
1529
+ const nextChar = first.charCodeAt(++i);
1530
+ if (a + 1 !== args.length) {
1531
+ switch (nextChar) {
1532
+ case 115: {
1533
+ const tempArg = args[++a];
1534
+ if (typeof tempArg === "number") {
1535
+ tempStr = formatPrimitive(ctx, tempArg);
1536
+ } else if (typeof tempArg === "bigint") {
1537
+ tempStr = formatPrimitive(ctx, tempArg);
1538
+ } else if (typeof tempArg !== "object" || tempArg === null) {
1539
+ tempStr = String(tempArg);
1540
+ } else {
1541
+ tempStr = inspect(tempArg, {
1542
+ ...inspectOptions,
1543
+ compact: 3,
1544
+ colors: false,
1545
+ depth: 0
1546
+ });
1547
+ }
1548
+ break;
1549
+ }
1550
+ case 106:
1551
+ tempStr = jsonStringifyRecursive(args[++a]);
1552
+ break;
1553
+ case 100: {
1554
+ const tempNum = args[++a];
1555
+ if (typeof tempNum === "bigint") {
1556
+ tempStr = formatPrimitive(ctx, tempNum);
1557
+ } else if (typeof tempNum === "symbol") {
1558
+ tempStr = "NaN";
1559
+ } else {
1560
+ tempStr = formatPrimitive(ctx, tempNum);
1561
+ }
1562
+ break;
1563
+ }
1564
+ case 79:
1565
+ tempStr = inspect(args[++a], inspectOptions);
1566
+ break;
1567
+ case 111:
1568
+ tempStr = inspect(args[++a], {
1569
+ ...inspectOptions,
1570
+ showHidden: true,
1571
+ showProxy: true,
1572
+ depth: 4
1573
+ });
1574
+ break;
1575
+ case 105: {
1576
+ const tempInteger = args[++a];
1577
+ if (typeof tempInteger === "bigint") {
1578
+ tempStr = formatPrimitive(ctx, tempInteger);
1579
+ } else if (typeof tempInteger === "symbol") {
1580
+ tempStr = "NaN";
1581
+ } else {
1582
+ tempStr = formatPrimitive(ctx, parseInt(tempStr));
1583
+ }
1584
+ break;
1585
+ }
1586
+ case 102: {
1587
+ const tempFloat = args[++a];
1588
+ if (typeof tempFloat === "symbol") {
1589
+ tempStr = "NaN";
1590
+ } else {
1591
+ tempStr = formatPrimitive(ctx, parseInt(tempFloat));
1592
+ }
1593
+ break;
1594
+ }
1595
+ case 99:
1596
+ a += 1;
1597
+ tempStr = "";
1598
+ break;
1599
+ case 37:
1600
+ str += first.slice(lastPos, i);
1601
+ lastPos = i + 1;
1602
+ continue;
1603
+ default:
1604
+ continue;
1605
+ }
1606
+ if (lastPos !== i - 1) {
1607
+ str += first.slice(lastPos, i - 1);
1608
+ }
1609
+ str += tempStr;
1610
+ lastPos = i + 1;
1611
+ } else if (nextChar === 37) {
1612
+ str += first.slice(lastPos, i);
1613
+ lastPos = i + 1;
1614
+ }
1615
+ }
1616
+ }
1617
+ if (lastPos !== 0) {
1618
+ a++;
1619
+ join = " ";
1620
+ if (lastPos < first.length) {
1621
+ str += first.slice(lastPos);
1622
+ }
1623
+ }
1624
+ }
1625
+ while (a < args.length) {
1626
+ const value = args[a];
1627
+ str += join;
1628
+ str += typeof value !== "string" ? inspect(value, inspectOptions) : value;
1629
+ join = " ";
1630
+ a++;
1631
+ }
1632
+ return str;
1633
+ }
1634
+
1635
+ // ../../node_modules/.bun/tslog@4.10.2/node_modules/tslog/esm/internal/environment.js
1636
+ function safeGetCwd() {
1637
+ try {
1638
+ const nodeProcess = globalThis?.process;
1639
+ if (typeof nodeProcess?.cwd === "function") {
1640
+ return nodeProcess.cwd();
1641
+ }
1642
+ } catch {}
1643
+ try {
1644
+ const deno = globalThis?.["Deno"];
1645
+ if (typeof deno?.cwd === "function") {
1646
+ return deno.cwd();
1647
+ }
1648
+ } catch {}
1649
+ return;
1650
+ }
1651
+ function isBrowserEnvironment() {
1652
+ return typeof window !== "undefined" && typeof document !== "undefined";
1653
+ }
1654
+ function consoleSupportsCssStyling() {
1655
+ if (!isBrowserEnvironment()) {
1656
+ return false;
1657
+ }
1658
+ const navigatorObj = globalThis?.navigator;
1659
+ const userAgent = navigatorObj?.userAgent ?? "";
1660
+ if (/firefox/i.test(userAgent)) {
1661
+ return true;
1662
+ }
1663
+ const windowObj = globalThis;
1664
+ if (windowObj?.CSS?.supports?.("color", "#000")) {
1665
+ return true;
1666
+ }
1667
+ return /safari/i.test(userAgent) && !/chrome/i.test(userAgent);
1668
+ }
1669
+
1670
+ // ../../node_modules/.bun/tslog@4.10.2/node_modules/tslog/esm/BaseLogger.js
1671
+ function createLoggerEnvironment() {
1672
+ const runtimeInfo = detectRuntimeInfo();
1673
+ const meta = createRuntimeMeta(runtimeInfo);
1674
+ const usesBrowserStack = runtimeInfo.name === "browser" || runtimeInfo.name === "worker";
1675
+ const callerIgnorePatterns = usesBrowserStack ? [...getDefaultIgnorePatterns(), /node_modules[\\/].*tslog/i] : [...getDefaultIgnorePatterns(), /node:(?:internal|vm)/i, /\binternal[\\/]/i];
1676
+ let cachedCwd;
1677
+ const environment = {
1678
+ getMeta(logLevelId, logLevelName, stackDepthLevel, hideLogPositionForPerformance, name, parentNames) {
1679
+ return Object.assign({}, meta, {
1680
+ name,
1681
+ parentNames,
1682
+ date: new Date,
1683
+ logLevelId,
1684
+ logLevelName,
1685
+ path: !hideLogPositionForPerformance ? environment.getCallerStackFrame(stackDepthLevel) : undefined
1686
+ });
1687
+ },
1688
+ getCallerStackFrame(stackDepthLevel, error = new Error) {
1689
+ const frames = buildStackTrace(error, (line) => parseStackLine(line));
1690
+ if (frames.length === 0) {
1691
+ return {};
1692
+ }
1693
+ const autoIndex = findFirstExternalFrameIndex(frames, callerIgnorePatterns);
1694
+ const useManualIndex = Number.isFinite(stackDepthLevel) && stackDepthLevel >= 0;
1695
+ const resolvedIndex = useManualIndex ? clampIndex(stackDepthLevel, frames.length) : clampIndex(autoIndex, frames.length);
1696
+ return frames[resolvedIndex] ?? {};
1697
+ },
1698
+ getErrorTrace(error) {
1699
+ return buildStackTrace(error, (line) => parseStackLine(line));
1700
+ },
1701
+ isError(value) {
1702
+ return isNativeError(value);
1703
+ },
1704
+ isBuffer(value) {
1705
+ return typeof Buffer !== "undefined" && typeof Buffer.isBuffer === "function" ? Buffer.isBuffer(value) : false;
1706
+ },
1707
+ prettyFormatLogObj(maskedArgs, settings) {
1708
+ return maskedArgs.reduce((result, arg) => {
1709
+ if (environment.isError(arg)) {
1710
+ result.errors.push(environment.prettyFormatErrorObj(arg, settings));
1711
+ } else {
1712
+ result.args.push(arg);
1713
+ }
1714
+ return result;
1715
+ }, { args: [], errors: [] });
1716
+ },
1717
+ prettyFormatErrorObj(error, settings) {
1718
+ const stackLines = formatStackFrames(environment.getErrorTrace(error), settings);
1719
+ const causeSections = collectErrorCauses(error).map((cause, index) => {
1720
+ const header = `Caused by (${index + 1}): ${cause.name ?? "Error"}${cause.message ? `: ${cause.message}` : ""}`;
1721
+ const frames = formatStackFrames(buildStackTrace(cause, (line) => parseStackLine(line)), settings);
1722
+ return [header, ...frames].join(`
1723
+ `);
1724
+ });
1725
+ const placeholderValuesError = {
1726
+ errorName: ` ${error.name} `,
1727
+ errorMessage: formatErrorMessage(error),
1728
+ errorStack: [...stackLines, ...causeSections].join(`
1729
+ `)
1730
+ };
1731
+ return formatTemplate(settings, settings.prettyErrorTemplate, placeholderValuesError);
1732
+ },
1733
+ transportFormatted(logMetaMarkup, logArgs, logErrors, logMeta, settings) {
1734
+ const prettyLogs = settings.stylePrettyLogs !== false;
1735
+ const logErrorsStr = (logErrors.length > 0 && logArgs.length > 0 ? `
1736
+ ` : "") + logErrors.join(`
1737
+ `);
1738
+ const sanitizedMetaMarkup = stripAnsi(logMetaMarkup);
1739
+ const metaMarkupForText = prettyLogs ? logMetaMarkup : sanitizedMetaMarkup;
1740
+ if (shouldUseCss(prettyLogs)) {
1741
+ settings.prettyInspectOptions.colors = false;
1742
+ const formattedArgs2 = formatWithOptionsSafe(settings.prettyInspectOptions, logArgs);
1743
+ const cssMeta = logMeta != null ? buildCssMetaOutput(settings, logMeta) : { text: sanitizedMetaMarkup, styles: [] };
1744
+ const hasCssMeta = cssMeta.text.length > 0 && cssMeta.styles.length > 0;
1745
+ const metaOutput = hasCssMeta ? cssMeta.text : sanitizedMetaMarkup;
1746
+ const output = metaOutput + formattedArgs2 + logErrorsStr;
1747
+ if (hasCssMeta) {
1748
+ console.log(output, ...cssMeta.styles);
1749
+ } else {
1750
+ console.log(output);
1751
+ }
1752
+ return;
1753
+ }
1754
+ settings.prettyInspectOptions.colors = prettyLogs;
1755
+ const formattedArgs = formatWithOptionsSafe(settings.prettyInspectOptions, logArgs);
1756
+ console.log(metaMarkupForText + formattedArgs + logErrorsStr);
1757
+ },
1758
+ transportJSON(json) {
1759
+ console.log(jsonStringifyRecursive(json));
1760
+ }
1761
+ };
1762
+ if (getNodeEnv() === "test") {
1763
+ environment.__resetWorkingDirectoryCacheForTests = () => {
1764
+ cachedCwd = undefined;
1765
+ };
1766
+ }
1767
+ return environment;
1768
+ function parseStackLine(line) {
1769
+ return usesBrowserStack ? parseBrowserStackLine(line) : parseServerStackLine(line);
1770
+ }
1771
+ function parseServerStackLine(rawLine) {
1772
+ if (typeof rawLine !== "string" || rawLine.length === 0) {
1773
+ return;
1774
+ }
1775
+ const trimmedLine = rawLine.trim();
1776
+ if (!trimmedLine.includes(" at ") && !trimmedLine.startsWith("at ")) {
1777
+ return;
1778
+ }
1779
+ const line = trimmedLine.replace(/^at\s+/, "");
1780
+ let method;
1781
+ let location = line;
1782
+ const methodMatch = line.match(/^(.*?)\s+\((.*)\)$/);
1783
+ if (methodMatch) {
1784
+ method = methodMatch[1];
1785
+ location = methodMatch[2];
1786
+ }
1787
+ const sanitizedLocation = location.replace(/^\(/, "").replace(/\)$/, "");
1788
+ const withoutQuery = sanitizedLocation.replace(/\?.*$/, "");
1789
+ let fileLine;
1790
+ let fileColumn;
1791
+ let filePathCandidate = withoutQuery;
1792
+ const segments = withoutQuery.split(":");
1793
+ if (segments.length >= 3 && /^\d+$/.test(segments[segments.length - 1] ?? "")) {
1794
+ fileColumn = segments.pop();
1795
+ fileLine = segments.pop();
1796
+ filePathCandidate = segments.join(":");
1797
+ } else if (segments.length >= 2 && /^\d+$/.test(segments[segments.length - 1] ?? "")) {
1798
+ fileLine = segments.pop();
1799
+ filePathCandidate = segments.join(":");
1800
+ }
1801
+ let normalizedPath = filePathCandidate.replace(/^file:\/\//, "");
1802
+ const cwd = getWorkingDirectory();
1803
+ if (cwd != null && normalizedPath.startsWith(cwd)) {
1804
+ normalizedPath = normalizedPath.slice(cwd.length);
1805
+ normalizedPath = normalizedPath.replace(/^[\\/]/, "");
1806
+ }
1807
+ if (normalizedPath.length === 0) {
1808
+ normalizedPath = filePathCandidate;
1809
+ }
1810
+ const normalizedPathWithoutLine = normalizeFilePath(normalizedPath);
1811
+ const effectivePath = normalizedPathWithoutLine.length > 0 ? normalizedPathWithoutLine : normalizedPath;
1812
+ const pathSegments = effectivePath.split(/\\|\//);
1813
+ const fileName = pathSegments[pathSegments.length - 1];
1814
+ const fileNameWithLine = fileName && fileLine ? `${fileName}:${fileLine}` : undefined;
1815
+ const filePathWithLine = effectivePath && fileLine ? `${effectivePath}:${fileLine}` : undefined;
1816
+ return {
1817
+ fullFilePath: sanitizedLocation,
1818
+ fileName,
1819
+ fileNameWithLine,
1820
+ fileColumn,
1821
+ fileLine,
1822
+ filePath: effectivePath,
1823
+ filePathWithLine,
1824
+ method
1825
+ };
1826
+ }
1827
+ function parseBrowserStackLine(line) {
1828
+ const href = globalThis.location?.origin;
1829
+ if (line == null) {
1830
+ return;
1831
+ }
1832
+ const match = line.match(BROWSER_PATH_REGEX);
1833
+ if (!match) {
1834
+ return;
1835
+ }
1836
+ const filePath = match[1]?.replace(/\?.*$/, "");
1837
+ if (filePath == null) {
1838
+ return;
1839
+ }
1840
+ const pathParts = filePath.split("/");
1841
+ const fileLine = match[2];
1842
+ const fileColumn = match[3];
1843
+ const fileName = pathParts[pathParts.length - 1];
1844
+ return {
1845
+ fullFilePath: href ? `${href}${filePath}` : filePath,
1846
+ fileName,
1847
+ fileNameWithLine: fileName && fileLine ? `${fileName}:${fileLine}` : undefined,
1848
+ fileColumn,
1849
+ fileLine,
1850
+ filePath,
1851
+ filePathWithLine: fileLine ? `${filePath}:${fileLine}` : undefined,
1852
+ method: undefined
1853
+ };
1854
+ }
1855
+ function formatStackFrames(frames, settings) {
1856
+ return frames.map((stackFrame) => formatTemplate(settings, settings.prettyErrorStackTemplate, { ...stackFrame }, true));
1857
+ }
1858
+ function formatErrorMessage(error) {
1859
+ return Object.getOwnPropertyNames(error).filter((key) => key !== "stack" && key !== "cause").reduce((result, key) => {
1860
+ const value = error[key];
1861
+ if (typeof value === "function") {
1862
+ return result;
1863
+ }
1864
+ result.push(String(value));
1865
+ return result;
1866
+ }, []).join(", ");
1867
+ }
1868
+ function shouldUseCss(prettyLogs) {
1869
+ return prettyLogs && (runtimeInfo.name === "browser" || runtimeInfo.name === "worker") && consoleSupportsCssStyling();
1870
+ }
1871
+ function stripAnsi(value) {
1872
+ return value.replace(ANSI_REGEX, "");
1873
+ }
1874
+ function buildCssMetaOutput(settings, metaValue) {
1875
+ if (metaValue == null) {
1876
+ return { text: "", styles: [] };
1877
+ }
1878
+ const { template, placeholders } = buildPrettyMeta(settings, metaValue);
1879
+ const parts = [];
1880
+ const styles = [];
1881
+ let lastIndex = 0;
1882
+ const placeholderRegex = /{{(.+?)}}/g;
1883
+ let match;
1884
+ while ((match = placeholderRegex.exec(template)) != null) {
1885
+ if (match.index > lastIndex) {
1886
+ parts.push(template.slice(lastIndex, match.index));
1887
+ }
1888
+ const key = match[1];
1889
+ const rawValue = placeholders[key] != null ? String(placeholders[key]) : "";
1890
+ const tokens = collectStyleTokens(settings.prettyLogStyles?.[key], rawValue);
1891
+ const css = tokensToCss(tokens);
1892
+ if (css.length > 0) {
1893
+ parts.push(`%c${rawValue}%c`);
1894
+ styles.push(css, "");
1895
+ } else {
1896
+ parts.push(rawValue);
1897
+ }
1898
+ lastIndex = placeholderRegex.lastIndex;
1899
+ }
1900
+ if (lastIndex < template.length) {
1901
+ parts.push(template.slice(lastIndex));
1902
+ }
1903
+ return {
1904
+ text: parts.join(""),
1905
+ styles
1906
+ };
1907
+ }
1908
+ function collectStyleTokens(style, value) {
1909
+ if (style == null) {
1910
+ return [];
1911
+ }
1912
+ if (typeof style === "string") {
1913
+ return [style];
1914
+ }
1915
+ if (Array.isArray(style)) {
1916
+ return style.flatMap((token) => collectStyleTokens(token, value));
1917
+ }
1918
+ if (typeof style === "object") {
1919
+ const normalizedValue = value.trim();
1920
+ const nextStyle = style[normalizedValue] ?? style["*"];
1921
+ if (nextStyle == null) {
1922
+ return [];
1923
+ }
1924
+ return collectStyleTokens(nextStyle, value);
1925
+ }
1926
+ return [];
1927
+ }
1928
+ function tokensToCss(tokens) {
1929
+ const seen = new Set;
1930
+ const cssParts = [];
1931
+ for (const token of tokens) {
1932
+ const css = styleTokenToCss(token);
1933
+ if (css != null && css.length > 0 && !seen.has(css)) {
1934
+ seen.add(css);
1935
+ cssParts.push(css);
1936
+ }
1937
+ }
1938
+ return cssParts.join("; ");
1939
+ }
1940
+ function styleTokenToCss(token) {
1941
+ const color = COLOR_TOKENS[token];
1942
+ if (color != null) {
1943
+ return `color: ${color}`;
1944
+ }
1945
+ const background = BACKGROUND_TOKENS[token];
1946
+ if (background != null) {
1947
+ return `background-color: ${background}`;
1948
+ }
1949
+ switch (token) {
1950
+ case "bold":
1951
+ return "font-weight: bold";
1952
+ case "dim":
1953
+ return "opacity: 0.75";
1954
+ case "italic":
1955
+ return "font-style: italic";
1956
+ case "underline":
1957
+ return "text-decoration: underline";
1958
+ case "overline":
1959
+ return "text-decoration: overline";
1960
+ case "inverse":
1961
+ return "filter: invert(1)";
1962
+ case "hidden":
1963
+ return "visibility: hidden";
1964
+ case "strikethrough":
1965
+ return "text-decoration: line-through";
1966
+ default:
1967
+ return;
1968
+ }
1969
+ }
1970
+ function getWorkingDirectory() {
1971
+ if (cachedCwd === undefined) {
1972
+ cachedCwd = safeGetCwd() ?? null;
1973
+ }
1974
+ return cachedCwd ?? undefined;
1975
+ }
1976
+ function shouldCaptureHostname() {
1977
+ return runtimeInfo.name === "node" || runtimeInfo.name === "deno" || runtimeInfo.name === "bun";
1978
+ }
1979
+ function shouldCaptureRuntimeVersion() {
1980
+ return runtimeInfo.name === "node" || runtimeInfo.name === "deno" || runtimeInfo.name === "bun";
1981
+ }
1982
+ function createRuntimeMeta(info) {
1983
+ if (info.name === "browser" || info.name === "worker") {
1984
+ return {
1985
+ runtime: info.name,
1986
+ browser: info.userAgent
1987
+ };
1988
+ }
1989
+ const metaStatic = {
1990
+ runtime: info.name
1991
+ };
1992
+ if (shouldCaptureRuntimeVersion()) {
1993
+ metaStatic.runtimeVersion = info.version ?? "unknown";
1994
+ }
1995
+ if (shouldCaptureHostname()) {
1996
+ metaStatic.hostname = info.hostname ?? "unknown";
1997
+ }
1998
+ return metaStatic;
1999
+ }
2000
+ function formatWithOptionsSafe(options, args) {
2001
+ try {
2002
+ return formatWithOptions(options, ...args);
2003
+ } catch {
2004
+ return args.map(stringifyFallback).join(" ");
2005
+ }
2006
+ }
2007
+ function stringifyFallback(value) {
2008
+ if (typeof value === "string") {
2009
+ return value;
2010
+ }
2011
+ try {
2012
+ return JSON.stringify(value);
2013
+ } catch {
2014
+ return String(value);
2015
+ }
2016
+ }
2017
+ function normalizeFilePath(value) {
2018
+ if (typeof value !== "string" || value.length === 0) {
2019
+ return value;
2020
+ }
2021
+ const replaced = value.replace(/\\+/g, "\\").replace(/\\/g, "/");
2022
+ const hasRootDoubleSlash = replaced.startsWith("//");
2023
+ const hasLeadingSlash = replaced.startsWith("/") && !hasRootDoubleSlash;
2024
+ const driveMatch = replaced.match(/^[A-Za-z]:/);
2025
+ const drivePrefix = driveMatch ? driveMatch[0] : "";
2026
+ const withoutDrive = drivePrefix ? replaced.slice(drivePrefix.length) : replaced;
2027
+ const segments = withoutDrive.split("/");
2028
+ const normalizedSegments = [];
2029
+ for (const segment of segments) {
2030
+ if (segment === "" || segment === ".") {
2031
+ continue;
2032
+ }
2033
+ if (segment === "..") {
2034
+ if (normalizedSegments.length > 0) {
2035
+ normalizedSegments.pop();
2036
+ }
2037
+ continue;
2038
+ }
2039
+ normalizedSegments.push(segment);
2040
+ }
2041
+ let normalized = normalizedSegments.join("/");
2042
+ if (hasRootDoubleSlash) {
2043
+ normalized = `//${normalized}`;
2044
+ } else if (hasLeadingSlash) {
2045
+ normalized = `/${normalized}`;
2046
+ } else if (drivePrefix !== "") {
2047
+ normalized = `${drivePrefix}${normalized.length > 0 ? `/${normalized}` : ""}`;
2048
+ }
2049
+ if (normalized.length === 0) {
2050
+ return value;
2051
+ }
2052
+ return normalized;
2053
+ }
2054
+ function detectRuntimeInfo() {
2055
+ if (isBrowserEnvironment()) {
2056
+ const navigatorObj = globalThis.navigator;
2057
+ return {
2058
+ name: "browser",
2059
+ userAgent: navigatorObj?.userAgent
2060
+ };
2061
+ }
2062
+ const globalScope = globalThis;
2063
+ if (typeof globalScope.importScripts === "function") {
2064
+ return {
2065
+ name: "worker",
2066
+ userAgent: globalScope.navigator?.userAgent
2067
+ };
2068
+ }
2069
+ const globalAny = globalThis;
2070
+ if (globalAny.Bun != null) {
2071
+ const bunVersion = globalAny.Bun.version;
2072
+ return {
2073
+ name: "bun",
2074
+ version: bunVersion != null ? `bun/${bunVersion}` : undefined,
2075
+ hostname: getEnvironmentHostname(globalAny.process, globalAny.Deno, globalAny.Bun, globalAny.location)
2076
+ };
2077
+ }
2078
+ if (globalAny.Deno != null) {
2079
+ const denoHostname = resolveDenoHostname(globalAny.Deno);
2080
+ const denoVersion = globalAny.Deno?.version?.deno;
2081
+ return {
2082
+ name: "deno",
2083
+ version: denoVersion != null ? `deno/${denoVersion}` : undefined,
2084
+ hostname: denoHostname ?? getEnvironmentHostname(globalAny.process, globalAny.Deno, globalAny.Bun, globalAny.location)
2085
+ };
2086
+ }
2087
+ if (globalAny.process?.versions?.node != null || globalAny.process?.version != null) {
2088
+ return {
2089
+ name: "node",
2090
+ version: globalAny.process?.versions?.node ?? globalAny.process?.version,
2091
+ hostname: getEnvironmentHostname(globalAny.process, globalAny.Deno, globalAny.Bun, globalAny.location)
2092
+ };
2093
+ }
2094
+ if (globalAny.process != null) {
2095
+ return {
2096
+ name: "node",
2097
+ version: "unknown",
2098
+ hostname: getEnvironmentHostname(globalAny.process, globalAny.Deno, globalAny.Bun, globalAny.location)
2099
+ };
2100
+ }
2101
+ return {
2102
+ name: "unknown"
2103
+ };
2104
+ }
2105
+ function getEnvironmentHostname(nodeProcess, deno, bun, location) {
2106
+ const processHostname = nodeProcess?.env?.HOSTNAME ?? nodeProcess?.env?.HOST ?? nodeProcess?.env?.COMPUTERNAME;
2107
+ if (processHostname != null && processHostname.length > 0) {
2108
+ return processHostname;
2109
+ }
2110
+ const bunHostname = bun?.env?.HOSTNAME ?? bun?.env?.HOST ?? bun?.env?.COMPUTERNAME;
2111
+ if (bunHostname != null && bunHostname.length > 0) {
2112
+ return bunHostname;
2113
+ }
2114
+ try {
2115
+ const denoEnvGet = deno?.env?.get;
2116
+ if (typeof denoEnvGet === "function") {
2117
+ const value = denoEnvGet("HOSTNAME");
2118
+ if (value != null && value.length > 0) {
2119
+ return value;
2120
+ }
2121
+ }
2122
+ } catch {}
2123
+ if (location?.hostname != null && location.hostname.length > 0) {
2124
+ return location.hostname;
2125
+ }
2126
+ return;
2127
+ }
2128
+ function resolveDenoHostname(deno) {
2129
+ try {
2130
+ if (typeof deno?.hostname === "function") {
2131
+ const value = deno.hostname();
2132
+ if (value != null && value.length > 0) {
2133
+ return value;
2134
+ }
2135
+ }
2136
+ } catch {}
2137
+ const locationHostname = globalThis.location?.hostname;
2138
+ if (locationHostname != null && locationHostname.length > 0) {
2139
+ return locationHostname;
2140
+ }
2141
+ return;
2142
+ }
2143
+ function getNodeEnv() {
2144
+ const globalProcess = globalThis?.process;
2145
+ return globalProcess?.env?.NODE_ENV;
2146
+ }
2147
+ function isNativeError(value) {
2148
+ if (value instanceof Error) {
2149
+ return true;
2150
+ }
2151
+ if (value != null && typeof value === "object") {
2152
+ const objectTag = Object.prototype.toString.call(value);
2153
+ if (/\[object .*Error\]/.test(objectTag)) {
2154
+ return true;
2155
+ }
2156
+ const name = value.name;
2157
+ if (typeof name === "string" && name.endsWith("Error")) {
2158
+ return true;
2159
+ }
2160
+ }
2161
+ return false;
2162
+ }
2163
+ }
2164
+ var ANSI_REGEX = /\u001b\[[0-9;]*m/g;
2165
+ var COLOR_TOKENS = {
2166
+ black: "#000000",
2167
+ red: "#ef5350",
2168
+ green: "#66bb6a",
2169
+ yellow: "#fdd835",
2170
+ blue: "#42a5f5",
2171
+ magenta: "#ab47bc",
2172
+ cyan: "#26c6da",
2173
+ white: "#fafafa",
2174
+ blackBright: "#424242",
2175
+ redBright: "#ff7043",
2176
+ greenBright: "#81c784",
2177
+ yellowBright: "#ffe082",
2178
+ blueBright: "#64b5f6",
2179
+ magentaBright: "#ce93d8",
2180
+ cyanBright: "#4dd0e1",
2181
+ whiteBright: "#ffffff"
2182
+ };
2183
+ var BACKGROUND_TOKENS = {
2184
+ bgBlack: "#000000",
2185
+ bgRed: "#ef5350",
2186
+ bgGreen: "#66bb6a",
2187
+ bgYellow: "#fdd835",
2188
+ bgBlue: "#42a5f5",
2189
+ bgMagenta: "#ab47bc",
2190
+ bgCyan: "#26c6da",
2191
+ bgWhite: "#fafafa",
2192
+ bgBlackBright: "#424242",
2193
+ bgRedBright: "#ff7043",
2194
+ bgGreenBright: "#81c784",
2195
+ bgYellowBright: "#ffe082",
2196
+ bgBlueBright: "#64b5f6",
2197
+ bgMagentaBright: "#ce93d8",
2198
+ bgCyanBright: "#4dd0e1",
2199
+ bgWhiteBright: "#ffffff"
2200
+ };
2201
+ var BROWSER_PATH_REGEX = /(?:(?:file|https?|global code|[^@]+)@)?(?:file:)?((?:\/[^:/]+){2,})(?::(\d+))?(?::(\d+))?/;
2202
+ var runtime = createLoggerEnvironment();
2203
+ class BaseLogger {
2204
+ constructor(settings, logObj, stackDepthLevel = Number.NaN) {
2205
+ this.logObj = logObj;
2206
+ this.stackDepthLevel = stackDepthLevel;
2207
+ this.runtime = runtime;
2208
+ this.maxErrorCauseDepth = 5;
2209
+ this.settings = {
2210
+ type: settings?.type ?? "pretty",
2211
+ name: settings?.name,
2212
+ parentNames: settings?.parentNames,
2213
+ minLevel: settings?.minLevel ?? 0,
2214
+ argumentsArrayName: settings?.argumentsArrayName,
2215
+ hideLogPositionForProduction: settings?.hideLogPositionForProduction ?? false,
2216
+ prettyLogTemplate: settings?.prettyLogTemplate ?? "{{yyyy}}.{{mm}}.{{dd}} {{hh}}:{{MM}}:{{ss}}:{{ms}}\t{{logLevelName}}\t{{filePathWithLine}}{{nameWithDelimiterPrefix}}\t",
2217
+ prettyErrorTemplate: settings?.prettyErrorTemplate ?? `
2218
+ {{errorName}} {{errorMessage}}
2219
+ error stack:
2220
+ {{errorStack}}`,
2221
+ prettyErrorStackTemplate: settings?.prettyErrorStackTemplate ?? ` • {{fileName}} {{method}}
2222
+ {{filePathWithLine}}`,
2223
+ prettyErrorParentNamesSeparator: settings?.prettyErrorParentNamesSeparator ?? ":",
2224
+ prettyErrorLoggerNameDelimiter: settings?.prettyErrorLoggerNameDelimiter ?? "\t",
2225
+ stylePrettyLogs: settings?.stylePrettyLogs ?? true,
2226
+ prettyLogTimeZone: settings?.prettyLogTimeZone ?? "UTC",
2227
+ prettyLogStyles: settings?.prettyLogStyles ?? {
2228
+ logLevelName: {
2229
+ "*": ["bold", "black", "bgWhiteBright", "dim"],
2230
+ SILLY: ["bold", "white"],
2231
+ TRACE: ["bold", "whiteBright"],
2232
+ DEBUG: ["bold", "green"],
2233
+ INFO: ["bold", "blue"],
2234
+ WARN: ["bold", "yellow"],
2235
+ ERROR: ["bold", "red"],
2236
+ FATAL: ["bold", "redBright"]
2237
+ },
2238
+ dateIsoStr: "white",
2239
+ filePathWithLine: "white",
2240
+ name: ["white", "bold"],
2241
+ nameWithDelimiterPrefix: ["white", "bold"],
2242
+ nameWithDelimiterSuffix: ["white", "bold"],
2243
+ errorName: ["bold", "bgRedBright", "whiteBright"],
2244
+ fileName: ["yellow"],
2245
+ fileNameWithLine: "white"
2246
+ },
2247
+ prettyInspectOptions: settings?.prettyInspectOptions ?? {
2248
+ colors: true,
2249
+ compact: false,
2250
+ depth: Infinity
2251
+ },
2252
+ metaProperty: settings?.metaProperty ?? "_meta",
2253
+ maskPlaceholder: settings?.maskPlaceholder ?? "[***]",
2254
+ maskValuesOfKeys: settings?.maskValuesOfKeys ?? ["password"],
2255
+ maskValuesOfKeysCaseInsensitive: settings?.maskValuesOfKeysCaseInsensitive ?? false,
2256
+ maskValuesRegEx: settings?.maskValuesRegEx,
2257
+ prefix: [...settings?.prefix ?? []],
2258
+ attachedTransports: [...settings?.attachedTransports ?? []],
2259
+ overwrite: {
2260
+ mask: settings?.overwrite?.mask,
2261
+ toLogObj: settings?.overwrite?.toLogObj,
2262
+ addMeta: settings?.overwrite?.addMeta,
2263
+ addPlaceholders: settings?.overwrite?.addPlaceholders,
2264
+ formatMeta: settings?.overwrite?.formatMeta,
2265
+ formatLogObj: settings?.overwrite?.formatLogObj,
2266
+ transportFormatted: settings?.overwrite?.transportFormatted,
2267
+ transportJSON: settings?.overwrite?.transportJSON
2268
+ }
2269
+ };
2270
+ this.captureStackForMeta = this._shouldCaptureStack();
2271
+ }
2272
+ log(logLevelId, logLevelName, ...args) {
2273
+ if (logLevelId < this.settings.minLevel) {
2274
+ return;
2275
+ }
2276
+ const resolvedArgs = this._resolveLogArguments(args);
2277
+ const logArgs = [...this.settings.prefix, ...resolvedArgs];
2278
+ const maskedArgs = this.settings.overwrite?.mask != null ? this.settings.overwrite?.mask(logArgs) : this.settings.maskValuesOfKeys != null && this.settings.maskValuesOfKeys.length > 0 ? this._mask(logArgs) : logArgs;
2279
+ const thisLogObj = this.logObj != null ? this._recursiveCloneAndExecuteFunctions(this.logObj) : undefined;
2280
+ const logObj = this.settings.overwrite?.toLogObj != null ? this.settings.overwrite?.toLogObj(maskedArgs, thisLogObj) : this._toLogObj(maskedArgs, thisLogObj);
2281
+ const logObjWithMeta = this.settings.overwrite?.addMeta != null ? this.settings.overwrite?.addMeta(logObj, logLevelId, logLevelName) : this._addMetaToLogObj(logObj, logLevelId, logLevelName);
2282
+ const logMeta = logObjWithMeta?.[this.settings.metaProperty];
2283
+ let logMetaMarkup;
2284
+ let logArgsAndErrorsMarkup = undefined;
2285
+ if (this.settings.overwrite?.formatMeta != null) {
2286
+ logMetaMarkup = this.settings.overwrite?.formatMeta(logObjWithMeta?.[this.settings.metaProperty]);
2287
+ }
2288
+ if (this.settings.overwrite?.formatLogObj != null) {
2289
+ logArgsAndErrorsMarkup = this.settings.overwrite?.formatLogObj(maskedArgs, this.settings);
2290
+ }
2291
+ if (this.settings.type === "pretty") {
2292
+ logMetaMarkup = logMetaMarkup ?? this._prettyFormatLogObjMeta(logObjWithMeta?.[this.settings.metaProperty]);
2293
+ logArgsAndErrorsMarkup = logArgsAndErrorsMarkup ?? runtime.prettyFormatLogObj(maskedArgs, this.settings);
2294
+ }
2295
+ if (logMetaMarkup != null && logArgsAndErrorsMarkup != null) {
2296
+ if (this.settings.overwrite?.transportFormatted != null) {
2297
+ const transport = this.settings.overwrite.transportFormatted;
2298
+ const declaredParams = transport.length;
2299
+ if (declaredParams < 4) {
2300
+ transport(logMetaMarkup, logArgsAndErrorsMarkup.args, logArgsAndErrorsMarkup.errors);
2301
+ } else if (declaredParams === 4) {
2302
+ transport(logMetaMarkup, logArgsAndErrorsMarkup.args, logArgsAndErrorsMarkup.errors, logMeta);
2303
+ } else {
2304
+ transport(logMetaMarkup, logArgsAndErrorsMarkup.args, logArgsAndErrorsMarkup.errors, logMeta, this.settings);
2305
+ }
2306
+ } else {
2307
+ runtime.transportFormatted(logMetaMarkup, logArgsAndErrorsMarkup.args, logArgsAndErrorsMarkup.errors, logMeta, this.settings);
2308
+ }
2309
+ } else {
2310
+ if (this.settings.overwrite?.transportJSON != null) {
2311
+ this.settings.overwrite.transportJSON(logObjWithMeta);
2312
+ } else if (this.settings.type !== "hidden") {
2313
+ runtime.transportJSON(logObjWithMeta);
2314
+ }
2315
+ }
2316
+ if (this.settings.attachedTransports != null && this.settings.attachedTransports.length > 0) {
2317
+ this.settings.attachedTransports.forEach((transportLogger) => {
2318
+ transportLogger(logObjWithMeta);
2319
+ });
2320
+ }
2321
+ return logObjWithMeta;
2322
+ }
2323
+ attachTransport(transportLogger) {
2324
+ this.settings.attachedTransports.push(transportLogger);
2325
+ }
2326
+ getSubLogger(settings, logObj) {
2327
+ const subLoggerSettings = {
2328
+ ...this.settings,
2329
+ ...settings,
2330
+ parentNames: this.settings?.parentNames != null && this.settings?.name != null ? [...this.settings.parentNames, this.settings.name] : this.settings?.name != null ? [this.settings.name] : undefined,
2331
+ prefix: [...this.settings.prefix, ...settings?.prefix ?? []]
2332
+ };
2333
+ const subLogger = new this.constructor(subLoggerSettings, logObj ?? this.logObj, this.stackDepthLevel);
2334
+ return subLogger;
2335
+ }
2336
+ _mask(args) {
2337
+ const maskKeys = this._getMaskKeys();
2338
+ return args?.map((arg) => {
2339
+ return this._recursiveCloneAndMaskValuesOfKeys(arg, maskKeys);
2340
+ });
2341
+ }
2342
+ _getMaskKeys() {
2343
+ const maskKeys = this.settings.maskValuesOfKeys ?? [];
2344
+ const signature = maskKeys.map(String).join("|");
2345
+ if (this.settings.maskValuesOfKeysCaseInsensitive === true) {
2346
+ if (this.maskKeysCache?.source === maskKeys && this.maskKeysCache.caseInsensitive === true && this.maskKeysCache.signature === signature) {
2347
+ return this.maskKeysCache.normalized;
2348
+ }
2349
+ const normalized = maskKeys.map((key) => typeof key === "string" ? key.toLowerCase() : String(key).toLowerCase());
2350
+ this.maskKeysCache = {
2351
+ source: maskKeys,
2352
+ caseInsensitive: true,
2353
+ normalized,
2354
+ signature
2355
+ };
2356
+ return normalized;
2357
+ }
2358
+ this.maskKeysCache = {
2359
+ source: maskKeys,
2360
+ caseInsensitive: false,
2361
+ normalized: maskKeys,
2362
+ signature
2363
+ };
2364
+ return maskKeys;
2365
+ }
2366
+ _resolveLogArguments(args) {
2367
+ if (args.length === 1 && typeof args[0] === "function") {
2368
+ const candidate = args[0];
2369
+ if (candidate.length === 0) {
2370
+ const result = candidate();
2371
+ return Array.isArray(result) ? result : [result];
2372
+ }
2373
+ }
2374
+ return args;
2375
+ }
2376
+ _recursiveCloneAndMaskValuesOfKeys(source, keys, seen = []) {
2377
+ if (seen.includes(source)) {
2378
+ return { ...source };
2379
+ }
2380
+ if (typeof source === "object" && source !== null) {
2381
+ seen.push(source);
2382
+ }
2383
+ if (runtime.isError(source) || runtime.isBuffer(source)) {
2384
+ return source;
2385
+ } else if (source instanceof Map) {
2386
+ return new Map(source);
2387
+ } else if (source instanceof Set) {
2388
+ return new Set(source);
2389
+ } else if (Array.isArray(source)) {
2390
+ return source.map((item) => this._recursiveCloneAndMaskValuesOfKeys(item, keys, seen));
2391
+ } else if (source instanceof Date) {
2392
+ return new Date(source.getTime());
2393
+ } else if (source instanceof URL) {
2394
+ return urlToObject(source);
2395
+ } else if (source !== null && typeof source === "object") {
2396
+ const baseObject = runtime.isError(source) ? this._cloneError(source) : Object.create(Object.getPrototypeOf(source));
2397
+ return Object.getOwnPropertyNames(source).reduce((o, prop) => {
2398
+ const lookupKey = this.settings?.maskValuesOfKeysCaseInsensitive !== true ? prop : typeof prop === "string" ? prop.toLowerCase() : String(prop).toLowerCase();
2399
+ o[prop] = keys.includes(lookupKey) ? this.settings.maskPlaceholder : (() => {
2400
+ try {
2401
+ return this._recursiveCloneAndMaskValuesOfKeys(source[prop], keys, seen);
2402
+ } catch {
2403
+ return null;
2404
+ }
2405
+ })();
2406
+ return o;
2407
+ }, baseObject);
2408
+ } else {
2409
+ if (typeof source === "string") {
2410
+ let modifiedSource = source;
2411
+ for (const regEx of this.settings?.maskValuesRegEx || []) {
2412
+ modifiedSource = modifiedSource.replace(regEx, this.settings?.maskPlaceholder || "");
2413
+ }
2414
+ return modifiedSource;
2415
+ }
2416
+ return source;
2417
+ }
2418
+ }
2419
+ _recursiveCloneAndExecuteFunctions(source, seen = []) {
2420
+ if (this.isObjectOrArray(source) && seen.includes(source)) {
2421
+ return this.shallowCopy(source);
2422
+ }
2423
+ if (this.isObjectOrArray(source)) {
2424
+ seen.push(source);
2425
+ }
2426
+ if (Array.isArray(source)) {
2427
+ return source.map((item) => this._recursiveCloneAndExecuteFunctions(item, seen));
2428
+ } else if (source instanceof Date) {
2429
+ return new Date(source.getTime());
2430
+ } else if (this.isObject(source)) {
2431
+ return Object.getOwnPropertyNames(source).reduce((o, prop) => {
2432
+ const descriptor = Object.getOwnPropertyDescriptor(source, prop);
2433
+ if (descriptor) {
2434
+ Object.defineProperty(o, prop, descriptor);
2435
+ const value = source[prop];
2436
+ o[prop] = typeof value === "function" ? value() : this._recursiveCloneAndExecuteFunctions(value, seen);
2437
+ }
2438
+ return o;
2439
+ }, Object.create(Object.getPrototypeOf(source)));
2440
+ } else {
2441
+ return source;
2442
+ }
2443
+ }
2444
+ isObjectOrArray(value) {
2445
+ return typeof value === "object" && value !== null;
2446
+ }
2447
+ isObject(value) {
2448
+ return typeof value === "object" && !Array.isArray(value) && value !== null;
2449
+ }
2450
+ shallowCopy(source) {
2451
+ if (Array.isArray(source)) {
2452
+ return [...source];
2453
+ } else {
2454
+ return { ...source };
2455
+ }
2456
+ }
2457
+ _toLogObj(args, clonedLogObj = {}) {
2458
+ args = args?.map((arg) => runtime.isError(arg) ? this._toErrorObject(arg) : arg);
2459
+ if (this.settings.argumentsArrayName == null) {
2460
+ if (args.length === 1 && !Array.isArray(args[0]) && runtime.isBuffer(args[0]) !== true && !(args[0] instanceof Date)) {
2461
+ clonedLogObj = typeof args[0] === "object" && args[0] != null ? { ...args[0], ...clonedLogObj } : { 0: args[0], ...clonedLogObj };
2462
+ } else {
2463
+ clonedLogObj = { ...clonedLogObj, ...args };
2464
+ }
2465
+ } else {
2466
+ clonedLogObj = {
2467
+ ...clonedLogObj,
2468
+ [this.settings.argumentsArrayName]: args
2469
+ };
2470
+ }
2471
+ return clonedLogObj;
2472
+ }
2473
+ _cloneError(error) {
2474
+ const cloned = new error.constructor;
2475
+ Object.getOwnPropertyNames(error).forEach((key) => {
2476
+ cloned[key] = error[key];
2477
+ });
2478
+ return cloned;
2479
+ }
2480
+ _toErrorObject(error, depth = 0, seen = new Set) {
2481
+ if (!seen.has(error)) {
2482
+ seen.add(error);
2483
+ }
2484
+ const errorObject = {
2485
+ nativeError: error,
2486
+ name: error.name ?? "Error",
2487
+ message: error.message,
2488
+ stack: runtime.getErrorTrace(error)
2489
+ };
2490
+ if (depth >= this.maxErrorCauseDepth) {
2491
+ return errorObject;
2492
+ }
2493
+ const causeValue = error.cause;
2494
+ if (causeValue != null) {
2495
+ const normalizedCause = toError(causeValue);
2496
+ if (!seen.has(normalizedCause)) {
2497
+ errorObject.cause = this._toErrorObject(normalizedCause, depth + 1, seen);
2498
+ }
2499
+ }
2500
+ return errorObject;
2501
+ }
2502
+ _addMetaToLogObj(logObj, logLevelId, logLevelName) {
2503
+ return {
2504
+ ...logObj,
2505
+ [this.settings.metaProperty]: runtime.getMeta(logLevelId, logLevelName, this.stackDepthLevel, !this.captureStackForMeta, this.settings.name, this.settings.parentNames)
2506
+ };
2507
+ }
2508
+ _shouldCaptureStack() {
2509
+ if (this.settings.hideLogPositionForProduction) {
2510
+ return false;
2511
+ }
2512
+ if (this.settings.type === "json") {
2513
+ return true;
2514
+ }
2515
+ const template = this.settings.prettyLogTemplate ?? "";
2516
+ const stackPlaceholders = /{{\s*(file(Name|Path|Line|PathWithLine|NameWithLine)|fullFilePath)\s*}}/;
2517
+ if (stackPlaceholders.test(template)) {
2518
+ return true;
2519
+ }
2520
+ return false;
2521
+ }
2522
+ _prettyFormatLogObjMeta(logObjMeta) {
2523
+ return buildPrettyMeta(this.settings, logObjMeta).text;
2524
+ }
2525
+ }
2526
+
2527
+ // ../../node_modules/.bun/tslog@4.10.2/node_modules/tslog/esm/index.js
2528
+ class Logger extends BaseLogger {
2529
+ constructor(settings, logObj) {
2530
+ const isBrowser = typeof window !== "undefined" && typeof document !== "undefined";
2531
+ const normalizedSettings = { ...settings ?? {} };
2532
+ if (isBrowser) {
2533
+ normalizedSettings.stylePrettyLogs = settings?.stylePrettyLogs ?? true;
2534
+ }
2535
+ super(normalizedSettings, logObj, Number.NaN);
2536
+ }
2537
+ log(logLevelId, logLevelName, ...args) {
2538
+ return super.log(logLevelId, logLevelName, ...args);
2539
+ }
2540
+ silly(...args) {
2541
+ return super.log(0, "SILLY", ...args);
2542
+ }
2543
+ trace(...args) {
2544
+ return super.log(1, "TRACE", ...args);
2545
+ }
2546
+ debug(...args) {
2547
+ return super.log(2, "DEBUG", ...args);
2548
+ }
2549
+ info(...args) {
2550
+ return super.log(3, "INFO", ...args);
2551
+ }
2552
+ warn(...args) {
2553
+ return super.log(4, "WARN", ...args);
2554
+ }
2555
+ error(...args) {
2556
+ return super.log(5, "ERROR", ...args);
2557
+ }
2558
+ fatal(...args) {
2559
+ return super.log(6, "FATAL", ...args);
2560
+ }
2561
+ getSubLogger(settings, logObj) {
2562
+ return super.getSubLogger(settings, logObj);
2563
+ }
2564
+ }
2565
+
2566
+ // ../nice-error/src/utils/logger.ts
2567
+ var logger_NiceError = new Logger({
2568
+ name: "NiceErrorLogger"
2569
+ });
2570
+ var logger_NiceError_testing = logger_NiceError.getSubLogger({
2571
+ name: "NiceErrorTestingLogger"
2572
+ });
2573
+
2574
+ // ../nice-error/src/utils/inspectPotentialError/inspectPotentialError.ts
2575
+ function interpretMessagePackedError(parsedError) {
2576
+ let packedErrorStr;
2577
+ if (typeof parsedError.message === "string" && parsedError.message.includes(DUR_OBJ_PACK_PREFIX) && parsedError.message.includes(DUR_OBJ_PACK_SUFFIX)) {
2578
+ packedErrorStr = parsedError.message;
2579
+ }
2580
+ if (typeof parsedError.cause === "string" && parsedError.cause.includes(DUR_OBJ_PACK_PREFIX) && parsedError.cause.includes(DUR_OBJ_PACK_SUFFIX)) {
2581
+ packedErrorStr = parsedError.cause;
2582
+ }
2583
+ if (packedErrorStr != null) {
2584
+ const jsonStr = packedErrorStr.split(DUR_OBJ_PACK_PREFIX)[1].split(DUR_OBJ_PACK_SUFFIX)[0];
2585
+ try {
2586
+ const errorObj = JSON.parse(jsonStr);
2587
+ if (isNiceErrorObject(errorObj)) {
2588
+ return {
2589
+ type: "niceErrorObject" /* niceErrorObject */,
2590
+ niceErrorObject: errorObj
2591
+ };
2592
+ }
2593
+ } catch {}
2594
+ }
2595
+ return null;
2596
+ }
2597
+ var inspectPotentialError = (potentialError) => {
2598
+ if (potentialError == null) {
2599
+ return {
2600
+ type: "nullish" /* nullish */,
2601
+ value: potentialError
2602
+ };
2603
+ }
2604
+ if (typeof potentialError === "number") {
2605
+ return {
2606
+ type: "jsDataType" /* jsDataType */,
2607
+ jsDataType: "number",
2608
+ jsDataValue: potentialError
2609
+ };
2610
+ }
2611
+ if (typeof potentialError === "boolean") {
2612
+ return {
2613
+ type: "jsDataType" /* jsDataType */,
2614
+ jsDataType: "boolean",
2615
+ jsDataValue: potentialError
2616
+ };
2617
+ }
2618
+ let parsedError = potentialError;
2619
+ if (typeof potentialError === "string") {
2620
+ if (potentialError.includes("{") && potentialError.includes("name")) {
2621
+ try {
2622
+ parsedError = JSON.parse(potentialError);
2623
+ } catch {
2624
+ return {
2625
+ type: "jsDataType" /* jsDataType */,
2626
+ jsDataType: "string",
2627
+ jsDataValue: potentialError
2628
+ };
2629
+ }
2630
+ } else {
2631
+ return {
2632
+ type: "jsDataType" /* jsDataType */,
2633
+ jsDataType: "string",
2634
+ jsDataValue: potentialError
2635
+ };
2636
+ }
2637
+ }
2638
+ if (typeof parsedError !== "object" || parsedError == null) {
2639
+ logger_NiceError.warn({
2640
+ message: "Received a potential error that is a primitive data type other than string, number, or boolean. This is unexpected and may indicate an issue with error handling in the code.",
2641
+ potentialError
2642
+ });
2643
+ return {
2644
+ jsDataValue: potentialError,
2645
+ type: "jsOther" /* jsOther */
2646
+ };
2647
+ }
2648
+ if (parsedError instanceof NiceError) {
2649
+ return {
2650
+ type: "niceError" /* niceError */,
2651
+ niceError: parsedError
2652
+ };
2653
+ }
2654
+ if (isNiceErrorObject(parsedError)) {
2655
+ return {
2656
+ type: "niceErrorObject" /* niceErrorObject */,
2657
+ niceErrorObject: parsedError
2658
+ };
2659
+ }
2660
+ if (parsedError instanceof Error) {
2661
+ const durObjResult = interpretMessagePackedError(parsedError);
2662
+ if (durObjResult != null) {
2663
+ return durObjResult;
2664
+ }
2665
+ return {
2666
+ type: "jsError" /* jsError */,
2667
+ jsError: parsedError
2668
+ };
2669
+ }
2670
+ if (isRegularErrorJsonObject(parsedError)) {
2671
+ const durObjResult = interpretMessagePackedError(parsedError);
2672
+ if (durObjResult != null) {
2673
+ return durObjResult;
2674
+ }
2675
+ return {
2676
+ type: "jsErrorObject" /* jsErrorObject */,
2677
+ jsErrorObject: parsedError
2678
+ };
2679
+ }
2680
+ return {
2681
+ type: "jsDataType" /* jsDataType */,
2682
+ jsDataType: "object",
2683
+ jsDataValue: parsedError
2684
+ };
2685
+ };
2686
+
2687
+ // ../nice-error/src/utils/castNiceError.ts
2688
+ var castNiceError = (error) => {
2689
+ const inspected = inspectPotentialError(error);
2690
+ switch (inspected.type) {
2691
+ case "niceError" /* niceError */:
2692
+ return inspected.niceError;
2693
+ case "niceErrorObject" /* niceErrorObject */: {
2694
+ const obj = inspected.niceErrorObject;
2695
+ return new NiceError(obj);
2696
+ }
2697
+ case "jsError" /* jsError */: {
2698
+ return err_cast_not_nice.fromContext({
2699
+ ["native_error" /* js_error */]: inspected
2700
+ }).withOriginError(inspected.jsError);
2701
+ }
2702
+ case "jsErrorObject" /* jsErrorObject */: {
2703
+ const err2 = err_cast_not_nice.fromContext({
2704
+ ["js_error_like_object" /* js_error_like_object */]: inspected
2705
+ });
2706
+ err2.cause = inspected.jsErrorObject;
2707
+ return err2;
2708
+ }
2709
+ case "nullish" /* nullish */:
2710
+ return err_cast_not_nice.fromContext({
2711
+ ["nullish_value" /* nullish_value */]: inspected
2712
+ });
2713
+ case "jsDataType" /* jsDataType */: {
2714
+ return err_cast_not_nice.fromContext({
2715
+ ["js_data_type" /* js_data_type */]: inspected
2716
+ });
2717
+ }
2718
+ default:
2719
+ return err_cast_not_nice.fromContext({
2720
+ ["js_other" /* js_other */]: inspected
2721
+ });
2722
+ }
2723
+ };
2724
+ // src/errors/err_nice_action.ts
2725
+ var EErrId_NiceAction;
2726
+ ((EErrId_NiceAction2) => {
2727
+ EErrId_NiceAction2["action_id_not_in_domain"] = "action_id_not_in_domain";
2728
+ EErrId_NiceAction2["domain_action_requester_conflict"] = "domain_action_handler_conflict";
2729
+ EErrId_NiceAction2["domain_no_handler"] = "domain_no_handler";
2730
+ EErrId_NiceAction2["hydration_domain_mismatch"] = "hydration_domain_mismatch";
2731
+ EErrId_NiceAction2["hydration_action_state_mismatch"] = "hydration_action_state_mismatch";
2732
+ EErrId_NiceAction2["hydration_action_id_not_found"] = "hydration_action_id_not_found";
2733
+ EErrId_NiceAction2["resolver_domain_not_registered"] = "resolver_domain_not_registered";
2734
+ EErrId_NiceAction2["resolver_action_not_registered"] = "resolver_action_not_registered";
2735
+ EErrId_NiceAction2["action_environment_not_found"] = "action_environment_not_found";
2736
+ EErrId_NiceAction2["environment_already_registered"] = "environment_already_registered";
2737
+ EErrId_NiceAction2["action_input_validation_failed"] = "action_input_validation_failed";
2738
+ })(EErrId_NiceAction ||= {});
2739
+ var err_nice_action = err_nice.createChildDomain({
2740
+ domain: "err_nice_action",
2741
+ defaultHttpStatusCode: 500,
2742
+ schema: {
2743
+ ["action_id_not_in_domain" /* action_id_not_in_domain */]: err({
2744
+ message: ({ actionId, domain }) => `Action with id "${actionId}" does not exist in domain "${domain}".`
2745
+ }),
2746
+ ["domain_action_handler_conflict" /* domain_action_requester_conflict */]: err({
2747
+ message: ({ domain }) => `Domain "${domain}" already has a handler set. Multiple handlers for the same domain are not allowed.`
2748
+ }),
2749
+ ["domain_no_handler" /* domain_no_handler */]: err({
2750
+ message: ({ domain }) => `Domain "${domain}" has no action handler registered. Call setActionHandler() before executing actions.`
2751
+ }),
2752
+ ["hydration_domain_mismatch" /* hydration_domain_mismatch */]: err({
2753
+ message: ({ expected, received }) => `Cannot hydrate action: domain mismatch. Expected "${expected}", got "${received}".`
2754
+ }),
2755
+ ["hydration_action_state_mismatch" /* hydration_action_state_mismatch */]: err({
2756
+ message: ({ expected, received }) => `Cannot hydrate action: action state type mismatch. Expected "${expected}", got "${received}".`
2757
+ }),
2758
+ ["hydration_action_id_not_found" /* hydration_action_id_not_found */]: err({
2759
+ message: ({ domain, actionId }) => `Cannot hydrate action: id "${actionId}" does not exist in domain "${domain}".`
2760
+ }),
2761
+ ["resolver_domain_not_registered" /* resolver_domain_not_registered */]: err({
2762
+ message: ({ domain }) => `No resolver registered for domain "${domain}". Add a NiceActionDomainResolver for this domain to the environment.`
2763
+ }),
2764
+ ["resolver_action_not_registered" /* resolver_action_not_registered */]: err({
2765
+ message: ({ domain, actionId }) => `No resolver registered for action "${actionId}" in domain "${domain}". Call .resolve("${actionId}", fn) on the domain resolver.`
2766
+ }),
2767
+ ["action_environment_not_found" /* action_environment_not_found */]: err({
2768
+ message: ({ domain, envId }) => `No handler or resolver registered with environment id "${envId}" on domain "${domain}".`
2769
+ }),
2770
+ ["environment_already_registered" /* environment_already_registered */]: err({
2771
+ message: ({ domain, envId }) => `Environment "${envId}" is already registered on domain "${domain}". Each environment id may only be registered once.`
2772
+ }),
2773
+ ["action_input_validation_failed" /* action_input_validation_failed */]: err({
2774
+ message: ({ domain, actionId, validationMessage }) => `Input validation failed for action "${actionId}" in domain "${domain}":
2775
+ ${validationMessage}`,
2776
+ httpStatusCode: 400
2777
+ })
2778
+ }
2779
+ });
2780
+
2781
+ // ../../node_modules/.bun/nanoid@5.1.9/node_modules/nanoid/url-alphabet/index.js
2782
+ var urlAlphabet = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
2783
+
2784
+ // ../../node_modules/.bun/nanoid@5.1.9/node_modules/nanoid/index.browser.js
2785
+ var nanoid = (size = 21) => {
2786
+ let id = "";
2787
+ let bytes = crypto.getRandomValues(new Uint8Array(size |= 0));
2788
+ while (size--) {
2789
+ id += urlAlphabet[bytes[size] & 63];
2790
+ }
2791
+ return id;
2792
+ };
2793
+
2794
+ // ../../node_modules/.bun/valibot@1.3.1+8e24a2f921b8d7be/node_modules/valibot/dist/index.mjs
2795
+ var store$4;
2796
+ function getGlobalConfig(config$1) {
2797
+ return {
2798
+ lang: config$1?.lang ?? store$4?.lang,
2799
+ message: config$1?.message,
2800
+ abortEarly: config$1?.abortEarly ?? store$4?.abortEarly,
2801
+ abortPipeEarly: config$1?.abortPipeEarly ?? store$4?.abortPipeEarly
2802
+ };
2803
+ }
2804
+ var store$3;
2805
+ function getGlobalMessage(lang) {
2806
+ return store$3?.get(lang);
2807
+ }
2808
+ var store$2;
2809
+ function getSchemaMessage(lang) {
2810
+ return store$2?.get(lang);
2811
+ }
2812
+ var store$1;
2813
+ function getSpecificMessage(reference, lang) {
2814
+ return store$1?.get(reference)?.get(lang);
2815
+ }
2816
+ function _stringify(input) {
2817
+ const type = typeof input;
2818
+ if (type === "string")
2819
+ return `"${input}"`;
2820
+ if (type === "number" || type === "bigint" || type === "boolean")
2821
+ return `${input}`;
2822
+ if (type === "object" || type === "function")
2823
+ return (input && Object.getPrototypeOf(input)?.constructor?.name) ?? "null";
2824
+ return type;
2825
+ }
2826
+ function _addIssue(context, label, dataset, config$1, other) {
2827
+ const input = other && "input" in other ? other.input : dataset.value;
2828
+ const expected = other?.expected ?? context.expects ?? null;
2829
+ const received = other?.received ?? /* @__PURE__ */ _stringify(input);
2830
+ const issue = {
2831
+ kind: context.kind,
2832
+ type: context.type,
2833
+ input,
2834
+ expected,
2835
+ received,
2836
+ message: `Invalid ${label}: ${expected ? `Expected ${expected} but r` : "R"}eceived ${received}`,
2837
+ requirement: context.requirement,
2838
+ path: other?.path,
2839
+ issues: other?.issues,
2840
+ lang: config$1.lang,
2841
+ abortEarly: config$1.abortEarly,
2842
+ abortPipeEarly: config$1.abortPipeEarly
2843
+ };
2844
+ const isSchema = context.kind === "schema";
2845
+ const message$1 = other?.message ?? context.message ?? /* @__PURE__ */ getSpecificMessage(context.reference, issue.lang) ?? (isSchema ? /* @__PURE__ */ getSchemaMessage(issue.lang) : null) ?? config$1.message ?? /* @__PURE__ */ getGlobalMessage(issue.lang);
2846
+ if (message$1 !== undefined)
2847
+ issue.message = typeof message$1 === "function" ? message$1(issue) : message$1;
2848
+ if (isSchema)
2849
+ dataset.typed = false;
2850
+ if (dataset.issues)
2851
+ dataset.issues.push(issue);
2852
+ else
2853
+ dataset.issues = [issue];
2854
+ }
2855
+ function _getStandardProps(context) {
2856
+ return {
2857
+ version: 1,
2858
+ vendor: "valibot",
2859
+ validate(value$1) {
2860
+ return context["~run"]({ value: value$1 }, /* @__PURE__ */ getGlobalConfig());
2861
+ }
2862
+ };
2863
+ }
2864
+ function includes(requirement, message$1) {
2865
+ const expects = /* @__PURE__ */ _stringify(requirement);
2866
+ return {
2867
+ kind: "validation",
2868
+ type: "includes",
2869
+ reference: includes,
2870
+ async: false,
2871
+ expects,
2872
+ requirement,
2873
+ message: message$1,
2874
+ "~run"(dataset, config$1) {
2875
+ if (dataset.typed && !dataset.value.includes(this.requirement))
2876
+ _addIssue(this, "content", dataset, config$1, { received: `!${expects}` });
2877
+ return dataset;
2878
+ }
2879
+ };
2880
+ }
2881
+ function length(requirement, message$1) {
2882
+ return {
2883
+ kind: "validation",
2884
+ type: "length",
2885
+ reference: length,
2886
+ async: false,
2887
+ expects: `${requirement}`,
2888
+ requirement,
2889
+ message: message$1,
2890
+ "~run"(dataset, config$1) {
2891
+ if (dataset.typed && dataset.value.length !== this.requirement)
2892
+ _addIssue(this, "length", dataset, config$1, { received: `${dataset.value.length}` });
2893
+ return dataset;
2894
+ }
2895
+ };
2896
+ }
2897
+ var _LruCache = class {
2898
+ constructor(config$1) {
2899
+ this.refCount = 0;
2900
+ this.maxSize = config$1?.maxSize ?? 1000;
2901
+ this.maxAge = config$1?.maxAge ?? Infinity;
2902
+ this.hasMaxAge = isFinite(this.maxAge);
2903
+ }
2904
+ #stringify(input) {
2905
+ const type = typeof input;
2906
+ if (type === "string")
2907
+ return `"${input}"`;
2908
+ if (type === "number" || type === "boolean")
2909
+ return `${input}`;
2910
+ if (type === "bigint")
2911
+ return `${input}n`;
2912
+ if (type === "object" || type === "function") {
2913
+ if (input) {
2914
+ this.refIds ??= /* @__PURE__ */ new WeakMap;
2915
+ let id = this.refIds.get(input);
2916
+ if (!id) {
2917
+ id = ++this.refCount;
2918
+ this.refIds.set(input, id);
2919
+ }
2920
+ return `#${id}`;
2921
+ }
2922
+ return "null";
2923
+ }
2924
+ return type;
2925
+ }
2926
+ key(input, config$1 = {}) {
2927
+ return `${this.#stringify(input)}|${this.#stringify(config$1.lang)}|${this.#stringify(config$1.message)}|${this.#stringify(config$1.abortEarly)}|${this.#stringify(config$1.abortPipeEarly)}`;
2928
+ }
2929
+ get(key) {
2930
+ if (!this.store)
2931
+ return;
2932
+ const entry = this.store.get(key);
2933
+ if (!entry)
2934
+ return;
2935
+ if (this.hasMaxAge && Date.now() - entry[1] > this.maxAge) {
2936
+ this.store.delete(key);
2937
+ return;
2938
+ }
2939
+ this.store.delete(key);
2940
+ this.store.set(key, entry);
2941
+ return entry[0];
2942
+ }
2943
+ set(key, value$1) {
2944
+ this.store ??= /* @__PURE__ */ new Map;
2945
+ this.store.delete(key);
2946
+ const timestamp = this.hasMaxAge ? Date.now() : 0;
2947
+ this.store.set(key, [value$1, timestamp]);
2948
+ if (this.store.size > this.maxSize)
2949
+ this.store.delete(this.store.keys().next().value);
2950
+ }
2951
+ clear() {
2952
+ this.store?.clear();
2953
+ }
2954
+ };
2955
+ function getFallback(schema, dataset, config$1) {
2956
+ return typeof schema.fallback === "function" ? schema.fallback(dataset, config$1) : schema.fallback;
2957
+ }
2958
+ function getDefault(schema, dataset, config$1) {
2959
+ return typeof schema.default === "function" ? schema.default(dataset, config$1) : schema.default;
2960
+ }
2961
+ function array(item, message$1) {
2962
+ return {
2963
+ kind: "schema",
2964
+ type: "array",
2965
+ reference: array,
2966
+ expects: "Array",
2967
+ async: false,
2968
+ item,
2969
+ message: message$1,
2970
+ get "~standard"() {
2971
+ return /* @__PURE__ */ _getStandardProps(this);
2972
+ },
2973
+ "~run"(dataset, config$1) {
2974
+ const input = dataset.value;
2975
+ if (Array.isArray(input)) {
2976
+ dataset.typed = true;
2977
+ dataset.value = [];
2978
+ for (let key = 0;key < input.length; key++) {
2979
+ const value$1 = input[key];
2980
+ const itemDataset = this.item["~run"]({ value: value$1 }, config$1);
2981
+ if (itemDataset.issues) {
2982
+ const pathItem = {
2983
+ type: "array",
2984
+ origin: "value",
2985
+ input,
2986
+ key,
2987
+ value: value$1
2988
+ };
2989
+ for (const issue of itemDataset.issues) {
2990
+ if (issue.path)
2991
+ issue.path.unshift(pathItem);
2992
+ else
2993
+ issue.path = [pathItem];
2994
+ dataset.issues?.push(issue);
2995
+ }
2996
+ if (!dataset.issues)
2997
+ dataset.issues = itemDataset.issues;
2998
+ if (config$1.abortEarly) {
2999
+ dataset.typed = false;
3000
+ break;
3001
+ }
3002
+ }
3003
+ if (!itemDataset.typed)
3004
+ dataset.typed = false;
3005
+ dataset.value.push(itemDataset.value);
3006
+ }
3007
+ } else
3008
+ _addIssue(this, "type", dataset, config$1);
3009
+ return dataset;
3010
+ }
3011
+ };
3012
+ }
3013
+ function literal(literal_, message$1) {
3014
+ return {
3015
+ kind: "schema",
3016
+ type: "literal",
3017
+ reference: literal,
3018
+ expects: /* @__PURE__ */ _stringify(literal_),
3019
+ async: false,
3020
+ literal: literal_,
3021
+ message: message$1,
3022
+ get "~standard"() {
3023
+ return /* @__PURE__ */ _getStandardProps(this);
3024
+ },
3025
+ "~run"(dataset, config$1) {
3026
+ if (dataset.value === this.literal)
3027
+ dataset.typed = true;
3028
+ else
3029
+ _addIssue(this, "type", dataset, config$1);
3030
+ return dataset;
3031
+ }
3032
+ };
3033
+ }
3034
+ function nullish(wrapped, default_) {
3035
+ return {
3036
+ kind: "schema",
3037
+ type: "nullish",
3038
+ reference: nullish,
3039
+ expects: `(${wrapped.expects} | null | undefined)`,
3040
+ async: false,
3041
+ wrapped,
3042
+ default: default_,
3043
+ get "~standard"() {
3044
+ return /* @__PURE__ */ _getStandardProps(this);
3045
+ },
3046
+ "~run"(dataset, config$1) {
3047
+ if (dataset.value === null || dataset.value === undefined) {
3048
+ if (this.default !== undefined)
3049
+ dataset.value = /* @__PURE__ */ getDefault(this, dataset, config$1);
3050
+ if (dataset.value === null || dataset.value === undefined) {
3051
+ dataset.typed = true;
3052
+ return dataset;
3053
+ }
3054
+ }
3055
+ return this.wrapped["~run"](dataset, config$1);
3056
+ }
3057
+ };
3058
+ }
3059
+ function object(entries$1, message$1) {
3060
+ return {
3061
+ kind: "schema",
3062
+ type: "object",
3063
+ reference: object,
3064
+ expects: "Object",
3065
+ async: false,
3066
+ entries: entries$1,
3067
+ message: message$1,
3068
+ get "~standard"() {
3069
+ return /* @__PURE__ */ _getStandardProps(this);
3070
+ },
3071
+ "~run"(dataset, config$1) {
3072
+ const input = dataset.value;
3073
+ if (input && typeof input === "object") {
3074
+ dataset.typed = true;
3075
+ dataset.value = {};
3076
+ for (const key in this.entries) {
3077
+ const valueSchema = this.entries[key];
3078
+ if (key in input || (valueSchema.type === "exact_optional" || valueSchema.type === "optional" || valueSchema.type === "nullish") && valueSchema.default !== undefined) {
3079
+ const value$1 = key in input ? input[key] : /* @__PURE__ */ getDefault(valueSchema);
3080
+ const valueDataset = valueSchema["~run"]({ value: value$1 }, config$1);
3081
+ if (valueDataset.issues) {
3082
+ const pathItem = {
3083
+ type: "object",
3084
+ origin: "value",
3085
+ input,
3086
+ key,
3087
+ value: value$1
3088
+ };
3089
+ for (const issue of valueDataset.issues) {
3090
+ if (issue.path)
3091
+ issue.path.unshift(pathItem);
3092
+ else
3093
+ issue.path = [pathItem];
3094
+ dataset.issues?.push(issue);
3095
+ }
3096
+ if (!dataset.issues)
3097
+ dataset.issues = valueDataset.issues;
3098
+ if (config$1.abortEarly) {
3099
+ dataset.typed = false;
3100
+ break;
3101
+ }
3102
+ }
3103
+ if (!valueDataset.typed)
3104
+ dataset.typed = false;
3105
+ dataset.value[key] = valueDataset.value;
3106
+ } else if (valueSchema.fallback !== undefined)
3107
+ dataset.value[key] = /* @__PURE__ */ getFallback(valueSchema);
3108
+ else if (valueSchema.type !== "exact_optional" && valueSchema.type !== "optional" && valueSchema.type !== "nullish") {
3109
+ _addIssue(this, "key", dataset, config$1, {
3110
+ input: undefined,
3111
+ expected: `"${key}"`,
3112
+ path: [{
3113
+ type: "object",
3114
+ origin: "key",
3115
+ input,
3116
+ key,
3117
+ value: input[key]
3118
+ }]
3119
+ });
3120
+ if (config$1.abortEarly)
3121
+ break;
3122
+ }
3123
+ }
3124
+ } else
3125
+ _addIssue(this, "type", dataset, config$1);
3126
+ return dataset;
3127
+ }
3128
+ };
3129
+ }
3130
+ function string(message$1) {
3131
+ return {
3132
+ kind: "schema",
3133
+ type: "string",
3134
+ reference: string,
3135
+ expects: "string",
3136
+ async: false,
3137
+ message: message$1,
3138
+ get "~standard"() {
3139
+ return /* @__PURE__ */ _getStandardProps(this);
3140
+ },
3141
+ "~run"(dataset, config$1) {
3142
+ if (typeof dataset.value === "string")
3143
+ dataset.typed = true;
3144
+ else
3145
+ _addIssue(this, "type", dataset, config$1);
3146
+ return dataset;
3147
+ }
3148
+ };
3149
+ }
3150
+ function pipe(...pipe$1) {
3151
+ return {
3152
+ ...pipe$1[0],
3153
+ pipe: pipe$1,
3154
+ get "~standard"() {
3155
+ return /* @__PURE__ */ _getStandardProps(this);
3156
+ },
3157
+ "~run"(dataset, config$1) {
3158
+ for (const item of pipe$1)
3159
+ if (item.kind !== "metadata") {
3160
+ if (dataset.issues && (item.kind === "schema" || item.kind === "transformation")) {
3161
+ dataset.typed = false;
3162
+ break;
3163
+ }
3164
+ if (!dataset.issues || !config$1.abortEarly && !config$1.abortPipeEarly)
3165
+ dataset = item["~run"](dataset, config$1);
3166
+ }
3167
+ return dataset;
3168
+ }
3169
+ };
3170
+ }
3171
+
3172
+ // src/NiceAction/NiceActionResponse.ts
3173
+ class NiceActionResponse {
3174
+ type = "response" /* response */;
3175
+ domain;
3176
+ allDomains;
3177
+ id;
3178
+ primed;
3179
+ result;
3180
+ timeResponded;
3181
+ constructor(primed, result, hydrationData) {
3182
+ this.primed = primed;
3183
+ this.result = result;
3184
+ this.domain = primed.coreAction.domain;
3185
+ this.allDomains = primed.coreAction.allDomains;
3186
+ this.id = primed.coreAction.id;
3187
+ this.timeResponded = hydrationData?.timeResponded ?? Date.now();
3188
+ }
3189
+ toJsonObject() {
3190
+ const base = this.primed.toJsonObject();
3191
+ if (this.result.ok) {
3192
+ return {
3193
+ ...base,
3194
+ type: "response" /* response */,
3195
+ ok: true,
3196
+ output: this.primed.coreAction.schema.serializeOutput(this.result.output),
3197
+ timeResponded: this.timeResponded
3198
+ };
3199
+ }
3200
+ return {
3201
+ ...base,
3202
+ type: "response" /* response */,
3203
+ ok: false,
3204
+ error: this.result.error.toJsonObject(),
3205
+ timeResponded: this.timeResponded
3206
+ };
3207
+ }
3208
+ toJsonString() {
3209
+ return JSON.stringify(this.toJsonObject());
3210
+ }
3211
+ }
3212
+ function hydrateNiceActionResponse(wire, coreAction) {
3213
+ const rawInput = coreAction.schema.deserializeInput(wire.input);
3214
+ const primed = new NiceActionPrimed(coreAction, rawInput, { timePrimed: wire.timePrimed });
3215
+ if (wire.ok) {
3216
+ const rawOutput = coreAction.schema.deserializeOutput(wire.output);
3217
+ return new NiceActionResponse(primed, { ok: true, output: rawOutput }, { timeResponded: wire.timeResponded });
3218
+ }
3219
+ return new NiceActionResponse(primed, { ok: false, error: castNiceError(wire.error) }, { timeResponded: wire.timeResponded });
3220
+ }
3221
+
3222
+ // src/NiceAction/NiceActionPrimed.ts
3223
+ class NiceActionPrimed {
3224
+ coreAction;
3225
+ input;
3226
+ type = "primed" /* primed */;
3227
+ domain;
3228
+ allDomains;
3229
+ id;
3230
+ timePrimed;
3231
+ constructor(coreAction, input, hydrationData) {
3232
+ this.coreAction = coreAction;
3233
+ this.input = input;
3234
+ this.domain = coreAction.domain;
3235
+ this.allDomains = coreAction.allDomains;
3236
+ this.id = coreAction.id;
3237
+ this.timePrimed = hydrationData?.timePrimed ?? Date.now();
3238
+ }
3239
+ toJsonObject() {
3240
+ return {
3241
+ ...this.coreAction.toJsonObject(),
3242
+ type: "primed" /* primed */,
3243
+ input: this.coreAction.schema.serializeInput(this.input),
3244
+ timePrimed: this.timePrimed
3245
+ };
3246
+ }
3247
+ toJsonString() {
3248
+ return JSON.stringify(this.toJsonObject());
3249
+ }
3250
+ setOutput(output) {
3251
+ return new NiceActionResponse(this, { ok: true, output });
3252
+ }
3253
+ processResponse(wire) {
3254
+ if (!wire.ok) {
3255
+ throw castNiceError(wire.error);
3256
+ }
3257
+ return this.coreAction.schema.deserializeOutput(wire.output);
3258
+ }
3259
+ async execute(envId) {
3260
+ return this.coreAction._actionDomain._dispatchAction(this, envId);
3261
+ }
3262
+ async executeSafe(envId) {
3263
+ try {
3264
+ const value = await this.execute(envId);
3265
+ return { ok: true, output: value };
3266
+ } catch (error) {
3267
+ return { ok: false, error };
3268
+ }
3269
+ }
3270
+ }
3271
+
3272
+ // src/NiceAction/NiceAction.ts
3273
+ class NiceAction {
3274
+ actionDomain;
3275
+ schema;
3276
+ id;
3277
+ type = "empty" /* empty */;
3278
+ domain;
3279
+ allDomains;
3280
+ _actionDomain;
3281
+ timeCreated;
3282
+ cuid;
3283
+ constructor(actionDomain, schema, id, hydrationData) {
3284
+ this.actionDomain = actionDomain;
3285
+ this.schema = schema;
3286
+ this.id = id;
3287
+ this._actionDomain = actionDomain;
3288
+ this.domain = actionDomain.domain;
3289
+ this.allDomains = actionDomain.allDomains;
3290
+ this.timeCreated = hydrationData?.timeCreated ?? Date.now();
3291
+ this.cuid = hydrationData?.cuid ?? nanoid();
3292
+ }
3293
+ toJsonObject() {
3294
+ return {
3295
+ type: "empty" /* empty */,
3296
+ domain: this.domain,
3297
+ allDomains: this.allDomains,
3298
+ id: this.id,
3299
+ timeCreated: this.timeCreated,
3300
+ cuid: this.cuid
3301
+ };
3302
+ }
3303
+ toValidationSchema() {
3304
+ return object({
3305
+ domain: literal(this.domain),
3306
+ allDomains: pipe(array(string()), length(this.allDomains.length), includes(this.domain)),
3307
+ id: literal(this.id)
3308
+ });
3309
+ }
3310
+ is(action) {
3311
+ return action instanceof NiceActionPrimed && action.coreAction.domain === this.domain && action.coreAction.id === this.id;
3312
+ }
3313
+ prime(input, hydrationData) {
3314
+ return new NiceActionPrimed(this, input, hydrationData);
3315
+ }
3316
+ async execute(input, envId) {
3317
+ const primed = new NiceActionPrimed(this, input);
3318
+ return this._actionDomain._dispatchAction(primed, envId);
3319
+ }
3320
+ async executeSafe(input, envId) {
3321
+ try {
3322
+ const value = await this.execute(input, envId);
3323
+ return { ok: true, output: value };
3324
+ } catch (error) {
3325
+ return { ok: false, error };
3326
+ }
3327
+ }
3328
+ async executeToResponse(input, envId) {
3329
+ const primed = this.prime(input);
3330
+ const result = await this.executeSafe(input, envId);
3331
+ return new NiceActionResponse(primed, result);
3332
+ }
3333
+ }
3334
+
3335
+ // src/ActionDomain/NiceActionDomain.ts
3336
+ class NiceActionDomain {
3337
+ domain;
3338
+ allDomains;
3339
+ actions;
3340
+ _listeners = [];
3341
+ _requesters = new Map;
3342
+ _responders = new Map;
3343
+ constructor(definition) {
3344
+ this.domain = definition.domain;
3345
+ this.allDomains = definition.allDomains;
3346
+ this.actions = definition.actions;
3347
+ }
3348
+ createChildDomain(subDomainDef) {
3349
+ return new NiceActionDomain({
3350
+ allDomains: [subDomainDef.domain, ...this.allDomains],
3351
+ domain: subDomainDef.domain,
3352
+ actions: subDomainDef.actions
3353
+ });
3354
+ }
3355
+ primeUnknown(actionId, input) {
3356
+ const action = this.action(actionId).prime(input);
3357
+ return action;
3358
+ }
3359
+ primeAction(id, input) {
3360
+ return this.action(id).prime(input);
3361
+ }
3362
+ action(id, hydrationData) {
3363
+ const actionSchema = this.actions[id];
3364
+ if (!actionSchema) {
3365
+ throw err_nice_action.fromId("action_id_not_in_domain" /* action_id_not_in_domain */, {
3366
+ domain: this.domain,
3367
+ actionId: id
3368
+ });
3369
+ }
3370
+ return new NiceAction(this, actionSchema, id, hydrationData);
3371
+ }
3372
+ isExactActionDomain(action) {
3373
+ return action instanceof NiceActionPrimed && this.domain === action.domain;
3374
+ }
3375
+ matchAction(action, id) {
3376
+ if (this.isExactActionDomain(action) && action.coreAction.id === id) {
3377
+ return action;
3378
+ }
3379
+ return null;
3380
+ }
3381
+ addActionListener(listener) {
3382
+ this._listeners.push(listener);
3383
+ return () => {
3384
+ this._listeners = this._listeners.filter((l) => l !== listener);
3385
+ };
3386
+ }
3387
+ async _dispatchAction(primed, envId) {
3388
+ if (envId != null) {
3389
+ const requester = this._requesters.get(envId);
3390
+ if (requester) {
3391
+ const validatedPrimed = await this._withValidatedInput(primed);
3392
+ const result = await requester.handleAction(validatedPrimed);
3393
+ for (const listener of this._listeners)
3394
+ await listener(validatedPrimed);
3395
+ return result;
3396
+ }
3397
+ const responder = this._responders.get(envId);
3398
+ if (responder) {
3399
+ const result = await responder._resolvePrimed(primed);
3400
+ for (const listener of this._listeners)
3401
+ await listener(primed);
3402
+ return result;
3403
+ }
3404
+ throw err_nice_action.fromId("action_environment_not_found" /* action_environment_not_found */, {
3405
+ domain: this.domain,
3406
+ envId
3407
+ });
3408
+ }
3409
+ const defaultHandler = this._requesters.get(undefined);
3410
+ if (defaultHandler) {
3411
+ const validatedPrimed = await this._withValidatedInput(primed);
3412
+ const result = await defaultHandler.handleAction(validatedPrimed);
3413
+ for (const listener of this._listeners)
3414
+ await listener(validatedPrimed);
3415
+ return result;
3416
+ }
3417
+ const defaultResolver = this._responders.get(undefined);
3418
+ if (defaultResolver) {
3419
+ const result = await defaultResolver._resolvePrimed(primed);
3420
+ for (const listener of this._listeners)
3421
+ await listener(primed);
3422
+ return result;
3423
+ }
3424
+ throw err_nice_action.fromId("domain_no_handler" /* domain_no_handler */, { domain: this.domain });
3425
+ }
3426
+ async _withValidatedInput(primed) {
3427
+ const validatedInput = await primed.coreAction.schema.validateInput(primed.input, {
3428
+ domain: this.domain,
3429
+ actionId: primed.coreAction.id
3430
+ });
3431
+ return primed.coreAction.prime(validatedInput);
3432
+ }
3433
+ hydratePrimed(serialized) {
3434
+ if (serialized.type !== "primed" /* primed */) {
3435
+ throw err_nice_action.fromId("hydration_action_state_mismatch" /* hydration_action_state_mismatch */, {
3436
+ expected: "primed" /* primed */,
3437
+ received: serialized.type
3438
+ });
3439
+ }
3440
+ if (serialized.domain !== this.domain) {
3441
+ throw err_nice_action.fromId("hydration_domain_mismatch" /* hydration_domain_mismatch */, {
3442
+ expected: this.domain,
3443
+ received: serialized.domain
3444
+ });
3445
+ }
3446
+ const id = serialized.id;
3447
+ if (!this.actions[id]) {
3448
+ throw err_nice_action.fromId("hydration_action_id_not_found" /* hydration_action_id_not_found */, {
3449
+ domain: this.domain,
3450
+ actionId: serialized.id
3451
+ });
3452
+ }
3453
+ const coreAction = this.action(id, {
3454
+ cuid: serialized.cuid,
3455
+ timeCreated: serialized.timeCreated
3456
+ });
3457
+ const rawInput = coreAction.schema.deserializeInput(serialized.input);
3458
+ return new NiceActionPrimed(coreAction, rawInput, {
3459
+ timePrimed: serialized.timePrimed
3460
+ });
3461
+ }
3462
+ hydrateResponse(serialized) {
3463
+ if (serialized.type !== "response" /* response */) {
3464
+ throw err_nice_action.fromId("hydration_action_state_mismatch" /* hydration_action_state_mismatch */, {
3465
+ expected: "response" /* response */,
3466
+ received: serialized.type
3467
+ });
3468
+ }
3469
+ if (serialized.domain !== this.domain) {
3470
+ throw err_nice_action.fromId("hydration_domain_mismatch" /* hydration_domain_mismatch */, {
3471
+ expected: this.domain,
3472
+ received: serialized.domain
3473
+ });
3474
+ }
3475
+ const id = serialized.id;
3476
+ if (!this.actions[id]) {
3477
+ throw err_nice_action.fromId("hydration_action_id_not_found" /* hydration_action_id_not_found */, {
3478
+ domain: this.domain,
3479
+ actionId: serialized.id
3480
+ });
3481
+ }
3482
+ const coreAction = this.action(id, {
3483
+ cuid: serialized.cuid,
3484
+ timeCreated: serialized.timeCreated
3485
+ });
3486
+ return hydrateNiceActionResponse(serialized, coreAction);
3487
+ }
3488
+ setActionRequester(handler, options) {
3489
+ const envId = options?.envId;
3490
+ if (this._requesters.has(envId)) {
3491
+ if (envId != null) {
3492
+ throw err_nice_action.fromId("environment_already_registered" /* environment_already_registered */, {
3493
+ domain: this.domain,
3494
+ envId
3495
+ });
3496
+ }
3497
+ throw err_nice_action.fromId("domain_action_handler_conflict" /* domain_action_requester_conflict */, {
3498
+ domain: this.domain
3499
+ });
3500
+ }
3501
+ const h = handler ?? new NiceActionRequester;
3502
+ this._requesters.set(envId, h);
3503
+ return h;
3504
+ }
3505
+ registerResponder(resolver, options) {
3506
+ const envId = options?.envId;
3507
+ if (this._responders.has(envId)) {
3508
+ throw err_nice_action.fromId("environment_already_registered" /* environment_already_registered */, {
3509
+ domain: this.domain,
3510
+ envId: envId ?? "(default)"
3511
+ });
3512
+ }
3513
+ this._responders.set(envId, resolver);
3514
+ return this;
3515
+ }
3516
+ }
3517
+
3518
+ // src/ActionDomain/createActionDomain.ts
3519
+ var createActionDomain = (definition) => {
3520
+ return new NiceActionDomain({
3521
+ ...definition,
3522
+ allDomains: [definition.domain]
3523
+ });
3524
+ };
3525
+ // src/ActionRequestResponse/ActionResponder/NiceActionResponder.ts
3526
+ class NiceActionDomainResponder {
3527
+ _domain;
3528
+ _responders = new Map;
3529
+ constructor(domain) {
3530
+ this._domain = domain;
3531
+ }
3532
+ get domainId() {
3533
+ return this._domain.domain;
3534
+ }
3535
+ resolveAction(actionId, fn) {
3536
+ this._responders.set(actionId, fn);
3537
+ return this;
3538
+ }
3539
+ async _resolvePrimed(primed) {
3540
+ const resolver = this._responders.get(primed.coreAction.id);
3541
+ if (resolver == null) {
3542
+ throw err_nice_action.fromId("resolver_action_not_registered" /* resolver_action_not_registered */, {
3543
+ domain: primed.domain,
3544
+ actionId: primed.coreAction.id
3545
+ });
3546
+ }
3547
+ const validatedInput = await primed.coreAction.schema.validateInput(primed.input, {
3548
+ domain: primed.domain,
3549
+ actionId: primed.coreAction.id
3550
+ });
3551
+ const response = await resolver(validatedInput);
3552
+ return response;
3553
+ }
3554
+ async _dispatch(wire) {
3555
+ const primed = this._domain.hydratePrimed(wire);
3556
+ const resolverFn = this._responders.get(wire.id);
3557
+ if (resolverFn == null) {
3558
+ throw err_nice_action.fromId("resolver_action_not_registered" /* resolver_action_not_registered */, {
3559
+ domain: wire.domain,
3560
+ actionId: wire.id
3561
+ });
3562
+ }
3563
+ try {
3564
+ const validatedInput = await primed.coreAction.schema.validateInput(primed.input, {
3565
+ domain: wire.domain,
3566
+ actionId: wire.id
3567
+ });
3568
+ const output = await resolverFn(validatedInput);
3569
+ return new NiceActionResponse(primed, {
3570
+ ok: true,
3571
+ output
3572
+ });
3573
+ } catch (e) {
3574
+ return new NiceActionResponse(primed, {
3575
+ ok: false,
3576
+ error: castNiceError(e)
3577
+ });
3578
+ }
3579
+ }
3580
+ }
3581
+ function createDomainResolver(domain) {
3582
+ return new NiceActionDomainResponder(domain);
3583
+ }
3584
+ // src/ActionRequestResponse/ActionResponder/NiceActionResponderEnvironment.ts
3585
+ class NiceActionResponderEnvironment {
3586
+ _resolvers = new Map;
3587
+ constructor(resolvers) {
3588
+ for (const resolver of resolvers) {
3589
+ this._resolvers.set(resolver.domainId, resolver);
3590
+ }
3591
+ }
3592
+ async dispatch(wire) {
3593
+ const resolver = this._resolvers.get(wire.domain);
3594
+ if (resolver == null) {
3595
+ throw err_nice_action.fromId("resolver_domain_not_registered" /* resolver_domain_not_registered */, {
3596
+ domain: wire.domain
3597
+ });
3598
+ }
3599
+ const response = await resolver._dispatch(wire);
3600
+ return response.toJsonObject();
3601
+ }
3602
+ }
3603
+ function createResponderEnvironment(resolvers) {
3604
+ return new NiceActionResponderEnvironment(resolvers);
3605
+ }
3606
+ // ../common-errors/src/validation/standard_schema/extractMessageFromStandardSchema.ts
3607
+ function extractPathFromIssue(issue) {
3608
+ let pathString = "";
3609
+ for (const segment of issue) {
3610
+ if (typeof segment === "object") {
3611
+ if (segment.key != null) {
3612
+ if (typeof segment.key === "number") {
3613
+ pathString += `[${String(segment.key)}]`;
3614
+ } else if (typeof segment.key === "symbol") {
3615
+ pathString += `[SYMBOL:${String(segment.key)}]`;
3616
+ } else {
3617
+ pathString += `.${String(segment.key)}`;
3618
+ }
3619
+ }
3620
+ } else {
3621
+ pathString += `.${String(segment)}`;
3622
+ }
3623
+ }
3624
+ return pathString.slice(1);
3625
+ }
3626
+ var extractMessageFromStandardSchema = (failureResult) => {
3627
+ let message = `Data validation failed:
3628
+ `;
3629
+ let issueCount = 0;
3630
+ for (const issue of failureResult.issues) {
3631
+ issueCount++;
3632
+ if (issue.path == null || issue.path.length === 0) {
3633
+ message += ` (issue ${issueCount}) ${issue.message}
3634
+ `;
3635
+ } else {
3636
+ message += ` (issue ${issueCount}) [${extractPathFromIssue(issue.path)}]: ${issue.message}
3637
+ `;
3638
+ }
3639
+ }
3640
+ return message;
3641
+ };
3642
+
3643
+ // ../common-errors/src/validation/err_validation.ts
3644
+ var err_validation = err_nice.createChildDomain({
3645
+ domain: "err_validation",
3646
+ defaultHttpStatusCode: StatusCodes.BAD_REQUEST,
3647
+ schema: {
3648
+ ["standard_schema" /* standard_schema */]: err({
3649
+ message: ({ issues }) => extractMessageFromStandardSchema({ issues })
3650
+ })
3651
+ }
3652
+ });
3653
+ // src/ActionSchema/NiceActionSchema.ts
3654
+ class NiceActionSchema {
3655
+ _errorDeclarations = [];
3656
+ inputOptions;
3657
+ outputOptions;
3658
+ get inputSchema() {
3659
+ return nullish(this.inputOptions?.schema);
3660
+ }
3661
+ get outputSchema() {
3662
+ return nullish(this.outputOptions?.schema);
3663
+ }
3664
+ input(options, serialize, deserialize) {
3665
+ if (serialize != null && deserialize != null) {
3666
+ this.inputOptions = { ...options, serialization: { serialize, deserialize } };
3667
+ } else {
3668
+ this.inputOptions = options;
3669
+ }
3670
+ return this;
3671
+ }
3672
+ output(options, serialize, deserialize) {
3673
+ if (serialize != null && deserialize != null) {
3674
+ this.outputOptions = { ...options, serialization: { serialize, deserialize } };
3675
+ } else {
3676
+ this.outputOptions = options;
3677
+ }
3678
+ return this;
3679
+ }
3680
+ throws(domain, ids) {
3681
+ this._errorDeclarations.push({ _domain: domain, _ids: ids });
3682
+ return this;
3683
+ }
3684
+ serializeInput(rawInput) {
3685
+ if (this.inputOptions?.serialization) {
3686
+ return this.inputOptions.serialization.serialize(rawInput);
3687
+ }
3688
+ return rawInput;
3689
+ }
3690
+ deserializeInput(serialized) {
3691
+ if (this.inputOptions?.serialization) {
3692
+ return this.inputOptions.serialization.deserialize(serialized);
3693
+ }
3694
+ return serialized;
3695
+ }
3696
+ async validateInput(value, meta) {
3697
+ if (this.inputOptions?.schema == null) {
3698
+ return value;
3699
+ }
3700
+ const result = await this.inputOptions.schema["~standard"].validate(value);
3701
+ if (result.issues != null) {
3702
+ throw err_nice_action.fromId("action_input_validation_failed" /* action_input_validation_failed */, {
3703
+ domain: meta.domain,
3704
+ actionId: meta.actionId,
3705
+ validationMessage: extractMessageFromStandardSchema(result)
3706
+ });
3707
+ }
3708
+ return result.value;
3709
+ }
3710
+ serializeOutput(rawOutput) {
3711
+ if (this.outputOptions?.serialization) {
3712
+ return this.outputOptions.serialization.serialize(rawOutput);
3713
+ }
3714
+ return rawOutput;
3715
+ }
3716
+ deserializeOutput(serialized) {
3717
+ if (this.outputOptions?.serialization) {
3718
+ return this.outputOptions.serialization.deserialize(serialized);
3719
+ }
3720
+ return serialized;
3721
+ }
3722
+ }
3723
+
3724
+ // src/ActionSchema/action.ts
3725
+ var action = () => {
3726
+ return new NiceActionSchema;
3727
+ };
3728
+ // src/utils/isActionResponseJsonObject.ts
3729
+ var isActionResponseJsonObject = (obj) => {
3730
+ return typeof obj === "object" && obj !== null && typeof obj.domain === "string" && typeof obj.id === "string" && "input" in obj && (("output" in obj) || ("error" in obj)) && typeof obj.ok === "boolean";
3731
+ };
3732
+ // src/utils/isPrimedActionJsonObject.ts
3733
+ var isPrimedActionJsonObject = (obj) => {
3734
+ return typeof obj === "object" && obj !== null && typeof obj.domain === "string" && typeof obj.id === "string" && "input" in obj;
3735
+ };
3736
+ export {
3737
+ isPrimedActionJsonObject,
3738
+ isActionResponseJsonObject,
3739
+ err_nice_action,
3740
+ createResponderEnvironment,
3741
+ createDomainResolver,
3742
+ createActionDomain,
3743
+ action,
3744
+ NiceActionSchema,
3745
+ NiceActionResponse,
3746
+ NiceActionResponderEnvironment,
3747
+ NiceActionRequester,
3748
+ NiceActionPrimed,
3749
+ NiceActionDomainResponder,
3750
+ NiceActionDomain,
3751
+ NiceAction,
3752
+ EErrId_NiceAction
3753
+ };