silgi 0.20.32 → 0.20.34

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.
@@ -1,2386 +0,0 @@
1
- import { existsSync, promises, readFileSync, writeFileSync, mkdirSync } from 'node:fs';
2
- import { readdir, readFile } from 'node:fs/promises';
3
- import consola$1, { consola } from 'consola';
4
- import { createHooks, createDebugger } from 'hookable';
5
- import { resolve, join, relative, dirname, basename, extname, isAbsolute } from 'pathe';
6
- import { useSilgiCLI, silgiCLICtx } from 'silgi/core';
7
- import { relativeWithDot, hash, resolveAlias, directoryToURL, addTemplate, writeFile, parseServices, normalizeTemplate, useLogger, initRuntimeConfig, hasError as hasError$1, resolveSilgiPath, isDirectory } from 'silgi/kit';
8
- import { runtimeDir } from 'silgi/runtime/meta';
9
- import { autoImportTypes } from 'silgi/types';
10
- import { scanExports, createUnimport, toExports } from 'unimport';
11
- import { c as createRouteRules } from '../_chunks/routeRules.mjs';
12
- import * as p from '@clack/prompts';
13
- import * as dotenv from 'dotenv';
14
- import { resolveModuleExportNames, findTypeExports, findExports, resolvePath, parseNodeModulePath, lookupNodeModuleSubpath } from 'mlly';
15
- import { createJiti } from 'dev-jiti';
16
- import { a as hasInstalledModule, h as hasError } from './compatibility.mjs';
17
- import { fileURLToPath } from 'node:url';
18
- import defu, { defu as defu$1 } from 'defu';
19
- import { resolveModuleURL } from 'exsolve';
20
- import { isRelative, withTrailingSlash } from 'ufo';
21
- import { generateTypes, resolveSchema } from 'untyped';
22
- import { globby } from 'globby';
23
- import ignore from 'ignore';
24
- import { parseSync } from '@oxc-parser/wasm';
25
- import { klona } from 'klona';
26
- import { createStorage, builtinDrivers } from 'unstorage';
27
- import { peerDependencies } from 'silgi/meta';
28
- import { l as loadOptions, s as silgiGenerateType } from './types.mjs';
29
- import { resolveAlias as resolveAlias$1 } from 'pathe/utils';
30
-
31
- async function prepare(_silgi) {
32
- }
33
-
34
- async function setupDotenv(options) {
35
- const targetEnvironment = options.env ?? process.env;
36
- const environment = await loadDotenv({
37
- cwd: options.cwd,
38
- fileName: options.fileName ?? ".env",
39
- env: targetEnvironment,
40
- interpolate: options.interpolate ?? true
41
- });
42
- for (const key in environment) {
43
- if (!key.startsWith("_") && targetEnvironment[key] === void 0) {
44
- targetEnvironment[key] = environment[key];
45
- }
46
- }
47
- return environment;
48
- }
49
- async function loadDotenv(options) {
50
- const environment = /* @__PURE__ */ Object.create(null);
51
- const dotenvFile = resolve(options.cwd, options.fileName);
52
- if (existsSync(dotenvFile)) {
53
- const parsed = dotenv.parse(await promises.readFile(dotenvFile, "utf8"));
54
- Object.assign(environment, parsed);
55
- }
56
- if (!options.env?._applied) {
57
- Object.assign(environment, options.env);
58
- environment._applied = true;
59
- }
60
- if (options.interpolate) {
61
- interpolate(environment);
62
- }
63
- return environment;
64
- }
65
- function interpolate(target, source = {}, parse = (v) => v) {
66
- function getValue(key) {
67
- return source[key] === void 0 ? target[key] : source[key];
68
- }
69
- function interpolate2(value, parents = []) {
70
- if (typeof value !== "string") {
71
- return value;
72
- }
73
- const matches = value.match(/(.?\$\{?[\w:]*\}?)/g) || [];
74
- return parse(
75
- matches.reduce((newValue, match) => {
76
- const parts = /(.?)\$\{?([\w:]+)?\}?/.exec(match) || [];
77
- const prefix = parts[1];
78
- let value2, replacePart;
79
- if (prefix === "\\") {
80
- replacePart = parts[0] || "";
81
- value2 = replacePart.replace(String.raw`\$`, "$");
82
- } else {
83
- const key = parts[2];
84
- replacePart = (parts[0] || "").slice(prefix.length);
85
- if (parents.includes(key)) {
86
- console.warn(
87
- `Please avoid recursive environment variables ( loop: ${parents.join(
88
- " > "
89
- )} > ${key} )`
90
- );
91
- return "";
92
- }
93
- value2 = getValue(key);
94
- value2 = interpolate2(value2, [...parents, key]);
95
- }
96
- return value2 === void 0 ? newValue : newValue.replace(replacePart, value2);
97
- }, value)
98
- );
99
- }
100
- for (const key in target) {
101
- target[key] = interpolate2(getValue(key));
102
- }
103
- }
104
-
105
- let initialized = false;
106
- async function prepareEnv(silgiConfig) {
107
- if (initialized)
108
- return;
109
- initialized = true;
110
- const customEnvironments = silgiConfig.environments;
111
- const environment = silgiConfig.activeEnvironment ? silgiConfig.activeEnvironment : await p.select({
112
- message: "Select an environment",
113
- options: customEnvironments?.length > 0 ? customEnvironments.map((env) => ({
114
- label: env.fileName,
115
- value: env.fileName
116
- })) : [
117
- { label: "Development (.env.dev)", value: "dev" },
118
- { label: "Docker (.env.docker)", value: "docker" },
119
- { label: "Staging (.env.staging)", value: "staging" },
120
- { label: "Testing (.env.testing)", value: "testing" },
121
- { label: "Production (.env)", value: ".env" }
122
- ]
123
- });
124
- const findEnv = customEnvironments?.find((env) => env.fileName === environment);
125
- if (findEnv) {
126
- await setupDotenv({
127
- cwd: findEnv.cwd || silgiConfig.rootDir,
128
- interpolate: findEnv.interpolate,
129
- fileName: findEnv.fileName,
130
- env: findEnv.env
131
- });
132
- } else {
133
- await setupDotenv({
134
- cwd: silgiConfig.rootDir,
135
- interpolate: true,
136
- fileName: environment === "prod" ? ".env" : `.env.${environment}`
137
- });
138
- }
139
- }
140
-
141
- async function emptyFramework(silgi) {
142
- if (silgi.options.preset === "npm-package" || !silgi.options.preset) {
143
- silgi.hook("after:prepare:schema.ts", (data) => {
144
- data.unshift("type FrameworkContextExtends = {}");
145
- });
146
- }
147
- }
148
-
149
- async function h3Framework(silgi, skip = false) {
150
- if (silgi.options.preset !== "h3" && skip === false)
151
- return;
152
- if (silgi.options.preset === "h3") {
153
- silgi.hook("after:prepare:schema.ts", (data) => {
154
- data.unshift("type FrameworkContextExtends = NitroApp");
155
- });
156
- }
157
- silgi.hook("prepare:schema.ts", (data) => {
158
- data.importItems.nitropack = {
159
- import: [
160
- {
161
- name: "NitroApp",
162
- type: true,
163
- key: "NitroApp"
164
- }
165
- ],
166
- from: "nitropack/types"
167
- };
168
- data.importItems.h3 = {
169
- import: [
170
- {
171
- name: "H3Event",
172
- type: true,
173
- key: "H3Event"
174
- }
175
- ],
176
- from: "h3"
177
- };
178
- data.events.push({
179
- key: "H3Event",
180
- value: "H3Event",
181
- extends: true,
182
- isSilgiContext: false
183
- });
184
- });
185
- silgi.hook("prepare:createDTSFramework", (data) => {
186
- data.importItems["silgi/types"] = {
187
- import: [
188
- {
189
- name: "SilgiRuntimeContext",
190
- type: true,
191
- key: "SilgiRuntimeContext"
192
- }
193
- ],
194
- from: "silgi/types"
195
- };
196
- data.customContent?.push(
197
- "",
198
- 'declare module "h3" {',
199
- " interface H3EventContext extends SilgiRuntimeContext {}",
200
- "}",
201
- ""
202
- );
203
- });
204
- silgi.hook("prepare:core.ts", (data) => {
205
- data._silgiConfigs.push(`captureError: (error, context = {}) => {
206
- const promise = silgi.hooks
207
- .callHookParallel('error', error, context)
208
- .catch((error_) => {
209
- console.error('Error while capturing another error', error_)
210
- })
211
-
212
- if (context.event && isEvent(context.event)) {
213
- const errors = context.event.context.nitro?.errors
214
- if (errors) {
215
- errors.push({ error, context })
216
- }
217
- if (context.event.waitUntil) {
218
- context.event.waitUntil(promise)
219
- }
220
- }
221
- }`);
222
- });
223
- if (silgi.options.imports !== false) {
224
- const h3Exports = await resolveModuleExportNames("h3", {
225
- url: import.meta.url
226
- });
227
- silgi.options.imports.presets ??= [];
228
- silgi.options.imports.presets.push({
229
- from: "h3",
230
- imports: h3Exports.filter((n) => !/^[A-Z]/.test(n) && n !== "use")
231
- });
232
- }
233
- }
234
-
235
- async function nitroFramework(silgi, skip = false) {
236
- if (silgi.options.preset !== "nitro" && skip === false)
237
- return;
238
- silgi.hook("prepare:schema.ts", (data) => {
239
- data.importItems.nitropack = {
240
- import: [
241
- {
242
- name: "NitroApp",
243
- type: true,
244
- key: "NitroApp"
245
- }
246
- ],
247
- from: "nitropack/types"
248
- };
249
- });
250
- silgi.hook("after:prepare:schema.ts", (data) => {
251
- data.unshift("type FrameworkContextExtends = NitroApp");
252
- });
253
- silgi.options.plugins.push({
254
- packageImport: "silgi/runtime/internal/nitro",
255
- path: join(runtimeDir, "internal/nitro")
256
- });
257
- silgi.hook("prepare:createDTSFramework", (data) => {
258
- data.importItems["nitropack/types"] = {
259
- import: [
260
- {
261
- name: "NitroRuntimeConfig",
262
- type: true,
263
- key: "NitroRuntimeConfig"
264
- }
265
- ],
266
- from: "nitropack/types"
267
- };
268
- data.customContent?.push(
269
- "",
270
- 'declare module "silgi/types" {',
271
- " interface SilgiRuntimeConfig extends NitroRuntimeConfig {}",
272
- "}",
273
- ""
274
- );
275
- });
276
- if (silgi.options.imports !== false) {
277
- silgi.options.imports.presets ??= [];
278
- silgi.options.imports.presets.push(...getNitroImportsPreset());
279
- }
280
- await h3Framework(silgi, true);
281
- }
282
- function getNitroImportsPreset() {
283
- return [
284
- {
285
- from: "nitropack/runtime/internal/app",
286
- imports: ["useNitroApp"]
287
- },
288
- {
289
- from: "nitropack/runtime/internal/config",
290
- imports: ["useRuntimeConfig", "useAppConfig"]
291
- },
292
- {
293
- from: "nitropack/runtime/internal/plugin",
294
- imports: ["defineNitroPlugin", "nitroPlugin"]
295
- },
296
- {
297
- from: "nitropack/runtime/internal/cache",
298
- imports: [
299
- "defineCachedFunction",
300
- "defineCachedEventHandler",
301
- "cachedFunction",
302
- "cachedEventHandler"
303
- ]
304
- },
305
- {
306
- from: "nitropack/runtime/internal/storage",
307
- imports: ["useStorage"]
308
- },
309
- {
310
- from: "nitropack/runtime/internal/renderer",
311
- imports: ["defineRenderHandler"]
312
- },
313
- {
314
- from: "nitropack/runtime/internal/meta",
315
- imports: ["defineRouteMeta"]
316
- },
317
- {
318
- from: "nitropack/runtime/internal/route-rules",
319
- imports: ["getRouteRules"]
320
- },
321
- {
322
- from: "nitropack/runtime/internal/context",
323
- imports: ["useEvent"]
324
- },
325
- {
326
- from: "nitropack/runtime/internal/task",
327
- imports: ["defineTask", "runTask"]
328
- },
329
- {
330
- from: "nitropack/runtime/internal/error/utils",
331
- imports: ["defineNitroErrorHandler"]
332
- }
333
- ];
334
- }
335
-
336
- async function nuxtFramework(silgi, skip = false) {
337
- if (silgi.options.preset !== "nuxt" && skip === false)
338
- return;
339
- await nitroFramework(silgi, true);
340
- }
341
-
342
- const frameworkSetup = [emptyFramework, h3Framework, nitroFramework, nuxtFramework];
343
-
344
- async function registerModuleExportScan(silgi) {
345
- silgi.hook("prepare:schema.ts", async (options) => {
346
- for (const module of silgi.scanModules) {
347
- const moduleReExports = [];
348
- const moduleTypes = await promises.readFile(module.entryPath.replace(/\.mjs$/, "Types.d.ts"), "utf8").catch(() => "");
349
- const normalisedModuleTypes = moduleTypes.replace(/export\s*\{.*?\}/gs, (match) => match.replace(/\b(type|interface)\b/g, ""));
350
- for (const e of findTypeExports(normalisedModuleTypes)) {
351
- moduleReExports.push(e);
352
- }
353
- for (const e of findExports(normalisedModuleTypes)) {
354
- moduleReExports.push(e);
355
- }
356
- const hasTypeExport = (name) => moduleReExports.find((exp) => exp.names?.includes(name));
357
- const configKey = module.meta.configKey;
358
- const moduleName = module.meta.name || module.meta._packageName;
359
- options.importItems[configKey] = {
360
- import: [],
361
- from: module.meta._packageName ? moduleName : relativeWithDot(silgi.options.build.typesDir, module.entryPath)
362
- };
363
- if (hasTypeExport("ModuleOptions")) {
364
- const importName = `_${hash(`${configKey}ModuleOptions`)}`;
365
- options.importItems[configKey].import.push({
366
- name: `ModuleOptions as ${importName}`,
367
- type: true,
368
- key: importName
369
- });
370
- options.options.push({ key: configKey, value: importName });
371
- }
372
- if (hasTypeExport("ModuleRuntimeOptions")) {
373
- const importName = `_${hash(`${configKey}ModuleRuntimeOptions`)}`;
374
- options.importItems[configKey].import.push({
375
- name: `ModuleRuntimeOptions as ${importName}`,
376
- type: true,
377
- key: importName
378
- });
379
- options.runtimeOptions.push({ key: configKey, value: importName });
380
- }
381
- if (hasTypeExport("ModuleRuntimeShareds")) {
382
- const importName = `_${hash(`${configKey}ModuleRuntimeShareds`)}`;
383
- options.importItems[configKey].import.push({
384
- name: `ModuleRuntimeShareds as ${importName}`,
385
- type: true,
386
- key: importName
387
- });
388
- options.shareds.push({ key: configKey, value: importName });
389
- }
390
- if (hasTypeExport("ModuleEvents")) {
391
- const importName = `_${hash(`${configKey}ModuleEvents`)}`;
392
- options.importItems[configKey].import.push({
393
- name: `ModuleEvents as ${importName}`,
394
- type: true,
395
- key: importName
396
- });
397
- options.events.push({ key: configKey, value: importName });
398
- }
399
- if (hasTypeExport("ModuleRuntimeContexts")) {
400
- const importName = `_${hash(`${configKey}ModuleRuntimeContexts`)}`;
401
- options.importItems[configKey].import.push({
402
- name: `ModuleRuntimeContexts as ${importName}`,
403
- type: true,
404
- key: importName
405
- });
406
- options.contexts.push({ key: configKey, value: importName });
407
- }
408
- if (hasTypeExport("ModuleHooks")) {
409
- const importName = `_${hash(`${configKey}ModuleHooks`)}`;
410
- options.importItems[configKey].import.push({
411
- name: `ModuleHooks as ${importName}`,
412
- type: true,
413
- key: importName
414
- });
415
- options.hooks.push({ key: configKey, value: importName });
416
- }
417
- if (hasTypeExport("ModuleRuntimeHooks")) {
418
- const importName = `_${hash(`${configKey}RuntimeHooks`)}`;
419
- options.importItems[configKey].import.push({
420
- name: `ModuleRuntimeHooks as ${importName}`,
421
- type: true,
422
- key: importName
423
- });
424
- options.runtimeHooks.push({ key: configKey, value: importName });
425
- }
426
- if (hasTypeExport("ModuleRuntimeActions")) {
427
- const importName = `_${hash(`${configKey}ModuleRuntimeActions`)}`;
428
- options.importItems[configKey].import.push({
429
- name: `ModuleRuntimeActions as ${importName}`,
430
- type: true,
431
- key: importName
432
- });
433
- options.actions.push({ key: configKey, value: importName });
434
- }
435
- if (hasTypeExport("ModuleRuntimeMethods")) {
436
- const importName = `_${hash(`${configKey}ModuleRuntimeMethods`)}`;
437
- options.importItems[configKey].import.push({
438
- name: `ModuleRuntimeMethods as ${importName}`,
439
- type: true,
440
- key: importName
441
- });
442
- options.methods.push({ key: configKey, value: importName });
443
- }
444
- if (hasTypeExport("ModuleRuntimeRouteRules")) {
445
- const importName = `_${hash(`${configKey}ModuleRuntimeRouteRules`)}`;
446
- options.importItems[configKey].import.push({
447
- name: `ModuleRuntimeRouteRules as ${importName}`,
448
- type: true,
449
- key: importName
450
- });
451
- options.routeRules.push({ key: configKey, value: importName });
452
- }
453
- if (hasTypeExport("ModuleRuntimeRouteRulesConfig")) {
454
- const importName = `_${hash(`${configKey}ModuleRuntimeRouteRulesConfig`)}`;
455
- options.importItems[configKey].import.push({
456
- name: `ModuleRuntimeRouteRulesConfig as ${importName}`,
457
- type: true,
458
- key: importName
459
- });
460
- options.routeRulesConfig.push({ key: configKey, value: importName });
461
- }
462
- }
463
- });
464
- }
465
-
466
- async function loadSilgiModuleInstance(silgiModule) {
467
- if (typeof silgiModule === "string") {
468
- throw new TypeError(`Could not load \`${silgiModule}\`. Is it installed?`);
469
- }
470
- if (typeof silgiModule !== "function") {
471
- throw new TypeError(`Nuxt module should be a function: ${silgiModule}`);
472
- }
473
- return { silgiModule };
474
- }
475
- async function installModules(silgi, prepare = false) {
476
- silgi.options.isPreparingModules = prepare;
477
- const jiti = createJiti(silgi.options.rootDir, {
478
- alias: silgi.options.alias,
479
- fsCache: false,
480
- moduleCache: false
481
- });
482
- for (const module of silgi.scanModules) {
483
- if (hasInstalledModule(module.meta.configKey)) {
484
- silgi.logger.info(`Module ${module.meta.configKey} installed`);
485
- }
486
- try {
487
- const silgiModule = await jiti.import(module.entryPath, {
488
- default: true,
489
- conditions: silgi.options.conditions
490
- });
491
- if (silgiModule.name !== "silgiNormalizedModule") {
492
- silgi.scanModules = silgi.scanModules.filter((m) => m.entryPath !== module.entryPath);
493
- continue;
494
- }
495
- await installModule(silgiModule, silgi, prepare);
496
- } catch (err) {
497
- silgi.logger.error(err);
498
- }
499
- }
500
- silgi.options.isPreparingModules = false;
501
- }
502
- async function installModule(moduleToInstall, silgi = useSilgiCLI(), inlineOptions, prepare = false) {
503
- const { silgiModule } = await loadSilgiModuleInstance(moduleToInstall);
504
- const res = await silgiModule(inlineOptions || {}, silgi) ?? {};
505
- if (res === false) {
506
- return false;
507
- }
508
- const metaData = await silgiModule.getMeta?.();
509
- if (prepare) {
510
- return metaData;
511
- }
512
- const installedModule = silgi.scanModules.find((m) => m.meta.configKey === metaData?.configKey);
513
- if (installedModule) {
514
- installedModule.installed = true;
515
- } else {
516
- throw new Error(`Module ${metaData?.name} not found`);
517
- }
518
- }
519
-
520
- const MissingModuleMatcher = /Cannot find module\s+['"]?([^'")\s]+)['"]?/i;
521
- async function _resolveSilgiModule(silgiModule, silgi) {
522
- let resolvedModulePath;
523
- let buildTimeModuleMeta = {};
524
- const jiti = createJiti(silgi.options.rootDir, {
525
- alias: silgi.options.alias
526
- });
527
- if (typeof silgiModule === "string") {
528
- silgiModule = resolveAlias(silgiModule, silgi.options.alias);
529
- if (isRelative(silgiModule)) {
530
- silgiModule = resolve(silgi.options.rootDir, silgiModule);
531
- }
532
- try {
533
- const src = resolveModuleURL(silgiModule, {
534
- from: silgi.options.modulesDir.map((m) => directoryToURL(m.replace(/\/node_modules\/?$/, "/"))),
535
- suffixes: ["silgi", "silgi/index", "module", "module/index", "", "index"],
536
- extensions: [".js", ".mjs", ".cjs", ".ts", ".mts", ".cts"]
537
- // Maybe add https://github.com/unjs/exsolve/blob/dfff3e9bbc4a3a173a2d56b9b9ff731ab15598be/src/resolve.ts#L7
538
- // conditions: silgi.options.conditions,
539
- });
540
- resolvedModulePath = fileURLToPath(src);
541
- const resolvedSilgiModule = await jiti.import(src, { default: true });
542
- if (typeof resolvedSilgiModule !== "function") {
543
- throw new TypeError(`Nuxt module should be a function: ${silgiModule}.`);
544
- }
545
- silgiModule = await jiti.import(src, {
546
- default: true,
547
- conditions: silgi.options.conditions
548
- });
549
- const moduleMetadataPath = new URL("module.json", src);
550
- if (existsSync(moduleMetadataPath)) {
551
- buildTimeModuleMeta = JSON.parse(await promises.readFile(moduleMetadataPath, "utf-8"));
552
- } else {
553
- if (typeof silgiModule === "function") {
554
- const meta = await silgiModule.getMeta?.();
555
- const _exports = await scanExports(resolvedModulePath, true);
556
- buildTimeModuleMeta = {
557
- ...meta,
558
- exports: _exports.map(({ from, ...rest }) => rest)
559
- };
560
- }
561
- }
562
- } catch (error) {
563
- const code = error.code;
564
- if (code === "MODULE_NOT_FOUND" || code === "ERR_PACKAGE_PATH_NOT_EXPORTED" || code === "ERR_MODULE_NOT_FOUND" || code === "ERR_UNSUPPORTED_DIR_IMPORT" || code === "ENOTDIR") {
565
- throw new TypeError(`Could not load \`${silgiModule}\`. Is it installed?`);
566
- }
567
- if (code === "MODULE_NOT_FOUND" || code === "ERR_MODULE_NOT_FOUND") {
568
- const module = MissingModuleMatcher.exec(error.message)?.[1];
569
- if (module && !module.includes(silgiModule)) {
570
- throw new TypeError(`Error while importing module \`${silgiModule}\`: ${error}`);
571
- }
572
- }
573
- }
574
- }
575
- if (!buildTimeModuleMeta) {
576
- throw new Error(`Module ${silgiModule} is not a valid Silgi module`);
577
- }
578
- if (typeof silgiModule === "function") {
579
- if (silgi.scanModules.some((m) => m.meta?.configKey === buildTimeModuleMeta.configKey)) {
580
- throw new Error(`Module with key \`${buildTimeModuleMeta.configKey}\` already exists`);
581
- }
582
- const options = await silgiModule.getOptions?.() || {};
583
- if (options) {
584
- silgi.options._c12.config[buildTimeModuleMeta.configKey] = defu(
585
- silgi.options._c12.config[buildTimeModuleMeta.configKey] || {},
586
- options || {}
587
- );
588
- } else {
589
- throw new TypeError(`Could not load \`${silgiModule}\`. Is it installed?`);
590
- }
591
- silgi.scanModules.push({
592
- meta: buildTimeModuleMeta,
593
- entryPath: resolvedModulePath || "",
594
- installed: false,
595
- options
596
- });
597
- }
598
- }
599
- async function scanModules$1(silgi) {
600
- const _modules = [
601
- ...silgi.options._modules,
602
- ...silgi.options.modules
603
- ];
604
- for await (const mod of _modules) {
605
- await _resolveSilgiModule(mod, silgi);
606
- }
607
- const moduleMap = new Map(
608
- silgi.scanModules.map((m) => [m.meta?.configKey, m])
609
- );
610
- const graphData = createDependencyGraph(silgi.scanModules);
611
- const sortedKeys = topologicalSort(graphData);
612
- const modules = sortedKeys.map((key) => moduleMap.get(key)).filter((module) => Boolean(module));
613
- silgi.scanModules = modules;
614
- }
615
- function createDependencyGraph(modules) {
616
- const graph = /* @__PURE__ */ new Map();
617
- const inDegree = /* @__PURE__ */ new Map();
618
- modules.forEach((module) => {
619
- const key = module.meta?.configKey;
620
- if (key) {
621
- graph.set(key, /* @__PURE__ */ new Set());
622
- inDegree.set(key, 0);
623
- }
624
- });
625
- modules.forEach((module) => {
626
- const key = module.meta?.configKey;
627
- if (!key) {
628
- return;
629
- }
630
- const requiredDeps = module.meta?.requiredDependencies || [];
631
- const beforeDeps = module.meta?.beforeDependencies || [];
632
- const afterDeps = module.meta?.afterDependencies || [];
633
- const processedDeps = /* @__PURE__ */ new Set();
634
- requiredDeps.forEach((dep) => {
635
- if (!graph.has(dep)) {
636
- throw new Error(`Required dependency "${dep}" for module "${key}" is missing`);
637
- }
638
- graph.get(dep)?.add(key);
639
- inDegree.set(key, (inDegree.get(key) || 0) + 1);
640
- processedDeps.add(dep);
641
- });
642
- beforeDeps.forEach((dep) => {
643
- if (!graph.has(dep)) {
644
- return;
645
- }
646
- graph.get(key)?.add(dep);
647
- inDegree.set(dep, (inDegree.get(dep) || 0) + 1);
648
- });
649
- afterDeps.forEach((dep) => {
650
- if (processedDeps.has(dep)) {
651
- return;
652
- }
653
- if (!graph.has(dep)) {
654
- return;
655
- }
656
- graph.get(dep)?.add(key);
657
- inDegree.set(key, (inDegree.get(key) || 0) + 1);
658
- });
659
- });
660
- return { graph, inDegree };
661
- }
662
- function findCyclicDependencies(graph) {
663
- const visited = /* @__PURE__ */ new Set();
664
- const recursionStack = /* @__PURE__ */ new Set();
665
- const cycles = [];
666
- function dfs(node, path = []) {
667
- visited.add(node);
668
- recursionStack.add(node);
669
- path.push(node);
670
- for (const neighbor of graph.get(node) || []) {
671
- if (recursionStack.has(neighbor)) {
672
- const cycleStart = path.indexOf(neighbor);
673
- if (cycleStart !== -1) {
674
- cycles.push([...path.slice(cycleStart), neighbor]);
675
- }
676
- } else if (!visited.has(neighbor)) {
677
- dfs(neighbor, [...path]);
678
- }
679
- }
680
- recursionStack.delete(node);
681
- path.pop();
682
- }
683
- for (const node of graph.keys()) {
684
- if (!visited.has(node)) {
685
- dfs(node, []);
686
- }
687
- }
688
- return cycles;
689
- }
690
- function topologicalSort(graphData) {
691
- const { graph, inDegree } = graphData;
692
- const order = [];
693
- const queue = [];
694
- for (const [node, degree] of inDegree.entries()) {
695
- if (degree === 0) {
696
- queue.push(node);
697
- }
698
- }
699
- while (queue.length > 0) {
700
- const node = queue.shift();
701
- order.push(node);
702
- const neighbors = Array.from(graph.get(node) || []);
703
- for (const neighbor of neighbors) {
704
- const newDegree = (inDegree.get(neighbor) || 0) - 1;
705
- inDegree.set(neighbor, newDegree);
706
- if (newDegree === 0) {
707
- queue.push(neighbor);
708
- }
709
- }
710
- }
711
- if (order.length !== graph.size) {
712
- const cycles = findCyclicDependencies(graph);
713
- if (cycles.length > 0) {
714
- const cycleStr = cycles.map((cycle) => ` ${cycle.join(" -> ")}`).join("\n");
715
- throw new Error(`Circular dependencies detected:
716
- ${cycleStr}`);
717
- } else {
718
- const unresolvedModules = Array.from(graph.keys()).filter((key) => !order.includes(key));
719
- throw new Error(`Unable to resolve dependencies for modules: ${unresolvedModules.join(", ")}`);
720
- }
721
- }
722
- return order;
723
- }
724
-
725
- async function commands(silgi) {
726
- const commands2 = {
727
- ...silgi.options.commands
728
- };
729
- await silgi.callHook("prepare:commands", commands2);
730
- addTemplate({
731
- filename: "cli.json",
732
- where: ".silgi",
733
- write: true,
734
- getContents: () => JSON.stringify(commands2, null, 2)
735
- });
736
- silgi.commands = commands2;
737
- silgi.hook("prepare:schema.ts", async (object) => {
738
- const allTags = Object.values(commands2).reduce((acc, commandGroup) => {
739
- Object.values(commandGroup).forEach((command) => {
740
- if (command.tags) {
741
- command.tags.forEach((tag) => acc.add(tag));
742
- }
743
- });
744
- return acc;
745
- }, /* @__PURE__ */ new Set());
746
- const data = [
747
- "",
748
- generateTypes(
749
- await resolveSchema(
750
- {
751
- ...Object.fromEntries(Array.from(allTags.values()).map((tag) => [tag, "string"]))
752
- }
753
- ),
754
- {
755
- interfaceName: "SilgiCommandsExtended",
756
- addExport: false,
757
- addDefaults: false,
758
- allowExtraKeys: false,
759
- indentation: 0
760
- }
761
- ),
762
- ""
763
- ];
764
- object.customImports?.push(...data);
765
- });
766
- }
767
-
768
- function buildUriMap(silgi, currentPath = []) {
769
- const uriMap = /* @__PURE__ */ new Map();
770
- function traverse(node, path = []) {
771
- if (!node || typeof node !== "object")
772
- return;
773
- if (path.length === 4) {
774
- const basePath = path.join("/");
775
- let pathString = "";
776
- if (node.pathParams) {
777
- let paths = null;
778
- if (node.pathParams?._def?.typeName !== void 0) {
779
- try {
780
- const shape = node.pathParams?.shape;
781
- paths = shape ? Object.keys(shape) : null;
782
- } catch {
783
- paths = null;
784
- }
785
- }
786
- if (paths?.length) {
787
- pathString = paths.map((p) => `:${p}`).join("/");
788
- }
789
- }
790
- uriMap.set(basePath, pathString);
791
- return;
792
- }
793
- for (const key in node) {
794
- if (!["_type", "fields"].includes(key)) {
795
- traverse(node[key], [...path, key]);
796
- }
797
- }
798
- }
799
- traverse(silgi.schemas, currentPath);
800
- silgi.uris = defu$1(silgi.uris, Object.fromEntries(uriMap));
801
- return uriMap;
802
- }
803
-
804
- async function readScanFile(silgi) {
805
- const path = resolve(silgi.options.silgi.serverDir, "scan.ts");
806
- const context = await promises.readFile(path, { encoding: "utf-8" });
807
- silgi.unimport = createUnimport(silgi.options.imports || {});
808
- await silgi.unimport.init();
809
- const injectedResult = await silgi.unimport.injectImports(context, path);
810
- if (!injectedResult) {
811
- throw new Error("Failed to inject imports");
812
- }
813
- const jiti = createJiti(silgi.options.rootDir, {
814
- fsCache: false,
815
- moduleCache: false,
816
- debug: silgi.options.debug,
817
- alias: silgi.options.alias
818
- });
819
- try {
820
- if (silgi.options.commandType === "prepare") {
821
- globalThis.$silgiSharedRuntimeConfig = silgi.options.runtimeConfig;
822
- injectedResult.code = `globalThis.$silgiSharedRuntimeConfig = ${JSON.stringify(silgi.options.runtimeConfig)};
823
- ${injectedResult.code}`;
824
- injectedResult.code = injectedResult.code.replace(/runtimeConfig: \{\}/, `runtimeConfig: ${JSON.stringify(silgi.options.runtimeConfig)}`);
825
- }
826
- const scanFile = await jiti.evalModule(
827
- injectedResult.code,
828
- {
829
- filename: path,
830
- async: true,
831
- conditions: silgi.options.conditions
832
- },
833
- async (data, name) => {
834
- return (await silgi.unimport.injectImports(data, name)).code;
835
- }
836
- );
837
- silgi.uris = defu$1(silgi.uris, scanFile.uris) || {};
838
- silgi.schemas = defu$1(scanFile.schemas, scanFile.uris) || {};
839
- silgi.services = defu$1(scanFile.services, scanFile.uris) || {};
840
- silgi.shareds = defu$1(scanFile.shareds, scanFile.shareds) || {};
841
- silgi.modulesURIs = defu$1(scanFile.modulesURIs, scanFile.modulesURIs) || {};
842
- return {
843
- context,
844
- object: {
845
- schemas: scanFile.schemas,
846
- uris: scanFile.uris,
847
- services: scanFile.services,
848
- shareds: scanFile.shareds,
849
- modulesURIs: scanFile.modulesURIs
850
- },
851
- path
852
- };
853
- } catch (error) {
854
- if (silgi.options.debug) {
855
- console.error("Failed to read scan.ts file:", error);
856
- } else {
857
- if (error instanceof Error) {
858
- consola.withTag("silgi").info(error.message);
859
- }
860
- }
861
- return {
862
- context,
863
- object: {
864
- schemas: {},
865
- uris: {},
866
- services: {},
867
- shareds: {},
868
- modulesURIs: {}
869
- },
870
- path
871
- };
872
- }
873
- }
874
-
875
- async function prepareServerFiles(silgi) {
876
- const importItems = {
877
- "silgi": {
878
- import: [
879
- { name: "createSilgi", key: "createSilgi" },
880
- { name: "createShared", key: "createShared" }
881
- ],
882
- from: "silgi"
883
- },
884
- "silgi/types": {
885
- import: [
886
- { name: "SilgiRuntimeOptions", type: true, key: "SilgiRuntimeOptions" },
887
- { name: "FrameworkContext", type: true, key: "FrameworkContext" }
888
- ],
889
- from: "silgi/types"
890
- },
891
- "#silgi/vfs": {
892
- import: [],
893
- from: "./vfs"
894
- },
895
- "configs.ts": {
896
- import: [
897
- {
898
- name: "cliConfigs",
899
- type: false,
900
- key: "cliConfigs"
901
- }
902
- ],
903
- from: "./configs.ts"
904
- }
905
- };
906
- const scanned = {
907
- uris: {},
908
- services: [],
909
- shareds: [
910
- `createShared({
911
- modulesURIs,
912
- })`
913
- ],
914
- schemas: [],
915
- modulesURIs: {},
916
- customImports: [],
917
- importItems
918
- };
919
- if (silgi.uris) {
920
- defu$1(scanned.uris, silgi.uris);
921
- }
922
- if (silgi.modulesURIs) {
923
- defu$1(scanned.modulesURIs, silgi.modulesURIs);
924
- }
925
- await silgi.callHook("prepare:scan.ts", scanned);
926
- if (importItems["#silgi/vfs"].import.length === 0) {
927
- delete importItems["#silgi/vfs"];
928
- }
929
- if (scanned.services.length > 0) {
930
- importItems.silgi.import.push({ name: "mergeServices", key: "mergeServices" });
931
- }
932
- if (scanned.shareds.length > 0) {
933
- importItems.silgi.import.push({ name: "mergeShared", key: "mergeShared" });
934
- }
935
- if (scanned.schemas.length > 0) {
936
- importItems.silgi.import.push({ name: "mergeSchemas", key: "mergeSchemas" });
937
- }
938
- for (const key in importItems) {
939
- importItems[key].import = deduplicateImportsByKey(importItems[key].import);
940
- }
941
- const importsContent = [
942
- ...Object.entries(importItems).map(([_name, { from, import: imports }]) => {
943
- if (silgi.options.typescript.removeFileExtension) {
944
- from = from.replace(/\.(js|ts|mjs|cjs|jsx|tsx)$/, "");
945
- }
946
- return `import { ${imports.map(({ type, name }) => type ? `type ${name}` : name).join(", ")} } from '${from}'`;
947
- }),
948
- "",
949
- ...scanned.customImports,
950
- ""
951
- ];
952
- const importData = [
953
- `export const uris = ${JSON.stringify(scanned.uris, null, 2)}`,
954
- "",
955
- `export const modulesURIs = ${JSON.stringify(scanned.modulesURIs, null, 2)}`,
956
- "",
957
- scanned.schemas.length > 0 ? "export const schemas = mergeSchemas([" : "export const schemas = {",
958
- ...scanned.schemas.map((name) => {
959
- return ` ${name},`;
960
- }),
961
- scanned.schemas.length > 0 ? "])" : "}",
962
- "",
963
- scanned.services.length > 0 ? "export const services = mergeServices([" : "export const services = {",
964
- ...scanned.services.map((name) => {
965
- return ` ${name},`;
966
- }),
967
- scanned.services.length > 0 ? "])" : "}",
968
- "",
969
- scanned.shareds.length > 0 ? "export const shareds = mergeShared([" : "export const shareds = {",
970
- ...scanned.shareds.map((name) => {
971
- return ` ${name},`;
972
- }),
973
- scanned.shareds.length > 0 ? "])" : "}",
974
- ""
975
- ];
976
- await silgi.callHook("after:prepare:scan.ts", importData);
977
- importData.unshift(...importsContent);
978
- return importData;
979
- }
980
- function deduplicateImportsByKey(imports) {
981
- const seenKeys = /* @__PURE__ */ new Map();
982
- return imports.filter((item) => {
983
- if (seenKeys.has(item.key)) {
984
- return false;
985
- }
986
- seenKeys.set(item.key, true);
987
- return true;
988
- });
989
- }
990
-
991
- async function writeScanFiles(silgi) {
992
- const data = await prepareServerFiles(silgi);
993
- await writeFile(
994
- resolve(silgi.options.silgi.serverDir, "scan.ts"),
995
- data.join("\n")
996
- );
997
- await readScanFile(silgi);
998
- buildUriMap(silgi);
999
- parseServices(silgi);
1000
- silgi.hook("prepare:scan.ts", (file) => {
1001
- file.uris = {
1002
- ...file.uris,
1003
- ...silgi.uris
1004
- };
1005
- file.modulesURIs = {
1006
- ...file.modulesURIs,
1007
- ...silgi.modulesURIs
1008
- };
1009
- });
1010
- }
1011
-
1012
- function resolveIgnorePatterns(silgi, relativePath) {
1013
- if (!silgi) {
1014
- return [];
1015
- }
1016
- const ignorePatterns = silgi.options.ignore.flatMap((s) => resolveGroupSyntax(s));
1017
- const nuxtignoreFile = join(silgi.options.rootDir, ".nuxtignore");
1018
- if (existsSync(nuxtignoreFile)) {
1019
- const contents = readFileSync(nuxtignoreFile, "utf-8");
1020
- ignorePatterns.push(...contents.trim().split(/\r?\n/));
1021
- }
1022
- return ignorePatterns;
1023
- }
1024
- function isIgnored(pathname, silgi, _stats) {
1025
- if (!silgi) {
1026
- return false;
1027
- }
1028
- if (!silgi._ignore) {
1029
- silgi._ignore = ignore(silgi.options.ignoreOptions);
1030
- silgi._ignore.add(resolveIgnorePatterns(silgi));
1031
- }
1032
- const relativePath = relative(silgi.options.rootDir, pathname);
1033
- if (relativePath[0] === "." && relativePath[1] === ".") {
1034
- return false;
1035
- }
1036
- return !!(relativePath && silgi._ignore.ignores(relativePath));
1037
- }
1038
- function resolveGroupSyntax(group) {
1039
- let groups = [group];
1040
- while (groups.some((group2) => group2.includes("{"))) {
1041
- groups = groups.flatMap((group2) => {
1042
- const [head, ...tail] = group2.split("{");
1043
- if (tail.length) {
1044
- const [body = "", ...rest] = tail.join("{").split("}");
1045
- return body.split(",").map((part) => `${head}${part}${rest.join("")}`);
1046
- }
1047
- return group2;
1048
- });
1049
- }
1050
- return groups;
1051
- }
1052
-
1053
- class SchemaParser {
1054
- options = {
1055
- debug: false
1056
- };
1057
- /**
1058
- *
1059
- */
1060
- constructor(options) {
1061
- this.options = {
1062
- ...this.options,
1063
- ...options
1064
- };
1065
- }
1066
- parseExports(content, filePath) {
1067
- const ast = parseSync(content, { sourceType: "module", sourceFilename: filePath });
1068
- if (this.options.debug)
1069
- writeFileSync(`${filePath}.ast.json`, JSON.stringify(ast.program, null, 2));
1070
- return {
1071
- exportVariables: (search, path) => this.parseTypeDeclarations(ast, search, path),
1072
- parseInterfaceDeclarations: (search, path) => this.parseInterfaceDeclarations(ast, search, path)
1073
- // parsePlugin: (path: string) => this.parsePlugin(ast, path),
1074
- };
1075
- }
1076
- parseVariableDeclaration(ast, path) {
1077
- const silgi = useSilgiCLI();
1078
- if (ast.program.body.length === 0) {
1079
- silgi.errors.push({
1080
- type: "Parser",
1081
- path
1082
- });
1083
- consola$1.warn("This file has a problem:", path);
1084
- }
1085
- const variableDeclarations = ast.program.body.filter((i) => i.type === "ExportNamedDeclaration").filter((i) => i.declaration?.type === "VariableDeclaration");
1086
- return variableDeclarations;
1087
- }
1088
- parseTSInterfaceDeclaration(ast, path = "") {
1089
- const silgi = useSilgiCLI();
1090
- if (ast.program.body.length === 0) {
1091
- silgi.errors.push({
1092
- type: "Parser",
1093
- path
1094
- });
1095
- consola$1.warn("This file has a problem:", path);
1096
- }
1097
- const interfaceDeclarations = ast.program.body.filter((i) => i.type === "ExportNamedDeclaration").filter((i) => i.declaration?.type === "TSInterfaceDeclaration");
1098
- return interfaceDeclarations;
1099
- }
1100
- parseTypeDeclarations(ast, find = "", path = "") {
1101
- const data = [];
1102
- const variableDeclarations = this.parseVariableDeclaration(ast, path);
1103
- for (const item of variableDeclarations) {
1104
- for (const declaration of item.declaration.declarations) {
1105
- if (declaration.init?.callee?.name === find) {
1106
- const options = {};
1107
- if (declaration.init.arguments) {
1108
- for (const argument of declaration.init.arguments) {
1109
- for (const propertie of argument.properties) {
1110
- if (propertie.key.name === "name")
1111
- options.pluginName = propertie.value.value;
1112
- }
1113
- }
1114
- }
1115
- for (const key in declaration.init.properties) {
1116
- const property = declaration.init.properties[key];
1117
- if (property.type === "ObjectProperty") {
1118
- if (property.key.name === "options") {
1119
- for (const key2 in property.value.properties) {
1120
- const option = property.value.properties[key2];
1121
- if (option.type === "ObjectProperty") {
1122
- options[option.key.name] = option.value.value;
1123
- }
1124
- }
1125
- }
1126
- }
1127
- }
1128
- options.type = false;
1129
- data.push({
1130
- exportName: declaration.id.name,
1131
- options,
1132
- // object: declaration.init,
1133
- path
1134
- });
1135
- }
1136
- }
1137
- }
1138
- return data;
1139
- }
1140
- parseInterfaceDeclarations(ast, find = "", path = "") {
1141
- const data = [];
1142
- for (const item of this.parseTSInterfaceDeclaration(ast, path)) {
1143
- if (!item?.declaration?.extends)
1144
- continue;
1145
- for (const declaration of item?.declaration?.extends) {
1146
- if (declaration.expression.name === find) {
1147
- const options = {};
1148
- options.type = true;
1149
- data.push({
1150
- exportName: item.declaration.id.name,
1151
- options,
1152
- // object: declaration.init,
1153
- path
1154
- });
1155
- }
1156
- }
1157
- }
1158
- return data;
1159
- }
1160
- // private parsePlugin(ast: any, path: string = '') {
1161
- // const data = {
1162
- // export: [],
1163
- // name: '',
1164
- // path: '',
1165
- // } as DataTypePlugin
1166
- // for (const item of this.parseVariableDeclaration(ast)) {
1167
- // for (const declaration of item.declaration.declarations) {
1168
- // if (declaration.init.callee?.name === 'defineSilgiModule') {
1169
- // if (declaration.init.arguments) {
1170
- // for (const argument of declaration.init.arguments) {
1171
- // for (const propertie of argument.properties) {
1172
- // if (propertie.key.name === 'name')
1173
- // data.name = propertie.value.value
1174
- // }
1175
- // }
1176
- // }
1177
- // data.export.push({
1178
- // name: data.name,
1179
- // as: camelCase(`${data.name}DefineSilgiModule`),
1180
- // type: false,
1181
- // })
1182
- // }
1183
- // }
1184
- // }
1185
- // for (const item of this.parseTSInterfaceDeclaration(ast)) {
1186
- // if (!item?.declaration?.extends)
1187
- // continue
1188
- // for (const declaration of item?.declaration?.extends) {
1189
- // if (declaration.expression.name === 'ModuleOptions') {
1190
- // data.export.push({
1191
- // name: item.declaration.id.name,
1192
- // as: camelCase(`${data.name}ModuleOptions`),
1193
- // type: true,
1194
- // })
1195
- // }
1196
- // // TODO add other plugins
1197
- // }
1198
- // }
1199
- // data.path = path
1200
- // return data
1201
- // }
1202
- }
1203
-
1204
- const processedScanItems = /* @__PURE__ */ new Map();
1205
- const processedSchemaItems = /* @__PURE__ */ new Map();
1206
- async function scanFiles$1(silgi, watchFiles) {
1207
- const isWatch = watchFiles && watchFiles.length > 0;
1208
- const filePaths = /* @__PURE__ */ new Set();
1209
- const scannedPaths = [];
1210
- const dir = silgi.options.serverDir;
1211
- const files = isWatch ? watchFiles : (await globby(dir, { cwd: silgi.options.rootDir, ignore: silgi.options.ignore })).sort();
1212
- if (files.length) {
1213
- const siblings = await readdir(dirname(dir)).catch(() => []);
1214
- const directory = basename(dir);
1215
- if (!siblings.includes(directory)) {
1216
- const directoryLowerCase = directory.toLowerCase();
1217
- const caseCorrected = siblings.find((sibling) => sibling.toLowerCase() === directoryLowerCase);
1218
- if (caseCorrected) {
1219
- const original = relative(silgi.options.serverDir, dir);
1220
- const corrected = relative(silgi.options.serverDir, join(dirname(dir), caseCorrected));
1221
- consola.warn(`Components not scanned from \`~/${corrected}\`. Did you mean to name the directory \`~/${original}\` instead?`);
1222
- }
1223
- }
1224
- }
1225
- if (isWatch && watchFiles) {
1226
- for (const file of watchFiles) {
1227
- const filePath = resolve(dir, file);
1228
- processedScanItems.delete(filePath);
1229
- processedSchemaItems.delete(filePath);
1230
- }
1231
- }
1232
- for (const _file of files) {
1233
- const filePath = resolve(dir, _file);
1234
- if (scannedPaths.find((d) => filePath.startsWith(withTrailingSlash(d))) || isIgnored(filePath, silgi)) {
1235
- continue;
1236
- }
1237
- if (filePaths.has(filePath)) {
1238
- continue;
1239
- }
1240
- filePaths.add(filePath);
1241
- if (silgi.options.extensions.includes(extname(filePath))) {
1242
- const parser = new SchemaParser({
1243
- debug: false
1244
- });
1245
- const readfile = await readFile(filePath, "utf-8");
1246
- const { exportVariables, parseInterfaceDeclarations } = parser.parseExports(readfile, filePath);
1247
- const createServices = exportVariables("createService", filePath);
1248
- if (hasError("Parser", silgi)) {
1249
- return;
1250
- }
1251
- const scanTS = [];
1252
- const schemaTS = [];
1253
- if (createServices.length > 0) {
1254
- scanTS.push(...createServices.map(({ exportName, path }) => {
1255
- silgi.options.devServer.watch.push(path);
1256
- const randomString = hash(basename(path) + exportName);
1257
- const _name = `_v${randomString}`;
1258
- return { exportName, path, _name, type: "service" };
1259
- }));
1260
- }
1261
- const createSchemas = exportVariables("createSchema", filePath);
1262
- if (hasError("Parser", silgi)) {
1263
- return;
1264
- }
1265
- if (createSchemas.length > 0) {
1266
- scanTS.push(...createSchemas.map(({ exportName, path }) => {
1267
- silgi.options.devServer.watch.push(path);
1268
- const randomString = hash(basename(path) + exportName);
1269
- const _name = `_v${randomString}`;
1270
- return { exportName, path, _name, type: "schema" };
1271
- }));
1272
- }
1273
- const createShareds = exportVariables("createShared", filePath);
1274
- if (hasError("Parser", silgi)) {
1275
- return;
1276
- }
1277
- if (createShareds.length > 0) {
1278
- scanTS.push(...createShareds.map(({ exportName, path }) => {
1279
- silgi.options.devServer.watch.push(path);
1280
- const randomString = hash(basename(path) + exportName);
1281
- const _name = `_v${randomString}`;
1282
- return { exportName, path, _name, type: "shared" };
1283
- }));
1284
- }
1285
- const sharedsTypes = parseInterfaceDeclarations("ExtendShared", filePath);
1286
- if (hasError("Parser", silgi)) {
1287
- return;
1288
- }
1289
- if (sharedsTypes.length > 0) {
1290
- schemaTS.push(...sharedsTypes.map(({ exportName, path }) => {
1291
- silgi.options.devServer.watch.push(path);
1292
- const randomString = hash(basename(path) + exportName);
1293
- const _name = `_v${randomString}`;
1294
- return { exportName, path, _name, type: "shared" };
1295
- }));
1296
- }
1297
- const contextTypes = parseInterfaceDeclarations("ExtendContext", filePath);
1298
- if (hasError("Parser", silgi)) {
1299
- return;
1300
- }
1301
- if (contextTypes.length > 0) {
1302
- schemaTS.push(...contextTypes.map(({ exportName, path }) => {
1303
- silgi.options.devServer.watch.push(path);
1304
- const randomString = hash(basename(path) + exportName);
1305
- const _name = `_v${randomString}`;
1306
- return { exportName, path, _name, type: "context" };
1307
- }));
1308
- }
1309
- silgi.hook("prepare:scan.ts", (options) => {
1310
- for (const { exportName, path, _name, type } of scanTS) {
1311
- const itemKey = `${path}:${exportName}`;
1312
- if (!processedScanItems.has(path)) {
1313
- processedScanItems.set(path, /* @__PURE__ */ new Set());
1314
- }
1315
- if (processedScanItems.get(path).has(itemKey)) {
1316
- continue;
1317
- }
1318
- processedScanItems.get(path).add(itemKey);
1319
- switch (type) {
1320
- case "service":
1321
- options.services.push(_name);
1322
- break;
1323
- case "shared":
1324
- options.shareds.push(_name);
1325
- break;
1326
- case "schema":
1327
- options.schemas.push(_name);
1328
- break;
1329
- }
1330
- addImport(options, path, exportName, _name, silgi.options.silgi.serverDir);
1331
- }
1332
- });
1333
- silgi.hook("prepare:schema.ts", (options) => {
1334
- for (const { exportName, path, _name, type } of schemaTS) {
1335
- const itemKey = `${path}:${exportName}`;
1336
- if (!processedSchemaItems.has(path)) {
1337
- processedSchemaItems.set(path, /* @__PURE__ */ new Set());
1338
- }
1339
- if (processedSchemaItems.get(path).has(itemKey)) {
1340
- continue;
1341
- }
1342
- processedSchemaItems.get(path).add(itemKey);
1343
- if (type === "shared") {
1344
- options.shareds.push({
1345
- key: _name,
1346
- value: _name
1347
- });
1348
- } else if (type === "context") {
1349
- options.contexts.push({
1350
- key: _name,
1351
- value: _name
1352
- });
1353
- }
1354
- addImport(options, path, exportName, _name, silgi.options.silgi.serverDir);
1355
- }
1356
- });
1357
- }
1358
- }
1359
- }
1360
- function addImport(options, path, exportName, _name, serverDir) {
1361
- const existingItem = options.importItems[path]?.import.find((item) => item.key === _name);
1362
- if (existingItem)
1363
- return;
1364
- options.importItems[path] ??= {
1365
- import: [],
1366
- from: relativeWithDot(serverDir, path)
1367
- };
1368
- options.importItems[path].import.push({
1369
- name: `${exportName} as ${_name}`,
1370
- key: _name
1371
- });
1372
- }
1373
-
1374
- async function createStorageCLI(silgi) {
1375
- const storage = createStorage();
1376
- const mounts = klona({
1377
- ...silgi.options.storage,
1378
- ...silgi.options.devStorage
1379
- });
1380
- for (const [path, opts] of Object.entries(mounts)) {
1381
- if (opts.driver) {
1382
- const driver = await import(builtinDrivers[opts.driver] || opts.driver).then((r) => r.default || r);
1383
- storage.mount(path, driver(opts));
1384
- } else {
1385
- silgi.logger.warn(`No \`driver\` set for storage mount point "${path}".`);
1386
- }
1387
- }
1388
- return storage;
1389
- }
1390
-
1391
- const vueShim = {
1392
- filename: "delete/testtest.d.ts",
1393
- where: ".silgi",
1394
- getContents: ({ app }) => {
1395
- if (!app.options.typescript.shim) {
1396
- return "";
1397
- }
1398
- return [
1399
- "declare module '*.vue' {",
1400
- " import { DefineComponent } from 'vue'",
1401
- " const component: DefineComponent<{}, {}, any>",
1402
- " export default component",
1403
- "}"
1404
- ].join("\n");
1405
- }
1406
- };
1407
- const pluginsDeclaration = {
1408
- filename: "delete/testtest1.d.ts",
1409
- where: ".silgi",
1410
- getContents: async () => {
1411
- return `
1412
- declare module 'nuxt' {
1413
- interface NuxtApp {
1414
- $myPlugin: any;
1415
- }
1416
- }
1417
- `;
1418
- }
1419
- };
1420
-
1421
- const defaultTemplates = {
1422
- __proto__: null,
1423
- pluginsDeclaration: pluginsDeclaration,
1424
- vueShim: vueShim
1425
- };
1426
-
1427
- const postTemplates = [
1428
- pluginsDeclaration.filename
1429
- ];
1430
- const logger = useLogger("silgi");
1431
- async function generateApp(app, options = {}) {
1432
- app.templates = Object.values(defaultTemplates).concat(app.options.build.templates);
1433
- await app.callHook("app:templates", app);
1434
- app.templates = app.templates.map((tmpl) => {
1435
- const dir = tmpl.where === ".silgi" ? app.options.build.dir : tmpl.where === "server" ? app.options.silgi.serverDir : tmpl.where === "client" ? app.options.silgi.clientDir : app.options.silgi.vfsDir;
1436
- return normalizeTemplate(tmpl, dir);
1437
- });
1438
- const filteredTemplates = {
1439
- pre: [],
1440
- post: []
1441
- };
1442
- for (const template of app.templates) {
1443
- if (options.filter && !options.filter(template)) {
1444
- continue;
1445
- }
1446
- const key = template.filename && postTemplates.includes(template.filename) ? "post" : "pre";
1447
- filteredTemplates[key].push(template);
1448
- }
1449
- const templateContext = { app };
1450
- const writes = [];
1451
- const dirs = /* @__PURE__ */ new Set();
1452
- const changedTemplates = [];
1453
- async function processTemplate(template) {
1454
- const dir = template.where === ".silgi" ? app.options.build.dir : template.where === "server" ? app.options.silgi.serverDir : template.where === "client" ? app.options.silgi.clientDir : app.options.silgi.vfsDir;
1455
- const fullPath = template.dst || resolve(dir, template.filename);
1456
- const start = performance.now();
1457
- const contents = await compileTemplate(template, templateContext).catch((e) => {
1458
- logger.error(`Could not compile template \`${template.filename}\`.`);
1459
- logger.error(e);
1460
- throw e;
1461
- });
1462
- template.modified = true;
1463
- if (template.modified) {
1464
- changedTemplates.push(template);
1465
- }
1466
- const perf = performance.now() - start;
1467
- const setupTime = Math.round(perf * 100) / 100;
1468
- if (app.options.debug || setupTime > 500) {
1469
- logger.info(`Compiled \`${template.filename}\` in ${setupTime}ms`);
1470
- }
1471
- if (template.modified && template.write) {
1472
- dirs.add(dirname(fullPath));
1473
- writes.push(() => writeFileSync(fullPath, contents, "utf8"));
1474
- }
1475
- }
1476
- await Promise.allSettled(filteredTemplates.pre.map(processTemplate));
1477
- await Promise.allSettled(filteredTemplates.post.map(processTemplate));
1478
- for (const dir of dirs) {
1479
- mkdirSync(dir, { recursive: true });
1480
- }
1481
- for (const write of writes) {
1482
- write();
1483
- }
1484
- if (changedTemplates.length) {
1485
- await app.callHook("app:templatesGenerated", app, changedTemplates, options);
1486
- }
1487
- }
1488
- async function compileTemplate(template, ctx) {
1489
- delete ctx.utils;
1490
- if (template.src) {
1491
- try {
1492
- return await promises.readFile(template.src, "utf-8");
1493
- } catch (err) {
1494
- logger.error(`[nuxt] Error reading template from \`${template.src}\``);
1495
- throw err;
1496
- }
1497
- }
1498
- if (template.getContents) {
1499
- return template.getContents({
1500
- ...ctx,
1501
- options: template.options
1502
- });
1503
- }
1504
- throw new Error(`[nuxt] Invalid template. Templates must have either \`src\` or \`getContents\`: ${JSON.stringify(template)}`);
1505
- }
1506
-
1507
- async function installPackages(silgi) {
1508
- const packages = {
1509
- dependencies: {
1510
- "@fastify/deepmerge": peerDependencies["@fastify/deepmerge"],
1511
- "@silgi/ecosystem": peerDependencies["@silgi/ecosystem"],
1512
- ...silgi.options.installPackages?.dependencies
1513
- },
1514
- devDependencies: {
1515
- ...silgi.options.installPackages?.devDependencies
1516
- }
1517
- };
1518
- await silgi.callHook("prepare:installPackages", packages);
1519
- if (silgi.options.preset === "npm-package") {
1520
- packages.devDependencies = {
1521
- ...packages.devDependencies,
1522
- ...packages.dependencies
1523
- };
1524
- packages.dependencies = {};
1525
- }
1526
- addTemplate({
1527
- filename: "install.json",
1528
- where: ".silgi",
1529
- write: true,
1530
- getContents: () => JSON.stringify(packages, null, 2)
1531
- });
1532
- }
1533
-
1534
- function useCLIRuntimeConfig(silgi) {
1535
- const _sharedRuntimeConfig = initRuntimeConfig(silgi.options.envOptions, silgi.options.runtimeConfig);
1536
- silgi.options.runtimeConfig = _sharedRuntimeConfig;
1537
- silgi.hook("prepare:configs.ts", (data) => {
1538
- data.runtimeConfig = _sharedRuntimeConfig;
1539
- silgi.options.envOptions = silgi.options.envOptions;
1540
- });
1541
- return _sharedRuntimeConfig;
1542
- }
1543
-
1544
- const GLOB_SCAN_PATTERN = "**/*.{js,mjs,cjs,ts,mts,cts,tsx,jsx}";
1545
- async function scanAndSyncOptions(silgi) {
1546
- const scannedModules = await scanModules(silgi);
1547
- silgi.options.modules = silgi.options.modules || [];
1548
- for (const modPath of scannedModules) {
1549
- if (!silgi.options.modules.includes(modPath)) {
1550
- silgi.options.modules.push(modPath);
1551
- }
1552
- }
1553
- }
1554
- async function scanModules(silgi) {
1555
- const files = await scanFiles(silgi, "silgi/modules");
1556
- return files.map((f) => f.fullPath);
1557
- }
1558
- async function scanFiles(silgi, name) {
1559
- const files = await Promise.all(
1560
- silgi.options.scanDirs.map((dir) => scanDir(silgi, dir, name))
1561
- ).then((r) => r.flat());
1562
- return files;
1563
- }
1564
- async function scanDir(silgi, dir, name) {
1565
- const fileNames = await globby(join(name, GLOB_SCAN_PATTERN), {
1566
- cwd: dir,
1567
- dot: true,
1568
- ignore: silgi.options.ignore,
1569
- absolute: true
1570
- });
1571
- return fileNames.map((fullPath) => {
1572
- return {
1573
- fullPath,
1574
- path: relative(join(dir, name), fullPath)
1575
- };
1576
- }).sort((a, b) => a.path.localeCompare(b.path));
1577
- }
1578
-
1579
- async function createSilgiCLI(config = {}, opts = {}) {
1580
- const options = await loadOptions(config, opts);
1581
- await prepareEnv(options);
1582
- const hooks = createHooks();
1583
- const silgi = {
1584
- modulesURIs: {},
1585
- scannedURIs: /* @__PURE__ */ new Map(),
1586
- services: {},
1587
- uris: {},
1588
- shareds: {},
1589
- schemas: {},
1590
- unimport: void 0,
1591
- options,
1592
- hooks,
1593
- errors: [],
1594
- commands: {},
1595
- _requiredModules: {},
1596
- logger: consola.withTag("silgi"),
1597
- close: () => silgi.hooks.callHook("close", silgi),
1598
- storage: void 0,
1599
- scanModules: [],
1600
- templates: [],
1601
- callHook: hooks.callHook,
1602
- addHooks: hooks.addHooks,
1603
- hook: hooks.hook,
1604
- async updateConfig(_config) {
1605
- },
1606
- routeRules: void 0
1607
- };
1608
- const routeRules = createRouteRules();
1609
- routeRules.importRules(options.routeRules ?? {});
1610
- silgi.routeRules = routeRules;
1611
- useCLIRuntimeConfig(silgi);
1612
- if (silgiCLICtx.tryUse()) {
1613
- silgiCLICtx.unset();
1614
- silgiCLICtx.set(silgi);
1615
- } else {
1616
- silgiCLICtx.set(silgi);
1617
- silgi.hook("close", () => silgiCLICtx.unset());
1618
- }
1619
- if (silgi.options.debug) {
1620
- createDebugger(silgi.hooks, { tag: "silgi" });
1621
- silgi.options.plugins.push({
1622
- path: join(runtimeDir, "internal/debug"),
1623
- packageImport: "silgi/runtime/internal/debug"
1624
- });
1625
- }
1626
- for (const framework of frameworkSetup) {
1627
- await framework(silgi);
1628
- }
1629
- await scanAndSyncOptions(silgi);
1630
- await scanModules$1(silgi);
1631
- await scanFiles$1(silgi);
1632
- if (hasError$1("Parser", silgi)) {
1633
- console.error("Please fix type errors before continuing");
1634
- process.exit(1);
1635
- }
1636
- await installModules(silgi, true);
1637
- await writeScanFiles(silgi);
1638
- silgi.storage = await createStorageCLI(silgi);
1639
- silgi.hooks.hook("close", async () => {
1640
- await silgi.storage.dispose();
1641
- });
1642
- if (silgi.options.logLevel !== void 0) {
1643
- silgi.logger.level = silgi.options.logLevel;
1644
- }
1645
- silgi.hooks.addHooks(silgi.options.hooks);
1646
- await installModules(silgi);
1647
- await silgi.hooks.callHook("scanFiles:done", silgi);
1648
- await commands(silgi);
1649
- await installPackages(silgi);
1650
- await generateApp(silgi);
1651
- if (silgi.options.imports) {
1652
- silgi.options.imports.dirs ??= [];
1653
- silgi.options.imports.dirs = silgi.options.imports.dirs.map((dir) => {
1654
- if (typeof dir === "string") {
1655
- if (dir.startsWith("!")) {
1656
- return `!${resolveSilgiPath(dir.slice(1), options, silgi.options.rootDir)}`;
1657
- }
1658
- return resolveSilgiPath(dir, options, silgi.options.rootDir);
1659
- }
1660
- return dir;
1661
- });
1662
- silgi.options.imports.presets.push({
1663
- from: "silgi/types",
1664
- imports: autoImportTypes.map((type) => type),
1665
- type: true
1666
- });
1667
- silgi.options.imports.presets.push({
1668
- from: "silgi/types",
1669
- imports: autoImportTypes.map((type) => type),
1670
- type: true
1671
- });
1672
- silgi.options.imports.presets.push({
1673
- from: "silgi/runtime/internal/ofetch",
1674
- imports: ["createSilgiFetch", "silgi$fetch"]
1675
- });
1676
- silgi.unimport = createUnimport(silgi.options.imports);
1677
- await silgi.unimport.init();
1678
- }
1679
- await registerModuleExportScan(silgi);
1680
- await writeScanFiles(silgi);
1681
- return silgi;
1682
- }
1683
-
1684
- function serializeToJs(obj, indent = 2, level = 0) {
1685
- if (obj === null || obj === void 0) {
1686
- return obj === void 0 ? "undefined as any" : String(obj);
1687
- }
1688
- if (typeof obj === "function") {
1689
- return obj.toString();
1690
- }
1691
- if (typeof obj !== "object") {
1692
- if (typeof obj === "string") {
1693
- if (obj.startsWith("runtime.")) {
1694
- return obj;
1695
- }
1696
- return `'${obj.replace(/'/g, "\\'")}'`;
1697
- }
1698
- return String(obj);
1699
- }
1700
- if (Array.isArray(obj)) {
1701
- if (obj.length === 0)
1702
- return "[]";
1703
- const items = obj.map((item) => serializeToJs(item, indent, level + 1)).join(`,
1704
- ${" ".repeat((level + 1) * indent)}`);
1705
- return `[
1706
- ${" ".repeat((level + 1) * indent)}${items}
1707
- ${" ".repeat(level * indent)}]`;
1708
- }
1709
- const entries = Object.entries(obj);
1710
- if (entries.length === 0)
1711
- return "{}";
1712
- const props = entries.map(([key, value]) => {
1713
- const keyStr = /^[a-z_$][\w$]*$/i.test(key) ? key : `'${key}'`;
1714
- return `${keyStr}: ${serializeToJs(value, indent, level + 1)}`;
1715
- }).join(`,
1716
- ${" ".repeat((level + 1) * indent)}`);
1717
- return `{
1718
- ${" ".repeat((level + 1) * indent)}${props}
1719
- ${" ".repeat(level * indent)}}`;
1720
- }
1721
- async function prepareConfigs(silgi) {
1722
- const _data = {
1723
- runtimeConfig: {}
1724
- };
1725
- for (const module of silgi.scanModules) {
1726
- if (module.meta.cliToRuntimeOptionsKeys && module.meta.cliToRuntimeOptionsKeys?.length > 0) {
1727
- for (const key of module.meta.cliToRuntimeOptionsKeys) {
1728
- _data[module.meta.configKey] = {
1729
- ..._data[module.meta.configKey],
1730
- [key]: module.options[key]
1731
- };
1732
- }
1733
- } else {
1734
- _data[module.meta.configKey] = {};
1735
- }
1736
- }
1737
- await silgi.callHook("prepare:configs.ts", _data);
1738
- const runtimeConfig = JSON.parse(JSON.stringify(_data.runtimeConfig || {}));
1739
- delete _data.runtimeConfig;
1740
- const importData = [
1741
- "import type { SilgiRuntimeOptions, SilgiRuntimeConfig, SilgiOptions } from 'silgi/types'",
1742
- "import { useSilgiRuntimeConfig } from 'silgi/kit'",
1743
- "",
1744
- `export const runtimeConfig: Partial<SilgiRuntimeConfig> = ${serializeToJs(runtimeConfig)}`,
1745
- "",
1746
- "const runtime = useSilgiRuntimeConfig(undefined, runtimeConfig)",
1747
- "",
1748
- "export const cliConfigs: Partial<SilgiRuntimeOptions & SilgiOptions> = {",
1749
- " runtimeConfig: runtime,",
1750
- ` ${serializeToJs(_data).replace(/^\{/, "").replace(/\}$/, "")}`,
1751
- "}",
1752
- ""
1753
- ];
1754
- return importData;
1755
- }
1756
-
1757
- async function prepareCoreFile(data, frameworkContext, silgi) {
1758
- let importItems = {
1759
- "silgi": {
1760
- import: [
1761
- {
1762
- name: "createSilgi",
1763
- key: "createSilgi"
1764
- }
1765
- ],
1766
- from: "silgi"
1767
- },
1768
- "silgi/types": {
1769
- import: [
1770
- {
1771
- name: "SilgiRuntimeOptions",
1772
- type: true,
1773
- key: "SilgiRuntimeOptions"
1774
- },
1775
- {
1776
- name: "FrameworkContext",
1777
- type: true,
1778
- key: "FrameworkContext"
1779
- },
1780
- {
1781
- name: "SilgiOptions",
1782
- type: true,
1783
- key: "SilgiOptions"
1784
- }
1785
- ],
1786
- from: "silgi/types"
1787
- },
1788
- "#silgi/vfs": {
1789
- import: [],
1790
- from: "./vfs"
1791
- },
1792
- "silgi/runtime/internal/defu": {
1793
- import: [
1794
- {
1795
- name: "mergeDeep",
1796
- key: "mergeDeep"
1797
- }
1798
- ],
1799
- from: "silgi/runtime/internal/defu"
1800
- },
1801
- "scan.ts": {
1802
- import: [
1803
- {
1804
- name: "uris",
1805
- type: false,
1806
- key: "uris"
1807
- },
1808
- {
1809
- name: "services",
1810
- type: false,
1811
- key: "services"
1812
- },
1813
- {
1814
- name: "shareds",
1815
- type: false,
1816
- key: "shareds"
1817
- },
1818
- {
1819
- name: "schemas",
1820
- type: false,
1821
- key: "schemas"
1822
- },
1823
- {
1824
- name: "modulesURIs",
1825
- type: false,
1826
- key: "modulesURIs"
1827
- }
1828
- ],
1829
- from: "./scan.ts"
1830
- },
1831
- "configs.ts": {
1832
- import: [
1833
- {
1834
- name: "cliConfigs",
1835
- type: false,
1836
- key: "cliConfigs"
1837
- }
1838
- ],
1839
- from: "./configs.ts"
1840
- },
1841
- "rules.ts": {
1842
- import: [
1843
- {
1844
- name: "routeRules",
1845
- key: "routeRules"
1846
- }
1847
- ],
1848
- from: "./rules.ts"
1849
- }
1850
- };
1851
- importItems = { ...data._importItems, ...importItems };
1852
- const _data = {
1853
- customImports: data._customImports || [],
1854
- buildSilgiExtraContent: [],
1855
- beforeBuildSilgiExtraContent: [],
1856
- afterCliOptions: [],
1857
- _silgiConfigs: [],
1858
- customContent: [],
1859
- importItems
1860
- };
1861
- await silgi.callHook("prepare:core.ts", _data);
1862
- if (importItems["#silgi/vfs"].import.length === 0) {
1863
- delete importItems["#silgi/vfs"];
1864
- }
1865
- const plugins = [];
1866
- for (const plugin of silgi.options.plugins) {
1867
- const pluginImportName = `_${hash(plugin.packageImport)}`;
1868
- _data.customImports.push(`import ${pluginImportName} from '${plugin.packageImport}'`);
1869
- plugins.push(pluginImportName);
1870
- }
1871
- const importsContent = [
1872
- ...Object.entries(importItems).map(([_name, { from, import: imports }]) => {
1873
- if (silgi.options.typescript.removeFileExtension) {
1874
- from = from.replace(/\.(js|ts|mjs|cjs|jsx|tsx)$/, "");
1875
- }
1876
- return `import { ${imports.map(({ type, name }) => type ? `type ${name}` : name).join(", ")} } from '${from}'`;
1877
- }),
1878
- "",
1879
- ..._data.customImports,
1880
- ""
1881
- ];
1882
- const importData = [
1883
- "",
1884
- "export async function buildSilgi(framework: FrameworkContext, moduleOptions?: Partial<SilgiRuntimeOptions>,buildOptions?: Partial<SilgiOptions>) {",
1885
- "",
1886
- _data.beforeBuildSilgiExtraContent.length > 0 ? _data.beforeBuildSilgiExtraContent.map(({ value, type }) => {
1887
- return type === "function" ? value : `const ${value}`;
1888
- }) : "",
1889
- "",
1890
- " const silgi = await createSilgi({",
1891
- " framework,",
1892
- " shared: shareds as any,",
1893
- " services: services as any,",
1894
- " schemas: schemas as any,",
1895
- " uris,",
1896
- " modulesURIs,",
1897
- ` plugins: [${plugins.join(", ")}],`,
1898
- _data._silgiConfigs.length > 0 ? ` ${_data._silgiConfigs.map((config) => typeof config === "string" ? config : typeof config === "object" ? Object.entries(config).map(([key, value]) => `${key}: ${value}`).join(",\n ") : "").join(",\n ")},` : "",
1899
- " options: mergeDeep(",
1900
- " {",
1901
- " runtimeConfig: {} as SilgiRuntimeOptions,",
1902
- " routeRules: routeRules as any,",
1903
- " },",
1904
- " moduleOptions || {},",
1905
- " {",
1906
- ` present: '${silgi.options.preset}',`,
1907
- " ...cliConfigs,",
1908
- " },",
1909
- " buildOptions,",
1910
- " ) as any,",
1911
- " })",
1912
- "",
1913
- ...frameworkContext,
1914
- "",
1915
- ..._data.buildSilgiExtraContent,
1916
- "",
1917
- " return silgi",
1918
- "}",
1919
- ""
1920
- ];
1921
- await silgi.callHook("after:prepare:core.ts", importData);
1922
- importData.unshift(...importsContent);
1923
- return importData;
1924
- }
1925
-
1926
- async function prepareFramework(silgi) {
1927
- const importItems = {
1928
- "silgi/types": {
1929
- import: [
1930
- {
1931
- name: "SilgiRuntimeContext",
1932
- type: true,
1933
- key: "SilgiRuntimeContext"
1934
- }
1935
- ],
1936
- from: "silgi/types"
1937
- }
1938
- };
1939
- const customImports = [];
1940
- const functions = [];
1941
- await silgi.callHook("prepare:createCoreFramework", {
1942
- importItems,
1943
- customImports,
1944
- functions
1945
- });
1946
- const content = [
1947
- ...functions.map((f) => f.params?.length ? ` await ${f.name}(framework, ${f.params.join(",")})` : ` await ${f.name}(framework)`)
1948
- ];
1949
- return {
1950
- content,
1951
- importItems,
1952
- customImports
1953
- };
1954
- }
1955
- async function createDTSFramework(silgi) {
1956
- const importItems = {
1957
- "silgi/types": {
1958
- import: [
1959
- {
1960
- name: "SilgiRuntimeContext",
1961
- type: true,
1962
- key: "SilgiRuntimeContext"
1963
- }
1964
- ],
1965
- from: "silgi/types"
1966
- }
1967
- };
1968
- const customImports = [];
1969
- const customContent = [];
1970
- await silgi.callHook("prepare:createDTSFramework", {
1971
- importItems,
1972
- customImports,
1973
- customContent
1974
- });
1975
- const content = [
1976
- ...Object.entries(importItems).map(([_name, { from, import: imports }]) => {
1977
- const path = isAbsolute(from) ? relativeWithDot(silgi.options.build.typesDir, from) : from;
1978
- if (silgi.options.typescript.removeFileExtension) {
1979
- from = from.replace(/\.(js|ts|mjs|cjs|jsx|tsx)$/, "");
1980
- }
1981
- return `import { ${imports.map(({ type, name }) => type ? `type ${name}` : name).join(", ")} } from '${path}'`;
1982
- }),
1983
- "",
1984
- ...customImports,
1985
- "",
1986
- ...customContent,
1987
- ""
1988
- ];
1989
- return {
1990
- content,
1991
- importItems
1992
- };
1993
- }
1994
-
1995
- async function writeCoreFile(silgi) {
1996
- const data = await prepareFramework(silgi);
1997
- const coreContent = await prepareCoreFile({
1998
- _importItems: data?.importItems ?? {},
1999
- _customImports: data?.customImports ?? []
2000
- }, data?.content ?? [], silgi);
2001
- const configs = await prepareConfigs(silgi);
2002
- const silgiDir = resolve(silgi.options.silgi.serverDir);
2003
- const buildFiles = [];
2004
- buildFiles.push({
2005
- path: join(silgiDir, "core.ts"),
2006
- contents: coreContent.join("\n")
2007
- });
2008
- buildFiles.push({
2009
- path: join(silgiDir, "configs.ts"),
2010
- contents: configs.join("\n")
2011
- });
2012
- for await (const file of buildFiles) {
2013
- await writeFile(
2014
- resolve(silgi.options.build.dir, file.path),
2015
- file.contents
2016
- );
2017
- }
2018
- }
2019
-
2020
- async function generateRouterDTS(silgi) {
2021
- const uris = silgi.uris;
2022
- const subPath = "srn";
2023
- const groupedPaths = /* @__PURE__ */ new Map();
2024
- Object.entries(uris || {}).forEach(([key, params]) => {
2025
- const [service, resource, method, action] = key.split("/");
2026
- const basePath = params ? `${subPath}/${service}/${resource}/${action}/${params}` : `${subPath}/${service}/${resource}/${action}`;
2027
- const fullPath = `${subPath}/${service}/${resource}/${action}`;
2028
- if (!groupedPaths.has(basePath)) {
2029
- groupedPaths.set(basePath, /* @__PURE__ */ new Map());
2030
- }
2031
- groupedPaths.get(basePath)?.set(method.toLowerCase(), fullPath);
2032
- });
2033
- const keys = [
2034
- " keys: {",
2035
- Array.from(groupedPaths.entries()).map(([basePath, methods]) => {
2036
- return ` '/${basePath}': {${Array.from(methods.entries()).map(([method, path]) => `
2037
- ${method}: '/${path}'`).join(",")}
2038
- }`;
2039
- }).join(",\n"),
2040
- " }",
2041
- ""
2042
- ].join("\n");
2043
- const groupedRoutes = Object.entries(uris || {}).reduce((acc, [key, _params]) => {
2044
- const [service, resource, method, action] = key.split("/");
2045
- const routePath = `${subPath}/${service}/${resource}/${action}`;
2046
- if (!acc[routePath]) {
2047
- acc[routePath] = {};
2048
- }
2049
- acc[routePath][method] = {
2050
- input: `ExtractInputFromURI<'${key}'>`,
2051
- output: `ExtractOutputFromURI<'${key}'>`,
2052
- queryParams: `ExtractQueryParamsFromURI<'${key}'>`,
2053
- pathParams: `ExtractPathParamsFromURI<'${key}'>`
2054
- };
2055
- return acc;
2056
- }, {});
2057
- const routerTypes = Object.entries(groupedRoutes).map(([path, methods]) => {
2058
- const methodEntries = Object.entries(methods).map(([method, { input, output, queryParams, pathParams }]) => {
2059
- return ` '${method}': {
2060
- input: ${input},
2061
- output: ${output},
2062
- queryParams: ${queryParams},
2063
- pathParams: ${pathParams}
2064
- }`;
2065
- }).join(",\n");
2066
- return ` '/${path}': {
2067
- ${methodEntries}
2068
- }`;
2069
- });
2070
- const nitro = [
2071
- "declare module 'nitropack/types' {",
2072
- " interface InternalApi extends RouterTypes {}",
2073
- "}"
2074
- ];
2075
- const content = [
2076
- keys.slice(0, -1),
2077
- // son satırdaki boş satırı kaldır
2078
- ...routerTypes
2079
- ].join(",\n");
2080
- const context = [
2081
- "import type { ExtractInputFromURI, ExtractOutputFromURI, ExtractQueryParamsFromURI, ExtractPathParamsFromURI } from 'silgi/types'",
2082
- "",
2083
- "export interface RouterTypes {",
2084
- content,
2085
- "}",
2086
- "",
2087
- "declare module 'silgi/types' {",
2088
- " interface SilgiRouterTypes extends RouterTypes {",
2089
- " }",
2090
- "}",
2091
- "",
2092
- silgi.options.preset === "h3" || silgi.options.preset === "nitro" ? nitro.join("\n") : "",
2093
- "",
2094
- "export {}"
2095
- ];
2096
- return context;
2097
- }
2098
-
2099
- async function prepareSchema(silgi) {
2100
- const importItems = {
2101
- "silgi/types": {
2102
- import: [
2103
- {
2104
- name: "URIsTypes",
2105
- type: true,
2106
- key: "URIsTypes"
2107
- },
2108
- {
2109
- name: "Namespaces",
2110
- type: true,
2111
- key: "Namespaces"
2112
- },
2113
- {
2114
- name: "SilgiRuntimeContext",
2115
- type: true,
2116
- key: "SilgiRuntimeContext"
2117
- }
2118
- ],
2119
- from: "silgi/types"
2120
- },
2121
- "silgi/scan": {
2122
- import: [{
2123
- key: "modulesURIs",
2124
- name: "modulesURIs",
2125
- type: false
2126
- }],
2127
- from: relativeWithDot(silgi.options.build.typesDir, `${silgi.options.silgi.serverDir}/scan.ts`)
2128
- }
2129
- };
2130
- const data = {
2131
- importItems,
2132
- customImports: [],
2133
- options: [],
2134
- contexts: [],
2135
- actions: [],
2136
- shareds: [
2137
- {
2138
- key: "modulesURIs",
2139
- value: "{ modulesURIs: typeof modulesURIs }"
2140
- }
2141
- ],
2142
- events: [],
2143
- storeBase: [],
2144
- hooks: [],
2145
- runtimeHooks: [],
2146
- runtimeOptions: [],
2147
- methods: [],
2148
- routeRules: [],
2149
- routeRulesConfig: []
2150
- };
2151
- await silgi.callHook("prepare:schema.ts", data);
2152
- relativeWithDot(silgi.options.build.typesDir, `${silgi.options.silgi.serverDir}/core.ts`);
2153
- const silgiScanTS = relativeWithDot(silgi.options.build.typesDir, `${silgi.options.silgi.serverDir}/scan.ts`);
2154
- let addSilgiContext = false;
2155
- const importsContent = [
2156
- ...Object.entries(importItems).map(([_name, { from, import: imports }]) => {
2157
- const path = isAbsolute(from) ? relativeWithDot(silgi.options.build.typesDir, from) : from;
2158
- if (silgi.options.typescript.removeFileExtension) {
2159
- from = from.replace(/\.(js|ts|mjs|cjs|jsx|tsx)$/, "");
2160
- }
2161
- return `import { ${imports.map(({ type, name }) => type ? `type ${name}` : name).join(", ")} } from '${path}'`;
2162
- }),
2163
- "",
2164
- ...data.customImports,
2165
- ""
2166
- ];
2167
- const importData = [
2168
- "interface InferredNamespaces {",
2169
- ...(silgi.options.namespaces || []).map((key) => ` ${key}: string,`),
2170
- "}",
2171
- "",
2172
- `type SchemaExtends = Namespaces<typeof import('${silgiScanTS}')['schemas']>`,
2173
- "",
2174
- `type SilgiURIsMerge = URIsTypes<typeof import('${silgiScanTS}')['uris']>`,
2175
- "",
2176
- `type SilgiModuleContextExtends = ${data.contexts.length ? data.contexts.map(({ value }) => value).join(" & ") : "{}"}`,
2177
- "",
2178
- data.events.length ? `interface SilgiModuleEventsExtends extends ${data.events.map((item) => item.extends ? item.value : "").join(", ")} {
2179
- ${data.events.map((item) => {
2180
- if (item.isSilgiContext) {
2181
- addSilgiContext = true;
2182
- }
2183
- return !item.extends && !addSilgiContext ? ` ${item.key}: ${item.value}` : item.isSilgiContext ? " context: SilgiRuntimeContext" : "";
2184
- }).join(",\n")}
2185
- }` : "interface SilgiModuleEventsExtends {}",
2186
- "",
2187
- `type RuntimeActionExtends = ${data.actions?.length ? data.actions.map(({ value }) => `${value}`).join(" & ") : "{}"}`,
2188
- "",
2189
- `type RuntimeMethodExtends = ${data.methods?.length ? data.methods.map(({ value }) => `${value}`).join(" & ") : "{}"}`,
2190
- "",
2191
- `type RuntimeRouteRulesExtends = ${data.routeRules?.length ? data.routeRules.map(({ value }) => `${value}`).join(" & ") : "{}"}`,
2192
- "",
2193
- `type RuntimeRouteRulesConfigExtends = ${data.routeRulesConfig?.length ? data.routeRulesConfig.map(({ value }) => `${value}`).join(" & ") : "{}"}`,
2194
- "",
2195
- `type SilgiModuleSharedExtends = ${data.shareds.length ? data.shareds.map(({ value }) => `${value}`).join(" & ") : "{}"}`,
2196
- "",
2197
- `type SilgiModuleOptionExtend = ${data.options?.length ? data.options.map(({ value }) => `${value}`).join(" & ") : "{}"}`,
2198
- "",
2199
- `type SilgiRuntimeOptionExtends = ${data.runtimeOptions?.length ? data.runtimeOptions.map(({ value }) => `${value}`).join(" & ") : "{}"}`,
2200
- "",
2201
- silgi.options.typescript.generateRuntimeConfigTypes ? generateTypes(
2202
- await resolveSchema(
2203
- {
2204
- ...Object.fromEntries(
2205
- Object.entries(silgi.options.runtimeConfig).filter(
2206
- ([key]) => !["app", "nitro", "nuxt"].includes(key)
2207
- )
2208
- )
2209
- }
2210
- ),
2211
- {
2212
- interfaceName: "SilgiRuntimeConfigExtends",
2213
- addExport: false,
2214
- addDefaults: false,
2215
- allowExtraKeys: false,
2216
- indentation: 0
2217
- }
2218
- ) : "",
2219
- "",
2220
- generateTypes(
2221
- await resolveSchema(
2222
- {
2223
- ...data.storeBase?.reduce((acc, key) => ({ ...acc, [key]: "" }), {}) || {},
2224
- ...silgi.options.storages?.reduce((acc, key) => ({ ...acc, [key]: "" }), {}) || {}
2225
- }
2226
- ),
2227
- {
2228
- interfaceName: "SilgiStorageBaseExtends",
2229
- addExport: false,
2230
- addDefaults: false,
2231
- allowExtraKeys: false,
2232
- indentation: 0
2233
- }
2234
- ),
2235
- "",
2236
- `type ModuleHooksExtend = ${data.hooks?.length ? data.hooks.map(({ value }) => `${value}`).join(" & ") : "{}"}`,
2237
- "",
2238
- `type SilgiRuntimeHooksExtends = ${data.runtimeHooks?.length ? data.runtimeHooks.map(({ value }) => `${value}`).join(" & ") : "{}"}`,
2239
- "",
2240
- "declare module 'silgi/types' {",
2241
- " interface FrameworkContext extends FrameworkContextExtends {}",
2242
- " interface SilgiSchema extends SchemaExtends {}",
2243
- " interface SilgiNamespaces extends InferredNamespaces {}",
2244
- " interface SilgiStorageBase extends SilgiStorageBaseExtends {}",
2245
- " interface SilgiURIs extends SilgiURIsMerge {}",
2246
- " interface SilgiRuntimeContext extends SilgiModuleContextExtends {}",
2247
- " interface SilgiEvents extends SilgiModuleEventsExtends {}",
2248
- " interface SilgiRuntimeSharedsExtend extends SilgiModuleSharedExtends {}",
2249
- " interface SilgiRuntimeActions extends RuntimeActionExtends {}",
2250
- " interface SilgiModuleOptions extends SilgiModuleOptionExtend {}",
2251
- " interface SilgiRuntimeOptions extends SilgiRuntimeOptionExtends {}",
2252
- " interface SilgiRuntimeHooks extends SilgiRuntimeHooksExtends {}",
2253
- " interface SilgiRuntimeConfig extends SilgiRuntimeConfigExtends {}",
2254
- " interface SilgiHooks extends ModuleHooksExtend {}",
2255
- " interface SilgiRuntimeMethods extends RuntimeMethodExtends {}",
2256
- " interface SilgiRuntimeRouteRules extends RuntimeRouteRulesExtends {}",
2257
- " interface SilgiRuntimeRouteRulesConfig extends RuntimeRouteRulesConfigExtends {}",
2258
- " interface SilgiCommands extends SilgiCommandsExtended {}",
2259
- "",
2260
- "}",
2261
- "",
2262
- "export {}"
2263
- ];
2264
- await silgi.callHook("after:prepare:schema.ts", importData);
2265
- importData.unshift(...importsContent);
2266
- return importData;
2267
- }
2268
-
2269
- async function prepareStore(silgi) {
2270
- silgi.hook("prepare:schema.ts", async (options) => {
2271
- if (silgi.options.storage) {
2272
- for (const [key, _value] of Object.entries(silgi.options.storage)) {
2273
- options.storeBase.push(key);
2274
- }
2275
- }
2276
- });
2277
- }
2278
-
2279
- async function writeTypesAndFiles(silgi) {
2280
- const routerDTS = await generateRouterDTS(silgi);
2281
- await prepareStore(silgi);
2282
- silgi.hook("prepare:types", (opts) => {
2283
- opts.references.push({ path: "./schema.d.ts" });
2284
- opts.references.push({ path: "./silgi-routes.d.ts" });
2285
- opts.references.push({ path: "./framework.d.ts" });
2286
- });
2287
- const schemaContent = await prepareSchema(silgi);
2288
- const frameworkDTS = await createDTSFramework(silgi);
2289
- const { declarations, tsConfig } = await silgiGenerateType(silgi);
2290
- const tsConfigPath = resolve(
2291
- silgi.options.rootDir,
2292
- silgi.options.typescript.tsconfigPath
2293
- );
2294
- const typesDir = resolve(silgi.options.build.typesDir);
2295
- let autoImportedTypes = [];
2296
- let autoImportExports = "";
2297
- if (silgi.unimport) {
2298
- await silgi.unimport.init();
2299
- const allImports = await silgi.unimport.getImports();
2300
- autoImportExports = toExports(allImports).replace(
2301
- /#internal\/nitro/g,
2302
- relative(typesDir, runtimeDir)
2303
- );
2304
- const resolvedImportPathMap = /* @__PURE__ */ new Map();
2305
- for (const i of allImports.filter((i2) => !i2.type)) {
2306
- if (resolvedImportPathMap.has(i.from)) {
2307
- continue;
2308
- }
2309
- let path = resolveAlias$1(i.from, silgi.options.alias);
2310
- if (isAbsolute(path)) {
2311
- const resolvedPath = await resolvePath(i.from, {
2312
- url: silgi.options.nodeModulesDirs
2313
- }).catch(() => null);
2314
- if (resolvedPath) {
2315
- const { dir, name } = parseNodeModulePath(resolvedPath);
2316
- if (!dir || !name) {
2317
- path = resolvedPath;
2318
- } else {
2319
- const subpath = await lookupNodeModuleSubpath(resolvedPath);
2320
- path = join(dir, name, subpath || "");
2321
- }
2322
- }
2323
- }
2324
- if (existsSync(path) && !await isDirectory(path)) {
2325
- path = path.replace(/\.[a-z]+$/, "");
2326
- }
2327
- if (isAbsolute(path)) {
2328
- path = relative(typesDir, path);
2329
- }
2330
- resolvedImportPathMap.set(i.from, path);
2331
- }
2332
- autoImportedTypes = [
2333
- silgi.options.imports && silgi.options.imports.autoImport !== false ? (await silgi.unimport.generateTypeDeclarations({
2334
- exportHelper: false,
2335
- resolvePath: (i) => resolvedImportPathMap.get(i.from) ?? i.from
2336
- })).trim() : ""
2337
- ];
2338
- }
2339
- const buildFiles = [];
2340
- buildFiles.push({
2341
- path: join(typesDir, "silgi-routes.d.ts"),
2342
- contents: routerDTS.join("\n")
2343
- });
2344
- buildFiles.push({
2345
- path: join(typesDir, "silgi-imports.d.ts"),
2346
- contents: [...autoImportedTypes, autoImportExports || "export {}"].join(
2347
- "\n"
2348
- )
2349
- });
2350
- buildFiles.push({
2351
- path: join(typesDir, "schema.d.ts"),
2352
- contents: schemaContent.join("\n")
2353
- });
2354
- buildFiles.push({
2355
- path: join(typesDir, "silgi.d.ts"),
2356
- contents: declarations.join("\n")
2357
- });
2358
- buildFiles.push({
2359
- path: tsConfigPath,
2360
- contents: JSON.stringify(tsConfig, null, 2)
2361
- });
2362
- buildFiles.push({
2363
- path: join(typesDir, "framework.d.ts"),
2364
- contents: frameworkDTS.content.join("\n")
2365
- });
2366
- for await (const file of buildFiles) {
2367
- await writeFile(
2368
- resolve(silgi.options.build.dir, file.path),
2369
- file.contents
2370
- );
2371
- }
2372
- }
2373
-
2374
- const commonArgs = {
2375
- dir: {
2376
- type: "string",
2377
- description: "project root directory"
2378
- },
2379
- _dir: {
2380
- type: "positional",
2381
- default: ".",
2382
- description: "project root directory (prefer using `--dir`)"
2383
- }
2384
- };
2385
-
2386
- export { createSilgiCLI as a, writeTypesAndFiles as b, commonArgs as c, writeCoreFile as d, prepareEnv as e, generateApp as g, prepare as p, scanFiles$1 as s, writeScanFiles as w };