silgi 0.42.5 → 0.43.0

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