@xrystal/core 3.32.1 → 3.37.4
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 +676 -136
- package/package.json +27 -24
- package/tsconfig.base.json +15 -0
- package/x/bin/commands/create.mjs +34 -5
- package/x/bin/commands/doctor.mjs +115 -25
- package/x/bin/commands/hooks.mjs +55 -0
- package/x/bin/commands/project.mjs +75 -42
- package/x/bin/commands/release.mjs +8 -3
- package/x/bin/commands/sync-toolchain.mjs +43 -0
- package/x/bin/commands/tmp.mjs +13 -4
- package/x/bin/helpers/.generated/.generated-from +1 -0
- package/x/bin/helpers/.generated/tmp-schema.mjs +192 -0
- package/x/bin/helpers/banner.mjs +66 -12
- package/x/bin/helpers/build-config.mjs +342 -0
- package/x/bin/helpers/cli-help.mjs +164 -0
- package/x/bin/helpers/create-target.mjs +18 -2
- package/x/bin/helpers/project-artifacts.mjs +142 -0
- package/x/bin/helpers/runtime-info.mjs +172 -0
- package/x/bin/helpers/tmp-config.mjs +11 -10
- package/x/bin/helpers/tmp-layout.mjs +10 -16
- package/x/bin/helpers/tmp-schema.mjs +9 -0
- package/x/bin/helpers/toolchain-config.mjs +233 -0
- package/x/bin/main-cli.js +31 -3
- package/x/bin/scripts/clean-source-types.mjs +19 -0
- package/x/bin/scripts/fix-dist-imports.mjs +80 -0
- package/x/bin/scripts/install-git-hooks.mjs +86 -0
- package/x/bin/scripts/minify-dist.mjs +50 -0
- package/x/bin/scripts/prepare-npm-publish.mjs +39 -0
- package/x/bin/scripts/publish-guard.mjs +113 -0
- package/x/bin/scripts/verify-npm-pack.mjs +12 -0
- package/x/bin/scripts/verify-publish-config.mjs +10 -0
- package/x/bin/scripts/verify-version-bump.mjs +27 -0
- package/x/bin/scripts/version-check.mjs +173 -0
- package/x/dist/index.js +1 -0
- package/x/dist/loader/clients/index.js +1 -0
- package/x/dist/loader/configs/index.js +1 -0
- package/{source → x/dist}/loader/controller/index.d.ts +20 -17
- package/x/dist/loader/controller/index.js +1 -0
- package/x/dist/loader/dto/index.js +1 -0
- package/x/dist/loader/events/index.js +1 -0
- package/x/dist/loader/index.d.ts +11 -0
- package/x/dist/loader/index.js +1 -0
- package/{source → x/dist}/loader/kafka/index.d.ts +1 -0
- package/x/dist/loader/kafka/index.js +1 -0
- package/x/dist/loader/localizations/index.js +1 -0
- package/{source → x/dist}/loader/logger/index.d.ts +1 -0
- package/x/dist/loader/logger/index.js +2 -0
- package/x/dist/loader/service/index.js +1 -0
- package/x/dist/loader/system/index.js +1 -0
- package/x/dist/project/index.d.ts +12 -0
- package/x/dist/project/index.js +1 -0
- package/x/dist/utils/constants/defaults.json +44 -0
- package/x/dist/utils/constants/index.js +1 -0
- package/x/dist/utils/helpers/configs/index.js +1 -0
- package/x/dist/utils/helpers/context/controller-store.js +1 -0
- package/x/dist/utils/helpers/context/index.js +1 -0
- package/{source → x/dist}/utils/helpers/core/index.d.ts +1 -1
- package/x/dist/utils/helpers/core/index.js +1 -0
- package/x/dist/utils/helpers/core/paths.js +1 -0
- package/x/dist/utils/helpers/core/tmp-layout.js +1 -0
- package/x/dist/utils/helpers/date/index.js +1 -0
- package/x/dist/utils/helpers/dispatch/index.js +1 -0
- package/x/dist/utils/helpers/dto/index.js +1 -0
- package/x/dist/utils/helpers/filters/index.js +1 -0
- package/x/dist/utils/helpers/framework/index.js +1 -0
- package/x/dist/utils/helpers/handlers/adapters.js +1 -0
- package/x/dist/utils/helpers/handlers/execute.js +1 -0
- package/x/dist/utils/helpers/handlers/index.js +1 -0
- package/x/dist/utils/helpers/hash/crypto.js +1 -0
- package/x/dist/utils/helpers/id/index.js +1 -0
- package/x/dist/utils/helpers/index.js +1 -0
- package/x/dist/utils/helpers/ip/index.js +1 -0
- package/x/dist/utils/helpers/is/index.js +1 -0
- package/x/dist/utils/helpers/locales/index.js +1 -0
- package/x/dist/utils/helpers/math/index.js +1 -0
- package/{source → x/dist}/utils/helpers/middleware/index.d.ts +2 -2
- package/x/dist/utils/helpers/middleware/index.js +1 -0
- package/x/dist/utils/helpers/objects/index.js +1 -0
- package/x/dist/utils/helpers/path/index.js +1 -0
- package/{source → x/dist}/utils/helpers/protocol/index.d.ts +2 -10
- package/x/dist/utils/helpers/protocol/index.js +1 -0
- package/x/dist/utils/helpers/protocol/options.js +1 -0
- package/x/dist/utils/helpers/regex/checkSpecialRegexControl.js +1 -0
- package/x/dist/utils/helpers/runtime/dto-access.js +1 -0
- package/x/dist/utils/helpers/runtime/dto-types.js +1 -0
- package/{source → x/dist}/utils/helpers/runtime/index.d.ts +1 -0
- package/x/dist/utils/helpers/runtime/index.js +1 -0
- package/x/dist/utils/helpers/runtime/shutdown.d.ts +3 -0
- package/x/dist/utils/helpers/runtime/shutdown.js +1 -0
- package/x/dist/utils/helpers/state/index.js +1 -0
- package/x/dist/utils/helpers/state/props-from-tmp.js +1 -0
- package/x/dist/utils/helpers/state/request-key-guard.js +1 -0
- package/x/dist/utils/helpers/state/scopes.js +1 -0
- package/x/dist/utils/helpers/string/index.js +1 -0
- package/x/dist/utils/helpers/tests/tmp-schema.test.js +1 -0
- package/x/dist/utils/helpers/tests/tmp-watch.test.d.ts +1 -0
- package/x/dist/utils/helpers/tests/tmp-watch.test.js +1 -0
- package/x/dist/utils/helpers/timer/index.js +1 -0
- package/x/dist/utils/helpers/tmp/index.d.ts +5 -0
- package/x/dist/utils/helpers/tmp/index.js +1 -0
- package/x/dist/utils/helpers/tmp/loader-tmp-sync.js +1 -0
- package/{source → x/dist}/utils/helpers/tmp/runtime-tmp.d.ts +2 -6
- package/x/dist/utils/helpers/tmp/runtime-tmp.js +1 -0
- package/{source → x/dist}/utils/helpers/tmp/tmp-loader.d.ts +1 -0
- package/x/dist/utils/helpers/tmp/tmp-loader.js +1 -0
- package/x/dist/utils/helpers/tmp/tmp-schema.d.ts +47 -0
- package/x/dist/utils/helpers/tmp/tmp-schema.js +1 -0
- package/x/dist/utils/helpers/tmp/tmp-watch.d.ts +1 -0
- package/x/dist/utils/helpers/tmp/tmp-watch.js +1 -0
- package/x/dist/utils/helpers/validates/index.js +1 -0
- package/x/dist/utils/index.js +1 -0
- package/x/dist/utils/models/classes/class.clients.js +1 -0
- package/x/dist/utils/models/classes/class.interfaces.js +1 -0
- package/x/dist/utils/models/classes/class.service-locator.js +1 -0
- package/{source → x/dist}/utils/models/classes/class.tmp-file-loader.d.ts +3 -2
- package/x/dist/utils/models/classes/class.tmp-file-loader.js +1 -0
- package/x/dist/utils/models/classes/class.x.js +1 -0
- package/x/dist/utils/models/enums/index.js +1 -0
- package/x/dist/utils/models/index.js +1 -0
- package/x/dist/utils/models/types/index.js +1 -0
- package/x/dist/utils/package-root.js +1 -0
- package/x/tmp.yml +51 -42
- package/source/index.js +0 -11
- package/source/loader/clients/index.js +0 -22
- package/source/loader/configs/index.js +0 -88
- package/source/loader/controller/index.js +0 -236
- package/source/loader/dto/index.js +0 -92
- package/source/loader/events/index.js +0 -44
- package/source/loader/index.d.ts +0 -11
- package/source/loader/index.js +0 -11
- package/source/loader/kafka/index.js +0 -137
- package/source/loader/localizations/index.js +0 -46
- package/source/loader/logger/index.js +0 -217
- package/source/loader/service/index.js +0 -7
- package/source/loader/system/index.js +0 -25
- package/source/project/index.d.ts +0 -8
- package/source/project/index.js +0 -70
- package/source/utils/constants/defaults.json +0 -15
- package/source/utils/constants/defaults.mjs +0 -10
- package/source/utils/constants/index.js +0 -22
- package/source/utils/helpers/configs/index.js +0 -1
- package/source/utils/helpers/context/controller-store.js +0 -12
- package/source/utils/helpers/context/index.js +0 -24
- package/source/utils/helpers/core/index.js +0 -58
- package/source/utils/helpers/core/paths.js +0 -78
- package/source/utils/helpers/core/tmp-layout.js +0 -241
- package/source/utils/helpers/date/index.js +0 -48
- package/source/utils/helpers/dispatch/index.js +0 -53
- package/source/utils/helpers/dto/index.js +0 -10
- package/source/utils/helpers/filters/index.js +0 -44
- package/source/utils/helpers/framework/index.js +0 -17
- package/source/utils/helpers/handlers/adapters.js +0 -40
- package/source/utils/helpers/handlers/execute.js +0 -82
- package/source/utils/helpers/handlers/index.js +0 -31
- package/source/utils/helpers/hash/crypto.js +0 -22
- package/source/utils/helpers/id/index.js +0 -24
- package/source/utils/helpers/index.js +0 -26
- package/source/utils/helpers/ip/index.js +0 -21
- package/source/utils/helpers/is/index.js +0 -35
- package/source/utils/helpers/locales/index.js +0 -82
- package/source/utils/helpers/math/index.js +0 -14
- package/source/utils/helpers/middleware/index.js +0 -36
- package/source/utils/helpers/objects/index.js +0 -55
- package/source/utils/helpers/path/index.js +0 -4
- package/source/utils/helpers/protocol/index.js +0 -99
- package/source/utils/helpers/protocol/options.js +0 -13
- package/source/utils/helpers/regex/checkSpecialRegexControl.js +0 -3
- package/source/utils/helpers/runtime/dto-access.js +0 -5
- package/source/utils/helpers/runtime/index.js +0 -1
- package/source/utils/helpers/state/index.js +0 -185
- package/source/utils/helpers/state/props-from-tmp.js +0 -44
- package/source/utils/helpers/state/request-key-guard.js +0 -42
- package/source/utils/helpers/state/scopes.js +0 -69
- package/source/utils/helpers/string/index.js +0 -9
- package/source/utils/helpers/timer/index.js +0 -5
- package/source/utils/helpers/tmp/index.d.ts +0 -3
- package/source/utils/helpers/tmp/index.js +0 -3
- package/source/utils/helpers/tmp/loader-tmp-sync.js +0 -13
- package/source/utils/helpers/tmp/runtime-tmp.js +0 -30
- package/source/utils/helpers/tmp/tmp-loader.js +0 -48
- package/source/utils/helpers/validates/index.js +0 -20
- package/source/utils/index.js +0 -3
- package/source/utils/models/classes/class.clients.js +0 -142
- package/source/utils/models/classes/class.interfaces.js +0 -10
- package/source/utils/models/classes/class.service-locator.js +0 -16
- package/source/utils/models/classes/class.tmp-file-loader.js +0 -38
- package/source/utils/models/classes/class.x.js +0 -180
- package/source/utils/models/enums/index.js +0 -148
- package/source/utils/models/index.js +0 -9
- package/source/utils/models/types/index.js +0 -2
- package/source/utils/models/types/shims.d.ts +0 -123
- package/source/utils/package-root.js +0 -5
- package/x/tests/cli.test.ts +0 -85
- package/x/tests/context.test.ts +0 -25
- package/x/tests/dispatch.test.ts +0 -84
- package/x/tests/fixtures/locales/en/translation.json +0 -8
- package/x/tests/fixtures/locales/tr/translation.json +0 -8
- package/x/tests/frameworks.integration.test.ts +0 -185
- package/x/tests/helpers/i18n-setup.ts +0 -52
- package/x/tests/helpers/middleware.ts +0 -23
- package/x/tests/helpers/register-test-dto.ts +0 -52
- package/x/tests/i18n.integration.test.ts +0 -77
- package/x/tests/i18n.test.ts +0 -96
- package/x/tests/middleware.test.ts +0 -83
- package/x/tests/project-layout.test.ts +0 -65
- package/x/tests/protocol.test.ts +0 -75
- package/x/tests/realtime.examples.test.ts +0 -198
- package/x/tests/runtime-tmp.test.ts +0 -49
- package/x/tests/socket.integration.test.ts +0 -174
- package/x/tests/state.test.ts +0 -183
- package/x/tests/tmp-layout-guard.test.ts +0 -40
- /package/{source → x/dist}/index.d.ts +0 -0
- /package/{source → x/dist}/loader/clients/index.d.ts +0 -0
- /package/{source → x/dist}/loader/configs/index.d.ts +0 -0
- /package/{source → x/dist}/loader/dto/index.d.ts +0 -0
- /package/{source → x/dist}/loader/events/index.d.ts +0 -0
- /package/{source → x/dist}/loader/localizations/index.d.ts +0 -0
- /package/{source → x/dist}/loader/service/index.d.ts +0 -0
- /package/{source → x/dist}/loader/system/index.d.ts +0 -0
- /package/{source → x/dist}/utils/constants/index.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/configs/index.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/context/controller-store.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/context/index.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/core/paths.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/core/tmp-layout.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/date/index.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/dispatch/index.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/dto/index.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/filters/index.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/framework/index.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/handlers/adapters.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/handlers/execute.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/handlers/index.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/hash/crypto.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/id/index.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/index.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/ip/index.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/is/index.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/locales/index.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/math/index.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/objects/index.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/path/index.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/protocol/options.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/regex/checkSpecialRegexControl.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/runtime/dto-access.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/runtime/dto-types.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/state/index.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/state/props-from-tmp.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/state/request-key-guard.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/state/scopes.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/string/index.d.ts +0 -0
- /package/{source/utils/helpers/runtime/dto-types.js → x/dist/utils/helpers/tests/tmp-schema.test.d.ts} +0 -0
- /package/{source → x/dist}/utils/helpers/timer/index.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/tmp/loader-tmp-sync.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/validates/index.d.ts +0 -0
- /package/{source → x/dist}/utils/index.d.ts +0 -0
- /package/{source → x/dist}/utils/models/classes/class.clients.d.ts +0 -0
- /package/{source → x/dist}/utils/models/classes/class.interfaces.d.ts +0 -0
- /package/{source → x/dist}/utils/models/classes/class.service-locator.d.ts +0 -0
- /package/{source → x/dist}/utils/models/classes/class.x.d.ts +0 -0
- /package/{source → x/dist}/utils/models/enums/index.d.ts +0 -0
- /package/{source → x/dist}/utils/models/index.d.ts +0 -0
- /package/{source → x/dist}/utils/models/types/index.d.ts +0 -0
- /package/{source → x/dist}/utils/package-root.d.ts +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Kafka as M,logLevel as N}from"kafkajs";import{bindLoaderTmpSync as O}from"../../utils/index.js";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}}
|
|
@@ -0,0 +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/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}}
|
|
@@ -0,0 +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/index.js";import{LogDTO as k}from"../../utils/index.js";import{bindLoaderTmpSync as u}from"../../utils/index.js";import{getRequestId as f}from"../../utils/index.js";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
|
+
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})}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export class BaseService{}export default class Service extends BaseService{constructor(){super()}async onInit(){}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{G as k,notifyRuntimeTmpChange as q,onTmpReload as v,setRuntimeTmpConfigs as w}from"../../utils/index.js";import{normalizeTmpDocument as x}from"../../utils/helpers/tmp/tmp-schema.js";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}}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export { ensureCoreTmpEntry, isCorePackageRoot } from '../utils/helpers/core/tmp-layout';
|
|
2
|
+
export { getTmpSnapshot } from '../utils/helpers/tmp/tmp-loader';
|
|
3
|
+
export declare const core: {
|
|
4
|
+
_: Record<string, unknown>;
|
|
5
|
+
};
|
|
6
|
+
export declare const coreInit: (params: {
|
|
7
|
+
locales?: Record<string, unknown>;
|
|
8
|
+
}) => Promise<void>;
|
|
9
|
+
declare const coreLoader: (_params?: Record<string, never>) => Promise<{
|
|
10
|
+
_: Record<string, unknown>;
|
|
11
|
+
}>;
|
|
12
|
+
export default coreLoader;
|
|
@@ -0,0 +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/index.js";import{Constants as X,getCore as Y,x as Z}from"../utils/index.js";import{ensureCoreTmpEntry as _,isCorePackageRoot as $}from"../utils/helpers/core/tmp-layout.js";import{getTmpSnapshot as v}from"../utils/helpers/tmp/tmp-loader.js";export{ensureCoreTmpEntry,isCorePackageRoot}from"../utils/helpers/core/tmp-layout.js";export{getTmpSnapshot}from"../utils/helpers/tmp/tmp-loader.js";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;
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
{
|
|
2
|
+
"packageName": "@xrystal/core",
|
|
3
|
+
"packageRootFolder": "x",
|
|
4
|
+
"tmpBaseName": "tmp",
|
|
5
|
+
"tmpExtension": ".yml",
|
|
6
|
+
"mainSourceFolder": "./source",
|
|
7
|
+
"layoutPaths": {
|
|
8
|
+
"tests": "tests",
|
|
9
|
+
"environments": "environments",
|
|
10
|
+
"dist": "dist"
|
|
11
|
+
},
|
|
12
|
+
"buildDefaults": {
|
|
13
|
+
"tsconfig": "tsconfig.json",
|
|
14
|
+
"typecheck": false,
|
|
15
|
+
"tscLenient": false,
|
|
16
|
+
"declarations": false,
|
|
17
|
+
"sourcemap": false,
|
|
18
|
+
"minify": false
|
|
19
|
+
},
|
|
20
|
+
"tsconfigDefaults": {
|
|
21
|
+
"pathAliasKey": "@/*",
|
|
22
|
+
"compilerOptions": {
|
|
23
|
+
"noEmit": false,
|
|
24
|
+
"noEmitOnError": false,
|
|
25
|
+
"declaration": true,
|
|
26
|
+
"emitDeclarationOnly": false,
|
|
27
|
+
"sourceMap": false,
|
|
28
|
+
"declarationMap": false,
|
|
29
|
+
"strict": true,
|
|
30
|
+
"noImplicitAny": true
|
|
31
|
+
}
|
|
32
|
+
},
|
|
33
|
+
"eslintDefaults": {
|
|
34
|
+
"restrictedImportDepth": 2
|
|
35
|
+
},
|
|
36
|
+
"tmpWatchDefaults": {
|
|
37
|
+
"intervalMs": 500,
|
|
38
|
+
"minIntervalMs": 100,
|
|
39
|
+
"maxIntervalMs": 10000
|
|
40
|
+
},
|
|
41
|
+
"publicFolderName": "public",
|
|
42
|
+
"kafkaLogsTopic": "log",
|
|
43
|
+
"templateRepoUri": "https://github.com/xdloper/api-gpt-svc"
|
|
44
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import a from"node:path";import{packageRootDir as e}from"../../utils/package-root.js";import t from"./defaults.json" with { type: 'json' };export const packageDefaults=Object.freeze({...t,layoutPaths:Object.freeze({...t.layoutPaths})}),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=a.join(e,packageDefaults.packageRootFolder,o)}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const configs={};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{AsyncLocalStorage as o}from"node:async_hooks";export const controllerContextStorage=new o,getControllerCtx=()=>controllerContextStorage.getStore(),runControllerStore=(t,e)=>controllerContextStorage.run(t,e);export function isFetchRequest(t){return typeof t==="object"&&t!==null&&t instanceof Request}export function adapterBagFromRequest(t){if(!t||isFetchRequest(t))return;return t}
|
|
@@ -0,0 +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.js";
|
|
@@ -8,7 +8,7 @@ export declare const getTmpConfig: ({ root, tmpFileName, ext, }?: {
|
|
|
8
8
|
root?: string;
|
|
9
9
|
tmpFileName?: string;
|
|
10
10
|
ext?: string;
|
|
11
|
-
}) =>
|
|
11
|
+
}) => Record<string, unknown>;
|
|
12
12
|
export declare function resolveObjWithHandlebars(obj: any, context: any): any;
|
|
13
13
|
export declare const withProtocol: <T>(callback: () => T | Promise<T>, protocol?: ProtocolEnum | string) => Promise<T>;
|
|
14
14
|
export declare const protocol: (callback: () => Promise<any>, proto?: ProtocolEnum) => Promise<any>;
|
|
@@ -0,0 +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.js";import{getTmpSnapshot as V}from"../../../utils/helpers/tmp/tmp-loader.js";import{findFileRecursively as X}from"../../../utils/helpers/core/paths.js";import{parseProtocol as Y}from"../../../utils/helpers/protocol/index.js";export*from"../../../utils/helpers/core/paths.js";export*from"../../../utils/helpers/core/tmp-layout.js";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)};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import s from"node:path";import l from"node:fs";export function findFileRecursively(o,c,n="",f=["node_modules",".git"]){if(typeof o!=="string"||!l.existsSync(o))return null;const y=c+(n.startsWith(".")?n:n?`.${n}`:"");try{const i=l.readdirSync(o,{withFileTypes:!0});for(const t of i){const r=s.join(o,t.name);if(t.isFile()){if(!n){const u=s.extname(t.name);if(s.basename(t.name,u)===c)return r}else if(t.name===y)return r}if(t.isDirectory()){if(t.name.startsWith(".")||f.includes(t.name))continue;const e=findFileRecursively(r,c,n,f);if(e)return e}}return null}catch(i){if(i&&typeof i==="object"&&"code"in i&&i.code==="EACCES")return null;return null}}export function findAllFilesRecursively(o,c,n="",f=["node_modules",".git"]){const y=c+(n.startsWith(".")?n:n?`.${n}`:""),i=[];function t(r){if(!l.existsSync(r))return;let u;try{u=l.readdirSync(r,{withFileTypes:!0})}catch{return}for(const e of u){const a=s.join(r,e.name);if(e.isFile()){if(!n){const d=s.extname(e.name);if(s.basename(e.name,d)===c)i.push(a)}else if(e.name===y)i.push(a);continue}if(e.isDirectory()){if(e.name.startsWith(".")||f.includes(e.name))continue;t(a)}}}t(s.resolve(o));return i}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import U from"node:fs";import I from"node:path";import z from"yaml";import{Constants as J}from"../../../utils/constants/index.js";import{findAllFilesRecursively as L,findFileRecursively as A}from"../../../utils/helpers/core/paths.js";import{normalizeTmpDocument as D,readTmpServiceBlock as B,normalizeRootFolder as b,normalizeSourceFolder as x,resolveServiceLayoutPaths as k}from"../../../utils/helpers/tmp/tmp-schema.js";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}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{PolarityTypeEnum as $}from"../../../utils/models/index.js";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}
|
|
@@ -0,0 +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/index.js";import{getFramework as T}from"../../../utils/helpers/framework/index.js";import{getDtoRuntime as U}from"../../../utils/helpers/runtime/index.js";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)}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{DTO,createDTO}from"@xrystal/dto/dto";export{ResponseDTO,Builder,createBuilderProxy,ResponsePresets,assembleResponseBody,dispatchExpressResponse,dispatchNodeResponse,toFetchResponse,applyElysiaTransport,dispatchWebSocketMessage,dispatchSocketIoMessage}from"@xrystal/dto/response";export{expressSink,expressMiddleware,ExpressAdapter}from"@xrystal/dto/express";export{nodeSink,nodeMiddleware,NodeAdapter}from"@xrystal/dto/node";export{fetchSink,fetchDerive,FetchAdapter}from"@xrystal/dto/fetch";export{elysiaSink,ElysiaAdapter}from"@xrystal/dto/elysia";export{websocketSink,WebSocketAdapter}from"@xrystal/dto/websocket";export{socketIoSink,SocketIoAdapter}from"@xrystal/dto/socketio";export{LogDTO,assembleLogBody}from"@xrystal/dto/log";export{QueueDTO,assembleQueueMessage}from"@xrystal/dto/queue";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function mongoFilter(t,n,r){const e={};if(!r)throw Error("MongoFilter helper property is required.");e[r]=e[r]||{};if(t&&n){e[r].$gte=t;e[r].$lte=n}else if(t)e[r].$gte=t;else if(n)e[r].$lte=n;return e}function filterUniqueOnce({arr:t,key:n,uniqueOnceValues:r}){const e=new Set;return t.filter((f)=>{const i=f[n];if(r.includes(i)){if(e.has(i))return!1;e.add(i);return!0}return!0})}function filterSortByPropOrder({arr:t,key:n,desiredOrder:r}){const e=new Map;r.forEach((f,i)=>e.set(f,i));return[...t].sort((f,i)=>{const o=e.get(f[n])??1/0,u=e.get(i[n])??1/0;return o-u})}function filterRemoveItemsByProps({arr:t,key:n,valuesToRemove:r}){return t.filter((e)=>!r.includes(e[n]))}export{mongoFilter,filterUniqueOnce,filterSortByPropOrder,filterRemoveItemsByProps};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{getRuntimeTmpConfigs as q}from"../../../utils/helpers/tmp/runtime-tmp.js";import{FrameworkEnum as j}from"../../../utils/models/index.js";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}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{FrameworkEnum as G,ProtocolEnum as K}from"../../../utils/models/index.js";import{detectSocketProtocol as L}from"../../../utils/helpers/protocol/index.js";import{getFramework as M}from"../../../utils/helpers/framework/index.js";import{runAction as I}from"../../../utils/helpers/handlers/execute.js";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);
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{randomUUID as Q}from"node:crypto";import{FrameworkEnum as V,ProtocolEnum as X}from"../../../utils/models/index.js";import{runControllerStore as Y}from"../../../utils/helpers/context/index.js";import{runWithRequestId as Z}from"../../../utils/helpers/context/index.js";import{dispatchResult as _}from"../../../utils/helpers/dispatch/index.js";import{getFramework as $}from"../../../utils/helpers/framework/index.js";import{attachSocketTransport as x,isRealtimeProtocol as H}from"../../../utils/helpers/protocol/index.js";import{getDtoRuntime as J}from"../../../utils/helpers/runtime/index.js";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)}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{FrameworkEnum as A}from"../../../utils/models/index.js";import{createDtoMiddleware as q}from"../../../utils/helpers/middleware/index.js";import{attachSocketTransport as B,detectSocketProtocol as C,resolveRealtimeMiddlewareProtocol as D}from"../../../utils/helpers/protocol/index.js";import{getDtoRuntime as j}from"../../../utils/helpers/runtime/index.js";export{runAction,runController,configureDto}from"../../../utils/helpers/handlers/execute.js";export{toHandler,toRealtimeHandler,toWebSocket,toSocketIo}from"../../../utils/helpers/handlers/adapters.js";export{getFramework}from"../../../utils/helpers/framework/index.js";export{dispatchResult}from"../../../utils/helpers/dispatch/index.js";export{getRequestId,getRunContext,runWithContext,runWithRequestId,runWithTrace}from"../../../utils/helpers/context/index.js";export{G,propsFromTmp,resolveGStoreBoot,G_PROP_NOT_ALLOWED,G_REQUEST_KEY_WARN,looksLikeRequestScopedKey,GStoreScopeEnum}from"../../../utils/helpers/state/index.js";export{bindLoaderTmpSync,getRuntimeTmpConfigs,setRuntimeTmpConfigs,onRuntimeTmpChange,notifyRuntimeTmpChange,getTmpSnapshot,onTmpReload}from"../../../utils/helpers/tmp/index.js";export{normalizeFrameworkKind,createDtoMiddleware,resolveDtoAdapter}from"../../../utils/helpers/middleware/index.js";export{resolveCtrOptions}from"../../../utils/helpers/protocol/options.js";export{parseProtocol,getConfiguredProtocols,getConfiguredRealtimeProtocols,defaultRealtimeProtocolFromConfig,getDefaultRealtimeProtocol,resolveRealtimeMiddlewareProtocol,detectSocketProtocol,isRealtimeProtocol,isHttpProtocol,resolveProtocolsFromConfig,REALTIME_MIDDLEWARE_HINT}from"../../../utils/helpers/protocol/index.js";export{getDtoRuntime}from"../../../utils/helpers/runtime/index.js";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");
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import t from"crypto";export function generateSHA256Hash(e,r){return t.createHmac("sha256",e).update(r?r:"").digest("hex")}export function generateNumberAndLetter(e=8){const r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",a=new Uint8Array(e);t.getRandomValues(a);return Array.from(a,(n)=>r[n%r.length]).join("")}export function generateCodeChallenge(e){return t.createHash("sha256").update(e).digest("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import d from"crypto";export const serverIdNameGenerator=({prefix:t,payload:e,suffix:r})=>{return`${t}-${e.toString()}-${r}`};export function generateRandomKey(t){const{length:e=48,format:r="hex",prefix:o="",suffix:i="",separator:n="-"}=t,a=d.randomBytes(e).toString(r);return[o,a,i].filter(Boolean).join(n)}export function generateReferenceCode(t,e="",r="",o=""){if(e.length+t+r.length+o.length<=0)throw Error("The total length (including prefix, middle, and suffix) must be greater than 0.");let n="";for(let c=0;c<t;c++){const s=Math.floor(Math.random()*10);n+=s.toString()}const a=Math.floor(n.length/2),l=n.slice(0,a)+r+n.slice(a);return`${e}${l}${o}`}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{default as pic}from"picocolors";export*from"../../utils/helpers/core/index.js";export*from"../../utils/helpers/path/index.js";export*from"../../utils/helpers/is/index.js";export*from"../../utils/helpers/id/index.js";export*from"../../utils/helpers/validates/index.js";export*from"../../utils/helpers/ip/index.js";export*from"../../utils/helpers/hash/crypto.js";export*from"../../utils/helpers/string/index.js";export*from"../../utils/helpers/objects/index.js";export*from"../../utils/helpers/locales/index.js";export*from"../../utils/helpers/timer/index.js";export*from"../../utils/helpers/date/index.js";export*from"../../utils/helpers/math/index.js";export*from"../../utils/helpers/regex/checkSpecialRegexControl.js";export*from"../../utils/helpers/filters/index.js";export*from"../../utils/helpers/framework/index.js";export*from"../../utils/helpers/protocol/index.js";export*from"../../utils/helpers/dto/index.js";export*from"../../utils/helpers/dispatch/index.js";export*from"../../utils/helpers/middleware/index.js";export*from"../../utils/helpers/context/index.js";export*from"../../utils/helpers/tmp/index.js";export*from"../../utils/helpers/state/index.js";export*from"../../utils/helpers/handlers/index.js";export*from"../../utils/helpers/runtime/index.js";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const getClientIp=(e,r={})=>{try{const f=e?.headers?.["x-forwarded-for"]||r?.headers?.["x-forwarded-for"];if(f)return f.split(",")[0].trim().replace("::ffff:","");if(r?.ip)return r.ip.replace("::ffff:","");if(e?.ip)return e.ip.replace("::ffff:","");const d=e?.socket?.remoteAddress||r?.req?.socket?.remoteAddress||e?.remoteAddress||r?.address;if(d)return d.replace("::ffff:","");return"127.0.0.1"}catch(f){return"127.0.0.1"}};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export function isFalsy(e,r){if(!r.ignoreFalse&&e===!1)return!0;if(!r.ignoreZero&&e===0)return!0;if(!r.ignoreEmptyString&&e==="")return!0;if(!r.ignoreNull&&e===null)return!0;if(!r.ignoreUndefined&&e===void 0)return!0;if(!r.ignoreNaN&&typeof e==="number"&&isNaN(e))return!0;return!1}export function isType(e,r){if(typeof e===r)return!0;else return!1}export function isInstance(e,r){if(e instanceof r)return!0;else return!1}export function isBcryptHash(e){return/^\$2[aby]\$\d{2}\$.{53}$/.test(e)}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const n=(...e)=>e.filter((r)=>r&&typeof r==="string"&&r.trim()!=="").join(" ").trim();export const coreMessages={successfully:(e="",r="",s)=>`${n(e,r)} ${s&&s("responseMessage.successfully")}.`.trim(),unsuccessful:(e="",r="",s)=>`${n(e,r)} ${s&&s("responseMessage.unsuccessful")}.`.trim(),notFound:(e="",r="",s)=>`${n(e,r)} ${s&&s("responseMessage.notFound")}.`.trim(),notMatch:(e="",r="",s)=>`${n(e,r)} ${s&&s("responseMessage.notMatch")}.`.trim(),notUse:(e="",r="",s)=>`${n(e,r)} ${s&&s("responseMessage.notUse")}.`.trim(),invalid:(e="",r="",s)=>`${n(e,r)} ${s&&s("responseMessage.invalid")}.`.trim(),checked:(e="",r="",s)=>`${n(e,r)} ${s&&s("responseMessage.checked")}.`.trim(),process:(e="",r="",s)=>`${n(e,r)} ${s&&s("responseMessage.process")}.`.trim(),missingData:(e="",r="",s)=>`${n(e,r)} ${s&&s("responseMessage.missingData")}.`.trim(),allreadyHave:(e="",r="",s)=>`${n(e,r)} ${s&&s("responseMessage.allreadyHave")}.`.trim(),wrongFormat:(e="",r="",s)=>`${n(e,r)} ${s&&s("responseMessage.wrongFormat")}.`.trim(),externalApiError:(e="",r="",s)=>`${n(e,r)}, ${s&&s("responseMessage.externalApiError")}.`.trim(),unauthorizedUrl:(e="",r="",s)=>`${n(e,r)}, ${s&&s("responseMessage.unauthorizedUrl")}.`.trim(),endpointNotWorking:(e="",r)=>`${e}, ${r&&r("responseMessage.endpointNotWorking")}.`.trim(),schemaMissingDataChecks:(e)=>`${e&&e("responseMessage.schemaMissingDataChecks")}.`.trim(),schemaInvalidDataChecks:(e)=>`${e&&e("responseMessage.schemaInvalidDataChecks")}.`.trim(),schemaUnknowErrorChecks:(e,r,s)=>`${s&&s("responseMessage.schemaUnknowErrorChecks")}. ${e}. ${s("responseMessage.schemaErrorExtraExplanation")}: ${r}`.trim(),schemaUnknowErrorLogic:(e,r,s)=>`${s&&s("responseMessage.schemaUnknowErrorLogic")}. ${e}. ${s("responseMessage.schemaErrorExtraExplanation")}: ${r}`.trim(),schemaUnknowErrorResponse:(e,r,s)=>`${s&&s("responseMessage.schemaUnknowErrorLogic")}. ${e}. ${s("responseMessage.schemaErrorExtraExplanation")}: ${r}`.trim(),schemaUnknowErrorMain:(e,r,s)=>`${s&&s("responseMessage.schemaUnknowErrorMain")}. ${e}. ${s("responseMessage.schemaErrorExtraExplanation")}: ${r}`.trim(),dbQueryError:(e="",r="",s)=>`${s&&s("responseMessage.dbQueryError")}. ${n(e,r)}`.trim(),unknowError:(e="",r="",s)=>`${s&&s("responseMessage.unknowError")}. ${n(e,r)}`.trim(),serverError:(e="",r="",s)=>`${s&&s("responseMessage.serverError")}. ${n(e,r)}`.trim(),emailWelcomeTemplateTitle:(e)=>`${e&&e("responseMessage.emailWelcomeTemplateTitle")}`.trim(),emailWelcomeTemplateExplanation:(e)=>`${e&&e("responseMessage.emailWelcomeTemplateExplanation")}.`.trim(),emailForgotPasswordTemplateTitle:(e)=>`${e&&e("responseMessage.emailForgotPasswordTemplateTitle")}`.trim(),emailForgotPasswordTemplateExplanation:(e)=>`${e&&e("responseMessage.emailForgotPasswordTemplateExplanation")}.`.trim(),allRightsReserved:(e="",r="",s)=>`${n(e,r)}, ${s&&s("responseMessage.allRightsReserved")}.`.trim(),emailButtonText:(e)=>`${e&&e("responseMessage.emailButtonText")}.`.trim(),emailIgnoreText:(e)=>`${e&&e("responseMessage.emailIgnoreText")}.`.trim(),welcomeMessage:(e="",r)=>`@${e} - ${r&&r("responseMessage.welcome")}.`.trim(),userIsBlocked:(e="",r)=>`${e}, ${r&&r("responseMessage.userIsBlocked")}.`.trim(),passwordChangeCode:(e="",r)=>`@${e} - ${r&&r("responseMessage.passwordChangeCode")}.`.trim(),notEnoughWalletBalance:(e="",r="",s)=>`${n(e,r)}, ${s&&s("responseMessage.notEnoughWalletBalance")}.`.trim(),openAuthConsumerOverhang:(e="",r="",s)=>`${n(e,r)}, ${s&&s("responseMessage.openAuthConsumerOverhang")}.`.trim(),thirdPartySystemOverhang:(e="",r="",s)=>`${n(e,r)}, ${s&&s("responseMessage.thirdPartySystems")}.`.trim(),deviceOverhang:(e="",r="",s)=>`${n(e,r)}, ${s&&s("responseMessage.deviceOverhang")}.`.trim(),provisionOverhang:(e="",r="",s)=>`${n(e,r)}, ${s&&s("responseMessage.provisionOverhang")}.`.trim(),balanceOverhang:(e="",r="",s)=>`${n(e,r)}, ${s&&s("responseMessage.balanceOverhang")}.`.trim(),debtOverhang:(e="",r="",s)=>`${n(e,r)}, ${s&&s("responseMessage.debtOverhang")}.`.trim(),shipmentNotAccepted:(e="",r="",s)=>`${s&&s("responseMessage.shipmentNotAccepted")}. ${n(e,r)}`.trim(),optionsMethod:(e="",r)=>`${r&&r("responseMessage.optionsMethod")}. ${e}`.trim(),notAllowedCORS:(e="",r)=>`${r&&r("responseMessage.notAllowedCORS")}. ${e}`.trim(),missingCRSFToken:(e)=>`${e&&e("responseMessage.missingCSRFToken")}.`.trim(),invalidCRSFToken:(e)=>`${e&&e("responseMessage.invalidCSRFToken")}.`.trim(),tooManyRequest:(e)=>`${e&&e("responseMessage.tooManyRequest")}.`.trim(),endpointNotFound:(e)=>`${e&&e("responseMessage.endpointNotFound")}.`.trim(),roleAccess:(e="",r)=>`${r&&r("responseMessage.roleAccess")}. ${e}`.trim(),authenticationRequiredTokenExpired:(e)=>`${e&&e("responseMessage.authenticationRequiredTokenExpired")}.`.trim(),authenticationRequired:(e)=>`${e&&e("responseMessage.authenticationRequired")}.`.trim()},responseMessageHelper=new Proxy(coreMessages,{get(e,r){if(r in e)return e[r];const s=globalThis.__LOCAL_MESSAGES__;if(s&&r in s)return s[r];return(o="",a="",i)=>`${n(o,a)} ${r}.`.trim()}});export function parseResponseMessage(e,r,s=!1){const o=String(e||"");if(!o)return s?responseMessageHelper.unsuccessful("","",r):responseMessageHelper.successfully("","",r);let a=s?"unsuccessful":"successfully",i=o;if(o.startsWith("@")){const t=o.split(" ");a=t[0].slice(1);i=t.slice(1).join(" ")}const m=i?i.split("-").map((t)=>t.trim()).filter(Boolean):[],l=m[0]??(o.startsWith("@")?void 0:""),p=m.length>1?m.slice(1).join(" "):o.startsWith("@")?void 0:"";if(responseMessageHelper[a])return responseMessageHelper[a](l,p,r);return s?responseMessageHelper.unsuccessful(l||"",p||"",r):responseMessageHelper.successfully(l||"",p||"",r)}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export function calcPercentace(r,n){if(typeof r!=="number"||typeof n!=="number")throw Error("Değerler sayısal olmalıdır.");return r*n/100}export function bankersRounding(r,n=2){const o=Math.pow(10,n),t=Math.round(r*o);return r*o%1===0.5&&t%2!==0?(t-1)/o:t/o}
|
|
@@ -2,8 +2,8 @@ import { FrameworkEnum } from '../../../utils/models';
|
|
|
2
2
|
export type DtoMiddlewareConfig = FrameworkEnum | string | {
|
|
3
3
|
framework?: unknown;
|
|
4
4
|
};
|
|
5
|
-
export type HttpMiddleware = (req:
|
|
6
|
-
export type SocketMiddleware = (socket:
|
|
5
|
+
export type HttpMiddleware = (req: unknown, res: unknown, next: (err?: unknown) => void) => void | Promise<void>;
|
|
6
|
+
export type SocketMiddleware = (socket: unknown, next?: (err?: unknown) => void) => void | Promise<void>;
|
|
7
7
|
export type ElysiaPlugin = object;
|
|
8
8
|
export type DtoAdapter = HttpMiddleware | SocketMiddleware | ElysiaPlugin | null;
|
|
9
9
|
type DtoAdapterRuntime = {
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{FrameworkEnum as j}from"../../../utils/models/index.js";import{getFramework as x,parseFramework as C}from"../../../utils/helpers/framework/index.js";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))}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export function pickProps(f,p){if(!f)return{};const r=new Set,l=new Set;for(const n of p)if(typeof n==="string"&&n.startsWith("-"))r.add(n.substring(1));else l.add(n);function a(n,t){return t.reduce((e,s)=>e&&e[s]!==void 0?e[s]:void 0,n)}function g(n,t,e){let s=n;for(let o=0;o<t.length-1;o++){if(!(t[o]in s))s[t[o]]={};s=s[t[o]]}s[t[t.length-1]]=e}if(r.size>0){let t=function(e,s=[],o){for(const i in e){const d=[...s,i].join(".");if(!Array.from(r).some((c)=>d===c||d.startsWith(c+".")))if(typeof e[i]==="object"&&e[i]!==null&&!Array.isArray(e[i])){o[i]={};t(e[i],[...s,i],o[i])}else o[i]=e[i]}};const n={};t(f,[],n);return n}const u={};for(const n of l){const t=n.split("."),e=a(f,t);if(e!==void 0)g(u,t,e)}return u}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import t from"path";import{fileURLToPath as r}from"url";export const __filename=(o)=>r(o),__dirname=(o)=>t.dirname(r(o));
|
|
@@ -1,18 +1,10 @@
|
|
|
1
1
|
import { ProtocolEnum } from '../../../utils/models/enums';
|
|
2
|
+
import { getRuntimeTmpConfigs } from '../../../utils/helpers/tmp/runtime-tmp';
|
|
2
3
|
declare const REALTIME_MIDDLEWARE_HINT = "[xrystal] tmp.yml lists both ws and socketio \u2014 use realtimeMiddleware(\"ws\") or realtimeMiddleware(\"socketio\")";
|
|
3
4
|
export declare function parseProtocol(value: unknown): ProtocolEnum;
|
|
4
5
|
export declare function isRealtimeProtocol(protocol?: ProtocolEnum): boolean;
|
|
5
6
|
export declare function isHttpProtocol(protocol?: ProtocolEnum): boolean;
|
|
6
|
-
export type TmpConfigs =
|
|
7
|
-
protocols?: unknown;
|
|
8
|
-
framework?: unknown;
|
|
9
|
-
loaders?: {
|
|
10
|
-
dto?: Record<string, unknown>;
|
|
11
|
-
loggers?: Record<string, unknown>;
|
|
12
|
-
localization?: Record<string, unknown>;
|
|
13
|
-
configs?: Record<string, unknown>;
|
|
14
|
-
};
|
|
15
|
-
};
|
|
7
|
+
export type TmpConfigs = NonNullable<ReturnType<typeof getRuntimeTmpConfigs>>['service'];
|
|
16
8
|
export declare function resolveProtocolsFromConfig(configs?: TmpConfigs): ProtocolEnum[];
|
|
17
9
|
export declare function getConfiguredProtocols(): ProtocolEnum[];
|
|
18
10
|
export declare function getConfiguredRealtimeProtocols(configs?: TmpConfigs): ProtocolEnum[];
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{ProtocolEnum as h}from"../../../utils/models/enums/index.js";import{getRuntimeTmpConfigs as J}from"../../../utils/helpers/tmp/runtime-tmp.js";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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{FrameworkEnum as e,ProtocolEnum as o}from"../../../utils/models/index.js";import{parseProtocol as t}from"../../../utils/helpers/protocol/index.js";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}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export function checkSpecialRegexControl(e,t){return t.test(e)}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{x as t}from"../../../utils/models/index.js";export const DTO_RUNTIME_KEY="dtoRuntime";export function getDtoRuntime(){return t.get(DTO_RUNTIME_KEY)}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{};
|
|
@@ -1,2 +1,3 @@
|
|
|
1
1
|
export { getDtoRuntime, DTO_RUNTIME_KEY } from '../../../utils/helpers/runtime/dto-access';
|
|
2
2
|
export type { IDtoRuntime, DtoAdapterRuntime, DtoConfigureOptions } from '../../../utils/helpers/runtime/dto-types';
|
|
3
|
+
export { gracefulShutdown, isShuttingDown, registerGracefulShutdown } from '../../../utils/helpers/runtime/shutdown';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{getDtoRuntime,DTO_RUNTIME_KEY}from"../../../utils/helpers/runtime/dto-access.js";export{gracefulShutdown,isShuttingDown,registerGracefulShutdown}from"../../../utils/helpers/runtime/shutdown.js";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{stopTmpLoader as y}from"../../../utils/helpers/tmp/tmp-loader.js";import{clearRuntimeTmpConfigs as z}from"../../../utils/helpers/tmp/runtime-tmp.js";import A from"../../../utils/models/classes/class.x.js";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)}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createStore as w}from"zustand/vanilla";import{subscribeWithSelector as I}from"zustand/middleware";import{GStoreScopeEnum as Z}from"../../../utils/models/enums/index.js";import{propsFromTmp,resolveGStoreBoot,G_PROP_NOT_ALLOWED}from"../../../utils/helpers/state/props-from-tmp.js";import{warnIfRequestScopedKey as Q,G_REQUEST_KEY_WARN,looksLikeRequestScopedKey}from"../../../utils/helpers/state/request-key-guard.js";import{buildStoresSnapshot as U,patchControllerScope as Y,patchRunScope as q}from"../../../utils/helpers/state/scopes.js";export{propsFromTmp,resolveGStoreBoot,G_PROP_NOT_ALLOWED,G_REQUEST_KEY_WARN,looksLikeRequestScopedKey};export{GStoreScopeEnum}from"../../../utils/models/enums/index.js";export{buildStoresSnapshot,summarizeController,runContextValues,patchControllerScope,patchRunScope}from"../../../utils/helpers/state/scopes.js";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;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{readTmpServiceBlock as I}from"../../../utils/helpers/tmp/tmp-schema.js";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()}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{getRunContext as B}from"../../../utils/helpers/context/index.js";import{getControllerCtx as D}from"../../../utils/helpers/context/controller-store.js";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})`)}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{GStoreScopeEnum as j}from"../../../utils/models/enums/index.js";import{getRunContext as q,patchRunContext as w}from"../../../utils/helpers/context/index.js";import{getControllerCtx as v}from"../../../utils/helpers/context/controller-store.js";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}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export function cleanStringForNormalize(e){if(typeof e!=="string")return"";return e.normalize("NFD").replace(/\u0307/g,"").normalize("NFC")}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{describe as K,expect as j,test as A}from"bun:test";import{normalizeRootFolder as H,normalizeTmpDocument as N,readTmpCoreBlock as O,readTmpServiceBlock as J,resolveServiceLayoutPaths as Q,resolveTmpRuntimeConfigs as U}from"../../../utils/helpers/tmp/tmp-schema.js";import{resolveTmpWatchIntervalMs as V}from"../../../utils/helpers/tmp/tmp-watch.js";const G={configs:{service:{name:"my-api",framework:"elysia",paths:{root:"./infra.js",source:"./src.js",special:{tests:"specs",environments:"env",dist:"out"}},protocols:["http"],build:{typecheck:!0},loaders:{dto:{withDefaultHeaders:!0}}},core:{tmp:{fileWatchIntervalMs:200}}}};K("tmp-schema service + core blocks",()=>{A("readTmpServiceBlock reads paths.root, paths.source, paths.special",()=>{const q=J(G.configs);j(q.paths?.root).toBe("./infra.js");j(q.paths?.source).toBe("./src.js");j(q.paths?.special?.tests).toBe("specs");j(q.name).toBe("my-api");j(q.build?.typecheck).toBe(!0)});A("readTmpCoreBlock reads core.tmp.fileWatchIntervalMs",()=>{j(O(G.configs).tmp?.fileWatchIntervalMs).toBe(200)});A("normalizeRootFolder strips ./ prefix",()=>{j(H("./x.js")).toBe("x");j(H("infra")).toBe("infra")});A("resolveTmpRuntimeConfigs returns service, core, and rootFolderPath",()=>{const q=U(G);j(Object.keys(q)).toEqual(["service","core","rootFolderPath"]);j(q.rootFolderPath).toBe("infra");j(q.service.paths?.special?.dist).toBe("out");j(q.service.framework).toBe("elysia");j(q.service.loaders).toEqual({dto:{withDefaultHeaders:!0}});j(q.core.tmp?.fileWatchIntervalMs).toBe(200);j("loaders"in q).toBe(!1);j("mainFolderPath"in q).toBe(!1)});A("normalizeTmpDocument merges service + core + derived rootFolderPath onto configs",()=>{const E=N(G).configs;j(E.service).toBeTruthy();j(E.core).toBeTruthy();j(E.rootFolderPath).toBe("infra");j(E.service.loaders).toBeTruthy();j(E.loaders).toBeUndefined();j(E.mainFolderPath).toBeUndefined()});A("resolveTmpWatchIntervalMs reads core.tmp.fileWatchIntervalMs",()=>{j(V(G)).toBe(200)});A("resolveServiceLayoutPaths uses defaults when special omitted",()=>{const q=Q(J({service:{paths:{}}}));j(q.tests).toBe("tests");j(q.dist).toBe("dist")})});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{describe as k,expect as f,test as j}from"bun:test";import{resolveTmpWatchIntervalMs as g}from"../../../utils/helpers/tmp/tmp-watch.js";k("resolveTmpWatchIntervalMs",()=>{j("defaults to 500ms when core.tmp omitted",()=>{f(g({configs:{}})).toBe(500)});j("reads configs.core.tmp.fileWatchIntervalMs",()=>{f(g({configs:{core:{tmp:{fileWatchIntervalMs:200}}}})).toBe(200)});j("clamps to min/max bounds",()=>{f(g({configs:{core:{tmp:{fileWatchIntervalMs:10}}}})).toBe(100);f(g({configs:{core:{tmp:{fileWatchIntervalMs:60000}}}})).toBe(1e4)})});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export async function delay({duration:e}){return new Promise((t,n)=>{setTimeout(()=>t(delay),e)})}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { setRuntimeTmpConfigs, getRuntimeTmpConfigs, onRuntimeTmpChange, notifyRuntimeTmpChange, clearRuntimeTmpConfigs, type RuntimeTmpConfigs, } from '../../../utils/helpers/tmp/runtime-tmp';
|
|
2
|
+
export { getTmpLoader, getTmpLoaderPath, getTmpSnapshot, onTmpReload, resetTmpLoaderForTests, stopTmpLoader, } from '../../../utils/helpers/tmp/tmp-loader';
|
|
3
|
+
export { bindLoaderTmpSync, type ITmpSyncLoader, } from '../../../utils/helpers/tmp/loader-tmp-sync';
|
|
4
|
+
export { resolveTmpWatchIntervalMs } from '../../../utils/helpers/tmp/tmp-watch';
|
|
5
|
+
export { normalizeTmpDocument, normalizeRootFolder, normalizeSourceFolder, readTmpCoreBlock, readTmpServiceBlock, resolveServiceLayoutPaths, resolveTmpRuntimeConfigs, } from '../../../utils/helpers/tmp/tmp-schema';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{setRuntimeTmpConfigs,getRuntimeTmpConfigs,onRuntimeTmpChange,notifyRuntimeTmpChange,clearRuntimeTmpConfigs}from"../../../utils/helpers/tmp/runtime-tmp.js";export{getTmpLoader,getTmpLoaderPath,getTmpSnapshot,onTmpReload,resetTmpLoaderForTests,stopTmpLoader}from"../../../utils/helpers/tmp/tmp-loader.js";export{bindLoaderTmpSync}from"../../../utils/helpers/tmp/loader-tmp-sync.js";export{resolveTmpWatchIntervalMs}from"../../../utils/helpers/tmp/tmp-watch.js";export{normalizeTmpDocument,normalizeRootFolder,normalizeSourceFolder,readTmpCoreBlock,readTmpServiceBlock,resolveServiceLayoutPaths,resolveTmpRuntimeConfigs}from"../../../utils/helpers/tmp/tmp-schema.js";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{onRuntimeTmpChange as k}from"../../../utils/helpers/tmp/runtime-tmp.js";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,9 +1,5 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
protocols?: unknown;
|
|
4
|
-
loaders?: Record<string, unknown>;
|
|
5
|
-
[key: string]: unknown;
|
|
6
|
-
};
|
|
1
|
+
import type { TmpRuntimeConfigs } from '../../../utils/helpers/tmp/tmp-schema';
|
|
2
|
+
export type RuntimeTmpConfigs = TmpRuntimeConfigs;
|
|
7
3
|
type TmpChangeListener = (configs: RuntimeTmpConfigs) => void | Promise<void>;
|
|
8
4
|
export declare function setRuntimeTmpConfigs(configs?: RuntimeTmpConfigs): void;
|
|
9
5
|
export declare function getRuntimeTmpConfigs(): RuntimeTmpConfigs | undefined;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
let e;const i=[];export function setRuntimeTmpConfigs(n){e=n}export function getRuntimeTmpConfigs(){return e}export function onRuntimeTmpChange(n){i.push(n);return()=>{const t=i.indexOf(n);if(t>=0)i.splice(t,1)}}export async function notifyRuntimeTmpChange(n){if(n)e=n;const t=e;if(!t)return;for(const o of i)await o(t)}export function clearRuntimeTmpConfigs(){e=void 0;i.length=0}
|
|
@@ -3,4 +3,5 @@ export declare function getTmpLoaderPath(): string;
|
|
|
3
3
|
export declare function getTmpLoader(): TmpFileLoader;
|
|
4
4
|
export declare function getTmpSnapshot(): Record<string, unknown>;
|
|
5
5
|
export declare function onTmpReload(listener: (tmp: Record<string, unknown>) => void): () => void;
|
|
6
|
+
export declare function stopTmpLoader(): void;
|
|
6
7
|
export declare function resetTmpLoaderForTests(): void;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import J from"node:fs";import K from"node:path";import{Constants as E}from"../../../utils/constants/index.js";import{assertCoreTmpGuard as M,coreCanonicalTmpPath as O,isCorePackageRoot as Q}from"../../../utils/helpers/core/tmp-layout.js";import{findFileRecursively as U}from"../../../utils/helpers/core/paths.js";import{TmpFileLoader as V}from"../../../utils/models/classes/class.tmp-file-loader.js";import{registerGracefulShutdown as W}from"../../../utils/helpers/runtime/shutdown.js";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()}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
export type TmpServiceSpecialPaths = {
|
|
2
|
+
tests?: string;
|
|
3
|
+
environments?: string;
|
|
4
|
+
dist?: string;
|
|
5
|
+
};
|
|
6
|
+
export type TmpServicePathsBlock = {
|
|
7
|
+
root?: string;
|
|
8
|
+
source?: string;
|
|
9
|
+
special?: TmpServiceSpecialPaths;
|
|
10
|
+
};
|
|
11
|
+
export type TmpServiceBlock = {
|
|
12
|
+
name?: string;
|
|
13
|
+
framework?: string;
|
|
14
|
+
paths?: TmpServicePathsBlock;
|
|
15
|
+
protocols?: unknown;
|
|
16
|
+
loaders?: Record<string, unknown>;
|
|
17
|
+
build?: Record<string, unknown>;
|
|
18
|
+
};
|
|
19
|
+
export type TmpCoreBlock = {
|
|
20
|
+
tmp?: {
|
|
21
|
+
fileWatchIntervalMs?: number | string;
|
|
22
|
+
};
|
|
23
|
+
};
|
|
24
|
+
export type TmpLayoutPathsFlat = {
|
|
25
|
+
tests: string;
|
|
26
|
+
environments: string;
|
|
27
|
+
dist: string;
|
|
28
|
+
};
|
|
29
|
+
export type TmpRuntimeConfigs = {
|
|
30
|
+
service: TmpServiceBlock & {
|
|
31
|
+
paths: Required<Pick<TmpServicePathsBlock, 'root' | 'source'>> & {
|
|
32
|
+
special: TmpLayoutPathsFlat;
|
|
33
|
+
};
|
|
34
|
+
};
|
|
35
|
+
core: TmpCoreBlock;
|
|
36
|
+
rootFolderPath: string;
|
|
37
|
+
};
|
|
38
|
+
/** `paths.root` → folder name under project root (`x`, `infra`). */
|
|
39
|
+
export declare function normalizeRootFolder(value?: string): string;
|
|
40
|
+
/** `paths.source` → dev/build source folder (`./source`, `./src`). */
|
|
41
|
+
export declare function normalizeSourceFolder(value?: string): string;
|
|
42
|
+
export declare function readTmpCoreBlock(configs?: Record<string, unknown>): TmpCoreBlock;
|
|
43
|
+
export declare function readTmpServiceBlock(configs?: Record<string, unknown>): TmpServiceBlock;
|
|
44
|
+
export declare function resolveServiceLayoutPaths(service: TmpServiceBlock): TmpLayoutPathsFlat;
|
|
45
|
+
/** Canonical tmp.yml shape — `service` + `core` + derived `rootFolderPath`. */
|
|
46
|
+
export declare function resolveTmpRuntimeConfigs(tmp?: Record<string, unknown> | null): TmpRuntimeConfigs;
|
|
47
|
+
export declare function normalizeTmpDocument(tmp: Record<string, unknown>): Record<string, unknown>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Constants as G}from"../../../utils/constants/index.js";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)}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function resolveTmpWatchIntervalMs(tmp?: Record<string, unknown> | null): number;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import I from"../../../utils/constants/defaults.json" with { type: 'json' };import{readTmpCoreBlock as J}from"../../../utils/helpers/tmp/tmp-schema.js";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)))}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const validateScopes=({scopes:i,permissions:t,resources:o})=>{const s=i.split(" ");function r(e){if(new Set(e).size!==e.length)return!0;return!1}if(r(s))return!1;return!s.some((e)=>{const[n,c]=e.split(":"),u=o.includes(n),l=t.includes(c);return!u||!l})};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export*from"../utils/constants/index.js";export*from"../utils/helpers/index.js";export*from"../utils/models/index.js";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createHash as k,createHmac as E}from"node:crypto";import{Configs as y,Logger as N}from"../../../loader/index.js";import{LoggerLayerEnum as x,x as b}from"../../../utils/index.js";import{getRequestId as D}from"../../../utils/helpers/context/index.js";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}}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export class ILifeCycle{async onInit(o={}){}onAfterInit(o){}onDispose(o){}}export class IProvide extends ILifeCycle{}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export class Locator{_context=new Map;constructor({}){}set=({service:t,reference:e,args:o})=>{this._context.set(t,new e(...o||[]))};get=(t)=>{if(!this._context.has(t))throw Error(`${t} not found in context.`);return this._context.get(t)}}export default new Locator({});
|
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import { EventEmitter } from
|
|
1
|
+
import { EventEmitter } from 'node:events';
|
|
2
2
|
export declare class TmpFileLoader extends EventEmitter {
|
|
3
3
|
#private;
|
|
4
4
|
constructor({ filePath }: {
|
|
5
5
|
filePath: string;
|
|
6
6
|
});
|
|
7
|
-
|
|
7
|
+
stop(): void;
|
|
8
|
+
getResolvedTmpFile(): Record<string, unknown>;
|
|
8
9
|
}
|
|
@@ -0,0 +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/index.js";import{normalizeTmpDocument as X}from"../../../utils/helpers/tmp/tmp-schema.js";import{resolveTmpWatchIntervalMs as A}from"../../../utils/helpers/tmp/tmp-watch.js";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))}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var __filename="/home/runner/work/-xrystal-core/-xrystal-core/x/dist/utils/models/classes/class.x.js";import{createContainer as w,asClass as y,asValue as L,InjectionMode as z,listModules as C,Lifetime as h}from"awilix";import p from"node:path";import{pathToFileURL as A}from"node:url";export const xSymbol=Symbol.for("@xrystal/core/di-container");class I{checkRegistration(e,t){return!!e.registrations[t]}}class N extends I{container;initializedNames=new Set;loadedPaths=new Set;registeredClasses=new Set;isInitializing=!1;constructor(){super();this.container=w({injectionMode:z.PROXY,strict:!0})}getName(e){if(typeof e==="string")return e.charAt(0).toLowerCase()+e.slice(1);if(typeof e==="function"&&e.name)return e.name.charAt(0).toLowerCase()+e.name.slice(1);return""}async load(e,t={}){const{verbose:r=!1,exclude:m=[],lifetime:s=h.SINGLETON}=t,i=process.cwd(),n=(Array.isArray(e)?e:[e]).map((c)=>{return(p.isAbsolute(c)?c:p.resolve(i,c)).replace(/\\/g,"/").toLowerCase()});let a=[];try{a=C(n)}catch(c){return this}for(const c of a){const f=c.path.replace(/\\/g,"/").toLowerCase();if(this.loadedPaths.has(f))continue;if(f===__filename.replace(/\\/g,"/").toLowerCase()||f.endsWith(".d.ts"))continue;try{const g=await import(A(c.path).href);let o=g.default;if(!o)o=Object.values(g).find((l)=>typeof l==="function"&&!!l.prototype&&!!l.name);if(typeof o==="function"&&!!o.prototype&&!!o.name){if(this.registeredClasses.has(o))continue;const l=this.getName(o);if(l&&!this.checkRegistration(this.container,l)){this.container.register({[l]:y(o).setLifetime(s)});this.loadedPaths.add(f);this.registeredClasses.add(o)}}}catch(u){if(r)console.error("[DI] Load Error:",u.message)}}return this}register(e,t=h.SINGLETON){const r=this.getName(e);if(!r||this.registeredClasses.has(e))return this;if(this.checkRegistration(this.container,r))return this;this.container.register({[r]:y(e).setLifetime(t)});this.registeredClasses.add(e);return this}registerInstance(e,t){if(!e)return this;const r=this.getName(e);this.container.register({[r]:L(t)});return this}async initialize(e,t=!1){if(this.isInitializing)return this;this.isInitializing=!0;try{const r=e?Array.isArray(e)?e:[e]:[];for(const s of r){const i=this.getName(s.service);if(!i||this.initializedNames.has(i))continue;const n=this.container.registrations[i];if(!n||n.lifetime!==h.SINGLETON)continue;try{const a=this.container.cradle[i];if(a&&typeof a.onInit==="function")await a.onInit(s.props||{});this.initializedNames.add(i)}catch(a){if(t)console.error(`[DI] Priority onInit Failed (${i}):`,a.message)}}const m=Object.keys(this.container.registrations);for(const s of m){if(this.initializedNames.has(s))continue;if(this.container.registrations[s].lifetime!==h.SINGLETON)continue;try{const n=this.container.cradle[s];if(n&&typeof n.onInit==="function")await n.onInit({});this.initializedNames.add(s)}catch(n){if(t)console.error(`[DI] Auto onInit Failed (${s}):`,n.message)}}for(const s of this.initializedNames)try{const i=this.container.cradle[s];if(i&&typeof i.onAfterInit==="function")await i.onAfterInit()}catch(i){if(t)console.error(`[DI] onAfterInit Failed (${s}):`,i.message)}}finally{this.isInitializing=!1}return this}get(e){const t=this.getName(e);return this.container.resolve(t)}async shutdown(){for(const e of this.initializedNames)try{const t=this.container.cradle[e];if(t&&typeof t.onDispose==="function")await t.onDispose()}catch(t){console.error(`[DI] onDispose Failed (${e})`)}await this.container.dispose()}get cradle(){return this.container.cradle}}const d=globalThis;if(!d[xSymbol])d[xSymbol]=new N;export default d[xSymbol];
|