silgi 0.0.14 → 0.1.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.
package/dist/index.mjs CHANGED
@@ -1,7 +1,465 @@
1
- export { c as createSilgi, d as defineService, a as defineSilgiPlugin, s as silgiCtx, e as useHook, u as useShared, b as useSilgi } from './shared/silgi.BMCYk2cR.mjs';
2
- import 'consola';
3
- import 'hookable';
4
- import 'node:buffer';
5
- import 'node:fs';
6
- import 'node:path';
1
+ import { createConsola } from 'consola';
2
+ import defu, { defu as defu$1 } from 'defu';
3
+ import { createHooks } from 'hookable';
4
+ import { applyDefaults } from 'untyped';
5
+ import { u as useSilgi, n as normalizeResult, S as SilgiConfigSchema, s as silgiCtx, t as tryUseSilgi } from './shared/silgi.wK7ZsagJ.mjs';
6
+ export { r as relativeWithDot, a as useHook, b as useShared } from './shared/silgi.wK7ZsagJ.mjs';
7
+ import satisfies from 'semver/functions/satisfies.js';
8
+ import { l as loadSilgiModuleInstance, p as parseURI, S as SilgiError, u as useStorage, a as SilgiErrorCode, g as generateStorageKey, s as scanHandler, c as createStorage } from './shared/silgi.CbXGs1ur.mjs';
9
+ export { b as createResolver, d as generateURI } from './shared/silgi.CbXGs1ur.mjs';
10
+ import { defineEventHandler, getQuery, readBody } from 'h3';
7
11
  import 'unctx';
12
+ import 'pathe';
13
+ import 'std-env';
14
+ import 'node:fs';
15
+ import 'node:buffer';
16
+ import 'klona';
17
+ import 'unstorage';
18
+ import 'unstorage/drivers/memory';
19
+ import 'node:url';
20
+ import 'mlly';
21
+ import 'pathe/utils';
22
+
23
+ const SEMANTIC_VERSION_RE = /-\d+\.[0-9a-f]+/;
24
+ function normalizeSemanticVersion(version) {
25
+ return version.replace(SEMANTIC_VERSION_RE, "");
26
+ }
27
+ const SILGI_VERSION_RE = /^v/g;
28
+ function getSilgiVersion(silgi = useSilgi()) {
29
+ const rawVersion = silgi?._version || silgi?.version || silgi?.constructor?.version;
30
+ if (typeof rawVersion !== "string") {
31
+ throw new TypeError("Cannot determine silgi version! Is current instance passed?");
32
+ }
33
+ return rawVersion.replace(SILGI_VERSION_RE, "");
34
+ }
35
+ async function checkSilgiCompatibility(constraints, silgi = useSilgi()) {
36
+ const issues = [];
37
+ if (constraints.silgi) {
38
+ const silgiVersion = getSilgiVersion(silgi);
39
+ if (!satisfies(normalizeSemanticVersion(silgiVersion), constraints.silgi, { includePrerelease: true })) {
40
+ issues.push({
41
+ name: "silgi",
42
+ message: `Silgi version \`${constraints.silgi}\` is required but currently using \`${silgiVersion}\``
43
+ });
44
+ }
45
+ }
46
+ await silgi.callHook("kit:compatibility", constraints, issues);
47
+ issues.toString = () => issues.map((issue) => ` - [${issue.name}] ${issue.message}`).join("\n");
48
+ return issues;
49
+ }
50
+ function hasInstalledModule(moduleKey, silgi = useSilgi()) {
51
+ const find = silgi.options._installedModules.find(({ meta }) => meta.configKey === moduleKey);
52
+ return find?.active ?? false;
53
+ }
54
+
55
+ async function installModules(silgi) {
56
+ for (const module of Object.keys(silgi._initializedModules)) {
57
+ if (hasInstalledModule(module)) {
58
+ silgi.logger.info(`Module ${module} installeddddd`);
59
+ }
60
+ try {
61
+ const silgiModule = silgi._initializedModules[module];
62
+ await installModule(silgiModule, silgi);
63
+ } catch (err) {
64
+ silgi.logger.error(err);
65
+ }
66
+ }
67
+ }
68
+ async function installModule(moduleToInstall, silgi = useSilgi(), inlineOptions) {
69
+ const { silgiModule } = await loadSilgiModuleInstance(moduleToInstall);
70
+ const res = await silgiModule({}, silgi, false) ?? {};
71
+ if (res === false) {
72
+ return false;
73
+ }
74
+ const metaData = await silgiModule.getMeta?.();
75
+ const installedModule = silgi.options._installedModules.find((m) => m.meta.configKey === metaData?.configKey);
76
+ if (installedModule) {
77
+ installedModule.active = true;
78
+ } else {
79
+ throw new Error(`Module ${metaData?.name} not found`);
80
+ }
81
+ }
82
+ function getModule(configKey, silgi = useSilgi()) {
83
+ if (silgi._initializedModules[configKey]) {
84
+ return true;
85
+ }
86
+ return false;
87
+ }
88
+
89
+ function silgi(event) {
90
+ return {
91
+ execute: (uriString, input) => {
92
+ return execute(uriString, input, event);
93
+ }
94
+ };
95
+ }
96
+ async function execute(uriString, input, event) {
97
+ const silgiCtx = useSilgi();
98
+ if (event) {
99
+ silgiCtx.callHook("event:before", event);
100
+ }
101
+ let success = false;
102
+ let cached = false;
103
+ let error;
104
+ let result;
105
+ let operation;
106
+ try {
107
+ operation = parseURI(uriString);
108
+ } catch {
109
+ throw new SilgiError({
110
+ code: "INVALID_URI",
111
+ message: `Invalid URI: ${uriString}`
112
+ });
113
+ }
114
+ if (!operation) {
115
+ throw new SilgiError({
116
+ code: "INVALID_URI",
117
+ message: `Invalid URI: ${uriString}`
118
+ });
119
+ }
120
+ const hookContext = {
121
+ operation,
122
+ input,
123
+ event
124
+ };
125
+ try {
126
+ await silgiCtx.callHook("method:before", {
127
+ operation,
128
+ input,
129
+ event
130
+ });
131
+ const handler = silgiCtx.scannedHandlers.get(operation.raw);
132
+ if (!handler) {
133
+ return {
134
+ success: false,
135
+ error: {
136
+ code: "METHOD_NOT_FOUND",
137
+ message: `Method ${String(operation.methodName)} not found`
138
+ }
139
+ };
140
+ }
141
+ if (event)
142
+ await silgiCtx.callHook("event:before", event);
143
+ const cacheData = await cacheExecute(operation.raw, input, operation, handler, event);
144
+ await callModules(operation, handler, input, result, event);
145
+ if (cacheData?.success) {
146
+ result = cacheData.data;
147
+ success = cacheData.success;
148
+ cached = cacheData.cached;
149
+ } else {
150
+ silgiCtx.shared.silgi = (_event) => silgi(_event || event);
151
+ result = await handler?.handler(input, silgiCtx.shared, event);
152
+ success = true;
153
+ }
154
+ await silgiCtx.callHook("method:after", {
155
+ operation,
156
+ input,
157
+ event,
158
+ result,
159
+ success
160
+ });
161
+ if (!cached) {
162
+ if (success && cacheData?.cachedKey && handler.storage) {
163
+ await useStorage(handler.storage.base).setItem(cacheData.cachedKey, result, handler.storage.options);
164
+ }
165
+ }
166
+ return { success: true, data: normalizeResult(result), cached };
167
+ } catch (err) {
168
+ error = err instanceof Error ? err : new Error("Unknown error");
169
+ if (error instanceof SilgiError) {
170
+ return {
171
+ success: false,
172
+ error: {
173
+ code: error.code,
174
+ message: error.message,
175
+ details: error.details
176
+ }
177
+ };
178
+ }
179
+ await silgiCtx.callHook("method:error", {
180
+ ...hookContext,
181
+ error,
182
+ timestamp: Date.now()
183
+ });
184
+ return {
185
+ success: false,
186
+ error: {
187
+ code: SilgiErrorCode.EXECUTION_ERROR,
188
+ message: error.message || String(error)
189
+ }
190
+ };
191
+ }
192
+ }
193
+ async function callModules(operation, handler, input, result, event) {
194
+ const silgi2 = useSilgi();
195
+ if (!handler.modules)
196
+ return;
197
+ for (const [moduleKey, config] of Object.entries(handler.modules)) {
198
+ const pluginConfig = config;
199
+ if (moduleKey) {
200
+ const module = getModule(moduleKey, silgi2);
201
+ if (module) {
202
+ await silgi2.callHook("module:before:excute", {
203
+ operation,
204
+ input,
205
+ event,
206
+ modules: handler.modules,
207
+ config: pluginConfig,
208
+ result
209
+ });
210
+ }
211
+ }
212
+ }
213
+ }
214
+ async function cacheExecute(uriString, input, operation, handler, event) {
215
+ if (!handler.storage)
216
+ return;
217
+ const cacheKey = handler.storage ? await generateStorageKey({
218
+ operation,
219
+ input,
220
+ keyGenerator: handler.storage.key,
221
+ storageOptions: handler.storage,
222
+ requestId: event?.requestId
223
+ }) : null;
224
+ if (cacheKey) {
225
+ const cachedResult = await useStorage(handler.storage.base).getItem(cacheKey);
226
+ if (cachedResult !== null) {
227
+ return {
228
+ success: true,
229
+ data: normalizeResult(cachedResult),
230
+ cached: true,
231
+ cachedKey: cacheKey
232
+ };
233
+ }
234
+ }
235
+ return {
236
+ success: false,
237
+ data: null,
238
+ cached: false,
239
+ cachedKey: cacheKey
240
+ };
241
+ }
242
+
243
+ class SilgiHelper {
244
+ setEvent(key, value) {
245
+ const silgi2 = useSilgi();
246
+ silgi2.options._eventContext ??= /* @__PURE__ */ new Map();
247
+ silgi2.options._eventContext.set(key, value);
248
+ }
249
+ getEvent(key) {
250
+ const silgi2 = useSilgi();
251
+ return silgi2.options._eventContext?.get(key);
252
+ }
253
+ async addH3App(router) {
254
+ const silgi2 = useSilgi();
255
+ silgi2.options.h3Router = router;
256
+ await silgi2.callHook("h3:app:setup", router);
257
+ }
258
+ async addNitroApp(nitro) {
259
+ const ctx = useSilgi();
260
+ ctx.options.nitro = nitro;
261
+ nitro.router.use("/srn/**", defineEventHandler({
262
+ handler: async (event) => {
263
+ const ctx2 = useSilgi();
264
+ if (ctx2.options.environment === "nitrojs" || ctx2.options.environment === "h3") {
265
+ const silgiConnect = silgi(event);
266
+ const query = getQuery(event);
267
+ const body = await readBody(event).catch(() => {
268
+ });
269
+ let newPath = event.path;
270
+ if (event.path.includes("?")) {
271
+ newPath = `${event.path}&method=${event.method}`;
272
+ } else {
273
+ newPath = `${event.path}?method=${event.method}`;
274
+ }
275
+ const data = await silgiConnect.execute(newPath, {
276
+ ...query,
277
+ ...body
278
+ });
279
+ return {
280
+ path: event.path,
281
+ method: event.method,
282
+ body,
283
+ query,
284
+ ...data
285
+ };
286
+ }
287
+ }
288
+ }));
289
+ await ctx.callHook("h3:app:setup", nitro.router);
290
+ }
291
+ /**
292
+ * [...router.ts] tum router tarayan ve ona gore isteklere yonlendiren alan.
293
+ */
294
+ // methods: ["delete", "get", "head", "options", "patch", "post", "put"]
295
+ async handler(_request) {
296
+ }
297
+ }
298
+
299
+ const silgiHooks = [
300
+ "close",
301
+ "ready",
302
+ "event:before",
303
+ "app:setup:start",
304
+ /* plugin hooks */
305
+ "module:register:after",
306
+ "module:register:before",
307
+ "module:setup:finish",
308
+ "module:error",
309
+ "module:before:excute",
310
+ "module:after:excute",
311
+ /* method hooks */
312
+ "method:after",
313
+ "method:before",
314
+ "method:error",
315
+ "method:finally",
316
+ "h3:app:setup",
317
+ // Kit
318
+ "kit:compatibility"
319
+ ];
320
+
321
+ const version = "0.0.1";
322
+ async function createSilgi(config) {
323
+ const hooks = createHooks();
324
+ await applyDefaults(SilgiConfigSchema, config.options);
325
+ const silgi = {
326
+ types: config.types,
327
+ _version: version,
328
+ services: config.services,
329
+ shared: config.shared,
330
+ uris: config.uris,
331
+ scannedHandlers: /* @__PURE__ */ new Map(),
332
+ storage: undefined,
333
+ _initializedModules: config._initializedModules,
334
+ options: config.options,
335
+ hooks,
336
+ hooksNames: silgiHooks,
337
+ callHook: hooks.callHook,
338
+ addHooks: hooks.addHooks,
339
+ hook: hooks.hook,
340
+ ready: () => {
341
+ return hooks.callHook("ready", silgi);
342
+ },
343
+ close: () => hooks.callHook("close", silgi),
344
+ logger: createConsola(defu(config.options.consolaOptions, {
345
+ tag: "silgi"
346
+ })).withTag("silgi")
347
+ // TODO: shared, uris, services burada olacak
348
+ };
349
+ await scanHandler(silgi);
350
+ silgi.storage = await createStorage(silgi);
351
+ silgi.shared.storage = (...data) => {
352
+ return useStorage(...data);
353
+ };
354
+ if (silgiCtx.tryUse()) {
355
+ silgiCtx.unset();
356
+ silgiCtx.set(silgi);
357
+ } else {
358
+ silgiCtx.set(silgi);
359
+ silgi.hook("close", () => silgiCtx.unset());
360
+ }
361
+ silgi.options.helper = new SilgiHelper();
362
+ await installModules(silgi);
363
+ silgi.logger.info("Silgi installed");
364
+ hooks.hookOnce("close", async () => {
365
+ hooks.removeAllHooks();
366
+ await silgi.storage.dispose();
367
+ });
368
+ return silgi.options.helper;
369
+ }
370
+
371
+ function defineSilgiModule(definition) {
372
+ if (definition) {
373
+ return _defineSilgiModule(definition);
374
+ }
375
+ return {
376
+ with: (definition2) => _defineSilgiModule(definition2)
377
+ };
378
+ }
379
+ function _defineSilgiModule(definition) {
380
+ if (typeof definition === "function") {
381
+ return _defineSilgiModule({ setup: definition });
382
+ }
383
+ const module = defu$1(definition, { meta: {} });
384
+ module.meta.configKey ||= module.meta.name;
385
+ async function getOptions(inlineOptions, silgi = useSilgi()) {
386
+ const nuxtConfigOptionsKey = module.meta.configKey || module.meta.name;
387
+ const nuxtConfigOptions = nuxtConfigOptionsKey && nuxtConfigOptionsKey in silgi.options ? silgi.options[nuxtConfigOptionsKey] : {};
388
+ const optionsDefaults = module.defaults instanceof Function ? await module.defaults(silgi) : module.defaults ?? {};
389
+ const options = defu$1(inlineOptions, nuxtConfigOptions, optionsDefaults);
390
+ return Promise.resolve(options);
391
+ }
392
+ async function normalizedModule(inlineOptions, silgi = tryUseSilgi(), cli = false) {
393
+ if (!silgi) {
394
+ throw new TypeError("Cannot use module outside of Silgi context");
395
+ }
396
+ const uniqueKey = module.meta.configKey || module.meta.name;
397
+ if (uniqueKey) {
398
+ silgi.options._requiredModules ||= {};
399
+ if (silgi.options._requiredModules[uniqueKey]) {
400
+ return false;
401
+ }
402
+ silgi.options._requiredModules[uniqueKey] = true;
403
+ }
404
+ if (module.meta.compatibility) {
405
+ const issues = await checkSilgiCompatibility(module.meta.compatibility, silgi);
406
+ if (issues.length) {
407
+ silgi.logger.warn(`Module \`${module.meta.name}\` is disabled due to incompatibility issues:
408
+ ${issues.toString()}`);
409
+ return;
410
+ }
411
+ }
412
+ const _options = await getOptions(inlineOptions, silgi);
413
+ if (module.hooks) {
414
+ silgi.hooks.addHooks(module.hooks);
415
+ }
416
+ const start = performance.now();
417
+ const res = cli ? await module.cli?.call(null, _options, silgi) ?? {} : await module.setup?.call(null, _options, silgi) ?? {};
418
+ const perf = performance.now() - start;
419
+ const setupTime = Math.round(perf * 100) / 100;
420
+ if (setupTime > 5e3 && uniqueKey !== "@silgi/telemetry") {
421
+ silgi.logger.warn(`Slow module \`${uniqueKey || "<no name>"}\` took \`${setupTime}ms\` to setup.`);
422
+ } else if (silgi.options.debug) {
423
+ silgi.logger.info(`Module \`${uniqueKey || "<no name>"}\` took \`${setupTime}ms\` to setup.`);
424
+ }
425
+ if (res === false) {
426
+ return false;
427
+ }
428
+ return defu$1(res, {
429
+ timings: {
430
+ setup: setupTime
431
+ }
432
+ });
433
+ }
434
+ normalizedModule.getMeta = () => Promise.resolve(module.meta);
435
+ normalizedModule.getOptions = getOptions;
436
+ normalizedModule.cli = normalizedModule;
437
+ return normalizedModule;
438
+ }
439
+
440
+ function merge(items) {
441
+ return Object.assign({}, ...Array.isArray(items) ? items : [items]);
442
+ }
443
+ function mergeSilgiTypes(typesOrArray) {
444
+ return merge(typesOrArray);
445
+ }
446
+ function mergeServices(servicesOrArray) {
447
+ return merge(servicesOrArray);
448
+ }
449
+ function mergeShared(sharedOrArray) {
450
+ return merge(sharedOrArray);
451
+ }
452
+
453
+ function createService(variables) {
454
+ return variables;
455
+ }
456
+
457
+ function createShared(shared) {
458
+ return shared;
459
+ }
460
+
461
+ function createType(silgiType) {
462
+ return silgiType;
463
+ }
464
+
465
+ export { SilgiError, SilgiHelper, createService, createShared, createSilgi, createType, defineSilgiModule, mergeServices, mergeShared, mergeSilgiTypes, normalizeResult, parseURI, silgi, silgiCtx, tryUseSilgi, useSilgi };