silgi 0.7.1 → 0.7.2

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 (83) hide show
  1. package/dist/_chunks/index.mjs +5 -0
  2. package/dist/cli/{utils/compatibility.mjs → compatibility.mjs} +1 -1
  3. package/dist/cli/config/index.d.mts +11 -0
  4. package/dist/cli/config/index.d.ts +11 -0
  5. package/dist/{core/config/types.mjs → cli/config/index.mjs} +19 -2
  6. package/dist/cli/index.mjs +3 -3
  7. package/dist/cli/loader.mjs +581 -0
  8. package/dist/cli/prepare.mjs +1488 -0
  9. package/dist/core/index.d.mts +2 -10
  10. package/dist/core/index.d.ts +2 -10
  11. package/dist/core/index.mjs +943 -16
  12. package/dist/ecosystem/nitro/index.mjs +62 -1
  13. package/dist/ecosystem/nuxt/module.mjs +1 -1
  14. package/dist/kit/index.mjs +299 -10
  15. package/dist/meta/index.d.mts +1 -1
  16. package/dist/meta/index.d.ts +1 -1
  17. package/dist/meta/index.mjs +1 -1
  18. package/package.json +5 -1
  19. package/dist/cli/build/framework/h3.mjs +0 -46
  20. package/dist/cli/build/framework/index.mjs +0 -7
  21. package/dist/cli/build/framework/nitro.mjs +0 -28
  22. package/dist/cli/build/framework/nuxt.mjs +0 -9
  23. package/dist/cli/build/prepare.mjs +0 -7
  24. package/dist/cli/build/scanURIs.mjs +0 -27
  25. package/dist/cli/build/template/framework.mjs +0 -91
  26. package/dist/cli/build/template/schema.mjs +0 -115
  27. package/dist/cli/build/template/silgi.mjs +0 -149
  28. package/dist/cli/build/types.mjs +0 -130
  29. package/dist/cli/commands/prepare.mjs +0 -49
  30. package/dist/cli/common.mjs +0 -13
  31. package/dist/cli/core/app.mjs +0 -89
  32. package/dist/cli/core/scan.mjs +0 -40
  33. package/dist/cli/core/silgi.mjs +0 -77
  34. package/dist/cli/core/storage.mjs +0 -11
  35. package/dist/cli/core/templates.mjs +0 -29
  36. package/dist/cli/module/exportScan.mjs +0 -69
  37. package/dist/cli/module/install.mjs +0 -52
  38. package/dist/cli/module/scan.mjs +0 -141
  39. package/dist/cli/utils/generateRouterDTS.mjs +0 -84
  40. package/dist/cli/utils/ignore.mjs +0 -46
  41. package/dist/cli/utils/readCoreFile.mjs +0 -47
  42. package/dist/cli/utils/scan.mjs +0 -147
  43. package/dist/cli/utils/storage.mjs +0 -21
  44. package/dist/cli/utils/uri.mjs +0 -71
  45. package/dist/core/config/defaults.mjs +0 -96
  46. package/dist/core/config/loader.mjs +0 -98
  47. package/dist/core/config/resolvers/compatibility.mjs +0 -90
  48. package/dist/core/config/resolvers/imports.mjs +0 -96
  49. package/dist/core/config/resolvers/paths.mjs +0 -194
  50. package/dist/core/config/resolvers/storage.mjs +0 -25
  51. package/dist/core/config/resolvers/url.mjs +0 -7
  52. package/dist/core/createSilgi.mjs +0 -84
  53. package/dist/core/error.mjs +0 -227
  54. package/dist/core/fetch/ofetch.mjs +0 -35
  55. package/dist/core/parser.mjs +0 -136
  56. package/dist/core/silgi.mjs +0 -114
  57. package/dist/core/silgiApp.mjs +0 -15
  58. package/dist/core/unctx.mjs +0 -27
  59. package/dist/core/uris/uri.mjs +0 -33
  60. package/dist/core/uris/utils.mjs +0 -127
  61. package/dist/core/utils/event.mjs +0 -5
  62. package/dist/core/utils/global.mjs +0 -12
  63. package/dist/core/utils/merge.mjs +0 -25
  64. package/dist/core/utils/schema.mjs +0 -5
  65. package/dist/core/utils/service.mjs +0 -5
  66. package/dist/core/utils/shared.mjs +0 -5
  67. package/dist/core/utils/storage.mjs +0 -70
  68. package/dist/ecosystem/nitro/module.mjs +0 -62
  69. package/dist/kit/esm.mjs +0 -10
  70. package/dist/kit/fs.mjs +0 -25
  71. package/dist/kit/isFramework.mjs +0 -25
  72. package/dist/kit/logger.mjs +0 -8
  73. package/dist/kit/module.mjs +0 -73
  74. package/dist/kit/path.mjs +0 -34
  75. package/dist/kit/preset.mjs +0 -6
  76. package/dist/kit/resolve.mjs +0 -78
  77. package/dist/kit/template.mjs +0 -47
  78. package/dist/kit/utils.mjs +0 -20
  79. package/dist/package.json.mjs +0 -5
  80. package/dist/schema/common.mjs +0 -43
  81. package/dist/schema/index.mjs +0 -9
  82. package/dist/schema/internal.mjs +0 -22
  83. /package/dist/cli/{commands/init.mjs → init.mjs} +0 -0
@@ -1,16 +1,943 @@
1
- export { loadOptions } from './config/loader.mjs';
2
- export { silgiGenerateType } from './config/types.mjs';
3
- export { createSilgi } from './createSilgi.mjs';
4
- export { createSilgiFetch } from './fetch/ofetch.mjs';
5
- export { SchemaParser } from './parser.mjs';
6
- export { silgi } from './silgi.mjs';
7
- export { parseURI } from './uris/utils.mjs';
8
- export { mergeSchemas, mergeServices, mergeShared } from './utils/merge.mjs';
9
- export { getEvent } from './utils/event.mjs';
10
- export { createSchema } from './utils/schema.mjs';
11
- export { createService } from './utils/service.mjs';
12
- export { createShared } from './utils/shared.mjs';
13
- export { createStorage, useSilgiStorage } from './utils/storage.mjs';
14
- export { ErrorCategory, ErrorFactory, ErrorSeverity, HttpStatus, SilgiError, isBaseError } from './error.mjs';
15
- export { silgiCtx, tryUseSilgi, useSilgi } from './unctx.mjs';
16
- export { silgiCLICtx, tryUseSilgiCLI, useSilgiCLI } from './silgiApp.mjs';
1
+ import { createConsola } from 'consola';
2
+ import defu from 'defu';
3
+ import { isEvent } from 'h3';
4
+ import { createHooks } from 'hookable';
5
+ import { defineUntypedSchema, applyDefaults } from 'untyped';
6
+ import { isDebug, isTest, isDevelopment } from 'std-env';
7
+ import { getContext } from 'unctx';
8
+ import { Buffer } from 'node:buffer';
9
+ import { klona } from 'klona';
10
+ import { createStorage as createStorage$1, builtinDrivers, prefixStorage } from 'unstorage';
11
+ import memoryDriver from 'unstorage/drivers/memory';
12
+ import { writeFileSync } from 'node:fs';
13
+ import { parseSync } from '@oxc-parser/wasm';
14
+
15
+ const common = defineUntypedSchema({
16
+ /**
17
+ * Environment to use.
18
+ *
19
+ * @default 'h3'
20
+ */
21
+ environment: {
22
+ $resolve: (val) => val ?? "h3"
23
+ },
24
+ /**
25
+ * Whether Nuxt is running in development mode.
26
+ *
27
+ * Normally, you should not need to set this.
28
+ */
29
+ dev: {
30
+ $resolve: (val) => val ?? Boolean(isDevelopment)
31
+ },
32
+ /**
33
+ * Whether your app is being unit tested.
34
+ */
35
+ test: {
36
+ $resolve: (val) => val ?? Boolean(isTest)
37
+ },
38
+ /**
39
+ * Set to `true` to enable debug mode.
40
+ *
41
+ * At the moment, it prints out hook names and timings on the server, and
42
+ * logs hook arguments as well in the browser.
43
+ *
44
+ */
45
+ debug: {
46
+ $resolve: (val) => val ?? isDebug
47
+ },
48
+ plugins: {
49
+ $resolve: (val) => (val || []).filter(Boolean)
50
+ },
51
+ $schema: {}
52
+ });
53
+
54
+ const internal = defineUntypedSchema({
55
+ /** @private */
56
+ _majorVersion: 4,
57
+ /** @private */
58
+ _generate: false,
59
+ /** @private */
60
+ _prepare: false,
61
+ /** @private */
62
+ _requiredPlugins: {},
63
+ /**
64
+ * @private
65
+ * @type {Array<{ meta: ModuleMeta; timings?: Record<string, number | undefined>; entryPath?: string }>}
66
+ */
67
+ _installedPlugins: [],
68
+ /** @private */
69
+ _plugins: [],
70
+ extensions: [".js", ".mjs", ".ts"]
71
+ });
72
+
73
+ const SilgiConfigSchema = {
74
+ ...common,
75
+ ...internal
76
+ };
77
+
78
+ const silgiCtx = getContext("silgi");
79
+ function useSilgi() {
80
+ const instance = silgiCtx.tryUse();
81
+ if (!instance) {
82
+ throw new Error("Silgi instance is unavailable!");
83
+ }
84
+ return instance;
85
+ }
86
+ function normalizeResult(result) {
87
+ if (Array.isArray(result)) {
88
+ return [...result];
89
+ }
90
+ if (result && typeof result === "object") {
91
+ if (Object.keys(result).every((key) => !Number.isNaN(Number(key)))) {
92
+ return Object.values(result);
93
+ }
94
+ return { ...result };
95
+ }
96
+ return result;
97
+ }
98
+ function tryUseSilgi() {
99
+ return silgiCtx.tryUse();
100
+ }
101
+
102
+ var HttpStatus = /* @__PURE__ */ ((HttpStatus2) => {
103
+ HttpStatus2[HttpStatus2["CONTINUE"] = 100] = "CONTINUE";
104
+ HttpStatus2[HttpStatus2["SWITCHING_PROTOCOLS"] = 101] = "SWITCHING_PROTOCOLS";
105
+ HttpStatus2[HttpStatus2["PROCESSING"] = 102] = "PROCESSING";
106
+ HttpStatus2[HttpStatus2["EARLY_HINTS"] = 103] = "EARLY_HINTS";
107
+ HttpStatus2[HttpStatus2["OK"] = 200] = "OK";
108
+ HttpStatus2[HttpStatus2["CREATED"] = 201] = "CREATED";
109
+ HttpStatus2[HttpStatus2["ACCEPTED"] = 202] = "ACCEPTED";
110
+ HttpStatus2[HttpStatus2["NON_AUTHORITATIVE_INFORMATION"] = 203] = "NON_AUTHORITATIVE_INFORMATION";
111
+ HttpStatus2[HttpStatus2["NO_CONTENT"] = 204] = "NO_CONTENT";
112
+ HttpStatus2[HttpStatus2["RESET_CONTENT"] = 205] = "RESET_CONTENT";
113
+ HttpStatus2[HttpStatus2["PARTIAL_CONTENT"] = 206] = "PARTIAL_CONTENT";
114
+ HttpStatus2[HttpStatus2["MULTI_STATUS"] = 207] = "MULTI_STATUS";
115
+ HttpStatus2[HttpStatus2["ALREADY_REPORTED"] = 208] = "ALREADY_REPORTED";
116
+ HttpStatus2[HttpStatus2["IM_USED"] = 226] = "IM_USED";
117
+ HttpStatus2[HttpStatus2["MULTIPLE_CHOICES"] = 300] = "MULTIPLE_CHOICES";
118
+ HttpStatus2[HttpStatus2["MOVED_PERMANENTLY"] = 301] = "MOVED_PERMANENTLY";
119
+ HttpStatus2[HttpStatus2["FOUND"] = 302] = "FOUND";
120
+ HttpStatus2[HttpStatus2["SEE_OTHER"] = 303] = "SEE_OTHER";
121
+ HttpStatus2[HttpStatus2["NOT_MODIFIED"] = 304] = "NOT_MODIFIED";
122
+ HttpStatus2[HttpStatus2["USE_PROXY"] = 305] = "USE_PROXY";
123
+ HttpStatus2[HttpStatus2["TEMPORARY_REDIRECT"] = 307] = "TEMPORARY_REDIRECT";
124
+ HttpStatus2[HttpStatus2["PERMANENT_REDIRECT"] = 308] = "PERMANENT_REDIRECT";
125
+ HttpStatus2[HttpStatus2["BAD_REQUEST"] = 400] = "BAD_REQUEST";
126
+ HttpStatus2[HttpStatus2["UNAUTHORIZED"] = 401] = "UNAUTHORIZED";
127
+ HttpStatus2[HttpStatus2["PAYMENT_REQUIRED"] = 402] = "PAYMENT_REQUIRED";
128
+ HttpStatus2[HttpStatus2["FORBIDDEN"] = 403] = "FORBIDDEN";
129
+ HttpStatus2[HttpStatus2["NOT_FOUND"] = 404] = "NOT_FOUND";
130
+ HttpStatus2[HttpStatus2["METHOD_NOT_ALLOWED"] = 405] = "METHOD_NOT_ALLOWED";
131
+ HttpStatus2[HttpStatus2["NOT_ACCEPTABLE"] = 406] = "NOT_ACCEPTABLE";
132
+ HttpStatus2[HttpStatus2["PROXY_AUTHENTICATION_REQUIRED"] = 407] = "PROXY_AUTHENTICATION_REQUIRED";
133
+ HttpStatus2[HttpStatus2["REQUEST_TIMEOUT"] = 408] = "REQUEST_TIMEOUT";
134
+ HttpStatus2[HttpStatus2["CONFLICT"] = 409] = "CONFLICT";
135
+ HttpStatus2[HttpStatus2["GONE"] = 410] = "GONE";
136
+ HttpStatus2[HttpStatus2["LENGTH_REQUIRED"] = 411] = "LENGTH_REQUIRED";
137
+ HttpStatus2[HttpStatus2["PRECONDITION_FAILED"] = 412] = "PRECONDITION_FAILED";
138
+ HttpStatus2[HttpStatus2["PAYLOAD_TOO_LARGE"] = 413] = "PAYLOAD_TOO_LARGE";
139
+ HttpStatus2[HttpStatus2["URI_TOO_LONG"] = 414] = "URI_TOO_LONG";
140
+ HttpStatus2[HttpStatus2["UNSUPPORTED_MEDIA_TYPE"] = 415] = "UNSUPPORTED_MEDIA_TYPE";
141
+ HttpStatus2[HttpStatus2["RANGE_NOT_SATISFIABLE"] = 416] = "RANGE_NOT_SATISFIABLE";
142
+ HttpStatus2[HttpStatus2["EXPECTATION_FAILED"] = 417] = "EXPECTATION_FAILED";
143
+ HttpStatus2[HttpStatus2["IM_A_TEAPOT"] = 418] = "IM_A_TEAPOT";
144
+ HttpStatus2[HttpStatus2["MISDIRECTED_REQUEST"] = 421] = "MISDIRECTED_REQUEST";
145
+ HttpStatus2[HttpStatus2["UNPROCESSABLE_ENTITY"] = 422] = "UNPROCESSABLE_ENTITY";
146
+ HttpStatus2[HttpStatus2["LOCKED"] = 423] = "LOCKED";
147
+ HttpStatus2[HttpStatus2["FAILED_DEPENDENCY"] = 424] = "FAILED_DEPENDENCY";
148
+ HttpStatus2[HttpStatus2["TOO_EARLY"] = 425] = "TOO_EARLY";
149
+ HttpStatus2[HttpStatus2["UPGRADE_REQUIRED"] = 426] = "UPGRADE_REQUIRED";
150
+ HttpStatus2[HttpStatus2["PRECONDITION_REQUIRED"] = 428] = "PRECONDITION_REQUIRED";
151
+ HttpStatus2[HttpStatus2["TOO_MANY_REQUESTS"] = 429] = "TOO_MANY_REQUESTS";
152
+ HttpStatus2[HttpStatus2["REQUEST_HEADER_FIELDS_TOO_LARGE"] = 431] = "REQUEST_HEADER_FIELDS_TOO_LARGE";
153
+ HttpStatus2[HttpStatus2["UNAVAILABLE_FOR_LEGAL_REASONS"] = 451] = "UNAVAILABLE_FOR_LEGAL_REASONS";
154
+ HttpStatus2[HttpStatus2["INTERNAL_SERVER_ERROR"] = 500] = "INTERNAL_SERVER_ERROR";
155
+ HttpStatus2[HttpStatus2["NOT_IMPLEMENTED"] = 501] = "NOT_IMPLEMENTED";
156
+ HttpStatus2[HttpStatus2["BAD_GATEWAY"] = 502] = "BAD_GATEWAY";
157
+ HttpStatus2[HttpStatus2["SERVICE_UNAVAILABLE"] = 503] = "SERVICE_UNAVAILABLE";
158
+ HttpStatus2[HttpStatus2["GATEWAY_TIMEOUT"] = 504] = "GATEWAY_TIMEOUT";
159
+ HttpStatus2[HttpStatus2["HTTP_VERSION_NOT_SUPPORTED"] = 505] = "HTTP_VERSION_NOT_SUPPORTED";
160
+ HttpStatus2[HttpStatus2["VARIANT_ALSO_NEGOTIATES"] = 506] = "VARIANT_ALSO_NEGOTIATES";
161
+ HttpStatus2[HttpStatus2["INSUFFICIENT_STORAGE"] = 507] = "INSUFFICIENT_STORAGE";
162
+ HttpStatus2[HttpStatus2["LOOP_DETECTED"] = 508] = "LOOP_DETECTED";
163
+ HttpStatus2[HttpStatus2["NOT_EXTENDED"] = 510] = "NOT_EXTENDED";
164
+ HttpStatus2[HttpStatus2["NETWORK_AUTHENTICATION_REQUIRED"] = 511] = "NETWORK_AUTHENTICATION_REQUIRED";
165
+ return HttpStatus2;
166
+ })(HttpStatus || {});
167
+ var ErrorSeverity = /* @__PURE__ */ ((ErrorSeverity2) => {
168
+ ErrorSeverity2["DEBUG"] = "DEBUG";
169
+ ErrorSeverity2["INFO"] = "INFO";
170
+ ErrorSeverity2["WARNING"] = "WARNING";
171
+ ErrorSeverity2["ERROR"] = "ERROR";
172
+ ErrorSeverity2["CRITICAL"] = "CRITICAL";
173
+ return ErrorSeverity2;
174
+ })(ErrorSeverity || {});
175
+ var ErrorCategory = /* @__PURE__ */ ((ErrorCategory2) => {
176
+ ErrorCategory2["AUTHENTICATION"] = "auth";
177
+ ErrorCategory2["AUTHORIZATION"] = "authorization";
178
+ ErrorCategory2["VALIDATION"] = "validation";
179
+ ErrorCategory2["BUSINESS"] = "business";
180
+ ErrorCategory2["INFRASTRUCTURE"] = "infrastructure";
181
+ ErrorCategory2["EXTERNAL"] = "external";
182
+ ErrorCategory2["UNKNOWN"] = "unknown";
183
+ return ErrorCategory2;
184
+ })(ErrorCategory || {});
185
+ class ErrorFactory {
186
+ static createMetadata(metadata) {
187
+ return {
188
+ timestamp: Date.now(),
189
+ ...metadata
190
+ };
191
+ }
192
+ static create(options) {
193
+ return new SilgiError({
194
+ code: options.code ?? options.httpStatus ?? 500 /* INTERNAL_SERVER_ERROR */,
195
+ message: options.message,
196
+ category: options.category ?? "unknown" /* UNKNOWN */,
197
+ severity: options.severity ?? "ERROR" /* ERROR */,
198
+ httpStatus: options.httpStatus ?? 500 /* INTERNAL_SERVER_ERROR */,
199
+ metadata: this.createMetadata(options.metadata),
200
+ cause: options.cause,
201
+ context: options.context
202
+ });
203
+ }
204
+ // Predefined error creators
205
+ static authenticationError(message, context) {
206
+ return this.create({
207
+ message,
208
+ code: 401,
209
+ category: "auth" /* AUTHENTICATION */,
210
+ severity: "ERROR" /* ERROR */,
211
+ httpStatus: 401 /* UNAUTHORIZED */,
212
+ context
213
+ });
214
+ }
215
+ static authorizationError(message, context) {
216
+ return this.create({
217
+ message,
218
+ code: 403,
219
+ category: "authorization" /* AUTHORIZATION */,
220
+ severity: "ERROR" /* ERROR */,
221
+ httpStatus: 403 /* FORBIDDEN */,
222
+ context
223
+ });
224
+ }
225
+ static validationError(message, context) {
226
+ return this.create({
227
+ message,
228
+ code: 400,
229
+ category: "validation" /* VALIDATION */,
230
+ severity: "WARNING" /* WARNING */,
231
+ httpStatus: 400 /* BAD_REQUEST */,
232
+ context
233
+ });
234
+ }
235
+ static notFoundError(message, context) {
236
+ return this.create({
237
+ message,
238
+ code: 404,
239
+ category: "business" /* BUSINESS */,
240
+ severity: "WARNING" /* WARNING */,
241
+ httpStatus: 404 /* NOT_FOUND */,
242
+ context
243
+ });
244
+ }
245
+ static internalError(message, cause) {
246
+ return this.create({
247
+ message,
248
+ code: 500,
249
+ category: "infrastructure" /* INFRASTRUCTURE */,
250
+ severity: "CRITICAL" /* CRITICAL */,
251
+ httpStatus: 500 /* INTERNAL_SERVER_ERROR */,
252
+ cause
253
+ });
254
+ }
255
+ }
256
+ class SilgiError extends Error {
257
+ code;
258
+ category;
259
+ severity;
260
+ httpStatus;
261
+ metadata;
262
+ context;
263
+ cause;
264
+ constructor(error) {
265
+ super(error.message);
266
+ this.name = "SilgiError";
267
+ this.code = error.code;
268
+ this.category = error.category;
269
+ this.severity = error.severity;
270
+ this.httpStatus = error.httpStatus;
271
+ this.metadata = error.metadata ?? { timestamp: Date.now() };
272
+ this.context = error.context;
273
+ this.cause = error.cause;
274
+ if (Error.captureStackTrace) {
275
+ Error.captureStackTrace(this, this.constructor);
276
+ }
277
+ }
278
+ toString() {
279
+ let str = `${this.name} [${this.code}] ${this.severity}: ${this.message}`;
280
+ str += `
281
+ Category: ${this.category}`;
282
+ str += `
283
+ HTTP Status: ${this.httpStatus}`;
284
+ if (this.context) {
285
+ str += `
286
+ Context: ${JSON.stringify(this.context, null, 2)}`;
287
+ }
288
+ if (this.metadata) {
289
+ str += `
290
+ Metadata: ${JSON.stringify(this.metadata, null, 2)}`;
291
+ }
292
+ if (this.stack) {
293
+ str += `
294
+ ${this.stack}`;
295
+ }
296
+ return str;
297
+ }
298
+ toJSON() {
299
+ return {
300
+ name: this.name,
301
+ code: this.code,
302
+ message: this.message,
303
+ category: this.category,
304
+ severity: this.severity,
305
+ httpStatus: this.httpStatus,
306
+ metadata: this.metadata,
307
+ context: this.context,
308
+ stack: this.stack
309
+ };
310
+ }
311
+ static isError(error) {
312
+ return error instanceof SilgiError;
313
+ }
314
+ static from(error) {
315
+ if (error instanceof SilgiError) {
316
+ return error;
317
+ }
318
+ return ErrorFactory.internalError(
319
+ error instanceof Error ? error.message : String(error),
320
+ error instanceof Error ? error : void 0
321
+ );
322
+ }
323
+ }
324
+ function isBaseError(error) {
325
+ return typeof error === "object" && error !== null && "code" in error && "message" in error && "category" in error && "severity" in error && "httpStatus" in error;
326
+ }
327
+
328
+ function parseURI(uri, uris) {
329
+ if (!uri) {
330
+ throw ErrorFactory.create({
331
+ message: "URI cannot be empty",
332
+ httpStatus: HttpStatus.BAD_REQUEST,
333
+ context: { uri }
334
+ });
335
+ }
336
+ if (!uris) {
337
+ throw ErrorFactory.create({
338
+ message: "URIs configuration is not provided",
339
+ httpStatus: HttpStatus.INTERNAL_SERVER_ERROR,
340
+ context: { uri }
341
+ });
342
+ }
343
+ const cleanUri = uri.replace(/^\/*(srn\/)?/, "").replace(/\/*$/, "");
344
+ const [path, queryString] = cleanUri.split("?");
345
+ const parts = path.split("/");
346
+ const query = queryString ? Object.fromEntries(
347
+ queryString.split("&").map((param) => param.split("="))
348
+ ) : void 0;
349
+ const method = query?.method ? query?.method.toLowerCase() : void 0;
350
+ const namespaceName = parts[0];
351
+ const serviceName = parts[1];
352
+ const methodName = method || parts[2];
353
+ const actionName = method ? parts[2] : parts[3];
354
+ if (!namespaceName || !serviceName || !methodName || !actionName) {
355
+ throw ErrorFactory.create({
356
+ message: "Invalid URI format: Insufficient path segments",
357
+ httpStatus: HttpStatus.BAD_REQUEST,
358
+ context: {
359
+ uri,
360
+ cleanUri,
361
+ partsLength: parts.length,
362
+ method,
363
+ namespaceName,
364
+ serviceName,
365
+ methodName,
366
+ actionName
367
+ }
368
+ });
369
+ }
370
+ const baseUri = `${namespaceName}/${serviceName}/${methodName}/${actionName}`;
371
+ const paramStartIndex = method ? 3 : 4;
372
+ const parameters = parts.slice(paramStartIndex);
373
+ const normalizedUri = method ? `${namespaceName}/${serviceName}/${method}/${actionName}${parameters.length ? `/${parameters.join("/")}` : ""}` : cleanUri;
374
+ const template = uris[baseUri];
375
+ if (template === void 0) {
376
+ throw ErrorFactory.create({
377
+ message: "No route found for URI",
378
+ httpStatus: HttpStatus.NOT_FOUND,
379
+ context: {
380
+ uri,
381
+ baseUri
382
+ }
383
+ });
384
+ }
385
+ if (template === "") {
386
+ if (parameters.length > 0) {
387
+ throw ErrorFactory.create({
388
+ message: "No parameters expected for this route",
389
+ httpStatus: HttpStatus.BAD_REQUEST,
390
+ context: {
391
+ uri,
392
+ baseUri,
393
+ extraParams: parameters
394
+ }
395
+ });
396
+ }
397
+ return {
398
+ namespaceName,
399
+ serviceName,
400
+ methodName,
401
+ actionName,
402
+ raw: normalizedUri,
403
+ parts: [namespaceName, serviceName, methodName, actionName],
404
+ routerParams: {},
405
+ query: method ? void 0 : query,
406
+ uri: baseUri
407
+ };
408
+ }
409
+ const routeTemplate = typeof template === "string" ? template : template.pattern;
410
+ const validators = typeof template === "string" ? void 0 : template.validators;
411
+ const routerParams = {};
412
+ const templateParts = routeTemplate.split("/").filter(Boolean);
413
+ const paramValues = parameters;
414
+ let valueIndex = 0;
415
+ templateParts.forEach((part) => {
416
+ if (part.startsWith(":")) {
417
+ const paramName = part.substring(1);
418
+ const paramValue = paramValues[valueIndex];
419
+ if (validators?.[paramName] && paramValue) {
420
+ if (!validators[paramName](paramValue)) {
421
+ throw ErrorFactory.create({
422
+ message: "Invalid value for parameter",
423
+ httpStatus: HttpStatus.UNPROCESSABLE_ENTITY,
424
+ context: {
425
+ uri,
426
+ paramName,
427
+ paramValue,
428
+ validatorName: paramName
429
+ }
430
+ });
431
+ }
432
+ }
433
+ routerParams[paramName] = paramValue || void 0;
434
+ valueIndex++;
435
+ } else if (part && part === paramValues[valueIndex]) {
436
+ valueIndex++;
437
+ }
438
+ });
439
+ return {
440
+ namespaceName,
441
+ serviceName,
442
+ methodName,
443
+ actionName,
444
+ raw: normalizedUri,
445
+ parts: [namespaceName, serviceName, methodName, actionName],
446
+ routerParams,
447
+ query: method ? void 0 : query,
448
+ uri: baseUri
449
+ };
450
+ }
451
+
452
+ async function findAction(silgi, uri) {
453
+ const { parts } = parseURI(uri, silgi.uris);
454
+ let result = silgi.services;
455
+ for (const part of parts) {
456
+ if (result && Object.prototype.hasOwnProperty.call(result, part)) {
457
+ result = Object.assign({}, result[part]);
458
+ } else {
459
+ console.error("Property not found:", part);
460
+ break;
461
+ }
462
+ }
463
+ return result;
464
+ }
465
+ async function scanAction(silgi) {
466
+ for (const [key, _value] of Object.entries(silgi.uris)) {
467
+ const segments = key.split("/").filter(Boolean);
468
+ if (segments.length !== 4) {
469
+ console.error(`Invalid URI format for key "${key}". URI must have exactly 4 segments in format: namespace/service/method/action`);
470
+ continue;
471
+ }
472
+ const [namespace, service, method, action] = segments;
473
+ if (!namespace || !service || !method || !action) {
474
+ console.error(`Invalid URI segments for key "${key}". All segments must be non-empty`);
475
+ continue;
476
+ }
477
+ const handler = await findAction(silgi, key);
478
+ silgi.scannedHandlers.set(key, handler);
479
+ }
480
+ }
481
+
482
+ async function createStorage(silgi) {
483
+ const storage = createStorage$1();
484
+ const mounts = klona({
485
+ ...silgi.options.storage,
486
+ ...silgi.options.devStorage
487
+ });
488
+ for (const [path, opts] of Object.entries(mounts)) {
489
+ if (opts.driver) {
490
+ const driver = await import(builtinDrivers[opts.driver] || opts.driver).then((r) => r.default || r);
491
+ storage.mount("/memory:cache", memoryDriver());
492
+ storage.mount(path, driver(opts));
493
+ } else {
494
+ silgi.logger.warn(`No \`driver\` set for storage mount point "${path}".`);
495
+ }
496
+ }
497
+ return storage;
498
+ }
499
+ function useSilgiStorage(base = "/memory:cache") {
500
+ const silgi = useSilgi();
501
+ return base ? prefixStorage(silgi.storage, base) : silgi.storage;
502
+ }
503
+ async function generateStorageKey(params) {
504
+ const {
505
+ operation,
506
+ input,
507
+ keyGenerator,
508
+ requestId,
509
+ storageOptions
510
+ } = params;
511
+ const cacheScopePrefix = storageOptions?.scope === "request" ? "req" : "global";
512
+ const parts = [
513
+ cacheScopePrefix,
514
+ // Always include scope prefix first
515
+ operation.namespaceName,
516
+ operation.serviceName,
517
+ operation.methodName
518
+ ].filter(Boolean);
519
+ if (storageOptions?.scope === "request") {
520
+ if (!requestId) {
521
+ throw ErrorFactory.create({
522
+ code: HttpStatus.BAD_REQUEST,
523
+ message: "Request ID is required for request-scoped cache",
524
+ context: {
525
+ requestId,
526
+ operation,
527
+ input,
528
+ storageOptions,
529
+ keyGenerator
530
+ }
531
+ });
532
+ }
533
+ parts.push(requestId);
534
+ }
535
+ if (keyGenerator) {
536
+ const customKey = await Promise.resolve(keyGenerator(input));
537
+ parts.push(customKey);
538
+ } else {
539
+ parts.push(typeof input === "object" ? JSON.stringify(input) : String(input));
540
+ }
541
+ return Buffer.from(parts.join(":")).toString("base64");
542
+ }
543
+
544
+ async function runSilgiPlugins(silgi) {
545
+ for (const plugin of silgi.plugins) {
546
+ try {
547
+ await plugin(silgi);
548
+ } catch (error) {
549
+ silgi.captureError(error, { tags: ["plugin"] });
550
+ throw error;
551
+ }
552
+ }
553
+ }
554
+ async function createSilgi(config) {
555
+ const hooks = createHooks();
556
+ await applyDefaults(SilgiConfigSchema, config.options);
557
+ const silgi = {
558
+ schemas: config.schemas,
559
+ services: config.services ?? {},
560
+ shared: config.shared ?? void 0,
561
+ uris: config.uris ?? {},
562
+ modulesURIs: config.modulesURIs ?? {},
563
+ scannedHandlers: /* @__PURE__ */ new Map(),
564
+ plugins: config.plugins ?? [],
565
+ framework: config.framework ?? void 0,
566
+ storage: config.storage ?? void 0,
567
+ options: config.options,
568
+ hooks,
569
+ callHook: hooks.callHook,
570
+ addHooks: hooks.addHooks,
571
+ hook: hooks.hook,
572
+ ready: () => {
573
+ return hooks.callHook("ready", silgi);
574
+ },
575
+ close: () => hooks.callHook("close", silgi),
576
+ logger: createConsola(defu(config.options.consolaOptions, {
577
+ tag: "silgi"
578
+ })).withTag("silgi"),
579
+ captureError: (error, context = {}) => {
580
+ const promise = hooks.callHookParallel("error", error, context).catch((error_) => {
581
+ console.error("Error while capturing another error", error_);
582
+ });
583
+ if (context.event && isEvent(context.event)) {
584
+ const errors = context.event.context.nitro?.errors;
585
+ if (errors) {
586
+ errors.push({ error, context });
587
+ }
588
+ if (context.event.waitUntil) {
589
+ context.event.waitUntil(promise);
590
+ }
591
+ }
592
+ }
593
+ };
594
+ await runSilgiPlugins(silgi);
595
+ await scanAction(silgi);
596
+ if (!silgi.storage) {
597
+ silgi.storage = await createStorage(silgi);
598
+ }
599
+ silgi.shared.storage = (...data) => {
600
+ return useSilgiStorage(...data);
601
+ };
602
+ if (silgiCtx.tryUse()) {
603
+ silgiCtx.unset();
604
+ silgiCtx.set(silgi);
605
+ } else {
606
+ silgiCtx.set(silgi);
607
+ silgi.hook("close", () => silgiCtx.unset());
608
+ }
609
+ silgi.logger.info("Silgi installed");
610
+ hooks.hookOnce("close", async () => {
611
+ hooks.removeAllHooks();
612
+ await silgi.storage.dispose();
613
+ });
614
+ return silgi;
615
+ }
616
+
617
+ function createSilgiFetch(options, localFetch) {
618
+ return (url, opts) => {
619
+ const finalOpts = {
620
+ ...typeof options === "function" ? options(opts) : options,
621
+ ...opts,
622
+ method: opts.method || "get"
623
+ };
624
+ const $fetch = getFetch(url, finalOpts, localFetch);
625
+ return $fetch(fillPath(url, opts.params), finalOpts);
626
+ };
627
+ }
628
+ function getFetch(url, opts, localFetch) {
629
+ if (import.meta.server && localFetch) {
630
+ const isLocalFetch = url[0] === "/" && (!opts.baseURL || opts.baseURL[0] === "/");
631
+ if (isLocalFetch)
632
+ return localFetch;
633
+ }
634
+ return globalThis.$fetch;
635
+ }
636
+ function fillPath(path, params) {
637
+ if (!params) {
638
+ if (path.includes(":"))
639
+ throw new Error("Parametreler dogru kullanmal\u0131s\u0131n\u0131z");
640
+ return path;
641
+ }
642
+ if (!path.includes(":"))
643
+ throw new Error("Path parametler : ile belirtilmelidir");
644
+ let result = path;
645
+ for (const [key, value] of Object.entries(params)) {
646
+ result = result.replace(`:${key}`, value);
647
+ }
648
+ return result;
649
+ }
650
+
651
+ class SchemaParser {
652
+ options = {
653
+ debug: false
654
+ };
655
+ /**
656
+ *
657
+ */
658
+ constructor(options) {
659
+ this.options = {
660
+ ...this.options,
661
+ ...options
662
+ };
663
+ }
664
+ parseExports(content, filePath) {
665
+ const ast = parseSync(content, { sourceType: "module", sourceFilename: filePath });
666
+ if (this.options.debug)
667
+ writeFileSync(`${filePath}.ast.json`, JSON.stringify(ast.program, null, 2));
668
+ return {
669
+ exportVariables: (search, path) => this.parseTypeDeclarations(ast, search, path),
670
+ parseInterfaceDeclarations: (search, path) => this.parseInterfaceDeclarations(ast, search, path)
671
+ // parsePlugin: (path: string) => this.parsePlugin(ast, path),
672
+ };
673
+ }
674
+ parseVariableDeclaration(ast) {
675
+ return ast.program.body.filter((i) => i.type === "ExportNamedDeclaration").filter((i) => i.declaration?.type === "VariableDeclaration");
676
+ }
677
+ parseTSInterfaceDeclaration(ast) {
678
+ return ast.program.body.filter((i) => i.type === "ExportNamedDeclaration").filter((i) => i.declaration?.type === "TSInterfaceDeclaration");
679
+ }
680
+ parseTypeDeclarations(ast, find = "", path = "") {
681
+ const data = [];
682
+ for (const item of this.parseVariableDeclaration(ast)) {
683
+ for (const declaration of item.declaration.declarations) {
684
+ if (declaration.init?.callee?.name === find) {
685
+ const options = {};
686
+ if (declaration.init.arguments) {
687
+ for (const argument of declaration.init.arguments) {
688
+ for (const propertie of argument.properties) {
689
+ if (propertie.key.name === "name")
690
+ options.pluginName = propertie.value.value;
691
+ }
692
+ }
693
+ }
694
+ for (const key in declaration.init.properties) {
695
+ const property = declaration.init.properties[key];
696
+ if (property.type === "ObjectProperty") {
697
+ if (property.key.name === "options") {
698
+ for (const key2 in property.value.properties) {
699
+ const option = property.value.properties[key2];
700
+ if (option.type === "ObjectProperty") {
701
+ options[option.key.name] = option.value.value;
702
+ }
703
+ }
704
+ }
705
+ }
706
+ }
707
+ options.type = false;
708
+ data.push({
709
+ exportName: declaration.id.name,
710
+ options,
711
+ // object: declaration.init,
712
+ path
713
+ });
714
+ }
715
+ }
716
+ }
717
+ return data;
718
+ }
719
+ parseInterfaceDeclarations(ast, find = "", path = "") {
720
+ const data = [];
721
+ for (const item of this.parseTSInterfaceDeclaration(ast)) {
722
+ if (!item?.declaration?.extends)
723
+ continue;
724
+ for (const declaration of item?.declaration?.extends) {
725
+ if (declaration.expression.name === find) {
726
+ const options = {};
727
+ options.type = true;
728
+ data.push({
729
+ exportName: item.declaration.id.name,
730
+ options,
731
+ // object: declaration.init,
732
+ path
733
+ });
734
+ }
735
+ }
736
+ }
737
+ return data;
738
+ }
739
+ // private parsePlugin(ast: any, path: string = '') {
740
+ // const data = {
741
+ // export: [],
742
+ // name: '',
743
+ // path: '',
744
+ // } as DataTypePlugin
745
+ // for (const item of this.parseVariableDeclaration(ast)) {
746
+ // for (const declaration of item.declaration.declarations) {
747
+ // if (declaration.init.callee?.name === 'defineSilgiModule') {
748
+ // if (declaration.init.arguments) {
749
+ // for (const argument of declaration.init.arguments) {
750
+ // for (const propertie of argument.properties) {
751
+ // if (propertie.key.name === 'name')
752
+ // data.name = propertie.value.value
753
+ // }
754
+ // }
755
+ // }
756
+ // data.export.push({
757
+ // name: data.name,
758
+ // as: camelCase(`${data.name}DefineSilgiModule`),
759
+ // type: false,
760
+ // })
761
+ // }
762
+ // }
763
+ // }
764
+ // for (const item of this.parseTSInterfaceDeclaration(ast)) {
765
+ // if (!item?.declaration?.extends)
766
+ // continue
767
+ // for (const declaration of item?.declaration?.extends) {
768
+ // if (declaration.expression.name === 'ModuleOptions') {
769
+ // data.export.push({
770
+ // name: item.declaration.id.name,
771
+ // as: camelCase(`${data.name}ModuleOptions`),
772
+ // type: true,
773
+ // })
774
+ // }
775
+ // // TODO add other plugins
776
+ // }
777
+ // }
778
+ // data.path = path
779
+ // return data
780
+ // }
781
+ }
782
+
783
+ function silgi(event) {
784
+ return {
785
+ execute: (uriString, input) => {
786
+ return execute(uriString, input, event);
787
+ }
788
+ };
789
+ }
790
+ async function execute(uriString, input, event) {
791
+ const silgiCtx = useSilgi();
792
+ if (event) {
793
+ await silgiCtx.callHook("event:before", event);
794
+ }
795
+ let success = false;
796
+ let cached = false;
797
+ let result;
798
+ try {
799
+ const operation = parseURI(uriString, silgiCtx.uris);
800
+ if (!operation) {
801
+ throw ErrorFactory.create({ message: "Invalid URI", httpStatus: HttpStatus.BAD_REQUEST });
802
+ }
803
+ const handler = silgiCtx.scannedHandlers.get(operation.uri);
804
+ if (!handler) {
805
+ throw ErrorFactory.create({
806
+ message: "Action not found",
807
+ httpStatus: HttpStatus.NOT_FOUND,
808
+ context: {
809
+ uri: uriString
810
+ }
811
+ });
812
+ }
813
+ await silgiCtx.callHook("action:before", {
814
+ operation,
815
+ input,
816
+ event,
817
+ modules: handler.modules,
818
+ result
819
+ });
820
+ const cacheData = await cacheExecute(input, operation, handler, event);
821
+ if (cacheData?.success) {
822
+ result = cacheData.data;
823
+ success = cacheData.success;
824
+ cached = cacheData.cached;
825
+ } else {
826
+ const router = {
827
+ params: operation.routerParams,
828
+ query: operation.query
829
+ };
830
+ silgiCtx.shared.silgi = (_event) => silgi(_event || event);
831
+ result = await handler?.handler(router, input, silgiCtx.shared, event);
832
+ success = true;
833
+ }
834
+ await silgiCtx.callHook("action:after", {
835
+ operation,
836
+ input,
837
+ event,
838
+ result,
839
+ success,
840
+ modules: handler.modules
841
+ });
842
+ if (!cached) {
843
+ if (success && cacheData?.cachedKey && handler.storage) {
844
+ await useSilgiStorage(handler.storage.base).setItem(cacheData.cachedKey, result, handler.storage.options);
845
+ }
846
+ }
847
+ return result;
848
+ } catch (err) {
849
+ await silgiCtx.callHook("action:error", {
850
+ input,
851
+ event,
852
+ error: err instanceof Error ? err : new Error(String(err)),
853
+ timestamp: Date.now()
854
+ });
855
+ silgiCtx.captureError(SilgiError.from(err), {
856
+ event,
857
+ tags: ["execute"]
858
+ });
859
+ throw err;
860
+ }
861
+ }
862
+ async function cacheExecute(input, operation, handler, event) {
863
+ if (!handler.storage)
864
+ return;
865
+ const cacheKey = handler.storage ? await generateStorageKey({
866
+ operation,
867
+ input,
868
+ keyGenerator: handler.storage.key,
869
+ storageOptions: handler.storage,
870
+ requestId: event?.requestId
871
+ }) : null;
872
+ if (cacheKey) {
873
+ const cachedResult = await useSilgiStorage(handler.storage.base).getItem(cacheKey);
874
+ if (cachedResult !== null) {
875
+ return {
876
+ success: true,
877
+ data: normalizeResult(cachedResult),
878
+ cached: true,
879
+ cachedKey: cacheKey
880
+ };
881
+ }
882
+ }
883
+ return {
884
+ success: false,
885
+ data: null,
886
+ cached: false,
887
+ cachedKey: cacheKey
888
+ };
889
+ }
890
+
891
+ function merge(items, maxLevel = 4, currentLevel = 3) {
892
+ const arrayItems = Array.isArray(items) ? items : [items];
893
+ return arrayItems.reduce((acc, item) => {
894
+ Object.keys(item).forEach((key) => {
895
+ if (typeof item[key] === "object" && item[key] !== null && currentLevel < maxLevel) {
896
+ acc[key] = acc[key] || {};
897
+ acc[key] = merge([acc[key], item[key]], maxLevel, currentLevel + 1);
898
+ } else {
899
+ acc[key] = item[key];
900
+ }
901
+ });
902
+ return acc;
903
+ }, {});
904
+ }
905
+ function mergeSchemas(typesOrArray) {
906
+ return merge(typesOrArray);
907
+ }
908
+ function mergeServices(servicesOrArray) {
909
+ return merge(servicesOrArray);
910
+ }
911
+ function mergeShared(sharedOrArray) {
912
+ return merge(sharedOrArray, 1, 1);
913
+ }
914
+
915
+ function getEvent(event) {
916
+ return event.event || event || {};
917
+ }
918
+
919
+ function createSchema(silgiType) {
920
+ return silgiType;
921
+ }
922
+
923
+ function createService(variables) {
924
+ return variables;
925
+ }
926
+
927
+ function createShared(shared) {
928
+ return shared;
929
+ }
930
+
931
+ const silgiCLICtx = getContext("SilgiCLI");
932
+ function useSilgiCLI() {
933
+ const instance = silgiCLICtx.tryUse();
934
+ if (!instance) {
935
+ throw new Error("Silgi instance is unavailable!");
936
+ }
937
+ return instance;
938
+ }
939
+ function tryUseSilgiCLI() {
940
+ return silgiCLICtx.tryUse();
941
+ }
942
+
943
+ export { ErrorCategory, ErrorFactory, ErrorSeverity, HttpStatus, SchemaParser, SilgiError, createSchema, createService, createShared, createSilgi, createSilgiFetch, createStorage, getEvent, isBaseError, mergeSchemas, mergeServices, mergeShared, parseURI, silgi, silgiCLICtx, silgiCtx, tryUseSilgi, tryUseSilgiCLI, useSilgi, useSilgiCLI, useSilgiStorage };