@jayfong/x-server 2.118.1 → 3.0.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 (290) hide show
  1. package/lib/_virtual/_rolldown/runtime.mjs +4 -0
  2. package/lib/cli/api_generator.d.mts +74 -0
  3. package/lib/cli/api_generator.mjs +310 -0
  4. package/lib/cli/build_util.d.mts +17 -0
  5. package/lib/cli/build_util.mjs +156 -0
  6. package/lib/cli/cli.d.mts +1 -0
  7. package/lib/cli/cli.mjs +355 -0
  8. package/lib/cli/css_register.d.mts +1 -0
  9. package/lib/cli/css_register.mjs +7 -0
  10. package/lib/cli/deploy_util.d.mts +23 -0
  11. package/lib/cli/deploy_util.mjs +70 -0
  12. package/lib/cli/dev_util.d.mts +7 -0
  13. package/lib/cli/dev_util.mjs +25 -0
  14. package/lib/cli/env_util.d.mts +45 -0
  15. package/lib/cli/env_util.mjs +207 -0
  16. package/lib/cli/esbuild_register.d.mts +1 -0
  17. package/lib/cli/esbuild_register.mjs +7 -0
  18. package/lib/cli/template_util.d.mts +18 -0
  19. package/lib/cli/template_util.mjs +85 -0
  20. package/lib/cli/templates/crons.ts +1 -1
  21. package/lib/cli/templates/handlers.ts +1 -1
  22. package/lib/cli/templates/hooks.ts +1 -1
  23. package/lib/cli/templates/models.ts +7 -7
  24. package/lib/cli/templates/package.json +11 -1
  25. package/lib/cli/templates/routes.ts +2 -1
  26. package/lib/core/ctx_storage.d.mts +3 -0
  27. package/lib/core/ctx_storage.mjs +4 -0
  28. package/lib/core/define_bus.d.mts +37 -0
  29. package/lib/core/define_bus.mjs +12 -0
  30. package/lib/core/{define_cron.d.ts → define_cron.d.mts} +2 -2
  31. package/lib/core/define_cron.mjs +11 -0
  32. package/lib/core/{define_handler.d.ts → define_handler.d.mts} +19 -19
  33. package/lib/core/define_handler.mjs +44 -0
  34. package/lib/core/define_hook.d.mts +2 -0
  35. package/lib/core/define_hook.mjs +6 -0
  36. package/lib/core/define_server.d.mts +3 -0
  37. package/lib/core/define_server.mjs +8 -0
  38. package/lib/core/{define_task.d.ts → define_task.d.mts} +2 -2
  39. package/lib/core/define_task.mjs +102 -0
  40. package/lib/core/get_handler_url.d.mts +2 -0
  41. package/lib/core/get_handler_url.mjs +7 -0
  42. package/lib/core/handler.d.mts +16 -0
  43. package/lib/core/handler.mjs +132 -0
  44. package/lib/core/http_error.d.mts +2 -0
  45. package/lib/core/http_error.mjs +1 -0
  46. package/lib/core/http_header.d.mts +856 -0
  47. package/lib/core/http_header.mjs +860 -0
  48. package/lib/core/http_method.d.mts +3 -0
  49. package/lib/core/http_method.mjs +10 -0
  50. package/lib/core/http_redirect.d.mts +5 -0
  51. package/lib/core/http_redirect.mjs +10 -0
  52. package/lib/core/server.d.mts +20 -0
  53. package/lib/core/server.mjs +186 -0
  54. package/lib/core/types.d.mts +256 -0
  55. package/lib/exports.d.mts +46 -0
  56. package/lib/exports.mjs +46 -0
  57. package/lib/index.d.mts +48 -0
  58. package/lib/index.mjs +45 -0
  59. package/lib/plugins/base.d.mts +4 -0
  60. package/lib/plugins/compress.d.mts +12 -0
  61. package/lib/plugins/compress.mjs +15 -0
  62. package/lib/plugins/cookie.d.mts +12 -0
  63. package/lib/plugins/cookie.mjs +15 -0
  64. package/lib/plugins/cors.d.mts +22 -0
  65. package/lib/plugins/cors.mjs +34 -0
  66. package/lib/plugins/file_parser.d.mts +15 -0
  67. package/lib/plugins/file_parser.mjs +24 -0
  68. package/lib/plugins/form_body_parser.d.mts +12 -0
  69. package/lib/plugins/form_body_parser.mjs +15 -0
  70. package/lib/plugins/ws_parser.d.mts +12 -0
  71. package/lib/plugins/ws_parser.mjs +15 -0
  72. package/lib/plugins/xml_parser.d.mts +19 -0
  73. package/lib/plugins/xml_parser.mjs +40 -0
  74. package/lib/services/ai.d.mts +31 -0
  75. package/lib/services/ai.mjs +44 -0
  76. package/lib/services/base.d.mts +4 -0
  77. package/lib/services/base.mjs +1 -0
  78. package/lib/services/cache.d.mts +165 -0
  79. package/lib/services/cache.mjs +323 -0
  80. package/lib/services/captcha.d.mts +65 -0
  81. package/lib/services/captcha.mjs +61 -0
  82. package/lib/services/{crypto.js → crypto.d.mts} +19 -78
  83. package/lib/services/crypto.mjs +141 -0
  84. package/lib/services/db_value.d.mts +60 -0
  85. package/lib/services/db_value.mjs +64 -0
  86. package/lib/services/dingtalk.d.mts +39 -0
  87. package/lib/services/dingtalk.mjs +44 -0
  88. package/lib/services/dispose.d.mts +17 -0
  89. package/lib/services/dispose.mjs +18 -0
  90. package/lib/services/emoji.d.mts +10 -0
  91. package/lib/services/emoji.mjs +2025 -0
  92. package/lib/services/file_store.d.mts +49 -0
  93. package/lib/services/file_store.mjs +58 -0
  94. package/lib/services/html.d.mts +11 -0
  95. package/lib/services/html.mjs +12 -0
  96. package/lib/services/jwt.d.mts +33 -0
  97. package/lib/services/jwt.mjs +42 -0
  98. package/lib/services/log.d.mts +37 -0
  99. package/lib/services/log.mjs +99 -0
  100. package/lib/services/mail.d.mts +22 -0
  101. package/lib/services/mail.mjs +28 -0
  102. package/lib/services/pay.d.mts +123 -0
  103. package/lib/services/pay.mjs +157 -0
  104. package/lib/services/random.d.mts +27 -0
  105. package/lib/services/random.mjs +42 -0
  106. package/lib/services/rate_limit.d.mts +37 -0
  107. package/lib/services/rate_limit.mjs +40 -0
  108. package/lib/services/redis.d.mts +11 -0
  109. package/lib/services/redis.mjs +6 -0
  110. package/lib/services/sensitive_words.d.mts +29 -0
  111. package/lib/services/sensitive_words.mjs +37 -0
  112. package/lib/services/sms.d.mts +40 -0
  113. package/lib/services/sms.mjs +30238 -0
  114. package/lib/types/dto.d.mts +30 -0
  115. package/lib/types/dto.mjs +1 -0
  116. package/lib/x.d.mts +11 -0
  117. package/lib/x.mjs +21 -0
  118. package/lib/x_init.d.mts +1 -0
  119. package/lib/x_init.mjs +10 -0
  120. package/package.json +99 -43
  121. package/lib/_cjs/cli/api_generator.js +0 -438
  122. package/lib/_cjs/cli/build_util.js +0 -243
  123. package/lib/_cjs/cli/cli.js +0 -378
  124. package/lib/_cjs/cli/css_register.js +0 -7
  125. package/lib/_cjs/cli/deploy_util.js +0 -76
  126. package/lib/_cjs/cli/dev_util.js +0 -25
  127. package/lib/_cjs/cli/env_util.js +0 -252
  128. package/lib/_cjs/cli/esbuild_register.js +0 -7
  129. package/lib/_cjs/cli/template_util.js +0 -101
  130. package/lib/_cjs/cli/templates/crons.ts +0 -2
  131. package/lib/_cjs/cli/templates/handlers.ts +0 -3
  132. package/lib/_cjs/cli/templates/hooks.ts +0 -2
  133. package/lib/_cjs/cli/templates/models.ts +0 -123
  134. package/lib/_cjs/cli/templates/package.json +0 -3
  135. package/lib/_cjs/cli/templates/routes.ts +0 -68
  136. package/lib/_cjs/core/ctx_storage.js +0 -6
  137. package/lib/_cjs/core/define_bus.js +0 -31
  138. package/lib/_cjs/core/define_cron.js +0 -13
  139. package/lib/_cjs/core/define_handler.js +0 -56
  140. package/lib/_cjs/core/define_hook.js +0 -8
  141. package/lib/_cjs/core/define_server.js +0 -10
  142. package/lib/_cjs/core/define_task.js +0 -113
  143. package/lib/_cjs/core/get_handler_url.js +0 -11
  144. package/lib/_cjs/core/handler.js +0 -216
  145. package/lib/_cjs/core/http_error.js +0 -6
  146. package/lib/_cjs/core/http_header.js +0 -142
  147. package/lib/_cjs/core/http_method.js +0 -12
  148. package/lib/_cjs/core/http_redirect.js +0 -11
  149. package/lib/_cjs/core/server.js +0 -221
  150. package/lib/_cjs/core/types.js +0 -8
  151. package/lib/_cjs/exports.js +0 -273
  152. package/lib/_cjs/index.js +0 -15
  153. package/lib/_cjs/plugins/base.js +0 -3
  154. package/lib/_cjs/plugins/compress.js +0 -18
  155. package/lib/_cjs/plugins/cookie.js +0 -18
  156. package/lib/_cjs/plugins/cors.js +0 -38
  157. package/lib/_cjs/plugins/file_parser.js +0 -28
  158. package/lib/_cjs/plugins/form_body_parser.js +0 -18
  159. package/lib/_cjs/plugins/ws_parser.js +0 -18
  160. package/lib/_cjs/plugins/xml_parser.js +0 -48
  161. package/lib/_cjs/services/ai.js +0 -48
  162. package/lib/_cjs/services/base.js +0 -3
  163. package/lib/_cjs/services/cache.js +0 -400
  164. package/lib/_cjs/services/captcha.js +0 -78
  165. package/lib/_cjs/services/crypto.js +0 -175
  166. package/lib/_cjs/services/db_value.js +0 -77
  167. package/lib/_cjs/services/dingtalk.js +0 -51
  168. package/lib/_cjs/services/dispose.js +0 -23
  169. package/lib/_cjs/services/emoji.js +0 -2034
  170. package/lib/_cjs/services/file_store.js +0 -67
  171. package/lib/_cjs/services/html.js +0 -17
  172. package/lib/_cjs/services/jwt.js +0 -65
  173. package/lib/_cjs/services/log.js +0 -108
  174. package/lib/_cjs/services/mail.js +0 -31
  175. package/lib/_cjs/services/pay.js +0 -191
  176. package/lib/_cjs/services/random.js +0 -51
  177. package/lib/_cjs/services/rate_limit.js +0 -54
  178. package/lib/_cjs/services/redis.js +0 -12
  179. package/lib/_cjs/services/sensitive_words.js +0 -62
  180. package/lib/_cjs/services/sms.js +0 -84
  181. package/lib/_cjs/types/dto.js +0 -3
  182. package/lib/_cjs/x.js +0 -35
  183. package/lib/cli/api_generator.d.ts +0 -74
  184. package/lib/cli/api_generator.js +0 -432
  185. package/lib/cli/build_util.d.ts +0 -17
  186. package/lib/cli/build_util.js +0 -236
  187. package/lib/cli/cli.d.ts +0 -2
  188. package/lib/cli/cli.js +0 -374
  189. package/lib/cli/css_register.js +0 -5
  190. package/lib/cli/deploy_util.d.ts +0 -23
  191. package/lib/cli/deploy_util.js +0 -70
  192. package/lib/cli/dev_util.d.ts +0 -8
  193. package/lib/cli/dev_util.js +0 -19
  194. package/lib/cli/env_util.d.ts +0 -45
  195. package/lib/cli/env_util.js +0 -246
  196. package/lib/cli/esbuild_register.js +0 -5
  197. package/lib/cli/template_util.d.ts +0 -18
  198. package/lib/cli/template_util.js +0 -95
  199. package/lib/core/ctx_storage.d.ts +0 -3
  200. package/lib/core/ctx_storage.js +0 -2
  201. package/lib/core/define_bus.d.ts +0 -37
  202. package/lib/core/define_bus.js +0 -27
  203. package/lib/core/define_cron.js +0 -9
  204. package/lib/core/define_handler.js +0 -48
  205. package/lib/core/define_hook.d.ts +0 -2
  206. package/lib/core/define_hook.js +0 -4
  207. package/lib/core/define_server.d.ts +0 -3
  208. package/lib/core/define_server.js +0 -6
  209. package/lib/core/define_task.js +0 -107
  210. package/lib/core/get_handler_url.d.ts +0 -2
  211. package/lib/core/get_handler_url.js +0 -7
  212. package/lib/core/handler.d.ts +0 -16
  213. package/lib/core/handler.js +0 -209
  214. package/lib/core/http_error.d.ts +0 -2
  215. package/lib/core/http_error.js +0 -2
  216. package/lib/core/http_header.d.ts +0 -856
  217. package/lib/core/http_header.js +0 -139
  218. package/lib/core/http_method.d.ts +0 -3
  219. package/lib/core/http_method.js +0 -8
  220. package/lib/core/http_redirect.d.ts +0 -5
  221. package/lib/core/http_redirect.js +0 -6
  222. package/lib/core/server.d.ts +0 -20
  223. package/lib/core/server.js +0 -215
  224. package/lib/core/types.d.ts +0 -265
  225. package/lib/core/types.js +0 -4
  226. package/lib/exports.d.ts +0 -45
  227. package/lib/exports.js +0 -47
  228. package/lib/index.d.ts +0 -2
  229. package/lib/index.js +0 -3
  230. package/lib/plugins/base.d.ts +0 -4
  231. package/lib/plugins/base.js +0 -1
  232. package/lib/plugins/compress.d.ts +0 -13
  233. package/lib/plugins/compress.js +0 -12
  234. package/lib/plugins/cookie.d.ts +0 -13
  235. package/lib/plugins/cookie.js +0 -12
  236. package/lib/plugins/cors.d.ts +0 -22
  237. package/lib/plugins/cors.js +0 -33
  238. package/lib/plugins/file_parser.d.ts +0 -16
  239. package/lib/plugins/file_parser.js +0 -22
  240. package/lib/plugins/form_body_parser.d.ts +0 -13
  241. package/lib/plugins/form_body_parser.js +0 -12
  242. package/lib/plugins/ws_parser.d.ts +0 -13
  243. package/lib/plugins/ws_parser.js +0 -12
  244. package/lib/plugins/xml_parser.d.ts +0 -19
  245. package/lib/plugins/xml_parser.js +0 -43
  246. package/lib/services/ai.d.ts +0 -31
  247. package/lib/services/ai.js +0 -43
  248. package/lib/services/base.d.ts +0 -4
  249. package/lib/services/base.js +0 -1
  250. package/lib/services/cache.d.ts +0 -173
  251. package/lib/services/cache.js +0 -394
  252. package/lib/services/captcha.d.ts +0 -65
  253. package/lib/services/captcha.js +0 -72
  254. package/lib/services/crypto.d.ts +0 -110
  255. package/lib/services/db_value.d.ts +0 -60
  256. package/lib/services/db_value.js +0 -72
  257. package/lib/services/dingtalk.d.ts +0 -39
  258. package/lib/services/dingtalk.js +0 -45
  259. package/lib/services/dispose.d.ts +0 -17
  260. package/lib/services/dispose.js +0 -17
  261. package/lib/services/emoji.d.ts +0 -10
  262. package/lib/services/emoji.js +0 -2029
  263. package/lib/services/file_store.d.ts +0 -49
  264. package/lib/services/file_store.js +0 -61
  265. package/lib/services/html.d.ts +0 -11
  266. package/lib/services/html.js +0 -12
  267. package/lib/services/jwt.d.ts +0 -34
  268. package/lib/services/jwt.js +0 -59
  269. package/lib/services/log.d.ts +0 -37
  270. package/lib/services/log.js +0 -102
  271. package/lib/services/mail.d.ts +0 -23
  272. package/lib/services/mail.js +0 -25
  273. package/lib/services/pay.d.ts +0 -123
  274. package/lib/services/pay.js +0 -185
  275. package/lib/services/random.d.ts +0 -27
  276. package/lib/services/random.js +0 -45
  277. package/lib/services/rate_limit.d.ts +0 -37
  278. package/lib/services/rate_limit.js +0 -49
  279. package/lib/services/redis.d.ts +0 -12
  280. package/lib/services/redis.js +0 -7
  281. package/lib/services/sensitive_words.d.ts +0 -30
  282. package/lib/services/sensitive_words.js +0 -57
  283. package/lib/services/sms.d.ts +0 -40
  284. package/lib/services/sms.js +0 -78
  285. package/lib/types/dto.d.ts +0 -86
  286. package/lib/types/dto.js +0 -1
  287. package/lib/x.d.ts +0 -17
  288. package/lib/x.js +0 -30
  289. /package/lib/{cli/css_register.d.ts → core/types.mjs} +0 -0
  290. /package/lib/{cli/esbuild_register.d.ts → plugins/base.mjs} +0 -0
@@ -1,252 +0,0 @@
1
- "use strict";
2
-
3
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
4
- exports.__esModule = true;
5
- exports.EnvUtil = void 0;
6
- var _nodePath = _interopRequireDefault(require("node:path"));
7
- var _fsExtra = _interopRequireDefault(require("fs-extra"));
8
- var _globby = _interopRequireDefault(require("globby"));
9
- var _pinyinPro = require("pinyin-pro");
10
- var _vtils = require("vtils");
11
- var _yaml = require("yaml");
12
- class EnvUtil {
13
- static async getAllChannel(cwd, excludeChannels) {
14
- const channelFiles = await (0, _globby.default)(['.env@*'], {
15
- cwd: cwd,
16
- onlyFiles: true,
17
- absolute: false
18
- });
19
- if (channelFiles.length === 0) {
20
- return [];
21
- }
22
- let channels = (0, _vtils.uniq)(channelFiles.map(channel => channel.split('@').pop().split('.')[0]));
23
- if (excludeChannels?.length) {
24
- channels = (0, _vtils.difference)(channels, excludeChannels);
25
- }
26
- return channels;
27
- }
28
- static async chooseChannel(cwd, excludeChannels) {
29
- const channels = await EnvUtil.getAllChannel(cwd, excludeChannels);
30
- if (channels.length === 0) return undefined;
31
- if (channels.length === 1) return channels[0];
32
- const channelOptions = channels.sort((a, b) => a.localeCompare(b, 'zh-CN')).map(channel => {
33
- const channelPinyin = (0, _pinyinPro.pinyin)(channel, {
34
- type: 'string',
35
- pattern: 'first',
36
- toneType: 'none',
37
- separator: '',
38
- removeNonZh: false,
39
- nonZh: 'consecutive'
40
- }).toLowerCase();
41
- return {
42
- name: channel,
43
- value: channel,
44
- pinyin: channelPinyin,
45
- description: `${channel}<${channelPinyin}>`
46
- };
47
- });
48
- // @ts-ignore
49
- const {
50
- default: autocomplete
51
- } = await import('inquirer-autocomplete-standalone');
52
- const selectedChannel = await autocomplete({
53
- message: '请选择渠道',
54
- source: async input => {
55
- return !input ? channelOptions : channelOptions.filter(channelOption => {
56
- return channelOption.pinyin.includes(input) || channelOption.name.includes(input);
57
- });
58
- }
59
- });
60
- return selectedChannel || undefined;
61
- }
62
- static async withChannel(options) {
63
- const successChannels = [];
64
- const failedChannels = [];
65
- if (options.channel?.startsWith('_')) {
66
- const excludeChannels = options.channel.split('!')[1]?.split(',').filter(Boolean);
67
- const channel = process.env.APP_CHANNEL || (await EnvUtil.chooseChannel(options.cwd, excludeChannels));
68
- console.log(`========= ${channel} =========`);
69
- try {
70
- await options.cb(channel);
71
- successChannels.push(channel);
72
- } catch (err) {
73
- console.error(err);
74
- failedChannels.push(channel);
75
- }
76
- } else if (options.channel?.startsWith('@')) {
77
- const excludeChannels = options.channel.split('!')[1]?.split(',').filter(Boolean);
78
- const channels = await EnvUtil.getAllChannel(options.cwd, excludeChannels);
79
- await Promise.all(channels.map((0, _vtils.asyncLimit)(async channel => {
80
- console.log(`========= ${channel} =========`);
81
- try {
82
- await options.cb(channel);
83
- successChannels.push(channel);
84
- } catch (err) {
85
- console.error(err);
86
- failedChannels.push(channel);
87
- }
88
- }, {
89
- concurrency: options.concurrency || 1
90
- })));
91
- } else {
92
- if (options.channel) {
93
- console.log(`========= ${options.channel} =========`);
94
- }
95
- try {
96
- await options.cb(options.channel);
97
- options.channel && successChannels.push(options.channel);
98
- } catch (err) {
99
- console.error(err);
100
- options.channel && failedChannels.push(options.channel);
101
- }
102
- }
103
- if (successChannels.length) {
104
- console.log(`✅(${successChannels.length}):${JSON.stringify(successChannels)}`);
105
- }
106
- if (failedChannels.length) {
107
- console.log(`❌(${failedChannels.length}):${JSON.stringify(failedChannels)}`);
108
- }
109
- }
110
- static getFile(env, channel, noBase) {
111
- const file = ['.env_meta', ...(noBase ? [] : ['.env'])];
112
- if (!noBase && channel) {
113
- file.push(`.env@${channel}`);
114
- }
115
- if (env) {
116
- file.push(`.env.${env}`);
117
- if (channel) {
118
- file.push(`.env@${channel}.${env}`);
119
- }
120
- }
121
- return file;
122
- }
123
- static parseContent(src, _envItemMap, _envValueMap, channel) {
124
- const envs = [];
125
- const envObj = (0, _yaml.parse)(src);
126
- if (channel) {
127
- const channelEnvs = envObj.__CHANNEL__;
128
- if (channelEnvs && Array.isArray(channelEnvs)) {
129
- for (const channelEnv of channelEnvs) {
130
- const channels = (0, _vtils.castArray)(channelEnv._).flatMap(item => item.split(','));
131
- if (channels.includes(channel)) {
132
- delete channelEnv._;
133
- Object.assign(envObj, channelEnv);
134
- break;
135
- }
136
- }
137
- }
138
- }
139
- delete envObj.__CHANNEL__;
140
- const inlineVars = value => {
141
- if (Array.isArray(value)) {
142
- return value.map(inlineVars);
143
- }
144
- if ((0, _vtils.isPlainObject)(value)) {
145
- return Object.keys(value).reduce((acc, key) => {
146
- acc[key] = inlineVars(value[key]);
147
- return acc;
148
- }, {});
149
- }
150
- if (typeof value === 'string') {
151
- return value.replace(/\{\{\s*(.+?)\s*\}\}/g, (_, key) => (0, _vtils.get)(_envValueMap || envObj, key) || process.env[key] || '');
152
- }
153
- return value;
154
- };
155
- Object.keys(envObj).forEach(key => {
156
- const value = inlineVars(envObj[key]);
157
- const envItem = {
158
- key: key,
159
- value: value,
160
- comment: src.match(new RegExp(`((#\\s*(.+?)\\s*[\\r\\n]+)+)\\s*${(0, _vtils.escapeRegExp)(key)}:`))?.[1].split(/(\r\n){2,}|\r{2,}|\n{2,}/g).pop()?.replace(/^#/gm, '').trim() || ''
161
- };
162
- if (_envItemMap) {
163
- _envItemMap[key] = envItem;
164
- }
165
- if (_envValueMap) {
166
- _envValueMap[key] = value;
167
- }
168
- envs.push(envItem);
169
- });
170
- return envs;
171
- }
172
- static async parseFile(options) {
173
- const envItemMap = {};
174
- const envValueMap = {
175
- APP_CHANNEL: options.channel
176
- };
177
- for (const file of options.file) {
178
- const isEnvMeta = file === '.env_meta';
179
- const envYmlFile = _nodePath.default.join(options.cwd, `${file}.yml`);
180
- const envYamlFile = _nodePath.default.join(options.cwd, `${file}.yaml`);
181
- const envFile = (await _fsExtra.default.pathExists(envYmlFile)) ? envYmlFile : (await _fsExtra.default.pathExists(envYamlFile)) ? envYamlFile : '';
182
- if (envFile) {
183
- const envContent = await _fsExtra.default.readFile(envFile, 'utf-8');
184
- EnvUtil.parseContent(envContent, isEnvMeta ? undefined : envItemMap, envValueMap, options.channel);
185
- }
186
- }
187
- return Object.values(envItemMap);
188
- }
189
- static async parseFileAsMap(options) {
190
- const envsObj = {
191
- APP_CHANNEL: options.channel
192
- };
193
- const envs = await EnvUtil.parseFile(options);
194
- for (const env of envs) {
195
- envsObj[env.key] = env.value;
196
- }
197
- return envsObj;
198
- }
199
- static async importFile(options) {
200
- const envsObj = {
201
- APP_CHANNEL: options.channel
202
- };
203
- const envs = await EnvUtil.parseFile(options);
204
- for (const env of envs) {
205
- envsObj[env.key] = env.value;
206
- process.env[env.key] = env.value;
207
- }
208
- process.env.X_SERVER_ENVS = JSON.stringify({
209
- ...JSON.parse(process.env.X_SERVER_ENVS || '{}'),
210
- ...envsObj
211
- });
212
- }
213
- static makeTypes(envs) {
214
- return (0, _vtils.dedent)`
215
- declare namespace NodeJS {
216
- interface ProcessEnv {
217
- /**
218
- * 当前环境
219
- */
220
- NODE_ENV: 'development' | 'production';
221
- /**
222
- * 当前渠道
223
- */
224
- APP_CHANNEL: string;
225
- ${envs.map(env => (0, _vtils.dedent)`
226
- ${env.comment ? (0, _vtils.dedent)`
227
- /**
228
- ${env.comment.split(/[\r\n]+/g).map(line => `* ${line.trim()}`).join('\n*\n')}
229
- */
230
- ` : ''}
231
- ${env.key}: ${EnvUtil.getTypesFromValue(env.value)};
232
- `).join('\n')}
233
- }
234
- }
235
- `;
236
- }
237
- static async outputTypes(options) {
238
- const envs = await EnvUtil.parseFile(options);
239
- const outFile = _nodePath.default.join(options.cwd, options.outFile);
240
- const types = EnvUtil.makeTypes(envs);
241
- await _fsExtra.default.outputFile(outFile, types);
242
- }
243
- static getTypesFromValue(value) {
244
- return Array.isArray(value) ? `Array<${value[0] ? EnvUtil.getTypesFromValue(value[0]) : 'any'}>` : (0, _vtils.isPlainObject)(value) ? Object.keys(value).length ? `{${Object.keys(value).map(key => `'${key}':${EnvUtil.getTypesFromValue(value[key])}`).join(',')}}` : `Record<any, any>` : typeof value;
245
- }
246
- }
247
- exports.EnvUtil = EnvUtil;
248
- EnvUtil.NEWLINE = '\n';
249
- EnvUtil.RE_INI_KEY_VAL = /^\s*([\w.-]+)\s*=\s*(.*)?\s*$/;
250
- EnvUtil.RE_NEWLINES = /\\n/g;
251
- EnvUtil.NEWLINES_MATCH = /\r\n|\n|\r/;
252
- EnvUtil.COMMENT_MATCH = /^#\s*(.+?)\s*$/;
@@ -1,7 +0,0 @@
1
- "use strict";
2
-
3
- var _node = require("esbuild-register/dist/node");
4
- (0, _node.register)({
5
- hookIgnoreNodeModules: false,
6
- hookMatcher: filename => filename.includes('/.x/') || !filename.includes('/node_modules/')
7
- });
@@ -1,101 +0,0 @@
1
- "use strict";
2
-
3
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
4
- exports.__esModule = true;
5
- exports.TemplateUtil = void 0;
6
- var _nodePath = _interopRequireDefault(require("node:path"));
7
- var _fsExtra = _interopRequireDefault(require("fs-extra"));
8
- var _globby = _interopRequireDefault(require("globby"));
9
- var _vscodeGenerateIndexStandalone = require("vscode-generate-index-standalone");
10
- var _vtils = require("vtils");
11
- class TemplateUtil {
12
- /**
13
- * 初始化。
14
- */
15
- static async init(cwd) {
16
- await Promise.all([this.initHelperPackage(cwd), this.initTasks(cwd)]);
17
- }
18
-
19
- /**
20
- * 初始化辅助包。
21
- */
22
- static async initHelperPackage(cwd) {
23
- const fromDir = _nodePath.default.join(__dirname, 'templates');
24
- const toDir = _nodePath.default.join(cwd, 'node_modules/.x');
25
- const hasDb = await _fsExtra.default.pathExists(_nodePath.default.join(cwd, 'src/db/schema.prisma'));
26
- const fromFiles = await (0, _globby.default)('*', {
27
- cwd: fromDir,
28
- onlyFiles: true,
29
- absolute: true
30
- });
31
- await _fsExtra.default.ensureDir(toDir);
32
- await Promise.all(fromFiles.map(async fromFile => {
33
- const toFile = fromFile.replace(fromDir, toDir);
34
- // 对于 models.ts, 项目未使用数据库相关功能时不生成
35
- if (fromFile.endsWith('models.ts') && !hasDb) {
36
- await _fsExtra.default.writeFile(toFile, 'export {}');
37
- } else {
38
- let fromFileContent = await _fsExtra.default.readFile(fromFile, 'utf-8');
39
- fromFileContent = fromFileContent.replaceAll('../../src', _nodePath.default.relative(toDir, `${cwd}/src`));
40
- await _fsExtra.default.writeFile(toFile, fromFileContent);
41
- }
42
- }));
43
- await (0, _vscodeGenerateIndexStandalone.generateManyIndex)({
44
- cwd: cwd,
45
- patterns: ['node_modules/.x/*.ts'],
46
- replaceFile: true
47
- });
48
- }
49
-
50
- /**
51
- * 初始化任务。
52
- */
53
- static async initTasks(cwd) {
54
- const tasksDir = _nodePath.default.join(cwd, 'src/tasks');
55
- const tasksIndexFile = _nodePath.default.join(tasksDir, 'index.ts');
56
- if (!(await _fsExtra.default.pathExists(tasksIndexFile))) {
57
- await _fsExtra.default.outputFile(tasksIndexFile, (0, _vtils.dedent)`
58
- // @index(['./**/*.ts', '!**/*.test.ts', '!**/_*'], f => \`export * from '\${f.path}'\`)
59
- // @endindex
60
- `);
61
- }
62
- }
63
-
64
- /**
65
- * 初始化模型。
66
- */
67
- static async initModels(cwd) {
68
- const modelsDir = _nodePath.default.join(cwd, 'src/models');
69
- const indexFile = _nodePath.default.join(modelsDir, 'index.ts');
70
- const indexFile2 = _nodePath.default.join(cwd, 'node_modules/.x/models.ts');
71
- const prismaClientFile = _nodePath.default.join(cwd, 'node_modules/.x/prisma/internal/prismaNamespace.ts');
72
- const prismaClientFileContent = await _fsExtra.default.readFile(prismaClientFile, 'utf8');
73
- const modelNames = [...prismaClientFileContent.match(/(?<=const ModelName).+?(?=\})/s)[0].matchAll(/(\S+?):/g)].map(match => (0, _vtils.camelCase)(match[1]));
74
- await Promise.all(modelNames.map(async modelName => {
75
- const model_name = (0, _vtils.snakeCase)(modelName);
76
- const ModelName = (0, _vtils.upperFirst)(modelName);
77
- const modelFile = _nodePath.default.join(modelsDir, `${model_name}.ts`);
78
- if (!(await _fsExtra.default.pathExists(modelFile))) {
79
- await _fsExtra.default.outputFile(modelFile, (0, _vtils.dedent)`
80
- import { ${ModelName}BaseModel } from '@jayfong/x-server'
81
-
82
- export class ${ModelName}Model extends ${ModelName}BaseModel {}
83
-
84
- export const ${modelName}Model = new ${ModelName}Model()
85
- `);
86
- }
87
- }));
88
- if (!(await _fsExtra.default.pathExists(indexFile))) {
89
- await _fsExtra.default.outputFile(indexFile, (0, _vtils.dedent)`
90
- // @index(['./**/*.ts', '!**/*.test.ts', '!**/_*'], f => \`export * from '\${f.path}'\`)
91
- // @endindex
92
- `);
93
- }
94
- await (0, _vscodeGenerateIndexStandalone.generateManyIndex)({
95
- cwd: cwd,
96
- patterns: [indexFile, indexFile2],
97
- replaceFile: true
98
- });
99
- }
100
- }
101
- exports.TemplateUtil = TemplateUtil;
@@ -1,2 +0,0 @@
1
- // @index(['../../src/crons/**/*.ts', '!**/_*', '!**/_*/**', '!**/*.test.*'], (f, _) => `import '${f.path}'`)
2
- // @endindex
@@ -1,3 +0,0 @@
1
- // @index(['../../src/handlers/**/*.ts', '!**/_*', '!**/_*/**', '!**/*.test.*'], (f, _) => `export * as __${_.pascal(f.path.replace('/src/handlers/', ''))}__ from '${f.path}'`)
2
-
3
- // @endindex
@@ -1,2 +0,0 @@
1
- // @index(['../../src/hooks/**/*.ts', '!**/_*', '!**/_*/**', '!**/*.test.*'], (f, _) => `import '${f.path}'`)
2
- // @endindex
@@ -1,123 +0,0 @@
1
- import { AsyncLocalStorage } from 'node:async_hooks';
2
- import { URL } from 'node:url';
3
- import { x } from '@jayfong/x-server';
4
- import { PrismaMariaDb } from '@prisma/adapter-mariadb';
5
- import { isNumeric, mapValues } from 'vtils';
6
- import { type Prisma, PrismaClient } from './prisma/client';
7
-
8
- const dbUri = new URL(process.env.DATABASE_URL!);
9
- const adapter = new PrismaMariaDb({
10
- host: dbUri.hostname,
11
- port: +dbUri.port,
12
- user: dbUri.username,
13
- password: dbUri.password,
14
- database: dbUri.pathname.slice(1),
15
- ...mapValues(Object.fromEntries(dbUri.searchParams.entries()), v => {
16
- return v === 'true'
17
- ? true
18
- : v === 'false'
19
- ? false
20
- : (isNumeric(v) as boolean)
21
- ? +v
22
- : (v[0] === '{' && v[v.length - 1] === '}') ||
23
- (v[0] === '[' && v[v.length - 1] === ']')
24
- ? JSON.parse(v)
25
- : v;
26
- }),
27
- });
28
- export const prismaClient = new PrismaClient({ adapter })
29
- // https://github.com/prisma/prisma/issues/7550#issuecomment-2437006346
30
- .$extends({
31
- name: 'findManyAndCount',
32
- model: {
33
- $allModels: {
34
- findManyAndCount<Model, Args>(
35
- this: Model,
36
- args: Prisma.Exact<Args, Prisma.Args<Model, 'findMany'>>,
37
- ): Promise<{
38
- data: Prisma.Result<Model, Args, 'findMany'>;
39
- total: number;
40
- }> {
41
- return prismaClient
42
- .$transaction([
43
- (this as any).findMany(args),
44
- (this as any).count({ where: (args as any).where }),
45
- ])
46
- .then(([data, total]: any) => ({ data, total }));
47
- },
48
- },
49
- },
50
- });
51
-
52
- x.dispose.add(() => prismaClient.$disconnect());
53
-
54
- type ModelName =
55
- // @index('./prisma/internal/prismaNamespace.ts', /(?<=const ModelName).+?(?=\})/s, /(\S+?):/g, (m, _) => `| '${_.camel(m[1])}'`)
56
- '';
57
- // @endindex
58
-
59
- function _makeBaseModel<TModelName extends ModelName>(name: TModelName) {
60
- return class BaseModel {
61
- public get query(): (typeof prismaClient)[TModelName] {
62
- const tx = transactionStorage.getStore();
63
- return tx?.[name] || prismaClient[name];
64
- }
65
-
66
- public transactionClient: Prisma.TransactionClient | null = null;
67
-
68
- public transactionify = (tx: Prisma.TransactionClient) => {
69
- // @ts-expect-error
70
- return new (class extends this.constructor {
71
- public query = tx[name];
72
-
73
- public transactionClient = tx;
74
- })() as typeof this;
75
- };
76
-
77
- public getModel = <T extends ModelName>(
78
- name: T,
79
- ): typeof import('../../src/models')[`${T}Model`] => {
80
- return this.transactionClient
81
- ? require('../../src/models')[`${name}Model`].transactionify(
82
- this.transactionClient,
83
- )
84
- : require('../../src/models')[`${name}Model`];
85
- };
86
- };
87
- }
88
-
89
- // @index('./prisma/internal/prismaNamespace.ts', /(?<=const ModelName).+?(?=\})/s, /(\S+?):/g, (m, _) => `export const ${m[1]}BaseModel = _makeBaseModel('${_.camel(m[1])}')`)
90
- // @endindex
91
-
92
- export * from './prisma/client';
93
-
94
- /**
95
- * @deprecated 使用 runInTransaction 代替
96
- */
97
- export const startTransaction = <T>(
98
- cb: (
99
- models: {
100
- [K in ModelName]: typeof import('../../src/models')[`${K}Model`];
101
- },
102
- ) => Promise<T>,
103
- ): Promise<T> => {
104
- return prismaClient.$transaction(async _tx => {
105
- const _models = require('../../src/models');
106
- const _cache = Object.create(null);
107
- return cb({
108
- // @index('./prisma/internal/prismaNamespace.ts', /(?<=const ModelName).+?(?=\})/s, /(\S+?):/g, (m, _) => `get ${_.camel(m[1])}() { return _cache.${_.camel(m[1])} || (_cache.${_.camel(m[1])} = _models.${_.camel(m[1])}Model.transactionify(_tx)) }, `)
109
- // @endindex
110
- });
111
- });
112
- };
113
-
114
- /** 事务上下文存储 */
115
- export const transactionStorage = new AsyncLocalStorage<any>();
116
- /** 在事务上下文中运行 */
117
- export const runInTransaction = <T>(cb: () => Promise<T>): Promise<T> => {
118
- const tx = transactionStorage.getStore();
119
- if (!tx) {
120
- return prismaClient.$transaction(tx => transactionStorage.run(tx, cb));
121
- }
122
- return cb();
123
- };
@@ -1,3 +0,0 @@
1
- {
2
- "name": ".x"
3
- }
@@ -1,68 +0,0 @@
1
- import { Handler, XServer } from '@jayfong/x-server';
2
- import * as handlers from './handlers';
3
-
4
- const basePathWithHandlers: Array<[string, Record<string, Handler>]> = [
5
- // @index(['../../src/handlers/**/*.ts', '!**/_*', '!**/_*/**', '!**/*.test.*'], (f, _) => `['${(f.path+'/').replace(/@dev/g, '').replace('../../src/handlers/', '/').replace(/\/index\/$/, '/').split('/').map(v => _.snake(v)).join('/')}', handlers.__${_.pascal(f.path.replace('/src/handlers/', ''))}__ as any],`)
6
- // @endindex
7
- ];
8
-
9
- // https://stackoverflow.com/questions/50374908/transform-union-type-to-intersection-type
10
- type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (
11
- k: infer I,
12
- ) => void
13
- ? I
14
- : never;
15
- type RouteMap = {
16
- // @index(['../../src/handlers/**/*.ts', '!**/_*', '!**/_*/**', '!**/*.test.*'], (f, _) => `'${(f.path+'/').replace('../../src/handlers/', '/').replace(/\/index\/$/, '/').split('/').map(v => _.snake(v)).join('/')}': typeof handlers.__${_.pascal(f.path.replace('/src/handlers/', ''))}__,`)
17
- // @endindex
18
- };
19
- export type HandlerMap = UnionToIntersection<
20
- {
21
- [K in keyof RouteMap]: {
22
- [X in keyof RouteMap[K]]: {
23
- [Y in `${K}${X & string}`]: RouteMap[K][X];
24
- };
25
- }[keyof RouteMap[K]];
26
- }[keyof RouteMap]
27
- >;
28
- export type HandlerPath = keyof HandlerMap;
29
- export type HandlerMetaMap = {
30
- [K in HandlerPath]: HandlerMap[K] extends Handler<infer X, infer Y, infer Z>
31
- ? {
32
- payload: X;
33
- result: Y;
34
- method: Z;
35
- }
36
- : {};
37
- };
38
- export type HandlerPayloadMap = {
39
- // @ts-ignore
40
- [K in HandlerPath]: HandlerMetaMap[K]['payload'];
41
- };
42
- export type HandlerResultMap = {
43
- // @ts-ignore
44
- [K in HandlerPath]: HandlerMetaMap[K]['result'];
45
- };
46
- export type HandlerMethodMap = {
47
- // @ts-ignore
48
- [K in HandlerPath]: HandlerMetaMap[K]['method'];
49
- };
50
-
51
- export const routes: XServer.Route[] = basePathWithHandlers.reduce<
52
- XServer.Route[]
53
- >((res, item) => {
54
- const validHandlerNames = Object.keys(item[1]).filter(
55
- name => !name.startsWith('_') && name !== 'default',
56
- );
57
- for (const handlerName of validHandlerNames) {
58
- const path = item[1][handlerName].options.requestPath || handlerName;
59
- const paths = Array.isArray(path) ? path : [path];
60
- for (const path of paths) {
61
- res.push({
62
- path: `${item[0]}${path}`,
63
- handler: item[1][handlerName],
64
- });
65
- }
66
- }
67
- return res;
68
- }, []);
@@ -1,6 +0,0 @@
1
- "use strict";
2
-
3
- exports.__esModule = true;
4
- exports.ctxStorage = void 0;
5
- var _nodeAsync_hooks = require("node:async_hooks");
6
- const ctxStorage = exports.ctxStorage = new _nodeAsync_hooks.AsyncLocalStorage();
@@ -1,31 +0,0 @@
1
- "use strict";
2
-
3
- exports.__esModule = true;
4
- exports.defineBus = defineBus;
5
- var _nodeEvents = require("node:events");
6
- class EventBus extends _nodeEvents.EventEmitter {
7
- onReturnOff(event, listener) {
8
- this.on(event, listener);
9
- return () => this.off(event, listener);
10
- }
11
- }
12
- function defineBus() {
13
- const eventEmitter = new EventBus();
14
- return eventEmitter;
15
- }
16
-
17
- // strict-event-emitter-types
18
- // https://github.com/bterlson/strict-event-emitter-types/blob/9ed45fc68a69f0b7f85ce4e5fe11ff53cc6a009e/src/index.ts
19
-
20
- // the overridden signatures need to be assignment compatible, but
21
- // due to how tuple types work[0] it's not possible to be assignment
22
- // compatible anymore. This hack fixes it with a unique symbol that
23
- // won't ever show up in parameter help etc.
24
- //
25
- // Unfortunately, this has the result of giving a poor error message when
26
- // you mix up types.
27
- // 0: https://github.com/Microsoft/TypeScript/issues/26013)
28
-
29
- // TODO: Stash under a symbol key once TS compiler bug is fixed
30
-
31
- // EventEmitter method overrides
@@ -1,13 +0,0 @@
1
- "use strict";
2
-
3
- exports.__esModule = true;
4
- exports.defineCron = defineCron;
5
- var _cron = require("cron");
6
- function defineCron(options) {
7
- return _cron.CronJob.from({
8
- cronTime: options.expression,
9
- runOnInit: options.runOnInit,
10
- start: true,
11
- onTick: options.handle
12
- });
13
- }
@@ -1,56 +0,0 @@
1
- "use strict";
2
-
3
- exports.__esModule = true;
4
- exports.defineHandler = defineHandler;
5
- exports.defineHandlerANY = defineHandlerANY;
6
- exports.defineHandlerFILE = defineHandlerFILE;
7
- exports.defineHandlerGET = defineHandlerGET;
8
- exports.defineHandlerXML = defineHandlerXML;
9
- var _handler = require("./handler");
10
- function defineHandler(options) {
11
- const handler = new _handler.Handler({
12
- ...options,
13
- requestMethod: 'POST'
14
- });
15
- return handler;
16
- }
17
- defineHandler.POST = defineHandler;
18
- function defineHandlerGET(options) {
19
- const handler = new _handler.Handler({
20
- ...options,
21
- requestMethod: 'GET'
22
- });
23
- return handler;
24
- }
25
- defineHandler.GET = defineHandlerGET;
26
- function defineHandlerFILE(options) {
27
- const handler = new _handler.Handler({
28
- ...options,
29
- requestMethod: 'FILE'
30
- });
31
- return handler;
32
- }
33
- defineHandler.FILE = defineHandlerFILE;
34
- defineHandler.WS = options => {
35
- const handler = new _handler.Handler({
36
- ...options,
37
- requestMethod: 'WS'
38
- });
39
- return handler;
40
- };
41
- function defineHandlerXML(options) {
42
- const handler = new _handler.Handler({
43
- ...options,
44
- requestMethod: 'XML'
45
- });
46
- return handler;
47
- }
48
- defineHandler.XML = defineHandlerXML;
49
- function defineHandlerANY(options) {
50
- const handler = new _handler.Handler({
51
- ...options,
52
- requestMethod: 'ANY'
53
- });
54
- return handler;
55
- }
56
- defineHandler.ANY = defineHandlerANY;