@xrystal/core 3.51.1 → 3.51.2
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/package.json +2 -2
- package/x/dist/loader/configs/index.js +1 -1
- package/x/dist/loader/kafka/index.js +1 -1
- package/x/dist/loader/kafka/resolve-ssl.js +1 -1
- package/x/dist/loader/mongo/index.js +1 -1
- package/x/dist/loader/mongo/resolve-connect.js +1 -1
- package/x/dist/loader/redis/index.js +1 -1
- package/x/dist/loader/redis/resolve-socket.js +1 -1
- package/x/dist/loader/registry/index.d.ts +0 -1
- package/x/dist/loader/system/index.js +1 -1
- package/x/dist/project/index.js +1 -1
- package/x/dist/utils/constants/index.js +1 -1
- package/x/dist/utils/constants/package-root.js +1 -1
- package/x/dist/utils/helpers/context/index.js +1 -1
- package/x/dist/utils/helpers/core/handlebars-resolve.js +1 -1
- package/x/dist/utils/helpers/core/index.js +1 -1
- package/x/dist/utils/helpers/core/tmp-layout.js +1 -1
- package/x/dist/utils/helpers/date/index.js +1 -1
- package/x/dist/utils/helpers/dispatch/index.js +1 -1
- package/x/dist/utils/helpers/framework/index.js +1 -1
- package/x/dist/utils/helpers/handlers/adapters.js +1 -1
- package/x/dist/utils/helpers/handlers/execute.js +1 -1
- package/x/dist/utils/helpers/handlers/index.js +1 -1
- package/x/dist/utils/helpers/index.d.ts +1 -0
- package/x/dist/utils/helpers/index.js +1 -1
- package/x/dist/utils/helpers/middleware/index.js +1 -1
- package/x/dist/utils/helpers/node-env/index.d.ts +2 -0
- package/x/dist/utils/helpers/node-env/index.js +1 -0
- package/x/dist/utils/helpers/path/index.js +1 -1
- package/x/dist/utils/helpers/path/resolve-alias-path.js +1 -1
- package/x/dist/utils/helpers/protocol/index.js +1 -1
- package/x/dist/utils/helpers/registry/index.d.ts +0 -4
- package/x/dist/utils/helpers/registry/index.js +1 -1
- package/x/dist/utils/helpers/runtime/shutdown.js +1 -1
- package/x/dist/utils/helpers/state/index.js +1 -1
- package/x/dist/utils/helpers/state/props-from-tmp.js +1 -1
- package/x/dist/utils/helpers/state/request-key-guard.js +1 -1
- package/x/dist/utils/helpers/state/scopes.js +1 -1
- package/x/dist/utils/helpers/tmp/loader-tmp-sync.js +1 -1
- package/x/dist/utils/helpers/tmp/runtime-tmp.js +1 -1
- package/x/dist/utils/helpers/tmp/seed-from-tmp.js +1 -1
- package/x/dist/utils/helpers/tmp/tmp-loader.js +1 -1
- package/x/dist/utils/helpers/tmp/tmp-schema.js +1 -1
- package/x/dist/utils/helpers/tmp/tmp-watch.js +1 -1
- package/x/dist/utils/helpers/tmp/toolchain-heal.js +2 -2
- package/x/dist/utils/models/classes/class.clients.js +1 -1
- package/x/dist/utils/models/classes/class.service-locator.js +1 -1
- package/x/dist/utils/models/classes/class.tmp-file-loader.js +1 -1
- package/x/dist/utils/models/classes/class.x.js +1 -1
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"author": "Yusuf Yasir KAYGUSUZ",
|
|
3
3
|
"name": "@xrystal/core",
|
|
4
|
-
"version": "3.51.
|
|
4
|
+
"version": "3.51.2",
|
|
5
5
|
"description": "microservice runtime library",
|
|
6
6
|
"publishConfig": {
|
|
7
7
|
"access": "public",
|
|
@@ -122,4 +122,4 @@
|
|
|
122
122
|
"typescript": "~5.9.3",
|
|
123
123
|
"typescript-eslint": "^8.62.1"
|
|
124
124
|
}
|
|
125
|
-
}
|
|
125
|
+
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import _ from"node:path";import p from"lodash";import{pathToFileURL as l}from"node:url";import{Constants as E}from "../../utils/constants/index.js";import{resolveTmpLoadPath as S}from "../../utils/helpers/path/resolve-alias-path.js";import{bindLoaderTmpSync as d}from "../../utils/helpers/tmp/loader-tmp-sync.js";import{normalizeNodeEnv as n}from "../../utils/helpers/node-env/index.js";export default class Configs{publicFolderName=E.publicFolderName;kafkaLogsTopic=E.kafkaLogsTopic;#s;#e;constructor({system:s}){this.#s=s;return new Proxy(this,{get:(r,t)=>{return r[t]||r.config?.[t]}})}onInit=async()=>{await this.syncFromTmp();d(this)};syncFromTmp=async()=>{const s=process.cwd(),e=this.#s.tmp,r=e.configs.service.loaders.configs.loadPath,t=S(r,e,s),f=import(l(t).href);this.#e={worker:process.env.WORKER==="true"?!0:!1,mode:process.env.MODE,nodeEnv:n("development"),debug:process.env.SYSTEM_LOGGER_LAYER??"",https:process.env.HTTPS??"false",httpsfileEncoding:process.env.ENCODING||"utf8",httpsCertfile:process.env.HTTPS_CERT_FILE??"",httpsKeyfile:process.env.HTTPS_KEY_FILE??"",rootFolderPath:e.configs.rootFolderPath||"x",projectName:e.project.name,serviceName:e.configs.service.name??"",projectNamePrefixEnv:process.env.PROJECT_NAME_PREFIX||"",projectNameEnv:process.env.PROJECT_NAME||"",projectNameSuffixEnv:process.env.PROJECT_NAME_SUFFIX||"",systemStaticFolderPath:_.resolve(e.configs.rootFolderPath,this.publicFolderName),systemLoggerLayer:process.env.SYSTEM_LOGGER_LAYER??"info",isKafkaPassive:process.env.IS_KAFKA_PASSIVE==="true"?!0:!1,kafkaClientId:e.configs.service.name??"",kafkaBrokers:process.env.KAFKA_BROKERS??"",kafkaUsername:process.env.KAFKA_USERNAME??"",kafkaPassword:process.env.KAFKA_PASSWORD??"",kafkaTopics:[],kafkaLogsTopic:this.kafkaLogsTopic,isRedisPassive:process.env.IS_REDIS_PASSIVE==="true"?!0:!1,redisUri:process.env.REDIS_URI??"",isMongoPassive:process.env.IS_MONGODB_PASSIVE==="true"?!0:!1,mongodbUri:process.env.MONGODB_URI??"",isRegistryEnabled:process.env.IS_REGISTRY_ENABLED==="true",registryMongodbUri:process.env.REGISTRY_MONGODB_URI??"",baseApiUri:process.env.HTTPS==="true"?process.env.SYSTEM_HTTPS_BASE_API_URI??"":process.env.SYSTEM_BASE_API_URI??"",port:Number(process.env.PORT),internalSecret:process.env.INTERNAL_SECRET??"",secret:process.env.SECRET??"",cwd:s,env:n("development")};try{const o=await f,v=o?.default||o?.configs||o||{},c=p.mergeWith({},this.#e,v,(a,m)=>{if(p.isArray(a))return a.concat(m)}),i=n(c.nodeEnv??c.env??"development");this.#e=Object.freeze({...c,nodeEnv:i,env:i})}catch{const o=n(this.#e.nodeEnv??this.#e.env??"development");this.#e=Object.freeze({...this.#e,nodeEnv:o,env:o})}};setConfig(s){const e=Object.assign(this.#e,s);this.#e=Object.freeze(e)}_(s){return this.#e[s]}get all(){return this.#e}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export{resolveKafkaJsSsl}from "./resolve-ssl.js";import{Kafka as
|
|
1
|
+
export{resolveKafkaJsSsl}from "./resolve-ssl.js";import{Kafka as c,logLevel as l}from"kafkajs";import{bindLoaderTmpSync as k}from "../../utils/helpers/tmp/loader-tmp-sync.js";import{resolveKafkaJsSsl as f}from "./resolve-ssl.js";export default class KafkaForCore{_instance;_producer;clientId="";brokers="";username=null;password=null;#a;#r;constructor({system:a,configs:r}){this.#a=a;this.#r=r}onDispose=async()=>{await this.teardownKafka()};onInit=async()=>{await this.syncFromTmp();k(this)};syncFromTmp=async()=>{await this.teardownKafka();this.clientId=this.#r.all?.kafkaClientId;this.brokers=this.#r.all?.kafkaBrokers;this.username=this.#r.all?.kafkaUsername;this.password=this.#r.all?.kafkaPassword;if(this.#r.all.isKafkaPassive)return;const a=(Array.isArray(this.brokers)?this.brokers:this.brokers?.split(",")??[]).map((r)=>r?.trim()).filter(Boolean);if(a.length===0)throw Error("Broker list error");await this.kafkaLoader({clientId:this.clientId,brokers:a,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:a,brokers:r,username:i,password:t})=>{const e={clientId:a,brokers:r,sasl:i&&t?{mechanism:"plain",username:i,password:t}:void 0,ssl:f(r),logLevel:l.ERROR,logCreator:()=>{return({level:s,log:o})=>{console.error(`Kafka ${o.message}`)}},retry:{initialRetryTime:100,retries:8}};try{const s=new c(e);this._instance=s;this._producer=s.producer();await this.producer.connect();return s}catch(s){console.error(`Kafka ${s}`)}};initializeKafkaInfrastructure=async()=>{const{kafkaBrokers:a,kafkaTopics:r,isKafkaPassive:i}={isKafkaPassive:process.env.IS_KAFKA_PASSIVE==="true"?!0:!1,kafkaBrokers:process.env?.KAFKA_BROKERS,kafkaTopics:[...new Set([...this.#r.all.kafkaTopics])]};if(i===!0||!a)return;const t=Array.isArray(r)?r:[];if(t.length===0)return;const e=this._instance.admin();try{await e.connect();const s=await e.listTopics(),o=t.filter((n)=>!s.includes(n)).map((n)=>({topic:n,numPartitions:1,replicationFactor:1}));if(o.length>0)await e.createTopics({waitForLeaders:!0,topics:o})}catch(s){}finally{await e.disconnect()}};sendMessage=async(a,r)=>{if(!this.producer)throw Error("Producer not ready");await this.producer.send({topic:a,messages:[{value:JSON.stringify(r)}],acks:0})};get producer(){return this._producer}get instance(){return this._instance}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import t from"node:fs";export function resolveKafkaJsSsl(r=[]){const s=process.env.KAFKA_SSL==="true",c=r.some((n)=>/:9095\b/.test(n));if(!s&&!c)return!1;const e=process.env.KAFKA_SSL_CA||"/etc/tls/infra/ca.crt";try{if(e&&t.existsSync(e))return{ca:[t.readFileSync(e,"utf-8")],rejectUnauthorized:!1}}catch{}return{rejectUnauthorized:!1}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export{resolveMongoConnectOptions}from "./resolve-connect.js";import{MongoClient as
|
|
1
|
+
export{resolveMongoConnectOptions}from "./resolve-connect.js";import{MongoClient as o}from"mongodb";import{bindLoaderTmpSync as i}from "../../utils/helpers/tmp/loader-tmp-sync.js";import{resolveMongoConnectOptions as s}from "./resolve-connect.js";export default class MongoForCore{#t=null;#n=null;#i;#o;constructor({system:t,configs:n}){this.#i=t;this.#o=n}onDispose=async()=>{await this.teardown()};onInit=async()=>{await this.syncFromTmp();i(this)};syncFromTmp=async()=>{await this.teardown();if(this.#o.all.isMongoPassive)return;const t=this.#o.all.mongodbUri?.trim();if(!t)return;const n=new o(t,s(t));await n.connect();this.#t=n;this.#n=n.db()};teardown=async()=>{if(!this.#t)return;try{await this.#t.close()}catch{}this.#t=null;this.#n=null};get client(){return this.#t}get db(){return this.#n}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export function resolveMongoConnectOptions(e){if(!((e?.trim()??"").includes("tls=true")||process.env.MONGODB_SSL==="true"))return{};const
|
|
1
|
+
export function resolveMongoConnectOptions(e){if(!((e?.trim()??"").includes("tls=true")||process.env.MONGODB_SSL==="true"))return{};const s=process.env.MONGODB_SSL_CA||process.env.KAFKA_SSL_CA||"/etc/tls/infra/ca.crt",t=process.env.MONGODB_SSL_PEM||"/etc/tls/infra/mongodb.pem";return{tls:!0,tlsCAFile:s,tlsCertificateKeyFile:t,tlsAllowInvalidHostnames:!0}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export{resolveRedisSocketOptions}from "./resolve-socket.js";import{createClient as
|
|
1
|
+
export{resolveRedisSocketOptions}from "./resolve-socket.js";import{createClient as r}from"redis";import{bindLoaderTmpSync as e}from "../../utils/helpers/tmp/loader-tmp-sync.js";import{resolveRedisSocketOptions as o}from "./resolve-socket.js";export default class RedisForCore{#t=null;#s;#i;constructor({system:t,configs:i}){this.#s=t;this.#i=i}onDispose=async()=>{await this.teardown()};onInit=async()=>{await this.syncFromTmp();e(this)};syncFromTmp=async()=>{await this.teardown();if(this.#i.all.isRedisPassive)return;const t=this.#i.all.redisUri?.trim();if(!t)return;const i=r({url:t,socket:o(t)});i.on("error",(s)=>{console.error(`Redis ${s}`)});await i.connect();this.#t=i};teardown=async()=>{if(!this.#t)return;try{await this.#t.quit()}catch{try{await this.#t.disconnect()}catch{}}this.#t=null};get client(){return this.#t}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import s from"node:fs";export function resolveRedisSocketOptions(r){const e={connectTimeout:1e4};if(!((r?.trim()??"").startsWith("rediss://")||process.env.REDIS_SSL==="true"))return e;const t=process.env.REDIS_SSL_CA||process.env.KAFKA_SSL_CA||"/etc/tls/infra/ca.crt";try{if(t&&s.existsSync(t))return{...e,tls:!0,ca:[s.readFileSync(t,"utf-8")],rejectUnauthorized:!1}}catch{}return{...e,tls:!0,rejectUnauthorized:!1}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{G as
|
|
1
|
+
import{G as m,notifyRuntimeTmpChange as o,onTmpReload as p,setRuntimeTmpConfigs as s}from "../../utils/index.js";import{normalizeTmpDocument as e}from "../../utils/helpers/tmp/tmp-schema.js";export default class System{_core={};_tmp={};cwd=process.cwd();g=m;onInit=async({core:i})=>{this._core=i;await this.applyTmp(this._core._);p((t)=>void this.applyTmp(t))};async applyTmp(i){this._tmp=e(i);const t=this._tmp.configs;s(t);this.g.configureFromTmp(this._tmp);await o(t)}get core(){return this._core}get tmp(){return this._tmp}}
|
package/x/dist/project/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import e from"path";import{fileURLToPath as a}from"node:url";import{System as c,Configs as n,Logger as l,Events as m,Localizations as f,DtoRuntime as g,Clients as u,Controller as C,KafkaForCore as d,RedisForCore as v,MongoForCore as x}from "../loader/index.js";import{Constants as h,getCore as E,x as S}from "../utils/index.js";import{ensureCoreTmpEntry as y,isCorePackageRoot as L}from "../utils/helpers/core/tmp-layout.js";import{getTmpSnapshot as R}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=E(),coreInit=async(s)=>{const{locales:o}=s;if(o)globalThis.__LOCAL_MESSAGES__=o};let t=!1;const i=e.dirname(a(import.meta.url)),T=e.join(i,"..","loader","**/*.{ts,js}"),_=e.join(i,"..","utils","**/class.x.{ts,js}"),j=async(s={})=>{if(t)return core;const o=process.cwd();if(L(o))y(o);R();try{await(await S.load([T],{exclude:[_]})).initialize([{service:c,props:{core}},{service:n,props:{}},{service:d,props:{}},{service:v,props:{}},{service:x,props:{}},{service:l,props:{}},{service:m,props:{}},{service:f,props:{}},{service:g,props:{}},{service:C,props:{}},{service:u,props:{}}]);t=!0;return core}catch(r){const p=r instanceof Error?r.message:String(r);console.error(`[${h.packageName} core failure]: ${p}`);throw r}};export default j;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import r from"node:path";import{packageRootDir as i}from "../../utils/constants/package-root.js";import e from"./defaults.json" with { type: 'json' };import{seedFromTmp as t}from "../../utils/helpers/tmp/seed-from-tmp.js";export const packageDefaults=Object.freeze({...e,mainSourceFolder:t.sourceFolder,framework:t.framework,layoutPaths:Object.freeze({...t.layout}),brand:Object.freeze({...e.brand}),runtimes:Object.freeze(Object.fromEntries(Object.entries(e.runtimes).map(([a,o])=>[a,Object.freeze({...o})]))),bundlers:Object.freeze([...e.bundlers]),buildDefaults:Object.freeze({...e.buildDefaults}),tmpWatchDefaults:Object.freeze({...e.tmpWatchDefaults}),cliBinNames:Object.freeze([...e.cliBinNames??[e.cliName]])}),coreVersionPattern=/^\d{2}\.\d{2}\.\d{2}-v\d+$/,semverVersionPattern=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-.]+)?(?:\+[0-9A-Za-z-.]+)?$/;const c=`${packageDefaults.tmpBaseName}${packageDefaults.tmpExtension}`;export class Constants{static packageName=packageDefaults.packageName;static packageRootFolder=packageDefaults.packageRootFolder;static tmpBaseName=packageDefaults.tmpBaseName;static tmpExtension=packageDefaults.tmpExtension;static publicFolderName=packageDefaults.publicFolderName;static kafkaLogsTopic=packageDefaults.kafkaLogsTopic;static templateRepoUri=packageDefaults.templateRepoUri;static cliName=packageDefaults.cliName;static cliBinNames=packageDefaults.cliBinNames;static pathAliasKey=packageDefaults.pathAliasKey;static brand=packageDefaults.brand;static mainSourceFolder=packageDefaults.mainSourceFolder;static framework=packageDefaults.framework;static layoutPaths=packageDefaults.layoutPaths;static cliBinFile=packageDefaults.cliBinFile;static logTag=packageDefaults.packageName;static bundledCoreTmpPath=r.join(i,packageDefaults.packageRootFolder,c)}export{seedFromTmp,loadSeedFromBundledTmp}from "../../utils/helpers/tmp/seed-from-tmp.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import o from"node:path";import{fileURLToPath as t}from"node:url";const r=o.dirname(t(import.meta.url));export const sourceDir=o.resolve(r,"..",".."),packageRootDir=o.resolve(r,"..","..","..");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{AsyncLocalStorage as
|
|
1
|
+
import{AsyncLocalStorage as n}from"node:async_hooks";export const runContextStorage=new n;export function getRunContext(){return runContextStorage.getStore()}export function getRequestId(){return getRunContext()?.requestId}export function runWithContext(e,t){return runContextStorage.run(e,t)}export function runWithRequestId(e,t,r="http"){return runWithContext({requestId:e,kind:r},t)}export function runWithTrace(e,t,r){return runWithContext({requestId:e,kind:"job",label:r},t)}export function patchRunContext(e){const t=getRunContext();if(!t)return;Object.assign(t,e)}export{controllerContextStorage,getControllerCtx,runControllerStore,adapterBagFromRequest,isFetchRequest}from "../../../utils/helpers/context/controller-store.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import i from"handlebars";export function resolveObjWithHandlebars(e,t){if(typeof e==="string")return i.compile(e)(t);if(typeof e==="object"&&e!==null){const r=e;for(const n in r)r[n]=resolveObjWithHandlebars(r[n],t)}return e}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Constants as
|
|
1
|
+
import{Constants as n,ProtocolEnum as c,TmpFileLoader as l}from"../../../utils/index.js";import{controllerContextStorage as i}from "../../../utils/helpers/context/controller-store.js";import{getTmpSnapshot as a}from "../../../utils/helpers/tmp/tmp-loader.js";import{findFileRecursively as m}from "../../../utils/helpers/core/paths.js";import{parseProtocol as f}from"../../../utils/helpers/protocol/index.js";export*from "../../../utils/helpers/core/paths.js";export*from "../../../utils/helpers/core/tmp-layout.js";export{resolveObjWithHandlebars}from "../../../utils/helpers/core/handlebars-resolve.js";export const getCore=()=>({_:a()}),getTmpConfig=({root:t=process.cwd(),tmpFileName:o=n.tmpBaseName,ext:r=n.tmpExtension}={})=>{const e=m(t,o,r);if(!e)throw Error(`${o}${r.startsWith(".")?r:`.${r}`} file not found`);return new l({filePath:e}).getResolvedTmpFile()},withProtocol=async(t,o=c.HTTP)=>{const r=f(o),e=i.getStore();if(e)e.protocol=r;return await t()},protocol=async(t,o=c.HTTP)=>withProtocol(t,o),argvsConverter=(t)=>{const o=t?.slice(2),r={};o.forEach((e)=>{if(e.startsWith("--")){console.log(e);const[s,p]=e.split("=");r[s.replace("--","")]=p||""}});return r},findExt=(t)=>{const o=t.split(".");return o[o.length-1]},changeExtensions=(t,o)=>{return t.replace(findExt(t),o)};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import c from"node:fs";import n from"node:path";import x from"yaml";import{Constants as r}from "../../../utils/constants/index.js";import{findAllFilesRecursively as P,findFileRecursively as k}from "../../../utils/helpers/core/paths.js";import{normalizeTmpDocument as S,readTmpServiceBlock as F,normalizeRootFolder as T,normalizeSourceFolder as E,resolveServiceLayoutPaths as R}from "../../../utils/helpers/tmp/tmp-schema.js";function v(t,e){return`${t}${e.startsWith(".")?e:`.${e}`}`}export function coreCanonicalTmpPath(t=process.cwd()){return n.join(n.resolve(t),r.packageRootFolder,v(r.tmpBaseName,r.tmpExtension))}export function assertCoreTmpGuard(t,e){if(!isCorePackageRoot(t))return;const o=coreCanonicalTmpPath(t);if(n.resolve(e)!==n.resolve(o))throw Error(`${r.packageName}: tmp.yml must stay at ${r.packageRootFolder}/tmp.yml (expected ${o}, got ${e})`)}function w(t,e){const o=n.resolve(t),s=n.resolve(e);return P(o,r.tmpBaseName,r.tmpExtension).filter((a)=>n.resolve(a)!==s)}export function ensureCoreTmpEntry(t=process.cwd(),e={}){const o=n.resolve(t);if(!isCorePackageRoot(o))throw Error(`ensureCoreTmpEntry is only for ${r.packageName} package root`);const s=coreCanonicalTmpPath(o),a=w(o,s);if(a.length>0){const p=a.map((l)=>n.relative(o,l)).join(", ");throw Error(`${r.packageName}: tmp.yml must only exist under ${r.packageRootFolder}/. Remove extra copies: ${p}`)}if(c.existsSync(s)){assertCoreTmpGuard(o,s);return{tmpFilePath:s,created:!1,layout:buildTmpLayout(o,f(s),s)}}return ensureTmpFile(o,{...e,patchServiceName:!1})}function N(t,e,o){const s=n.resolve(t);if(isCorePackageRoot(s)){const a=coreCanonicalTmpPath(s);return c.existsSync(a)?a:null}return k(s,e,o)}function f(t){return x.parse(c.readFileSync(t,"utf8"))}export function isCorePackageRoot(t){const e=n.join(n.resolve(t),"package.json");if(!c.existsSync(e))return!1;try{return JSON.parse(c.readFileSync(e,"utf8")).name===r.packageName}catch{return!1}}export function resolveRootFolderPath(t,e,o){const s=S(t).configs,a=F(s);if(a.paths?.root?.trim())return T(a.paths.root);const p=t.project;if(typeof p?.name==="string"&&p.name.trim())return p.name.trim();const l=n.relative(n.resolve(o),n.dirname(n.resolve(e)));if(l&&l!==".")return l;return r.packageRootFolder}export function resolveLayoutPaths(t){const e=F(t);return R(e)}export function resolveMainFolderPath(t){const e=F(t);if(e.paths?.source?.trim())return E(e.paths.source);return r.mainSourceFolder}export function buildTmpLayout(t,e,o){const s=n.resolve(t),a=e?S(e).configs:void 0,p=e&&o&&!isCorePackageRoot(s)?resolveRootFolderPath(e,o,s):r.packageRootFolder,l=n.join(s,p),m=resolveLayoutPaths(a),i=resolveMainFolderPath(a),u={tests:n.join(l,m.tests),environments:n.join(l,m.environments),dist:n.join(l,m.dist)};return{projectRoot:s,rootFolderPath:p,rootFolderAbs:l,tmpFilePath:o,mainFolderPath:i,paths:m,pathsAbs:u}}export function resolveTmpLayout(t=process.cwd(),e={}){const o=e.tmpFileName??r.tmpBaseName,s=e.ext??r.tmpExtension,a=N(t,o,s);if(!a)throw Error(`${v(o,s)} not found under ${n.resolve(t)}`);if(isCorePackageRoot(n.resolve(t)))assertCoreTmpGuard(t,a);return buildTmpLayout(t,f(a),a)}export function resolveTmpLayoutOrDefaults(t=process.cwd()){const e=N(t,r.tmpBaseName,r.tmpExtension);if(!e)return buildTmpLayout(t,null,null);return buildTmpLayout(t,f(e),e)}export function resolveBundledCoreTmpPath(t=process.cwd()){if(c.existsSync(r.bundledCoreTmpPath))return r.bundledCoreTmpPath;let e=n.resolve(t);while(e!==n.dirname(e)){const o=n.join(e,"node_modules","@xrystal","core",r.packageRootFolder,v(r.tmpBaseName,r.tmpExtension));if(c.existsSync(o))return o;const s=n.join(e,"package.json");if(c.existsSync(s)){if(JSON.parse(c.readFileSync(s,"utf8")).name===r.packageName){const p=n.join(e,r.packageRootFolder,v(r.tmpBaseName,r.tmpExtension));if(c.existsSync(p))return p}}e=n.dirname(e)}throw Error(`${r.packageName} bundled ${r.packageRootFolder}/tmp.yml not found`)}export function ownerTmpFilePath(t=process.cwd(),e){const o=e??resolveTmpLayoutOrDefaults(t);return n.join(o.rootFolderAbs,v(r.tmpBaseName,r.tmpExtension))}export function ensureTmpFile(t=process.cwd(),e={}){const o=n.resolve(t),s=e.patchServiceName??!0;if(isCorePackageRoot(o)){const i=coreCanonicalTmpPath(o),u=w(o,i);if(u.length>0){const d=u.map((y)=>n.relative(o,y)).join(", ");throw Error(`${r.packageName}: tmp.yml must only exist under ${r.packageRootFolder}/. Remove extra copies: ${d}`)}if(c.existsSync(i)){assertCoreTmpGuard(o,i);return{tmpFilePath:i,created:!1,layout:buildTmpLayout(o,f(i),i)}}}else{const i=k(o,r.tmpBaseName,r.tmpExtension);if(i)return{tmpFilePath:i,created:!1,layout:buildTmpLayout(o,f(i),i)}}const a=e.templatePath??resolveBundledCoreTmpPath(o);if(!c.existsSync(a))throw Error(`${r.packageName} bundled ${r.packageRootFolder}/tmp.yml not found`);const p=buildTmpLayout(o,null,null);c.mkdirSync(p.rootFolderAbs,{recursive:!0});const l=ownerTmpFilePath(o,p);let m=c.readFileSync(a,"utf8");if(s)try{const i=n.join(o,"package.json");if(c.existsSync(i)){const u=JSON.parse(c.readFileSync(i,"utf8")),d=typeof u.name==="string"?u.name.replace(/^@/,"").replace(/\//g,"-"):null;if(d){const y=x.parse(m),h=y.configs??{},g=h.service;if(typeof g==="object"&&g!==null&&!Array.isArray(g))g.name=d;else h.service={name:d};y.configs=h;m=x.stringify(y)}}}catch{}c.writeFileSync(l,m);return{tmpFilePath:l,created:!0,layout:buildTmpLayout(o,f(l),l)}}export function resolveTmpLayoutEnsured(t=process.cwd()){return ensureTmpFile(t).layout}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{PolarityTypeEnum as
|
|
1
|
+
import{PolarityTypeEnum as d}from "../../../utils/models/index.js";export function dateZoneConverter({polarity:e,date:o,zone:n,factor:r=1000}){let s=null;if(e===d.NEGATIVE)s=o.getTime()-r*n;else s=o.getTime()+r*n;return new Date(s).toISOString()}export function convertDate(e,o="/",n="-"){return e.split(o).map((s,t)=>t!==2?n:s)}export function convertTime(e,o=":",n="-"){return e.split(o).map((s,t)=>t!==2?n:s)}export function getDateAndTime({getDate:e=!0,getTime:o=!0,dateCharacter:n="-",timeCharacter:r=":",separatorCharacter:s="&"}){const t=new Date;let u="";if(!e&&!o)throw Error("Invalid options! Required one true value");if(e){const i=t.getDate().toString().padStart(2,"0"),a=(t.getMonth()+1).toString().padStart(2,"0");u=`${t.getFullYear()}${n}${a}${n}${i}`}if(o){const i=t.getHours().toString().padStart(2,"0"),a=t.getMinutes().toString().padStart(2,"0"),S=t.getSeconds().toString().padStart(2,"0");u=`${i}${r}${a}${r}${S}`}if(e&&o){const i=t.getDate().toString().padStart(2,"0"),a=(t.getMonth()+1).toString().padStart(2,"0"),S=t.getFullYear(),c=t.getHours().toString().padStart(2,"0"),g=t.getMinutes().toString().padStart(2,"0"),p=t.getSeconds().toString().padStart(2,"0");u=`${S}${n}${a}${n}${i}${s}${c}${r}${g}${r}${p}`}return u}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{expressSink as
|
|
1
|
+
import{expressSink as p}from"@xrystal/dto/express";import{nodeSink as f}from"@xrystal/dto/node";import{fetchSink as a}from"@xrystal/dto/fetch";import{elysiaSink as m}from"@xrystal/dto/elysia";import{websocketSink as k}from"@xrystal/dto/websocket";import{socketIoSink as S}from"@xrystal/dto/socketio";import{FrameworkEnum as t,ProtocolEnum as r}from "../../../utils/models/index.js";import{getFramework as d}from "../../../utils/helpers/framework/index.js";import{getDtoRuntime as h}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 E=(o)=>!!o&&typeof o==="object"&&("body"in o)&&("statusCode"in o),x=(o)=>o instanceof Response||o instanceof Blob||o instanceof Uint8Array||o instanceof ArrayBuffer,s=(o)=>o.socket??o.ctx?.ws??o.ctx,w=()=>h().config.socket?.event??"response";export function dispatchResult(o,e,i){if(o===void 0||o===null)return;if(x(o))return o;if(!E(o))return o;if(e.protocol===r.SOCKETIO||e.framework===t.SOCKETIO){S(s(e),w()).dispatch(o);return}if(e.protocol===r.WEBSOCKET||e.framework===t.WEBSOCKET){k(s(e)).dispatch(o);return}const c=e.framework??d(),n=i;switch(c){case t.EXPRESS:if(n&&!n.headersSent)p(i).dispatch(o);return;case t.NODE:if(n&&!n.headersSent)f(i).dispatch(o);return;case t.FETCH:return a.dispatch(o);case t.ELYSIA:default:return m(e.ctx?.set??{}).dispatch(o)}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getRuntimeTmpConfigs as
|
|
1
|
+
import{getRuntimeTmpConfigs as n}from "../../../utils/helpers/tmp/runtime-tmp.js";import{FrameworkEnum as t}from "../../../utils/models/index.js";const o=new Set(Object.values(t));export function parseFramework(r){const e=r?String(r).toLowerCase():void 0;return e&&o.has(e)?e:t.ELYSIA}export function getFramework(r){if(r)return r;try{return parseFramework(n()?.service?.framework)}catch{return t.ELYSIA}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{FrameworkEnum as
|
|
1
|
+
import{FrameworkEnum as a,ProtocolEnum as s}from "../../../utils/models/index.js";import{detectSocketProtocol as l}from "../../../utils/helpers/protocol/index.js";import{getFramework as E}from "../../../utils/helpers/framework/index.js";import{runAction as m}from "../../../utils/helpers/handlers/execute.js";import{Constants as u}from "../../../utils/constants/index.js";export function toRealtimeHandler(t,c){const e=(r)=>{const n=l(r,c);return m({socket:r,ctx:{ws:r},protocol:n},t)},o=(r)=>e(r);o.with=(r)=>()=>e(r);return o}export const toHandler=(t,c)=>{const e=c??E();switch(e){case a.ELYSIA:return(o)=>m({framework:e,ctx:o},t);case a.FETCH:return(o,r)=>m({framework:e,ctx:{request:o,...r}},t);case a.NODE:return(o,r)=>m({framework:e,req:o,res:r},t,r);case a.EXPRESS:return(o,r,n)=>{m({framework:e,req:o,res:r,metadata:{locals:r.locals||{}}},t,r).catch(n)};case a.WEBSOCKET:case a.SOCKETIO:throw Error(`[${u.packageName}] realtime: ctr({ ... }, { protocol: "ws" | "socketio" })`);default:return(o)=>m({framework:a.ELYSIA,ctx:o},t)}},toWebSocket=(t,c)=>toRealtimeHandler(c,s.WEBSOCKET)(t),toSocketIo=(t,c)=>toRealtimeHandler(c,s.SOCKETIO)(t);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{randomUUID as
|
|
1
|
+
import{randomUUID as a}from"node:crypto";import{FrameworkEnum as m,ProtocolEnum as q}from "../../../utils/models/index.js";import{runControllerStore as x}from "../../../utils/helpers/context/index.js";import{runWithRequestId as p}from "../../../utils/helpers/context/index.js";import{dispatchResult as l}from "../../../utils/helpers/dispatch/index.js";import{getFramework as I}from "../../../utils/helpers/framework/index.js";import{attachSocketTransport as g,isRealtimeProtocol as c}from "../../../utils/helpers/protocol/index.js";import{getDtoRuntime as s}from "../../../utils/helpers/runtime/index.js";export const runController=x;const w=(t)=>({framework:t.framework??(c(t.protocol)?void 0:I()),protocol:t.protocol??q.HTTP,...t,metadata:{locals:{},...t.metadata}}),i=(t,r)=>{if(!t)return;if(t instanceof Headers)return t.get(r)??t.get(r.toLowerCase());if(typeof t.get==="function"){const e=t.get;return e(r)??e(r.toLowerCase())}const o=t;return o[r]??o[r.toLowerCase()]},k=(t)=>{const r=t.ctx??{},o=t.req??{},e=o.headers??r.request?.headers;return t.requestId??r.requestId??o.ctx?.requestId??i(e,"x-request-id")??i(e,"x-correlation-id")??""},R=(t)=>{const r=String(k(t)||a());t.requestId=r;t.ctx={...t.ctx,requestId:r};if(t.req)t.req.ctx={...t.req.ctx,requestId:r};return r},h=(t)=>{if(t.framework!==m.FETCH||t.ctx?.builder)return;const r=t.ctx?.request??t.req;if(!(r instanceof Request))return;t.ctx={...t.ctx,...s().forRequest(r)};if(t.ctx.requestId)t.requestId=String(t.ctx.requestId)},y=async(t,r,o)=>{const e=l(t,r,o),n=o;if(e instanceof Response&&n?.send){n.status?.(e.status);e.headers.forEach((f,d)=>n.setHeader?.(d,f));const u=e.headers.get("content-type")||"";if(u.includes("json")||u.includes("text/"))return n.send(await e.text());return n.send(Buffer.from(await e.arrayBuffer()))}return e},C=(t)=>c(t.protocol)?"ws":"http";export async function runAction(t,r,o){const e=w(t);if(c(e.protocol)&&e.socket&&!e.socket.builder)g(e.socket,e.protocol,s());h(e);const n=R(e);return p(n,()=>runController(e,async()=>y(await r(),e,o)),C(e))}export function configureDto(t,r){return s().configure(t,r)}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{FrameworkEnum as
|
|
1
|
+
import{FrameworkEnum as l}from "../../../utils/models/index.js";import{createDtoMiddleware as r}from "../../../utils/helpers/middleware/index.js";import{attachSocketTransport as a,detectSocketProtocol as c,resolveRealtimeMiddlewareProtocol as p}from "../../../utils/helpers/protocol/index.js";import{getDtoRuntime as t}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=(o)=>r(t(),o);export function realtimeMiddleware(o){const n=p(o);return(m,i)=>{try{const e=c(m,n);a(m,e,t());i?.()}catch(e){i?.(e instanceof Error?e:Error(String(e)))}}}export const websocketMiddleware=(o)=>o?r(t(),o):realtimeMiddleware("ws"),socketIoMiddleware=(o)=>o?r(t(),o??l.SOCKETIO):realtimeMiddleware("socketio");
|
|
@@ -1 +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";
|
|
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";export*from "../../utils/helpers/node-env/index.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{FrameworkEnum as
|
|
1
|
+
import{FrameworkEnum as r}from "../../../utils/models/index.js";import{getFramework as o,parseFramework as a}from "../../../utils/helpers/framework/index.js";const n={express:r.EXPRESS,elysia:r.ELYSIA,node:r.NODE,fetch:r.FETCH,websocket:r.WEBSOCKET,ws:r.WEBSOCKET,socketio:r.SOCKETIO};export function normalizeFrameworkKind(e){if(e===void 0)return o();const t=typeof e==="object"&&e!==null&&"framework"in e?e.framework:e;if(!t)return o();const s=String(t).toLowerCase().replace(/[-_\s]/g,"");return n[s]??a(t)}export function resolveDtoAdapter(e,t){switch(t){case r.ELYSIA:return e.elysia();case r.NODE:return e.node();case r.SOCKETIO:return e.socketIo();case r.WEBSOCKET:return e.websocket();case r.FETCH:return null;case r.EXPRESS:return e.express();default:return e.elysia()}}export function createDtoMiddleware(e,t){return resolveDtoAdapter(e,normalizeFrameworkKind(t))}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{NodeEnvEnum as e}from "../../../utils/models/enums/index.js";const o={development:e.DEV,dev:e.DEV,production:e.PROD,prod:e.PROD,test:e.TEST};export function normalizeNodeEnv(r){const t=typeof r==="string"?r.trim().toLowerCase():"";if(!t)return e.DEV;const n=o[t];if(n)return n;if(Object.values(e).includes(t))return t;return e.DEV}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import t from"path";import{fileURLToPath as r}from"url";export*from "../../../utils/helpers/path/resolve-alias-path.js";export const __filename=(o)=>r(o),__dirname=(o)=>t.dirname(r(o));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import u from"node:fs";import n from"node:path";import i from"../../../utils/constants/defaults.json" with { type: 'json' };const h=[".ts",".js",".mjs"];function c(t){return String(t).replace(/^\.\//,"")}function p(t){for(const e of h){const o=`${t}${e}`;if(u.existsSync(o))return o}for(const e of h){const o=n.join(t,`index${e}`);if(u.existsSync(o))return o}return null}export function resolveAliasModulePath(t,e={}){const o=e.cwd??process.cwd(),l=e.aliasPrefix??i.pathAliasKey.replace("*","");if(!t.startsWith(l))return n.isAbsolute(t)?t:n.resolve(o,t);const s=c(e.sourceFolder??"source");let r=t.slice(l.length).replace(/^\/+/,"");if(r===s||r.startsWith(`${s}/`))r=r===s?"":r.slice(s.length+1);const a=n.join(o,s,r),d=p(a);if(d)return d;const g=c(e.rootFolder??i.packageRootFolder),m=c(e.distSegment??"dist"),F=n.join(o,g,m,r),f=p(F);if(f)return f;return a}export function resolveTmpLoadPath(t,e,o=process.cwd()){const l=i.pathAliasKey.replace("*",""),s=e.configs??{};if(!t.startsWith(l)){const d=s.rootFolderPath??i.packageRootFolder;return n.resolve(o,d,t)}const r=s.service?.paths??{},a=r.special??{};return resolveAliasModulePath(t,{cwd:o,sourceFolder:c(String(r.source??"source")),rootFolder:s.rootFolderPath??i.packageRootFolder,distSegment:c(String(a.dist??"dist"))})}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Constants as
|
|
1
|
+
import{Constants as s}from "../../../utils/constants/index.js";import{ProtocolEnum as r}from "../../../utils/models/enums/index.js";import{getRuntimeTmpConfigs as u}from "../../../utils/helpers/tmp/runtime-tmp.js";const c={http:r.HTTP,https:r.HTTPS,ws:r.WEBSOCKET,websocket:r.WEBSOCKET,socketio:r.SOCKETIO,socket:r.SOCKETIO},REALTIME_MIDDLEWARE_HINT=`[${s.packageName}] tmp.yml lists both ws and socketio — use realtimeMiddleware("ws") or realtimeMiddleware("socketio")`;export function parseProtocol(t){if(!t)return r.HTTP;const e=String(t).toLowerCase().replace(/[-_\s.]/g,"");if(c[e])return c[e];return Object.values(r).includes(String(t))?t:r.HTTP}export function isRealtimeProtocol(t){return t===r.WEBSOCKET||t===r.SOCKETIO}export function isHttpProtocol(t){return!t||t===r.HTTP||t===r.HTTPS}function i(){return u()?.service}export function resolveProtocolsFromConfig(t){const e=t?.protocols;if(!e)return[r.HTTP];return(Array.isArray(e)?e:[e]).map(parseProtocol)}export function getConfiguredProtocols(){try{return resolveProtocolsFromConfig(i())}catch{return[r.HTTP,r.WEBSOCKET]}}export function getConfiguredRealtimeProtocols(t){return resolveProtocolsFromConfig(t).filter(isRealtimeProtocol)}export function defaultRealtimeProtocolFromConfig(t){const e=getConfiguredRealtimeProtocols(t);if(e.length===1)return e[0];if(e.length>1)return;return r.WEBSOCKET}export function getDefaultRealtimeProtocol(){try{return defaultRealtimeProtocolFromConfig(i())}catch{return r.WEBSOCKET}}export function resolveRealtimeMiddlewareProtocol(t,e){if(t!==void 0&&t!==null&&t!=="")return parseProtocol(t);let o=e;if(!o)try{o=i()}catch{return r.WEBSOCKET}const n=getConfiguredRealtimeProtocols(o);if(n.length===1)return n[0];if(n.length>1)throw Error(REALTIME_MIDDLEWARE_HINT);return r.WEBSOCKET}export function detectSocketProtocol(t,e){if(e)return e;const o=t;if(o?.__xrystalProtocol)return o.__xrystalProtocol;return r.WEBSOCKET}export function attachSocketTransport(t,e,o){const n=t;if(e===r.SOCKETIO)o.attachSocketIo(t);else o.attachWebSocket(t);n.__xrystalProtocol=e}export{REALTIME_MIDDLEWARE_HINT};
|
|
@@ -1,13 +1,10 @@
|
|
|
1
1
|
export declare const REGISTRY_COLLECTION = "registry";
|
|
2
|
-
/** Legacy gateway target keys → registry service name / Eski target key → servis adi */
|
|
3
2
|
export declare const LEGACY_TARGET_KEY_TO_SERVICE: Record<string, string>;
|
|
4
|
-
/** Alias names in targets (e.g. root) → registry name / Hedef alias */
|
|
5
3
|
export declare const TARGET_SERVICE_ALIASES: Record<string, string>;
|
|
6
4
|
export interface RegistryEntryOthers {
|
|
7
5
|
created?: Date | string;
|
|
8
6
|
updated?: Date | string;
|
|
9
7
|
}
|
|
10
|
-
/** Mongo registry doc — env omitted (DB per env: dev_registry_db / prod_registry_db) */
|
|
11
8
|
export interface RegistryEntry {
|
|
12
9
|
_id?: string;
|
|
13
10
|
name: string;
|
|
@@ -20,7 +17,6 @@ export declare function registryRedisHashKey(nodeEnv: string): string;
|
|
|
20
17
|
export declare function normalizeRegistryServiceName(name: string): string;
|
|
21
18
|
export declare function isAbsoluteHttpUrl(value: string): boolean;
|
|
22
19
|
export declare function looksLikeLegacyConfigTargetKey(key: string): boolean;
|
|
23
|
-
/** Normalize Mongo doc (supports legacy registeredAt/lastSeenAt/env) / Mongo doc normalize */
|
|
24
20
|
export declare function normalizeRegistryDoc(doc: Record<string, unknown> | null | undefined): RegistryEntry | null;
|
|
25
21
|
export declare function serializeRegistryEntry(entry: RegistryEntry): string;
|
|
26
22
|
export declare function parseRegistryEntry(raw: string | null | undefined): RegistryEntry | null;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export const REGISTRY_COLLECTION="registry",LEGACY_TARGET_KEY_TO_SERVICE={coreTargetUri:"core",rootTargetUri:"core",iamTargetUri:"iam",websocketTargetUri:"websocket",mqttTargetUri:"mqtt"},TARGET_SERVICE_ALIASES={root:"core"};export function buildInternalBaseUrl(
|
|
1
|
+
export const REGISTRY_COLLECTION="registry",LEGACY_TARGET_KEY_TO_SERVICE={coreTargetUri:"core",rootTargetUri:"core",iamTargetUri:"iam",websocketTargetUri:"websocket",mqttTargetUri:"mqtt"},TARGET_SERVICE_ALIASES={root:"core"};export function buildInternalBaseUrl(t,r=3000){const e=String(t??"").trim();if(!e)return"";return`http://${e}-service:${r}`}export function registryRedisHashKey(t){return`${t}:registry`}export function normalizeRegistryServiceName(t){const r=String(t??"").trim();if(!r)return"";return TARGET_SERVICE_ALIASES[r]??r}export function isAbsoluteHttpUrl(t){return/^https?:\/\//i.test(String(t??"").trim())}export function looksLikeLegacyConfigTargetKey(t){return/TargetUri$/i.test(String(t??"").trim())}export function normalizeRegistryDoc(t){if(!t)return null;const r=String(t.name??"").trim(),e=String(t.internalBaseUrl??"").trim();if(!r||!e)return null;const{others:n,registeredAt:i,lastSeenAt:o}=t;return{...t._id?{_id:String(t._id)}:{},name:r,internalBaseUrl:e,...t.version?{version:String(t.version)}:{},others:{created:n?.created??i,updated:n?.updated??o}}}export function serializeRegistryEntry(t){const r=t.others??{};return JSON.stringify({...t._id?{_id:t._id}:{},name:t.name,internalBaseUrl:t.internalBaseUrl,...t.version?{version:t.version}:{},others:{created:r.created instanceof Date?r.created.toISOString():r.created,updated:r.updated instanceof Date?r.updated.toISOString():r.updated}})}export function parseRegistryEntry(t){if(!t)return null;try{return normalizeRegistryDoc(JSON.parse(t))}catch{return null}}export function snapshotFromHash(t){const r={};for(const[e,n]of Object.entries(t??{})){const i=parseRegistryEntry(n);if(i)r[e]=i}return r}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{stopTmpLoader as
|
|
1
|
+
import{stopTmpLoader as n}from "../../../utils/helpers/tmp/tmp-loader.js";import{clearRuntimeTmpConfigs as s}from "../../../utils/helpers/tmp/runtime-tmp.js";import i from "../../../utils/models/classes/class.x.js";let o=!1,r=!1;export function isShuttingDown(){return o}export async function gracefulShutdown(t=0){if(o){process.exit(t);return}o=!0;try{await i.shutdown()}catch{}n();s();await new Promise((e)=>setImmediate(e));process.exit(t)}export function registerGracefulShutdown(){if(r)return;r=!0;const t=(e)=>{gracefulShutdown(e==="SIGINT"?130:e==="SIGTERM"?143:0)};process.on("SIGINT",t);process.on("SIGTERM",t)}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createStore as
|
|
1
|
+
import{createStore as h}from"zustand/vanilla";import{subscribeWithSelector as l}from"zustand/middleware";import{GStoreScopeEnum as a}from "../../../utils/models/enums/index.js";import{propsFromTmp,resolveGStoreBoot,G_PROP_NOT_ALLOWED}from "../../../utils/helpers/state/props-from-tmp.js";import{warnIfRequestScopedKey as c,G_REQUEST_KEY_WARN,looksLikeRequestScopedKey}from "../../../utils/helpers/state/request-key-guard.js";import{buildStoresSnapshot as p,patchControllerScope as S,patchRunScope as f}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 i=(t)=>JSON.parse(JSON.stringify(t));function u(t,e){const s=new Set([...Object.keys(t),...Object.keys(e)]),o=[];for(const r of s)if(t[r]!==e[r])o.push({key:r,value:e[r],prev:t[r]});return o}class GStoreFacade{store;baseline={};allowedKeys=new Set;allowAutoCreateProps=!0;warnOnRequestKeys=!0;constructor(){this.store=h(l(()=>({})))}configureFromTmp(t={}){const e=resolveGStoreBoot(t);this.allowAutoCreateProps=e.allowAutoCreateProps;this.warnOnRequestKeys=e.warnOnRequestKeys;this.allowedKeys=new Set(Object.keys(e.vars));const s=i(e.bootstrap?e.vars:{});this.store.setState(s,!0);this.baseline=i(s);return this}allowsAutoCreateProps(){return this.allowAutoCreateProps}declaredKeys(){return[...this.allowedKeys]}guardRequestKey(t){c(t,this.warnOnRequestKeys)}assertPropAllowed(t){if(this.allowAutoCreateProps)return;if(!this.allowedKeys.has(t))throw Error(`${G_PROP_NOT_ALLOWED}: ${t}`)}registerAllowedKeys(t){for(const e of t)this.allowedKeys.add(e)}getState(){return this.store.getState()}select(t){return t(this.getState())}get(t,e){const s=this.getState();if(!(t in s))return e;return s[t]}set(t,e){this.guardRequestKey(t);this.assertPropAllowed(t);const s=this.getState();if(s[t]===e)return this;this.store.setState({...s,[t]:e});return this}merge(t){for(const o of Object.keys(t)){this.guardRequestKey(o);this.assertPropAllowed(o)}const e=this.getState();if(!u(e,{...e,...t}).length)return this;this.store.setState({...e,...t});return this}has(t){return t in this.getState()}remove(...t){const s={...this.getState()};let o=!1;for(const r of t)if(r in s){delete s[r];o=!0}if(o)this.store.setState(s,!0);return this}keys(){return Object.keys(this.getState())}entries(){return Object.entries(this.getState())}snapshot(){return{...this.getState()}}subscribe(t){return this.store.subscribe((e,s)=>t(e,s,u(s,e)))}subscribeKey(t,e){return this.store.subscribe((s)=>s[t],(s,o)=>e(s,o,{key:t,value:s,prev:o}))}bootstrap(t){if(!this.allowAutoCreateProps)for(const e of Object.keys(t))this.assertPropAllowed(e);else this.registerAllowedKeys(Object.keys(t));this.merge(t);this.baseline=i(this.getState());return this}reset(){this.store.setState(i(this.baseline),!0)}stores(){return p(this.snapshot())}list(){return Object.values(this.stores())}scope(t){const s=this.stores()[t],o={name:t,active:s.active,keys:()=>s.keys,get(r,n){if(!s.values||!(r in s.values))return n;return s.values[r]}};if(t===a.GLOBAL)return{...o,set:(r,n)=>{this.set(r,n);return!0},merge:(r)=>{this.merge(r);return!0}};if(t===a.RUN)return{...o,patch:(r)=>f(r)};return{...o,patch:(r)=>S(r)}}}export{GStoreFacade};export const G=new GStoreFacade;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Constants as
|
|
1
|
+
import{Constants as u}from "../../../utils/constants/index.js";import{readTmpServiceBlock as p}from "../../../utils/helpers/tmp/tmp-schema.js";export const G_PROP_NOT_ALLOWED=`[${u.packageName}] G prop not declared in tmp.yml vars — set autoCreateProps: true to allow runtime keys`;const n=()=>({});function c(r){return p(r).loaders?.system?.gStore}function f(r){if(typeof r.bootstrap==="boolean")return r.bootstrap;return!0}function l(r){if(typeof r.autoCreateProps==="boolean")return r.autoCreateProps;return!0}function i(r){if(typeof r.warnOnRequestKeys==="boolean")return r.warnOnRequestKeys;return!0}export function resolveGStoreBoot(r={}){const t=r.configs??r,o=c(t);if(!o)return{bootstrap:!0,allowAutoCreateProps:!0,warnOnRequestKeys:!0,vars:n()};const s=o.options??{},e=o.vars,a=e&&typeof e==="object"&&!Array.isArray(e)?{...e}:n();return{bootstrap:f(s),allowAutoCreateProps:l(s),warnOnRequestKeys:i(s),vars:a}}export function propsFromTmp(r={}){const t=resolveGStoreBoot(r);return t.bootstrap?t.vars:n()}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Constants as
|
|
1
|
+
import{Constants as t}from "../../../utils/constants/index.js";import{getRunContext as s}from "../../../utils/helpers/context/index.js";import{getControllerCtx as n}from "../../../utils/helpers/context/controller-store.js";export const G_REQUEST_KEY_WARN=`[${t.packageName}] G: key looks request-scoped — use run/controller context, not global G`;const i=new Set(["requestid","reqid","correlationid","cookies","cookie","headers","header","body","query","queries","params","locals","session","sessionid"]);export function looksLikeRequestScopedKey(o){const r=o.trim();if(!r)return!1;const e=r.toLowerCase();if(i.has(e))return!0;if(e.endsWith("requestid")||e.endsWith("correlationid"))return!0;if(e==="req"||e==="res")return!0;return!1}export function warnIfRequestScopedKey(o,r){if(!r||!looksLikeRequestScopedKey(o))return;const e=s()?"run":n()?"controller":"outside-request";console.warn(`${G_REQUEST_KEY_WARN} (key: ${o}, scope: ${e})`)}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{GStoreScopeEnum as
|
|
1
|
+
import{GStoreScopeEnum as r}from "../../../utils/models/enums/index.js";import{getRunContext as a,patchRunContext as u}from "../../../utils/helpers/context/index.js";import{getControllerCtx as n}from "../../../utils/helpers/context/controller-store.js";export function summarizeController(e){if(!e)return null;return{protocol:e.protocol,framework:e.framework,requestId:e.requestId,metadata:e.metadata,hasReq:!!e.req,hasRes:!!e.res,hasSocket:!!e.socket}}export function runContextValues(e){if(!e)return null;return{...e}}export function buildStoresSnapshot(e){const t=a(),o=summarizeController(n());return{[r.GLOBAL]:{name:r.GLOBAL,active:!0,keys:Object.keys(e),values:{...e}},[r.RUN]:{name:r.RUN,active:!!t,keys:t?Object.keys(t):[],values:runContextValues(t)},[r.CONTROLLER]:{name:r.CONTROLLER,active:!!o,keys:o?Object.keys(o):[],values:o}}}export function patchControllerScope(e){const t=n();if(!t)return!1;if(e.requestId!==void 0)t.requestId=e.requestId;if(e.metadata)t.metadata={...t.metadata,...e.metadata,locals:{...t.metadata?.locals??{},...e.metadata.locals??{}}};return!0}export function patchRunScope(e){if(!a())return!1;u(e);return!0}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{packageDefaults as
|
|
1
|
+
import{packageDefaults as e}from "../../../utils/constants/index.js";import{onRuntimeTmpChange as t}from "../../../utils/helpers/tmp/runtime-tmp.js";export function bindLoaderTmpSync(n){const o=n.constructor.name;t(async()=>{try{await n.syncFromTmp()}catch(a){const r=a instanceof Error?a.message:String(a);console.warn(`[${e.packageName}] ${o} tmp reload failed: ${r}`)}})}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{packageDefaults as
|
|
1
|
+
import{packageDefaults as s}from "../../../utils/constants/index.js";import{healToolchainIfLayoutNeedsSync as a,resetToolchainHealState as c}from "../../../utils/helpers/tmp/toolchain-heal.js";let o;const i=[];export function setRuntimeTmpConfigs(n){o=n}export function getRuntimeTmpConfigs(){return o}export function onRuntimeTmpChange(n){i.push(n);return()=>{const e=i.indexOf(n);if(e>=0)i.splice(e,1)}}export async function notifyRuntimeTmpChange(n){if(n)o=n;const e=o;if(!e)return;if(e.rootFolderPath&&e.service?.paths)try{a(process.cwd(),e)}catch(t){const r=t instanceof Error?t.message:String(t);console.warn(`[${s.packageName}] toolchain auto-sync skipped: ${r}`)}for(const t of i)await t(e)}export function clearRuntimeTmpConfigs(){o=void 0;i.length=0;c()}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import a from"node:fs";import c from"node:path";import{fileURLToPath as d}from"node:url";import l from"yaml";import defaults from"../../../utils/constants/defaults.json" with { type: 'json' };import{normalizeRootFolder as u,normalizeSourceFolder as g}from "../../../utils/helpers/tmp/path-normalize.js";export{defaults as packageIdentityDefaults};const f=c.dirname(d(import.meta.url)),p=`${defaults.tmpBaseName}${defaults.tmpExtension}`;function i(e,o){if(typeof e!=="string"||!e.trim())throw Error(`${defaults.packageName}: bundled tmp.yml missing ${o}`);return e.trim()}function y(e){const o=e&&typeof e==="object"&&!Array.isArray(e)?e:{};return{tests:i(o.tests,"configs.service.paths.special.tests"),environments:i(o.environments,"configs.service.paths.special.environments"),dist:i(o.dist,"configs.service.paths.special.dist")}}function h(){try{return process.cwd()}catch{return null}}function w(e){if(e){if(!a.existsSync(e))throw Error(`${defaults.packageName}: bundled tmp.yml missing at ${e}`);return e}const o=[f,h()].filter((t)=>Boolean(t));for(const t of o){let r=c.resolve(t);for(;;){const s=c.join(r,defaults.packageRootFolder,p);if(a.existsSync(s))return s;const n=c.dirname(r);if(n===r)break;r=n}}throw Error(`${defaults.packageName}: bundled ${defaults.packageRootFolder}/${p} not found from ${f}`)}export function loadSeedFromBundledTmp(e){const o=w(e),t=l.parse(a.readFileSync(o,"utf8")),r=t?.configs&&typeof t.configs==="object"?t.configs:{},s=r.service&&typeof r.service==="object"?r.service:{},n=s.paths&&typeof s.paths==="object"?s.paths:{},m=i(n.source,"configs.service.paths.source");return{rootFolder:u(n.root,defaults.packageRootFolder),sourceFolder:g(m,m),framework:i(s.framework,"configs.service.framework"),layout:y(n.special)}}export const seedFromTmp=loadSeedFromBundledTmp();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import s from"node:fs";import m from"node:path";import{Constants as t}from "../../../utils/constants/index.js";import{assertCoreTmpGuard as f,coreCanonicalTmpPath as c,isCorePackageRoot as u}from "../../../utils/helpers/core/tmp-layout.js";import{findFileRecursively as d}from "../../../utils/helpers/core/paths.js";import{TmpFileLoader as T}from "../../../utils/models/classes/class.tmp-file-loader.js";import{registerGracefulShutdown as h}from "../../../utils/helpers/runtime/shutdown.js";let r=null,a=null;function g(i=process.cwd(),e=t.tmpBaseName,o=t.tmpExtension){const n=m.resolve(i);if(u(n)){const p=c(n);if(!s.existsSync(p))throw Error(`${t.packageRootFolder}/tmp.yml not found. Run ${t.cliName} tmp or ensureCoreTmpEntry() before starting ${t.packageName}`);f(n,p);return p}const l=d(n,e,o);if(!l)throw Error(`${e}${o.startsWith(".")?o:`.${o}`} file not found`);return l}export function getTmpLoaderPath(){if(!a)a=g();return a}export function getTmpLoader(){if(!r){r=new T({filePath:getTmpLoaderPath()});h()}return r}export function getTmpSnapshot(){return getTmpLoader().getResolvedTmpFile()}export function onTmpReload(i){const e=getTmpLoader(),o=()=>i(e.getResolvedTmpFile());e.on("reload",o);return()=>e.off("reload",o)}export function stopTmpLoader(){if(r){r.stop();r=null;a=null}}export function resetTmpLoaderForTests(){stopTmpLoader()}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import l from"../../../utils/constants/defaults.json" with { type: 'json' };import{BundlerEnum as n,RuntimeEnum as u}from "../../../utils/models/enums/index.js";import{seedFromTmp as c}from "../../../utils/helpers/tmp/seed-from-tmp.js";import{interpolateWithContext as d}from "../../../utils/helpers/tmp/tmp-interpolate.js";import{normalizeLayoutPaths as m,normalizeRootFolder as g,normalizeSourceFolder as b}from "../../../utils/helpers/tmp/path-normalize.js";function t(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function h(e){if(typeof e==="number"||typeof e==="string")return e;return}export function normalizeRuntime(e){const r=typeof e==="string"?e.trim().toLowerCase():"";if(r===u.NODE)return u.NODE;if(r===u.BUN)return u.BUN;if(!r)throw Error(`${l.packageName}: configs.global.runtime is required (${Object.values(u).join("|")})`);throw Error(`${l.packageName}: unknown configs.global.runtime "${String(e)}" (expected ${Object.values(u).join("|")})`)}export function normalizeBundler(e){const r=typeof e==="string"?e.trim().toLowerCase():"";if(!r)return n.AUTO;if(r===n.TSC)return n.TSC;if(r===n.ESBUILD)return n.ESBUILD;if(r===n.BUN)return n.BUN;if(r===n.AUTO)return n.AUTO;throw Error(`${l.packageName}: unknown build.bundler "${String(e)}" (expected ${Object.values(n).join("|")})`)}export function resolveEffectiveBundler(e,r){if(e!==n.AUTO)return e;return n.TSC}export function normalizeRootFolder(e){return g(e,l.packageRootFolder)}export function normalizeSourceFolder(e){return b(e,c.sourceFolder)}export function readTmpGlobalBlock(e){const r=t(e?.global)?e.global:{},o=t(r.vars)?r.vars:{};return{runtime:normalizeRuntime(r.runtime),vars:{...o}}}export function readTmpCoreBlock(e){const r=t(e?.core)?e.core:{},o=t(r.tmp)?r.tmp:{};return{tmp:{fileWatchIntervalMs:h(o.fileWatchIntervalMs)}}}export function readTmpServiceBlock(e){const r=t(e?.service)?e.service:{},o=t(r.paths)?r.paths:{},i=t(o.special)?o.special:{};let s=t(r.loaders)?{...r.loaders}:void 0,a=t(r.build)?r.build:void 0;if(s&&t(s.build)){const{build:f,...p}=s;s=p;if(!a&&t(f))a=f}return{name:typeof r.name==="string"?r.name:void 0,framework:typeof r.framework==="string"?r.framework:void 0,paths:{root:typeof o.root==="string"?o.root:void 0,source:typeof o.source==="string"?o.source:void 0,special:{tests:typeof i.tests==="string"?i.tests:void 0,environments:typeof i.environments==="string"?i.environments:void 0,dist:typeof i.dist==="string"?i.dist:void 0}},protocols:r.protocols,loaders:s,build:a}}export function resolveServiceLayoutPaths(e){return m(e.paths?.special,c.layout)}function y(e){const r=resolveServiceLayoutPaths(e);return{name:e.name,framework:e.framework??c.framework,paths:{root:e.paths?.root??l.packageRootFolder,source:e.paths?.source??c.sourceFolder,special:r},protocols:e.protocols,loaders:e.loaders,build:e.build}}function w(e){return{tmp:{fileWatchIntervalMs:e.tmp?.fileWatchIntervalMs}}}export function buildTmpVarContext(e){return{...e.vars,runtime:e.runtime,global:e}}export function applyTmpGlobalVars(e){const r=t(e.configs)?e.configs:{},o=readTmpGlobalBlock(r);return d(e,buildTmpVarContext(o))}export function resolveTmpRuntimeConfigs(e){const r=t(e?.configs)?e.configs:{},o=readTmpGlobalBlock(r),i=readTmpServiceBlock(r),s=readTmpCoreBlock(r),a=y(i);return{global:o,service:a,core:w(s),rootFolderPath:normalizeRootFolder(a.paths.root)}}export function normalizeTmpDocument(e){const r=applyTmpGlobalVars(e);return{...r,configs:resolveTmpRuntimeConfigs(r)}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{packageDefaults as
|
|
1
|
+
import{packageDefaults as o}from "../../../utils/constants/index.js";import{readTmpCoreBlock as u}from "../../../utils/helpers/tmp/tmp-schema.js";const f=o.tmpWatchDefaults;function e(n){const t=f?.[n];if(typeof t!=="number"||!Number.isFinite(t))throw Error(`${o.packageName}: tmpWatchDefaults.${n} missing in defaults.json`);return t}export function resolveTmpWatchIntervalMs(n){const t=n?.configs,s=u(t),r=e("intervalMs"),c=s.tmp?.fileWatchIntervalMs??r,a=Number(c);if(!Number.isFinite(a))return r;const i=e("minIntervalMs"),m=e("maxIntervalMs");return Math.min(m,Math.max(i,Math.round(a)))}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import
|
|
2
|
-
`,"utf8");return{wrote:!0,created:
|
|
1
|
+
import c from"node:fs";import f from"node:path";import{packageDefaults as r}from "../../../utils/constants/index.js";import{normalizeSourceFolder as y}from "../../../utils/helpers/tmp/path-normalize.js";function d(t){return String(t).replace(/^\.\//,"")}function h(){const t=r.buildDefaults?.tsconfig;if(!t||!String(t).trim())throw Error(`${r.packageName}: buildDefaults.tsconfig missing in defaults.json`);return String(t)}export function layoutOptionsFromRuntimeConfigs(t){const e=t.service?.paths,o=e?.special;return{rootFolderPath:t.rootFolderPath||r.packageRootFolder,mainFolderPath:y(e?.source,r.mainSourceFolder),pathsDist:o?.dist||r.layoutPaths.dist,pathsTests:o?.tests||r.layoutPaths.tests}}export function layoutFingerprint(t){return[t.rootFolderPath,d(t.mainFolderPath),t.pathsDist,t.pathsTests].join("\x00")}export function resolveRecommendedTsconfig(t){const e=d(t.mainFolderPath),o=t.rootFolderPath,s=r.pathAliasKey;return{include:[e],exclude:[`${o}/${t.pathsTests}`],compilerOptions:{baseUrl:".",paths:{[s]:[`${e}/*`]},rootDir:`./${e}`,outDir:`./${o}/${t.pathsDist}`}}}function S(t){const e=f.join(t,"package.json");if(!c.existsSync(e))return`${r.packageName}/tsconfig.base.json`;try{if(JSON.parse(c.readFileSync(e,"utf8")).name===r.packageName)return"./tsconfig.base.json"}catch{}return`${r.packageName}/tsconfig.base.json`}function F(t,e,o){const s=e.compilerOptions??{};return{...e,extends:e.extends??o,include:t.include,exclude:t.exclude,compilerOptions:{...s,baseUrl:t.compilerOptions.baseUrl,paths:t.compilerOptions.paths,rootDir:t.compilerOptions.rootDir,outDir:t.compilerOptions.outDir}}}export function auditTsconfigAgainstLayout(t,e,o=h()){const s=f.join(t,o);if(!c.existsSync(s))return{ok:!1,missing:!0,notes:[`${o} missing`]};let i;try{i=JSON.parse(c.readFileSync(s,"utf8"))}catch{return{ok:!1,missing:!1,notes:[`${o} unreadable`]}}const n=resolveRecommendedTsconfig(e),a=[],u=i.compilerOptions??{},p=r.pathAliasKey;if(u.outDir!==n.compilerOptions.outDir)a.push("outDir drift");if(!(Array.isArray(i.include)?i.include.map(String):[]).some((m)=>d(m)===n.include[0]))a.push("include drift");const g=u.paths?.[p];if(JSON.stringify(g)!==JSON.stringify(n.compilerOptions.paths[p]))a.push(`paths ${p} drift`);return{ok:a.length===0,missing:!1,notes:a}}export function writeTsconfigFromLayout(t,e,o=h()){const s=f.join(t,o),i=!c.existsSync(s);let n={};if(!i)try{n=JSON.parse(c.readFileSync(s,"utf8"))}catch{n={}}const a=resolveRecommendedTsconfig(e),u=F(a,n,S(t));c.writeFileSync(s,`${JSON.stringify(u,null,2)}
|
|
2
|
+
`,"utf8");return{wrote:!0,created:i,abs:s}}let l=null;export function resetToolchainHealState(){l=null}export function healToolchainIfLayoutNeedsSync(t,e,o={}){const s=layoutOptionsFromRuntimeConfigs(e),i=layoutFingerprint(s),n=h(),a=auditTsconfigAgainstLayout(t,s,n);if(l===null){l=i;if(a.ok)return{healed:!1,tsconfigRel:n,fingerprint:i};writeTsconfigFromLayout(t,s,n);if(!o.quiet)console.info(`[${r.packageName}] toolchain auto-synced (${n}) — bootstrap layout drift`);return{healed:!0,reason:"bootstrap",tsconfigRel:n,fingerprint:i}}if(i===l)return{healed:!1,tsconfigRel:n,fingerprint:i};l=i;writeTsconfigFromLayout(t,s,n);if(!o.quiet)console.info(`[${r.packageName}] toolchain auto-synced (${n}) — tmp layout paths changed`);return{healed:!0,reason:"layout-changed",tsconfigRel:n,fingerprint:i}}
|
|
@@ -1 +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
|
|
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:v,debug:C,...h}=e;let o=h.body;if(o&&typeof o==="object"&&!u&&!d)o=JSON.stringify(o);if(p){const a={method:h.method||"GET",url:n,body:o&&typeof o==="string"?JSON.parse(o):o};console.log(`[DEBUG] ${this.clientName}`,a);this.logger.winston.info(`${this.clientName} Request`,a)}const m=new AbortController,g=setTimeout(()=>m.abort(),this.timeout);try{const a=await fetch(n,{...h,body:o,headers:l,signal:m.signal});clearTimeout(g);return a}catch(a){clearTimeout(g);throw a}}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export class Locator{_context=new Map;constructor({}){}set=({service:t,reference:
|
|
1
|
+
export class Locator{_context=new Map;constructor({}){}set=({service:t,reference:n,args:e})=>{this._context.set(t,new n(...e||[]))};get=(t)=>{if(!this._context.has(t))throw Error(`${t} not found in context.`);return this._context.get(t)}}export default new Locator({});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{EventEmitter as
|
|
1
|
+
import{EventEmitter as h}from"node:events";import{readFileSync as a,unwatchFile as r,watchFile as l}from"node:fs";import{resolve as n}from"node:path";import{parse as m}from"yaml";import{resolveObjWithHandlebars as c}from "../../../utils/helpers/core/handlebars-resolve.js";import{normalizeTmpDocument as p}from "../../../utils/helpers/tmp/tmp-schema.js";import{resolveTmpWatchIntervalMs as s}from "../../../utils/helpers/tmp/tmp-watch.js";export class TmpFileLoader extends h{#t={};#e;#i=s(null);#s=!1;constructor({filePath:t}){super();this.#e=n(t);this.#r();this.#o()}#r(){try{const t=a(this.#e,"utf8"),e=m(t),i=s(e),o=this.#s&&i!==this.#i;this.#t=e;this.#i=i;this.emit("reload",this.#t);if(o)this.#o()}catch(t){console.error(`[TmpFileLoader] Error: ${t}`)}}#o(){if(this.#s)r(this.#e);this.#i=s(this.#t);l(this.#e,{interval:this.#i},(t,e)=>{if(t.mtimeMs!==e.mtimeMs)this.#r()});this.#s=!0}stop(){if(this.#s){r(this.#e);this.#s=!1}this.removeAllListeners()}getResolvedTmpFile(){const t=Object.keys(this.#t).length>0?this.#t:(this.#r(),this.#t);return p(c(t,t))}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var __filename="/
|
|
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";import S from"../../../utils/constants/defaults.json" with { type: 'json' };export const xSymbol=Symbol.for(`${S.packageName}/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];
|