silgi 0.3.13 → 0.4.1

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 (71) 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 -184
  8. package/dist/cli/prepare.mjs +1350 -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 -29
  15. package/dist/ecosystem/nuxt/module.mjs +4 -25
  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 +10 -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/presets/nuxt/preset.d.ts +2 -0
  38. package/dist/presets/nuxt/preset.mjs +26 -0
  39. package/dist/runtime/index.d.ts +1 -0
  40. package/dist/runtime/index.mjs +1 -0
  41. package/dist/runtime/internal/debug.d.ts +2 -0
  42. package/dist/runtime/internal/debug.mjs +5 -0
  43. package/dist/runtime/internal/nitro.d.ts +2 -0
  44. package/dist/runtime/internal/nitro.mjs +45 -0
  45. package/dist/runtime/internal/plugin.d.ts +3 -0
  46. package/dist/runtime/internal/plugin.mjs +4 -0
  47. package/dist/shared/silgi.40ZJYm8F.d.mts +11 -0
  48. package/dist/shared/silgi.40ZJYm8F.d.ts +11 -0
  49. package/dist/shared/{silgi.ClpvycKI.d.ts → silgi.CzUPBllI.d.mts} +452 -438
  50. package/dist/shared/{silgi.ClpvycKI.d.mts → silgi.D_LzzCtJ.d.ts} +452 -438
  51. package/dist/types/index.d.mts +42 -0
  52. package/dist/types/index.d.ts +42 -0
  53. package/dist/types/index.mjs +1 -0
  54. package/kit.d.ts +1 -0
  55. package/meta.d.ts +1 -0
  56. package/package.json +89 -39
  57. package/presets.d.ts +1 -0
  58. package/runtime-meta.d.ts +4 -0
  59. package/runtime-meta.mjs +32 -0
  60. package/runtime.d.ts +1 -0
  61. package/types.d.ts +1 -0
  62. package/bin/silgi.mjs +0 -3
  63. package/dist/chunks/generate.mjs +0 -1257
  64. package/dist/cli/config.d.mts +0 -1633
  65. package/dist/cli/config.d.ts +0 -1633
  66. package/dist/index.d.mts +0 -198
  67. package/dist/index.d.ts +0 -198
  68. package/dist/index.mjs +0 -503
  69. package/dist/shared/silgi.D2yb1XAa.mjs +0 -842
  70. /package/dist/{chunks → cli}/init.mjs +0 -0
  71. /package/dist/{cli/config.mjs → config/index.mjs} +0 -0
@@ -1,842 +0,0 @@
1
- import { lstatSync, promises, existsSync } from 'node:fs';
2
- import { isAbsolute, dirname, resolve, join, relative, basename, normalize } 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 { loadConfig } from 'c12';
9
- import { defineUntypedSchema, applyDefaults } from 'untyped';
10
- import { isDevelopment, isTest, isDebug } from 'std-env';
11
- import { fileURLToPath } from 'node:url';
12
- import { resolvePath as resolvePath$1 } from 'mlly';
13
- import { resolveAlias as resolveAlias$1 } from 'pathe/utils';
14
-
15
- const silgiCtx = getContext("silgi");
16
- function useShared() {
17
- const instance = silgiCtx.tryUse();
18
- if (!instance) {
19
- throw new Error("Silgi instance is unavailable!");
20
- }
21
- return instance.options.shared;
22
- }
23
- function useSilgi() {
24
- const instance = silgiCtx.tryUse();
25
- if (!instance) {
26
- throw new Error("Silgi instance is unavailable!");
27
- }
28
- return instance;
29
- }
30
- function useHook() {
31
- const instance = silgiCtx.tryUse();
32
- if (!instance) {
33
- throw new Error("Silgi instance is unavailable!");
34
- }
35
- return instance.hooks.hook;
36
- }
37
- function normalizeResult(result) {
38
- if (Array.isArray(result)) {
39
- return [...result];
40
- }
41
- if (result && typeof result === "object") {
42
- if (Object.keys(result).every((key) => !Number.isNaN(Number(key)))) {
43
- return Object.values(result);
44
- }
45
- return { ...result };
46
- }
47
- return result;
48
- }
49
- function tryUseSilgi() {
50
- return silgiCtx.tryUse();
51
- }
52
-
53
- function getDirectory(p) {
54
- try {
55
- return isAbsolute(p) && lstatSync(p).isFile() ? dirname(p) : p;
56
- } catch {
57
- }
58
- return p;
59
- }
60
- async function loadSilgiModuleInstance(silgiModule) {
61
- if (typeof silgiModule === "string") {
62
- throw new TypeError(`Could not load \`${silgiModule}\`. Is it installed?`);
63
- }
64
- if (typeof silgiModule !== "function") {
65
- throw new TypeError(`Nuxt module should be a function: ${silgiModule}`);
66
- }
67
- return { silgiModule };
68
- }
69
-
70
- const common = defineUntypedSchema({
71
- /**
72
- * Environment to use.
73
- *
74
- * @default 'nitrojs'
75
- */
76
- environment: {
77
- $resolve: (val) => val ?? "h3"
78
- },
79
- /**
80
- * Define the root directory of your application.
81
- *
82
- * This property can be overwritten (for example, running `nuxt ./my-app/`
83
- * will set the `rootDir` to the absolute path of `./my-app/` from the
84
- * current/working directory.
85
- *
86
- * It is normally not needed to configure this option.
87
- */
88
- rootDir: {
89
- $resolve: (val) => typeof val === "string" ? resolve(val) : process.cwd()
90
- },
91
- // /**
92
- // * Define the workspace directory of your application.
93
- // *
94
- // * Often this is used when in a monorepo setup. Nuxt will attempt to detect
95
- // * your workspace directory automatically, but you can override it here.
96
- // *
97
- // * It is normally not needed to configure this option.
98
- // */
99
- // workspaceDir: {
100
- // $resolve: async (val: string | undefined, get): Promise<string> => {
101
- // const rootDir = await get('rootDir') as string
102
- // return val ? resolve(rootDir, val) : await findWorkspaceDir(rootDir).catch(() => rootDir)
103
- // },
104
- // },
105
- /**
106
- * Define the server directory of your Nuxt application, where Nitro
107
- * routes, middleware and plugins are kept.
108
- *
109
- * If a relative path is specified, it will be relative to your `rootDir`.
110
- *
111
- */
112
- serverDir: {
113
- $resolve: async (val, get) => {
114
- if (val) {
115
- const rootDir = await get("rootDir");
116
- return resolve(rootDir, val);
117
- }
118
- return join(await get("rootDir"), "server");
119
- }
120
- },
121
- silgiDir: {
122
- $resolve: async (val, get) => {
123
- if (val) {
124
- return resolve(await get("rootDir"), val);
125
- }
126
- return join(await get("serverDir"), "silgi");
127
- }
128
- },
129
- /**
130
- * Define the directory where your built Nuxt files will be placed.
131
- *
132
- * Many tools assume that `.nuxt` is a hidden directory (because it starts
133
- * with a `.`). If that is a problem, you can use this option to prevent that.
134
- * @example
135
- * ```js
136
- * export default {
137
- * buildDir: 'nuxt-build'
138
- * }
139
- * ```
140
- */
141
- buildDir: {
142
- $resolve: async (val, get) => {
143
- const rootDir = await get("rootDir");
144
- return resolve(rootDir, val ?? ".silgi");
145
- }
146
- },
147
- /**
148
- * Used to set the modules directories for path resolving (for example, webpack's
149
- * `resolveLoading`, `nodeExternals` and `postcss`).
150
- *
151
- * The configuration path is relative to `options.rootDir` (default is current working directory).
152
- *
153
- * Setting this field may be necessary if your project is organized as a yarn workspace-styled mono-repository.
154
- * @example
155
- * ```js
156
- * export default {
157
- * modulesDir: ['../../node_modules']
158
- * }
159
- * ```
160
- */
161
- modulesDir: {
162
- $default: ["node_modules"],
163
- $resolve: async (val, get) => {
164
- const rootDir = await get("rootDir");
165
- return [.../* @__PURE__ */ new Set([
166
- ...(val || []).map((dir) => resolve(rootDir, dir)),
167
- resolve(rootDir, "node_modules")
168
- ])];
169
- }
170
- },
171
- /**
172
- * Whether Nuxt is running in development mode.
173
- *
174
- * Normally, you should not need to set this.
175
- */
176
- dev: {
177
- $resolve: (val) => val ?? Boolean(isDevelopment)
178
- },
179
- /**
180
- * Whether your app is being unit tested.
181
- */
182
- test: {
183
- $resolve: (val) => val ?? Boolean(isTest)
184
- },
185
- /**
186
- * Set to `true` to enable debug mode.
187
- *
188
- * At the moment, it prints out hook names and timings on the server, and
189
- * logs hook arguments as well in the browser.
190
- *
191
- */
192
- debug: {
193
- $resolve: (val) => val ?? isDebug
194
- },
195
- /**
196
- * Modules are Nuxt extensions which can extend its core functionality and add endless integrations.
197
- *
198
- * Each module is either a string (which can refer to a package, or be a path to a file), a
199
- * tuple with the module as first string and the options as a second object, or an inline module function.
200
- *
201
- * Nuxt tries to resolve each item in the modules array using node require path
202
- * (in `node_modules`) and then will be resolved from project `srcDir` if `~` alias is used.
203
- * @note Modules are executed sequentially so the order is important. First, the modules defined in `nuxt.config.ts` are loaded. Then, modules found in the `modules/`
204
- * directory are executed, and they load in alphabetical order.
205
- * @example
206
- * ```js
207
- * modules: [
208
- * // Using package name
209
- * '@nuxtjs/axios',
210
- * // Relative to your project srcDir
211
- * '~/modules/awesome.js',
212
- * // Providing options
213
- * ['@nuxtjs/google-analytics', { ua: 'X1234567' }],
214
- * // Inline definition
215
- * function () {}
216
- * ]
217
- * ```
218
- * @type {(typeof import('../src/types/module').NuxtModule<any> | string | [typeof import('../src/types/module').NuxtModule | string, Record<string, any>] | undefined | null | false)[]}
219
- */
220
- modules: {
221
- $resolve: (val) => (val || []).filter(Boolean)
222
- },
223
- /**
224
- * Hooks are listeners to Nuxt events that are typically used in modules,
225
- * but are also available in `nuxt.config`.
226
- *
227
- * Internally, hooks follow a naming pattern using colons (e.g., build:done).
228
- *
229
- * For ease of configuration, you can also structure them as an hierarchical
230
- * object in `nuxt.config` (as below).
231
- * @example
232
- * ```js
233
- * import fs from 'node:fs'
234
- * import path from 'node:path'
235
- * export default {
236
- * hooks: {
237
- * build: {
238
- * done(builder) {
239
- * const extraFilePath = path.join(
240
- * builder.nuxt.options.buildDir,
241
- * 'extra-file'
242
- * )
243
- * fs.writeFileSync(extraFilePath, 'Something extra')
244
- * }
245
- * }
246
- * }
247
- * }
248
- * ```
249
- * @type {typeof import('../src/types/hooks').NuxtHooks}
250
- */
251
- hooks: null,
252
- /**
253
- * Customize default directory structure used by Nuxt.
254
- *
255
- * It is better to stick with defaults unless needed.
256
- */
257
- dir: {
258
- client: {
259
- $resolve: async (val, get) => {
260
- const [srcDir, rootDir] = await Promise.all([get("srcDir"), get("rootDir")]);
261
- return resolve(await get("srcDir"), val || (srcDir === rootDir ? "app" : "."));
262
- }
263
- },
264
- /**
265
- * The modules directory, each file in which will be auto-registered as a Nuxt module.
266
- */
267
- modules: {
268
- $resolve: async (val, get) => {
269
- if (val) {
270
- return join(await get("rootDir"), val);
271
- }
272
- return resolve(await get("serverDir"), "silgi/modules");
273
- }
274
- },
275
- /**
276
- * The shared directory. This directory is shared between the app and the server.
277
- */
278
- shared: {
279
- $resolve: async (val, get) => {
280
- return resolve(await get("rootDir"), val || "shared");
281
- }
282
- },
283
- /**
284
- * The directory containing your static files, which will be directly accessible via the Nuxt server
285
- * and copied across into your `dist` folder when your app is generated.
286
- */
287
- public: {
288
- $resolve: async (val, get) => {
289
- return resolve(await get("rootDir"), val || "public");
290
- }
291
- }
292
- },
293
- /**
294
- * More customizable than `ignorePrefix`: all files matching glob patterns specified
295
- * inside the `ignore` array will be ignored in building.
296
- */
297
- ignore: {
298
- $resolve: async (val, get) => {
299
- const [rootDir, ignorePrefix, analyzeDir, buildDir] = await Promise.all([get("rootDir"), get("ignorePrefix"), get("analyzeDir"), get("buildDir")]);
300
- return [
301
- "**/*.stories.{js,cts,mts,ts,jsx,tsx}",
302
- // ignore storybook files
303
- "**/*.{spec,test}.{js,cts,mts,ts,jsx,tsx}",
304
- // ignore tests
305
- "**/*.d.{cts,mts,ts}",
306
- // ignore type declarations
307
- "**/.{pnpm-store,vercel,netlify,output,git,cache,data}",
308
- relative(rootDir, analyzeDir),
309
- relative(rootDir, buildDir),
310
- ignorePrefix && `**/${ignorePrefix}*.*`,
311
- ...val || []
312
- ].filter(Boolean);
313
- }
314
- },
315
- /**
316
- * You can improve your DX by defining additional aliases to access custom directories
317
- * within your JavaScript and CSS.
318
- * @note Within a webpack context (image sources, CSS - but not JavaScript) you _must_ access
319
- * your alias by prefixing it with `~`.
320
- * @note These aliases will be automatically added to the generated `.nuxt/tsconfig.json` so you can get full
321
- * type support and path auto-complete. In case you need to extend options provided by `./.nuxt/tsconfig.json`
322
- * further, make sure to add them here or within the `typescript.tsConfig` property in `nuxt.config`.
323
- * @example
324
- * ```js
325
- * export default {
326
- * alias: {
327
- * 'images': fileURLToPath(new URL('./assets/images', import.meta.url)),
328
- * 'style': fileURLToPath(new URL('./assets/style', import.meta.url)),
329
- * 'data': fileURLToPath(new URL('./assets/other/data', import.meta.url))
330
- * }
331
- * }
332
- * ```
333
- *
334
- * ```html
335
- * <template>
336
- * <img src="~images/main-bg.jpg">
337
- * </template>
338
- *
339
- * <script>
340
- * import data from 'data/test.json'
341
- * <\/script>
342
- *
343
- * <style>
344
- * // Uncomment the below
345
- * //@import '~style/variables.scss';
346
- * //@import '~style/utils.scss';
347
- * //@import '~style/base.scss';
348
- * body {
349
- * background-image: url('~images/main-bg.jpg');
350
- * }
351
- * </style>
352
- * ```
353
- * @type {Record<string, string>}
354
- */
355
- alias: {
356
- $resolve: async (val, get) => {
357
- const [srcDir, rootDir, assetsDir, publicDir, _buildDir, sharedDir, silgiDir] = await Promise.all([get("srcDir"), get("rootDir"), get("dir.assets"), get("dir.public"), get("buildDir"), get("dir.shared"), get("silgiDir")]);
358
- return {
359
- "~": srcDir,
360
- "@": srcDir,
361
- "~~": rootDir,
362
- "@@": rootDir,
363
- "#shared": resolve(rootDir, sharedDir),
364
- [basename(assetsDir)]: resolve(srcDir, assetsDir),
365
- [basename(publicDir)]: resolve(srcDir, publicDir),
366
- "#silgi": silgiDir,
367
- // '#build': buildDir,
368
- // '#internal/nuxt/paths': resolve(buildDir, 'paths.mjs'),
369
- ...val
370
- };
371
- }
372
- },
373
- $schema: {}
374
- });
375
-
376
- const internal = defineUntypedSchema({
377
- isPackage: false,
378
- /** @private */
379
- _majorVersion: 4,
380
- /** @private */
381
- _legacyGenerate: false,
382
- /** @private */
383
- _start: false,
384
- /** @private */
385
- _build: false,
386
- /** @private */
387
- _generate: false,
388
- /** @private */
389
- _prepare: false,
390
- /** @private */
391
- _cli: false,
392
- /** @private */
393
- _requiredModules: {},
394
- /** @private */
395
- _silgiConfigFile: undefined,
396
- /** @private */
397
- _silgiConfigFiles: [],
398
- /**
399
- * @private
400
- * @type {Array<{ meta: ModuleMeta; timings?: Record<string, number | undefined>; entryPath?: string }>}
401
- */
402
- _installedModules: [],
403
- /** @private */
404
- _modules: [],
405
- extensions: [".js", ".mjs", ".ts"]
406
- });
407
-
408
- const typescript = defineUntypedSchema({
409
- /**
410
- * Configuration for Nuxt's TypeScript integration.
411
- *
412
- */
413
- typescript: {
414
- /**
415
- * TypeScript comes with certain checks to give you more safety and analysis of your program.
416
- * Once you’ve converted your codebase to TypeScript, you can start enabling these checks for greater safety.
417
- * [Read More](https://www.typescriptlang.org/docs/handbook/migrating-from-javascript.html#getting-stricter-checks)
418
- */
419
- strict: true,
420
- /**
421
- * Which builder types to include for your project.
422
- *
423
- * By default Nuxt infers this based on your `builder` option (defaulting to 'vite') but you can either turn off
424
- * builder environment types (with `false`) to handle this fully yourself, or opt for a 'shared' option.
425
- *
426
- * The 'shared' option is advised for module authors, who will want to support multiple possible builders.
427
- * @type {'vite' | 'webpack' | 'rspack' | 'shared' | false | undefined}
428
- */
429
- builder: {
430
- $resolve: (val) => val ?? null
431
- },
432
- /**
433
- * Modules to generate deep aliases for within `compilerOptions.paths`. This does not yet support subpaths.
434
- * It may be necessary when using Nuxt within a pnpm monorepo with `shamefully-hoist=false`.
435
- */
436
- hoist: {
437
- $resolve: (val) => {
438
- const defaults = [
439
- // Nitro auto-imported/augmented dependencies
440
- "nitro/types",
441
- "nitro/runtime",
442
- "defu",
443
- "h3",
444
- "consola",
445
- "ofetch",
446
- // Key nuxt dependencies
447
- "@unhead/vue",
448
- "@nuxt/devtools",
449
- "vue",
450
- "@vue/runtime-core",
451
- "@vue/compiler-sfc",
452
- "vue-router",
453
- "vue-router/auto-routes",
454
- "unplugin-vue-router/client",
455
- "@nuxt/schema",
456
- "nuxt"
457
- ];
458
- return val === false ? [] : Array.isArray(val) ? val.concat(defaults) : defaults;
459
- }
460
- },
461
- /**
462
- * Include parent workspace in the Nuxt project. Mostly useful for themes and module authors.
463
- */
464
- includeWorkspace: false,
465
- /**
466
- * Enable build-time type checking.
467
- *
468
- * If set to true, this will type check in development. You can restrict this to build-time type checking by setting it to `build`.
469
- * Requires to install `typescript` and `vue-tsc` as dev dependencies.
470
- * @see [Nuxt TypeScript docs](https://nuxt.com/docs/guide/concepts/typescript)
471
- * @type {boolean | 'build'}
472
- */
473
- typeCheck: false,
474
- /**
475
- * You can extend generated `.nuxt/tsconfig.json` using this option.
476
- * @type {0 extends 1 & VueCompilerOptions ? typeof import('pkg-types')['TSConfig'] : typeof import('pkg-types')['TSConfig'] & { vueCompilerOptions?: Omit<typeof import('@vue/language-core')['VueCompilerOptions'], 'plugins'> & { plugins?: string[] } }}
477
- */
478
- tsConfig: {},
479
- /**
480
- * Generate a `*.vue` shim.
481
- *
482
- * We recommend instead letting the [official Vue extension](https://marketplace.visualstudio.com/items?itemName=Vue.volar)
483
- * generate accurate types for your components.
484
- *
485
- * Note that you may wish to set this to `true` if you are using other libraries, such as ESLint,
486
- * that are unable to understand the type of `.vue` files.
487
- */
488
- shim: false
489
- }
490
- });
491
-
492
- const SilgiConfigSchema = {
493
- ...common,
494
- ...internal,
495
- ...typescript
496
- };
497
-
498
- var SilgiErrorCode = /* @__PURE__ */ ((SilgiErrorCode2) => {
499
- SilgiErrorCode2["AUTH_UNAUTHORIZED"] = "AUTH_UNAUTHORIZED";
500
- SilgiErrorCode2["AUTH_MISSING_CONTEXT"] = "AUTH_MISSING_CONTEXT";
501
- SilgiErrorCode2["AUTH_INVALID_CONTEXT"] = "AUTH_INVALID_CONTEXT";
502
- SilgiErrorCode2["AUTH_PERMISSION_DENIED"] = "AUTH_PERMISSION_DENIED";
503
- SilgiErrorCode2["PLUGIN_ERROR"] = "PLUGIN_ERROR";
504
- SilgiErrorCode2["METHOD_NOT_FOUND"] = "METHOD_NOT_FOUND";
505
- SilgiErrorCode2["EXECUTION_ERROR"] = "EXECUTION_ERROR";
506
- SilgiErrorCode2["CACHE_ERROR"] = "CACHE_ERROR";
507
- SilgiErrorCode2["PLUGIN_ALREADY_EXISTS"] = "PLUGIN_ALREADY_EXISTS";
508
- SilgiErrorCode2["PLUGIN_NOT_FOUND"] = "PLUGIN_NOT_FOUND";
509
- SilgiErrorCode2["PLUGIN_INIT_ERROR"] = "PLUGIN_INIT_ERROR";
510
- return SilgiErrorCode2;
511
- })(SilgiErrorCode || {});
512
- class SilgiError extends Error {
513
- code;
514
- details;
515
- meta;
516
- timestamp;
517
- cause;
518
- constructor(options) {
519
- super(options.message);
520
- this.name = "SilgiError";
521
- this.code = options.code;
522
- this.details = options.details;
523
- this.meta = options.meta;
524
- this.cause = options.cause;
525
- this.timestamp = Date.now();
526
- if (Error.captureStackTrace) {
527
- Error.captureStackTrace(this, this.constructor);
528
- }
529
- }
530
- // Improve error formatting
531
- toString() {
532
- let str = `${this.name} [${this.code}]: ${this.message}`;
533
- if (this.details) {
534
- str += `
535
- Details: ${JSON.stringify(this.details, null, 2)}`;
536
- }
537
- if (this.meta) {
538
- str += `
539
- Meta: ${JSON.stringify(this.meta, null, 2)}`;
540
- }
541
- if (this.stack) {
542
- str += `
543
- ${this.stack}`;
544
- }
545
- return str;
546
- }
547
- toJSON() {
548
- return {
549
- name: this.name,
550
- code: this.code,
551
- message: this.message,
552
- details: this.details,
553
- meta: this.meta,
554
- timestamp: this.timestamp,
555
- stack: this.stack
556
- };
557
- }
558
- static createFrom(error, code = "UNKNOWN_ERROR") {
559
- if (error instanceof SilgiError) {
560
- return error;
561
- }
562
- return new SilgiError({
563
- code,
564
- message: error instanceof Error ? error.message : String(error),
565
- cause: error instanceof Error ? error : undefined
566
- });
567
- }
568
- static isSilgiError(error) {
569
- return error instanceof SilgiError;
570
- }
571
- }
572
-
573
- function traverseObject(silgi, obj, currentPath = []) {
574
- const uriMap = /* @__PURE__ */ new Map();
575
- function traverse(node, path = []) {
576
- if (!node || typeof node !== "object")
577
- return;
578
- if (path.length === 4) {
579
- const basePath = path.join("/");
580
- let paramString = "";
581
- if (node.router) {
582
- let params = null;
583
- if (node.router?._def?.typeName !== undefined) {
584
- try {
585
- const shape = node.router?.shape?.params?.shape;
586
- params = shape ? Object.keys(shape) : null;
587
- } catch {
588
- params = null;
589
- }
590
- }
591
- if (params?.length) {
592
- paramString = params.map((p) => `:${p}`).join("/");
593
- }
594
- }
595
- uriMap.set(basePath, paramString);
596
- return;
597
- }
598
- for (const key in node) {
599
- if (!["_type", "fields"].includes(key)) {
600
- traverse(node[key], [...path, key]);
601
- }
602
- }
603
- }
604
- traverse(obj, currentPath);
605
- return uriMap;
606
- }
607
- function parseURI(uri, uris) {
608
- if (!uris) {
609
- const silgiCtx = useSilgi();
610
- uris = silgiCtx.uris;
611
- }
612
- uri = uri.replace("/srn", "");
613
- const [cleanPath, queryString] = uri.split("?");
614
- const query = new URLSearchParams(queryString);
615
- const methodQuery = query.get("method")?.toLowerCase();
616
- const parts = cleanPath.split("/").filter(Boolean);
617
- const [namespace, service, methodOrAction, action, ...routerParams] = parts;
618
- let uriKey = `${namespace}/${service}/${methodOrAction}/${action}`;
619
- if (methodQuery) {
620
- uriKey = `${namespace}/${service}/${methodQuery}/${methodOrAction}`;
621
- routerParams.unshift(action);
622
- }
623
- const paramTemplate = uris[uriKey];
624
- const routerParamsData = {};
625
- if (paramTemplate && routerParams.length > 0) {
626
- const paramNames = paramTemplate.split("/").map((p) => p.replace(":", ""));
627
- routerParams.forEach((value, index) => {
628
- if (paramNames[index]) {
629
- routerParamsData[paramNames[index]] = value;
630
- }
631
- });
632
- }
633
- return {
634
- namespaceName: namespace,
635
- serviceName: service,
636
- methodName: methodQuery || methodOrAction,
637
- actionName: methodQuery ? methodOrAction : action,
638
- raw: uri,
639
- parts: [namespace, service, methodQuery || methodOrAction, action],
640
- routerParams: routerParamsData,
641
- query: query.toString() ? Object.fromEntries(query) : undefined,
642
- uri: uriKey
643
- };
644
- }
645
-
646
- async function createStorage(silgi) {
647
- const storage = createStorage$1();
648
- const mounts = klona({
649
- ...silgi.options.storage,
650
- ...silgi.options.devStorage
651
- });
652
- for (const [path, opts] of Object.entries(mounts)) {
653
- if (opts.driver) {
654
- const driver = await import(builtinDrivers[opts.driver] || opts.driver).then((r) => r.default || r);
655
- storage.mount("/memory:cache", memoryDriver());
656
- storage.mount(path, driver(opts));
657
- } else {
658
- silgi.logger.warn(`No \`driver\` set for storage mount point "${path}".`);
659
- }
660
- }
661
- return storage;
662
- }
663
- function useStorage(base = "/memory:cache") {
664
- const silgi = useSilgi();
665
- return base ? prefixStorage(silgi.storage, base) : silgi.storage;
666
- }
667
- async function generateStorageKey(params) {
668
- const {
669
- operation,
670
- input,
671
- keyGenerator,
672
- requestId,
673
- storageOptions
674
- } = params;
675
- const cacheScopePrefix = storageOptions?.scope === "request" ? "req" : "global";
676
- const parts = [
677
- cacheScopePrefix,
678
- // Always include scope prefix first
679
- operation.namespaceName,
680
- operation.serviceName,
681
- operation.methodName
682
- ].filter(Boolean);
683
- if (storageOptions?.scope === "request") {
684
- if (!requestId) {
685
- throw new SilgiError({
686
- code: "CACHE_ERROR",
687
- message: "Request ID is required for request-scoped cache"
688
- });
689
- }
690
- parts.push(requestId);
691
- }
692
- if (keyGenerator) {
693
- const customKey = await Promise.resolve(keyGenerator(input));
694
- parts.push(customKey);
695
- } else {
696
- parts.push(typeof input === "object" ? JSON.stringify(input) : String(input));
697
- }
698
- return Buffer.from(parts.join(":")).toString("base64");
699
- }
700
- async function generateSilgiStorageBaseType(silgi) {
701
- silgi.hook("prepare:schema.ts", async (options) => {
702
- if (silgi.options.storage) {
703
- for (const [key, _value] of Object.entries(silgi.options.storage)) {
704
- options.storeBase.push(key);
705
- }
706
- }
707
- });
708
- }
709
-
710
- async function generateUris(silgi) {
711
- silgi.hook("read:core.ts", async (data) => {
712
- const { context, object, path } = await data();
713
- const uriMap = traverseObject(silgi, object.schemas, []);
714
- if (uriMap.size > 0) {
715
- const uriContent = Array.from(uriMap.entries()).map(([uri, params]) => ` '${uri}': '${params}',`).join("\n");
716
- const newContext = context.replace(
717
- /export const uris = \{[^}]*\}/,
718
- `export const uris = {
719
- ${uriContent}
720
- }`
721
- );
722
- await promises.writeFile(path, newContext);
723
- }
724
- });
725
- }
726
- async function findAction(silgi, uri) {
727
- const { parts } = parseURI(uri, silgi);
728
- let result = silgi.services;
729
- for (const part of parts) {
730
- if (result && Object.prototype.hasOwnProperty.call(result, part)) {
731
- result = Object.assign({}, result[part]);
732
- } else {
733
- console.error("Property not found:", part);
734
- break;
735
- }
736
- }
737
- return result;
738
- }
739
- async function scanAction(silgi) {
740
- for (const [key, _value] of Object.entries(silgi.uris)) {
741
- const handler = await findAction(silgi, key);
742
- silgi.scannedHandlers.set(key, handler);
743
- }
744
- }
745
-
746
- async function loadSilgiConfig(opts) {
747
- globalThis.defineSilgiConfig = (c) => c;
748
- const result = await loadConfig({
749
- name: "silgi",
750
- configFile: "silgi.config",
751
- rcFile: ".silgirc",
752
- // extend: { extendKey: ['theme', 'extends', '_extends'] },
753
- dotenv: true,
754
- globalRc: true,
755
- ...opts
756
- });
757
- delete globalThis.defineSilgiConfig;
758
- const { configFile, cwd } = result;
759
- const silgiConfig = result.config;
760
- silgiConfig.rootDir = silgiConfig.rootDir || cwd;
761
- silgiConfig._silgiConfigFile = configFile;
762
- silgiConfig._silgiConfigFiles = [configFile];
763
- return await applyDefaults(SilgiConfigSchema, silgiConfig);
764
- }
765
-
766
- async function resolvePath(path, opts = {}) {
767
- const _path = path;
768
- path = normalize(path);
769
- if (isAbsolute(path)) {
770
- if (existsSync(path) && !await isDirectory(path)) {
771
- return path;
772
- }
773
- }
774
- const cwd = opts.cwd || process.cwd();
775
- const extensions = opts.extensions || [".ts", ".mjs", ".cjs", ".json"];
776
- const modulesDir = opts.modulesDir || [];
777
- path = resolveAlias(path);
778
- if (!isAbsolute(path)) {
779
- path = resolve(cwd, path);
780
- }
781
- let _isDir = false;
782
- if (existsSync(path)) {
783
- _isDir = await isDirectory(path);
784
- if (!_isDir) {
785
- return path;
786
- }
787
- }
788
- for (const ext of extensions) {
789
- const pathWithExt = path + ext;
790
- if (existsSync(pathWithExt)) {
791
- return pathWithExt;
792
- }
793
- const pathWithIndex = join(path, `index${ext}`);
794
- if (_isDir && existsSync(pathWithIndex)) {
795
- return pathWithIndex;
796
- }
797
- }
798
- const resolveModulePath = await resolvePath$1(_path, { url: [cwd, ...modulesDir] }).catch(() => null);
799
- if (resolveModulePath) {
800
- return resolveModulePath;
801
- }
802
- return opts.fallbackToOriginal ? _path : path;
803
- }
804
- async function isDirectory(path) {
805
- return (await promises.lstat(path)).isDirectory();
806
- }
807
- function resolveAlias(path, alias) {
808
- return resolveAlias$1(path, {});
809
- }
810
- function createResolver(base) {
811
- if (!base) {
812
- throw new Error("`base` argument is missing for createResolver(base)!");
813
- }
814
- base = base.toString();
815
- if (base.startsWith("file://")) {
816
- base = dirname(fileURLToPath(base));
817
- }
818
- return {
819
- resolve: (...path) => resolve(base, ...path),
820
- resolvePath: (path, opts) => resolvePath(path, { cwd: base, ...opts })
821
- };
822
- }
823
- async function resolveSilgiModule(base, paths) {
824
- const resolved = [];
825
- const resolver = createResolver(base);
826
- for (const path of paths) {
827
- if (path.startsWith(base)) {
828
- resolved.push(path.split("/index.ts")[0]);
829
- } else {
830
- const resolvedPath = await resolver.resolvePath(path);
831
- resolved.push(resolvedPath.slice(0, resolvedPath.lastIndexOf(path) + path.length));
832
- }
833
- }
834
- return resolved;
835
- }
836
-
837
- const RELATIVE_RE = /^([^.])/;
838
- function relativeWithDot(from, to) {
839
- return relative(from, to).replace(RELATIVE_RE, "./$1") || ".";
840
- }
841
-
842
- export { SilgiError as S, loadSilgiModuleInstance as a, useStorage as b, SilgiErrorCode as c, SilgiConfigSchema as d, createStorage as e, silgiCtx as f, generateStorageKey as g, createResolver as h, useHook as i, useShared as j, getDirectory as k, loadSilgiConfig as l, resolveSilgiModule as m, normalizeResult as n, resolvePath as o, parseURI as p, generateUris as q, relativeWithDot as r, scanAction as s, tryUseSilgi as t, useSilgi as u, generateSilgiStorageBaseType as v };