silgi 0.3.12 → 0.4.0

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 (70) hide show
  1. package/README.md +1 -31
  2. package/cli.d.ts +1 -0
  3. package/config.d.ts +1 -0
  4. package/core.d.ts +1 -0
  5. package/dist/_chunks/index.mjs +233 -0
  6. package/dist/cli/compatibility.mjs +42 -0
  7. package/dist/cli/index.mjs +3 -178
  8. package/dist/cli/prepare.mjs +1346 -0
  9. package/dist/config/index.d.mts +5 -0
  10. package/dist/config/index.d.ts +5 -0
  11. package/dist/core/index.d.mts +136 -0
  12. package/dist/core/index.d.ts +136 -0
  13. package/dist/core/index.mjs +1444 -0
  14. package/dist/ecosystem/nitro/index.mjs +21 -10
  15. package/dist/ecosystem/nuxt/module.mjs +4 -6
  16. package/dist/kit/index.d.mts +90 -0
  17. package/dist/kit/index.d.ts +90 -0
  18. package/dist/kit/index.mjs +316 -0
  19. package/dist/meta/index.d.mts +3 -0
  20. package/dist/meta/index.d.ts +3 -0
  21. package/dist/meta/index.mjs +1 -0
  22. package/dist/presets/_all.gen.d.ts +2 -0
  23. package/dist/presets/_all.gen.mjs +8 -0
  24. package/dist/presets/_resolve.d.ts +8 -0
  25. package/dist/presets/_resolve.mjs +58 -0
  26. package/dist/presets/_types.gen.d.ts +5 -0
  27. package/dist/presets/_types.gen.mjs +1 -0
  28. package/dist/presets/h3/preset.d.ts +2 -0
  29. package/dist/presets/h3/preset.mjs +22 -0
  30. package/dist/presets/index.d.mts +1 -0
  31. package/dist/presets/index.d.ts +2 -0
  32. package/dist/presets/index.mjs +1 -0
  33. package/dist/presets/nitro/preset.d.ts +2 -0
  34. package/dist/presets/nitro/preset.mjs +26 -0
  35. package/dist/presets/npmpackage/preset.d.ts +2 -0
  36. package/dist/presets/npmpackage/preset.mjs +23 -0
  37. package/dist/runtime/index.d.ts +1 -0
  38. package/dist/runtime/index.mjs +1 -0
  39. package/dist/runtime/internal/debug.d.ts +2 -0
  40. package/dist/runtime/internal/debug.mjs +5 -0
  41. package/dist/runtime/internal/nitro.d.ts +2 -0
  42. package/dist/runtime/internal/nitro.mjs +45 -0
  43. package/dist/runtime/internal/plugin.d.ts +3 -0
  44. package/dist/runtime/internal/plugin.mjs +4 -0
  45. package/dist/shared/silgi.40ZJYm8F.d.mts +11 -0
  46. package/dist/shared/silgi.40ZJYm8F.d.ts +11 -0
  47. package/dist/shared/{silgi.ClpvycKI.d.mts → silgi.D8h2AAVk.d.ts} +451 -437
  48. package/dist/shared/{silgi.ClpvycKI.d.ts → silgi.DSHNePNA.d.mts} +451 -437
  49. package/dist/types/index.d.mts +42 -0
  50. package/dist/types/index.d.ts +42 -0
  51. package/dist/types/index.mjs +1 -0
  52. package/kit.d.ts +1 -0
  53. package/meta.d.ts +1 -0
  54. package/package.json +89 -39
  55. package/presets.d.ts +1 -0
  56. package/runtime-meta.d.ts +4 -0
  57. package/runtime-meta.mjs +32 -0
  58. package/runtime.d.ts +1 -0
  59. package/types.d.ts +1 -0
  60. package/bin/silgi.mjs +0 -3
  61. package/dist/chunks/generate.mjs +0 -1258
  62. package/dist/cli/config.d.mts +0 -1633
  63. package/dist/cli/config.d.ts +0 -1633
  64. package/dist/index.d.mts +0 -196
  65. package/dist/index.d.ts +0 -196
  66. package/dist/index.mjs +0 -499
  67. package/dist/shared/silgi.b9yhSIGd.mjs +0 -459
  68. package/dist/shared/silgi.mBwNj1W0.mjs +0 -386
  69. /package/dist/{chunks → cli}/init.mjs +0 -0
  70. /package/dist/{cli/config.mjs → config/index.mjs} +0 -0
@@ -1,386 +0,0 @@
1
- import { lstatSync, promises, existsSync } from 'node:fs';
2
- import { isAbsolute, dirname, resolve, normalize, join } from 'pathe';
3
- import { Buffer } from 'node:buffer';
4
- import { klona } from 'klona';
5
- import { createStorage as createStorage$1, builtinDrivers, prefixStorage } from 'unstorage';
6
- import memoryDriver from 'unstorage/drivers/memory';
7
- import { getContext } from 'unctx';
8
- import { fileURLToPath } from 'node:url';
9
- import { resolvePath as resolvePath$1 } from 'mlly';
10
- import { resolveAlias as resolveAlias$1 } from 'pathe/utils';
11
-
12
- const silgiCtx = getContext("silgi");
13
- function useShared() {
14
- const instance = silgiCtx.tryUse();
15
- if (!instance) {
16
- throw new Error("Silgi instance is unavailable!");
17
- }
18
- return instance.options.shared;
19
- }
20
- function useSilgi() {
21
- const instance = silgiCtx.tryUse();
22
- if (!instance) {
23
- throw new Error("Silgi instance is unavailable!");
24
- }
25
- return instance;
26
- }
27
- function useHook() {
28
- const instance = silgiCtx.tryUse();
29
- if (!instance) {
30
- throw new Error("Silgi instance is unavailable!");
31
- }
32
- return instance.hooks.hook;
33
- }
34
- function normalizeResult(result) {
35
- if (Array.isArray(result)) {
36
- return [...result];
37
- }
38
- if (result && typeof result === "object") {
39
- if (Object.keys(result).every((key) => !Number.isNaN(Number(key)))) {
40
- return Object.values(result);
41
- }
42
- return { ...result };
43
- }
44
- return result;
45
- }
46
- function tryUseSilgi() {
47
- return silgiCtx.tryUse();
48
- }
49
-
50
- function getDirectory(p) {
51
- try {
52
- return isAbsolute(p) && lstatSync(p).isFile() ? dirname(p) : p;
53
- } catch {
54
- }
55
- return p;
56
- }
57
- async function loadSilgiModuleInstance(silgiModule) {
58
- if (typeof silgiModule === "string") {
59
- throw new TypeError(`Could not load \`${silgiModule}\`. Is it installed?`);
60
- }
61
- if (typeof silgiModule !== "function") {
62
- throw new TypeError(`Nuxt module should be a function: ${silgiModule}`);
63
- }
64
- return { silgiModule };
65
- }
66
-
67
- var SilgiErrorCode = /* @__PURE__ */ ((SilgiErrorCode2) => {
68
- SilgiErrorCode2["AUTH_UNAUTHORIZED"] = "AUTH_UNAUTHORIZED";
69
- SilgiErrorCode2["AUTH_MISSING_CONTEXT"] = "AUTH_MISSING_CONTEXT";
70
- SilgiErrorCode2["AUTH_INVALID_CONTEXT"] = "AUTH_INVALID_CONTEXT";
71
- SilgiErrorCode2["AUTH_PERMISSION_DENIED"] = "AUTH_PERMISSION_DENIED";
72
- SilgiErrorCode2["PLUGIN_ERROR"] = "PLUGIN_ERROR";
73
- SilgiErrorCode2["METHOD_NOT_FOUND"] = "METHOD_NOT_FOUND";
74
- SilgiErrorCode2["EXECUTION_ERROR"] = "EXECUTION_ERROR";
75
- SilgiErrorCode2["CACHE_ERROR"] = "CACHE_ERROR";
76
- SilgiErrorCode2["PLUGIN_ALREADY_EXISTS"] = "PLUGIN_ALREADY_EXISTS";
77
- SilgiErrorCode2["PLUGIN_NOT_FOUND"] = "PLUGIN_NOT_FOUND";
78
- SilgiErrorCode2["PLUGIN_INIT_ERROR"] = "PLUGIN_INIT_ERROR";
79
- return SilgiErrorCode2;
80
- })(SilgiErrorCode || {});
81
- class SilgiError extends Error {
82
- code;
83
- details;
84
- meta;
85
- timestamp;
86
- cause;
87
- constructor(options) {
88
- super(options.message);
89
- this.name = "SilgiError";
90
- this.code = options.code;
91
- this.details = options.details;
92
- this.meta = options.meta;
93
- this.cause = options.cause;
94
- this.timestamp = Date.now();
95
- if (Error.captureStackTrace) {
96
- Error.captureStackTrace(this, this.constructor);
97
- }
98
- }
99
- // Improve error formatting
100
- toString() {
101
- let str = `${this.name} [${this.code}]: ${this.message}`;
102
- if (this.details) {
103
- str += `
104
- Details: ${JSON.stringify(this.details, null, 2)}`;
105
- }
106
- if (this.meta) {
107
- str += `
108
- Meta: ${JSON.stringify(this.meta, null, 2)}`;
109
- }
110
- if (this.stack) {
111
- str += `
112
- ${this.stack}`;
113
- }
114
- return str;
115
- }
116
- toJSON() {
117
- return {
118
- name: this.name,
119
- code: this.code,
120
- message: this.message,
121
- details: this.details,
122
- meta: this.meta,
123
- timestamp: this.timestamp,
124
- stack: this.stack
125
- };
126
- }
127
- static createFrom(error, code = "UNKNOWN_ERROR") {
128
- if (error instanceof SilgiError) {
129
- return error;
130
- }
131
- return new SilgiError({
132
- code,
133
- message: error instanceof Error ? error.message : String(error),
134
- cause: error instanceof Error ? error : undefined
135
- });
136
- }
137
- static isSilgiError(error) {
138
- return error instanceof SilgiError;
139
- }
140
- }
141
-
142
- function traverseObject(silgi, obj, currentPath = []) {
143
- const uriMap = /* @__PURE__ */ new Map();
144
- function traverse(node, path = []) {
145
- if (!node || typeof node !== "object")
146
- return;
147
- if (path.length === 4) {
148
- const basePath = path.join("/");
149
- let paramString = "";
150
- if (node.router) {
151
- let params = null;
152
- if (node.router?._def?.typeName !== undefined) {
153
- try {
154
- const shape = node.router?.shape?.params?.shape;
155
- params = shape ? Object.keys(shape) : null;
156
- } catch {
157
- params = null;
158
- }
159
- }
160
- if (params?.length) {
161
- paramString = params.map((p) => `:${p}`).join("/");
162
- }
163
- }
164
- uriMap.set(basePath, paramString);
165
- return;
166
- }
167
- for (const key in node) {
168
- if (!["_type", "fields"].includes(key)) {
169
- traverse(node[key], [...path, key]);
170
- }
171
- }
172
- }
173
- traverse(obj, currentPath);
174
- return uriMap;
175
- }
176
- function parseURI(uri, uris) {
177
- if (!uris) {
178
- const silgiCtx = useSilgi();
179
- uris = silgiCtx.uris;
180
- }
181
- uri = uri.replace("/srn", "");
182
- const [cleanPath, queryString] = uri.split("?");
183
- const query = new URLSearchParams(queryString);
184
- const methodQuery = query.get("method")?.toLowerCase();
185
- const parts = cleanPath.split("/").filter(Boolean);
186
- const [namespace, service, methodOrAction, action, ...routerParams] = parts;
187
- let uriKey = `${namespace}/${service}/${methodOrAction}/${action}`;
188
- if (methodQuery) {
189
- uriKey = `${namespace}/${service}/${methodQuery}/${methodOrAction}`;
190
- routerParams.unshift(action);
191
- }
192
- const paramTemplate = uris[uriKey];
193
- const routerParamsData = {};
194
- if (paramTemplate && routerParams.length > 0) {
195
- const paramNames = paramTemplate.split("/").map((p) => p.replace(":", ""));
196
- routerParams.forEach((value, index) => {
197
- if (paramNames[index]) {
198
- routerParamsData[paramNames[index]] = value;
199
- }
200
- });
201
- }
202
- return {
203
- namespaceName: namespace,
204
- serviceName: service,
205
- methodName: methodQuery || methodOrAction,
206
- actionName: methodQuery ? methodOrAction : action,
207
- raw: uri,
208
- parts: [namespace, service, methodQuery || methodOrAction, action],
209
- routerParams: routerParamsData,
210
- query: query.toString() ? Object.fromEntries(query) : undefined,
211
- uri: uriKey
212
- };
213
- }
214
-
215
- async function createStorage(silgi) {
216
- const storage = createStorage$1();
217
- const mounts = klona({
218
- ...silgi.options.storage,
219
- ...silgi.options.devStorage
220
- });
221
- for (const [path, opts] of Object.entries(mounts)) {
222
- if (opts.driver) {
223
- const driver = await import(builtinDrivers[opts.driver] || opts.driver).then((r) => r.default || r);
224
- storage.mount("/memory:cache", memoryDriver());
225
- storage.mount(path, driver(opts));
226
- } else {
227
- silgi.logger.warn(`No \`driver\` set for storage mount point "${path}".`);
228
- }
229
- }
230
- return storage;
231
- }
232
- function useStorage(base = "/memory:cache") {
233
- const silgi = useSilgi();
234
- return base ? prefixStorage(silgi.storage, base) : silgi.storage;
235
- }
236
- async function generateStorageKey(params) {
237
- const {
238
- operation,
239
- input,
240
- keyGenerator,
241
- requestId,
242
- storageOptions
243
- } = params;
244
- const cacheScopePrefix = storageOptions?.scope === "request" ? "req" : "global";
245
- const parts = [
246
- cacheScopePrefix,
247
- // Always include scope prefix first
248
- operation.namespaceName,
249
- operation.serviceName,
250
- operation.methodName
251
- ].filter(Boolean);
252
- if (storageOptions?.scope === "request") {
253
- if (!requestId) {
254
- throw new SilgiError({
255
- code: "CACHE_ERROR",
256
- message: "Request ID is required for request-scoped cache"
257
- });
258
- }
259
- parts.push(requestId);
260
- }
261
- if (keyGenerator) {
262
- const customKey = await Promise.resolve(keyGenerator(input));
263
- parts.push(customKey);
264
- } else {
265
- parts.push(typeof input === "object" ? JSON.stringify(input) : String(input));
266
- }
267
- return Buffer.from(parts.join(":")).toString("base64");
268
- }
269
- async function generateSilgiStorageBaseType(silgi) {
270
- silgi.hook("prepare:schema.ts", async (options) => {
271
- if (silgi.options.storage) {
272
- for (const [key, _value] of Object.entries(silgi.options.storage)) {
273
- options.storeBase.push(key);
274
- }
275
- }
276
- });
277
- }
278
-
279
- async function generateUris(silgi) {
280
- silgi.hook("read:core.ts", async (data) => {
281
- const { context, object, path } = await data();
282
- const uriMap = traverseObject(silgi, object.schemas, []);
283
- if (uriMap.size > 0) {
284
- const uriContent = Array.from(uriMap.entries()).map(([uri, params]) => ` '${uri}': '${params}',`).join("\n");
285
- const newContext = context.replace(
286
- /export const uris = \{[^}]*\}/,
287
- `export const uris = {
288
- ${uriContent}
289
- }`
290
- );
291
- await promises.writeFile(path, newContext);
292
- }
293
- });
294
- }
295
- async function findAction(silgi, uri) {
296
- const { parts } = parseURI(uri, silgi);
297
- let result = silgi.services;
298
- for (const part of parts) {
299
- if (result && Object.prototype.hasOwnProperty.call(result, part)) {
300
- result = Object.assign({}, result[part]);
301
- } else {
302
- console.error("Property not found:", part);
303
- break;
304
- }
305
- }
306
- return result;
307
- }
308
- async function scanAction(silgi) {
309
- for (const [key, _value] of Object.entries(silgi.uris)) {
310
- const handler = await findAction(silgi, key);
311
- silgi.scannedHandlers.set(key, handler);
312
- }
313
- }
314
-
315
- async function resolvePath(path, opts = {}) {
316
- const _path = path;
317
- path = normalize(path);
318
- if (isAbsolute(path)) {
319
- if (existsSync(path) && !await isDirectory(path)) {
320
- return path;
321
- }
322
- }
323
- const cwd = opts.cwd || process.cwd();
324
- const extensions = opts.extensions || [".ts", ".mjs", ".cjs", ".json"];
325
- const modulesDir = opts.modulesDir || [];
326
- path = resolveAlias(path);
327
- if (!isAbsolute(path)) {
328
- path = resolve(cwd, path);
329
- }
330
- let _isDir = false;
331
- if (existsSync(path)) {
332
- _isDir = await isDirectory(path);
333
- if (!_isDir) {
334
- return path;
335
- }
336
- }
337
- for (const ext of extensions) {
338
- const pathWithExt = path + ext;
339
- if (existsSync(pathWithExt)) {
340
- return pathWithExt;
341
- }
342
- const pathWithIndex = join(path, `index${ext}`);
343
- if (_isDir && existsSync(pathWithIndex)) {
344
- return pathWithIndex;
345
- }
346
- }
347
- const resolveModulePath = await resolvePath$1(_path, { url: [cwd, ...modulesDir] }).catch(() => null);
348
- if (resolveModulePath) {
349
- return resolveModulePath;
350
- }
351
- return opts.fallbackToOriginal ? _path : path;
352
- }
353
- async function isDirectory(path) {
354
- return (await promises.lstat(path)).isDirectory();
355
- }
356
- function resolveAlias(path, alias) {
357
- return resolveAlias$1(path, {});
358
- }
359
- function createResolver(base) {
360
- if (!base) {
361
- throw new Error("`base` argument is missing for createResolver(base)!");
362
- }
363
- base = base.toString();
364
- if (base.startsWith("file://")) {
365
- base = dirname(fileURLToPath(base));
366
- }
367
- return {
368
- resolve: (...path) => resolve(base, ...path),
369
- resolvePath: (path, opts) => resolvePath(path, { cwd: base, ...opts })
370
- };
371
- }
372
- async function resolveSilgiModule(base, paths) {
373
- const resolved = [];
374
- const resolver = createResolver(base);
375
- for (const path of paths) {
376
- if (path.startsWith(base)) {
377
- resolved.push(path.split("/index.ts")[0]);
378
- } else {
379
- const resolvedPath = await resolver.resolvePath(path);
380
- resolved.push(resolvedPath.slice(0, resolvedPath.lastIndexOf(path) + path.length));
381
- }
382
- }
383
- return resolved;
384
- }
385
-
386
- export { SilgiError as S, useStorage as a, SilgiErrorCode as b, createStorage as c, silgiCtx as d, createResolver as e, useHook as f, generateStorageKey as g, useShared as h, getDirectory as i, resolvePath as j, generateUris as k, loadSilgiModuleInstance as l, generateSilgiStorageBaseType as m, normalizeResult as n, parseURI as p, resolveSilgiModule as r, scanAction as s, tryUseSilgi as t, useSilgi as u };
File without changes
File without changes