@xrystal/core 3.38.2 → 3.38.3
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.
- package/README.md +251 -2146
- package/package.json +3 -3
- package/x/bin/helpers/.generated/tmp-schema.mjs +8 -1
- package/x/bin/helpers/build-config.mjs +1 -0
- package/x/bin/scripts/clean-dist-tests.mjs +50 -0
- package/x/bin/scripts/fix-dist-imports.mjs +7 -2
- package/x/dist/loader/clients/index.js +1 -1
- package/x/dist/loader/configs/index.js +1 -1
- package/x/dist/loader/controller/index.js +1 -1
- package/x/dist/loader/dto/index.js +1 -1
- package/x/dist/loader/events/index.js +1 -1
- package/x/dist/loader/index.js +1 -1
- package/x/dist/loader/kafka/index.js +1 -1
- package/x/dist/loader/localizations/index.js +1 -1
- package/x/dist/loader/logger/index.js +1 -1
- package/x/dist/loader/system/index.js +1 -1
- package/x/dist/project/index.js +1 -1
- package/x/dist/utils/constants/index.js +1 -1
- package/x/dist/utils/helpers/context/index.js +1 -1
- package/x/dist/utils/helpers/core/index.js +1 -1
- package/x/dist/utils/helpers/core/tmp-layout.js +1 -1
- package/x/dist/utils/helpers/date/index.js +1 -1
- package/x/dist/utils/helpers/dispatch/index.js +1 -1
- package/x/dist/utils/helpers/framework/index.js +1 -1
- package/x/dist/utils/helpers/handlers/adapters.js +1 -1
- package/x/dist/utils/helpers/handlers/execute.js +1 -1
- package/x/dist/utils/helpers/handlers/index.js +1 -1
- package/x/dist/utils/helpers/index.js +1 -1
- package/x/dist/utils/helpers/middleware/index.js +1 -1
- package/x/dist/utils/helpers/protocol/index.js +1 -1
- package/x/dist/utils/helpers/protocol/options.js +1 -1
- package/x/dist/utils/helpers/runtime/dto-access.js +1 -1
- package/x/dist/utils/helpers/runtime/index.js +1 -1
- package/x/dist/utils/helpers/runtime/shutdown.js +1 -1
- package/x/dist/utils/helpers/state/index.js +1 -1
- package/x/dist/utils/helpers/state/props-from-tmp.js +1 -1
- package/x/dist/utils/helpers/state/request-key-guard.js +1 -1
- package/x/dist/utils/helpers/state/scopes.js +1 -1
- package/x/dist/utils/helpers/tmp/index.js +1 -1
- package/x/dist/utils/helpers/tmp/loader-tmp-sync.js +1 -1
- package/x/dist/utils/helpers/tmp/tmp-loader.js +1 -1
- package/x/dist/utils/helpers/tmp/tmp-schema.js +1 -1
- package/x/dist/utils/helpers/tmp/tmp-watch.js +1 -1
- package/x/dist/utils/index.js +1 -1
- package/x/dist/utils/models/classes/class.clients.js +1 -1
- package/x/dist/utils/models/classes/class.tmp-file-loader.js +1 -1
- package/x/dist/utils/models/index.js +1 -1
- package/x/dist/utils/helpers/tests/tmp-schema.test.d.ts +0 -1
- package/x/dist/utils/helpers/tests/tmp-schema.test.js +0 -1
- package/x/dist/utils/helpers/tests/tmp-watch.test.d.ts +0 -1
- package/x/dist/utils/helpers/tests/tmp-watch.test.js +0 -1
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"author": "Yusuf Yasir KAYGUSUZ",
|
|
3
3
|
"name": "@xrystal/core",
|
|
4
|
-
"version": "3.38.
|
|
4
|
+
"version": "3.38.3",
|
|
5
5
|
"description": "Project core for xrystal",
|
|
6
6
|
"publishConfig": {
|
|
7
7
|
"access": "public",
|
|
@@ -57,10 +57,10 @@
|
|
|
57
57
|
"scripts": {
|
|
58
58
|
"dev": "node x/bin/main-cli.js dev",
|
|
59
59
|
"build": "node x/bin/main-cli.js build",
|
|
60
|
-
"test": "bun test x/tests",
|
|
60
|
+
"test": "bun test x/tests source/utils/helpers/tests",
|
|
61
61
|
"lint": "eslint source",
|
|
62
62
|
"prepublishOnly": "bun run release:prepare && node x/bin/scripts/verify-publish-config.mjs",
|
|
63
|
-
"release:prepare": "bun run lint && bun run build && bun test x/tests",
|
|
63
|
+
"release:prepare": "bun run lint && bun run build && bun test x/tests source/utils/helpers/tests",
|
|
64
64
|
"build:prod": "bun run release:prepare && node x/bin/scripts/clean-source-types.mjs",
|
|
65
65
|
"build:dev": "node x/bin/main-cli.js dev",
|
|
66
66
|
"start": "node x/bin/main-cli.js start",
|
|
@@ -56,7 +56,14 @@ var defaults_default = {
|
|
|
56
56
|
// source/utils/constants/index.ts
|
|
57
57
|
var packageDefaults = Object.freeze({
|
|
58
58
|
...defaults_default,
|
|
59
|
-
layoutPaths: Object.freeze({ ...defaults_default.layoutPaths })
|
|
59
|
+
layoutPaths: Object.freeze({ ...defaults_default.layoutPaths }),
|
|
60
|
+
buildDefaults: Object.freeze({ ...defaults_default.buildDefaults }),
|
|
61
|
+
tsconfigDefaults: Object.freeze({
|
|
62
|
+
...defaults_default.tsconfigDefaults,
|
|
63
|
+
compilerOptions: Object.freeze({ ...defaults_default.tsconfigDefaults.compilerOptions })
|
|
64
|
+
}),
|
|
65
|
+
eslintDefaults: Object.freeze({ ...defaults_default.eslintDefaults }),
|
|
66
|
+
tmpWatchDefaults: Object.freeze({ ...defaults_default.tmpWatchDefaults })
|
|
60
67
|
});
|
|
61
68
|
var tmpFileName = `${packageDefaults.tmpBaseName}${packageDefaults.tmpExtension}`;
|
|
62
69
|
|
|
@@ -287,6 +287,7 @@ export function resolveCoreBuildSteps(root, distRel, buildConfig = {}) {
|
|
|
287
287
|
steps.push('node x/bin/scripts/minify-dist.mjs')
|
|
288
288
|
}
|
|
289
289
|
steps.push('node x/bin/scripts/fix-dist-imports.mjs')
|
|
290
|
+
steps.push('node x/bin/scripts/clean-dist-tests.mjs')
|
|
290
291
|
steps.push('node x/bin/scripts/clean-source-types.mjs')
|
|
291
292
|
return steps
|
|
292
293
|
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import fs from 'node:fs'
|
|
2
|
+
import path from 'node:path'
|
|
3
|
+
|
|
4
|
+
const distRoot = path.join(process.cwd(), 'x', 'dist')
|
|
5
|
+
const TEST_FILE_RE = /\.test\.(js|d\.ts)$/
|
|
6
|
+
|
|
7
|
+
export function cleanDistTests(distDir = distRoot) {
|
|
8
|
+
if (!fs.existsSync(distDir)) {
|
|
9
|
+
return { removed: 0 }
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
let removed = 0
|
|
13
|
+
|
|
14
|
+
function walk(dir) {
|
|
15
|
+
for (const name of fs.readdirSync(dir)) {
|
|
16
|
+
const abs = path.join(dir, name)
|
|
17
|
+
const stat = fs.statSync(abs)
|
|
18
|
+
if (stat.isDirectory()) {
|
|
19
|
+
walk(abs)
|
|
20
|
+
continue
|
|
21
|
+
}
|
|
22
|
+
if (!TEST_FILE_RE.test(name)) continue
|
|
23
|
+
fs.unlinkSync(abs)
|
|
24
|
+
removed++
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
walk(distDir)
|
|
29
|
+
|
|
30
|
+
function pruneEmptyDirs(dir) {
|
|
31
|
+
for (const name of fs.readdirSync(dir)) {
|
|
32
|
+
const abs = path.join(dir, name)
|
|
33
|
+
if (fs.statSync(abs).isDirectory()) pruneEmptyDirs(abs)
|
|
34
|
+
}
|
|
35
|
+
if (dir !== distDir && fs.readdirSync(dir).length === 0) {
|
|
36
|
+
fs.rmdirSync(dir)
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
pruneEmptyDirs(distDir)
|
|
41
|
+
return { removed }
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const invoked = process.argv[1] ? path.resolve(process.argv[1]) : ''
|
|
45
|
+
const isMain = invoked.endsWith(`${path.sep}clean-dist-tests.mjs`)
|
|
46
|
+
|
|
47
|
+
if (isMain) {
|
|
48
|
+
const result = cleanDistTests()
|
|
49
|
+
console.log(`clean-dist-tests: removed ${result.removed} file(s)`)
|
|
50
|
+
}
|
|
@@ -50,10 +50,15 @@ export function fixImportSpecifiersInSource(source, fileDir) {
|
|
|
50
50
|
const fixed = fixRelativeSpecifier(fileDir, spec)
|
|
51
51
|
return fixed === spec ? match : `from ${quote}${fixed}${quote}`
|
|
52
52
|
})
|
|
53
|
-
|
|
53
|
+
next = next.replace(/import\s*(['"])(\.\.?\/[^'"]+?)\1/g, (match, quote, spec) => {
|
|
54
54
|
const fixed = fixRelativeSpecifier(fileDir, spec)
|
|
55
|
-
return fixed === spec ? match :
|
|
55
|
+
return fixed === spec ? match : `import ${quote}${fixed}${quote}`
|
|
56
56
|
})
|
|
57
|
+
next = next.replace(/import\s*\(\s*(['"])(\.\.?\/[^'"]+?)\1\s*\)/g, (match, quote, spec) => {
|
|
58
|
+
const fixed = fixRelativeSpecifier(fileDir, spec)
|
|
59
|
+
return fixed === spec ? match : `import(${quote}${fixed}${quote})`
|
|
60
|
+
})
|
|
61
|
+
return next
|
|
57
62
|
}
|
|
58
63
|
|
|
59
64
|
export function fixDistImports(distDir = distRoot) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{BaseApiClient as t,CoreClientsEnum as s}from"../../utils
|
|
1
|
+
import{BaseApiClient as t,CoreClientsEnum as s}from"../../utils";import{bindLoaderTmpSync as i}from"../../utils";export default class Clients{_instances={};#s;constructor({configs:n}){this.#s=n}async onInit(){await this.syncFromTmp();i(this)}syncFromTmp=async()=>{this._instances[s.BASE_API_CLIENT]=new t({clientName:s.BASE_API_CLIENT,baseURL:this.#s.all.baseApiUri||""})};get instances(){return this._instances}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import c from"node:path";import i from"lodash";import{pathToFileURL as l}from"node:url";import{bindLoaderTmpSync as v}from"../../utils
|
|
1
|
+
import c from"node:path";import i from"lodash";import{pathToFileURL as l}from"node:url";import{bindLoaderTmpSync as v}from"../../utils";import{Constants as a}from"../../utils";export default class Configs{publicFolderName=a.publicFolderName;kafkaLogsTopic=a.kafkaLogsTopic;#s;#e;constructor({system:s}){this.#s=s;return new Proxy(this,{get:(o,r)=>{return o[r]||o.config?.[r]}})}onInit=async()=>{await this.syncFromTmp();v(this)};syncFromTmp=async()=>{const s=process.cwd(),e=this.#s.tmp,o=e.configs.service.loaders.configs.loadPath,r=o.startsWith("@/")?c.join(process.cwd(),o.slice(2)):c.resolve(e.configs.rootFolderPath,o),p=import(l(r).href);this.#e={worker:process.env.WORKER==="true"?!0:!1,mode:process.env.MODE,nodeEnv:"development",debug:process.env.SYSTEM_LOGGER_LAYER??"",https:process.env.HTTPS??"false",httpsfileEncoding:process.env.ENCODING||"utf8",httpsCertfile:process.env.HTTPS_CERT_FILE??"",httpsKeyfile:process.env.HTTPS_KEY_FILE??"",rootFolderPath:e.configs.rootFolderPath||"x",projectName:e.project.name,serviceName:e.configs.service.name??"",projectNamePrefixEnv:process.env.PROJECT_NAME_PREFIX||"",projectNameEnv:process.env.PROJECT_NAME||"",projectNameSuffixEnv:process.env.PROJECT_NAME_SUFFIX||"",systemStaticFolderPath:c.resolve(e.configs.rootFolderPath,this.publicFolderName),systemLoggerLayer:process.env.SYSTEM_LOGGER_LAYER??"info",isKafkaPassive:process.env.IS_KAFKA_PASSIVE==="true"?!0:!1,kafkaClientId:e.configs.service.name??"",kafkaBrokers:process.env.KAFKA_BROKERS??"",kafkaUsername:process.env.KAFKA_USERNAME??"",kafkaPassword:process.env.KAFKA_PASSWORD??"",kafkaTopics:[],kafkaLogsTopic:this.kafkaLogsTopic,baseApiUri:process.env.HTTPS==="true"?process.env.SYSTEM_HTTPS_BASE_API_URI??"":process.env.SYSTEM_BASE_API_URI??"",port:Number(process.env.PORT),internalSecret:process.env.INTERNAL_SECRET??"",secret:process.env.SECRET??"",cwd:s,env:"development"};try{const t=await p,f=t?.default||t?.configs||t||{},m=i.mergeWith({},this.#e,f,(n,E)=>{if(i.isArray(n))return n.concat(E)});this.#e=Object.freeze(m)}catch{this.#e=Object.freeze(this.#e)}};setConfig(s){const e=Object.assign(this.#e,s);this.#e=Object.freeze(e)}_(s){return this.#e[s]}get all(){return this.#e}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import y from"qs";import C from"../../loader/logger
|
|
1
|
+
import y from"qs";import C from"../../loader/logger";import S from"../../loader/system";import{bindLoaderTmpSync as T,getClientIp as E,getConfiguredProtocols as D,isRealtimeProtocol as h,LoggerLayerEnum as O,parseResponseMessage as j,ProtocolEnum as g,x as q,controllerContextStorage,getControllerCtx,runControllerStore as P,adapterBagFromRequest as B,isFetchRequest as I,toHandler as M,toRealtimeHandler as H,resolveCtrOptions as A}from"../../utils";export{controllerContextStorage,getControllerCtx};export const runController=P;function x(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 b(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 w(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 R(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("[xrystal] use dtoMiddleware() — builder attaches at request start via @xrystal/dto adapter")}export class BaseController{system=q.get(S);logger=q.get(C);supportedProtocols=[g.HTTP,g.WEBSOCKET];get store(){return getControllerCtx()}get protocol(){return this.store?.protocol||g.HTTP}get req(){const t=this.store,e=t?.ctx||{},r=t?.req||{},a=I(e.request)?e.request:void 0,o=B(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=y.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:E(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("[xrystal] 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=R(a.headers["content-type"]).toLowerCase(),n=parseInt(R(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 y.parse(d);try{return JSON.parse(d)}catch{try{return y.parse(d)}catch{return d}}},c=F,u=s&&typeof s==="object"&&!c(s)&&Object.keys(s).length>0;if(!h(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",(k)=>{m+=String(k)});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();T(this)}syncFromTmp=()=>{this.supportedProtocols=D()};parseMessage(t,e,r=!1){return j(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){b(t,e);const{data:a,extraData:o}=w(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}=w(n);if(typeof c==="string")o=c;b(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(x(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(x(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(O.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(h(a))return H(o,a);return M(o,r)}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{DTO as u}from"@xrystal/dto/dto";import{bindLoaderTmpSync as m}from"../../utils
|
|
1
|
+
import{DTO as u}from"@xrystal/dto/dto";import{bindLoaderTmpSync as m}from"../../utils";import{FrameworkEnum as c,parseFramework as f}from"../../utils";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 +1 @@
|
|
|
1
|
-
import{LoggerLayerEnum as a,registerGracefulShutdown as s}from"../../utils
|
|
1
|
+
import{LoggerLayerEnum as a,registerGracefulShutdown as s}from"../../utils";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()}}
|
package/x/dist/loader/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import System from"./system
|
|
1
|
+
import System from"./system";import Configs from"./configs";import KafkaForCore from"./kafka";import Logger from"./logger";import Events from"./events";import Localizations from"./localizations";import DtoRuntime from"./dto";import Controller from"./controller";import Service from"./service";import Clients from"./clients";export{System,Configs,Logger,Events,Localizations,DtoRuntime,Controller,Service,Clients,KafkaForCore};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Kafka as M,logLevel as N}from"kafkajs";import{bindLoaderTmpSync as O}from"../../utils
|
|
1
|
+
import{Kafka as M,logLevel as N}from"kafkajs";import{bindLoaderTmpSync as O}from"../../utils";export default class KafkaForCore{_instance;_producer;clientId="";brokers="";username=null;password=null;#q;#h;constructor({system:h,configs:q}){this.#q=h;this.#h=q}onDispose=async()=>{await this.teardownKafka()};onInit=async()=>{await this.syncFromTmp();O(this)};syncFromTmp=async()=>{await this.teardownKafka();this.clientId=this.#h.all?.kafkaClientId;this.brokers=this.#h.all?.kafkaBrokers;this.username=this.#h.all?.kafkaUsername;this.password=this.#h.all?.kafkaPassword;if(this.#h.all.isKafkaPassive)return;const h=(Array.isArray(this.brokers)?this.brokers:this.brokers?.split(",")??[]).map((q)=>q?.trim()).filter(Boolean);if(h.length===0)throw Error("Broker list error");await this.kafkaLoader({clientId:this.clientId,brokers:h,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:h,brokers:q,username:F,password:E})=>{const D={clientId:h,brokers:q,sasl:F&&E?{mechanism:"plain",username:F,password:E}:void 0,ssl:!1,logLevel:N.ERROR,logCreator:()=>{return({level:z,log:G})=>{console.error(`Kafka ${G.message}`)}},retry:{initialRetryTime:100,retries:8}};try{const z=new M(D);this._instance=z;this._producer=z.producer();await this.producer.connect();return z}catch(z){console.error(`Kafka ${z}`)}};initializeKafkaInfrastructure=async()=>{const{kafkaBrokers:h,kafkaTopics:q,isKafkaPassive:F}={isKafkaPassive:process.env.IS_KAFKA_PASSIVE==="true"?!0:!1,kafkaBrokers:process.env?.KAFKA_BROKERS,kafkaTopics:[...new Set([...this.#h.all.kafkaTopics])]};if(F===!0||!h)return;const E=Array.isArray(q)?q:[];if(E.length===0)return;const D=this._instance.admin();try{await D.connect();const z=await D.listTopics(),G=E.filter((J)=>!z.includes(J)).map((J)=>({topic:J,numPartitions:1,replicationFactor:1}));if(G.length>0)await D.createTopics({waitForLeaders:!0,topics:G})}catch(z){}finally{await D.disconnect()}};sendMessage=async(h,q)=>{if(!this.producer)throw Error("Producer not ready");await this.producer.send({topic:h,messages:[{value:JSON.stringify(q)}],acks:0})};get producer(){return this._producer}get instance(){return this._instance}}
|
|
@@ -1 +1 @@
|
|
|
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
|
|
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";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,2 +1,2 @@
|
|
|
1
|
-
import l,{format as o}from"winston";import p from"winston-transport";import"winston-daily-rotate-file";import d from"node:path";import{Partitioners as y}from"kafkajs";import{LoggerLayerEnum as r}from"../../utils
|
|
1
|
+
import l,{format as o}from"winston";import p from"winston-transport";import"winston-daily-rotate-file";import d from"node:path";import{Partitioners as y}from"kafkajs";import{LoggerLayerEnum as r}from"../../utils";import{LogDTO as k}from"../../utils";import{bindLoaderTmpSync as u}from"../../utils";import{getRequestId as f}from"../../utils";class h extends p{service;constructor(e,t){super(e);this.service=t}log(e,t){setImmediate(()=>this.emit("logged",e));this.service.logToKafka(e).finally(()=>t())}}const v={critical:r.CRITICAL,error:r.ERROR,warn:r.WARN,info:r.INFO,http:r.HTTP,debug:r.DEBUG},w={critical:"red",error:"magenta",warn:"yellow",info:"green",http:"cyan",debug:"blue"};export default class Logger{serviceName="";isKafkaReady=!1;kafkaProducer=null;kafkaLogsTopic="";winston;#t;#e;#s;constructor({system:e,configs:t,kafkaForCore:a}){this.#t=e;this.#e=t;this.#s=a}onDispose=async()=>{await this.teardownLogger()};onInit=async()=>{await this.syncFromTmp();u(this)};syncFromTmp=async()=>{await this.teardownLogger();this.serviceName=this.#t?.tmp?.configs?.service?.name??"";this.kafkaLogsTopic=this.#e?.all?.kafkaLogsTopic;l.addColors(w);const e=this.#t?.tmp?.configs?.service?.loaders?.loggers,{kafkaBrokers:t,isKafkaPassive:a}=this.#e.all,i=t?String(t).split(",").map((m)=>m.trim()):[];if(a===!1&&i.length>0&&this.#s.instance){this.kafkaProducer=this.#s.instance.producer({createPartitioner:y.DefaultPartitioner,retry:{initialRetryTime:500,retries:5}});try{await this.kafkaProducer?.connect();this.isKafkaReady=!0}catch{this.isKafkaReady=!1}}const c=e?.loadPath||"logs",s=e?.logLevel||e?.loggerLevel||"info";this.winstonLoader({loadPath:d.join(this.#e.all.rootFolderPath,c),loggerLevel:s})};teardownLogger=async()=>{if(this.kafkaProducer){try{await this.kafkaProducer.disconnect()}catch{}this.kafkaProducer=null}this.isKafkaReady=!1;if(this.winston){this.winston.clear();this.winston.close()}};winstonLoader=({loadPath:e,loggerLevel:t})=>{const{combine:a,timestamp:i,json:n,errors:c}=o,s=this.getTracingFormat(),m=a(s,i({format:"YYYY-MM-DD HH:mm:ss"}),c({stack:!0}),n({replacer:this.safeReplacer})),g=[new l.transports.Console({format:this.getConsoleFormat()}),new l.transports.DailyRotateFile({filename:d.resolve(e,"error","%DATE%_error.log"),level:"error",format:m,maxSize:"2mb",maxFiles:"7d"}),new l.transports.DailyRotateFile({filename:d.resolve(e,"critical","%DATE%_critical.log"),level:"critical",format:m,maxSize:"2mb",maxFiles:"14d"})];if(this.isKafkaReady&&this.kafkaProducer)g.push(new h({level:t},this));this.winston=l.createLogger({level:t,levels:v,format:s,transports:g});return this.winston};safeReplacer=(e,t)=>{if(t instanceof Headers)return Object.fromEntries(t.entries());if(t instanceof Error)return{message:t.message,stack:t.stack};return t};getTracingFormat=o((e)=>{if(e.id)return e;const t=f();if(t)e.id=t;return e});getConsoleFormat(){return o.combine(this.getTracingFormat(),o.timestamp({format:"YYYY-MM-DD HH:mm:ss"}),o.colorize({all:!0}),o.printf((e)=>{const t=typeof e.message==="object"?JSON.stringify(e.message,this.safeReplacer):e.message,a=e.id?` : id: ${e.id}`:"",i=e.payload?`
|
|
2
2
|
Payload: ${JSON.stringify(e.payload,this.safeReplacer)}`:"",n=e.code?` [Code: ${e.code}]`:"";return`${e.timestamp} [${this.serviceName}] ${e.level}${n}: ${t}${a}${i}`}))}normalizeLevel(e){return typeof e==="string"?e.toLowerCase():r[e].toLowerCase()}normalizeMessage(e){if(e===void 0||e===null)return;return typeof e==="string"?e:JSON.stringify(e,this.safeReplacer)}buildLogBody(e){return k.schema({level:this.normalizeLevel(e.level),service:this.serviceName,message:this.normalizeMessage(e.message),payload:e.payload,code:e.code,timestamp:e.timestamp??new Date().toISOString(),id:e.id??f()??void 0,env:this.#e.all.env}).build()}async logToKafka(e){if(!this.kafkaProducer||!this.isKafkaReady)return;try{const t=this.buildLogBody({level:e.level,message:e.message,payload:e.payload,code:e.code,id:e.id,timestamp:e.timestamp});await this.kafkaProducer.send({topic:this.kafkaLogsTopic,messages:[{value:JSON.stringify(t,this.safeReplacer)}],acks:1})}catch(t){this.isKafkaReady=!1}}log(e,t,a,i){const c=typeof e==="object"&&e!==null&&"level"in e?e:{level:e,message:t,payload:a,code:i},s=this.buildLogBody(c);this.winston.log(s.level,s.message,{id:s.id,payload:s.payload,code:s.code,service:s.service,timestamp:s.timestamp,env:s.env})}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{G as k,notifyRuntimeTmpChange as q,onTmpReload as v,setRuntimeTmpConfigs as w}from"../../utils
|
|
1
|
+
import{G as k,notifyRuntimeTmpChange as q,onTmpReload as v,setRuntimeTmpConfigs as w}from"../../utils";import{normalizeTmpDocument as x}from"../../utils/helpers/tmp/tmp-schema";export default class System{_core={};_tmp={};cwd=process.cwd();g=k;onInit=async({core:j})=>{this._core=j;await this.applyTmp(this._core._);v((b)=>void this.applyTmp(b))};async applyTmp(j){this._tmp=x(j);const b=this._tmp.configs;w(b);this.g.configureFromTmp(this._tmp);await q(b)}get core(){return this._core}get tmp(){return this._tmp}}
|
package/x/dist/project/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var __dirname="/home/runner/work/-xrystal-core/-xrystal-core/x/dist/project";import w from"path";import{System as G,Configs as I,Logger as J,Events as N,Localizations as O,DtoRuntime as Q,Clients as U,Controller as V,KafkaForCore as W}from"../loader
|
|
1
|
+
var __dirname="/home/runner/work/-xrystal-core/-xrystal-core/x/dist/project";import w from"path";import{System as G,Configs as I,Logger as J,Events as N,Localizations as O,DtoRuntime as Q,Clients as U,Controller as V,KafkaForCore as W}from"../loader";import{Constants as X,getCore as Y,x as Z}from"../utils";import{ensureCoreTmpEntry as _,isCorePackageRoot as $}from"../utils/helpers/core/tmp-layout";import{getTmpSnapshot as v}from"../utils/helpers/tmp/tmp-loader";export{ensureCoreTmpEntry,isCorePackageRoot}from"../utils/helpers/core/tmp-layout";export{getTmpSnapshot}from"../utils/helpers/tmp/tmp-loader";export const core=Y(),coreInit=async(q)=>{const{locales:b}=q;if(b)globalThis.__LOCAL_MESSAGES__=b};let A=!1;const x=async(q={})=>{if(A)return core;const b=process.cwd();if($(b))_(b);v();try{await(await Z.load([w.join(__dirname,"..","loader","**/*.{ts,js}")],{exclude:[w.join(__dirname,"..","utils","**/class.x.{ts,js}")]})).initialize([{service:G,props:{core}},{service:I,props:{}},{service:W,props:{}},{service:J,props:{}},{service:N,props:{}},{service:O,props:{}},{service:Q,props:{}},{service:V,props:{}},{service:U,props:{}}]);A=!0;return core}catch(j){const B=j instanceof Error?j.message:String(j);console.error(`[${X.packageName} core failure]: ${B}`);throw j}};export default x;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import e from"node:path";import{packageRootDir as a}from"../../utils/package-root
|
|
1
|
+
import e from"node:path";import{packageRootDir as a}from"../../utils/package-root";import t from"./defaults.json" with { type: 'json' };export const packageDefaults=Object.freeze({...t,layoutPaths:Object.freeze({...t.layoutPaths}),buildDefaults:Object.freeze({...t.buildDefaults}),tsconfigDefaults:Object.freeze({...t.tsconfigDefaults,compilerOptions:Object.freeze({...t.tsconfigDefaults.compilerOptions})}),eslintDefaults:Object.freeze({...t.eslintDefaults}),tmpWatchDefaults:Object.freeze({...t.tmpWatchDefaults})}),coreVersionPattern=/^\d{2}\.\d{2}\.\d{2}-v\d+$/,semverVersionPattern=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-.]+)?(?:\+[0-9A-Za-z-.]+)?$/;const o=`${packageDefaults.tmpBaseName}${packageDefaults.tmpExtension}`;export class Constants{static packageName=packageDefaults.packageName;static packageRootFolder=packageDefaults.packageRootFolder;static tmpBaseName=packageDefaults.tmpBaseName;static tmpExtension=packageDefaults.tmpExtension;static mainSourceFolder=packageDefaults.mainSourceFolder;static layoutPaths=packageDefaults.layoutPaths;static publicFolderName=packageDefaults.publicFolderName;static kafkaLogsTopic=packageDefaults.kafkaLogsTopic;static templateRepoUri=packageDefaults.templateRepoUri;static bundledCoreTmpPath=e.join(a,packageDefaults.packageRootFolder,o)}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{AsyncLocalStorage as w}from"node:async_hooks";export const runContextStorage=new w;export function getRunContext(){return runContextStorage.getStore()}export function getRequestId(){return getRunContext()?.requestId}export function runWithContext(m,j){return runContextStorage.run(m,j)}export function runWithRequestId(m,j,v="http"){return runWithContext({requestId:m,kind:v},j)}export function runWithTrace(m,j,v){return runWithContext({requestId:m,kind:"job",label:v},j)}export function patchRunContext(m){const j=getRunContext();if(!j)return;Object.assign(j,m)}export{controllerContextStorage,getControllerCtx,runControllerStore,adapterBagFromRequest,isFetchRequest}from"../../../utils/helpers/context/controller-store
|
|
1
|
+
import{AsyncLocalStorage as w}from"node:async_hooks";export const runContextStorage=new w;export function getRunContext(){return runContextStorage.getStore()}export function getRequestId(){return getRunContext()?.requestId}export function runWithContext(m,j){return runContextStorage.run(m,j)}export function runWithRequestId(m,j,v="http"){return runWithContext({requestId:m,kind:v},j)}export function runWithTrace(m,j,v){return runWithContext({requestId:m,kind:"job",label:v},j)}export function patchRunContext(m){const j=getRunContext();if(!j)return;Object.assign(j,m)}export{controllerContextStorage,getControllerCtx,runControllerStore,adapterBagFromRequest,isFetchRequest}from"../../../utils/helpers/context/controller-store";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import M from"handlebars";import{Constants as I,ProtocolEnum as J,TmpFileLoader as Q}from"../../../utils/index.js";import{controllerContextStorage as U}from"../../../utils/helpers/context/controller-store
|
|
1
|
+
import M from"handlebars";import{Constants as I,ProtocolEnum as J,TmpFileLoader as Q}from"../../../utils/index.js";import{controllerContextStorage as U}from"../../../utils/helpers/context/controller-store";import{getTmpSnapshot as V}from"../../../utils/helpers/tmp/tmp-loader";import{findFileRecursively as X}from"../../../utils/helpers/core/paths";import{parseProtocol as Y}from"../../../utils/helpers/protocol/index.js";export*from"../../../utils/helpers/core/paths";export*from"../../../utils/helpers/core/tmp-layout";export const getCore=()=>({_:V()}),getTmpConfig=({root:q=process.cwd(),tmpFileName:z=I.tmpBaseName,ext:B=I.tmpExtension}={})=>{const D=X(q,z,B);if(!D)throw Error(`${z}${B.startsWith(".")?B:`.${B}`} file not found`);return new Q({filePath:D}).getResolvedTmpFile()};export function resolveObjWithHandlebars(q,z){if(typeof q==="string")return M.compile(q)(z);else if(typeof q==="object"&&q!==null)for(const B in q)q[B]=resolveObjWithHandlebars(q[B],z);return q}export const withProtocol=async(q,z=J.HTTP)=>{const B=Y(z),D=U.getStore();if(D)D.protocol=B;return await q()},protocol=async(q,z=J.HTTP)=>withProtocol(q,z),argvsConverter=(q)=>{const z=q?.slice(2),B={};z.forEach((D)=>{if(D.startsWith("--")){console.log(D);const[G,K]=D.split("=");B[G.replace("--","")]=K||""}});return B},findExt=(q)=>{const z=q.split(".");return z[z.length-1]},changeExtensions=(q,z)=>{return q.replace(findExt(q),z)};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import U from"node:fs";import I from"node:path";import z from"yaml";import{Constants as J}from"../../../utils/constants
|
|
1
|
+
import U from"node:fs";import I from"node:path";import z from"yaml";import{Constants as J}from"../../../utils/constants";import{findAllFilesRecursively as L,findFileRecursively as A}from"../../../utils/helpers/core/paths";import{normalizeTmpDocument as D,readTmpServiceBlock as B,normalizeRootFolder as b,normalizeSourceFolder as x,resolveServiceLayoutPaths as k}from"../../../utils/helpers/tmp/tmp-schema";function M(E,q){return`${E}${q.startsWith(".")?q:`.${q}`}`}export function coreCanonicalTmpPath(E=process.cwd()){return I.join(I.resolve(E),J.packageRootFolder,M(J.tmpBaseName,J.tmpExtension))}export function assertCoreTmpGuard(E,q){if(!isCorePackageRoot(E))return;const H=coreCanonicalTmpPath(E);if(I.resolve(q)!==I.resolve(H))throw Error(`@xrystal/core: tmp.yml must stay at ${J.packageRootFolder}/tmp.yml (expected ${H}, got ${q})`)}function N(E,q){const H=I.resolve(E),K=I.resolve(q);return L(H,J.tmpBaseName,J.tmpExtension).filter((Q)=>I.resolve(Q)!==K)}export function ensureCoreTmpEntry(E=process.cwd(),q={}){const H=I.resolve(E);if(!isCorePackageRoot(H))throw Error("ensureCoreTmpEntry is only for @xrystal/core package root");const K=coreCanonicalTmpPath(H),Q=N(H,K);if(Q.length>0){const X=Q.map((W)=>I.relative(H,W)).join(", ");throw Error(`@xrystal/core: tmp.yml must only exist under ${J.packageRootFolder}/. Remove extra copies: ${X}`)}if(U.existsSync(K)){assertCoreTmpGuard(H,K);return{tmpFilePath:K,created:!1,layout:buildTmpLayout(H,_(K),K)}}return ensureTmpFile(H,{...q,patchServiceName:!1})}function S(E,q,H){const K=I.resolve(E);if(isCorePackageRoot(K)){const Q=coreCanonicalTmpPath(K);return U.existsSync(Q)?Q:null}return A(K,q,H)}function _(E){return z.parse(U.readFileSync(E,"utf8"))}export function isCorePackageRoot(E){const q=I.join(I.resolve(E),"package.json");if(!U.existsSync(q))return!1;try{return JSON.parse(U.readFileSync(q,"utf8")).name===J.packageName}catch{return!1}}export function resolveRootFolderPath(E,q,H){const K=D(E).configs,Q=B(K);if(Q.paths?.root?.trim())return b(Q.paths.root);const X=E.project;if(typeof X?.name==="string"&&X.name.trim())return X.name.trim();const W=I.relative(I.resolve(H),I.dirname(I.resolve(q)));if(W&&W!==".")return W;return J.packageRootFolder}export function resolveLayoutPaths(E){const q=B(E);return k(q)}export function resolveMainFolderPath(E){const q=B(E);if(q.paths?.source?.trim())return x(q.paths.source);return J.mainSourceFolder}export function buildTmpLayout(E,q,H){const K=I.resolve(E),Q=q?D(q).configs:void 0,X=q&&H&&!isCorePackageRoot(K)?resolveRootFolderPath(q,H,K):J.packageRootFolder,W=I.join(K,X),Y=resolveLayoutPaths(Q),V=resolveMainFolderPath(Q),Z={tests:I.join(W,Y.tests),environments:I.join(W,Y.environments),dist:I.join(W,Y.dist)};return{projectRoot:K,rootFolderPath:X,rootFolderAbs:W,tmpFilePath:H,mainFolderPath:V,paths:Y,pathsAbs:Z}}export function resolveTmpLayout(E=process.cwd(),q={}){const H=q.tmpFileName??J.tmpBaseName,K=q.ext??J.tmpExtension,Q=S(E,H,K);if(!Q)throw Error(`${M(H,K)} not found under ${I.resolve(E)}`);if(isCorePackageRoot(I.resolve(E)))assertCoreTmpGuard(E,Q);return buildTmpLayout(E,_(Q),Q)}export function resolveTmpLayoutOrDefaults(E=process.cwd()){const q=S(E,J.tmpBaseName,J.tmpExtension);if(!q)return buildTmpLayout(E,null,null);return buildTmpLayout(E,_(q),q)}export function resolveBundledCoreTmpPath(E=process.cwd()){if(U.existsSync(J.bundledCoreTmpPath))return J.bundledCoreTmpPath;let q=I.resolve(E);while(q!==I.dirname(q)){const H=I.join(q,"node_modules","@xrystal","core",J.packageRootFolder,M(J.tmpBaseName,J.tmpExtension));if(U.existsSync(H))return H;const K=I.join(q,"package.json");if(U.existsSync(K)){if(JSON.parse(U.readFileSync(K,"utf8")).name===J.packageName){const X=I.join(q,J.packageRootFolder,M(J.tmpBaseName,J.tmpExtension));if(U.existsSync(X))return X}}q=I.dirname(q)}throw Error("@xrystal/core bundled x/tmp.yml not found")}export function ownerTmpFilePath(E=process.cwd(),q){const H=q??resolveTmpLayoutOrDefaults(E);return I.join(H.rootFolderAbs,M(J.tmpBaseName,J.tmpExtension))}export function ensureTmpFile(E=process.cwd(),q={}){const H=I.resolve(E),K=q.patchServiceName??!0;if(isCorePackageRoot(H)){const V=coreCanonicalTmpPath(H),Z=N(H,V);if(Z.length>0){const $=Z.map((w)=>I.relative(H,w)).join(", ");throw Error(`@xrystal/core: tmp.yml must only exist under ${J.packageRootFolder}/. Remove extra copies: ${$}`)}if(U.existsSync(V)){assertCoreTmpGuard(H,V);return{tmpFilePath:V,created:!1,layout:buildTmpLayout(H,_(V),V)}}}else{const V=A(H,J.tmpBaseName,J.tmpExtension);if(V)return{tmpFilePath:V,created:!1,layout:buildTmpLayout(H,_(V),V)}}const Q=q.templatePath??resolveBundledCoreTmpPath(H);if(!U.existsSync(Q))throw Error("@xrystal/core bundled x/tmp.yml not found");const X=buildTmpLayout(H,null,null);U.mkdirSync(X.rootFolderAbs,{recursive:!0});const W=ownerTmpFilePath(H,X);let Y=U.readFileSync(Q,"utf8");if(K)try{const V=I.join(H,"package.json");if(U.existsSync(V)){const Z=JSON.parse(U.readFileSync(V,"utf8")),$=typeof Z.name==="string"?Z.name.replace(/^@/,"").replace(/\//g,"-"):null;if($){const w=z.parse(Y),G=w.configs??{},O=G.service;if(typeof O==="object"&&O!==null&&!Array.isArray(O))O.name=$;else G.service={name:$};w.configs=G;Y=z.stringify(w)}}}catch{}U.writeFileSync(W,Y);return{tmpFilePath:W,created:!0,layout:buildTmpLayout(H,_(W),W)}}export function resolveTmpLayoutEnsured(E=process.cwd()){return ensureTmpFile(E).layout}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{PolarityTypeEnum as $}from"../../../utils/models
|
|
1
|
+
import{PolarityTypeEnum as $}from"../../../utils/models";export function dateZoneConverter({polarity:e,date:o,zone:n,factor:r=1000}){let s=null;if(e===$.NEGATIVE)s=o.getTime()-r*n;else s=o.getTime()+r*n;return new Date(s).toISOString()}export function convertDate(e,o="/",n="-"){return e.split(o).map((s,t)=>t!==2?n:s)}export function convertTime(e,o=":",n="-"){return e.split(o).map((s,t)=>t!==2?n:s)}export function getDateAndTime({getDate:e=!0,getTime:o=!0,dateCharacter:n="-",timeCharacter:r=":",separatorCharacter:s="&"}){const t=new Date;let u="";if(!e&&!o)throw Error("Invalid options! Required one true value");if(e){const i=t.getDate().toString().padStart(2,"0"),a=(t.getMonth()+1).toString().padStart(2,"0");u=`${t.getFullYear()}${n}${a}${n}${i}`}if(o){const i=t.getHours().toString().padStart(2,"0"),a=t.getMinutes().toString().padStart(2,"0"),S=t.getSeconds().toString().padStart(2,"0");u=`${i}${r}${a}${r}${S}`}if(e&&o){const i=t.getDate().toString().padStart(2,"0"),a=(t.getMonth()+1).toString().padStart(2,"0"),S=t.getFullYear(),c=t.getHours().toString().padStart(2,"0"),g=t.getMinutes().toString().padStart(2,"0"),p=t.getSeconds().toString().padStart(2,"0");u=`${S}${n}${a}${n}${i}${s}${c}${r}${g}${r}${p}`}return u}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{expressSink as J}from"@xrystal/dto/express";import{nodeSink as K}from"@xrystal/dto/node";import{fetchSink as L}from"@xrystal/dto/fetch";import{elysiaSink as M}from"@xrystal/dto/elysia";import{websocketSink as N}from"@xrystal/dto/websocket";import{socketIoSink as Q}from"@xrystal/dto/socketio";import{FrameworkEnum as z,ProtocolEnum as C}from"../../../utils/models
|
|
1
|
+
import{expressSink as J}from"@xrystal/dto/express";import{nodeSink as K}from"@xrystal/dto/node";import{fetchSink as L}from"@xrystal/dto/fetch";import{elysiaSink as M}from"@xrystal/dto/elysia";import{websocketSink as N}from"@xrystal/dto/websocket";import{socketIoSink as Q}from"@xrystal/dto/socketio";import{FrameworkEnum as z,ProtocolEnum as C}from"../../../utils/models";import{getFramework as T}from"../../../utils/helpers/framework";import{getDtoRuntime as U}from"../../../utils/helpers/runtime";export{expressSink}from"@xrystal/dto/express";export{nodeSink}from"@xrystal/dto/node";export{fetchSink}from"@xrystal/dto/fetch";export{elysiaSink}from"@xrystal/dto/elysia";export{websocketSink}from"@xrystal/dto/websocket";export{socketIoSink}from"@xrystal/dto/socketio";export{dispatchExpressResponse,dispatchNodeResponse,toFetchResponse,applyElysiaTransport,dispatchWebSocketMessage,dispatchSocketIoMessage}from"@xrystal/dto/response";const V=(j)=>!!j&&typeof j==="object"&&("body"in j)&&("statusCode"in j),W=(j)=>j instanceof Response||j instanceof Blob||j instanceof Uint8Array||j instanceof ArrayBuffer,G=(j)=>j.socket??j.ctx?.ws??j.ctx,X=()=>U().config.socket?.event??"response";export function dispatchResult(j,q,B){if(j===void 0||j===null)return;if(W(j))return j;if(!V(j))return j;if(q.protocol===C.SOCKETIO||q.framework===z.SOCKETIO){Q(G(q),X()).dispatch(j);return}if(q.protocol===C.WEBSOCKET||q.framework===z.WEBSOCKET){N(G(q)).dispatch(j);return}const H=q.framework??T(),A=B;switch(H){case z.EXPRESS:if(A&&!A.headersSent)J(B).dispatch(j);return;case z.NODE:if(A&&!A.headersSent)K(B).dispatch(j);return;case z.FETCH:return L.dispatch(j);case z.ELYSIA:default:return M(q.ctx?.set??{}).dispatch(j)}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getRuntimeTmpConfigs as q}from"../../../utils/helpers/tmp/runtime-tmp
|
|
1
|
+
import{getRuntimeTmpConfigs as q}from"../../../utils/helpers/tmp/runtime-tmp";import{FrameworkEnum as j}from"../../../utils/models";const x=new Set(Object.values(j));export function parseFramework(b){const c=b?String(b).toLowerCase():void 0;return c&&x.has(c)?c:j.ELYSIA}export function getFramework(b){if(b)return b;try{return parseFramework(q()?.service?.framework)}catch{return j.ELYSIA}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{FrameworkEnum as G,ProtocolEnum as K}from"../../../utils/models
|
|
1
|
+
import{FrameworkEnum as G,ProtocolEnum as K}from"../../../utils/models";import{detectSocketProtocol as L}from"../../../utils/helpers/protocol";import{getFramework as M}from"../../../utils/helpers/framework";import{runAction as I}from"../../../utils/helpers/handlers/execute";export function toRealtimeHandler(z,D){const B=(b)=>{const J=L(b,D);return I({socket:b,ctx:{ws:b},protocol:J},z)},j=(b)=>B(b);j.with=(b)=>()=>B(b);return j}export const toHandler=(z,D)=>{const B=D??M();switch(B){case G.ELYSIA:return(j)=>I({framework:B,ctx:j},z);case G.FETCH:return(j,b)=>I({framework:B,ctx:{request:j,...b}},z);case G.NODE:return(j,b)=>I({framework:B,req:j,res:b},z,b);case G.EXPRESS:return(j,b,J)=>{I({framework:B,req:j,res:b,metadata:{locals:b.locals||{}}},z,b).catch(J)};case G.WEBSOCKET:case G.SOCKETIO:throw Error('[xrystal] realtime: ctr({ ... }, { protocol: "ws" | "socketio" })');default:return(j)=>I({framework:G.ELYSIA,ctx:j},z)}},toWebSocket=(z,D)=>toRealtimeHandler(D,K.WEBSOCKET)(z),toSocketIo=(z,D)=>toRealtimeHandler(D,K.SOCKETIO)(z);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{randomUUID as Q}from"node:crypto";import{FrameworkEnum as V,ProtocolEnum as X}from"../../../utils/models
|
|
1
|
+
import{randomUUID as Q}from"node:crypto";import{FrameworkEnum as V,ProtocolEnum as X}from"../../../utils/models";import{runControllerStore as Y}from"../../../utils/helpers/context";import{runWithRequestId as Z}from"../../../utils/helpers/context";import{dispatchResult as _}from"../../../utils/helpers/dispatch";import{getFramework as $}from"../../../utils/helpers/framework";import{attachSocketTransport as x,isRealtimeProtocol as H}from"../../../utils/helpers/protocol";import{getDtoRuntime as J}from"../../../utils/helpers/runtime";export const runController=Y;const B=(b)=>({framework:b.framework??(H(b.protocol)?void 0:$()),protocol:b.protocol??X.HTTP,...b,metadata:{locals:{},...b.metadata}}),M=(b,z)=>{if(!b)return;if(b instanceof Headers)return b.get(z)??b.get(z.toLowerCase());if(typeof b.get==="function"){const j=b.get;return j(z)??j(z.toLowerCase())}const A=b;return A[z]??A[z.toLowerCase()]},K=(b)=>{const z=b.ctx??{},A=b.req??{},j=A.headers??z.request?.headers;return b.requestId??z.requestId??A.ctx?.requestId??M(j,"x-request-id")??M(j,"x-correlation-id")??""},T=(b)=>{const z=String(K(b)||Q());b.requestId=z;b.ctx={...b.ctx,requestId:z};if(b.req)b.req.ctx={...b.req.ctx,requestId:z};return z},W=(b)=>{if(b.framework!==V.FETCH||b.ctx?.builder)return;const z=b.ctx?.request??b.req;if(!(z instanceof Request))return;b.ctx={...b.ctx,...J().forRequest(z)};if(b.ctx.requestId)b.requestId=String(b.ctx.requestId)},v=async(b,z,A)=>{const j=_(b,z,A),G=A;if(j instanceof Response&&G?.send){G.status?.(j.status);j.headers.forEach((N,O)=>G.setHeader?.(O,N));const L=j.headers.get("content-type")||"";if(L.includes("json")||L.includes("text/"))return G.send(await j.text());return G.send(Buffer.from(await j.arrayBuffer()))}return j},y=(b)=>H(b.protocol)?"ws":"http";export async function runAction(b,z,A){const j=B(b);if(H(j.protocol)&&j.socket&&!j.socket.builder)x(j.socket,j.protocol,J());W(j);const G=T(j);return Z(G,()=>runController(j,async()=>v(await z(),j,A)),y(j))}export function configureDto(b,z){return J().configure(b,z)}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{FrameworkEnum as A}from"../../../utils/models
|
|
1
|
+
import{FrameworkEnum as A}from"../../../utils/models";import{createDtoMiddleware as q}from"../../../utils/helpers/middleware";import{attachSocketTransport as B,detectSocketProtocol as C,resolveRealtimeMiddlewareProtocol as D}from"../../../utils/helpers/protocol";import{getDtoRuntime as j}from"../../../utils/helpers/runtime";export{runAction,runController,configureDto}from"../../../utils/helpers/handlers/execute";export{toHandler,toRealtimeHandler,toWebSocket,toSocketIo}from"../../../utils/helpers/handlers/adapters";export{getFramework}from"../../../utils/helpers/framework";export{dispatchResult}from"../../../utils/helpers/dispatch";export{getRequestId,getRunContext,runWithContext,runWithRequestId,runWithTrace}from"../../../utils/helpers/context";export{G,propsFromTmp,resolveGStoreBoot,G_PROP_NOT_ALLOWED,G_REQUEST_KEY_WARN,looksLikeRequestScopedKey,GStoreScopeEnum}from"../../../utils/helpers/state";export{bindLoaderTmpSync,getRuntimeTmpConfigs,setRuntimeTmpConfigs,onRuntimeTmpChange,notifyRuntimeTmpChange,getTmpSnapshot,onTmpReload}from"../../../utils/helpers/tmp";export{normalizeFrameworkKind,createDtoMiddleware,resolveDtoAdapter}from"../../../utils/helpers/middleware";export{resolveCtrOptions}from"../../../utils/helpers/protocol/options";export{parseProtocol,getConfiguredProtocols,getConfiguredRealtimeProtocols,defaultRealtimeProtocolFromConfig,getDefaultRealtimeProtocol,resolveRealtimeMiddlewareProtocol,detectSocketProtocol,isRealtimeProtocol,isHttpProtocol,resolveProtocolsFromConfig,REALTIME_MIDDLEWARE_HINT}from"../../../utils/helpers/protocol";export{getDtoRuntime}from"../../../utils/helpers/runtime";export const dtoMiddleware=(b)=>q(j(),b);export function realtimeMiddleware(b){const z=D(b);return(u,y)=>{try{const h=C(u,z);B(u,h,j());y?.()}catch(h){y?.(h instanceof Error?h:Error(String(h)))}}}export const websocketMiddleware=(b)=>b?q(j(),b):realtimeMiddleware("ws"),socketIoMiddleware=(b)=>b?q(j(),b??A.SOCKETIO):realtimeMiddleware("socketio");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export{default as pic}from"picocolors";export*from"../../utils/helpers/core
|
|
1
|
+
export{default as pic}from"picocolors";export*from"../../utils/helpers/core";export*from"../../utils/helpers/path";export*from"../../utils/helpers/is";export*from"../../utils/helpers/id";export*from"../../utils/helpers/validates";export*from"../../utils/helpers/ip";export*from"../../utils/helpers/hash/crypto";export*from"../../utils/helpers/string";export*from"../../utils/helpers/objects";export*from"../../utils/helpers/locales";export*from"../../utils/helpers/timer";export*from"../../utils/helpers/date";export*from"../../utils/helpers/math";export*from"../../utils/helpers/regex/checkSpecialRegexControl";export*from"../../utils/helpers/filters";export*from"../../utils/helpers/framework";export*from"../../utils/helpers/protocol";export*from"../../utils/helpers/dto";export*from"../../utils/helpers/dispatch";export*from"../../utils/helpers/middleware";export*from"../../utils/helpers/context";export*from"../../utils/helpers/tmp";export*from"../../utils/helpers/state";export*from"../../utils/helpers/handlers";export*from"../../utils/helpers/runtime";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{FrameworkEnum as j}from"../../../utils/models
|
|
1
|
+
import{FrameworkEnum as j}from"../../../utils/models";import{getFramework as x,parseFramework as C}from"../../../utils/helpers/framework";const G={express:j.EXPRESS,elysia:j.ELYSIA,node:j.NODE,fetch:j.FETCH,websocket:j.WEBSOCKET,ws:j.WEBSOCKET,socketio:j.SOCKETIO};export function normalizeFrameworkKind(b){if(b===void 0)return x();const q=typeof b==="object"&&b!==null&&"framework"in b?b.framework:b;if(!q)return x();const B=String(q).toLowerCase().replace(/[-_\s]/g,"");return G[B]??C(q)}export function resolveDtoAdapter(b,q){switch(q){case j.ELYSIA:return b.elysia();case j.NODE:return b.node();case j.SOCKETIO:return b.socketIo();case j.WEBSOCKET:return b.websocket();case j.FETCH:return null;case j.EXPRESS:return b.express();default:return b.elysia()}}export function createDtoMiddleware(b,q){return resolveDtoAdapter(b,normalizeFrameworkKind(q))}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ProtocolEnum as h}from"../../../utils/models/enums
|
|
1
|
+
import{ProtocolEnum as h}from"../../../utils/models/enums";import{getRuntimeTmpConfigs as J}from"../../../utils/helpers/tmp/runtime-tmp";const G={http:h.HTTP,https:h.HTTPS,ws:h.WEBSOCKET,websocket:h.WEBSOCKET,socketio:h.SOCKETIO,socket:h.SOCKETIO},REALTIME_MIDDLEWARE_HINT='[xrystal] tmp.yml lists both ws and socketio — use realtimeMiddleware("ws") or realtimeMiddleware("socketio")';export function parseProtocol(b){if(!b)return h.HTTP;const j=String(b).toLowerCase().replace(/[-_\s.]/g,"");if(G[j])return G[j];return Object.values(h).includes(String(b))?b:h.HTTP}export function isRealtimeProtocol(b){return b===h.WEBSOCKET||b===h.SOCKETIO}export function isHttpProtocol(b){return!b||b===h.HTTP||b===h.HTTPS}function B(){return J()?.service}export function resolveProtocolsFromConfig(b){const j=b?.protocols;if(!j)return[h.HTTP];return(Array.isArray(j)?j:[j]).map(parseProtocol)}export function getConfiguredProtocols(){try{return resolveProtocolsFromConfig(B())}catch{return[h.HTTP,h.WEBSOCKET]}}export function getConfiguredRealtimeProtocols(b){return resolveProtocolsFromConfig(b).filter(isRealtimeProtocol)}export function defaultRealtimeProtocolFromConfig(b){const j=getConfiguredRealtimeProtocols(b);if(j.length===1)return j[0];if(j.length>1)return;return h.WEBSOCKET}export function getDefaultRealtimeProtocol(){try{return defaultRealtimeProtocolFromConfig(B())}catch{return h.WEBSOCKET}}export function resolveRealtimeMiddlewareProtocol(b,j){if(b!==void 0&&b!==null&&b!=="")return parseProtocol(b);let q=j;if(!q)try{q=B()}catch{return h.WEBSOCKET}const z=getConfiguredRealtimeProtocols(q);if(z.length===1)return z[0];if(z.length>1)throw Error(REALTIME_MIDDLEWARE_HINT);return h.WEBSOCKET}export function detectSocketProtocol(b,j){if(j)return j;const q=b;if(q?.__xrystalProtocol)return q.__xrystalProtocol;return h.WEBSOCKET}export function attachSocketTransport(b,j,q){const z=b;if(j===h.SOCKETIO)q.attachSocketIo(b);else q.attachWebSocket(b);z.__xrystalProtocol=j}export{REALTIME_MIDDLEWARE_HINT};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{FrameworkEnum as e,ProtocolEnum as o}from"../../../utils/models
|
|
1
|
+
import{FrameworkEnum as e,ProtocolEnum as o}from"../../../utils/models";import{parseProtocol as t}from"../../../utils/helpers/protocol";export function resolveCtrOptions(r){if(r===void 0)return{protocol:o.HTTP};if(typeof r==="string"){if(Object.values(e).includes(r))return{framework:r,protocol:o.HTTP};return{protocol:t(r)}}return{protocol:o.HTTP,...r}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{x as t}from"../../../utils/models
|
|
1
|
+
import{x as t}from"../../../utils/models";export const DTO_RUNTIME_KEY="dtoRuntime";export function getDtoRuntime(){return t.get(DTO_RUNTIME_KEY)}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export{getDtoRuntime,DTO_RUNTIME_KEY}from"../../../utils/helpers/runtime/dto-access
|
|
1
|
+
export{getDtoRuntime,DTO_RUNTIME_KEY}from"../../../utils/helpers/runtime/dto-access";export{gracefulShutdown,isShuttingDown,registerGracefulShutdown}from"../../../utils/helpers/runtime/shutdown";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{stopTmpLoader as y}from"../../../utils/helpers/tmp/tmp-loader
|
|
1
|
+
import{stopTmpLoader as y}from"../../../utils/helpers/tmp/tmp-loader";import{clearRuntimeTmpConfigs as z}from"../../../utils/helpers/tmp/runtime-tmp";import A from"../../../utils/models/classes/class.x";let k=!1,q=!1;export function isShuttingDown(){return k}export async function gracefulShutdown(b=0){if(k){process.exit(b);return}k=!0;try{await A.shutdown()}catch{}y();z();await new Promise((j)=>setImmediate(j));process.exit(b)}export function registerGracefulShutdown(){if(q)return;q=!0;const b=(j)=>{gracefulShutdown(j==="SIGINT"?130:j==="SIGTERM"?143:0)};process.on("SIGINT",b);process.on("SIGTERM",b)}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createStore as w}from"zustand/vanilla";import{subscribeWithSelector as I}from"zustand/middleware";import{GStoreScopeEnum as Z}from"../../../utils/models/enums
|
|
1
|
+
import{createStore as w}from"zustand/vanilla";import{subscribeWithSelector as I}from"zustand/middleware";import{GStoreScopeEnum as Z}from"../../../utils/models/enums";import{propsFromTmp,resolveGStoreBoot,G_PROP_NOT_ALLOWED}from"../../../utils/helpers/state/props-from-tmp";import{warnIfRequestScopedKey as Q,G_REQUEST_KEY_WARN,looksLikeRequestScopedKey}from"../../../utils/helpers/state/request-key-guard";import{buildStoresSnapshot as U,patchControllerScope as Y,patchRunScope as q}from"../../../utils/helpers/state/scopes";export{propsFromTmp,resolveGStoreBoot,G_PROP_NOT_ALLOWED,G_REQUEST_KEY_WARN,looksLikeRequestScopedKey};export{GStoreScopeEnum}from"../../../utils/models/enums";export{buildStoresSnapshot,summarizeController,runContextValues,patchControllerScope,patchRunScope}from"../../../utils/helpers/state/scopes";const V=(j)=>JSON.parse(JSON.stringify(j));function $(j,z){const H=new Set([...Object.keys(j),...Object.keys(z)]),M=[];for(const J of H)if(j[J]!==z[J])M.push({key:J,value:z[J],prev:j[J]});return M}class GStoreFacade{store;baseline={};allowedKeys=new Set;allowAutoCreateProps=!0;warnOnRequestKeys=!0;constructor(){this.store=w(I(()=>({})))}configureFromTmp(j={}){const z=resolveGStoreBoot(j);this.allowAutoCreateProps=z.allowAutoCreateProps;this.warnOnRequestKeys=z.warnOnRequestKeys;this.allowedKeys=new Set(Object.keys(z.vars));const H=V(z.bootstrap?z.vars:{});this.store.setState(H,!0);this.baseline=V(H);return this}allowsAutoCreateProps(){return this.allowAutoCreateProps}declaredKeys(){return[...this.allowedKeys]}guardRequestKey(j){Q(j,this.warnOnRequestKeys)}assertPropAllowed(j){if(this.allowAutoCreateProps)return;if(!this.allowedKeys.has(j))throw Error(`${G_PROP_NOT_ALLOWED}: ${j}`)}registerAllowedKeys(j){for(const z of j)this.allowedKeys.add(z)}getState(){return this.store.getState()}select(j){return j(this.getState())}get(j,z){const H=this.getState();if(!(j in H))return z;return H[j]}set(j,z){this.guardRequestKey(j);this.assertPropAllowed(j);const H=this.getState();if(H[j]===z)return this;this.store.setState({...H,[j]:z});return this}merge(j){for(const M of Object.keys(j)){this.guardRequestKey(M);this.assertPropAllowed(M)}const z=this.getState();if(!$(z,{...z,...j}).length)return this;this.store.setState({...z,...j});return this}has(j){return j in this.getState()}remove(...j){const H={...this.getState()};let M=!1;for(const J of j)if(J in H){delete H[J];M=!0}if(M)this.store.setState(H,!0);return this}keys(){return Object.keys(this.getState())}entries(){return Object.entries(this.getState())}snapshot(){return{...this.getState()}}subscribe(j){return this.store.subscribe((z,H)=>j(z,H,$(H,z)))}subscribeKey(j,z){return this.store.subscribe((H)=>H[j],(H,M)=>z(H,M,{key:j,value:H,prev:M}))}bootstrap(j){if(!this.allowAutoCreateProps)for(const z of Object.keys(j))this.assertPropAllowed(z);else this.registerAllowedKeys(Object.keys(j));this.merge(j);this.baseline=V(this.getState());return this}reset(){this.store.setState(V(this.baseline),!0)}stores(){return U(this.snapshot())}list(){return Object.values(this.stores())}scope(j){const H=this.stores()[j],M={name:j,active:H.active,keys:()=>H.keys,get(J,X){if(!H.values||!(J in H.values))return X;return H.values[J]}};if(j===Z.GLOBAL)return{...M,set:(J,X)=>{this.set(J,X);return!0},merge:(J)=>{this.merge(J);return!0}};if(j===Z.RUN)return{...M,patch:(J)=>q(J)};return{...M,patch:(J)=>Y(J)}}}export{GStoreFacade};export const G=new GStoreFacade;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readTmpServiceBlock as I}from"../../../utils/helpers/tmp/tmp-schema
|
|
1
|
+
import{readTmpServiceBlock as I}from"../../../utils/helpers/tmp/tmp-schema";export const G_PROP_NOT_ALLOWED="[xrystal] G prop not declared in tmp.yml vars — set autoCreateProps: true to allow runtime keys";const F=()=>({});function J(j){return I(j).loaders?.system?.gStore}function L(j){if(typeof j.bootstrap==="boolean")return j.bootstrap;return!0}function M(j){if(typeof j.autoCreateProps==="boolean")return j.autoCreateProps;return!0}function Q(j){if(typeof j.warnOnRequestKeys==="boolean")return j.warnOnRequestKeys;return!0}export function resolveGStoreBoot(j={}){const x=j.configs??j,z=J(x);if(!z)return{bootstrap:!0,allowAutoCreateProps:!0,warnOnRequestKeys:!0,vars:F()};const E=z.options??{},D=z.vars,H=D&&typeof D==="object"&&!Array.isArray(D)?{...D}:F();return{bootstrap:L(E),allowAutoCreateProps:M(E),warnOnRequestKeys:Q(E),vars:H}}export function propsFromTmp(j={}){const x=resolveGStoreBoot(j);return x.bootstrap?x.vars:F()}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getRunContext as B}from"../../../utils/helpers/context
|
|
1
|
+
import{getRunContext as B}from"../../../utils/helpers/context";import{getControllerCtx as D}from"../../../utils/helpers/context/controller-store";export const G_REQUEST_KEY_WARN="[xrystal] G: key looks request-scoped — use run/controller context, not global G";const F=new Set(["requestid","reqid","correlationid","cookies","cookie","headers","header","body","query","queries","params","locals","session","sessionid"]);export function looksLikeRequestScopedKey(j){const z=j.trim();if(!z)return!1;const f=z.toLowerCase();if(F.has(f))return!0;if(f.endsWith("requestid")||f.endsWith("correlationid"))return!0;if(f==="req"||f==="res")return!0;return!1}export function warnIfRequestScopedKey(j,z){if(!z||!looksLikeRequestScopedKey(j))return;const f=B()?"run":D()?"controller":"outside-request";console.warn(`${G_REQUEST_KEY_WARN} (key: ${j}, scope: ${f})`)}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{GStoreScopeEnum as j}from"../../../utils/models/enums
|
|
1
|
+
import{GStoreScopeEnum as j}from"../../../utils/models/enums";import{getRunContext as q,patchRunContext as w}from"../../../utils/helpers/context";import{getControllerCtx as v}from"../../../utils/helpers/context/controller-store";export function summarizeController(d){if(!d)return null;return{protocol:d.protocol,framework:d.framework,requestId:d.requestId,metadata:d.metadata,hasReq:!!d.req,hasRes:!!d.res,hasSocket:!!d.socket}}export function runContextValues(d){if(!d)return null;return{...d}}export function buildStoresSnapshot(d){const f=q(),k=summarizeController(v());return{[j.GLOBAL]:{name:j.GLOBAL,active:!0,keys:Object.keys(d),values:{...d}},[j.RUN]:{name:j.RUN,active:!!f,keys:f?Object.keys(f):[],values:runContextValues(f)},[j.CONTROLLER]:{name:j.CONTROLLER,active:!!k,keys:k?Object.keys(k):[],values:k}}}export function patchControllerScope(d){const f=v();if(!f)return!1;if(d.requestId!==void 0)f.requestId=d.requestId;if(d.metadata)f.metadata={...f.metadata,...d.metadata,locals:{...f.metadata?.locals??{},...d.metadata.locals??{}}};return!0}export function patchRunScope(d){if(!q())return!1;w(d);return!0}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export{setRuntimeTmpConfigs,getRuntimeTmpConfigs,onRuntimeTmpChange,notifyRuntimeTmpChange,clearRuntimeTmpConfigs}from"../../../utils/helpers/tmp/runtime-tmp
|
|
1
|
+
export{setRuntimeTmpConfigs,getRuntimeTmpConfigs,onRuntimeTmpChange,notifyRuntimeTmpChange,clearRuntimeTmpConfigs}from"../../../utils/helpers/tmp/runtime-tmp";export{getTmpLoader,getTmpLoaderPath,getTmpSnapshot,onTmpReload,resetTmpLoaderForTests,stopTmpLoader}from"../../../utils/helpers/tmp/tmp-loader";export{bindLoaderTmpSync}from"../../../utils/helpers/tmp/loader-tmp-sync";export{resolveTmpWatchIntervalMs}from"../../../utils/helpers/tmp/tmp-watch";export{normalizeTmpDocument,normalizeRootFolder,normalizeSourceFolder,readTmpCoreBlock,readTmpServiceBlock,resolveServiceLayoutPaths,resolveTmpRuntimeConfigs}from"../../../utils/helpers/tmp/tmp-schema";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{onRuntimeTmpChange as k}from"../../../utils/helpers/tmp/runtime-tmp
|
|
1
|
+
import{onRuntimeTmpChange as k}from"../../../utils/helpers/tmp/runtime-tmp";export function bindLoaderTmpSync(c){const f=c.constructor.name;k(async()=>{try{await c.syncFromTmp()}catch(b){const j=b instanceof Error?b.message:String(b);console.warn(`[xrystal] ${f} tmp reload failed: ${j}`)}})}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import J from"node:fs";import K from"node:path";import{Constants as E}from"../../../utils/constants
|
|
1
|
+
import J from"node:fs";import K from"node:path";import{Constants as E}from"../../../utils/constants";import{assertCoreTmpGuard as M,coreCanonicalTmpPath as O,isCorePackageRoot as Q}from"../../../utils/helpers/core/tmp-layout";import{findFileRecursively as U}from"../../../utils/helpers/core/paths";import{TmpFileLoader as V}from"../../../utils/models/classes/class.tmp-file-loader";import{registerGracefulShutdown as W}from"../../../utils/helpers/runtime/shutdown";let q=null,A=null;function X(B=process.cwd(),j=E.tmpBaseName,b=E.tmpExtension){const z=K.resolve(B);if(Q(z)){const D=O(z);if(!J.existsSync(D))throw Error(`${E.packageRootFolder}/tmp.yml not found. Run xcore tmp or ensureCoreTmpEntry() before starting @xrystal/core`);M(z,D);return D}const H=U(z,j,b);if(!H)throw Error(`${j}${b.startsWith(".")?b:`.${b}`} file not found`);return H}export function getTmpLoaderPath(){if(!A)A=X();return A}export function getTmpLoader(){if(!q){q=new V({filePath:getTmpLoaderPath()});W()}return q}export function getTmpSnapshot(){return getTmpLoader().getResolvedTmpFile()}export function onTmpReload(B){const j=getTmpLoader(),b=()=>B(j.getResolvedTmpFile());j.on("reload",b);return()=>j.off("reload",b)}export function stopTmpLoader(){if(q){q.stop();q=null;A=null}}export function resetTmpLoaderForTests(){stopTmpLoader()}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Constants as G}from"../../../utils/constants
|
|
1
|
+
import{Constants as G}from"../../../utils/constants";function A(j){return typeof j==="object"&&j!==null&&!Array.isArray(j)}function M(j){if(typeof j==="number"||typeof j==="string")return j;return}export function normalizeRootFolder(j){if(!j?.trim())return G.packageRootFolder;return j.trim().replace(/^\.\/+/,"")}export function normalizeSourceFolder(j){if(!j?.trim())return G.mainSourceFolder;const q=j.trim();if(q.startsWith("./")||q.startsWith("../"))return q;return`./${q}`}export function readTmpCoreBlock(j){const q=A(j?.core)?j.core:{},x=A(q.tmp)?q.tmp:{};return{tmp:{fileWatchIntervalMs:M(x.fileWatchIntervalMs)}}}export function readTmpServiceBlock(j){const q=A(j?.service)?j.service:{},x=A(q.paths)?q.paths:{},D=A(x.special)?x.special:{};let E=A(q.loaders)?{...q.loaders}:void 0,H=A(q.build)?q.build:void 0;if(E&&A(E.build)){const{build:J,...K}=E;E=K;if(!H&&A(J))H=J}return{name:typeof q.name==="string"?q.name:void 0,framework:typeof q.framework==="string"?q.framework:void 0,paths:{root:typeof x.root==="string"?x.root:void 0,source:typeof x.source==="string"?x.source:void 0,special:{tests:typeof D.tests==="string"?D.tests:void 0,environments:typeof D.environments==="string"?D.environments:void 0,dist:typeof D.dist==="string"?D.dist:void 0}},protocols:q.protocols,loaders:E,build:H}}export function resolveServiceLayoutPaths(j){const q=j.paths?.special??{};return{tests:q.tests?.trim()||G.layoutPaths.tests,environments:q.environments?.trim()||G.layoutPaths.environments,dist:q.dist?.trim()||G.layoutPaths.dist}}function O(j){const q=resolveServiceLayoutPaths(j);return{name:j.name,framework:j.framework??"elysia",paths:{root:j.paths?.root??G.packageRootFolder,source:j.paths?.source??G.mainSourceFolder,special:q},protocols:j.protocols,loaders:j.loaders,build:j.build}}function Q(j){return{tmp:{fileWatchIntervalMs:j.tmp?.fileWatchIntervalMs}}}export function resolveTmpRuntimeConfigs(j){const q=A(j?.configs)?j.configs:{},x=readTmpServiceBlock(q),D=readTmpCoreBlock(q),E=O(x);return{service:E,core:Q(D),rootFolderPath:normalizeRootFolder(E.paths.root)}}export function normalizeTmpDocument(j){return{...j,configs:resolveTmpRuntimeConfigs(j)}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import I from"../../../utils/constants/defaults.json" with { type: 'json' };import{readTmpCoreBlock as J}from"../../../utils/helpers/tmp/tmp-schema
|
|
1
|
+
import I from"../../../utils/constants/defaults.json" with { type: 'json' };import{readTmpCoreBlock as J}from"../../../utils/helpers/tmp/tmp-schema";const b=I.tmpWatchDefaults??{intervalMs:500,minIntervalMs:100,maxIntervalMs:1e4};export function resolveTmpWatchIntervalMs(q){const v=q?.configs,y=J(v).tmp?.fileWatchIntervalMs??b.intervalMs,j=Number(y);if(!Number.isFinite(j))return b.intervalMs;const z=b.minIntervalMs??100,G=b.maxIntervalMs??1e4;return Math.min(G,Math.max(z,Math.round(j)))}
|
package/x/dist/utils/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export*from"../utils/constants
|
|
1
|
+
export*from"../utils/constants";export*from"../utils/helpers";export*from"../utils/models";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHash as k,createHmac as E}from"node:crypto";import{Configs as y,Logger as N}from"../../../loader
|
|
1
|
+
import{createHash as k,createHmac as E}from"node:crypto";import{Configs as y,Logger as N}from"../../../loader";import{LoggerLayerEnum as x,x as b}from"../../../utils";import{getRequestId as D}from"../../../utils/helpers/context";export class ClientStore{static _store={};static get(t){return this._store[t]||{}}static set(t,e){this._store[t]={...this._store[t],...e}}}export class Client{logger=b.get(N);configs=b.get(y);clientName;baseURL;version=null;timeout=15000;debug;authConfigs;breaker={failures:0,lastFailure:0,state:"CLOSED",threshold:5,cooldown:30000};constructor({clientName:t,baseURL:e,version:r,timeout:i,auth:s,debug:n}){this.clientName=t;this.baseURL=e;this.version=r||null;this.authConfigs=s;this.timeout=i||15000;const c=Number(this.configs.all.debug)>=x.DEBUG;this.debug=n??c;if(s?.token)ClientStore.set(t,{accessToken:s.token})}resolvePath(t,e){return e.split(".").reduce((r,i)=>r?r[i]:void 0,t)}static cryptoHashGenerate=({algorithm:t,input:e,digest:r="hex"})=>{return k(t).update(e).digest(r)}}export class BaseApiClient extends Client{constructor(t){super(t)}async request(t,e={}){if(this.breaker.state==="OPEN")if(Date.now()-this.breaker.lastFailure>this.breaker.cooldown)this.breaker.state="HALF_OPEN";else throw Error(`[CircuitBreaker] ${this.clientName} is OPEN`);const r=e.retries??3;let i=0;while(i<r)try{const s=await this._execute(t,{...e});if(s.ok||s.status===401){this.breaker.failures=0;this.breaker.state="CLOSED";return s}if([502,503,504].includes(s.status))throw Error(`Server Error: ${s.status}`);return s}catch(s){i++;this.breaker.failures++;this.breaker.lastFailure=Date.now();if(this.breaker.failures>=this.breaker.threshold)this.breaker.state="OPEN";if(i>=r)throw s;const n=Math.pow(2,i)*500;await new Promise((c)=>setTimeout(c,n))}throw Error(`${this.clientName} failed after ${r} attempts`)}async _execute(t,e){const r=this.baseURL.replace(/\/$/,""),i=e.version!==void 0?e.version:this.version,s=i?`/${i.replace(/^\//,"")}`:"",n=`${r}${s}${t}`,c=D(),l=new Headers(e.headers||{}),u=e.body instanceof URLSearchParams,d=e.body instanceof FormData;if(!u&&!d)l.set("Content-Type","application/json");if(c)l.set("x-correlation-id",c);const f=this.configs.all.internalSecret||process.env.INTERNAL_SECRET;if(f){const a=Date.now().toString(),w=E("sha256",f).update(a+this.clientName).digest("hex");l.set("x-internal-signature",w);l.set("x-internal-timestamp",a);l.set("x-internal-client",this.clientName)}const p=e.debug??this.debug,{version:L,retries:$,debug:v,...h}=e;let o=h.body;if(o&&typeof o==="object"&&!u&&!d)o=JSON.stringify(o);if(p){const a={method:h.method||"GET",url:n,body:o&&typeof o==="string"?JSON.parse(o):o};console.log(`[DEBUG] ${this.clientName}`,a);this.logger.winston.info(`${this.clientName} Request`,a)}const m=new AbortController,g=setTimeout(()=>m.abort(),this.timeout);try{const a=await fetch(n,{...h,body:o,headers:l,signal:m.signal});clearTimeout(g);return a}catch(a){clearTimeout(g);throw a}}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{EventEmitter as L}from"node:events";import{readFileSync as N,unwatchFile as G,watchFile as Q}from"node:fs";import{resolve as R}from"node:path";import{parse as U}from"yaml";import{resolveObjWithHandlebars as V}from"../../../utils/helpers
|
|
1
|
+
import{EventEmitter as L}from"node:events";import{readFileSync as N,unwatchFile as G,watchFile as Q}from"node:fs";import{resolve as R}from"node:path";import{parse as U}from"yaml";import{resolveObjWithHandlebars as V}from"../../../utils/helpers";import{normalizeTmpDocument as X}from"../../../utils/helpers/tmp/tmp-schema";import{resolveTmpWatchIntervalMs as A}from"../../../utils/helpers/tmp/tmp-watch";export class TmpFileLoader extends L{#k={};#q;#B=A(null);#A=!1;constructor({filePath:k}){super();this.#q=R(k);this.#G();this.#K()}#G(){try{const k=N(this.#q,"utf8"),q=U(k),B=A(q),K=this.#A&&B!==this.#B;this.#k=q;this.#B=B;this.emit("reload",this.#k);if(K)this.#K()}catch(k){console.error(`[TmpFileLoader] Error: ${k}`)}}#K(){if(this.#A)G(this.#q);this.#B=A(this.#k);Q(this.#q,{interval:this.#B},(k,q)=>{if(k.mtimeMs!==q.mtimeMs)this.#G()});this.#A=!0}stop(){if(this.#A){G(this.#q);this.#A=!1}this.removeAllListeners()}getResolvedTmpFile(){const k=Object.keys(this.#k).length>0?this.#k:(this.#G(),this.#k);return X(V(k,k))}}
|