silgi 0.9.35 → 0.10.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.
@@ -1,1928 +1,43 @@
1
1
  import { defineCommand } from 'citty';
2
- import consola, { consola as consola$1 } from 'consola';
3
- import { resolve, isAbsolute, relative, join, dirname, basename, extname } from 'pathe';
4
- import { peerDependencies, version } from 'silgi/meta';
5
- import { promises, existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';
6
- import { readdir } from 'node:fs/promises';
7
- import { resolvePath, parseNodeModulePath, lookupNodeModuleSubpath, resolveModuleExportNames, resolve as resolve$1 } from 'mlly';
8
- import { resolveAlias } from 'pathe/utils';
9
- import { relativeWithDot, hash, isDirectory, writeFile, resolveAlias as resolveAlias$1, resolvePath as resolvePath$1, normalizeTemplate, useLogger, addTemplate, applyEnv } from 'silgi/kit';
10
- import { runtimeDir } from 'silgi/runtime/meta';
11
- import { toExports, scanExports, createUnimport } from 'unimport';
12
- import { createJiti } from 'dev-jiti';
13
- import { readPackageJSON } from 'pkg-types';
14
- import { s as silgiGenerateType } from './types.mjs';
2
+ import consola from 'consola';
3
+ import { resolve } from 'pathe';
4
+ import { version } from 'silgi/meta';
5
+ import { c as createSilgiCLI, p as prepare$1, w as writeTypesAndFiles, a as writeCoreFile } from './writeTypesAndFiles.mjs';
15
6
  import { c as commonArgs } from './common.mjs';
16
- import { createHooks, createDebugger } from 'hookable';
17
- import { useSilgiCLI, silgiCLICtx } from 'silgi/core';
18
- import { autoImportTypes } from 'silgi/types';
19
- import { p as prepareEnv } from './env.mjs';
20
- import { pascalCase } from 'scule';
21
- import { h as hasInstalledModule } from './compatibility.mjs';
22
- import { pathToFileURL, fileURLToPath } from 'node:url';
23
- import defu from 'defu';
24
- import { isRelative, withTrailingSlash } from 'ufo';
25
- import { globby } from 'globby';
26
- import ignore from 'ignore';
27
- import { parseSync } from '@oxc-parser/wasm';
28
- import { klona } from 'klona';
29
- import { createStorage, builtinDrivers } from 'unstorage';
30
- import { l as loadOptions } from './loader.mjs';
7
+ import 'node:fs';
8
+ import 'node:fs/promises';
9
+ import 'hookable';
10
+ import 'silgi/core';
11
+ import 'silgi/kit';
12
+ import 'silgi/runtime/meta';
13
+ import 'silgi/types';
14
+ import 'unimport';
15
+ import './env.mjs';
31
16
  import '@clack/prompts';
32
17
  import 'dotenv';
18
+ import 'mlly';
19
+ import 'scule';
20
+ import 'dev-jiti';
21
+ import './compatibility.mjs';
33
22
  import 'semver/functions/satisfies.js';
23
+ import 'node:url';
24
+ import 'defu';
25
+ import 'ufo';
26
+ import 'globby';
27
+ import 'ignore';
28
+ import '@oxc-parser/wasm';
29
+ import 'klona';
30
+ import 'unstorage';
31
+ import './loader.mjs';
34
32
  import 'c12';
35
33
  import 'compatx';
36
34
  import 'klona/full';
37
35
  import 'std-env';
38
36
  import 'consola/utils';
39
37
  import 'escape-string-regexp';
40
-
41
- async function prepare$1(_silgi) {
42
- }
43
-
44
- async function generateSilgiStorageBaseType(silgi) {
45
- silgi.hook("prepare:schema.ts", async (options) => {
46
- if (silgi.options.storage) {
47
- for (const [key, _value] of Object.entries(silgi.options.storage)) {
48
- options.storeBase.push(key);
49
- }
50
- }
51
- });
52
- }
53
-
54
- async function generateRouterDTS(silgi) {
55
- silgi.hook("finish:types", async (data) => {
56
- const uris = data.object.uris;
57
- const subPath = "srn";
58
- const groupedPaths = /* @__PURE__ */ new Map();
59
- Object.entries(uris || {}).forEach(([key, params]) => {
60
- const [service, resource, method, action] = key.split("/");
61
- const basePath = params ? `${subPath}/${service}/${resource}/${action}/${params}` : `${subPath}/${service}/${resource}/${action}`;
62
- const fullPath = `${subPath}/${service}/${resource}/${action}`;
63
- if (!groupedPaths.has(basePath)) {
64
- groupedPaths.set(basePath, /* @__PURE__ */ new Map());
65
- }
66
- groupedPaths.get(basePath)?.set(method.toLowerCase(), fullPath);
67
- });
68
- const keys = [
69
- " keys: {",
70
- Array.from(groupedPaths.entries()).map(([basePath, methods]) => {
71
- return ` '/${basePath}': {${Array.from(methods.entries()).map(([method, path]) => `
72
- ${method}: '/${path}'`).join(",")}
73
- }`;
74
- }).join(",\n"),
75
- " }",
76
- ""
77
- ].join("\n");
78
- const groupedRoutes = Object.entries(uris || {}).reduce((acc, [key, _params]) => {
79
- const [service, resource, method, action] = key.split("/");
80
- const routePath = `${subPath}/${service}/${resource}/${action}`;
81
- if (!acc[routePath]) {
82
- acc[routePath] = {};
83
- }
84
- acc[routePath][method] = {
85
- input: `ExtractInputFromURI<'${key}'>`,
86
- output: `ExtractOutputFromURI<'${key}'>`,
87
- params: `ExtractRouterParamsFromURI<'${key}'>['params']`
88
- };
89
- return acc;
90
- }, {});
91
- const routerTypes = Object.entries(groupedRoutes).map(([path, methods]) => {
92
- const methodEntries = Object.entries(methods).map(([method, { input, output, params }]) => {
93
- return ` '${method}': {
94
- input: ${input},
95
- output: ${output}
96
- params: ${params}
97
- }`;
98
- }).join(",\n");
99
- return ` '/${path}': {
100
- ${methodEntries}
101
- }`;
102
- });
103
- const nitro = [
104
- "declare module 'nitropack/types' {",
105
- " interface InternalApi extends RouterTypes {}",
106
- "}"
107
- ];
108
- const content = [
109
- keys.slice(0, -1),
110
- // son satırdaki boş satırı kaldır
111
- ...routerTypes
112
- ].join(",\n");
113
- const context = [
114
- "import type { ExtractInputFromURI, ExtractOutputFromURI, ExtractRouterParamsFromURI } from 'silgi/types'",
115
- "",
116
- "export interface RouterTypes {",
117
- content,
118
- "}",
119
- "",
120
- "declare module 'silgi/types' {",
121
- " interface SilgiRouterTypes extends RouterTypes {",
122
- " }",
123
- "}",
124
- "",
125
- silgi.options.preset === "h3" || silgi.options.preset === "nitro" ? nitro.join("\n") : "",
126
- "",
127
- "export {}"
128
- ].join("\n");
129
- const outputPath = resolve(silgi.options.build.typesDir, "silgi-routes.d.ts");
130
- await promises.writeFile(outputPath, context);
131
- });
132
- }
133
-
134
- async function readCoreFile(silgi) {
135
- const path = resolve(silgi.options.silgi.serverDir, "core.ts");
136
- const context = await promises.readFile(path, { encoding: "utf-8" });
137
- const injectedResult = await silgi.unimport.injectImports(context, path);
138
- if (!injectedResult) {
139
- throw new Error("Failed to inject imports");
140
- }
141
- const jiti = createJiti(silgi.options.rootDir, {
142
- fsCache: false,
143
- moduleCache: false,
144
- debug: silgi.options.debug,
145
- alias: silgi.options.alias
146
- });
147
- try {
148
- if (silgi.options.commandType === "prepare") {
149
- globalThis.$silgiSharedRuntimeConfig = silgi.options.runtimeConfig;
150
- injectedResult.code = `globalThis.$silgiSharedRuntimeConfig = ${JSON.stringify(silgi.options.runtimeConfig)};
151
- ${injectedResult.code}`;
152
- injectedResult.code = injectedResult.code.replace(/runtimeConfig: \{\}/, `runtimeConfig: ${JSON.stringify(silgi.options.runtimeConfig)}`);
153
- }
154
- const coreFile = await jiti.evalModule(
155
- injectedResult.code,
156
- {
157
- filename: path,
158
- async: true,
159
- conditions: silgi.options.conditions
160
- },
161
- async (data, name) => {
162
- return (await silgi.unimport.injectImports(data, name)).code;
163
- }
164
- );
165
- silgi.uris = coreFile.uris;
166
- silgi.schemas = coreFile.schemas;
167
- silgi.services = coreFile.services;
168
- silgi.shareds = coreFile.shareds;
169
- silgi.modulesURIs = coreFile.modulesURIs;
170
- return {
171
- context,
172
- object: {
173
- schemas: coreFile.schemas,
174
- uris: coreFile.uris,
175
- services: coreFile.services,
176
- shareds: coreFile.shareds,
177
- modulesURIs: coreFile.modulesURIs
178
- },
179
- path
180
- };
181
- } catch (error) {
182
- if (silgi.options.debug) {
183
- console.error("Failed to read core.ts file:", error);
184
- } else {
185
- if (error instanceof Error) {
186
- consola.withTag("silgi").error(error.message);
187
- }
188
- }
189
- return {
190
- context,
191
- object: {
192
- schemas: {},
193
- uris: {},
194
- services: {},
195
- shareds: {},
196
- modulesURIs: {}
197
- },
198
- path
199
- };
200
- }
201
- }
202
-
203
- function traverseObject(silgi, obj, currentPath = []) {
204
- const uriMap = /* @__PURE__ */ new Map();
205
- function traverse(node, path = []) {
206
- if (!node || typeof node !== "object")
207
- return;
208
- if (path.length === 4) {
209
- const basePath = path.join("/");
210
- let paramString = "";
211
- if (node.router) {
212
- let params = null;
213
- if (node.router?._def?.typeName !== void 0) {
214
- try {
215
- const shape = node.router?.shape?.params?.shape;
216
- params = shape ? Object.keys(shape) : null;
217
- } catch {
218
- params = null;
219
- }
220
- }
221
- if (params?.length) {
222
- paramString = params.map((p) => `:${p}`).join("/");
223
- }
224
- }
225
- uriMap.set(basePath, paramString);
226
- return;
227
- }
228
- for (const key in node) {
229
- if (!["_type", "fields"].includes(key)) {
230
- traverse(node[key], [...path, key]);
231
- }
232
- }
233
- }
234
- traverse(obj, currentPath);
235
- return uriMap;
236
- }
237
- function scanActionModulesUris(silgi, obj, currentPath = []) {
238
- const uriMap = {};
239
- function traverse(node, path = []) {
240
- if (!node || typeof node !== "object")
241
- return;
242
- if (path.length === 4) {
243
- const basePath = path.join("/");
244
- let moduleName = "";
245
- if (node.modules?.graphql) {
246
- let field = null;
247
- if (node.modules?.graphql?.field) {
248
- moduleName = "graphql";
249
- field = node.modules?.graphql?.field;
250
- }
251
- if (!field) {
252
- return;
253
- }
254
- uriMap[moduleName] ??= {};
255
- if (typeof uriMap[moduleName].field === "object" && uriMap[moduleName].field[field]) {
256
- silgi.logger.withTag("scanActionModulesUris").error(`Hata ${moduleName} ${field} ${basePath} bu zaten burada kullanilmis.`);
257
- }
258
- uriMap[moduleName].field ??= {};
259
- uriMap[moduleName].field[field] = basePath;
260
- }
261
- return;
262
- }
263
- for (const key in node) {
264
- if (!["_type", "fields"].includes(key)) {
265
- traverse(node[key], [...path, key]);
266
- }
267
- }
268
- }
269
- traverse(obj, currentPath);
270
- return uriMap;
271
- }
272
-
273
- async function scanUris(silgi) {
274
- const { context, object, path } = await readCoreFile(silgi);
275
- const uriMap = traverseObject(silgi, object.schemas, []);
276
- const modulesURIs = scanActionModulesUris(silgi, object.services, []);
277
- const uriContent = Array.from(uriMap.entries()).map(([uri, params]) => ` '${uri}': '${params}',`).join("\n");
278
- let newContext = "";
279
- if (uriMap.size > 0) {
280
- newContext = context.replace(
281
- /export const uris = \{[^}]*\}/,
282
- `export const uris = {
283
- ${uriContent}
284
- }`
285
- ).replace(
286
- /export const modulesURIs = \{[^}]*\}/,
287
- `export const modulesURIs = ${JSON.stringify(modulesURIs, null, 2)}`
288
- );
289
- } else {
290
- newContext = context;
291
- }
292
- await promises.writeFile(path, newContext);
293
- }
294
-
295
- async function createCoreFramework(silgi) {
296
- const relativeRootDir = relativeWithDot(silgi.options.rootDir, silgi.options.serverDir);
297
- const importItems = {
298
- "silgi/types": {
299
- import: [
300
- { name: "SilgiRuntimeContext", type: true }
301
- ],
302
- from: "silgi/types"
303
- }
304
- };
305
- await Promise.all([...silgi.options.modules, ...silgi.options._modules].map(async (id) => {
306
- if (typeof id !== "string") {
307
- return;
308
- }
309
- const pkg = await readPackageJSON(id, { url: silgi.options.modulesDir }).catch(() => null);
310
- if (!pkg?.name) {
311
- return;
312
- }
313
- if (importItems[pkg.name]) {
314
- importItems[pkg.name].from = isAbsolute(id) ? relativeWithDot(relativeRootDir, id) : id;
315
- }
316
- }));
317
- const customImports = [];
318
- const functions = [];
319
- await silgi.callHook("prepare:createCoreFramework", {
320
- importItems,
321
- customImports,
322
- functions
323
- });
324
- const content = [
325
- ...functions.map((f) => f.params?.length ? ` await ${f.name}(framework, ${f.params.join(",")})` : ` await ${f.name}(framework)`)
326
- ];
327
- return {
328
- content,
329
- importItems,
330
- customImports
331
- };
332
- }
333
- async function createDTSFramework(silgi) {
334
- const relativeRootDir = relativeWithDot(silgi.options.rootDir, silgi.options.serverDir);
335
- const importItems = {
336
- "silgi/types": {
337
- import: [
338
- { name: "SilgiRuntimeContext", type: true }
339
- ],
340
- from: "silgi/types"
341
- }
342
- };
343
- await Promise.all([...silgi.options.modules, ...silgi.options._modules].map(async (id) => {
344
- if (typeof id !== "string") {
345
- return;
346
- }
347
- const pkg = await readPackageJSON(id, { url: silgi.options.modulesDir }).catch(() => null);
348
- if (!pkg?.name) {
349
- return;
350
- }
351
- if (importItems[pkg.name]) {
352
- importItems[pkg.name].from = isAbsolute(id) ? relativeWithDot(relativeRootDir, id) : id;
353
- }
354
- }));
355
- const customImports = [];
356
- const customContent = [];
357
- await silgi.callHook("prepare:createDTSFramework", {
358
- importItems,
359
- customImports,
360
- customContent
361
- });
362
- const content = [
363
- ...Object.entries(importItems).map(([_name, { from, import: imports }]) => {
364
- const path = isAbsolute(from) ? relativeWithDot(silgi.options.build.typesDir, from) : from;
365
- return `import { ${imports.map(({ type, name }) => type ? `type ${name}` : name).join(", ")} } from '${path}'`;
366
- }),
367
- "",
368
- ...customImports,
369
- "",
370
- ...customContent,
371
- ""
372
- ];
373
- return {
374
- content,
375
- importItems
376
- };
377
- }
378
-
379
- async function schemaTemplate(silgi) {
380
- const relativeRootDir = relativeWithDot(silgi.options.rootDir, silgi.options.serverDir);
381
- const importItems = {
382
- "silgi/types": {
383
- import: [
384
- { name: "URIsTypes", type: true },
385
- { name: "Namespaces", type: true },
386
- { name: "SilgiRuntimeContext", type: true }
387
- ],
388
- from: "silgi/types"
389
- }
390
- };
391
- await Promise.all([...silgi.options.modules, ...silgi.options._modules].map(async (id) => {
392
- if (typeof id !== "string") {
393
- return;
394
- }
395
- const pkg = await readPackageJSON(id, { url: silgi.options.modulesDir }).catch(() => null);
396
- if (!pkg?.name) {
397
- return;
398
- }
399
- if (importItems[pkg.name]) {
400
- importItems[pkg.name].from = isAbsolute(id) ? relativeWithDot(relativeRootDir, id) : id;
401
- }
402
- }));
403
- const data = {
404
- importItems,
405
- customImports: [],
406
- options: [],
407
- contexts: [],
408
- actions: [],
409
- shareds: [],
410
- events: [],
411
- storeBase: [],
412
- hooks: [],
413
- runtimeHooks: [],
414
- runtimeOptions: [],
415
- methods: []
416
- };
417
- const storeBase = [];
418
- await silgi.callHook("prepare:schema.ts", data);
419
- const silgiExport = relativeWithDot(silgi.options.build.typesDir, `${silgi.options.silgi.serverDir}/core.ts`);
420
- let addSilgiContext = false;
421
- const importsContent = [
422
- ...Object.entries(importItems).map(([_name, { from, import: imports }]) => {
423
- const path = isAbsolute(from) ? relativeWithDot(silgi.options.build.typesDir, from) : from;
424
- return `import { ${imports.map(({ type, name }) => type ? `type ${name}` : name).join(", ")} } from '${path}'`;
425
- }),
426
- "",
427
- ...data.customImports,
428
- ""
429
- ];
430
- const importData = [
431
- "interface InferredNamespaces {",
432
- ...(silgi.options.namespaces || []).map((key) => ` ${key}: string,`),
433
- "}",
434
- "",
435
- `type SchemaExtends = Namespaces<typeof import('${silgiExport}')['schemas']>`,
436
- "",
437
- `type SilgiURIsMerge = URIsTypes<typeof import('${silgiExport}')['uris']>`,
438
- "",
439
- `type SilgiModuleContextExtends = ${data.contexts.length ? data.contexts.map(({ value }) => value).join(" & ") : "{}"}`,
440
- "",
441
- data.events.length ? `interface SilgiModuleEventsExtends extends ${data.events.map((item) => item.extends ? item.value : "").join(", ")} {
442
- ${data.events.map((item) => {
443
- if (item.isSilgiContext) {
444
- addSilgiContext = true;
445
- }
446
- return !item.extends && !addSilgiContext ? ` ${item.key}: ${item.value}` : item.isSilgiContext ? " context: SilgiRuntimeContext" : "";
447
- }).join(",\n")}
448
- }` : "interface SilgiModuleEventsExtends {}",
449
- "",
450
- `type RuntimeActionExtends = ${data.actions?.length ? data.actions.map(({ value }) => `${value}`).join(" & ") : "{}"}`,
451
- "",
452
- `type RuntimeMethodExtends = ${data.methods?.length ? data.methods.map(({ value }) => `${value}`).join(" & ") : "{}"}`,
453
- "",
454
- `type SilgiModuleSharedExtends = ${data.shareds.length ? data.shareds.map(({ value }) => `${value}`).join(" & ") : "{}"}`,
455
- "",
456
- `type SilgiModuleOptionExtend = ${data.options?.length ? data.options.map(({ value }) => `${value}`).join(" & ") : "{}"}`,
457
- "",
458
- `type SilgiRuntimeOptionExtends = ${data.runtimeOptions?.length ? data.runtimeOptions.map(({ value }) => `${value}`).join(" & ") : "{}"}`,
459
- "",
460
- "interface SilgiStorageBaseExtends {",
461
- ...(storeBase || []).map((value) => ` ${value}: ''`),
462
- "}",
463
- "",
464
- `type ModuleHooksExtend = ${data.hooks?.length ? data.hooks.map(({ value }) => `${value}`).join(" & ") : "{}"}`,
465
- "",
466
- `type SilgiRuntimeHooksExtends = ${data.runtimeHooks?.length ? data.runtimeHooks.map(({ value }) => `${value}`).join(" & ") : "{}"}`,
467
- "",
468
- "declare module 'silgi/types' {",
469
- " interface FrameworkContext extends FrameworkContextExtends {}",
470
- " interface SilgiSchema extends SchemaExtends {}",
471
- " interface SilgiNamespaces extends InferredNamespaces {}",
472
- " interface SilgiStorageBase extends SilgiStorageBaseExtends {}",
473
- " interface SilgiURIs extends SilgiURIsMerge {}",
474
- " interface SilgiRuntimeContext extends SilgiModuleContextExtends {}",
475
- " interface SilgiEvents extends SilgiModuleEventsExtends {}",
476
- " interface SilgiRuntimeShareds extends SilgiModuleSharedExtends {}",
477
- " interface SilgiRuntimeActions extends RuntimeActionExtends {}",
478
- " interface SilgiModuleOptions extends SilgiModuleOptionExtend {}",
479
- " interface SilgiRuntimeOptions extends SilgiRuntimeOptionExtends {}",
480
- " interface SilgiRuntimeHooks extends SilgiRuntimeHooksExtends {}",
481
- " interface SilgiHooks extends ModuleHooksExtend {}",
482
- " interface SilgiRuntimeMethods extends RuntimeMethodExtends {}",
483
- "}",
484
- "",
485
- "export {}"
486
- ];
487
- await silgi.callHook("after:prepare:schema.ts", importData);
488
- importData.unshift(...importsContent);
489
- return importData;
490
- }
491
-
492
- async function silgiCoreFile(data, frameworkContext, silgi) {
493
- const relativeRootDir = relativeWithDot(silgi.options.rootDir, silgi.options.serverDir);
494
- let importItems = {
495
- "silgi/core": {
496
- import: [
497
- { name: "createSilgi" },
498
- { name: "createShared" }
499
- ],
500
- from: "silgi/core"
501
- },
502
- "silgi/types": {
503
- import: [
504
- { name: "SilgiRuntimeOptions", type: true },
505
- { name: "FrameworkContext", type: true },
506
- { name: "BuildConfig", type: true }
507
- ],
508
- from: "silgi/types"
509
- },
510
- "#silgi/vfs": {
511
- import: [],
512
- from: "./vfs"
513
- },
514
- "silgi/runtime/internal/defu": {
515
- import: [
516
- {
517
- name: "mergeDeep"
518
- }
519
- ],
520
- from: "silgi/runtime/internal/defu"
521
- }
522
- };
523
- importItems = { ...data._importItems, ...importItems };
524
- await Promise.all([...silgi.options.modules, ...silgi.options._modules].map(async (id) => {
525
- if (typeof id !== "string") {
526
- return;
527
- }
528
- const pkg = await readPackageJSON(id, { url: silgi.options.modulesDir }).catch(() => null);
529
- if (!pkg?.name) {
530
- return;
531
- }
532
- if (importItems[pkg.name]) {
533
- importItems[pkg.name].from = isAbsolute(id) ? relativeWithDot(relativeRootDir, id) : id;
534
- }
535
- }));
536
- const _data = {
537
- customImports: data._customImports || [],
538
- uris: [],
539
- services: [],
540
- shareds: [],
541
- schemas: [],
542
- buildSilgiExtraContent: [],
543
- beforeBuildSilgiExtraContent: [],
544
- cliOptions: {},
545
- afterCliOptions: [],
546
- _silgiConfigs: [],
547
- customContent: [],
548
- importItems
549
- };
550
- for (const module of silgi.scanModules) {
551
- if (module.meta.cliToRuntimeOptionsKeys && module.meta.cliToRuntimeOptionsKeys?.length > 0) {
552
- for (const key of module.meta.cliToRuntimeOptionsKeys) {
553
- _data.cliOptions[module.meta.configKey] = {
554
- ..._data.cliOptions[module.meta.configKey],
555
- [key]: module.options[key]
556
- };
557
- }
558
- } else {
559
- _data.cliOptions[module.meta.configKey] = {};
560
- }
561
- }
562
- await silgi.callHook("prepare:core.ts", _data);
563
- if (importItems["#silgi/vfs"].import.length === 0) {
564
- delete importItems["#silgi/vfs"];
565
- }
566
- if (_data.services.length > 0) {
567
- importItems["silgi/core"].import.push({ name: "mergeServices" });
568
- }
569
- if (_data.shareds.length > 0) {
570
- importItems["silgi/core"].import.push({ name: "mergeShared" });
571
- }
572
- if (_data.schemas.length > 0) {
573
- importItems["silgi/core"].import.push({ name: "mergeSchemas" });
574
- }
575
- const plugins = [];
576
- for (const plugin of silgi.options.plugins) {
577
- const pluginImportName = `_${hash(plugin.packageImport)}`;
578
- _data.customImports.push(`import ${pluginImportName} from '${plugin.packageImport}'`);
579
- plugins.push(pluginImportName);
580
- }
581
- const importsContent = [
582
- ...Object.entries(importItems).map(([_name, { from, import: imports }]) => {
583
- return `import { ${imports.map(({ type, name }) => type ? `type ${name}` : name).join(", ")} } from '${from}'`;
584
- }),
585
- "",
586
- ..._data.customImports,
587
- ""
588
- ];
589
- const importData = [
590
- `export const cliOptions: SilgiRuntimeOptions = ${JSON.stringify(_data.cliOptions, null, 2)}`,
591
- "",
592
- ..._data.afterCliOptions,
593
- "",
594
- "export const uris = {}",
595
- "",
596
- "export const modulesURIs = {}",
597
- "",
598
- _data.schemas.length > 0 ? "export const schemas = mergeSchemas([" : "export const schemas = {",
599
- ..._data.schemas.map((name) => {
600
- return ` ${name},`;
601
- }),
602
- _data.schemas.length > 0 ? "])" : "}",
603
- "",
604
- _data.services.length > 0 ? "export const services = mergeServices([" : "export const services = {",
605
- ..._data.services.map((name) => {
606
- return ` ${name},`;
607
- }),
608
- _data.services.length > 0 ? "])" : "}",
609
- "",
610
- _data.shareds.length > 0 ? "export const shareds = mergeShared([" : "export const shareds = {",
611
- ..._data.shareds.map((name) => {
612
- return ` ${name},`;
613
- }),
614
- _data.shareds.length > 0 ? "])" : "}",
615
- "",
616
- "export async function buildSilgi(framework: FrameworkContext, moduleOptions?: Partial<SilgiRuntimeOptions>,buildOptions?: Partial<BuildConfig>) {",
617
- "",
618
- _data.beforeBuildSilgiExtraContent.length > 0 ? _data.beforeBuildSilgiExtraContent.map(({ value, type }) => {
619
- return type === "function" ? value : `const ${value}`;
620
- }) : "",
621
- "",
622
- " const silgi = await createSilgi({",
623
- " framework,",
624
- " shared: shareds as any,",
625
- " services: services as any,",
626
- " schemas: schemas as any,",
627
- " uris,",
628
- " modulesURIs,",
629
- ` plugins: [${plugins.join(", ")}],`,
630
- _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 ")},` : "",
631
- " runtimeConfig: {},",
632
- " ...buildOptions,",
633
- " options: mergeDeep(",
634
- " moduleOptions || {},",
635
- " {",
636
- ` present: '${silgi.options.preset}',`,
637
- " ...cliOptions,",
638
- " },",
639
- " ) as any,",
640
- " })",
641
- "",
642
- ...frameworkContext,
643
- "",
644
- ..._data.buildSilgiExtraContent,
645
- "",
646
- " return silgi",
647
- "}",
648
- ""
649
- ];
650
- await silgi.callHook("after:prepare:core.ts", importData);
651
- importData.unshift(...importsContent);
652
- return importData;
653
- }
654
-
655
- async function writeTypesAndFiles(silgi) {
656
- const data = await createCoreFramework(silgi);
657
- await generateSilgiStorageBaseType(silgi);
658
- await generateRouterDTS(silgi);
659
- silgi.hook("prepare:types", (opts) => {
660
- opts.references.push({ path: "./schema.d.ts" });
661
- opts.references.push({ path: "./silgi-routes.d.ts" });
662
- opts.references.push({ path: "./framework.d.ts" });
663
- });
664
- const schemaContent = await schemaTemplate(silgi);
665
- const coreContent = await silgiCoreFile({
666
- _importItems: data?.importItems ?? {},
667
- _customImports: data?.customImports ?? []
668
- }, data?.content ?? [], silgi);
669
- const frameworkDTS = await createDTSFramework(silgi);
670
- const { declarations, tsConfig } = await silgiGenerateType(silgi);
671
- const tsConfigPath = resolve(
672
- silgi.options.rootDir,
673
- silgi.options.typescript.tsconfigPath
674
- );
675
- const typesDir = resolve(silgi.options.build.typesDir);
676
- const silgiDir = resolve(silgi.options.silgi.serverDir);
677
- let autoImportedTypes = [];
678
- let autoImportExports = "";
679
- if (silgi.unimport) {
680
- await silgi.unimport.init();
681
- const allImports = await silgi.unimport.getImports();
682
- autoImportExports = toExports(allImports).replace(
683
- /#internal\/nitro/g,
684
- relative(typesDir, runtimeDir)
685
- );
686
- const resolvedImportPathMap = /* @__PURE__ */ new Map();
687
- for (const i of allImports.filter((i2) => !i2.type)) {
688
- if (resolvedImportPathMap.has(i.from)) {
689
- continue;
690
- }
691
- let path = resolveAlias(i.from, silgi.options.alias);
692
- if (isAbsolute(path)) {
693
- const resolvedPath = await resolvePath(i.from, {
694
- url: silgi.options.nodeModulesDirs
695
- }).catch(() => null);
696
- if (resolvedPath) {
697
- const { dir, name } = parseNodeModulePath(resolvedPath);
698
- if (!dir || !name) {
699
- path = resolvedPath;
700
- } else {
701
- const subpath = await lookupNodeModuleSubpath(resolvedPath);
702
- path = join(dir, name, subpath || "");
703
- }
704
- }
705
- }
706
- if (existsSync(path) && !await isDirectory(path)) {
707
- path = path.replace(/\.[a-z]+$/, "");
708
- }
709
- if (isAbsolute(path)) {
710
- path = relative(typesDir, path);
711
- }
712
- resolvedImportPathMap.set(i.from, path);
713
- }
714
- autoImportedTypes = [
715
- silgi.options.imports && silgi.options.imports.autoImport !== false ? (await silgi.unimport.generateTypeDeclarations({
716
- exportHelper: false,
717
- resolvePath: (i) => resolvedImportPathMap.get(i.from) ?? i.from
718
- })).trim() : ""
719
- ];
720
- }
721
- const buildFiles = [];
722
- buildFiles.push({
723
- path: join(typesDir, "silgi-routes.d.ts"),
724
- // contents: uris.join('\n'),
725
- contents: ""
726
- });
727
- buildFiles.push({
728
- path: join(silgiDir, "core.ts"),
729
- contents: coreContent.join("\n")
730
- });
731
- buildFiles.push({
732
- path: join(typesDir, "schema.d.ts"),
733
- contents: schemaContent.join("\n")
734
- });
735
- buildFiles.push({
736
- path: join(typesDir, "silgi-imports.d.ts"),
737
- contents: [...autoImportedTypes, autoImportExports || "export {}"].join(
738
- "\n"
739
- )
740
- });
741
- buildFiles.push({
742
- path: join(typesDir, "silgi.d.ts"),
743
- contents: declarations.join("\n")
744
- });
745
- buildFiles.push({
746
- path: tsConfigPath,
747
- contents: JSON.stringify(tsConfig, null, 2)
748
- });
749
- buildFiles.push({
750
- path: join(typesDir, "framework.d.ts"),
751
- contents: frameworkDTS.content.join("\n")
752
- });
753
- for await (const file of buildFiles) {
754
- await writeFile(
755
- resolve(silgi.options.build.dir, file.path),
756
- file.contents
757
- );
758
- }
759
- await scanUris(silgi);
760
- const readCore = await readCoreFile(silgi);
761
- silgi.uris = readCore.object.uris;
762
- silgi.modulesURIs = readCore.object.modulesURIs;
763
- silgi.schemas = readCore.object.schemas;
764
- silgi.shareds = readCore.object.shareds;
765
- await silgi.hooks.callHook("finish:types", readCore);
766
- }
767
-
768
- async function emptyFramework(silgi) {
769
- if (silgi.options.preset === "npm-package" || !silgi.options.preset) {
770
- silgi.hook("after:prepare:schema.ts", (data) => {
771
- data.unshift("type FrameworkContextExtends = {}");
772
- });
773
- }
774
- }
775
-
776
- async function h3Framework(silgi, skip = false) {
777
- if (silgi.options.preset !== "h3" && skip === false)
778
- return;
779
- if (silgi.options.preset === "h3") {
780
- silgi.hook("after:prepare:schema.ts", (data) => {
781
- data.unshift("type FrameworkContextExtends = NitroApp");
782
- });
783
- }
784
- silgi.hook("prepare:schema.ts", (data) => {
785
- data.importItems.nitropack = {
786
- import: [
787
- { name: "NitroApp", type: true }
788
- ],
789
- from: "nitropack/types"
790
- };
791
- data.importItems.h3 = {
792
- import: [
793
- { name: "H3Event", type: true }
794
- ],
795
- from: "h3"
796
- };
797
- data.events.push({
798
- key: "H3Event",
799
- value: "H3Event",
800
- extends: true,
801
- isSilgiContext: false
802
- });
803
- });
804
- silgi.hook("prepare:createDTSFramework", (data) => {
805
- data.importItems["silgi/types"] = {
806
- import: [
807
- { name: "SilgiRuntimeContext", type: true }
808
- ],
809
- from: "silgi/types"
810
- };
811
- data.customContent?.push(
812
- "",
813
- 'declare module "h3" {',
814
- " interface H3EventContext extends SilgiRuntimeContext {}",
815
- "}",
816
- ""
817
- );
818
- });
819
- silgi.hook("prepare:core.ts", (data) => {
820
- data._silgiConfigs.push(`captureError: (error, context = {}) => {
821
- const promise = silgi.hooks
822
- .callHookParallel('error', error, context)
823
- .catch((error_) => {
824
- console.error('Error while capturing another error', error_)
825
- })
826
-
827
- if (context.event && isEvent(context.event)) {
828
- const errors = context.event.context.nitro?.errors
829
- if (errors) {
830
- errors.push({ error, context })
831
- }
832
- if (context.event.waitUntil) {
833
- context.event.waitUntil(promise)
834
- }
835
- }
836
- }`);
837
- });
838
- if (silgi.options.imports !== false) {
839
- const h3Exports = await resolveModuleExportNames("h3", {
840
- url: import.meta.url
841
- });
842
- silgi.options.imports.presets ??= [];
843
- silgi.options.imports.presets.push({
844
- from: "h3",
845
- imports: h3Exports.filter((n) => !/^[A-Z]/.test(n) && n !== "use")
846
- });
847
- }
848
- }
849
-
850
- async function nitroFramework(silgi, skip = false) {
851
- if (silgi.options.preset !== "nitro" && skip === false)
852
- return;
853
- silgi.hook("prepare:schema.ts", (data) => {
854
- data.importItems.nitropack = {
855
- import: [
856
- { name: "NitroApp", type: true }
857
- ],
858
- from: "nitropack/types"
859
- };
860
- });
861
- silgi.hook("after:prepare:schema.ts", (data) => {
862
- data.unshift("type FrameworkContextExtends = NitroApp");
863
- });
864
- silgi.options.plugins.push({
865
- packageImport: "silgi/runtime/internal/nitro",
866
- path: join(runtimeDir, "internal/nitro")
867
- });
868
- silgi.hook("prepare:createDTSFramework", (data) => {
869
- data.importItems["nitropack/types"] = {
870
- import: [
871
- { name: "NitroRuntimeConfig", type: true }
872
- ],
873
- from: "nitropack/types"
874
- };
875
- data.customContent?.push(
876
- "",
877
- 'declare module "silgi/types" {',
878
- " interface SilgiRuntimeOptions extends NitroRuntimeConfig {}",
879
- "}",
880
- ""
881
- );
882
- });
883
- if (silgi.options.imports !== false) {
884
- silgi.options.imports.presets ??= [];
885
- silgi.options.imports.presets.push(...getNitroImportsPreset());
886
- }
887
- await h3Framework(silgi, true);
888
- }
889
- function getNitroImportsPreset() {
890
- return [
891
- {
892
- from: "nitropack/runtime/internal/app",
893
- imports: ["useNitroApp"]
894
- },
895
- {
896
- from: "nitropack/runtime/internal/config",
897
- imports: ["useRuntimeConfig", "useAppConfig"]
898
- },
899
- {
900
- from: "nitropack/runtime/internal/plugin",
901
- imports: ["defineNitroPlugin", "nitroPlugin"]
902
- },
903
- {
904
- from: "nitropack/runtime/internal/cache",
905
- imports: [
906
- "defineCachedFunction",
907
- "defineCachedEventHandler",
908
- "cachedFunction",
909
- "cachedEventHandler"
910
- ]
911
- },
912
- {
913
- from: "nitropack/runtime/internal/storage",
914
- imports: ["useStorage"]
915
- },
916
- {
917
- from: "nitropack/runtime/internal/renderer",
918
- imports: ["defineRenderHandler"]
919
- },
920
- {
921
- from: "nitropack/runtime/internal/meta",
922
- imports: ["defineRouteMeta"]
923
- },
924
- {
925
- from: "nitropack/runtime/internal/route-rules",
926
- imports: ["getRouteRules"]
927
- },
928
- {
929
- from: "nitropack/runtime/internal/context",
930
- imports: ["useEvent"]
931
- },
932
- {
933
- from: "nitropack/runtime/internal/task",
934
- imports: ["defineTask", "runTask"]
935
- },
936
- {
937
- from: "nitropack/runtime/internal/error/utils",
938
- imports: ["defineNitroErrorHandler"]
939
- }
940
- ];
941
- }
942
-
943
- async function nuxtFramework(silgi, skip = false) {
944
- if (silgi.options.preset !== "nuxt" && skip === false)
945
- return;
946
- await nitroFramework(silgi, true);
947
- }
948
-
949
- const frameworkSetup = [emptyFramework, h3Framework, nitroFramework, nuxtFramework];
950
-
951
- async function registerModuleExportScan(silgi) {
952
- silgi.hook("prepare:schema.ts", async (options) => {
953
- for (const module of silgi.scanModules) {
954
- if (module.meta._packageName || silgi.options.preset === "npm-package") {
955
- continue;
956
- }
957
- const exports = module.meta.exports;
958
- if (!exports?.length)
959
- continue;
960
- const configKey = module.meta.configKey;
961
- const moduleName = module.meta.name || module.meta._packageName;
962
- options.importItems[configKey] = {
963
- import: [],
964
- from: module.meta._packageName ? moduleName : relativeWithDot(silgi.options.build.typesDir, module.entryPath)
965
- };
966
- const exportedTypes = exports.filter((exp) => exp.type).map((exp) => exp.name);
967
- if (exportedTypes.includes("ModuleOptions")) {
968
- const importName = pascalCase(`${configKey}Config`);
969
- options.importItems[configKey].import.push({
970
- name: `ModuleOptions as ${importName}`,
971
- type: true
972
- });
973
- options.options.push({ key: configKey, value: importName });
974
- }
975
- if (exportedTypes.includes("SilgiRuntimeOptions")) {
976
- const importName = pascalCase(`${configKey}RuntimeConfig`);
977
- options.importItems[configKey].import.push({
978
- name: `SilgiRuntimeOptions as ${importName}`,
979
- type: true
980
- });
981
- options.runtimeOptions.push({ key: configKey, value: importName });
982
- }
983
- if (exportedTypes.includes("ModuleRuntimeContext")) {
984
- const importName = pascalCase(`${configKey}RuntimeContext`);
985
- options.importItems[configKey].import.push({
986
- name: `ModuleRuntimeContext as ${importName}`,
987
- type: true
988
- });
989
- options.contexts.push({ key: configKey, value: importName });
990
- }
991
- if (exportedTypes.includes("ModuleRuntimeAction")) {
992
- const importName = pascalCase(`${configKey}Action`);
993
- options.importItems[configKey].import.push({
994
- name: `ModuleRuntimeAction as ${importName}`,
995
- type: true
996
- });
997
- options.actions.push({ key: configKey, value: importName });
998
- }
999
- if (exportedTypes.includes("ModuleRuntimeShareds")) {
1000
- const importName = pascalCase(`${configKey}Shared`);
1001
- options.importItems[configKey].import.push({
1002
- name: `ModuleRuntimeShareds as ${importName}`,
1003
- type: true
1004
- });
1005
- options.shareds.push({ key: configKey, value: importName });
1006
- }
1007
- if (exportedTypes.includes("ModuleHooks")) {
1008
- const importName = pascalCase(`${configKey}Hooks`);
1009
- options.importItems[configKey].import.push({
1010
- name: `ModuleHooks as ${importName}`,
1011
- type: true
1012
- });
1013
- options.hooks.push({ key: configKey, value: importName });
1014
- }
1015
- if (exportedTypes.includes("ModuleRuntimeHooks")) {
1016
- const importName = pascalCase(`${configKey}RuntimeHooks`);
1017
- options.importItems[configKey].import.push({
1018
- name: `ModuleRuntimeHooks as ${importName}`,
1019
- type: true
1020
- });
1021
- options.runtimeHooks.push({ key: configKey, value: importName });
1022
- }
1023
- if (exportedTypes.includes("ModuleRuntimeOptions")) {
1024
- const importName = pascalCase(`${configKey}RuntimeOptions`);
1025
- options.importItems[configKey].import.push({
1026
- name: `ModuleRuntimeOptions as ${importName}`,
1027
- type: true
1028
- });
1029
- options.runtimeOptions.push({ key: configKey, value: importName });
1030
- }
1031
- if (exportedTypes.includes("SilgiRuntimeMethods")) {
1032
- const importName = pascalCase(`${configKey}RuntimeMethods`);
1033
- options.importItems[configKey].import.push({
1034
- name: `SilgiRuntimeMethods as ${importName}`,
1035
- type: true
1036
- });
1037
- options.methods.push({ key: configKey, value: importName });
1038
- }
1039
- }
1040
- });
1041
- }
1042
-
1043
- async function loadSilgiModuleInstance(silgiModule) {
1044
- if (typeof silgiModule === "string") {
1045
- throw new TypeError(`Could not load \`${silgiModule}\`. Is it installed?`);
1046
- }
1047
- if (typeof silgiModule !== "function") {
1048
- throw new TypeError(`Nuxt module should be a function: ${silgiModule}`);
1049
- }
1050
- return { silgiModule };
1051
- }
1052
- async function installModules(silgi) {
1053
- const jiti = createJiti(silgi.options.rootDir, {
1054
- alias: silgi.options.alias
1055
- });
1056
- for (const module of silgi.scanModules) {
1057
- if (hasInstalledModule(module.meta.configKey)) {
1058
- silgi.logger.info(`Module ${module.meta.configKey} installed`);
1059
- }
1060
- try {
1061
- const silgiModule = await jiti.import(module.entryPath, {
1062
- default: true,
1063
- conditions: silgi.options.conditions
1064
- });
1065
- if (silgiModule.name !== "silgiNormalizedModule") {
1066
- silgi.scanModules = silgi.scanModules.filter((m) => m.entryPath !== module.entryPath);
1067
- continue;
1068
- }
1069
- await installModule(silgiModule, silgi);
1070
- } catch (err) {
1071
- silgi.logger.error(err);
1072
- }
1073
- }
1074
- }
1075
- async function installModule(moduleToInstall, silgi = useSilgiCLI(), inlineOptions) {
1076
- const { silgiModule } = await loadSilgiModuleInstance(moduleToInstall);
1077
- const res = await silgiModule({}, silgi) ?? {};
1078
- if (res === false) {
1079
- return false;
1080
- }
1081
- const metaData = await silgiModule.getMeta?.();
1082
- const installedModule = silgi.scanModules.find((m) => m.meta.configKey === metaData?.configKey);
1083
- if (installedModule) {
1084
- installedModule.installed = true;
1085
- } else {
1086
- throw new Error(`Module ${metaData?.name} not found`);
1087
- }
1088
- }
1089
-
1090
- const logger$1 = consola$1;
1091
- async function _resolveSilgiModule(mod, silgi) {
1092
- let _url;
1093
- let buildTimeModuleMeta = {};
1094
- const jiti = createJiti(silgi.options.rootDir, {
1095
- alias: silgi.options.alias
1096
- });
1097
- if (typeof mod === "string") {
1098
- const paths = /* @__PURE__ */ new Set();
1099
- mod = resolveAlias$1(mod, silgi.options.alias);
1100
- if (isRelative(mod)) {
1101
- mod = resolve(silgi.options.rootDir, mod);
1102
- }
1103
- paths.add(join(mod, "module"));
1104
- paths.add(mod);
1105
- for (const path of paths) {
1106
- try {
1107
- const src = isAbsolute(path) ? pathToFileURL(await resolvePath$1(path, { fallbackToOriginal: false, extensions: silgi.options.extensions })).href : await resolve$1(path, { url: silgi.options.modulesDir.map((m) => pathToFileURL(m.replace(/\/node_modules\/?$/, ""))), extensions: silgi.options.extensions });
1108
- mod = await jiti.import(src, {
1109
- default: true,
1110
- conditions: silgi.options.conditions
1111
- });
1112
- _url = fileURLToPath(new URL(src));
1113
- const moduleMetadataPath = new URL("module.json", src);
1114
- if (existsSync(moduleMetadataPath)) {
1115
- buildTimeModuleMeta = JSON.parse(await promises.readFile(moduleMetadataPath, "utf-8"));
1116
- } else {
1117
- if (typeof mod === "function") {
1118
- const meta = await mod.getMeta?.();
1119
- const _exports = await scanExports(_url, true);
1120
- buildTimeModuleMeta = {
1121
- ...meta,
1122
- exports: _exports.map(({ from, ...rest }) => rest)
1123
- };
1124
- }
1125
- }
1126
- break;
1127
- } catch (error) {
1128
- const code = error.code;
1129
- if (code === "MODULE_NOT_FOUND" || code === "ERR_PACKAGE_PATH_NOT_EXPORTED" || code === "ERR_MODULE_NOT_FOUND" || code === "ERR_UNSUPPORTED_DIR_IMPORT" || code === "ENOTDIR") {
1130
- continue;
1131
- }
1132
- logger$1.error(`Error while importing module \`${mod}\`: ${error}`);
1133
- throw error;
1134
- }
1135
- }
1136
- }
1137
- if (!buildTimeModuleMeta) {
1138
- throw new Error(`Module ${mod} is not a valid Silgi module`);
1139
- }
1140
- if (typeof mod === "function") {
1141
- if (silgi.scanModules.some((m) => m.meta?.configKey === buildTimeModuleMeta.configKey)) {
1142
- throw new Error(`Module with key \`${buildTimeModuleMeta.configKey}\` already exists`);
1143
- }
1144
- const options = await mod.getOptions?.() || {};
1145
- if (options) {
1146
- silgi.options._c12.config[buildTimeModuleMeta.configKey] = defu(
1147
- silgi.options._c12.config[buildTimeModuleMeta.configKey] || {},
1148
- options || {}
1149
- );
1150
- }
1151
- silgi.scanModules.push({
1152
- meta: buildTimeModuleMeta,
1153
- entryPath: _url,
1154
- installed: false,
1155
- options
1156
- });
1157
- }
1158
- }
1159
- async function scanModules$1(silgi) {
1160
- const _modules = [
1161
- ...silgi.options._modules,
1162
- ...silgi.options.modules
1163
- ];
1164
- for await (const mod of _modules) {
1165
- await _resolveSilgiModule(mod, silgi);
1166
- }
1167
- const moduleMap = new Map(
1168
- silgi.scanModules.map((m) => [m.meta?.configKey, m])
1169
- );
1170
- const graphData = createDependencyGraph(silgi.scanModules);
1171
- const sortedKeys = topologicalSort(graphData);
1172
- const modules = sortedKeys.map((key) => moduleMap.get(key)).filter((module) => Boolean(module));
1173
- silgi.scanModules = modules;
1174
- }
1175
- function createDependencyGraph(modules) {
1176
- const graph = /* @__PURE__ */ new Map();
1177
- const inDegree = /* @__PURE__ */ new Map();
1178
- modules.forEach((module) => {
1179
- const key = module.meta?.configKey;
1180
- if (key) {
1181
- graph.set(key, /* @__PURE__ */ new Set());
1182
- inDegree.set(key, 0);
1183
- }
1184
- });
1185
- modules.forEach((module) => {
1186
- const key = module.meta?.configKey;
1187
- if (!key) {
1188
- return;
1189
- }
1190
- const requiredDeps = module.meta?.requiredDependencies || [];
1191
- const beforeDeps = module.meta?.beforeDependencies || [];
1192
- const afterDeps = module.meta?.afterDependencies || [];
1193
- const processedDeps = /* @__PURE__ */ new Set();
1194
- requiredDeps.forEach((dep) => {
1195
- if (!graph.has(dep)) {
1196
- throw new Error(`Required dependency "${dep}" for module "${key}" is missing`);
1197
- }
1198
- graph.get(dep)?.add(key);
1199
- inDegree.set(key, (inDegree.get(key) || 0) + 1);
1200
- processedDeps.add(dep);
1201
- });
1202
- beforeDeps.forEach((dep) => {
1203
- if (!graph.has(dep)) {
1204
- return;
1205
- }
1206
- graph.get(key)?.add(dep);
1207
- inDegree.set(dep, (inDegree.get(dep) || 0) + 1);
1208
- });
1209
- afterDeps.forEach((dep) => {
1210
- if (processedDeps.has(dep)) {
1211
- return;
1212
- }
1213
- if (!graph.has(dep)) {
1214
- return;
1215
- }
1216
- graph.get(dep)?.add(key);
1217
- inDegree.set(key, (inDegree.get(key) || 0) + 1);
1218
- });
1219
- });
1220
- return { graph, inDegree };
1221
- }
1222
- function findCyclicDependencies(graph) {
1223
- const visited = /* @__PURE__ */ new Set();
1224
- const recursionStack = /* @__PURE__ */ new Set();
1225
- const cycles = [];
1226
- function dfs(node, path = []) {
1227
- visited.add(node);
1228
- recursionStack.add(node);
1229
- path.push(node);
1230
- for (const neighbor of graph.get(node) || []) {
1231
- if (recursionStack.has(neighbor)) {
1232
- const cycleStart = path.indexOf(neighbor);
1233
- if (cycleStart !== -1) {
1234
- cycles.push([...path.slice(cycleStart), neighbor]);
1235
- }
1236
- } else if (!visited.has(neighbor)) {
1237
- dfs(neighbor, [...path]);
1238
- }
1239
- }
1240
- recursionStack.delete(node);
1241
- path.pop();
1242
- }
1243
- for (const node of graph.keys()) {
1244
- if (!visited.has(node)) {
1245
- dfs(node, []);
1246
- }
1247
- }
1248
- return cycles;
1249
- }
1250
- function topologicalSort(graphData) {
1251
- const { graph, inDegree } = graphData;
1252
- const order = [];
1253
- const queue = [];
1254
- for (const [node, degree] of inDegree.entries()) {
1255
- if (degree === 0) {
1256
- queue.push(node);
1257
- }
1258
- }
1259
- while (queue.length > 0) {
1260
- const node = queue.shift();
1261
- order.push(node);
1262
- const neighbors = Array.from(graph.get(node) || []);
1263
- for (const neighbor of neighbors) {
1264
- const newDegree = (inDegree.get(neighbor) || 0) - 1;
1265
- inDegree.set(neighbor, newDegree);
1266
- if (newDegree === 0) {
1267
- queue.push(neighbor);
1268
- }
1269
- }
1270
- }
1271
- if (order.length !== graph.size) {
1272
- const cycles = findCyclicDependencies(graph);
1273
- if (cycles.length > 0) {
1274
- const cycleStr = cycles.map((cycle) => ` ${cycle.join(" -> ")}`).join("\n");
1275
- throw new Error(`Circular dependencies detected:
1276
- ${cycleStr}`);
1277
- } else {
1278
- const unresolvedModules = Array.from(graph.keys()).filter((key) => !order.includes(key));
1279
- throw new Error(`Unable to resolve dependencies for modules: ${unresolvedModules.join(", ")}`);
1280
- }
1281
- }
1282
- return order;
1283
- }
1284
-
1285
- function resolveIgnorePatterns(silgi, relativePath) {
1286
- if (!silgi) {
1287
- return [];
1288
- }
1289
- const ignorePatterns = silgi.options.ignore.flatMap((s) => resolveGroupSyntax(s));
1290
- const nuxtignoreFile = join(silgi.options.rootDir, ".nuxtignore");
1291
- if (existsSync(nuxtignoreFile)) {
1292
- const contents = readFileSync(nuxtignoreFile, "utf-8");
1293
- ignorePatterns.push(...contents.trim().split(/\r?\n/));
1294
- }
1295
- return ignorePatterns;
1296
- }
1297
- function isIgnored(pathname, silgi, _stats) {
1298
- if (!silgi) {
1299
- return false;
1300
- }
1301
- if (!silgi._ignore) {
1302
- silgi._ignore = ignore(silgi.options.ignoreOptions);
1303
- silgi._ignore.add(resolveIgnorePatterns(silgi));
1304
- }
1305
- const relativePath = relative(silgi.options.rootDir, pathname);
1306
- if (relativePath[0] === "." && relativePath[1] === ".") {
1307
- return false;
1308
- }
1309
- return !!(relativePath && silgi._ignore.ignores(relativePath));
1310
- }
1311
- function resolveGroupSyntax(group) {
1312
- let groups = [group];
1313
- while (groups.some((group2) => group2.includes("{"))) {
1314
- groups = groups.flatMap((group2) => {
1315
- const [head, ...tail] = group2.split("{");
1316
- if (tail.length) {
1317
- const [body = "", ...rest] = tail.join("{").split("}");
1318
- return body.split(",").map((part) => `${head}${part}${rest.join("")}`);
1319
- }
1320
- return group2;
1321
- });
1322
- }
1323
- return groups;
1324
- }
1325
-
1326
- class SchemaParser {
1327
- options = {
1328
- debug: false
1329
- };
1330
- /**
1331
- *
1332
- */
1333
- constructor(options) {
1334
- this.options = {
1335
- ...this.options,
1336
- ...options
1337
- };
1338
- }
1339
- parseExports(content, filePath) {
1340
- const ast = parseSync(content, { sourceType: "module", sourceFilename: filePath });
1341
- if (this.options.debug)
1342
- writeFileSync(`${filePath}.ast.json`, JSON.stringify(ast.program, null, 2));
1343
- return {
1344
- exportVariables: (search, path) => this.parseTypeDeclarations(ast, search, path),
1345
- parseInterfaceDeclarations: (search, path) => this.parseInterfaceDeclarations(ast, search, path)
1346
- // parsePlugin: (path: string) => this.parsePlugin(ast, path),
1347
- };
1348
- }
1349
- parseVariableDeclaration(ast) {
1350
- return ast.program.body.filter((i) => i.type === "ExportNamedDeclaration").filter((i) => i.declaration?.type === "VariableDeclaration");
1351
- }
1352
- parseTSInterfaceDeclaration(ast) {
1353
- return ast.program.body.filter((i) => i.type === "ExportNamedDeclaration").filter((i) => i.declaration?.type === "TSInterfaceDeclaration");
1354
- }
1355
- parseTypeDeclarations(ast, find = "", path = "") {
1356
- const data = [];
1357
- for (const item of this.parseVariableDeclaration(ast)) {
1358
- for (const declaration of item.declaration.declarations) {
1359
- if (declaration.init?.callee?.name === find) {
1360
- const options = {};
1361
- if (declaration.init.arguments) {
1362
- for (const argument of declaration.init.arguments) {
1363
- for (const propertie of argument.properties) {
1364
- if (propertie.key.name === "name")
1365
- options.pluginName = propertie.value.value;
1366
- }
1367
- }
1368
- }
1369
- for (const key in declaration.init.properties) {
1370
- const property = declaration.init.properties[key];
1371
- if (property.type === "ObjectProperty") {
1372
- if (property.key.name === "options") {
1373
- for (const key2 in property.value.properties) {
1374
- const option = property.value.properties[key2];
1375
- if (option.type === "ObjectProperty") {
1376
- options[option.key.name] = option.value.value;
1377
- }
1378
- }
1379
- }
1380
- }
1381
- }
1382
- options.type = false;
1383
- data.push({
1384
- exportName: declaration.id.name,
1385
- options,
1386
- // object: declaration.init,
1387
- path
1388
- });
1389
- }
1390
- }
1391
- }
1392
- return data;
1393
- }
1394
- parseInterfaceDeclarations(ast, find = "", path = "") {
1395
- const data = [];
1396
- for (const item of this.parseTSInterfaceDeclaration(ast)) {
1397
- if (!item?.declaration?.extends)
1398
- continue;
1399
- for (const declaration of item?.declaration?.extends) {
1400
- if (declaration.expression.name === find) {
1401
- const options = {};
1402
- options.type = true;
1403
- data.push({
1404
- exportName: item.declaration.id.name,
1405
- options,
1406
- // object: declaration.init,
1407
- path
1408
- });
1409
- }
1410
- }
1411
- }
1412
- return data;
1413
- }
1414
- // private parsePlugin(ast: any, path: string = '') {
1415
- // const data = {
1416
- // export: [],
1417
- // name: '',
1418
- // path: '',
1419
- // } as DataTypePlugin
1420
- // for (const item of this.parseVariableDeclaration(ast)) {
1421
- // for (const declaration of item.declaration.declarations) {
1422
- // if (declaration.init.callee?.name === 'defineSilgiModule') {
1423
- // if (declaration.init.arguments) {
1424
- // for (const argument of declaration.init.arguments) {
1425
- // for (const propertie of argument.properties) {
1426
- // if (propertie.key.name === 'name')
1427
- // data.name = propertie.value.value
1428
- // }
1429
- // }
1430
- // }
1431
- // data.export.push({
1432
- // name: data.name,
1433
- // as: camelCase(`${data.name}DefineSilgiModule`),
1434
- // type: false,
1435
- // })
1436
- // }
1437
- // }
1438
- // }
1439
- // for (const item of this.parseTSInterfaceDeclaration(ast)) {
1440
- // if (!item?.declaration?.extends)
1441
- // continue
1442
- // for (const declaration of item?.declaration?.extends) {
1443
- // if (declaration.expression.name === 'ModuleOptions') {
1444
- // data.export.push({
1445
- // name: item.declaration.id.name,
1446
- // as: camelCase(`${data.name}ModuleOptions`),
1447
- // type: true,
1448
- // })
1449
- // }
1450
- // // TODO add other plugins
1451
- // }
1452
- // }
1453
- // data.path = path
1454
- // return data
1455
- // }
1456
- }
1457
-
1458
- async function scanFiles$1(silgi) {
1459
- const filePaths = /* @__PURE__ */ new Set();
1460
- const scannedPaths = [];
1461
- const dir = silgi.options.serverDir;
1462
- const files = (await globby(dir, { cwd: silgi.options.rootDir, ignore: silgi.options.ignore })).sort();
1463
- if (files.length) {
1464
- const siblings = await readdir(dirname(dir)).catch(() => []);
1465
- const directory = basename(dir);
1466
- if (!siblings.includes(directory)) {
1467
- const directoryLowerCase = directory.toLowerCase();
1468
- const caseCorrected = siblings.find((sibling) => sibling.toLowerCase() === directoryLowerCase);
1469
- if (caseCorrected) {
1470
- const original = relative(silgi.options.serverDir, dir);
1471
- const corrected = relative(silgi.options.serverDir, join(dirname(dir), caseCorrected));
1472
- consola$1.warn(`Components not scanned from \`~/${corrected}\`. Did you mean to name the directory \`~/${original}\` instead?`);
1473
- }
1474
- }
1475
- }
1476
- for (const _file of files) {
1477
- const filePath = resolve(dir, _file);
1478
- if (scannedPaths.find((d) => filePath.startsWith(withTrailingSlash(d))) || isIgnored(filePath, silgi)) {
1479
- continue;
1480
- }
1481
- if (filePaths.has(filePath)) {
1482
- continue;
1483
- }
1484
- filePaths.add(filePath);
1485
- if (silgi.options.extensions.includes(extname(filePath))) {
1486
- const parser = new SchemaParser({
1487
- debug: false
1488
- });
1489
- const readfile = readFileSync(filePath, "utf-8");
1490
- const { exportVariables, parseInterfaceDeclarations } = parser.parseExports(readfile, filePath);
1491
- const createServices = exportVariables("createService", filePath);
1492
- if (createServices.length > 0) {
1493
- for (const createService of createServices) {
1494
- const { exportName, path } = createService;
1495
- const randomString = hash(basename(path) + exportName);
1496
- const _name = `_v${randomString}`;
1497
- silgi.hook("prepare:core.ts", (options) => {
1498
- options.services.push(_name);
1499
- });
1500
- silgi.hook("prepare:core.ts", (options) => {
1501
- options.importItems[path] ??= {
1502
- import: [],
1503
- from: relativeWithDot(silgi.options.silgi.serverDir, path)
1504
- };
1505
- options.importItems[path].import.push({
1506
- name: `${exportName} as ${_name}`
1507
- });
1508
- });
1509
- }
1510
- }
1511
- const createSchemas = exportVariables("createSchema", filePath);
1512
- if (createSchemas.length > 0) {
1513
- for (const createSchema of createSchemas) {
1514
- const { exportName, path } = createSchema;
1515
- const randomString = hash(basename(path) + exportName);
1516
- const _name = `_v${randomString}`;
1517
- silgi.hook("prepare:core.ts", (options) => {
1518
- options.schemas.push(_name);
1519
- });
1520
- silgi.hook("prepare:core.ts", (options) => {
1521
- options.importItems[path] ??= {
1522
- import: [],
1523
- from: relativeWithDot(silgi.options.silgi.serverDir, path)
1524
- };
1525
- options.importItems[path].import.push({
1526
- name: `${exportName} as ${_name}`
1527
- });
1528
- });
1529
- }
1530
- }
1531
- const createShareds = exportVariables("createShared", filePath);
1532
- if (createShareds.length > 0) {
1533
- for (const createShared of createShareds) {
1534
- const { exportName, path } = createShared;
1535
- const randomString = hash(basename(path) + exportName);
1536
- const _name = `_v${randomString}`;
1537
- silgi.hook("prepare:core.ts", (options) => {
1538
- options.shareds.push(_name);
1539
- });
1540
- silgi.hook("prepare:core.ts", (options) => {
1541
- options.importItems[path] ??= {
1542
- import: [],
1543
- // Relative path kaldirmamiz gerekiyor bunlar hooklarin bittigi yerde karar verilmeli.
1544
- from: relativeWithDot(silgi.options.silgi.serverDir, path)
1545
- };
1546
- options.importItems[path].import.push({
1547
- name: `${exportName} as ${_name}`
1548
- });
1549
- });
1550
- }
1551
- }
1552
- const sharedsTypes = parseInterfaceDeclarations("ExtendShared", filePath);
1553
- if (sharedsTypes.length > 0) {
1554
- for (const sharedType of sharedsTypes) {
1555
- const { exportName, path } = sharedType;
1556
- const randomString = hash(basename(path) + exportName);
1557
- const _name = `_v${randomString}`;
1558
- silgi.hook("prepare:schema.ts", (options) => {
1559
- options.shareds.push({
1560
- key: _name,
1561
- value: _name
1562
- });
1563
- });
1564
- silgi.hook("prepare:schema.ts", (options) => {
1565
- options.importItems[path] ??= {
1566
- import: [],
1567
- from: path
1568
- };
1569
- options.importItems[path].import.push({
1570
- name: `${exportName} as ${_name}`,
1571
- type: true
1572
- });
1573
- });
1574
- }
1575
- }
1576
- const contextTypes = parseInterfaceDeclarations("ExtendContext", filePath);
1577
- if (contextTypes.length > 0) {
1578
- for (const contextType of contextTypes) {
1579
- const { exportName, path } = contextType;
1580
- const randomString = hash(basename(path) + exportName);
1581
- const _name = `_v${randomString}`;
1582
- silgi.hook("prepare:schema.ts", (options) => {
1583
- options.contexts.push({
1584
- key: _name,
1585
- value: _name
1586
- });
1587
- });
1588
- silgi.hook("prepare:schema.ts", (options) => {
1589
- options.importItems[path] ??= {
1590
- import: [],
1591
- from: path
1592
- };
1593
- options.importItems[path].import.push({
1594
- name: `${exportName} as ${_name}`,
1595
- type: true
1596
- });
1597
- });
1598
- }
1599
- }
1600
- }
1601
- }
1602
- }
1603
-
1604
- async function createStorageCLI(silgi) {
1605
- const storage = createStorage();
1606
- const mounts = klona({
1607
- ...silgi.options.storage,
1608
- ...silgi.options.devStorage
1609
- });
1610
- for (const [path, opts] of Object.entries(mounts)) {
1611
- if (opts.driver) {
1612
- const driver = await import(builtinDrivers[opts.driver] || opts.driver).then((r) => r.default || r);
1613
- storage.mount(path, driver(opts));
1614
- } else {
1615
- silgi.logger.warn(`No \`driver\` set for storage mount point "${path}".`);
1616
- }
1617
- }
1618
- return storage;
1619
- }
1620
-
1621
- const vueShim = {
1622
- filename: "delete/testtest.d.ts",
1623
- where: ".silgi",
1624
- getContents: ({ app }) => {
1625
- if (!app.options.typescript.shim) {
1626
- return "";
1627
- }
1628
- return [
1629
- "declare module '*.vue' {",
1630
- " import { DefineComponent } from 'vue'",
1631
- " const component: DefineComponent<{}, {}, any>",
1632
- " export default component",
1633
- "}"
1634
- ].join("\n");
1635
- }
1636
- };
1637
- const pluginsDeclaration = {
1638
- filename: "delete/testtest1.d.ts",
1639
- where: ".silgi",
1640
- getContents: async () => {
1641
- return `
1642
- declare module 'nuxt' {
1643
- interface NuxtApp {
1644
- $myPlugin: any;
1645
- }
1646
- }
1647
- `;
1648
- }
1649
- };
1650
-
1651
- const defaultTemplates = {
1652
- __proto__: null,
1653
- pluginsDeclaration: pluginsDeclaration,
1654
- vueShim: vueShim
1655
- };
1656
-
1657
- const postTemplates = [
1658
- pluginsDeclaration.filename
1659
- ];
1660
- const logger = useLogger("silgi");
1661
- async function generateApp(app, options = {}) {
1662
- app.templates = Object.values(defaultTemplates).concat(app.options.build.templates);
1663
- await app.callHook("app:templates", app);
1664
- app.templates = app.templates.map((tmpl) => {
1665
- 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;
1666
- return normalizeTemplate(tmpl, dir);
1667
- });
1668
- const filteredTemplates = {
1669
- pre: [],
1670
- post: []
1671
- };
1672
- for (const template of app.templates) {
1673
- if (options.filter && !options.filter(template)) {
1674
- continue;
1675
- }
1676
- const key = template.filename && postTemplates.includes(template.filename) ? "post" : "pre";
1677
- filteredTemplates[key].push(template);
1678
- }
1679
- const templateContext = { app };
1680
- const writes = [];
1681
- const dirs = /* @__PURE__ */ new Set();
1682
- const changedTemplates = [];
1683
- async function processTemplate(template) {
1684
- 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;
1685
- const fullPath = template.dst || resolve(dir, template.filename);
1686
- const start = performance.now();
1687
- const contents = await compileTemplate(template, templateContext).catch((e) => {
1688
- logger.error(`Could not compile template \`${template.filename}\`.`);
1689
- logger.error(e);
1690
- throw e;
1691
- });
1692
- template.modified = true;
1693
- if (template.modified) {
1694
- changedTemplates.push(template);
1695
- }
1696
- const perf = performance.now() - start;
1697
- const setupTime = Math.round(perf * 100) / 100;
1698
- if (app.options.debug || setupTime > 500) {
1699
- logger.info(`Compiled \`${template.filename}\` in ${setupTime}ms`);
1700
- }
1701
- if (template.modified && template.write) {
1702
- dirs.add(dirname(fullPath));
1703
- writes.push(() => writeFileSync(fullPath, contents, "utf8"));
1704
- }
1705
- }
1706
- await Promise.allSettled(filteredTemplates.pre.map(processTemplate));
1707
- await Promise.allSettled(filteredTemplates.post.map(processTemplate));
1708
- for (const dir of dirs) {
1709
- mkdirSync(dir, { recursive: true });
1710
- }
1711
- for (const write of writes) {
1712
- write();
1713
- }
1714
- if (changedTemplates.length) {
1715
- await app.callHook("app:templatesGenerated", app, changedTemplates, options);
1716
- }
1717
- }
1718
- async function compileTemplate(template, ctx) {
1719
- delete ctx.utils;
1720
- if (template.src) {
1721
- try {
1722
- return await promises.readFile(template.src, "utf-8");
1723
- } catch (err) {
1724
- logger.error(`[nuxt] Error reading template from \`${template.src}\``);
1725
- throw err;
1726
- }
1727
- }
1728
- if (template.getContents) {
1729
- return template.getContents({
1730
- ...ctx,
1731
- options: template.options
1732
- });
1733
- }
1734
- throw new Error(`[nuxt] Invalid template. Templates must have either \`src\` or \`getContents\`: ${JSON.stringify(template)}`);
1735
- }
1736
-
1737
- async function commands(silgi) {
1738
- const commands2 = {
1739
- ...silgi.options.commands
1740
- };
1741
- await silgi.callHook("prepare:commands", commands2);
1742
- addTemplate({
1743
- filename: "cli.json",
1744
- where: ".silgi",
1745
- write: true,
1746
- getContents: () => JSON.stringify(commands2, null, 2)
1747
- });
1748
- }
1749
-
1750
- async function installPackages(silgi) {
1751
- const packages = {
1752
- dependencies: {
1753
- "@fastify/deepmerge": peerDependencies["@fastify/deepmerge"],
1754
- ...silgi.options.installPackages?.dependencies
1755
- },
1756
- devDependencies: {
1757
- ...silgi.options.installPackages?.devDependencies
1758
- }
1759
- };
1760
- await silgi.callHook("prepare:installPackages", packages);
1761
- if (silgi.options.preset === "npm-package") {
1762
- packages.devDependencies = {
1763
- ...packages.devDependencies,
1764
- ...packages.dependencies
1765
- };
1766
- packages.dependencies = {};
1767
- }
1768
- addTemplate({
1769
- filename: "install.json",
1770
- where: ".silgi",
1771
- write: true,
1772
- getContents: () => JSON.stringify(packages, null, 2)
1773
- });
1774
- }
1775
-
1776
- function _deepFreeze(object) {
1777
- const propNames = Object.getOwnPropertyNames(object);
1778
- for (const name of propNames) {
1779
- const value = object[name];
1780
- if (value && typeof value === "object") {
1781
- _deepFreeze(value);
1782
- }
1783
- }
1784
- return Object.freeze(object);
1785
- }
1786
- function useCLIRuntimeConfig(silgi) {
1787
- const _inlineRuntimeConfig = silgi.options.runtimeConfig;
1788
- const envOptions = {
1789
- prefix: "NITRO_",
1790
- altPrefix: process.env.NITRO_ENV_PREFIX ?? process.env.SILGI_ENV_PREFIX ?? "_",
1791
- silgiPrefix: "SILGI_",
1792
- envExpansion: process.env.NITRO_ENV_EXPANSION ?? process.env.SILGI_ENV_EXPANSION ?? false,
1793
- ...silgi.options.envOptions
1794
- };
1795
- silgi.hook("prepare:core.ts", (data) => {
1796
- data.cliOptions.envOptions = envOptions;
1797
- });
1798
- const _sharedRuntimeConfig = _deepFreeze(
1799
- applyEnv(klona(_inlineRuntimeConfig), envOptions)
1800
- );
1801
- silgi.options.runtimeConfig = _sharedRuntimeConfig;
1802
- return _sharedRuntimeConfig;
1803
- }
1804
-
1805
- const GLOB_SCAN_PATTERN = "**/*.{js,mjs,cjs,ts,mts,cts,tsx,jsx}";
1806
- async function scanAndSyncOptions(silgi) {
1807
- const scannedModules = await scanModules(silgi);
1808
- silgi.options.modules = silgi.options.modules || [];
1809
- for (const modPath of scannedModules) {
1810
- if (!silgi.options.modules.includes(modPath)) {
1811
- silgi.options.modules.push(modPath);
1812
- }
1813
- }
1814
- }
1815
- async function scanModules(silgi) {
1816
- const files = await scanFiles(silgi, "silgi/modules");
1817
- return files.map((f) => f.fullPath);
1818
- }
1819
- async function scanFiles(silgi, name) {
1820
- const files = await Promise.all(
1821
- silgi.options.scanDirs.map((dir) => scanDir(silgi, dir, name))
1822
- ).then((r) => r.flat());
1823
- return files;
1824
- }
1825
- async function scanDir(silgi, dir, name) {
1826
- const fileNames = await globby(join(name, GLOB_SCAN_PATTERN), {
1827
- cwd: dir,
1828
- dot: true,
1829
- ignore: silgi.options.ignore,
1830
- absolute: true
1831
- });
1832
- return fileNames.map((fullPath) => {
1833
- return {
1834
- fullPath,
1835
- path: relative(join(dir, name), fullPath)
1836
- };
1837
- }).sort((a, b) => a.path.localeCompare(b.path));
1838
- }
1839
-
1840
- async function createSilgiCLI(config = {}, opts = {}) {
1841
- const options = await loadOptions(config, opts);
1842
- await prepareEnv(options);
1843
- const hooks = createHooks();
1844
- const silgi = {
1845
- modulesURIs: {},
1846
- scannedURIs: /* @__PURE__ */ new Map(),
1847
- services: {},
1848
- uris: {},
1849
- shareds: {},
1850
- schemas: {},
1851
- unimport: void 0,
1852
- options,
1853
- hooks,
1854
- // vfs: {}
1855
- _requiredModules: {},
1856
- logger: consola$1.withTag("silgi"),
1857
- close: () => silgi.hooks.callHook("close", silgi),
1858
- storage: void 0,
1859
- scanModules: [],
1860
- templates: [],
1861
- callHook: hooks.callHook,
1862
- addHooks: hooks.addHooks,
1863
- hook: hooks.hook,
1864
- async updateConfig(_config) {
1865
- }
1866
- };
1867
- useCLIRuntimeConfig(silgi);
1868
- if (silgiCLICtx.tryUse()) {
1869
- silgiCLICtx.unset();
1870
- silgiCLICtx.set(silgi);
1871
- } else {
1872
- silgiCLICtx.set(silgi);
1873
- silgi.hook("close", () => silgiCLICtx.unset());
1874
- }
1875
- if (silgi.options.debug) {
1876
- createDebugger(silgi.hooks, { tag: "silgi" });
1877
- silgi.options.plugins.push({
1878
- path: join(runtimeDir, "internal/debug"),
1879
- packageImport: "silgi/runtime/internal/debug"
1880
- });
1881
- }
1882
- for (const framework of frameworkSetup) {
1883
- await framework(silgi);
1884
- }
1885
- await scanAndSyncOptions(silgi);
1886
- await scanModules$1(silgi);
1887
- await scanFiles$1(silgi);
1888
- silgi.storage = await createStorageCLI(silgi);
1889
- silgi.hooks.hook("close", async () => {
1890
- await silgi.storage.dispose();
1891
- });
1892
- if (silgi.options.logLevel !== void 0) {
1893
- silgi.logger.level = silgi.options.logLevel;
1894
- }
1895
- silgi.hooks.addHooks(silgi.options.hooks);
1896
- await installModules(silgi);
1897
- await silgi.hooks.callHook("scanFiles:done", silgi);
1898
- await commands(silgi);
1899
- await installPackages(silgi);
1900
- await generateApp(silgi);
1901
- if (silgi.options.imports) {
1902
- silgi.options.imports.dirs ??= [];
1903
- silgi.options.imports.dirs.push(
1904
- join(silgi.options.serverDir, "**/*")
1905
- );
1906
- silgi.options.imports.presets.push({
1907
- from: "silgi/types",
1908
- imports: autoImportTypes.map((type) => type),
1909
- type: true
1910
- });
1911
- silgi.options.imports.presets.push({
1912
- from: "silgi/types",
1913
- imports: autoImportTypes.map((type) => type),
1914
- type: true
1915
- });
1916
- silgi.options.imports.presets.push({
1917
- from: "silgi/runtime/internal/ofetch",
1918
- imports: ["createSilgiFetch", "silgi$fetch"]
1919
- });
1920
- silgi.unimport = createUnimport(silgi.options.imports);
1921
- await silgi.unimport.init();
1922
- }
1923
- await registerModuleExportScan(silgi);
1924
- return silgi;
1925
- }
38
+ import 'pkg-types';
39
+ import 'pathe/utils';
40
+ import './types.mjs';
1926
41
 
1927
42
  const prepare = defineCommand({
1928
43
  meta: {
@@ -1942,27 +57,25 @@ const prepare = defineCommand({
1942
57
  }
1943
58
  },
1944
59
  async run({ args }) {
1945
- async function generate() {
1946
- const rootDir = resolve(args.dir || args._dir || ".");
1947
- const silgi = await createSilgiCLI({
1948
- rootDir,
1949
- dev: args.stub,
1950
- stub: args.stub,
1951
- preset: args.preset,
1952
- commandType: "prepare"
1953
- });
1954
- await prepare$1();
1955
- await writeTypesAndFiles(silgi);
1956
- await silgi.callHook("read:core.ts", async () => {
1957
- const data = await readCoreFile(silgi);
1958
- return data;
1959
- });
60
+ const rootDir = resolve(args.dir || args._dir || ".");
61
+ const silgi = await createSilgiCLI({
62
+ rootDir,
63
+ dev: args.stub,
64
+ stub: args.stub,
65
+ preset: args.preset,
66
+ commandType: "prepare"
67
+ });
68
+ await prepare$1();
69
+ await writeTypesAndFiles(silgi);
70
+ await writeCoreFile(silgi);
71
+ const close = async () => {
1960
72
  await silgi.close();
1961
- }
1962
- await generate();
1963
- await generate();
73
+ await silgi.callHook("close", silgi);
74
+ consola.withTag("silgi").success("Process terminated");
75
+ };
76
+ await silgi.callHook("close", silgi);
1964
77
  consola.withTag("silgi").success("Prepare completed");
1965
- process.exit(0);
78
+ await close();
1966
79
  }
1967
80
  });
1968
81