@xrystal/core 3.51.6 → 3.52.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 (120) hide show
  1. package/README.md +35 -1
  2. package/package.json +1 -1
  3. package/x/bin/commands/create.mjs +44 -0
  4. package/x/bin/commands/projects.mjs +53 -0
  5. package/x/bin/commands/sync.mjs +49 -1
  6. package/x/bin/commands/tmp.mjs +1 -1
  7. package/x/bin/helpers/.generated/.generated-from +2 -0
  8. package/x/bin/helpers/.generated/seed-from-tmp.mjs +25 -31
  9. package/x/bin/helpers/.generated/tmp-schema.mjs +156 -96
  10. package/x/bin/helpers/.generated/workspace.mjs +402 -0
  11. package/x/bin/helpers/.generated/xrystal-home-registry.mjs +310 -0
  12. package/x/bin/helpers/build-config.mjs +3 -2
  13. package/x/bin/helpers/cli-help.mjs +3 -1
  14. package/x/bin/helpers/project-artifacts.mjs +9 -0
  15. package/x/bin/helpers/tmp-config.mjs +13 -12
  16. package/x/bin/helpers/tmp-layout.mjs +28 -52
  17. package/x/bin/helpers/tmp-schema.mjs +9 -3
  18. package/x/bin/helpers/workspace-resolve.mjs +11 -0
  19. package/x/bin/helpers/workspace-scaffold.mjs +23 -0
  20. package/x/bin/helpers/xrystal-registry.mjs +13 -0
  21. package/x/bin/main-cli.js +2 -0
  22. package/x/dist/index.js +5 -1
  23. package/x/dist/loader/clients/index.js +22 -1
  24. package/x/dist/loader/configs/index.js +97 -1
  25. package/x/dist/loader/controller/index.js +267 -1
  26. package/x/dist/loader/dto/index.js +92 -1
  27. package/x/dist/loader/events/index.js +39 -1
  28. package/x/dist/loader/index.js +13 -1
  29. package/x/dist/loader/kafka/index.js +142 -1
  30. package/x/dist/loader/kafka/resolve-ssl.js +23 -1
  31. package/x/dist/loader/localizations/index.js +46 -1
  32. package/x/dist/loader/logger/index.js +229 -2
  33. package/x/dist/loader/mongo/index.js +52 -1
  34. package/x/dist/loader/mongo/resolve-connect.js +16 -1
  35. package/x/dist/loader/redis/index.js +57 -1
  36. package/x/dist/loader/redis/resolve-socket.js +31 -1
  37. package/x/dist/loader/registry/index.js +1 -1
  38. package/x/dist/loader/service/index.js +7 -1
  39. package/x/dist/loader/system/index.js +26 -1
  40. package/x/dist/project/index.js +51 -1
  41. package/x/dist/utils/constants/defaults.json +3 -1
  42. package/x/dist/utils/constants/index.d.ts +1 -0
  43. package/x/dist/utils/constants/index.js +42 -1
  44. package/x/dist/utils/constants/package-root.js +6 -1
  45. package/x/dist/utils/helpers/configs/index.js +1 -1
  46. package/x/dist/utils/helpers/context/controller-store.js +12 -1
  47. package/x/dist/utils/helpers/context/index.js +24 -1
  48. package/x/dist/utils/helpers/core/handlebars-resolve.js +15 -1
  49. package/x/dist/utils/helpers/core/index.js +46 -1
  50. package/x/dist/utils/helpers/core/paths.js +78 -1
  51. package/x/dist/utils/helpers/core/tmp-layout.d.ts +4 -4
  52. package/x/dist/utils/helpers/core/tmp-layout.js +229 -1
  53. package/x/dist/utils/helpers/date/index.js +48 -1
  54. package/x/dist/utils/helpers/dispatch/index.js +53 -1
  55. package/x/dist/utils/helpers/dto/index.js +10 -1
  56. package/x/dist/utils/helpers/filters/index.js +44 -1
  57. package/x/dist/utils/helpers/framework/index.js +18 -1
  58. package/x/dist/utils/helpers/handlers/adapters.js +41 -1
  59. package/x/dist/utils/helpers/handlers/execute.js +82 -1
  60. package/x/dist/utils/helpers/handlers/index.js +31 -1
  61. package/x/dist/utils/helpers/hash/crypto.js +22 -1
  62. package/x/dist/utils/helpers/id/index.js +24 -1
  63. package/x/dist/utils/helpers/index.d.ts +1 -0
  64. package/x/dist/utils/helpers/index.js +28 -1
  65. package/x/dist/utils/helpers/ip/index.js +21 -1
  66. package/x/dist/utils/helpers/is/index.js +35 -1
  67. package/x/dist/utils/helpers/kafka-loader-options/index.js +14 -1
  68. package/x/dist/utils/helpers/locales/index.js +82 -1
  69. package/x/dist/utils/helpers/logger-layer/index.js +33 -1
  70. package/x/dist/utils/helpers/math/index.js +14 -1
  71. package/x/dist/utils/helpers/middleware/index.js +36 -1
  72. package/x/dist/utils/helpers/node-env/index.js +20 -1
  73. package/x/dist/utils/helpers/objects/index.js +55 -1
  74. package/x/dist/utils/helpers/path/index.js +5 -1
  75. package/x/dist/utils/helpers/path/resolve-alias-path.d.ts +1 -1
  76. package/x/dist/utils/helpers/path/resolve-alias-path.js +62 -1
  77. package/x/dist/utils/helpers/protocol/index.d.ts +1 -1
  78. package/x/dist/utils/helpers/protocol/index.js +100 -1
  79. package/x/dist/utils/helpers/protocol/options.js +13 -1
  80. package/x/dist/utils/helpers/regex/checkSpecialRegexControl.js +3 -1
  81. package/x/dist/utils/helpers/registry/index.js +103 -1
  82. package/x/dist/utils/helpers/runtime/dto-access.js +5 -1
  83. package/x/dist/utils/helpers/runtime/dto-types.js +1 -1
  84. package/x/dist/utils/helpers/runtime/index.js +2 -1
  85. package/x/dist/utils/helpers/runtime/shutdown.js +36 -1
  86. package/x/dist/utils/helpers/state/index.js +185 -1
  87. package/x/dist/utils/helpers/state/props-from-tmp.js +46 -1
  88. package/x/dist/utils/helpers/state/request-key-guard.js +43 -1
  89. package/x/dist/utils/helpers/state/scopes.js +69 -1
  90. package/x/dist/utils/helpers/string/index.js +9 -1
  91. package/x/dist/utils/helpers/timer/index.js +5 -1
  92. package/x/dist/utils/helpers/tmp/index.d.ts +2 -2
  93. package/x/dist/utils/helpers/tmp/index.js +8 -1
  94. package/x/dist/utils/helpers/tmp/loader-tmp-sync.js +14 -1
  95. package/x/dist/utils/helpers/tmp/path-normalize.js +27 -1
  96. package/x/dist/utils/helpers/tmp/runtime-tmp.js +42 -1
  97. package/x/dist/utils/helpers/tmp/seed-from-tmp.d.ts +2 -2
  98. package/x/dist/utils/helpers/tmp/seed-from-tmp.js +62 -1
  99. package/x/dist/utils/helpers/tmp/tmp-interpolate.js +22 -1
  100. package/x/dist/utils/helpers/tmp/tmp-loader.js +56 -1
  101. package/x/dist/utils/helpers/tmp/tmp-schema.d.ts +35 -23
  102. package/x/dist/utils/helpers/tmp/tmp-schema.js +211 -1
  103. package/x/dist/utils/helpers/tmp/tmp-watch.js +23 -1
  104. package/x/dist/utils/helpers/tmp/toolchain-heal.js +157 -2
  105. package/x/dist/utils/helpers/validates/index.js +20 -1
  106. package/x/dist/utils/helpers/workspace/index.d.ts +42 -0
  107. package/x/dist/utils/helpers/workspace/index.js +222 -0
  108. package/x/dist/utils/helpers/xrystal-home/registry.d.ts +32 -0
  109. package/x/dist/utils/helpers/xrystal-home/registry.js +92 -0
  110. package/x/dist/utils/index.js +3 -1
  111. package/x/dist/utils/models/classes/class.clients.js +142 -1
  112. package/x/dist/utils/models/classes/class.interfaces.js +10 -1
  113. package/x/dist/utils/models/classes/class.service-locator.js +16 -1
  114. package/x/dist/utils/models/classes/class.tmp-file-loader.js +61 -1
  115. package/x/dist/utils/models/classes/class.x.js +181 -1
  116. package/x/dist/utils/models/enums/index.d.ts +9 -1
  117. package/x/dist/utils/models/enums/index.js +169 -1
  118. package/x/dist/utils/models/index.js +9 -1
  119. package/x/dist/utils/models/types/index.js +2 -1
  120. package/x/tmp.yml +7 -50
@@ -1 +1,267 @@
1
- import{Constants as h}from "../../utils/constants/index.js";import g from"qs";import S from "../../loader/logger/index.js";import T from "../../loader/system/index.js";import{bindLoaderTmpSync as E,getClientIp as D,getConfiguredProtocols as O,isRealtimeProtocol as q,LoggerLayerEnum as j,parseResponseMessage as P,ProtocolEnum as y,x,controllerContextStorage,getControllerCtx,runControllerStore as B,adapterBagFromRequest as I,isFetchRequest as M,toHandler as H,toRealtimeHandler as N,resolveCtrOptions as A}from "../../utils/index.js";export{controllerContextStorage,getControllerCtx};export const runController=B;function b(t){return t instanceof Response||t instanceof Blob||t instanceof Uint8Array||t instanceof ArrayBuffer}function l(t){if(!t||typeof t!=="object")return null;return t}function w(t,e){const r=l(e);if(!r)return;if(r.statusCode!==void 0)return void t.httpStatus(Number(r.statusCode));if(r.code!==void 0){const a=Number(r.code);if(a>=100)t.httpStatus(a);else t.code(a)}}function R(t){const e=l(t);if(!e)return{data:void 0,extraData:void 0,message:void 0};const r=l(e.payload);if(r)return{data:r.data!==void 0?r.data:r,extraData:r.extraData,message:e.message};if(e.data!==void 0||e.extraData!==void 0)return{data:e.data,extraData:e.extraData,message:e.message};if(!(e.status!==void 0||e.message!==void 0||e.code!==void 0||e.statusCode!==void 0)&&Object.keys(e).length>0)return{data:e,extraData:void 0,message:e.message};return{data:void 0,extraData:void 0,message:e.message}}function F(t){return t instanceof ReadableStream||typeof t==="object"&&t!==null&&typeof t.getReader==="function"}function k(t){if(Array.isArray(t))return t[0]??"";return t??""}export function resolveBuilder(t){const e=t.ctx?.builder??t.res?.builder??t.socket?.builder;if(e)return e;throw Error(`[${h.packageName}] use dtoMiddleware() — builder attaches at request start via @xrystal/dto adapter`)}export class BaseController{system=x.get(T);logger=x.get(S);supportedProtocols=[y.HTTP,y.WEBSOCKET];get store(){return getControllerCtx()}get protocol(){return this.store?.protocol||y.HTTP}get req(){const t=this.store,e=t?.ctx||{},r=t?.req||{},a=M(e.request)?e.request:void 0,o=I(e.request),n=e.headers??r.headers??a?.headers??o?.headers,s=n instanceof Headers?Object.fromEntries(n.entries()):n??{},i=a?.url??o?.url??r.url??e.url??"";let c=t?.metadata?.parsedQuery||e.query||r.query||o?.query||{};if(!Object.keys(c).length&&i.includes("?"))c=g.parse(i.split("?")[1]);let u=e.cookies||r.cookies||o?.cookies||{};const d=s.cookie;if(!Object.keys(u).length&&typeof d==="string")u=Object.fromEntries(d.split(";").map((f)=>{const[m,p]=f.trim().split("=");return[decodeURIComponent(m),decodeURIComponent(p||"")]}));return{url:i,method:(e.method||r.method||a?.method||o?.method||"").toUpperCase(),headers:s,body:t?.metadata?.parsedBody||e.body||r.body||o?.body||{},query:c,params:{...r.params,...e.params,...o?.params,...o?.routeParams},cookies:u,ip:D(r,e),lang:e.lang||r.lang||"en",requestId:t?.requestId??e.requestId??r.ctx?.requestId??String(s["x-request-id"]??s["x-correlation-id"]??""),startTime:e.startTime??r.ctx?.startTime??Date.now(),t:e.t||r.t||((f)=>f),accounts:e.accounts||r.accounts||e.user}}get res(){const t=this.store;if(!t)throw Error(`[${h.packageName}] controller context missing`);const e=t.metadata?.locals??{};return{builder:resolveBuilder(t),locals:e}}async parseRequestBody(){const t=this.store;if(!t)return;const e=t.ctx?.request,r=t.req||e||t.ctx?.req,a=this.req,o=k(a.headers["content-type"]).toLowerCase(),n=parseInt(k(a.headers["content-length"])||"-1",10);let s=a.body;const i=(d)=>{if(!d)return{};if(o.includes("application/json"))try{return JSON.parse(d)}catch{return d}if(o.includes("application/x-www-form-urlencoded"))return g.parse(d);try{return JSON.parse(d)}catch{try{return g.parse(d)}catch{return d}}},c=F,u=s&&typeof s==="object"&&!c(s)&&Object.keys(s).length>0;if(!q(this.protocol)&&!["GET","HEAD","OPTIONS"].includes(a.method)&&!u){if(r instanceof Request&&(c(s)||n>0))try{s=i(await r.clone().text())}catch{if(typeof s==="string")s=i(s)}else if(r&&typeof r==="object"&&"on"in r&&typeof r.on==="function"&&n!==0){const d=r;s=await new Promise((f)=>{let m="";const p=setTimeout(()=>f({}),200);d.on("data",(C)=>{m+=String(C)});d.on("end",()=>{clearTimeout(p);f(i(m))});d.on("error",()=>{clearTimeout(p);f({})})})}else if(typeof s==="string"&&s.length)s=i(s)}if(typeof FormData<"u"&&s instanceof FormData)s=Object.fromEntries(s.entries());if(!t.metadata)t.metadata={locals:{}};t.metadata.parsedBody=s||{};t.metadata.parsedQuery=a.query}}export default class Controller extends BaseController{async onInit(){await this.syncFromTmp();E(this)}syncFromTmp=()=>{this.supportedProtocols=O()};parseMessage(t,e,r=!1){return P(t,e,r)}args(t){const e=this.req,r=this.store.metadata?.locals??{};return{req:e,res:{builder:t,locals:r},builder:t,body:e.body,query:e.query,queries:e.query,params:e.params,cookies:e.cookies,locals:r,t:e.t}}fail(t,e,r){w(t,e);const{data:a,extraData:o}=R(e),n=l(e),s=this.parseMessage(n?.message??e,r,!0),i=a!==void 0||o!==void 0?{data:a,extraData:o}:void 0;return(a!==void 0?t.as.fail(a,s,i):t.as.fail(s,i)).build()}ok(t,e,r,a){let o="success_process",n=e!==void 0?e:r;if(typeof e==="string"){o=e;n=r}const{data:s,extraData:i,message:c}=R(n);if(typeof c==="string")o=c;w(t,n);return t.as.ok(s,this.parseMessage(o,a,!1),i!==void 0?{extraData:i}:void 0).build()}async schema({checks:t,logic:e,response:r}){const a=resolveBuilder(this.store);try{await this.parseRequestBody();const n=this.args(a);if(t){const u=await t(n);if(u!==!0)return this.fail(a,u,n.req.t)}let s=e?await e(n):{};const i=l(s);if(i&&typeof i.response==="function")s=await i.response();if(b(s))return s;if(i?.status===!1)return this.fail(a,s,n.req.t);const c=r?await r({...n,logicResult:s}):s;if(b(c))return c;return this.ok(a,c,s,n.req.t)}catch(o){const n=o instanceof Error?o.message:String(o);this.logger?.log(j.ERROR,`Controller Error: ${n}`);return a.as.internalServerError(this.parseMessage(n,this.req.t,!0)).build()}}ctr(t,e){const{framework:r,protocol:a}=A(e),o=()=>this.schema(t);if(q(a))return N(o,a);return H(o,r)}}
1
+ import { Constants } from '../../utils/constants/index.js';
2
+ import qs from 'qs';
3
+ import Logger from '../../loader/logger/index.js';
4
+ import System from '../../loader/system/index.js';
5
+ import { bindLoaderTmpSync, getClientIp, getConfiguredProtocols, isRealtimeProtocol, LoggerLayerEnum, parseResponseMessage, ProtocolEnum, x, controllerContextStorage, getControllerCtx, runControllerStore, adapterBagFromRequest, isFetchRequest, toHandler, toRealtimeHandler, resolveCtrOptions, } from '../../utils/index.js';
6
+ export { controllerContextStorage, getControllerCtx };
7
+ export const runController = runControllerStore;
8
+ function isRawResponse(value) {
9
+ return value instanceof Response || value instanceof Blob || value instanceof Uint8Array || value instanceof ArrayBuffer;
10
+ }
11
+ function asPayloadRecord(value) {
12
+ if (!value || typeof value !== 'object')
13
+ return null;
14
+ return value;
15
+ }
16
+ function applyResultMeta(builder, obj) {
17
+ const record = asPayloadRecord(obj);
18
+ if (!record)
19
+ return;
20
+ if (record.statusCode !== undefined)
21
+ return void builder.httpStatus(Number(record.statusCode));
22
+ if (record.code !== undefined) {
23
+ const code = Number(record.code);
24
+ if (code >= 100)
25
+ builder.httpStatus(code);
26
+ else
27
+ builder.code(code);
28
+ }
29
+ }
30
+ function extractPayload(obj) {
31
+ const record = asPayloadRecord(obj);
32
+ if (!record)
33
+ return { data: undefined, extraData: undefined, message: undefined };
34
+ const payload = asPayloadRecord(record.payload);
35
+ if (payload) {
36
+ return {
37
+ data: payload.data !== undefined ? payload.data : payload,
38
+ extraData: payload.extraData,
39
+ message: record.message,
40
+ };
41
+ }
42
+ if (record.data !== undefined || record.extraData !== undefined) {
43
+ return { data: record.data, extraData: record.extraData, message: record.message };
44
+ }
45
+ const hasMeta = record.status !== undefined || record.message !== undefined || record.code !== undefined || record.statusCode !== undefined;
46
+ if (!hasMeta && Object.keys(record).length > 0) {
47
+ return { data: record, extraData: undefined, message: record.message };
48
+ }
49
+ return { data: undefined, extraData: undefined, message: record.message };
50
+ }
51
+ function isReadableBodyStream(value) {
52
+ return value instanceof ReadableStream
53
+ || (typeof value === 'object' && value !== null && typeof value.getReader === 'function');
54
+ }
55
+ function headerValue(value) {
56
+ if (Array.isArray(value))
57
+ return value[0] ?? '';
58
+ return value ?? '';
59
+ }
60
+ export function resolveBuilder(store) {
61
+ const attached = store.ctx?.builder ?? store.res?.builder ?? store.socket?.builder;
62
+ if (attached)
63
+ return attached;
64
+ throw new Error(`[${Constants.packageName}] use dtoMiddleware() — builder attaches at request start via @xrystal/dto adapter`);
65
+ }
66
+ export class BaseController {
67
+ system = x.get(System);
68
+ logger = x.get(Logger);
69
+ supportedProtocols = [ProtocolEnum.HTTP, ProtocolEnum.WEBSOCKET];
70
+ get store() {
71
+ return getControllerCtx();
72
+ }
73
+ get protocol() {
74
+ return this.store?.protocol || ProtocolEnum.HTTP;
75
+ }
76
+ get req() {
77
+ const store = this.store;
78
+ const ctx = store?.ctx || {};
79
+ const req = store?.req || {};
80
+ const fetchRequest = isFetchRequest(ctx.request) ? ctx.request : undefined;
81
+ const ctxReq = adapterBagFromRequest(ctx.request);
82
+ const headerSource = ctx.headers ?? req.headers ?? fetchRequest?.headers ?? ctxReq?.headers;
83
+ const headers = headerSource instanceof Headers
84
+ ? Object.fromEntries(headerSource.entries())
85
+ : (headerSource ?? {});
86
+ const url = fetchRequest?.url ?? ctxReq?.url ?? req.url ?? ctx.url ?? "";
87
+ let query = (store?.metadata?.parsedQuery || ctx.query || req.query || ctxReq?.query || {});
88
+ if (!Object.keys(query).length && url.includes('?'))
89
+ query = qs.parse(url.split('?')[1]);
90
+ let cookies = (ctx.cookies || req.cookies || ctxReq?.cookies || {});
91
+ const cookieHeader = headers.cookie;
92
+ if (!Object.keys(cookies).length && typeof cookieHeader === 'string') {
93
+ cookies = Object.fromEntries(cookieHeader.split(';').map((part) => {
94
+ const [k, v] = part.trim().split('=');
95
+ return [decodeURIComponent(k), decodeURIComponent(v || '')];
96
+ }));
97
+ }
98
+ return {
99
+ url,
100
+ method: (ctx.method || req.method || fetchRequest?.method || ctxReq?.method || '').toUpperCase(),
101
+ headers,
102
+ body: store?.metadata?.parsedBody || ctx.body || req.body || ctxReq?.body || {},
103
+ query,
104
+ params: { ...req.params, ...ctx.params, ...ctxReq?.params, ...ctxReq?.routeParams },
105
+ cookies,
106
+ ip: getClientIp(req, ctx),
107
+ lang: ctx.lang || req.lang || 'en',
108
+ requestId: store?.requestId ?? ctx.requestId ?? req.ctx?.requestId ?? String(headers['x-request-id'] ?? headers['x-correlation-id'] ?? ''),
109
+ startTime: (ctx.startTime ?? req.ctx?.startTime ?? Date.now()),
110
+ t: (ctx.t || req.t || ((k) => k)),
111
+ accounts: ctx.accounts || req.accounts || ctx.user,
112
+ };
113
+ }
114
+ get res() {
115
+ const store = this.store;
116
+ if (!store)
117
+ throw new Error(`[${Constants.packageName}] controller context missing`);
118
+ const locals = store.metadata?.locals ?? {};
119
+ return { builder: resolveBuilder(store), locals: locals };
120
+ }
121
+ async parseRequestBody() {
122
+ const store = this.store;
123
+ if (!store)
124
+ return;
125
+ const ctxRequest = store.ctx?.request;
126
+ const raw = store.req || ctxRequest || store.ctx?.req;
127
+ const base = this.req;
128
+ const type = headerValue(base.headers['content-type']).toLowerCase();
129
+ const length = parseInt(headerValue(base.headers['content-length']) || '-1', 10);
130
+ let body = base.body;
131
+ const parse = (text) => {
132
+ if (!text)
133
+ return {};
134
+ if (type.includes('application/json'))
135
+ try {
136
+ return JSON.parse(text);
137
+ }
138
+ catch {
139
+ return text;
140
+ }
141
+ if (type.includes('application/x-www-form-urlencoded'))
142
+ return qs.parse(text);
143
+ try {
144
+ return JSON.parse(text);
145
+ }
146
+ catch {
147
+ try {
148
+ return qs.parse(text);
149
+ }
150
+ catch {
151
+ return text;
152
+ }
153
+ }
154
+ };
155
+ const isStream = isReadableBodyStream;
156
+ const ready = body && typeof body === 'object' && !isStream(body) && Object.keys(body).length > 0;
157
+ if (!isRealtimeProtocol(this.protocol) && !['GET', 'HEAD', 'OPTIONS'].includes(base.method) && !ready) {
158
+ if (raw instanceof Request && (isStream(body) || length > 0)) {
159
+ try {
160
+ body = parse(await raw.clone().text());
161
+ }
162
+ catch {
163
+ if (typeof body === 'string')
164
+ body = parse(body);
165
+ }
166
+ }
167
+ else if (raw && typeof raw === 'object' && 'on' in raw && typeof raw.on === 'function' && length !== 0) {
168
+ const stream = raw;
169
+ body = await new Promise((resolve) => {
170
+ let text = '';
171
+ const timer = setTimeout(() => resolve({}), 200);
172
+ stream.on('data', (chunk) => { text += String(chunk); });
173
+ stream.on('end', () => { clearTimeout(timer); resolve(parse(text)); });
174
+ stream.on('error', () => { clearTimeout(timer); resolve({}); });
175
+ });
176
+ }
177
+ else if (typeof body === 'string' && body.length) {
178
+ body = parse(body);
179
+ }
180
+ }
181
+ if (typeof FormData !== 'undefined' && body instanceof FormData) {
182
+ body = Object.fromEntries(body.entries());
183
+ }
184
+ if (!store.metadata)
185
+ store.metadata = { locals: {} };
186
+ store.metadata.parsedBody = body || {};
187
+ store.metadata.parsedQuery = base.query;
188
+ }
189
+ }
190
+ export default class Controller extends BaseController {
191
+ async onInit() {
192
+ await this.syncFromTmp();
193
+ bindLoaderTmpSync(this);
194
+ }
195
+ syncFromTmp = () => {
196
+ this.supportedProtocols = getConfiguredProtocols();
197
+ };
198
+ parseMessage(msg, t, isError = false) {
199
+ return parseResponseMessage(msg, t, isError);
200
+ }
201
+ args(builder) {
202
+ const req = this.req;
203
+ const locals = this.store.metadata?.locals ?? {};
204
+ return { req, res: { builder, locals }, builder, body: req.body, query: req.query, queries: req.query, params: req.params, cookies: req.cookies, locals, t: req.t };
205
+ }
206
+ fail(builder, source, t) {
207
+ applyResultMeta(builder, source);
208
+ const { data, extraData } = extractPayload(source);
209
+ const record = asPayloadRecord(source);
210
+ const message = this.parseMessage(record?.message ?? source, t, true);
211
+ const extras = data !== undefined || extraData !== undefined ? { data, extraData } : undefined;
212
+ const terminal = data !== undefined ? builder.as.fail(data, message, extras) : builder.as.fail(message, extras);
213
+ return terminal.build();
214
+ }
215
+ ok(builder, resResult, logicResult, t) {
216
+ let message = 'success_process';
217
+ let source = resResult !== undefined ? resResult : logicResult;
218
+ if (typeof resResult === 'string') {
219
+ message = resResult;
220
+ source = logicResult;
221
+ }
222
+ const { data, extraData, message: custom } = extractPayload(source);
223
+ if (typeof custom === 'string')
224
+ message = custom;
225
+ applyResultMeta(builder, source);
226
+ return builder.as.ok(data, this.parseMessage(message, t, false), extraData !== undefined ? { extraData } : undefined).build();
227
+ }
228
+ async schema({ checks, logic, response }) {
229
+ const builder = resolveBuilder(this.store);
230
+ try {
231
+ await this.parseRequestBody();
232
+ const args = this.args(builder);
233
+ const typedArgs = args;
234
+ if (checks) {
235
+ const check = await checks(typedArgs);
236
+ if (check !== true)
237
+ return this.fail(builder, check, typedArgs.req.t);
238
+ }
239
+ let result = logic ? await logic(typedArgs) : {};
240
+ const resultRecord = asPayloadRecord(result);
241
+ if (resultRecord && typeof resultRecord.response === 'function') {
242
+ result = await resultRecord.response();
243
+ }
244
+ if (isRawResponse(result))
245
+ return result;
246
+ if (resultRecord?.status === false)
247
+ return this.fail(builder, result, typedArgs.req.t);
248
+ const out = response ? await response({ ...typedArgs, logicResult: result }) : result;
249
+ if (isRawResponse(out))
250
+ return out;
251
+ return this.ok(builder, out, result, typedArgs.req.t);
252
+ }
253
+ catch (error) {
254
+ const message = error instanceof Error ? error.message : String(error);
255
+ this.logger?.log(LoggerLayerEnum.ERROR, `Controller Error: ${message}`);
256
+ return builder.as.internalServerError(this.parseMessage(message, this.req.t, true)).build();
257
+ }
258
+ }
259
+ ctr(definition, opts) {
260
+ const { framework, protocol } = resolveCtrOptions(opts);
261
+ const action = () => this.schema(definition);
262
+ if (isRealtimeProtocol(protocol)) {
263
+ return toRealtimeHandler(action, protocol);
264
+ }
265
+ return toHandler(action, framework);
266
+ }
267
+ }
@@ -1 +1,92 @@
1
- import{DTO as u}from"@xrystal/dto/dto";import{bindLoaderTmpSync as m}from "../../utils/index.js";import{FrameworkEnum as c,parseFramework as f}from "../../utils/index.js";export const DEFAULT_DTO_CONFIG={withDefaultHeaders:!0};function r(t,e){return{...t,...e,codes:e.codes?{...t.codes,...e.codes}:t.codes,defaultHeaders:e.defaultHeaders?{...t.defaultHeaders,...e.defaultHeaders}:t.defaultHeaders,socket:e.socket?{...t.socket,...e.socket}:t.socket,hooks:e.hooks??t.hooks,plugins:e.plugins?[...t.plugins??[],...e.plugins]:t.plugins}}export default class DtoRuntime{_runtime;_system;_config={...DEFAULT_DTO_CONFIG};_framework=c.ELYSIA;_bootConfig={};constructor({system:t}){this._system=t}async onInit(t={}){this._bootConfig=t.config??{};await this.syncFromTmp();m(this)}syncFromTmp=async()=>{this._framework=f(this._system?.tmp?.configs?.service?.framework);this.applyConfig(DEFAULT_DTO_CONFIG,this._system?.tmp?.configs?.service?.loaders?.dto??{},this._bootConfig,{rebuild:!0})};get instance(){return this._runtime}get config(){return this._config}get framework(){return this._framework}configure(t={},e={}){this.applyConfig(this._config,t,e);return this}use(...t){this._runtime.use(...t);this._config=r(this._config,{plugins:t});return this}express(){return this._runtime.express()}elysia(){return this._runtime.elysia()}node(){return this._runtime.node()}websocket(){return this._runtime.websocket()}socketIo(){return this._runtime.socketIo()}attachWebSocket(t,e){return this._runtime.attachWebSocket(t,e)}attachSocketIo(t){return this._runtime.attachSocketIo(t)}fetch(){return this._runtime.fetch()}forRequest(t){return this._runtime.forRequest(t)}applyConfig(...t){const e=t[t.length-1],i=e&&"rebuild"in e?t.pop():{},o=t.reduce((s,n)=>r(s,n),{...DEFAULT_DTO_CONFIG});this._config=o;if(!this._runtime||i.rebuild!==!1)this._runtime=new u(this._config)}}
1
+ import { DTO } from '@xrystal/dto/dto';
2
+ import { bindLoaderTmpSync } from '../../utils/index.js';
3
+ import { FrameworkEnum, parseFramework } from '../../utils/index.js';
4
+ export const DEFAULT_DTO_CONFIG = {
5
+ withDefaultHeaders: true,
6
+ };
7
+ function mergeDtoConfig(base, patch) {
8
+ return {
9
+ ...base,
10
+ ...patch,
11
+ codes: patch.codes ? { ...base.codes, ...patch.codes } : base.codes,
12
+ defaultHeaders: patch.defaultHeaders
13
+ ? { ...base.defaultHeaders, ...patch.defaultHeaders }
14
+ : base.defaultHeaders,
15
+ socket: patch.socket ? { ...base.socket, ...patch.socket } : base.socket,
16
+ hooks: patch.hooks ?? base.hooks,
17
+ plugins: patch.plugins ? [...(base.plugins ?? []), ...patch.plugins] : base.plugins,
18
+ };
19
+ }
20
+ export default class DtoRuntime {
21
+ _runtime;
22
+ _system;
23
+ _config = { ...DEFAULT_DTO_CONFIG };
24
+ _framework = FrameworkEnum.ELYSIA;
25
+ _bootConfig = {};
26
+ constructor({ system }) {
27
+ this._system = system;
28
+ }
29
+ async onInit(props = {}) {
30
+ this._bootConfig = props.config ?? {};
31
+ await this.syncFromTmp();
32
+ bindLoaderTmpSync(this);
33
+ }
34
+ syncFromTmp = async () => {
35
+ this._framework = parseFramework(this._system?.tmp?.configs?.service?.framework);
36
+ this.applyConfig(DEFAULT_DTO_CONFIG, this._system?.tmp?.configs?.service?.loaders?.dto ?? {}, this._bootConfig, { rebuild: true });
37
+ };
38
+ get instance() {
39
+ return this._runtime;
40
+ }
41
+ get config() {
42
+ return this._config;
43
+ }
44
+ get framework() {
45
+ return this._framework;
46
+ }
47
+ configure(config = {}, options = {}) {
48
+ this.applyConfig(this._config, config, options);
49
+ return this;
50
+ }
51
+ use(...plugins) {
52
+ this._runtime.use(...plugins);
53
+ this._config = mergeDtoConfig(this._config, { plugins });
54
+ return this;
55
+ }
56
+ express() {
57
+ return this._runtime.express();
58
+ }
59
+ elysia() {
60
+ return this._runtime.elysia();
61
+ }
62
+ node() {
63
+ return this._runtime.node();
64
+ }
65
+ websocket() {
66
+ return this._runtime.websocket();
67
+ }
68
+ socketIo() {
69
+ return this._runtime.socketIo();
70
+ }
71
+ attachWebSocket(socket, requestId) {
72
+ return this._runtime.attachWebSocket(socket, requestId);
73
+ }
74
+ attachSocketIo(socket) {
75
+ return this._runtime.attachSocketIo(socket);
76
+ }
77
+ fetch() {
78
+ return this._runtime.fetch();
79
+ }
80
+ forRequest(request) {
81
+ return this._runtime.forRequest(request);
82
+ }
83
+ applyConfig(...sources) {
84
+ const last = sources[sources.length - 1];
85
+ const options = last && 'rebuild' in last ? sources.pop() : {};
86
+ const merged = sources.reduce((acc, part) => mergeDtoConfig(acc, part), { ...DEFAULT_DTO_CONFIG });
87
+ this._config = merged;
88
+ if (!this._runtime || options.rebuild !== false) {
89
+ this._runtime = new DTO(this._config);
90
+ }
91
+ }
92
+ }
@@ -1 +1,39 @@
1
- import{LoggerLayerEnum as a,registerGracefulShutdown as s}from "../../utils/index.js";export default class Events{#e;constructor({logger:e}){this.#e=e}onInit=({})=>{this._globalLoader();this._DILoader()};_globalLoader=()=>{process.on("uncaughtException",(e,o)=>{this.#e.log({level:a.CRITICAL,message:`Uncaught Exception: ${e.message}`,payload:{stack:e.stack,origin:o}})});process.on("unhandledRejection",(e,o)=>{const t=e instanceof Error?e:Error(String(e));this.#e.log({level:a.CRITICAL,message:`Unhandled Rejection: ${t.message}`,payload:{stack:t.stack}})})};_DILoader=()=>{s()};get global(){return this._globalLoader()}}
1
+ import { LoggerLayerEnum, registerGracefulShutdown } from '../../utils/index.js';
2
+ export default class Events {
3
+ #logger;
4
+ constructor({ logger }) {
5
+ this.#logger = logger;
6
+ }
7
+ onInit = ({}) => {
8
+ this._globalLoader();
9
+ this._DILoader();
10
+ };
11
+ _globalLoader = () => {
12
+ process.on("uncaughtException", (error, origin) => {
13
+ this.#logger.log({
14
+ level: LoggerLayerEnum.CRITICAL,
15
+ message: `Uncaught Exception: ${error.message}`,
16
+ payload: {
17
+ stack: error.stack,
18
+ origin: origin
19
+ }
20
+ });
21
+ });
22
+ process.on("unhandledRejection", (reason, promise) => {
23
+ const error = reason instanceof Error ? reason : new Error(String(reason));
24
+ this.#logger.log({
25
+ level: LoggerLayerEnum.CRITICAL,
26
+ message: `Unhandled Rejection: ${error.message}`,
27
+ payload: {
28
+ stack: error.stack,
29
+ }
30
+ });
31
+ });
32
+ };
33
+ _DILoader = () => {
34
+ registerGracefulShutdown();
35
+ };
36
+ get global() {
37
+ return this._globalLoader();
38
+ }
39
+ }
@@ -1 +1,13 @@
1
- import System from "./system/index.js";import Configs from "./configs/index.js";import KafkaForCore from "./kafka/index.js";import RedisForCore from "./redis/index.js";import MongoForCore from "./mongo/index.js";import Logger from "./logger/index.js";import Events from "./events/index.js";import Localizations from "./localizations/index.js";import DtoRuntime from "./dto/index.js";import Controller from "./controller/index.js";import Service from "./service/index.js";import Clients from "./clients/index.js";export{System,Configs,Logger,Events,Localizations,DtoRuntime,Controller,Service,Clients,KafkaForCore,RedisForCore,MongoForCore};
1
+ import System from "./system/index.js";
2
+ import Configs from "./configs/index.js";
3
+ import KafkaForCore from "./kafka/index.js";
4
+ import RedisForCore from "./redis/index.js";
5
+ import MongoForCore from "./mongo/index.js";
6
+ import Logger from "./logger/index.js";
7
+ import Events from "./events/index.js";
8
+ import Localizations from "./localizations/index.js";
9
+ import DtoRuntime from "./dto/index.js";
10
+ import Controller from "./controller/index.js";
11
+ import Service from "./service/index.js";
12
+ import Clients from "./clients/index.js";
13
+ export { System, Configs, Logger, Events, Localizations, DtoRuntime, Controller, Service, Clients, KafkaForCore, RedisForCore, MongoForCore };
@@ -1 +1,142 @@
1
- export{resolveKafkaJsSsl}from "./resolve-ssl.js";import{Kafka as N,logLevel as P}from"kafkajs";import{bindLoaderTmpSync as Q}from "../../utils/helpers/tmp/loader-tmp-sync.js";import{resolveKafkaJsSsl as R}from "./resolve-ssl.js";import{readKafkaLoaderOptions as M}from "../../utils/helpers/kafka-loader-options/index.js";export default class KafkaForCore{_instance;_producer;clientId="";brokers="";username=null;password=null;#q;#j;constructor({system:z,configs:j}){this.#q=z;this.#j=j}onDispose=async()=>{await this.teardownKafka()};onInit=async()=>{await this.syncFromTmp();Q(this)};syncFromTmp=async()=>{await this.teardownKafka();this.clientId=this.#j.all?.kafkaClientId;this.brokers=this.#j.all?.kafkaBrokers;this.username=this.#j.all?.kafkaUsername;this.password=this.#j.all?.kafkaPassword;if(!M(this.#q?.tmp?.configs?.service?.loaders).enabled)return;const j=(Array.isArray(this.brokers)?this.brokers:this.brokers?.split(",")??[]).map((D)=>D?.trim()).filter(Boolean);if(j.length===0)return;await this.kafkaLoader({clientId:this.clientId,brokers:j,username:this.username,password:this.password});await this.initializeKafkaInfrastructure()};teardownKafka=async()=>{if(this._producer){try{await this._producer.disconnect()}catch{}this._producer=void 0}};kafkaLoader=async({clientId:z,brokers:j,username:D,password:F})=>{const E={clientId:z,brokers:j,sasl:D&&F?{mechanism:"plain",username:D,password:F}:void 0,ssl:R(j),logLevel:P.ERROR,logCreator:()=>{return({level:q,log:G})=>{console.error(`Kafka ${G.message}`)}},retry:{initialRetryTime:100,retries:8}};try{const q=new N(E);this._instance=q;this._producer=q.producer();await this.producer.connect();return q}catch(q){console.error(`Kafka ${q}`)}};initializeKafkaInfrastructure=async()=>{const z=M(this.#q?.tmp?.configs?.service?.loaders),j=this.#j.all.kafkaBrokers,D=[...new Set([...this.#j.all.kafkaTopics])];if(!z.enabled||!j)return;const F=Array.isArray(D)?D:[];if(F.length===0)return;const E=this._instance.admin();try{await E.connect();const q=await E.listTopics(),G=F.filter((H)=>!q.includes(H)).map((H)=>({topic:H,numPartitions:1,replicationFactor:1}));if(G.length>0)await E.createTopics({waitForLeaders:!0,topics:G})}catch(q){}finally{await E.disconnect()}};sendMessage=async(z,j)=>{if(!this.producer)throw Error("Producer not ready");await this.producer.send({topic:z,messages:[{value:JSON.stringify(j)}],acks:0})};get producer(){return this._producer}get instance(){return this._instance}}
1
+ export { resolveKafkaJsSsl } from './resolve-ssl.js';
2
+ import { Kafka as KafkaClient, logLevel } from "kafkajs";
3
+ import { bindLoaderTmpSync } from '../../utils/helpers/tmp/loader-tmp-sync.js';
4
+ import { resolveKafkaJsSsl } from './resolve-ssl.js';
5
+ import { readKafkaLoaderOptions } from '../../utils/helpers/kafka-loader-options/index.js';
6
+ export default class KafkaForCore {
7
+ _instance;
8
+ _producer;
9
+ clientId = "";
10
+ brokers = "";
11
+ username = null;
12
+ password = null;
13
+ #system;
14
+ #configs;
15
+ constructor({ system, configs, }) {
16
+ this.#system = system;
17
+ this.#configs = configs;
18
+ }
19
+ onDispose = async () => {
20
+ await this.teardownKafka();
21
+ };
22
+ onInit = async () => {
23
+ await this.syncFromTmp();
24
+ bindLoaderTmpSync(this);
25
+ };
26
+ syncFromTmp = async () => {
27
+ await this.teardownKafka();
28
+ this.clientId = this.#configs.all?.kafkaClientId;
29
+ this.brokers = this.#configs.all?.kafkaBrokers;
30
+ this.username = this.#configs.all?.kafkaUsername;
31
+ this.password = this.#configs.all?.kafkaPassword;
32
+ const kafkaOpts = readKafkaLoaderOptions(this.#system?.tmp?.configs?.service?.loaders);
33
+ if (!kafkaOpts.enabled) {
34
+ return;
35
+ }
36
+ const brokersArray = (Array.isArray(this.brokers) ? this.brokers : (this.brokers?.split(',') ?? []))
37
+ .map(b => b?.trim())
38
+ .filter(Boolean);
39
+ if (brokersArray.length === 0) {
40
+ return;
41
+ }
42
+ await this.kafkaLoader({
43
+ clientId: this.clientId,
44
+ brokers: brokersArray,
45
+ username: this.username,
46
+ password: this.password,
47
+ });
48
+ await this.initializeKafkaInfrastructure();
49
+ };
50
+ teardownKafka = async () => {
51
+ if (this._producer) {
52
+ try {
53
+ await this._producer.disconnect();
54
+ }
55
+ catch { }
56
+ this._producer = undefined;
57
+ }
58
+ };
59
+ kafkaLoader = async ({ clientId, brokers, username, password }) => {
60
+ const kafkaConfig = {
61
+ clientId,
62
+ brokers,
63
+ sasl: (username && password) ? { mechanism: 'plain', username, password } : undefined,
64
+ ssl: resolveKafkaJsSsl(brokers),
65
+ logLevel: logLevel.ERROR,
66
+ logCreator: () => {
67
+ return ({ level, log }) => {
68
+ console.error(`Kafka ${log.message}`);
69
+ };
70
+ },
71
+ retry: {
72
+ initialRetryTime: 100,
73
+ retries: 8
74
+ }
75
+ };
76
+ try {
77
+ const kafka = new KafkaClient(kafkaConfig);
78
+ this._instance = kafka;
79
+ this._producer = kafka.producer();
80
+ await this.producer.connect();
81
+ return kafka;
82
+ }
83
+ catch (error) {
84
+ console.error(`Kafka ${error}`);
85
+ }
86
+ };
87
+ initializeKafkaInfrastructure = async () => {
88
+ const kafkaOpts = readKafkaLoaderOptions(this.#system?.tmp?.configs?.service?.loaders);
89
+ const kafkaBrokers = this.#configs.all.kafkaBrokers;
90
+ const kafkaTopics = [
91
+ ...new Set([
92
+ ...this.#configs.all.kafkaTopics
93
+ ])
94
+ ];
95
+ if (!kafkaOpts.enabled || !kafkaBrokers) {
96
+ return;
97
+ }
98
+ const topicsToCreate = Array.isArray(kafkaTopics) ? kafkaTopics : [];
99
+ if (topicsToCreate.length === 0)
100
+ return;
101
+ const admin = this._instance.admin();
102
+ try {
103
+ await admin.connect();
104
+ const existingTopics = await admin.listTopics();
105
+ const newTopics = topicsToCreate
106
+ .filter(topic => !existingTopics.includes(topic))
107
+ .map(topic => ({
108
+ topic,
109
+ numPartitions: 1,
110
+ replicationFactor: 1
111
+ }));
112
+ if (newTopics.length > 0) {
113
+ await admin.createTopics({
114
+ waitForLeaders: true,
115
+ topics: newTopics
116
+ });
117
+ }
118
+ }
119
+ catch (error) {
120
+ //console.log('Core kafka error', error)
121
+ }
122
+ finally {
123
+ await admin.disconnect();
124
+ }
125
+ };
126
+ // => Helpers
127
+ sendMessage = async (topic, message) => {
128
+ if (!this.producer)
129
+ throw new Error("Producer not ready");
130
+ await this.producer.send({
131
+ topic,
132
+ messages: [{ value: JSON.stringify(message) }],
133
+ acks: 0
134
+ });
135
+ };
136
+ get producer() {
137
+ return this._producer;
138
+ }
139
+ get instance() {
140
+ return this._instance;
141
+ }
142
+ }
@@ -1 +1,23 @@
1
- import q from"node:fs";export function resolveKafkaJsSsl(x=[]){const y=process.env.KAFKA_SSL==="true",z=x.some((B)=>/:9095\b/.test(B));if(!y&&!z)return!1;const j=process.env.KAFKA_SSL_CA||"/etc/tls/infra/ca.crt";try{if(j&&q.existsSync(j))return{ca:[q.readFileSync(j,"utf-8")],rejectUnauthorized:!1}}catch{}return{rejectUnauthorized:!1}}
1
+ import fs from 'node:fs';
2
+ /** Bare-metal SASL_SSL (9095) from KAFKA_SSL + KAFKA_SSL_CA / bare-metal Kafka TLS */
3
+ export function resolveKafkaJsSsl(brokers = []) {
4
+ const envSsl = process.env.KAFKA_SSL === 'true';
5
+ const portSsl = brokers.some((b) => /:9095\b/.test(b));
6
+ if (!envSsl && !portSsl) {
7
+ return false;
8
+ }
9
+ const caPath = process.env.KAFKA_SSL_CA || '/etc/tls/infra/ca.crt';
10
+ try {
11
+ if (caPath && fs.existsSync(caPath)) {
12
+ return {
13
+ ca: [fs.readFileSync(caPath, 'utf-8')],
14
+ // Private CA + ts_ip broker — match infra kafka-test (no hostname verify)
15
+ rejectUnauthorized: false,
16
+ };
17
+ }
18
+ }
19
+ catch {
20
+ // fall through — still enable TLS without custom CA
21
+ }
22
+ return { rejectUnauthorized: false };
23
+ }
@@ -1 +1,46 @@
1
- import o from"path";import n from"i18next";import s from"i18next-fs-backend";import*as e from"i18next-http-middleware";import{bindLoaderTmpSync as r}from "../../utils/index.js";export default class Localizations{_instance=null;#t;#n;constructor({system:t,configs:a}){this.#t=t;this.#n=a}onInit=async()=>{await this.syncFromTmp();r(this)};syncFromTmp=async()=>{this._instance=null;const t=this.#t.tmp.configs.service.loaders.localization;this.i18next({loadPath:o.join(this.#t.tmp.configs.rootFolderPath,t.loadPath),fallbackLang:t.fallbackLang,preloadLang:t.preloadLangs})};i18next=({loadPath:t,fallbackLang:a,preloadLang:i})=>{if(this._instance)return this._instance;n.use(s).use(e.LanguageDetector).init({fallbackLng:a,preload:i,backend:{loadPath:`${t}/{{lng}}.json`}});if(n)this._instance=n;return n};get instance(){return this._instance}}
1
+ import path from "path";
2
+ import i18next from "i18next";
3
+ import Backend from 'i18next-fs-backend';
4
+ import * as middleware from 'i18next-http-middleware';
5
+ import { bindLoaderTmpSync } from '../../utils/index.js';
6
+ export default class Localizations {
7
+ _instance = null;
8
+ #system;
9
+ #configs;
10
+ constructor({ system, configs, }) {
11
+ this.#system = system;
12
+ this.#configs = configs;
13
+ }
14
+ onInit = async () => {
15
+ await this.syncFromTmp();
16
+ bindLoaderTmpSync(this);
17
+ };
18
+ syncFromTmp = async () => {
19
+ this._instance = null;
20
+ const localization = this.#system.tmp.configs.service.loaders.localization;
21
+ this.i18next({
22
+ loadPath: path.join(this.#system.tmp.configs.rootFolderPath, localization.loadPath),
23
+ fallbackLang: localization.fallbackLang,
24
+ preloadLang: localization.preloadLangs,
25
+ });
26
+ };
27
+ i18next = ({ loadPath, fallbackLang, preloadLang, }) => {
28
+ if (this._instance) {
29
+ return this._instance;
30
+ }
31
+ i18next
32
+ .use(Backend)
33
+ .use(middleware.LanguageDetector)
34
+ .init({
35
+ fallbackLng: fallbackLang,
36
+ preload: preloadLang,
37
+ backend: { loadPath: `${loadPath}/{{lng}}.json` }
38
+ });
39
+ if (i18next)
40
+ this._instance = i18next;
41
+ return i18next;
42
+ };
43
+ get instance() {
44
+ return this._instance;
45
+ }
46
+ }