silgi 0.24.19 → 0.24.21

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.
@@ -0,0 +1,763 @@
1
+ import { createConsola } from 'consola';
2
+ import defu, { defu as defu$1 } from 'defu';
3
+ import { createHooks } from 'hookable';
4
+ import { c as createRouteRules } from '../_chunks/silgiApp.mjs';
5
+ export { s as silgiCLICtx, t as tryUseSilgiCLI, u as useSilgiCLI } from '../_chunks/silgiApp.mjs';
6
+ import { getContext } from 'unctx';
7
+ import { Buffer } from 'node:buffer';
8
+ import { klona } from 'klona';
9
+ import { useSilgiRuntimeConfig } from 'silgi/runtime';
10
+ import { createStorage as createStorage$1, builtinDrivers, prefixStorage } from 'unstorage';
11
+ import 'ufo';
12
+
13
+ const silgiCtx = getContext("silgi");
14
+ function useSilgi() {
15
+ const instance = silgiCtx.tryUse();
16
+ if (!instance) {
17
+ throw new Error("Silgi instance is unavailable!");
18
+ }
19
+ return instance;
20
+ }
21
+ function normalizeResult(result) {
22
+ if (Array.isArray(result)) {
23
+ return [...result];
24
+ }
25
+ if (result && typeof result === "object") {
26
+ if (Object.keys(result).every((key) => !Number.isNaN(Number(key)))) {
27
+ return Object.values(result);
28
+ }
29
+ return { ...result };
30
+ }
31
+ return result;
32
+ }
33
+ function tryUseSilgi() {
34
+ return silgiCtx.tryUse();
35
+ }
36
+
37
+ var HttpStatus = /* @__PURE__ */ ((HttpStatus2) => {
38
+ HttpStatus2[HttpStatus2["CONTINUE"] = 100] = "CONTINUE";
39
+ HttpStatus2[HttpStatus2["SWITCHING_PROTOCOLS"] = 101] = "SWITCHING_PROTOCOLS";
40
+ HttpStatus2[HttpStatus2["PROCESSING"] = 102] = "PROCESSING";
41
+ HttpStatus2[HttpStatus2["EARLY_HINTS"] = 103] = "EARLY_HINTS";
42
+ HttpStatus2[HttpStatus2["OK"] = 200] = "OK";
43
+ HttpStatus2[HttpStatus2["CREATED"] = 201] = "CREATED";
44
+ HttpStatus2[HttpStatus2["ACCEPTED"] = 202] = "ACCEPTED";
45
+ HttpStatus2[HttpStatus2["NON_AUTHORITATIVE_INFORMATION"] = 203] = "NON_AUTHORITATIVE_INFORMATION";
46
+ HttpStatus2[HttpStatus2["NO_CONTENT"] = 204] = "NO_CONTENT";
47
+ HttpStatus2[HttpStatus2["RESET_CONTENT"] = 205] = "RESET_CONTENT";
48
+ HttpStatus2[HttpStatus2["PARTIAL_CONTENT"] = 206] = "PARTIAL_CONTENT";
49
+ HttpStatus2[HttpStatus2["MULTI_STATUS"] = 207] = "MULTI_STATUS";
50
+ HttpStatus2[HttpStatus2["ALREADY_REPORTED"] = 208] = "ALREADY_REPORTED";
51
+ HttpStatus2[HttpStatus2["IM_USED"] = 226] = "IM_USED";
52
+ HttpStatus2[HttpStatus2["MULTIPLE_CHOICES"] = 300] = "MULTIPLE_CHOICES";
53
+ HttpStatus2[HttpStatus2["MOVED_PERMANENTLY"] = 301] = "MOVED_PERMANENTLY";
54
+ HttpStatus2[HttpStatus2["FOUND"] = 302] = "FOUND";
55
+ HttpStatus2[HttpStatus2["SEE_OTHER"] = 303] = "SEE_OTHER";
56
+ HttpStatus2[HttpStatus2["NOT_MODIFIED"] = 304] = "NOT_MODIFIED";
57
+ HttpStatus2[HttpStatus2["USE_PROXY"] = 305] = "USE_PROXY";
58
+ HttpStatus2[HttpStatus2["TEMPORARY_REDIRECT"] = 307] = "TEMPORARY_REDIRECT";
59
+ HttpStatus2[HttpStatus2["PERMANENT_REDIRECT"] = 308] = "PERMANENT_REDIRECT";
60
+ HttpStatus2[HttpStatus2["BAD_REQUEST"] = 400] = "BAD_REQUEST";
61
+ HttpStatus2[HttpStatus2["UNAUTHORIZED"] = 401] = "UNAUTHORIZED";
62
+ HttpStatus2[HttpStatus2["PAYMENT_REQUIRED"] = 402] = "PAYMENT_REQUIRED";
63
+ HttpStatus2[HttpStatus2["FORBIDDEN"] = 403] = "FORBIDDEN";
64
+ HttpStatus2[HttpStatus2["NOT_FOUND"] = 404] = "NOT_FOUND";
65
+ HttpStatus2[HttpStatus2["METHOD_NOT_ALLOWED"] = 405] = "METHOD_NOT_ALLOWED";
66
+ HttpStatus2[HttpStatus2["NOT_ACCEPTABLE"] = 406] = "NOT_ACCEPTABLE";
67
+ HttpStatus2[HttpStatus2["PROXY_AUTHENTICATION_REQUIRED"] = 407] = "PROXY_AUTHENTICATION_REQUIRED";
68
+ HttpStatus2[HttpStatus2["REQUEST_TIMEOUT"] = 408] = "REQUEST_TIMEOUT";
69
+ HttpStatus2[HttpStatus2["CONFLICT"] = 409] = "CONFLICT";
70
+ HttpStatus2[HttpStatus2["GONE"] = 410] = "GONE";
71
+ HttpStatus2[HttpStatus2["LENGTH_REQUIRED"] = 411] = "LENGTH_REQUIRED";
72
+ HttpStatus2[HttpStatus2["PRECONDITION_FAILED"] = 412] = "PRECONDITION_FAILED";
73
+ HttpStatus2[HttpStatus2["PAYLOAD_TOO_LARGE"] = 413] = "PAYLOAD_TOO_LARGE";
74
+ HttpStatus2[HttpStatus2["URI_TOO_LONG"] = 414] = "URI_TOO_LONG";
75
+ HttpStatus2[HttpStatus2["UNSUPPORTED_MEDIA_TYPE"] = 415] = "UNSUPPORTED_MEDIA_TYPE";
76
+ HttpStatus2[HttpStatus2["RANGE_NOT_SATISFIABLE"] = 416] = "RANGE_NOT_SATISFIABLE";
77
+ HttpStatus2[HttpStatus2["EXPECTATION_FAILED"] = 417] = "EXPECTATION_FAILED";
78
+ HttpStatus2[HttpStatus2["IM_A_TEAPOT"] = 418] = "IM_A_TEAPOT";
79
+ HttpStatus2[HttpStatus2["MISDIRECTED_REQUEST"] = 421] = "MISDIRECTED_REQUEST";
80
+ HttpStatus2[HttpStatus2["UNPROCESSABLE_ENTITY"] = 422] = "UNPROCESSABLE_ENTITY";
81
+ HttpStatus2[HttpStatus2["LOCKED"] = 423] = "LOCKED";
82
+ HttpStatus2[HttpStatus2["FAILED_DEPENDENCY"] = 424] = "FAILED_DEPENDENCY";
83
+ HttpStatus2[HttpStatus2["TOO_EARLY"] = 425] = "TOO_EARLY";
84
+ HttpStatus2[HttpStatus2["UPGRADE_REQUIRED"] = 426] = "UPGRADE_REQUIRED";
85
+ HttpStatus2[HttpStatus2["PRECONDITION_REQUIRED"] = 428] = "PRECONDITION_REQUIRED";
86
+ HttpStatus2[HttpStatus2["TOO_MANY_REQUESTS"] = 429] = "TOO_MANY_REQUESTS";
87
+ HttpStatus2[HttpStatus2["REQUEST_HEADER_FIELDS_TOO_LARGE"] = 431] = "REQUEST_HEADER_FIELDS_TOO_LARGE";
88
+ HttpStatus2[HttpStatus2["UNAVAILABLE_FOR_LEGAL_REASONS"] = 451] = "UNAVAILABLE_FOR_LEGAL_REASONS";
89
+ HttpStatus2[HttpStatus2["INTERNAL_SERVER_ERROR"] = 500] = "INTERNAL_SERVER_ERROR";
90
+ HttpStatus2[HttpStatus2["NOT_IMPLEMENTED"] = 501] = "NOT_IMPLEMENTED";
91
+ HttpStatus2[HttpStatus2["BAD_GATEWAY"] = 502] = "BAD_GATEWAY";
92
+ HttpStatus2[HttpStatus2["SERVICE_UNAVAILABLE"] = 503] = "SERVICE_UNAVAILABLE";
93
+ HttpStatus2[HttpStatus2["GATEWAY_TIMEOUT"] = 504] = "GATEWAY_TIMEOUT";
94
+ HttpStatus2[HttpStatus2["HTTP_VERSION_NOT_SUPPORTED"] = 505] = "HTTP_VERSION_NOT_SUPPORTED";
95
+ HttpStatus2[HttpStatus2["VARIANT_ALSO_NEGOTIATES"] = 506] = "VARIANT_ALSO_NEGOTIATES";
96
+ HttpStatus2[HttpStatus2["INSUFFICIENT_STORAGE"] = 507] = "INSUFFICIENT_STORAGE";
97
+ HttpStatus2[HttpStatus2["LOOP_DETECTED"] = 508] = "LOOP_DETECTED";
98
+ HttpStatus2[HttpStatus2["NOT_EXTENDED"] = 510] = "NOT_EXTENDED";
99
+ HttpStatus2[HttpStatus2["NETWORK_AUTHENTICATION_REQUIRED"] = 511] = "NETWORK_AUTHENTICATION_REQUIRED";
100
+ return HttpStatus2;
101
+ })(HttpStatus || {});
102
+ var ErrorSeverity = /* @__PURE__ */ ((ErrorSeverity2) => {
103
+ ErrorSeverity2["DEBUG"] = "DEBUG";
104
+ ErrorSeverity2["INFO"] = "INFO";
105
+ ErrorSeverity2["WARNING"] = "WARNING";
106
+ ErrorSeverity2["ERROR"] = "ERROR";
107
+ ErrorSeverity2["CRITICAL"] = "CRITICAL";
108
+ return ErrorSeverity2;
109
+ })(ErrorSeverity || {});
110
+ var ErrorCategory = /* @__PURE__ */ ((ErrorCategory2) => {
111
+ ErrorCategory2["AUTHENTICATION"] = "auth";
112
+ ErrorCategory2["AUTHORIZATION"] = "authorization";
113
+ ErrorCategory2["VALIDATION"] = "validation";
114
+ ErrorCategory2["BUSINESS"] = "business";
115
+ ErrorCategory2["INFRASTRUCTURE"] = "infrastructure";
116
+ ErrorCategory2["EXTERNAL"] = "external";
117
+ ErrorCategory2["UNKNOWN"] = "unknown";
118
+ return ErrorCategory2;
119
+ })(ErrorCategory || {});
120
+ class ErrorFactory {
121
+ static createMetadata(metadata) {
122
+ return {
123
+ timestamp: Date.now(),
124
+ ...metadata
125
+ };
126
+ }
127
+ static create(options) {
128
+ return new SilgiError({
129
+ code: options.code ?? options.httpStatus ?? 500 /* INTERNAL_SERVER_ERROR */,
130
+ message: options.message,
131
+ category: options.category ?? "unknown" /* UNKNOWN */,
132
+ severity: options.severity ?? "ERROR" /* ERROR */,
133
+ httpStatus: options.httpStatus ?? 500 /* INTERNAL_SERVER_ERROR */,
134
+ metadata: this.createMetadata(options.metadata),
135
+ cause: options.cause,
136
+ context: options.context
137
+ });
138
+ }
139
+ // Predefined error creators
140
+ static authenticationError(message, context) {
141
+ return this.create({
142
+ message,
143
+ code: 401,
144
+ category: "auth" /* AUTHENTICATION */,
145
+ severity: "ERROR" /* ERROR */,
146
+ httpStatus: 401 /* UNAUTHORIZED */,
147
+ context
148
+ });
149
+ }
150
+ static authorizationError(message, context) {
151
+ return this.create({
152
+ message,
153
+ code: 403,
154
+ category: "authorization" /* AUTHORIZATION */,
155
+ severity: "ERROR" /* ERROR */,
156
+ httpStatus: 403 /* FORBIDDEN */,
157
+ context
158
+ });
159
+ }
160
+ static validationError(message, context) {
161
+ return this.create({
162
+ message,
163
+ code: 400,
164
+ category: "validation" /* VALIDATION */,
165
+ severity: "WARNING" /* WARNING */,
166
+ httpStatus: 400 /* BAD_REQUEST */,
167
+ context
168
+ });
169
+ }
170
+ static notFoundError(message, context) {
171
+ return this.create({
172
+ message,
173
+ code: 404,
174
+ category: "business" /* BUSINESS */,
175
+ severity: "WARNING" /* WARNING */,
176
+ httpStatus: 404 /* NOT_FOUND */,
177
+ context
178
+ });
179
+ }
180
+ static internalError(message, cause) {
181
+ return this.create({
182
+ message,
183
+ code: 500,
184
+ category: "infrastructure" /* INFRASTRUCTURE */,
185
+ severity: "CRITICAL" /* CRITICAL */,
186
+ httpStatus: 500 /* INTERNAL_SERVER_ERROR */,
187
+ cause
188
+ });
189
+ }
190
+ }
191
+ class SilgiError extends Error {
192
+ code;
193
+ category;
194
+ severity;
195
+ httpStatus;
196
+ metadata;
197
+ context;
198
+ cause;
199
+ constructor(error) {
200
+ super(error.message);
201
+ this.name = "SilgiError";
202
+ this.code = error.code;
203
+ this.category = error.category;
204
+ this.severity = error.severity;
205
+ this.httpStatus = error.httpStatus;
206
+ this.metadata = error.metadata ?? { timestamp: Date.now() };
207
+ this.context = error.context;
208
+ this.cause = error.cause;
209
+ if (Error.captureStackTrace) {
210
+ Error.captureStackTrace(this, this.constructor);
211
+ }
212
+ }
213
+ toString() {
214
+ let str = `${this.name} [${this.code}] ${this.severity}: ${this.message}`;
215
+ str += `
216
+ Category: ${this.category}`;
217
+ str += `
218
+ HTTP Status: ${this.httpStatus}`;
219
+ if (this.context) {
220
+ str += `
221
+ Context: ${JSON.stringify(this.context, null, 2)}`;
222
+ }
223
+ if (this.metadata) {
224
+ str += `
225
+ Metadata: ${JSON.stringify(this.metadata, null, 2)}`;
226
+ }
227
+ if (this.stack) {
228
+ str += `
229
+ ${this.stack}`;
230
+ }
231
+ return str;
232
+ }
233
+ toJSON() {
234
+ return {
235
+ name: this.name,
236
+ code: this.code,
237
+ message: this.message,
238
+ category: this.category,
239
+ severity: this.severity,
240
+ httpStatus: this.httpStatus,
241
+ metadata: this.metadata,
242
+ context: this.context,
243
+ stack: this.stack
244
+ };
245
+ }
246
+ static isError(error) {
247
+ return error instanceof SilgiError || typeof error === "object" && error !== null && "name" in error && error.name === "SilgiError";
248
+ }
249
+ static from(error) {
250
+ if (error instanceof SilgiError) {
251
+ return error;
252
+ }
253
+ return ErrorFactory.internalError(
254
+ error instanceof Error ? error.message : String(error),
255
+ error instanceof Error ? error : void 0
256
+ );
257
+ }
258
+ }
259
+ function isBaseError(error) {
260
+ return typeof error === "object" && error !== null && "code" in error && "message" in error && "category" in error && "severity" in error && "httpStatus" in error;
261
+ }
262
+
263
+ function parseURI(uri, uris) {
264
+ if (!uri) {
265
+ throw ErrorFactory.create({
266
+ message: "URI cannot be empty",
267
+ httpStatus: HttpStatus.BAD_REQUEST,
268
+ context: { uri }
269
+ });
270
+ }
271
+ if (!uris) {
272
+ throw ErrorFactory.create({
273
+ message: "URIs configuration is not provided",
274
+ httpStatus: HttpStatus.INTERNAL_SERVER_ERROR,
275
+ context: { uri }
276
+ });
277
+ }
278
+ const cleanUri = uri.replace(/^\/*(srn\/)?/, "").replace(/\/*$/, "");
279
+ const [path, queryString] = cleanUri.split("?");
280
+ const parts = path.split("/");
281
+ const query = queryString ? Object.fromEntries(
282
+ queryString.split("&").map((param) => param.split("="))
283
+ ) : void 0;
284
+ const method = query?.method ? query?.method.toLowerCase() : void 0;
285
+ const namespaceName = parts[0];
286
+ const serviceName = parts[1];
287
+ const methodName = method || parts[2];
288
+ const actionName = method ? parts[2] : parts[3];
289
+ if (!namespaceName || !serviceName || !methodName || !actionName) {
290
+ throw ErrorFactory.create({
291
+ message: "Invalid URI format: Insufficient path segments",
292
+ httpStatus: HttpStatus.BAD_REQUEST,
293
+ context: {
294
+ uri,
295
+ cleanUri,
296
+ partsLength: parts.length,
297
+ method,
298
+ namespaceName,
299
+ serviceName,
300
+ methodName,
301
+ actionName
302
+ }
303
+ });
304
+ }
305
+ const baseUri = `${namespaceName}/${serviceName}/${methodName}/${actionName}`;
306
+ const paramStartIndex = method ? 3 : 4;
307
+ const parameters = parts.slice(paramStartIndex);
308
+ const normalizedUri = method ? `${namespaceName}/${serviceName}/${method}/${actionName}${parameters.length ? `/${parameters.join("/")}` : ""}` : cleanUri;
309
+ const template = uris[baseUri];
310
+ if (template === void 0) {
311
+ throw ErrorFactory.create({
312
+ message: "No route found for URI",
313
+ httpStatus: HttpStatus.NOT_FOUND,
314
+ context: {
315
+ uri,
316
+ baseUri
317
+ }
318
+ });
319
+ }
320
+ if (template === "") {
321
+ if (parameters.length > 0) {
322
+ throw ErrorFactory.create({
323
+ message: "No parameters expected for this route",
324
+ httpStatus: HttpStatus.BAD_REQUEST,
325
+ context: {
326
+ uri,
327
+ baseUri,
328
+ extraParams: parameters
329
+ }
330
+ });
331
+ }
332
+ if (query && query.method) {
333
+ delete query.method;
334
+ }
335
+ return {
336
+ namespaceName,
337
+ serviceName,
338
+ methodName,
339
+ actionName,
340
+ raw: normalizedUri,
341
+ parts: [namespaceName, serviceName, methodName, actionName],
342
+ routerParams: {},
343
+ query,
344
+ uri: baseUri
345
+ };
346
+ }
347
+ const routeTemplate = typeof template === "string" ? template : template.pattern;
348
+ const validators = typeof template === "string" ? void 0 : template.validators;
349
+ const routerParams = {};
350
+ const templateParts = routeTemplate.split("/").filter(Boolean);
351
+ const paramValues = parameters;
352
+ let valueIndex = 0;
353
+ templateParts.forEach((part) => {
354
+ if (part.startsWith(":")) {
355
+ const paramName = part.substring(1);
356
+ const paramValue = paramValues[valueIndex];
357
+ if (validators?.[paramName] && paramValue) {
358
+ if (!validators[paramName](paramValue)) {
359
+ throw ErrorFactory.create({
360
+ message: "Invalid value for parameter",
361
+ httpStatus: HttpStatus.UNPROCESSABLE_ENTITY,
362
+ context: {
363
+ uri,
364
+ paramName,
365
+ paramValue,
366
+ validatorName: paramName
367
+ }
368
+ });
369
+ }
370
+ }
371
+ routerParams[paramName] = paramValue || void 0;
372
+ valueIndex++;
373
+ } else if (part && part === paramValues[valueIndex]) {
374
+ valueIndex++;
375
+ }
376
+ });
377
+ return {
378
+ namespaceName,
379
+ serviceName,
380
+ methodName,
381
+ actionName,
382
+ raw: normalizedUri,
383
+ parts: [namespaceName, serviceName, methodName, actionName],
384
+ routerParams,
385
+ query: method ? void 0 : query,
386
+ uri: baseUri
387
+ };
388
+ }
389
+
390
+ async function findAction(silgi, uri) {
391
+ const { parts } = parseURI(uri, silgi.uris);
392
+ let result = silgi.services;
393
+ for (const part of parts) {
394
+ if (result && Object.prototype.hasOwnProperty.call(result, part)) {
395
+ result = Object.assign({}, result[part]);
396
+ } else {
397
+ silgi.logger.fail("Action not found:", `${parts.join("/")}`);
398
+ continue;
399
+ }
400
+ }
401
+ return result;
402
+ }
403
+ async function scanAction(silgi) {
404
+ for (const [key, _value] of Object.entries(silgi.uris)) {
405
+ const segments = key.split("/").filter(Boolean);
406
+ if (segments.length !== 4) {
407
+ console.error(`Invalid URI format for key "${key}". URI must have exactly 4 segments in format: namespace/service/method/action`);
408
+ continue;
409
+ }
410
+ const [namespace, service, method, action] = segments;
411
+ if (!namespace || !service || !method || !action) {
412
+ console.error(`Invalid URI segments for key "${key}". All segments must be non-empty`);
413
+ continue;
414
+ }
415
+ const handler = await findAction(silgi, key);
416
+ silgi.scannedHandlers.set(key, handler);
417
+ }
418
+ }
419
+
420
+ function replaceRuntimeValues(obj, runtime) {
421
+ if (!obj || typeof obj !== "object")
422
+ return obj;
423
+ for (const key in obj) {
424
+ if (typeof obj[key] === "string" && obj[key].startsWith("runtime.")) {
425
+ const runtimePath = obj[key].substring(8).split(".");
426
+ let value = runtime;
427
+ for (const segment of runtimePath) {
428
+ if (value === void 0 || value === null)
429
+ break;
430
+ value = value[segment];
431
+ }
432
+ if (value !== void 0)
433
+ obj[key] = value;
434
+ } else if (typeof obj[key] === "object" && obj[key] !== null) {
435
+ obj[key] = replaceRuntimeValues(obj[key], runtime);
436
+ }
437
+ }
438
+ return obj;
439
+ }
440
+
441
+ async function createStorage(silgi) {
442
+ const storage = createStorage$1();
443
+ const runtime = useSilgiRuntimeConfig();
444
+ const mounts = klona({
445
+ ...silgi.options.storage,
446
+ ...silgi.options.devStorage
447
+ });
448
+ for (const [path, opts] of Object.entries(mounts)) {
449
+ if (opts.driver) {
450
+ const driver = await import(builtinDrivers[opts.driver] || opts.driver).then((r) => r.default || r);
451
+ const processedOpts = replaceRuntimeValues({ ...opts }, runtime);
452
+ storage.mount(path, driver(processedOpts));
453
+ } else {
454
+ silgi.logger.warn(`No \`driver\` set for storage mount point "${path}".`);
455
+ }
456
+ }
457
+ return storage;
458
+ }
459
+ function useSilgiStorage(base = "/memory:cache") {
460
+ const silgi = useSilgi();
461
+ return base ? prefixStorage(silgi.storage, base) : silgi.storage;
462
+ }
463
+ async function generateStorageKey(params) {
464
+ const {
465
+ operation,
466
+ input,
467
+ keyGenerator,
468
+ requestId,
469
+ storageOptions
470
+ } = params;
471
+ const cacheScopePrefix = storageOptions?.scope === "request" ? "req" : "global";
472
+ const parts = [
473
+ cacheScopePrefix,
474
+ // Always include scope prefix first
475
+ operation.namespaceName,
476
+ operation.serviceName,
477
+ operation.methodName
478
+ ].filter(Boolean);
479
+ if (storageOptions?.scope === "request") {
480
+ if (!requestId) {
481
+ throw ErrorFactory.create({
482
+ code: HttpStatus.BAD_REQUEST,
483
+ message: "Request ID is required for request-scoped cache",
484
+ context: {
485
+ requestId,
486
+ operation,
487
+ input,
488
+ storageOptions,
489
+ keyGenerator
490
+ }
491
+ });
492
+ }
493
+ parts.push(requestId);
494
+ }
495
+ if (keyGenerator) {
496
+ const customKey = await Promise.resolve(keyGenerator(input));
497
+ parts.push(customKey);
498
+ } else {
499
+ parts.push(typeof input === "object" ? JSON.stringify(input) : String(input));
500
+ }
501
+ return Buffer.from(parts.join(":")).toString("base64");
502
+ }
503
+
504
+ async function runSilgiPlugins(silgi) {
505
+ for (const plugin of silgi.plugins) {
506
+ try {
507
+ await plugin(silgi);
508
+ } catch (error) {
509
+ silgi.captureError(error, { tags: ["plugin"] });
510
+ throw error;
511
+ }
512
+ }
513
+ }
514
+ async function createSilgi(config) {
515
+ const hooks = createHooks();
516
+ const silgi = {
517
+ schemas: config.schemas,
518
+ services: config.services ?? {},
519
+ shared: config.shared ?? void 0,
520
+ uris: config.uris ?? {},
521
+ modulesURIs: config.modulesURIs ?? {},
522
+ scannedHandlers: /* @__PURE__ */ new Map(),
523
+ plugins: config.plugins ?? [],
524
+ framework: config.framework ?? void 0,
525
+ storage: config.options.putStorage ?? void 0,
526
+ options: config.options ?? {},
527
+ hooks,
528
+ callHook: hooks.callHook,
529
+ addHooks: hooks.addHooks,
530
+ hook: hooks.hook,
531
+ ready: () => {
532
+ return hooks.callHook("ready", silgi);
533
+ },
534
+ envOptions: config.envOptions ?? {},
535
+ close: () => hooks.callHook("close", silgi),
536
+ logger: createConsola(defu(config.options?.consolaOptions ?? {}, {
537
+ tag: "silgi"
538
+ })).withTag("silgi"),
539
+ captureError: config.captureError ?? (() => {
540
+ }),
541
+ routeRules: void 0
542
+ };
543
+ const routeRules = createRouteRules();
544
+ routeRules.importRules(config.options.routeRules ?? {});
545
+ silgi.routeRules = routeRules;
546
+ silgi.hooks.addHooks(silgi.options.hooks);
547
+ await runSilgiPlugins(silgi);
548
+ await scanAction(silgi);
549
+ if (!silgi.storage) {
550
+ silgi.storage = await createStorage(silgi);
551
+ }
552
+ silgi.shared.storage = (...data) => {
553
+ return useSilgiStorage(...data);
554
+ };
555
+ silgi.shared.runtimeConfig = silgi.options.runtimeConfig;
556
+ if (silgiCtx.tryUse()) {
557
+ silgiCtx.unset();
558
+ silgiCtx.set(silgi);
559
+ } else {
560
+ silgiCtx.set(silgi);
561
+ silgi.hook("close", () => silgiCtx.unset());
562
+ }
563
+ silgi.logger.info("Silgi installed");
564
+ hooks.hookOnce("close", async () => {
565
+ hooks.removeAllHooks();
566
+ await silgi.storage.dispose();
567
+ });
568
+ return silgi;
569
+ }
570
+
571
+ function silgi(event) {
572
+ return {
573
+ execute: (uriString, input, source, queryParams) => {
574
+ return execute(uriString, input, event, source, queryParams);
575
+ }
576
+ };
577
+ }
578
+ async function execute(uriString, input, event, source, queryParams) {
579
+ const silgiCtx = useSilgi();
580
+ const config = {
581
+ returnNull: false
582
+ };
583
+ try {
584
+ const operation = parseURI(uriString, silgiCtx.uris);
585
+ if (!operation) {
586
+ throw ErrorFactory.create({ message: "Invalid URI", httpStatus: HttpStatus.BAD_REQUEST });
587
+ }
588
+ let success = false;
589
+ let cached = false;
590
+ let result;
591
+ const handler = silgiCtx.scannedHandlers.get(operation.uri);
592
+ if (!handler) {
593
+ throw ErrorFactory.create({
594
+ message: "execute not found",
595
+ httpStatus: HttpStatus.NOT_FOUND,
596
+ context: {
597
+ uri: uriString
598
+ }
599
+ });
600
+ }
601
+ await silgiCtx.callHook("execute:before", {
602
+ operation,
603
+ input,
604
+ event,
605
+ modules: handler.modules,
606
+ source,
607
+ config
608
+ });
609
+ if (config.returnNull) {
610
+ return result;
611
+ }
612
+ const cacheData = await cacheExecute(input, operation, handler, event);
613
+ if (cacheData?.success) {
614
+ result = cacheData.data;
615
+ success = cacheData.success;
616
+ cached = cacheData.cached;
617
+ } else {
618
+ let parameters = defu$1(operation.routerParams, operation.query) || {};
619
+ if (queryParams) {
620
+ parameters = defu$1(queryParams, parameters);
621
+ }
622
+ silgiCtx.shared.silgi = silgi(event);
623
+ result = await handler?.handler(
624
+ defu$1(input, { parameters }),
625
+ silgiCtx.shared,
626
+ event,
627
+ source
628
+ );
629
+ success = true;
630
+ }
631
+ await silgiCtx.callHook("execute:after", {
632
+ operation,
633
+ input,
634
+ event,
635
+ result,
636
+ success,
637
+ source,
638
+ modules: handler.modules,
639
+ config
640
+ });
641
+ if (!cached) {
642
+ if (success && cacheData?.cachedKey && handler.storage) {
643
+ await useSilgiStorage(handler.storage.base).setItem(cacheData.cachedKey, result, handler.storage.options);
644
+ }
645
+ }
646
+ return result;
647
+ } catch (err) {
648
+ await silgiCtx.callHook("execute:error", {
649
+ input,
650
+ event,
651
+ source,
652
+ error: err instanceof Error ? err : new Error(String(err)),
653
+ timestamp: Date.now(),
654
+ config
655
+ });
656
+ silgiCtx.captureError(SilgiError.from(err), {
657
+ event,
658
+ tags: ["execute"]
659
+ });
660
+ throw err;
661
+ }
662
+ }
663
+ async function cacheExecute(input, operation, handler, event) {
664
+ if (!handler.storage)
665
+ return;
666
+ const cacheKey = handler.storage ? await generateStorageKey({
667
+ operation,
668
+ input,
669
+ keyGenerator: handler.storage.key,
670
+ storageOptions: handler.storage,
671
+ requestId: event?.requestId
672
+ }) : null;
673
+ if (cacheKey) {
674
+ const cachedResult = await useSilgiStorage(handler.storage.base).getItem(cacheKey);
675
+ if (cachedResult !== null) {
676
+ return {
677
+ success: true,
678
+ data: normalizeResult(cachedResult),
679
+ cached: true,
680
+ cachedKey: cacheKey
681
+ };
682
+ }
683
+ }
684
+ return {
685
+ success: false,
686
+ data: null,
687
+ cached: false,
688
+ cachedKey: cacheKey
689
+ };
690
+ }
691
+
692
+ function merge(items, maxLevel = 4, currentLevel = 1) {
693
+ const arrayItems = Array.isArray(items) ? items : [items];
694
+ return arrayItems.reduce((acc, item) => {
695
+ if (!item)
696
+ return acc;
697
+ Object.keys(item).forEach((key) => {
698
+ if (typeof item[key] === "object" && item[key] !== null && currentLevel < maxLevel) {
699
+ if (!acc[key] || typeof acc[key] !== "object") {
700
+ acc[key] = {};
701
+ }
702
+ acc[key] = merge([acc[key], item[key]], maxLevel, currentLevel + 1);
703
+ } else if (acc[key] === void 0) {
704
+ acc[key] = item[key];
705
+ }
706
+ });
707
+ return acc;
708
+ }, {});
709
+ }
710
+ function mergeSchemas(typesOrArray) {
711
+ return merge(typesOrArray);
712
+ }
713
+ function mergeServices(servicesOrArray) {
714
+ return merge(servicesOrArray);
715
+ }
716
+ function mergeShared(sharedOrArray) {
717
+ return merge(sharedOrArray, 1, 1);
718
+ }
719
+
720
+ function getEvent(event) {
721
+ const silgi = useSilgi();
722
+ if (silgi.options.present === "h3" || silgi.options.present === "nitro" || silgi.options.present === "nuxt") {
723
+ return event.event;
724
+ }
725
+ return event;
726
+ }
727
+ function getEventContext(event) {
728
+ const _event = getEvent(event);
729
+ return _event.context;
730
+ }
731
+
732
+ function createSchema(silgiType) {
733
+ return silgiType;
734
+ }
735
+
736
+ function createService(variables) {
737
+ return variables;
738
+ }
739
+
740
+ function createShared(shared) {
741
+ return shared;
742
+ }
743
+
744
+ function storageMount(silgi) {
745
+ const _silgi = silgi || useSilgi();
746
+ return (base, driver) => {
747
+ const existingStorage = _silgi.storage.getMount(base);
748
+ if (existingStorage) {
749
+ return existingStorage.driver;
750
+ }
751
+ const storage = _silgi.storage.mount(base, driver);
752
+ return storage;
753
+ };
754
+ }
755
+
756
+ const autoImportTypes = [
757
+ "ExtractInputFromURI",
758
+ "ExtractOutputFromURI",
759
+ "ExtractPathParamsFromURI",
760
+ "ExtractQueryParamsFromURI"
761
+ ];
762
+
763
+ export { ErrorCategory, ErrorFactory, ErrorSeverity, HttpStatus, SilgiError, autoImportTypes, createSchema, createService, createShared, createSilgi, createStorage, getEvent, getEventContext, isBaseError, mergeSchemas, mergeServices, mergeShared, parseURI, replaceRuntimeValues, silgi, silgiCtx, storageMount, tryUseSilgi, useSilgi, useSilgiStorage };